From 1d742889168e7cae8d057f1c7ce06be7a75ada81 Mon Sep 17 00:00:00 2001 From: GAJ3T Date: Mon, 26 Oct 2026 04:18:54 -0400 Subject: [PATCH] Copying Repo to Demo --- .gitignore | 12 + README.md | 784 ++++++++++++ docs/architecture.md | 1105 +++++++++++++++++ docs/articulation-profiles.md | 400 ++++++ docs/compatibility.md | 265 ++++ docs/formats/agp.md | 128 ++ docs/formats/sdp.md | 162 +++ prompts/plan.md | 886 +++++++++++++ prompts/report_1.md | 212 ++++ prompts/report_10.md | 621 +++++++++ prompts/report_11.md | 204 +++ prompts/report_12.md | 194 +++ prompts/report_13.md | 338 +++++ prompts/report_14.md | 249 ++++ prompts/report_15.md | 175 +++ prompts/report_15_fix.md | 204 +++ prompts/report_16.md | 327 +++++ prompts/report_2.md | 223 ++++ prompts/report_3.md | 242 ++++ prompts/report_4.md | 271 ++++ prompts/report_5.md | 333 +++++ prompts/report_5_fix.md | 237 ++++ prompts/report_6.md | 275 ++++ prompts/report_7.md | 228 ++++ prompts/report_7_fix.md | 442 +++++++ prompts/report_8.md | 221 ++++ prompts/report_8_fix.md | 267 ++++ prompts/report_9.md | 326 +++++ prompts/report_9_fix.md | 322 +++++ prompts/report_9_fix_controls.md | 222 ++++ prompts/step_1.md | 133 ++ prompts/step_10.md | 98 ++ prompts/step_10_fix.md | 85 ++ prompts/step_11.md | 99 ++ prompts/step_12.md | 151 +++ prompts/step_13.md | 65 + prompts/step_14.md | 100 ++ prompts/step_15.md | 176 +++ prompts/step_15_fix.md | 44 + prompts/step_16.md | 99 ++ prompts/step_2.md | 123 ++ prompts/step_3.md | 124 ++ prompts/step_4.md | 137 ++ prompts/step_5.md | 166 +++ prompts/step_5_fix.md | 183 +++ prompts/step_6.md | 128 ++ prompts/step_7.md | 91 ++ prompts/step_7_fix.md | 132 ++ prompts/step_8.md | 68 + prompts/step_8_fix.md | 144 +++ prompts/step_9.md | 121 ++ prompts/step_9_fix.md | 122 ++ prompts/step_9_fix_controls.md | 92 ++ pyproject.toml | 61 + src/riff_groove_builder/__init__.py | 3 + src/riff_groove_builder/__main__.py | 32 + src/riff_groove_builder/articulations.py | 424 +++++++ src/riff_groove_builder/compose.py | 332 +++++ src/riff_groove_builder/data/__init__.py | 1 + .../data/profiles/__init__.py | 10 + .../ample-metal-eclipse-4.0.1-riffer-v1.json | 119 ++ .../ample-metal-ray5-4.1.0-riffer-v1.json | 100 ++ .../profiles/general-midi-percussion-v1.json | 115 ++ .../data/profiles/standard-midi-bass-v1.json | 62 + .../data/profiles/standard-midi-lead-v1.json | 62 + .../profiles/toontrack-sd3-3.4.4-core-v1.json | 69 + src/riff_groove_builder/description.py | 362 ++++++ src/riff_groove_builder/errors.py | 202 +++ src/riff_groove_builder/formats/__init__.py | 16 + src/riff_groove_builder/formats/agp.py | 497 ++++++++ src/riff_groove_builder/formats/sdp.py | 744 +++++++++++ src/riff_groove_builder/hybrid.py | 459 +++++++ src/riff_groove_builder/midi.py | 310 +++++ src/riff_groove_builder/pitch.py | 219 ++++ src/riff_groove_builder/profiles.py | 613 +++++++++ src/riff_groove_builder/schemas.py | 919 ++++++++++++++ src/riff_groove_builder/server.py | 169 +++ src/riff_groove_builder/service.py | 564 +++++++++ tests/fixtures/profiles/synthetic-bass.json | 56 + tests/fixtures/profiles/synthetic-drums.json | 40 + tests/fixtures/profiles/synthetic-lead.json | 50 + tests/fixtures/riffer/original-bass.briff | 18 + tests/fixtures/riffer/original-lead.griff | 19 + tests/fixtures/sd3/original-score.json | 36 + tests/fixtures/sd3/original-template.sd3p | 81 ++ tests/integration/test_agp_capability.py | 136 ++ tests/integration/test_articulation_midi.py | 565 +++++++++ tests/integration/test_cc_stdio.py | 332 +++++ tests/integration/test_contracts.py | 363 ++++++ tests/integration/test_distribution.py | 923 ++++++++++++++ tests/integration/test_explicit_music.py | 251 ++++ tests/integration/test_generation_service.py | 421 +++++++ tests/integration/test_hybrid_stdio.py | 352 ++++++ tests/integration/test_midi_files.py | 428 +++++++ tests/integration/test_native_service.py | 740 +++++++++++ tests/integration/test_phrase_stdio.py | 239 ++++ tests/integration/test_riffer_files.py | 92 ++ tests/integration/test_sd3p_files.py | 60 + tests/integration/test_sdp_capability.py | 231 ++++ tests/integration/test_stdio.py | 595 +++++++++ tests/integration/test_text_feedback.py | 217 ++++ tests/integration/test_text_to_midi.py | 261 ++++ tests/unit/test_agp.py | 233 ++++ tests/unit/test_articulations.py | 529 ++++++++ tests/unit/test_cc_controls.py | 247 ++++ tests/unit/test_compose.py | 266 ++++ tests/unit/test_description.py | 308 +++++ tests/unit/test_errors.py | 88 ++ tests/unit/test_explicit_plan.py | 212 ++++ tests/unit/test_hybrid.py | 377 ++++++ tests/unit/test_midi.py | 683 ++++++++++ tests/unit/test_native_contracts.py | 67 + tests/unit/test_package.py | 53 + tests/unit/test_phrase_timing.py | 340 +++++ tests/unit/test_pitch.py | 225 ++++ tests/unit/test_profiles.py | 444 +++++++ tests/unit/test_readme.py | 125 ++ tests/unit/test_riffer.py | 512 ++++++++ tests/unit/test_schemas.py | 821 ++++++++++++ tests/unit/test_sd3p.py | 454 +++++++ tests/unit/test_sdp.py | 250 ++++ tests/unit/test_server.py | 550 ++++++++ tests/unit/test_service.py | 508 ++++++++ tests/unit/test_standard_profiles.py | 180 +++ 124 files changed, 32998 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 docs/architecture.md create mode 100644 docs/articulation-profiles.md create mode 100644 docs/compatibility.md create mode 100644 docs/formats/agp.md create mode 100644 docs/formats/sdp.md create mode 100644 prompts/plan.md create mode 100644 prompts/report_1.md create mode 100644 prompts/report_10.md create mode 100644 prompts/report_11.md create mode 100644 prompts/report_12.md create mode 100644 prompts/report_13.md create mode 100644 prompts/report_14.md create mode 100644 prompts/report_15.md create mode 100644 prompts/report_15_fix.md create mode 100644 prompts/report_16.md create mode 100644 prompts/report_2.md create mode 100644 prompts/report_3.md create mode 100644 prompts/report_4.md create mode 100644 prompts/report_5.md create mode 100644 prompts/report_5_fix.md create mode 100644 prompts/report_6.md create mode 100644 prompts/report_7.md create mode 100644 prompts/report_7_fix.md create mode 100644 prompts/report_8.md create mode 100644 prompts/report_8_fix.md create mode 100644 prompts/report_9.md create mode 100644 prompts/report_9_fix.md create mode 100644 prompts/report_9_fix_controls.md create mode 100644 prompts/step_1.md create mode 100644 prompts/step_10.md create mode 100644 prompts/step_10_fix.md create mode 100644 prompts/step_11.md create mode 100644 prompts/step_12.md create mode 100644 prompts/step_13.md create mode 100644 prompts/step_14.md create mode 100644 prompts/step_15.md create mode 100644 prompts/step_15_fix.md create mode 100644 prompts/step_16.md create mode 100644 prompts/step_2.md create mode 100644 prompts/step_3.md create mode 100644 prompts/step_4.md create mode 100644 prompts/step_5.md create mode 100644 prompts/step_5_fix.md create mode 100644 prompts/step_6.md create mode 100644 prompts/step_7.md create mode 100644 prompts/step_7_fix.md create mode 100644 prompts/step_8.md create mode 100644 prompts/step_8_fix.md create mode 100644 prompts/step_9.md create mode 100644 prompts/step_9_fix.md create mode 100644 prompts/step_9_fix_controls.md create mode 100644 pyproject.toml create mode 100644 src/riff_groove_builder/__init__.py create mode 100644 src/riff_groove_builder/__main__.py create mode 100644 src/riff_groove_builder/articulations.py create mode 100644 src/riff_groove_builder/compose.py create mode 100644 src/riff_groove_builder/data/__init__.py create mode 100644 src/riff_groove_builder/data/profiles/__init__.py create mode 100644 src/riff_groove_builder/data/profiles/ample-metal-eclipse-4.0.1-riffer-v1.json create mode 100644 src/riff_groove_builder/data/profiles/ample-metal-ray5-4.1.0-riffer-v1.json create mode 100644 src/riff_groove_builder/data/profiles/general-midi-percussion-v1.json create mode 100644 src/riff_groove_builder/data/profiles/standard-midi-bass-v1.json create mode 100644 src/riff_groove_builder/data/profiles/standard-midi-lead-v1.json create mode 100644 src/riff_groove_builder/data/profiles/toontrack-sd3-3.4.4-core-v1.json create mode 100644 src/riff_groove_builder/description.py create mode 100644 src/riff_groove_builder/errors.py create mode 100644 src/riff_groove_builder/formats/__init__.py create mode 100644 src/riff_groove_builder/formats/agp.py create mode 100644 src/riff_groove_builder/formats/sdp.py create mode 100644 src/riff_groove_builder/hybrid.py create mode 100644 src/riff_groove_builder/midi.py create mode 100644 src/riff_groove_builder/pitch.py create mode 100644 src/riff_groove_builder/profiles.py create mode 100644 src/riff_groove_builder/schemas.py create mode 100644 src/riff_groove_builder/server.py create mode 100644 src/riff_groove_builder/service.py create mode 100644 tests/fixtures/profiles/synthetic-bass.json create mode 100644 tests/fixtures/profiles/synthetic-drums.json create mode 100644 tests/fixtures/profiles/synthetic-lead.json create mode 100644 tests/fixtures/riffer/original-bass.briff create mode 100644 tests/fixtures/riffer/original-lead.griff create mode 100644 tests/fixtures/sd3/original-score.json create mode 100644 tests/fixtures/sd3/original-template.sd3p create mode 100644 tests/integration/test_agp_capability.py create mode 100644 tests/integration/test_articulation_midi.py create mode 100644 tests/integration/test_cc_stdio.py create mode 100644 tests/integration/test_contracts.py create mode 100644 tests/integration/test_distribution.py create mode 100644 tests/integration/test_explicit_music.py create mode 100644 tests/integration/test_generation_service.py create mode 100644 tests/integration/test_hybrid_stdio.py create mode 100644 tests/integration/test_midi_files.py create mode 100644 tests/integration/test_native_service.py create mode 100644 tests/integration/test_phrase_stdio.py create mode 100644 tests/integration/test_riffer_files.py create mode 100644 tests/integration/test_sd3p_files.py create mode 100644 tests/integration/test_sdp_capability.py create mode 100644 tests/integration/test_stdio.py create mode 100644 tests/integration/test_text_feedback.py create mode 100644 tests/integration/test_text_to_midi.py create mode 100644 tests/unit/test_agp.py create mode 100644 tests/unit/test_articulations.py create mode 100644 tests/unit/test_cc_controls.py create mode 100644 tests/unit/test_compose.py create mode 100644 tests/unit/test_description.py create mode 100644 tests/unit/test_errors.py create mode 100644 tests/unit/test_explicit_plan.py create mode 100644 tests/unit/test_hybrid.py create mode 100644 tests/unit/test_midi.py create mode 100644 tests/unit/test_native_contracts.py create mode 100644 tests/unit/test_package.py create mode 100644 tests/unit/test_phrase_timing.py create mode 100644 tests/unit/test_pitch.py create mode 100644 tests/unit/test_profiles.py create mode 100644 tests/unit/test_readme.py create mode 100644 tests/unit/test_riffer.py create mode 100644 tests/unit/test_schemas.py create mode 100644 tests/unit/test_sd3p.py create mode 100644 tests/unit/test_sdp.py create mode 100644 tests/unit/test_server.py create mode 100644 tests/unit/test_service.py create mode 100644 tests/unit/test_standard_profiles.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb4efc1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +.venv/ +.test-artifacts/ +build/ +dist/ +*.egg-info/ +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +.coverage +htmlcov/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..a844627 --- /dev/null +++ b/README.md @@ -0,0 +1,784 @@ +# Riff-Groove-Builder + +Local Windows Python MCP server that turns supported text into coordinated +native Riffer/SD3 and Standard MIDI lead, bass, and drum parts. The supported +target subsets are evidence-backed, not application-certified. The amended approved +[plan](prompts/plan.md) is authoritative. + +**Current release: 0.2.0 — exact hybrid Counts/Events/Notes/Chords notation, +pitch/voicing interpretation, native/MIDI generation and atomic publication.** +The single version source is `riff_groove_builder.__version__`; package metadata +and MCP initialization both report **0.2.0** after a server restart. +The SDK-backed tools list three target defaults and three explicit standard +fallback profiles, and generate real native files and type-1 `.mid` files +from a deterministic closed grammar. +**Real Riffer XML 2.1 `.griff`/`.briff` writers and independent saved-file +validation support AME 4.0.1 normal/palm-mute/pinch-harmonic and AMR 4.1.0 +normal/palm-mute subsets.** +**SD3 3.4.4 now has a real operator-template `.sd3p` song codec and SL-DFH +core three-voice subset.** All codecs are wired to the MCP service. +Application open/play/save/reload and Cubase acceptance remain unrun. +See [native codec API/evidence](docs/formats/agp.md) and +[SD3 codec/results](docs/formats/sdp.md), [current report](prompts/report_16.md). +Step-numbered earlier reports remain historical evidence, not retroactive +claims that earlier releases already supported public hybrid notation. +This is not a general natural-language model. + +## Python and dependencies + +The declared Python minimum is **3.11**. Selected direct dependencies' published +Python requirements permit that minimum; only **CPython 3.13.13, Windows AMD64** +has actually been tested. Other runtimes are not certified. + +Runtime dependencies are the official `mcp` Python SDK (maintained 1.x API line), +Pydantic 2, and Mido. The development extra includes MIDIUtil for independent +synthetic MIDI reference tests, pytest, AnyIO's built-in pytest plugin, Ruff, mypy, +build tooling, and directly declared jsonschema plus its typing stubs for +contract validation. Future asynchronous tests should use `@pytest.mark.anyio` +with an `anyio_backend` fixture selecting `"asyncio"`, as the SDK does; +Trio and pytest-asyncio are not required. + +Ranges are bounded compatibility constraints, not a lockfile or a claim that +every allowed version was tested. Exact tested versions are recorded in +[report_1.md](prompts/report_1.md), [report_2.md](prompts/report_2.md), and +[report_3.md](prompts/report_3.md), plus [report_4.md](prompts/report_4.md). +The current tested configuration and separate software/application outcomes are +in the [compatibility matrix](docs/compatibility.md#tested-software-configuration) +and [release report](prompts/report_16.md). +The SDK installs its own transport-related +transitive dependencies; this project adds no HTTP application or audio backend. + +## Windows PowerShell setup + +Run from the repository root. Set `$Python` to your installed Python >=3.11; +the following is the actual interpreter used for Step 1. No activation or +global package installation is needed. Scratch/build/install files stay inside +the ignored repository-local `.test-artifacts` directory. + +```powershell +$Python = 'C:\Users\g3\AppData\Local\Programs\Python\Python313\python.exe' +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +& $Python -m venv .venv +& '.\.venv\Scripts\python.exe' -m pip install --disable-pip-version-check --no-cache-dir -e '.[dev]' +& '.\.venv\Scripts\python.exe' -m pip check +``` + +Initial dependency installation needs access to the package index (or an +operator-provided local wheelhouse). All subsequent checks below are offline +once those dependencies are installed. Set the scratch environment variables +again in each new shell before running builds. + +## Start the MCP stdio service + +After installing the package, provision an output directory yourself (or choose +an existing local directory). The server requires this option and pins the root. +Generation writes only under this root; startup does not probe writeability. +For example, in PowerShell: + +```powershell +# Operator setup only; omit this if the directory already exists. +New-Item -ItemType Directory -Path 'D:\MusicGenOutput' +& '.\.venv\Scripts\python.exe' -m riff_groove_builder --output-dir 'D:\MusicGenOutput' +# Optional operator-local SD3 template; never supplied through tool arguments: +& '.\.venv\Scripts\python.exe' -m riff_groove_builder --output-dir 'D:\MusicGenOutput' --sd3-template 'C:\Users\g3\Documents\Toontrack\Superior Drummer 3\sd3-demo.sd3p' +``` + +This is a stdio protocol process, not an interactive console: normally an MCP +client launches it and sends initialization. Closing stdin ends the SDK session; +there is no custom shutdown request. No HTTP transport is provided. Missing, +nonexistent, non-directory, URI, UNC, device, and drive-relative roots are +rejected with stderr diagnostics and a nonzero exit, without protocol stdout. +Local existing relative paths are resolved against the launch working directory. +Root/ancestor links and Windows reparse points, traversal and mapped network +drives are rejected. Existing directory identities are rechecked during generation. +Publication currently requires Windows no-replace directory-rename semantics; +other OSes explicitly fail generation rather than silently weaken collision safety. +See [filesystem guarantees and limitations](docs/architecture.md#implemented-in-step-9). +Use trusted operator-controlled ACLs on the root, ancestors and volume: path +identity/reparse checks are not hostile-race-proof Windows handle confinement. +Failures clean only the verified owned stage; denied/unsafe cleanup is an +explicit error and may leave a stage for inspection. Rename is the commit point: +a crash or client disconnect afterward may leave valid output without a response. +No fsync/power-loss durability or post-publication rollback is promised. + +### LM Studio MCP configuration + +Following the [official LM Studio MCP setup](https://lmstudio.ai/docs/app/mcp), +the operator opens **Program → Install → Edit mcp.json**. +In LM Studio's MCP configuration, use the top-level **`mcpServers`** object, +not VS Code's `servers` object or its `type` field. The absolute interpreter +path makes this independent of LM Studio's working directory. The configured +output root **must already exist**; this example does not create it: + +```json +{ + "mcpServers": { + "riff-groove-builder": { + "command": "D:\\_Repos\\Code\\GAJ3T\\MCPs\\MusicGen\\GAJ3T.MusicGen.Riff-Groove-Builder\\.venv\\Scripts\\python.exe", + "args": ["-m", "riff_groove_builder", "--output-dir", "D:\\MusicGenOutput"] + } + } +} +``` + +Adapt the interpreter and existing root to your installation. VS Code uses a +different `.vscode\mcp.json` shape (`servers` and `type: "stdio"`); do not paste +that shape into LM Studio. This is operator documentation only: no live +LM Studio configuration, active chat, process or DAW is modified or certified. +Automated tests use the official MCP client and real module subprocesses. +For all-native operation append `"--sd3-template", "C:\\Users\\g3\\Documents\\Toontrack\\Superior Drummer 3\\sd3-demo.sd3p"` +to the client `args` array. Use your own SD3 3.4.4 SL-DFH project; no private +project or kit is shipped. It is read-only, validated at startup and pinned by +identity/size/mtime/hash during generation. Absent optional template is known +native unavailability; explicitly supplied missing, corrupt, unsupported or +changed templates are visible errors (never fallback). Source kit/mixer/tracker +and other non-song bytes are preserved in the generated local project. + +Exactly two tools publish the reviewed input/output schemas: + +- `list_instrument_profiles({})` returns six profiles: three target defaults + and three explicit standard fallbacks (`mapping_kind=standard_midi`). + `native_available` is runtime readiness, not just codec metadata. + SD3 `toontrack.sd3.3.4.4.core.v1` additionally requires a local template; + its mapped MIDI works without a template. Version/library/subset, defaults, + template requirements and unrun application certification appear in limitations. +- `generate_music` validates arguments, resolves text, selects maps, composes, + compiles, writes/reads back every requested available output in one unique stage, + then atomically publishes `\`. Success returns `structuredContent` + matching `GenerationResult`. Every profile-list, generation and domain/validation + error result also includes the complete same public object encoded as JSON in + one `TextContent` block: `json.loads(content[0].text) == structuredContent`. + Text-only MCP clients therefore see real IDs, paths, metadata, warnings and + actionable corrections, not just a summary. +- Omitted/null `formats` means combined MIDI plus each selected part's actual native + target: `_lead.griff`, `_bass.briff`, + `_drums.sd3p`, and `.mid`. + Explicit `["mid"]` is complete without native preflight or a template. + Native-only requests emit only requested native files when all are available. + Missing template with allowed fallback retains real lead/bass natives plus one + combined MIDI with `fallback_for=["drums"]` and a per-part + `NATIVE_FORMAT_UNAVAILABLE` warning. Fallback disabled fails before staging. +- Requests also accept actual `griff` / `briff` / `sd3p` suffix names for their + corresponding parts; `agp` / `sdp` remain logical aliases. Public profile and + artifact metadata use actual suffixes, never mislabeled `agp` / `sdp` bytes. + Aliases and actual names together are deduplicated by actual part/format. +- Target parts receive `VERIFIED_SUBSET_LIMITS` warnings, even for MIDI-only + output; saved-file validation does not certify every tuning/technique/library. +- All standard-profile parts always receive `STANDARD_MIDI_MAPPING` warnings, + including explicit MIDI-only successes. No vendor compatibility is implied. +- Existing destinations (including empty directories) return `OUTPUT_EXISTS`; + no replacement or merge is allowed. Other IO/serialization/unsupported-technique + failures never become fallback successes. +- Invalid tool inputs return typed `INVALID_REQUEST` errors with safe field/reason/correction + details. Unknown tools and protocol errors retain SDK error behavior rather + than being disguised as domain errors. + +For guitar-only output use `parts: ["lead"]` and omit `formats`, or request +`["griff", "mid"]` (`agp` is the lead/bass alias). Bass uses `briff`/`agp`; +drums uses `sd3p`/`sdp`; `mid` works for all. `sd3p` is not a guitar format. +Omit `profiles` for defaults, or call `list_instrument_profiles({})` and copy +exact IDs for the selected parts. Never invent IDs such as `aggressive_rock`. +Do not add CC events (including reverb CC91) unless the user requests them. +Pass musical intent faithfully: the bounded beat-range/triplet/PH-hold grammar and +the [precise hybrid lanes](#hybrid-prose-and-exact-lanes) below are supported; +arbitrary prose melodies and changes/sequences are +unsupported, not invitations to invent a simpler result. + +Structured `key` accepts full forms (`E minor`, `E Minor`, `Bb major`) and +conventional minor shorthand (`Em`, `F#m`, `Bbm`), canonicalized to sharp-spelled +pitch classes and lowercase mode. Thus `Em` and both E-minor full forms resolve +to `E minor`; `Bbm` resolves to `A# minor`. Use one optional ASCII `#` or +lowercase `b`; other modes, missing modes/bare letters, double/Unicode accidentals, +tabs and newlines remain invalid in structured keys. Description text also accepts +attached minor shorthand (`Em`, `F#m`, `Bbm`). + +After updating an existing LM Studio installation, restart its MCP server and +start a **fresh chat** to refresh cached tool schemas/descriptions; an existing +chat can keep stale tool descriptions and previous wrong-call assumptions. +The operator must do both, then confirm initialization reports version **0.1.1**, +rediscover the two tools and, if selecting explicit profiles, call +`list_instrument_profiles({})` again. Retry the original request verbatim with +the minimal arguments below, not fabricated profiles, a drum format for lead, +or unsolicited CC91. Automated tests launch their own stdio children only; +they do not restart the live LM Studio process or demonstrate live model/UI success. + +stdout contains only UTF-8 newline-delimited MCP JSON-RPC. Logs and startup +errors use stderr. SDK malformed-input handling can also send a protocol +`notifications/message` with generic `Internal Server Error`; this is not a raw +stdout log or a parse-error response. See [observed protocol behavior and +privacy boundaries](docs/architecture.md#implemented-in-step-3). + +## Deterministic text-to-MIDI generation + +Example MCP `generate_music` arguments: + +```json +{ + "description": "lead bass drums 137.5 BPM 2 bars 7/8 Bb minor quarter rests", + "basename": "example", + "formats": ["mid"], + "profiles": { + "lead": "standard.lead.v1", + "bass": "standard.bass.v1", + "drums": "standard.gm-drums.v1" + }, + "seed": 42 +} +``` + +Discover available IDs with `list_instrument_profiles({})` before selecting +`profiles`, for example `{"lead":"standard.lead.v1","bass":"standard.bass.v1", +"drums":"standard.gm-drums.v1"}`. These are explicit standard fallbacks, not defaults. +Defaults are `ample.ame.4.0.1.riffer.v1`, `ample.amr.4.1.0.riffer.v1`, +`toontrack.sd3.3.4.4.core.v1`. IDs must match selected parts. +For all-native generation with the optional template configured: + +```json +{ + "description": "lead bass drums palm mute 137.5 BPM 2 bars 7/8 Bb minor quarter rests", + "basename": "example_native", + "formats": ["agp", "sdp"], + "seed": 42, + "allow_midi_fallback": false +} +``` + +Omitting `formats` additionally requests MIDI. Without a template, omit +`allow_midi_fallback=false` to get real lead/bass natives plus drum MIDI fallback. + +### Optional exact controller points + +`cc_events` defaults to `[]`; omission/empty leaves all existing output unchanged. +Each strict object has only `part`, `beat`, `controller`, `value`. Beats are +nonnegative rational **quarter-note** positions relative to the common musical +start (after any articulation pre-roll), not absolute MIDI ticks or bar numbers. +For example, request lead/bass CC1 points and an explicit musical-end reset: + +```json +{ + "description": "lead bass 2 bars 7/8 quarter", + "basename": "controlled", + "allow_midi_fallback": false, + "cc_events": [ + {"part": "lead", "beat": {"numerator": 0}, "controller": 1, "value": 11}, + {"part": "lead", "beat": {"numerator": 1, "denominator": 2}, "controller": 1, "value": 73}, + {"part": "lead", "beat": {"numerator": 7}, "controller": 1, "value": 0}, + {"part": "bass", "beat": {"numerator": 1}, "controller": 1, "value": 127}, + {"part": "bass", "beat": {"numerator": 7}, "controller": 1, "value": 0} + ] +} +``` + +Controller/value are strict integers 0–127 (no booleans, floats, strings or +clamping). The rational numerator/denominator are strict integers; denominator +must be positive. Ratios normalize; duplicate `(part, beat, controller)` points +are rejected even if values agree or fractions differ in spelling. Parts must +be selected after text resolution, points must fit the resolved musical duration +(end resets are valid), and beats must fit the exact 960-PPQ tick grid. Controls, +musical note-ons/offs and articulation switches share the 100,000-event budget. +An explicit point colliding with an articulation-generated controller is an +actionable `INVALID_REQUEST`, not an override. Controls precede note-ons at the +same tick; no implicit reset or controller-to-technique/effect inference exists. + +MIDI retains every valid requested controller/channel/tick/value, including +multiple controllers and end resets. The observed Riffer subset preserves only +CC1 stair points on its exact 480-PPQ grid; other controllers or sub-native-grid +timing cannot be silently dropped. The observed SD3 native subset establishes +note triples, **not controller triples**. A legitimate drum CC yields the +precise native preflight reason `sd3_native_controller_not_supported`. +Allowed fallback replaces only the affected native target with combined MIDI; +other valid natives remain. `allow_midi_fallback=false` fails before staging. +Wrong channel/note/role/release, corrupt templates and writer/read-back failures +remain errors, never controller fallback. Explicit `formats: ["mid"]` supports +all valid controls without native preflight or a drum template. + +The explicit **standard-profile** MIDI example's shared public payload is shown below; +the 324-byte artifact is independently checked by installed-wheel tests. +The wire result has `isError: false`, this object in `structuredContent`, and +one text block containing a JSON encoding of the entire same object. +Its non-null `profiles` do not create structured musical overrides: + +```json +{ + "status": "complete", + "resolved": { + "parts": ["lead", "bass", "drums"], + "tempo_bpm": 137.5, + "bars": 2, + "time_signature": {"numerator": 7, "denominator": 8}, + "key": "A# minor", + "seed": 42, + "profile_ids": { + "lead": "standard.lead.v1", + "bass": "standard.bass.v1", + "drums": "standard.gm-drums.v1" + }, + "assumptions": [ + "template: omitted; using rock.", + "technique: omitted; using normal." + ], + "overrides": [], + "musical_start_tick": 0, + "musical_end_tick": 6720, + "ticks_per_quarter": 960 + }, + "artifacts": [ + { + "format": "mid", + "parts": ["lead", "bass", "drums"], + "path": "D:\\MusicGenOutput\\example\\example.mid", + "size_bytes": 324, + "profile_ids": ["standard.lead.v1", "standard.bass.v1", "standard.gm-drums.v1"], + "fallback_for": [] + } + ], + "warnings": [ + {"code": "STANDARD_MIDI_MAPPING", "part": "lead", "message": "standard.lead.v1 uses Standard MIDI only; not a verified Eclips/Ray/SD3 mapping or vendor compatibility claim."}, + {"code": "STANDARD_MIDI_MAPPING", "part": "bass", "message": "standard.bass.v1 uses Standard MIDI only; not a verified Eclips/Ray/SD3 mapping or vendor compatibility claim."}, + {"code": "STANDARD_MIDI_MAPPING", "part": "drums", "message": "standard.gm-drums.v1 uses Standard MIDI only; not a verified Eclips/Ray/SD3 mapping or vendor compatibility claim."} + ] +} +``` + +Explicitly selecting those standard profiles with native formats reports +`status="midi_fallback"`, `fallback_for=["lead","bass","drums"]` +on the single combined artifact, and three additional per-part +`NATIVE_FORMAT_UNAVAILABLE` warnings with `riffer_profile_not_supported` (lead/bass) +or `sdp_profile_not_supported` (standard drums). It returns no native artifact. +For example, `{"description":"drums only","basename":"disabled", +"allow_midi_fallback":false}` returns `isError=true`, text guidance, and: + +```json +{ + "code": "NATIVE_FORMAT_UNAVAILABLE", + "message": "Request MIDI fallback or select a profile with verified native support.", + "details": {"part": "drums", "format": "sd3p", "reason": "sdp_template_required"} +} +``` + +That object is both `structuredContent` and the decoded JSON text, not a +JSON-RPC protocol error. No `disabled` +directory is created. The default drum profile is MIDI-capable without a template. +`lead only palm mute` now produces actual PM data with the default target profile; +explicit standard profiles still return `UNSUPPORTED_ARTICULATION`. + +The Python service API is +`GenerationService(Path(existing_root), sd3_template=Path(local_sd3p)).generate_music(GenerateMusicRequest(...))`. +The `sd3_template` keyword is optional; `create_server` accepts the same typed keyword. +`list_instrument_profiles()` returns `ProfileListResult`. Service failures use +the existing named domain errors; raw descriptions/file bytes are not results. +Only the final directory is published. No sidecar manifests are generated. + +The supported vocabulary is intentionally small. For example: + +- `lead only 90 BPM 2 bars in 3/4 D major quarter` +- `bass guitar groove 72.5 BPM 3 bars 6/8 Bb minor eighth` +- `drums only 155 BPM 2 bars 7/8 sixteenth` +- `lead bass drums 137.5 BPM 4 bars F# minor metal eighth with rests` +- `no drums` selects lead and bass, not drums. + +Lower-level usage with an **existing** output directory (the writer never creates +directories or overwrites a destination): + +```python +from pathlib import Path + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.midi import write_midi +from riff_groove_builder.profiles import load_profile_registry +from riff_groove_builder.schemas import GenerateMusicRequest, ProfileSelection + +request = GenerateMusicRequest( + description="bass only 1 bar C major quarter", basename="example", seed=0 +) +resolution = resolve_description(request) +profiles = load_profile_registry().select( + resolution.intent.parts, request.profiles or ProfileSelection() +) +score = compose_score(resolution.intent, profiles) +plan = compile_score(score, profiles) +write_midi(Path(r"D:\MusicGenOutput") / f"{request.basename}.mid", plan) +``` + +`resolution.assumptions` and `.overrides` are explicit string records used by +the service's `ResolvedGeneration`; this lower-level API does not create a result. +Structured tempo/bars/meter/key/parts win, including contradictory text for that +field. Unresolved contradictions and unknown material are named errors. +Defaults: 120 quarter-note BPM, four bars, 4/4, E minor, all three parts, +straight eighth notes, rock template, no rests, normal technique; request seed 0. +`slow` is 80 BPM and `fast` is 160, not a genre-dependent interpretation. + +Case/whitespace-insensitive grammar supports decimal `BPM` (20–300), integer-valued +`bar(s)` (1–256; text `4.0 bars` is four bars), one fixed `n/d` meter +(numerator 1–16, denominator 1/2/4/8/16), major/natural-minor keys, +part lists/`only`/exclusions, +`quarter`/`eighth`/`sixteenth` (optional `-note(s)` or ` note(s)`), `rock`/`metal`, +and `rests`/`no rests`. Rests omit the last subdivision slot of **every** bar; +they do not shorten the score. Simple pattern instructions are global, not per-part schedules. +Palm mute applies to selected lead/bass only; in mixed requests drums remain +normal and that applicability is recorded in assumptions. Drum-only palm mute +fails explicitly, never silently disappearing. Part aliases include guitar/riff -> lead, bass guitar +(optionally riff/groove) -> bass, drum/drums -> drums. +Only these filler words are ignored: `please create produce generate make write a an the +some simple music pattern groove for with and at in of on notes note key tempo +meter straight`. This is not arbitrary prose; at least one recognized instruction +or `music`/`pattern`/`groove` is required. +Keys use A–G with optionally one ASCII `#` or `b`, then `major`/`minor` or attached `m`; +structured keys require ASCII spaces and reject other modes/double accidentals. +Enharmonic names normalize to sharp spelling (`Bb minor` → `A# minor`). +Non-null structured tempo/bars/meter/key/parts override text for that field, +including contradictions, and are disclosed in `overrides`; null is unresolved. +They do not authorize unknown vocabulary or changing instructions. Structured +integer fields reject `4.0`, booleans and strings even though text bars accept +integer-valued decimals. Descriptions are 1–4000 nonblank characters; +seed is a structured integer 0–2147483647, default 0, not text syntax. +See the [exact grammar, defaults, registers and template policies](docs/architecture.md#implemented-in-step-6-deterministic-text-and-composition). + +### Hybrid prose and exact lanes + +`generate_music.description` also accepts the following **public** notation. +Prose sets context; lanes specify exact music, never timing from column width. +The original two-measure E2 request remains byte-identical. This is the exact +description tested through source and the persisted 0.2.0 wheel: + +```text +Lead guitar in E minor, 4/4, 120 BPM, 2 bars. +Bar 1: +Counts: 1 & 2 & 3 & [4 trip let] +Events: x x x x x x [x x ^] +Notes: E2 E2 E2 E2 E2 E2 E2 E2 E2 +Hold the final E2 through the end of bar 2 without retriggering. +``` + +### Restart and fresh-chat prompt for 0.2.0 + +**After this verified update, restart the riff-groove-builder MCP in LM Studio +NOW, then start a NEW chat** to refresh cached tool descriptions and schemas. +The existing configured `.venv\Scripts\python.exe` resolves 0.2.0; no MCP config +edit or config reinstall is required. No live LM Studio/model/DAW interaction +or playback was run. + +Copy the following prompt into that fresh chat. The description between the +markers is exactly the description above; markers/instructions are not part +of the tool's `description`. Pick a new unique basename on each later run: + +```text +Call generate_music once. Set basename to "em_e2_hybrid_20261020_fresh_chat_01" +and allow_midi_fallback to false. Set description verbatim to the text between +BEGIN DESCRIPTION and END DESCRIPTION below. Omit all other arguments; do not +invent formats, profiles, control changes, programs, effects or an SD3 template. +Return the actual tool result and its output paths, not a claimed playback. +BEGIN DESCRIPTION +Lead guitar in E minor, 4/4, 120 BPM, 2 bars. +Bar 1: +Counts: 1 & 2 & 3 & [4 trip let] +Events: x x x x x x [x x ^] +Notes: E2 E2 E2 E2 E2 E2 E2 E2 E2 +Hold the final E2 through the end of bar 2 without retriggering. +END DESCRIPTION +``` + +Minimal arguments `description` and `basename` alone are also tested; seed +defaults to 0, and lead-only `.mid` plus `.griff` and the target AME profile +resolve without invented IDs. The strict prompt above disables fallback to +require a real native file. It produces eight PM E2 attacks then one PH E2, +with no bar-2 retrigger, no CC/program/effects and no drum template. + +For chords plus melody, replace those pitch rows with: + +```text +Chords: F#2 F#2 D3 D3 Bb2 Bb2 - - - +Notes: - - - - - - C4 E4 G4 +``` + +Change the hold's pitch to G4. This gives **21 musical tones**: six PM major +chord attacks, PM C4/E4, then one PH G4 through bar 2. D3 is exactly +MIDI50/54/57; explicit **D2** means MIDI38/42/45 and cannot be fingered +simultaneously on the accepted AME tuning. D2 therefore requires allowed +exact-MIDI fallback, or fails before publication when fallback is disabled. +It is never silently transposed to D3. + +- Lane labels are case-insensitive; pitch letters remain uppercase A–G, + optional ASCII `#`/`b`, optional octave (**C4=60**). Compact/space/tab forms + are equivalent; `Chords: F#F# D3D3 BbBb ---` resolves omitted octaves visibly. +- Counts use meter-denominator beats: `1&` / `1 &` are eighths, + `1e&a` / `1 E & A` are sixteenths, `[4 trip let]` declares triplets. + Bare `1&a` errors unless `Grid:` / `Subdivision:` is `sixteenths` or + `eighth-triplets`; `eighths` is also supported. Bare numbers always mean + whole denominator beats. With sixteenth grid, `1&a` explicitly omits `e` + and uses offsets 0, 1/2, 3/4 (durations to next position/beat end). + 3/4 and other denominator units use exact rational math, not compound grouping. +- `o` is normal/open **articulation**, not open-string fingering; `x` is PM; + `^` is AME lead-only PH; `-` is silence; `~` extends the adjacent prior sound + without a new attack. A tie after silence or carrying new pitches errors. + `/` and `\` in Events are **reserved, not implemented** slides, not normal + notes. They return an actionable origin/destination/timing codec error; + slash/Over in Chords is a separate supported bass-voicing operation. +- `Chords:` supports bare major, `m`/`min`, `(add4)`, octave-qualified roots, + `/` or `Over` bass and `[C3 E3 G3]` simultaneous explicit voicing. + In **Notes** (and Events), brackets group consecutive slots, not a chord. + `Em4OverB2` gives 47/64/67/71; `Em4/B` gives 59/64/67/71 with the bass + octave assumption disclosed. An explicit bass must already be lowest. +- One selected guitar/lead or bass part; Counts/Events are required per bar; + absent Notes/Chords rows are empty. One pitch source per slot; an entirely + unspecified attack source uses the disclosed low tonic nearest MIDI40. + Matching `|` boundaries or ordered `Bar N:` blocks support additional bars. + `Bar 2: hold previous note to bar end` or an all-`~` second bar also sustains + the same original attack and articulation. +- Key is context, never retuning. Contradictory explicit pitch/technique prose, + mismatched rows, ambiguous counts, invalid labels, unknown material, conflicting + rests/holds or incompatible meter/shorter-bar overrides are actionable errors. + Aggressive/tight metal style, low-register chord voicings and bounded velocity + variation do not alter precise notation. Seed policy is one existing bounded + draw per attack, shared by its tones; no unrequested CC/effects. + +Complete text JSON and `structuredContent` include identical +`resolved.interpretation`: pitch sets, rational quarter-beat start/duration, +technique, part and held status. `resolved.assumptions` discloses register, +slash-bass and missing-pitch defaults. Prose-only outputs retain their old +musical bytes. No arbitrary natural-language rhythm or slide support is claimed. + +Standard profiles realize `normal`/`sustain` only (`sustain` is not CC64). +Recognized `palm mute`, `palm-mute`, `palm muted`, `palm-muted`, `palm muting` fail with +`UnsupportedArticulationError` under those profiles; they are never simulated +by softer notes. Other techniques/instruments/modes, arbitrary triplets, swing, +polyrhythms, tempo changes, sections, vendor-name selection and audio requests +are unsupported. Composition is original bounded templates with local seeded +variation, not a genre engine, audio engine, factory loop or vendor map. +Target normal uses C0/24 with velocities 64–126. Target guitar palm mute uses +D0/26 and native PM; bass uses C0/24 with musical velocity 32–63 and native +**PMP**, not the separate D0 PM mode. Timing/channel/interpolation policy is +documented separately from vendor facts in the profile docs. + +### Exact beat-range / triplet / cross-bar PH phrase + +The following description works directly, with only a safe `basename`: + +> Please produce a 4/4 riff in Em. With Chugging palm muting 8th notes from 1 to 3&; +> and triplets on 4&A with the A as a pinch harmonic that carries over a whole note +> in the 2nd measure. + +Minimal executable `generate_music` arguments (the description is verbatim, +including its line breaks): + +```json +{ + "description": "Please produce a 4/4 riff in Em. With Chugging palm muting 8th notes from 1 to 3&;\nand triplets on 4&A with the A as a pinch harmonic that carries over a whole note\nin the 2nd measure.", + "basename": "phrase-original" +} +``` + +Omitted `parts`, `formats` and `profiles` resolve to lead only, `.mid` plus +`_lead.griff`, and `ample.ame.4.0.1.riffer.v1`. No drum template is needed. +`allow_midi_fallback` defaults to true; setting it to false is optional and +also succeeds for this evidenced native phrase. Omitted `cc_events` is empty. + +This bounded lead-only 4/4 grammar requires both clauses: `[Chugging] palm +mute/muted/muting eighth/8th [notes] from X to Y`, and `triplets on B & A with +the A as a pinch harmonic that carries over a whole note in the second/2nd measure`. +Hyphenated palm-mute/muted/muting and pinch-harmonic also work. X/Y are inclusive +numeric beat labels 1–4, optionally followed by `&`; B is a numeric beat 1–4. +Whitespace around `&` is optional. Numeric ranges are computed, not canned: +`from 2 to 3&` starts at quarter beat 1 instead of 0. Overlapping/reversed +ranges, out-of-bar counts, non-4/4 meter, fewer than two bars, other parts, +extra rhythm/technique instructions and unsupported prose fail explicitly. +Scalar overrides cannot erase scheduled notes. Explicit longer scores keep +the phrase once, with trailing silence, not repeated bars. + +Assumptions are returned: unspecified tempo remains **120 BPM**; a hold through +measure 2 implies **two bars**; `A` is the last eighth-triplet **count**, not an +A pitch; all notes use the playable tonic nearest MIDI40 (**E2/MIDI40** for +default Em/AME). There is no invented melody, transposition or CC/effect. +The final PH holds continuously through all of measure 2, without a bar-2 attack. +At MIDI960 the nine onsets are **0,480,960,1440,1920,2400,2880,3200,3520**; +durations are six ×480, two ×320, then **4160**, with final off/EOT **7680**. +AME switches PM=D0/26 then PH=G0/31, with zero lead and positive 30-tick pulse +gates (generator policy). Native480 uses half these times and actual `PM`/`PH`; +PH ends at **3840**. Only AME has evidenced PH support; bass/SD3/standard maps +are not promoted. See [mapping evidence](docs/articulation-profiles.md#eclipse-pinch-harmonic-extension). + +The score uses exact quarter-note fractions; MIDI uses 960 ticks/quarter. +Each track spans exactly `bars * numerator * 4 / denominator` beats, including +rests. Simple-template notes may shorten only to fit the common bar boundary; +explicit phrase notes retain their exact cross-bar lengths. MIDI numbering +uses **C4 = 60**; simple-template preferred root anchors are E4 = 64 (lead), +E2 = 40 (bass), +adjusted to actual profile ranges, never clamped. GM kick/snare/hat aliases +resolve through the selected profile; no physical vendor notes are guessed. + +Focused offline checks (existing venv): + +```powershell +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_description.py tests\unit\test_compose.py tests\integration\test_text_to_midi.py -q +& '.\.venv\Scripts\python.exe' -m ruff check . +& '.\.venv\Scripts\python.exe' -m ruff format --check . +& '.\.venv\Scripts\python.exe' -m mypy --strict src tests +``` + +The integration checks write/read actual MIDI on disk, assert independent +tempo/meter/duration/pitch/channel/pairing facts, precise bass/drum events, +seeded byte determinism, and measured changes from supported text. +Their UUID-named repository-local workspaces clean themselves on success/failure. + +## Explicit event-plan MIDI writer + +`riff_groove_builder.midi` exposes typed internal-pipeline APIs: + +- `beats_to_ticks(beats, ppq=960)`, `bar_ticks(meter, bars=1, ppq=960)`, and + `quarter_tempo(tempo_bpm)` perform exact rational timing/tempo conversion. +- `validate_event_plan(plan)` checks strict model content, timing/SMF bounds, + channel isolation, and musical/keyswitch note pairing. +- `write_midi(path: Path, plan: EventPlan) -> Path` exclusively creates one SMF + type 1 file, validates it in memory, then reads actual saved bytes with Mido + and compares all tracks/events against the plan. Existing destinations are + never overwritten and parent directories are never created. +- `validate_midi_file(path: Path, plan: EventPlan)` independently reads disk + content for the same expected-content check; it never deletes its input. + +Timing uses integer ticks, default 960 ticks/quarter; off-grid fractions are +errors, not rounded approximations. BPM always means quarter notes/minute, +including 6/8. Tracks are Conductor followed by selected parts in resolved order, +with supplied notes/keyswitches/CCs, zero-tick tempo/meter, and one shared EOT. +Pre-roll and release tails are preserved without per-part shifts. +Same-channel/same-pitch overlap is rejected (including musical/keyswitch +collisions); boundary retriggers must release before re-onset according to the +supplied `(tick, priority, sequence)`. Different pitches can be polyphonic. +Distinct parts cannot share any stateful channel; no default drum channel, +program, real articulation map, or lead time is invented. + +This writer does not compile logical notes or verify instrument compatibility. +The Step 9 service adds directory confinement checks, atomic artifact-set +publication, requested formats, fallback policy and MCP wiring. See the detailed +[timing and failure policies](docs/architecture.md#implemented-in-step-4). + +## Validation + +```powershell +# Targeted tests +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_profiles.py tests\unit\test_articulations.py tests\integration\test_articulation_midi.py -q +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_midi.py tests\integration\test_midi_files.py -q +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_server.py tests\integration\test_stdio.py -q +& '.\.venv\Scripts\python.exe' -m pytest tests\integration\test_distribution.py -q -s +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_schemas.py tests\unit\test_errors.py tests\integration\test_contracts.py -q +& '.\.venv\Scripts\python.exe' -m pytest tests\unit -q +& '.\.venv\Scripts\python.exe' -m pytest tests\integration -q -s +# Complete current suite +& '.\.venv\Scripts\python.exe' -m pytest -q -s +# Lint, formatting, and strict types +& '.\.venv\Scripts\python.exe' -m ruff check . +& '.\.venv\Scripts\python.exe' -m ruff format --check . +& '.\.venv\Scripts\python.exe' -m mypy +& '.\.venv\Scripts\python.exe' -m pip check +# Both sdist and wheel; the wheel is built from the sdist by default +& '.\.venv\Scripts\python.exe' -m build --no-isolation +``` + +If the editor test runner cannot discover these files, use the explicit +`.venv\Scripts\python.exe -m pytest` commands above; editor discovery failure +is not a test pass. Model/schema integration tests are entirely in memory and +make no mapping or file-generation claims. See the implemented +[contract and timing representation](docs/architecture.md#implemented-in-step-2). +The stdio tests launch the editable installed module with isolated imports from +a different working directory, negotiate with the SDK client, and use a small +raw test client for IDs, notifications, malformed input, stderr privacy, and EOF. +Timeouts and process cleanup are enforced; actual generated disk MIDI is inspected. +The MIDI tests create only small synthetic files in unique `.test-artifacts` +workspaces and remove them afterward. They compare real disk read-back and +independent MIDIUtil note/control events in 4/4, 3/4, 6/8, and 7/8, explicitly +accounting for MIDIUtil's release velocities, truncated tempo, conductor layout, +and local EOT conventions. This is SMF evidence, not plugin/application acceptance. + +Patch-release acceptance can test the **exact persisted** wheel/sdist rather +than build another pair. With the scratch variables above set and an unused +release directory, build the wheel from the sdist and test that exact pair: + +```powershell +& '.\.venv\Scripts\python.exe' -m build --no-isolation --outdir 'dist\lmstudio-fix-20261020' +$env:RIFF_RELEASE_DIST = (Resolve-Path 'dist\lmstudio-fix-20261020').Path +& '.\.venv\Scripts\python.exe' -m pytest -q +Remove-Item Env:\RIFF_RELEASE_DIST +``` + +Without that variable, distribution tests build their own pair offline. +The configured directory must be under this repository's ignored `dist` +directory and contain exactly one wheel and one sdist. Both modes install +noneditably with `--no-deps`, run the wheel from outside the checkout with +isolated Python, verify module/resource origins and text-only error recovery, +and independently inspect original MIDI/native notes. + +The distribution integration tests build both distributions with installed build tools and +`--no-isolation`, then install the wheel in a separate local venv using +`--no-index --no-deps`. They import in isolated Python mode from the existing +parent directory **outside this checkout**, reject editable/source imports, +check the installed module's location, and compare public and metadata versions. +The subprocess venv and build workspace are cleaned even on test failure. +An additional real server acceptance test installs the built wheel offline with +`--no-index --no-deps --no-cache-dir --target `. An isolated +`-I -B` Python bootstrap explicitly prepends that target, verifies all 16 package/ +submodule entry locations and metadata there, and runs the installed `__main__` +from the existing parent directory **outside the checkout**. Runtime dependencies +are reused from the development venv; this is **not a fresh full dependency +installation/certification**. Six JSON resources are compared to real wheel +members and loaded by the installed server. Initialize/two tools/six profiles, +explicit MIDI/default/native-only fallback, schema-checked errors, exact real-disk +MIDI, UTF-8 protocol stdout, separate sanitized diagnostics, clean EOF before/after +initialization and bounded child cleanup are exercised offline. +The installed server also receives `--sd3-template` pointing to an independently +authored original minimal template, generates full default, alias and actual-name +native-only sets plus MIDI-only, and validates all saved outputs against the +requested score. Exact CC1/native stair points, explicit resets, mixed-controller +fallback, absent-template fallback, disabled fallback and no-overwrite errors +are exercised. README JSON examples are also checked against the typed schemas. +The ordinary `.venv` installs all declared dependencies; `pip check`, unit tests, +lint, types, and builds use that environment. + +The package's version is authored only in `src\riff_groove_builder\__init__.py`; +setuptools derives distribution metadata from it. Package-data rules already +include the three standard and three native subset `data\profiles\*.json` resources. +Installed-wheel tests also write and independently read original `.griff`, +`.briff` and `.sd3p` files outside the checkout using synthetic original content. + +## Profile/compiler mechanics (not production compatibility) + +`profiles.load_profile_registry()` uses packaged resources and an explicit +six-resource manifest, not the working directory. Missing selections remain typed, +actionable failures; synthetic test-only profiles are rejected by production +discovery. `articulations.compile_score(score, selected_profiles, ppq=960)` +compiles explicit maps to the reviewed EventPlan/MIDI APIs with exact common +pre-roll, layer selection, stateful switches/CCs, polyphony checks, reset tails, +and a 100,000-event budget. It does not compose text or change the stdio tools. +The explicit standard fallbacks are `standard.lead.v1` (channel 0), +`standard.bass.v1` (1), and `standard.gm-drums.v1` (9), with public +`mapping_kind=standard_midi` and matching provenance. They support only normal/sustain, +no controls, and a documented +linear intensity-to-velocity policy. Pitched notes use the legal 0–127 range; +percussion uses the documented GM Level 1 map, **not an SD3 default map**. +The summary `instrument` field identifies intended routing only; product names +and limitations state **NOT verified Eclips/Ray/SD3 maps**. +See [profile schema, standard sources and policy](docs/articulation-profiles.md) +and [report_5_fix.md](prompts/report_5_fix.md). Synthetic numbers remain excluded. +Application compatibility remains unverified. Step 9 now connects these +APIs to the text-generation tools without changing the mapping evidence gates. + +## Evidence gates + +See the [architecture](docs/architecture.md), +[compatibility matrix](docs/compatibility.md), and evidence checklists for +[Riffer `.griff`/`.briff`](docs/formats/agp.md) and [SD3 `.sd3p`](docs/formats/sdp.md). +AME 4.0.1 and AMR 4.1.0 identities, Riffer layout and supported subset mappings +are established from local/public evidence. SD3 3.4.4's template-song format and +three core SL-DFH pad aliases are established from local native evidence. +Native service wiring is verified; real application import acceptance remains separate. +Renamed MIDI is not native-format support; +a preset-only container does not prove that generated musical content is stored. +The existing [AGP fix handoff](prompts/step_7_fix.md) and +[SDP fix handoff](prompts/step_8_fix.md) distinguish implemented codecs +from remaining application work. Codecs and service are no longer evidence-blocked. +Software/package acceptance is separate from original full native-project +completion. Cubase/plugin MIDI import and native load/save/reload are **UNRUN**, +not pytest skips or inferred successes from Mido parsing. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..74d1f35 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,1105 @@ +# Architecture overview + +The amended approved [implementation plan](../prompts/plan.md) defines the +authoritative contracts and sequencing. The native/MIDI MCP service is operational +on Windows with real installed-wheel stdio acceptance. Target defaults are the +AME 4.0.1 / AMR 4.1.0 Riffer normal/palm-mute subsets and SD3 3.4.4 SL-DFH +core three-voice subset. SD3 native writing needs an operator-local template. +Every actual saved native/MIDI file is validated before one atomic publication. +Application open/play/save/reload and Cubase acceptance remain unrun. +`agp`/`sdp` are request aliases; actual metadata uses `griff`/`briff`/`sd3p`. +Step-numbered sections retain the original layer acceptance history; the +current [native service report](../prompts/report_9_fix.md), +[Riffer codec](formats/agp.md) and [profiles](articulation-profiles.md#riffer-subset-policy-v1) +supersede historical default/capability statements in earlier step sections. +See the +[Step 10 evidence](../prompts/report_10.md) for separate outcomes. + +Current release **0.2.0** includes the accepted Step14 pitch/voicing and +corrected Step15 public hybrid layers below. `__version__` is the sole package +version source; setuptools metadata and MCP initialization derive from it. +The final persisted wheel/sdist, exact original E2 prompt, source/installed +numeric acceptance and new user-output publication are recorded in +[report16](../prompts/report_16.md). Earlier reports/artifacts remain historical. +Restart the MCP after updating, then open a fresh chat for current schemas; +the existing configured venv needs no config edit or config reinstall. +Bounded local deterministic prose is not arbitrary language understanding. +Events `/` and backslash are reserved slides, not implemented: origin/target/ +timing codec evidence is still required. Chord slash/Over bass is implemented, +not a slide. Exact explicit pitches are never secretly retuned/revoiced to +the key or to rescue an impossible native fingering. Live playback is unrun. + +## Implemented in Step 1 + +- A `src`-layout Python package, standard setuptools build backend, one literal + public version, and metadata derived from that version. +- An import-only initializer with no service startup, logging, dependency + imports, filesystem writes, or transport initialization. +- pytest unit tests and offline sdist/wheel integration tests, Ruff, and strict + mypy. AnyIO's pytest plugin provides SDK-aligned asynchronous test support. +- Package-data inclusion for six versioned profile JSON resources (three target + defaults and three explicit standard fallbacks). +- An evidence inventory; **no target instrument is certified**. + +## Implemented in Step 2 + +`riff_groove_builder.schemas` is the authoritative Pydantic v2 contract; +`riff_groove_builder.errors` supplies explicit domain exceptions and stable +public codes. Neither imports MCP, starts a server, inspects files, or loads a +profile registry. The initializer remains unchanged and dependency-free. + +### Tool boundary and reuse + +- `ListInstrumentProfilesRequest` accepts exactly `{}`. + `ProfileListResult` contains three target defaults and three explicit standard fallbacks; + the contract also permits an honestly empty registry in isolated tests. + `ProfileSummary` fixes Eclipse/griff to lead, Ray5/briff to bass, and SD3/sd3p to + drums. Unavailable MIDI or native capabilities require explicit limitations. + IDs are opaque, nonblank strings, not evidence that a mapping exists. +- `GenerateMusicRequest` implements Section 7's parameter names and limits: + nonblank 1–4000-character descriptions; 1–64-character safe basenames; + unique, nonempty selected parts/formats; finite numeric tempo 20–300 BPM + (including integer/fractional BPM); 1–256 integer bars; bounded meter; + key grammar below; per-part profile IDs; seed 0–2147483647 (default 0); + and a strict fallback boolean (default true). +- Optional `cc_events` defaults empty. Each `ScheduledControl` contains exactly + selected `part`, exact `RationalBeat` relative to musical start, strict MIDI + `controller` and `value` integers 0–127. Normalized duplicate points, sub-tick + beats, out-of-duration points and unselected parts are invalid; part association + is rechecked after description inference. The post-compilation + `apply_scheduled_controls` helper preserves original note/switch events and + timing, appends unique sequence keys on the profile channel, sorts controls + before note-ons, and shares the existing 100,000-event budget. Articulation CC + collisions fail with actionable `INVALID_REQUEST`; no implicit resets or + vendor-effect inference. See the [concrete CC example](../README.md#optional-exact-controller-points). + Empty controls return the original compiled plan unchanged. Native preflight + distinguishes supported Riffer CC1 stairs from unsupported controllers and + SD3's precise `sd3_native_controller_not_supported` limitation. Note/channel/ + role/release corruption is checked first and is never controller fallback. +- Unspecified `parts`, `formats`, tempo, bars, meter, key, and profiles stay + `None`; explicit null on those optional fields also means unresolved. + `model_fields_set` distinguishes omission from explicit null. + Serialize requests with `model_dump_json(exclude_unset=True)` to preserve + this distinction. `ProfileSelection.selected()` excludes unresolved entries. + Empty profile selections are valid; profile-ID values, when present, are + nonblank. No defaults, text interpretation, or production profiles are chosen. +- Explicit parts constrain profile selection and applicable formats immediately: + agp needs lead/bass, sdp needs drums; actual griff/briff/sd3p suffix requests + require lead/bass/drums respectively. If parts are unresolved, these checks + must run again after text/default resolution. Registry lookup, profile-ID/part + identity, supported vocabulary, text contradictions, and verified articulation + availability necessarily belong to later services. +- `tool_input_schema(name)` and `tool_output_schema(name)` return fresh schema + dictionaries for **exactly** `list_instrument_profiles` and `generate_music`. + Step 3 reuses these and the models rather than duplicating their fields. + Both output schemas have an object root and explicit mutually exclusive + `oneOf` success/error branches. `GENERATION_OUTPUT` and `PROFILE_LIST_OUTPUT` + are reusable typed union adapters for validation and JSON round trips. + +All contract objects reject unknown fields. Numeric inputs reject booleans, +numeric strings, nonfinite numbers, and fractional/floating representations of +integer-only fields; meter's integer literals also receive an explicit strict +type check. Lists of enums and declared unique strings reject duplicates. +Empty arrays are rejected where selection/content is required; empty registry, +warnings, assumptions, overrides, supported-articulation lists, and note/event +tracks remain meaningful (including rests or unavailable capabilities). + +Basenames use `[A-Za-z0-9][A-Za-z0-9_-]{0,63}` and reject case-insensitive +CON, PRN, AUX, NUL, COM1–COM9, and LPT1–LPT9. Separators, traversal, drive +prefixes, extensions, trailing dots/spaces/newlines, and non-ASCII characters +cannot pass. This is lexical validation, not output-root or link confinement. + +Key grammar is one A–G pitch-class letter (case-insensitive), optionally one +ASCII `#` or lowercase `b`, one or more ASCII spaces, then `major` or `minor` +(case-insensitive). Structured key inputs also accept an attached lowercase `m` +minor suffix: `Em`, `F#m`, `Bbm`. Optional outer ASCII spaces are accepted. Examples: +`Bb major` -> `A# major`, `db MINOR` -> `C# minor`, `Cb minor` -> `B minor`. +Normalization uses the twelve sharp-spelled pitch classes and lowercase mode; +it retains pitch-class meaning, not original enharmonic spelling. Tabs, +newlines, Unicode accidentals, double accidentals, bare letters/other modes, and +multiple or contradictory keys are rejected. This is key-string parsing only, +not description interpretation. + +### Internal structures and units + +`MusicalIntent` requires resolved description, parts, tempo, bars, meter, key, +and seed; rhythm terms/techniques are unique nonblank names, not an implemented +text vocabulary. It computes exact duration as +`bars * numerator * 4 / denominator` quarter-note beats using `Fraction`. + +`RationalBeat` serializes as `{"numerator": 1, "denominator": 3}` with strict +nonnegative integer numerator and positive integer denominator. Ratios reduce +exactly (2/6 -> 1/3, 0/n -> 0/1); `.value` returns `fractions.Fraction`. +`PositiveBeat` additionally rejects zero. Floats, decimal approximations, and +string fractions are not timing inputs. Sub-tick logical durations survive +serialization exactly; later quantization must explicitly accept/reject them. + +`LogicalNote` is a discriminated union: `PitchedNote(kind="pitched")` has lead +or bass plus numeric pitch, while `DrumNote(kind="drum")` has drums plus a +logical voice name. Both have exact start/duration, normalized finite intensity +0–1 (inclusive, never clamped), and a nonblank articulation name. Numeric +pitches 0–127 only establish MIDI's logical envelope, not an instrument's +playable range. Voice/articulation names are not verified maps. + +`Score` retains intent, rational shared start/end, and exactly one track per +selected part in selected-part order. Positive duration equals bars/meter; +every note belongs to its track and fits the shared interval. Empty note lists +allow rests. These contracts do not compose notes or modify random state; +Step 6 supplies the separate composer. + +`ScheduledEvent` is a discriminated union of `NoteOnEvent`, `NoteOffEvent`, +and `ControlChangeEvent`, not a bag of optional payloads: + +| Quantity | Representation/range | +| --- | --- | +| Absolute event tick, priority, sequence | strict nonnegative integers | +| MIDI channel | 0–15, not 1–16 | +| Note number, controller number/value | 0–127 | +| Note-on velocity (including keyswitches) | 1–127 | +| Note-off velocity | 0–127; default 0 | +| Note role | `musical_note` or `keyswitch` | +| CC role | `articulation_control` | + +The stable ordering key is `(tick, priority, sequence)`; keys must be unique +within each part track. Priority is supplied metadata, **not** a scheduler or +a claim that arbitrary numeric priorities satisfy profile-specific causality. +`EventPlan` retains the logical score and one event track per selected part, +positive ticks-per-quarter (default 960), common nonnegative musical start/end, +and a shared overall end allowing control-release tails. Musical tick duration +must exactly match the score; all events fit the overall end, musical events +fit the musical interval, and musical note-ons precede its end. Keyswitches and +controls may occupy pre-roll/tails. Plans reject more than 100,000 events. +Step 4 now implements exact grid checks, sorting, pair/retrigger validation, +channel independence, and event writing. Compiling profile-specific controls, +verified lead times, and articulation state transitions remain Step 5. + +### Results, errors, and validation limits + +`GenerationResult` contains the planned status, resolved metadata, nonempty +artifacts, and warnings. `ResolvedGeneration` requires exact selected-part +profile coverage, unique profile IDs, and end tick >= start tick. Artifact +size is a positive integer; parts/profile IDs are nonempty and unique. Paths +must be lexically absolute Windows or POSIX local-file paths (without nulls or +line breaks); they are not resolved or checked on disk. Native artifacts +contain exactly one applicable part. Only one combined MIDI can be reported, +and it must cover all selected parts. Artifact profile IDs must match resolved +parts. Duplicate format/part outputs and unselected warning parts are rejected. + +`complete` cannot contain substituted parts or native-unavailability warnings. +`midi_fallback` requires a combined MIDI artifact naming substituted parts, +an explicit `NATIVE_FORMAT_UNAVAILABLE` warning for each such part, and no +native artifact for a substituted part. Unavailability warnings must identify +substituted parts. Other public warnings can be part-specific or global. +These validate internally feasible claims, not successful generation: actual +existence/size, requested-format coverage, fallback permission, verified maps, +resolved root/link confinement, atomic publication, and read-back are Step 9's +responsibility. Synthetic in-memory tests do not create or certify artifacts. + +`GenerationError {code, message, details}` supports these named exceptions: +`InvalidRequestError`, `UnsupportedDescriptionError`, `ProfileRequiredError`, +`ProfileNotFoundError` (same `PROFILE_REQUIRED` code, with a missing-ID message), +`UnsupportedArticulationError`, `NativeFormatUnavailableError`, +`OutputExistsError`, `OutputIOError`, and `SerializationError`. +Messages are fixed actionable public guidance. `GenerationError.from_domain` +copies only the declared code/message and explicitly provided finite JSON +details; it never reads exception causes, traceback text, or private files. +Callers must supply public-safe details, not raw exception strings/paths. +Step 3 sets MCP `isError` for domain failures; protocol failures remain SDK +errors. These contracts themselves implement no transport behavior. + +Published schemas use JSON Schema 2020-12 vocabulary, including `uniqueItems`, +static conditional part/format/profile associations, native artifact shape, +and complete/fallback branch conditions. Standard JSON Schema cannot compare +two arbitrary field values (end >= start, rational arithmetic, profile-ID +correspondence, fallback warning coverage, or cross-track ordering). Those +remain enforced by the authoritative Pydantic validators; schema validation +alone is not sufficient at a service boundary. JSON Schema also treats `4.0` +as an integer mathematically; the typed models intentionally reject it in +integer-only fields. Nonfinite floats are not JSON numbers at all. Downstream +code must always validate with these models, not rely solely on client-side +JSON Schema checks. Do not mutate validated model fields/containers in place; +revalidate changed payloads rather than using unchecked `model_copy(update=...)`. + +## Implemented in Step 3 + +`server.py` uses the installed official MCP **1.30.0 low-level `Server`**, +`@server.list_tools()`, `@server.call_tool(validate_input=False)`, and +`mcp.server.stdio.stdio_server`. The SDK owns framing, JSON-RPC parsing and +dispatch, IDs, notifications, initialization/negotiation, and EOF cancellation. +There is no second protocol layer or custom shutdown method. FastMCP inference +is unnecessary: tool definitions copy the exact reviewed `tool_input_schema` +and `tool_output_schema`, with no wrapper or weakened union. + +The SDK's JSON-Schema-only input checker is disabled deliberately. Its error +messages can echo input values, and JSON Schema accepts `4.0` as an integer. +Both handlers instead validate arguments using the authoritative Pydantic +request models, including strict types and cross-field validators. Validation +details contain only model-known field names, numeric list positions, +`` placeholders for unknown properties, Pydantic/authored reason codes, +and fixed, authored field corrections (grammar, bounds, shapes and recovery actions). +They never copy input, raw descriptions, validation messages/contexts, exception +representations, or causes. An issue at the whole-request boundary uses +`$request` only when no precise field is available. Part/format/profile and CC +cross-field validators use typed custom reasons; their public issues identify +`formats`, `profiles` or `cc_events`, not a generic root `value_error`. +The service repeats these same safe checks after omitted parts resolve. + +Results are constructed as authoritative output models, serialized into explicit +SDK `CallToolResult` objects with structured content and the complete identical +public JSON object in a single text block. Returning +`CallToolResult` bypasses the SDK decorator's automatic output-schema check; +the typed constructors and tests against the published schemas provide that +validation without losing `isError` on the success/error union. Narrow type +ignores are confined to the SDK's untyped decorators; strict project mypy +remains enabled. Schema constraints, `isError`, strict models and SDK lifecycle +are preserved; text/description guidance and structured-key shorthand are Step 11 updates. + +Exactly two tools are registered: + +- `list_instrument_profiles` returns the real six-profile `ProfileListResult`. +- `generate_music` calls the concrete service described in Step 9, returning + real published Standard MIDI or an explicit typed error. The old development + skeleton is historical in report_3.md and is no longer the server's behavior. + +Known `DomainError`s preserve only their declared public code/message/details. +Unexpected handler failures are not silently relabeled as invalid requests: +they log the failure class (without values, traceback, or exception text) on +stderr and return the SDK's ordinary error result with a fixed internal-error +message. Internal output-model failures follow this diagnostic path as well. +Unexpected failures never become success-shaped fallback. + +`__main__.py` requires `--output-dir`, validates/resolves an existing directory, +configures stderr logging only on CLI execution, and runs the SDK on asyncio. +The root is retained in the SDK lifespan context and pinned by the service. +Importing the package, server, or entry module starts nothing and prints nothing. +Startup rejects URI/network/device/drive-relative syntax, controls, missing +roots, and regular files. It does not create roots or test writeability. +Step 9 additionally implements root/ancestor reparse checks, volume +classification, identity checks, collisions and atomic publication; trusted ACL +and race/crash limits remain explicit below. + +### Observed SDK protocol behavior + +Real subprocess tests exercise the installed SDK, not an invented dispatcher: + +- Normal initialization sends/accepts the initialized notification. Requested + supported versions are retained; unsupported requested versions negotiate to + an SDK-supported version. Only the tools capability is registered. +- String and integer request IDs are preserved. Valid notifications and unknown + notifications produce no response. Ping continues working after bad input. +- Invalid tool arguments are typed `INVALID_REQUEST` tool results. + Unknown tools are SDK `isError` text results, not declared domain errors. +- An unknown method outside the SDK request union or invalid method parameters + yields `INVALID_PARAMS` (-32602). A recognized but unregistered method + (`resources/list`) reaches SDK dispatch and yields `METHOD_NOT_FOUND` (-32601). +- Invalid JSON, array messages, and messages without a required method are + handled by the SDK as stream-validation exceptions: a generic + `notifications/message` (`Internal Server Error`) is sent, with no invented + parse-error response or ID. The connection remains usable. +- The SDK parses a request-like object with `id: null` as a notification. + An unknown such method is logged/rejected without a response. Tests preserve + this observed behavior rather than asserting a nonexistent parse error. +- The SDK's validation logs can contain raw values. A CLI-only logging filter + replaces its known stream/request/notification-validation and unlisted-tool + diagnostics with fixed safe messages. Parsing, dispatch, and protocol responses + are untouched. Operational diagnostics are not suppressed. Debug logging is + not enabled by this application. +- stdout is exclusively valid UTF-8 newline-delimited JSON-RPC, including the + SDK's generic logging notifications. Human-readable startup errors/diagnostics + remain on stderr. Closing stdin exits zero, including before initialization; + there is no protocol shutdown request. + +The tests run the installed editable package with `-I -B` and no `PYTHONPATH` +or `PYTHONHOME`, from a different repository-local working directory. The normal +flow uses the official client, including its bounded stdin-close/termination +cleanup. A small raw subprocess test client validates every stdout line and +enforces bounded waits and exact-process kill fallback before workspace cleanup. +Valid supported requests generate real MIDI; unsupported/native-disabled +requests create no output directory. Built-wheel execution outside the checkout +is additionally covered below. Manual MCP-client/Cubase/plugin checks are UNRUN. +See [startup and Windows client configuration](../README.md#start-the-mcp-stdio-service). + +## Implemented in Step 4 + +`riff_groove_builder.midi` consumes the authoritative `EventPlan`; it neither +composes music nor compiles a `Score` into controls. The reviewed models, tool +schemas and errors are reused by the operational service. + +### Exact timing and ordering API + +- `beats_to_ticks(Fraction | RationalBeat | int, ppq=960) -> int` requires exact + nonnegative quarter-note beats and a legal positive, non-SMPTE PPQ (1–32767). + Floats, numeric booleans/strings, and sub-tick fractions are rejected. +- `bar_ticks(TimeSignature, bars=1, ppq=960) -> int` uses + `bars * numerator * 4 / denominator` without intermediate floats. +- `quarter_tempo(tempo_bpm) -> int` treats BPM as quarter notes/minute, regardless + of meter denominator. It rounds the exact decimal-rational reciprocal + `60_000_000 / Fraction(str(bpm))` to the nearest integer microseconds/quarter, + ties to even, requiring 1–0xFFFFFF. It never calls a meter-adjusted BPM helper. + The `EventPlan` retains the stricter intent tempo range of 20–300 BPM. +- `validate_event_plan(EventPlan) -> None` revalidates the whole mutable model + graph before checking MIDI-specific invariants. Unsupported payloads, strict + type errors, timeline violations, duplicate ordering keys, and the existing + 100,000 scheduled-event limit therefore cannot bypass the writer through + unchecked model copies or list/field mutations. That budget counts scheduled + events, not the bounded conductor/name/EOT metadata. + +Logical note offsets relative to `Score.start` and durations must fit the grid. +A nonzero logical score origin is not extra pre-roll: the compiler's intended +conversion is `musical_start_tick + ticks(note.start - score.start)`. The writer +preserves the supplied compiled ticks and does not reconstruct notes from the +score or claim to validate profile-specific compilation. + +Absolute events are stable-sorted only by their authoritative +`(tick, priority, sequence)` key, never by pitch or a replacement generic control +priority. Delta times are computed once when constructing Mido tracks. +All deltas are strict integers in 0–0x0FFFFFFF (the four-byte SMF VLQ range). +With no artificial conductor filler events, its final EOT delta spans the +entire plan, so this writer also limits the shared `end_tick` to 0x0FFFFFFF. +It rejects larger plans rather than emitting invalid deltas or inventing timing +events. PPQ 960 represents straight and triplet subdivisions exactly; other +resolutions and fractions are accepted only when exact. + +### Notes, channels, and shared tracks + +Active notes are keyed by `(channel, note)` within each part. Every musical +note and keyswitch needs a positive-duration matching-role release. Orphan +releases, dangling notes, wrong-role releases, and same-channel/same-pitch +overlapping onsets are errors, including collisions between keyswitch and +musical roles. This conservative policy does not guess voice allocation. +At a same-pitch boundary the supplied ordering must release the old note before +the new onset. Roles may reuse a pitch only after release. Different pitches +on a part's channel are valid polyphony; the same pitch on separate channels +is independent. + +Each used channel is reserved to its owning part for the whole plan, including +keyswitch-only and CC-only usage. Different parts cannot share a channel even +at disjoint times. A part may use several otherwise disjoint channels. Empty +parts reserve none. No channel 10/zero-based 9 assumption or program change is +added. Role labels guide validation/diagnostics; they are not extra MIDI metadata. + +SMF type 1 has `Conductor` followed by `Lead`, `Bass`, and/or `Drums` in the +resolved selection order, not a fixed instrument order. Conductor name, tempo, +and meter are at zero (standard clocks-per-click 24, notated 32nds/quarter 8). +Part names are at zero. Controls and keyswitches stay in their affected part +track. Exactly one EOT per track is at the common `end_tick`, preserving common +pre-roll, exact musical span, and any control-release tail. Musical onsets +cannot occur before the musical start or at/after the musical end; musical +releases cannot exceed it. Keyswitches/CCs may occupy pre-roll and tails. + +### Disk validation and failure boundaries + +`write_midi(path: Path, plan: EventPlan) -> Path` constructs and validates Mido +SMF bytes in memory, exclusively opens only the supplied path (`xb`), closes +the saved file, and reads its actual bytes back. `validate_midi_file(path, plan) +-> None` exposes that disk expected-content check without writing or cleanup. +Both enforce header signature/length/type/track count/PPQ and compare every +absolute-tick message payload, track name/order, tempo/meter, channel, +note/CC/velocity, event sequence, and shared EOT. Opening with Mido alone is +not success; readable but changed content, missing/extra events, corruption, +truncation, and trailing data fail. Exact comparison with the already-pair-checked +plan also validates pairing of the saved events. + +Failures use existing named `SerializationError`, `OutputExistsError`, and +`OutputIOError` with fixed safe reason codes, never raw exception values or +paths. Expected Mido/encoding and OS failures are caught narrowly; unexpected +programming failures propagate rather than becoming a successful fallback. +Failed writes/read-back remove only the newly exclusively created file, +checking its device/inode identity before unlinking. Pre-existing data and +replacements are not removed. Cleanup failures or ownership changes themselves +raise explicit IO failures; no success is returned if cleanup is denied. +The standalone validator never deletes an input, even if corrupt. + +No parent directories are created. Relative and absolute `Path` destinations +are accepted, with no claim of output-root confinement, all-format publication, +fsync/crash durability, or adversarial race-proof filesystem operations. +The Step 9 service supplies staging/root/link checks and publishes the complete +artifact set only after actual saved-file validation. + +### Independent evidence and limitations + +Tests construct a synthetic three-part Score/EventPlan with a nonzero score +origin, 240-tick common pre-roll, triplets, retriggers, keyswitches, CCs, +120-tick tail, and non-GM drum channel/pitch. Mido reloads real saved production +files; independent MIDIUtil `addNote`/duration and controller APIs build equivalent +reference files in 4/4, 3/4, 6/8, and 7/8, including fractional BPM. +Comparison preserves exact note/control ticks, channels, pitches, onset and +release velocities, and control payloads. Fixtures explicitly match MIDIUtil +1.2.1's release-velocity convention (copies the onset velocity); production +preserves any valid supplied release velocity rather than imposing that rule. + +MIDIUtil type 1 inserts a conductor before its three user tracks; meter uses +a denominator exponent in its API. Its tempo truncates instead of rounding +(137.5 BPM: 436363 versus the correctly rounded production 436364). +Tempo is tested independently rather than treated as an equivalent payload. +Reference EOTs occur at each track's local last event; production EOTs share +the full tail. These explicit metadata conventions are excluded from normalized +note/control equality, with separate assertions for conductor/meter/tempo/end +semantics. Duplicate removal, deinterleaving, and origin adjustment are disabled +in the reference to avoid silently changing the fixture's intended events. +Repeated production inputs, including permuted event-list input order, yield +identical bytes with the tested Mido version. + +Test workspaces live under `.test-artifacts` and are removed in fixture cleanup. +No licensed or checked-in binary fixtures, production mappings, native codecs, +or Cubase/plugin acceptance are introduced. Focused verification: + +```powershell +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_midi.py tests\integration\test_midi_files.py -q +``` + +## Implemented in Step 5: mechanics and Standard MIDI fallback + +`profiles.py` defines strict schema-version-1 declarative identity/provenance, +MIDI range/voice/alias/layer/action models, typed registry failures, and +deterministic production selection. `importlib.resources` loads an explicit +manifest from packaged resource initializers; three resources provide standard +pitched lead/bass and GM Level 1 percussion. Inaccessible/malformed/undeclared resources are errors, +not empty-registry success. Test-only data cannot enter production discovery. + +`articulations.compile_score` revalidates explicit score/profile graphs and +produces a reviewed EventPlan. It uses exact quarter-note timing, per-part +channel ownership, latched deduplication, per-note momentary pulses/CCs, +reference-counted held controls, declared normal setup/restoration, and +conservative incompatible-state/physical-trigger rejection. One common pre-roll +and shared release/reset/restoration tail retain alignment and logical origin. +Deterministic release/reset/selection/onset priority and sequence preserve +writer causality; the 100,000-event budget and reviewed MIDI validator are +enforced before return. + +See [articulation profiles](articulation-profiles.md) for schema/action details, +supported overlap boundaries, interpolation, named errors, API examples, exact +public standard sources and policy, and the remaining vendor evidence gate. Synthetic three-part +tests verify independently expected compiler events and real Mido disk read-back. +Built-wheel installed and ZIP-resource probes run outside the repository and +confirm exactly the three standard-only profiles and normal default selection. +Standard three-part tests also assert independent expected events and real MIDI +read-back. Public summaries add `mapping_kind: instrument | standard_midi` +(default `instrument` for existing contracts). Standard profiles have matching +`standard_midi` provenance, public fact references and separate generator policy; +neither can certify vendor evidence. Channels 0/1/9, normal/sustain without +controls, full legal pitched range, GM percussion numbers and linear positive +velocity policy are explicit. `instrument` identifies routing intent, not +compatibility; public product names and limitations disclose unverified vendors. + +Only the explicit summary discriminator/provenance additions changed contracts; +the exact MIDI APIs and generic compiler remain unchanged. Step 9's operational +server lists the three profiles and reuses this compiler. +**Step 6 uses standard fallback**, under the amended plan. +Vendor maps remain unverified; native formats and application acceptance are +separately unverified. Standard fallback does not close those evidence gates. + +## Implemented in Step 6: deterministic text and composition + +`description.resolve_description(GenerateMusicRequest) -> DescriptionResolution` +revalidates the authoritative request and returns `intent: MusicalIntent`, +`assumptions: list[str]`, `overrides: list[str]` (unique, nonblank records). +The records feed the service's `ResolvedGeneration` metadata, not a +fabricated successful `GenerationResult`. No files, registries, network/model +providers or service transports are used by resolution. + +`compose.compose_score(intent, selected_profiles, *, ppq=960) -> Score` +revalidates intent/profile graphs, then composes on one rational timeline. +The registry remains authoritative: callers select using +`registry.select(resolution.intent.parts, request.profiles or ProfileSelection())`. +The composer does not guess instruments from vendor words. Compile that score +with `articulations.compile_score`, then use the existing `midi.write_midi`. +If overriding PPQ for direct use, pass the same PPQ to the compiler. +Format/capability/fallback decisions and post-resolution request-format checks +are service responsibilities; the resolver does not serialize native +formats or infer output filenames/profiles. + +### Exact description grammar + +Case is folded and all whitespace collapsed before matching whole words. +Clauses may appear in any order. This is a closed grammar, not free-form prose: + +| Input | Interpretation | +| --- | --- | +| `120 BPM`, `137.5 bpm`, `+.25 bpm` | Signed decimal numeric quarter-note BPM; final value must be 20–300. No exponent, fraction, textual number or unit conversion. | +| `4 bars`, `1 bar` | Numeric integer-valued count, 1–256. Decimal spelling `4.0 bars` also has integer value; fractional values fail. | +| `in 7/8`, `meter 3/4`, `6 / 8` | Numerator 1–16; denominator 1, 2, 4, 8 or 16. No mixed/changing meter. | +| `E minor`, `Bb major`, `key F# minor`, `Em`, `F#m` | A–G, optional single ASCII `#`/`b`, major or natural minor, including attached minor `m`; canonical sharp-spelled key. Case-insensitive text, including accidentals. | +| `lead`, `lead guitar`, `guitar`, `riff` | Lead part. | +| `bass`, `bass guitar`, `bass riff`, `bass groove`, `bass guitar riff/groove` | Bass part; slash here means either word, not literal `/`. | +| `drum`, `drums`, `drum groove`, `drums groove` | Drum part; groove is optional filler. | +| `lead and bass`, `bass, drums`, `lead + drums`, `bass & drums` | Part list. Separate positive part mentions also combine. Text order resolves to lead, bass, drums order. | +| `only bass and drums`, `lead and bass only` | Only-selection over that entire contiguous list. An additional positive part outside it is contradictory. | +| `no drums`, `without lead and bass`, `exclude bass, drums` | Exclude the entire contiguous list, never include negated words. With only exclusions, subtract from all three and record that baseline assumption. | +| `quarter`, `eighth`, `sixteenth` | Straight slots of 1, 1/2, 1/4 quarter-note beats, respectively. Optional ` note`, ` notes`, `-note`, `-notes`; `straight` is filler. | +| `rests`, `rest`, `no rests`, `no rest` | Omit the final slot of every bar, or omit none. No arbitrary rest schedule. | +| `rock`, `metal` | The two bounded original template policies below; `riff`/`groove` do not invoke a larger genre engine. | +| `slow`, `fast` | Fixed tempo candidates 80/160 BPM. Conflicting numeric/qualitative tempos are errors unless structured tempo overrides them. | +| `normal`, `sustain` | Same global normal technique. Sustain is an alias, not a pedal, CC64 or a different gate. | +| `palm mute`, `palm-mute`, `palm muted`, `palm-muted`, `palm muting` | Canonical `palm_mute`, applied only to selected lead/bass. Mixed-request drums stay normal and assumptions disclose applicability; drum-only palm mute errors. Standard pitched profiles cannot realize it. | + +Simple subdivision, template and rest instructions apply globally. Palm mute has +the pitched-only applicability above; no arbitrary per-part technique schedule is +inferred. There are no per-part rhythms, sections, note +spellings, chords, arbitrary durations, accents or dynamics syntax. +Use the structured `parts` list to retain noncanonical part order. +Excluded and included occurrences of the same part are contradictory; an empty +selection is an error. `no drums only` is rejected as ambiguous rather than guessed. +Negation is supported only by the listed part exclusions and `no rest(s)`; +other negated instructions are errors, not silently ignored. + +Only these exact filler words are ignored: +`please create produce generate make write a an the some simple music pattern groove +for with and at in of on notes note key tempo meter straight`. +Comma, period, semicolon, colon, exclamation/question marks, `&` and `+` are +separators; other punctuation/unrecognized tokens fail. At least one recognized +instruction or `music`/`pattern`/`groove` is required (`please` alone fails). +Whole-word matching never interprets bassoon as bass or leadership as lead. +Filler is not evidence that arbitrary prose was understood. + +Tempo, bars, meter and key default to **120 BPM, 4 bars, 4/4, E minor**. +No explicit part language defaults to **lead, bass, drums**, with a record. +Pattern defaults are **eighth, rock, no_rests, normal**, also with records. +Seed is the authoritative request's seed (default 0), never read from text. +Structured tempo/bars/meter/key/parts take precedence, even over distinct +contradictory or out-of-range scalar text for the same field. Every non-null +structured value records its value and observed text candidates (even if none); +it is not mislabeled as an assumption. Repeated equivalent values, including +enharmonic keys, are not contradictions. Null means unresolved. +Structured overrides never authorize unknown material or changing instructions. +`then`, `to`, `from`, changes/changing, ramp, accelerando, ritardando, rallentando, +speed up and slow down fail explicitly, including with a structured tempo. +Only complete supported beat-range clauses (below) consume `from`/`to` before this guard. + +Unresolved conflicts raise `DescriptionConflictError`, an +`UnsupportedDescriptionError` subtype with public `UNSUPPORTED_DESCRIPTION` +and the field to correct. Unknown words, unsupported material and out-of-bound +text raise named `UnsupportedDescriptionError`; invalid/mutated requests retain +`InvalidRequestError`. Unknown instruments (piano, violin, etc.), unsupported +modes/techniques, vendor names, audio, swing/arbitrary triplets, tempo changes, +polyrhythm and song sections are never discarded into a default loop. + +### Typed rational phrase schedules (Step 12) + +`TimedNote` contains reduced rational `start`/positive `duration`, a closed +`normal`/`palm_mute`/`pinch_harmonic` technique and optional finite intensity. +`PhrasePlan` contains a sole pitched part, low-tonic register policy, exact +duration and an ordered, nonoverlapping, event-budget-bounded note list. +`MusicalIntent.phrase_plan` is optional; a phrase must fit its selected part and +score duration and cannot coexist with global template terms/techniques. +Defensive revalidation rejects mutated invalid plans. No public score tool is added. + +The bounded description parser composes two clauses, never a whole-prompt match: +`[chugging] palm mute/muted/muting eighth/8th [notes] from X to Y` and +`triplets on B&A with the A as a pinch harmonic that carries over a whole note +in the second/2nd measure`. Palm/pinch hyphens and spacing around `&` are accepted. +X/Y are inclusive 1–4 labels with optional `&`; B is a beat 1–4. Straight notes +advance by 1/2 quarter beat; triplets by exactly 1/3. The last triplet ends at +quarter beat 8, tying through all of measure 2. Reversed ranges, overlaps, +out-of-bar labels, insufficient length, non-4/4 meter, extra global rhythm or +techniques and other prose fail without dropping instructions. This text grammar +requires lead only and both clauses, not arbitrary melodies/sections/ties. +Longer explicit scores contain the phrase once and then silence. + +The original 1-to-3& / beat-4 request yields six PM eighths, two PM triplets and +one PH of duration 13/3, at quarter beats 0,1/2,1,3/2,2,5/2,3,10/3,11/3. +The hold infers two bars when omitted; 120 BPM remains the disclosed default. +`A` is a count, not a pitch. The composer generically applies per-note timing, +technique and intensity, resolving each profile articulation without fallback. +All notes use the tonic nearest MIDI40 within actual range and native tuning; +default AME Em is E2/MIDI40. Seeded intensity uses the unchanged local RNG policy +unless a typed note intensity is present. All PPQ conversion remains exact; +event budgets, compiler ordering, CC handling and atomic file transactions remain +unchanged. Simple patterns do not use the phrase path or change their notes. + +### Deterministic composition and exact musical policy + +- One common interval starts at 0 and ends at + `bars * numerator * 4 / denominator` quarter-note beats. Every part shares + it, and the existing writer emits a common end-of-track tick even after rests. + BPM is always quarter-note BPM, including 6/8. +- Slots restart at every bar. If the chosen subdivision does not divide the + bar (e.g. quarter in 7/8 or 1/16), only the last slot is shortened to that bar + boundary. This is an explicit policy, not duration drift or rounding. +- Rests omit the last slot, including its drum hits, of every bar. A single-slot + bar with rests is entirely silent but retains its exact duration. No requested + technique is dropped even for silence: profile validation still runs. +- Major intervals are 0,2,4,5,7,9,11; natural minor 0,2,3,5,7,8,10. Lead requires + a full ascending seven-degree scale fitting the actual inclusive profile range. + Bass requires a root/fifth pair (0,7) fitting the range. Choose a root nearest + MIDI 64 for lead and 40 for bass (lower root breaks a distance tie), among + candidates that fit the entire palette. **C4 = 60, E4 = 64, E2 = 40**; profile + note numbers, not vendor octave labels, remain authoritative. No pitch clamping, + chromatic notes, dropped degrees or guessed alternate octave mapping. +- Lead rock degree cycle is (0,2,4,6), metal (0,0,4,1), zero-based; each bar starts + at degree 0. Other slots add a seeded 0/1 degree variation modulo seven. + Bass rock alternates root/fifth; metal uses root,root,fifth,root. These are + original simple policy patterns, not factory/demo content or genre fidelity. +- Drum hats use selected profile alias `closed_hat` on every active slot. + Metrical pulse is `max(slot_length, 4/denominator)`; on pulse-aligned slots, + alternate `kick` and `snare` starting with kick each bar. Metal additionally + adds kick on off-pulse slots. This is the explicit odd/compound-meter rule, + not a claim of idiomatic 6/8 or automatic accent grouping. It avoids losing + snares when a coarse subdivision skips denominator units. +- Resolve all three required drum aliases before allocation. All physical notes + are deferred to the compiler's selected profile lookup; no GM/vendor number + is embedded in composition. Missing aliases fail rather than substituting. +- Pitched gates fill the slot; drum gates are `min(slot_length, 1/4 beat)`. + Adjacent same-pitch notes only touch at boundaries (compiler releases first). + Each slot has seeded intensity from {0.5, 0.625, 0.75}, shared by simultaneous + drum hits. Profiles perform real supported velocity conversion, never clamping. +- Local `Random(seed + part_offset)` uses lead/bass/drums offsets 0/1/2, so + adding/reordering other parts does not perturb a part's notes. Calls never + change global random state. Same intent/seed yields the same score/events/bytes + in the tested Python environment; no cross-runtime RNG certification is claimed. +- Revalidate exact profile coverage, part identity and distinct channels. + Resolve each requested articulation to a canonical profile name, with only + one global canonical technique allowed. `UnsupportedArticulationError` + identifies part/profile/technique, including honest palm-mute failure for + standard maps. No softer-note or guessed-switch approximation exists. +- Before constructing notes, count exact active slots/hits over all bars and + reserve at least two events per note against the existing 100,000-event budget. + The compiler remains authoritative for additional control events/pre-roll/tails. + Grid-check slot offsets, lengths, drum gates and total duration using existing + `beats_to_ticks`; off-grid PPQ fails without rounding. + `CompositionError` (`SERIALIZATION_ERROR`) identifies range, missing-voice, + coverage/channel, unsupported direct-intent terms or budget problems. + Existing exact timing/profile/compiler errors are not hidden by fallback. + +The unchanged production registry supplies only Standard MIDI normal/sustain, +channels 0/1/9, legal pitched ranges and declared GM aliases. It supplies no +vendor techniques. One synthetic switch-profile unit test proves real compiler +coupling only; it does not advertise vendor compatibility. No authoritative +shared model/profile/compiler/writer changes were necessary in Step 6. + +Focused validation: + +```powershell +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_description.py tests\unit\test_compose.py tests\integration\test_text_to_midi.py -q +& '.\.venv\Scripts\python.exe' -m pytest -q +& '.\.venv\Scripts\python.exe' -m ruff check . +& '.\.venv\Scripts\python.exe' -m ruff format --check . +& '.\.venv\Scripts\python.exe' -m mypy --strict src tests +``` + +Actual-disk tests cover lead/bass/drums/all-parts, 3/4, 6/8, 7/8, nondefault +tempo/key/length, independent event/pitch/channel/duration/pairing assertions, +precise expected bass/drum sequences, seed byte determinism and text-driven +rhythm changes. Tests use self-cleaning UUID directories under `.test-artifacts`. +The unchanged Step 3 tool handlers are **not** a text-generation service. + +## Implemented in Step 7 fix: real native Riffer codec + +`formats.NativeCapability` is a small frozen/slotted internal result with part, +format, available and a fixed safe reason. It is not an exporter framework, +artifact, or caller-supplied authorization. The concrete AGP APIs are: + +- `check_agp_capability(part: Part, profile: InstrumentProfile) -> NativeCapability` +- `require_agp_capability(part: Part, profile: InstrumentProfile) -> NativeCapability` + +Both reject non-lead/bass requests and defensively revalidate the full profile +through `checked_profile`, preserving the existing target/part/format and +native-metadata constraints. Valid wrong-part profiles raise the existing +`ProfilePartMismatchError`; malformed/mutated profiles raise +`InvalidProfileError`, not native-unavailable. + +Checks are still pure/no-IO and keep `format=agp` as a legacy request alias. +The evidenced native subset returns `available=True`, `reason=riffer_xml_2_1`; +standard/synthetic maps return false with `riffer_profile_not_supported`. +Matching metadata alone is insufficient: strict native settings, provenance +and supported target/version are required. + +`write_riffer(path, plan, part, profile)` exclusively creates an actual `.griff` +or `.briff` staged file. It validates/recompiles the score/event plan, assigns +physical strings with bounded backtracking, serializes real XML note/CC fields, +and invokes `validate_riffer_file` on actual saved bytes. The separate reader +checks structure, physical validity and requested musical content, not a second +serialization. Native PPQ 480 conversion is exact; unsupported pre-roll/tails, +off-grid events, other CCs/techniques or impossible strings fail explicitly. +Legacy write/validate AGP names alias these APIs, never emit `.agp` files. + +At completion of Step 7 the two target profiles were nondefault. The service available-codec +guard remains: native service registration is deliberately not part of this +fix. Standard default MIDI/fallback behavior remains operational. Public +artifacts/summary metadata expose actual suffixes, while requests also accept +`agp`/`sdp`. The subsequent Step 8 fix adds SD3; no application automation is added. +See [native schema/evidence/acceptance](formats/agp.md). Plugin/Cubase acceptance +remains unrun, independently of actual XML generation/read-back success. + +## Implemented in Step 8 fix: native SD3 template song codec + +`formats.sdp` supplies a bounded balanced-text 3.4.4 parser, read-only +`inspect_sdp_template`, template-aware check/require APIs, exclusive staged +`write_sdp` and independent `validate_sdp_file`. The explicit typed optional +`template: Path | None` is an operator-local input, never a bundled private +project. Missing optional template is `sdp_template_required`; supplied bad, +unreadable, versioned or map-mismatched templates are errors, not fallback. +Standard profiles still report `sdp_profile_not_supported` with no IO. + +The nondefault `toontrack.sd3.3.4.4.core.v1` profile covers only locally verified +SL-DFH kickR/36, snareR/38 and hatsTP/42. The codec validates actual pad aliases +and input channel before use. Channel 9, intensity interpolation and neutral +song controls are generator policy, not vendor defaults. + +All source active song tracks/clips/references are replaced with one original +note-only track/clip. Packed status/pitch/velocity triples and exact finite +decimal beat times are independently decoded from saved bytes and compared +with a recompiled score/event plan. Unsupported event semantics, pre-roll, +tails, release velocity, precision and corrupt input fail explicitly. +Every non-song byte (kit/mixer/tracker and other operator state) is preserved. +Only the staged output is exclusively written and read back; no publication. + +Native tests use newly authored original fixtures and an opt-in read-only local +template integration. SD3 application/Cubase acceptance is UNRUN, not inferred. +At completion of Step 8, service wiring, CLI template configuration and defaults +were untouched; Step 9 fix below now implements all three. +See [SD3 API, limitations and evidence](formats/sdp.md) and +[current verification](../prompts/report_8_fix.md). + + + +## Implemented in Step 9 (updated by native integration fix) + +`service.GenerationService(output_root: Path, *, registry: ProfileRegistry | None += None, sd3_template: Path | None = None)` loads the packaged registry and pins +the existing local root. CLI `--sd3-template` threads a typed operator Path through +`run_stdio`/`create_server`; no tool argument can select a template. +Its two public operations are `list_instrument_profiles() -> ProfileListResult` +and `generate_music(request: GenerateMusicRequest) -> GenerationResult`. +The SDK handlers use this same concrete service, with no alternate composition +or exporter framework. The optional registry supports isolated tests; production +loads exactly six declared resources: three target defaults and three explicitly +selected standard fallbacks. Strict target validation still enforces evidence, +versions, tunings/voices, switches, velocity bands and timing policy. + +The service revalidates mutable request graphs, resolves text, rechecks +parts/formats/profile associations after inference, selects/revalidates maps, +composes/compiles once, and preflights actual native capabilities/content before +any output staging. Omitted/null formats request MIDI and relevant native suffixes. +`agp` expands to selected lead `.griff` and bass `.briff`; `sdp` to drums `.sd3p`. +Aliases and actual names deduplicate. Explicit MIDI-only skips native capability +preflight and works with target maps even without a template. +Only known unavailable capability/representation limits permit fallback. Preflight +uses codec content/grid/routing checks without writing. Narrow fixed reason codes +cover common pre-roll/tails, exact native grid/decimal precision, unsupported Riffer +CC and impossible physical-string assignment. Invalid plans/maps, search exhaustion, +template errors, serializer/read-back/IO faults are errors, never fallback. +An explicitly supplied template is validated at construction and checked by source +identity/size/mtime/SHA-256 during listing/generation and before publication. +Even a MIDI-only request never hides an explicitly invalid configured template. + +Composition and compilation reuse existing exact-timing APIs and event budget. +Registered writers create `.mid`, `_lead.griff`, +`_bass.briff`, `_drums.sd3p` as requested. Each exclusively +opens its path and invokes an optional `on_created(fstat)` hook **before writing**: +the service records that actual new file's identity, including on partial failure. +The hook is the only shared writer change; standalone APIs retain their behavior. +The service independently invokes each saved-file validator after the writer's +own read-back, bounds files to positive <=16 MiB, rejects reparse/nonregular/ +hardlinked files, and checks identity/size/mtime/SHA-256 stability. It constructs and +revalidates the anticipated result including JSON serialization, then publishes. +A result-model error is `SERIALIZATION_ERROR / invalid_generation_result` before +publication, not a post-publication false failure. + +MIDI is emitted only when requested or needed for fallback; it includes all selected +parts. Successful native-only requests have no MIDI. `fallback_for` contains selected native-requested +parts whose capability was unavailable. Each gets `NATIVE_FORMAT_UNAVAILABLE`; +status is `midi_fallback`. Explicit MIDI-only success is `complete`. Every selected +standard-only map gets `STANDARD_MIDI_MAPPING`, never vendor compatibility. +Target subsets get per-part `VERIFIED_SUBSET_LIMITS` warnings. +Missing drum template with allowed fallback preserves lead/bass natives and adds +one combined MIDI with fallback only for drums. Disabled fallback errors before +stage creation. Runtime profile summaries combine real preflight readiness with +version/library/subset/default and application-limit disclosures. +Results contain only actual published absolute paths, actual sizes, part/profile +IDs, resolved musical metadata, assumptions/overrides and public warnings. +Known failures use typed `GenerationError` with MCP `isError`; unexpected bugs +retain the sanitized diagnostic/SDK error path. Profile listing is now real. + +### Filesystem guarantees and limitations + +- Tool inputs contain only the strict safe basename, not arbitrary paths. + Startup rejects URI/UNC/device/drive-relative/network-drive syntax, `..`, files, + nonexistent roots and all existing root/ancestor symlinks or Windows reparse + points (including junctions). Windows drive type must be fixed/removable/RAM. + The root and every ancestor's device/inode identity are pinned and rechecked. +- One exclusive UUID stage under the root is owned per request (at most three + name attempts). No global scratch or persistent job database is used. + Directory checks verify stage identity, non-reparse status and parent + confinement. Enumerations examine at most requested file count + 1 entries + (at most five); only the exact planned names and claimed file identities are allowed. + No sidecar manifests, renamed MIDI substitutes or extra formats are generated. + All snapshots/hashes are rechecked immediately before commit, including earlier + files after the last writer. Unknown injected content causes an error. +- A same-volume `Path.rename` of the whole completed stage publishes + `\`. **Windows only:** `os.rename` refuses existing destinations, + including empty directories. Precheck improves diagnostics; the rename itself + supplies no-replace semantics for concurrent same-name requests. No `replace`, + merge, POSIX replacing rename, or delete-destination workaround is used. + Non-Windows generation fails `OUTPUT_IO_ERROR / + no_replace_publication_requires_windows` before staging. +- Existing output/sentinel data are never overwritten. `OUTPUT_EXISTS / + destination_exists` is explicit. Only a verified owned stage is cleaned: + first verify all present entries have recorded exclusive-create identities and + are regular, non-reparse and singly linked; unlink only those owned files, then remove that + specific empty stage. Unexpected content or lost identity refuses cleanup; + nothing follows links or recursively deletes output-root contents. +- Cleanup failure is explicit `OUTPUT_IO_ERROR / stage_cleanup_failed`, carrying + only the original domain code (or `internal`), and can leave the owned stage + for operator inspection. Root/stage replacement similarly refuses unsafe + cleanup. Permissions, disk failures, missing roots and publication failures + remain visible; fallback cannot hide them. +- These portable path/lstat/recheck APIs **do not** provide comprehensive hostile + race safety. A local actor able to replace directories/files between checks + and opens/unlinks/rename can race them. Use an operator-controlled root and + ancestors/volume with trusted ACLs; no handle-relative Windows NT namespace + confinement, cross-process malicious-lock protocol, mount-change defense, + or power-loss/fsync durability is claimed. Directory mode 0700 is advisory on + Windows, not an ACL guarantee. Root identity checks are not indefinite handle + pins and cannot prove against filesystem file-ID reuse. +- Publication success is the commit point; a client disconnect or process crash + afterward can leave a valid published output without a received response. + No post-publication rollback or acknowledgement database is implemented. + +The new unit/integration tests exercise these concrete guarantees, including +failure injection, concurrent same-basename publication, actual Windows +junctions, real stdio generation from another working directory and disk MIDI +inspection. Exact executed evidence and persistent example artifacts are in +`prompts/report_9_fix.md`. Native software integration is verified; application +acceptance remains separately unrun. + +## Installed software acceptance in Step 10 + +`tests/integration/test_distribution.py` extends the existing offline build +fixture and reuses the raw stdio client from `test_stdio.py`, without a second +production transport or duplicate build harness. The default build creates an +sdist then builds its wheel. The earlier dependency-free separate-venv import +test remains; the new server test installs that wheel with `pip --no-index +--no-deps --no-cache-dir --target` into an owned test directory. + +The `-I -B` bootstrap explicitly prepends this install target and asserts the +actual package, server, service, schemas, profiles, compiler, MIDI, native +boundaries, resource packages and `__main__` entry resolve there (16 locations), +not editable `src`. Distribution metadata must also resolve to the target. +It reuses development-venv runtime dependencies: this is isolated application +installation/execution, not a fresh full dependency-environment certification. +The process working directory is the pre-existing parent **outside** the +checkout; the test does not create files there. + +Six packaged JSON files are compared byte-for-byte to wheel archive members, +then discovered/read as installed resources and listed over real stdio. +Initialize, exactly two tools, exactly six profiles, public +input/output schemas, explicit MIDI, default fallback and native-only fallback +are exercised with **explicit standard IDs**. Independent Mido inspection checks type 1 / PPQ 960, +436364 microseconds/quarter at 137.5 BPM, 7/8, Conductor/Lead/Bass/Drums, common +end 6720, exact onsets/gates, legal positive onsets, complete note pairs and +channels 0/1/9. Returned paths/sizes/profile IDs/status/warnings must agree. +All three request-format policies produce the same 324-byte musical content, +not different native encodings. Additional real installed-server calls use an +original minimal SD3 template and target defaults to generate actual full +default/native-alias/actual-name/MIDI-only outputs, exact CC1 stairs/resets and +per-part controller fallback. Missing-template target fallback, disabled fallback +and native collisions are also checked. All saved `.griff`/`.briff`/`.sd3p` and +MIDI files are independently checked against the same requested score. + +Native-disabled, unsupported palm mute, Unicode unsupported text and collision +errors are schema-checked and cannot leave new output directories. +The client validates every UTF-8 newline stdout message as MCP JSON-RPC; +deliberate malformed input produces only a generic protocol notification on +stdout and sanitized diagnostics on stderr, with successful ping recovery. +Both initialized and pre-initialize EOF exit zero. Reads/writes/termination are +bounded; cleanup kills only the owned child if EOF times out, reaps it, and +removes the owned distribution/install/output workspace even on failure. + +The full suite, Ruff lint/format, strict mypy, `pip check` and final real +sdist/wheel build are separate checks. See [current tested configuration and +outcomes](compatibility.md#tested-software-configuration) and +[report_10.md](../prompts/report_10.md). These are native/MIDI software checks, +not receiver, Eclipse/Ray5/SD3 application or Cubase acceptance. + +## Operational service and remaining native boundaries + +```text +MCP client + -> SDK stdio lifecycle and two operational tools + -> strict Pydantic request/domain/result models (implemented contracts) + -> deterministic closed-grammar description and coordinated score (implemented) + -> versioned target subset defaults or explicitly selected standard fallback profiles + -> native check/require (Riffer subsets; SD3 subset requires local-template preflight) + -> explicit service fallback policy for known unavailable native capabilities only + -> Mido SMF writer / actual Riffer XML and SD3 template-song codecs + -> read-back validation -> staged, atomic local publication -> typed result +``` + +The registered tools are `list_instrument_profiles` and `generate_music`. +The SDK owns JSON-RPC lifecycle/negotiation. stdout is reserved for stdio +protocol traffic; diagnostics go to stderr. No HTTP application, GUI, database, +plugin host, audio engine, DAW automation, or model provider is introduced. + +Keep intent, logical notes, scheduled MIDI events, and native representation +separate. The planned shared timeline uses rational beat arithmetic before tick +quantization, aligned lead/bass/drum tracks, deterministic local random state, +and profile-specified control timing. Mido is the production MIDI library; +MIDIUtil is an independent test-fixture library, not a second production writer. + +Instrument-specific production profiles must identify exact instruments, versions, +source provenance, playable ranges, drum maps, keyswitch/CC semantics and layers. +Standard-only profiles instead identify their standard and explicit generator +policy; they cannot use verified vendor provenance or imply native availability. +Synthetic fixtures test mechanics but cannot become production maps. +Guitar/bass native adapters may share code only if evidence proves shared layout. + +The service publishes complete validated native/MIDI artifact sets under an +operator-configured local output root, rejecting unsafe names and collisions. +Unavailable native capabilities may permit explicitly reported MIDI fallback; +unverified vendor mappings and unexpected serialization/IO errors cannot be hidden +by a fallback success. A selected standard profile must remain explicitly +standard-only in metadata/warnings, never represented as a working vendor map. +A preset-only native format may contradict the requested +song-content requirement and needs a decision, not a fabricated implementation. + +## Sequencing and evidence + +Step 11 fixes a verified text-only feedback failure: the prior profile result +exposed only a count in text, and lead + sd3p with valid `E minor` exposed only +generic guidance while the useful error object lived in structured content. +Both result representations now contain the same complete safe JSON object. +Unit, official-client, raw-stdio and installed-wheel tests decode text and +assert equality with structured content. The text-only recovery scenario lists +real IDs, receives a `formats` correction, receives a separate missing-profile +recovery action, and generates/read-backs actual guitar `.griff` and `.mid` +using a returned ID and structured `Em`. Unrequested CC91 is removed by the +test consumer, not silently stripped by the server. Step 12 adds the bounded +beat-range/triplet/cross-bar-PH phrase above; arbitrary triplet melodies still error. +MCP schema constraints and protocol handling have not been simplified or replaced. +An existing LM Studio setup needs an operator MCP restart and a fresh chat to +refresh cached tool definitions; no live client/configuration is changed here. + +Steps 2–4 define typed contracts, an honest stdio skeleton, and a controlled +MIDI writer without inventing instrument data. Step 5 generic profile/compiler +mechanics and standard-fallback production profiles are implemented; vendor +mapping acceptance remains gated and does not block standard-only Step 6. +Standard-only composition, native Riffer writers/validators and the native SD3 +template-song codec and native/MIDI service wiring are implemented. +Step 9 fix verifies actual native integration, not a bypass of application acceptance. +Mapping evidence gates production instrument claims; +separate native structure and actual application acceptance gates each native +writer. The [compatibility inventory](compatibility.md) records those gaps. +The existing [AGP native fix](../prompts/step_7_fix.md) and +[SDP native fix](../prompts/step_8_fix.md) distinguish completed codecs from +remaining application work. Independent Step 10 +software acceptance does not satisfy the original full native definition of done. + +## Step 14: internal explicit pitch and polyphonic attack foundation + +Step14 introduced internal atoms/plans, not a public score tool. Step15 below +now exposes those atoms through bounded public hybrid description lanes. +The legacy low-tonic `PhrasePlan` and ordinary pattern paths are unchanged. + +`pitch.py` exposes immutable `PitchToken`, `ChordSymbol`, `ExplicitVoicing`, +`NotationToken`, and `ResolvedVoicing` values and these reusable functions: + +- `parse_pitch(text)` parses exactly one uppercase A–G, optional single ASCII + `#`/`b`, optional signed octave. C4=60; C-1=0; G9=127. Accidentals cross + octave boundaries correctly (Cb4=59, B#3=60). Unsupported spellings or + explicit pitches outside MIDI 0–127 fail. `.midi` on an octave-free token + fails until register resolution; `.pitch_class` remains available. +- `parse_chord(text)` parses a bare major root, `m`/`min` minor, optional root + octave **after** the quality, optional `(add4)`, and optional `/` or `Over` + bass. Thus Em4 is E4–G4–B4, not a fourth/add4 quality. Intervals are major + `[0,4,7]`, minor `[0,3,7]`, major-add4 `[0,4,5,7]`, and minor-add4 + `[0,3,5,7]`. Digits always mean root octave, never seventh/extensions. + Other qualities, extension syntax, or guessed slides fail. + `[C3 E3 G3]` is an explicit whitespace-separated octave-qualified pitch set; + duplicate numeric pitches (including enharmonic duplicates) are invalid. +- `tokenize_notation(text, kind="note" | "chord")` lexes compact runs up to + 4000 characters: F#F#, DD, BbBb, CEG, C4E4G4, and concatenated chord atoms. + `text`, `start`, `end`, and exact `leading_space` preserve token boundaries + and spacing width without assigning rhythmic meaning. Note and chord modes + are deliberately separate: C4 is one note in note mode, a major chord root + in chord mode. Unknown/ambiguous tails are errors, not ignored text. +- `resolve_voicing(value, profile)` returns sorted independent MIDI pitches + and disclosed `assumptions`. An absent note/root octave selects the playable + root nearest MIDI40 (lower wins ties) under the chosen profile range/tuning, + **before** constructing the chord. It does not search for another octave + if the complete chord then fails to fit. Explicit pitches are never changed + to match a key. Slash bass is strictly lower than every upper chord tone: + Em4/B2 and Em4OverB2 -> `[47,64,67,71]`; Em4/B and Em4OverB -> + `[59,64,67,71]`, with the nearest-below default reported. Contradictory + explicit bass octaves fail. Identical computed pitches are deduplicated. + `validate_voicing(pitches, profile)` checks every tone against MIDI bounds, + profile range, and evidenced individual-string tuning without dropping, + spreading, transposing, or arbitrarily revoicing. + +`schemas.ExplicitAttack` extends exact `TimedNote` timing/technique/intensity +with a nonempty unique set of MIDI `pitches`. `ExplicitAttackPlan` contains +one pitched `part`, positive rational `duration`, ordered `attacks`, and +optional register `assumptions` supplied by the notation resolver. It bounds +the timeline to the existing maximal score length, validates half-open +intervals, forbids independent same-pitch overlaps, permits disjoint compatible +polyphony, and rejects overlapping different profile-wide techniques. +Attack duration means one continuous sustain; gaps mean silence. There are no +rest, continuation, slide, lane-spacing, or prose-interpretation guesses. +Later parsing can represent rests with gaps and continuation by extending the +original duration rather than retriggering. It must propagate assumptions. + +`MusicalIntent.explicit_plan` is internal and mutually exclusive with +`phrase_plan`; it requires its sole part, sufficient bars/meter, and no global +rhythm/technique overrides. `compose_score` expands **all** tones as independent +simultaneous `PitchedNote`s at exact starts/durations. One seed draw per attack +provides shared chord intensity unless explicitly supplied, with the existing +bass seed offset. Techniques resolve through the actual selected profile. +The plan counts expanded note-on/off pairs; explicit composition also invokes +the authoritative compiler to enforce the 100,000-event ceiling **including** +articulation controls and to validate grid/control timing. Subsequent explicit +CC points remain subject to the existing combined compiler/control budget. + +The unchanged Riffer codec assigns independent tones using bounded physical +string allocation and validates saved pitch/fret/timing/technique data. A +full voicing with no physical string assignment can use only the existing +explicit `no_physical_string_assignment` MIDI-fallback policy; all pitches +survive in MIDI. Out-of-map pitches are composition errors, not fallback. +No profiles, tunings, vendor claims, dependencies, versions, or public request +fields were changed. Integration tests inject an internal resolution solely +to exercise actual service publication; they do not claim public chord prose +or lane parsing. Saved Mido/XML checks independently assert 11 musical tones, +4 MIDI selectors, 30 scheduled events, exact thirds, PM/PH, a non-key F# major +chord, both slash-bass octaves/aliases, and legal occupied physical strings. + +## Step 15: public hybrid prose and precise lanes + +`hybrid.py` separates lane/hold clauses before the legacy prose sequence guard. +`description.resolve_description` reuses the closed prose resolver for context, +then attaches a strict, profile-independent `HybridPlan` of rational +`HybridSlot`s. Count labels are denominator beats; widths/spaces are lexical only. +`count_grid` is reusable exact Fraction math for complete eighth/sixteenth and +explicit eighth-triplet beats, including 3/4 and non-quarter denominators. +`1&a` is rejected without a disambiguating grid; under sixteenths its `e` is +omitted (positions 0, 1/2, 3/4), while under eighth-triplets it is 0, 1/3, 2/3. +Bare labels remain one denominator beat even with a Grid directive. + +After profile selection, service and composer both reuse `hybrid.materialize`. +It calls Step14 tokenization/voicing resolution, never a second voicing engine, +and creates the existing `ExplicitAttackPlan`. `~` extends the previous +adjacent attack duration; rests create real gaps; prose ties extend a final +attack to an exact bar end only if no specified rest/new attack conflicts. +Exact source/installed E2 prose-tie, all-tilde-bar and continuation-clause outputs +are byte-identical. Structured meter changes cannot reinterpret explicit +labels; bars cannot truncate notation or holds. + +`o/x/^/-/~`, Notes/Chords empty lanes, compact tokens, explicit chord voicings, +slash/Over bass and ordered Bar blocks or matching `|` spans are public. +Events/Notes brackets group consecutive positions; Chords brackets specify +simultaneous notes. A slide direction in Events returns specific unsupported +origin/destination/timing guidance; slash chord spelling is unrelated. +Unknown prose is rejected, including tempo changes; style does not modify +precise pitches/times. Global techniques and explicit prose pitch claims must +agree with affected events. No implicit CC, transpose, revoice or dropped tone. + +The additive default-empty `resolved.interpretation` lists `InterpretedAttack` +records: exact pitches, rational start/duration, part, technique, optional +intensity and held status. Register/bass/default/velocity policy is in +`resolved.assumptions`. Text-only JSON and structuredContent are identical; +errors expose static authored reasons/guidance, never raw user text or paths. + +The corrected native fixture uses F#2 major, **D3 major [50,54,57]**, Bb2 major, +then C4/E4/G4: 21 musical tones with legal independent string assignments. +The old explicit D2 major [38,42,45] is deliberately a negative-native / +positive-exact-MIDI test, not a reason to disable the generic parser. +Native validation/tuning/fallback/publication/CC/event budgets are unchanged. +See README's hybrid section for tested public syntax and limits. diff --git a/docs/articulation-profiles.md b/docs/articulation-profiles.md new file mode 100644 index 0000000..c4c2263 --- /dev/null +++ b/docs/articulation-profiles.md @@ -0,0 +1,400 @@ +# Versioned profiles and articulation compiler + +**The operational MCP service defaults to three evidence-backed target subsets.** +Three explicit Standard MIDI fallback profiles also remain packaged and available. +Actual built-wheel generation/discovery is verified outside the checkout; +this is not application compatibility. +Installed AME 4.0.1 / AMR 4.1.0 identities and native Riffer XML 2.1 are now +locally verified, with default native subset profiles. +SD3 3.4.4 has a default SL-DFH core three-voice subset. +All application acceptance remains unrun. +Synthetic fixtures stay test-only. +Step 6 supplies composition; Step 9 connects the compiler to real MCP generation +and lists all six profiles with runtime native readiness and subset limitations. +Installed resource and stdio/software evidence is recorded in +[final native report_10.md](../prompts/report_10.md), separately from the unrun receiver, +plugin and Cubase checks. No bank/program setup is sent: configure receiver +patches and channel routing externally before importing/playing the MIDI. + +## SD3 core subset policy v1 + +`toontrack.sd3.3.4.4.core.v1` / `toontrack-sd3-3.4.4-core-v1.json` is a +default `verified_subset`, not a GM profile promoted to vendor support. +Read-only SD3 3.4.4 SL-DFH native declarations establish kickR/36, snareR/38, +hatsTP/42 and ordinary packed MIDI velocities 1–127. These are the only +declared voices: kick, snare, closed_hat (with documented convenience aliases). +No extra GM pitches, hat-controller states, choke behavior, named velocity +layers or other libraries are claimed. Actual template pad aliases and the +library/input-channel are checked at codec preflight. + +Zero-based channel 9, linear intensity-to-velocity interpolation, no controls +or reset events, common score-relative zero and six-place finite-decimal timing +are **generator policies**, separate from local vendor facts. The profile has +one action-free normal/sustain articulation. Templates are operator-local; +their kit/mixer/non-song state is preserved. Native output needs the actual +template, not just a metadata flag. See [SD3 codec](formats/sdp.md). +The template is configured only through operator CLI `--sd3-template` or typed +service/server keyword. Without it the target MIDI map still works, but runtime +native readiness is false. Invalid supplied templates error; no hidden fallback. +Real service wiring is verified; application acceptance remains unrun. + +## Standard fallback policy v1 + +These are standard MIDI facts plus explicit generator policy, **NOT verified +Eclips/Ray/SD3 maps**. They are neither synthetic fixtures nor vendor defaults. + +| Production ID / resource | Part | Zero-based channel | Range / voices | +| --- | --- | --- | --- | +| `standard.lead.v1` / `standard-midi-lead-v1.json` | lead | 0 | inclusive MIDI numbers 0–127 | +| `standard.bass.v1` / `standard-midi-bass-v1.json` | bass | 1 | inclusive MIDI numbers 0–127 | +| `standard.gm-drums.v1` / `general-midi-percussion-v1.json` | drums | 9 | all 47 GM Level 1 percussion sounds, 35–81 | + +Each is explicitly selectable by ID, not a default. Summary `mapping_kind` and +provenance `status` are both `standard_midi`; product/mapping versions identify +the MIDI standard and `standard-fallback-1`, not an installed plugin version. +The existing summary `instrument` field (`eclips` / `ray` / `sd3`) identifies +intended routing only, **never compatibility**. `native_format` identifies the actual target suffix (`griff` / `briff` / `sd3p`), +not a request alias or available writer; `native_available=false` for fallbacks. +Public product names and limitations explicitly disclose the fallback. + +Lead/bass channels 0/1 and accepting the full legal note-number range are output +policy, not guitar/bass playable-range claims. Drum channel 9 is the deliberate +selection of GM's human-numbered channel 10; it is not the SD3 default map. +Canonical drum names normalize the source sound names. Convenience aliases +(`kick`=36, `snare`=38, `closed_hat`/`hihat`=42, `pedal_hat`=44, +`open_hat`=46, `crash`=49, `ride`=51, `clap`=39) are generator vocabulary. +No other drum voice, instrument-specific variation, or choke behavior is inferred. + +Only canonical `normal` with alias `sustain` is supported, using no actions. +`sustain` means normal note duration, **not sustain-pedal CC64**. Palm mute, +slide, accent, and every undeclared technique fail explicitly. There are no +keyswitches, CCs, program/bank changes, GM-on messages, reset/state changes, or +control lead/gate/release tails. Notes use the score's exact rational start and +duration, converted without rounding at the selected PPQ; normal compilation +does not add pre-roll. Generic switch/CC mechanics remain available for separate +instrument/test profiles, not these fallbacks. + +All three profiles use a single interpolation interval `[0,1]` and positive +velocity range 1–127: `round(1 + 126 * intensity)`, nearest integer, ties to even. +Examples: 0→1, .25→32, .5→64, .75→96, 1→127. This is generator dynamics policy, +**not vendor velocity layers** or a claim that every receiver sounds every note. +Receiver patch selection, GM mode, routing, tuning, and sound behavior must be +configured externally. Service results carry per-part `STANDARD_MIDI_MAPPING` +warnings, including MIDI-only successes, and never claim vendor compatibility. + +### Public facts checked 2026-10-19 + +- **MIDI1-MESSAGES**: [MIDI Association message summary](https://midi.org/summary-of-midi-1-0-messages) + gives seven-bit note/velocity fields and zero-based channels 0–15. Hence + note numbers 0–127 are legal; sounding-note velocities here are 1–127. +- **GM1-OVERVIEW**: [MIDI Association GM Level 1 overview](https://midi.org/general-midi-level-1) + establishes the standard and distinguishes named sounds from acoustic timbre. + The overview alone does **not** supply the numerical percussion map. +- **GM1-PERCUSSION-TABLE**: [Computer Music Resource's Vanderbilt University + Blair School of Music teaching table](https://computermusicresource.com/GM.Percussion.KeyMap.html) + explicitly gives channel 10 and every percussion number 35–81. Checked core + entries include bass drum 1=36, acoustic snare=38, closed hi-hat=42, pedal + hi-hat=44, open hi-hat=46, crash cymbal 1=49, ride cymbal 1=51; endpoints + acoustic bass drum=35 and open triangle=81. All 47 numeric/name pairs have + independent regression assertions. Octave labels are deliberately unused. + +The profile sources use `standard_public` for external facts and +`generator_policy` for this policy section. Neither kind can satisfy `verified` +vendor provenance. Public reference URLs and facts only are stored, not manuals +or factory songs. No plugin or Cubase import test is implied. + +## Riffer subset policy v1 + +The production registry packages these **default** target maps: + +| ID / resource | Target | MIDI channel (policy) | Explicit tuning by descending string ID | Conservative frets/range | +| --- | --- | --- | --- | --- | +| `ample.ame.4.0.1.riffer.v1` / `ample-metal-eclipse-4.0.1-riffer-v1.json` | Ample Metal Eclipse 4.0.1, `.griff` | 0 | 36,43,48,53,57,62 | 0–22, MIDI 36–84 | +| `ample.amr.4.1.0.riffer.v1` / `ample-metal-ray5-4.1.0-riffer-v1.json` | Ample Metal Ray5 4.1.0, `.briff` | 1 | 35,40,45,50,55 | 0–19, MIDI 35–74 | + +These profiles declare `mapping_kind=instrument`, `status=verified_subset`, +`native_available=true` for the independently callable codec. This does **not** +mean application acceptance is complete. Native service wiring is implemented. +Target MIDI-only requests use mapped MIDI without needing a native template; +default/native requests generate actual native files whenever preflight succeeds. +Runtime listing supplements stored codec metadata with actual template readiness. + +### Description technique applicability + +`palm mute`, `palm-mute`, `palm muted`, `palm-muted` and `palm muting` apply to every selected +pitched part. In mixed lead/bass/drum requests the drums deliberately retain +normal articulation and this applicability is recorded in resolved assumptions. +Drum-only palm mute raises `UNSUPPORTED_ARTICULATION / pitched_parts_required`; +it is not silently ignored or interpreted as a drum choke. +Selected standard pitched profiles cannot implement palm mute and still error. +Integration tests assert actual guitar MIDI D0/26 and native PM, bass C0/24, +musical velocity 32–63 and native PMP, with ordinary mapped drum notes. + +### Instrument facts + +Read-only ProductVersion and native XML evidence IDs are +`LOCAL-AME-401-RIFF21-20261019` and `LOCAL-AMR-410-RIFF21-20261019`. +They establish XML 2.1 / PPQ 480, string layouts, MIDI pitch minus fret, `Sus` / +`PM` / bass `PMP`, off velocity, and discrete raw-unit CC1 points. Default-tuning subsets were +distinguished from actual drop variants. Fret limits above deliberately bound +generation to target-observed maxima; they are not claims about every possible +instrument configuration. + +Public main-panel manuals were checked in memory, without saving manual assets: +[Eclipse](https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf), sections +2.2.1–2.2.4, and [Ray5](https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf), +sections 2.2.1–2.2.4. Vendor C0 is numeric **24**, consistent with Eclipse's +documented C1 low range and native MIDI 36. D0 is **26**. Do not apply another +DAW's octave-label convention to these maps. + +- **Eclipse normal:** C0/24. Actual current manual sustain bands are 1–15 full + mute, 16–31 three-quarter mute, 32–63 half mute, **64–126 sustain**, and + 127 Pop/PH depending on Settings. Therefore normal generation uses **64–126**, + not a falsely normal 1–127 sweep. +- **Eclipse palm mute:** D0/26, native `PM`; lower velocity means greater mute + depth. Uses legal positive velocities **1–127** without inventing sublayers. +- **Ray5 normal:** C0/24, **64–126** sustain; 127 accent is excluded. +- **Ray5 palm mute:** also C0/24, **32–63** documented palm-mute band; below 32 + dead notes are excluded. D0's separate high/low dead-note behavior is not used. + The native C0-band representation is `PMP`, not D0's `PM`. Target-local + numeric observations distinguish them: 313 `PMP` notes use 40–60, whereas + 56 `PM` notes use 70–100 and 89 `DN` notes use 30–60. This distinction matters: + writing D0 `PM` with a C0-band velocity would conflate different modes. + Only the supported C0-band technique is generated; no additional named mode + or guessed D0 threshold is introduced. + +### Eclipse pinch harmonic extension + +AME mapping revision `riffer-subset-2` retains the existing production ID, +product 4.0.1 and XML 2.1 codec. A read-only check on 2026-10-20 verified the +installed VST3 ProductVersion 4.0.1 and aggregated 35 local AME `.griff` files: +17 `Articulation="PH"` notes, observed velocities 80–100 and NoteID pitches +49–73. No note sequences or factory assets were retained or copied. +The official [Main Panel manual](https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf) +was fetched and parsed in memory: page 6, section 2.2.1 lists PH at G0 with +range C1–C5; page 9, section 2.2.9 confirms G0. Established vendor C0=24 gives +G0=31 and C1–C5=36–84. The local observation range is not a technique limit. + +Only AME receives `pinch_harmonic` (alias `ph`), dedicated keyswitch31 and native +`PH`; AMR, SD3 and standard fallbacks remain unchanged. Strict native maps reject +wrong PH switch/label, arbitrary labels and bass PH. Legal positive velocities +1–127 with linear intensity interpolation, latched switching, zero lead and +1/32-quarter positive gates are generator policy, not inferred PH velocity +layers or vendor timing guarantees. No normal-C0 velocity127 shortcut or CC +effect is substituted. PH may remain one continuous cross-bar note. + +No named vibrato technique is enabled. Eclipse's manual describes default auto +vibrato while Ray5 describes manual mod-wheel behavior and configurable auto +modulation. The codec preserves already compiled CC1 stair points in raw MIDI +units; it does not guess a named mode, normalize values or invent resets. + +### Generator policy (not vendor facts) + +- Channels 0/1 route the two parts independently; configure receivers externally. +- Supported target techniques are explicitly latched. MIDI switch velocity 100, + zero lead, 1/32-quarter-note positive pulse, same-tick switch-before-note + ordering and no release offset are deliberate scheduling policy. They avoid + automatic pre-roll, not a claim that every host guarantees audible switching. +- One linear interval interpolates intensity using ties-to-even rounding: + `round(low + (high-low) * intensity)`. Vendor facts bound the legal technique + band; interpolation within it is **not** an asserted vendor layer definition. +- Native note mapping consumes only verified MIDI switches, uses explicit + physical strings/frets, and rejects impossible allocation, unsupported CCs, + off-grid timing, nonzero pre-roll or tails. It never clips or shifts content. + +Strict `riffer` settings include version, PPQ, instrument, actual extension, +per-string ID/open MIDI note/max fret, native articulation map and allowed CC1. +Unknown fields, wrong target/version, booleans masquerading as integer literals, +arbitrary tunings/fret policies and fabricated mappings are rejected. There is +no template scripting or filename-derived tuning. See the +[codec and independent reader](formats/agp.md) for API and saved-file limits. + +## Internal APIs + +- `profiles.parse_profile(str | bytes) -> InstrumentProfile`: strict JSON and + model validation, including duplicate JSON object-key rejection. +- `profiles.load_profile_registry() -> ProfileRegistry`: use + `importlib.resources.files`, not repository paths or the working directory. + `data.profiles.PROFILE_RESOURCES` explicitly lists three target defaults and + three explicit standard fallback resources. + Both resource package initializers are bundled in wheels; an inaccessible + package, missing or undeclared JSON, duplicate manifest entry, invalid JSON, + invalid profile, duplicate ID/default, or synthetic map is an error, not an + empty-registry success. Optional `package`/`declared` arguments support + resource testing; they do not bypass production validation. +- `ProfileRegistry.summaries() -> list[ProfileSummary]`: returns independent + copies of the reviewed public summary contract, sorted by ID. +- `ProfileRegistry.select(parts, ProfileSelection) -> dict[Part, InstrumentProfile]`: + explicit IDs must exist and match the part. Only an explicitly marked unique + production default is automatic; even a single nondefault requires an explicit + choice. Missing mappings use `ProfileRequiredError`/`ProfileNotFoundError`; + ambiguity uses `AmbiguousProfileError`; wrong parts use + `ProfilePartMismatchError`. Errors give fixed safe reasons and actionable + messages; ambiguity lists only the registry's validated IDs. +- `articulations.compile_score(score, selected_profiles, *, ppq=960) -> EventPlan`: + requires complete explicit selections, defensively revalidates score/profile + graphs, compiles events, enforces the 100,000-event budget incrementally, and + calls the reviewed `midi.validate_event_plan` before returning. + Explicit synthetic selections are supported for tests; discovery and registry + selection never admit them. + +Registry/profile failures are named `SerializationError` subclasses; selection +failures retain `PROFILE_REQUIRED`. Compilation failures use +`ArticulationCompileError` or the existing named timing/writer failures. +Unsupported techniques use `UnsupportedArticulationError`. Public details never +copy raw JSON, validation messages, unsupported input strings, or file paths. +Programming errors are not turned into successful fallback results. + +## Schema version 1 + +All objects inherit the strict shared `ContractModel`: unknown fields, numeric +strings/booleans, nonfinite numbers, and invalid MIDI ranges are rejected. +Version is the exact string `"1"`, not a coerced number. Required fields have no +guessed musical defaults (summary `mapping_kind` alone defaults to `instrument` +for existing contracts/fixtures). See the three clearly labeled +`tests\fixtures\profiles\synthetic-*.json` files for complete **test-only** +examples; they are not packaged production resources. + +A profile declares: + +- `id`, reviewed `summary`, `provenance`, explicit `default`, zero-based + `channel`, `playable_range` **or** `drum_voices`, canonical + `normal_articulation`, and `articulations`. +- Summary ID, product/mapping version, supported canonical techniques, MIDI + capability, and limitations must agree with the map/provenance. + Stored `native_available` agrees with strict `riffer` or `sdp` settings; + a flag or mapping evidence alone cannot authorize a serializer. +- Public summary `mapping_kind` is `instrument` (backward-compatible default) or + `standard_midi`; standard summaries expose only `normal`, with native unavailable. +- Provenance status is `test_only`, `verified`, `verified_subset`, or `standard_midi`. + `verified_subset` separates official/local identity, range, actions and velocity + facts from generator channel/state/timing policy, with explicit limitations. + `standard_midi` must + agree exactly with summary `mapping_kind`, use an explicit Standard/General + MIDI product label, declare only action-free normal/sustain, and separately + cover standard identity/range facts and generator channel/action/state/timing/ + velocity policy. It is not vendor verification. Test profiles require `test.` + IDs, a `SYNTHETIC ` product-name prefix, no vendor sources, and no default flag. + Production profiles cannot use that test identity. +- Provenance requires target build, mapping/preset identifier, product/mapping + versions, and limitations. Full `verified` attestations require explicit official + HTTPS or lawfully held local references covering identity, range/voices, + channels, actions, state/reset, timing, and velocity. This is a metadata + completeness rule, **not** automated verification that assertions are true. + Human evidence review remains mandatory. In-memory registry-policy tests use + unmistakable TEST-HARNESS references, not vendor evidence. +- Pitched profiles require an inclusive numeric range; drums require unique + logical voices with unambiguous physical MIDI numbers. No GM/channel-9 + convention is inferred. Musical pitches must be disjoint from all switches. +- Articulations/voices declare canonical names and aliases. Normalization + case-folds and collapses ASCII spaces, hyphens, and underscores to `_`; + resulting names must be ASCII alphanumeric segments. Every canonical/alias + collision, including within one item, is rejected. + +### Actions, layers, and units + +An articulation declares `mode: latched | momentary`, actions, and velocity +layers. Explicit typed actions can occur separately or together: + +| Action | Required data | +| --- | --- | +| `keyswitch` | MIDI note, positive velocity, `pulse` or `hold`, lead, positive gate, release offset | +| `cc` | controller, value, explicit reset value or null, lead, release offset | + +All action timing is rational **quarter-note beats**, using existing +`RationalBeat`/`PositiveBeat`; every declared value, even on unused techniques, +must convert exactly at the chosen PPQ. No rounding or milliseconds are implied. +Pulse switches release at selection tick plus gate, with zero release offset. +Holds release after the last compatible active note plus offset; gate is their +minimum positive duration, and an undersized hold is rejected, not extended. +Latched switches must be pulses. Momentary CCs require explicit reset values; +latched CCs cannot declare resets/tails. Duplicate physical actions in a +technique are invalid. Latched techniques must explicitly cover the same CC +controller set to prevent omitted-controller state leakage. + +Intensity intervals exactly cover 0 through 1, with no gaps/overlap: +`[low, high)`, except the last interval includes 1. Velocity bounds are +inclusive integers 1–127, monotonic, and disjoint across layers. Linear +interpolation within the selected interval rounds to nearest integer, ties +to even; there is no clamp. At an internal intensity boundary the upper layer +wins by definition, not arbitrary overlapping-layer precedence. + +## State and causal ordering + +Each selected part owns exactly one declared channel. Selected channels must +be distinct, including selected empty tracks. Notes and state never migrate +between parts/channels. Different physical musical pitches permit polyphony; +same-pitch overlap is rejected by the reviewed writer, not merged away. + +For a stateful profile, normal must be latched and **every** technique needs +explicit actions. Normal is not MIDI pitch zero or an assumed universal CC. +Velocity-only profiles can have no actions; differing velocity-only techniques +then overlap safely without global control state. + +- Latched selections are emitted initially and on transitions only; compatible + overlapping notes and repeated same-technique notes across gaps deduplicate. +- Overlapping controlled notes must request the same canonical technique. + Different techniques are conservatively incompatible even if some actions + happen to match; no unsupported independent-voice state is inferred. +- Compatible momentary overlaps form one active interval. Held switches remain + held until the final note releases; CC selections and pulse triggers remain + per-note, while resets wait for the final note plus declared offsets. +- A momentary overlay starts from declared normal. If necessary, normal's actual + actions are established before the overlay's first controls, allowing positive + switch gates to finish. Its normal actions are emitted again after the final + reset/release. A preceding nonnormal latched state needs enough room for this + explicit setup; it is never silently inherited as the overlay baseline. +- Lead/setup/restoration controls cannot change state while previous incompatible + musical notes remain active. Restoration and physical switch tails must fit + before subsequent incompatible demands; unsafe schedules fail explicitly. + Simultaneous conflicting switch triggers are not guessed into a valid map. +- Per-note pulses that overlap the same physical switch are unrepresentable and + rejected, not deduplicated. Exact release/retrigger boundaries are legal. + +Notes are deterministically sorted before scheduling. Raw integer schedules +can start before zero; one common pre-roll is exactly `max(0, -earliest_event)`. +Every part is shifted by that amount. `Score.start` remains a logical origin; +relative offsets, not that origin's absolute size, become ticks. +The shared end is the musical end or the latest switch/reset/restoration tail, +whichever is later, including when other tracks are empty. Restoration's declared +lead-time readiness is included even if the last physical event occurs earlier. + +Within a tick, priority 0 releases notes/switches, 10 resets CCs, 20 performs +selection/restoration controls (in causal emission sequence), and 30 starts +musical notes. Sequence values are unique and deterministic per track. +Every switch/musical note has a positive-duration paired release. Boundary +same-pitch retriggers release before re-onset. The existing writer performs +the final role, overlap, grid, channel, SMF-bound, and pairing checks. + +## Verification and remaining vendor/native gates + +Tests cover strict JSON/provenance/resource/selection policy, aliases, ranges, +layers/endpoints, separate and combined actions, state transitions, compatible +and incompatible overlap, per-note retriggers, exact timing/pre-roll/tails, +mutated graphs, deterministic output, and exactly 100,000 events versus overflow. +The three-part integration fixture has palm-muted lead, bass holds, articulated +drums, compatible overlapping notes, and boundary retriggers. Independently +hand-derived event lists are checked against both the compiler and a real +saved MIDI parsed by Mido, including channels, pairing, tempo, and common EOT. +Built-wheel tests install offline into an isolated import target and also load +resources directly from the wheel ZIP; both probes run outside the checkout +with isolated Python imports and confirm six production profiles, target defaults, +explicit standard selections/channels, core GM numbers and absence of synthetic +maps. Standard compilation is separately checked against independent events +and real MIDI read-back, including note range/velocity endpoints, no controls, +and honest unsupported-technique/voice failures. + +The old simplified Ample-page extraction was incomplete: raw official HTML +exposes public Eclipse/Ray5 main-panel, Riffer, Strummer, and settings PDFs. +See [compatibility](compatibility.md) for exact links and limitations. +To add verified **vendor** profiles, obtain installed product/edition/build and +mapping/preset/library versions, +lawful authoritative numeric ranges/channels/voices/keyswitches, latch/hold/ +reset/CC semantics, control lead/gate/release timing, velocity-layer/intensity +rules, and target-behavior verification with provenance/permission recorded. +Native layout/content evidence, controlled files, and plugin/Cubase load/save +round trips are a **separate** gate. No application acceptance test ran. +The [Step 5 fix report](../prompts/report_5_fix.md) records validation. +The current target subset maps, real native writers and native/MIDI service wiring +are verified in report_9_fix; standard fallbacks remain explicitly selectable. +Broader mappings and actual application acceptance remain separate, unrun gates. diff --git a/docs/compatibility.md b/docs/compatibility.md new file mode 100644 index 0000000..8a64091 --- /dev/null +++ b/docs/compatibility.md @@ -0,0 +1,265 @@ +# Compatibility and evidence inventory + +Inventory updated for release **0.2.0**, Step 16 software acceptance on 2026-10-20. +**Target subset defaults generate real native Riffer/SD3 and mapped MIDI outputs.** +AME 4.0.1 / AMR 4.1.0 ProductVersions, XML 2.1 structure and limited mappings +are verified; real `.griff`/`.briff` writers independently read saved originals. +The AME-only PH extension and exact beat-range/triplet/hold grammar, visible +text-only recovery and Em shorthand were added in Steps 11/12 and released +in 0.1.1. This does not retroactively change earlier report evidence. +Release 0.2.0 includes Step14/15 reusable exact voicings and public +hybrid Counts/Events/Notes/Chords parsing, with visible rational interpretation. +The corrected F#2/D3/Bb2 example passes real source and installed-wheel native +tests; explicit D2 remains exact-MIDI fallback, never hidden transposition. +The original E2 phrase remains byte-identical. These are software acceptance +results, not application playback certification; see +[the release report](../prompts/report_16.md) and historical +[Step15 correction report](../prompts/report_15_fix.md). +Slides (`/` and backslash Events) are reserved, not implemented. Exact pitches +are never key-retuned; explicit raw voicings can be physically unplayable and +then require honest exact-MIDI fallback or an error with fallback disabled. +Six production profiles exist; three standard maps remain explicit fallbacks. SD3 3.4.4 +has a real template song writer/parser/validator and SL-DFH core three-voice +profile. Native service integration is verified, including actual stdio and +installed-wheel generation. All application acceptance remains unrun. +Missing optional SD3 template permits drum-only fallback while preserving +real lead/bass natives. Explicit template errors never become fallback. + +Software acceptance covers the real service, stdio generation, actual +saved MIDI/read-back and Windows no-overwrite publication (including real junction +checks), plus the built-wheel server outside the checkout. The Riffer fix adds real +native saved-file evidence but does not close application acceptance. Publication +on non-Windows is explicitly unsupported until a no-replace primitive is supplied. + + + +## Tested software configuration (CURRENT release 0.2.0) + +Current full-suite/package/static results, exact persisted distribution hashes, +and retained original native read-back paths are in +[the Step 16 report](../prompts/report_16.md). The unchanged +[Step 10 native report](../prompts/report_10.md) is historical baseline evidence, +not acceptance of the later precise phrase or text-only recovery. + +Only this configuration was executed, not every version permitted by metadata: + +| Component | Actual tested version / outcome | +| --- | --- | +| OS / architecture | Windows 11, build 10.0.26200, AMD64 | +| Python | CPython 3.13.13, MSC v.1944 64 bit; declared minimum 3.11 is not a test of 3.11/3.12/other runtimes | +| Runtime | mcp 1.30.0; pydantic 2.14.1; mido 1.3.3 | +| Tests / contracts | pytest 9.1.1; anyio 4.15.1; MIDIUtil 1.2.1; jsonschema 4.26.0; types-jsonschema 4.26.0.20261006 | +| Static checks | Ruff 0.17.1 lint/format; mypy 2.4.0 strict | +| Build / install | build 1.6.1; setuptools 84.2.0; wheel 0.48.0; packaging 26.3; pip 26.0.1 | +| Package / MCP version | 0.2.0, from one authoritative source; editable metadata refreshed offline without reinstalling dependencies | +| Complete automated suite | Final counts in report_16.md; includes original E2 hybrid, canonical D3 and honest D2 fallback, slash/explicit voicings, exact phrase, text-only recovery, native/MIDI/CC and atomic/privacy checks; no application evidence is represented as a skip | +| Installed-wheel acceptance | PASS: exact persisted final wheel installed offline/noneditably; isolated package/submodule/metadata and six resource paths, real stdio native/default/alias/actual-name/MIDI/CC generation with disk read-back outside checkout; existing dev-venv dependencies reused, not a fresh dependency certification | +| Final distributions | Real 0.2.0 sdist and wheel (wheel built from sdist), under `dist\hybrid-0.2.0-20261020`; exact paths/hashes and final acceptance in report_16.md | +| Lint / format / strict types / dependency metadata | PASS: Ruff lint/format, strict mypy, `pip check` | +| Applications / receivers | UNRUN: Cubase MIDI import; Eclipse/Ray5/SD3 routing, native load/save/close/reload; installed AME/AMR versions are now verified, host/configuration acceptance remains unrun | + +Reproduce with the [validation commands](../README.md#validation). +The built-wheel workflow extends `tests/integration/test_distribution.py`; all +six packaged JSON resources and all 18 package/submodule entry locations are +asserted under the wheel target. The server's cwd is the checkout's existing +parent, not the repository, and `-I -B` plus explicit install-target precedence +prevents accidental editable imports. Normal tests use no network. +Current exact commands, cleanup and separate results are in +[report_16.md](../prompts/report_16.md). `pip check` certifies installed dependency +metadata consistency, not all behavior of every transitive package. +After this update restart the MCP, then start a fresh LM Studio chat to refresh +schemas. The configured venv now resolves 0.2.0 without config edit/reinstall; +the exact copy-ready original prompt is in README. Live model/playback is unrun. + +## Separate evidence gates + +| Target / product and version | MIDI mappings | Native layouts | Automated checks | Application import acceptance | +| --- | --- | --- | --- | --- | +| Standard MIDI pitched lead/bass and GM Level 1 percussion; mapping policy `standard-fallback-1` | Production `standard.lead.v1`, `standard.bass.v1`, `standard.gm-drums.v1`; public `mapping_kind=standard_midi`, NOT vendor maps; explicit zero-based channels 0/1/9 | No native availability; real `.mid` generation via service/MCP | Strict profiles, independent numeric GM assertions, exact compiled events, real MIDI read-back, service/stdio publication, installed/ZIP wheel resources and actual built-wheel server generation outside checkout | UNRUN in a receiver/plugin/Cubase; sound configuration external | +| Lead: Ample Metal Eclipse 4.0.1 (local VST3 ProductVersion) | Default normal/palm-mute/PH subset; C0=24/D0=26/G0=31; normal 64–126, documented PM depth and PH range36–84; tuning/range and generator policy distinguished | Real `.griff`, Riffer XML 2.1 / PPQ 480; `agp` request alias only; actual PM/PH labels and cross-bar PH hold | Actual service/stdio/installed-wheel original XML and independent saved-file note/CC/timing validation, including exact nine-note phrase; strict profiles/contracts and corruption/physical-string/timing rejection | UNRUN in plugin/Cubase; native software success is not application certification | +| Bass: Ample Metal Ray5 4.1.0 (local VST3 ProductVersion) | Default normal/palm-mute subset; C0=24, sustain 64–126, PM 32–63 and native PMP; no accent/dead-note leakage | Real `.briff`, Riffer XML 2.1 / PPQ 480; `agp` request alias only | Actual service/stdio/installed-wheel native output; independent note/CC/timing/velocity/technique validation and partial-fallback regression | UNRUN in plugin/Cubase; native software success is not application certification | +| Drums: Superior Drummer 3 standalone 3.4.4, local SL-DFH pad/alias evidence | Default verified subset: kickR/36, snareR/38, hatsTP/42 only; channel/intensity policy separate; no full GM-map claim | Real `.sd3p` template-based song replacement and bounded parser; `sdp` request alias only; operator-local matching template required | Actual service/stdio/installed-wheel output, original minimal and genuine read-only local-template checks, exact note/tempo/meter/channel/velocity, full source-song replacement, byte-identical non-song state; malformed/version/IO/fault rejection | UNRUN in SD3/Cubase; preserved host sync/mute/routing settings and acoustic behavior remain operator/application concerns | +| Cubase15 user project previously observed (PID 41836); exact edition/build and routing unconfirmed | Imported tempo/meter, part alignment, routing and control preservation unverified | No `.cpr` writer is in scope; plugin-native imports are separate operations | Original generated SMF/native saved-byte checks only; no DAW tests | UNRUN: no project manipulation, global input or competing audio host/driver | + +Native-file readability, correct mapping, automated structure checks, and actual +application acceptance are distinct. No column can be inferred from another. +Renaming a `.mid` to `.agp` or `.sdp` is **not** support. A file that stores only +presets/settings might not carry the requested notes, rhythm, or song content. + +## Remaining application evidence to obtain + +The executable codecs, local layout/map facts and original controlled fixtures +are established. The following checklist concerns broader receiver/application +certification and expansion beyond current verified subsets, not a current +native implementation blocker. + +1. Record receiver configuration, SD3 installed library/preset/active MIDI map, + Cubase version and routing. AME/AMR product identities/versions are now known. +2. Record the exact application's native export/import menu actions, extension + and file category. Establish whether notes/patterns/song tracks are actually + stored, embedded, or merely referenced. +3. Obtain lawful empty, one-note/hit, multi-note/hit exports, plus controlled + single-variable changes to tempo, timing, velocity and articulation. + See separate [AGP](formats/agp.md) and [SDP](formats/sdp.md) checklists. +4. Obtain authoritative mapping evidence for MIDI numbers (not ambiguous octave + labels), channels, ranges, switches/CC timing/reset/latch rules and layers. +5. Record real native load/save/reload acceptance and MIDI import in Cubase: + notes, tempo/meter, aligned duration, dynamics, articulation and routing. +6. Record evidence ID, product/version, workflow, source/date, observed facts, + unknowns, expected/observed results, and redistribution permission. + Keep private absolute paths and licensed content out of distributed metadata. + +Do not upload private files, credentials, or code. Do not bypass authentication +or copy licensed manuals. Check in native fixtures only with explicit +redistribution rights. Otherwise keep files local in an operator-owned location, +document local-only fixture IDs and an opt-in test procedure, and report missing +private/application tests as unrun, not passed. New checked-in native fixtures +contain exclusively original generated content, not factory or private exports. +SD3's local-template generated evidence retains private kit state and stays +ignored outside source/tests. See [SD3 evidence/results](../prompts/report_8_fix.md). + +## Historical public checks through Step 10 + +The following records earlier discovery, superseded where the current native +implementation above supplies local facts. It is not a current absent-evidence +blocker for Riffer. + +Checked 2026-10-19, using unauthenticated public pages only: + +| Source | Observation | What it establishes | +| --- | --- | --- | +| [Official Python MCP SDK, maintained v1.x metadata](https://github.com/modelcontextprotocol/python-sdk/blob/v1.x/pyproject.toml) and [test configuration](https://github.com/modelcontextprotocol/python-sdk/blob/v1.x/tests/conftest.py) | SDK uses AnyIO; tests select its asyncio backend; Python floor allows 3.11 | Dependency/test choice, not this project's transport or instrument support | +| [AnyIO testing documentation](https://anyio.readthedocs.io/en/stable/testing.html) | pytest plugin ships with AnyIO; backend selection is explicit | No separate pytest-asyncio plugin required | +| [Ample public manual entry point](https://www.amplesound.net/en/manual.asp) | Initial simplified text extraction missed links; raw official HTML exposes public main-panel, Riffer, Strummer and settings PDFs listed below | Documentation is publicly accessible; exact installed mappings, octave labels and `.agp` native layout are not verified by link discovery | +| [Toontrack SD3 manual entry point](https://www.toontrack.com/manual/superior-drummer-3/) | Page says to log in to view manuals; no login attempted | No `.sdp` layout or song-content claim verified | +| [MIDI Association GM Level 1 overview](https://midi.org/general-midi-level-1) | Describes the GM Level 1 standard and named sound portability, without defining acoustic timbre | Standard identity only, not an SD3 preset/map | +| [MIDI Association message summary](https://midi.org/summary-of-midi-1-0-messages) | Seven-bit note/velocity data and channel numbers 0–15 | Legal MIDI values, not plugin playable ranges | +| [Computer Music Resource / Vanderbilt Blair School of Music numerical table](https://computermusicresource.com/GM.Percussion.KeyMap.html) | Explicit GM channel 10 and all 47 note-to-sound pairs 35–81, checked independently of the overview | GM percussion numbers, not SD3 default-map or application acceptance | + +Package versions and `Requires-Python` were checked against public +[PyPI JSON metadata](https://docs.pypi.org/api/json/) and resolved in `.venv`. +Those checks are dependency evidence, not proprietary format documentation. +The [plan's references](../prompts/plan.md#15-planning-references) retain earlier +MCP/Mido/MIDIUtil documentation; no earlier planning assertion is promoted into +an application compatibility result. + +## Historical readiness before executable native fixes (superseded) + +This section records the old unavailable-boundary state only. Current codecs +and native service are implemented; see the matrix and report_9_fix above. + +Foundation checks and their exact outcomes belong to +[report_1.md](../prompts/report_1.md). Step 2 typed models are not blocked by +unknown native layouts. Step 6 standard-only composition is implemented under +the amended continuation decision. Step 7 implements the honest AGP capability +boundary, not a native writer. Step 8 implements the corresponding SDP boundary; +both are reused by Step 9's operational standard-MIDI service/fallback path. +Step 10 independently verifies installed software/package behavior without +claiming native acceptance. Verified instrument profiles +and native writers remain gated. If a requested container cannot hold the requested musical data, +record that contradiction and obtain a scope decision; do not substitute formats. +The unresolved [AGP fix handoff](../prompts/step_7_fix.md) and +[SDP fix handoff](../prompts/step_8_fix.md) stay **BLOCKED**: no actual native +schema/codec, lawful controlled fixture corpus, version/content proof or real +application round trip was supplied. No full native-project completion is claimed. + +## Corrected Ample documentation discovery + +On 2026-10-19 the raw official manual-page HTML was checked directly and exposes: + +- [Eclipse main panel](https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf) +- [Ray5 main panel](https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf) +- [Guitar Riffer](https://www.amplesound.net/en/Guitar_Riffer.pdf) +- [Guitar Strummer](https://www.amplesound.net/en/Guitar_Strummer.pdf) +- [Settings and CPC](https://www.amplesound.net/en/Settings_and_CPCv2.pdf) + +The prior conclusion that the page contained only a domain label was an +extraction error, not evidence that manuals were unavailable. These public +links identify documentation candidates; this standard-only fix does not +certify their numeric mappings against installed products. Octave labels must +be resolved to MIDI numbers; installed versions, selected presets/maps, +control semantics and native content/layout still require verification. +No manual or factory MIDI song was downloaded into the repository or copied. +Toontrack authentication was not bypassed. No private data was uploaded. + +## Historical standard-only registry (now explicit fallback resources) + +The three resources below remain available by explicit ID. The current manifest +also includes three target subset defaults; installed and ZIP-resource tests +verify all six and distinguish target defaults from standard selections. + +The explicit manifest lists `standard-midi-lead-v1.json`, +`standard-midi-bass-v1.json`, and `general-midi-percussion-v1.json`. +Standard provenance separates public facts (`standard_public`) from routing, +normal/sustain-only behavior and linear velocity policy (`generator_policy`). +See [policy, source IDs and exact values](articulation-profiles.md#standard-fallback-policy-v1). +`standard_midi` is not `verified` instrument provenance. Reviewed `instrument` +values are routing intent only. Public labels/limitations remain in profile +listing and per-part `STANDARD_MIDI_MAPPING` warnings in Step 9 results. + +Installed-wheel and ZIP-resource probes outside the checkout verify exactly +these three production profiles, normal selection and absence of synthetic/ +verified-vendor profiles. Synthetic maps remain in `tests\fixtures\profiles`, +excluded from discovery. No test attestation or synthetic number is promoted. + +The [profile/compiler mechanics](articulation-profiles.md) implement versioned +validation, layer/action/state scheduling, common pre-roll and tails, and +actual synthetic and standard three-part MIDI read-back. They do **not** verify Eclips/Ray/ +SD3 behavior. Exact evidence needed is listed above and in +[report_5.md](../prompts/report_5.md), with the continuation clarified in +[report_5_fix.md](../prompts/report_5_fix.md). **Composition is standard +fallback only**. Vendor maps, native evidence and actual plugin/Cubase load/save +acceptance are separately unresolved/unrun, not passed. + +## Historical Step 7 AGP boundary (superseded by executable fixes) + +The following unavailable-boundary record is historical, not current codec +status. The current matrix above and reports 7_fix/8_fix supersede it. + +`check_agp_capability` returns a typed immutable unavailable result for valid +lead/bass profiles. `require_agp_capability` raises +`NATIVE_FORMAT_UNAVAILABLE` with `format=agp`, requested `part`, and fixed +`reason=agp_layout_not_established` before output IO. Invalid requests, +wrong-part selection and corrupt/mutated profiles remain distinct named +failures. Metadata alone never enables a native codec. Standard `.mid` +composition/writing remains independently usable, not native serialization. + +The [AGP evidence/API record](formats/agp.md) records the supplied official +main-panel/Riffer evidence and prior public-demo archive metadata inspection: +range/articulation labels and MIDI/preset UI are not a native schema; the +archive yielded no AGP fixture, not proof that the format does not exist. +Those prior observations were not independently re-downloaded in Step 7. +No licensed content/native fixtures were copied. Actual layout, lawful +controlled fixtures, separate product/version encoding and real Eclips/Ray +load/save/reload remain missing. Software capability tests may pass while +**native acceptance remains BLOCKED and application/round-trip tests UNRUN**. + +## Historical Step 8 SDP boundary (superseded by executable Step 8 fix) + +The following unavailable-boundary record is historical. Native SD3 parsing, +song writing and saved-file validation are now implemented; only service and +application acceptance remains open; native service integration is complete. +See the current matrix and report_9_fix. + +`check_sdp_capability` returns the shared immutable `NativeCapability` for valid +drums profiles: `part=drums`, `format=sdp`, `available=False`, +`reason=sdp_layout_not_established`. `require_sdp_capability` freshly checks and +raises `NATIVE_FORMAT_UNAVAILABLE` with the same format/part/reason before any +path is touched. Non-drums requests, valid wrong-part profiles and corrupted/ +mutated/unchecked invalid models fail explicitly, not as native fallback. + +The [SDP evidence/API record](formats/sdp.md) distinguishes this passing software +boundary from the still-blocked native writer. Prior official manual access +required login; no new specification or genuine native fixture was obtained, +no authentication bypass or licensed-content copy occurred. Content category, +layout, supported versions, selected library/map semantics and actual generated +drum events must still be established from lawful controlled exports and real +SD3 import/save/close/reload. Preset-only settings do not meet drum-song scope. + +Production General MIDI percussion remains explicitly NOT an SD3 map/native +capability. Separate real drums-only/combined `.mid` tests validate the current +standard pipeline, contain no SDP artifact and do not certify SD3 or Cubase. +**SDP serialization/native acceptance: BLOCKED; native round trips and actual +SD3/Cubase acceptance: UNRUN.** Step 9 implements the independent standard-MIDI +service/fallback path under the amended continuation decision; its operational +wiring and publication do not satisfy the SDP serialization/application gates. diff --git a/docs/formats/agp.md b/docs/formats/agp.md new file mode 100644 index 0000000..40bdec5 --- /dev/null +++ b/docs/formats/agp.md @@ -0,0 +1,128 @@ +# Ample Riffer XML 2.1: `.griff` / `.briff` + +**Implemented:** native musical-content writers and independent saved-file +validators for Ample Metal Eclipse **4.0.1** and Ample Metal Ray5 **4.1.0**. +`agp` is a logical request/legacy Python API alias, **not a file extension**. +No MIDI is renamed. Plugin/Cubase load/save/reload acceptance remains **UNRUN**. +The native profiles are now **defaults**, wired to MCP generation alongside +the SD3 template-song codec. See [service verification](../../prompts/report_9_fix.md) +and [final exact-wheel native acceptance](../../prompts/report_10.md). + +## Evidence and reproducibility + +Read-only local evidence checked 2026-10-19: + +| Safe evidence ID | Technical observations | +| --- | --- | +| `LOCAL-AME-401-RIFF21-20261019` | Installed VST3 ProductVersion 4.0.1; 35 target AME preset files, XML `Riff`, `Ver="2.1"`, `PPQBase="480"`, six strings, `Inst="AME"` | +| `LOCAL-AMR-410-RIFF21-20261019` | Installed VST3 ProductVersion 4.1.0; 30 target AMR preset files with the same XML version/PPQ and five strings; factory files omit `Inst`, a user-authored example includes `Inst="AMR"` | + +Only schema/numeric facts were extracted. Factory sequences, plugin binaries, +manuals and private templates were neither copied into the repository nor +uploaded. Public [Eclipse](https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf) +and [Ray5](https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf) main-panel +manuals establish the limited technique semantics; the +[Riffer manual](https://www.amplesound.net/en/Guitar_Riffer.pdf) documents +Riffer save/load separately from MIDI import/export. +See [profile facts versus generator policy](../articulation-profiles.md#riffer-subset-policy-v1). + +Original generated, independently validated XML fixtures: + +- `tests\fixtures\riffer\original-lead.griff` +- `tests\fixtures\riffer\original-bass.briff` + +Integration tests retain real generated read-back evidence under +`.test-artifacts\native-riffer-evidence-v1\`. These are newly composed minimal +verification notes and CC points, **not vendor music or application re-saves**. +Tests require no vendor files, network, plugin installation or manual parser. + +## APIs + +The module remains `riff_groove_builder.formats.agp` for compatibility: + +- `check_riffer_capability(part, profile)` / `require_riffer_capability(...)`. + Legacy `check_agp_capability` / `require_agp_capability` retain their signatures. + Checks perform **no filesystem IO**, revalidate the whole mutable profile, + and return frozen `NativeCapability(part, format="agp", available, reason)`. + Supported target/version/settings return `available=True`, + `reason="riffer_xml_2_1"`; standard and synthetic profiles return + `available=False`, `reason="riffer_profile_not_supported"`. +- `write_riffer(path: Path, plan: EventPlan, part: Part, profile: InstrumentProfile) + -> Path`, also named `write_agp`. It exclusively creates the **supplied staged + path**, requires the actual case-sensitive suffix, flushes/fsyncs, then reads + the saved file back. It creates no parent, sibling, template or fallback file. + The caller owns staging, cleanup and publication. An invalid saved file is + left in its stage for inspection and is never reported as success. +- `validate_riffer_file(path, plan, part, profile) -> RifferReadback`, also named + `validate_agp_file`. Reads bounded actual saved XML without calling the + serializer; returns parsed notes, discrete CC1 points and native end tick. + Independently checks root metadata, tuning/frets, string overlap, velocities, + technique, exact timeline and every requested note/CC against the score/plan. +- `preflight_riffer(plan, part, profile)` runs exact content/grid/physical-string + checks without output IO. Service fallback recognizes only specific known + representation failures from preflight, never write/read-back corruption. + Writers accept optional `on_created(fstat)` for service-owned partial-file + identity tracking, invoked immediately after exclusive open and before writes. + +Only AME 4.0.1 / AMR 4.1.0 with the strict native subset can authorize this codec. +A native flag, mapping attestation, synthetic profile or product string alone +cannot do so. Profile schema `"1"` and mapping version are not container versions. +Malformed/mutated models raise `SERIALIZATION_ERROR`; wrong-part selection +raises `PROFILE_REQUIRED`; invalid requested parts raise `INVALID_REQUEST`. +Unavailable profiles raise `NATIVE_FORMAT_UNAVAILABLE`; wrong suffix, unsupported +content, unrepresentable timing and saved-content mismatches are serialization +failures in the codec. The service may explicitly fall back only for known +preflight capability/representation limits. Existing output raises `OUTPUT_EXISTS`; IO errors use +`OUTPUT_IO_ERROR`. Unexpected programming failures propagate. + +## Encoded subset + +- UTF-8 XML `Riff` root, `Ver="2.1"`, `PPQBase="480"`, `Inst="AME"` / `"AMR"`, + `numStr=6` / `5`. Author is the generator name, Category `Metal`, Type `Riff`, + Rating `0`, Quantize `1/32`; these are output metadata, not quantization. + Measures, Time-Signature, Tempo and Key come from the score. Native keys use + pitch class plus `m` for minor. Loop spans the exact whole score from zero. +- Strings are emitted in descending physical ID order, including empty strings. + Explicit guitar tuning by ID 6..1: **36,43,48,53,57,62**; bass 5..1: + **35,40,45,50,55**. Conservative maximum frets are respectively **22 / 19**. + Observed drop variants are **not** inferred or silently substituted. +- Every note has NoteID (MIDI pitch), Fret, Begin, End, Velocity, Off-Velocity, + Articulation (`Sus`; guitar `PM`, bass C0-band `PMP`), Legato (`No Legato`), + Muted (`False`). Bass `PM` is the separate D0 high-velocity mode, not the + C0 32–63 band selected by this profile. + Physical routing uses bounded deterministic backtracking, preferring lower + frets. If no assignment exists, or 200,000 search iterations are exhausted, + it explicitly fails; it never steals a string, shortens or drops notes. + Legal chords occupy distinct strings. Same-string boundary-touching notes + are allowed; overlapping notes on a string are not. +- Native normal/palm-mute fields replace the compiler's verified MIDI + keyswitches, not musical notes. A separate recompile of the selected score + part verifies every musical and switch on/off before serialization. + Off velocities come from the actual event plan, not a fabricated constant. +- Compiled CC1 is preserved in `cc-1.Mod` with root `ccName-1="1.Mod"`, + `ccVisibility-1="1"` and `p(tick,value,curveType="stair")`. Values remain + raw MIDI **0..127**, not normalized 0..1. No reset or named vibrato mode is + invented. Other CCs, duplicate-tick CC1 actions, curved interpolation, + legato/effects/strums or arbitrary extra XML content are explicitly rejected. + +## Timing and limitations + +Score beats are exact fractions. Conversion to PPQ 480 never rounds. +The score origin is translated to zero exactly as the MIDI compiler does; +notes retain their exact relative starts/durations. Multiple score parts may +be supplied, but one explicit selected part is written to each native file. + +**Nonzero compiled pre-roll or any control tail is rejected.** There is not yet +an evidence-backed fractional pickup/extra-measure origin contract shared by +native and MIDI outputs. Shifting notes back, clipping tails, inserting guessed +bars or changing loop bounds would falsely claim alignment. The new profiles +use same-tick ordered switches, zero lead, and a 1/32-quarter-note pulse as +generator MIDI policy; no vendor timing guarantee is claimed. Native controls +at valid ticks inside the shared musical span are retained exactly. + +The independent reader deliberately validates this generated subset, not all +vendor-authored Riffer files. It rejects DTD/entities, non-UTF-8 input, over +16 MiB, links/reparse points, unknown fields/content, illegal numeric values, +wrong target/version and note/CC corruption. It does not launch a plugin, +prove audible articulation or certify native load/save/reload. Those are +separate application acceptance tasks, not pytest skips. diff --git a/docs/formats/sdp.md b/docs/formats/sdp.md new file mode 100644 index 0000000..a9951d1 --- /dev/null +++ b/docs/formats/sdp.md @@ -0,0 +1,162 @@ +# Superior Drummer 3 `.sd3p` template song codec + +**Implemented: bounded native SD3 3.4.4 parser, operator-template song writer, +preflight and independent saved-file validator, wired to actual MCP generation. +SD3 application load/save/reload and Cubase acceptance remain UNRUN.** +`sdp` is a request/API alias; actual native artifacts require `.sd3p`. + +## Evidence and ownership + +Read-only local evidence establishes installed standalone ProductVersion 3.4.4, +five native UTF-8 projects with `PlugVersion 3.4.4`, `SAMPLER/HQ` library +`SL-DFH`, actual pad aliases and `SongTrack/MidiLoop/MidiEvents` fields. +Safe provenance ID: `LOCAL-SD3-344-DFH-PADS-20261019`. +No factory music, private project, manual or executable is bundled. + +The installed “Operation Manual.pdf” is a **one-page link sheet**, not the +complete manual. Its official [manual link](https://www.toontrack.com/manual/superior-drummer-3/) +still requires login (checked 2026-10-20); no login was attempted. Core mapping +facts therefore come from actual local native pad/alias declarations, not an +invented public-manual citation or the GM table. + +The default `toontrack.sd3.3.4.4.core.v1` resource supports just: + +| Voice | Native pad | MIDI pitch | +| --- | --- | --- | +| kick | `kickR` | 36 | +| snare | `snareR` | 38 | +| closed_hat | `hatsTP` | 42 | + +Aliases must resolve uniquely to these actual defined pads in `xpad 0 SL-DFH`; +the template's main library must match. Active sampler MIDI-learn overrides +and incompatible input-channel filtering are rejected. Kit choice, mic/mixer +state and all other non-song state stay operator-owned. + +## Python APIs + +- `parse_sdp_project(raw: bytes) -> SdpProject`: bounded structural parser; + exposes exact `non_song_bytes`, parsed source note triples and SHA-256. +- `inspect_sdp_template(path: Path) -> SdpTemplateInfo`: read-only filesystem, + version, structure, pad-map and input-channel preflight. +- `check_sdp_capability(part, profile, *, template: Path | None = None)`. +- `require_sdp_capability(part, profile, *, template: Path | None = None)`. +- `write_sdp(path, plan, part, profile, *, template: Path | None = None) -> Path`. +- `validate_sdp_file(path, plan, part, profile, *, template=None) -> SdpReadback`. + `write_sd3p` / `validate_sd3p_file` alias the same real codec. +- `preflight_sdp(plan, part, profile)` runs event/precision checks without output IO. + Writers additionally accept optional `on_created(fstat)` for exact service-owned + partial-file identity tracking immediately after exclusive open. + +The CLI exposes optional operator `--sd3-template `, +threaded as `sd3_template: Path | None` through `create_server`/`GenerationService`. +No tool-controlled arbitrary path is allowed. The service pins and checks source +identity/size/mtime/hash; explicit template failures remain visible even when +fallback is allowed. Missing optional template permits only drum native fallback, +preserving available Riffer natives and one combined MIDI. + +Check/require defensively revalidate mutable profiles and reject wrong parts. +Without an explicitly supplied template they do **no IO**. Standard GM or +mapping-only profiles return `sdp_profile_not_supported`. The supported target +without optional template returns `sdp_template_required`, a named capability +limitation. With a valid supplied template it returns available, reason +`sd3_3_4_4_template_song`. Stored `summary.native_available` describes a real codec; +the service's listing reports actual runtime readiness after template preflight, +with version/library/subset and application-limit disclosures. + +Explicitly supplied missing/unreadable paths are `OUTPUT_IO_ERROR`, not +unavailability. Wrong suffix, corrupt UTF-8/state/events, unsupported version, +ambiguous tracks or mismatched mapping are `SERIALIZATION_ERROR`. Invalid +requests/profiles remain their existing named errors. Never silently fall back +on these errors. There is no template scripting, subprocess or code evaluation. + +## Native representation and replacement + +Native text has balanced, newline-delimited blocks. Quoted/escaped text, +braces inside quotes, UTF-8, LF/CRLF and the observed single terminal NUL are +handled without decoding/re-encoding opaque payload contents. Boundaries: +16 MiB per file, nesting 64, one million tokens, 100,000 note triples, +1–32 contiguous source tracks, numerical positions no greater than 16,384 +quarter-note beats. Invalid/unbalanced/duplicate core state is rejected. + +`MidiEvents/Events` contains repeating **packed integer, start beat, end beat** +triples. Packing is `status | (pitch << 8) | (velocity << 16)` where status is +`0x90 | channel`. Read-back extracts all three bytes independently. Genuine +`8332944 == 0x7f2690` decodes to channel 0, pitch 38, velocity 127. +It does not encode release velocity. Only note-on messages with explicit +positive duration are supported; CC, note-off and other status semantics are +rejected, never interpreted as notes. `Drumtracker/Track/trackstuff` and +`tempoMap` are unrelated tracker state, not the song MIDI. + +The writer replaces **every** active top-level `SongTrack` record and the +current-track selection with one original track, one clip, common zero start, +requested end/tempo/meter, zero offset and neutral clip transforms. Original +grooves, additional clips/tracks, source MIDI/database paths, humanize/KP +transforms, velocities, loop/playhead settings inside the old song are removed. +`ClearTracksFirst`, `SAMPLER`, mixer, tracker and every unrelated character +remain byte-for-byte identical. No template is written or copied into fixtures. + +The selected score part is independently recompiled and compared to all +compiled note/switch events, including velocities and channels. Pre-roll/tails, +nonzero note-off velocity, switch semantics, mismatched score/event plan, +empty music and unrepresentable timing are errors before output creation. +Explicit request `cc_events` remain valid MIDI; only an otherwise exact drum plan +with valid controller routing returns `sd3_native_controller_not_supported`. +No native controller-triple encoding has been established. This precise reason +permits only the affected drum native to fall back, when allowed, while combined +MIDI retains every controller point. Channel/note/role/release corruption is +checked before this reason and cannot become successful fallback. Disabled +fallback fails before staging; MIDI-only requests require no native preflight. +Quarter-note timing must be an exact finite decimal with at most six fractional +places; no rounding/truncation is performed (e.g. 1/3 and 1/128 are rejected). +Absolute score starts are normalized to the common score-relative zero, not +retained as clip offsets. Key metadata is neutral percussion metadata; pitched +key semantics are not an SD3 drum feature claimed by this codec. + +Only the supplied staged `.sd3p` path is exclusively created (`xb`), flushed, +fsynced, bounded and independently read back. No parent/sibling/publication +directory is created. Existing output/template paths are never overwritten. +Saved validation checks structure, exact note multiset, boundaries, metadata, +all supported neutral controls, absence of extra fields/references/tracks, +and exact non-song bytes against the template. Template hash stability is +checked during writes. Serialization/IO failure may leave the caller-owned +failed staging file; it must not be published as successful. + +## Tests and local evidence + +`tests/fixtures/sd3/original-template.sd3p` and `original-score.json` are newly +authored minimal original fixtures, not stripped private/factory exports. +The template contains original sentinel state and a deliberately replaceable +original source clip; it is a parser fixture, not a playable redistributed kit. +Unit tests cover packing boundaries, corruption, nesting/quoting, multiple +tracks, precise timing, controls, state preservation and exclusive IO. +Integration retains generated originals under `.test-artifacts/native-sd3-evidence-v1`. +Installed-wheel acceptance generates its own minimal original template and +actual `.sd3p` outside the checkout. + +To additionally test an operator-local template, set `RIFF_SD3_TEMPLATE` to its +absolute `.sd3p` path and run: + + .\.venv\Scripts\python.exe -m pytest tests\integration\test_sd3p_files.py -q -s + +The test asserts source inode/size/mtime/hash stability, replaces all source +notes, compares exact non-song bytes and independently validates new original +notes. Local outputs retain private kit state: keep them local and ignored, +never publish them as distributable fixtures. Normal tests need no plugin, +private template, network or application. Full results are in +[report_8_fix.md](../../prompts/report_8_fix.md); actual native service/stdio/ +installed-wheel evidence is in [report_9_fix.md](../../prompts/report_9_fix.md). +Final persisted-wheel/default/alias/CC and genuine read-only generated evidence +is in [CURRENT report_10.md](../../prompts/report_10.md). +Run `tests\integration\test_native_service.py` with the same environment variable +for genuine read-only service acceptance, or without it for portable original fixtures. + +## Remaining readiness gates + +CLI/template configuration, native service registration and target defaults are +implemented and software-verified. Application behavior remains outside this task. +`SyncToHost`, receiver mute/routing and all other non-song operator settings are +preserved; host synchronization may override project tempo during playback. +Actual SD3 open/inspect/play/save/close/reload must verify the saved notes, +tempo/meter, dynamics, selected kit and mapping; Cubase routing/import needs a +separate recorded version/configuration test. Structural native read-back is +not an audible application-compatibility claim. diff --git a/prompts/plan.md b/prompts/plan.md new file mode 100644 index 0000000..5e3d183 --- /dev/null +++ b/prompts/plan.md @@ -0,0 +1,886 @@ +# Riff-Groove-Builder: Architecture and Phased Implementation Plan + +Status: Approved. Executable fixes 7/8 implement real Riffer `.griff`/`.briff` +and SD3 `.sd3p` codecs, original fixtures and independent saved validators. +Step 9 fix wires them into actual MCP/installed-wheel generation, target defaults, +operator-local template configuration and atomic multi-artifact publication. +See CURRENT `report_7_fix.md`, `report_8_fix.md`, `report_9_fix.md`. +Final native/MIDI/CC software, exact persisted wheel and read-only operator +template acceptance are recorded CURRENT-first in `report_10.md`; the earlier +MIDI-only report is preserved there as retracted historical scope. +The original full native/application definition of done is NOT complete: +plugin/SD3 open/play/save/reload, audible checks and Cubase import remain UNRUN. +Native codec/service implementation is no longer absent-evidence BLOCKED. +Earlier step descriptions below retain historical sequencing, not current readiness. + +## Continuation decision: functional MIDI fallback + +### Retraction of interim closure and native-format continuation + +At the earlier MIDI-only Step 10 checkpoint, independent fallback software was verified, +including installed-wheel stdio generation, 1,119 passing tests, lint, formatting, +strict types, dependency checks, and wheel/sdist builds. The final targeted +native investigation is recorded in `report_7_fix.md`; it did not establish an +AGP layout or obtain a usable native fixture. + +The earlier interim closure was an orchestration error, not user approval to +reduce scope. The original native-output requirement remains active. The user +explicitly required continued implementation; native capability checks are not +accepted as native writers. + +Read-only inspection of the standard local vendor folders subsequently found +genuine installed evidence that should have been checked earlier: + +- Ample Metal Eclipse VST3 version 4.0.1; native Riffer guitar `.griff` files. +- Ample Metal Ray5 VST3 version 4.1.0; native Riffer bass `.briff` files. +- Both Riffer containers are XML with `Riff` root, layout `Ver="2.1"` and + `PPQBase="480"`, including actual note, articulation and CC fields. +- Superior Drummer executable version 3.4.4 and genuine text `.sd3p` projects + with `PlugVersion 3.4.4`, `SongTrack`, `MidiLoop` and packed `MidiEvents`. + +The requested `.agp`/`.sdp` suffixes do not match these observed installed native +examples. A focused format-choice question received an unavailable-user response +delegating a pragmatic choice. The compatibility-preserving implementation +decision is to generate the actual `.griff`/`.briff`/`.sd3p` native files and +retain `agp`/`sdp` as request aliases, explicitly documenting this correction. +This preserves all three native targets; it is not another MIDI-only deferral +and does not authorize mislabeled file bytes. No `.strumseq` exporter is added. + +Local native files remain read-only evidence. No factory musical sequence, +licensed manual, plugin binary or private template is copied into source/tests +or uploaded. Tests generate original minimal content. SD3 instrument setup may +use an operator-local template with its song replaced, never a shipped private +project. Native codecs, target maps, service wiring and final validation must +now be implemented and reviewed before full completion is claimed. + +### Current native integration outcome (Step 9 fix, 2026-10-20) + +The native implementation continuation above is executed in software: +all three target subsets are the unambiguous part defaults; standard maps remain +explicitly selectable fallbacks, never relabeled vendor maps. Default requests +produce combined MIDI and actual selected native suffixes. `agp`/`sdp` remain +aliases only. Native-only requests do not force MIDI unless known fallback is +required. Optional operator `--sd3-template` is not a tool-controlled path; +bad supplied templates are errors, absent optional template permits drum-only +fallback while preserving Riffer outputs. Source identity/content is preserved. +Palm mute is reachable for lead/bass, with native PM/PMP and MIDI switch/velocity +semantics; mixed-request drums stay normal with disclosed applicability. +Owned exclusive-create file identities and saved-content hashes cover the complete +multi-file stage before one Windows no-replace directory rename. Partial writes, +validation/model/IO/publication faults never become successful fallback. +Actual stdio and installed-wheel native generation and read-only genuine local +template acceptance use original generated music; private state stays ignored/local. +Report 9 fix records exact checks and remaining application-only limits. +No later prompt, application hosting or commit is part of this fix. + +### Historical fallback execution clarification (superseded by native fixes above) + +The plan was approved and Steps 1-4 accepted. Step 5 mechanics passed, while +real-target mappings and native layouts remained unverified. On the user's +autonomous-continuation instruction, the following execution clarification +supersedes earlier clauses that made every subsequent development step depend +on all vendor maps: + +- Standard MIDI fallback is already in scope. Ship explicitly labeled standard + pitched-note/General MIDI percussion fallback profiles, distinguished from + vendor mappings in public profile metadata and generation warnings. +- Standard fallback data must be sourced from MIDI facts and documented server + policy, not relabeled synthetic fixtures or claims of plugin compatibility. + Unsupported vendor techniques remain explicit errors; never simulate a + keyswitch by guessing a vendor note. +- Step 5 fix can accept standard-fallback production mechanics while retaining + a separately tracked real-target mapping gate. This permits Step 6 text/MIDI + composition and the Step 9 fallback/service path to become operational. +- Implement native capability checks and explicit unavailability when layouts + cannot be established. Missing native evidence is not a completed native + writer, and MIDI fallback is never reported as native generation. +- Steps 7/8 real serialization and Step 10 application acceptance remain gated. + Their blockers must persist in reports and compatibility documentation; they + must not prevent independent fallback functionality from being completed. +- Worker prompts and report reviews still occur one at a time, with fix prompts + for defects. Any skipped/deferred native acceptance is disclosed, not passed. + +Raw official Ample manual-page HTML, unlike the initial simplified extraction, +exposes the public Eclipse/Ray5 main-panel manuals and Riffer/Strummer manuals. +The initial "no usable mapping documentation" finding was incomplete. Their +technical facts may be used with precise source/limitations; no licensed manual +or factory song content is copied into the repository. Access to the manuals +alone does not verify native layouts or the user's installed configuration. + +## 1. Purpose and scope + +Build a Python MCP server that converts text descriptions into coordinated lead, +bass, and drum parts, then generates: + +- `.agp` content for the user's Ample Guitars Eclips lead instrument. +- `.agp` content for the user's Ample Ray bass instrument. +- `.sdp` content for Superior Drummer 3. +- Standard MIDI `.mid` files, both directly requested and as an explicit fallback. + +Use the user's instrument names until exact product names, versions, and import +workflows are verified. Native files are instrument-specific content loaded into +the relevant plugins in Cubase; they are not Cubase `.cpr` project files. +Compatibility must be demonstrated, not inferred from an extension. + +The server uses JSON-RPC over stdio only. No HTTP server, GUI, audio analysis, +audio rendering, plugin hosting, DAW automation, external language-model service, +database, or unrelated musical/export formats are included. + +This document is a design, not a claim that any implementation or compatibility +test already exists. + +## 2. Repository findings and evidence gates + +Initial inspection found an empty Git worktree with `docs`, `prompts`, and `src` +directories, no tracked files, and no existing Python manifest or tests. + +Verified from public documentation: + +- MCP stdio messages are UTF-8 JSON-RPC messages delimited by newlines. + stdout must contain only protocol messages; diagnostics belong on stderr. +- MCP requires initialization and capability/protocol negotiation. +- Mido can write and read Standard MIDI Files, including synchronous type 1 + files, with integer delta times in ticks. +- MIDIUtil can independently construct multi-track MIDI files. + +Not verified: + +- What `.agp` represents in each exact Ample product/version, whether it contains + the required riff/groove data, and whether guitar and bass share a layout. +- What `.sdp` represents in the user's Superior Drummer 3 workflow and whether + it can contain generated song-track MIDI rather than only preset settings. +- Native file layouts, supported versions, templates, checksums, or serialization. +- Exact playable ranges, keyswitch numbers, CC semantics, velocity layers, and + drum maps for the user's instrument versions and presets. + +The Ample manual URL fetched during planning did not yield usable format +documentation. The Toontrack manual page required login. Neither is evidence +that the requested native formats can be generated by writing MIDI with a new +extension. + +### Native-format and profile evidence gate + +Before implementing a native writer, obtain lawfully usable vendor documentation +or user-provided minimal files produced by the installed application: + +1. Exact product/version and the application's export/import operation. +2. Empty, one-note/hit, and multi-note/hit examples. +3. Controlled examples changing tempo, timing, velocity, and articulation. +4. A documented native load/save round trip in the target plugin. +5. Permission to store and redistribute fixtures, or a documented local-only + fixture procedure when redistribution is not permitted. + +Record source, version, observed structure, and unresolved fields. Do not upload +user files, credentials, licensed content, or repository code to third parties. +Do not bypass vendor authentication or copy licensed manuals into the repository. + +Use a documented serializer when possible. A template-based serializer is +acceptable only after its fields, lengths/checksums, version constraints, and +content ownership are understood and round-trip tests prove the output works. +Do not patch arbitrary offsets or silently preserve unexplained musical data. + +If evidence shows the requested extension cannot carry the required content, +report the contradiction and request a decision. Do not substitute another +proprietary format or expand scope without approval. + +Native evidence and MIDI mapping evidence are separate gates: a usable MIDI +articulation map does not establish a native file layout. MIDI-only development +can continue without native layouts, but plugin-specific MIDI compatibility and +articulation claims still require verified instrument mappings. + +## 3. Technology and dependency decisions + +- Python with a proposed minimum of 3.11; verify compatibility with the selected + dependencies during Step 1 before committing the supported-version policy. +- Official Python MCP SDK for stdio transport, lifecycle, protocol validation, + tool registration, and JSON-RPC behavior. Do not write a competing transport. +- Pydantic models and JSON Schema for tool inputs, outputs, musical structures, + and profile validation, aligned with the selected SDK. +- `mido` as the single production MIDI event writer and read-back validator. + It provides explicit control over ticks and event ordering. +- `MIDIUtil` / `python-midiutil` as an independent test-fixture generator for + cross-library MIDI interoperability checks, not a second production writer. +- `pytest`, the MCP SDK's supported asynchronous test approach, Ruff, and one + type checker, configured in `pyproject.toml`. Avoid redundant test/lint tools. +- Standard-library JSON, `fractions.Fraction`, `pathlib`, temporary directories, + and deterministic `random.Random` instances where useful. + +Select and record compatible dependency versions in Step 1. Do not install +dependencies merely to produce this plan. No MIDI device, audio backend, Cubase +installation, or proprietary SDK is required for ordinary unit tests. + +## 4. Proposed directory structure + +Only this plan is created in the architecture phase. The remaining files are +created by their owning worker steps. + +```text +. +|-- pyproject.toml +|-- README.md +|-- .gitignore +|-- src/ +| `-- riff_groove_builder/ +| |-- __init__.py +| |-- __main__.py +| |-- server.py +| |-- schemas.py +| |-- errors.py +| |-- description.py +| |-- compose.py +| |-- profiles.py +| |-- articulations.py +| |-- midi.py +| |-- service.py +| |-- formats/ +| | |-- __init__.py +| | |-- agp.py +| | `-- sdp.py +| `-- data/ +| `-- profiles/ +| |-- eclips..json +| |-- ray..json +| `-- sd3..json +|-- tests/ +| |-- unit/ +| |-- integration/ +| `-- fixtures/ +| |-- descriptions/ +| |-- profiles/ +| |-- midi/ +| `-- native/ +|-- docs/ +| |-- architecture.md +| |-- compatibility.md +| |-- articulation-profiles.md +| `-- formats/ +| |-- agp.md +| `-- sdp.md +`-- prompts/ + |-- plan.md + |-- step_N.md + |-- report_N.md + |-- step_N_fix.md + `-- report_N_fix.md +``` + +Angle-bracket version placeholders above are naming examples, not literal file +names or verified version identifiers. Production profile files are created +only when their data is supported by evidence. Synthetic test profiles remain +under test fixtures and are never advertised as real instrument mappings. + +## 5. Core modules and data flow + +```text +MCP client + -> server: SDK lifecycle, tools/list, tools/call + -> schemas: strict input validation + -> description: text -> normalized musical intent + -> compose: intent -> coordinated logical score + -> profiles + articulations: score -> instrument-specific event plan + -> service: output capability checks and requested-format policy + -> midi / formats.agp / formats.sdp: render into staging directory + -> independent read-back/structural validation + -> service: publish the complete artifact directory + -> server: typed structured result and concise text summary +``` + +| Module | Responsibility | +| --- | --- | +| `__main__.py` | Start the stdio server; accept a required local output-root setting; send startup failures to stderr and exit nonzero. | +| `server.py` | Register exactly the tools below, expose schemas, translate known domain failures to MCP tool errors, and keep stdout protocol-clean. | +| `schemas.py` | Define strict request/result models, normalized intent, logical score, scheduled MIDI events, profile capabilities, and artifact metadata. | +| `errors.py` | Define specific validation, unsupported-description, mapping, native-capability, serialization, and filesystem errors. | +| `description.py` | Resolve supported natural-language terms and explicit overrides; report contradictions, missing capabilities, and meaningful unsupported instructions. | +| `compose.py` | Generate deterministic lead/bass/drum patterns on one shared musical timeline, within verified ranges. | +| `profiles.py` | Load packaged, versioned profile data; validate MIDI ranges, layers, provenance, and native capabilities. | +| `articulations.py` | Compile logical techniques into note, keyswitch, velocity, and CC events with appropriate state/reset behavior. | +| `midi.py` | Convert scheduled absolute events to stable type 1 SMF tracks and validate the saved files with Mido. | +| `formats/agp.py` | Write and validate verified Ample native layouts, with separate target/version handling where required. | +| `formats/sdp.py` | Write and validate the verified Superior Drummer 3 native layout. | +| `service.py` | Coordinate the pipeline, enforce fallback policy, stage files, prevent output collisions, publish artifacts, and return actual results. | + +Keep these as small concrete modules; introduce no generic plugin framework, +queue, database, persistent job system, or arbitrary exporter-discovery layer. +The three fixed output formats need only a small internal capability dispatch. + +## 6. Internal musical representation + +Separate musical intent from MIDI mechanics and native serialization. + +- `MusicalIntent`: resolved description, selected parts, tempo, meter, key/mode, + bar count, supported rhythm/technique terms, and deterministic seed. +- `Score`: one shared tempo, meter, musical start, and end; ordered lead, bass, + and/or drum tracks. +- `LogicalNote`: part, pitch or drum voice, rational start/duration in + quarter-note beats, intensity, and normalized articulation name. +- `EventPlan`: absolute integer ticks, MIDI channel, event type, payload, + event role such as musical note or keyswitch, and stable ordering information. +- `InstrumentProfile`: exact instrument/map version, playable range, channel, + drum voice map if applicable, articulation definitions, evidence metadata, + and independently verified MIDI/native capabilities. + +Use exact rational beat arithmetic until quantization. Proposed resolution is +960 ticks per quarter note. A bar lasts `numerator * 4 / denominator` quarter +notes, not always four beats. Reject unsupported subdivisions rather than +accumulating floating-point drift. + +Do not model keyswitches as ordinary generated musical pitches. Preserve the +logical score as well as the compiled event plan so a native adapter can use +whichever representation its verified format actually requires. + +## 7. MCP contract + +Use the SDK's supported protocol negotiation; the 2025-11-25 specification is +the planning reference, not a license to hard-code an unsupported SDK version. +Advertise tools only, plus mandatory SDK protocol behavior. No sampling, +resources, prompts, HTTP, or remote requests are needed. + +Both tools publish input and output JSON Schemas. Reject unknown input fields, +booleans masquerading as numeric values, non-finite numbers, duplicate list +items, and invalid cross-field combinations. Tool handlers call the same service +functions exercised by integration tests. + +### Tool 1: `list_instrument_profiles` + +Purpose: discover real instrument mappings, supported techniques, and format +availability before generation. + +Parameters: an empty object; no additional properties. + +Return type: + +```text +ProfileListResult { + profiles: ProfileSummary[] +} + +ProfileSummary { + id: string, + part: "lead" | "bass" | "drums", + instrument: "eclips" | "ray" | "sd3", + product_name: string, + product_version: string, + mapping_version: string, + midi_available: boolean, + native_format: "agp" | "sdp", + native_available: boolean, + supported_articulations: string[], + limitations: string[] +} +``` + +An empty registry is returned honestly as an empty list. Unavailable capabilities +may be listed with explicit limitations; synthetic fixtures are excluded. +No absolute private fixture paths or licensed manual contents are exposed. + +### Tool 2: `generate_music` + +Purpose: create coordinated musical content from a description and export the +requested native files and/or MIDI. + +| Parameter | Type | Required/default | Meaning | +| --- | --- | --- | --- | +| `description` | string, 1-4000 nonblank characters | Required | Natural-language musical request within the documented supported vocabulary. | +| `basename` | string matching `[A-Za-z0-9][A-Za-z0-9_-]{0,63}` | Required | Safe artifact-directory/file stem; Windows reserved names are also rejected. | +| `parts` | unique nonempty array of `lead`, `bass`, `drums` | Optional | If absent, infer explicit part-selection language; otherwise default to all three and report that assumption. | +| `formats` | unique nonempty array of `mid`, `agp`, `sdp` | Optional | If absent, request MIDI and the native format relevant to each selected part. | +| `tempo_bpm` | finite number, 20-300 | Optional | Explicit tempo override. | +| `bars` | integer, 1-256 | Optional | Explicit length override. | +| `time_signature` | object `{numerator: integer 1-16, denominator: 1|2|4|8|16}` | Optional | Explicit meter override. | +| `key` | string from documented pitch-class plus `major`/`minor` grammar | Optional | Explicit tonality override. | +| `profiles` | object with optional `lead`, `bass`, `drums` profile-ID strings | Optional | Select verified versions; entries must refer to selected parts. | +| `seed` | integer, 0-2147483647 | Default `0` | Local deterministic variation; never use global random state. | +| `allow_midi_fallback` | boolean | Default `true` | Permit explicitly reported MIDI substitution for unavailable requested native capabilities. | + +The limits are proposed bounded-generation defaults, subject to plan review. +Also enforce a documented generated-event budget, initially 100,000 events, +before serialization. These are resource safeguards, not extra musical features. + +Rules: + +- Explicit structured overrides win over text and are disclosed in the result. + Contradictory text without an override is an error with actionable details. +- Unspecified musical defaults are 120 BPM, four bars, 4/4, and E minor; return + the assumptions. Do not invent unrequested song sections or tempo changes. +- Eclips is lead, Ray is bass, SD3 is drums. Select a default profile only when + the registry declares an unambiguous verified default; otherwise return a + profile-selection error identifying the available choices. +- Explicit `agp` requires at least one selected lead/bass part; explicit `sdp` + requires drums. Apply a format only to its relevant selected parts. +- One combined `.mid` contains every selected part when MIDI is requested. +- An allowed native fallback also emits one combined `.mid` containing all + selected parts, even if `mid` was not explicitly listed. Explain which native + targets it substitutes for. Emit it only once. +- Unknown or unverifiable plugin mappings are not repaired by guessed MIDI + events. MIDI fallback for a target requires a verified map for the requested + notes/techniques; otherwise fail explicitly. + +Success return type: + +```text +GenerationResult { + status: "complete" | "midi_fallback", + resolved: { + parts: ("lead" | "bass" | "drums")[], + tempo_bpm: number, + bars: integer, + time_signature: {numerator: integer, denominator: integer}, + key: string, + seed: integer, + profile_ids: object, + assumptions: string[], + overrides: string[], + musical_start_tick: integer, + musical_end_tick: integer, + ticks_per_quarter: integer + }, + artifacts: [{ + format: "mid" | "agp" | "sdp", + parts: ("lead" | "bass" | "drums")[], + path: string, + size_bytes: integer, + profile_ids: string[], + fallback_for: ("lead" | "bass" | "drums")[] + }], + warnings: [{code: string, part: string | null, message: string}] +} +``` + +`path` is the resolved absolute local path to an actually published file, not +encoded file bytes. No MCP resource endpoint or on-disk sidecar is introduced. +Native artifacts each identify one part; the MIDI artifact identifies all its +included tracks. `complete` means every requested applicable output was made. +`midi_fallback` means native output was unavailable and an allowed substitution +was made; it must include explicit warnings, not success-shaped silence. + +Use MCP `structuredContent` with a concise text content summary for successful +results. For domain failures, return `isError: true` and a structured +`GenerationError {code, message, details}` branch declared in the tool's output +schema, subject to the selected SDK's schema facilities. Protocol-level malformed +requests remain SDK JSON-RPC errors; do not mislabel every error as a parse error. + +Expected error codes include `INVALID_REQUEST`, `UNSUPPORTED_DESCRIPTION`, +`PROFILE_REQUIRED`, `UNSUPPORTED_ARTICULATION`, `NATIVE_FORMAT_UNAVAILABLE`, +`OUTPUT_EXISTS`, `OUTPUT_IO_ERROR`, and `SERIALIZATION_ERROR`. + +## 8. Text interpretation and composition strategy + +Start with a documented, deterministic local vocabulary rather than adding a +model provider. Support explicit note/key names, tempo, meter, bar length, +part selection, note subdivisions, rests, and verified articulation aliases. +Small rhythm templates implement riff, lead, bass groove, and drum-pattern +requests; each template shares the same grid and key. + +Translate supported qualitative terms through documented rules, such as a +specific tempo for "slow" when no numeric tempo is provided. Freeze those rules +in tests. Descriptive filler may be ignored, but materially unsupported musical +instructions must produce an actionable error, not an unrelated generic loop. +Support more text vocabulary only when necessary for this scoped generation. + +Lead and bass use the resolved key and verified playable ranges. Drums use the +selected SD3 map, never an assumed General MIDI map disguised as an SD3 map. +Requested lead/bass/drum parts align over exactly the resolved bar count. +Any optional variation is seeded, bounded, and cannot move notes outside the +range, timeline, or supported articulation semantics. + +## 9. Articulation mapping and event scheduling + +Profiles are declarative, versioned JSON data validated at load time. For each +articulation store the applicable combination of: + +- Canonical name and supported text aliases. +- Keyswitch note number, velocity, gate length, lead time, and channel. +- Whether switching is latched or momentary, and required reset/release actions. +- CC number/value actions, their channel and timing, and any reset value. +- Verified velocity-layer ranges and intensity-to-layer behavior. +- Playable note range or percussion voice mapping and overlap restrictions. +- Source/version provenance and limitations. + +For example, text "palm mute" normalizes to `palm_mute`. The selected verified +Eclips or Ray profile supplies the actual keyswitch/CC/layer values; the compiler +emits those controls before the associated musical note and releases/resets +them according to the profile. This plan intentionally specifies no unverified +vendor note number. Tests may use clearly labeled synthetic values. + +MIDI numbers are authoritative; octave labels alone are insufficient because +applications label octaves differently. Musical note-on velocity is 1-127; +controller values and note-off velocities are 0-127. Layer boundaries must be +valid, non-overlapping, and tested at both ends. Never silently clamp an invalid +profile or intensity into a plausible output. + +The scheduler must: + +1. Resolve profile state independently per part/channel; lead, bass, and drums + use separate channels, with the drum channel documented by its profile. +2. Emit selection controls only when needed, unless a momentary technique + requires per-note triggers. +3. Reject overlapping notes requiring incompatible latched articulations on + the same channel unless the verified profile supplies a supported mechanism. +4. Never emit negative ticks. For required pre-note lead time at song start, + calculate one common pre-roll for all parts and all applicable native + adapters. Report the musical-start tick; never independently shift one part. + If a native format cannot preserve that relationship, mark that native + capability unavailable rather than misaligning outputs. +5. Apply profile lead times explicitly. At equal ticks, finish applicable + releases/note-offs, then selection/reset controls as dictated by state + transitions, then note-ons; use stable tie-breaking. Do not let a generic + sort undo a profile's required causal ordering. +6. Pair every musical note and keyswitch note with a release, handle repeated + same-pitch notes, and restore momentary CC/keyswitch state appropriately. +7. Preserve control events in the same part track as affected notes so a + single Cubase part import does not lose its switches. + +Standard MIDI fallback retains the verified target's articulation events. +It does not guarantee that arbitrary General MIDI synthesizers will reproduce +plugin articulations. + +## 10. File generation and publication + +### Standard MIDI + +- Produce synchronous SMF type 1 with a conductor track plus selected part + tracks, shared resolution, tempo, time signature, and meaningful track names. +- Quantize exact beat positions to the documented tick grid, stable-sort + absolute events, and convert to nonnegative integer delta times once. +- Include valid end-of-track events at the shared end boundary, accounting for + pre-roll and necessary control releases. Distinguish musical end from any + documented release tail. +- Mido reads each saved file back. Validate header/type, track layout, timing, + channels, tempo/meter, note pairing, CC payloads, and expected duration. +- Use MIDIUtil-generated reference files in tests to compare normalized musical + events. Do not require byte equality across libraries. + +### Ample `.agp` + +- Lead and bass get separate artifacts, normally `_lead.agp` and + `_bass.agp`. +- Support only layouts/versions established by the native evidence gate. +- Determine whether the native format stores notes, patterns, articulation + identifiers, MIDI events, preset state, or references. Serialize the correct + representation; do not assume it is a MIDI container. +- Reuse shared score/event structures, but share guitar/bass serialization only + if evidence proves compatibility. +- Validate structure and supported round trips automatically. Require an actual + Eclips/Ray import test before claiming each instrument/version compatible. + +### Superior Drummer 3 `.sdp` + +- Normally emit `_drums.sdp`. +- Verify whether the extension supports the generated groove/song data. + Preset-only support does not satisfy a drum-song writer. +- Preserve the selected verified drum map, event timing, velocity, and supported + articulation controls in the representation the real format requires. +- Validate structure/round trips and require a real SD3 import test before a + compatibility claim. + +### Fallback and filesystem behavior + +Check known native capabilities before writing. If a requested native capability +is unavailable and fallback is allowed, retain available requested native outputs +and emit the combined MIDI plus explicit `NATIVE_FORMAT_UNAVAILABLE` warnings. +If fallback is disabled, fail without publishing any files. + +Fallback applies only to known capability limitations. Unexpected serialization +errors, corrupt templates, invalid profiles, permission errors, and disk errors +must fail visibly; do not hide them by returning a MIDI-only success. + +The startup output root is local and configured by the operator. Tool requests +cannot supply arbitrary output paths. Resolve and validate it, reject unsafe +basenames and Windows reserved names, and prevent path traversal or escaping +through links/reparse points. + +Stage the complete validated artifact set in a unique directory under that root. +Publish it as `/` with a same-volume directory rename, +rejecting any existing destination rather than overwriting. A competing request +for the same basename must fail explicitly; do not overwrite or merge directories. +Return paths only after publication succeeds. On failure, clean up only this +request's temporary files. Keep all behavior testable with temporary directories. + +No manifests, project databases, audio files, or extra output formats are needed. + +## 11. Testing and compatibility strategy + +### Unit tests + +- Strict schemas: valid bounds, invalid numeric types/values, unknown fields, + conflicting parts/formats/profiles, and safe basenames. +- Text parsing: supported phrases, aliases, structured override precedence, + defaults, contradictions, and materially unsupported requests. +- Musical generation: exact bar lengths in different meters, aligned parts, + key/range constraints, deterministic seeds, and event-budget rejection. +- Profiles: provenance/capability fields, corrupt JSON, MIDI ranges, layer + boundaries, drum maps, and exclusion of synthetic production mappings. +- Articulations: keyswitch ordering/lead times, latching, momentary release, + CC reset, velocity layers, channel isolation, retriggers, and incompatible + overlapping articulations. +- MIDI: integer nonnegative deltas, note pairing, conductor data, pre-roll, + shared endings, and deterministic semantic output. +- Native adapters: verified structure/version behavior, known fixtures, + corrupted/truncated inputs, and explicit capability failures. +- Service: fallback enabled/disabled, honest warnings/status, no false native + artifacts, no publication after failure, and output-collision handling. + +### Automated integration tests + +- Description -> score -> mapped MIDI -> disk -> Mido read-back. +- MIDIUtil reference file -> Mido normalization, compared with production + output for the same controlled musical events. +- Request native and MIDI together; verify output names, actual signatures, + artifact metadata, exact musical events, and fallback policy. +- Use real verified native fixtures/validators when available; fake adapters + may test service plumbing but never establish native compatibility. +- Launch the installed Python module as a subprocess and exercise initialize, + initialized notification, tools/list, and tools/call over real stdio. +- Check parse/invalid-parameter/unknown-method handling supported by the SDK, + request-ID preservation, notification behavior, protocol-clean stdout, and + clean EOF shutdown. Do not invent a JSON-RPC `shutdown` method. +- Run from a different working directory and from the built distribution to + prove packaged profiles and imports work outside the repository. +- Check temporary-root confinement, unsafe paths, same-name collisions, + permission/serialization failures, and cleanup without deleting other files. + +### Manual application acceptance + +Keep a versioned matrix in `docs/compatibility.md` covering: + +1. Import the MIDI into Cubase; confirm tempo/meter, track alignment, duration, + instrument routing, switches/CC, and usable musical content. +2. Load lead `.agp` into the exact Eclips version and bass `.agp` into Ray; + verify notes, timing, velocity, articulation, and subsequent save/reload. +3. Load `.sdp` into the exact SD3 version and verify drum song/groove content, + mapping, timing, dynamics, and save/reload. +4. Confirm native and MIDI variants represent the same requested musical parts. +5. Record application versions, fixture identifiers, expected/observed results, + and limitations without publishing licensed user data. + +Pure-Python CI cannot replace these application checks. A missing application +or private fixture is a named blocker, not a passed test. Separate public tests +from private compatibility tests and disclose any skips in every report. + +Use targeted tests during development, plus the complete suite, configured +lint/type checks, and package-build checks at final acceptance. No benchmarks, +coverage threshold, or unrelated CI platform is required by this scope. + +## 12. Phased worker sequence + +Every row becomes exactly one detailed worker prompt only when its turn is +approved. File lists identify the main owned surfaces; each prompt will specify +the exact test files and documentation changes after inspecting prior work. +Later workers reuse reviewed contracts rather than replacing working modules. + +### Step 1: Foundation and compatibility evidence inventory + +- Objective: establish packaging, test/lint/type commands, the package skeleton, + and an honest product/format/profile evidence inventory. +- Files: `pyproject.toml`, `.gitignore`, `README.md`, package `__init__.py`, + initial test scaffold, `docs/architecture.md`, `docs/compatibility.md`, + `docs/formats/agp.md`, and `docs/formats/sdp.md`. +- Implementation: select supported dependencies/Python policy, establish `src` + layout, record lawful fixture sources and exact instrument/version questions, + and document native/mapping gates without inventing implementations. +- Unit tests: package import/version smoke tests. +- Integration tests: build/install into a test environment and import from + outside the repository; run the configured checks. +- Acceptance: reproducible foundation and explicit evidence/blocker inventory. + An inventory can be complete while native evidence remains unresolved; + that does not certify a writer or permit bypassing its later gate. + +### Step 2: Typed domain models and MCP tool contracts + +- Depends on: Step 1. +- Files: `schemas.py`, `errors.py`, schema/domain tests, related contract docs. +- Implementation: strict request/result models, profile summaries, musical + intent/score/event models, validation rules, errors, and JSON Schemas. +- Unit tests: parameter bounds, default resolution boundaries, unknown fields, + incompatible combinations, event validity, and result/error schemas. +- Integration tests: representative requests/results round-trip through models + and published schemas, including all parts and formats. +- Acceptance: one authoritative typed contract with no duplicated validation. + +### Step 3: MCP stdio server skeleton + +- Depends on: Steps 1 and 2. +- Files: `server.py`, `__main__.py`, package entry point configuration, + protocol integration tests, startup usage documentation. +- Implementation: SDK stdio lifecycle, two tool registrations, output-root + configuration, stderr logging, and explicit unfinished-service errors. + Temporary unfinished errors are development-only and removed in Step 9. +- Unit tests: handler argument/result/error translation and root validation. +- Integration tests: real subprocess initialization, listing tools/schemas, + notification behavior, malformed requests, stdout cleanliness, and EOF. +- Acceptance: valid MCP skeleton; unfinished generation never claims success. + +### Step 4: MIDI timing, scheduling, and file writer + +- Depends on: Step 2. +- Files: `midi.py`, event-model refinements if needed, MIDI unit/integration + tests, lawful MIDI fixtures, timing documentation. +- Implementation: exact timeline math, deterministic event ordering, SMF type 1 + writing, conductor/part tracks, and post-write validation. +- Unit tests: multiple meters, boundaries, repeated pitches, channels, event + ordering, pre-roll, release tails, note pairing, and invalid event rejection. +- Integration tests: multi-part files read back with Mido and independently + generated MIDIUtil reference-event comparisons. +- Acceptance: valid deterministic MIDI from explicit controlled event plans; + no unverified instrument-specific claims. + +### Step 5: Instrument profiles and articulation compiler + +- Depends on: Steps 2 and 4; verified mapping evidence for production targets. +- Files: `profiles.py`, `articulations.py`, verified profile JSON files, + synthetic profile fixtures, profile/compiler tests, + `docs/articulation-profiles.md`. +- Implementation: versioned mappings, real playable/drum ranges, keyswitch/CC + actions, layer selection, state transitions, and overlap restrictions. +- Unit tests: layer boundaries, aliases, latched/momentary switches, resets, + profile rejection, and channel/state isolation. +- Integration tests: logical palm-muted lead/bass and articulated drums compiled + to MIDI; assert exact events using documented profile values. +- Acceptance: real mappings have evidence. Synthetic tests can prove compiler + mechanics but cannot close a missing production-profile gate. + +### Step 6: Text interpretation and coordinated composition + +- Depends on: Steps 2, 4, and 5. +- Files: `description.py`, `compose.py`, description fixtures, parser/composer + unit tests, full text-to-MIDI integration tests, supported-text usage docs. +- Implementation: supported vocabulary, defaults/overrides, seeded bounded + patterns, aligned parts, key/range validation, and event-budget enforcement. +- Unit tests: parsing contradictions/unknown instructions, exact meter/bar + lengths, seed reproducibility, range compliance, and articulation selection. +- Integration tests: representative descriptions covering lead-only, + bass-only, drums-only, and combined parts, verified after MIDI read-back. +- Acceptance: genuinely text-driven content; no silent unrelated default loop. + +### Step 7: Verified Ample `.agp` generation + +- Depends on: Steps 4-6 and the Ample native evidence gate. +- Files: `formats/__init__.py`, `formats/agp.py`, lawful native fixtures, + Ample unit/integration tests, `docs/formats/agp.md`, compatibility matrix. +- Implementation: supported layout/version serialization for Eclips and Ray; + preserve exact rhythm, dynamics, and required articulation semantics. +- Unit tests: native fields, version checks, invalid data, fixture round trips, + and distinct guitar/bass behavior where necessary. +- Integration tests: generated native files structurally validated against + evidence; actual Eclips/Ray import and save/reload recorded separately. +- Acceptance: both targets verified. An unavailable adapter or renamed MIDI is + not completion. If blocked, issue an evidence/fix prompt and seek the needed + files/decision rather than pretending this step passed. + +### Step 8: Verified Superior Drummer 3 `.sdp` generation + +- Depends on: Steps 4-6 and the SD3 native evidence gate. +- Files: `formats/sdp.py`, lawful SD3 fixtures, SD3 unit/integration tests, + `docs/formats/sdp.md`, compatibility matrix. +- Implementation: the confirmed SD3 container/content representation with + generated drum events, mapping, timing, and dynamics. +- Unit tests: supported fields/versions, corrupt/truncated data, fixture + round trips, and mapping/articulation preservation. +- Integration tests: structural validation plus real SD3 import/save/reload. +- Acceptance: actual drum content loads correctly; a preset-only file or + metadata stub does not satisfy the requested generation. + +### Step 9: Generation service, fallback, and complete MCP wiring + +- Depends on: Steps 3-8. +- Files: `service.py`, `server.py`, result/error integration, service and + end-to-end stdio tests, final output/fallback usage documentation. +- Implementation: connect the full pipeline, profiles tool, capability policy, + all requested artifacts, atomic publication, structured results, and explicit + operational failures. Remove development-only unfinished handlers. +- Unit tests: output planning, fallback policy, error translation, safe names, + collision handling, and exact artifact/result metadata. +- Integration tests: real stdio generation in all formats; injected unavailable + capabilities with fallback on/off; serialization/IO failures; no partial + publication; concurrent same-basename requests. +- Acceptance: externally usable tools with honest results and no silent failures. + +### Step 10: Compatibility acceptance and release readiness + +- Depends on: Steps 1-9. +- Files: end-to-end/regression tests, packaging metadata as needed, `README.md`, + architecture/format/profile docs, and compatibility matrix. +- Implementation: close task-caused defects, verify installed distribution + behavior, and document MCP client configuration and Cubase/plugin imports. + Do not add unrelated capabilities during final hardening. +- Unit tests: complete suite with regressions for any fixes. +- Integration tests: installed-package stdio workflow, representative combined + exports, validated native fixtures, and final application acceptance matrix. +- Acceptance: configured lint/type checks, build, full automated suite, and + required manual compatibility evidence pass; all skips/blockers disclosed. + +Although some dependencies are technically independent, execution is deliberately +one worker prompt at a time in the listed order. If a blocker requires reordering +independent work, the orchestrator must first record the proposed adjustment and +obtain review; it must not silently skip a failed or unreviewed step. + +## 13. Worker prompt and report protocol + +After this plan is reviewed: + +1. Create only `prompts/step_1.md`; do not generate the later prompts in bulk. +2. Each prompt contains the objective, prerequisites/evidence gates, exact + files, implementation constraints, unit tests, integration tests, validation + commands, and measurable acceptance criteria. +3. Include this exact instruction, substituting the current step number for N: + + > 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 + +4. Also require changed-file summaries, exact commands and outcomes, skipped + tests with reasons, compatibility evidence where relevant, and unresolved + blockers. Require the entire report inside one plain triple-backtick fence, + with no content outside it. +5. Hand off that prompt and wait. Do not implement the worker's task in parallel + or assume that creating a prompt means its task is complete. +6. Read `prompts/report_N.md`, inspect relevant implementation/evidence, and + evaluate acceptance critically. A report alone is not proof: run focused + checks where needed; native claims require real application evidence. +7. If defects, failed tests, undisclosed skips, or blockers remain, create + `prompts/step_N_fix.md` instead of the next step. Require + `prompts/report_N_fix.md`; read and evaluate it before advancing. If further + corrections are needed, revise the fix prompt and require a fresh report, + preserving prior outcomes in the report's history. +8. Ask for missing user-owned evidence or decisions when a blocker cannot be + resolved locally. Do not manufacture fixtures, maps, or passing results. +9. Create `prompts/step_(N+1).md` only after the current step is accepted. + +Historical planning decision: no worker was launched and no first worker prompt +was created during the initial architecture-only request. User approval and the +continuation decision above subsequently authorized implementation; the initial +awaiting-review state is no longer current. Prior step reports remain historical. + +## 14. Final definition of done + +- A packaged Python server implements the reviewed MCP stdio contracts. +- Supported text descriptions generate aligned lead, bass, and drum content. +- Verified keyswitch, velocity-layer, and CC behavior survives export. +- Standard MIDI files validate and import into Cubase. +- Actual `.griff` / `.briff` files load into Eclipse 4.0.1 / Ray5 4.1.0; + `agp` is retained as a request alias, not a mislabeled file suffix. +- Actual `.sd3p` files load the generated drum content into SD3 3.4.4/SL-DFH; + `sdp` remains a request alias. Software serialization is verified, while + application load/play/save/reload remains UNRUN. +- Native fallback is explicit, test-covered, and never masks data/IO failures. +- No false file extensions, fabricated mappings, partial published requests, + protocol-noisy stdout, or unreported compatibility gaps remain. +- Tests, packaging checks, documentation, and required application evidence are + complete. MIDI-only support is useful interim progress, not completion of the + full requested scope. + +## 15. Planning references + +Public documentation consulted during architecture planning: + +- [MCP stdio transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports) +- [MCP lifecycle](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle) +- [MCP tools and schemas](https://modelcontextprotocol.io/specification/2025-11-25/server/tools) +- [Mido Standard MIDI Files](https://mido.readthedocs.io/en/stable/files/midi.html) +- [MIDIUtil documentation](https://midiutil.readthedocs.io/en/1.2.1/) +- [Ample manual entry point](https://www.amplesound.net/en/manual.asp): + attempted; no usable format specification obtained. +- [Superior Drummer 3 manual entry point](https://www.toontrack.com/manual/superior-drummer-3/): + login required; no native layout verified. + +Vendor references above identify evidence still needed; they do not establish +that `.agp` or `.sdp` serialization has been verified. diff --git a/prompts/report_1.md b/prompts/report_1.md new file mode 100644 index 0000000..eb0d439 --- /dev/null +++ b/prompts/report_1.md @@ -0,0 +1,212 @@ +``` +Step 1 report — foundation and compatibility evidence inventory +Date: 2026-10-19 +Result: PASS for Step 1. Ready for Step 2 review/authorization only. + +IMPLEMENTATION AND OWNERSHIP + +Created exactly these requested files: +- pyproject.toml +- .gitignore +- README.md +- src\riff_groove_builder\__init__.py +- tests\unit\test_package.py +- tests\integration\test_distribution.py +- docs\architecture.md +- docs\compatibility.md +- docs\formats\agp.md +- docs\formats\sdp.md +- prompts\report_1.md + +No additional support source files were needed. The approved prompts\plan.md +and the pre-existing untracked prompts\step_1.md were preserved. No commits, +later prompts, server, generator, native writer, or fabricated profiles/fixtures +were added. + +Setuptools builds a src-layout package named +gaj3t-musicgen-riff-groove-builder, importable as riff_groove_builder. +The sole authored version is __version__ = "0.1.0" in the initializer; +distribution metadata derives from it. Import has no dependency imports, +stdout/stderr output, or service startup. Future data\profiles\*.json package +data is configured without inventing any files. + +Pytest discovers both test directories; Ruff and strict mypy cover source/tests. +AnyIO's bundled pytest plugin and explicit asyncio backend selection match the +maintained official MCP SDK testing approach. No redundant async plugin added. + +ENVIRONMENT AND EXACT VERSIONS + +OS: Windows; CPython AMD64. +Base interpreter: +C:\Users\g3\AppData\Local\Programs\Python\Python313\python.exe +Exact interpreter: +3.13.13 (tags/v3.13.13:01104ce, Apr 7 2026, 19:25:48) +[MSC v.1944 64 bit (AMD64)] +Development executable: +D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder\.venv\Scripts\python.exe +Verified sys.prefix != sys.base_prefix: True. + +Declared/tested direct runtime dependencies: +- mcp 1.30.0 +- pydantic 2.14.1 +- mido 1.3.3 + +Declared/tested development/build dependencies: +- MIDIUtil 1.2.1 +- pytest 9.1.1 +- anyio 4.15.1 +- ruff 0.17.1 +- mypy 2.4.0 +- build 1.6.1 +- setuptools 84.2.0 +- wheel 0.48.0 +- packaging 26.3 +Development pip: 26.0.1. + +Other installed dependencies, from the tested environment: +annotated-types 0.8.0; ast_serialize 0.13.1; attrs 26.1.0; +certifi 2026.10.18; cffi 2.1.1; click 8.5.0; colorama 0.4.6; +cryptography 50.0.2; h11 0.16.0; httpcore 1.0.9; httpx 0.28.1; +httpx-sse 0.4.3; idna 3.20; iniconfig 2.3.1; jsonschema 4.26.0; +jsonschema-specifications 2025.9.1; librt 0.16.0; mypy_extensions 1.1.0; +pathspec 1.1.1; pluggy 1.7.0; pycparser 3.11; pydantic_core 2.50.1; +pydantic-settings 2.16.0; Pygments 2.21.0; PyJWT 2.15.1; +pyproject_hooks 1.3.3; python-dotenv 1.2.4; python-multipart 0.0.32; +pywin32 312; referencing 0.37.0; rpds-py 2026.9.1; +sse-starlette 3.5.0; starlette 1.9.0; typing_extensions 4.16.0; +typing-inspection 0.4.4; uvicorn 0.54.0. +These SDK/tool transitive dependencies do not constitute an HTTP application. + +Selected direct releases and Python requirements were checked using public +PyPI metadata. The declared >=3.11 policy is allowed by those dependencies; +only 3.13.13 was executed. No claim of testing 3.11, 3.12, another OS, or every +version allowed by the bounded ranges is made. The maintained MCP 1.x line was +chosen deliberately; published 2.x availability does not certify its API here. +Dependency resolution and import smoke checks are not exhaustive SDK testing. + +SETUP AND EXACT VALIDATION COMMANDS + +All commands ran from the repository root, using PowerShell. +Setup, after writing the dependency manifest: + +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +& 'C:\Users\g3\AppData\Local\Programs\Python\Python313\python.exe' -m venv .venv +& '.\.venv\Scripts\python.exe' -m pip install --disable-pip-version-check --no-cache-dir -e '.[dev]' + +PASS: local venv created; complete runtime/dev dependency installation resolved. +No global/other-user environment was installed into or modified. + +Preferred editor test tool was attempted with both absolute test-file paths; +it returned "No tests found in the files." This is a discovery limitation, +not a passed test. The required project pytest fallback was then used: + +& '.\.venv\Scripts\python.exe' -m pytest tests\unit tests\integration -q -s +PASS: 6 passed in 6.75s; 0 failed, 0 skipped, no warnings. +Breakdown: 4 unit tests; 2 integration tests. + +Repeatability check with index access explicitly disabled: +$env:PIP_NO_INDEX = '1' +& '.\.venv\Scripts\python.exe' -m pytest -q -s +PASS: 6 passed in 6.05s; 0 failed, 0 skipped, no warnings. + +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: "All checks passed!" +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: "10 files already formatted" +& '.\.venv\Scripts\python.exe' -m mypy +PASS: "Success: no issues found in 3 source files" +& '.\.venv\Scripts\python.exe' -m pip check +PASS: "No broken requirements found." + +Additional actual smoke invocation: +& '.\.venv\Scripts\python.exe' -c "import importlib.metadata as m; import sys; import mcp, pydantic, mido, midiutil, anyio; from pathlib import Path; print('Executable:', sys.executable); print('Version:', sys.version); print('Isolated venv:', sys.prefix != sys.base_prefix); print('Runtime/dev imports: mcp, pydantic, mido, midiutil, anyio OK'); print('Remaining distribution workspaces:', list(Path('.test-artifacts').glob('distribution-*'))); print('Declared package dependencies:'); print('\n'.join(m.requires('gaj3t-musicgen-riff-groove-builder') or []))" +PASS: all five imports succeeded, metadata included every declared dependency, +isolated venv True, remaining distribution workspaces []. + +Offline repeat installation/build, with scratch variables set as above: +$env:PIP_NO_INDEX = '1' +& '.\.venv\Scripts\python.exe' -m pip install --quiet --disable-pip-version-check --no-cache-dir --no-build-isolation -e '.[dev]' +& '.\.venv\Scripts\python.exe' -m build --no-isolation +PASS: editable reinstall succeeded without an index. +PASS: "Successfully built gaj3t_musicgen_riff_groove_builder-0.1.0.tar.gz +and gaj3t_musicgen_riff_groove_builder-0.1.0-py3-none-any.whl" +No build warnings or errors were reported. +Default build produced the wheel from the built sdist. + +Persisted, ignored build products: +- dist\gaj3t_musicgen_riff_groove_builder-0.1.0-py3-none-any.whl + 3,884 bytes; SHA256: + 9D82CE1FFD886C74176E83822B7352976FF4506D2BD4C05318EF4BB804F03403 +- dist\gaj3t_musicgen_riff_groove_builder-0.1.0.tar.gz + 4,146 bytes; SHA256: + 95AF2713E2DEC8ACC562BD3677EC8591F056D006DB2F01E99B6345CF9F3C2B8E +Hashes identify this run; reproducible byte-for-byte archives are not claimed. + +git --no-pager diff --check +PASS: no whitespace errors in tracked diffs; new Python files separately +passed Ruff. Editor diagnostics reported no errors for the queried files. +git status confirmed only requested new surfaces plus existing step_1.md. +Ignore checks confirmed venv, scratch, distributions and test/lint/type caches +are ignored, while source, prompts and evidence docs remain visible. + +INDEPENDENT WHEEL EVIDENCE + +Each integration run creates a unique .test-artifacts\distribution- +workspace, builds offline with --no-isolation, creates a separate wheel venv, +and installs the wheel using --no-index --no-deps --no-cache-dir. Python +subprocesses use -I -B; PYTHONPATH/PYTHONHOME are removed. Scratch remains +repository-local. Test workspaces/venvs are removed in fixture cleanup. + +Final actual import probe: +cwd = D:\_Repos\Code\GAJ3T\MCPs\MusicGen +isolated = 1 +version = metadata_version = 0.1.0 +prefix = +D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder\.test-artifacts\distribution-6020968823604f81b75e0653d1288c9a\wheel-venv +module_path = +D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder\.test-artifacts\distribution-6020968823604f81b75e0653d1288c9a\wheel-venv\Lib\site-packages\riff_groove_builder\__init__.py + +The working directory was outside the repository; module_path matched the +installed distribution file, was inside the independent venv, and was not +inside src. Import was silent and did not import mcp/server. Archive checks +found the package in wheel and sdist and no environment/scratch content. +The import-only --no-deps test proves layout/import safety, not full runtime +dependency certification. The ordinary development venv installed all declared +dependencies and independently passed pip check and runtime/dev import smoke. + +ISSUES, UNRUN CHECKS AND EVIDENCE GATES + +No unresolved Step 1 implementation failures; no automated test skips. +Editor test discovery required the documented pytest CLI fallback. +Only CPython 3.13.13/Windows was tested; other versions/platforms are unrun. + +Official public vendor checks yielded no usable native-format specification: +- Ample manual entry point returned only a domain label. +- Toontrack SD3 manual entry point required login; none was attempted. + +Exact Eclips/Ray product names/editions and all target installed versions, +SD3 library/preset/map, MIDI ranges/channels/keyswitches/CCs/velocity layers, +both native layouts/content semantics, lawful controlled fixtures, permission +to redistribute, and actual Cubase/plugin load/save/reload remain unresolved. +Application checks were not performed or represented as automated skips. +No private evidence was uploaded, no authentication bypassed, and no licensed +manual or native fixture copied. + +The compatibility matrix has separate MIDI, native-layout, automated-check, +and application-acceptance columns. Format docs request exact versions/workflows, +lawful empty/one-note/multi-note examples, controlled tempo/timing/velocity/ +articulation changes, and real acceptance. Renamed MIDI is not AGP/SDP support; +a preset-only container may not satisfy musical-content requirements. +Inventory completion does not close these later production/native gates. + +READINESS + +Step 1 acceptance is met: package, isolated installed wheel, reproducible +validation commands, passing tests/lint/types/build, and truthful evidence +inventory are persistent. Ready for the orchestrator to review and authorize +Step 2 typed contracts. This is not full-project readiness or authorization +to claim native/mapping compatibility. No later step was started. +``` diff --git a/prompts/report_10.md b/prompts/report_10.md new file mode 100644 index 0000000..a88a01f --- /dev/null +++ b/prompts/report_10.md @@ -0,0 +1,621 @@ +``` +CURRENT — STEP 10 FINAL REAL NATIVE/MIDI SOFTWARE ACCEPTANCE +Date: 2026-10-20 +Executed: prompts\step_10_fix.md + +RESULT / CERTIFICATION BOUNDARY + +PASS: implemented Eclipse 4.0.1 Riffer XML 2.1 .griff, Ray5 4.1.0 .briff, +SD3 3.4.4/SL-DFH template-song .sd3p and Standard MIDI software subset. +PASS: full suite, lint/format, strict types, pip consistency, final wheel/sdist, +EXACT persisted final wheel real-stdio generation outside the checkout, +independent saved-byte music checks and genuine READ-ONLY local-template run. +Native serialization is implemented, not a renamed-MIDI or unavailable-writer +placeholder. agp/sdp are request aliases; artifact metadata uses real suffixes. + +UNRUN: actual Eclipse/Ray5/SD3 open/inspect/play/save/close/reload, audible +articulation/controller response, Cubase MIDI/native import/routing and playback. +The previously observed Cubase15 unnamed user project (PID 41836) was never +manipulated, closed or saved. No global input, audio host/driver launch, audio +analysis/rendering, plugin hosting or DAW automation was performed. +Read-only process inspection is not an application test or permission to host. +No full-library/all-version/arbitrary-technique or acoustic compatibility claim. +Software readiness is COMPLETE; the original full application definition of +done remains uncertified. These limits are not pytest skips or fake passes. + +WHAT CHANGED / WHAT WAS PRESERVED + +Read the latest plan, CURRENT native/service/CC reports 7_fix, 8_fix, 9_fix, +9_fix_controls, current codecs/service/contracts/composition/tests and docs. +Preserved all pre-existing native implementation and unrelated working changes. +No production-code defect was exposed; no speculative production patch, +dependency-manifest change, package/dependency restore, commit, delegation, +later prompt execution or unrelated feature was introduced. + +Directly necessary acceptance changes: +- tests\integration\test_distribution.py now additionally verifies installed + target-default missing-template partial fallback and disabled-fallback error, + actual-name native-only requests, and native collision byte preservation. + Existing musical/control/privacy/atomic assertions remain intact. +- tests\unit\test_readme.py adds eight tests: six executable JSON contracts, + their inventory, and current local documentation file/anchor links. + Requests also resolve, compose and compile against current profiles. +- README/current architecture/profiles/format/compatibility docs and plan now + identify actual native defaults, aliases, CC/technique boundaries, current + software acceptance and separate UNRUN live checks. Exact filler vocabulary + is documented; stale five-profile/current MIDI-only status is removed. +- Found a real coupled documentation defect: README's publication-safety link + targeted #implemented-in-step-9, lost when the native-fix heading changed. + Restored an explicit stable anchor and added the local-link regression. + The compatibility section's existing public anchor is also retained. +- This report is CURRENT-first; the entire prior MIDI-only report remains below + as explicitly retracted historical scope, not approved native completion. + +FINAL EXECUTED VALIDATION — ALL PASS + +PowerShell, existing repository .venv, Windows 11 build 10.0.26200 AMD64, +CPython 3.13.13 / MSC v.1944 64 bit. +Scratch/build temporary locations were explicitly repository-local: + $scratch = (Resolve-Path '.test-artifacts\scratch').Path + $env:TEMP=$scratch; $env:TMP=$scratch; $env:TMPDIR=$scratch + $env:PIP_NO_INDEX='1' +Full-suite genuine-template activation: + $env:RIFF_SD3_TEMPLATE='C:\Users\g3\Documents\Toontrack\Superior Drummer 3\sd3-demo.sd3p' + + .\.venv\Scripts\python.exe -m pytest -q --tb=short + 1421 passed in 63.67s; 0 failed, 0 skipped, 0 xfails. + Prior current baseline independently rerun: 1413 passed in 61.51s. + Eight new documentation contract/link cases account for the count change. + Includes native/MIDI/CC/physical-string/profile/stdin/packaging regressions, + read-only genuine-template cases, real Windows junctions, concurrent + publication, all-or-nothing multi-artifact failures and no-overwrite. + Final log: .test-artifacts\step10-full-final.log + + .\.venv\Scripts\python.exe -m pytest tests\unit\test_readme.py tests\integration\test_distribution.py -q --tb=short + 11 passed in 12.66s; 0 failures/skips. + Log: .test-artifacts\step10-focused-final.log + .\.venv\Scripts\python.exe -m ruff check . + All checks passed. + .\.venv\Scripts\python.exe -m ruff format --check . + 85 files already formatted. + .\.venv\Scripts\python.exe -m mypy --strict src tests + Success: no issues found in 47 source files. + .\.venv\Scripts\python.exe -m pip check + No broken requirements found. + git --no-pager diff --check + PASS, no whitespace errors. + Editor Problems on both changed Python tests: no errors. + Editor runTests: "No tests found"; not represented as a pass or skip. + Actual repository-venv pytest above is the authoritative test execution. + Static log: .test-artifacts\step10-static-final.log + +Actual versions: + mcp 1.30.0; pydantic 2.14.1; mido 1.3.3; MIDIUtil 1.2.1; + pytest 9.1.1; anyio 4.15.1; ruff 0.17.1; mypy 2.4.0; + build 1.6.1; setuptools 84.2.0; wheel 0.48.0; packaging 26.3; + jsonschema 4.26.0; types-jsonschema 4.26.0.20261006; pip 26.0.1. +No claim of testing Python 3.11/3.12, other OSes or every permitted dependency +version. Existing dev-venv dependencies were reused for installed-wheel runtime; +this is not a fresh complete dependency-environment certification. + +FINAL PERSISTED DISTRIBUTIONS / SOURCE IDENTITY + +After all source/test/README/current-doc/plan edits: + .\.venv\Scripts\python.exe -I -B -m build --no-isolation --outdir .\dist\step10-native-20261020 +PASS: real sdist followed by wheel built from that sdist; offline. + +Retained FINAL files, package version 0.1.0: + dist\step10-native-20261020\gaj3t_musicgen_riff_groove_builder-0.1.0-py3-none-any.whl + 74822 bytes; SHA256 + cb4e6978d7d778d96eda88ce70b5f5c43a17e44aae9fcfdc834e3ea3a0d0502d + dist\step10-native-20261020\gaj3t_musicgen_riff_groove_builder-0.1.0.tar.gz + 85030 bytes; SHA256 + 26671d01c39c9746fd1ea251aca1a2cb20496c8fd3a1d88e09533614b27552de + +Final 68-file source/test/fixture/docs/manifest/README/plan SHA256 manifest: + 5765b606bf661da59858914f4d146956c647a7beaf88ea2f168a3301d3a07d9e +Stored as source_manifest in the retained final acceptance.json. The digest +covers sorted compact JSON of relative paths -> file-byte SHA256; it excludes +this self-referential report, caches, build metadata and ignored evidence. +Separate delivery checks rehash every file and both final archives. + +All 22 actual package Python/JSON files match BOTH archives byte-for-byte; +sdist README matches final README. Wheel has 26 entries including metadata, +16 Python modules/entry locations, SIX real JSON profile resources and actual +formats\agp.py / formats\sdp.py codecs. All six resource hashes also match +the installed wheel resources. Archive inspections exclude private templates, +factory/native musical files, manuals, executables/plugins and scratch trees. +No private template, kit, factory song, licensed manual, binary, credential or +upload was added to source/tests/distributions. Original portable fixtures are +newly authored test content, not stripped private exports. +Prior dist files were preserved; initial/pre-link builds under separately +labeled dist directories are NOT the final accepted wheel above. + +EXACT FINAL-WHEEL REAL STDIO / SAVED ORIGINAL EVIDENCE + +Retained root (R below): + .test-artifacts\step10-final-native-20261020\final-verified +Driver/checkers retained in its parent: + accept.py; verify_saved.py; verify_delivery.py +Final execution: + .\.venv\Scripts\python.exe -B .\.test-artifacts\step10-final-native-20261020\accept.py + .\.venv\Scripts\python.exe -I -B .\.test-artifacts\step10-final-native-20261020\verify_saved.py + .\.venv\Scripts\python.exe -I -B .\.test-artifacts\step10-final-native-20261020\verify_delivery.py + +The driver installed THAT exact persisted wheel with +--no-index --no-deps --no-cache-dir --target R\installed-wheel, noneditably. +Every real server subprocess used -I -B and cwd: + D:\_Repos\Code\GAJ3T\MCPs\MusicGen +That existing directory is OUTSIDE the checkout; no files were created there. +All 16 imported package/submodule/entry locations and distribution metadata +resolve under R\installed-wheel, not editable src. Actual service location: + R\installed-wheel\riff_groove_builder\service.py +Installed importlib.resources reads all six real profile JSONs there. +Probe/resource/module hashes and complete requests/results/live schemas are +saved in R\acceptance.json. No earlier build substitutes for this proof. + +Three actual initialized/EOF stdio sessions, stderr EMPTY and exit 0 each: + portable: 11 successful generations, 5 expected errors, 20 stdout lines + missing-template: 2 successful generations, 2 expected errors, 7 stdout lines + genuine-private: 1 successful generation, 1 expected error, 5 stdout lines +All 32 UTF-8 stdout lines validate as MCP JSON-RPC. Missing-template disabled +fallback, invalid associations/endpoints, unsupported native CC disabled +fallback and collisions leave output snapshots unchanged. +Separate corrupt-template startup: exit 2, ZERO stdout bytes, ZERO outputs, +visible stderr error; no successful fallback. Only an owned deliberately bad +portable-template file was removed after that probe. + +Portable cases use an unchanged copy of the ORIGINAL fixture +tests\fixtures\sd3\original-template.sd3p, not a genuine/private kit template. +R\portable contains: + default: actual mid + griff + briff + sd3p (four outputs); + aliases: agp+sdp -> griff/briff/sd3p only; + actual: griff+briff+sd3p -> those three native outputs only; + midi: explicit MIDI-only with native fallback disabled; + final-cc-pitched/drums/other/midi/tick/omitted/empty: seven exact CC cases. +R\missing-template contains: + fallback: griff/briff plus ONE MIDI, fallback_for=["drums"] only; + midi-no-template: explicit MIDI plus pitched CC1/reset, no SD3 template needed. +R\genuine-private\genuine-original contains four genuine-template outputs. +Total: 14 successful generation scenarios, 8 intentionally rejected tool calls, +38 actual retained musical artifacts; no .agp/.sdp mislabeled files. + +Independent SECOND process imports NO riff_groove_builder modules. It reopens +every saved file using Mido, ElementTree and a separate quoted-brace/SD3 triple +decoder, with fixed numeric music/velocity/fingering expectations, not the +production serializer/compiler as its expected output. +R\independent-saved-checks.json: 38 passed; 0 failed; 0 skipped; +package_imported=false; source_templates_unchanged=true. +It checks exact note on/off timing/velocities, native physical string/fret, +PM/PMP, tempo/meter/key/end, switches/channels/CC raw bytes/native stairs, +artifact size/suffix/profile metadata, subset/fallback warnings, directory +coverage, original no-control hashes and exact non-song template bytes. +R\delivery-checks.json additionally confirms 66 current local documentation +file/anchor links and all retained source/build/artifact hashes. +All six README fenced JSON examples pass current typed contracts; all three +request examples compile, and the real installed server's discovered schemas +also validate the documented requests/response/error. + +EXACT ORIGINAL MUSICAL CONTENT / DEFAULT HASHES + +Request: seed 42; original "lead bass drums palm mute 137.5 BPM 2 bars 7/8 +Bb minor quarter rests"; target defaults; fallback disabled when configured. +Resolved A# minor; MIDI PPQ960, start0/end6720; native PPQ480/end3360; +SD3 interval0..7 quarter beats. Tempo 436364 us/quarter, meter7/8, +Conductor/Lead/Bass/Drums, channels0/1/9, every MIDI track EOT6720. +Pitched onsets: 0,960,1920,3360,4320,5280; duration960; release velocity0. +Lead pitches: 58,61,66,58,61,65; velocities96,64,96,64,64,96. +Bass pitches: 46,53,46,46,53,46; velocities48,51,55,48,51,51. +Drums: simultaneous hat42 and hit36,38,36,36,38,36 at those onsets; +each duration240; paired velocities80,96,96,96,64,64. +Lead selector26/bass24, switch velocity100, interval0..30; no drum switch. +Native lead PM, bass PMP, not separate D0 bass PM. +Physical lead pitch -> (string,fret): 58->(2,1),61->(2,4), +66->(1,4),65->(1,3); bass46->(3,1),53->(2,3). +Notes neither dropped nor shortened; final rests preserve full score duration. + +R\portable\default: + default.mid 336 bytes + 8fc4cfbe66c0706f223ec33a61692ead046a56a9dba51c6566f967690cee186c + default_lead.griff 1296 bytes + fe7a2a5c98d0ae16f6894e681e7f001a658c90d11b3f1beb313d5c98b6c810c9 + default_bass.briff 1282 bytes + 5da9b05e92e6989366f41f8abf22a0f8b88ae14591bc8b544e4c7c0cf47827c4 + default_drums.sd3p 1491 bytes + 8bee8a86a7e60320d02c4404e36d818639af1d8f4ebce27f6c23a25e7ebd0589 +Aliases/actual native-only originals match these native bytes. Omitted and +empty CC requests remain pinned to these PRE-controls report_9_fix hashes. + +CC1 MIDI (tick,controller,value): + lead channel0: (0,1,11),(480,1,73),(6720,1,0) + bass channel1: (0,1,21),(960,1,127),(6720,1,0) +Native tick/value stairs: + lead: (0,11),(240,73),(3360,0) + bass: (0,21),(480,127),(3360,0) +End zeros are EXPLICIT requests, never invented resets. Same-tick controls +precede note-ons. All-part CC4 drum points (320,4,96),(6720,4,0) yield ONLY +drum fallback, reason sd3_native_controller_not_supported; Riffer files survive. +Lead CC74 (320,74,127),(6720,74,0) yields ONLY lead native fallback, reason +unsupported_native_controller; bass/SD3 natives survive. MIDI-only retains all +ten mixed controls; one-tick lead CC1=99 at tick1 has no invented reset. +No audible modulation/vibrato/effect semantics are inferred from raw CC data. + +GENUINE READ-ONLY LOCAL TEMPLATE / PRIVATE STATE + +Read in place only: + C:\Users\g3\Documents\Toontrack\Superior Drummer 3\sd3-demo.sd3p +Before/after identity/content verified both by service and separate saved check: + size75393; inode166633186213030518; mtime_ns1788614183091903900; + SHA256 06f54b02079e4b32d532ecc232b813c3fe1865799e6f5b2b21b5ddf398b0533d +All 170 old source-song notes are replaced by twelve ORIGINAL generated notes, +one track/clip, exact137.5BPM/7/8/0..7beats/channel9/velocities64..96. +R\genuine-private\genuine-original\genuine-original_drums.sd3p: + 66325 bytes; SHA256 + 265535e1b885ff7765becce8281873ec627e28b35b5404a0f0cd9b533c424680 +Non-song bytes, including kit/sampler/mixer/tracker/host-sync, are identical: + SHA256 10340dc5c057f2580c474ebc56277b2deae3263cee49e4674e07b8c9cc421d32 +Its MIDI/griff/briff hashes equal the portable originals above. +Generated genuine evidence RETAINS PRIVATE KIT STATE; it stays local/ignored +under .test-artifacts, never source/tests/distributions/uploads. +Portable original source1110bytes has SHA256 + ef72e05498d2809ac47432e925d6072258cbe3c918de13b9079c2353af1759a4 +and also remains unchanged in bytes/identity/size/mtime. + +FAULTS / CLEANUP / HONEST LIMITS + +Full-suite tests prove partial last-native writes, corrupted saved bytes, +same-size/mtime-restored earlier-artifact corruption, ownership replacement, +unknown stage entries, denied cleanup, publish/model/serialization/IO faults +do not publish partial successes or overwrite existing output. Concurrent +four-file publication has one winner and one OUTPUT_EXISTS. Unexpected faults +never become MIDI successes. Explicit corrupt templates are errors. + +Only issues encountered here: documented editor test discovery absence; +the real stale documentation anchor fixed/tested above; an initial independent +evidence script assumed LF rather than preserving genuine CRLF and omitted +null profile-selection fields in its comparison. Those checker assumptions +were corrected without changing musical expectations or production behavior. +Final independent checks pass on actual original native bytes. + +Every owned stdio child was EOF-closed and awaited; no acceptance host/server +is left running. UUID distribution/native-service/stdio/control test workspaces +were cleaned by fixtures; no incomplete stage remains in retained final trees. +Retained original outputs, installed-wheel provenance, all JSON checks and final +builds are intentionally preserved and ignored. Earlier evidence/builds were +not deleted or represented as this exact-wheel acceptance. +Trusted local ACL/no-hostile-race/power-loss limits remain documented. + +READY: all actionable final native/MIDI SOFTWARE acceptance is verified and +persistent. No implementation/package blocker remains for the declared subset. +NOT CERTIFIED: live receiver/plugin/Cubase behavior, audible performance, broader +libraries/versions/techniques/controllers, other runtimes/OSes or fresh complete +dependency installation. No later prompt was executed or new host launched. + +====================================================================== +HISTORICAL — PRIOR MIDI-ONLY STEP 10 REPORT (RETRACTED INTERIM SCOPE) +The following original report is retained verbatim as history. Its MIDI-only +closure and BLOCKED native implementation findings are superseded above; +they were not user approval to reduce the native-output requirement. +====================================================================== + +Step 10 — installed software acceptance and truthful delivery documentation +Date: 2026-10-19 + +SEPARATE OUTCOMES + +Independent Windows Standard MIDI software/package/docs acceptance: PASS. +Complete current pytest suite: 1119 passed; 0 failed; 0 skipped. +Actual final persisted wheel server outside checkout and disk read-back: PASS. +Final real sdist/wheel build, lint, format, strict types and pip check: PASS. +Verified Eclips/Ray/SD3 vendor mappings: BLOCKED; not supplied or certified. +Real AGP/SDP serialization/native acceptance: BLOCKED. +Cubase/plugin/receiver import and native load/save/reload: UNRUN. +No full native-project completion or original full release acceptance is claimed. + +IMPLEMENTED AND PRESERVED + +Executed prompts\step_10.md under the amended approved functional-MIDI plan. +Reviewed the amended plan, report_9.md/prior report evidence, native fix +handoffs, and current implementation, documentation and tests. + +Updated: +- tests\integration\test_distribution.py: one new installed-wheel server + acceptance test, extending the existing offline sdist/wheel build fixture. + Reuses RawStdio/TIMEOUT from test_stdio.py instead of duplicating transport + client logic. Existing separate-venv import/distribution tests remain. +- README.md: operational standard-only identity, tested configuration, + setup/existing-root requirements, absolute Windows MCP configuration, profile + discovery, accepted requests, schema-valid concrete responses/errors, + exact limits/defaults/overrides, routing and filesystem limitations, + installed-wheel acceptance and explicit remaining native handoffs. +- docs\architecture.md: removes obsolete current empty-registry/unfinished + generation statements, documents actual service layers and installed-wheel + acceptance, preserves native gates and trusted-ACL/race/crash limits. +- docs\compatibility.md: actual current Python/OS/dependency versions and + software results, separately BLOCKED native/vendor and UNRUN application rows. +- docs\articulation-profiles.md: installed standard-only resources/routing, + external receiver setup and unchanged vendor limitations. +- docs\formats\agp.md and sdp.md: current operational service/fallback status, + explicit BLOCKED step_7_fix.md/step_8_fix.md handoffs and missing evidence. +- prompts\plan.md: corrects obsolete proposed/awaiting-review status to the + approved partial-native status; labels the old review instruction historical. + The pre-existing continuation decision and original full definition of done + remain intact. +- prompts\report_10.md: this persistent report. + +No production source, profile JSON, dependency manifest, prior report or native +fix prompt was changed. No actual production defect was exposed by acceptance, +so no speculative source fix or artificial regression was added. The new test +closes the real installed-server acceptance gap. No commits, delegation, later +prompts, extra formats, vendor profiles, native fixtures or application claims. +Pre-existing unrelated/untracked implementation work was preserved. + +TESTED ENVIRONMENT + +Windows 11 / 10.0.26200 / AMD64. +CPython 3.13.13, MSC v.1944 64 bit (AMD64). +Existing interpreter: +D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder\.venv\Scripts\python.exe + +Actual versions: +mcp 1.30.0; pydantic 2.14.1; mido 1.3.3; MIDIUtil 1.2.1; +pytest 9.1.1; anyio 4.15.1; ruff 0.17.1; mypy 2.4.0; +build 1.6.1; setuptools 84.2.0; wheel 0.48.0; packaging 26.3; +jsonschema 4.26.0; types-jsonschema 4.26.0.20261006; pip 26.0.1. + +No project dependency installation/restoration/reinstallation was performed. +Tests installed only their built application wheels offline into owned targets +and the existing isolated import-test venv. Runtime server dependencies were +reused from the development venv. This is NOT a fresh full dependency-install +certification, a test of all allowed dependency versions, Python 3.11/3.12, +another OS, or actual receiver/plugin behavior. + +EXACT VALIDATION COMMANDS AND RESULTS + +Commands ran in PowerShell from the repository root. Repository-local +test/build scratch setup (repeated for each relevant shell): + +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +$env:PIP_NO_INDEX = '1' + +Editor runTests was attempted for the absolute distribution test path: +"No tests found in the files." This is the known discovery limitation, +not a pass or pytest skip. The working repository-venv CLI was used. + +Final focused acceptance: +& '.\.venv\Scripts\python.exe' -m pytest tests\integration\test_distribution.py -q -s --tb=short +PASS: 3 passed in 10.12s; 0 failed; 0 skipped. +Includes both original build/import tests and the new real installed-wheel +server generation/error/EOF acceptance. An earlier focused run before the last +assertion additions also passed 3 tests in 9.81s. + +Final complete current suite: +& '.\.venv\Scripts\python.exe' -m pytest -q --tb=short +PASS: 1119 passed in 38.13s; 0 failed; 0 skipped. +Preserves all source/distribution/profile/compiler/description/composition/ +MIDI/MIDIUtil/native-unavailability/service/stdio tests, including genuine +Windows junction and competing publication regressions. Native/application +evidence missing outside this executable software suite is not a pytest skip. + +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: All checks passed! +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: 69 files already formatted on the final rerun after persisting this report +(68 on the earlier pre-report run). +& '.\.venv\Scripts\python.exe' -m mypy --strict src tests +PASS: Success: no issues found in 38 source files. +& '.\.venv\Scripts\python.exe' -m pip check +PASS: No broken requirements found. +git --no-pager diff --check +PASS: no tracked-diff whitespace errors. Existing implementation is largely +untracked; Ruff separately checked the actual Python files. +Editor problems: no errors in the changed Python test. + +Final distributions, after the final test/source/README edits: +& '.\.venv\Scripts\python.exe' -m build --no-isolation +PASS: Successfully built gaj3t_musicgen_riff_groove_builder-0.1.0.tar.gz +and gaj3t_musicgen_riff_groove_builder-0.1.0-py3-none-any.whl. +The default build built the wheel from the real sdist. Index access disabled. + +Persisted under dist: +- gaj3t_musicgen_riff_groove_builder-0.1.0-py3-none-any.whl + 51,462 bytes; SHA256: + 841DF0BF582257EEE3FA5A5F9165A41776937CC74D1726D342827FC897E9C0AE +- gaj3t_musicgen_riff_groove_builder-0.1.0.tar.gz + 52,548 bytes; SHA256: + 8AAE99D375BF34F62FCD4B98C91EBEA7C376A5DF8DCA873087FEE197F057B274 + +An additional archive inspection compared all 19 current Python/JSON source +files byte-for-byte to BOTH final distributions; all matched. The sdist README +matched the current README byte-for-byte. Wheel contents included no synthetic +fixtures, native files or manuals. Hashes identify these builds; byte-for-byte +reproducibility across build times is not asserted. + +README validation additionally parsed all five fenced JSON examples: one MCP +configuration, two accepted requests, one success response, one typed error. +Requests passed strict models, profile selection, composition and compilation; +both ended at 6720 ticks. Success passed the published output schema and model, +including exact assumptions; error passed its model. Local documentation file +links were checked (the report link was completed when this file was written). +Current docs contain no active empty-profile/unfinished-generation claims. +Final persistence check confirmed exactly one plain report fence, every local +documentation file link resolving, unchanged final archive hashes and cleanup; +lint/format/strict types/pip check all passed again after report creation. + +INSTALLED-WHEEL SERVER PROOF + +Normal test procedure: +- Build real sdist and wheel offline from current source. +- pip install --no-index --no-deps --no-cache-dir --target +- Launch the repository-venv Python with -I -B and an explicit bootstrap that + prepends the wheel target to sys.path, asserts all application import/spec + locations and distribution metadata there, then executes installed __main__ + with --output-dir . +- Working directory: + D:\_Repos\Code\GAJ3T\MCPs\MusicGen + This is the existing parent OUTSIDE the checkout. No file was created there. +- Dependency MCP import: + \.venv\Lib\site-packages\mcp\__init__.py +- Application/version metadata: non-editable wheel 0.1.0, not src. + +Final focused test workspace (subsequently removed): +\.test-artifacts\distribution-fc21b3bebca9492c9b263bd561028085 +Its installed server PID 33388 exited 0; 13 protocol stdout lines were checked. + +To prove the EXACT persisted final wheel, not just a separately built wheel, +the same acceptance function was also replayed against a hash-identical copy +of dist's final wheel. Exact replay command: + +@' +import asyncio +import hashlib +import os +from pathlib import Path +import shutil +import sys +import uuid +root = Path.cwd().resolve() +sys.path.insert(0, str(root.joinpath('tests', 'integration'))) +from test_distribution import test_built_wheel_real_stdio_generation_outside_checkout +wheel = root.joinpath('dist', 'gaj3t_musicgen_riff_groove_builder-0.1.0-py3-none-any.whl') +workspace = root.joinpath('.test-artifacts', 'step10-final-wheel-' + uuid.uuid4().hex) +workspace.joinpath('dist').mkdir(parents=True) +scratch = workspace.joinpath('scratch') +scratch.mkdir() +env = os.environ.copy() +for name in ('PYTHONPATH', 'PYTHONHOME'): + env.pop(name, None) +env.update(TEMP=str(scratch), TMP=str(scratch), TMPDIR=str(scratch), PIP_NO_INDEX='1', PIP_NO_CACHE_DIR='1', PIP_DISABLE_PIP_VERSION_CHECK='1', PYTHONDONTWRITEBYTECODE='1') +try: + copied = workspace.joinpath('dist', wheel.name) + shutil.copy2(wheel, copied) + expected = hashlib.sha256(wheel.read_bytes()).hexdigest() + assert hashlib.sha256(copied.read_bytes()).hexdigest() == expected + asyncio.run(test_built_wheel_real_stdio_generation_outside_checkout((workspace, env))) + print('FINAL persisted wheel acceptance replay: PASS; SHA256=' + expected) +finally: + shutil.rmtree(workspace) +assert not workspace.exists() +print('Final-wheel replay workspace removed: ' + str(workspace)) +'@ | & '.\.venv\Scripts\python.exe' - + +PASS: exact persisted wheel SHA256 matches 841DF0BF...E9C0AE above. +Actual replay target: +\.test-artifacts\step10-final-wheel-d903ac35181845ceb73e70d8e2c5e04c\installed-server +Actual replay package path: +\riff_groove_builder\__init__.py +Server/service paths: +\riff_groove_builder\server.py +\riff_groove_builder\service.py +All 16 asserted package/submodule entry locations: +__init__, __main__, server, service, schemas, errors, description, compose, +profiles, articulations, midi, formats.__init__, formats.agp, formats.sdp, +data.__init__, data.profiles.__init__. +None resolved into editable src. Both probe and actual server bootstrap +enforce these checks; this is not merely a separate import smoke test. + +Actual wheel JSON members compared to installed bytes and loaded as resources: +general-midi-percussion-v1.json; standard-midi-bass-v1.json; +standard-midi-lead-v1.json. Exactly three resources, no synthetic/vendor profile. + +Replay PID 46304 initialized through the real SDK, listed exactly +list_instrument_profiles and generate_music, listed exactly standard.bass.v1, +standard.gm-drums.v1 and standard.lead.v1, all standard_midi/native-unavailable/ +normal-only. Schemas equal the authoritative contracts. Requests and all +profile/success/error structured outputs were independently schema-validated. + +Actual request description, seed 42: +lead bass drums 137.5 BPM 2 bars 7/8 Bb minor quarter rests + +Actual published files relative to that replay's server-outputs root: +- explicit\explicit.mid — ["mid"], complete, fallback_for=[], 3 mapping warnings. +- default\default.mid — formats omitted, midi_fallback, fallback_for all three + parts, 3 mapping plus 3 native-unavailable warnings. +- native\native.mid — ["agp","sdp"], the same explicit fallback/warning coverage. + +Each actual disk file was 324 bytes, began MThd and had SHA256: +7d61b8d4a8c42a19091126ce7301b159744bbae4e78456b0cd1894f6269aea4b +Independent saved-file Mido parsing verified SMF type 1, PPQ 960, +137.5 quarter-note BPM encoded as 436364 microseconds/quarter at tick zero, +7/8 at zero, tracks Conductor/Lead/Bass/Drums, and one EOT per track at 6720. +Resolved tonality A# minor, exact profile IDs, parts, measured sizes and paths +matched actual artifacts. Standard channels were zero-based 0/1/9. +Note-on counts were 0/6/6/12; pitched onsets 0,960,1920,3360,4320,5280; +each drum onset had two hits. Pitched gates 960 ticks, drum gates 240; +every note was legal, positive-onset-velocity, non-overlapping and pair-complete. +Drum pitches were 36/38/42, with no program/bank/CC/keyswitch payloads. +Identical content across format policies is MIDI substitution, not native data. + +The same process verified typed failures and unchanged output directory lists: +- Native-disabled drums -> NATIVE_FORMAT_UNAVAILABLE, sdp_layout_not_established. +- Native-disabled lead -> NATIVE_FORMAT_UNAVAILABLE, agp_layout_not_established. +- Lead palm mute under standard map -> UNSUPPORTED_ARTICULATION. +- Unicode unsupported description -> UNSUPPORTED_DESCRIPTION, no text leakage. +- Existing explicit basename -> OUTPUT_EXISTS; no new directory appeared. +No disabled/unsupported/Unicode directory or stage/native artifact was created. + +Every captured server stdout line was newline-delimited UTF-8, parsed as JSON +and validated as MCP JSON-RPC; exactly 13 lines, no extra nonprotocol output. +Deliberate malformed Unicode input yielded only the SDK generic protocol +notification on stdout, separate sanitized diagnostics on stderr, and successful +ping recovery. Closing stdin reaped the initialized server with exit code 0. +A second installed-wheel child also exited 0 with zero stdout/stderr on EOF +before initialization. Reads/writes/shutdown have bounded waits; cleanup can +kill only the owned child and reap it if normal EOF fails. + +ISSUES AND CLEANUP + +Initial static checks found two wrapping findings, a loop-closure lint finding +and a test-local dictionary-type inference conflict. Refactored the schema-call +helper, explicitly typed heterogeneous failure options and formatted the changed +test. No production bug, weakened check, broad ignore or dependency change. +All final checks pass. A build-directory inspection found it already absent; +subsequent explicit cleanup checks confirmed that absence, not a build failure. + +All owned UUID distribution/install/server/output/junction/test workspaces were +removed, including the final-wheel replay outputs after actual disk inspection. +The evidence paths above identify observed files, not retained MIDI downloads. +Only pre-existing scratch and step9-verified remain under .test-artifacts. +No .riff-stage-* directories or Python module-server processes remain; process +enumeration verified this after the focused test and replay. build is absent. +The repository venv/caches, prior step9 evidence and unrelated work were preserved. +Final dist wheel/sdist remain as intentional delivery artifacts. +No scratch scripts, background helpers, native binaries, secrets, manuals or +factory songs were added. No external/vendor/application work was fabricated. + +REMAINING ORIGINAL NATIVE/VENDOR/APPLICATION BLOCKERS + +1. Vendor MIDI maps: exact Eclips/Ray identity/build and SD3 build/library/preset/ + selected map, real numeric ranges/voices/channels/keyswitch/CC semantics, + velocity layers and reset/timing evidence remain unverified. Standard maps + and synthetic compiler tests cannot close this gate. +2. AGP: actual content-bearing native layout/version/encoding, lawful controlled + empty/one-note/multi-note exports and isolated tempo/timing/velocity/technique + changes, source/fixture permission and true native round trips are missing. + Guitar and bass must be established independently; no shared layout inferred. + prompts\step_7_fix.md remains BLOCKED and was not executed or rewritten. +3. SDP: real song/groove-versus-preset content category, container/version/schema, + mapping/library dependencies, lawful controlled hit/variable-change exports, + permission and actual native round trips remain missing. + prompts\step_8_fix.md remains BLOCKED and was not executed or rewritten. +4. Applications: actual Eclips/Ray/SD3 native import/inspect/save/close/reload, + receiver routing, Cubase MIDI import/tempo/meter/alignment/dynamics/control + behavior and native/MIDI content equivalence are UNRUN. Exact versions, + workflows and evidence are unavailable. Mido opening a MIDI file is not + any of these application acceptances. +5. If a requested native extension cannot hold the musical content, that is + an unresolved scope contradiction requiring real evidence/decision, not + permission to rename MIDI, emit preset-only files or substitute formats. + +SOFTWARE READINESS / STOP + +Ready for use/review as the documented Windows Standard MIDI MCP generator on +the tested configuration, including real built-wheel execution. All independent +Step 10 software acceptance is complete and persistent in tests/docs/artifacts. +Not ready to claim the original native/application definition of done. +No next worker prompt, commit or delegated task was created. Stopped after +verified software/report completion, not merely because native gates exist. +``` diff --git a/prompts/report_11.md b/prompts/report_11.md new file mode 100644 index 0000000..bb9c405 --- /dev/null +++ b/prompts/report_11.md @@ -0,0 +1,204 @@ +``` +Step 11 — COMPLETE: visible JSON feedback and actionable request recovery +Date: 2026-10-20 + +Implemented +- Both tools now put the COMPLETE safe public object into structuredContent + and one JSON TextContent block. json.loads(content[0].text) equals + structuredContent for profile lists, generation successes, validation errors + and known domain errors. isError remains correct. No vague summary substitutes + for IDs, resolved metadata, artifacts, warnings or error details. +- Added authored field/reason/correction issues for formats, profiles and CC + cross-field failures. Applied the same safe validation after inferred parts + resolve. Meter type failures identify time_signature.denominator. +- Added actionable key/meter/parts/formats/profile/CC grammar, bounds and shape + guidance. Missing fields and unknown properties retain strict validation. + Known profile-selection and unsupported-description errors expose explicit + recovery/limitations in the JSON text, not success-shaped approximations. +- Added accurate tool and input descriptions: omit formats for automatic output; + guitar lead -> griff/agp, bass -> briff/agp, drums -> sd3p/sdp; mid for all. + Omit profiles for defaults or use exact list_instrument_profiles IDs. Never + invent IDs or add CC events without user intent. Preserve musical intent and + identify unsupported instructions rather than silently simplifying them. +- Structured keys accept attached lowercase-m minor shorthand. Full forms and + strict malformed/unknown-mode rejection remain intact. +- Updated README, architecture documentation, unit/schema/service tests, + official-client tests and real source/installed-wheel stdio acceptance. + +Actual BEFORE evidence, captured before edits +A fresh real stdio process reproduced the failing fields from the supplied +report; no LM Studio conversations/configuration were read or edited. + +list_instrument_profiles TextContent: + "6 profiles; inspect mapping_kind and limitations." + +generate_music fixture: + parts=["lead"], formats=["sd3p","mid"], key="E minor", + profiles={"lead":"aggressive_rock"}, + cc_events=[{"part":"lead","beat":{"numerator":0},"controller":91,"value":64}] + +TextContent: + "Correct the invalid request fields identified in details and retry." +Structured details, not visible to the reported text-only client: + {"issues":[{"field":"$request","reason":"value_error"}]} + +Direct validation in the same reproduction: + E minor -> E minor + E Minor -> E minor + Em -> rejected +Process exit: 0. Stderr: empty. +This was a hidden-feedback/format-association problem, not evidence that the +valid E minor spelling was wrong. + +Actual AFTER evidence: source AND isolated installed-wheel stdio +The consumer makes recovery decisions from decoded TextContent only. +Equality with structuredContent is separately asserted for every response. + +The profile-list text now exposes all six actual IDs and complete capabilities +and limitations: + ample.ame.4.0.1.riffer.v1 + ample.amr.4.1.0.riffer.v1 + standard.bass.v1 + standard.gm-drums.v1 + standard.lead.v1 + toontrack.sd3.3.4.4.core.v1 + +The original wrong-format fixture now returns this complete decoded text: +{"code":"INVALID_REQUEST","message":"Correct the invalid request fields identified in details and retry.","details":{"issues":[{"field":"formats","reason":"format_parts","correction":"Omit formats for automatic per-part native output plus MIDI. sd3p/sdp requires drums; griff requires lead; briff requires bass; agp requires lead or bass. Guitar lead uses griff/agp or mid; bass uses briff/agp or mid; drums uses sd3p/sdp or mid. Use a nonempty unique array of these format names."}]}} + +After omitting formats, the independently wrong profile becomes actionable: +{"code":"PROFILE_REQUIRED","message":"The requested profile is missing; list profiles with list_instrument_profiles({}) and select an available ID for that part, or omit profiles for defaults. Never invent profile IDs.","details":{"part":"lead","reason":"missing_profile"}} + +Neither failure publishes a directory. A separate detailed-triplet-description +probe returns UNSUPPORTED_DESCRIPTION, with supported vocabulary and the +explicit limitation "Detailed triplet patterns, arbitrary melodies and +changes/sequences are not supported." It also publishes nothing. + +The supported quarter-note recovery fixture uses an exact returned lead ID: +{"description":"lead only 1 bar quarter","basename":"text-recovered","parts":["lead"],"key":"Em","profiles":{"lead":"ample.ame.4.0.1.riffer.v1"}} + +Formats are omitted for automatic correct output. Unrequested CC91 is omitted +by the consumer, not silently removed by the backend. This supported fixture +is NOT a claimed approximation of the user's unsupported triplet composition. + +Source and installed wheel both produced: + status: complete + canonical key: E minor + profile: ample.ame.4.0.1.riffer.v1 + text-recovered.mid: 117 bytes + SHA256 922d4c30e4618b6cce61a2ecebb36193773ca3884e56db80f7c18fe18e813f26 + text-recovered_lead.griff: 1014 bytes + SHA256 213adde1c4785dccd2289e6888328c16bca720fb8d2786edb4df34f3863d1c2f + warning code: VERIFIED_SUBSET_LIMITS + fallback_for: [] on both artifacts + +Independent disk checks: +- MIDI type 1; tracks Conductor/Lead; 960 ticks/quarter; both tracks end at 3840. +- Five MIDI note-ons: four musical notes plus the required normal-articulation + keyswitch at note 24. Articulation behavior was preserved, not discarded. +- Real Riffer XML root Riff, four native notes, no fabricated CC lane. +- Zero CC91 events. No partial publication from wrong/unsupported calls and no + leftover owned stage. Successful paths and full warnings are visible in text. +- Source process exits 0 with empty stderr. Installed acceptance checks real + JSON-RPC framing, lifecycle/EOF, output schemas and sanitized malformed-input + diagnostics. Its expanded initialized process has exactly 20 protocol stdout lines. +- Installed-wheel acceptance imports all 16 checked modules from the noneditable + installed wheel, outside the source checkout, with -I/-B; all six packaged + profile resources and existing native/template/MIDI/CC checks remain verified. + +Schema, strictness and privacy decisions +- Retained JSON Schema constraints, conditional associations, uniqueItems, + numeric/array/string bounds, additionalProperties=false, output unions and + SDK protocol/lifecycle behavior. No schema simplification, transport rewrite, + model change or grammar-engine theory was used. +- E minor / E Minor / Em normalize to E minor; F#m -> F# minor; + Bbm -> A# minor; Bb major -> A# major. Accepted spellings are advertised in + schema examples and checked against both JSON Schema and runtime validation. +- Only explicit full major/minor forms or lowercase-m minor suffix are accepted. + Bare letters/missing modes, EM, E m, Emin, unknown modes, double/Unicode + accidentals, tabs and newlines remain errors. No arbitrary mode default. + Description text still requires full major/minor forms. +- Strict integer/boolean distinctions, finite numbers, CC bounds/grid/budget, + normalized duplicate rejection, profile identity/part checks and atomic/root + safety were not weakened. Explicit requested CC behavior remains supported. +- Public validation contains only known field names, numeric indices, redacted + property locations, controlled reason codes and static corrections. + No raw Pydantic input/context/message, exception cause, traceback or unknown + user property name is serialized. Synthetic private-/secret/path/Unicode + privacy sentinels remain absent from validation/domain results and diagnostics. +- Unknown tools/protocol failures and unexpected internal failures retain SDK + error semantics rather than being mislabeled as request/domain errors. + +Validation: exact executed results +Runtime: Windows; Python 3.13.13; MCP 1.30.0; Pydantic 2.14.1; Mido 1.3.3. +Commands use .\.venv\Scripts\python.exe; no dependency manifest changed. + +1. Focused server/schema/service/text-only tests: + -m pytest tests\unit\test_server.py tests\unit\test_schemas.py + tests\unit\test_service.py tests\integration\test_text_feedback.py -q --tb=short + PASS: 408 passed in 4.54s. + +2. Expanded focused validation: + -m pytest tests\unit\test_server.py tests\unit\test_schemas.py + tests\unit\test_service.py tests\unit\test_errors.py + tests\unit\test_cc_controls.py tests\unit\test_description.py + tests\unit\test_readme.py tests\integration\test_contracts.py + tests\integration\test_stdio.py tests\integration\test_text_feedback.py + -q --tb=short + PASS: 642 passed in 22.26s. + +3. Affected offline distribution/installed-wheel tests: + -m pytest tests\integration\test_distribution.py -q --tb=short + PASS: 3 passed in 12.63s. + +4. Final complete regression suite: + -m pytest -q --tb=short + PASS: 1458 passed in 61.68s; no failures or skips. + Includes native codecs/read-back, CC, atomic publication, source-template, + schemas, stdio, composition, packaging and installed-wheel regressions. + +5. Final source plus installed text-only evidence rerun: + -m pytest tests\integration\test_text_feedback.py + tests\integration\test_distribution.py -q -s --tb=short + PASS: 4 passed in 13.34s. Both printed identical artifact sizes/hashes and + the actual text-only error/recovery evidence recorded above. + +6. Final static/environment checks: + -m ruff check src tests + PASS: All checks passed! + -m ruff format --check src tests + PASS: 48 files already formatted. + -m mypy --strict src tests + PASS: Success: no issues found in 48 source files. + -m pip check + PASS: No broken requirements found. + git diff --check + PASS: exit 0, no whitespace errors. + Editor diagnostics for changed Python files: no errors found. + +Issues encountered and resolved +- Editor runTests reported "No tests found"; used the actual configured venv + pytest commands above instead. No discovery/tooling changes were needed. +- Initial focused checks caught two test assumptions: raw Windows paths are + JSON-escaped in text, and the MIDI includes a required articulation keyswitch. + Tests now assert the decoded exact path and five note-ons with the explicit + four-musical/one-keyswitch split; no behavior or checks were weakened. +- The first full run had 1457 passed / 1 failed: the installed fixture expected + its old 15 response lines after five new recovery calls were added. Updated + the exact expected count to 20. Also fixed one strict-mypy test-fixture + dictionary annotation. Installed and full reruns above are all green. +- Existing unsupported detailed musical requests remain explicit domain errors. + Native plugin/Cubase application certification remains outside these tests. +- Project-local acceptance logs were used only as scratch evidence and removed; + generated test workspaces are fixture-cleaned. No user output/chat was changed. + +Readiness and limits +Step 11 is implemented, persistent in the working tree, and verified. +Ready for review and then Step 12. The detailed triplet composer is NOT +implemented; no later prompt was executed. No commits or delegation occurred. +No user LM Studio chat/configuration, DAW, model or network service was modified. + +Operator action required: restart the LM Studio MCP server and start a fresh +chat to refresh its cached tool schema/descriptions. Its live UI was NOT +restarted or verified here; real source/installed-wheel stdio recovery was. +``` diff --git a/prompts/report_12.md b/prompts/report_12.md new file mode 100644 index 0000000..997fae4 --- /dev/null +++ b/prompts/report_12.md @@ -0,0 +1,194 @@ +``` +Step 12 — COMPLETE: exact rational beat scheduling, triplets and cross-bar PH +Date: 2026-10-20 + +Implemented +- Added reusable strict TimedNote/PhrasePlan models with reduced rational start, + positive duration, per-note technique and optional finite intensity. Plans + enforce ordering, nonoverlap, part coverage, score length and event budgets. + They are internal composition models, not a new public score tool. +- Added bounded clause parsing, not a whole-string prompt match or canned riff: + [chugging] palm mute/muted/muting eighth/8th [notes] from X to Y; + triplets on B&A with the A as a pinch harmonic that carries over a whole note + in the second/2nd measure. + X/Y are inclusive beats 1-4 with optional &, B is a beat 1-4. + Spacing around &, supported palm/pinch hyphens, Em/full E minor and F#m work. +- Generic phrase composition applies actual rational note timing, technique, + seeded or explicit intensity, low-tonic pitch policy and profile validation. + The typed composer also passes an independently authored 3/4 bass schedule + with mixed normal/PM durations, demonstrating reuse beyond this text phrase. +- Added only AME pinch_harmonic/PH, keyswitch31 and native Articulation="PH". + AME product 4.0.1 and production ID ample.ame.4.0.1.riffer.v1 are retained; + mapping_version is riffer-subset-2. XML layout remains 2.1/native PPQ480. + Ray, SD3 and Standard MIDI profiles have NOT gained PH. +- Updated supported-text guidance shared by errors, tool descriptions and + request schema; README, architecture and articulation-profile documentation. + Complete safe JSON remains identical in TextContent and structuredContent. + +Before / after grammar +- Before: description Em shorthand, from/to timing clauses and triplets/PH + could not express this request. The blanket changes/sequences guard rejected + temporal clauses; the ordinary template could not represent mixed durations + or a per-note cross-bar PH. +- After: complete recognized range/hold clauses are consumed before that guard. + Numeric positions produce the plan mathematically. Unrelated from/to tempo + changes, then/sequences, unsupported prose and embellishments still fail. + Existing simple global templates use the original composition path. +- Exact original wording is sent verbatim through real source stdio and a fresh + noneditable installed wheel, with only basename and allow_midi_fallback=false. + Formats/profiles/key/tempo/parts are NOT supplied as corrective overrides. + Both return complete success with automatic mid+griff, lead only, E minor, + the real default AME ID and no fallback or drum project. + +Returned assumptions +- A is the final eighth-triplet COUNT, not an A-pitch instruction. +- The PH is one continuous note through ALL of measure 2, without retrigger. +- Low tonic nearest MIDI40 within selected profile range/tuning; default Em + produces E2/MIDI40 for every musical note, including the PH. +- Tempo omitted: documented 120 quarter-note BPM. +- Length omitted: the hold implies two bars, eight quarter beats. + There are no invented melodies, transpositions, CC91 or effects. + +Exact observed acceptance, independently parsed from saved files +All musical notes: MIDI pitch40; native string6, fret4. + +Index Technique MIDI960 on/off Native480 Begin/End Velocity +1 PM 0 / 480 0 / 240 80 +2 PM 480 / 960 240 / 480 80 +3 PM 960 / 1440 480 / 720 64 +4 PM 1440 / 1920 720 / 960 80 +5 PM 1920 / 2400 960 / 1200 96 +6 PM 2400 / 2880 1200 / 1440 80 +7 PM 2880 / 3200 1440 / 1600 80 +8 PM 3200 / 3520 1600 / 1760 80 +9 PH 3520 / 7680 1760 / 3840 80 + +- Six durations 1/2, then two durations 1/3, then PH duration 13/3 quarter beats. + No rounding: MIDI durations 480 x6, 320 x2, 4160; native exactly half. +- Exactly nine musical note-ons: eight PM plus one PH. No musical onset at + MIDI3840/native1920; no split, second-measure attack or bar-boundary retrigger. +- MIDI selectors: PM=D0/26 on0/off30; PH=G0/31 on3520/off3550; velocity100. + Selector-before-musical-note ordering is independently checked. + Zero lead, 1/32-quarter positive pulse gates, channel0, latched state and + interpolation are explicit generator POLICY, not vendor timing guarantees. + Total MIDI note-ons = 11 including two switches, not eleven musical notes. +- MIDI type1, PPQ960, Conductor/Lead tracks, 120 BPM, 4/4, common EOT7680. + Existing writer does not emit a key-signature meta event; E minor is verified + in resolved metadata/native key Em and actual low-tonic pitch40. +- Native Riff XML: AME, PPQBase480, Measures2, 4/4, loopEnd3840, Key Em; + eight actual PM labels and one actual PH label. Final End3840. +- Zero MIDI CC events, zero program changes and no fabricated native CC lane. + Existing native ccName metadata is not a generated CC event. +- Native saved-file validator is also run against the requested typed score + and compiled events, in addition to independent Mido/XML numeric assertions. + +Source and installed-wheel output bytes are identical +phrase-original.mid: 168 bytes +SHA256 c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62 +phrase-original_lead.griff: 1701 bytes +SHA256 e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c + +Persistent ORIGINAL authored acceptance evidence only under: + .test-artifacts\step12\source\ + .test-artifacts\step12\installed-wheel\ +Each contains the original MIDI/griff and independently checked evidence.json. +Full final suite output: .test-artifacts\step12\full-suite.txt. +No requested riff was published outside test artifacts. + +Nearby variants / invalid requests +- Original with 1-to-3& changed to 2-to-3& works through BOTH real transports. + Musical starts: 960,1440,1920,2400,2880,3200,3520; PH still ends7680. + Four straight PM eighths, two PM triplets and one continuous PH: seven notes. +- Another unit variant changes range to 1-to-2& and triplets to beat3. + Starts: 0,1/2,1,3/2,2,7/3,8/3; final duration16/3, end8. + This independently demonstrates computed range and triplet positions. +- Overlapping 1-to-4 range and a one-bar score return UNSUPPORTED_DESCRIPTION + on source and wheel, without publishing directories or leaving owned stages. +- Tests reject reversed/out-of-bar labels, extra &, fractional beat labels, + duplicate clauses, invalid meter, too-short explicit length, other parts, + unsupported techniques/prose and unrelated tempo changes. +- Explicit longer scores keep the phrase ONCE with trailing silence. + Structured scalar overrides cannot erase notes or invalidate the hold. + +Native PH evidence verified before declaring support +- Read-only AME.vst3 ProductVersion check: 4.0.1. +- Read-only aggregate of 35 local .griff files under the requested AME Presets + folder: 17 genuine Articulation PH notes, velocities80-100, NoteID49-73. + Those observations establish encoding, NOT hard PH pitch/velocity limits. + No factory sequences, filenames, assets or manual copies entered source, + tests, retained artifacts or external uploads. +- Official https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf was fetched + and parsed entirely in memory with the already installed pypdf. + Page6 section2.2.1 lists PH: G0, C1-C5; page9 section2.2.9 confirms G0. + Established vendor octave mapping C0=24 gives G0=31 and C1-C5=36-84. + Thus generated E2/MIDI40 is within documented PH range even though below + the local factory aggregate's observed pitch minimum49. +- PH uses dedicated G0/31, NOT normal-C0 velocity127 or a softer PM substitute. + Positive musical velocities1-127 and interpolation are declared generator + policy, not invented vendor PH layers or factory-observed hard bounds. + Native guards reject wrong PH switch/label, arbitrary labels and bass PH. + +Preservation / safety +- Step11's simple lead quarter-note recovery remains BYTE-identical: + MIDI SHA256 922d4c30e4618b6cce61a2ecebb36193773ca3884e56db80f7c18fe18e813f26 + griff SHA256 213adde1c4785dccd2289e6888328c16bca720fb8d2786edb4df34f3863d1c2f + Both source and wheel tests assert these previously recorded baselines. +- Ordinary defaults/patterns, strict request/private feedback, integer/finite + checks, profile identity/ranges, string assignment, shared duration, stable + ordering and source/installed discovery regressions pass unchanged. +- Explicit CC1/CC91 on the held phrase survives the compiler exactly as asked; + it is never inferred, silently removed or reset. Existing native CC limits, + fallback=false failures, combined event budget and atomic/root safety tests + continue to pass. Unrequested original acceptance contains no controls. +- Both note-pair and compiler budgets (including switch events) are tested. + Mutated invalid plans/profiles fail defensively rather than approximating. +- No dependency manifests changed, no new dependencies were installed. + Existing distribution tests build/install the requested project wheel + noneditably and verify all 16 module origins outside the source checkout. + +Executed final validation +Interpreter: repository .venv, Python3.13.13. +1. Focused parser/composer/Riffer/phrase source-stdio command: + python -m pytest tests\unit\test_phrase_timing.py + tests\unit\test_description.py tests\unit\test_compose.py + tests\unit\test_riffer.py tests\integration\test_phrase_stdio.py -q + PASS: 286 tests in 2.99s. +2. Complete current suite: python -m pytest -q + PASS: 1502 tests in 63.15s; no failures/skips. + Includes real source and noneditable installed-wheel stdio, actual saved + MIDI/native comparisons, private errors, explicit CC and atomicity tests. + The expanded installed native process has 23 expected protocol stdout lines, + exits0, and has empty diagnostics; source phrase also exits0/empty stderr. +3. python -m ruff check src tests: PASS, all checks passed. +4. python -m ruff format --check src tests: PASS, 50 files already formatted. +5. python -m mypy src tests --strict: PASS, 50 source files, no issues. +6. python -m pip check: PASS, no broken requirements. +7. Editor diagnostics for changed source/new tests: no errors. +8. git diff --check: PASS. +9. Retained source/wheel evidence JSON and actual file hashes were independently + compared and are identical. + +Issues encountered and resolved +- Test discovery tool reported no discovered tests; actual pytest CLI runs + supplied all focused/full validation, not a claim based on editor discovery. +- Initial precise-parser test caught acceptance of an extra &, due to existing + separator policy. Tightened the numeric range boundary; rejection now passes. +- Initial register field name shadowed a Pydantic base attribute; renamed it + register_policy. No runtime warning remains. +- New independent tests initially assumed omitted null profile fields and an + existing MIDI key-signature event. Corrected those test assumptions to the + actual preserved contract; no unrelated writer/protocol change was made. +- Initial format checks identified long/new expressions; final format/lint and + strict type checks are clean. No unresolved implementation blocker. + +Unsupported limits / readiness +The expanded text grammar remains deliberately bounded to the documented +lead-only 4/4 range-plus-triplet/cross-bar-PH phrase. It is NOT arbitrary +melodies, sections, arbitrary triplet prose, tempo/meter changes, legato or +effects; no bass/drum/standard PH support is implied. Saved-file/software +validation does not claim audible plugin/Cubase/DAW acceptance. + +Ready for review and the next authorized step. Stopped here: no commits, +delegation, later prompts, LM Studio data/configuration, app/UI manipulation +or DAW edits. Pre-existing accepted Step11 work has been preserved. +``` diff --git a/prompts/report_13.md b/prompts/report_13.md new file mode 100644 index 0000000..94c2e2d --- /dev/null +++ b/prompts/report_13.md @@ -0,0 +1,338 @@ +``` +Step 13 — COMPLETE: 0.1.1 LM Studio recovery / precise-riff patch acceptance +Date: 2026-10-20 + +RESULT +PASS: authoritative version 0.1.1, refreshed editable application metadata, +final wheel/sdist, EXACT persisted-wheel stdio acceptance outside checkout, +text-only recovery, original phrase/native/MIDI verification, full checks. +Ready for the orchestrator's final user-file-generation request after review. +The Step13 worker created no user-facing output. Final orchestrator acceptance +is recorded below. No unresolved implementation blocker. +Live LM Studio/model/UI and plugin/Cubase/audio acceptance remain UNRUN. + +PATH DEFINITIONS +R = D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder +A = D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder\.test-artifacts\lmstudio-fix-0.1.1 +All R\ and A\ references below expand to these exact absolute Windows paths. +Outside-checkout launch/independent-verifier cwd: + D:\_Repos\Code\GAJ3T\MCPs\MusicGen +Interpreter: R\.venv\Scripts\python.exe +Report: R\prompts\report_13.md + +IMPLEMENTED +- Only src\riff_groove_builder\__init__.py authors the package version: 0.1.1. + pyproject.toml continues deriving setuptools metadata from that attribute. + Runtime MCP initialization uses that same source. Tests now require 0.1.1 + package/metadata agreement and assert real source/wheel handshake versions. +- Refreshed ONLY the editable application, offline: + python -m pip install --disable-pip-version-check --no-cache-dir --no-index + --no-deps --no-build-isolation -e . + Existing 0.1.0 application metadata was replaced with 0.1.1; runtime/dev + dependencies were NOT reinstalled. No dependency manifest/ranges changed. + No global install, dependency restore, new tool or dependency was required. +- Distribution tests accept RIFF_RELEASE_DIST for an exact already-persisted + pair under R\dist, without rebuilding/substituting another wheel. Normal + unset-variable behavior still builds its own offline wheel from its sdist. + Installation remains noneditable, no-index/no-deps/no-cache-dir. +- Retained current source/wheel original phrase and simple-recovery evidence + under the new version-specific A path, not by replacing Step12 evidence. + Original phrase acceptance now sends ONLY description and basename. + Nearby/error cases additionally exercise allow_midi_fallback=false. + Numeric event assertions remain independent of the composing code; original + phrase hashes are also pinned to independently recorded Step12 baselines. +- README now documents LM Studio mcpServers, not VS Code servers/type, + absolute Python/args, required already-existing output root, actual suffixes, + exact verbatim minimal original JSON, defaults, grammar/interpretation limits, + no invented profiles/CC91, and restart plus fresh-chat remediation. + Updated current compatibility documentation; old reports remain history. + Official configuration reference checked: + https://lmstudio.ai/docs/app/mcp + All seven README JSON blocks parse and pass their executable checks: + one LM Studio config, four tool requests, two output payloads. + Requests pass actual JSON schemas, typed resolution, mapping and compilation. + LM Studio config is checked separately as launch configuration, not falsely + passed to the generate_music schema or claimed as a live-client test. + +FINAL DISTRIBUTIONS — DO NOT CONFUSE WITH OLD 0.1.0 ARTIFACTS +Wheel: + D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder\dist\lmstudio-fix-20261020\gaj3t_musicgen_riff_groove_builder-0.1.1-py3-none-any.whl + 82175 bytes + SHA256 1d72dce98c775f958288049fde008e4d2bb4bab12bf858bf53f8b0231781b540 +Sdist: + D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder\dist\lmstudio-fix-20261020\gaj3t_musicgen_riff_groove_builder-0.1.1.tar.gz + 97774 bytes + SHA256 04ec8bda391d7170b69c7bbd6309f68277d8081f98f6c44cba953a229d7258ae + +Built offline using existing tools: + python -I -B -m build --no-isolation --outdir dist\lmstudio-fix-20261020 +The default build produced the wheel FROM the sdist, not just directly from +the checkout. A\build.txt records the successful final build. +Independent audit: wheel26 entries, sdist31 files, six production JSON profiles. +Every packaged source/profile byte matches current source; README/pyproject +in the sdist match current files. Other members are packaging metadata only. +No private template, chat, kit/song, factory music, licensed manual, audio, +generated MIDI/native output, venv, test artifact or report is packaged. + +EXACT PERSISTED-WHEEL ACCEPTANCE +The full final pytest run set: + RIFF_RELEASE_DIST=R\dist\lmstudio-fix-20261020 +Thus both isolated wheel imports and the real server test installed the exact +wheel path/hash above; no alternate generated wheel satisfied these checks. +Wheel SHA256 was checked unchanged after the real server run and independently. +Evidence: A\installed-wheel\distribution-acceptance.json + +- Fresh separate venv imports verified package file, metadata version 0.1.1, + silent import and no server/MCP import side effects, outside the checkout. +- Real installed server reused existing dev-venv dependencies but loaded ALL + 16 package/module entry locations and all six resources from its noneditable + install target, not R\src or the editable package. + Launch used -I -B with cwd D:\_Repos\Code\GAJ3T\MCPs\MusicGen. + This is not a fresh full dependency-installation certification. +- Actual newline-delimited JSON-RPC initialize negotiated 2025-11-25, named + riff-groove-builder/version0.1.1; tools/list returned exactly + list_instrument_profiles and generate_music with actual input/output schemas. +- Text-only decisions used json.loads(content[0].text), including readable + profile IDs and safe field/reason/correction messages. For success and all + exercised domain/validation failures, exactly one complete TextContent JSON + equals structuredContent and passes the actual output schema. +- Wrong lead sd3p/mid request returned INVALID_REQUEST / formats / format_parts + with explicit guitar-vs-drum format correction. No files were published. + Removing wrong formats and unsolicited CC91 exposed PROFILE_REQUIRED with + safe list-profiles/default guidance, no echoed invented profile value. + Arbitrary unsupported triplet prose returned UNSUPPORTED_DESCRIPTION. + Selecting the visible real AME ID and key Em recovered to complete + mid+griff; key normalized to E minor, no fallback, four musical notes and + one keyswitch, zero CC91. Old simple-output hashes remain exact. +- Source recovery also used a real independently launched stdio child, + version0.1.1, six valid stdout messages, exit0, empty stderr. + Source original phrase: five valid stdout messages, exit0, empty stderr. + Source transport records: + A\source\text-transport.json + A\source\phrase-transport.json +- Installed no-template/main process: 20 valid protocol stdout messages, exit0; + intentionally malformed-protocol privacy case emits only its expected + sanitized SDK diagnostic, never private input. Uninitialized EOF also exits0. + Installed native/CC/original-phrase process: 23 valid stdout messages, + exit0, EMPTY stderr. It also exercised original-template native sets, + aliases/actual suffixes, MIDI-only, exact CC, fallback and no-overwrite. + Temporary install/venv/output workspaces were cleaned after acceptance. + JSON origins/paths under distribution-70726b2645ec41ed921c5400fc9331db describe + that completed transient run, not currently retained installations. + +VERBATIM ORIGINAL PHRASE — NO CORRECTIVE MUSICAL OVERRIDES +Description sent exactly, with these line breaks: +Please produce a 4/4 riff in Em. With Chugging palm muting 8th notes from 1 to 3&; +and triplets on 4&A with the A as a pinch harmonic that carries over a whole note +in the 2nd measure. + +Only other argument: basename="phrase-original". +No explicit parts, format, profile, key, tempo, bars or CC. Automatic result: +complete; lead only; default ample.ame.4.0.1.riffer.v1; E minor; two bars; +120 quarter-note BPM; mid+griff; no fallback/drum file/control/program event. + +Both source and installed-wheel original files persist: + A\source\phrase-original\phrase-original.mid + A\source\phrase-original\phrase-original_lead.griff + A\installed-wheel\phrase-original\phrase-original.mid + A\installed-wheel\phrase-original\phrase-original_lead.griff +Each directory also contains independently checked evidence.json. + +Source and installed bytes are IDENTICAL, and unchanged from Step12: + phrase-original.mid — 168 bytes + SHA256 c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62 + phrase-original_lead.griff — 1701 bytes + SHA256 e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c + +Independent saved MIDI/XML numeric results: +Index Art MIDI960 on/off Native480 Begin/End Pitch Velocity +1 PM 0 / 480 0 / 240 40 80 +2 PM 480 / 960 240 / 480 40 80 +3 PM 960 / 1440 480 / 720 40 64 +4 PM 1440 / 1920 720 / 960 40 80 +5 PM 1920 / 2400 960 / 1200 40 96 +6 PM 2400 / 2880 1200 / 1440 40 80 +7 PM 2880 / 3200 1440 / 1600 40 80 +8 PM 3200 / 3520 1600 / 1760 40 80 +9 PH 3520 / 7680 1760 / 3840 40 80 + +Exactly eight PM plus one PH; no MIDI3840/native1920 onset/bar2 retrigger. +Six straight eighths then three triplet attacks; final PH duration4160 MIDI +ticks = 13/3 quarter beats. Native uses exactly half every MIDI time. +MIDI type1, PPQ960, Conductor/Lead, 4/4, tempo500000us, both EOT7680. +Keyswitches: PM26 on0/off30; PH31 on3520/off3550, channel0/velocity100, +each ordered before its corresponding musical note. Eleven total note-ons +INCLUDE the two switches; there are NINE musical note-ons, not eleven. +Native Riff/AME/PPQBase480/Measures2/KeyEm/loopEnd3840, all string6/fret4, +eight actual PM labels and one actual PH label. No fabricated native CC lane. +The existing MIDI writer has no key-signature meta event; resolved/native Em +and actual pitch40 verify tonic/key, not an invented MIDI meta-event claim. + +Independence beyond producer read-back: + A\verify_release.py ran with -I -B from the outside-checkout cwd above, + using Mido/ElementTree/hashlib, WITHOUT importing riff_groove_builder. + It checked the retained actual files, exact build bytes/provenance, source + versus installed equality, selector ordering and preservation snapshots. + PASS; A\independent-verification.json and .txt retain results. +Nearby computed 2-to-3& range and overlap/too-short rejection also pass through +both real transports, without stray stage directories or error publications. + +RETURNED ASSUMPTIONS / LIMITS +- count-A is the FINAL COUNT of the eighth-note triplet, not the pitch A. +- The final PH is ONE continuous note through ALL of measure2, no retrigger. +- Register is the playable low tonic nearest MIDI40 within profile range/ + tuning; default Em/AME is E2/MIDI40, not an invented melody/transposition. +- Omitted tempo is 120 quarter-note BPM; omitted bars resolve to two here + because the phrase implies the measure2 hold, not the ordinary four-bar default. +- PM/PH selector zero lead and positive30-tick pulse gates are explicit generator + policy, not a promise about plugin response. No profile/effect/CC is inferred. +- Bounded lead-only 4/4 range-plus-triplet/PH grammar, not arbitrary prose, + melodies, arbitrary triplets, changing tempo/meter, sections, audio or legato. + Only AME has evidenced PH; bass/SD3/standard profiles have not gained PH. + griff/briff/sd3p are actual native suffixes; agp/sdp are request aliases. + A matching operator-local SD3 template is necessary only for native drums. + +OLD SIMPLE / NO-PHRASE MUSICAL BYTES PRESERVED +Source AND installed text-recovery originals: + A\source\text-recovered\ and A\installed-wheel\text-recovered\ + text-recovered.mid — 117 bytes + SHA256 922d4c30e4618b6cce61a2ecebb36193773ca3884e56db80f7c18fe18e813f26 + text-recovered_lead.griff — 1014 bytes + SHA256 213adde1c4785dccd2289e6888328c16bca720fb8d2786edb4df34f3863d1c2f + Four native/musical quarter notes, one MIDI keyswitch, no controls. +Ordinary installed three-part standard request, explicit/default/native-fallback: + 324-byte MIDI SHA256 + 7d61b8d4a8c42a19091126ce7301b159744bbae4e78456b0cd1894f6269aea4b +Ordinary native-target no-control baselines still match Step10: + MIDI336bytes: + 8fc4cfbe66c0706f223ec33a61692ead046a56a9dba51c6566f967690cee186c + griff1296bytes: + fe7a2a5c98d0ae16f6894e681e7f001a658c90d11b3f1beb313d5c98b6c810c9 + briff1282bytes: + 5da9b05e92e6989366f41f8abf22a0f8b88ae14591bc8b544e4c7c0cf47827c4 + synthetic-template sd3p1491bytes: + 8bee8a86a7e60320d02c4404e36d818639af1d8f4ebce27f6c23a25e7ebd0589 +Existing tests assert the native-target no-control baselines; no weakened +assertions, blanket skips or unsupported approximations were introduced. + +FINAL EXECUTED VALIDATION +Windows11/build10.0.26200/AMD64; repository CPython3.13.13. +Only this runtime was executed; declared Python>=3.11 is not multi-runtime +certification. Existing runtime mcp1.30.0 / pydantic2.14.1 / mido1.3.3. +1. Focused version/docs/source recovery/phrase checks: + python -m pytest tests\unit\test_package.py tests\unit\test_readme.py + tests\integration\test_text_feedback.py tests\integration\test_phrase_stdio.py -q + PASS: 15 tests in1.98s; A\focused-suite.txt. +2. FINAL full current suite: python -m pytest -q + RIFF_RELEASE_DIST=R\dist\lmstudio-fix-20261020 + RIFF_SD3_TEMPLATE=C:\Users\g3\Documents\Toontrack\Superior Drummer 3\sd3-demo.sd3p + PASS: 1503 passed in61.86s, ZERO failures/skips; A\full-suite.txt. + Includes all current parser/normalization/text-only, native/MIDI/CC/template, + privacy/sanitization, corruption, event-budget, filesystem/root/junction, + concurrency/atomic publication and installed-wheel regressions. +3. python -m ruff check . — PASS, all checks passed. +4. python -m ruff format --check . — PASS, 94 files already formatted. +5. python -m mypy --strict src tests — PASS, 50 source files/no issues. +6. python -m pip check — PASS, no broken requirements. + Static/dependency results retained in A\checks.txt. +7. Editor diagnostics for release-touched Python files — no errors. +8. git diff --check — PASS. +9. Independent isolated outside-checkout persisted-file/archive/preservation + verification — PASS, no application-package import. + +PRESERVATION / PRIVACY / CLEANUP +Independent before/after check: ALL25 snapshotted files unchanged in hash, +size, identity and mtime: 17 pre-existing historical reports, seven source +fixtures/templates, and the genuine local SD3 reference below. + C:\Users\g3\Documents\Toontrack\Superior Drummer 3\sd3-demo.sd3p + size75393; inode166633186213030518; mtime_ns1788614183091903900 + SHA256 06f54b02079e4b32d532ecc232b813c3fe1865799e6f5b2b21b5ddf398b0533d +Local-template tests were opt-in-enabled and READ-ONLY. They preserve non-song +kit/mixer/tracker state; none enters source or distributions. +Other local musical/factory references were not modified or copied. No private +chat, manual or factory asset was read/exported as part of this release work. +Accepted Step11/12 implementation remains present; previous reports were +NOT rewritten and their original Step12 evidence was not overwritten. + +A\preservation-before.json retains the25-file baseline. +A\source-manifest.json covers71 current package/test/fixture/docs/README/ +pyproject/.gitignore files, excluding reports and ignored build/test artifacts. +SHA256 of sorted compact JSON path->file-SHA256: + f6d73d0a3a6ad6c3d72398f8fbe34dcf317baf4a22d228a7b8d2a2ca7e9d1a66 +Final build/module/resource provenance is independently checked against source. +Owned failed/intermediate initial distributions were removed. Test stdio +children exited0 and transient installation/build/output workspaces were +cleaned by fixtures. Final distributions, clearly named original evidence, +logs/verifier/manifests and this report remain. +No unrelated files were deleted; no user output file was replaced. + +ISSUES ENCOUNTERED AND RESOLVED +- Editor test discovery returned no tests; actual pytest CLI supplied focused + and full execution. No success was inferred from editor discovery. +- Initial new test string/assertion layout needed Ruff line wrapping. + Fixed before the final build, then rebuilt the final pair and passed all + static/full checks. Superseded owned build pair was removed. +- Independent archive probe initially assumed LF-only wheel METADATA. Actual + metadata uses platform line endings; switched to the standard email metadata + parser. Verified actual Version=0.1.1; no package-byte alteration was needed. +- No unresolved implementation, dependency, musical-event or privacy blocker. + +OPERATOR-REQUIRED STARTUP / FINAL GENERATION HANDOFF +Do NOT treat an already-running MCP process or existing LM Studio chat as proof +that the new package/schema is in use. The operator must: +1. Use LM Studio's Program -> Install -> Edit mcp.json if configuration is needed; + use README's mcpServers example with the repository venv Python and an + already-existing output root. Do not substitute VS Code servers/type JSON. +2. RESTART the LM Studio MCP SERVER after this update. +3. START A FRESH CHAT; rediscover tools/profiles and verify initialization + version0.1.1. Old chats may retain cached schema/description/failed assumptions. +4. Only after review, issue the final original request using minimal supported + arguments. Do not invent aggressive_rock, lead sd3p, CC91 or other effects. +The operator/orchestrator performs those actions; this task did NOT restart, +edit or manipulate LM Studio, any active chat/config/process, Cubase or DAW. +Software stdio/filesystem success is NOT live LM Studio/model, audible +plugin/native import/play/save/reload, routing or Cubase acceptance. + +READY: final user-file generation can proceed on the verified 0.1.1 build +after orchestrator review and the operator's restart/fresh-chat requirement. +No files were generated under D:\MusicGenOutput in Step13. +Stopped here: no commits, delegation, later prompts, user-output generation +or application/configuration/process/DAW manipulation. + +ORCHESTRATOR FINAL USER-FILE ACCEPTANCE + +After reviewing the complete report, independently reran the full current suite +against the exact persisted 0.1.1 release pair: + 1503 passed in 60.82s, zero failures/skips. +Ruff lint/format, strict mypy and pip check also independently passed. +Source and installed metadata both report version 0.1.1. + +A NEW real stdio child, launched outside the checkout with the user's configured +output root and unchanged optional SD3 template, initialized as 0.1.1. +TextContent JSON matched structuredContent for profile discovery, a deliberate +lead+sd3p error, and the actual successful original-description request. +Wrong format identified formats with a correction; it published no directory. +The original description was sent verbatim, without invented profile/format/ +CC parameters; allow_midi_fallback=false ensured actual native success. + +Actual user-facing outputs, exclusively created and independently reopened: +D:\MusicGenOutput\em_chug_triplet_ph_20261020_030601\ + em_chug_triplet_ph_20261020_030601.mid + 168 bytes + SHA256 c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62 + em_chug_triplet_ph_20261020_030601_lead.griff + 1701 bytes + SHA256 e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c + +Independent Mido/ElementTree checks confirmed: + E minor, E2/MIDI40, 120 BPM default, 4/4, two measures. + 9 musical notes = 8 PM + 1 PH; no bar2 retrigger. + MIDI onsets 0,480,960,1440,1920,2400,2880,3200,3520; PHoff7680. + PM26 and PH31 selectors ordered before musical onsets. + Native PPQ480, exact half-timings, PM/PH labels, string6/fret4, PHend3840. + No CC91, other CC/program events, fabricated drum artifact or sidecar. +The source SD3 template's identity/size/mtime/hash remained unchanged. +The test child was closed cleanly. The existing LM Studio server/chat, +configuration, model and Cubase session were NOT manipulated or restarted. +Operator restart plus a fresh LM Studio chat remain required to use 0.1.1 there. +``` diff --git a/prompts/report_14.md b/prompts/report_14.md new file mode 100644 index 0000000..8d563a9 --- /dev/null +++ b/prompts/report_14.md @@ -0,0 +1,249 @@ +``` +Step 14 — COMPLETE: reusable explicit pitch/chord and exact polyphonic attacks +Date: 2026-10-20 + +RESULT +Implemented and verified the internal foundation, with actual MIDI and .griff +publication/read-back. Ready for Step15 work after review. No full lane parser, +public score tool, arbitrary chord-prose claim, slide semantics, later prompt, +application manipulation, commit, delegation, dependency or version change. +Package version remains the accepted 0.1.1. No release artifacts refreshed. + +READ / PRESERVATION +Read step_14, current plan, accepted reports11-13, schemas, composer, profiles, +compiler, service/native fallback policy, native writer/validator and tests. +Pre-edit phrase/composer baseline: 87 passed in 1.10s. +Preserved the existing dirty accepted 0.1.1 changes rather than resetting them. +85 existing tracked source/test/doc/manifest and report files were hashed +before edits; 82 remain identical. Only these baseline files changed: + src\riff_groove_builder\schemas.py + src\riff_groove_builder\compose.py + docs\architecture.md +Added pitch.py, test_pitch.py, test_explicit_plan.py, test_explicit_music.py, +and this report. Existing profiles/tunings, compiler/native/service behavior, +public tool schemas/descriptions, version, dependencies and old tests remain +unchanged by this step. Preservation manifests and pre-edit status: + .test-artifacts\step14\preservation-before.json + .test-artifacts\step14\preservation-after.json + .test-artifacts\step14\status-before.txt + +REUSABLE INTERNAL APIS +riff_groove_builder.pitch: + PitchToken(letter, accidental="", octave=None) + ChordSymbol(root, quality="major", add4=False, bass=None) + ExplicitVoicing(notes: tuple[PitchToken, ...]) + NotationToken(value, text, start, end, leading_space) + ResolvedVoicing(pitches: tuple[int, ...], assumptions: tuple[str, ...]) + parse_pitch(text) -> PitchToken + parse_chord(text) -> ChordSymbol | ExplicitVoicing + tokenize_notation(text, *, kind="note" | "chord") -> tuple[NotationToken, ...] + resolve_voicing(value, profile) -> ResolvedVoicing + validate_voicing(pitches, profile) -> None + +riff_groove_builder.schemas: + ExplicitAttack extends TimedNote: + start, duration, technique, optional intensity, unique MIDI pitches + ExplicitAttackPlan: + part, duration, ordered attacks, optional disclosed assumptions + MusicalIntent.explicit_plan: + optional internal plan, separate from legacy low-tonic PhrasePlan + +Existing compose_score(intent, profiles, ppq=960) consumes explicit plans. +compile_score, write_midi, write_riffer, saved-file validators and the real +GenerationService publication/fallback path are reused, not replaced. +Integration tests inject an internal DescriptionResolution to reach that +path; this is explicitly NOT evidence of public chord/lane prose parsing. +Architecture documentation describes APIs, policy and this boundary. + +PITCH / CHORD / TOKEN POLICIES +- Uppercase A-G, optional one ASCII #/b, optional signed octave. + C4=60, E4=64, G4=67; C-1=0, G9=127; C+4=60. + Accidental rollover is correct: Cb4=59, B#3=60. + Enharmonic spellings preserve numerical meaning, not forced sharp spelling. + Malformed/double/Unicode accidentals and out-of-MIDI explicit notes fail. + Missing octave stays None; accessing .midi before resolution fails. +- Bare root means major; m/min means minor. Root octave follows quality. + F# -> [42,46,49], D -> [38,42,45], Bb -> [46,50,53] on target lead. + F#3 -> [54,58,61]; Bb2 -> [46,50,53]; Em4 -> [64,67,71]. + Major intervals [0,4,7]; minor [0,3,7]. + Parenthesized (add4) adds interval5, retaining third and fifth: + Em(add4) -> [40,43,45,47] + Em4(add4) -> [64,67,69,71] + E4(add4) -> [64,68,69,71] + Digits are octaves, not seventh/extension qualities. Unsupported quality + syntax is rejected rather than guessed. +- Missing note/root octave chooses the playable root nearest MIDI40 for the + selected profile range/tuning; lower wins ties. The exact MIDI choice and + profile are disclosed in ResolvedVoicing.assumptions. The root is selected + BEFORE constructing the chord: no alternate octave search to rescue a chord. +- Em4/B2 and Em4OverB2 -> [47,64,67,71]. + Em4/B and Em4OverB -> [59,64,67,71]. + Missing bass octave means the nearest matching pitch STRICTLY BELOW the + lowest upper-chord tone; the MIDI59 default is reported. + Explicit equal/higher bass (Em4/E4, Em4/B4) fails, never gets moved. +- Explicit [C3 E3 G3] -> [48,52,55]; pitches are sorted without changing + octaves. Explicit duplicate/enharmonic duplicate pitches are rejected. + Computed chord pitches are deduplicated. No key-based correction exists. +- A complete voicing must fit MIDI/profile bounds and individually evidenced + tuning positions. No dropped tone, arbitrary revoicing, octave spreading, + key retuning or fabricated native success. Simultaneous physical allocation + remains native preflight's responsibility. +- Deterministic compact lexing handles F#F#, DD, BbBb, CEG, C4E4G4 and + concatenated qualified chord atoms. Exact offsets and leading whitespace + preserve boundaries/spacing; spacing is NOT interpreted as duration. + Note mode and chord mode are separate: C4 means a note versus major root. + Unknown/ambiguous leftovers fail; notation input is bounded to 4000 chars. + No whole-example match or canned musical-output branch was introduced. + +PLAN / COMPOSITION POLICIES +- Exact reduced nonnegative rational starts and positive rational durations; + unique 0-127 integer pitch sets, finite optional intensity0-1, techniques + normal/palm_mute/pinch_harmonic only. +- One pitched part per plan; sole selected part, sufficient bars/meter, no + competing legacy phrase or global rhythm/technique instruction. +- Start-ordered attacks, score-bounded ends, maximum16384 quarter beats. + Independent same-pitch overlaps fail; half-open adjacent repeats are valid. + Different pitches may overlap with compatible shared technique. Conflicting + simultaneous profile-wide techniques fail rather than silently changing. +- All chord tones become independent simultaneous PitchedNotes, keeping exact + start/duration and explicit pitches even when outside the intent's key. + Explicit intensity wins; otherwise existing seeded intensity policy uses + one draw per attack, shared by chord tones, with the existing bass offset. +- Gaps represent silence and one attack's duration represents uninterrupted + sustain. Rest/continuation lane tokens are not parsed or guessed. + Later continuation parsing must extend the original attack, not retrigger. +- Expanded note-on/off pairs share the100000 scheduled-event budget. + Explicit composition invokes the authoritative compiler to include actual + articulation controls, not merely count chord tokens. Tests prove six + tones consume12 events on the standard profile and14 with the target's + selector; the latter fails a test ceiling12. Seven tones already exceed12 + before controls. Existing explicit-CC combined-budget enforcement is retained. +- Grids, real selected-profile techniques, mutated-plan revalidation and + profile range/tuning are checked; slides remain unsupported. + +ACTUAL MIDI / NATIVE MUSIC CHECKS +Four independently published original plans cover / and Over aliases, each +with explicit B2 or default B3 bass. Intent is D minor, but the F# major +chord's [66,70,73] is preserved exactly; there is no key correction. + +Attack MIDI960 on/off Native480 Begin/End Pitches +Em4/B2 or OverB2 0 / 640 0 / 320 47,64,67,71 +Em4/B or OverB 0 / 640 0 / 320 59,64,67,71 +[C3 E3 G3] PM 960 / 1280 480 / 640 48,52,55 +F#4 major normal 1280 / 1920 640 / 960 66,70,73 +C4 single PH 1920 / 3840 960 / 1920 60 + +Each saved plan has exactly: + 4 attacks, 11 independent musical tones, 11 native Note elements. + 4 MIDI selector-ons: (tick,pitch)=(0,24),(960,26),(1280,24),(1920,31). + Selector velocity100 and gate30 ticks;15 total MIDI note-ons. + 30 scheduled events including all musical/selector note-offs. + Musical velocities95,32,110,127 by attack. + Zero CC/program events and no fake native CC lane. + MIDI type1, PPQ960, Conductor/Lead tracks, common EOT3840. + Native Riff AME, key Dm, PPQ480, loopEnd1920, Sus/PM/Sus/PH labels. + Exact thirds, uninterrupted PH ending at score end, no dropped chord tone. + +Independent Mido and ElementTree parsing compares saved numerical pitches, +begins/ends/velocities/labels against authored expectations. Native checks +derive every pitch from the unchanged tuning plus fret, enforce frets0-22, +no occupancy overlap per physical string, and four distinct strings for the +opening four-tone chord. Producer saved-file validators also pass. +Actual opening physical assignments, written as pitch=string/fret: + B2 case: 47=5/4, 64=3/11, 67=2/10, 71=1/9 + B3 case: 59=2/2, 64=4/16, 67=3/14, 71=1/9 +Remaining assignments: + [48,52,55] -> 4/0,5/9,3/2 + [66,70,73] -> 2/9,3/17,1/11 + 60 -> 2/3 +No vendor tuning/map changed to make these fit. + +Persistent final full-suite evidence under .test-artifacts\step14\: + explicit-e9b2540d542d48c4b041af85459c0a63 — Em4/B2 + explicit-33adb31397b541e6a79ce9606fd63485 — Em4OverB2 + explicit-0701890c8372424e9b460098fc86d3a0 — Em4/B + explicit-487d819893344859b4297c551dda8901 — Em4OverB +Each contains chords\chords.mid, chords\chords_lead.griff and evidence.json +with actual pitch/time/string/fret/count/size/SHA256 values. +All MIDI files178bytes; all griff files2018bytes. +B2 / and Over aliases have identical bytes: + MIDI d3f7b10e92a1ca228602a94add3cc6eec1a4f7d482b8527d23d936d98100a9d1 + griff1547b32fb666f8006547cf89f391ea613db05c4e78273f940f4542e354115a60 +B3 / and Over aliases have identical bytes: + MIDI 38a3b247bdee334f04c072f651645d205588dc820fb2ce84ae4202482c5f5f02 + griff80c3a770a45accbd2de371063f2f92cd34b1b9f7a4a55b558c301112b15de838 +Redundant earlier-run copies were removed; final verified evidence retained. + +ERROR / FALLBACK / NO-OVERWRITE CHECKS +- Explicit [36,37,38] is individually in range but needs three simultaneous + notes on only the lowest physical string. Existing native preflight reports + no_physical_string_assignment. Fallback=false fails before publication. + Fallback=true returns midi_fallback and one MIDI artifact with fallback_for + ["lead"], containing ALL THREE exact pitches and their complete durations. + No .griff with omitted tones is produced. +- [35,60,64] fails as out-of-map for BOTH fallback settings, publishes nothing + and leaves a preexisting sentinel unchanged. This is not native fallback. +- Reusing a successful basename fails OutputExistsError and both actual + MIDI/griff byte strings remain unchanged. + +OLD 0.1.1 OUTPUT PRESERVATION +Real source and independently installed-wheel stdio tests still assert the +accepted musical byte baselines, including the original PM-triplet-PH phrase: + phrase-original.mid168bytes: + c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62 + phrase-original_lead.griff1701bytes: + e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c + text-recovered.mid117bytes: + 922d4c30e4618b6cce61a2ecebb36193773ca3884e56db80f7c18fe18e813f26 + text-recovered_lead.griff1014bytes: + 213adde1c4785dccd2289e6888328c16bca720fb8d2786edb4df34f3863d1c2f +Original phrase remains nine musical MIDI40 notes, eight PM plus one PH, +with the same exact starts, cross-bar PH duration and native string6/fret4. +Ordinary/native/CC/stdio/schema/service/error/atomic-write regressions pass. + +EXECUTED VALIDATION +Interpreter: repository .venv\Scripts\python.exe, Python3.13.13. +No claim of executing other supported Python versions. +1. New foundation coverage:150 unit +8 integration tests, all passing in the + final focused/full runs;158 additional tests over the accepted1503. +2. Focused new + relevant composer/phrase/text-feedback/stdio regressions: + pytest tests\unit\test_pitch.py tests\unit\test_explicit_plan.py + tests\integration\test_explicit_music.py tests\unit\test_phrase_timing.py + tests\unit\test_compose.py tests\integration\test_phrase_stdio.py + tests\integration\test_text_feedback.py -q + PASS:247 passed in3.68s. +3. Full current suite: python -m pytest -q + PASS:1661 passed in68.52s; zero failures/skips. + Includes existing offline isolated distribution and real installed-wheel + stdio checks. Those tests build/install only test-scoped project packages; + no release wheel/sdist, editable metadata or dependency was refreshed. +4. python -m ruff check . — PASS. +5. python -m ruff format --check . — PASS,99 files already formatted. +6. python -m mypy --strict src tests — PASS,54 source files/no issues. +7. Editor diagnostics on all six changed/new Python files — no errors. +8. git diff --check — PASS. +Logs: .test-artifacts\step14\focused-suite.txt, full-suite.txt, +strict-types.txt, lint.txt, format.txt. + +ISSUES ENCOUNTERED / RESOLVED +- Editor test runner found no tests; actual configured-venv pytest was used. +- Initial integration fixture incorrectly expected fallback_for=["griff"]. + Corrected to the preserved public contract's PART ["lead"], without + altering service policy or dropping the exact-pitch MIDI assertion. +- Used the existing narrow Mido import-untyped annotation convention rather + than adding stubs/dependencies. Initial lint/format findings were corrected. +- No unresolved implementation blocker. Optional genuine local SD3-template + acceptance was not configured in this run; ordinary synthetic/native SD3 + regressions passed. No user template, application, LM Studio chat/config, + DAW, plugin/audio or external output directory was manipulated. + +STEP15 READINESS / STOP +Ready: strict pitch/chord atoms and deterministic lexical tokens can feed +the exact internal attack plan, which reaches working polyphonic MIDI/native +output with truthful existing fallback and byte-preserved legacy behavior. +Still intentionally absent: full Counts/Events/Chords/Notes lane parsing, +spacing-to-time inference, public score input, arbitrary prose and slides. +Later authorized parsing must propagate register assumptions, encode +rests/continuations without guessed attacks, and preserve these constraints. +Stopped after Step14 verification/report. No Step15 prompt read or created. +``` diff --git a/prompts/report_15.md b/prompts/report_15.md new file mode 100644 index 0000000..b8dbdcc --- /dev/null +++ b/prompts/report_15.md @@ -0,0 +1,175 @@ +``` +Step 15 — BLOCKED: canonical native requirement is physically incompatible +Date: 2026-10-20 + +OUTCOME / STEP16 READINESS +NOT READY for Step16. Stopped at a demonstrated blocker, as instructed. +No Step15 public hybrid parser is shipped. Provisional implementation and its +tests were removed after the canonical native acceptance gate failed. +Accepted Step14 source/tests/docs remain in place. This is not a completion +report, not an approval to advance, and not a claim that lane descriptions +work in the restored source or installed package. + +BLOCKER +The mandatory canonical example requires two simultaneous D2 major attacks: + MIDI pitches [38,42,45], at MIDI960 ticks960 and1440, each480 ticks. + +The selected/default lead profile is ample.ame.4.0.1.riffer.v1. +Its accepted native tuning, strings6..1, is: + MIDI [36,43,48,53,57,62], maximum22 frets on every string. + +Exhaustive legal positions for the D2-major pitches: + MIDI38 -> string6/fret2 ONLY. + MIDI42 -> string6/fret6 ONLY. + MIDI45 -> string6/fret9 OR string5/fret2. + +MIDI38 and MIDI42 must sound together but require two different frets on the +same string at the same instant. No legal simultaneous assignment exists. +This is a physical contradiction, not a whitespace, octave-convention, +tokenizer, key-resolution, MIDI-grid or backtracking bug. + +Evidence sources in the preserved code: + src\riff_groove_builder\data\profiles\ + ample-metal-eclipse-4.0.1-riffer-v1.json:108-114 + src\riff_groove_builder\formats\agp.py:206-244 + _assign searches legal positions and rejects occupied-string overlaps. + The independent native reader also checks string/fret/pitch and + nonoverlapping notes on each string. + +Both the provisional public-description path and, separately, the restored +Step14 ExplicitAttackPlan -> compose_score -> compile_score -> preflight_riffer +path reproduce no_physical_string_assignment with all21 pitches preserved. +No duplicate voicing engine or whole-example canned branch was used. + +Changing the tuning/default profile, moving D2 to another octave, dropping +F#2, splitting a simultaneous chord into retriggers, emitting overlapping +impossible string notes, or accepting MIDI-only output would violate at least +one mandatory acceptance condition. None was used to claim native success. + +ACTUAL PUBLIC SOURCE STDIO OBSERVATION DURING THE PROTOTYPE +The exact canonical description was sent to a real subprocess. +Text JSON and structuredContent were identical for both calls: + + allow_midi_fallback=false: + isError=true + code=NATIVE_FORMAT_UNAVAILABLE + details={part:lead, format:griff, reason:no_physical_string_assignment} + No destination/artifacts published. + + allow_midi_fallback=true: + status=midi_fallback + Exactly one .mid, explicit native-unavailability warning, no .griff. + Independently parsed MIDI contains all21 required musical note-ons. + Zero control_change messages; no bar2 musical retrigger. + +The second result is evidence of the blocker, NOT a passing native result. +The prototype result included rational interpretation, exact resolved pitches, +technique and held status. That result surface was removed with the prototype; +it is not advertised as available in the restored product. + +INDEPENDENT CANONICAL MIDI READ-BACK +MIDI960 start/end, pitches, technique: + 0 / 480 [42,46,49] PM + 480 / 960 [42,46,49] PM + 960 / 1440 [38,42,45] PM <-- impossible native simultaneous fingering + 1440 / 1920 [38,42,45] PM <-- same conflict + 1920 / 2400 [46,50,53] PM + 2400 / 2880 [46,50,53] PM + 2880 / 3200 [60] PM + 3200 / 3520 [64] PM + 3520 / 7680 [67] PH, one continuous hold + +Nine attacks expand to21 independent musical tones. +Selector-ons: (0,26), (3520,31); selector velocity100 and30-tick gate. +46 scheduled note events including musical tones and selectors. +Final G4 start=11/3, duration=13/3 quarter-note beats. +No retuning into E minor, omitted chord tone, hidden retrigger or controller. + +After restoring Step14, reconstructed the exact same explicit plan through +the accepted APIs, repeated native preflight failure, and wrote MIDI bytes +identical to the provisional real-stdio fallback: + SHA256: + 4ce995ca751590b32cd85c72c3a2d8dad7f478cdf34d3abb12616d121719c3b4 + +There is deliberately NO canonical native event read-back to present. +There is deliberately NO claim of installed-wheel hybrid parsing acceptance. + +GRAMMAR / INTERPRETATION STATUS +The disposable parser used case-insensitive labeled rows, exact Fraction +counts and bracketed triplets; deterministic Step14 pitch-tokenization and +selected-profile resolution; o/x/^ attacks, rest/tie processing, explicit +slash/Over/bracket voicings and cross-bar holds. Spacing was lexical only. +Its76 unit cases passed, including canonical/compact nearby-pitch variants, +eighth/sixteenth/triplet counts, bare1&a ambiguity, rests, ties, voicing +conflicts, selected-profile limits, slide rejection and bounded style context. +The first real source canonical native gate then failed as detailed above. +Installed hybrid gates were not completed. The implementation was not kept +as an incomplete new public contract, and those provisional tests are absent +from the final passing suite. + +Final supported grammar remains the accepted documented0.1.1 prose/template, +original beat-range/triplet-hold phrase, and internal Step14 pitch/plan APIs. +Counts/Events/Chords/Notes lanes, new Grid directives and a new interpretation +surface are NOT newly supported in this blocked result. No documentation or +tool guidance was changed to imply otherwise. + +PRESERVED ORIGINAL E2 MUSIC — SOURCE AND INSTALLED WHEEL +The full accepted suite reran real source and offline built/installed-wheel +stdio tests. Both independently read nine MIDI40 musical notes and nine native +notes, matching the original phrase: + onsets: 0,480,960,1440,1920,2400,2880,3200,3520 + ends: 480,960,1440,1920,2400,2880,3200,3520,7680 + velocities:80,80,64,80,96,80,80,80,80 + PM26 at0; PH31 at3520; no bar2 retrigger; native PM/PH at half MIDI times. + +Source and installed-wheel original-byte hashes still match: + .mid: + c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62 + .griff: + e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c + +FINAL VALIDATION AFTER REMOVING THE PROTOTYPE +All commands used .\.venv\Scripts\python.exe: + -m pytest -q --tb=short: + PASS,1661 tests,64.71s; full unit/integration/package suite. + Includes offline sdist/wheel build, isolated wheel installation, real + source/installed stdio, pitch/native/CC/privacy/atomic and old phrase tests. + -m ruff check .: + PASS, all checks passed. + -m ruff format --check .: + PASS,101 files already formatted. + -m mypy --strict src tests: + PASS, no issues in54 source files. + -m pip check: + PASS, no broken requirements. + git diff --check: + PASS. + Earlier targeted preserved description/phrase/explicit-plan run: + PASS,186 tests. + +PRESERVATION / PERSISTENT EVIDENCE +Final git status matches the initial accepted dirty state, plus this report. +No version/dependency/release metadata, profile tuning, native/CC compiler, +public tools, application configuration or existing source behavior changed. +No commits, delegation, later prompts, user-app manipulations or new dependency +installation. Prototype files and project-local validation scratch removed. +The Step14 preservation manifest still has exactly82/85 unchanged baseline +files, with ONLY its already accepted changes: + docs\architecture.md + src\riff_groove_builder\compose.py + src\riff_groove_builder\schemas.py + +Retained reproducible numeric/error/transport evidence and actual MIDI: + .test-artifacts\step15\blocker-source\evidence.json + .test-artifacts\step15\blocker-source\ + canonical-midi-fallback\canonical-midi-fallback.mid + .test-artifacts\step15\accepted-foundation\canonical.mid + .test-artifacts\step15\preserved-original-evidence.json + +REQUIRED RESOLUTION BEFORE STEP15 CAN BE ACCEPTED +An authorized requirement decision is needed: permit an explicitly chosen, +evidence-backed alternate tuning/profile that can voice both low tones; +change the canonical D2 voicing/register; or permit declared MIDI fallback +for this physically impossible native chord. None can be chosen silently. +Step16 remains NOT READY. Stopped here with the blocker demonstrated. +``` diff --git a/prompts/report_15_fix.md b/prompts/report_15_fix.md new file mode 100644 index 0000000..4223a3c --- /dev/null +++ b/prompts/report_15_fix.md @@ -0,0 +1,204 @@ +``` +Step 15 correction — COMPLETE and verified; READY for Step16 review +Date: 2026-10-20 + +AUTHORITATIVE CORRECTION / HISTORY +Read step_15_fix.md, step_15.md, report14/15 and the accepted current +pitch/strict-plan/composer/description/service/native/transport foundation. +The canonical native chord is D3=[50,54,57], NOT D2=[38,42,45]. +No tuning, native validator, user-explicit pitch, profile or fallback rule was +changed to make a physically impossible chord appear native. +report_15.md is preserved unchanged as historical blocked-attempt evidence; +its unsupported-parser/readiness statements are superseded by this report. +Historical report15 SHA256: +812c33ef2c1e6279cedaa7f769dfff385dad1ef680b06afb1839d318bab9b8b1 + +IMPLEMENTED PUBLIC PATH +generate_music.description now actually accepts hybrid prose and precise +Counts/Events/Notes/Chords lanes, through the real source and installed tool. +No resolver injection, whole-example recognition or canned music branch. + +Added hybrid.py: +- Separate recognized lane/hold clauses before the legacy prose sequence + guard. Unknown remainder still goes through the closed context grammar. +- Reusable count_grid uses exact Fraction quarter-beat timing, with numeric + labels counting meter-denominator units, never visual width. +- Typed unresolved HybridSlot/HybridPlan in schemas preserve exact positions + while selected-profile pitch resolution waits for routing. +- materialize reuses Step14 tokenize_notation/parse_pitch/parse_chord/ + resolve_voicing and creates the existing ExplicitAttackPlan. +- description and compose/service reuse that one parser/materializer without + introducing circular dependencies or a duplicate voicing engine. +- Existing compose/compiler, profile articulation resolution, MIDI/native + codecs, independent readers, CC budgets and atomic publication remain in use. + +Service results add default-empty resolved.interpretation for compatibility. +Each hybrid attack exposes resolved MIDI pitch sets, exact rational start/ +duration, technique, part, optional intensity and held status. Assumptions +disclose root/bass/default pitch resolution, no-key-retuning and seed policy. +Complete text JSON equals structuredContent, including interpretation and +errors. Guidance advertises bounded actual support rather than arbitrary +natural-language rhythm understanding. README/architecture/compatibility +document supported grammar and the corrected D3 versus explicit D2 policy. + +GRAMMAR / POLICIES / LIMITS +- Case-insensitive row labels, normal whitespace/tabs, compact pitch/event + runs, ordered Bar/Measure N headers or matching | boundaries. + Notes/Chords are independently optional; Counts/Events required per bar. + Present rows must match exact slot counts and bar spans; never zip-truncate. +- Complete 1& = eighths; 1 E & A = sixteenths; [4 trip let] = three explicit + eighth-triplet positions. Bare N is one full denominator beat. + Grid:/Subdivision: eighths, sixteenths, eighth-triplets are supported. + Bare 1&a is ambiguous without an explicit sixteenth/triplet grid. + Sixteenth-grid 1&a explicitly omits e: starts0,1/2,3/4, lengths1/2,1/4,1/4. + Triplet-grid 1&a starts0,1/3,2/3. No inferred triplet from three attacks. + Tested 3/4, 4/4 and denominator2/4/8/16 math, no compound-grouping claim. +- o=normal/open articulation (not fingering), x=PM, ^=evidenced AME lead PH, + -=rest, ~=adjacent prior sound extension with no retrigger. A rest truly + ends sound; continuation after silence/new pitch fails. PH ties preserve PH. + Events / and backslash give a specific reserved-slide origin/destination/ + timing error, never a silently ordinary attack or slash-chord confusion. +- Uppercase pitch letters A-G, ASCII #/b, optional signed octave; C4=60. + Major, m/min, (add4), root octaves, / and Over bass and explicit voicings + use the accepted Step14 rules. Chords:[C3 E3 G3] is simultaneous, whereas + Notes/Events brackets group consecutive slots. Compact lane dashes work + before/after/between pitch atoms without losing signed-octave semantics. + Em4OverB2 and Em4/B2=[47,64,67,71]; Em4/B and Em4OverB=[59,64,67,71]. + Default octaves are disclosed; explicit bass must already be lowest. +- One selected pitched part. At most one sounding pitch source per slot. + A genuinely unspecified attack uses the disclosed low-tonic context default; + an explicit source is never overwritten. Key/style never alter exact tones. +- Hold/Tie the final note/chord/G4/E2 through/to the end of bar/measure2, + optionally without retriggering; Bar2 hold previous note to bar end; or + all-tilde continuation rows extend one original attack/chord. + Pitch mismatch, target0/out-of-range, rests or new attacks in a held span, + nonadjacent ties and shorter-bar/incompatible-meter overrides fail. +- Global techniques and direct prose pitch claims must agree with exact + lanes. Bounded first-PM-then-PH prose is not mistaken for an accidental + global conflict. Extra contradictory technique claims still fail. + Low-register chord voicings, aggressive/tight metal style and bounded + velocity variation are context, not permission to change precise music. + Existing seed intensity policy: one draw per attack shared by chord tones. +- 4000-character public input bound, strict typed plans, exact compiler grid, + expanded tone-plus-articulation event budget and existing explicit-CC + combined budget. No unrequested CC/effects, arbitrary prose, new drum-lane + language, hidden revoice, dropped tone, transpose or plugin/DAW claim. + Malformed/unknown material returns static authored private-safe errors. + Prose-only requests remain on the old paths with old safeguards and bytes. + +ACTUAL SOURCE AND INSTALLED NATIVE/MIDI READ-BACK +Both transports used the PUBLIC tool with allow_midi_fallback=false for D3. +Both returned complete with .mid and .griff, no fallback_for target, no CC. +Independent Mido/XML readers checked every tone, onset, duration, velocity, +articulation, native string/fret/tuning and occupied-string nonoverlap. + +Corrected canonical, MIDI960 starts/ends: + 0 / 480 [42,46,49] PM + 480 / 960 [42,46,49] PM + 960 / 1440 [50,54,57] PM + 1440 / 1920 [50,54,57] PM + 1920 / 2400 [46,50,53] PM + 2400 / 2880 [46,50,53] PM + 2880 / 3200 [60] PM + 3200 / 3520 [64] PM + 3520 / 7680 [67] PH, no bar2 retrigger +Nine attacks, exactly21 musical note-ons,21 native Note elements. +Native480 times are exactly half these MIDI times. +D3 legal assignments: MIDI50 string4/fret2,54 string3/fret1,57 string2/fret0. +F#2:42 string6/fret6,46 string5/fret3,49 string4/fret1. +Bb2:46 string5/fret3,50 string4/fret2,53 string3/fret0. +C4 string2/fret3; E4 string1/fret2; G4 string1/fret5. +MIDI selector-ons (tick,pitch)=(0,26),(3520,31), velocity100,30-tick gates. +46 scheduled note events including selectors; no controllers/program changes. +Final G4 start11/3, duration13/3 quarter beats, held=true in interpretation. +Source/installed/compact bytes agree: + mid SHA256: + 6fd027fe4f74fec953be4c31fecda8eb14dec9bae0d15f76ae0c3dc481fdd181 + griff SHA256: + 45084055f11997d4f046f58190a08856bdb5e9de7d647a62227213a9994b6f1f + +HONEST OLD D2 NEGATIVE-NATIVE / POSITIVE-EXACT-MIDI +Both real transports also used the original explicit D2 row unchanged. +allow_midi_fallback=false: + NATIVE_FORMAT_UNAVAILABLE, no_physical_string_assignment, no publication. +allow_midi_fallback=true: + midi_fallback, exactly one .mid, explicit native-unavailability warning, + fallback_for=[lead], all21 musical tones preserved including both38/42/45 + chord sets at960/1440. No .griff, dropped tone or hidden D3 transposition. +Both fallback MIDIs are byte-identical to report15's independently proven MIDI: +4ce995ca751590b32cd85c72c3a2d8dad7f478cdf34d3abb12616d121719c3b4 + +ORIGINAL E2 TWO-MEASURE PHRASE UNCHANGED +Both transports verified hybrid E2, all-tilde bar2 and continuation-clause +bar2 against the accepted original nine-note source/installed byte hashes. +All four spellings preserve nine MIDI40 notes and nine native notes: + starts:0,480,960,1440,1920,2400,2880,3200,3520 + ends:480,960,1440,1920,2400,2880,3200,3520,7680 + velocities:80,80,64,80,96,80,80,80,80 + PM26 at0,PH31 at3520; no bar2 retrigger, no CC. + mid SHA256: + c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62 + griff SHA256: + e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c +The existing verbatim original prose source/installed tests also remain active. + +OTHER LIVE PUBLIC ACCEPTANCE +Source AND built/installed-wheel transports independently verified slash/Over +aliases and both bass-octave policies, [C3 E3 G3], Em4(add4), default F# with +visible root assumptions, and out-of-key exact tones. They checked the real +rest-separated E2 attacks and adjacent tilde extension, plus compact canonical +bytes. Invalid row mismatch, ambiguous1&a, slide, conflicting hold, private +unknown prose and disabled D2 fallback published no artifacts/staging remnants. +All successes/failures preserved text JSON/structuredContent/schema parity. +Installed bootstrap verified hybrid/pitch modules came from the installed +noneditable wheel, not src. Test-only distributions were built offline from +sdist and installed outside the checkout; dist release files were not refreshed. + +VALIDATION / ISSUES ENCOUNTERED +All commands use .\.venv\Scripts\python.exe. +Focused new unit/source/installed-distribution acceptance: + -m pytest -q tests\unit\test_hybrid.py + tests\integration\test_hybrid_stdio.py + tests\integration\test_distribution.py --tb=short + PASS127 in16.57s after the final PM/PH alias case and formatting. +First full-suite run:1781 passed,1 failed in69.31s. + The sole failure was the new documentation link to this not-yet-written + report, not music/parser/native behavior. This file resolves that link. +Earlier focused failures were test harness assumptions about the old installed +module count and exact legacy guidance wording; updated module count to include +hybrid/pitch and retained compatible, more precise guidance. Both now pass. +Strict typing annotations and one overlong test string were corrected. +No new technical/music blocker remains. +Final full-suite result: + -m pytest -q --tb=short: + PASS1785 in68.66s, including real source and installed-wheel public hybrid + native/MIDI, original phrase, all previous native/template/CC/privacy/ + atomic/strict-plan/pitch regressions and documentation links. + The only subsequent code-tree change was formatting one test expression; + focused127 and all static checks passed again on that final tree. +Latest static checks: + -m ruff check .: PASS, all checks passed. + -m ruff format --check .: PASS,107 files already formatted. + -m mypy --strict src tests: PASS,57 source files. + -m pip check: PASS, no broken requirements. + git diff --check: PASS. +Editor problems: no diagnostics in changed parser/schema/description/service. + +PERSISTENCE / PRESERVATION / NEXT STEP +Persistent independent numeric evidence, interpretation, SHA256 hashes and +actual copied MIDI/.griff files are retained at: + .test-artifacts\step15-fix\source\evidence.json + .test-artifacts\step15-fix\installed-wheel\evidence.json + .test-artifacts\step15-fix\\hybrid-* +These survive cleanup of per-test subprocess/distribution scratch workspaces. +Pre-existing accepted dirty changes were preserved. No version, dependency, +tuning, native codec, compiler, application configuration or release artifact +changes; no dependency installation beyond existing offline test-wheel +acceptance; no commits, delegation, later prompts or user-app operations. + +Step16 readiness: READY for review and the next authorized step. +All requested software gates passed; no new precise technical blocker remains. +Version remains0.1.1; final release/version work belongs to Step16. +Do not mistake historical report15 for the current supported public contract. +No next prompt was created. +``` diff --git a/prompts/report_16.md b/prompts/report_16.md new file mode 100644 index 0000000..e4d52f8 --- /dev/null +++ b/prompts/report_16.md @@ -0,0 +1,327 @@ +``` +Step 16 — COMPLETE: release 0.2.0, exact original E2 hybrid verified/published +Date: 2026-10-20 + +OUTCOME / STOP +The accepted Step14 and corrected Step15 implementation is released as 0.2.0. +The original single-note E2 request works directly, not just the chord variant. +Final persisted wheel/sdist, real source and installed stdio, independent saved +MIDI/XML checks and one new user publication are verified. No later prompt was +opened/executed, no commit/delegation, dependency addition, application restart, +live chat/config edit, DAW operation or playback occurred. This update is ready +for the user's MCP restart and fresh chat; no next implementation step is run. + +OWNED CHANGES +- Sole package version source src\riff_groove_builder\__init__.py now 0.2.0. + Existing pyproject dynamic metadata and MCP initialization derive from it. + Existing configured venv metadata was refreshed OFFLINE: + .venv\Scripts\python.exe -m pip install --no-index --no-deps + --no-build-isolation --no-cache-dir -e . + Package import and importlib.metadata both report 0.2.0. + No runtime/development dependencies were installed/restored/changed. +- Current README, architecture and compatibility describe the actual release, + exact tested prompt, bounded grammar, pitch/voicing/fallback policy, reserved + slides and restart/fresh-chat instructions. Historical reports are unchanged. +- Tests now assert 0.2.0, exact README description, minimal original arguments, + E2 compact/all-tilde equivalence, native metadata/string6-fret4, full transport + payload equality and final archive/source/resource/README identity/privacy. +- Installed hybrid acceptance now uses a separate real no-SD3-template process. + Evidence writes to step16 rather than overwriting historical evidence paths. + No parser/composer/profile-tuning/native/compiler defect or change was needed. + +EXACT FINAL RELEASE FILES +Repository root R: +D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder + +Wheel, 96021 bytes: +R\dist\hybrid-0.2.0-20261020\gaj3t_musicgen_riff_groove_builder-0.2.0-py3-none-any.whl +SHA256 9e4ffcd9e1b997ccdafc7dcc906aa1a64c90c1930d69f27f22b20d661c1ae5a0 + +Sdist, 115302 bytes: +R\dist\hybrid-0.2.0-20261020\gaj3t_musicgen_riff_groove_builder-0.2.0.tar.gz +SHA256 7aa757c228bafa9dc5ccd54ac610c496cedabf5de06ade2fe6989e1886e7f5dc + +Built offline with .venv\Scripts\python.exe -I -B -m build --no-isolation +--outdir dist\hybrid-0.2.0-20261020 . (wheel built from the sdist). +The final full suite selected this EXACT directory with RIFF_RELEASE_DIST; +it did not substitute another disposable build for release acceptance. +Final wheel hash is also asserted unchanged across installed stdio tests. + +ARCHIVE / INSTALLED IDENTITY AND PRIVACY +Wheel package .py/.json member set equals current src package exactly, and +each member is byte-identical. Six profile resources are included, no extras. +Sdist source/profile/README/pyproject bytes match current files exactly. +Wheel METADATA reports 0.2.0 and contains the current README (only standard +Windows CRLF versus LF normalization for its metadata text comparison). +Wheel-only metadata members are METADATA, WHEEL, RECORD and top_level.txt. +Sdist contains only package sources/profiles, README, pyproject, setup.cfg, +PKG-INFO and setuptools egg-info. No private chat/template, factory music, +manual binary, output song, test artifact, venv or application config shipped. + +The exact wheel was installed offline/noneditably with --no-index --no-deps. +An isolated fresh-venv import and a real installed-target stdio server ran with +cwd outside the checkout: +D:\_Repos\Code\GAJ3T\MCPs\MusicGen +-I -B, no PYTHONPATH/PYTHONHOME; dev-venv dependencies reused for server tests. +All 18 package/submodule/entry paths and all six resource paths were asserted +under the wheel install target, not src. Module and resource hashes match +current source. Metadata is noneditable and 0.2.0; real initialize returns +0.2.0, protocol 2025-11-25. This is not fresh dependency certification. +Disposable wheel environments and native probes were cleaned by test fixtures. + +FINAL VALIDATION +All commands use R\.venv\Scripts\python.exe: + -m pytest -q --tb=short, RIFF_RELEASE_DIST=final persisted directory: + PASS 1786 tests, 66.21s, no failures/skips. + Includes full original simple/native/CC/SD3/template/atomic/privacy suites, + pitch/voicing/hybrid suites, source and exact installed-wheel stdio. + -m ruff check .: + PASS, all checks passed. + -m ruff format --check .: + PASS, 109 files already formatted. + -m mypy --strict src tests: + PASS, no issues in 57 source files. + -m pip check: + PASS, no broken requirements found. + git diff --check: + PASS. + Focused hybrid/readme/package/source transport run: + PASS 138 tests, 2.43s. + Editor problems on changed Python files: + no errors. +The editor test runner discovered no tests; pytest was used directly instead. + +SOURCE AND EXACT INSTALLED ORIGINAL E2 ACCEPTANCE +Both real processes received only: + description = the exact final description copied below + basename = hybrid-e2 +No explicit formats/profiles/parts/seed/CC/template were supplied. Default seed +is 0. Both returned complete with .mid/.griff, no fallback_for. Complete decoded +JSON TextContent equals structuredContent, including nine interpretation rows. +Both public input/output schemas validate. Each no-template transport had +22 stdout response lines, empty stderr and exit0. + +Independent Mido/XML numeric read-back, SOURCE = exact wheel = user output: +Attack MIDI pitch MIDI960 start/end Native480 start/end Technique Velocity +1 40 (E2) 0 / 480 0 / 240 PM 80 +2 40 (E2) 480 / 960 240 / 480 PM 80 +3 40 (E2) 960 / 1440 480 / 720 PM 64 +4 40 (E2) 1440 / 1920 720 / 960 PM 80 +5 40 (E2) 1920 / 2400 960 / 1200 PM 96 +6 40 (E2) 2400 / 2880 1200 / 1440 PM 80 +7 40 (E2) 2880 / 3200 1440 / 1600 PM 80 +8 40 (E2) 3200 / 3520 1600 / 1760 PM 80 +9 40 (E2) 3520 / 7680 1760 / 3840 PH 80 + +MIDI: SMF type1, PPQ960, two tracks, tempo120, 4/4, both EOT7680. +Exactly nine musical on/off pairs plus PM26 selector0..30 and PH31 +selector3520..3550, selector velocity100, channel0; 22 scheduled note events. +No CC, program changes, effects or bar2 retrigger. +Native: Riff XML2.1, Measures2, Time-Signature4/4, KeyEm, PPQ480, +loopEnd3840. Nine actual Note elements, all string6/fret4, eight PM and one PH, +No Legato; no occupied-string overlap or CC data. +Interpretation lists all nine exact MIDI40 attacks, starts/durations in reduced +quarter-beat fractions, first eight palm_mute, last pinch_harmonic held=true. +Final start11/3, duration13/3, through end of bar2; no new bar2 attack. + +SOURCE/installed compact E2, explicit all-tilde bar2 and continuation-clause +bar2 preserve the exact same bytes, not an approximate rerendered pattern. +All source/wheel musical-output hashes agree across the 15 successful public +cases per transport; six negative cases per transport return visible errors +without publication or leaked private suffix. No owned .riff-stage remained. + +Retained exact original copies (relative to R): + .test-artifacts\step16\source\hybrid-e2\hybrid-e2.mid 168 bytes + .test-artifacts\step16\source\hybrid-e2\hybrid-e2_lead.griff 1701 bytes + .test-artifacts\step16\installed-wheel\hybrid-e2\hybrid-e2.mid 168 bytes + .test-artifacts\step16\installed-wheel\hybrid-e2\hybrid-e2_lead.griff + 1701 bytes +All MIDI copies SHA256: +c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62 +All griff copies SHA256: +e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c +These equal accepted original 0.1.1 musical hashes exactly. + +CORRECTED CANONICAL D3 / HONEST EXPLICIT D2 +Same Counts/Events; canonical rows: +Chords: F#2 F#2 D3 D3 Bb2 Bb2 - - - +Notes: - - - - - - C4 E4 G4 +Hold final G4, not E2. Nine attacks expand to exactly21 musical tones: + starts0/480: [42,46,49] PM,480 ticks each + starts960/1440: [50,54,57] PM,480 ticks each + starts1920/2400: [46,50,53] PM,480 ticks each + start2880: [60] PM,320 ticks + start3200: [64] PM,320 ticks + start3520: [67] PH,to7680; no bar2 retrigger +Both real transports with fallback=false return native+MIDI; independent +readers verify all21 pitches, legal string/fret/timing, velocities, selectors +and no CC/programs. Native PPQ480 is exactly half MIDI timing. +Canonical and compact hashes: + mid 6fd027fe4f74fec953be4c31fecda8eb14dec9bae0d15f76ae0c3dc481fdd181 + griff 45084055f11997d4f046f58190a08856bdb5e9de7d647a62227213a9994b6f1f + +Explicit D2 remains [38,42,45] at960/1440, not hidden D3: + fallback=false: NATIVE_FORMAT_UNAVAILABLE/no_physical_string_assignment, + no published destination. + fallback=true: midi_fallback, exactly one .mid, fallback_for=[lead], + visible native warning, all21 exact tones, no native file. +D2 exact-MIDI SHA256: +4ce995ca751590b32cd85c72c3a2d8dad7f478cdf34d3abb12616d121719c3b4 +MIDI38 and42 require different frets on string6 simultaneously; the accepted +tuning/physical validator is unchanged. No dropped tones/hidden octave rescue. + +PUBLIC VOICING AND NEGATIVE ACCEPTANCE +Real source AND exact wheel exercise: + Em4OverB2 = Em4/B2 = [47,64,67,71] + Em4/B = Em4OverB = [59,64,67,71], default B3 disclosed + [C3 E3 G3] = [48,52,55] + Em4(add4) = [64,67,69,71] + F# = [42,46,49], default root octave disclosed +These retain their pitches even in D minor context. Also actual rest/tie +read-back and D2 rejection, ambiguous grid, mismatched lane, reserved slide, +hold/rest conflict and private-suffix failure paths are tested on both stdio +transports. Full unit coverage retains case/tab/width/compact invariance, +duplicate/mismatched lanes, incompatible prose, grid/denominator boundaries, +slash/explicit voicing validation and no approximate fallback weakening. + +ONE ACTUAL USER PUBLICATION +NEW official-SDK stdio MCP process, version0.2.0, configured venv interpreter, +cwd outside checkout, output root D:\MusicGenOutput, no SD3 template. +Arguments: exact final description, seed default0, unique basename +em_e2_hybrid_20261020_104001_3876e257, allow_midi_fallback=false. +Observed successful tool result: complete, isError=false; schemas valid, +TextContent JSON=structuredContent; every interpretation/pitch/tick/technique +and native/MIDI read-back passed before a late verification-harness assertion. +Both actual user files were then independently reopened again, not regenerated: + +D:\MusicGenOutput\em_e2_hybrid_20261020_104001_3876e257\em_e2_hybrid_20261020_104001_3876e257.mid +168 bytes +SHA256 c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62 + +D:\MusicGenOutput\em_e2_hybrid_20261020_104001_3876e257\em_e2_hybrid_20261020_104001_3876e257_lead.griff +1701 bytes +SHA256 e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c + +Exactly these two new files; no sidecars. Prior user directory +em_chug_triplet_ph_20261020_030601 and both original files remain byte-identical. +No successful output was deleted, overwritten or republished. + +ISSUES ENCOUNTERED / HONEST EVIDENCE BOUNDARY +1. Initial new test lint line was formatted with existing Ruff. +2. First full run:1785 passed,1 failed because wheel METADATA used Windows + CRLF but README.read_text normalizes LF. Corrected only the test's text + comparison; byte-exact source/resource and sdist README checks remain. + Exact persisted wheel was NOT replaced. Final full run:1786 passed. +3. User publication succeeded, then its harness incorrectly required warnings + to be empty. The default profile has the legitimate VERIFIED_SUBSET_LIMITS + warning, as independently retained source/installed responses show. Native + success and all requested musical checks had already passed. The original + user raw tool response was not persisted before that late assertion. + Recovery did NOT fabricate that lost response or generate another copy. + user-publication.json records observed pre-error assertions and independent + actual-file reopening against retained source interpretation. Full raw + source and installed TextContent/structuredContent remain available. + The isolated harness assertion is not a product/native/fallback failure. + +PERSISTENT EVIDENCE / PRESERVATION +R\.test-artifacts\step16: + release-files.json; build.log; metadata-refresh.log + pytest-full-final.log (1786 pass) + source\evidence.json; source\hybrid-transport.json + installed-wheel\evidence.json + installed-wheel\distribution-acceptance.json + user-publication.json; user-reopen.log; user-stdio-stderr.log (empty) + preservation-before.json; final-identity.json +Source and installed evidence include full arguments/TextContent/structured +results, interpretation and actual numeric musical/native records. +Their published workspace paths are historical transport locations; durable +copied bytes are under the retained source/installed-wheel directories above. + +All57 preexisting files in the prompt/report + previous dist + user-output +preservation manifest remain hash-identical. Historical reports14/15/15_fix, +old release artifacts, accepted dirty work and previous user output are kept. +New validation evidence is separate from old Step13/15 evidence. +No owned generation stage or running helper is left. Test fixtures cleaned +their disposable processes/installations; final release/output/evidence persist. + +Final source/doc identities (SHA256): + README.md + b07fa6347e29b3f20caf1f1dc8a3738553c8eb587126df81d312ab5645e16e3a + docs\architecture.md + b475508c6aeaa3f9d9931c69c3a427b6d57d5c96758b12506450b169891b1285 + docs\compatibility.md + eecb1a4e3321f97ac10029ed94f152c9a7a0e657aa8627987e665c66f1b7dcea + pyproject.toml (unchanged dependency/build declarations) + ed2c8de067a4e0ea6ad10b21d3dab846c355d244d1c85b21f63f36f84a082d25 + src\riff_groove_builder\__init__.py + 2549a2b71d86a16bb0433641891b716bbc2f3dd055db65d2ab0a2d757aad961d + src\riff_groove_builder\hybrid.py + 5e2f7b62dae9bcb3696391604338b4d24576342c732485a0831737f6d4fd4827 + src\riff_groove_builder\pitch.py + b443ef587c49c26a3a9b2e2c736d89f83d8c291c14b76a0d292a0efedd345f4f +All six profile path/hashes and all18 loaded module hashes are retained in +installed-wheel\distribution-acceptance.json and checked against current src. + +LIMITS / PRECISE MEANING +Implemented Events: o=normal/open articulation, x=PM, ^=AME lead PH, +-=rest, ~=adjacent continuation without retrigger. Open is not fingering. +Events / and backslash slides are RESERVED, NOT IMPLEMENTED; actionable +origin/destination/timing codec errors are returned. Chord / and Over bass +are a separate implemented operation, not generated slides. +C4=MIDI60; a chord digit is the root octave, not a seventh/extension. +Omitted slash bass picks the nearest matching pitch strictly below all +upper tones and discloses it; explicit bass must already be lower. +Key/style never secretly retune, transpose, revoice or drop explicit tones. +Raw explicit voicings can be physically unplayable: exact MIDI fallback is +truthful, while fallback=false returns an error without fabricated native. +Counts use meter-denominator beats with exact rational grids, not visual +spacing or compound grouping. Triplet count A is not pitch A. +Prose is bounded/local deterministic, not arbitrary model comprehension: +4000-character limit, documented grids/clauses, strict plan/event budgets, +one selected pitched hybrid part, static authored private-safe errors. +No new CC/effects/program claims, audio synthesis or application certification. +Live LM Studio/model behavior, plugin native load/save/reload/playback and +Cubase routing/import acceptance remain UNRUN. + +USER ACTION — AFTER THIS VERIFIED UPDATE +Restart the riff-groove-builder MCP in LM Studio NOW, THEN open a NEW chat to +refresh cached schemas/tool descriptions. The existing configured interpreter +R\.venv\Scripts\python.exe now resolves 0.2.0. No config edit, config reinstall +or dependency reinstall is required. No live restart was done on your behalf. + +FINAL COPY-READY FRESH-CHAT PROMPT (identical to tested README prompt) +Call generate_music once. Set basename to "em_e2_hybrid_20261020_fresh_chat_01" +and allow_midi_fallback to false. Set description verbatim to the text between +BEGIN DESCRIPTION and END DESCRIPTION below. Omit all other arguments; do not +invent formats, profiles, control changes, programs, effects or an SD3 template. +Return the actual tool result and its output paths, not a claimed playback. +BEGIN DESCRIPTION +Lead guitar in E minor, 4/4, 120 BPM, 2 bars. +Bar 1: +Counts: 1 & 2 & 3 & [4 trip let] +Events: x x x x x x [x x ^] +Notes: E2 E2 E2 E2 E2 E2 E2 E2 E2 +Hold the final E2 through the end of bar 2 without retriggering. +END DESCRIPTION + +Choose a new unique basename for each later run; existing files never overwrite. +The markers/instructions are not part of the tool description. Minimal +description+basename alone was also verified through source and exact wheel. + +ORCHESTRATOR INDEPENDENT ACCEPTANCE AFTER REPORT REVIEW +Read the full current report, reviewed native/pitch/hybrid parser and service +interpretation paths, and independently reran the complete final suite against +RIFF_RELEASE_DIST=dist\hybrid-0.2.0-20261020: + 1786 passed in66.48s, zero failures/skips. +Ruff source/test lint and format, strict mypy (57 source files) and pip check +independently passed. Source/imported metadata both report0.2.0. +Final wheel/sdist SHA256 independently match this report. + +Independently reopened both ACTUAL user-facing files using Mido/ElementTree, +without the production parser/composer/native readers. Verified exact nineE2 +onsets/offs,8PM+1PH, selector26/31 ordering, no second-bar attack or CC, native +PPQ480/Measures2/KeyEm, both original musical hashes and exact two-file coverage. +No incomplete .riff-stage directory remains under the user's output root. +Prior files were not overwritten, and LM Studio/Cubase were not manipulated. +STOP: verified release/report complete; no later prompt. +``` diff --git a/prompts/report_2.md b/prompts/report_2.md new file mode 100644 index 0000000..acf0447 --- /dev/null +++ b/prompts/report_2.md @@ -0,0 +1,223 @@ +``` +Step 2 report — typed domain models and MCP tool contracts +Date: 2026-10-19 +Result: PASS. Step 2 is verified and ready for Step 3 review/authorization. + +SCOPE AND CHANGED FILES + +Created: +- src\riff_groove_builder\schemas.py +- src\riff_groove_builder\errors.py +- tests\unit\test_schemas.py +- tests\unit\test_errors.py +- tests\integration\test_contracts.py +- prompts\report_2.md + +Updated: +- docs\architecture.md — implemented contracts, units, serialization, reuse, + validation limits, and later-step responsibilities. +- README.md — accurate Step 1–2 scope, direct contract-test dependencies, + focused validation command, and editor-discovery fallback. +- pyproject.toml — directly declared jsonschema>=4.26,<5 and + types-jsonschema>=4.26,<5 development dependencies. + +No additional support files were necessary. Existing foundation tests, +initializer, approved plan, Step 1 report, prompts, and unrelated work were +preserved. No commits or delegation. No later prompts, server, scheduler, +writer, parser/composer, production profiles, or native codecs were created. + +IMPLEMENTED CONTRACT + +Pydantic v2 is authoritative. Contract objects reject unknown fields, numeric +booleans/strings, nonfinite numbers, invalid bounds/enums, duplicate selection +members, and required empty arrays. Integer-only fields reject floats even +when mathematically integral; integer and fractional BPM are accepted. +The meter denominator has an additional strict type guard for Literal values. + +Exactly two tool contracts are exposed: +- list_instrument_profiles: empty-object request; profile-list/error output. +- generate_music: the approved parameters; generation-result/error output. + +tool_input_schema(name) and tool_output_schema(name) return fresh dictionaries. +Both output schemas have an object root and explicit oneOf success/error +branches. GENERATION_OUTPUT and PROFILE_LIST_OUTPUT are reusable typed union +adapters. Step 3 can reuse these contracts without re-declaring fields. + +Omitted parts, formats, musical overrides, and profiles remain None. Explicit +null on those optional fields also means unresolved; model_fields_set and +model_dump_json(exclude_unset=True) preserve the omission/null distinction. +Seed defaults to 0 and allow_midi_fallback to true. No musical defaults, text +inference, default instrument selection, or profile lookup are implemented. + +Explicit parts constrain native formats and per-part profile selections now. +Unresolved parts require those checks again after later intent resolution. +Profile summaries enforce Eclips/lead/agp, Ray/bass/agp, SD3/drums/sdp and +explicit limitations for unavailable capabilities. An empty registry is valid. +Synthetic metadata appears only in tests and is not a registry or real mapping. + +Basenames enforce the approved ASCII grammar, 1–64 characters, case-insensitive +Windows device-name rejection, and no separators/traversal/trailing whitespace +or dots. A discovered trailing-newline regex edge case was fixed and tested in +both typed-model and published-schema validation. + +Key grammar: A–G letter (case-insensitive), optionally one ASCII # or lowercase +b, ASCII spaces, then major/minor (case-insensitive); outer spaces are allowed. +Keys normalize to twelve sharp-spelled pitch classes and lowercase mode: +Bb major -> A# major; Cb minor -> B minor. Contradictory/multiple keys, other +modes, malformed/double accidentals, Unicode accidentals, tabs, and newlines +are rejected. This parses only a structured key, not a musical description. + +INTERNAL REPRESENTATION + +MusicalIntent requires resolved fields; bars/meter yield exact Fraction duration. +RationalBeat uses reduced integer numerator/denominator JSON objects in +quarter-note beats. Positions are nonnegative; PositiveBeat durations are +strictly positive. No floating timing is accumulated or silently quantized. + +LogicalNote is a discriminated pitched/drum union. Lead/bass carry a numeric +pitch; drums carry a logical voice. Both carry exact timing, finite 0–1 intensity +without clamping, and an articulation name. Score enforces shared positive +duration, one ordered track per selected part, matching note parts, and bounds. + +ScheduledEvent is a discriminated note-on/note-off/CC union with no irrelevant +optional payload fields. Channels are 0–15; note/CC data are 0–127; note-on +velocity is 1–127; note-off velocity is 0–127. Note roles distinguish musical +notes from keyswitches; CCs carry an articulation-control role. + +Nonnegative tick/priority/sequence metadata defines a unique per-track ordering +key but does not implement sorting or scheduling. EventPlan retains the score, +selected event tracks, exact musical tick span, shared pre-roll/end/tail +boundaries, and positive resolution (default 960 ticks/quarter). Musical and +overall event bounds and the 100,000-event budget are validated. + +RESULTS AND ERRORS + +GenerationResult validates complete/midi_fallback status, resolved profile +coverage, end >= start, positive artifact sizes, absolute-path syntax, +format/part applicability, resolved artifact profile IDs, duplicate outputs, +one combined MIDI covering all selected parts, and selected warning parts. +Fallback requires explicit substituted parts and per-part native-unavailability +warnings, with no simultaneous native output for a substituted part. + +GenerationError has stable code/message/details fields. Named exceptions cover +invalid requests, unsupported descriptions/articulations, required/missing +profiles, unavailable native formats, collisions, output IO, and serialization. +ProfileNotFoundError uses PROFILE_REQUIRED with a specific missing-ID message. +Messages give fixed public actions. Finite JSON details are explicitly supplied; +conversion never copies exception causes, tracebacks, or private file content. + +VALIDATION ENVIRONMENT AND DEPENDENCIES + +Windows AMD64; repository .venv; CPython 3.13.13. +The existing >=3.11 policy is unchanged; no other runtime/OS was executed. +New directly used development dependencies installed/tested: +- jsonschema 4.26.0 +- types-jsonschema 4.26.0.20261006 + +Dependencies were installed only after the manifest edit: +& '.\.venv\Scripts\python.exe' -m pip install --disable-pip-version-check --no-cache-dir -e '.[dev]' +PASS: editable installation/dependency resolution completed. Only the repository +venv was targeted. Final pip check passed. + +All validation below ran from the repository root. Scratch setup: +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName + +The editor runTests tool was attempted for the three absolute new test paths. +It returned "No tests found in the files." This was not counted as a pass or +automated skip; the known working pytest fallback was used. + +FINAL EXACT COMMANDS AND OUTCOMES + +$env:PIP_NO_INDEX = '1' + +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_schemas.py tests\unit\test_errors.py tests\integration\test_contracts.py -q +PASS: 321 passed in 1.40s; 0 failed, 0 skipped. + +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_package.py tests\integration\test_distribution.py -q -s +PASS: all 6 unchanged foundation/distribution tests passed in 6.33s; +0 failed, 0 skipped. Includes four unit tests and two distribution tests. + +& '.\.venv\Scripts\python.exe' -m pytest -q -s +PASS: final combined suite, 327 passed in 7.46s; 0 failed, 0 skipped. +No test warnings were reported. + +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: All checks passed! + +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: 17 files already formatted. + +& '.\.venv\Scripts\python.exe' -m mypy +PASS: Success: no issues found in 8 source files. + +& '.\.venv\Scripts\python.exe' -m pip check +PASS: No broken requirements found. + +git --no-pager diff --check +PASS: no tracked-diff whitespace errors. Existing untracked work remains +untracked; authored Python is additionally covered by Ruff lint/format. + +Editor problems tool: no errors in the five new Python files. +Formatting was applied only to the five owned new Python files: +& '.\.venv\Scripts\python.exe' -m ruff format src\riff_groove_builder\schemas.py src\riff_groove_builder\errors.py tests\unit\test_schemas.py tests\unit\test_errors.py tests\integration\test_contracts.py + +Distribution tests rebuilt both sdist and wheel offline with --no-isolation, +installed the wheel with --no-index --no-deps in a unique repository-local +venv, and imported the initializer with -I -B from outside the checkout. +Final installed-wheel evidence: +- version and distribution metadata: 0.1.0 +- cwd: D:\_Repos\Code\GAJ3T\MCPs\MusicGen +- isolated mode: 1 +- module: repository-local .test-artifacts\distribution-bbb54d7455604f1db2132f58a0c8d749\wheel-venv\Lib\site-packages\riff_groove_builder\__init__.py +This proves distribution layout/import safety, not all dependency/runtime +combinations or instrument support. Unique build/wheel-venv workspaces were +cleaned; only the existing ignored scratch directory remains. + +DEVELOPMENT FAILURES AND CORRECTIONS + +The first focused pytest run had 318 passed, 1 failed: basename "a\n" incorrectly +matched a regex ending in $. An absolute-end assertion fixed it, and matching +schema regressions were added for basename/key newlines. An intermediate +focused run passed 319 tests; the final focused run passes all 321. + +Initial strict mypy checks found generic dictionary/literal inference and +heterogeneous test-fixture typing issues (two source diagnostics, then six test +diagnostics). These were corrected with explicit typed data structures and a +schema callback. No broad ignores or Any casts were added. + +Initial Ruff checks identified overlong literals (four source diagnostics, +then seven combined diagnostics). Formatting and split literals corrected +them; a remaining import-smoke string was caught and split before the final +successful full lint/format/type rerun. No known step-caused failures remain. + +LIMITS AND READINESS + +JSON Schema 2020-12 expresses static shapes, bounds, uniqueness, and conditional +associations/branches. Standard JSON Schema cannot compare arbitrary field +values, perform rational arithmetic, or fully express projected ID uniqueness, +profile correspondence, fallback-warning coverage, and timeline invariants. +Portable path checks and these relational checks remain model validators. +JSON Schema also considers 4.0 an integer; strict typed integer fields do not. +Downstream boundaries must use the authoritative models, not schema-only +validation. Revalidate changed payloads rather than mutating validated objects +or using unchecked model_copy updates. + +Later work must resolve text/default intent and profile identity, validate +verified instrument ranges/voices/techniques/channels, implement scheduling, +quantization and note pairing, and verify actual files, root/link confinement, +requested-output coverage, fallback permission, and atomic publication. +None of these later behaviors is claimed here. + +No target instrument maps, AGP/SDP layouts, lawful native fixtures, or actual +Cubase/plugin load/save compatibility have been verified. The prior evidence +gates remain open. Synthetic tests prove contracts only and do not create +generated music, real native output, or compatible files. + +No genuine Step 2 blocker remains. Required contracts, owned tests/docs, +offline foundation/distribution regression checks, lint, formatting, and strict +types pass. Ready for Step 3 to reuse the reviewed schemas and errors; Step 3 +was not implemented, and this is not full-project or application readiness. +``` diff --git a/prompts/report_3.md b/prompts/report_3.md new file mode 100644 index 0000000..7c405e3 --- /dev/null +++ b/prompts/report_3.md @@ -0,0 +1,242 @@ +``` +Step 3 report — SDK-backed MCP stdio server skeleton +Date: 2026-10-19 +Result: PASS for Step 3. Ready for Step 4 review/authorization. + +IMPLEMENTATION AND PRESERVED SCOPE + +Created: +- src\riff_groove_builder\server.py +- src\riff_groove_builder\__main__.py +- tests\unit\test_server.py +- tests\integration\test_stdio.py +- prompts\report_3.md + +Updated: +- README.md — actual module startup, existing-root setup, Windows VS Code MCP + configuration, honest tool behavior, and protocol-test commands. +- docs\architecture.md — SDK choice, validation/error/logging boundaries, + observed protocol semantics, lifecycle, and remaining pipeline work. + +Read the approved plan, Step 3 prompt, reports 1–2, authoritative schemas/errors, +package/test tooling, and installed SDK implementation/signatures. Existing +models, errors, initializer, foundation/contract/distribution tests, package +configuration, plan, and prior prompts/reports were preserved. pyproject.toml +did not need changes; no console executable or additional transport was added. + +No delegation, commits, later prompts, MIDI/native generation, music fixtures, +invented production profiles, external model calls, or service implementation. + +SDK INTERFACE AND TOOL CONTRACT + +Selected official MCP 1.30.0 low-level Server with its list_tools/call_tool +decorators and mcp.server.stdio.stdio_server transport. The SDK owns UTF-8 +newline framing, parsing, request IDs, dispatch, notifications, initialization, +protocol negotiation, lifecycle, and EOF shutdown. No production protocol code +was hand-written; raw framing exists only in the integration-test client. + +Exactly list_instrument_profiles and generate_music are registered. Their +inputSchema/outputSchema exactly equal the existing tool_input_schema and +tool_output_schema dictionaries, including the explicit success/error union. +No fields, result branches, or reviewed validation rules were redefined. + +call_tool(validate_input=False) deliberately disables the SDK's schema-only +input checker: its errors echo values and JSON Schema accepts 4.0 as an integer. +Authoritative Pydantic input models instead enforce strict types and cross-field +rules. Errors contain only known field names, numeric positions, +placeholders, and reason codes; no validation messages, inputs, contexts, +descriptions, arbitrary property names/values, causes, or private paths. + +Explicit CallToolResult objects preserve structuredContent, a concise text +summary, and isError. This SDK return path bypasses automatic output-schema +validation; authoritative model constructors validate outputs and unit/real +subprocess tests independently validate them against the published schemas. +Two narrow ignore comments cover only the SDK's untyped decorators; strict +mypy remains enabled, with no configuration relaxation. + +Profile listing truthfully returns {"profiles":[]}, isError false, and +"No verified instrument profiles." No mapping/capability claims are invented. + +Every valid generate_music call returns isError true and the existing typed +SERIALIZATION_ERROR schema branch, with the explicit message: +"Music generation is not implemented in this development-only stdio skeleton." +Details: {"reason":"generation_not_implemented","development_only":true}. +This provisional code does not claim a serializer ran, blame native support, +publish paths, or create files. Step 9 must replace the unfinished handler. + +Known domain errors preserve their public code/message/explicit details only. +Unexpected execution/output-model failures log the failure class to stderr +without traceback/exception values and return an SDK error with a fixed safe +message. They are not silently treated as invalid input or successful fallback. + +STARTUP, DIAGNOSTICS, AND IMPORTS + +Required startup: +& '.\.venv\Scripts\python.exe' -m riff_groove_builder --output-dir + +The CLI resolves an existing root and stores it in the SDK lifespan context. +Missing/nonexistent/file roots and URI, UNC, device, drive-relative, alternate +stream, and control-character forms are rejected. No root is auto-created; +no writeability claim/probe or publication takes place. Full link/reparse-point, +volume, permissions, collision, and publication checks remain Step 9. + +Logging is configured only by CLI execution, on stderr. A narrow filter replaces +the selected SDK's value-containing validation/unlisted-tool diagnostics with +fixed messages, without changing dispatch or suppressing operational failures. +Importing package, server, or __main__ is silent and does not start services. +stdout remains exclusively valid UTF-8 newline-delimited JSON-RPC. + +The README includes an absolute-path Windows VS Code .vscode\mcp.json example +and operator provisioning example. No manual MCP-client test is claimed. + +OBSERVED REAL-SUBPROCESS PROTOCOL BEHAVIOR + +- Official ClientSession.initialize performs the normal initialization and + initialized notification; both tools are discovered and called over real + stdio. Published schemas and returned structured content are checked. +- Raw tests independently exercise initialization, both tools, and clean stdout. + String and integer IDs are preserved. Initialized/progress notifications + produce no response; ping barriers and bounded quiet checks verify this. +- Supported requested versions are retained. An unsupported requested version + negotiates to an SDK-supported version; production code hard-codes none. +- Tool validation failures return typed INVALID_REQUEST with isError true. + Unknown tools use SDK text error results ("Unknown tool."), not invented + domain results or success. +- Unknown methods outside the SDK request union and invalid method parameters + return INVALID_PARAMS (-32602). Recognized but unregistered resources/list + reaches SDK dispatch and returns METHOD_NOT_FOUND (-32601). +- Invalid JSON, array messages, and objects missing a required method produce + the SDK's generic notifications/message ("Internal Server Error"), not an + invented parse-error response. Sanitized diagnostics remain on stderr. + The connection subsequently handles ping correctly. +- The installed SDK classifies an object with id:null and a method as a + notification. An unknown such method yields no response, with sanitized + stderr diagnostics. Tests assert actual SDK behavior rather than overriding it. +- Every captured stdout line decodes as UTF-8, ends in a newline, parses as JSON, + and validates as an SDK JSONRPCMessage. SDK generic logging notifications + are protocol messages, not freeform stdout logs. +- Closing stdin exits zero both after a session and before initialization. + No shutdown method is invented. +- Six bad-startup subprocess cases exit nonzero with empty stdout and stderr + diagnostics; nonexistent roots remain absent and unrelated sentinel data + remains intact. +- Editable-install metadata is verified. Real server processes use -I -B, + cleared PYTHONPATH/PYTHONHOME, and a different, otherwise empty working + directory under .test-artifacts. Startup therefore does not depend on cwd + source imports. Unicode request descriptions traverse real UTF-8 stdio. +- Every valid generation call stays explicitly unfinished and leaves its + output directory empty, including native requests with fallback disabled. + +ENVIRONMENT AND EXACT FINAL VERIFICATION + +Windows AMD64, repository .venv, CPython 3.13.13. +Selected installed versions: +mcp 1.30.0; pydantic 2.14.1; pytest 9.1.1; anyio 4.15.1; +ruff 0.17.1; mypy 2.4.0; jsonschema 4.26.0. +No dependency installation/reinstallation was required or performed. + +All commands ran from the repository root. For pytest/build scratch: +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +The combined regression/full-suite run additionally set: +$env:PIP_NO_INDEX = '1' + +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_server.py tests\integration\test_stdio.py -q +PASS: 53 passed in 11.94s; 0 failed, 0 skipped. +Breakdown: 36 unit tests and 17 real-process integration tests. + +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_schemas.py tests\unit\test_errors.py tests\integration\test_contracts.py tests\unit\test_package.py -q +PASS: 325 passed in 1.45s; 0 failed, 0 skipped. +Includes all 321 previously accepted contract checks and four import/foundation +unit checks, unchanged. + +& '.\.venv\Scripts\python.exe' -m pytest -q -s +PASS: 380 passed in 19.66s; 0 failed, 0 skipped; no warnings reported. +This includes every new test, all 327 prior tests, and both offline distribution +tests. They build sdist/wheel with --no-isolation, install a separate --no-deps +wheel venv offline, and import its initializer with -I -B outside the checkout. +Observed installed-wheel evidence: +- version and metadata_version: 0.1.0 +- cwd: D:\_Repos\Code\GAJ3T\MCPs\MusicGen +- isolated: 1 +- module_path: repository-local .test-artifacts\distribution-fd0502e0224b40dfb9ae26b615ebf0e7\wheel-venv\Lib\site-packages\riff_groove_builder\__init__.py +The distribution workspace was removed after successful checks. This existing +wheel test proves package/import safety, not installed-wheel protocol or full +runtime-dependency certification; real protocol tests use the editable install. + +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: All checks passed! + +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: 23 files already formatted. + +& '.\.venv\Scripts\python.exe' -m mypy +PASS: Success: no issues found in 12 source files. + +& '.\.venv\Scripts\python.exe' -m pip check +PASS: No broken requirements found. + +git --no-pager diff --check +PASS: no tracked-diff whitespace errors. Existing/new untracked source is +additionally covered by full Ruff lint/format checks. + +Editor problems tool: no errors in all four new Python files. +Known editor pytest discovery limitation: used the explicitly authorized, +verified .venv pytest CLI fallback; no editor test pass is claimed. + +CHILD CLEANUP AND PERSISTENCE + +All real subprocess waits are bounded. Raw fixtures always close stdin, wait +for the exact process, and have an exact-process kill/reap fallback on timeout +or cancellation. Successful EOF tests require return code zero, not forced +termination. Official stdio_client context cleanup closes stdin and applies +the SDK's bounded termination fallback. Blocking startup/import subprocesses +use subprocess.run with a timeout. + +Final inspection: +Remaining step/distribution workspaces: [] +Remaining matching test child processes: 0 +The latter used Get-CimInstance Win32_Process, filtered to the exact repository +.venv executable and test/module command patterns; no process was killed by +name. Per-test workspaces and diagnostics were removed in fixture cleanup. +No background services/tasks were launched. Existing ignored scratch/build +products were not deleted or claimed as generated music. + +DEVELOPMENT ISSUES AND CORRECTIONS + +The first test collection failed in both new modules because a module-wide +parametrized anyio_backend marker also affected synchronous tests. Replaced it +with an explicit asyncio backend fixture. Initial strict mypy/lint findings +were corrected using typed test case/name collections, separate capability +checks, narrow SDK-decorator ignores, and Ruff formatting. + +The first executable run then had 49 passed, 1 failed: a test incorrectly +expected id:null to trigger a malformed-input logging notification. Direct SDK +model inspection proved it is parsed as JSONRPCNotification. Split that case +into its own no-response regression and used a genuinely malformed missing- +method message for the stream-error case. Added clean EOF-before-initialization +and internal-output-validation diagnostic coverage. Final focused/full checks +pass with no remaining step-caused failures. + +LIMITATIONS AND STEP 4 READINESS + +No genuine Step 3 blocker remains. The SDK-backed skeleton, honest tools, +strict schemas/errors, startup validation, protocol-clean stdout, EOF cleanup, +tests, documentation, and this report are persistent and verified. + +Ready for Step 4 review/authorization: controlled event-plan MIDI timing, +scheduling, and writing can proceed against the existing typed contracts. +No Step 4 implementation or later prompt was created. + +Generation remains intentionally unavailable until later service wiring. +No production instrument mapping, AGP/SDP layout, lawful native fixture, +Cubase/plugin load-save round trip, or actual application compatibility has +been verified. Those independent evidence gates remain open. No manual client +or application acceptance test ran, and none is represented as a passing +automated test or skip. Only CPython 3.13.13/Windows and the selected dependency +versions were executed; other supported runtimes/platforms/SDK versions are +not certified. Startup syntax checks are not full filesystem confinement. +This is Step 3 readiness, not full-project or production-generation readiness. +``` diff --git a/prompts/report_4.md b/prompts/report_4.md new file mode 100644 index 0000000..7eebc70 --- /dev/null +++ b/prompts/report_4.md @@ -0,0 +1,271 @@ +``` +Step 4 report — exact event-plan MIDI writer and saved-content validator +Date: 2026-10-19 +Result: PASS. Step 4 acceptance is verified; no implementation blocker remains. + +SCOPE AND PRESERVED WORK + +Read the approved plan, reports 1–3, authoritative Score/EventPlan/event/error +models, existing test configuration, and installed Mido/MIDIUtil APIs/source +before implementation. Independently verified the accepted contract/import +baseline rather than treating the prior reports as test execution evidence. + +Created: +- src\riff_groove_builder\midi.py +- tests\unit\test_midi.py +- tests\integration\test_midi_files.py +- prompts\report_4.md + +Updated: +- README.md +- docs\architecture.md + +No schema/model/error/manifest changes were needed. Existing untracked work, +prior prompts/reports, package initializer, server/CLI, and earlier tests were +preserved. No commits, delegation, later prompts, production instrument maps, +native codecs, description/composition, or MCP generation wiring were added. +No dependencies were installed or restored. + +API AND SERIALIZATION DECISIONS + +Public typed APIs: +- beats_to_ticks(Fraction | RationalBeat | int, ppq=960) -> int +- bar_ticks(TimeSignature, bars=1, ppq=960) -> int +- quarter_tempo(tempo_bpm: float) -> int +- validate_event_plan(EventPlan) -> None +- write_midi(path: Path, plan: EventPlan) -> Path +- validate_midi_file(path: Path, plan: EventPlan) -> None + +Mido is the sole production SMF serializer/parser. MIDIUtil is test-only. +Strict Pydantic models are revalidated through the whole mutable graph before +MIDI-specific checks, so mutated lists/fields and unchecked model updates do +not bypass event, payload, timeline, uniqueness, or event-budget validation. +Named failures reuse SerializationError, OutputExistsError, and OutputIOError. +Details contain fixed safe reasons and selected safe numeric/role/part context, +not raw exceptions, descriptions, private paths, or tracebacks. + +Quarter-note timing stays exact. Floats/booleans/string beat positions and +off-grid fractions are rejected. Bar duration is numerator * 4 / denominator +quarter notes, multiplied by bars and PPQ. Relative logical-note offsets and +durations must be representable; a nonzero Score.start is not extra pre-roll. +The writer preserves compiled absolute ticks rather than compiling the score. +PPQ defaults to 960 and must be an integer in 1–32767 (no SMPTE division). +Every delta is an integer in 0–0x0FFFFFFF. Because the conductor has no invented +filler events, its EOT delta spans the plan, so end_tick is also bounded by +0x0FFFFFFF. Oversize gaps fail explicitly instead of being split or rounded. +The existing 100,000 scheduled-event budget excludes bounded SMF metadata. +Tests accept 99,999 and 100,000 events and reject 100,001. + +Tempo means quarter-note BPM regardless of meter denominator. The exact +decimal-rational reciprocal is rounded to nearest microseconds/quarter, ties +to even, within 1–0xFFFFFF. Intent still enforces its existing 20–300 BPM range. +Examples verified: 120 -> 500000; 120.125 -> 499480; 137.5 -> 436364; +102.4 -> 585938 and 61.44 -> 976562 exercise opposite half-even ties. + +SMF type 1 contains Conductor followed by selected part tracks in resolved +order. Names are Conductor/Lead/Bass/Drums, without plugin identity claims. +Conductor tempo and meter are at zero. Supplied notes, keyswitches, velocities, +and CC payloads remain in their part tracks. Exactly one EOT per track uses +the shared end_tick, including empty parts and control-release tails. +No programs, GM drum channel/map, real switches, or control lead times are +invented. Common pre-roll, musical span, and release tails remain unchanged; +musical onsets at/after musical end and out-of-span musical releases fail. + +ORDERING, NOTE PAIRING, AND CHANNEL POLICY + +Events are stable-sorted only by (tick, priority, sequence). Input lists are +not mutated, and valid explicit control causality is not replaced by generic +priority/pitch sorting. Integer absolute ticks become deltas exactly once +when constructing Mido tracks. + +Active notes are keyed by channel/note within a part, with musical/keyswitch +roles retained for validation and diagnostics. Every onset needs a matching +positive-duration same-role release. Orphans, dangling notes, role-mismatched +releases, and same-channel/same-pitch overlaps are rejected. That includes +musical/keyswitch collisions: no ambiguous voice allocation is guessed. +A boundary retrigger must release first in the supplied ordering. A pitch can +change role after release. Different pitches on one part channel are valid +polyphony; the same pitch on separate channels is independent. + +Every used channel belongs to one part for the entire plan, including CC-only +and keyswitch usage. Distinct parts cannot share it even at different times. +A part can own multiple otherwise disjoint channels; empty parts reserve none. +No zero-based channel 9/default drum-channel assumption is made. + +REAL SAVED-FILE VALIDATION AND FAILURES + +The writer serializes and expected-content-validates in memory, exclusively +creates only the requested path with xb, closes it, reads the actual saved +bytes, and parses them with Mido. It compares header/type/PPQ/track count, +names/order, conductor tempo/meter, every absolute message tick and payload, +channels, note/CC/velocity data, event ordering, and shared EOT against expected +content. Exact equality to the already-pair-validated plan also verifies the +saved note pairs. Merely opening a readable MIDI file is not success. +Truncation, corrupt chunks/header, trailing data, and readable wrong content +all fail. An integration fault actually modifies a just-saved file on disk; +the read-back mismatch is detected and the owned file is removed. + +Pre-existing files/directories are rejected; xb also protects a collision +after the precheck. Parent directories are not created. Expected IO/library +failures have narrow catches; unexpected programming errors propagate and +still trigger owned-file cleanup. No MIDI-shaped success/fallback hides errors. +Cleanup checks device/inode identity and never removes a replacement file. +If deletion itself is denied or ownership changes, a named explicit IO error +is returned rather than a success or silent cleanup failure. The standalone +validator never deletes its input, including deliberately corrupt files. + +The API acts only on the supplied Path. Output-root confinement, adversarial +link/race protection, fsync/crash durability, directory publication, requested +format/fallback policy, and MCP integration are not claimed. Step 9 must stage +all artifacts and publish only after every writer succeeds. + +INDEPENDENT MIDIUTIL EVIDENCE + +Four real-disk comparisons pass: +- 4/4, 120 BPM +- 3/4, 137.5 BPM +- 6/8, 120.125 BPM +- 7/8, 137.5 BPM + +Each constructs a synthetic three-part Score/EventPlan, logical score origin +2 beats, 240-tick common pre-roll, triplet durations, same-pitch retrigger, +keyswitches, CC selections/resets, and a 120-tick shared tail. Resolved order +is Bass/Drums/Lead, using channels 5/12/2. All pitches, voices, controllers, +switches, and channels are arbitrary test-local values, not production maps. + +An independent MIDIUtil builder uses explicit addNote(start, duration, volume) +and addControllerEvent calls, not production sorting/timing/render helpers or +iteration over production EventPlan events. Mido parses both saved files. +Normalized note/control events compare exactly by absolute tick, event kind, +channel, pitch/controller, and onset/release velocity or CC value. Explicit +expected event lists independently check all those values and durations. + +Verified and explicitly accounted library conventions: +- MIDIUtil type 1 inserts a conductor ahead of its three user tracks. +- Its time-signature API takes the denominator exponent. +- Its note-off velocity copies the onset velocity. The independent fixture's + supplied release velocities match this convention; comparison does not + discard release velocities. Production separately preserves arbitrary legal + releases, including zero, 17, and 127; no MIDIUtil convention is imposed. +- Its tempo truncates: 137.5 -> 436363 and 120.125 -> 499479. Production correctly + rounds to 436364 and 499480. Tempo is tested separately, not falsely declared + byte/payload-equal across libraries. +- Reference EOTs are local last-event positions; production uses the common + full tail. Both conventions and meter/conductor data are separately asserted. + Only these metadata conventions are excluded from note/control equality. +- Duplicate removal, deinterleaving, and origin adjustment are disabled in the + reference so intended events and pre-roll are not silently transformed. + +Repeated identical production plans, and plans with reversed input event +lists, produce identical bytes with Mido 1.3.3. Cross-library byte equality +and untested dependency-version byte reproducibility are not claimed. + +EXACT VALIDATION COMMANDS AND OUTCOMES + +Environment: Windows AMD64; repository .venv; CPython 3.13.13. +Verified versions: Mido 1.3.3; MIDIUtil 1.2.1; Pydantic 2.14.1; +pytest 9.1.1; Ruff 0.17.1; mypy 2.4.0; MCP 1.30.0. +Other Python versions/OSes/dependency versions were not executed. + +All commands ran at the repository root. Scratch variables: +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +$env:PIP_NO_INDEX = '1' + +Independent pre-implementation accepted-contract/import baseline: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_schemas.py tests\unit\test_errors.py tests\integration\test_contracts.py tests\unit\test_package.py -q +PASS: 325 passed in 1.43s; 0 failed, 0 skipped. + +Final focused new tests: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_midi.py tests\integration\test_midi_files.py -q --tb=short +PASS: 135 passed in 2.27s; 0 failed, 0 skipped. +Breakdown: 110 unit cases and 25 integration cases. + +Final complete suite: +& '.\.venv\Scripts\python.exe' -m pytest -q --tb=short +PASS: 515 passed in 21.73s; 0 failed, 0 skipped; no warnings reported. +Includes all 135 new MIDI cases and every 380 existing regression case: +strict schemas/errors/JSON contracts, import/package smoke, real stdio +protocol/unfinished-handler tests, and both offline distribution build/install +checks. Those existing distribution tests build sdist/wheel with no isolation, +install an isolated wheel venv offline, and verify package imports outside +the checkout; they do not certify plugin compatibility or installed-wheel MIDI. + +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: All checks passed! +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: 28 files already formatted. +& '.\.venv\Scripts\python.exe' -m mypy +PASS: Success: no issues found in 15 source files. +& '.\.venv\Scripts\python.exe' -m pip check +PASS: No broken requirements found. +git --no-pager diff --check +PASS: no tracked-diff whitespace errors. Work remains untracked, so full Ruff +checks additionally cover authored Python rather than relying on git diff. + +Editor runTests was attempted with both absolute new test paths and returned +"No tests found in the files." This is not a pass or skip. The authorized +verified pytest CLI fallback above supplied actual execution evidence. +Editor problems queries reported no errors in all three new Python files. +Strict mypy/lint settings were not relaxed. Only narrow import-untyped ignores +cover the installed Mido/MIDIUtil libraries, which do not provide typing stubs. + +DEVELOPMENT ISSUES AND CORRECTIONS + +Initial lint found three overlong lines; formatting fixed them. Initial mypy +found five variable/literal inference diagnostics; distinct score/event-track +variables and explicit Part list typing fixed them without broad suppression. + +The first focused run had 118 passed and 5 failed: +- Windows xb on an existing directory raised PermissionError rather than + FileExistsError. An existence precheck now reports OutputExistsError, with + exclusive creation retained and a separate collision-race regression. +- Four independent comparisons exposed the actual MIDIUtil release-velocity + convention. Corrected the synthetic equivalent input/expected events to + include those velocities rather than weakening normalization or ignoring + payload differences. The five previously failing cases then passed. + +Added boundary coverage for rational helper mutation, half-even tempo ties, +huge/unrepresentable tempo, PPQ endpoints on disk, MIDI payload endpoints, +keyswitch release tails, invalid paths, short writes, and collision races. +The final focused and complete runs above pass; no known step-caused failure +or unresolved Step 4 implementation issue remains. + +CLEANUP, PERSISTENCE, AND READINESS GATES + +All new MIDI files use unique repository-local .test-artifacts\midi-unit-* +and midi-files-* workspaces, removed by fixture finally cleanup even on failed +tests. No licensed/checked-in binary fixtures or external temporary workspaces +were authored. Injected cleanup-denial residue is explicitly removed after the +test restores normal filesystem operations. Pre-existing ignored scratch, +caches, and build products were preserved. +Final inspection: remaining owned MIDI/distribution/stdio workspaces = 0; +remaining matching repository test child processes = 0. No background services +were started. Prompt inventory stops at step_4.md; no later prompt exists. + +Step 4 acceptance gate: SATISFIED — exact deterministic type 1 SMF from explicit +plans, tested safe ordering/pairing/channels, actual saved-content comparison, +independent MIDIUtil event evidence, explicit failure/cleanup behavior, and all +regressions/lint/format/types passing. Implementation, tests, docs, and this +report persist in the requested repository. + +Can Step 5 start? YES for reviewed profile/compiler mechanics and synthetic +tests after Step 4 acceptance; this report does not authorize invented maps. +Is Step 5's real production-mapping acceptance gate currently satisfiable? NO. +Exact Eclips/Ray product identities/versions, SD3 version/library/preset/map, +lawful evidence for playable ranges, channels, keyswitch/CC semantics, velocity +layers, and actual target behavior remain unverified. Synthetic compiler tests +cannot close that gate; verified vendor/user evidence is still required. + +Native gates remain separately OPEN: AGP/SDP layouts and content semantics, +lawful controlled fixtures/redistribution permission or local-only procedures, +and actual target-plugin/Cubase import/load/save/reload acceptance are missing. +No manual application/client acceptance ran, and none is represented as an +automated pass or skip. Renamed MIDI is not native support. + +The stdio registry remains empty and generate_music remains the reviewed +development-only unfinished handler. This is Step 4 readiness, not a functioning +text-to-music server, instrument-compatible generator, or full-project release. +``` diff --git a/prompts/report_5.md b/prompts/report_5.md new file mode 100644 index 0000000..d4d9ed1 --- /dev/null +++ b/prompts/report_5.md @@ -0,0 +1,333 @@ +``` +Step 5 report — versioned profiles and articulation compiler +Date: 2026-10-19 + +MECHANICS: IMPLEMENTED AND VERIFIED. +FULL STEP 5 PRODUCTION ACCEPTANCE: BLOCKED — authoritative target maps missing. +NATIVE/APPLICATION STATUS: separately unresolved; no native support or acceptance claimed. +READY FOR STEP 6: NO. Passing synthetic mechanics does not close the production gate. + +SCOPE AND CHANGED FILES + +Created: +- src\riff_groove_builder\profiles.py +- src\riff_groove_builder\articulations.py +- src\riff_groove_builder\data\__init__.py +- src\riff_groove_builder\data\profiles\__init__.py +- tests\unit\test_profiles.py +- tests\unit\test_articulations.py +- tests\integration\test_articulation_midi.py +- tests\fixtures\profiles\synthetic-lead.json +- tests\fixtures\profiles\synthetic-bass.json +- tests\fixtures\profiles\synthetic-drums.json +- docs\articulation-profiles.md +- prompts\report_5.md + +Updated: +- README.md +- docs\architecture.md +- docs\compatibility.md + +Reused the approved plan, accepted reports 1–4, current strict domain/error +contracts, and reviewed exact MIDI writer/validator. No shared schemas, errors, +MIDI APIs, manifest, dependency constraints, server/CLI, reviewed tool contract, +or prior report required changes. + +No delegation, commits, later prompts, text composer, native codecs, service +wiring, or replacement of the development-only unfinished generation handler. +The public stdio profile listing remains honestly empty and generation remains +explicitly unimplemented. Generic compiler APIs are not connected to the tools. + +PROFILE API, VALIDATION, AND RESOURCE DECISIONS + +Public internal-pipeline APIs: +- parse_profile(str | bytes) -> InstrumentProfile +- checked_profile(InstrumentProfile) -> InstrumentProfile +- load_profile_registry(*, package=..., declared=...) -> ProfileRegistry +- ProfileRegistry.summaries() -> list[ProfileSummary] +- ProfileRegistry.select(parts, ProfileSelection) -> dict[Part, InstrumentProfile] +- compile_score(Score, dict[Part, InstrumentProfile], *, ppq=960) -> EventPlan + +Schema version is the exact string "1". Models reuse ContractModel, Part, +Channel, MidiData, RationalBeat, PositiveBeat, ProfileSelection, and the reviewed +ProfileSummary. Profiles declare explicit identity/version/build/preset, +provenance, default status, part/channel, inclusive pitched range or logical +drum voice map, canonical normal technique, aliases, velocity layers, and +typed keyswitch/CC actions. There is no generic plugin framework or executable +settings bag. + +JSON parsing rejects duplicate object keys and malformed documents. Strict +models reject unknown fields, invalid numeric types/ranges, inconsistent +identity/provenance/capabilities, ambiguous aliases/voices, invalid controls, +incomplete state declarations, and musical/switch pitch collisions. +Mutable input graphs are defensively revalidated at compiler/registry boundaries. + +Test-only profiles require test.* IDs, SYNTHETIC product names, no claimed vendor +sources, and no default flag. The production registry rejects test-only input +instead of advertising it. Verified metadata requires source coverage for +identity, range/voices, channels, actions, state/reset, timing, and velocity, +with matching versions and explicit build/preset. This validates completeness +of an attestation, not the truth of its assertions; human evidence review is +still mandatory. In-memory registry-policy fixtures use clearly marked +TEST-HARNESS references and are not real evidence or packaged mappings. + +Production resource manifest: + riff_groove_builder.data.profiles.PROFILE_RESOURCES = () +Production profile JSON files: ZERO. +Production public summaries: []. + +Minimal resource package initializers make the explicit empty registry +wheel-safe. importlib.resources, not cwd-relative filesystem paths, loads the +package and checks its JSON resources against the manifest. An absent/broken +package, missing or undeclared JSON, duplicate manifest entries/IDs/defaults, +invalid maps, corrupt documents, and synthetic leakage are explicit failures, +not empty-registry success. + +Selection is deterministic and returns defensive copies. Explicit IDs must +exist and match the requested part. Only an explicitly declared unique verified +default is automatic; even one nondefault requires an explicit choice. +Missing/ambiguous/wrong-part cases use named ProfileRequiredError, +ProfileNotFoundError, AmbiguousProfileError, or ProfilePartMismatchError. +InvalidProfileError/ProfileRegistryError retain SERIALIZATION_ERROR; +ArticulationCompileError and existing timing/writer exceptions cover unsafe +compilation. Unsupported techniques use UnsupportedArticulationError. +Messages are actionable and details contain fixed safe reasons, not raw JSON, +unsupported input text, validation messages, exception causes, or private paths. + +VELOCITY, TIMING, STATE, AND ORDERING + +Intensity intervals cover 0–1 without gaps/overlap: [low, high), with final +high=1 inclusive. Velocity ranges are positive 1–127, ordered, disjoint, and +monotonic. Within a selected layer, complete linear interpolation rounds to +nearest integer, ties to even. No clamping or guessed layers. Tests cover +both endpoints, internal boundaries, and half-even cases. + +Every action lead/gate/release offset is exact rational quarter-note beats. +All declared timing, including unused techniques, must fit the selected PPQ. +Off-grid timing fails through the reviewed beats_to_ticks helper. + +Keyswitches declare pulse/hold, note, velocity, positive gate, lead, and release +offset. Pulse releases use gate and cannot declare a separate release offset. +Holds use gate as a minimum positive duration, releasing after the final +compatible active note plus offset. Undersized holds fail, not silently extend. +Latched switches are pulses. CCs declare selection/reset values and timing; +momentary CCs require explicit resets, and latched CCs cannot declare resets. +Latched techniques explicitly cover the same CC set to prevent state leakage. + +Each selected part owns one explicit, distinct channel, including empty tracks. +No default channel-9 drum route, GM-as-SD3 map, pitch, controller, or technique +is invented. Voice and articulation resolution uses only the selected map. + +Latched selections deduplicate across compatible overlaps and repeated notes +through rests. Controlled overlapping notes must use the same canonical +technique; incompatible overlaps and too-early selection leads fail explicitly. +Velocity-only profiles permit overlapping different techniques without global +control state. Same physical musical-pitch overlaps are never merged away. + +Compatible momentary notes form one active interval. Held switches stay active +until its last release; CC selections and pulse switches remain per-note. +Final CC resets/held-switch releases respect declared offsets. Per-note pulses +that overlap the same physical switch fail; exact off/on retrigger boundaries +are preserved. + +A momentary overlay establishes the actual declared normal selection first +when needed, finishing positive baseline switch pulses before overlay controls. +After final release/reset, normal is restored using its actual actions, not +a universal invented reset. Setup/restoration needs enough room before later +demands. Ambiguous overlapping state/physical controls fail conservatively. + +Raw exact integer schedules determine one common pre-roll: +max(0, -earliest scheduled event). All parts shift equally; Score.start is only +a logical origin. The shared end includes musical duration, physical switch/ +reset tails, and declared normal-restoration readiness even when that readiness +occurs after the final physical event. + +Same-tick priorities: +0 = musical/switch releases +10 = CC resets +20 = selection/restoration switches and CCs, causally sequenced +30 = musical onsets + +Per-track sequences are unique and deterministic. All musical/switch notes have +positive-duration paired releases. The compiler enforces the 100,000-event +budget incrementally, constructs the reviewed EventPlan, and calls +validate_event_plan before returning. Tests accept exactly 100,000 events and +reject overflow. No success-shaped fallback hides errors. + +REAL MIDI AND WHEEL EVIDENCE + +The synthetic three-part integration score uses logical origin 2 beats, +arbitrary channels 2/5/12, overlapping compatible palm-muted lead/bass/drum +notes, explicit normal restoration, and boundary musical retriggers. +Independent hand-derived absolute event lists check every compiled event and +the real saved file parsed by Mido. Expected common boundaries: +- musical_start_tick = 120 +- musical_end_tick = 3960 +- shared end_tick = 4020 + +Tests check note/keyswitch pairing and positive durations, channels, velocity, +CC selections/resets, event ordering, conductor tempo, all track EOTs, actual +saved-content validation, and repeat output byte equality with tested Mido. +These arbitrary fixture values are NOT real Eclips/Ray/SD3 or GM evidence. +All prior independent MIDIUtil writer/read-back regressions also pass unchanged. + +The new wheel test builds sdist then wheel offline with --no-isolation, installs +the wheel offline with --no-deps into a unique target, and probes both that +installation and direct wheel-ZIP resource loading from outside the checkout. +Probes use -I -B and the existing development runtime dependencies; they prove +resource/import layout, not every dependency version or a clean full dependency +installation. They verify the imported profiles module location, package +initializers, empty manifest/JSON set, empty summaries, and typed missing map. + +Final focused probe evidence: +cwd: D:\_Repos\Code\GAJ3T\MCPs\MusicGen +isolated: 1 +profiles: [] +installed module: +.test-artifacts\articulation-caf1de20694445e99ca53ec51b44680f\installed\riff_groove_builder\profiles.py +ZIP module: +.test-artifacts\articulation-caf1de20694445e99ca53ec51b44680f\dist\gaj3t_musicgen_riff_groove_builder-0.1.0-py3-none-any.whl\riff_groove_builder\profiles.py + +Both locations were actual wheel contents, not source/editable profile imports. +Their unique workspace was removed after the checks. Existing distribution +tests additionally build/install an isolated package-only wheel venv and check +silent initializer imports outside the checkout. + +BOUNDED PUBLIC OFFICIAL EVIDENCE CHECK + +Exactly three unauthenticated public official URLs were fetched on 2026-10-19: + +1. https://www.amplesound.net/en/manual.asp + Returned only "amplesound.net", not usable mapping documentation. + No exact Eclips/Ray edition/build, numeric ranges, switches, channels, + timing, CC/reset rules, or velocity-layer evidence was obtained. + +2. https://www.toontrack.com/manual/superior-drummer-3/ + Page states login is required to view Toontrack manuals. + No credentials, authentication, or access bypass was attempted. + No usable selected SD3 mapping/build/library/preset details were obtained. + +3. https://www.toontrack.com/product/superior-drummer-3/ + Retrieved trademark/registered-design notices, not the required numeric map, + switching semantics, or installed preset/library/build information. + +Research stopped there rather than guessing URLs or spending the session on +unresolved documentation. Existing evidence and prior reports likewise contain +no verified target map. No private files/code/credentials were sent to third +parties; no licensed manual was copied or user fixture uploaded. + +Finding: production mapping evidence remains unresolved. ZERO production +profiles were invented. Passing synthetic mechanics cannot establish actual +target compatibility, close the production gate, or authorize native_available. + +EXACT VERIFICATION COMMANDS AND OUTCOMES + +Environment: repository .venv; Windows AMD64; CPython 3.13.13. +Existing tested environment: Pydantic 2.14.1, Mido 1.3.3, MIDIUtil 1.2.1, +MCP 1.30.0, pytest 9.1.1, Ruff 0.17.1, mypy 2.4.0. +No dependency manifests changed and no runtime/dev dependencies were installed +or restored. Package-only offline wheel installation occurred inside tests. +Other runtimes, OSes, vendor instruments, and dependency versions were not run. + +Commands ran from the repository root. Repository-local scratch setup: +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +$env:PIP_NO_INDEX = '1' + +Final focused new tests: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_profiles.py tests\unit\test_articulations.py tests\integration\test_articulation_midi.py -q -s --tb=short +PASS: 137 passed in 9.11s; 0 failed, 0 skipped; no warnings reported. +Includes real MIDI disk read-back and built-wheel installed/ZIP resource probes. +Used the explicitly authorized known-working repository-venv pytest fallback; +no editor test-discovery pass is claimed. + +Directly affected accepted regressions: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_midi.py tests\integration\test_midi_files.py tests\unit\test_schemas.py tests\unit\test_errors.py tests\integration\test_contracts.py tests\unit\test_server.py tests\integration\test_stdio.py tests\unit\test_package.py tests\integration\test_distribution.py -q --tb=short +PASS: 515 passed in 22.01s; 0 failed, 0 skipped. +Includes all accepted MIDI, contract/error, real stdio/unfinished-handler, +package, and distribution checks. + +Final complete current suite: +& '.\.venv\Scripts\python.exe' -m pytest -q --tb=short +PASS: 652 passed in 30.88s; 0 failed, 0 skipped; no warnings reported. +All 515 prior regressions and 137 new checks pass together on final code. + +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: All checks passed! +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: 38 files already formatted. +& '.\.venv\Scripts\python.exe' -m mypy +PASS: Success: no issues found in 22 source files. +& '.\.venv\Scripts\python.exe' -m pip check +PASS: No broken requirements found. +git --no-pager diff --check +PASS: no tracked-diff whitespace errors. Existing work is untracked; full Ruff +checks additionally cover the new Python files rather than relying on git diff. +Editor problems queries: no errors in both new source modules and all three +new test modules. Strict lint/type configuration was not weakened. + +Formatting command used during implementation: +& '.\.venv\Scripts\python.exe' -m ruff format src\riff_groove_builder\profiles.py src\riff_groove_builder\articulations.py tests\unit\test_profiles.py tests\unit\test_articulations.py tests\integration\test_articulation_midi.py +Resource initializers were also included in the initial formatting pass. + +ISSUES AND CORRECTIONS + +The initial focused run passed 122 tests. Early static checks found union-list +attribute inference, test exception-variable inference, invariant note-list +typing, formatting/line lengths, and one missing explicit zip(strict=False). +These were fixed with precise annotations, distinct variable names, and normal +formatting; no broad suppressions or checker relaxation. + +Additional inspection and regressions tightened disjoint velocity ranges, +complete half-even interpolation rather than rounding only the velocity offset, +mutated-profile serialization safety, selection-part validation, and shared +end coverage for normal-restoration readiness after the last physical event. +Expanded focused runs passed 135, then final 137 tests; the earlier complete +650-test run was superseded by the final 652-test run above. + +An early direct-wheel build left an ignored root build directory. The wheel +test now builds through the sdist with all intermediates in its unique local +scratch workspace; the owned root build directory was removed. Final inspection: +- remaining owned articulation/distribution/MIDI/stdio test workspaces: 0 +- root build directory present: false +- remaining matching repository Python test child processes: 0 +- production profile JSON count: 0 +Pre-existing venv, scratch, caches, and dist products were preserved. +No background services were started. Test subprocess waits are bounded and +unique workspaces are removed in fixture finally cleanup. + +PRECISE PRODUCTION/NATIVE BLOCKERS AND READINESS + +To close full Step 5 production acceptance, obtain lawful authoritative evidence +and reviewable provenance for EACH requested real target: +- exact Eclips/Ray vendor product name, edition and installed build/version; +- exact SD3 installed build, library, active map and mapping/preset version; +- numeric playable ranges or every logical drum voice's physical MIDI number; +- actual zero-based channels and channel-state assumptions; +- canonical techniques/aliases, numeric keyswitches and positive velocities; +- latch/hold/momentary behavior, retrigger/polyphony constraints and normal state; +- CC selections, reset values, interaction rules and normal-restoration actions; +- explicit lead/gate/release/reset timing representable at selected PPQ; +- complete velocity-layer boundaries and intensity behavior; +- source/version/permission records and target-behavior verification. + +Octave labels alone, assumed GM maps, generic product pages, and synthetic +values do not satisfy those requirements. Metadata attestations do not replace +review of the underlying evidence. No such evidence was fabricated here. + +Native gates remain independently OPEN: AGP/SDP musical-content semantics, +supported layouts/versions, lawful controlled exports/permission or local-only +procedures, and real plugin/Cubase load/save/reload acceptance. Native files +were not generated. No application acceptance test ran or was counted as a +passing automated test or skip. MIDI mapping evidence alone could not close +those native gates. + +Conclusion: +- Generic versioned profile/articulation compiler mechanics: VERIFIED. +- Full Step 5 production acceptance: BLOCKED by missing real mapping evidence. +- Production registry: explicitly and reliably EMPTY, including built wheels. +- Native and actual application compatibility: UNVERIFIED, separately gated. +- Ready for Step 6: NO. Stop here; no later prompt or implementation started. +``` diff --git a/prompts/report_5_fix.md b/prompts/report_5_fix.md new file mode 100644 index 0000000..67ba499 --- /dev/null +++ b/prompts/report_5_fix.md @@ -0,0 +1,237 @@ +``` +Step 5 fix report — explicitly labeled Standard MIDI fallback +Date: 2026-10-19 + +CURRENT EXECUTABLE OBJECTIVE: IMPLEMENTED AND VERIFIED. +STEP 6 READINESS: YES, using Standard MIDI fallback only. +VERIFIED VENDOR MAPS: NONE; Eclips/Ray/SD3 mapping gates remain open. +NATIVE/APPLICATION ACCEPTANCE: UNVERIFIED; no native support claimed. + +SCOPE AND PERSISTENT CHANGES + +Implemented only the current objective at the top of prompts\step_5_fix.md, +following the amended continuation decision in prompts\plan.md and reviewing +report_5.md, existing contracts, profile/compiler code and tests. Historical +vendor-only stop wording was not treated as a blocker for standard fallback. + +Created: +- src\riff_groove_builder\data\profiles\standard-midi-lead-v1.json +- src\riff_groove_builder\data\profiles\standard-midi-bass-v1.json +- src\riff_groove_builder\data\profiles\general-midi-percussion-v1.json +- tests\unit\test_standard_profiles.py +- prompts\report_5_fix.md + +Updated: +- src\riff_groove_builder\schemas.py +- src\riff_groove_builder\profiles.py +- src\riff_groove_builder\errors.py +- src\riff_groove_builder\data\profiles\__init__.py +- tests\unit\test_profiles.py +- tests\unit\test_schemas.py +- tests\integration\test_contracts.py +- tests\integration\test_articulation_midi.py +- README.md +- docs\architecture.md +- docs\articulation-profiles.md +- docs\compatibility.md +- docs\formats\agp.md + +No delegation, commits, later prompts, parser/composer, native codecs, service +wiring, dependency-manifest changes or dependency restoration. Existing server, +CLI, generic compiler, MIDI writer, synthetic fixtures and previous reports +were not edited. The Step 3 server still lists no profiles and returns its +unfinished generation error until Step 9; no service completion is claimed. + +PUBLIC CONTRACT AND PROVENANCE + +ProfileSummary.mapping_kind is precisely typed as instrument | standard_midi. +Its backward-compatible default is instrument. Existing fixtures/models retain +that default; serialized summaries expose the discriminator. JSON Schema and +model validation agree on the new enum and standard normal-only/native-false +conditions. Existing strict/extra-forbid/numeric validation is preserved. + +Provenance adds status=standard_midi, distinct from verified and test_only. +Standard mapping kind and provenance must agree. Standard profiles require +public standard identity/range-or-voice facts and separately referenced +generator channel/action/state/timing/velocity policy. New standard_public +and generator_policy source kinds cannot satisfy verified vendor provenance. +Existing verified profiles still require complete official/lawful evidence. +Test-only identities remain excluded from production, with no fixture promotion. + +Standard profiles are constrained to canonical normal, alias sustain, +latched/action-free behavior, explicit Standard/General MIDI product labels, +and no native capability. Unsupported techniques are explicit named errors. +Error wording no longer calls an arbitrary selected standard profile verified; +error codes and envelope shapes were not changed. + +THREE PRODUCTION PROFILES, NOT VERIFIED INSTRUMENT MAPS + +ID Standard/product version Mapping version Channel +standard.lead.v1 MIDI 1.0 standard-fallback-1 0 +standard.bass.v1 MIDI 1.0 standard-fallback-1 1 +standard.gm-drums.v1 General MIDI Level 1 standard-fallback-1 9 + +Exactly these three JSON resources are declared and packaged. Each is the unique +default for its part; explicit-ID selection remains available and defensive. +Pitched profiles accept inclusive legal MIDI note numbers 0–127, not asserted +Eclips/Ray playable ranges. The drum profile explicitly declares all 47 GM Level +1 sounds, note numbers 35–81. It is NOT the SD3 default map. + +Channels 0/1 are generator routing policy; channel 9 explicitly selects GM's +human-numbered percussion channel 10. Intended instrument routing fields remain +eclips/ray/sd3, disambiguated by mapping_kind, product names and public limitations. +No installed vendor build or preset is asserted: target_build/mapping_preset +explicitly identify standards/policy and the absence of verified vendor setup. + +All three profiles use normal/sustain only, no keyswitches, CC actions, pedal, +program/bank changes or GM initialization. Sustain is a normal-technique alias, +not CC64. Every undeclared requested technique fails rather than being simulated. +Single-interval dynamics use round(1 + 126 * intensity), ties to even: +0 -> 1, .25 -> 32, .5 -> 64, .75 -> 96, 1 -> 127. +These are positive MIDI velocities and generator policy, not vendor layers. +Exact score starts/durations are retained; no control pre-roll/tails are added. +Receiver configuration and drum choke behavior remain external. + +EVIDENCE AND SOURCE IDS — CHECKED 2026-10-19 + +MIDI1-MESSAGES: +https://midi.org/summary-of-midi-1-0-messages +Official MIDI Association table exposes seven-bit note/velocity fields and +zero-based channels 0–15. Supports legal pitched-note numbers 0–127 and MIDI +message identity, not vendor playable ranges or routing defaults. +Used by standard.lead.v1 and standard.bass.v1 as standard_public provenance. + +GM1-OVERVIEW: +https://midi.org/general-midi-level-1 +Official MIDI Association overview establishes GM Level 1 and standardized +sound names, not acoustic timbre. It alone is not a numerical percussion map. +Used by standard.gm-drums.v1 for standard identity. + +GM1-PERCUSSION-TABLE: +https://computermusicresource.com/GM.Percussion.KeyMap.html +Accessible Computer Music Resource teaching table identifies Vanderbilt +University's Blair School of Music, explicitly gives GM channel 10 and all +47 number-to-sound pairs 35–81. Independently checked core entries: +35 acoustic bass drum; 36 bass drum 1; 38 acoustic snare; 42 closed hi-hat; +44 pedal hi-hat; 46 open hi-hat; 49 crash cymbal 1; 51 ride cymbal 1; +81 open triangle. Tests independently transcribe/assert all 47 pairs. +Octave labels were not used to derive numeric notes. +Used by standard.gm-drums.v1 for percussion facts, never SD3 verification. + +GENERATOR-POLICY-V1: +docs/articulation-profiles.md#standard-fallback-policy-v1 +Separately documents routing, aliases, legal pitched acceptance, action-free +normal/sustain, timing and intensity policy. All three profiles reference it. +External facts are not misrepresented as evidence for generator-specific policy. + +CORRECTED AMPLE DOCUMENTATION + +The raw HTML of https://www.amplesound.net/en/manual.asp was checked in memory. +It exposes these exact relative public links under https://www.amplesound.net/en/: +- Main_Panel_Manual-AME.pdf +- Main_Panel_Manual-AMR.pdf +- Guitar_Riffer.pdf +- Guitar_Strummer.pdf +- Settings_and_CPCv2.pdf + +Compatibility, profile, architecture/README status and AGP evidence documentation +were corrected. The earlier simplified extraction missed links; it did not prove +that the manual page contained only a domain label. Discovering public manuals +does not verify installed versions/maps, resolve octave-label interpretation +or establish native layouts. No manual or factory MIDI song was copied into +the repository, and no authenticated vendor access was attempted. + +ACTUAL VALIDATION COMMANDS AND RESULTS + +Environment: existing repository .venv, Windows AMD64, CPython 3.13.13. +No other Python/OS/plugin configurations are certified by these runs. +Commands below ran from the repository root. Repository-local scratch setup: + +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +$env:PIP_NO_INDEX = '1' + +Focused schema/profile/compiler/MIDI/wheel validation: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_profiles.py tests\unit\test_standard_profiles.py tests\unit\test_schemas.py tests\integration\test_contracts.py tests\integration\test_articulation_midi.py -q -s --tb=short +PASS: 453 passed in 4.24s; 0 failed, 0 skipped. +Includes installed and ZIP-wheel profile evidence, independent standard MIDI +events/read-back, defaults, all GM numbers, provenance and schema regressions. + +Final full current suite, after all code corrections: +& '.\.venv\Scripts\python.exe' -m pytest -q --tb=short +PASS: 700 passed in 31.00s; 0 failed, 0 skipped; no warnings reported. +This is 48 additional cases over the previous 652-test suite. Existing generic +switch/CC/state/timing, contract, errors, writer, distribution and real stdio +skeleton regressions remain passing. Unsupported standard techniques/voices +fail honestly; no synthetic/vendor maps appear in the production registry. + +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: All checks passed! +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: 41 files already formatted. +& '.\.venv\Scripts\python.exe' -m mypy +PASS: Success: no issues found in 23 source files. +& '.\.venv\Scripts\python.exe' -m pip check +PASS: No broken requirements found. +git --no-pager diff --check +PASS: no tracked-diff whitespace errors. Existing implementation files are +untracked in this worktree; Ruff checks cover the actual Python files too. + +Additional final wheel-only verification: +& '.\.venv\Scripts\python.exe' -m pytest tests\integration\test_articulation_midi.py -k built_wheel_standard_registry -q -s --tb=short +PASS: 1 passed, 8 deselected in 2.73s; 0 failed, 0 skipped. +The test builds through an actual sdist/wheel using build --no-isolation, +installs the package offline/no-deps into its isolated target, and probes both +the installed target and wheel ZIP with Python -I -B from ROOT.parent, outside +the checkout. Both actual module locations were printed and validated; both +reported isolated=1 and exactly: + standard.bass.v1, standard.gm-drums.v1, standard.lead.v1 +Probes check the exact JSON manifest, standard-only metadata, no synthetic +identity or verified vendor status, normal/sustain, default channels 0/1/9 and +core drum numbers. Full-suite distribution tests additionally build both +artifacts and import from a real isolated wheel venv outside the checkout. +These are packaging/MIDI tests, not target-application acceptance. + +Editor problems checks reported no errors in all changed Python modules/tests. +Editor runTests found no discovered tests for the supplied absolute paths; +the actual repository-venv pytest runs above provide execution evidence instead. + +ISSUES RESOLVED AND CLEANUP + +- Initial strict typing identified an unannotated heterogeneous test-update + collection and a test assuming channel lived on EventTrack. Added a precise + list annotation and asserted actual per-event channels; no suppressions. +- Ruff found one 102-column error-message line; wrapped it without changing + its value. Final full suite and all static checks pass on the corrected code. +- Two candidate CMU table URLs returned 404; the accessible Vanderbilt teaching + table supplied the numerical evidence. Missing vendor maps were not treated + as a standard-fallback implementation blocker. +- Final owned articulation/distribution/MIDI/stdio workspace count: 0. + Root build directory: absent. Unique wheel/test workspaces clean themselves. + Existing venv, caches, dist products and repository scratch were preserved. + No background services were started. + +REMAINING GATES AND FINAL DECISION + +Standard MIDI fallback registry, selection, compilation, real SMF read-back and +wheel resources: VERIFIED and persistent. + +Verified Eclips/Ray/SD3 maps: STILL OPEN. Exact installed products/builds, +libraries/presets/active maps, numeric playable ranges/controls, switching and +reset timing, vendor layers and target behavior require separate evidence. +Public manual links and GM facts do not verify those configurations. + +Native AGP/SDP: STILL OPEN. Musical-content semantics, actual supported layouts, +lawful controlled exports/permissions and plugin/Cubase load/save/reload +acceptance remain unverified. No native files were serialized. + +Actual application acceptance: NOT RUN, not counted as a passing test or skip. +Future generation results must expose standard-only identity and warnings; +the unchanged server remains development-only until Step 9 service wiring. + +Ready for Step 6: YES, STANDARD FALLBACK ONLY, as permitted by the amended plan. +No later prompt or implementation was started. This is not completion of the +vendor mapping, native, application, service or full-project gates. Stop here. +``` diff --git a/prompts/report_6.md b/prompts/report_6.md new file mode 100644 index 0000000..30fd914 --- /dev/null +++ b/prompts/report_6.md @@ -0,0 +1,275 @@ +``` +Step 6 report — deterministic description and coordinated Standard MIDI +Date: 2026-10-19 + +OUTCOME: IMPLEMENTED, PERSISTENT AND VERIFIED. +FINAL VALIDATION: 868 passed; 0 failed; 0 skipped. +STANDARD MIDI ONLY: no verified vendor maps, native formats or application acceptance. +NEXT-STEP STATUS: ready for Step 6 review; native evidence gates remain open. + +SCOPE + +Read prompts\step_6.md, the amended approved plan's continuation decision and +Step 6 scope, accepted report_5_fix.md, current request/intent/score/result/error +contracts, profile models/registry, compiler, exact timing helpers and writer. +Implemented only the owned Step 6 surfaces: + +Created: +- src\riff_groove_builder\description.py +- src\riff_groove_builder\compose.py +- tests\unit\test_description.py +- tests\unit\test_compose.py +- tests\integration\test_text_to_midi.py +- prompts\report_6.md + +Updated: +- README.md +- docs\architecture.md + +No shared contract, profile/resource, compiler, MIDI writer, Step 3 handler, +dependency manifest or earlier report/plan was changed by this step. +No network/model service, audio, native codec, MCP wiring, later-prompt work, +commit or delegation. Existing unrelated/pre-existing worktree changes remain. + +APIS AND RESOLUTION + +resolve_description(request: GenerateMusicRequest) -> DescriptionResolution +returns intent: MusicalIntent, assumptions: unique list[str], overrides: +unique list[str]. These records are suitable for future ResolvedGeneration, +not a fabricated GenerationResult. It revalidates mutable request graphs. + +compose_score(intent: MusicalIntent, selected_profiles: +dict[Part, InstrumentProfile], *, ppq=960) -> Score revalidates intent/profiles. +Call the authoritative registry's select(intent.parts, request.profiles or +ProfileSelection()), compose, compile_score, then write_midi. Nondefault PPQ +must also be passed to compile_score. No parser/composer filesystem IO occurs. + +Structured non-null tempo/bars/meter/key/parts win over text, even contradictory +or out-of-bounds scalar candidates for that field. Every structured value is +disclosed with its text candidates, including when none were present. +Null remains unresolved. Unknown material/changing instructions cannot be +authorized by these overrides. Equivalent repeated values and enharmonic keys +are not contradictions; distinct unresolved candidates are actionable errors. +Textual part order is lead,bass,drums; structured order is preserved. + +EXACT SUPPORTED GRAMMAR AND DEFAULTS + +This is a closed grammar, not free-form language or a general genre engine. +Case is folded, whitespace collapsed, whole words matched. Clauses may appear +in any order. The following are global instructions, not per-part schedules: + +- Numeric BPM: signed decimal number followed by BPM, optional whitespace, + final 20-300 quarter-note beats/minute. Example: 137.5 BPM. No fractional + notation, exponent, textual numbers, beat-unit conversion or tempo changes. +- Bars: signed numeric value followed by bar/bars; integer-valued 1-256. + 4.0 bars is accepted as four; 1.5 bars is not. +- Meter: n/d, optional spaces around slash; optional in/meter filler. + Numerator 1-16; denominator 1,2,4,8,16. No changing or mixed meters. +- Key: A-G, optional one ASCII #/b, major/minor. Natural minor only. + Existing canonical sharp spelling is retained: Bb major -> A# major. +- Lead aliases: lead, lead guitar, guitar, riff. +- Bass aliases: bass, bass guitar, bass riff/groove, bass guitar riff/groove. + Here riff/groove means either word, not a literal slash. +- Drum aliases: drum, drums, optionally followed by groove. +- Part lists: comma, and, &, +; separate positive mentions also combine. + Prefix only or suffix only selects that whole contiguous list. + Example: only bass and drums; lead and bass only. +- Exclusions: no/without/exclude plus a contiguous part list. + no drums selects lead+bass; without bass and drums selects lead. + Exclusions alone subtract from all three and disclose that baseline. + Positive/excluded overlap, an outside positive part after only-selection, + or an empty selection is an error unless structured parts override it. + Ambiguous negated-only syntax is rejected. +- Subdivision: quarter, eighth, sixteenth, optionally " note"/" notes" or + "-note"/"-notes". Exact slots are 1,1/2,1/4 quarter-note beats. +- Rest policy: rest/rests omits the final slot of every bar; + no rest/no rests omits none. No arbitrary rest schedule. +- Template: rock or metal; simple original policies, not genre fidelity. +- slow/fast are fixed tempo candidates 80/160 BPM. Distinct numeric/qualitative + candidates conflict without a structured tempo override. +- normal and sustain are the same global normal technique, not CC64. +- palm mute, palm-mute, palm muted, palm-muted retain canonical palm_mute. + Composition must validate it against every selected profile, even for silence. + +Defaults, each disclosed as an assumption when omitted: +120 BPM, four bars, 4/4, E minor, lead+bass+drums, +eighth, rock, no_rests, normal. Seed is the existing request seed (default 0), +not a parsed text instruction. + +Only these exact filler words are ignored: +please create generate make write a an the some simple music pattern groove +for with and at in of on notes note key tempo meter straight + +Comma, period, semicolon, colon, !, ?, &, + are separators. Other unknown +tokens/punctuation fail. Require a recognized instruction or music/pattern/ +groove: filler-only "please" fails. No bassoon->bass or leadership->lead match. +Negation is supported only for the documented part and rest grammar. + +Unsupported instruments, modes, other techniques, vendor-name selection, +triplets, swing, polyrhythm, sections, audio and changing instructions fail, +not disappear into a default. then/to/from, changes/changing, ramp, +accelerando/ritardando/rallentando, speed up and slow down are rejected. +No song sections, per-part instructions, arbitrary dynamics/rests/durations, +chord/individual-note syntax or extra modes are claimed. + +DescriptionConflictError is an UnsupportedDescriptionError subtype with +UNSUPPORTED_DESCRIPTION and the field to correct. Other unsupported/invalid +text uses UnsupportedDescriptionError; invalid mutated request models use +InvalidRequestError. The composer uses named CompositionError for unsafe +intent/range/voice/channel/coverage/budget conditions and preserves exact +timing/profile errors. UnsupportedArticulationError identifies part, profile +and unavailable requested technique. No raw network/vendor inference exists. + +COMPOSITION POLICY + +- Common score origin 0 and exact end bars*numerator*4/denominator quarter + beats. Each part and actual MIDI EOT share this duration, including rests. +- Slots restart per bar. Only the final slot may shorten to the bar boundary, + e.g. quarter notes in 7/8 end with 1/2 beat. This is explicit truncation of + a note slot, never a change to requested musical length. +- Rests remove the final slot/hits of every bar. A single-slot bar can be + entirely silent and still retain its full shared duration. +- Major intervals 0,2,4,5,7,9,11; natural minor 0,2,3,5,7,8,10. + Require the full lead scale or bass root/fifth pair inside actual map range. + Choose the root nearest 64 for lead, 40 for bass among valid palettes; + lower root breaks ties. MIDI octave convention C4=60, E4=64, E2=40. + No clamping, dropped degrees, chromatic pitches or invented vendor ranges. +- Lead zero-based rock degrees (0,2,4,6), metal (0,0,4,1), with each bar's + first slot root; other slots add seeded 0/1 modulo seven. + Bass rock alternates root/fifth; metal uses root,root,fifth,root. +- Drums resolve closed_hat, kick and snare aliases through the selected map. + Hat each active slot; pulse=max(subdivision,4/denominator). + At pulse-aligned slots alternate kick/snare from kick each bar. + Metal adds off-pulse kick. This explicit odd/compound-meter policy is not + automatic grouping or a claim of idiomatic 6/8 accents. +- Pitched gates fill slots; drum gates=min(slot length,1/4 beat). + Same-pitch notes never overlap; compiler releases before boundary retriggers. +- Intensities are seeded choices 0.5,0.625,0.75, shared by simultaneous hits. + Profiles perform their supported real velocity conversion. +- Local Random(seed+0/1/2 for lead/bass/drums) never changes global state. + Adding/reordering parts does not perturb another part's notes. +- Before note allocation, exact active-slot/hit counts reserve at least + note-on/off pairs within 100,000 events. The compiler still validates extra + controls. Extreme valid requests fail early without excessive allocation. +- Existing exact tick helpers check total/slot/gate timing; no rounding. + Default 960 PPQ supports every documented straight grid and meter. + +Only existing real standard.lead.v1, standard.bass.v1, standard.gm-drums.v1 +are selected in production integration, with normal/sustain and channels 0/1/9. +No keyswitches/CCs/pedal/program/bank/GM initialization are invented. +Standard palm mute fails before any artifact, never becomes softer generic MIDI. +One synthetic switch-profile unit test proves real compiler/pre-roll coupling, +explicitly test-only and never vendor compatibility. +Keys affect actual pitches; the unchanged writer does not add key-signature meta. + +MEASURABLE ACTUAL-DISK EVIDENCE + +Tests resolve, compose, select real standard profiles, compile, exclusively +write MIDI, validate actual bytes, and independently read them with Mido. +Assertions cover tempo/meter, common end, track names/channels, in-key/range +pitches, physical GM voices, positive velocities, and complete note pairing. + +Representative descriptions and independently checked ends at 960 PPQ: +- Lead only: 90 BPM, 2 bars, 3/4, D major, quarter -> 5760 ticks. +- Bass only: 72.5 BPM, 3 bars, 6/8, Bb minor, eighth -> 8640 ticks. +- Drums only: 155 BPM, 2 bars, 7/8, sixteenth -> 6720 ticks. +- All parts: 137.5 BPM, 4 bars, 4/4, F# minor, eighth -> 15360 ticks. +- No drums: 111 BPM, 1 bar, 7/8, Eb major, quarter rests -> 3360 ticks. + +Independent exact bass case: "bass only 1 bar C major quarter", seed 0: +channel 1, pitches 36/43/36/43, velocities 64/96/64/80; +onsets 0/960/1920/2880, offs 960/1920/2880/3840. +Independent exact drum case: quarter, 1 bar, seed 0: +channel 9, kick/snare/kick/snare 36/38/36/38 plus closed hat 42; +onsets 0/960/1920/2880, each gate 240 ticks; +slot velocities 64/64/64/80, common EOT 3840. +Expected event payloads/order are hand-specified, not copied from compiler output. + +For one 4/4 bar, read-back note-on counts bass/drums: +quarter 4/8; eighth 8/12; sixteenth 16/20; +eighth rests 7/11; eighth metal 8/16. +Bass onsets are independently asserted as 960/480/240 tick grids; rest omits +the final eighth onset at 3360 while EOT remains 3840. +Same input/seed produces identical score/events and actual file bytes; +changed seed changes content. Key changes pitches; tempo changes conductor +metadata without changing tick positions; bars/meter change exact common end. +Unsupported palm mute/slide/audio cases create no file or child artifact. + +VALIDATION — EXACT FINAL COMMANDS AND OUTCOMES + +Environment: existing .venv, CPython 3.13.13, Windows AMD64. +No additional runtime/OS/plugin configuration is certified. +No dependencies were installed/restored or manifests changed. +Shell setup for test/build subprocesses (repository-local scratch): + +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +$env:PIP_NO_INDEX = '1' + +Focused final command: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_description.py tests\unit\test_compose.py tests\integration\test_text_to_midi.py -q --tb=short +PASS: 168 passed in 1.12s; 0 failed; 0 skipped. + +Full current suite: +& '.\.venv\Scripts\python.exe' -m pytest -q --tb=short +PASS: 868 passed in 32.41s; 0 failed; 0 skipped. +Includes previous schemas/errors, profile/standard-map/compiler/MIDI, +protocol/stdio, packaging/distribution and installed-wheel/resource regressions. + +Owned-file formatting: +& '.\.venv\Scripts\python.exe' -m ruff format src\riff_groove_builder\description.py src\riff_groove_builder\compose.py tests\unit\test_description.py tests\unit\test_compose.py tests\integration\test_text_to_midi.py +PASS: 5 files reformatted. + +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: All checks passed. + +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: 48 files already formatted. + +& '.\.venv\Scripts\python.exe' -m mypy --strict src tests +PASS: Success: no issues found in 28 source files. + +Editor problems: no errors in all five new Python files. +Editor runTests reported no discovered tests for supplied absolute paths; +the actual repository-venv pytest CLI fallback above is the execution evidence. +No failing/skipped pytest result is hidden by that discovery limitation. + +ISSUES ENCOUNTERED AND RESOLVED + +- Initial collection failed with two errors because standalone TypeAdapter(Key) + used Pydantic's default Rust regex engine, which cannot compile the existing + key contract's lookaround. Configured this owned adapter with strict=True and + python-re, matching the authoritative contract. No shared contract was changed. +- Initial Ruff found three local issues (zip strictness and long lines). + Replaced zip with enumerated names and wrapped/formatted the owned code. + Final whole-project lint/format and strict mypy pass without new suppressions. +- Explicit tempo bounds are checked as Fraction before float conversion, so + an extreme 3500-digit textual BPM yields a named error, not OverflowError. + The same scalar can be replaced by a valid disclosed structured override. +- Bass guitar is parsed as the bass phrase rather than accidentally requesting + lead as well. Negation/only/conflict/whole-word tests verify actual behavior. +- Intermediate focused checks passed 141 then 156 tests; final expanded focused + count is 168 and the full suite is 868. No implementation blocker remains. + +CLEANUP AND LIMITATIONS + +All owned UUID test/build/stdio/MIDI children cleaned up; final relevant child +workspace count 0, root build directory absent. Existing scratch, caches, venv, +dist products and unrelated worktree content were preserved. +No background processes/services were started or left running. + +This is tested bounded Standard MIDI composition, not a neural model, +instrument emulation, genre engine, native writer or end-to-end MCP service. +Real Eclips/Ray/SD3 maps, installed versions/presets, keyswitch/control behavior, +vendor layering, AGP/SDP layouts and plugin/Cubase load/save/reload acceptance +remain unverified. No application acceptance was run or counted as a pytest skip. +RNG behavior is verified on the tested interpreter, not certified cross-runtime. + +Step 6 is complete and ready for review/next permitted work. +Steps 7/8 real native serialization still require their existing evidence gates; +this report does not claim readiness to bypass them. Step 9 service wiring is +not implemented: the unchanged Step 3 handlers still list no profiles and reject +valid generation requests as unfinished. No later prompt was executed. Stop here. +``` diff --git a/prompts/report_7.md b/prompts/report_7.md new file mode 100644 index 0000000..d4faccd --- /dev/null +++ b/prompts/report_7.md @@ -0,0 +1,228 @@ +``` +Step 7 report — honest Ample AGP capability and require boundary +Date: 2026-10-19 + +SOFTWARE CAPABILITY OUTCOME: PASS — implemented, persistent and verified. +REAL NATIVE AGP ACCEPTANCE: BLOCKED — no actual layout, codec or native fixtures. +NATIVE ROUND TRIPS / ECLIPS-RAY APPLICATION ACCEPTANCE: UNRUN, not passing. + +SCOPE AND FILES + +Executed prompts\step_7.md under the amended functional-MIDI continuation +decision. Read reports 1–6, including report_5_fix.md, the current strict +profile/summary/error APIs, related architecture/compatibility records, and +the supplied official-document/demo-archive evidence observations. + +Created: +- src\riff_groove_builder\formats\__init__.py +- src\riff_groove_builder\formats\agp.py +- tests\unit\test_agp.py +- tests\integration\test_agp_capability.py +- prompts\report_7.md + +Updated: +- docs\formats\agp.md +- docs\compatibility.md +- docs\architecture.md + +No existing source/test/profile/resource/error/schema API was changed. +Prior reports, the amended plan and unrelated pre-existing worktree content +were preserved. No commits, delegation, later prompts, SDP implementation, +service wiring, dependency installation/restoration or manifest changes. +No native writer/parser, fake native success API or generic exporter framework. + +IMPLEMENTED CONTRACT + +formats.NativeCapability is a frozen/slotted concrete dataclass with exactly: +- part: Part +- format: Literal["agp", "sdp"] +- available: bool +- reason: str + +The shared value type does not implement SDP or register any codec. +The result is not an output artifact, path or caller-supplied authorization. + +formats.agp exposes: +- check_agp_capability(part: Part, profile: InstrumentProfile) + -> NativeCapability +- require_agp_capability(part: Part, profile: InstrumentProfile) + -> NativeCapability + +Both reject requests other than lead/bass, revalidate the whole mutable profile +through checked_profile, enforce existing target/part/format associations, +and reject a valid profile belonging to the wrong part. No path is accepted. +Check returns only an immutable capability value, never an artifact path. + +For every valid matching lead/bass profile: + part = requested part + format = "agp" + available = false + reason = "agp_layout_not_established" + +This remains true for standard profiles, instrument mapping fixtures and +mapping-attestation metadata. Neither mapping_kind, product/version strings +nor mapping provenance establishes a native codec. The current profile model +already rejects native_available=true; mutation/unchecked copies do not bypass +that validation. No shared profile rules were weakened. + +Require performs a fresh check and raises NativeFormatUnavailableError: + code = NATIVE_FORMAT_UNAVAILABLE + details = { + "format": "agp", + "part": "lead" or "bass", + "reason": "agp_layout_not_established" + } + +Other failures are not mislabeled native-unavailable: +- Bad/drum part: InvalidRequestError / INVALID_REQUEST, fixed + reason=unsupported_agp_part and format=agp. +- Valid wrong-part profile: ProfilePartMismatchError / PROFILE_REQUIRED, + reason=wrong_part with requested part and format. +- Wrong model type, corrupt/mutated profile or inconsistent target/format: + InvalidProfileError / SERIALIZATION_ERROR, reason=invalid_profile_model. +- Unexpected programming failures propagate; no catch-all fallback conversion. + +Future callers must preflight before preparing/touching output paths. Only +the named unavailable condition can inform allowed, explicitly reported MIDI +fallback. Invalid requests/profiles and actual serialization/IO failures cannot +be hidden. Fallback policy, warnings, staging/publication and MCP integration +are not implemented by this step; Step 3 handlers remain unchanged. + +TEST COVERAGE AND OBSERVED EFFECTS + +68 new unit cases: +- Typed explicit lead/bass results, immutability and repeatability. +- Standard/native-false and instrument/unknown-layout results. +- Mapping attestation and native metadata cannot enable a codec. +- Safe named unavailable context. +- Invalid/drum parts, wrong-target/part profiles, wrong model types. +- Deep mutation of range/aliases/provenance, inconsistent native target/format, + invalid channel/schema, unchecked copies and incomplete constructed models. +- Fresh require validation after an earlier check and propagation of + unexpected validation failures rather than fallback success. + +6 new integration cases: +- Real production registry selection for lead/bass. +- Guarded pathlib open/mkdir/touch/read/write/stat/rename/replace/unlink, + builtins.open and os.open: no calls during capability/require. +- Empty output stays empty; nonexistent child directory stays absent. +- Existing AGP-named sentinel retains bytes, identity, size and mtime. + This operator-data sentinel is explicitly NOT a native AGP fixture. +- Corrupt profile leaves existing output intact. +- Explicit independent Standard MIDI composition/compilation writes and + validates real MThd .mid bytes; no .agp file or fake artifact path. + +VERIFICATION COMMANDS AND EXACT FINAL RESULTS + +Environment: repository .venv, Windows AMD64, CPython 3.13.13. +Observed installed versions: Pydantic 2.14.1, Mido 1.3.3, pytest 9.1.1, +Ruff 0.17.1 and mypy 2.4.0. +Only this interpreter/OS/dependency configuration was executed. + +Repository-local scratch setup for pytest/build subprocesses: +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +$env:PIP_NO_INDEX = '1' + +Focused new tests: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_agp.py tests\integration\test_agp_capability.py -q --tb=short +PASS: 74 passed in 0.30s; 0 failed, 0 skipped. + +Relevant accepted regressions: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_profiles.py tests\unit\test_standard_profiles.py tests\unit\test_articulations.py tests\unit\test_midi.py tests\unit\test_package.py tests\unit\test_errors.py tests\integration\test_articulation_midi.py tests\integration\test_midi_files.py tests\integration\test_text_to_midi.py tests\integration\test_distribution.py -q --tb=short +PASS: 354 passed in 18.20s; 0 failed, 0 skipped. +Includes profile/standard-map/compiler mechanics, independent MIDIUtil and +actual MIDI read-back, text-to-MIDI, package/error regressions, offline +sdist/wheel build/install and installed/ZIP-wheel profile resource checks. +These packaging/MIDI checks do not certify native files or plugin behavior. +No full-suite execution is claimed; validation was deliberately focused on +new behavior and relevant existing regressions as requested. + +Owned-file formatting: +& '.\.venv\Scripts\python.exe' -m ruff format src\riff_groove_builder\formats tests\unit\test_agp.py tests\integration\test_agp_capability.py +PASS: 1 file reformatted, 3 files left unchanged. + +Whole-project static checks: +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: All checks passed! +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: 54 files already formatted. +& '.\.venv\Scripts\python.exe' -m mypy --strict src tests +PASS: Success: no issues found in 32 source files. +git --no-pager diff --check +PASS: no tracked-diff whitespace errors. Existing implementation work is +untracked; Ruff checks cover actual authored Python files independently. + +Editor test discovery returned "No tests found in the files"; this was not +counted as a pass or skip. The repository-venv pytest commands above provide +execution evidence. Editor problems reported no errors in all four new +Python files. No broad ignores, dependency changes or relaxed checks. + +ISSUES ENCOUNTERED AND RESOLVED + +Initial static checks found four constant-setattr lint findings, one format +difference, an intentionally invalid schema assignment rejected by mypy and +a test request using "midi" instead of the existing contract spelling "mid". +Used ordinary valid-type mutation, a dynamic all-fields frozen-value test, +unchecked-copy schema validation and the authoritative "mid" literal; formatted +only owned files. All focused tests then passed, followed by the regression +and final whole-project static checks. A metadata-only version probe had an +extra parenthesis; the corrected probe verified the versions recorded above. +No implementation/test/static-check failure remains. + +EVIDENCE CONCLUSIONS — NO NEW NATIVE SCHEMA + +The supplied prior observations, not new downloads in this step, establish: +- Raw https://www.amplesound.net/en/manual.asp exposes public + Main_Panel_Manual-AME.pdf, Main_Panel_Manual-AMR.pdf, Guitar_Riffer.pdf, + Guitar_Strummer.pdf and Settings_and_CPCv2.pdf links under /en/. +- Main-panel PDFs contain range/articulation labels. Riffer documents MIDI + import/export and preset Save/Load UI. Neither fact establishes an AGP + binary layout, required musical fields or installed-product acceptance. +- Prior unauthenticated metadata inspection of + https://www.amplesound.net/dl0822/ds/AME-Eclipse.zip found MIDI, DAW projects + and plugin-state files but no AGP files. This supplied no native fixture; + absence there is NOT proof that AGP does not exist or cannot hold music. + +docs\formats\agp.md records exact links, source/observation limitations, +expected future _lead.agp and _bass.agp roles, separate +product/build/native-version handling and the missing schema/fixture gate. +No archive/manual/factory music was downloaded or copied; no native fixture, +private upload, guessed-URL sweep or access-control bypass occurred. + +REAL NATIVE GATE — BLOCKED / APPLICATION CHECKS UNRUN + +Still required independently for Eclips and Ray: +- Exact installed identity/version/build, preset and native save/load operation. +- Proof that the requested file category stores the required notes, rhythm, + dynamics and techniques rather than only settings or external references. +- Actual container/encoding/version identification and musical-field schema; + lengths/checksums/compression/dependency semantics and unknown-field handling. +- Lawful empty/one-note/multi-note exports plus controlled tempo/meter, + timing/duration, velocity and articulation differences; redistribution + permission or a documented local-only fixture/test procedure. +- Evidence-based serializer/fixture and corrupt/version rejection tests. +- Real generated-file load, inspect, save, close/reload acceptance in both + exact installed products, preserving musical content; separate host/Cubase + routing/import evidence as appropriate. + +No real AGP serialization, native round trip, corrupt-native-file parser test, +Eclips/Ray load/save/reload or Cubase application test ran. These are UNRUN, +not passing automated checks or skips. Public manuals/MIDI mappings, self- +consistent invented encodings and renamed MIDI cannot close this gate. + +CLEANUP AND READINESS + +Final remaining relevant UUID test/build workspaces: 0. +Root build directory: absent. Existing venv, caches, dist products, scratch +and unrelated worktree content were preserved. No background process/service +was started. Implementation/tests/docs and this fenced report persist. + +Ready for review and the next independent capability/service work: YES, +using this explicit unavailable boundary and the already independent +Standard MIDI path. No later prompt/work was started. +Software capability objective: PASS. +Full native AGP acceptance: BLOCKED; real native/application checks: UNRUN. +``` diff --git a/prompts/report_7_fix.md b/prompts/report_7_fix.md new file mode 100644 index 0000000..fad601c --- /dev/null +++ b/prompts/report_7_fix.md @@ -0,0 +1,442 @@ +``` +CURRENT EXECUTABLE IMPLEMENTATION — REAL NATIVE RIFFER CODECS +Verification date: 2026-10-19 +Status: IMPLEMENTED AND VERIFIED; native plugin/DAW acceptance remains UNRUN. +This section supersedes the unavailable-layout conclusion in the labeled +historical research below. Riffer implementation is NOT evidence-blocked. + +SCOPE AND FACTS + +Read prompts/step_7_fix.md amendment, latest prompts/plan.md continuation, +current profiles/models/compiler/service/native boundaries/tests and docs. +Preserved the pre-existing plan/prompt amendments; no commits, delegation, +later prompts, service native registration or SD3 implementation. + +Read-only local verification: +- AME.vst3 ProductVersion 4.0.1; AMR.vst3 ProductVersion 4.1.0. +- 35 target AME Presets .griff and 30 target AMR Preset .briff files. + Root Riff, Ver=2.1, PPQBase=480, six/five strings; AME Inst=AME. + Target factory bass omits Inst; a direct user-authored bass file confirms + Inst=AMR, Ver=2.1, PPQBase=480, numStr=5. +- Verified integer NoteID/Fret/Begin/End/Velocity/Off-Velocity, articulation, + No Legato/False states, descending physical IDs, native metadata/key syntax, + CC1 raw MIDI-unit stair points and the existence of separate drop tunings. +- Safe provenance IDs: LOCAL-AME-401-RIFF21-20261019 and + LOCAL-AMR-410-RIFF21-20261019. No private absolute paths in packaged metadata. +- Public Main_Panel_Manual-AME.pdf and Main_Panel_Manual-AMR.pdf were decoded + in memory for technical facts. No manual assets, plugin binaries, factory + musical sequences or private templates were copied into the repository or + uploaded. Tests need no installed plugin, local factory file or network. + +IMPORTANT EVIDENCE-DRIVEN CORRECTIONS + +The current Eclipse manual specifies C0 sustain velocity bands: 1-15 full mute, +16-31 three-quarter mute, 32-63 half mute, 64-126 sustain, 127 Pop/PH depending +on Settings. Consequently guitar NORMAL is 64-126, NOT a misleading 1-127 +normal sweep. Guitar palm mute uses D0/26 with lower velocity increasing depth; +no invented mute sublayers are declared. + +Bass uses C0/24 for both named techniques: 64-126 normal, 32-63 palm mute. +Native bass C0-band palm mute uses PMP, NOT the separate D0 high-velocity PM +representation. Read-only target facts distinguish 313 PMP notes at 40-60, +56 PM notes at 70-100, 89 DN notes at 30-60, and Acc at 127. The initial native +PM/C0-band conflation was corrected before final acceptance, and the original +bass fixture regenerated through the actual writer. No D0 threshold or extra +named bass mode is fabricated. Audible acceptance remains explicitly unrun. + +IMPLEMENTED + +1. Strict nondefault production subset profiles: + ample.ame.4.0.1.riffer.v1 / ample-metal-eclipse-4.0.1-riffer-v1.json + ample.amr.4.1.0.riffer.v1 / ample-metal-ray5-4.1.0-riffer-v1.json + Explicit tuning by descending ID: guitar 36/43/48/53/57/62, bass + 35/40/45/50/55; conservative frets 0-22 / 0-19. Explicit actual extension, + version/PPQ, native articulation map and supported raw CC1 representation. + verified_subset provenance separates vendor/local facts from generator + routing/switch timing/interpolation policy; no test-profile promotion. + +2. formats/agp.py now supplies real native APIs: + check_riffer_capability / require_riffer_capability + write_riffer(path, plan, part, profile) + validate_riffer_file(path, plan, part, profile) -> RifferReadback + Legacy check_agp_capability / require_agp_capability remain compatible; + write_agp / validate_agp_file alias the real codec and require real suffixes. + Capability checks remain no-IO. Metadata alone cannot invent a codec. + +3. Real UTF-8 Riff XML 2.1 / PPQ 480 writers, actual target metadata, + exact rational score-relative timing, preserved musical on/off velocities, + guitar Sus/PM and bass Sus/PMP. Verified switches are accounted for by + independent selected-score recompile, then represented as native technique + fields rather than stray musical notes. + Bounded deterministic physical-string backtracking handles valid chords, + including a regression requiring backtracking instead of greedy routing. + No same-string overlaps, note stealing, truncation, rounding or dropping. + +4. Saved-file validation reads actual bounded XML; it does NOT serialize an + expected XML tree and compare serializer output to itself. It checks root, + target/version/PPQ/tempo/meter/measures/key/loop, notes and legal fret/pitch + arithmetic, ordering/physical overlap, exact requested velocities/techniques, + all discrete CC1 points, and exact score/event-plan correspondence. + Wrong suffix/version/target, malformed/extra content, DTD/entities, + unsupported CCs/techniques, bad grid and corrupted saved output fail. + Writer uses exclusive creation of the supplied staged path only, with + flush/fsync and read-back; no parent/template/sibling/publication is created. + +5. Compiled CC1 stair points preserve integer tick/value in raw MIDI 0-127, + with ccName-1=1.Mod / ccVisibility-1=1. No fabricated resets, normalization, + modulation layer bands or named vibrato mode. Original fixtures explicitly + request their CC points; zeros in those fixtures are NOT injected resets. + +6. Honest timing boundary: nonzero compiled pre-roll or any control tail is + explicitly rejected, not shifted, clipped or hidden. Current subset MIDI + policy uses zero lead, same-tick switch-before-note ordering, velocity-100 + switches, and a 1/32-quarter pulse. These are generator policy, not vendor + host/timing guarantees. Impossible routing/search exhaustion also errors. + +7. Strict request/artifact/profile/model/JSON Schema contracts: + requests retain agp/sdp aliases and accept actual griff/briff/sd3p names. + Artifact format and path suffix must agree and use actual suffixes only. + Profile summaries expose actual target suffixes. Corrected standard and + synthetic fixture metadata without making them native-capable. + Registry now contains five packaged resources, retaining the same three + standard defaults. Minimal service association changes prevent actual + suffix metadata from bypassing native preflight; NO native writer is wired. + Explicit target native requests hit native_writer_not_registered as before; + default MIDI/fallback and explicit mapped MIDI remain operational. + +8. Updated README, architecture, profile facts/policy, compatibility and native + format docs, and directly coupled contract/resource/stdio regression tests. + SD3 metadata uses sd3p truthfully; SDP capability remains unavailable. + +ACTUAL GENERATED ORIGINAL READ-BACK EVIDENCE (PERSISTENT) + +Checked-in, newly generated minimal native fixtures: + tests\fixtures\riffer\original-lead.griff + tests\fixtures\riffer\original-bass.briff +Retained actual generated outputs: + .test-artifacts\native-riffer-evidence-v1\original-lead.griff + .test-artifacts\native-riffer-evidence-v1\original-bass.briff + +Each saved native file independently validates three original notes, PPQ 480, +123.5 BPM, 4/4, one measure / end tick 1920, native key Cm. +Guitar pitches 36/84 at 0..480 and PM 38 at 960..1440. +Bass pitches 35/74 at 0..480 and PMP 37 at 960..1440. +Normal velocities 64/126; guitar PM 64, bass PMP 48; all musical off velocities +45, explicitly supplied in the event plan. CC1 points (0,0), (480,120), +(1440,0), explicitly requested by the original verification plan. +Fixture bytes and retained generated bytes are independently checked identical. +Lead: 1055 bytes, SHA-256 + cfb4d60b58c2ca11d66b97bb71384d674cb56f63ff665cce066b44ae08e5204a +Bass: 1036 bytes, SHA-256 + 8dec4f241ff4473c30d86365ac259c6c9f361ccd5631b25c894c4f35f51a1238 + +Installed-wheel acceptance additionally generates and independently reads real +original .griff/.briff files from the non-editable offline installed wheel +while its cwd is outside the checkout. It verifies both target resources, +one native note per target, the correct PM/PMP label and raw-unit CC1. +That bounded test workspace is cleaned; the persistent originals above remain. + +FINAL VALIDATION — ALL PASS, NO SKIPS + +Interpreter: .\.venv\Scripts\python.exe (CPython 3.13.13, Windows). +Exact focused command: + .\.venv\Scripts\python.exe -m pytest tests\unit\test_riffer.py tests\unit\test_native_contracts.py tests\unit\test_profiles.py tests\unit\test_schemas.py tests\unit\test_agp.py tests\integration\test_contracts.py tests\integration\test_riffer_files.py -q --tb=short + PASS: 571 tests, 0 failures. + + .\.venv\Scripts\python.exe -m pytest -q --tb=short + PASS: 1221 tests, 0 failures, 0 skips (40.76 seconds). + Includes wheel/sdist builds, installed and ZIP resources, isolated installed + native read-back, real installed stdio/default MIDI/fallback, and MIDI + read-back/publication regressions. No dependency manifests were changed and + no project dependencies installed/restored. + + .\.venv\Scripts\python.exe -m ruff check src tests + PASS: all checks passed. + .\.venv\Scripts\python.exe -m ruff format --check src tests + PASS: 41 files already formatted (formatter applied before final validation). + .\.venv\Scripts\python.exe -m mypy src tests + PASS: strict configuration, no issues in 41 source files. + .\.venv\Scripts\python.exe -m pip check + PASS: no broken requirements. + git --no-pager diff --check + PASS; report single-fence/history preservation and retained native files + independently verified after writing this report. + Editor Problems: no errors in source/tests. + +LIMITATIONS / READINESS + +Real native CODEC/profile/contract implementation is complete for this subset. +No absent-evidence stop remains for these Riffer targets. This is NOT a claim +of plugin/Cubase native load/save/reload, audible articulation, arbitrary +Riffer import, every tuning/technique, native service output or SD3 support. +All application acceptance is UNRUN, not a pytest skip or inferred success. +Ready for later native service integration/SD3 work; neither is performed here. + +======================================================================= +HISTORICAL RESEARCH — PRESERVED, SUPERSEDED BY CURRENT IMPLEMENTATION ABOVE +The following is the prior research-only report, unchanged. Its statements +about missing local/version/layout evidence describe that earlier investigation, +NOT the present implementation or a current Riffer blocker. +======================================================================= + +Step 7 fix report — new targeted public-source AGP evidence investigation +Date: 2026-10-19 + +SCOPE: Research-only, per prompts/step_7_fix.md. No source/tests/docs/prompts +were modified. No commits, no delegation, no implementation. The existing +native AGP boundary in src/riff_groove_builder/formats/agp.py (available=False, +reason="agp_layout_not_established") is UNCHANGED and still correct per the +evidence below. + +RESULT SUMMARY + +No ".agp" binary layout, version header, field list, checksum/compression +rule, or redistributable fixture was found anywhere public. This investigation +goes materially beyond the prior three simplified fetches: it downloaded the +five official PDFs as raw bytes (not simplified text extraction), parsed real +page text with pypdf, and extracted the embedded UI screenshots from inside +the PDFs to inspect actual in-app dialogs. The literal string "agp"/"AGP" does +not appear anywhere in ~89,700 characters of extracted real manual text, and +does not appear in any extracted screenshot. The native-AGP gate remains +honestly BLOCKED. Several new, concrete, lawfully-obtained facts were +established and are recorded below, including one genuine structural +contradiction risk the orchestrator should review. + +METHOD (new, not a repeat of prior simplified fetches) + +1. Re-fetched https://www.amplesound.net/en/manual.asp as raw HTML (public, + unauthenticated) and confirmed the exact current link set and the site's + product navigation menu (Metal Series: "Ample Metal Hellrazer", "Ample + Metal Eclipse", "Ample Metal Ray5"). +2. Downloaded the five linked PDFs as raw bytes via a stdlib-only + (urllib.request) script, run in a disposable research virtual environment + created at %TEMP%\research_pdf_venv (NOT the project .venv; no project + dependency was added or changed): + - https://www.amplesound.net/en/Guitar_Riffer.pdf + - https://www.amplesound.net/en/Guitar_Strummer.pdf + - https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf + - https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf + - https://www.amplesound.net/en/Settings_and_CPCv2.pdf +3. Installed `pypdf` and `pillow` only into that disposable research venv + (`pip install pypdf pillow`, PyPI, network-enabled in this sandbox) to + extract real page text and embedded raster images (UI screenshots) from + each PDF. This is standard, lawful text/graphic extraction of a publicly + posted manual for inspection, not redistribution; no PDF, image or manual + text was copied into the repository. +4. Searched all extracted real text (not the earlier raw zlib-byte-soup scan, + which produced false "agp" hits inside undecoded binary image streams) for + "agp", ".agp", "riff file", "groove", "preset", "export", "save", "load", + "bank", "extension", "file format", case-insensitively. +5. Viewed the highest-value embedded screenshots directly (Riffer Save Window, + Riffer Preset/Browse Window, Strummer Pattern browse/save windows, Eclipse + and Ray5 main-panel renders) to look for a visible filename-extension + string that text extraction could miss. +6. Searched GitHub (github-mcp-server search_code / search_repositories, + public, unauthenticated) for any open-source Ample Sound AGP parser, + `extension:agp`, and known multi-format sample/preset converters. +7. Attempted exact-phrase public web search (DuckDuckGo HTML endpoint, Bing) + and the official Ample Sound KVR Audio sub-forum link exposed in + manual.asp (http://www.kvraudio.com/forum/viewforum.php?f=245). +No login, CAPTCHA, or access control was bypassed. No factory song, licensed +manual page, or screenshot was saved into the repository; all downloaded +files and extracted images remained under this machine's %TEMP%, outside the +repository working tree, and are not committed or referenced as fixtures. + +VERIFIED NEW FINDINGS (public, unauthenticated, directly observed) + +1. No "agp" string anywhere in real extracted text. Per-document character + counts of real pypdf-extracted text and the explicit negative result: + - Guitar_Riffer.pdf ("Ample Riffer 4 Manual", 37 pages, 36,395 chars): 0 + occurrences of "agp"/"AGP". + - Guitar_Strummer.pdf ("Strummer Panel Manual", 15 pages, 11,685 chars): 0 + occurrences. + - Main_Panel_Manual-AME.pdf ("Ample Metal Eclipse Main Panel Manual", 14 + pages, 14,056 chars): 0 occurrences. + - Main_Panel_Manual-AMR.pdf (title text literally reads "Ample Metal R Main + Panel Manual", 14 pages, 14,373 chars): 0 occurrences. + - Settings_and_CPCv2.pdf ("Settings and CPC Manual", 16 pages, 13,250 + chars): 0 occurrences. + An earlier crude pass that zlib-decompressed every PDF stream and grepped + the raw bytes did show byte sequences matching "agp"/"AGP", but those were + confirmed to be random bytes inside undecoded JPEG/image XObject streams, + not real text — a false lead correctly discarded before relying on it. + +2. Confirmed exact current official product names and category, directly + from three independent in-document signals (site nav menu text, PDF title + text, and the rendered plugin UI screenshot baked into the manual): + - Lead/guitar target: "Ample Metal Eclipse" (file AME; rendered UI banner + reads "AMPLE METAL ECLIPSE"). The site's Metal Series category also + lists "Ample Metal Hellrazer" and "Ample Metal Ray5" alongside it. + - Bass target: storefront/UI name is "Ample Metal Ray5" (rendered UI banner + reads "AMPLE METAL RAY5"), but the AMR manual's own text layer title + reads "Ample Metal R Main Panel Manual" (missing "ay5") — a minor, + verified documentation inconsistency in Ample's own PDF, not a file- + format fact, but worth recording since step_7_fix.md flagged exact + product names as unconfirmed. This narrows "Ample Guitars Eclips" / + "Ample Ray" (as used in the user's prior wording) to the plugins' real + names, which belong to the "Metal Series", not a generic/acoustic guitar + or bass line. + - Exact installed version/build/edition (e.g. a specific plugin build + number or purchased edition) is still NOT established by any of this; + only the product identity/category is now confirmed from public + material. + +3. Riffer 4's own File Menu (section "4.5 File Menu", real body text, + Guitar_Riffer.pdf) lists exactly: New, Load, Save, Save As, Import MIDI, + Export MIDI, Export Audio — i.e. Riffer documents Save/Load as actions + distinct from Import MIDI/Export MIDI. This is textual confirmation (not + an inference from a filename) that Riffer's native Save/Load is not simply + a MIDI import/export relabeled; it is presented as its own save format in + the plugin's own menu, consistent with (but not proof of) a proprietary + container. + +4. Extracted the actual embedded screenshot of Riffer's "Save Window" (manual + section 4.5.2) and "Preset Window"/browse dialog (section 4.5.1): + - Save Window default path: `C:\Users\User\Documents\Ample Sound\Riff4\ + Guitar4`, fields Name / Author / Category / Type, a Save button. This is + a custom in-app widget, not an OS Save-As dialog, so the screenshot does + NOT display any filename-extension text anywhere in the rendered image. + - Preset/browse window: left-hand folder tree uses per-instrument-model + codes (AGM Pick, AGM Preset, AGM Strum, AGPF Preset, AGRB Preset, AGSC + Clean/Funk/Overdrive/Preset, AGSH Preset, AGSJ Preset), and the file list + has an "Inst" column populated with the same codes (e.g. AGPF, AGSH). + These are instrument/model abbreviations used as folder/category labels + inside the custom browser UI, not a visible file extension string; none + of them is literally "AGP" alone, and no extension is rendered anywhere + in this screenshot either. + +5. Strummer documents three distinct, separately-pathed save/load features, + confirmed from real body text (not just the table of contents): + - "1.5.1 Select Mode" — explicit "Save/Load Whole Chord Bank" buttons. + - "1.6.3 Save/Load Pattern" — default path `C:\Users\User\Documents\Ample + Sound\Strum Patterns` (screenshot captured and viewed), fields Name / + Author / Category / BPM / Signature / Quantize, a Save button. Different + default path from Riffer's `Riff4\Guitar4` tree. + - "1.6.6 Convert Pattern to Riffer" — an explicit, one-directional command + that turns a Strummer rhythm Pattern into Riffer data, with the caveat + "ensure the time signature or quantization of the current pattern + matches the Riffer settings." + This is the closest this investigation got to the requested "concrete + contradiction (preset vs riff/strum extension)": the vendor's own UI/ + documentation treats "Chord Bank", "Pattern" (Strummer/groove) and "Riff" + (Riffer) as three separate saved-content categories with three different + default folders and an explicit one-way conversion step between Pattern + and Riff, rather than one interchangeable native container shared across + "riff" and "groove" content. This is a real structural distinction to flag + for a scope decision — it is not proof that the on-disk extensions differ, + because no extension string was ever visible in any screenshot or text. + +6. Main_Panel_Manual-AME.pdf's own body text (section 1.2 Preset Bar) states: + "Clicking the preset name text box will open the preset file list window," + i.e. the main-panel "Preset" feature is the instrument/tone patch system + (sound settings), textually confirmed separate from Riffer's riff/groove + note content — consistent with, and now textually verified from the real + manual body (not just inferred from UI labels), the existing docs/formats/ + agp.md caution that "a preset-only container may not hold the requested + riff/groove." + +7. Settings_and_CPCv2.pdf section "1.2.2 Export Mode" (real body text) is + exclusively about MIDI channel-per-string export configuration ("MIDI + Guitar Channels" vs "Single Channel"), not a native save/export format. + This rules out one possible misreading of "Export" as native-AGP evidence. + +8. No public open-source AGP parser or Ample Sound format support was found. + GitHub code search (search_code) for "Ample Sound" + riff/preset parsing, + `extension:agp`, and `"AGPF" OR "AGSH" OR "AGRB" Ample` returned only + unrelated false positives: the unrelated "Accelerated Graphics Port" bus- + driver `files.agp` in NetBSD/src, and substring matches inside unrelated + words ("bagpipe", "tagPolyphony") in git-moss/ConvertWithMoss, a actively + maintained open-source multi-format sample/preset converter supporting + dozens of competing plugin preset formats (Decent Sampler, TX16Wx, SFZ, + etc.). That project has no Ample Sound format support at all — useful + negative evidence that no public reverse-engineered AGP schema exists in + a well-known community converter project either. + +9. Exact-phrase public web search could not be executed reliably in this + sandbox: the DuckDuckGo HTML endpoint returned an anti-bot/email- + verification challenge page instead of results, and Bing returned a + stale/irrelevant snippet about an unrelated agribusiness company named + "AGP", not real search results. The official Ample Sound KVR Audio sub- + forum index linked from manual.asp (http://www.kvraudio.com/forum/ + viewforum.php?f=245) loaded (no login required) but its thread listing is + JavaScript-rendered and did not return readable thread content through + static fetch; browsing further thread pages was judged outside the + 12-access, narrowly-targeted bound for this pass and was not pursued. + +NO NEW NATIVE SCHEMA — GATE STILL HONESTLY BLOCKED + +None of the above establishes: a container signature/magic bytes, a version +number scheme, a field list for pitch/start/duration/tempo/velocity/ +articulation, any length/checksum/compression rule, or any external-reference +semantics. No actual ".agp" (or correctly-named equivalent) file, lawful +empty/one-note/multi-note export, or redistribution permission was obtained. +Native AGP acceptance for Ample Metal Eclipse (lead) and Ample Metal Ray5 +(bass) remains BLOCKED exactly as recorded in report_7.md and docs/formats/ +agp.md. This report does not reverse, soften, or re-derive that conclusion; +it adds verified detail and rules out several plausible-sounding shortcuts +(renamed MIDI export, preset/tone file, Export Mode MIDI-channel setting) +without inventing a layout. + +REMAINING BLOCKERS + +- The real on-disk extension used by Riffer "Riff" saves, Strummer "Pattern" + saves, and Strummer "Chord Bank" saves is still not established from any + public source; no screenshot or manual text ever displays the filename + extension because both Riffer's and Strummer's save/browse dialogs are + custom in-app widgets, not OS file pickers, and no manual prose names the + extension in writing. +- Exact installed product build/edition/version for the user's "Ample Metal + Eclipse" and "Ample Metal Ray5" copies is still unconfirmed. +- No lawful controlled empty/one-note/multi-note export exists, so no + pitch/timing/tempo/velocity/articulation field layout can be derived or + tested. +- No redistribution permission or documented local-only fixture procedure + exists for any native file. +- No real Eclipse/Ray5 load, inspect, save, close/reload acceptance test has + been run; this remains UNRUN, not a passing or skipped automated check. +- The Strummer Pattern/Chord-Bank vs Riffer Riff distinction (finding 5 above) + is a genuine open structural question for the orchestrator: if the user's + requested "groove" content for bass is actually a Strummer Pattern/Chord + Bank (not a Riffer Riff), a single shared lead/bass ".agp" writer assumption + may be wrong even if a real schema is eventually obtained for one of them. + This should be resolved by product-specific confirmation, not invented. + +EXACT LAWFUL INPUTS STILL NEEDED (unchanged in kind from docs/formats/agp.md, +now sharpened by the product-identity confirmation above) + +1. Confirmation of the exact installed product/edition/build for the user's + "Ample Metal Eclipse" (lead) and "Ample Metal Ray5" (bass) copies, and + which specific save feature (Riffer Riff, Strummer Pattern, or Strummer + Chord Bank) the user actually means by "riff"/"groove" content for each. +2. A real Save-As (or equivalent OS file dialog, if any exists outside the + custom in-app browser) performed once by the rights-holder/operator on + that exact installed copy, so the real on-disk filename and extension can + be observed directly instead of guessed. +3. Lawfully created empty, one-note, and multi-note exports from that same + controlled setup, with redistribution permission, or an explicit + operator-documented local-only fixture ID and test procedure if + redistribution is not permitted. +4. One-variable-at-a-time controlled exports (tempo, note timing/duration, + velocity, and each required articulation / release type) from the same + installed copy, needed to derive the real field layout once a sample + container is obtained. +5. Real load/save/close/reload acceptance performed in the actual Eclipse and + Ray5 plugins (and Cubase routing, if relevant), recording whether pitch, + timing, dynamics and articulation survive. + +READINESS + +Software capability boundary: unchanged, still PASS (from report_7.md). +Real native AGP acceptance: still BLOCKED. No fabricated layout, no renamed +MIDI, no invented extension was substituted. This fix step is complete as a +bounded, honest research pass: 2 negative/limited search attempts +(DuckDuckGo, Bing), 1 partially-useful public page (KVR forum index, no +readable thread content), and 9 substantive public-source accesses (manual.asp +raw HTML, the 5 official PDFs each independently re-parsed for text AND +images, and GitHub code/repo search across 5 queries) were used, within the +requested bound. No commit, delegation, or scope expansion occurred. Ready +for the orchestrator to decide between (a) obtaining the exact lawful inputs +listed above, or (b) a scope decision about whether Strummer Pattern/Chord- +Bank content should be targeted instead of, or in addition to, Riffer Riff +content for the bass/groove side. +``` diff --git a/prompts/report_8.md b/prompts/report_8.md new file mode 100644 index 0000000..3b5b763 --- /dev/null +++ b/prompts/report_8.md @@ -0,0 +1,221 @@ +``` +Step 8 report — honest SDP capability and require boundary +Date: 2026-10-19 + +SOFTWARE CAPABILITY BOUNDARY: PASS — implemented, persistent and verified. +REAL SDP SERIALIZATION / NATIVE ACCEPTANCE: BLOCKED — no established layout/codec. +REAL NATIVE ROUND TRIPS / SD3 AND CUBASE APPLICATION ACCEPTANCE: UNRUN. +STEP 9 INDEPENDENT STANDARD-MIDI SERVICE/FALLBACK READINESS: YES. + +SCOPE AND FILES + +Executed only prompts\step_8.md under the amended plan's functional-MIDI +continuation decision. Read the amended plan, reports 1–7 including the +standard-fallback correction, current shared NativeCapability/AGP boundary, +strict profile/summary/error APIs and related architecture/compatibility records. +Passing AGP software does not close its separately blocked real native gate; +no Step 7 fix or later prompt was executed. + +Created: +- src\riff_groove_builder\formats\sdp.py +- tests\unit\test_sdp.py +- tests\integration\test_sdp_capability.py +- prompts\report_8.md + +Updated: +- docs\formats\sdp.md +- docs\architecture.md +- docs\compatibility.md + +Reused the shared NativeCapability and checked_profile without changing them. +Existing AGP, profile/resource, compiler, MIDI, schema/error, package and server +APIs were preserved. No manifest changes, dependency restoration/installation, +commits, delegation, service wiring, later prompts or background processes. +Existing unrelated worktree content and prior reports/plan were preserved. + +IMPLEMENTED CONTRACT + +formats.sdp exposes: +- check_sdp_capability(part: Part, profile: InstrumentProfile) + -> NativeCapability +- require_sdp_capability(part: Part, profile: InstrumentProfile) + -> NativeCapability + +Both reject non-drums requests first, defensively revalidate the entire mutable +profile using checked_profile, preserve the existing SD3/drums/sdp association, +and reject a valid profile belonging to another part. + +For every valid matching drums profile, check returns the existing immutable, +frozen/slotted NativeCapability with exactly: + part = "drums" + format = "sdp" + available = false + reason = "sdp_layout_not_established" + +This includes production standard.gm-drums.v1, synthetic instrument mappings, +and clearly test-harness-only complete mapping attestations. Mapping provenance, +product/version strings and metadata cannot enable a nonexistent native codec. +The current profile model rejects native_available=true; unchecked mutations +are revalidated rather than treated as authorization. + +Require freshly checks and raises NativeFormatUnavailableError: + code = NATIVE_FORMAT_UNAVAILABLE + details = { + "format": "sdp", + "part": "drums", + "reason": "sdp_layout_not_established" + } + +Other failures remain distinct and are not fallback: +- Lead, bass or invalid request part: InvalidRequestError / INVALID_REQUEST; + details format=sdp, reason=unsupported_sdp_part. +- Valid wrong-part profile: ProfilePartMismatchError / PROFILE_REQUIRED; + details format=sdp, part=drums, reason=wrong_part. +- Wrong target/format, corrupt/deeply mutated profile, invalid unchecked model + or wrong model type: InvalidProfileError / SERIALIZATION_ERROR; + details reason=invalid_profile_model. +- Unexpected validation/programming errors propagate. + +Neither API accepts paths, performs filesystem IO, returns an artifact path, +serializes native bytes or automatically converts to MIDI. There is no fake +successful write API, parser, new registry/framework or invented native fixture. +Future service code must run preflight before preparing/touching output paths. +Only the named unavailable condition may inform allowed, explicit MIDI fallback; +bad requests/profiles and actual serialization/IO failures must stay visible. + +TEST COVERAGE AND ACTUAL OBSERVATIONS + +79 new unit cases: +- Typed immutable/slotted unavailable result, stable fields/repeated checks, + no mutation of the source profile and explicit standard-only GM identity. +- Synthetic and test-harness mapping metadata cannot establish a codec. +- Native metadata cannot override the model's gate. +- Stable named require error with complete safe format/part/reason. +- Lead/bass/invalid parts and valid wrong-part profiles have distinct failures. +- Revalidation rejects wrong instrument/part/native format/flag/channel, + invalid/duplicate drum notes, ambiguous voice aliases, absent voices, + pitched-range misuse, articulation aliases, invalid velocity layers, + deep provenance mutations, inconsistent mapping kind/version/schema, + unchecked copy/construct and wrong model types. +- Check-before-mutation cannot authorize require; unexpected validation errors + propagate; bad-request precedence is explicit. + +10 new integration cases: +- Real production registry selection, not an invented mapping API. +- Guarded pathlib open/mkdir/touch/read/write/stat/rename/replace/unlink, + builtins.open and os.open observe zero calls during valid check/require. +- Empty output remains empty; a nonexistent child directory remains absent. +- Existing SDP-named operator-data sentinel retains bytes, identity, size + and mtime. This sentinel is NOT a native fixture or generated SDP. +- Invalid part, wrong-part profile, wrong target, deep mutation, forged native + flag and unchecked model fail before guarded IO and preserve existing data. +- Separate explicit drums-only and three-part descriptions use the actual + resolver, registry, composer, compiler and MIDI writer/read-back APIs. + Saved files begin MThd, are type 1 at 960 PPQ, have exact track names, + all track endings at 3840 ticks, eight drum hits using GM notes 36/38/42 + on zero-based channel 9 with positive legal velocities. Independent Mido + parsing and production expected-content validation both pass. + Only the actual .mid file exists; no .sdp/.agp artifact or fake path exists. + +These tests prove software preflight and independent standard MIDI, NOT a native +SDP writer, real SD3 mapping or the service's future fallback/publication policy. + +EXACT VERIFICATION AND RESULTS + +Environment: repository .venv, Windows, CPython 3.13.13. +Observed installed versions: Pydantic 2.14.1, Mido 1.3.3, pytest 9.1.1, +Ruff 0.17.1, mypy 2.4.0. No other runtime/OS/application was tested. + +Commands ran from the repository root. Test/build subprocess scratch setup: +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +$env:PIP_NO_INDEX = '1' + +Focused new tests: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_sdp.py tests\integration\test_sdp_capability.py -q --tb=short +PASS: 89 passed in 0.34s; 0 failed, 0 skipped. + +Relevant accepted regressions: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_agp.py tests\integration\test_agp_capability.py tests\unit\test_profiles.py tests\unit\test_standard_profiles.py tests\unit\test_articulations.py tests\unit\test_midi.py tests\unit\test_package.py tests\unit\test_errors.py tests\integration\test_articulation_midi.py tests\integration\test_midi_files.py tests\integration\test_text_to_midi.py tests\integration\test_distribution.py -q --tb=short +PASS: 428 passed in 18.37s; 0 failed, 0 skipped. +Includes all 74 AGP capability cases, profile/standard-map/compiler mechanics, +actual MIDI and independent MIDIUtil checks, text-to-MIDI, package/error checks, +offline sdist/wheel build/install and installed/ZIP-wheel profile resources. +Those package installations are isolated existing test procedures, not project +dependency changes/restoration. No full-suite execution is claimed. + +Initial owned-file checks: +& '.\.venv\Scripts\python.exe' -m ruff check src\riff_groove_builder\formats\sdp.py tests\unit\test_sdp.py tests\integration\test_sdp_capability.py +PASS: All checks passed! +& '.\.venv\Scripts\python.exe' -m ruff format --check src\riff_groove_builder\formats\sdp.py tests\unit\test_sdp.py tests\integration\test_sdp_capability.py +PASS: 3 files already formatted; no reformatting needed. + +Final whole-project checks: +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: All checks passed! +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: 60 files already formatted. +& '.\.venv\Scripts\python.exe' -m mypy --strict src tests +PASS: Success: no issues found in 35 source files. +git --no-pager diff --check +PASS: no tracked-diff whitespace errors. Existing implementation is untracked; +Ruff separately checks the actual Python files, not only tracked diffs. + +Editor problems reported no errors in the three new Python files. Editor +runTests returned "No tests found in the files"; this discovery limitation is +not counted as a pass or skip. The repository-venv pytest executions above +provide the actual execution evidence. No pytest/lint/format/type failure +occurred; no ignores or configuration relaxations were added except the +existing narrow convention for the untyped Mido import in the new test. + +EVIDENCE LIMITATIONS AND REAL NATIVE BLOCKERS + +No new downloads, lawful native specifications or controlled SDP fixtures became +available. The prior official SD3 manual login requirement remains an evidence +limitation, not an invitation to bypass authentication or infer a layout. +No credentials, vendor login, licensed-content copying or private upload occurred. + +docs\formats\sdp.md records the intended future _drums.sdp role and +the exact evidence still needed: +- Installed SD3 product/build/version, OS/plugin mode, sound library, preset, + selected map/version and exact native save/export/load/import operation. +- Proof the file category stores generated drum-song/groove notes, not only + preset settings or unresolved external references. +- Actual container/encoding/version and musical representation; compression, + embedded/referenced data, library/map dependencies, structural invariants, + lengths/checksums, field ownership and unknown-field behavior. +- Lawful empty/one-hit/multi-hit exports and controlled tempo/meter, + onset/duration, velocity and supported articulation/control changes. +- Rights for redistributable fixtures or a documented operator-local procedure. +- Evidence-based serializer validation, genuine fixture/version/corruption + checks, followed by real generated-file import, inspect, save, close/reload + in the exact SD3 setup and separately recorded Cubase/routing acceptance. + +Public GM facts do not establish the SD3 map or SDP layout. A preset-only +container is insufficient for drum-song generation; a scope contradiction +would require a decision, not a different guessed proprietary extension. +Renamed MIDI and self-consistent invented JSON/XML/native encodings are not +native support. No such bytes or claimed native files were produced. + +Real SDP serialization, native fixture/parser round trips, corrupt-native +parsing, SD3 application acceptance and Cubase acceptance did not run: +UNRUN, not pytest skips or passing tests. Full native acceptance stays BLOCKED. +The separate AGP native/application blockers likewise remain unresolved. + +CLEANUP AND CONTINUATION + +Final relevant UUID test/build workspace count: 0. +Root build directory: absent. Existing caches, venv, dist products, scratch +and unrelated worktree content were preserved. No background service started. +Only owned implementation/tests/docs and this single-fenced report persist. + +Ready for Step 9's independent standard-MIDI service/fallback implementation: +YES under the amended plan, reusing both honest unavailable boundaries, +explicit standard-only identity/warnings and the verified MIDI pipeline. +Step 9 still owns fallback permission, error translation, staged publication, +filesystem confinement and complete MCP wiring; none was implemented here. +Passing capability software is NOT a finished native writer or full release. +Stopped after Step 8 verification/reporting; no later work started. +``` diff --git a/prompts/report_8_fix.md b/prompts/report_8_fix.md new file mode 100644 index 0000000..5a82cfd --- /dev/null +++ b/prompts/report_8_fix.md @@ -0,0 +1,267 @@ +``` +CURRENT EXECUTABLE IMPLEMENTATION — REAL NATIVE SD3 TEMPLATE SONG CODEC +Verification: 2026-10-19 local / 2026-10-20 UTC +Status: IMPLEMENTED AND VERIFIED by native saved-file structural/content +read-back. SD3 application open/play/save/reload and Cubase acceptance: UNRUN. +This supersedes the historical unavailable-layout gate, not application testing. + +SCOPE + +Executed the current implementation amendment atop prompts\step_8_fix.md. +Read latest plan continuation, CURRENT report_7_fix implementation and current +profiles, compiler, event/MIDI contracts, native APIs, service and tests. +Implemented formats\sdp.py, necessary strict profile/model/resource extensions, +SD3 tests/original fixtures, related resource/stdio/service regression assertions +and directly related format/architecture/profile/compatibility/README docs. + +Existing Riffer implementation and working standard defaults were preserved. +No service implementation edits, native service registration, CLI template +configuration, default flips, commits, delegation or later prompt work. +The checkout already contained Step 7 and plan/prompt changes when this task +started; those pre-existing changes, including service.py, were not reverted +or misrepresented as Step 8 implementation. + +READ-ONLY EVIDENCE AND FACTS + +- Installed Superior Drummer 3.exe ProductVersion: 3.4.4. +- Five operator-local projects were read in place, never copied into fixtures: + all UTF-8, PlugVersion 3.4.4, one SongTrack and a terminal NUL. + sd3-demo.sd3p has 170 packed note triples in two clips. + Three transcription projects each have 1,169 triples; the other project has + no song notes. All observed packed messages have note-on status 0x90. + All five passed actual parser + library/pad/input-channel preflight. +- Actual library location is SAMPLER/HQ/soundlib "SL-DFH". + Native pad/alias declarations establish kickR -> 36, snareR -> 38, + hatsTP -> 42. Only these three voices were promoted to the target subset. + Other GM pitches were NOT promoted merely because their numbers resemble GM. +- Genuine 8332944 = 0x7f2690 independently decodes as note-on channel 0, + pitch 38, velocity 127. Start/end triple coordinates are quarter-note beats. +- Drumtracker/Track is unrelated tracker state. Its trackstuff/tempoMap and + all other non-song bytes are preserved, not treated as song MIDI or decoded + into an audio-analysis feature. +- The installed Operation Manual.pdf is actually a 20,744-byte ONE-PAGE link + sheet, not the complete SD3 manual. Local in-memory PDF inspection confirmed + its official manual URL; that public URL still requires login. No login or + bypass was attempted. Mapping evidence is the local setup/project pad + declarations, NOT a fabricated manual mapping citation. +- Local provenance identifier: LOCAL-SD3-344-DFH-PADS-20261019. + pypdf 6.21.1 was installed solely as a local evidence reader after the + selected import failed for a missing tool. No project dependency or package + manifest was changed for PDF reading. + +No private template, factory musical sequence, manual asset or executable was +copied into source/tests, packaged as a fixture, or uploaded. Generated local +evidence retains operator kit state and stays in ignored .test-artifacts, +outside source/tests. Public fetch sent only the official manual URL. + +IMPLEMENTED CODEC AND PROFILE + +1. Public Python APIs: + parse_sdp_project(raw: bytes) -> SdpProject + inspect_sdp_template(path: Path) -> SdpTemplateInfo + check_sdp_capability(part, profile, *, template: Path | None = None) + require_sdp_capability(part, profile, *, template: Path | None = None) + write_sdp(path, plan, part, profile, *, template=None) -> Path + validate_sdp_file(path, plan, part, profile, *, template=None) -> SdpReadback + write_sd3p / validate_sd3p_file alias the same real native implementation. + sdp remains the request alias; actual files MUST use lowercase .sd3p. + +2. Nondefault strict production profile: + toontrack.sd3.3.4.4.core.v1 + toontrack-sd3-3.4.4-core-v1.json + Provenance is verified_subset; version 3.4.4, library SL-DFH, core three + pad voices only, normal/sustain only. The actual template must uniquely + assign these pitches to matching defined pads in the evidenced xpad. + Active sampler MIDI-learn overrides/incompatible input filtering error. + Channel 9, linear intensity interpolation 1..127, action-free/reset-free + scheduling and precision restrictions are explicitly generator policy, + NOT vendor channel defaults, named sample layers or a complete SD3 map. + Invalid promotions/version/library/voice/control/default changes fail. + +3. Capability is executable, not a metadata switch: + standard/mapping-only profiles -> sdp_profile_not_supported; + supported target, no optional template -> sdp_template_required; + supported target + actual valid template -> available, + sd3_3_4_4_template_song. + No-template checks preserve the old no-IO boundary contract. + An explicitly supplied unreadable/missing template is OUTPUT_IO_ERROR; + supplied corrupt/versioned/map-mismatched state is SERIALIZATION_ERROR. + These errors are not swallowed as a MIDI fallback opportunity. + Mutable/unchecked profile validation and wrong-part errors remain strict. + +4. Actual bounded native text parser: + Balanced blocks, quoted/escaped strings, quoted record keys, braces inside + quoted state, Unicode, LF/CRLF, single optional terminal NUL. + Limits: 16 MiB, depth 64, 1,000,000 tokens, 100,000 note triples, + 1..32 contiguous source tracks, numeric beat bounds <= 16,384. + Rejects wrong/duplicate version, unbalanced/malformed state, ambiguous + track/current-track/clip ownership, invalid tempo/meter maps, misplaced + song music, malformed/truncated triples and invalid timing/message bytes. + No template scripting, eval, subprocess or arbitrary executable content. + +5. Actual native writer: + Replaces ALL source SongTrack records and current-song selection with + exactly one generated drum track/clip. Old grooves, clips, extra active + tracks, offsets, MIDI/database references and per-song transformations + are removed. Shared start/end, tempo/meter, velocities, drum pitches and + channel survive as new original native events. + Every unrelated template byte remains unchanged, including ClearTracksFirst, + kit/sampler/mixer/editor/tracker/e-drum/metronome/host-sync state. + The template is never written. Output uses exclusive xb on the supplied + staged path only, flush/fsync, bounded positive size and saved validation. + No parent/sibling/publication is created; no existing destination is + overwritten. Template content stability is checked across the write. + +6. Independent saved-content validation: + Parses saved bytes and independently extracts status/channel, pitch and + velocity from packed integers; it does not reserialize expected native + text and compare the writer against itself. + Recompiles the selected score and accounts for ALL compiled events. + Compares exact native note multisets, common bounds, tempo/meter, neutral + clip controls, supported structural fields and exact non-song bytes. + Extra references/fields/tracks, mutated content or retained source-song + semantics fail with named serialization errors. + +7. Explicit supported subset boundaries: + Only ordinary note-on triples with explicit positive-duration endpoints. + CC/switch/status semantics, nonzero release velocity, empty music, + score/event mismatch, wrong channels, pre-roll or tail are rejected. + Exact finite-decimal quarter-beat coordinates, <= six fractional places; + nonterminating 1/3 and overprecision 1/128 error rather than round. + Different PPQs are converted exactly, not assumed to be 960. + Absolute score start is normalized to the common score-relative zero. + Native percussion key metadata is neutral, not a pitched-key claim. + Failed caller-owned staging files can remain after serialization/IO failure; + they are never a successful published artifact. + +ACTUAL ORIGINAL NATIVE RESULTS — PERSISTENT AND REVALIDATED + +Original score: 137.5 BPM, 7/8, one bar, 3.5 quarter beats. +Logical score interval is 8..11.5; compiled/common musical interval is 0..3.5. +Zero-based MIDI channel 9. Three original notes: + + voice pitch velocity start beat end beat + kick 36 1 0 0.125 + closed_hat 42 64 0.25 0.375 + snare 38 127 3 3.125 + +Actual new Events triples, independently decoded from saved native files: + 74905 0 0.125 (0x012499) + 4205209 0.25 0.375 (0x402a99) + 8332953 3 3.125 (0x7f2699) + +Read-only genuine template run: + Input: prompt-specified operator-local sd3-demo.sd3p, 75,393 bytes. + Source SHA-256: + 06f54b02079e4b32d532ecc232b813c3fe1865799e6f5b2b21b5ddf398b0533d + Output: + .test-artifacts\native-sd3-evidence-v1\operator-local\original-drums.sd3p + Actual output: 66,194 bytes; SHA-256: + c747670d81736441928f368d8092d5363ad8e1bf3cad453af3173c1102674f88 + Source 170 events/two clips -> saved three original notes/one clip/one track. + Saved metadata is 137.5 BPM, 7/8, start 0, end 3.5, Offset 0. + No source song FileName/DatabasePath/KPTransform content survives inside + the generated song. Native validation disallows those extra fields. + +Exact non-song preservation: + 65,591 bytes, byte-for-byte identical before/after, SHA-256: + 10340dc5c057f2580c474ebc56277b2deae3263cee49e4674e07b8c9cc421d32 + Independently compared raw block spans: + SAMPLER 60,637 bytes identical (includes selected kit/mixer) + editorVars 885 bytes identical + mixerState 146 bytes identical + Drumtracker 1,409 bytes identical + SongCreator 32 bytes identical + EdrumPreset 1,024 bytes identical + MetronomeSettings 156 bytes identical + SAMPLER SHA-256: + 026a27006d04555942b11124b3cc8ea6803c2fca299f8efa74a0191e84b91fc5 + Drumtracker SHA-256: + 3c71b1d1079bc083a0f9249e21dec130171196dcb4e47ca48ffb0abe3ac8bd60 + Source inode/file ID 166633186213030518, size 75393, + mtime_ns 1788614183091903900 and full content hash were unchanged. + SyncToHost and MIDI input configuration were preserved, not silently reset. + +Original minimal fixture run: + tests\fixtures\sd3\original-template.sd3p and original-score.json contain + newly authored original sentinel state/music, not a stripped private export. + Output: + .test-artifacts\native-sd3-evidence-v1\synthetic-original\original-drums.sd3p + Actual output: 1,360 bytes; SHA-256: + 5b7e3e7e8615d58ba8b6a4e9df818caf94d0ce2eb5a4fc1dc546c6da6c3f0e6a + Same three generated notes/tempo/meter/bounds; source fixture hash/identity + unchanged. The minimal fixture is a codec fixture, not a redistributed kit. + +All retained local files above are ignored by git. No output was promoted +into source/tests and no private input was modified. + +FINAL VALIDATION — ALL PASS, NO SKIPS + +Environment: existing Windows CPython 3.13.13 venv. +runTests editor integration discovered no tests for the new file; actual pytest +execution below is authoritative. Editor problems reported no errors in the +changed codec/profile/new SD3 test files. + +Focused native/service/resource/package suite: + .\.venv\Scripts\python.exe -m pytest + tests\unit\test_sd3p.py tests\unit\test_sdp.py + tests\unit\test_service.py tests\integration\test_sd3p_files.py + tests\integration\test_sdp_capability.py + tests\integration\test_articulation_midi.py + tests\integration\test_distribution.py -q --tb=short + RIFF_SD3_TEMPLATE was set to the prompt's genuine sd3-demo.sd3p. + Result: 266 passed in 15.52 seconds. + +Final full current regression suite: + .\.venv\Scripts\python.exe -m pytest -q --tb=short + Result: 1,320 passed in 41.39 seconds; 0 failed, 0 skipped. + Prior current baseline was 1,221. Added 96 SD3 unit cases, one native + integration case and two targeted service readiness/MIDI cases. + +Final static/dependency checks: + .\.venv\Scripts\python.exe -m ruff check src tests + All checks passed. + .\.venv\Scripts\python.exe -m ruff format --check src tests + 43 files already formatted. + .\.venv\Scripts\python.exe -m mypy src tests + Success: no issues found in 43 source files (strict project config). + .\.venv\Scripts\python.exe -m pip check + No broken requirements found. + git --no-pager diff --check + PASS. + +Full/targeted package tests rebuilt real sdist/wheel offline, installed and +imported the wheel outside the checkout, verified all six packaged JSON +resources under both installed and ZIP resource loading, and ran the actual +installed stdio service. Installed-wheel native probes generated/read back +original .griff, .briff AND .sd3p files from the installed codec. The SD3 probe +uses its own original minimal template and confirms one snare note with +channel 9/pitch 38/velocity 127 and positive native size. +Owned build/install/test workspaces were cleaned; persistent evidence remains. +No dependency restore was needed for application/tests/build tools. + +During development, fixture CRLF assumptions and an old exact five-resource +assertion failed; both were corrected without weakening state/resource checks. +All final suites above were rerun successfully after those corrections. + +READINESS AND REMAINING LIMITS + +READY: actual bounded native codec, typed optional template input, testable +read-only preflight, nondefault evidence-backed core profile, exact native +music validation, ignored original local-template evidence and package APIs. +The registry now exposes six profiles; the original three standard defaults +and operational standard-MIDI service/fallback behavior are unchanged. +Explicit MIDI with the SD3 subset also passes without template/native wiring. +Explicit SD3 native service requests without optional template fail preflight +before staging when fallback is disabled; no native service output is claimed. + +NOT DONE HERE: native writer registration/service transaction integration, +optional CLI template configuration, default-profile changes, full SD3 map, +other libraries/versions/control semantics, application acceptance. +Preserved host sync/mute/routing/operator settings may affect playback or +override project tempo; structural read-back cannot certify receiver behavior. + +Actual SD3 load/inspect/play/save/close/reload, acoustic pad/dynamics checks, +and Cubase routing/native/MIDI comparison remain UNRUN. No fabricated plugin +or DAW result is inferred from the real .sd3p structural/content success. +``` diff --git a/prompts/report_9.md b/prompts/report_9.md new file mode 100644 index 0000000..e29ef72 --- /dev/null +++ b/prompts/report_9.md @@ -0,0 +1,326 @@ +``` +Step 9 report — operational Standard MIDI MCP service and explicit native fallback +Date: 2026-10-19 + +OUTCOME: IMPLEMENTED, PERSISTENT AND VERIFIED ON WINDOWS. +Final complete suite: 1118 passed; 0 failed; 0 skipped. +Final focused service/server/stdio suite: 140 passed; 0 failed; 0 skipped. +AGP/SDP serialization and vendor mapping gates: STILL OPEN / BLOCKED. +Eclips/Ray/SD3/Cubase application acceptance: UNRUN, not passing. + +SCOPE AND PERSISTENT CHANGES + +Read step_9.md, the amended plan/continuation decision, reports 5_fix/6/7/8, +and the current contracts, profile registry, resolver, composer, articulation +compiler, MIDI writer/read-back, native boundaries and SDK server. + +Created: +- src\riff_groove_builder\service.py +- tests\unit\test_service.py +- tests\integration\test_generation_service.py +- prompts\report_9.md + +Updated: +- src\riff_groove_builder\server.py and __main__.py +- tests\unit\test_server.py and tests\integration\test_stdio.py +- README.md +- docs\architecture.md, compatibility.md, articulation-profiles.md +- docs\formats\agp.md and sdp.md + +Removed registered tools' empty-registry/unfinished-generation behavior. +No shared schemas/errors/profile maps, resolver/composer/compiler/writer, +dependency manifests or prior reports/prompts were changed. No weakened +validation, new suppressions, native codecs, fabricated native outputs, +audio/model/HTTP service, sidecar manifests, commits or delegation. +No later prompt or application-acceptance work was executed. + +CONCRETE APIS AND DATA FLOW + +service.validate_output_root(value: str) -> Path + Retained as a server-module re-export for existing CLI/tests/callers, with + stronger actual root/ancestor reparse and Windows local-volume checks. + +GenerationService(output_root: Path, *, registry: ProfileRegistry | None = None) + Uses the actual packaged three-profile registry by default. The optional + concrete registry is an isolated-test seam, not exporter discovery. + +GenerationService.list_instrument_profiles() -> ProfileListResult + Returns three actual, defensively checked maps, sorted by registry ID: + standard.bass.v1, standard.gm-drums.v1, standard.lead.v1. + Each exposes mapping_kind=standard_midi, normal-only articulations, + actual product/standard versions and limitations, midi_available=true, + native_available=false. Intended routing is not vendor compatibility. + +GenerationService.generate_music(request: GenerateMusicRequest) + -> GenerationResult, or existing named domain errors. + Revalidates the complete mutable request graph, then: + resolve_description -> post-resolution association validation -> + registry selection/revalidated maps -> real native capability preflight -> + compose_score -> compile_score -> exclusive staged write_midi -> + actual saved-file checks and validate_midi_file -> anticipated result + construction/revalidation/JSON serialization -> directory publication. + +No duplicate note-generation logic. Existing exact timing, articulation, +profile provenance, event-pairing and 100,000-event safeguards remain intact. +Only actual published absolute paths and measured sizes are returned. +Result metadata includes parts, profile IDs, BPM/bars/meter/key/seed, common +musical start/end/PPQ, assumptions/structured overrides and explicit warnings. +No raw description, file bytes or private exception text is included. + +FORMAT AND WARNING POLICY + +- Omitted/null formats request MIDI plus applicable native targets: + AGP for selected lead/bass and SDP for selected drums. +- Explicit ["mid"] means MIDI only, status=complete, fallback_for=[]. + Native capability checks are not run for this case. +- Explicit AGP/SDP applies only to the corresponding selected parts. + Applicability/profile associations are rechecked after text inference; + omitted pre-parser parts cannot bypass these checks. +- Current real checks report agp_layout_not_established or + sdp_layout_not_established. With fallback allowed, one combined MIDI + contains ALL selected parts even when "mid" was not requested. +- status=midi_fallback, fallback_for and NATIVE_FORMAT_UNAVAILABLE warnings + cover exactly the selected unavailable native-requested parts. +- Every selected standard-only map always gets STANDARD_MIDI_MAPPING, + including complete MIDI-only success. Example message: + "standard.lead.v1 uses Standard MIDI only; not a verified Eclips/Ray/SD3 + mapping or vendor compatibility claim." +- Native lead example: + "agp: agp_layout_not_established; the combined Standard MIDI substitutes + for this native target." +- Native-disabled requests fail before staging. No native path is returned. + A future capability flag without an actual writer fails explicitly; + it cannot produce fake native success. +- Invalid input, unsupported palm mute, corrupt maps, serializer/read-back, + disk/permission/publication failures and unexpected bugs never become + fallback successes. + +EXACT NAMED FAILURE BOUNDARIES + +Reuses INVALID_REQUEST, UNSUPPORTED_DESCRIPTION, PROFILE_REQUIRED, +UNSUPPORTED_ARTICULATION, NATIVE_FORMAT_UNAVAILABLE, OUTPUT_EXISTS, +OUTPUT_IO_ERROR and SERIALIZATION_ERROR; no new public code invented. + +Representative exact details: +- Invalid mutable request: reason=invalid_request_model. +- Inferred invalid associations: reason=resolved_part_association. +- Wrong-part profile: existing PROFILE_REQUIRED / reason=wrong_part. +- Disabled drums native: + {"part":"drums","format":"sdp","reason":"sdp_layout_not_established"}. +- Existing output: OUTPUT_EXISTS / reason=destination_exists. +- Root/ancestor identity or reparse change: OUTPUT_IO_ERROR / + reason=output_root_changed. +- Stage identity/confinement failure: reason=stage_ownership_changed. +- Stage create/name/initial-identity errors: + stage_create_failed, stage_name_collisions, stage_ownership_unestablished. +- Unusable staged file: SERIALIZATION_ERROR / invalid_staged_midi. +- Content changed during read-back: OUTPUT_IO_ERROR / staged_content_changed. +- Result-model failure before rename: + SERIALIZATION_ERROR / invalid_generation_result. +- Rename permission/disk failure: OUTPUT_IO_ERROR / publication_failed. +- Other staged OSError: OUTPUT_IO_ERROR / staging_io_failed. +- Unsafe/failed cleanup: OUTPUT_IO_ERROR / stage_cleanup_failed, with only + original_code= when handling failure. + +Known domain failures become schema-declared structuredContent with isError. +Successful MCP responses have schema-declared structuredContent and concise +text containing status, parts, warning count and published paths. +Unexpected bugs still propagate through the existing sanitized stderr +diagnostic/SDK error path, not a fabricated typed success or invalid-input blame. +Strict schemas, IDs, initialization, protocol errors, stdout framing and EOF +behavior are preserved. + +FILESYSTEM GUARANTEES AND PRECISE LIMITATIONS + +- Only the operator chooses the existing root; tools choose only the existing + strict 1-64-character ASCII basename, with reserved Windows names rejected. +- Rejects URI/UNC/device/drive-relative paths, controls, traversal, missing + roots, files, existing root/ancestor symlinks and all Windows reparse points. + GetDriveTypeW rejects mapped network, optical, unknown and no-root volumes; + configured volume must classify fixed/removable/RAM. This is not a write probe. +- Pins device/inode identities for root AND ancestors and rechecks them + throughout staging, cleanup and publication. Checks stage identity, + non-reparse status and resolved-parent confinement. +- One exclusively created UUID stage lives INSIDE the output root. At most + three name attempts. Only .mid is permitted. Directory inspection + examines at most two entries; unexpected contents refuse publication/cleanup. +- Saved MIDI must be a regular non-reparse file, positive and <=16 MiB. + The service checks actual size, full saved content through the existing + validator, and stable identity/size/mtime. Existing composer/compiler + bounds reject excessive musical events before staging/allocation. +- Constructs/revalidates the anticipated result and JSON representation + before the commit point. No result-model failure publishes a final directory. +- Publishes the whole stage as \ using same-volume Windows + directory rename. The final directory never contains a partial artifact set. + Windows os.rename refuses existing files, populated OR EMPTY directories, + and concurrent same-name destinations. There is no replace/merge/delete + workaround. Exactly one competing request wins; the loser is OUTPUT_EXISTS. +- This publication implementation is explicitly WINDOWS ONLY. Non-Windows + generation fails before staging: + OUTPUT_IO_ERROR / no_replace_publication_requires_windows. + POSIX replacing-rename semantics are never silently accepted. +- Cleanup removes only the specific verified owned stage's expected regular + non-reparse MIDI, then that empty stage directory. It does not recursively + delete root contents, follow junctions, remove other stages or touch sentinels. + Lost ownership, root change, injected content or cleanup permissions can + leave a stage for operator inspection and are explicit cleanup failures. +- Path/lstat/recheck APIs are NOT comprehensive adversarial race protection. + A local actor with replacement rights can race checks versus filesystem + operations. Use trusted operator-controlled ACLs on root/ancestors/volume. + No handle-relative NT namespace confinement, malicious mount/remapping + defense, permanent open identity pin or protection against file-ID reuse + is claimed. mode=0700 is not a Windows ACL guarantee. +- No fsync/power-loss durability or transaction acknowledgement database. + Rename is the publication commit point: a crash/client disconnect afterward + can leave a valid output even if the caller never receives the response. + No destructive post-publication rollback is attempted. + +ACTUAL REAL-STDIO AND PERSISTENT DISK EVIDENCE + +Launched the actual installed editable module using isolated Python imports: + .venv\Scripts\python.exe -I -B -m riff_groove_builder + --output-dir \.test-artifacts\step9-verified\outputs +Working directory was the separate owned client-cwd, NOT the repository root. +PID 21540 initialized protocol 2025-11-25, listed exactly two tools and the +three real profiles, generated four files and exercised five known failures. +12 newline-delimited response objects preserved string/integer IDs. +All profile/generation/error structured results passed their declared JSON +Schemas. Closing stdin yielded exit code 0, zero stderr bytes, zero additional +stdout bytes and zero remaining stage directories. The child was reaped. +The empty owned client-cwd was removed after validation. + +Persistent outputs are under this absolute root: +D:\_Repos\Code\GAJ3T\MCPs\MusicGen\GAJ3T.MusicGen.Riff-Groove-Builder\ + .test-artifacts\step9-verified\outputs + +Three-part description: +"lead bass drums 137.5 BPM 2 bars 7/8 Bb minor quarter rests", seed=42. +Resolved: lead/bass/drums; 137.5 BPM; two bars; 7/8; A# minor; +start=0, end=6720, PPQ=960, actual IDs standard.lead.v1/standard.bass.v1/ +standard.gm-drums.v1; disclosed omitted rhythm/technique assumptions. + +Files relative to that root: +- midi_only\midi_only.mid: 324 bytes; explicit ["mid"]; status=complete; + fallback_for=[]; three STANDARD_MIDI_MAPPING warnings. +- default_all\default_all.mid: 324 bytes; formats omitted; + status=midi_fallback; fallback_for=["lead","bass","drums"]; three standard + mapping plus three native-unavailable warnings. +- native_only\native_only.mid: 324 bytes; formats=["agp","sdp"]; + same explicit fallback coverage and six warnings; no native files. + +All three actually begin MThd, are SMF type 1 / 960 PPQ, with tracks +Conductor, Lead, Bass, Drums; all four EOTs=6720. +Note-on counts by track: 0,6,6,12. SHA256 for EACH: +7d61b8d4a8c42a19091126ce7301b159744bbae4e78456b0cd1894f6269aea4b +Identical bytes demonstrate unchanged musical content across requested-format +policies, not three independent native encodings. + +- bass_only\bass_only.mid: 237 bytes; "bass only 72.5 BPM 3 bars 6/8 + Bb minor eighth", seed=0, explicit mid; complete, one mapping warning. + Type 1 / PPQ=960; Conductor/Bass; both EOTs=8640; note-on counts 0,18. + SHA256: + 9dbd7e537c462a4d1a041d954cb91cd586c23c7b85ca5f820d33eda86724daf9 + +The same real process also returned exact expected typed failures for: +bars=1.0 -> INVALID_REQUEST; +inferred drums plus agp -> INVALID_REQUEST; +native-disabled drums -> NATIVE_FORMAT_UNAVAILABLE; +lead palm mute -> UNSUPPORTED_ARTICULATION; +existing midi_only basename -> OUTPUT_EXISTS. +No bad/disabled/unsupported directories, AGP/SDP files or sidecars exist. +Each published directory contains only its actual correctly named .mid. +An independent follow-up disk inspection verified all sizes, hashes, headers, +track names, common endings and note counts above. + +TESTS, STATIC CHECKS AND EXACT FINAL RESULTS + +Environment: existing .venv, CPython 3.13.13, Windows AMD64. +No other runtime/OS/receiver/plugin setup is certified. +No dependencies were installed/restored or manifests changed. +Existing distribution tests still perform their isolated offline wheel installs. + +Repository-local subprocess scratch setup: +$scratch = New-Item -ItemType Directory -Force '.test-artifacts\scratch' +$env:TEMP = $scratch.FullName +$env:TMP = $scratch.FullName +$env:TMPDIR = $scratch.FullName +$env:PIP_NO_INDEX = '1' + +Final focused: +& '.\.venv\Scripts\python.exe' -m pytest tests\unit\test_service.py tests\unit\test_server.py tests\integration\test_generation_service.py tests\integration\test_stdio.py -q --tb=short +PASS: 140 passed in 13.89s; 0 failed, 0 skipped. + +Final complete current suite: +& '.\.venv\Scripts\python.exe' -m pytest -q --tb=short +PASS: 1118 passed in 34.95s; 0 failed, 0 skipped. +Includes strict contracts/errors, all standard/vendor-test mechanics, parser, +composer, compiler, MIDI/MIDIUtil read-back, both native-unavailable boundaries, +real stdio protocol/generation, offline sdist/wheel build/install and installed/ +ZIP-wheel packaged-resource regressions from different working directories. + +& '.\.venv\Scripts\python.exe' -m ruff check . +PASS: All checks passed! +& '.\.venv\Scripts\python.exe' -m ruff format --check . +PASS: 67 files already formatted (final rerun after persisting this report). +& '.\.venv\Scripts\python.exe' -m mypy --strict src tests +PASS: Success: no issues found in 38 source files. +& '.\.venv\Scripts\python.exe' -m pip check +PASS: No broken requirements found. +git --no-pager diff --check +PASS: no tracked-diff whitespace errors. Most existing implementation files +remain untracked; Ruff checked actual authored Python files independently. + +All seven authored/updated Python files also have no editor-reported problems. +Editor runTests reported no discovered tests; this is not a pass or pytest skip. +The explicit venv pytest commands above are the actual execution evidence. + +TEST COVERAGE AND ISSUES RESOLVED + +Tests cover default/explicit/native-only formats; exact warning/status/part/ +profile/fallback coverage; MIDI-only with fallback disabled; post-inference +associations; unsupported palm mute; mutated/unchecked request graphs and +corrupt maps; future flags cannot invent codecs; event-budget rejection; +partial writes, actual corruption, read-back IO, result-model failures, +unexpected bugs, changing content, root/ancestor identity replacement, +bounded stage retries, create/publication/cleanup failures and ownership. +Existing file/populated/EMPTY directory identity and sentinel preservation +are checked, as are competing same-basename requests with one winner. + +Genuine Windows junction tests ALL RAN AND PASSED (five parameter cases): +root, ancestor, pinned root replacement, destination and staged-directory +replacement. These are actual mklink /J reparse points, not only mocked flags. +They do not certify comprehensive hostile race safety. Every created junction +was explicitly removed; outside sentinels survived. No environment skips. +Local-volume classification and reparse flags also have focused unit coverage. + +Initial focused run: six assertions incorrectly expected lowercase MIDI track +names. Existing writer contract is Conductor/Lead/Bass/Drums; corrected the new +tests, not the writer or its checks. Initial Ruff findings were unused import +and line wrapping; fixed/formatted authored files with no rule relaxation. +Final suite, lint, format, strict mypy and pip check all pass. + +CLEANUP AND SEPARATE READINESS + +Owned UUID service/server/stdio/junction/MIDI/distribution test workspaces +cleaned up. Only existing scratch and the deliberately retained step9-verified +MIDI evidence directory remain under .test-artifacts. No generated evidence +script, child server, stage directory or background helper remains. +Existing caches/venv/dist and unrelated worktree content were preserved. + +Software Standard MIDI MCP generation: VERIFIED, ready for review/use on the +tested Windows configuration. No implementation blocker remains for Step 9. + +Verified vendor Eclips/Ray/SD3 mapping acceptance: STILL OPEN. +Installed product/build/library/preset/map, actual control/range/layer behavior +and evidence are not established by these standard maps. + +Real AGP and SDP layouts/serializers: BLOCKED separately. Existing step_7_fix.md +and step_8_fix.md remain untouched and unresolved. No genuine native fixtures, +native serialization/parser round trips or native success were manufactured. + +Actual Eclips/Ray/SD3 and Cubase import/routing/load/save/reload acceptance: +UNRUN, not test passes or skips. The amended plan permits this independent +standard-MIDI completion, not full native/application/release acceptance. +Ready for review of this step, not a claim that those separate gates are passed. +Stopped after verified implementation/evidence/report; no later prompt executed. +``` diff --git a/prompts/report_9_fix.md b/prompts/report_9_fix.md new file mode 100644 index 0000000..0fbc207 --- /dev/null +++ b/prompts/report_9_fix.md @@ -0,0 +1,322 @@ +``` +STEP 9 FIX — VERIFIED REAL NATIVE MCP INTEGRATION +Date: 2026-10-20 +Result: COMPLETE for the implemented native/MIDI software subset. +Application open/play/save/reload, audible checks and Cubase acceptance: UNRUN. + +SCOPE / PRESERVATION + +Executed prompts\step_9_fix.md against the latest plan continuation, CURRENT +report_7_fix/report_8_fix and existing codecs/profiles/contracts/compiler-facing +pipeline/service/server/tests. Existing real codecs were used, not replaced +with unavailable placeholders or renamed MIDI. Prior reports and unrelated +pre-existing work were preserved. No commits, delegation, later prompts, audio, +plugin hosting, network uploads or private/factory-content distribution. + +IMPLEMENTED + +1. Real service registration of write_riffer/validate_riffer_file, + write_sdp/validate_sdp_file and existing MIDI APIs. Defaults request combined + MIDI plus each selected native target. Actual published names: + .mid + _lead.griff + _bass.briff + _drums.sd3p + Artifacts contain actual suffix/part/profile/size/path metadata. + agp expands to relevant griff/briff; sdp to sd3p. Actual names also work; + requesting aliases and actual names together deduplicates real outputs. + Available native-only requests produce no unnecessary MIDI. + +2. Unambiguous target defaults: + lead ample.ame.4.0.1.riffer.v1 + bass ample.amr.4.1.0.riffer.v1 + drums toontrack.sd3.3.4.4.core.v1 + standard.lead.v1 / standard.bass.v1 / standard.gm-drums.v1 remain explicit + standard fallbacks, not relabeled vendor maps. Strict profile validation + still enforces target/version/tuning/voice/switch/velocity/provenance facts; + it now permits evidence-backed target defaults. Old standard behavior tests + explicitly select standard IDs, while separate tests verify target defaults. + +3. Optional operator --sd3-template threads typed Path through CLI, run_stdio, + create_server and GenerationService, then native preflight/write/validation. + The path is absolute-pinned at service construction, inspected read-only, + and checked by file identity/size/mtime/SHA-256 throughout the transaction. + No tool-controlled template path exists. Missing optional template is known + native unavailability; an explicitly supplied missing/unreadable/corrupt/ + unsupported/map-mismatched/changed template is a visible error, never fallback. + Startup errors use stderr, nonzero exit, no protocol stdout or project bytes. + +4. Missing drum template with allowed fallback emits real griff/briff plus ONE + combined MIDI with fallback_for=["drums"]. Native-disabled fallback errors + before staging. Explicit MIDI-only target maps need no optional template. + Known native pre-roll/tail/grid/decimal/controller/physical-string limits + are preflighted without output creation; a narrow fixed reason allowlist + controls representation fallback. Corrupt maps/plans, string search + exhaustion, writer/read-back corruption, template/IO/programming faults are + not successful fallback. There is no native_writer_not_registered path. + +5. Runtime profile listing reports actual native readiness, corrected suffixes, + version/library/subset/default limitations and template requirement. + Stored codec availability is not confused with configured SD3 readiness. + Target results carry per-part VERIFIED_SUBSET_LIMITS; explicit standard + profiles retain STANDARD_MIDI_MAPPING. Fallback adds exact per-part + NATIVE_FORMAT_UNAVAILABLE warnings. Resolved metadata/assumptions/overrides + and actual saved sizes/profile IDs remain validated. + +6. Palm mute reaches real lead/bass generation from all documented spellings. + Guitar: MIDI D0/26 selector and native PM. Bass: C0/24 selector, musical + velocity 32..63 and native PMP, NOT the separate D0 native PM mode. + Mixed pitched+drum requests apply palm mute to selected lead/bass only; + drums stay normal, explicitly disclosed in resolved assumptions. + Drum-only palm mute raises UNSUPPORTED_ARTICULATION/pitched_parts_required. + Explicit standard pitched profiles still reject palm mute rather than + approximating or silently dropping it. Applicability is documented/tested. + +MULTI-ARTIFACT TRANSACTION / SHARED CHANGES + +One exclusively created UUID stage lives directly under the pinned local root. +Only requested native/MIDI outputs are staged, at most four files. Each writer +now accepts an optional on_created(fstat) observer immediately after its exclusive +open, before bytes are written. This minimal shared API extension lets the +service record the ACTUAL created file identity even on partial native failure; +standalone behavior and exclusive-create rules remain intact. + +Every saved file is independently validated after the writer's own read-back. +Files must be regular, non-reparse, singly linked and positive <=16 MiB. +Identity/size/mtime/SHA-256 and exact filename coverage are rechecked after all +writers, immediately before publication; same-size/mtime-restored corruption +of an earlier native file is detected. Complete result construction, model +revalidation and JSON serialization precede the commit. + +Commit is the existing same-volume Windows no-replace directory rename. +No overwrites, merges, partial final directories or delete-destination tricks. +Concurrent four-artifact requests have exactly one winner and one OUTPUT_EXISTS. +Root/ancestor/stage identities and reparse checks remain enforced. + +Cleanup first checks ALL present entries against exclusively recorded identities, +then unlinks only owned regular files and removes that specific empty stage. +Unknown injected content, same-name replacement or lost directory ownership +causes explicit stage_cleanup_failed and preserves suspicious/user data. +No recursive service cleanup. Permission-denied cleanup remains visible, with +only the original public error code. A failure in the last native writer after +MIDI/griff/briff exist cleans the owned partial sd3p and all earlier owned outputs. +Native corruption/publication failures never become MIDI-only successes. + +ACTUAL STDIO EVIDENCE — ORIGINAL MINIMAL TEMPLATE, RETAINED + +Root: + .test-artifacts\step9-stdio-32274b1a3f384ef89a37e025182bb8f5 +Original template: copied solely from the newly authored portable fixture +tests\fixtures\sd3\original-template.sd3p, not a stripped private/vendor export. +Source template identity/mtime/bytes were unchanged. + +Real isolated module subprocess, cwd=\other-cwd, operator +--sd3-template configured; initialize, tools/profile/schema discovery, generate +and EOF were exercised. Eight stdout lines all validated as JSON-RPC, stderr +empty, exit 0. An attempted tool template-path argument was rejected privately. + +Original request: + lead bass drums palm mute 137.5 BPM 2 bars 7/8 Bb minor quarter rests + seed=42, allow_midi_fallback=false +Resolved: target IDs above, A# minor, PPQ 960, musical start=0/end=6720. +Native Riffer PPQ=480, end=3360. SD3 common interval=0..7 quarter beats. +Combined MIDI conductor tempo=436364 microseconds/quarter, meter=7/8, +Conductor/Lead/Bass/Drums, common EOT=6720 and channels 0/1/9. +Musical notes: lead 6, bass 6, drums 12; MIDI pitched switches are additional +selection events, not miscounted musical notes. + +Published default set under outputs\default: + default.mid 336 bytes + SHA256 8fc4cfbe66c0706f223ec33a61692ead046a56a9dba51c6566f967690cee186c + default_lead.griff 1296 bytes, six PM notes, velocity range 64..96 + SHA256 fe7a2a5c98d0ae16f6894e681e7f001a658c90d11b3f1beb313d5c98b6c810c9 + default_bass.briff 1282 bytes, six PMP notes, velocity range 48..55 + SHA256 5da9b05e92e6989366f41f8abf22a0f8b88ae14591bc8b544e4c7c0cf47827c4 + default_drums.sd3p 1491 bytes, twelve normal notes, velocity range 64..96 + SHA256 8bee8a86a7e60320d02c4404e36d818639af1d8f4ebce27f6c23a25e7ebd0589 + +outputs\aliases (formats agp+sdp) and outputs\actual (griff+briff+sd3p) each +contain exactly THREE native files, byte-identical to the default natives. +outputs\midi contains only the same 336-byte MIDI. All statuses are complete, +fallback_for empty, with three subset-limit warnings and disclosed drum +normal/pitched-only palm-mute applicability. + +Independent content checks parse actual saved XML, MIDI messages and packed +SD3 triples and invoke saved validators against the same requested score. +Guitar musical pitch multiset: 58x2, 61x2, 65, 66. +Bass: 46x4, 53x2. Guitar uses selector 26; bass selector 24, switch velocity +100, musical bass velocities 48/51/55 (within C0 palm-mute band). +Drums use only actual mapped 36/38/42 on channel 9, no palm-mute switches. +Expected native note intervals are 0..480, 480..960, 960..1440, +1680..2160, 2160..2640, 2640..3120; final rests retain the full bar boundaries. + +Additional cases cover normal technique, 123 BPM, 3/4, F# major, metal sixteenths, +structured tempo override, aliases, single parts and mixed parts. Exact score, +tempo/meter/key/seed/profile/velocity/technique and filesystem coverage are checked. +evidence.json retains request/result/content hashes, not private source bytes. + +ACTUAL INSTALLED-WHEEL NATIVE SERVICE EVIDENCE + +Offline distribution tests built an sdist then wheel, installed the real wheel +with --no-index --no-deps --no-cache-dir --target, and ran installed __main__ +using isolated -I -B Python outside the checkout: + cwd D:\_Repos\Code\GAJ3T\MCPs\MusicGen +Verified all 16 package/submodule locations and metadata under the noneditable +install target, plus all six JSON resources against wheel members. +The targeted acceptance run's actual service module was: + .test-artifacts\distribution-fb8b998358e341a7b3cce5a45b6101ed\ + installed-server\riff_groove_builder\service.py +This owned distribution workspace was subsequently cleaned. + +The installed codec probe authors its OWN original minimal SD3 template from +scratch. The actual installed stdio server receives that operator template and +generates default four-artifact, agp+sdp native-only three-artifact, and +MIDI-only one-artifact results. Saved validators independently compare every +file to the same original request, including PM/PMP and correct bass band. + +Installed native service results: + MIDI 336, griff 1296 and briff 1282 bytes, same hashes/content as above. + sd3p 1037 bytes, twelve drum notes, velocities 64..96: + SHA256 48300d8f14d89e8169fad4ee68ad73a7d986e14d4ae9a850cc80f3ee3171e953 +Different sd3p size/hash reflects its independently authored minimal non-song +state, not different music. Template bytes/identity/mtime unchanged. +Configured native-process stderr empty and EOF exit 0. Separate uninitialized +installed EOF also exits 0. Standard-profile/error/privacy probes remain intact. +Dependencies are reused from the development venv, not claimed as a fresh +complete dependency-environment installation. + +GENUINE READ-ONLY LOCAL-TEMPLATE SERVICE ACCEPTANCE — RETAINED / IGNORED + +Operator source, read in place only: + C:\Users\g3\Documents\Toontrack\Superior Drummer 3\sd3-demo.sd3p +Source size 75393; inode/file ID 166633186213030518; +mtime_ns 1788614183091903900; SHA256: + 06f54b02079e4b32d532ecc232b813c3fe1865799e6f5b2b21b5ddf398b0533d +All identity/size/mtime/content checks unchanged after generation and later +independent retained-file revalidation. Source had 170 old song notes. + +Retained root: + .test-artifacts\step9-genuine-4965d4bf9dfe4ff6940acaafc12df01a +genuine-original contains actual four native/MIDI artifacts from the same +original request above. MIDI/griff/briff sizes/hashes equal original stdio. +genuine-original_drums.sd3p: + 66325 bytes, twelve newly generated notes, one generated song track/clip, + exact 137.5 BPM/7/8/0..7 beats/channel 9/velocities 64..96. + SHA256 265535e1b885ff7765becce8281873ec627e28b35b5404a0f0cd9b533c424680 +All old source song tracks/clips/references were replaced, not mixed into output. +Non-song state is byte-identical, SHA256: + 10340dc5c057f2580c474ebc56277b2deae3263cee49e4674e07b8c9cc421d32 +Kit/mixer/tracker/host-sync and other unrelated operator bytes are preserved. +These local generated files therefore retain PRIVATE KIT STATE: they stay +ignored under .test-artifacts, never source/tests, package fixtures or uploads. +git check-ignore confirms both retained native evidence trees are ignored. + +After acceptance, a separate Python process independently reopened/revalidated +ALL 15 retained actual native/MIDI artifacts (11 stdio + 4 genuine), compared +their saved evidence hashes/sizes/content, and reconfirmed the source 170-note +template. Result: 15 passed, source unchanged. No incomplete stage remains in +either retained evidence tree. + +EXECUTED VALIDATION — FINAL ALL PASS, NO SKIPS + +Windows existing .venv, CPython 3.13.13. No dependency manifest changes and no +application/test dependencies restored or installed. Offline package target +installation is the required distribution acceptance, not a dependency restore. + +Focused native/service/publication run: + .\.venv\Scripts\python.exe -m pytest tests\integration\test_native_service.py tests\unit\test_service.py tests\integration\test_generation_service.py -q --tb=short + Earlier implementation checkpoint: 129 passed in 5.07s. + +Focused service/stdio/distribution/static-refinement run: + .\.venv\Scripts\python.exe -m pytest tests\integration\test_native_service.py tests\unit\test_agp.py tests\unit\test_service.py tests\integration\test_distribution.py tests\integration\test_stdio.py -q --tb=short + Earlier checkpoint: 203 passed in 31.72s, before final added cases. + +Retained native acceptance: + $env:RIFF_SD3_TEMPLATE = 'C:\Users\g3\Documents\Toontrack\Superior Drummer 3\sd3-demo.sd3p' + $env:RIFF_NATIVE_EVIDENCE = '1' + .\.venv\Scripts\python.exe -m pytest tests\integration\test_native_service.py tests\integration\test_distribution.py -q -s --tb=short + PASS: 49 passed in 18.93s, no failures/skips. + Captured .test-artifacts\step9-native-acceptance.log contains real + editable-stdio, genuine-template and installed-wheel evidence. + +Final full current regression (RIFF_SD3_TEMPLATE set as above; retain flag absent): + .\.venv\Scripts\python.exe -m pytest -q --tb=short + PASS: 1369 passed in 53.92s; 0 failures, 0 skips. + Prior accepted current suite: 1320 tests; 49 additional cases now cover + native service/stdio/transactions/template/CLI failures. + Log: .test-artifacts\step9-full-final.log. + + .\.venv\Scripts\python.exe -m ruff check src tests + PASS: all checks passed. + .\.venv\Scripts\python.exe -m ruff format --check src tests + PASS: 44 files already formatted. + .\.venv\Scripts\python.exe -m mypy src tests + PASS: strict project configuration, no issues in 44 source files. + .\.venv\Scripts\python.exe -m pip check + PASS: no broken requirements. + git --no-pager diff --check + PASS. + Editor Problems for src/tests: no errors. + Editor runTests discovered no tests; explicit pytest execution above is + authoritative, not a falsely reported editor test pass. + +FAILURES ENCOUNTERED / CLEANUP + +The first intentional default-change regression run showed 119 failed, +1201 passed and one fixture-teardown error. Old standard-default assertions, +unregistered-writer expectations, one-file stage assumptions and writer mocks +needed coherent updates. Those old behavior tests now explicitly select the +same standard IDs rather than weakening numerical/music/atomic assertions. +The subsequent complete run had four wrong-part standard helper failures +(1353 passed): its drums selection incorrectly formed standard.drums.v1. +Corrected to standard.gm-drums.v1. New target-native assertions and tests +separately cover the changed behavior. Ruff import/line-length/format issues +were fixed before final full verification; strict types pass. + +Injected failures tested and verified: + - last native partial write; corruption of actual saved sd3p; + - native writer/read-back SerializationError and OutputIOError; + - corrupt map/score-plan mismatch versus known native decimal/pre-roll limits; + - publication failure and denied cleanup after all four files exist; + - unknown injected stage content and same-name file identity replacement; + - earlier native mutation after its validation, including restored size/mtime; + - existing destination/sentinel identity preservation; four-file concurrent + one-winner publication; shared existing real Windows junction tests; + - result construction/serialization failure before publication; + - explicit bad/changed operator templates and private startup diagnostics. +No failing path returned successful fallback or published a partial directory. +Expected safe-owned failures cleaned every staged owned file. Suspicious or +cleanup-denied stages intentionally remain at service level; test fixtures +cleaned only their exclusively owned test workspaces afterward. Existing +operator destinations/sentinels were preserved. Distribution/install/test +workspaces and subprocesses were cleaned; only requested ignored evidence/logs +remain. No user/private template was altered or copied into source. + +DOCUMENTATION / READINESS + +Updated README startup/client configuration and actual native/default/alias/ +fallback examples, architecture transaction guarantees and limits, profile +default/runtime/PM applicability docs, native format APIs, compatibility matrix +and current plan status. Historical reports remain unchanged by this task. +Existing native codecs received only no-output preflight helpers and optional +exclusive-create observers; the actual encodings/readers remain the prior +evidence-backed implementations. + +READY: verified real native software integration, runtime capability summaries, +safe owned multi-artifact publication, default/alias stdio generation, +installed-wheel native generation, original/genuine-template content validation, +complete regression/static/dependency checks and persistent evidence/report. +No later prompt or application work was started. + +REMAINING APPLICATION-ONLY LIMITS: actual Eclipse/Ray5/SD3 load/inspect/play/ +save/close/reload, audible articulation/velocity behavior, Cubase import and +exact receiver routing/configuration remain UNRUN, not pytest skips/passes. +Only the declared versions/tunings/normal-palm-mute and SL-DFH three-voice +subsets are supported; arbitrary techniques/libraries/containers are not +claimed. Original minimal templates are codec fixtures, not shipped playable kits. +Preserved SD3 host-sync/mute/routing settings can affect playback/tempo. +Trusted output-root/ancestor ACLs remain required: path identity/hash/reparse +checks are not adversarial handle-relative Windows confinement. Directory +rename is the commit point; crash/client disconnect afterward may leave valid +output without a response. No power-loss durability or rollback guarantee. +``` diff --git a/prompts/report_9_fix_controls.md b/prompts/report_9_fix_controls.md new file mode 100644 index 0000000..bb6db6e --- /dev/null +++ b/prompts/report_9_fix_controls.md @@ -0,0 +1,222 @@ +``` +STEP 9 CONTROLS FIX — VERIFIED SCOPED MCP CONTROLLER REQUESTS +Date: 2026-10-20 +Result: COMPLETE. Ready for final native application acceptance. +Application open/play/save/reload, audible behavior and Cubase acceptance: UNRUN. + +SCOPE / IMPLEMENTATION + +Executed prompts\step_9_fix_controls.md against CURRENT report_9_fix.md and the +existing strict contracts, compiler, service, MIDI, Riffer and SD3 codecs. +Preserved the pre-existing working tree and earlier reports. No commits, +delegation, later prompts, new dependencies, domains, audio/hosting/model +features, private templates or guessed vendor-effect mappings. + +1. GenerateMusicRequest now accepts optional cc_events, default []. + Each strict ScheduledControl has exactly part, beat, controller and value. + Parts are lead/bass/drums; beats reuse reduced RationalBeat quarter-note + positions; controller/value are strict integers 0..127. Unknown fields, + booleans, strings, floats, invalid bounds and sub-tick beats are rejected. + JSON Schema exposes the strict item, maximum 100,000 items and explicit + selected-part associations. Normalized (part, beat, controller) duplicates + fail even with identical values or differently spelled equivalent ratios. + Association is checked again after text inference. + +2. apply_scheduled_controls runs after ordinary compile_score, reusing + ControlChangeEvent/EventTrack/EventPlan and the existing exact tick helper. + It adds the common musical-start offset, uses the selected profile channel, + preserves all original notes/switches/order keys and score/timeline fields, + assigns new unique sequences, and sorts CC before same-tick note-ons. + Controls plus all compiled musical/switch events share the existing 100,000 + event budget. Beat <= resolved musical duration is required; explicit end + resets are valid. No reset or controller-to-technique inference is invented. + Empty controls return the original compiled plan unchanged. + +3. An explicit CC at an articulation-owned tick/controller is INVALID_REQUEST, + even for an identical value. Details identify cc_events, part, tick and + controller and say to remove/move the point. No silent articulation override. + +4. Existing real MIDI/Riffer codecs retain the controls, without changing their + encodings. MIDI preserves every valid requested controller/channel/tick/value. + Riffer retains the evidenced CC1 stair lane at native PPQ 480; unsupported + controllers remain precise known native unavailability, not dropped messages. + +5. SD3 preflight now reports sd3_native_controller_not_supported ONLY after + checking channels, note roles, release semantics and exact score/note-event + agreement. The observed native subset establishes note triples, not CC + triples. Only this new controller-specific reason was added to the existing + narrow representation-fallback allowlist; corruption is not allowlisted. + Allowed fallback replaces only the affected native target with combined + MIDI; other valid native targets survive. Disabled fallback fails before + staging. MIDI-only controls bypass native preflight and need no SD3 template. + +6. Updated README with a concrete optional cc_events/reset example, exact + units/grid/budget/collision rules and native limitations; updated the MCP + architecture contract and SD3 codec documentation. + +ACTUAL REAL STDIO / NATIVE / MIDI EVIDENCE + +The original portable fixture tests\fixtures\sd3\original-template.sd3p was +copied into exclusively owned test workspaces, supplied as an operator CLI +template and checked unchanged in bytes/file identity/mtime afterward. +No private project or kit state was accessed for this task. + +Actual isolated Python -I -B module stdio subprocess, different working +directory, initialization, live input/output schema discovery, generation, +error cases and EOF were exercised. Checkout control acceptance observed +13 valid JSON-RPC stdout lines, empty stderr and exit 0. + +Request baseline: original seed=42, 137.5 BPM, 2 bars 7/8, Bb minor, quarter +rests, palm mute on pitched parts only. MIDI PPQ=960, musical start=0, +musical end/EOT=6720; native Riffer PPQ=480, end=3360. + +Independently expected and read-back MIDI controls (tick, controller, value): + lead, channel 0: (0,1,11), (480,1,73), (6720,1,0) + bass, channel 1: (0,1,21), (960,1,127), (6720,1,0) +Native XML cc-1.Mod/p stair points (native tick, value): + lead: (0,11), (240,73), (3360,0) + bass: (0,21), (480,127), (3360,0) +Both native read-back validators and independent XML parsing confirm every +point, including the explicit reset. Mido independently accumulates deltas, +checks exact channels and raw [0xB0|channel, controller, value] message bytes, +and verifies same-tick CC precedes note-ons. Musical notes/switches and native +PM/PMP techniques/velocities continue to pass the original saved validators. + +Seven successful cases and four rejected cases run through actual stdio: + + pitched CC1: + 6 combined-MIDI CCs, 3 lead + 3 bass native stair points; + actual outputs mid, griff, briff; complete, no native fallback. + all-part drum CC: + adds channel-9 (320,4,96), (6720,4,0), 8 combined-MIDI CCs total; + actual outputs mid, griff, briff; fallback_for=["drums"] ONLY; + warning reason sd3_native_controller_not_supported. + unsupported lead Riffer CC74: + adds lead (320,74,127), (6720,74,0), 8 combined-MIDI CCs total; + actual outputs mid, briff, sd3p; fallback_for=["lead"] ONLY; + warning reason unsupported_native_controller. Bass and drum natives survive. + explicit MIDI-only mixed controls: + lead/bass CC1, lead CC74 and drum CC4, 10 exact CCs total; + one actual .mid, complete with fallback disabled, no fallback warning. + exact one-tick MIDI-only CC: + lead/channel-0 CC1=99 at tick 1 (beat 1/960), exactly one CC; + no rounding, no implicit reset, complete. + controls omitted / controls []: + four actual outputs each, zero CCs; all four byte-identical to each other + AND pinned to the original report_9_fix pre-controls SHA-256 baseline. + rejected drum CC with fallback=false: + NATIVE_FORMAT_UNAVAILABLE / sd3_native_controller_not_supported. + rejected unsupported lead CC with fallback=false: + NATIVE_FORMAT_UNAVAILABLE / unsupported_native_controller. + rejected drum CC on inferred lead-only request: + INVALID_REQUEST / resolved_part_association. + rejected CC at tick 6721: + INVALID_REQUEST / beat_after_musical_end. + +All rejected stdio cases leave the output directory snapshot unchanged: +no staged/partial artifacts, mislabeled native output or successful fallback. +Successful cases produce exactly 19 artifacts across their seven directories +per control acceptance run; every saved artifact is independently validated. + +NO-CONTROL ORIGINAL BYTE REGRESSION + +SHA-256 values independently checked for BOTH omitted and empty controls: + MIDI: + 8fc4cfbe66c0706f223ec33a61692ead046a56a9dba51c6566f967690cee186c + lead griff: + fe7a2a5c98d0ae16f6894e681e7f001a658c90d11b3f1beb313d5c98b6c810c9 + bass briff: + 5da9b05e92e6989366f41f8abf22a0f8b88ae14591bc8b544e4c7c0cf47827c4 + drums sd3p: + 8bee8a86a7e60320d02c4404e36d818639af1d8f4ebce27f6c23a25e7ebd0589 +These are the original fixture/request hashes recorded before cc_events existed, +not newly generated golden values that merely compare the implementation to itself. + +INSTALLED-WHEEL ACCEPTANCE + +The affected distribution tests build the real sdist then wheel offline, install +the wheel noneditably with --no-index --no-deps --no-cache-dir --target, and +run the installed server outside the checkout under isolated Python. +Existing assertions verify all 16 package/submodule locations under the install +target, metadata and all six packaged JSON profile resources against the wheel. +Dependencies are reused from the existing venv; this is not a claimed clean +installation of the complete dependency environment. + +The same seven successful/four rejected control cases above run against this +actual installed stdio server, with live input/output schema comparisons, +independent Mido/XML/native saved-content validation, the copied original +portable SD3 fixture, byte-pinned no-control regression and exact fallback +checks. The configured installed native-process sequence has 17 valid JSON-RPC +stdout lines, empty stderr and exit 0 (including the existing three baseline +native/default/alias/MIDI requests and profile discovery). The original template +bytes/identity/mtime remain unchanged. Existing installed codec probes and +standard-profile/default/alias/error/privacy/EOF acceptance also pass. + +UNIT / SERVICE EVIDENCE + +37 new unit cases cover strict items/schema, rational normalization, duplicate +projection, part/grid/bounds, exact offset/order/channel/value/reset behavior, +unchanged original note/switch events, unique ordering keys, empty identity, +no invented reset, actionable articulation collisions and native preflight. +The offset test uses score origin 7 beats, common pre-roll 120 ticks and exact +1/3-beat CC at tick 440; end reset is tick 3960, not score-absolute beat 11. +The real 100,000 combined-event boundary succeeds; adding controls without +budgeting compiled notes/switches is rejected. + +7 new integration cases include real stdio, inferred-part preflight, actual +100,000-item request plus composed-event budget rejection before _new_stage, +and four corruption injections. Wrong drum channel, altered drum note, wrong +note role and nonzero release velocity combined with otherwise valid CCs each +remain SERIALIZATION_ERROR with no artifacts, never controller fallback. +Corresponding precise native preflight unit cases also pass. + +EXECUTED VALIDATION — FINAL ALL PASS + +Windows, existing .venv, CPython 3.13.13. + + .\.venv\Scripts\python.exe -m pytest tests\unit\test_cc_controls.py tests\integration\test_cc_stdio.py tests\integration\test_distribution.py -q + PASS: 47 passed in 21.47s. + + .\.venv\Scripts\python.exe -m pytest -q + PASS: 1413 passed in 62.18s; 0 failures, 0 skips, 0 xfails. + Original current suite: 1369; 44 new unit/integration cases added. + All native/default/alias/transaction/profile/MIDI regressions remain. + + .\.venv\Scripts\python.exe -m pytest tests\integration\test_cc_stdio.py::test_real_stdio_exact_controls -q -s + PASS: 1 passed in 1.92s; printed independent exact CC/output/fallback evidence. + + .\.venv\Scripts\python.exe -m ruff check src tests + PASS: all checks passed. + .\.venv\Scripts\python.exe -m ruff format --check src tests + PASS: 46 files already formatted. + .\.venv\Scripts\python.exe -m mypy --strict src tests + PASS: no issues found in 46 source files. + .\.venv\Scripts\python.exe -m pip check + PASS: no broken requirements found. + git --no-pager diff --check + PASS: no whitespace errors. + Editor Problems for all touched Python files: + PASS: no errors. Editor runTests discovered no tests; actual explicit + pytest runs above provide execution evidence, not an invented editor pass. + +ISSUES / CLEANUP / READINESS + +Initial new-test runs exposed two test-setup mistakes: a nonzero score origin +without shifting its logical note, and an empty-control expected dictionary +lookup. Corrected those fixtures/assertions; no expected-failure markers or +weaker success checks were introduced. Ruff formatting/import ordering and +strict test dictionary annotations were corrected. Final runs are all green. + +All exclusively owned cc-controls-* and distribution-* workspaces were removed +by fixture cleanup. No new incomplete service stage remains; every subprocess +was closed and awaited. Existing ignored native/private evidence trees and +prior work were preserved. No private template was copied into source. +No dependency manifests changed and no dependency restore was needed. + +READY for final native application acceptance of the declared software subset. +No implementation blocker remains. Actual Eclipse/Ray5/SD3 open/inspect/play/ +save/close/reload, audible controller behavior and Cubase routing/import still +require application acceptance and are explicitly UNRUN, not test passes. +No vendor vibrato/effect semantics, broader controller encoding, new native +techniques, libraries or playback compatibility are claimed. +``` diff --git a/prompts/step_1.md b/prompts/step_1.md new file mode 100644 index 0000000..2e1a627 --- /dev/null +++ b/prompts/step_1.md @@ -0,0 +1,133 @@ +# Step 1: Project foundation and compatibility evidence inventory + +## Objective + +Implement only Step 1 of the approved `prompts/plan.md`: a reproducible Python +package foundation, working validation commands, and an honest inventory of the +evidence required for the target instruments and proprietary formats. + +Read the approved plan and applicable repository instructions before editing. +Do not create another worker prompt, start a later step, or modify the plan's +scope. Preserve unrelated work. Do not commit. + +## Files to create + +- `pyproject.toml` +- `.gitignore` +- `README.md` +- `src/riff_groove_builder/__init__.py` +- `tests/unit/test_package.py` +- `tests/integration/test_distribution.py` +- `docs/architecture.md` +- `docs/compatibility.md` +- `docs/formats/agp.md` +- `docs/formats/sdp.md` +- `prompts/report_1.md` + +Create another small support file only if needed for a working package or the +listed tests, and explain the reason in the report. + +## Implementation details + +1. Use the `src` package layout and a standard build backend. Set the project + name to `gaj3t-musicgen-riff-groove-builder` and the Python import package to + `riff_groove_builder`. An initial version of `0.1.0` is appropriate. +2. Confirm which Python interpreter is actually available. Adopt the proposed + Python >=3.11 policy only if the selected dependencies support it; record the + interpreter/version actually tested, without claiming untested runtimes. +3. Declare runtime dependencies on the official Python `mcp` SDK, Pydantic, and + Mido. Declare development/test dependencies for MIDIUtil, pytest, the SDK's + appropriate asynchronous testing support, Ruff, one type checker, and build + tooling. Use tested compatible ranges; do not guess nonexistent versions. + Do not add an audio backend, model-provider SDK, HTTP application, database, + plugin host, or general-purpose framework. +4. Keep the package initializer small. Publish a version using one authoritative + source so package metadata and the imported version agree. +5. Configure discoverable unit/integration tests, Ruff, and the chosen type + checker in `pyproject.toml`. Include package-data rules suitable for the future + profile JSON directory, without inventing profile files. +6. Use a repository-local virtual environment for installs if dependencies are + missing. Change the manifest before installing. Do not install into or modify + another user's/global environment. Ignore the environment and build/test + caches. Preserve normal source, prompts, and evidence documentation. +7. Document executable Windows-friendly commands for editable installation with + development dependencies, unit/integration tests, lint, types, and building + both wheel and sdist. Do not document an operational server command as working + before Step 3 implements it. +8. Write a concise architecture overview consistent with the approved plan. + The plan remains authoritative; avoid copying its entire contents. +9. Create a compatibility/evidence matrix with separate columns for MIDI + mappings, native layouts, automated checks, and application import acceptance. + Mark every currently unverified product/version/mapping honestly. +10. Document the native evidence requirements for each format: exact product and + version, real export/import workflow, lawful empty/one-note/multi-note files, + controlled tempo/velocity/articulation changes, and real load/save acceptance. + Distinguish evidence inventory completion from native-format completion. +11. Explain explicitly that a renamed MIDI file is not `.agp`/`.sdp` support, that + a preset-only container might not carry the requested musical content, and + that exact Eclips/Ray product names and versions still require confirmation. + Do not fabricate layouts, mappings, fixtures, or compatibility claims. +12. Use only publicly accessible official documentation for any external checks. + Do not upload private content, bypass login, copy licensed manuals, or add + native fixtures without redistribution permission. + +## Required unit tests + +- Importing the package succeeds. +- The public version is a nonempty valid release version and agrees with + installed distribution metadata. +- Importing the package does not emit stdout or start a server. + +## Required integration tests + +- Build an sdist and wheel successfully. +- Test the wheel in an isolated environment (a separate temporary venv is + appropriate), importing from a working directory outside the repository. +- Verify the installed package's version/metadata agreement in that environment. +- Ensure the distribution test does not pass by accidentally importing the + editable checkout or relying on the current working directory. +- A focused import-only wheel install may use `--no-deps` because Step 1's + initializer must not require the future server dependencies to import; + document that this is a package-layout test, not full dependency certification. +- The ordinary development environment must nevertheless resolve/install the + declared runtime and development dependencies and run the configured checks. + +Make integration tests repeatable and offline once build dependencies are +installed. Do not force network access during every test run. Do not check in +build products or virtual environments. + +## Validation and acceptance + +Run the smallest relevant test selection, the configured lint and type checks, +and a real package build. Prefer the test tool when it can discover this project; +otherwise use the project's pytest command and record the exact invocation. +Fix failures caused by this step. List every skip, warning, and unresolved +environment limitation; do not replace failed checks with claims of success. + +Acceptance requires: + +- A working package, import-safe initializer, and independently installed wheel. +- Reproducible commands and passing Step 1 tests/lint/types/build. +- A truthful evidence inventory with unresolved native/mapping gates named. +- No production server, MIDI generator, native serializer, or fabricated profile + added prematurely. + +Missing proprietary evidence is not a Step 1 implementation failure when it is +clearly documented, but it remains a blocker for the later corresponding steps. + +## Required end-of-step 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 + +Place the entire report inside exactly one plain triple-backtick fence, with no +content outside it. Include: + +- Files created/modified and the implementation summary. +- Exact interpreter and dependency versions actually tested. +- Exact validation commands with pass/fail counts and important output. +- Package-build and outside-checkout wheel-import evidence. +- Skipped checks or limitations and unresolved product/native/mapping evidence. +- A clear Step 2 readiness conclusion; do not claim full project readiness. + +Do not silently stop after writing code: run validation, write the persistent +report, and return its location with a concise outcome. diff --git a/prompts/step_10.md b/prompts/step_10.md new file mode 100644 index 0000000..78e08a0 --- /dev/null +++ b/prompts/step_10.md @@ -0,0 +1,98 @@ +# Step 10: Installed software acceptance and truthful delivery documentation + +## Objective and prerequisites + +Read the amended plan and reports through `report_9.md`. The operational +Standard MIDI service was independently verified with 140 focused service/server +tests. Native AGP/SDP writers and real vendor/application acceptance remain +blocked, not passed. Complete all independent software/package/docs checks now. + +This is not permission to label the original full native project complete. +Report software acceptance and native/application acceptance separately. +No scope expansion, commits, delegation or additional worker prompts. + +## Owned files + +- Add `tests/integration/test_installed_server.py`, or extend the existing + distribution/stdio integration surface if simpler without duplication. +- Add narrowly necessary regression tests/source fixes for defects found here. +- Update `README.md`, `docs/architecture.md`, `docs/compatibility.md`, + `docs/articulation-profiles.md` and format docs only for accurate final status. +- Correct the plan's obsolete initial "proposed/awaiting review" status to the + actual approved/partial-native status; preserve historical decisions/reports. +- Update packaging metadata only for an actual distribution defect. +- Write `prompts/report_10.md`. + +Do not change prior worker reports, invent vendor profiles, fabricate native +files or application results, add more formats, or create unrequested planning +files. Preserve unrelated work. + +## Installed-distribution acceptance + +1. Build current wheel AND sdist from the final source. +2. Run the actual installed wheel's server outside the checkout, not accidentally + importing the editable source. Assert the imported package/submodule locations. +3. Reuse existing development dependencies without unnecessary reinstalls. + An offline --no-deps install into an isolated target plus an explicit isolated + Python probe path is acceptable when documented accurately; do not call that + a fresh full dependency certification. Avoid network access in normal tests. +4. Through real stdio, initialize, list exactly two tools and three standard-only + profiles, generate a combined explicitly requested MIDI and default/native + fallback, and verify structured outputs against published schemas. +5. Parse actual published MIDI: exact type/PPQ/tempo/meter/track layout, aligned + duration, legal/pair-complete notes, profile IDs, channels and warning/status + coverage. Verify native-disabled and unsupported techniques produce errors + with no output directories. +6. Verify protocol-clean UTF-8 stdout, separate diagnostics, working-directory + independence, clean EOF and bounded child cleanup. +7. Exercise packaged JSON/resources as real wheel contents. Preserve all current + distribution/source/profile/compiler/MIDI/native-boundary/service tests. +8. No Cubase/plugin acceptance is implied by Mido opening a file. Record those + application checks as UNRUN if applications/evidence are unavailable. + +## Documentation and consistency + +- Present the project as an operational Windows Standard MIDI MCP generator with + explicit unavailable-native fallback, NOT a finished native AGP/SDP exporter. +- Include verified setup, required existing output root, absolute Windows MCP + client configuration, profile discovery, concrete accepted request examples, + actual response shape and error/fallback behavior. +- Make the closed local grammar discoverable; do not imply arbitrary descriptions + or vendor techniques work. Explain normal/sustain, unsupported palm mute with + standard maps, exact keys/meters/subdivisions/defaults, and override precedence. +- Explain standard mapping identity and receiver routing, no bank/program setup + or claimed real vendor compatibility, and valid MIDI import versus native files. +- Explain output-directory naming, no overwrite, Windows publication restriction, + trusted ACL assumptions, reparse checks, cleanup behavior and race/crash limits. +- Keep native format requirements and `step_7_fix.md`/`step_8_fix.md` handoffs + explicit; required real fixture/schema/application evidence is not a pytest skip. +- Update compatibility matrix with actual tested Python/OS/dependency versions, + installed-package/software results and separately unrun applications. +- Ensure no stale "empty registry" or "generation unimplemented" statements remain + in current docs, except clearly identified historical reports/decisions. + +## Required validation + +- New installed-wheel stdio integration and any targeted regressions. +- Complete current pytest suite. +- Ruff lint and format checks, strict mypy and pip check. +- Actual wheel/sdist build from final code. +- Confirm owned temporary build/test processes/workspaces clean up, no background + server remains, and no secrets/manuals/factory songs were added. + +Use existing tools/configuration. The known editor pytest discovery limitation +may use the verified repository-venv CLI fallback. Fix tightly coupled defects +with focused regressions; do not weaken checks or silently skip failures. + +## Acceptance and report + +Software delivery is verified only when actual installed-wheel stdio generation, +all automated checks and documentation consistency pass. Full Step 10 original +native/application acceptance remains BLOCKED while those inputs are missing. + +When complete, write your end-of-step report to ./prompts/report_10.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Use exactly one plain triple-backtick fence for the entire report. Include exact +commands/counts, installed-wheel evidence, software/build status, cleanup, +precise remaining native/vendor/application blockers, and an explicit statement +that no full native-project completion is claimed. diff --git a/prompts/step_10_fix.md b/prompts/step_10_fix.md new file mode 100644 index 0000000..bab076a --- /dev/null +++ b/prompts/step_10_fix.md @@ -0,0 +1,85 @@ +# Step 10 fix: Final real native/MIDI package acceptance + +## Objective and reviewed prerequisites + +Read the latest plan continuation and CURRENT report_7_fix/report_8_fix/ +report_9_fix/report_9_fix_controls. Real native codecs, target subset maps, +atomic native/MIDI MCP service and explicit CC requests are implemented and +reviewed. The previous MIDI-only closure was retracted; this is real native +software acceptance, not a fallback-only delivery. + +Complete final tests/build/docs/evidence for the actual supported versions and +formats: Eclipse 4.0.1 `.griff`, Ray5 4.1.0 `.briff`, SD3 3.4.4/SL-DFH `.sd3p`, +and MIDI. `agp`/`sdp` remain accepted request aliases, not mislabeled file bytes. + +No commits, delegation, later prompts, unrelated features, audio analysis or +new plugin host. + +## Safety and application status + +A live Cubase15 process with an unnamed project was observed (PID 41836 at the +check). Do NOT manipulate/close/save that user project, send global keyboard/ +mouse input, or launch competing audio hosts/drivers for acceptance. +No software test may be falsely reported as actual audible or DAW import +acceptance. Record live plugin/Cubase checks as UNRUN if safe operator validation +is unavailable; distinguish that certification limit from implemented native +serialization and exact native content checks. + +## Owned work + +- Final directly necessary native/package/stdio regressions, if any gap remains. +- Fix only actual task-caused bugs with focused tests; do not weaken existing + assertions or add cosmetic abstractions. +- README, current architecture/profile/format/compatibility docs and plan status + for actual native/MIDI behavior; remove stale current blocked-layout/MIDI-only/ + unregistered-writer claims, preserve clearly labeled historical reports. +- Update `prompts/report_10.md` with a new CURRENT native implementation/software + acceptance section; keep prior MIDI-only acceptance as labeled history inside + the same single plain triple-backtick fence. + +## Required final acceptance + +1. Run full current pytest, Ruff lint/format, strict mypy and pip check. +2. Build final wheel and sdist from the actual final source. +3. Run the EXACT persisted final wheel outside the checkout with real stdio, + not only editable source or an earlier build. Verify imported module and + JSON resources actually come from the installed noneditable wheel. +4. Use an original minimal test template for ordinary installed acceptance. + Generate default all-part four-artifact output, legacy-alias native-only, + actual-name native-only, MIDI-only, palm-muted lead/bass, CC1/native points + and explicit reset, missing-template fallback and disabled-fallback errors. +5. Independently reopen generated MIDI/XML/SD3 saved bytes and compare exact + requested musical notes, velocities, physical fingering, techniques, + tempo/meter/end, channels, controller events, artifact metadata and warnings. +6. Run genuine read-only local-template acceptance with ORIGINAL generated + music against: + C:\Users\g3\Documents\Toontrack\Superior Drummer 3\sd3-demo.sd3p + Preserve source bytes/identity/mtime/hash and all non-song instrument state. + Keep generated private-kit-state evidence ignored, outside source/tests/ + distributions; never upload it or ship the template. +7. Verify failures/collisions/corruption do not publish partial sets or overwrite + existing output. Clean only owned test workspaces and child processes. +8. Confirm packages include six real profile resources and the actual codecs, + no private native templates/factory music/manuals/executables/credentials. +9. Validate README JSON examples against live typed schemas; document exact + current text vocabulary, technique/CC limits, native aliases, target defaults, + optional operator template requirement, setup/client configuration and + trusted-root/no-overwrite/fallback behavior accurately. +10. Record the final source/build hashes/versions, pass/fail/skip counts, actual + outputs and source preservation. No full-library/all-plugin-version/ + arbitrary-technique/live-playback compatibility claim. + +Additional locally verified Riffer facts, if useful for acceptance: +all 1,089 installed riff XMLs contain conventional Key values including Cm, +A#m and other major/minor spellings; 1,049 loop-enabled examples use loopEnd in +PPQ480 ticks (e.g. 4 bars 4/4 -> 7680). These are schema facts, not test music; +do not copy any factory sequence into fixtures. + +## Required report + +When complete, write your end-of-step report to ./prompts/report_10.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +One plain triple-backtick fence for the entire report, current native acceptance +first and prior MIDI-only report labeled historical. State clearly which native +software outputs are implemented/verified and which live application checks were +not performed. Do not rewrite history as if the earlier interim was approved. diff --git a/prompts/step_11.md b/prompts/step_11.md new file mode 100644 index 0000000..3a8099c --- /dev/null +++ b/prompts/step_11.md @@ -0,0 +1,99 @@ +# Step 11: Fix LM Studio-visible results and actionable request recovery + +## Objective and verified reproduction + +Fix the actual client-facing root cause, not speculative key capitalization. +Read current server/schemas/errors/profile/service tests and current architecture. +Keep the strict Python/Mido/native implementation. No commits or delegation. + +Verified before editing: + +- `"E minor"` and `"E Minor"` both validate and normalize to E minor. +- `"Em"` currently fails the structured key regex. +- The active LM Studio chat's FIRST actual generate_music arguments had + parts=["lead"], formats=["sd3p","mid"], key="E minor", + profiles={"lead":"aggressive_rock"}, and unrequested CC91. +- Lead+sd3p produces INVALID_REQUEST with issues field="$request", + reason="value_error". The text content is only + "Correct the invalid request fields identified in details and retry." +- The stored LM Studio tool result given to the model contains ONLY that + generic text. Structured details are not visible in that client message. +- Profile text currently says only "6 profiles; inspect mapping_kind and + limitations", so that text-only client cannot see the real IDs either. +- Exact user description is also currently unsupported; that musical feature + is Step 12 after this fix is reviewed. Do not pretend argument changes alone + make it supported. + +Do not read/edit unrelated LM Studio chats/configuration. Do not upload local +conversation data. Do not modify the user's active chat or DAW. + +## Owned implementation + +- server.py: all client-visible result/error content and useful tool descriptions. +- schemas.py / errors.py: strict public validation context and field guidance, + canonical key shorthand if appropriate. +- Directly related unit/integration/stdio/schema/installed tests and docs. +- prompts/report_11.md. + +## Required behavior + +1. For every ProfileListResult, GenerationResult and GenerationError, include the + COMPLETE safe public JSON in TextContent as well as structuredContent. + JSON text must decode to the same public object; do not only print a vague + summary and expect every client to consume structuredContent. + This follows MCP structured-output backward-compatibility guidance. +2. Preserve isError, schemas, stdout framing, SDK lifecycle, and all native/MIDI + functionality. Text-only clients must see exact profile IDs, artifacts, + warnings and useful error details without private exception inputs. +3. Cross-field errors identify the actual field and correction, e.g. + formats: sd3p/sdp require drums; lead uses griff/agp or mid, bass briff/agp. + Use typed/custom error reasons or an equally safe precise approach. + Never expose raw Pydantic input/context/exception strings or unknown keys. +4. Include safe actionable expected grammar/bounds for key, meter, profile IDs, + parts/formats and CC shape/grid. Do not infer that the key is wrong for every + generic root error. Backend strict types, limits and privacy remain enforced. +5. Accept conventional structured key shorthand such as Em/F#m/Bb major and + canonicalize correctly without breaking existing major/minor full forms. + Make advertised schema/examples match actual accepted input. Preserve + malformed/unknown-mode rejection; do not weaken into arbitrary defaults. +6. Add concise input/tool descriptions explaining: + - omit formats for automatic correct per-part output; + - guitar lead -> griff, bass -> briff, drums -> sd3p, mid works for all; + - omit profiles for defaults, or use exact IDs from list_instrument_profiles; + - never invent profile IDs or add CC events without user intent; + - supported text vocabulary/known musical limits, and pass user intent + faithfully rather than embellishing unsupported instructions. +7. Do not strip JSON Schema constraints or change transport spec on an unproven + theory that llama.cpp cannot parse them. The verified bug is hidden text + feedback. Any schema simplification needs concrete engine evidence. +8. Known profile-selection/unsupported-description domain errors must also expose + an actionable public message/details in text. No success-shaped approximations. + +## Tests + +Unit: +- json.loads(TextContent.text) equals structuredContent for both tools, success + and validation/domain errors; exact IDs/corrections are visible through text. +- Reproduce lead+sd3p with valid E minor: error points to formats and lists valid + lead choices, not generic root value_error. +- Em, E minor, E Minor and other conventional aliases normalize identically; + invalid modes/values remain errors and privacy sentinels remain absent. +- Wrong/invented profile has an exact list-profiles/default recovery action. +- CC, meter, missing/unknown fields retain strict validation and useful context. + +Integration: +- Real stdio text-only consumer can list IDs, receive wrong-format correction, + repair the call and generate actual guitar native/MIDI without guessing. +- Real installed-wheel client sees equivalent complete text/structured payloads. +- Existing native/CC/atomic/schema/stdio/source-template regressions still pass. + +Run focused tests, full current suite, Ruff lint/format, strict mypy and pip check. +Fix actual regressions without weakening assertions. No model change, network +service, extra features, triplet composer implementation or later prompts here. + +When complete, write your end-of-step report to ./prompts/report_11.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 inside exactly one plain triple-backtick fence. Include actual +before/after text-only recovery evidence, exact tests/counts, privacy checks, +schema/key decisions and Step 12 readiness. Require LM Studio MCP restart/fresh +chat to refresh its cached tool schema; do not claim its live UI was restarted. diff --git a/prompts/step_12.md b/prompts/step_12.md new file mode 100644 index 0000000..c488feb --- /dev/null +++ b/prompts/step_12.md @@ -0,0 +1,151 @@ +# Step 12: Exact beat-scheduled chugs, triplets, pinch harmonic and cross-bar hold + +## Objective and reviewed prerequisite + +Step 11 is reviewed/accepted: complete JSON TextContent now reaches text-only +clients, errors identify formats/profile recovery, and structured Em works. +Read report_11.md and current description/composition/schema/profile/compiler/ +native writer APIs. Implement the user's actual musical request accurately, +not a generic loop or an error-message-only workaround. + +Original user description (from the shared LM Studio screenshot): + +Please produce a 4/4 riff in Em. With Chugging palm muting 8th notes from 1 to 3&; +and triplets on 4&A with the A as a pinch harmonic that carries over a whole note +in the 2nd measure. + +No commits, delegation, later prompts, audio analysis/hosting or DAW changes. +Do not read/edit the user’s LM Studio conversation/configuration. + +## Musical interpretation and exact acceptance + +Interpret 4 & A as the three eighth-note-triplet subdivisions of beat 4; +"A" refers to the final count, not an A-pitch instruction. The last note sustains +through ALL of measure 2 without retrigger. Return these assumptions explicitly. +Tempo was unspecified: retain the documented 120 BPM default and disclose it. +Use a documented low-tonic chug register (E2/MIDI40 for the default target) +unless an actual supported pitch instruction says otherwise; do not invent a +melody or silently transpose the PH to an unrelated key. + +At 960 PPQ, for the original request: + +- Six palm-muted eighth notes at 0,480,960,1440,1920,2400, duration 480. +- First two beat-4 PM triplets at 2880 and 3200, duration 320 each. +- Final triplet PH starts 3520 and ends 7680, one continuous note. +- Musical score duration: 2 bars / 8 quarter beats / 7680 MIDI ticks. +- Exactly 9 musical note-ons: 8 PM + 1 PH; no musical onset at bar-2 tick 3840. +- MIDI keyswitch PM=D0/26; PH=G0/31; current zero-lead policy and positive + switch gates remain explicit generator policy. +- Native Riffer PPQ480: musical starts + 0,240,480,720,960,1200,1440,1600,1760; PH end=3840; + PM and PH are the actual native note Articulation values. + +Do not truncate the hold, retrigger at the bar, quantize triplets to eighths, +or count keyswitches as musical notes. + +## Evidence-backed native PH mapping + +- Actual AME ProductVersion 4.0.1; target factory folder: + C:\Users\g3\Documents\Ample Sound\Riff4\Guitar4\AME Presets +- A read-only aggregate found 17 genuine native PH notes, label "PH", + observed velocities 80..100 and pitches 49..73. These observations establish + encoding, not hard limits of the articulation. Copy no factory sequence. +- Official Main_Panel_Manual-AME.pdf at https://www.amplesound.net/en/ + documents PH at G0 and range C1-C5; existing numeric octave interpretation + establishes C0=24, so G0=31. Verify these technical facts before declaring + support. No copyrighted manual/factory assets in source/tests or uploads. +- Extend only the evidenced guitar profile/native PH mapping. Do not invent + Ray/SD3 PH support or loosen all native mappings to arbitrary labels. + +## Owned implementation + +- schemas.py: the smallest reusable typed internal note/phrase timing plan needed + to represent mixed subdivisions and per-note articulation; reuse rational + beat models. Avoid a prompt-specific flag or untyped dicts. +- description.py: bounded natural-language beat-range/triplet/PH-hold parsing, + shorthand key recognition, and explicit assumptions/unsupported diagnostics. +- compose.py: generic application of the typed timing plan, low tonic selection, + per-note articulation/velocity and range/budget validation. +- profiles.py + the Eclipse profile JSON: strict evidenced PH support; update + native articulation types/guards and profile metadata/version facts coherently. +- errors.py/tool/schema descriptions and docs for the actual expanded grammar. +- Unit/integration/stdio/installed/native tests; generated original fixtures only. +- prompts/report_12.md. + +Do not add a new public score tool, model-provider API, unrelated file format or +generic plugin framework. The original description should work directly. + +## Parser and model requirements + +1. Implement reusable parsed rational timing, not an exact whole-string match + returning a canned riff. Parse numeric beat positions/ranges and generate + the corresponding subdivisions; test a nearby range variant too. +2. Support the original wording/spelling/spacing, eighth/8th, palm mute/ + palm-muted/palm muting, 4&A/4 & A, 2nd/second measure, and Em/full E minor. + Recognized beat-range from/to clauses must not trip the old blanket + changes/sequences guard. Unrelated tempo changes/unsupported instructions + still fail; do not globally remove that protection. +3. A first-measure phrase tied through measure 2 implies two bars when length + is absent. Validate explicit meter/length overrides against the actual plan. + Reject impossible overlaps, out-of-range beat labels and too-short scores + rather than silently dropping material. Preserve explicit/default semantics. +4. New precise grammar must remain bounded/documented. Do not advertise arbitrary + melodies, song sections or every free-form instruction as supported. + New model-generated embellishment outside that grammar must remain actionable, + not be ignored into an approximate success. +5. Existing simple patterns/defaults produce unchanged musical output. + Every newly parsed timing/technique instruction is represented in the plan + and survives composition/compilation; no profile-based accidental fallback. + +## Composer and native requirements + +1. Use exact Fraction/rational arithmetic; triplet duration 1/3 and tied final + duration 13/3 quarter notes remain exact through MIDI960/native480. +2. Respect selected profile ranges/tuning and per-note articulation. PH must + switch using the actual profile data and render native PH, not softer PM. +3. Extend strict Riffer guards only for the supported AME PH mapping, leaving + Ray/standard/SD3 unsupported-technique errors honest. +4. A continuous PH note crosses the bar boundary; no duplicate/split retrigger. + Existing pairing/string assignment/shared duration safeguards still apply. +5. Enforce the same event budget, finite values, stable ordering and file + transaction safety. Preserve explicit CC requests; do not invent CC91/effects. +6. Update supported-text/tool/profile descriptions and old tests which explicitly + classified THIS now-supported phrase/PH as unsupported. Preserve rejection + tests for genuinely unsupported modes/instructions/invalid maps. + +## Required unit tests + +- Parse exact user wording plus spacing/wording/key aliases and a changed + beat-range variant; plan math independently asserted. +- Parsed per-note articulation, inferred 2 bars/default tempo/register/count-A + assumptions, invalid overlaps/meter/too-short length, unsupported prose. +- Compose exact timing/range/pitch/intensity plan, one cross-bar PH, no second-bar + attack, deterministic seed, budget and invalid-profile rejection. +- Verified PH keyswitch/native label; no bass/drum PH promotion. +- Existing ordinary pattern/default byte/semantic regressions remain intact. + +## Required integration tests + +- Real source stdio AND noneditable installed wheel receive the original + description verbatim with only safe basename/optional fallback=false. +- Text-only consumer sees full corrected arguments/results; automatic formats + are mid+griff for lead, no bogus drum project/profile/CC. +- Independently parse actual MIDI: 9 musical notes, 8 PM/1 PH, selector26 then31, + exact note-on/off times above, common EOT7680, E-minor low tonic and legal + velocities; no CC91 or unspecified effects. +- Independently parse actual .griff: PPQ480, two measures, correct PM/PH, + exact Begin/End/fret/pitch/velocities and final End3840. +- Native validator/independent comparison must match the same requested score; + actual saved files, not just file existence or serializer self-equality. +- Preserve simple native/MIDI/CC/atomic/source-template/package regressions. + +Run focused tests, complete current suite, Ruff lint/format, strict mypy and pip. +Generate/retain only ORIGINAL acceptance evidence; no real user output creation +yet outside test artifacts (the orchestrator will make the final requested riff +after reviewing this report). No app/UI manipulation. + +When complete, write your end-of-step report to ./prompts/report_12.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 in exactly one plain triple-backtick fence. Include exact observed +MIDI/native timings/PH proof, unsupported limits, assumptions, before/after +grammar changes, exact test counts and next-step readiness. diff --git a/prompts/step_13.md b/prompts/step_13.md new file mode 100644 index 0000000..6660bc6 --- /dev/null +++ b/prompts/step_13.md @@ -0,0 +1,65 @@ +# Step 13: Final LM Studio recovery/precise-riff patch release acceptance + +## Objective and accepted prerequisites + +Steps 11 and 12 are accepted after full report/source review and independent +tests. Hidden TextContent feedback is fixed, Em is accepted, and the exact +original beat-range/triplet/PH-hold description produces correct real MIDI and +native guitar content. Finish final package/docs/regression acceptance. + +No commits, delegation, later prompts, user LM Studio data/config changes, DAW +changes, audio/host features or unrelated cleanup. + +## Owned work + +- Release version source/metadata/tests as directly necessary for patch 0.1.1. +- Directly related documentation/examples/acceptance tests and actual defects. +- `prompts/report_13.md`. + +Preserve previous reports as historical evidence; do not rewrite them as if +earlier versions supported this phrase. Do not overwrite user output files. + +## Required behavior and validation + +1. Set the single authoritative package version to 0.1.1 so a restarted MCP + reports the fixed build and distributed wheels cannot be mistaken for 0.1.0. + Update directly coupled packaging/test expectations and current docs. + Refresh only editable application metadata in the repository venv as needed; + no unnecessary dependency restores/global installs. +2. Confirm exact JSON TextContent/structuredContent parity, readable profile IDs, + correct lead/drum-format validation and Em/full-form normalization remain. +3. Confirm original text works VERBATIM, minimal arguments, no fabricated profile, + drum format or CC91. Independent musical acceptance remains: + 8 PM + 1 PH, MIDI onsets0,480,960,1440,1920,2400,2880,3200,3520, + PHend7680, no bar2 retrigger; native times half and PH end3840. +4. Build final 0.1.1 wheel/sdist under a clearly identified directory such as + dist/lmstudio-fix-20261020. Run the EXACT persisted wheel outside checkout, + real stdio initialization/tool discovery and text-only consumer recovery, + then original requested phrase generation and independent saved-file checks. +5. Run full current pytest, Ruff lint/format, strict mypy and pip check. + Preserve native/MIDI/CC/template/atomic/privacy regressions and ordinary + no-phrase musical-output hashes. Fix actual coupled failures, no weakened + checks, blanket skips or success-shaped unsupported approximations. +6. Update README with LM Studio mcpServers (not VS Code servers) configuration, + existing output-root requirement, exact current supported original example, + minimal tool arguments and restart/fresh-chat remediation for cached schemas. + Explain actual griff/briff/sd3p suffixes, defaults, precise grammar limits, + count-A interpretation, low-tonic/default-tempo assumptions and no unsolicited + profiles/effects. Validate executable JSON examples against actual schemas. +7. Do NOT manipulate/restart the live LM Studio application/MCP process or active + chat, and do not touch the user’s Cubase session. Report that UI action is + operator-required rather than claiming live UI/model success. +8. Tests may retain original acceptance files under ignored test artifacts. + Do NOT create the user-facing requested files under D:\MusicGenOutput here; + the orchestrator will issue the final request after reviewing this report. +9. Confirm source templates/local musical references remain unchanged and no + private chat/template/factory music/manual asset enters source/packages. + Clean only owned temporary build/test/process workspaces; retain clearly + named final original evidence, reports and distributions. + +When complete, write your end-of-step report to ./prompts/report_13.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 in exactly one plain triple-backtick fence. Include patch version, +exact final build paths/hashes, actual source/installed text-only recovery and +musical-event evidence, final test/check counts, startup restart instructions, +scope/interpretation limits and readiness for the final user-file generation. diff --git a/prompts/step_14.md b/prompts/step_14.md new file mode 100644 index 0000000..1b6fff8 --- /dev/null +++ b/prompts/step_14.md @@ -0,0 +1,100 @@ +# Step 14: Reusable explicit pitch, chord and timed-attack foundation + +## Objective and prerequisites + +Implement the agreed hybrid notation foundation, before parsing lane text. +Read current plan, reports11-13, schemas, composer, profiles, compiler and native +Riffer validation. Preserve all prior work (dirty worktree includes accepted +0.1.1 changes). No commits, delegation, later prompts or application changes. + +User wants prose for context plus precise Counts/Events/Chords/Notes lanes. +Explicit pitches/chords must never be changed to fit a key. C4=MIDI60. +Chord root octave is custom input syntax: Em4 means E4-G4-B4; Em4OverB2 or +Em4/B2 means B2 plus E4-G4-B4. Em4OverB defaults to the closest B BELOW the +upper chord's lowest pitch (B3); report that default. Slash bass must truly +be the lowest pitch; reject explicit contradictory bass octaves. + +## Owned surfaces + +- Small `pitch.py` (or equivalently named focused module) with typed note/chord + parsing, octave arithmetic and voicing; no new package dependency. +- Reusable strict internal explicit-attack plan in schemas.py, separate from + the legacy low-tonic monophonic PhrasePlan unless unification is demonstrably + simpler without changing existing semantics. +- compose.py for consuming that plan into actual polyphonic PitchedNotes. +- Related pitch/plan/composer/native tests and architecture docs. +- prompts/report_14.md. + +Do not implement full lane parser or public score tool yet. Public generate_music +description contract remains, shared internal intent may add an optional plan. + +## Required foundation + +1. Typed pitch token supports A-G, optional one #/b, optional signed octave with + C4=60. No-octave tokens remain unresolved until instrument/register policy, + not silently assumed from accidental math. Reject out-of-MIDI/unsupported + spellings; preserve enharmonic numerical values. +2. Chord symbols: bare root means major; m/min means minor; explicit octave + follows quality (Em4, F#3, Bb2). Add4 should use an explicit parenthesized + form such as Em(add4) or Em4(add4), not be confused with the octave digit. + No other ambiguous quality is silently accepted. Correct octave-qualified + Over/slash bass and explicit pitch-set voicing [C3 E3 G3] are supported. +3. Tokenization must be deterministic for concatenated roots F#F#, DD, BbBb + and note run CEG later used in compact lanes. Keep a clear distinction + between whitespace token boundaries and spacing width. Avoid whole-string + musical-example hacks. Unknown/ambiguous leftovers are errors. +4. Unspecified note/chord root octave: choose the low playable root nearest + MIDI40 under the selected part profile; report the decision. Do NOT transpose + explicit notes/chords; explicit C4/E4/G4 remain exactly 60/64/67. +5. Chord default voicing: close root-position major/minor/add4 (documented + intervals), explicit slash bass prepended as lowest, deduplicate identical + pitches. If full voicing cannot fit the map/tuning, error rather than drop, + revoice arbitrarily, spread octaves or emit an incomplete chord. +6. Score representation supports exact rational start/duration, one event's + simultaneous pitch-set, technique normal/palm_mute/pinch_harmonic, optional + intensity, rest/continuation semantics at a later parsing stage. + Validate pitch uniqueness, positive duration, bounded timeline/count, and + incompatible same-pitch overlaps. Compatible polyphonic chords remain valid. +7. Composition consumes the actual explicit plan into all simultaneous notes; + preserve seed/intensity behavior and enforce total event budget on EXPANDED + chord tones plus compiler controls, not one count per chord token. +8. Ordinary simple patterns and original 0.1.1 PM-triplet-PH phrase must remain + byte/semantically unchanged. Current source/native profiles/tunings unchanged + except necessary typed extensibility. No invented slide behavior. +9. Native Riffer output must contain the actual independent chord tones with + legal physical string assignment; MIDI fallback is allowed only through + existing policy for genuinely unrepresentable native voicings. No fake + success for an explicit out-of-map pitch. +10. New internal plan use does not imply arbitrary prose support yet. + +## Unit tests + +- C4=60, E4=64, G4=67; flats/sharps/octave bounds and malformed symbols. +- F#, D, Bb majors and Em4=[64,67,71]. +- Em4OverB and Em4/B -> [59,64,67,71]. +- Em4OverB2 and Em4/B2 -> [47,64,67,71]. +- Explicit [C3 E3 G3] -> [48,52,55]; no key-based correction. +- Em(add4) vs Em4 octave unambiguous, invalid/unsupported qualities. +- Compact pitch/chord runs and malformed ambiguous tails. +- Voicing/register/range/duplicate/overlap/budget validation. +- Internal simultaneous chord composition with exact starts/ends and valid + profile technique, no hidden transposition. + +## Integration tests + +- Compose a small original explicit chord+single-note plan, compile/write actual + MIDI and real .griff; independently parse saved pitches/times/articulation + and chord physical-string assignment. Include slash bass and non-key chord. +- Explicit impossible chord/pitch fails or uses existing known native fallback + truthfully, with no dropped tones or overwritten files. +- All prior ordinary phrase/native/CC/stdio/contracts regressions. + +Run focused new tests, relevant regressions, Ruff lint/format, strict mypy, +and full current suite if shared schema/composer changes (expected). +Do not refresh version/build release until final Step16. + +When complete, write your end-of-step report to ./prompts/report_14.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +One plain triple-backtick fence for the entire report. Include public internal +APIs, exact chord/pitch policies and actual native/MIDI musical checks/counts, +source preservation and Step15 readiness. Do not create the next prompt. diff --git a/prompts/step_15.md b/prompts/step_15.md new file mode 100644 index 0000000..d151551 --- /dev/null +++ b/prompts/step_15.md @@ -0,0 +1,176 @@ +# Step 15: Hybrid prose plus precise Counts/Events/Chords/Notes lanes + +## Objective and accepted prerequisite + +Step14 is reviewed and independently verified (158 new pitch/plan/native tests). +Read report14/current pitch.py/strict plans/composer, description/service/tool +feedback and native codecs. Implement the actual PUBLIC description path for +the agreed hybrid notation. No new public tool, new dependency, commit, +delegation, later prompts, model service, audio/host or user-app changes. + +Prose supplies context/defaults; notation fixes events where supplied. Explicit +pitches/timing/articulation/ties cannot be overwritten by improvisation. +Spacing width is NEVER timing. Contradictory prose is an actionable error, not +silent precedence. Unknown material is not ignored into an approximate success. + +## Owned surfaces + +- One focused `notation.py`/`hybrid.py` parser as appropriate, reused from + description.py and compose.py. Keep module/dependency direction acyclic. +- Minimal reusable unresolved/typed hybrid plan in schemas.py if needed. + Reuse Step14 pitch resolution and ExplicitAttackPlan, never duplicate voicing. +- service.py/result models only to expose accurate interpreted events/assumptions. +- errors.py/server.py/schema descriptions and current docs for actual support. +- Unit/integration/real stdio/installed-package hybrid tests, original fixtures. +- prompts/report_15.md. + +## Canonical public example that MUST work directly + +Lead guitar, 4/4, 120 BPM, 2 bars. +Bar 1: +Counts: 1 & 2 & 3 & [4 trip let] +Events: x x x x x x [x x ^] +Chords: F#2 F#2 D2 D2 Bb2 Bb2 - - - +Notes: - - - - - - C4 E4 G4 +Hold the final G4 through the end of bar 2 without retriggering. + +This is six PM chord attacks followed by PM C4, PM E4, PH G4 sustained across +the bar boundary. Exact native/MIDI pitches must be F#2 major42/46/49, +D2 major38/42/45, Bb2 major46/50/53, C4=60 E4=64 G4=67; explicit chords are +not retuned into a key. Exactly21 musical note-ons, not counting switches. +Onsets MIDI960: chord groups0,480,960,1440,1920,2400; C4=2880/E4=3200/ +G4=3520; first durations480/two triplets320; final G4 end7680. + +Also support original single-note two-measure request using lanes: +Lead guitar, E minor, 4/4, 120 BPM, 2 bars. +Bar 1: +Counts: 1& 2& 3& [4 trip let] +Events: xx xx xx xx^ +Notes: E2E2 E2E2 E2E2 E2E2E2 +Hold the final E2 through the end of bar 2 without retriggering. + +That MUST preserve the exact previous original phrase's nine musical events, +PM26/PH31 switches, durations, pitches and seed0 velocities/bytes where feasible. +Accept normal whitespace and tabs, not column-position heuristics. + +## Count/grid semantics + +1. Parse labeled Counts:/Events:/Chords:/Notes: rows case-insensitively, preserve + pitch-token capitalization semantics from pitch.py. Rows describe one + selected pitched part; lead/guitar or bass inferred from prose/part override. + No simultaneous drum-lane language is invented in this implementation. +2. Numeric labels identify counted meter-denominator beats (quarter in4/4). + Complete `1 &`/`1&` = two eighth positions. Complete `1 e & a` = four + sixteenth positions, uppercase E/A equivalent (not a different rhythm). + A bare single beat label = one beat. Explicit `[4 trip let]` is a3-way + eighth-triplet beat; bracket syntax declares the subdivision, not visual width. +3. Support an explicit Grid:/Subdivision: eighths/sixteenths/eighth-triplets + directive for disambiguation, with a clear tested count-label interpretation. + Bare `1&a` without explicit sixteenth/triplet grid is AMBIGUOUS and errors. + Never infer a triplet just from three attacks or lowercase letters. +4. Counts ordered within bar, range checked against meter, no duplicate/regressed + position. Use exact Fraction math and proper denominator units, reject + unsupported grids rather than floating rounding. At least different 3/4 + simple-meter case plus4/4; do not claim idiomatic compound grouping. +5. Multiple `Bar N:` blocks and/or matching `|` bar boundaries may be supported + if kept simple; at least a second explicit continuation bar must work. + Validate all labeled rows' flattened slots/bar spans agree. No silently + truncated/zip-shortened mismatched rows. +6. Brackets on Events/Notes may group matching triplet tokens; they are not + simultaneous chord syntax there. Chords: `[C3 E3 G3]` is one explicit + simultaneous voicing token. Document and test this distinction. Avoid nested + bracket heuristics silently swallowing a voiced chord as three attacks. + +## Event/pitch/hold semantics + +- `o` = normal/open attack (not open-string fingering). +- `x` = palm-muted attack. +- `^` = pinch-harmonic attack (evidenced AME only). +- `-` in Events = rest (ends active prior sound unless it ended already). +- `~` = extend PREVIOUS sounding attack/chord without retrigger; cannot follow + silence, conflict with new pitch/articulation or silently create a new note. +- `|` = bar boundary, when used consistently. +- `/` and `\` in Events are RESERVED slide directions. Without an implemented + evidence-backed origin/destination/timing representation, return a specific + unsupported-slide error with guidance; do NOT silently emit a normal attack + or confuse Chords:Em4/B2 with an Events:/ symbol. + +1. Each slot has one event symbol and exactly one sounding pitch source or none. + Chords/Notes rows are optional individually; absent row is all `-`. + Both sounding at one slot is a conflict, not an arbitrary merge. A pitch-lane + `-` means empty lane, not necessarily global rest. Active event with no + pitch may use the explicitly disclosed low-tonic context default; never invent + pitches when another precise pitch source exists. +2. Whitespace separates tokens but runs may be compact: Events:`xxxxxx^`; + Chords:`F#F# DD BbBb ---`; Notes:`-- -- -- C4E4G4`. + Use Step14 deterministic tokenizer to resolve atoms; values never depend on + how many spaces were used. Slash/Over bass, octave-qualified chords and + [explicit voicing] must remain one slot, not be split by naive whitespace. +3. Explicit notes/chords override key-based generation by design, not by silently + altering prose: a stated key is context; raw pitches stay exact. If prose + directly specifies a different pitch for the SAME event, flag the conflict. +4. Resolve octave defaults through Step14 profile/routing policy, propagating all + chosen roots/bass octaves and voicings as visible assumptions/interpretation. + `Em4OverB2`=[47,64,67,71], Em4/B=[59,64,67,71]; reject explicit bass not lowest. + No dropped chord tone, automatic key retune or hidden revoicing. +5. Hold directive supports natural `Hold/Tie the final [note|chord|G4|E2] + through/to the end of bar/measure 2 without retriggering.` An optional pitch + must match that final note. Extend to exact bar end, no second attack. + `Bar 2: hold previous note to bar end` should also work and not be consumed + by the unsupported global `to/from` rule. Restrict recognized clauses first. +6. A second `Counts` bar with all Events:`~` and empty pitch lanes must yield + one uninterrupted prior note/chord. Sustaining PH preserves its original + articulation. Explicit rests/new attacks cannot be overridden by a prose + hold. Reject a hold spanning specified conflicting notation. +7. Structured scalar overrides retain existing documented precedence ONLY when + compatible with explicit timing/pitches; a shorter bars override or incompatible + meter must error instead of dropping/regenerating exact material. + +## Prose/context and observed interpretation + +- Support documented common context around the rows (guitar/bass, key incl.Em, + numeric BPM/bars/meter, "two bars", low-register chord voicings, aggressive/ + tight metal style and bounded velocity variation). State actual policy: + exact notation cannot be altered by style; no unrequested CC/effects. +- Prose-only inputs continue on old paths byte-identically. Do not remove + old unsupported-tempo-change safeguards or accept arbitrary instructions. +- When prose specifies a global technique and lanes explicitly differ for the + same events, raise an actionable conflict. Do not mistake explicit intentional + phrase overrides (first PM then PH) for contradictory accidental global input. +- The tool should show its interpretation. Add a backward-compatible optional/ + default result interpretation surface if necessary: exact resolved pitch sets, + start/duration as rational beats, technique and holds. Include canonical + voicings/register assumptions in complete JSON text and structuredContent. + Do not dump private raw text or paths in errors. Existing simple callers + should not need to provide new required fields. +- Help text must clearly advertise tested lane syntax/count grid/pitch convention, + not overclaim arbitrary natural-language rhythm comprehension. + +## Required tests + +Unit: canonical/compact examples, width/case invariance, complete eighth/ +sixteenth/explicit triplet grids, ambiguous1&a rejection/explicit-grid recovery, +row slot mismatches, brackets/voicing/slash bass, rests/lane-empty vs rest, +continuation/hold no retrigger, contradictory pitch/articulation/prose, bad +bars/meters/labels/keys, per-part capability errors (PH on bass), slide reserved, +malformed/huge inputs/budget, raw explicit pitches preserved outside key. + +Integration: +- Real source stdio AND installed-wheel native/MIDI with text-only JSON parity. +- Independently assert21 tones for the exact chord example and9 for the original + E2 example, exact onsets/durations/PH and no bar2 retrigger, every chord tone, + legal native fingering and actual controller absence. +- Em4OverB2/Em4/B/explicit voicing survive the public description to real MIDI/ + griff without retune/drop, default bass/root assumptions visible. +- All-~ bar matches prose-tie bytes/semantics; dash/rest truly separates attacks. +- Genuine invalid/mismatched/ambiguous notation errors publish no artifacts. +- All current template/native/CC/atomic/privacy/old-phrase/pitch regressions. + +Run focused new tests, full current suite, Ruff lint/format, strict mypy and pip. +No version/release metadata changes yet (Step16 owns final0.2.0). + +When complete, write your end-of-step report to ./prompts/report_15.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 in exactly one plain triple-backtick fence. Include supported +grammar/policies/limits, actual native/MIDI event proof, compact and nearby +examples, exact counts/checks, result interpretation and Step16 readiness. diff --git a/prompts/step_15_fix.md b/prompts/step_15_fix.md new file mode 100644 index 0000000..bd93d38 --- /dev/null +++ b/prompts/step_15_fix.md @@ -0,0 +1,44 @@ +# Step 15 fix: Resolve impossible D2 fixture; complete hybrid implementation + +## Authoritative correction after report review + +The orchestrator read report_15.md in full and independently confirmed the +physical contradiction: MIDI38 and42 each require AME string6. The requirement +for simultaneous native D2-major [38,42,45] was an ERROR IN THE WORKER PROMPT, +not a reason to abandon hybrid notation or the user's actual E2 phrase. +No change to tuning, native validation or user-explicit pitch is authorized. + +Apply these surgical overrides to step_15.md: + +1. The CANONICAL NATIVE chord example uses D3, not D2: + Chords: F#2 F#2 D3 D3 Bb2 Bb2 - - - + Its two D-major pitch sets are [50,54,57]; other attacks/times unchanged. + All21 tones now have real physical string assignments. Require source AND + installed native/MIDI acceptance with fallback=false for THIS example. +2. Retain the old explicit D2 example as a NEGATIVE NATIVE / POSITIVE MIDI + exactness test: allowed fallback preserves every [38,42,45] pitch; disabled + fallback errors before publishing. Do not transpose, drop or call that native. +3. Original user's E2-only two-measure phrase remains required unchanged and + fully native-capable. The final prompt primarily uses this original phrase. +4. Restore/implement the complete Step15 hybrid parser and tests under this + correction. A single unplayable chord cannot block generic notation. Do not + remove working public parser code/tests merely because a negative native + test demonstrates expected fallback. + +All OTHER Step15 requirements remain: actual public prose+lanes, reusable +count math, o/x/^/-/~, explicit notes/octaves/major-minor/add4/slash bass/voicings, +visible interpretation, correct rests/holds, ambiguity/conflict errors, slides +reserved with guidance, no key retuning, no timing from spacing width and no +factory/user-app changes. Preserve old0.1.1 outputs and strict/privacy/atomic/CC +behaviors. No commits/delegation/later prompts/version changes here. + +Read report14/15/current foundation and execute step15 under the corrected +acceptance above. Rebuild no release until Step16. Run new focused tests, +full current suite, Ruff lint/format, strict mypy/pip and installed acceptance. + +When complete, write your end-of-step report to ./prompts/report_15_fix.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +One plain triple-backtick fence for the entire report. Preserve original +report15 as history, not a current unsupported-parser claim. Include actual +playable D3 chord/native tests, honest D2 fallback, original E2 exactness, grammar/ +interpretation and Step16 readiness. Do not create the next prompt. diff --git a/prompts/step_16.md b/prompts/step_16.md new file mode 100644 index 0000000..31e1870 --- /dev/null +++ b/prompts/step_16.md @@ -0,0 +1,99 @@ +# Step 16: Release0.2.0 hybrid notation; verify exact restart prompt + +## Objective and accepted prerequisites + +Read reports14/15/15_fix and current accepted hybrid source/tests/docs. Step14 +pitch/voicing and corrected Step15 public hybrid paths are accepted after +report/source review and independent158+124 focused tests. +The old report15 D2 fixture blocker is historical; do not call hybrid unsupported. +Final user request: implement the hybrid then tell them when to restart their +LM Studio MCP and provide an updated working prompt for the original2 bars. + +No commits, delegation, later prompts, user LM Studio chat/config/process/DAW +changes, new dependency or unrelated feature. + +## Release and owned work + +- Single source package version0.2.0, necessary package/tests/current doc updates. +- Directly necessary parser defects exposed by final example/acceptance, with + focused regressions. Do not weaken exactness/privacy/atomic tests. +- Real final wheel+sdist under dist/hybrid-0.2.0-20261020. +- Current README/architecture/compatibility with tested hybrid/chord/notation, + restart/fresh-chat and a copy-ready ORIGINAL two-measure prompt. +- prompts/report_16.md. + +Do not overwrite historical reports or artifacts. Refresh only local editable +application metadata offline/no-deps/no-build-isolation if necessary for version; +no runtime/development dependency restore/global install. + +## Exact final description (must work directly) + +Lead guitar in E minor, 4/4, 120 BPM, 2 bars. +Bar 1: +Counts: 1 & 2 & 3 & [4 trip let] +Events: x x x x x x [x x ^] +Notes: E2 E2 E2 E2 E2 E2 E2 E2 E2 +Hold the final E2 through the end of bar 2 without retriggering. + +This is the original E2 single-note phrase, not the later chord variant. +The final response will tell LM Studio's model to call generate_music with this +description verbatim, new basename and no fabricated formats/profiles/CC. + +Actual expectations (seed0): +-8 palm-muted E2 notes then1PH E2; no bar2 retrigger. +-MIDI960 onsets0,480,960,1440,1920,2400,2880,3200,3520; lastoff7680. +-Native480 half-times,8PM+1PH,Measures2/KeyEm/PPQ480/end3840/string6fret4. +-PM26 selector0..30;PH31 selector3520..3550; no CC/programs/effects. +-Original0.1.1 musical byte hashes remain unchanged: + MIDI c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62 + griff e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c +-Result interpretation lists all9 exact attacks/pitches/techniques and final hold. + +## Required acceptance + +1. Full pytest, Ruff lint/format, strict mypy and pip check. +2. Build final current0.2.0 wheel/sdist FROM final source; run the EXACT persisted + wheel noneditably outside checkout with real stdio and verify loaded package + modules/profile resources truly originate there and report0.2.0. +3. Validate original final prompt minimal arguments through SOURCE and exact + wheel, complete JSON TextContent=structuredContent, actual native/MIDI bytes, + independent Mido/XML reader expectations above. Compact variant and explicit + all-tilde second bar must preserve music, not rerender to approximate pattern. +4. Validate corrected playable chord example: + Chords:F#2 F#2 D3 D3 Bb2 Bb2 - - - + Notes:- - - - - - C4 E4 G4; sameEvents/Counts, finalG4 hold. + 21 exact musical tones; real native and MIDI. Explicit D2 variant must keep + exact MIDI with allowed fallback, never hiddenD3 revoice/native success. +5. Public exact Em4OverB2,Em4/B,explicit[C3 E3 G3] tests; case/width/compact/ + grid ambiguity, duplicate mismatched lanes, rest/continuation/prose conflict, + reserved slide error. Old simple/native/CC/SD3/template/atomic suites intact. +6. Publish ONE original requested E2 riff through a NEW real0.2.0 MCP process + under existing operator root D:\MusicGenOutput with unique descriptive + basename (include hybrid/date to avoid collisions). No unnecessary SD3 + template for lead-only. Use fallback=false to require actual native guitar. + Independently reopen/user output and record exact paths/sizes/hashes/ + interpretation. Do NOT overwrite prior user files or create sidecars. +7. Recheck final wheel/profile/doc/source identity and no private chat/template/ + factory music/manual binary in packages. Clean owned temp processes/stages. +8. Documentation must distinguish implemented o/x/^/-/~ from reserved slides. + Do NOT claim / or backslash slides generated. They return actionable errors + until evidenced target/origin/timing codec support exists. +9. Explain C4=60, chord digit=root octave, slash/Over bass policy, no key retune, + raw explicit pitches may be unplayable physically (truthful native fallback). + Do not conflate compound grouping or countA with pitchA. Prose remains + bounded/local deterministic, not arbitrary language-model understanding. +10. No live LM Studio restart/manipulation. Tell user to restart MCP NOW AFTER + this verified update, then start a fresh chat to refresh schemas/cached tool + descriptions. Their existing configured venv path now resolves0.2.0, no + config edit/reinstall required. Never claim actual live model success. + +Tests use original portable/native references read-only, no private template +shipped. Genuine SD3 optional tests can be opt-in if untouched, not required +for this lead-only notation feature. Disclose app/playback certification unrun. + +When complete, write your end-of-step report to ./prompts/report_16.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +One plain triple-backtick fence for entire report. Include exact final build +paths/hash/version, final copied working prompt, actual SOURCE/installed/user +MIDI+griff/interpretation evidence, test counts, preservation/limits and precise +restart/fresh-chat instruction. Stop after verified/report; no next prompt. diff --git a/prompts/step_2.md b/prompts/step_2.md new file mode 100644 index 0000000..2ccb42c --- /dev/null +++ b/prompts/step_2.md @@ -0,0 +1,123 @@ +# Step 2: Typed domain models and MCP tool contracts + +## Objective and prerequisites + +Step 1 has been reviewed and accepted: its persistent report was read and all +six foundation/distribution tests independently passed. Implement Step 2 of the +approved plan, not server behavior, generation, mapping data, or native writers. + +Read `prompts/plan.md`, `prompts/report_1.md`, and the current package/tooling. +Keep the reviewed public MCP contract consistent with Section 7 of the plan. +Do not delegate, commit, generate later prompts, or fabricate compatibility data. + +## Owned files + +- Create `src/riff_groove_builder/schemas.py`. +- Create `src/riff_groove_builder/errors.py`. +- Create `tests/unit/test_schemas.py` and `tests/unit/test_errors.py`. +- Create `tests/integration/test_contracts.py`. +- Update `docs/architecture.md` with the implemented contracts. +- Update `README.md` only where needed for accurate validation instructions. +- Update `pyproject.toml` only if a directly used test/type dependency is needed; + install only after its manifest change. +- Write `prompts/report_2.md`. + +Keep existing foundation tests intact. Explain any additional directly necessary +file. Do not change Step 1's report or the approved plan. + +## Implementation details + +1. Use Pydantic v2 typed models and a small explicit domain-error hierarchy. + Reject unknown fields and invalid input with actionable messages. +2. Implement request and response models for exactly `list_instrument_profiles` + and `generate_music` as specified by the approved plan, including the explicit + success/error output-schema branches. Empty list-profile input accepts only + an empty object. Expose reusable JSON Schema helpers/constants as appropriate; + Step 3 must not duplicate the contract. +3. Preserve absent override fields as absent/None. Text inference, default + musical intent resolution, and choosing a production profile are later work. + Enforce cross-field constraints when sufficient fields are explicitly known, + and clearly define which checks require resolved intent later. +4. Strictly validate numeric inputs: reject booleans as integers/numbers, + non-finite values, out-of-range values, duplicate enum-list members, empty + arrays, unsupported fields, and invalid part/format/profile combinations. + Accept valid integer or fractional BPM values within the proposed limits. +5. Validate safe basenames, including Windows reserved device names, path + separators/traversal, trailing dots/spaces, length, and the approved ASCII + grammar. Filesystem root/link resolution is future service work. +6. Parse/normalize the documented key grammar for pitch classes (including + conventional sharps/flats) plus major/minor. Reject unsupported modes, + malformed accidentals, or contradictory key strings; test normalization. +7. Define the internal intent, score, logical-note, instrument-profile summary, + and scheduled-event structures needed by the plan. Avoid speculative native + fields. Define exact rational beat positions/durations using Fraction or an + equally explicit rational representation; do not accumulate float timing. +8. Document the representation and units. MIDI channel numbers are 0-15; notes + and CC payloads are 0-127; musical note-on velocity is 1-127; event ticks are + nonnegative integers. Separate keyswitch events from musical-note roles. + Intensity, if normalized to 0-1, is finite and validated rather than clamped. +9. Keep event payloads type-safe: prefer small discriminated event models or + explicit valid combinations over a bag of optional/Any fields. Model stable + event ordering metadata without implementing the scheduler in this step. +10. Make shared timeline/part invariants enforceable: nonempty selected parts, + valid meter, unique part tracks, positive duration, valid note/event ranges. + Distinguish logical musical range checks from future verified profile checks. +11. Define GenerationResult and GenerationError types matching the plan. Validate + feasible result invariants (status/warnings, artifact parts/formats, positive + sizes, and end >= start) without inventing fake files or inspecting disk. + Runtime existence, publication, and full output coverage belong to Step 9. +12. Provide specific named domain exceptions/codes, including invalid requests, + unsupported descriptions/articulations, missing profiles, unavailable native + formats, output collision/IO, and serialization errors. Keep public messages + actionable without exposing stack traces/private file content. +13. Keep package imports side-effect-free and dependency direction simple. + No placeholders pretending to generate files, real production profiles, + parser/composer, filesystem publication, or proprietary codecs. + +## Required unit tests + +- Every generate_music parameter at valid and invalid boundaries. +- Strict numeric types, NaN/infinity, duplicate/empty lists, invalid enums, + unknown fields, bad profile-part associations, incompatible explicit formats. +- Optional parts/formats/overrides remain unresolved when omitted. +- Safe basenames including case-insensitive Windows reserved names and traversal. +- Keys, meter, seed, exact rational timing, duration/intensity, event payloads, + note/channel/controller ranges, and malformed combinations. +- Empty list-profile input/output and valid/unavailable profile summaries. +- Valid success/fallback/error results and invalid claimed result combinations. +- Domain error codes and stable, useful public details. + +## Required integration tests + +- Representative requests for each part and combined parts validate and + JSON-round-trip without losing optional-field semantics. +- Published input/output schemas are valid JSON Schemas and agree with the + typed models for representative accepted/rejected payloads. +- Valid success and error branches round-trip through their published schema. +- Logical score/event structures preserve rational timing exactly in documented + serialization, without depending on a production instrument map. +- The existing foundation/distribution tests still pass. + +If importing jsonschema directly in tests, declare it directly as a development +dependency rather than depending implicitly on the MCP SDK's transitive package. +Use repository-standard typing without broad ignores or Any casts. + +## Verification and acceptance + +Run focused new tests, existing relevant tests, Ruff lint/format checks, and +strict mypy. Do not claim an unavailable editor test runner passed; use the +known working `.venv\Scripts\python.exe -m pytest` fallback when necessary. +Run the distribution test if package/dependency configuration changes. + +Acceptance requires one authoritative, strict, serializable contract ready for +the Step 3 server and Step 4 MIDI writer. No real mapping/native evidence is +required for purely synthetic model tests, and none may be invented. + +## Required 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 + +The report must be entirely inside exactly one plain triple-backtick fence. +Include changed files, model/schema design decisions, exact validation commands +and pass/fail/skip counts, unresolved limits, and whether Step 3 is ready. +Do not claim any server, generated music, or target application compatibility. diff --git a/prompts/step_3.md b/prompts/step_3.md new file mode 100644 index 0000000..9985a48 --- /dev/null +++ b/prompts/step_3.md @@ -0,0 +1,124 @@ +# Step 3: MCP stdio server skeleton + +## Objective and accepted prerequisites + +Implement only Step 3 of `prompts/plan.md`. Steps 1 and 2 are accepted after +report/implementation review and independent tests (6 foundation tests and 321 +focused contract tests). Use the existing typed contracts; do not redefine them. + +Read the plan, reports 1-2, current `schemas.py`, `errors.py`, and package tooling. +Inspect the installed MCP 1.x SDK APIs before choosing the simplest integration. +Do not delegate, commit, create later prompts, implement generation/native +writers, or claim production mapping compatibility. + +## Owned files + +- Create `src/riff_groove_builder/server.py`. +- Create `src/riff_groove_builder/__main__.py`. +- Create `tests/unit/test_server.py`. +- Create `tests/integration/test_stdio.py`. +- Update `README.md` and `docs/architecture.md` for implemented startup/protocol. +- Change `pyproject.toml` only if a console entry point or directly necessary + typing/test configuration is needed. `python -m riff_groove_builder` is required; + an additional executable/transport is not required. +- Write `prompts/report_3.md`. + +Preserve existing models/tests. Explain any tightly coupled change rather than +silently changing the reviewed tool contract. + +## Implementation constraints + +1. Use the official SDK's stdio transport, Server lifecycle, JSON-RPC parsing, + request IDs, notifications, initialization, negotiation, and EOF shutdown. + Do not hand-roll framing, Content-Length headers, or protocol dispatch. +2. Register exactly `list_instrument_profiles` and `generate_music`. Reuse + `tool_input_schema` and `tool_output_schema` without wrapping or weakening + them. Revalidate incoming arguments through their authoritative models, + including strict types and cross-field rules. +3. Choose the SDK interface that correctly preserves the existing explicit + input/output schemas and structured success/error union. The low-level + official SDK Server is acceptable if its tool decorators are clearer than + FastMCP's inferred schemas. Do not build a second abstraction/framework. +4. Successful calls include `structuredContent` plus a concise text summary. + Known domain failures return `isError: true` and the declared typed error. + Protocol errors, unknown methods/tools, malformed JSON, invalid parameters, + and notifications retain correct SDK behavior. +5. `list_instrument_profiles` currently returns the truthful empty registry: + `{"profiles":[]}`. No guessed entries or synthetic production profiles. +6. Valid `generate_music` requests currently return an explicit development-only + typed error stating that generation is not implemented in this skeleton. + Use an existing error-schema branch with a clear message/reason rather than + pretending a file exists or blaming an unverified native format. + This handler is replaced in Step 9. It must never create artifacts. +7. Validate known model failures into public-safe field/reason details. + Do not echo raw descriptions, arbitrary user values, private fixture paths, + tracebacks, or exception representations into protocol results/logs. + Unexpected operational failures must be visible through standard diagnostics; + do not add broad silent catches or success-shaped fallbacks. +8. Startup: `python -m riff_groove_builder --output-dir `. + Require this option. Reject nonexistent/non-directory roots and clearly + unsafe/non-local forms with stderr diagnostics and nonzero exit. + Resolve/store the root for later service wiring. Do not create files, + auto-create arbitrary roots, or claim writeability before an actual write. + Full publication/link-confinement checks remain Step 9. +9. Keep stdout strictly UTF-8 newline-delimited protocol messages. Startup + messages, logs, and errors go to stderr. Importing either the package or + server module must not start services or print. +10. Keep implementation/test seams small and concrete. An internal create-server + helper is fine; no generic handler registry, HTTP server, plugin framework, + persistent jobs, or external model calls. +11. Document that tool discovery works but generation intentionally remains + unfinished. Include an accurate Windows MCP-client stdio configuration and + existing-root setup example without claiming a client was manually tested. + +## Required unit tests + +- Both tool definitions exactly reuse the reviewed schemas. +- Input model validation rejects malformed/unknown/strict-type failures. +- Empty profile list has valid structured output and no false capabilities. +- Generation returns the explicit unfinished error and publishes no files. +- Error conversion preserves public code/message while excluding private data. +- Output-root validation and required CLI argument failures. +- Importing server/package is silent and does not run the CLI. + +## Required integration tests + +Use a real module subprocess, with bounded timeouts and guaranteed process +cleanup. Prefer the official client for the normal handshake, and a small raw +stdio harness only where needed to exercise malformed requests. The harness is +a test client, not production protocol code. + +- Initialize, send initialized notification, list tools/schemas, call each tool. +- Verify response-ID preservation and no response to notifications. +- Verify valid structured outputs against the published schemas. +- Exercise invalid tool arguments, unknown tools/methods, malformed JSON, and + SDK-supported malformed-request behavior without assuming every error code is + a parse error. Follow the selected SDK's actual protocol semantics. +- Confirm stdout has only valid JSON-RPC lines; diagnostics remain on stderr. +- Close stdin and verify clean EOF shutdown; no invented shutdown method. +- Missing/bad output root exits nonzero without protocol-noisy stdout. +- Run the module from a different working directory using the installed editable + package, proving no current-directory import assumptions. +- Verify every valid generation call remains explicitly unfinished and creates + no artifacts. + +Do not leave child processes running. Do not kill processes by name. + +## Verification and acceptance + +Run the focused new tests, relevant existing contract/import checks, Ruff +lint/format, strict mypy, and distribution tests if package configuration changes. +The editor test runner is known not to discover this project; the verified +`.venv\Scripts\python.exe -m pytest` CLI fallback is acceptable. + +Acceptance: genuine SDK-backed MCP stdio lifecycle and honest tool skeleton, +correct schemas/errors, clean shutdown, protocol-clean stdout, passing checks. +No MIDI/native generation or application acceptance is claimed. + +## Required 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 + +Place the complete report inside exactly one plain triple-backtick fence. +Include exact commands/results, SDK interface choice and observed protocol +behavior, child cleanup, skips/limitations, and Step 4 readiness. diff --git a/prompts/step_4.md b/prompts/step_4.md new file mode 100644 index 0000000..d256cf9 --- /dev/null +++ b/prompts/step_4.md @@ -0,0 +1,137 @@ +# Step 4: Deterministic MIDI timing, scheduling, and file writer + +## Objective and prerequisites + +Implement only Step 4 of the approved plan. Steps 1-3 are accepted after +persistent report review, source inspection, and independent test runs. + +Read the approved plan, reports 1-3, current schemas/errors, and installed Mido +and MIDIUtil APIs. Implement real Standard MIDI serialization from explicit +controlled EventPlan structures. Do not implement text parsing/composition, +production instrument maps, native writers, service wiring, or later prompts. +Do not delegate or commit. + +## Owned files + +- Create `src/riff_groove_builder/midi.py`. +- Create `tests/unit/test_midi.py`. +- Create `tests/integration/test_midi_files.py`. +- Update `docs/architecture.md` and `README.md` with implemented timing/writer + behavior and focused verification commands. +- Refine `schemas.py` and its directly relevant tests only if a concrete + representation issue prevents a correct writer; preserve the MCP contract + and explain any tightly coupled change. +- Write `prompts/report_4.md`. + +Generate small controlled test MIDI files in temporary workspaces. Do not add +licensed fixtures or check in build/test output. + +## Implementation details + +1. Mido is the only production SMF writer. Use integer absolute event ticks and + the authoritative EventPlan model, then convert to integer nonnegative delta + ticks exactly once after stable sorting. +2. Provide small reusable helpers for exact rational beats-to-ticks and + bar-duration math where needed. Default PPQ is 960. Reject off-grid fractions + rather than accumulating float error or silently rounding. +3. Validate MIDI-specific encodability: legal positive non-SMPTE PPQ, finite + representable tempo, valid event/tick/delta ranges, supported event payloads, + the event budget, and shared timeline. Do not let a low-level struct error + masquerade as success or produce corrupt output. +4. Write synchronous SMF type 1 with one conductor track followed by selected + part tracks in resolved order. Add meaningful track names, conductor tempo + and time signature at tick zero, and exactly one end-of-track per track at + the shared event-plan end. +5. Tempo is quarter-note BPM, independent of the meter denominator. Compare + serialized integer microseconds-per-quarter against the correctly rounded + target, including fractional BPM tests. +6. Preserve note, keyswitch, and CC events in the part track. Do not invent + programs, GM drum mappings, real vendor switches, or keyswitch lead times. + Step 5 supplies profile-specific compiled controls. +7. Respect EventPlan ordering_key (tick, priority, sequence). It is the + compiler's explicit causal ordering; do not sort solely by note number or + blindly rewrite valid control priorities. At boundaries, verify off/on + retrigger ordering actually gives an unambiguous event sequence. +8. Validate note pairing by channel/note and distinguish musical and keyswitch + roles for diagnostics. Reject orphan releases and dangling notes. + Define/test an explicit safe rule for overlapping same-channel/same-pitch + note-ons, including collisions between switch and musical notes; do not + accidentally release a different active voice or claim ambiguous semantics. +9. Require part/channel isolation according to the plan without assuming a + default drum channel or hard-coding a real plugin mapping. Distinct parts + may not share a stateful MIDI channel. Do not reject polyphonic different + pitches merely because they share their own part's channel. +10. Preserve the common pre-roll, musical span, and shared control-release tail. + No negative events, part-specific shifts, or musical note-ons at/after the + musical end. Native alignment remains a later adapter requirement. +11. Serialize and validate in memory where useful, then write to the requested + file and read the saved file back with Mido. Validate the actual saved + header/type/PPQ, conductor data, track names/order, event sequence, + channels/payloads, pairing, and shared end. Round-trip validation must compare + against expected content, not merely prove that Mido can open a file. +12. Expose a small typed writer/validator API ready for the future service. + The writer acts only on its supplied file path; output-root confinement, + directory publication, requested-format policy, and MCP calls remain Step 9. + Do not overwrite an existing file silently. Handle path/IO and serialization + failures explicitly with the repository's named errors and safe reason + details. Clean up only a newly created file owned by this request on failure. +13. Use narrow exception handling for actual expected library/IO failures, not + broad silent catches, invalid-input defaults, or MIDI-shaped fallback on + corruption. Preserve a useful explicit failure for callers. +14. Do not call this a functioning text-to-music server or instrument-compatible + file generator yet. The stdio tool remains the reviewed unfinished handler. + +## Required unit tests + +- Exact beat/bar tick math for 4/4, 3/4, 6/8, and an odd meter. +- Straight and triplet subdivisions, invalid fractions, illegal PPQ/delta ranges, + strict values, nonzero score starts, and event-budget boundaries as applicable. +- Stable ordering with unsorted input, equal-tick controls, off/on retriggers, + and deliberate priority/sequence ordering. +- Musical/keyswitch note pairing, dangling/orphan events, same-pitch overlap + policy, and role collisions. +- Valid polyphony within a part and invalid channel sharing between parts. +- Conductor tempo/meter and fractional BPM, part names/order, shared EOT. +- Common pre-roll, exact musical duration, release tails, and empty part tracks. +- No silent overwrite; IO/serialization/read-back mismatch failures surface + explicitly and leave no newly published corrupt file. + +## Required integration tests + +- Construct a synthetic three-part Score/EventPlan with musical notes, + keyswitches, CCs, pre-roll, and a release tail; write to disk and read back, + asserting exact absolute events, durations, channels, and metadata. +- Build an independent MIDIUtil reference for controlled equivalent music and + compare normalized musical/control events against production output using + Mido. Account explicitly for library-specific conductor layout and harmless + end-of-track conventions; do not compare entire byte streams. +- Write/reload cases in more than one meter and fractional tempo. +- Detect a deliberately corrupt/truncated file and a structurally readable file + whose content differs from the expected EventPlan. +- Verify deterministic bytes or documented deterministic semantic output for + repeated identical input. +- Existing schema/import/protocol tests remain passing. + +All mappings used here must be clearly synthetic and test-local. No application +compatibility is established by these tests. + +## Validation and acceptance + +Run focused new MIDI tests, directly affected contract regressions, Ruff +lint/format, strict mypy, and relevant existing smoke/protocol tests. The +verified `.venv\Scripts\python.exe -m pytest` CLI fallback is acceptable. +Escalate to the complete current suite if changes touch shared schemas. + +Acceptance: valid deterministic type 1 MIDI from explicit event plans, exact +timing and ordering, independent reference/read-back evidence, honest failures, +and no regressions. Production mapping/native gates remain open. + +## Required 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 inside exactly one plain triple-backtick fence. +Include owned files/API decisions, exact commands/pass-fail-skip results, +MIDIUtil comparison evidence, overlap/channel policies, temporary-file cleanup, +and unresolved mapping/native evidence. State whether Step 5 can start and +whether its real production-mapping acceptance gate is currently satisfiable. diff --git a/prompts/step_5.md b/prompts/step_5.md new file mode 100644 index 0000000..76db40b --- /dev/null +++ b/prompts/step_5.md @@ -0,0 +1,166 @@ +# Step 5: Versioned profiles and articulation compiler + +## Objective and accepted prerequisites + +Implement Step 5 of the approved plan using the reviewed contracts and MIDI +writer. Steps 1-4 are accepted; the orchestrator independently reran 135 MIDI +tests and reviewed the complete Step 4 report and writer. + +Important: Step 4 explicitly reports that production mapping evidence is not +currently available. Implement and verify the reusable profile/compiler +mechanics, attempt a bounded check of lawful public official evidence, and +report the production acceptance gate as BLOCKED if it remains unresolved. +Do not fill the gap with invented values or mark the whole step ready. + +Read the plan, reports 1-4, schemas/errors, and MIDI API. Do not delegate, +commit, generate later prompts, implement text composition/native codecs, or +replace the Step 3 unfinished generation handler. + +## Owned files + +- Create `src/riff_groove_builder/profiles.py`. +- Create `src/riff_groove_builder/articulations.py`. +- Create `tests/unit/test_profiles.py`. +- Create `tests/unit/test_articulations.py`. +- Create `tests/integration/test_articulation_midi.py`. +- Create clearly synthetic JSON fixtures under `tests/fixtures/profiles/`. +- Create `docs/articulation-profiles.md`. +- Update `docs/architecture.md` and `docs/compatibility.md` for actual outcomes. +- Update `README.md` only for accurate current capability/validation status. +- Create minimal resource-package initializers under + `src/riff_groove_builder/data/` and `data/profiles/` only if needed to make an + explicitly empty packaged registry reliable in wheels. +- Create real production profile JSON only if supported by sufficient evidence. +- Write `prompts/report_5.md`. + +Explain any tightly coupled schema/error/MIDI changes and add regressions. +Preserve the reviewed public tool contract and prior reports. + +## Evidence and production-registry requirements + +1. Check existing evidence and publicly accessible official sources before + assuming anything about Eclips, Ray, or SD3. Limit research to a focused + attempt; do not spend the whole session guessing URLs. Record exact sources + and findings, including failed/blocked documentation access. +2. Exact product/build, mapping/preset version, playable range, channels, drum + voices, keyswitch MIDI numbers, latch/momentary semantics, CC/reset actions, + timing, and velocity layers need evidence. Octave labels alone are not enough. +3. Use no credentials, bypass, user-file upload, licensed manual copying, + guessed MIDI numbers, assumed GM-as-SD3 map, or synthetic production evidence. +4. Provenance must distinguish test-only data from verified mappings. Synthetic + fixture values prove compiler mechanics only. The packaged production + registry must never advertise or load test-only profiles as real targets. +5. If no real maps can be verified, ship an explicitly empty production registry + and document the blocker. Do not claim that the production part of Step 5 + passed. Missing profiles must remain actionable typed failures. +6. Native `.agp`/`.sdp` availability is independent: real MIDI mapping evidence + cannot set native_available=true without the separate native evidence gate. + +## Implementation details + +1. Define strict, versioned declarative profile models, reusing shared MIDI + ranges/parts/timing types. Keep them in profiles.py unless shared schema + extraction is genuinely needed. Do not add a generic plugin framework. +2. Profiles describe target identity, part/channel, playable range or logical + drum voice map, canonical articulations/aliases, velocity behavior, switch + and CC actions, latch/momentary state/reset semantics, and provenance. +3. Support keyswitch notes, velocity-layer selection, and CC actions individually + and in combination, using a small explicit action model rather than arbitrary + code or an untyped settings bag. +4. Define timing units explicitly and convert with the reviewed exact tick + helpers. Any profile lead time, switch gate, or release/reset offset must be + representable at the selected PPQ; reject off-grid values. +5. Validate layer boundaries/ranges and intensity behavior; do not silently + clamp, resolve overlapping layers arbitrarily, invent defaults, or accept + aliases that collide after normalization. Test endpoints. +6. Load packaged JSON through importlib.resources so an installed wheel works + outside the repository. An intentionally empty registry is valid; malformed + JSON, inconsistent metadata, duplicate IDs/defaults, invalid maps, missing + declared resources, and synthetic-production leakage must fail explicitly. + Distinguish an empty registry from failed resource loading. +7. Provide deterministic profile selection: explicit IDs must match the part; + missing/ambiguous verified defaults return named errors with safe actionable + details. Public summaries reuse the reviewed ProfileSummary contract. +8. Compile a Score and explicit selected profiles into an EventPlan. The + compiler accepts synthetic profiles in explicit tests, but production + discovery/selection must exclude them. Resolve pitches/drum voices and + articulation aliases against the selected map, never a global guess. +9. State is isolated per part/channel. Deduplicate latched selection actions + while preserving required per-note momentary actions, switch releases, and + CC resets. Restore a normal technique using its actual declared actions, + not an assumed universal reset. +10. Account correctly for polyphony: same-articulation overlaps must not release + controls still required by active notes. Incompatible overlapping state + requirements must fail explicitly unless the profile has a supported + mechanism. Reject unrepresentable overlapping physical switch triggers + rather than merging away required retriggers or producing invalid notes. +11. Compute one common nonnegative pre-roll from control lead requirements and + shift every part equally. Score.start is a logical origin, not additional + pre-roll. Include all required release/reset tails in the shared end_tick. +12. Order same-tick releases, state changes, switches/CC, and musical onsets + causally using EventPlan priority/sequence. Boundary retriggers must work + with the reviewed writer's strict note-pair/overlap/channel checks. +13. Every musical/switch note gets a matching positive-duration release. + Reject out-of-range notes, unsupported voices/techniques, colliding switch + and musical pitches, shared channels across parts, and ambiguous state. +14. Enforce the 100,000-event budget and call the reviewed event-plan validator + before returning. Surface named errors with public-safe fixed reasons. + No silent dropped articulations, defaults for invalid profiles, or broad + success-shaped fallback. +15. Keep service wiring and tool registry behavior unchanged for now. + +## Required unit tests + +- JSON loading, version/identity/provenance, wrong/missing/duplicate resources, + corrupt profiles, explicit empty registry, wheel-safe access. +- Test-only exclusion; no real target claimed from synthetic fixture values. +- Correct part/default/explicit profile selection and actionable missing/ambiguous + profile failures. +- Channels, playable ranges/drum voices, alias normalization/collisions, + keyswitch/CC data, timing rules, layer gaps/overlaps/boundaries. +- Keyswtich-only, CC-only, velocity-only and combined techniques. +- Latched transitions/deduplication, momentary releases/resets, normal-technique + restoration, same-articulation overlaps, incompatible overlaps, and retriggers. +- Positive switch gates, no dangling/orphan notes, musical/switch collisions, + part/channel isolation, nonzero logical origin, exact pre-roll/tails. +- Off-grid timings, invalid/unsupported score content, deterministic output, + and event-budget rejection. + +## Required integration tests + +- Synthetic palm-muted lead, bass techniques, and articulated drums compile to + exact independently expected events, then write/read back through Mido. +- Assert exact keyswitch numbers, velocities/layers, CC values/timing/reset, + common pre-roll, channel isolation, note pairing, and shared end. +- Use a synthetic three-part score with overlapping compatible notes and + boundary transitions; verify the compiler and MIDI writer agree. +- Exercise packaged profile discovery in a built wheel outside the repository, + proving an intentionally empty registry remains honest and resource loading + is not current-directory dependent. +- Run all relevant existing contract/MIDI/server/distribution regressions. + +These tests prove mechanics, not vendor compatibility. If real maps are verified, +add separate evidence-based target cases and clearly distinguish their source. + +## Verification and acceptance + +Run focused new tests, directly affected regressions, Ruff lint/format, strict +mypy, and the complete current suite before reporting. Use the known working +repository-venv pytest CLI fallback as needed. Clean up owned temporary files +and child processes. + +Report two distinct conclusions: + +- Mechanics implemented/verified, with actual test evidence. +- Full Step 5 production acceptance satisfied or BLOCKED by named missing + mapping evidence. Do not declare readiness for Step 6 if that gate is open. + +## Required 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 + +The entire report must be inside exactly one plain triple-backtick fence. +Include changed files, API/state/layer decisions, exact test/check commands and +outcomes, production registry contents, public evidence attempts, separate +mechanics/production/native status, and precise evidence needed to unblock. +Stop after writing this report. Do not fabricate a passing gate or start Step 6. diff --git a/prompts/step_5_fix.md b/prompts/step_5_fix.md new file mode 100644 index 0000000..e90020d --- /dev/null +++ b/prompts/step_5_fix.md @@ -0,0 +1,183 @@ +# Step 5 fix: Resolve the production mapping evidence gate + +Status: RESUMED for the approved Standard MIDI fallback. Read the continuation +decision at the top of `prompts/plan.md`. The following amendment supersedes +earlier gate/acceptance wording below; it does not authorize invented vendor maps. + +## Current executable fix objective + +Complete a functional, explicitly identified standard MIDI mapping path instead +of leaving the production registry empty until every vendor map is available: + +1. Add a public profile-summary discriminator `mapping_kind`, with values + `instrument` (default for backward-compatible existing models/fixtures) and + `standard_midi`. Update schemas, relevant tests, and docs coherently. +2. Add a corresponding honest provenance status for standard MIDI profiles. + Standard MIDI facts plus explicit generator/routing policy are not evidence + of a particular vendor configuration. Keep test_only excluded from production. +3. Create three real, non-synthetic fallback data files: standard pitched lead, + standard pitched bass, and General MIDI percussion. Use unique channels + 0/1/9 as documented output-routing policy. These are not invented vendor + defaults. Use standard valid MIDI note ranges and a simple documented + intensity-to-velocity policy; do not assert vendor velocity layers. +4. Restrict standard profiles to normal/sustain technique with no invented + keyswitches or CC actions. Existing generic compiler support for switch/CC + profiles remains tested. Unsupported requested techniques must fail honestly. +5. Default selections may use these fallback profiles, but summaries and eventual + generation results must clearly state they are NOT verified Eclips/Ray/SD3 + maps. The reviewed instrument field may identify intended routing, never + compatibility; mapping_kind and product_name/limitations disambiguate it. +6. Source General MIDI drum-note facts from accessible public documentation: + the MIDI Association overview at https://midi.org/general-midi-level-1 + establishes the standard; independently check the core percussion numbers + against an accessible reliable table (e.g. the General MIDI article). + Do not silently call a GM map the SD3 default map. +7. Update registry/wheel tests that previously required no JSON/empty summaries + to assert these exact standard-only profiles, absence of synthetic/vendor + claims, and normal selection behavior. The old Step 3 server remains unchanged + until Step 9 wiring, so its temporary empty-list tests may remain for now. +8. Correct compatibility documentation: raw official Ample HTML exposed public + PDFs at `Main_Panel_Manual-AME.pdf`, `Main_Panel_Manual-AMR.pdf`, + `Guitar_Riffer.pdf`, `Guitar_Strummer.pdf`, and `Settings_and_CPCv2.pdf` + under https://www.amplesound.net/en/. Do not repeat the mistaken conclusion + that the manual page contains only a domain label. Note that octave labels, + exact installed versions/maps, and native layouts still require verification. +9. Do not copy manuals or factory MIDI songs into the repository. No native + serialization or real vendor compatibility is claimed by this amendment. +10. Run the full current suite, Ruff lint/format, strict types, and real + outside-checkout wheel resource tests. Preserve existing strict contracts + except for the explicit discriminator/provenance additions. + +Current acceptance: the standard MIDI fallback registry and generic compilation +are operational, accurately described, and verified. Step 6 may then proceed +using these real standard profiles. Report vendor-map/native/application gates +as still open rather than calling the full native project complete. + +The historical evidence-specific objective and checklist below remain applicable +to later real-target profile additions, but missing vendor evidence must not +block this standard-only fix. Write `prompts/report_5_fix.md` as required below. + +## Orchestrator review decision + +Read `prompts/report_5.md` before working. The profile/compiler mechanics have +been implemented and independently checked: 137 focused tests passed, including +actual MIDI read-back and built-wheel resource checks. Steps 1-4 were accepted. + +Full Step 5 is NOT accepted. Its production registry contains zero maps. +Synthetic fixtures test mechanics only, and the stdio generation tool remains +explicitly unfinished. The report correctly says it is not ready for Step 6. + +The official Ample manual entry point yielded no usable map; the official +Toontrack manual required login. Repeating the same blocked fetches, changing +test_only to verified, or assuming GM drum mappings does not resolve the gate. + +Do not run an implementation worker against missing evidence. Execute this +fix when usable authoritative evidence becomes available. If only some targets +are documented, record that progress but keep full acceptance blocked until +every scoped target is resolved. + +## Objective + +Turn reviewed, lawfully obtained evidence into real versioned production MIDI +profiles for the user's Eclips lead, Ray bass, and SD3 drums. Preserve the tested +generic compiler and close only the MIDI mapping gate. Native-format and real +application acceptance gates remain independent. + +## Prerequisites to supply or locate lawfully + +For each target: + +- Exact vendor product name/edition and documented product/build version. +- For SD3, the selected library, active MIDI map, and relevant preset version. +- Numeric playable range or supported logical drum-voice MIDI numbers. +- MIDI channel configuration, including whether channels are configurable. +- Canonical techniques and aliases; numeric keyswitches and trigger velocities. +- Actual latching, momentary/hold, reset, retrigger, and polyphony behavior. +- Applicable CC selections/resets and explicit normal-technique restoration. +- Supported lead/gate/release timing, including any relevant tempo constraints. +- Verified velocity-layer boundaries and usable intensity behavior. +- Evidence source/version references and permission to store any fixtures. + +Do not require a nonexistent control mechanism: if a documented technique uses +no CC or no keyswitch, record that verified absence rather than inventing one. +Distinguish actual instrument layers from the generator's documented intensity +policy. If a target's real semantics cannot be represented by the current +profile model, describe the specific evidence-backed mismatch and implement a +small tested correction; do not falsify data to fit a synthetic fixture. + +Public official documentation is suitable when it establishes the selected +target version and behavior. User-owned lawful local evidence may be referenced +by safe evidence IDs. Do not publish private absolute paths or copy licensed +manuals. Never request/store credentials, bypass authentication, or upload +private files/code to third parties. + +## Files to create or modify + +- Add evidence-backed, version-named JSON profiles under + `src/riff_groove_builder/data/profiles/`. +- Update that package's `PROFILE_RESOURCES` manifest. +- Modify `profiles.py` or `articulations.py` only for an actual documented + mismatch; add focused regressions for any change. +- Add separate evidence-based cases to `tests/unit/test_profiles.py`, + `tests/unit/test_articulations.py`, and + `tests/integration/test_articulation_midi.py`, or a directly related target + test file if it makes the evidence/mechanics distinction clearer. +- Update `docs/articulation-profiles.md`, `docs/compatibility.md`, and relevant + README/architecture status text. +- Write `prompts/report_5_fix.md`. + +Preserve prior prompts/reports and the approved public contract. Do not commit, +delegate, create Step 6, implement native codecs, or wire the generation service. + +## Implementation constraints + +1. Review the underlying evidence, not merely a profile's assertion of verified + provenance. Confirm every production number and state rule against sources. +2. Keep synthetic test profiles excluded from production. Do not relabel the + existing test.lead/test.bass/test.drums fixtures as real maps. +3. Production IDs and metadata identify the actual supported versions/maps. + Declare a default only when unambiguous and justified. +4. Keep `native_available=false` until the separate native gates pass. Real + MIDI mapping does not certify `.agp`/`.sdp` serialization or Cubase loading. +5. Preserve exact timing, profile validation, layer bounds, part/channel + isolation, control resets, state transitions, and honest named failures. +6. If evidence contradicts the requested product or extension, report the exact + contradiction and required decision rather than choosing a different target. +7. If evidence is still unavailable, write a fresh blocked fix report with the + exact remaining fields/sources. Make no speculative production additions. + +## Required unit and integration tests + +- Parse and validate every new real profile with evidence/version consistency. +- Verify exact documented notes/voices, switches, CCs, layer boundaries, aliases, + and state rules; assertions must not simply copy the implementation's output. +- Verify selection/default behavior and synthetic exclusion in the production + registry. +- Compile representative real-target parts and compare independently expected + events, then write/read back actual MIDI through the reviewed writer. +- Verify packaged JSON discovery and profile summaries from the installed wheel, + outside the repository; update former empty-registry expectations accurately. +- Keep corrupt/missing-resource and invalid-profile cases failing explicitly. +- Run all existing mechanics, contract, MIDI, stdio, and distribution regressions. +- Run Ruff lint/format, strict mypy, and dependency checks. +- Record any actual target-plugin/Cubase MIDI acceptance separately; do not call + a pure-Python test an application import test or fabricate an observed result. + +## Acceptance criteria + +Full Step 5 is accepted only when the scoped real mappings are supported by +reviewed evidence and the above tests pass. Document unsupported techniques +explicitly; no silent dropped controls or plausible guesses. + +The orchestrator must read this fix report and review the evidence/tests before +creating `prompts/step_6.md`. If blockers remain, the sequence stays paused here. + +## Required report + +When complete, write your end-of-step report to ./prompts/report_5_fix.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +Place the entire report inside exactly one plain triple-backtick fence. Include +changed files, each target's evidence/version/source IDs, exact test commands +and pass/fail/skip counts, unresolved fields, separate MIDI/native/application +status, and a clear Step 6 readiness decision. Do not claim completion of the +full project merely because this mapping fix passes. diff --git a/prompts/step_6.md b/prompts/step_6.md new file mode 100644 index 0000000..f290af5 --- /dev/null +++ b/prompts/step_6.md @@ -0,0 +1,128 @@ +# Step 6: Text interpretation and coordinated composition + +## Objective and prerequisites + +Implement Step 6 of the amended approved plan. Read the continuation decision +and accepted `report_5_fix.md`: standard MIDI fallback profiles now exist and +were independently verified. Their normal/sustain-only limitation is explicit; +real vendor maps and native/application acceptance are not claimed. + +Build genuine deterministic text -> intent -> score -> mapped MIDI behavior, +not a generic loop unrelated to the text. Do not implement MCP service wiring, +native serialization, later prompts, or extra scope. No commits or delegation. + +## Owned files + +- Create `src/riff_groove_builder/description.py`. +- Create `src/riff_groove_builder/compose.py`. +- Create `tests/unit/test_description.py`. +- Create `tests/unit/test_compose.py`. +- Create `tests/integration/test_text_to_midi.py`. +- Add small text/JSON cases under `tests/fixtures/descriptions/` if useful. +- Update `README.md` and `docs/architecture.md` with the actual supported grammar, + template/default policies, limitations, and focused validation commands. +- Write `prompts/report_6.md`. + +Reuse the authoritative request/intent/score models, profile registry, compiler, +exact tick helpers, writer and named errors. Explain/test any necessary tightly +coupled shared change rather than replacing existing working contracts. + +## Text-resolution requirements + +1. Provide a small typed API resolving GenerateMusicRequest into MusicalIntent + plus explicit assumptions/override records for future GenerationResult. +2. Extract numeric tempo (`120 BPM`), bar count (`4 bars`), meter (`in 7/8`), + key (`E minor`), and explicit selected part words (`lead`/`guitar`, `bass`, + `drums`). No external model API, network, audio, or new parser framework. +3. Structured override values win over text and are disclosed. Contradictory + text without an applicable override is an actionable named error. + Never silently choose one of two distinct numeric tempos/keys/meters. +4. Omitted tempo/bars/meter/key resolve to 120 BPM, four bars, 4/4, E minor, with + assumptions. If no explicit part-selection language exists, default to all + three and disclose that assumption; structured parts win over text. +5. Support a documented bounded vocabulary for riff/lead/bass groove/drum groove, + straight quarter/eighth/sixteenth-note subdivisions, rests, and optional + eighth-note triplets if represented exactly. Document deterministic rules + for qualitative slow/fast and simple rock/metal/groove pattern terms if used. + Do not add a general genre engine, song sections, or extra modes. +6. Meaningful unsupported instructions (unrecognized instrument/technique, + unsupported mode, tempo changes, polyrhythm, audio requests, etc.) must fail + explicitly rather than disappear into a default loop. Ignore only documented + filler. Match whole words, including negation/part-only selection, not + accidental substrings. Do not treat "no drums" as a request for drums. +7. Recognize canonical technique phrases such as palm mute without pretending the + standard profile can realize them. Validate techniques against selected + profiles and return UnsupportedArticulationError for unavailable techniques. + Normal/sustain must work. Do not map palm mute to softer generic MIDI. +8. Keep parsing and composition separate. Do not select production instruments + by guessing vendor names from text; registry selection remains authoritative. + +## Composition requirements + +1. Compose selected tracks over exactly bars * numerator * 4/denominator + quarter-note beats on the common rational grid. Each track shares start/end. +2. Generate original simple musical content from the resolved intent: + scale-based lead/riff patterns, root/fifth-oriented bass, and kick/snare/hat + drum grooves with documented meter/subdivision behavior. + Use seeded local variation, not copied factory/demo sequences. +3. Respect major/minor key pitch classes, selected profile ranges/voices and + supported articulations. Define the MIDI octave-number convention explicitly. + Prefer sensible lead/bass registers, but choose notes within the actual map. +4. Use exact fractions and supported tick divisions. Gate notes/rests to avoid + ambiguous same-pitch overlap; truncate only as an explicit composition policy + at the shared bar/end boundary, never alter requested musical duration. +5. Drum voice names resolve through the selected profile's aliases. Do not + assume every profile contains every GM sound or use guessed physical notes. +6. No global random state, unsafe pitch/velocity clamping, silent out-of-range + notes, per-track drift, or dropped requested techniques. Invalid/narrow maps + that cannot support the pattern must produce useful named errors. +7. Enforce the event budget before constructing excessive notes; account for + at least note-on/off pairs and leave final control-event validation to the + existing compiler. Keep resource use bounded for extreme valid inputs. +8. Do not change the current Step 3 server handler; the pipeline is exercised + directly until Step 9 connects it. + +## Required unit tests + +- Valid structured/text values; defaults and assumption records; override + precedence/disclosure; contradictory numeric/key/meter instructions. +- Part inference/ordering, exclusions, only-selection, explicit parts override, + and unsupported instrument/mode/technique/material instruction failures. +- Whole-word extraction, filler, case/spacing, malformed/empty descriptions, + fraction/tempo/bar boundaries, and unsupported tempo changes. +- Different meters, exact bar/end boundaries, seed reproducibility/variation, + key/register/range compliance, no same-pitch overlaps, and subdivision/rest + effects on actual generated content. +- Standard normal/sustain succeeds; requested palm mute fails honestly under + standard-only maps. Synthetic switch profiles may test real compiler coupling + but must never be advertised as vendor compatibility. +- Missing voices, unrepresentable timing, and event-budget rejection. + +## Required integration tests + +- Lead-only, bass-only, drums-only and all-parts descriptions resolve/compose, + select real standard profiles, compile, write actual MIDI and read it back. +- Independently assert tempo/meter, musical duration, parts/channels, key/range, + rhythm changes from text, and emitted note pairing, not merely file existence. +- Include 3/4, 6/8, 7/8 and nondefault tempo/key/length cases. +- Same input/seed yields deterministic output; changed supported intent changes + measurable output. Compare precise expected events for simple cases. +- Unsupported vendor techniques fail without artifacts. +- Preserve all existing contracts/compiler/MIDI/protocol/package regressions. + +## Validation and acceptance + +Run focused new tests, relevant prior checks, Ruff lint/format, strict mypy, and +the full current suite after shared changes. The known working venv pytest CLI +fallback is acceptable. Clean up owned test files/children. + +Accept only tested text-driven, bounded, aligned standard-MIDI composition. +Real vendor articulation/native/application gates remain open and documented. + +## Required report + +When complete, write your end-of-step report to ./prompts/report_6.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 complete report inside exactly one plain triple-backtick fence. +Include APIs, exact supported grammar/default policies, measurable text-to-MIDI +evidence, exact commands/results/skips, limitations and next-step readiness. diff --git a/prompts/step_7.md b/prompts/step_7.md new file mode 100644 index 0000000..083e5f7 --- /dev/null +++ b/prompts/step_7.md @@ -0,0 +1,91 @@ +# Step 7: Ample native capability assessment and safe fallback boundary + +## Objective + +Execute the Ample portion of the amended plan after reading reports through +`report_6.md`. Text-to-MIDI and standard mappings are accepted. The real AGP +layout is not established. Implement a truthful native-capability boundary +ready for Step 9; implement serialization only if actual evidence supports it. + +The continuation decision permits independent fallback functionality while +preserving a blocked native-serialization acceptance gate. A capability check +is not a completed AGP writer. Never write renamed MIDI, invented JSON/XML, or a +preset that cannot carry the requested musical content. + +## Owned files + +- `src/riff_groove_builder/formats/__init__.py` +- `src/riff_groove_builder/formats/agp.py` +- `tests/unit/test_agp.py` +- `tests/integration/test_agp_capability.py` +- `docs/formats/agp.md` +- Relevant compatibility/architecture status updates. +- `prompts/report_7.md` + +No commits, delegation, later prompts, SDP implementation, or MCP service wiring. +Preserve prior reports and all existing tests/code. + +## Evidence already obtained + +Raw https://www.amplesound.net/en/manual.asp exposes official public manuals +Main_Panel_Manual-AME.pdf, Main_Panel_Manual-AMR.pdf, Guitar_Riffer.pdf, +Guitar_Strummer.pdf and Settings_and_CPCv2.pdf. +The main-panel documents contain articulation/range labels; Riffer documents +MIDI import/export and preset Save/Load UI, not a verified native binary schema. +Their availability corrects the earlier simplified-page extraction error. + +The publicly linked demo archive +https://www.amplesound.net/dl0822/ds/AME-Eclipse.zip was readable without login. +Its metadata contained MIDI, DAW projects and plugin state files, but no AGP +files. Do not re-download/copy factory music into tests or treat that absence as +proof no AGP format exists. No actual AGP layout has been observed. + +Review accessible relevant official evidence as needed, but do not loop through +guessed URLs or bypass access controls. Record facts, limitations and sources. + +## Implementation requirements + +1. Provide a small typed capability API for lead/bass AGP support, reusable by + service.py. Validate target/part and distinguish no verified format support + from bad requests or corrupted input. +2. A shared concrete NativeCapability type in formats/__init__.py is acceptable + for reuse by SD3. Keep fields simple: part, format, available and safe reason. + No generic exporter plugin framework or speculative native parser. +3. Current standard profiles and unknown layouts must return available=false + with explicit stable NATIVE_FORMAT_UNAVAILABLE context. Do not assume + native_available metadata alone proves a codec exists. +4. Expose an explicit require/check boundary that raises the repository's named + native-unavailable error before any path is created or touched when support + is absent. Do not add a fake successful write API. +5. If lawful real fixtures/specifications actually establish a layout, implement + its correct writer and validation with evidence-based tests; otherwise + document that serialization remains unimplemented and application untested. +6. Document expected future lead/bass artifact roles/names, separate product + version handling, precise missing schema/fixture requirements and real + Eclips/Ray load/save acceptance needed. + +## Required unit and integration tests + +- Lead and bass capability results are typed and explicit. +- Drum/wrong-target or mutated-profile input is rejected, not misclassified. +- Standard profile/native false and codec-not-established cases remain honest. +- Require/check raises named errors with format/part/reason context. +- Capability/unavailable operations create no files, do not overwrite an existing + sentinel, and never return fake artifact paths or MIDI with AGP extensions. +- Preserve profile/compiler/MIDI/package regressions; run focused new tests, + Ruff lint/format and strict mypy. +- Real native round trips/application checks only if genuine evidence exists; + missing tests are reported UNRUN, never counted as passing compatibility. + +## Acceptance and report + +The software capability/fallback boundary may pass while full native AGP +acceptance remains BLOCKED. State both distinctly. No application evidence may +be fabricated. This step is substantial evidence/contract work, not a claim that +an unavailable capability is a native writer. + +When complete, write your end-of-step report to ./prompts/report_7.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step + +The whole report must be inside exactly one plain triple-backtick fence. Include +files/API, exact test/check outcomes, evidence conclusions, unresolved native +gate, and readiness for the next independent capability/service work. diff --git a/prompts/step_7_fix.md b/prompts/step_7_fix.md new file mode 100644 index 0000000..6034773 --- /dev/null +++ b/prompts/step_7_fix.md @@ -0,0 +1,132 @@ +# Step 7 native fix: Implement AGP only from real format evidence + +## Current executable implementation amendment + +Read the latest native-format continuation at the top of `plan.md`. Real local +evidence HAS BEEN FOUND. Implement the actual native Riffer writers now, rather +than another research-only or unavailable-capability report. + +The installed target versions are observed from VST3 ProductVersion metadata: +`C:\Program Files\Common Files\VST3\AME.vst3` = 4.0.1 and +`C:\Program Files\Common Files\VST3\AMR.vst3` = 4.1.0. +Read-only references: + +- `C:\Users\g3\Documents\Ample Sound\Riff4\Guitar4\AME Presets\*.griff` +- `C:\Users\g3\Documents\Ample Sound\Riff4\Bass4\AMR Preset\*.briff` +- User-authored examples may also exist directly under Guitar4/Bass4. + +Do NOT upload these files or copy factory musical sequences into the repository. +Only schema/numeric facts may become documentation and generated original tests. +The real suffixes are `.griff` for lead and `.briff` for bass. `agp` remains a +logical request alias; never write an incorrectly suffixed native artifact. + +### Observed schema facts, to verify before implementation + +- XML `Riff` root, `Ver="2.1"`, `PPQBase="480"`, numStr 6/5. +- Root fields Author/Category/Measures/Time-Signature/Quantize/Tempo/Type/Rating/ + Key/loopMode/loopStart/loopEnd; guitar Inst="AME"; bass may omit Inst but + user-authored AMR example includes it. +- `String ID="6"` down to 1 (guitar), 5 down to 1 (bass). +- Child `Note`: NoteID, Fret, Begin, End, Velocity, Off-Velocity, Articulation, + Legato, Muted. MIDI pitch is NoteID; Begin/End are integer ticks at PPQBase. +- Observed labels: Sus/PM (both), guitar PH/Tap/Mute/SI, bass Acc/DN/PMP/STA. + Support only evidence-backed semantics; normal and palm mute are sufficient + initial target techniques. No guessed special legato or effects. +- Default guitar open-string notes by ID 6..1: 36,43,48,53,57,62; one factory + variant uses 38 on string 6, so tuning must be explicit rather than inferred + indiscriminately. Default bass 5..1: 35,40,45,50,55; observed drop variants + use 33/38 on lower strings, not a universal default. +- Root `ccName-1="1.Mod"` / `ccVisibility-1="1"` and `cc-1.Mod` child with `p` + points tick/value/curveType. Values are MIDI controller units (observed + 0..120), not normalized 0..1. `curveType="stair"` encodes discrete CC actions. + Optional curvePointTickProp/curvePointValueProp exist for curved interpolation. + +### Owned implementation + +1. Replace the unavailable AGP boundary with real Riffer capability/writer/ + saved-file validator APIs for supported version/target profiles. Keep legacy + check/require names compatible; native metadata alone cannot invent a codec. +2. Add strict native Riffer mapping/settings to InstrumentProfile as needed: + layout version, explicit tuning/fret/range policy, actual extension and + supported articulation/CC representations. No arbitrary template scripting. +3. Add evidence-backed Eclipse 4.0.1 and Ray5 4.1.0 profile JSON files and + provenance. Use public manuals plus safe local evidence IDs, not private + absolute paths in distributed metadata. Keep existing standard profiles + explicit fallbacks and synthetic profiles excluded. +4. Public/native artifact contracts must represent actual griff/briff/sd3p + suffixes, while retaining agp/sdp request aliases. Make the smallest coherent + schema additions and update relevant validation/tests. Do not relabel actual + extensions as agp/sdp in result metadata. +5. Keep new target profiles NONDEFAULT until the later integration fix wires + all native writers. Preserve operational default MIDI service meanwhile. +6. Map verified normal/palm_mute techniques and velocity behavior. Public + manuals establish guitar C0 normal/D0 palm mute; numeric C0=24 is consistent + with the vendor's public exported Eclipse MIDI and actual native note ranges. + Bass normal C0 has explicit velocity bands: 64..126 sustain, 32..63 palm mute; + avoid 127 accent and <32 dead-note when generating those named techniques. + Describe generator timing/routing policy separately from instrument facts. + Confirm facts against local/manual evidence; do not mark unsupported modes. +7. Add CC1 modulation/vibrato support only if its exact behavior is established; + the native renderer must at least preserve supported compiled CC1 events. + No hard-coded fabricated CC reset or vendor layer ranges. +8. Render generated ORIGINAL score notes with correct string/fret assignment, + no overlapping notes on a physical string, exact rational timing converted + to PPQ 480, on/off velocities and native articulation. Preserve or explicitly + reject unrepresentable pre-roll/tails rather than silently misalign MIDI. +9. Write exclusively into the supplied staged path, reject wrong suffix/version/ + target/unsupported content, read saved XML back and independently compare + actual notes/CC/timing to the requested score/event plan. No fake success. +10. Update native/profile/model/contract tests and docs, including truthful + corrected suffixes. Add generated original minimal XML fixtures only. + Existing factory files are read-only local evidence, not redistributed tests. + +Run focused new native/profile/schema tests, the full current suite, Ruff +lint/format, strict mypy and package/resource checks as affected. Fix actual +regressions; do not weaken the tests or claim all existing profiles native. +Do not wire service native output yet, implement SDP, commit, delegate or create +later prompts. Produce actual generated .griff/.briff read-back evidence. + +Update `prompts/report_7_fix.md` with a current implementation section and retain +the earlier research as clearly labeled historical evidence inside the same +single plain triple-backtick report fence. Report implementation/tests/actual +native files/limitations and next-step readiness, not a research-only stop. + +--- + +Historical evidence gate (superseded where the amendment supplies facts): + +Status: native acceptance BLOCKED; capability software reviewed and verified. +Read `report_7.md` and `docs/formats/agp.md`. The current boundary intentionally +returns native unavailable and performs no filesystem IO. + +## Objective and required inputs + +Implement real Eclips/Ray musical-content AGP export after lawful specifications +or controlled real exports establish the layout, supported versions and content +semantics. Required: empty/one-note/multi-note files, isolated timing/tempo/ +velocity/articulation changes, source/permission records, and exact native +load/save workflow. Do not substitute preset-only settings or renamed MIDI. + +## Files and constraints + +Modify `formats/agp.py`, only necessary shared capability/profile definitions, +AGP unit/integration tests, `docs/formats/agp.md` and compatibility documentation. +Add redistributable native fixtures only with permission; otherwise document +local-only tests using safe evidence IDs. Preserve MIDI fallback and strict +errors. Native availability requires an actual codec, not profile metadata. +No scope expansion, commits, delegation or later prompts. + +## Tests and acceptance + +Unit-test verified field serialization, version/invalid input handling, +length/checksum/compression rules, and separate guitar/bass behavior as required. +Integration-test actual fixture round trips and generated musical content; +record real Eclips/Ray load/save/reload acceptance separately. Run related +fallback/MIDI regressions, Ruff lint/format and strict types. +If evidence is unavailable, keep native acceptance blocked; do not invent it. +The orchestrator must review this report before claiming native completion. + +When complete, write your end-of-step report to ./prompts/report_7_fix.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 exact commands, +source/fixture versions, application acceptance, skips and unresolved blockers. diff --git a/prompts/step_8.md b/prompts/step_8.md new file mode 100644 index 0000000..55d5096 --- /dev/null +++ b/prompts/step_8.md @@ -0,0 +1,68 @@ +# Step 8: SD3 native capability assessment and safe fallback boundary + +## Objective and prerequisites + +Read the amended plan and reports through `report_7.md`. AGP capability software +was reviewed and independently passed 74 tests; real AGP native acceptance +remains separately blocked with `step_7_fix.md`. + +Implement the corresponding honest SDP capability boundary for the later +service. The official SD3 manual page required login; no layout or controlled +SDP fixture has been established. Do not bypass authentication or claim a +preset-only container contains generated drum-song data. + +## Owned files + +- Create `src/riff_groove_builder/formats/sdp.py`. +- Create `tests/unit/test_sdp.py`. +- Create `tests/integration/test_sdp_capability.py`. +- Update `docs/formats/sdp.md` and relevant architecture/compatibility status. +- Write `prompts/report_8.md`. + +Reuse `formats.NativeCapability` and the existing AGP boundary pattern rather +than introducing another registry/framework. No commits, delegation, later +prompts, service wiring or fake native writer. + +## Implementation requirements + +1. Provide typed check/require APIs for drums/SDP, defensively revalidating + profiles and rejecting bad target/part/mutated model input explicitly. +2. Valid matching profiles currently produce available=false and a stable safe + layout-not-established reason. Mapping provenance/metadata cannot enable a + nonexistent codec. +3. Require/check raises NativeFormatUnavailableError with part/format/reason + before any path is touched. Bad requests/profiles are not native fallback. +4. No fake successful write API, renamed MIDI, invented XML/JSON, or fixture + that merely agrees with an invented parser. +5. Document expected future drums artifact role, exact content/layout/version + evidence needed, selected library/map concerns and actual SD3 import/save + acceptance. Public MIDI facts do not establish SDP. +6. If genuine lawful specifications/fixtures become available, implement the + real serializer only with evidence-based validation; otherwise report the + real native gate BLOCKED, software boundary independently testable. + +## Required unit and integration tests + +- Typed immutable unavailable drums capability and stable named require error. +- Lead/bass/invalid parts, wrong target, deep mutation and unchecked-model cases + fail correctly rather than being hidden as unavailable. +- Standard GM fallback remains explicitly NOT an SD3-native capability. +- No filesystem side effects, fake paths or overwritten sentinels. +- Actual separately generated standard MIDI remains valid and contains no SDP + artifact. Test against real registry/compiler/writer APIs. +- Relevant AGP/profile/MIDI/package regressions remain passing. +- Run focused new tests, Ruff lint/format and strict mypy. +- Real native round trips/application acceptance are reported UNRUN unless + actually executed against genuine data and the real installed application. + +## Acceptance and report + +Software capability boundary can pass while real SDP serialization remains +BLOCKED. Report both, preserving the independent fallback continuation decision. +Do not call an unavailable capability a finished native writer. + +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 + +Use exactly one plain triple-backtick fence for the entire report. Include +files/APIs, exact checks/results, evidence limitations, native/app blockers and +readiness for Step 9's independent standard-MIDI service/fallback path. diff --git a/prompts/step_8_fix.md b/prompts/step_8_fix.md new file mode 100644 index 0000000..2060b31 --- /dev/null +++ b/prompts/step_8_fix.md @@ -0,0 +1,144 @@ +# Step 8 native fix: Implement SDP only from real format evidence + +## Current executable native implementation amendment + +Real native evidence now exists. Read the latest plan continuation and CURRENT +implementation section of `report_7_fix.md` (Riffer native implementation has +passed 1,221 tests). Implement SD3 native output now, not another unavailable +boundary or public-research-only report. This amendment supersedes the old +absent-evidence gate below. + +### Read-only local evidence + +- Installed executable: + `C:\Program Files\Toontrack\Superior Drummer\Superior Drummer 3.exe`, + ProductVersion 3.4.4. +- Local official documentation: + `C:\Program Files\Toontrack\Superior Drummer\Superior Drummer 3 Operation Manual.pdf`. + Read locally if needed; do not upload/copy the manual into the repository. +- Genuine project: + `C:\Users\g3\Documents\Toontrack\Superior Drummer 3\sd3-demo.sd3p` + (75,393 bytes); four other .sd3p projects exist in that same folder. + Treat them as private read-only evidence, not redistributable fixtures. +- Actual suffix is `.sd3p`; `sdp` is a request/API alias, not a file extension + to write. Models now distinguish request aliases and actual ArtifactFormat. + +### Observed native structure to verify + +UTF-8 text begins `PlugVersion 3.4.4`. There is a substantial `SAMPLER` block +with selected `soundlib "SL-DFH"` and kit/mixer state. Preserve operator state +instead of inventing/shipping proprietary kit data. + +Top-level: +`ClearTracksFirst` followed by `SongTrack 0 { ... }`. +Track fields include Minimized, ClearTrackFirst, TrackLength, VisibleArea, Zoom, +Tempo ` 0 0`, TimeSig ` 0`, KeySign, TrackName, MutedCCs, +ClearSongParts, GridRes, LoopArea, LoopActive, StartNumber, PlayHeadPos. +Each `MidiLoop 0 { ... }` has Name, RealEndTime, StartTime, EndTime, Offset, +tapQuantize, Velocity, ClearNotes, TimeSig and a `MidiEvents { ... }` block. +MidiEvents includes EndTime, one Events line, KeySign, TimeSig and Tempo. + +Events are repeating triples: packed MIDI message integer, start beat, end beat. +Observed 8332944 = 0x7f2690 = note-on status 0x90, pitch 38, velocity 127. +Packing is status | (note << 8) | (velocity << 16); notes have explicit start/end +positions in quarter-note beats. Verify against actual local samples rather +than reusing any musical sequence. Use original generated events in tests. + +Important: later `Drumtracker { Track 0 { trackstuff ... } }` is a DIFFERENT +audio-tracker state, not the song track. Its custom base64 payload decodes to +`trackStuff`/GeneralStuff settings, while `tempoMap` decodes to XML. Do not +mistake those opaque tracker fields for the song MIDI or add audio analysis. +Do not alter them to implement song generation. + +### Owned implementation + +- `formats/sdp.py`: real bounded versioned project parser, check/require, + template-based writer and independent saved-file validator. +- Only necessary shared model/profile/schema corrections and a nondefault + evidence-backed SD3 3.4.4 subset profile/resource. +- New/updated SD3 unit/integration/native contract/resource tests, format/ + architecture/compatibility docs and `report_8_fix.md`. +- No native service wiring/default-profile changes yet; that is the next fix. + +### Constraints and acceptance + +1. A project template is an operator-local configuration input, never bundled + private state. Expose a typed template argument for the writer and an + inspection/preflight API ready for later optional CLI configuration. + Absent template is an explicit known native-capability limitation; corrupt, + unsupported-version or unreadable explicitly supplied templates are errors, + not silent MIDI fallback. No arbitrary code execution/template scripting. +2. Parse balanced native blocks with quoted/escaped strings correctly. + Bound bytes/nesting/events. Reject unsupported version, malformed/unbalanced + state, ambiguous active tracks and invalid music; preserve unrelated kit/ + mixer/non-song template text byte-for-byte. +3. Replace ALL active template SongTrack musical data with one original + generated drum track/clip. Do not accidentally retain original grooves, + offsets, source MIDI references or extra active tracks. +4. Preserve requested tempo, meter, common start/end, drum pitches, velocities, + channels and exact representable timing. Decode saved native event triples + independently and compare musical events to the supplied plan/score. + Explicitly reject any unsupported control/event semantics rather than drop. +5. The generated .sd3p must contain actual new song events, not only a preset, + arbitrary JSON, an invented wrapper, a renamed MIDI or a copied old song. +6. Verify core drum note mapping from the local official manual/project/setup + evidence. Keep the profile a verified SUBSET if only core voices are proven. + Separate routing/intensity generator policy from vendor facts; do not call + every GM sound the SD3 map. Existing defaults remain standard until integration. +7. Codec capability is not just a metadata flag. The actual template/version + requirement must be testable and exposed to later service preflight. +8. Exclusive staged-path writes, explicit correct suffix, positive bounded file + size, saved-file structural/content validation and no modifications of input + templates. Any mismatch is a named serialization failure, not success. +9. Use generated original minimal test templates/state, no copied private or + licensed project. Also run read-only local-template integration here with + generated original music and retain only generated evidence outside source. +10. Test malformed/unsupported templates, quoting/nesting, multiple tracks, + timing/packing boundaries, song replacement, unchanged non-song state, + template identity/content preservation, wrong suffix, IO/corruption failures. + Run full current suite, Ruff lint/format, strict mypy and package/resource + checks as affected. Do not weaken prior working behavior. + +No commits, delegation, later prompts, source factory songs or service wiring. +Write the full current implementation/testing/results/readiness report to +`prompts/report_8_fix.md`, entirely inside one plain triple-backtick fence. +Actual plugin/Cubase acceptance must be distinguished from structural native +read-back; no fabricated application result. + +--- + +Historical gate (superseded by the genuine local evidence above): + +Status: real native acceptance BLOCKED; capability software reviewed/verified. +Read `report_8.md` and `docs/formats/sdp.md`. The current boundary deliberately +returns unavailable with no filesystem IO; it is not a native writer. + +## Objective and inputs + +Implement real SD3 musical-content SDP export after lawful specifications or +controlled real exports establish the container/version, song/groove fields, +mapping dependencies and import workflow. Obtain empty/one-hit/multi-hit files, +controlled timing/tempo/velocity/articulation differences, source/permission +records, and actual SD3 version/library/map information. Do not bypass login, +guess a different extension, emit preset-only state or rename MIDI. + +## Owned files and constraints + +Modify `formats/sdp.py`, only necessary shared capability/profile definitions, +SDP tests, format docs and compatibility matrix. Add fixtures only with rights; +otherwise use documented private local evidence IDs. Preserve honest fallback +and explicit errors. No commits, delegation, scope expansion or later prompts. + +## Required tests and acceptance + +Unit-test evidence-based serialization, format/version invariants, invalid data, +length/checksum/compression handling. Integration-test genuine round trips and +generated drum-content equivalence. Record real SD3 import/inspect/save/reload +and Cubase routing checks separately. Run related fallback/MIDI regressions, +Ruff lint/format and strict types. Missing evidence remains blocked, not passed. +The orchestrator must review the fix report before claiming native completion. + +When complete, write your end-of-step report to ./prompts/report_8_fix.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 commands, +sources/fixture versions, native/application evidence, skips and blockers. diff --git a/prompts/step_9.md b/prompts/step_9.md new file mode 100644 index 0000000..4010926 --- /dev/null +++ b/prompts/step_9.md @@ -0,0 +1,121 @@ +# Step 9: Operational MCP generation service and explicit MIDI fallback + +## Objective and accepted prerequisites + +Implement the amended plan's independent end-to-end Standard MIDI path. +Read reports 5_fix, 6, 7 and 8 and the continuation decision. The parser, +composer, profile registry, compiler, MIDI writer and native capability checks +are reviewed/tested. Real native serialization is still blocked with persistent +step_7_fix/step_8_fix prompts; do not call those native gates passed. + +Replace the Step 3 unfinished handlers with useful real behavior. No fake native +success, invented maps, extra output formats, audio, model service, commit, +delegation or later prompts. + +## Owned files + +- Create `src/riff_groove_builder/service.py`. +- Modify `server.py` and `__main__.py` only as required for actual service wiring. +- Create `tests/unit/test_service.py`. +- Create `tests/integration/test_generation_service.py`. +- Update server/stdio tests that intentionally expected empty/unimplemented tools. +- Update `README.md`, `docs/architecture.md`, compatibility/profile status docs + as necessary for accurate operational usage. +- Write `prompts/report_9.md`. + +Reuse strict existing contracts/errors/APIs; explain and test any necessary +shared corrections. Do not weaken lint/types or duplicate the composition logic. + +## Generation and result requirements + +1. Provide one small concrete service API using the configured output root and + real packaged ProfileRegistry. Revalidate incoming models and mutable graphs. +2. Wire resolve_description -> profile selection -> compose_score -> + compile_score -> write_midi/read-back -> publication -> GenerationResult. +3. Recheck parts/formats/profile associations after text resolution; request + fields omitted before parsing must not bypass applicability checks. +4. Missing formats mean MIDI plus applicable native targets for selected parts. + Explicit mid means MIDI only; AGP applies to lead/bass, SDP to drums. +5. Preflight native capabilities using the real check APIs before touching output. + Currently no native codec is available. With allowed fallback, emit one + combined MIDI for all selected parts even if mid was not listed. With + fallback=false and requested unavailable native output, fail before files. +6. Only known native-capability unavailability permits fallback. Invalid requests, + unsupported techniques, corrupt maps, serialization/read-back failure, + permissions/disk failures and unexpected bugs must remain explicit failures. +7. Return actual published absolute paths/sizes/part/profile IDs, resolved musical + metadata, assumptions/overrides and exact fallback_for coverage. Never include + nonexistent native artifacts, raw private inputs or file bytes. +8. Standard-only mappings need explicit per-part STANDARD_MIDI_MAPPING warnings + and honest profile summaries. Native substitutions additionally need per-part + NATIVE_FORMAT_UNAVAILABLE warnings, status=midi_fallback and matching + fallback_for. Explicit MIDI-only output can be complete but still includes + standard-mapping warnings; it never claims vendor compatibility. +9. List profiles from the actual registry (three standard profiles today), + keeping mapping_kind/product limitations. Remove development-only descriptions + and unfinished errors from registered tools. +10. Successful output includes declared structuredContent plus useful concise + text. Known failures use declared typed isError output; protocol behavior, + strict schemas, sanitization, stderr diagnostics and EOF must remain intact. +11. Build/validate the anticipated result before publication where possible so + a result-model bug cannot publish files and then report generation failure. + +## Filesystem/publication requirements + +1. Tool input cannot choose arbitrary paths. Validate local output-root directory + and safe basename with existing helpers plus necessary confinement checks. +2. Pin/recheck root identity and reject relevant symlink/junction/reparse-point + escapes or root changes. Do not claim comprehensive adversarial race safety + if the portable APIs cannot provide it; document exact behavior/limitations. +3. Stage files under one unique owned directory inside the output root. Write + `.mid`, validate the actual saved file and compute real size. +4. Publish the complete set as `/` by same-volume directory + rename. No partial final directories, silent overwrite/merge, or replacement + of existing empty directories. Concurrent same-name requests have one winner + and explicit collision failure. If relying on Windows no-replace semantics, + enforce/document that accurately rather than silently weakening other OSes. +5. No unrelated output-root files are deleted. Cleanup only a specific owned + stage directory with verified identity; surface cleanup failures explicitly. + Preserve sentinels and existing outputs on every failure path. +6. Keep this simple: no persistent job database, generic exporter framework, + remote server, on-disk sidecar manifests or broad silent catches. + +## Required unit tests + +- Default/explicit formats, text-resolved part applicability and profile mismatch. +- Exact success/fallback artifact/warning/status coverage. +- Fallback false/no files; unsupported palm mute/no dropped articulation. +- Mutated/corrupt inputs, map or serialization/read-back/IO failures stay errors. +- Safe names/root validation, root identity changes, reparse/confinement checks, + collisions, cleanup ownership/failures and no silent overwrite. +- Accurate real profile listing and MCP result/error conversion. + +## Required integration tests + +- Real description -> selected standard maps -> actual MIDI -> read-back -> + published directory -> schema-valid metadata for individual/all parts. +- Default native requests yield only actual MIDI with explicit fallback warnings. +- Native-only request with allowed fallback yields one combined MIDI; disabled + fallback publishes nothing. Invalid format associations fail after inference. +- Inject write/read-back/publication/cleanup failure and verify no corrupt/partial + final directory or overwritten sentinel. Test competing same-basename requests. +- Test genuine Windows junction/reparse handling where available; report any + environment skip honestly, not as passed confinement. +- Real stdio initialize/list/call generation: inspect returned actual disk MIDI, + warnings/profiles/output schema, strict invalid arguments, IDs, stdout and EOF. +- Different working directory and existing distribution/resource regressions. + +## Validation and acceptance + +Run focused service/server tests, complete current suite, Ruff lint/format, +strict mypy and pip check. Clean up owned test workspaces and child processes. + +Acceptance is a working standard-MIDI MCP generator with explicit native fallback +and safe publication, not full native/vendor/application completion. Do not +leave generation as a placeholder merely because native layouts are unknown. + +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 + +Entire report inside exactly one plain triple-backtick fence. Include real stdio +generation evidence, exact checks/results, filesystem guarantees/limitations, +artifact/warning examples, cleanup and separate software/native/app readiness. diff --git a/prompts/step_9_fix.md b/prompts/step_9_fix.md new file mode 100644 index 0000000..9f0669e --- /dev/null +++ b/prompts/step_9_fix.md @@ -0,0 +1,122 @@ +# Step 9 fix: Wire every real native writer into the MCP service + +## Objective and accepted prerequisites + +Read the latest plan continuation and CURRENT report_7_fix/report_8_fix. +Real Riffer .griff/.briff and SD3 .sd3p codecs, saved-file validators and +evidence-backed target subset profiles are implemented. The orchestrator +reviewed both reports and independently reran their new native tests. + +Finish the original native-generation functionality end-to-end. Do not merely +keep returning unavailable or native_writer_not_registered. Preserve correct +explicit MIDI fallback where a real configured capability is missing. +No commits, delegation, later prompts, audio analysis, plugin hosting or scope +expansion. Actual native suffixes correct the original request names; agp/sdp +remain accepted request aliases, never misleading artifact suffixes. + +## Owned surfaces + +- `service.py`, `server.py`, `__main__.py` +- Minimal coherent native preflight helpers if needed; do not replace codecs. +- Target/standard profile default flags and necessary strict validation updates. +- Unit/integration/stdio/installed-distribution/native transaction tests. +- README, architecture, compatibility, profile/format docs and current plan status. +- `prompts/report_9_fix.md` + +Preserve all previous reports and unrelated work. Explain/test shared changes. + +## Functional integration + +1. Register write_riffer/validate_riffer_file and write_sdp/validate_sdp_file + alongside MIDI. Defaults request MIDI and each selected part's actual native + suffix. Explicit native aliases and actual names resolve coherently: + agp -> relevant griff/briff; sdp -> sd3p. +2. Use actual format/suffix/part metadata in artifacts: + `_lead.griff`, `_bass.briff`, + `_drums.sd3p`, combined `.mid`. + No renamed MIDI or artifact format=agp/sdp fiction. +3. Promote actual evidence-backed target subsets to unambiguous defaults for + their parts once service wiring works. Keep standard profiles available by + explicit ID as fallbacks, not silently relabeled target mappings. +4. Add optional operator CLI `--sd3-template `, thread the + typed Path through create_server/GenerationService and native preflight/ + write/validation. No tool-controlled arbitrary template path. + Missing optional template is known native unavailability; corrupt/unreadable/ + unsupported explicitly supplied template is a visible error, never hidden + as fallback. Preserve source template identity/content. +5. Do not auto-bundle/distribute private kit state or factory music. For genuine + local acceptance use the known read-only operator template: + C:\Users\g3\Documents\Toontrack\Superior Drummer 3\sd3-demo.sd3p + Tests must use original synthetic minimal template state and remain portable + without that private file. Current CLI docs/config may show operator paths + but never include private project bytes. +6. Profile listing must accurately describe runtime native readiness, actual + corrected suffixes, version/library/subset limits and any template requirement. + Selected target MIDI maps work even without a native project template. +7. All requested available native outputs must be emitted, even when another + part requires fallback. A missing drum template with allowed fallback should + yield real lead/bass native files plus one combined MIDI, with fallback_for + only drums. Fallback=false must fail before staging/publishing. +8. Only actual known representation/capability limitations may cause fallback. + Native write/read-back corruption, map errors, template errors and IO failures + remain failures. Preflight known native grid/pre-roll/tail/control limitations + when possible; do not stage partial outputs and then claim success. +9. Correct success/fallback coverage, profile IDs, sizes, assumptions/overrides + and per-part warnings. Verified-subset limitations should be visible without + claiming every technique/tuning/library or full application certification. +10. Palm mute on the native lead/bass profiles must be reachable through the + description path and produce actual switch/velocity/native PM/PMP data. + If mixed pitched+drum descriptions request pitched-only techniques, define + and test the intended applicability rather than requesting drum palm mute + or silently dropping a meaningful instruction. + +## Multi-file transaction and failures + +- Stage at most the requested native/MIDI files under one uniquely owned root + child. Validate every actual saved native/MIDI file before publication. +- Generalize owned filename/size/identity checks and cleanup from the old single + MIDI file. Unknown injected content/reparse points or ownership changes remain + errors; never recursively erase unrelated files or user data. +- Build/validate complete result metadata before the same-volume Windows + no-replace rename commit. No partial final directories, overwrites or merges. +- Failure of the last native writer must clean all owned partial stage files + and publish nothing. Preserve existing destination/sentinel identities. +- Keep root/ancestor checks, concurrent one-winner behavior, trusted ACL/race/ + crash limits and stdout/error privacy accurate. + +## Required tests + +Unit: requested alias/actual-format resolution, target defaults, explicit standard +selection, template absent/valid/corrupt, runtime profile summaries, correct +artifact/warning coverage, no native placeholders, and multi-file cleanup/ +ownership/collision/fault paths. + +Integration: +- All-parts default/native-only/MIDI-only with a generated original SD3 template. + Validate actual .griff/.briff/.sd3p plus MIDI against the same requested score. +- Different meters/tempo/key/seed and lead/bass palm mute (including correct bass + PMP/C0 band). Assert MIDI switches/velocity and native technique fields. +- Missing template: available Riffer natives survive alongside explicit MIDI + fallback for drums; fallback disabled publishes nothing. +- Corrupt/unsupported supplied template, native write/read-back fault, publication + and cleanup failure never become successful fallback or partial publication. +- Real stdio generate calls, profile/schema discovery and EOF from a different + cwd; installed-wheel full native generation with only original test template. +- Read-only genuine local-template acceptance with original generated music; + retain generated evidence only under ignored test artifacts, not source. + +Update old standard-default assertions intentionally: explicitly select standard +IDs where testing the old standard behavior, and separately test new target +defaults. Do not weaken expectations to accommodate accidental regression. +Run the complete current suite, Ruff lint/format, strict mypy, pip check and +affected package/installed-server checks. + +## Required report + +When complete, write your end-of-step report to ./prompts/report_9_fix.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 in exactly one plain triple-backtick fence. Include real default +and alias stdio native outputs, original/genuine-template evidence, actual +format/part/profile/tempo/meter/velocity/content checks, atomic failure results, +exact commands/counts, source preservation and remaining application-only limits. +Do not call existing native codecs unavailable because old research was blocked. diff --git a/prompts/step_9_fix_controls.md b/prompts/step_9_fix_controls.md new file mode 100644 index 0000000..a06d9c8 --- /dev/null +++ b/prompts/step_9_fix_controls.md @@ -0,0 +1,92 @@ +# Step 9 controls fix: Expose scoped CC messages through the MCP request + +## Objective + +The real native/MIDI integration is accepted after report/source review and +independent tests. Read CURRENT `report_9_fix.md`, schemas/compiler/service and +native codecs. Complete the scoped CC-message surface: CC generation already +works internally, but callers need a strict way to request it through the MCP +tool. Do not invent a vendor vibrato mapping or add audio/host/model features. + +No commits, delegation, later prompts or unrelated refactoring. + +## Owned surfaces + +- `schemas.py` for a typed optional request property. +- A small exact scheduled-control helper in `articulations.py` or `service.py`, + reusing existing event models rather than duplicating the scheduler. +- `service.py` for applying controls and honest native preflight. +- A precise SD3 unsupported-controller reason if needed to distinguish known + format limits from corrupt note/channel/release semantics. +- Related request/schema/service/stdio/installed/native tests and docs. +- `prompts/report_9_fix_controls.md`. + +## Contract and behavior + +1. Add optional `cc_events`, default empty list, to GenerateMusicRequest. + Each strict item contains: + - part: lead | bass | drums + - beat: existing RationalBeat quarter-note position relative to musical start + - controller: strict MIDI data integer 0..127 + - value: strict MIDI data integer 0..127 + No filenames, raw code, arbitrary properties, silent clamping or float drift. +2. Reuse the existing 100,000-event resource budget; count controls together with + all note/switch events. Bounds/strict booleans/types and unknown fields remain + enforced. No new unrelated dependency. +3. Validate part association before/after text inference as appropriate, exact + tick representability and beat <= resolved musical duration. End-boundary + explicit resets are valid. Reject duplicate normalized + (part, beat, controller) points rather than choosing an arbitrary winner. +4. Apply explicit controls after ordinary score compilation, using common + musical-start offset and stable event ordering (controls before note-ons). + Preserve unique ordering keys and all original note/switch events. +5. Do not silently override an articulation-generated controller at the same + instant/controller. Detect conflicting controls and return an actionable + INVALID_REQUEST, unless an existing explicit repository policy proves otherwise. + No implicit reset is invented; callers can request value=0 at musical end. +6. MIDI exports must retain every requested valid controller/channel/tick/value. + Native Riffer preserves supported CC1 stair events already implemented. + An unsupported native controller is known capability unavailability, so only + the affected native target may fall back when allowed; combined MIDI still + preserves ALL controls. No silent dropped native CC. +7. SD3's observed native subset does not establish CC triples. Give legitimate + explicit drum CC requests a precise unsupported-controller preflight reason, + distinct from corrupted channel/note/role/release data. Only that known + controller limitation permits native fallback. fallback=false errors before + staging. Explicit MIDI-only drum CC remains supported. +8. Default empty cc_events preserves existing outputs exactly. No unsupported + vendor technique is inferred from a controller number or vice versa. + +## Required unit tests + +- Strict CC object schema/types/ranges, rational normalization, projected + duplicates, part associations, beat bounds/grid and event-budget rejection. +- Exact controller ordering/channel/tick/value and unchanged musical/switch + events; multiple controllers and end resets. +- Explicit-control/articulation conflict failure. +- Precise native controller fallback versus corruption errors; disabled fallback + produces no artifacts. + +## Required integration tests + +- Actual real stdio lead/bass CC1 request + explicit end reset: MIDI and Riffer + native read-back both contain independently expected exact control points. +- All-part request with drum CC: valid guitar/bass natives survive; only drum + native is substituted, combined MIDI preserves requested CC, correct warnings. +- Unsupported Riffer CC and fallback disabled/enabled cases; no mislabeled native + output, dropped messages or partial publication. +- MIDI-only controls retain exact bytes/positions independently parsed by Mido. +- Installed-wheel input/output schema and actual control generation outside the + checkout; portable original template only, no private state in source. +- All existing native/default/alias/transaction/profile/MIDI tests remain. + +Run focused new tests, full current suite, Ruff lint/format, strict mypy, pip +check and affected installed-package tests. Use no blanket expected-failure +markers or weaker assertions. Update MCP contract/usage documentation with a +concrete optional cc_events example and exact native limitations. + +When complete, write your end-of-step report to ./prompts/report_9_fix_controls.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 inside exactly one plain triple-backtick fence. Include actual +stdio/native/MIDI control evidence, exact checks/counts, no-control regression, +explicit fallback results, cleanup and readiness for final native acceptance. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..54ec54f --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,61 @@ +[build-system] +requires = ["setuptools>=84.2,<85", "wheel>=0.48,<0.49"] +build-backend = "setuptools.build_meta" + +[project] +name = "gaj3t-musicgen-riff-groove-builder" +dynamic = ["version"] +description = "Foundation for a local, stdio-only riff and groove MCP server." +readme = "README.md" +requires-python = ">=3.11" +dependencies = [ + "mcp>=1.30,<2", + "pydantic>=2.14.1,<3", + "mido>=1.3.3,<2", +] + +[project.optional-dependencies] +dev = [ + "MIDIUtil>=1.2.1,<2", + "pytest>=9.1.1,<10", + "anyio>=4.15.1,<5", + "ruff>=0.17.1,<0.18", + "mypy>=2.4,<3", + "build>=1.6.1,<2", + "setuptools>=84.2,<85", + "wheel>=0.48,<0.49", + "packaging>=26.3,<27", + "jsonschema>=4.26,<5", + "types-jsonschema>=4.26,<5", +] + +[tool.setuptools.dynamic] +version = {attr = "riff_groove_builder.__version__"} + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.setuptools.package-data] +riff_groove_builder = ["data/profiles/*.json"] + +[tool.pytest.ini_options] +testpaths = ["tests/unit", "tests/integration"] +addopts = "-ra --strict-config --strict-markers" +anyio_mode = "strict" +markers = [ + "integration: offline distribution build and isolated wheel installation", +] + +[tool.ruff] +target-version = "py311" +line-length = 100 +src = ["src"] +extend-exclude = [".test-artifacts", "build", "dist"] + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B"] + +[tool.mypy] +python_version = "3.11" +files = ["src", "tests"] +strict = true diff --git a/src/riff_groove_builder/__init__.py b/src/riff_groove_builder/__init__.py new file mode 100644 index 0000000..75d639c --- /dev/null +++ b/src/riff_groove_builder/__init__.py @@ -0,0 +1,3 @@ +"""Riff-Groove-Builder package foundation; importing does not start services.""" + +__version__ = "0.2.0" diff --git a/src/riff_groove_builder/__main__.py b/src/riff_groove_builder/__main__.py new file mode 100644 index 0000000..5911526 --- /dev/null +++ b/src/riff_groove_builder/__main__.py @@ -0,0 +1,32 @@ +"""Required local output-root configuration and SDK stdio startup.""" + +import argparse +from collections.abc import Sequence +from pathlib import Path + +import anyio + +from riff_groove_builder.errors import DomainError +from riff_groove_builder.server import configure_logging, run_stdio, validate_output_root + + +def main(argv: Sequence[str] | None = None) -> None: + parser = argparse.ArgumentParser(description="Riff-Groove-Builder native/MIDI MCP service") + parser.add_argument("--output-dir", required=True, help="Existing local output directory") + parser.add_argument( + "--sd3-template", type=Path, help="Optional operator-local SD3 3.4.4 SL-DFH project" + ) + arguments = parser.parse_args(argv) + try: + output_root = validate_output_root(arguments.output_dir) + except ValueError as error: + parser.error(str(error)) + configure_logging() + try: + anyio.run(run_stdio, output_root, arguments.sd3_template, backend="asyncio") + except DomainError as error: + parser.error(f"{error.code}: {error.public_message}") + + +if __name__ == "__main__": + main() diff --git a/src/riff_groove_builder/articulations.py b/src/riff_groove_builder/articulations.py new file mode 100644 index 0000000..1fe6bdb --- /dev/null +++ b/src/riff_groove_builder/articulations.py @@ -0,0 +1,424 @@ +"""Compile explicit maps to exact events; no composition, vendor defaults, or IO.""" + +from dataclasses import dataclass, field +from typing import Literal + +from pydantic import ValidationError +from pydantic_core import PydanticSerializationError + +from riff_groove_builder.errors import ( + InvalidRequestError, + SerializationError, + UnsupportedArticulationError, +) +from riff_groove_builder.midi import beats_to_ticks, validate_event_plan +from riff_groove_builder.profiles import ( + Articulation, + CCAction, + InstrumentProfile, + KeyswitchAction, + checked_profile, +) +from riff_groove_builder.schemas import ( + MAX_SCHEDULED_EVENTS, + TICKS_PER_QUARTER, + ControlChangeEvent, + DrumNote, + EventPlan, + EventTrack, + NoteOffEvent, + NoteOnEvent, + Part, + PitchedNote, + ScheduledControl, + ScheduledEvent, + Score, +) + + +class ArticulationCompileError(SerializationError): + public_message = "The score cannot use this profile safely; revise its timing or articulation." + + +def _fail(reason: str) -> ArticulationCompileError: + return ArticulationCompileError(details={"reason": reason}) + + +@dataclass +class _Note: + start: int + end: int + pitch: int + velocity: int + articulation: Articulation + + +@dataclass +class _Group: + articulation: Articulation + notes: list[_Note] + end: int + + +@dataclass +class _Raw: + tick: int + priority: int + kind: Literal["note_on", "note_off", "control_change"] + data: int + value: int + role: Literal["musical_note", "keyswitch", "articulation_control"] + + +@dataclass +class _Builder: + ppq: int + count: int = 0 + required_end: int = 0 + tracks: dict[Part, list[_Raw]] = field(default_factory=dict) + + def add(self, part: Part, event: _Raw) -> None: + if self.count >= MAX_SCHEDULED_EVENTS: + raise _fail("event_budget_exceeded") + self.tracks.setdefault(part, []).append(event) + self.count += 1 + + def pair( + self, + part: Part, + start: int, + end: int, + pitch: int, + velocity: int, + role: Literal["musical_note", "keyswitch"], + ) -> None: + if end <= start: + raise _fail("nonpositive_note_duration") + self.add( + part, + _Raw(start, 30 if role == "musical_note" else 20, "note_on", pitch, velocity, role), + ) + self.add(part, _Raw(end, 0, "note_off", pitch, 0, role)) + + def cc(self, part: Part, tick: int, action: CCAction, *, reset: bool = False) -> None: + value = action.reset_value if reset else action.value + if value is None: + raise _fail("missing_cc_reset") + self.add( + part, + _Raw( + tick, + 10 if reset else 20, + "control_change", + action.controller, + value, + "articulation_control", + ), + ) + + def lead(self, art: Articulation) -> int: + return max((beats_to_ticks(a.lead, self.ppq) for a in art.actions), default=0) + + def pulse_span(self, art: Articulation) -> int: + return max( + ( + beats_to_ticks(a.gate, self.ppq) + for a in art.actions + if isinstance(a, KeyswitchAction) + ), + default=0, + ) + + def select(self, part: Part, art: Articulation, anchor: int) -> int: + finish = anchor + for action in art.actions: + start = anchor - beats_to_ticks(action.lead, self.ppq) + if isinstance(action, CCAction): + self.cc(part, start, action) + else: + end = start + beats_to_ticks(action.gate, self.ppq) + self.pair(part, start, end, action.note, action.velocity, "keyswitch") + finish = max(finish, end) + return finish + + def momentary(self, part: Part, group: _Group) -> int: + release_end = group.end + for action in group.articulation.actions: + offset = beats_to_ticks(action.release_offset, self.ppq) + if isinstance(action, CCAction): + for note in group.notes: + self.cc(part, note.start - beats_to_ticks(action.lead, self.ppq), action) + self.cc(part, group.end + offset, action, reset=True) + release_end = max(release_end, group.end + offset) + elif action.behavior == "hold": + start = group.notes[0].start - beats_to_ticks(action.lead, self.ppq) + end = group.end + offset + if end - start < beats_to_ticks(action.gate, self.ppq): + raise _fail("hold_shorter_than_declared_gate") + self.pair(part, start, end, action.note, action.velocity, "keyswitch") + release_end = max(release_end, end) + else: + for note in group.notes: + start = note.start - beats_to_ticks(action.lead, self.ppq) + end = start + beats_to_ticks(action.gate, self.ppq) + self.pair(part, start, end, action.note, action.velocity, "keyswitch") + release_end = max(release_end, end) + return release_end + + +def _check_grid(profile: InstrumentProfile, ppq: int) -> None: + for art in profile.articulations: + for action in art.actions: + beats_to_ticks(action.lead, ppq) + beats_to_ticks(action.release_offset, ppq) + if isinstance(action, KeyswitchAction): + beats_to_ticks(action.gate, ppq) + + +def _compile_controls( + builder: _Builder, + part: Part, + profile: InstrumentProfile, + notes: list[_Note], +) -> None: + if not any(art.actions for art in profile.articulations): + return + groups: list[_Group] = [] + for note in notes: + if groups and note.start < groups[-1].end: + if groups[-1].articulation.name != note.articulation.name: + raise _fail("incompatible_articulation_overlap") + groups[-1].notes.append(note) + groups[-1].end = max(groups[-1].end, note.end) + else: + groups.append(_Group(note.articulation, [note], note.end)) + normal = profile.resolve_articulation(profile.normal_articulation) + state: str | None = None + active_end: int | None = None + state_ready: int | None = None + physical_free: int | None = None + for group in groups: + art = group.articulation + onset = group.notes[0].start + earliest = onset - builder.lead(art) + if state_ready is not None and onset < state_ready: + raise _fail("restoration_overlaps_next_note") + if art.mode == "latched" and state == art.name: + active_end = max(active_end if active_end is not None else group.end, group.end) + continue + if active_end is not None and earliest < active_end: + raise _fail("control_lead_overlaps_active_notes") + if physical_free is not None and earliest < physical_free: + raise _fail("control_trigger_overlap") + if art.mode == "latched": + physical_free = builder.select(part, art, onset) + state = art.name + state_ready = onset + else: + # A momentary overlay starts from the actual declared normal selection, + # not an assumed startup state or the preceding latched technique. + if state != normal.name: + anchor = earliest - builder.pulse_span(normal) + first = anchor - builder.lead(normal) + if active_end is not None and first < active_end: + raise _fail("normal_setup_overlaps_active_notes") + if physical_free is not None and first < physical_free: + raise _fail("normal_setup_trigger_overlap") + builder.select(part, normal, anchor) + release_end = builder.momentary(part, group) + restore_anchor = release_end + builder.lead(normal) + physical_free = builder.select(part, normal, restore_anchor) + builder.required_end = max(builder.required_end, restore_anchor) + state_ready = restore_anchor + state = normal.name + active_end = group.end + + +def compile_score( + score: Score, + selected_profiles: dict[Part, InstrumentProfile], + *, + ppq: int = TICKS_PER_QUARTER, +) -> EventPlan: + """Compile explicit selections, including explicit test-only maps in tests only.""" + if not isinstance(score, Score): + raise _fail("invalid_score") + try: + checked = Score.model_validate(score.model_dump(mode="python", warnings="error")) + except (ValidationError, PydanticSerializationError): + raise _fail("invalid_score") from None + duration = beats_to_ticks(checked.end.value - checked.start.value, ppq) + if set(selected_profiles) != set(checked.intent.parts): + raise _fail("profile_coverage_mismatch") + profiles = {part: checked_profile(p) for part, p in selected_profiles.items()} + if any(profile.summary.part != part for part, profile in profiles.items()): + raise _fail("profile_part_mismatch") + if len({p.channel for p in profiles.values()}) != len(profiles): + raise _fail("shared_channel") + builder = _Builder(ppq) + for track in checked.tracks: + profile = profiles[track.part] + _check_grid(profile, ppq) + notes: list[_Note] = [] + for note in track.notes: + try: + art = profile.resolve_articulation(note.articulation) + except (KeyError, ValueError): + raise UnsupportedArticulationError( + details={"part": track.part, "reason": "unsupported_articulation"} + ) from None + if isinstance(note, PitchedNote): + playable = profile.playable_range + if playable is None or not playable.low <= note.pitch <= playable.high: + raise _fail("pitch_outside_profile_range") + pitch = note.pitch + elif isinstance(note, DrumNote): + try: + pitch = profile.resolve_voice(note.voice) + except (KeyError, ValueError): + raise _fail("unsupported_drum_voice") from None + start = beats_to_ticks(note.start.value - checked.start.value, ppq) + end = start + beats_to_ticks(note.duration, ppq) + notes.append(_Note(start, end, pitch, art.velocity(note.intensity), art)) + notes.sort(key=lambda n: (n.start, n.end, n.pitch, n.articulation.name, n.velocity)) + for compiled in notes: + builder.pair( + track.part, + compiled.start, + compiled.end, + compiled.pitch, + compiled.velocity, + "musical_note", + ) + _compile_controls(builder, track.part, profile, notes) + preroll = max(0, -min((e.tick for es in builder.tracks.values() for e in es), default=0)) + end_tick = max( + duration + preroll, + builder.required_end + preroll, + max((e.tick + preroll for es in builder.tracks.values() for e in es), default=0), + ) + tracks: list[EventTrack] = [] + for part in checked.intent.parts: + events: list[ScheduledEvent] = [] + for sequence, raw in enumerate(builder.tracks.get(part, [])): + tick = raw.tick + preroll + channel = profiles[part].channel + if raw.kind == "control_change": + event: ScheduledEvent = ControlChangeEvent( + tick=tick, + part=part, + channel=channel, + priority=raw.priority, + sequence=sequence, + controller=raw.data, + value=raw.value, + ) + else: + if raw.role == "articulation_control": + raise _fail("invalid_note_role") + if raw.kind == "note_on": + event = NoteOnEvent( + tick=tick, + part=part, + channel=channel, + priority=raw.priority, + sequence=sequence, + role=raw.role, + note=raw.data, + velocity=raw.value, + ) + else: + event = NoteOffEvent( + tick=tick, + part=part, + channel=channel, + priority=raw.priority, + sequence=sequence, + role=raw.role, + note=raw.data, + velocity=raw.value, + ) + events.append(event) + tracks.append(EventTrack(part=part, events=sorted(events, key=lambda e: e.ordering_key))) + plan = EventPlan( + score=checked, + ticks_per_quarter=ppq, + musical_start_tick=preroll, + musical_end_tick=duration + preroll, + end_tick=end_tick, + tracks=tracks, + ) + validate_event_plan(plan) + return plan + + +def apply_scheduled_controls( + plan: EventPlan, + controls: list[ScheduledControl], + profiles: dict[Part, InstrumentProfile], +) -> EventPlan: + """Append exact explicit points without changing compiled notes, switches or offsets.""" + if not controls: + return plan + validate_event_plan(plan) + if sum(len(track.events) for track in plan.tracks) + len(controls) > MAX_SCHEDULED_EVENTS: + raise InvalidRequestError(details={"field": "cc_events", "reason": "event_budget_exceeded"}) + additions: dict[Part, list[ScheduledControl]] = {} + seen: set[tuple[Part, int, int]] = set() + for cc in controls: + if cc.part not in plan.score.intent.parts: + raise InvalidRequestError( + details={"field": "cc_events", "part": cc.part, "reason": "unselected_part"} + ) + if cc.beat.value > plan.score.intent.duration_beats: + raise InvalidRequestError( + details={"field": "cc_events", "part": cc.part, "reason": "beat_after_musical_end"} + ) + ticks = cc.beat.value * plan.ticks_per_quarter + if ticks.denominator != 1: + raise InvalidRequestError(details={"field": "cc_events", "reason": "off_grid_beats"}) + key = cc.part, plan.musical_start_tick + ticks.numerator, cc.controller + if key in seen: + raise InvalidRequestError( + details={"field": "cc_events", "reason": "duplicate_control_point"} + ) + seen.add(key) + additions.setdefault(cc.part, []).append(cc) + tracks = [] + for track in plan.tracks: + events = list(track.events) + existing = {(e.tick, e.controller) for e in events if isinstance(e, ControlChangeEvent)} + sequence = max((e.sequence for e in events), default=-1) + 1 + for cc in additions.get(track.part, []): + tick = plan.musical_start_tick + beats_to_ticks(cc.beat, plan.ticks_per_quarter) + if (tick, cc.controller) in existing: + raise InvalidRequestError( + details={ + "field": "cc_events", + "reason": "articulation_control_conflict", + "part": track.part, + "tick": tick, + "controller": cc.controller, + "action": "Remove or move this CC point; the articulation owns it.", + } + ) + events.append( + ControlChangeEvent( + tick=tick, + part=track.part, + channel=profiles[track.part].channel, + priority=10, + sequence=sequence, + controller=cc.controller, + value=cc.value, + ) + ) + sequence += 1 + tracks.append( + EventTrack(part=track.part, events=sorted(events, key=lambda e: e.ordering_key)) + ) + result = EventPlan.model_validate( + {**plan.model_dump(), "tracks": [track.model_dump() for track in tracks]} + ) + validate_event_plan(result) + return result diff --git a/src/riff_groove_builder/compose.py b/src/riff_groove_builder/compose.py new file mode 100644 index 0000000..1db0457 --- /dev/null +++ b/src/riff_groove_builder/compose.py @@ -0,0 +1,332 @@ +"""Original bounded templates on a common exact grid, using only explicit profile facts.""" + +from fractions import Fraction +from random import Random + +from pydantic import ValidationError +from pydantic_core import PydanticSerializationError + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.errors import SerializationError, UnsupportedArticulationError +from riff_groove_builder.hybrid import materialize +from riff_groove_builder.midi import beats_to_ticks +from riff_groove_builder.pitch import validate_voicing +from riff_groove_builder.profiles import InstrumentProfile, checked_profile +from riff_groove_builder.schemas import ( + MAX_SCHEDULED_EVENTS, + TICKS_PER_QUARTER, + DrumNote, + LogicalNote, + MusicalIntent, + Part, + PitchedNote, + PositiveBeat, + RationalBeat, + Score, + ScoreTrack, +) + +_STEPS = {"quarter": Fraction(1), "eighth": Fraction(1, 2), "sixteenth": Fraction(1, 4)} +_ROOTS = { + name: index + for index, name in enumerate(("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B")) +} + + +class CompositionError(SerializationError): + public_message = "The intent cannot be composed safely; revise the identified intent or map." + + +def _fail(reason: str, part: Part | None = None) -> CompositionError: + return CompositionError(details={"reason": reason, "part": part}) + + +def _beat(value: Fraction) -> RationalBeat: + return RationalBeat(numerator=value.numerator, denominator=value.denominator) + + +def _duration(value: Fraction) -> PositiveBeat: + return PositiveBeat(numerator=value.numerator, denominator=value.denominator) + + +def _palette(intent: MusicalIntent, profile: InstrumentProfile, part: Part) -> list[int]: + root, mode = intent.key.split() + intervals = ( + (0, 7) + if part == "bass" + else (0, 2, 4, 5, 7, 9, 11) + if mode == "major" + else (0, 2, 3, 5, 7, 8, 10) + ) + playable = profile.playable_range + if playable is None: + raise _fail("pitched_range_required", part) + candidates = [ + pitch + for pitch in range(playable.low, playable.high + 1) + if pitch % 12 == _ROOTS[root] and pitch + max(intervals) <= playable.high + ] + if not candidates: + raise _fail("range_cannot_fit_root_fifth_or_complete_lead_scale", part) + anchor = min(candidates, key=lambda pitch: (abs(pitch - (40 if part == "bass" else 64)), pitch)) + return [anchor + interval for interval in intervals] + + +def _compose_phrase( + intent: MusicalIntent, profiles: dict[Part, InstrumentProfile], ppq: int +) -> Score: + phrase = intent.phrase_plan + assert phrase is not None + part = phrase.part + profile = profiles[part] + playable = profile.playable_range + if playable is None: + raise _fail("pitched_range_required", part) + root = _ROOTS[intent.key.split()[0]] + candidates = [ + pitch + for pitch in range(playable.low, playable.high + 1) + if pitch % 12 == root + and ( + profile.riffer is None + or any( + 0 <= pitch - string.open_note <= string.max_fret + for string in profile.riffer.strings + ) + ) + ] + if not candidates: + raise _fail("range_cannot_fit_low_tonic", part) + pitch = min(candidates, key=lambda value: (abs(value - 40), value)) + if len(phrase.notes) * 2 > MAX_SCHEDULED_EVENTS: + raise _fail("note_pair_event_budget_exceeded", part) + beats_to_ticks(intent.duration_beats, ppq) + rng = Random(intent.seed + (1 if part == "bass" else 0)) + notes: list[LogicalNote] = [] + for timing in phrase.notes: + beats_to_ticks(timing.start.value, ppq) + beats_to_ticks(timing.duration.value, ppq) + try: + articulation = profile.resolve_articulation(timing.technique).name + except (KeyError, ValueError): + raise UnsupportedArticulationError( + details={ + "part": part, + "profile_id": profile.id, + "technique": timing.technique, + "reason": "unsupported_articulation", + } + ) from None + notes.append( + PitchedNote( + part=part, + pitch=pitch, + start=timing.start, + duration=timing.duration, + articulation=articulation, + intensity=( + timing.intensity if timing.intensity is not None else 0.5 + rng.randrange(3) / 8 + ), + ) + ) + return Score( + intent=intent, + start=_beat(Fraction(0)), + end=_beat(intent.duration_beats), + tracks=[ScoreTrack(part=part, notes=notes)], + ) + + +def _compose_explicit( + intent: MusicalIntent, profiles: dict[Part, InstrumentProfile], ppq: int +) -> Score: + plan = intent.explicit_plan + assert plan is not None + part = plan.part + profile = profiles[part] + rng = Random(intent.seed + (1 if part == "bass" else 0)) + notes: list[LogicalNote] = [] + beats_to_ticks(intent.duration_beats, ppq) + for attack in plan.attacks: + beats_to_ticks(attack.start.value, ppq) + beats_to_ticks(attack.duration.value, ppq) + try: + validate_voicing(tuple(attack.pitches), profile) + except ValueError: + raise _fail("explicit_voicing_outside_profile_range_or_tuning", part) from None + try: + articulation = profile.resolve_articulation(attack.technique).name + except (KeyError, ValueError): + raise UnsupportedArticulationError( + details={ + "part": part, + "profile_id": profile.id, + "technique": attack.technique, + "reason": "unsupported_articulation", + } + ) from None + intensity = attack.intensity if attack.intensity is not None else 0.5 + rng.randrange(3) / 8 + notes.extend( + PitchedNote( + part=part, + pitch=pitch, + start=attack.start, + duration=attack.duration, + articulation=articulation, + intensity=intensity, + ) + for pitch in attack.pitches + ) + score = Score( + intent=intent, + start=_beat(Fraction(0)), + end=_beat(intent.duration_beats), + tracks=[ScoreTrack(part=part, notes=notes)], + ) + # The compiler is authoritative for the expanded tones PLUS articulation controls. + compile_score(score, profiles, ppq=ppq) + return score + + +def compose_score( + intent: MusicalIntent, + selected_profiles: dict[Part, InstrumentProfile], + *, + ppq: int = TICKS_PER_QUARTER, +) -> Score: + """Compose selected parts; ppq must also be passed to compile_score if nondefault.""" + try: + intent = MusicalIntent.model_validate(intent.model_dump(mode="python", warnings="error")) + except (ValidationError, PydanticSerializationError, AttributeError): + raise _fail("invalid_intent_model") from None + if set(selected_profiles) != set(intent.parts): + raise _fail("profile_coverage_mismatch") + profiles = {part: checked_profile(profile) for part, profile in selected_profiles.items()} + if any(profile.summary.part != part for part, profile in profiles.items()): + raise _fail("profile_part_mismatch") + if len({profile.channel for profile in profiles.values()}) != len(profiles): + raise _fail("shared_channel") + intent = materialize(intent, profiles) + if intent.explicit_plan is not None: + return _compose_explicit(intent, profiles, ppq) + if intent.phrase_plan is not None: + return _compose_phrase(intent, profiles, ppq) + + terms = set(intent.rhythm_terms) + if terms - {*_STEPS, "rock", "metal", "rests", "no_rests"}: + raise _fail("unsupported_rhythm_term") + subdivisions = terms & _STEPS.keys() + templates = terms & {"rock", "metal"} + if len(subdivisions) > 1 or len(templates) > 1 or {"rests", "no_rests"} <= terms: + raise _fail("conflicting_rhythm_terms") + step = _STEPS[next(iter(subdivisions), "eighth")] + metal = "metal" in templates + bar = intent.time_signature.beats_per_bar + slots = -(-bar // step) + active_slots = slots - (1 if "rests" in terms else 0) + pulse = max(step, Fraction(4, intent.time_signature.denominator)) + stride = int(pulse / step) + drum_hits = active_slots * 2 if metal else active_slots + -(-active_slots // stride) + notes_per_bar = sum(drum_hits if part == "drums" else active_slots for part in intent.parts) + if notes_per_bar * intent.bars * 2 > MAX_SCHEDULED_EVENTS: + raise _fail("note_pair_event_budget_exceeded") + + # Check all slot lengths before allocating notes, including a partial final slot. + beats_to_ticks(intent.duration_beats, ppq) + for index in range(slots): + offset = index * step + length = min(step, bar - offset) + beats_to_ticks(offset, ppq) + beats_to_ticks(length, ppq) + if "drums" in intent.parts: + beats_to_ticks(min(length, Fraction(1, 4)), ppq) + + articulations: dict[Part, str] = {} + palettes: dict[Part, list[int]] = {} + if intent.techniques == ["palm_mute"] and intent.parts == ["drums"]: + raise UnsupportedArticulationError( + details={"part": "drums", "technique": "palm_mute", "reason": "pitched_parts_required"} + ) + for part in intent.parts: + profile = profiles[part] + requested = intent.techniques or ["normal"] + if part == "drums" and requested == ["palm_mute"]: + requested = ["normal"] + names: list[str] = [] + for technique in requested: + try: + names.append(profile.resolve_articulation(technique).name) + except (KeyError, ValueError): + raise UnsupportedArticulationError( + details={ + "part": part, + "profile_id": profile.id, + "technique": technique, + "reason": "unsupported_articulation", + } + ) from None + if len(set(names)) != 1: + raise _fail("multiple_global_techniques_require_an_explicit_schedule", part) + articulations[part] = names[0] + if part == "drums": + for voice in ("kick", "snare", "closed_hat"): + try: + profile.resolve_voice(voice) + except (KeyError, ValueError): + raise CompositionError( + details={ + "reason": "required_drum_alias_missing", + "part": part, + "voice": voice, + } + ) from None + else: + palettes[part] = _palette(intent, profile, part) + + tracks: list[ScoreTrack] = [] + offsets: dict[Part, int] = {"lead": 0, "bass": 1, "drums": 2} + for part in intent.parts: + rng = Random(intent.seed + offsets[part]) + notes: list[LogicalNote] = [] + for bar_index in range(intent.bars): + for index in range(active_slots): + offset = index * step + start = bar_index * bar + offset + length = min(step, bar - offset) + intensity = 0.5 + rng.randrange(3) / 8 + if part == "drums": + voices = ["closed_hat"] + if offset % pulse == 0: + voices.append("kick" if int(offset / pulse) % 2 == 0 else "snare") + elif metal: + voices.append("kick") + notes.extend( + DrumNote( + start=_beat(start), + duration=_duration(min(length, Fraction(1, 4))), + intensity=intensity, + articulation=articulations[part], + voice=voice, + ) + for voice in voices + ) + else: + if part == "bass": + degree = (0, 0, 1, 0)[index % 4] if metal else index % 2 + else: + pattern = (0, 0, 4, 1) if metal else (0, 2, 4, 6) + degree = 0 if index == 0 else (pattern[index % 4] + rng.randrange(2)) % 7 + notes.append( + PitchedNote( + part=part, + start=_beat(start), + duration=_duration(length), + intensity=intensity, + articulation=articulations[part], + pitch=palettes[part][degree], + ) + ) + tracks.append(ScoreTrack(part=part, notes=notes)) + return Score( + intent=intent, start=_beat(Fraction(0)), end=_beat(intent.duration_beats), tracks=tracks + ) diff --git a/src/riff_groove_builder/data/__init__.py b/src/riff_groove_builder/data/__init__.py new file mode 100644 index 0000000..e983aa2 --- /dev/null +++ b/src/riff_groove_builder/data/__init__.py @@ -0,0 +1 @@ +"""Packaged declarative resources; no vendor mapping evidence is bundled.""" diff --git a/src/riff_groove_builder/data/profiles/__init__.py b/src/riff_groove_builder/data/profiles/__init__.py new file mode 100644 index 0000000..8b84a70 --- /dev/null +++ b/src/riff_groove_builder/data/profiles/__init__.py @@ -0,0 +1,10 @@ +"""Standard defaults and explicitly selected evidence-backed native subsets.""" + +PROFILE_RESOURCES: tuple[str, ...] = ( + "standard-midi-lead-v1.json", + "standard-midi-bass-v1.json", + "general-midi-percussion-v1.json", + "ample-metal-eclipse-4.0.1-riffer-v1.json", + "ample-metal-ray5-4.1.0-riffer-v1.json", + "toontrack-sd3-3.4.4-core-v1.json", +) diff --git a/src/riff_groove_builder/data/profiles/ample-metal-eclipse-4.0.1-riffer-v1.json b/src/riff_groove_builder/data/profiles/ample-metal-eclipse-4.0.1-riffer-v1.json new file mode 100644 index 0000000..b48166b --- /dev/null +++ b/src/riff_groove_builder/data/profiles/ample-metal-eclipse-4.0.1-riffer-v1.json @@ -0,0 +1,119 @@ +{ + "schema_version": "1", + "id": "ample.ame.4.0.1.riffer.v1", + "summary": { + "id": "ample.ame.4.0.1.riffer.v1", + "part": "lead", + "mapping_kind": "instrument", + "instrument": "eclips", + "product_name": "Ample Metal Eclipse", + "product_version": "4.0.1", + "mapping_version": "riffer-subset-2", + "midi_available": true, + "native_format": "griff", + "native_available": true, + "supported_articulations": ["normal", "palm_mute", "pinch_harmonic"], + "limitations": [ + "Default lead Riffer XML 2.1 subset; real native/MIDI service output is validated, but plugin/Cubase acceptance remains unrun.", + "Explicit C1/G1/C2/F2/A2/D3 tuning (MIDI 36/43/48/53/57/62); configure the receiver accordingly, not the observed drop variant.", + "Normal, palm mute and pinch harmonic only, frets 0-22; no legato, effects, strums or named vibrato technique.", + "Normal C0 uses velocities 64-126, avoiding muted layers and 127 Pop/PH; D0 palm mute uses 1-127 with lower velocity increasing mute depth.", + "PH uses dedicated G0/31 and native PH, range C1-C5 (36-84); observed local velocities 80-100 are encoding evidence, not hard limits. Positive 1-127 interpolation is generator policy.", + "Channels, same-tick switch ordering, pulse gate and interpolation are generator policy, not vendor timing guarantees.", + "Native pre-roll and control tails are rejected, not shifted or truncated; compiled discrete CC1 is preserved without fabricated resets." + ] + }, + "provenance": { + "status": "verified_subset", + "product_version": "4.0.1", + "mapping_version": "riffer-subset-2", + "target_build": "AME VST3 ProductVersion 4.0.1", + "mapping_preset": "Explicit six-string Riffer subset; no factory preset content", + "sources": [ + { + "kind": "official_public", + "reference": "https://www.amplesound.net/en/Main_Panel_Manual-AME.pdf", + "aspects": ["identity", "actions", "velocity"] + }, + { + "kind": "official_public", + "reference": "https://www.amplesound.net/en/Guitar_Riffer.pdf", + "aspects": ["actions"] + }, + { + "kind": "lawful_local", + "reference": "LOCAL-AME-401-RIFF21-20261019", + "aspects": ["identity", "range_or_voices", "actions", "velocity"] + }, + { + "kind": "lawful_local", + "reference": "LOCAL-AME-401-PH-20261020: read-only aggregate, 17 PH notes; velocities 80-100; pitches 49-73; no sequences retained", + "aspects": ["identity", "actions", "range_or_voices", "velocity"] + }, + { + "kind": "generator_policy", + "reference": "docs/articulation-profiles.md#riffer-subset-policy-v1", + "aspects": ["channels", "state_reset", "timing", "velocity"] + } + ], + "limitations": [ + "Default lead Riffer XML 2.1 subset; real native/MIDI service output is validated, but plugin/Cubase acceptance remains unrun.", + "Explicit C1/G1/C2/F2/A2/D3 tuning (MIDI 36/43/48/53/57/62); configure the receiver accordingly, not the observed drop variant.", + "Normal, palm mute and pinch harmonic only, frets 0-22; no legato, effects, strums or named vibrato technique.", + "Normal C0 uses velocities 64-126, avoiding muted layers and 127 Pop/PH; D0 palm mute uses 1-127 with lower velocity increasing mute depth.", + "PH uses dedicated G0/31 and native PH, range C1-C5 (36-84); observed local velocities 80-100 are encoding evidence, not hard limits. Positive 1-127 interpolation is generator policy.", + "Channels, same-tick switch ordering, pulse gate and interpolation are generator policy, not vendor timing guarantees.", + "Native pre-roll and control tails are rejected, not shifted or truncated; compiled discrete CC1 is preserved without fabricated resets." + ] + }, + "default": true, + "channel": 0, + "playable_range": {"low": 36, "high": 84}, + "drum_voices": [], + "normal_articulation": "normal", + "articulations": [ + { + "name": "normal", + "aliases": ["sustain"], + "mode": "latched", + "actions": [ + {"kind": "keyswitch", "note": 24, "velocity": 100, "behavior": "pulse", "lead": {"numerator": 0}, "gate": {"numerator": 1, "denominator": 32}, "release_offset": {"numerator": 0}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 64, "velocity_high": 126}] + }, + { + "name": "palm_mute", + "aliases": ["pm"], + "mode": "latched", + "actions": [ + {"kind": "keyswitch", "note": 26, "velocity": 100, "behavior": "pulse", "lead": {"numerator": 0}, "gate": {"numerator": 1, "denominator": 32}, "release_offset": {"numerator": 0}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 1, "velocity_high": 127}] + }, + { + "name": "pinch_harmonic", + "aliases": ["ph"], + "mode": "latched", + "actions": [ + {"kind": "keyswitch", "note": 31, "velocity": 100, "behavior": "pulse", "lead": {"numerator": 0}, "gate": {"numerator": 1, "denominator": 32}, "release_offset": {"numerator": 0}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 1, "velocity_high": 127}] + } + ], + "riffer": { + "layout_version": "2.1", + "ppq": 480, + "instrument": "AME", + "extension": "griff", + "strings": [ + {"id": 6, "open_note": 36, "max_fret": 22}, + {"id": 5, "open_note": 43, "max_fret": 22}, + {"id": 4, "open_note": 48, "max_fret": 22}, + {"id": 3, "open_note": 53, "max_fret": 22}, + {"id": 2, "open_note": 57, "max_fret": 22}, + {"id": 1, "open_note": 62, "max_fret": 22} + ], + "articulations": {"normal": "Sus", "palm_mute": "PM", "pinch_harmonic": "PH"}, + "controllers": [1] + } +} diff --git a/src/riff_groove_builder/data/profiles/ample-metal-ray5-4.1.0-riffer-v1.json b/src/riff_groove_builder/data/profiles/ample-metal-ray5-4.1.0-riffer-v1.json new file mode 100644 index 0000000..3fba9b7 --- /dev/null +++ b/src/riff_groove_builder/data/profiles/ample-metal-ray5-4.1.0-riffer-v1.json @@ -0,0 +1,100 @@ +{ + "schema_version": "1", + "id": "ample.amr.4.1.0.riffer.v1", + "summary": { + "id": "ample.amr.4.1.0.riffer.v1", + "part": "bass", + "mapping_kind": "instrument", + "instrument": "ray", + "product_name": "Ample Metal Ray5", + "product_version": "4.1.0", + "mapping_version": "riffer-subset-1", + "midi_available": true, + "native_format": "briff", + "native_available": true, + "supported_articulations": ["normal", "palm_mute"], + "limitations": [ + "Default bass Riffer XML 2.1 subset; real native/MIDI service output is validated, but plugin/Cubase acceptance remains unrun.", + "Explicit B0/E1/A1/D2/G2 tuning (MIDI 35/40/45/50/55); configure the receiver accordingly, not observed drop variants.", + "Normal and palm mute only, frets 0-19; no accent, dead notes, legato, effects or named vibrato technique.", + "Both MIDI techniques use C0=24: normal velocities 64-126, palm mute 32-63 (native PMP, not D0 PM); never velocity 127 accent or less than 32 dead note.", + "Channels, same-tick switch ordering, pulse gate and interpolation are generator policy; native pre-roll/tails are rejected and discrete CC1 preserved." + ] + }, + "provenance": { + "status": "verified_subset", + "product_version": "4.1.0", + "mapping_version": "riffer-subset-1", + "target_build": "AMR VST3 ProductVersion 4.1.0", + "mapping_preset": "Explicit five-string Riffer subset; no factory preset content", + "sources": [ + { + "kind": "official_public", + "reference": "https://www.amplesound.net/en/Main_Panel_Manual-AMR.pdf", + "aspects": ["identity", "actions", "velocity"] + }, + { + "kind": "official_public", + "reference": "https://www.amplesound.net/en/Guitar_Riffer.pdf", + "aspects": ["actions"] + }, + { + "kind": "lawful_local", + "reference": "LOCAL-AMR-410-RIFF21-20261019", + "aspects": ["identity", "range_or_voices", "actions", "velocity"] + }, + { + "kind": "generator_policy", + "reference": "docs/articulation-profiles.md#riffer-subset-policy-v1", + "aspects": ["channels", "state_reset", "timing", "velocity"] + } + ], + "limitations": [ + "Default bass Riffer XML 2.1 subset; real native/MIDI service output is validated, but plugin/Cubase acceptance remains unrun.", + "Explicit B0/E1/A1/D2/G2 tuning (MIDI 35/40/45/50/55); configure the receiver accordingly, not observed drop variants.", + "Normal and palm mute only, frets 0-19; no accent, dead notes, legato, effects or named vibrato technique.", + "Both MIDI techniques use C0=24: normal velocities 64-126, palm mute 32-63 (native PMP, not D0 PM); never velocity 127 accent or less than 32 dead note.", + "Channels, same-tick switch ordering, pulse gate and interpolation are generator policy; native pre-roll/tails are rejected and discrete CC1 preserved." + ] + }, + "default": true, + "channel": 1, + "playable_range": {"low": 35, "high": 74}, + "drum_voices": [], + "normal_articulation": "normal", + "articulations": [ + { + "name": "normal", + "aliases": ["sustain"], + "mode": "latched", + "actions": [ + {"kind": "keyswitch", "note": 24, "velocity": 100, "behavior": "pulse", "lead": {"numerator": 0}, "gate": {"numerator": 1, "denominator": 32}, "release_offset": {"numerator": 0}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 64, "velocity_high": 126}] + }, + { + "name": "palm_mute", + "aliases": ["pm"], + "mode": "latched", + "actions": [ + {"kind": "keyswitch", "note": 24, "velocity": 100, "behavior": "pulse", "lead": {"numerator": 0}, "gate": {"numerator": 1, "denominator": 32}, "release_offset": {"numerator": 0}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 32, "velocity_high": 63}] + } + ], + "riffer": { + "layout_version": "2.1", + "ppq": 480, + "instrument": "AMR", + "extension": "briff", + "strings": [ + {"id": 5, "open_note": 35, "max_fret": 19}, + {"id": 4, "open_note": 40, "max_fret": 19}, + {"id": 3, "open_note": 45, "max_fret": 19}, + {"id": 2, "open_note": 50, "max_fret": 19}, + {"id": 1, "open_note": 55, "max_fret": 19} + ], + "articulations": {"normal": "Sus", "palm_mute": "PMP"}, + "controllers": [1] + } +} diff --git a/src/riff_groove_builder/data/profiles/general-midi-percussion-v1.json b/src/riff_groove_builder/data/profiles/general-midi-percussion-v1.json new file mode 100644 index 0000000..eaa7587 --- /dev/null +++ b/src/riff_groove_builder/data/profiles/general-midi-percussion-v1.json @@ -0,0 +1,115 @@ +{ + "schema_version": "1", + "id": "standard.gm-drums.v1", + "summary": { + "id": "standard.gm-drums.v1", + "part": "drums", + "mapping_kind": "standard_midi", + "instrument": "sd3", + "product_name": "General MIDI Level 1 percussion fallback (NOT a verified SD3 map)", + "product_version": "General MIDI Level 1", + "mapping_version": "standard-fallback-1", + "midi_available": true, + "native_format": "sd3p", + "native_available": false, + "supported_articulations": ["normal"], + "limitations": [ + "Standard MIDI fallback only; NOT verified Eclips/Ray/SD3 maps or application compatibility.", + "instrument identifies intended routing only; zero-based channel 9 is explicit GM percussion routing, NOT an SD3 default-map claim.", + "Normal/sustain only; no keyswitches, CCs, program/bank changes, GM initialization, or vendor velocity layers.", + "Explicit standard fallback profile, not an SD3 native map; receiver setup, choke behavior and plugin/Cubase acceptance remain external." + ] + }, + "provenance": { + "status": "standard_midi", + "product_version": "General MIDI Level 1", + "mapping_version": "standard-fallback-1", + "target_build": "Not applicable: GM Level 1 standard, no installed SD3 build verified", + "mapping_preset": "GM Level 1 percussion key map; generator routing policy v1; no SD3 preset", + "sources": [ + { + "kind": "standard_public", + "reference": "https://midi.org/general-midi-level-1", + "aspects": ["identity"] + }, + { + "kind": "standard_public", + "reference": "https://computermusicresource.com/GM.Percussion.KeyMap.html", + "aspects": ["range_or_voices", "channels"] + }, + { + "kind": "generator_policy", + "reference": "docs/articulation-profiles.md#standard-fallback-policy-v1", + "aspects": ["channels", "actions", "state_reset", "timing", "velocity"] + } + ], + "limitations": [ + "Standard MIDI fallback only; NOT verified Eclips/Ray/SD3 maps or application compatibility.", + "instrument identifies intended routing only; zero-based channel 9 is explicit GM percussion routing, NOT an SD3 default-map claim.", + "Normal/sustain only; no keyswitches, CCs, program/bank changes, GM initialization, or vendor velocity layers.", + "Explicit standard fallback profile, not an SD3 native map; receiver setup, choke behavior and plugin/Cubase acceptance remain external." + ] + }, + "default": false, + "channel": 9, + "playable_range": null, + "drum_voices": [ + {"name": "acoustic_bass_drum", "aliases": [], "note": 35}, + {"name": "bass_drum_1", "aliases": ["kick"], "note": 36}, + {"name": "side_stick", "aliases": [], "note": 37}, + {"name": "acoustic_snare", "aliases": ["snare"], "note": 38}, + {"name": "hand_clap", "aliases": ["clap"], "note": 39}, + {"name": "electric_snare", "aliases": [], "note": 40}, + {"name": "low_floor_tom", "aliases": [], "note": 41}, + {"name": "closed_hi_hat", "aliases": ["closed_hat", "hihat"], "note": 42}, + {"name": "high_floor_tom", "aliases": [], "note": 43}, + {"name": "pedal_hi_hat", "aliases": ["pedal_hat"], "note": 44}, + {"name": "low_tom", "aliases": [], "note": 45}, + {"name": "open_hi_hat", "aliases": ["open_hat"], "note": 46}, + {"name": "low_mid_tom", "aliases": [], "note": 47}, + {"name": "hi_mid_tom", "aliases": [], "note": 48}, + {"name": "crash_cymbal_1", "aliases": ["crash"], "note": 49}, + {"name": "high_tom", "aliases": [], "note": 50}, + {"name": "ride_cymbal_1", "aliases": ["ride"], "note": 51}, + {"name": "chinese_cymbal", "aliases": [], "note": 52}, + {"name": "ride_bell", "aliases": [], "note": 53}, + {"name": "tambourine", "aliases": [], "note": 54}, + {"name": "splash_cymbal", "aliases": [], "note": 55}, + {"name": "cowbell", "aliases": [], "note": 56}, + {"name": "crash_cymbal_2", "aliases": [], "note": 57}, + {"name": "vibraslap", "aliases": [], "note": 58}, + {"name": "ride_cymbal_2", "aliases": [], "note": 59}, + {"name": "hi_bongo", "aliases": [], "note": 60}, + {"name": "low_bongo", "aliases": [], "note": 61}, + {"name": "mute_hi_conga", "aliases": [], "note": 62}, + {"name": "open_hi_conga", "aliases": [], "note": 63}, + {"name": "low_conga", "aliases": [], "note": 64}, + {"name": "high_timbale", "aliases": [], "note": 65}, + {"name": "low_timbale", "aliases": [], "note": 66}, + {"name": "high_agogo", "aliases": [], "note": 67}, + {"name": "low_agogo", "aliases": [], "note": 68}, + {"name": "cabasa", "aliases": [], "note": 69}, + {"name": "maracas", "aliases": [], "note": 70}, + {"name": "short_whistle", "aliases": [], "note": 71}, + {"name": "long_whistle", "aliases": [], "note": 72}, + {"name": "short_guiro", "aliases": [], "note": 73}, + {"name": "long_guiro", "aliases": [], "note": 74}, + {"name": "claves", "aliases": [], "note": 75}, + {"name": "hi_wood_block", "aliases": [], "note": 76}, + {"name": "low_wood_block", "aliases": [], "note": 77}, + {"name": "mute_cuica", "aliases": [], "note": 78}, + {"name": "open_cuica", "aliases": [], "note": 79}, + {"name": "mute_triangle", "aliases": [], "note": 80}, + {"name": "open_triangle", "aliases": [], "note": 81} + ], + "normal_articulation": "normal", + "articulations": [ + { + "name": "normal", + "aliases": ["sustain"], + "mode": "latched", + "actions": [], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 1, "velocity_high": 127}] + } + ] +} diff --git a/src/riff_groove_builder/data/profiles/standard-midi-bass-v1.json b/src/riff_groove_builder/data/profiles/standard-midi-bass-v1.json new file mode 100644 index 0000000..eebca11 --- /dev/null +++ b/src/riff_groove_builder/data/profiles/standard-midi-bass-v1.json @@ -0,0 +1,62 @@ +{ + "schema_version": "1", + "id": "standard.bass.v1", + "summary": { + "id": "standard.bass.v1", + "part": "bass", + "mapping_kind": "standard_midi", + "instrument": "ray", + "product_name": "Standard MIDI pitched bass fallback (NOT a verified Ray map)", + "product_version": "MIDI 1.0", + "mapping_version": "standard-fallback-1", + "midi_available": true, + "native_format": "briff", + "native_available": false, + "supported_articulations": ["normal"], + "limitations": [ + "Standard MIDI fallback only; NOT verified Eclips/Ray/SD3 maps or application compatibility.", + "instrument identifies intended routing only; channel 1 and full note range 0-127 are generator policy, not a Ray playable range.", + "Normal/sustain only; no keyswitches, CCs, program/bank changes, GM initialization, or vendor velocity layers.", + "Explicit standard fallback profile, not a native target mapping; receiver setup and plugin/Cubase acceptance remain external." + ] + }, + "provenance": { + "status": "standard_midi", + "product_version": "MIDI 1.0", + "mapping_version": "standard-fallback-1", + "target_build": "Not applicable: MIDI standard, no installed vendor build verified", + "mapping_preset": "Generator routing policy v1; no vendor preset", + "sources": [ + { + "kind": "standard_public", + "reference": "https://midi.org/summary-of-midi-1-0-messages", + "aspects": ["identity", "range_or_voices"] + }, + { + "kind": "generator_policy", + "reference": "docs/articulation-profiles.md#standard-fallback-policy-v1", + "aspects": ["channels", "actions", "state_reset", "timing", "velocity"] + } + ], + "limitations": [ + "Standard MIDI fallback only; NOT verified Eclips/Ray/SD3 maps or application compatibility.", + "instrument identifies intended routing only; channel 1 and full note range 0-127 are generator policy, not a Ray playable range.", + "Normal/sustain only; no keyswitches, CCs, program/bank changes, GM initialization, or vendor velocity layers.", + "Explicit standard fallback profile, not a native target mapping; receiver setup and plugin/Cubase acceptance remain external." + ] + }, + "default": false, + "channel": 1, + "playable_range": {"low": 0, "high": 127}, + "drum_voices": [], + "normal_articulation": "normal", + "articulations": [ + { + "name": "normal", + "aliases": ["sustain"], + "mode": "latched", + "actions": [], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 1, "velocity_high": 127}] + } + ] +} diff --git a/src/riff_groove_builder/data/profiles/standard-midi-lead-v1.json b/src/riff_groove_builder/data/profiles/standard-midi-lead-v1.json new file mode 100644 index 0000000..4723668 --- /dev/null +++ b/src/riff_groove_builder/data/profiles/standard-midi-lead-v1.json @@ -0,0 +1,62 @@ +{ + "schema_version": "1", + "id": "standard.lead.v1", + "summary": { + "id": "standard.lead.v1", + "part": "lead", + "mapping_kind": "standard_midi", + "instrument": "eclips", + "product_name": "Standard MIDI pitched lead fallback (NOT a verified Eclips map)", + "product_version": "MIDI 1.0", + "mapping_version": "standard-fallback-1", + "midi_available": true, + "native_format": "griff", + "native_available": false, + "supported_articulations": ["normal"], + "limitations": [ + "Standard MIDI fallback only; NOT verified Eclips/Ray/SD3 maps or application compatibility.", + "instrument identifies intended routing only; channel 0 and full note range 0-127 are generator policy, not an Eclips playable range.", + "Normal/sustain only; no keyswitches, CCs, program/bank changes, GM initialization, or vendor velocity layers.", + "Explicit standard fallback profile, not a native target mapping; receiver setup and plugin/Cubase acceptance remain external." + ] + }, + "provenance": { + "status": "standard_midi", + "product_version": "MIDI 1.0", + "mapping_version": "standard-fallback-1", + "target_build": "Not applicable: MIDI standard, no installed vendor build verified", + "mapping_preset": "Generator routing policy v1; no vendor preset", + "sources": [ + { + "kind": "standard_public", + "reference": "https://midi.org/summary-of-midi-1-0-messages", + "aspects": ["identity", "range_or_voices"] + }, + { + "kind": "generator_policy", + "reference": "docs/articulation-profiles.md#standard-fallback-policy-v1", + "aspects": ["channels", "actions", "state_reset", "timing", "velocity"] + } + ], + "limitations": [ + "Standard MIDI fallback only; NOT verified Eclips/Ray/SD3 maps or application compatibility.", + "instrument identifies intended routing only; channel 0 and full note range 0-127 are generator policy, not an Eclips playable range.", + "Normal/sustain only; no keyswitches, CCs, program/bank changes, GM initialization, or vendor velocity layers.", + "Explicit standard fallback profile, not a native target mapping; receiver setup and plugin/Cubase acceptance remain external." + ] + }, + "default": false, + "channel": 0, + "playable_range": {"low": 0, "high": 127}, + "drum_voices": [], + "normal_articulation": "normal", + "articulations": [ + { + "name": "normal", + "aliases": ["sustain"], + "mode": "latched", + "actions": [], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 1, "velocity_high": 127}] + } + ] +} diff --git a/src/riff_groove_builder/data/profiles/toontrack-sd3-3.4.4-core-v1.json b/src/riff_groove_builder/data/profiles/toontrack-sd3-3.4.4-core-v1.json new file mode 100644 index 0000000..12a1424 --- /dev/null +++ b/src/riff_groove_builder/data/profiles/toontrack-sd3-3.4.4-core-v1.json @@ -0,0 +1,69 @@ +{ + "schema_version": "1", + "id": "toontrack.sd3.3.4.4.core.v1", + "summary": { + "id": "toontrack.sd3.3.4.4.core.v1", + "part": "drums", + "mapping_kind": "instrument", + "instrument": "sd3", + "product_name": "Superior Drummer 3 SL-DFH core three-voice subset", + "product_version": "3.4.4", + "mapping_version": "sd3-344-dfh-core-1", + "midi_available": true, + "native_format": "sd3p", + "native_available": true, + "supported_articulations": ["normal"], + "limitations": [ + "Default drums verified subset: SL-DFH kickR/36, snareR/38 and hatsTP/42 only; not the entire GM or SD3 map.", + "Native output requires an operator-local SD3 3.4.4 template with matching pad aliases and input channel; no kit or private project is bundled.", + "Channel 9 and intensity interpolation across MIDI velocities 1-127 are generator policy, not vendor channel defaults or velocity-layer claims.", + "Note-only song replacement; CC, nonzero release velocity, pre-roll, tails and nonterminating or over-six-place decimal timing are rejected.", + "Real native/MIDI service output is validated. SD3 load/play/save/reload and Cubase acceptance remain unrun; host sync, mute and routing stay operator-controlled." + ] + }, + "provenance": { + "status": "verified_subset", + "product_version": "3.4.4", + "mapping_version": "sd3-344-dfh-core-1", + "target_build": "Superior Drummer 3 standalone 3.4.4 Windows", + "mapping_preset": "Operator-local SL-DFH pads; matching aliases checked at preflight", + "sources": [ + { + "kind": "lawful_local", + "reference": "LOCAL-SD3-344-DFH-PADS-20261019; installed executable and read-only native project alias/pad declarations", + "aspects": ["identity", "range_or_voices", "actions", "velocity"] + }, + { + "kind": "generator_policy", + "reference": "docs/articulation-profiles.md#sd3-core-subset-policy-v1", + "aspects": ["channels", "state_reset", "timing", "velocity"] + } + ], + "limitations": [ + "Default drums verified subset: SL-DFH kickR/36, snareR/38 and hatsTP/42 only; not the entire GM or SD3 map.", + "Native output requires an operator-local SD3 3.4.4 template with matching pad aliases and input channel; no kit or private project is bundled.", + "Channel 9 and intensity interpolation across MIDI velocities 1-127 are generator policy, not vendor channel defaults or velocity-layer claims.", + "Note-only song replacement; CC, nonzero release velocity, pre-roll, tails and nonterminating or over-six-place decimal timing are rejected.", + "Real native/MIDI service output is validated. SD3 load/play/save/reload and Cubase acceptance remain unrun; host sync, mute and routing stay operator-controlled." + ] + }, + "default": true, + "channel": 9, + "playable_range": null, + "drum_voices": [ + {"name": "kick", "aliases": ["bass_drum"], "note": 36}, + {"name": "snare", "aliases": ["acoustic_snare"], "note": 38}, + {"name": "closed_hat", "aliases": ["hihat", "closed_hi_hat"], "note": 42} + ], + "normal_articulation": "normal", + "articulations": [ + { + "name": "normal", + "aliases": ["sustain"], + "mode": "latched", + "actions": [], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 1, "velocity_high": 127}] + } + ], + "sdp": {"layout_version": "3.4.4", "extension": "sd3p", "sound_library": "SL-DFH"} +} diff --git a/src/riff_groove_builder/description.py b/src/riff_groove_builder/description.py new file mode 100644 index 0000000..83ef766 --- /dev/null +++ b/src/riff_groove_builder/description.py @@ -0,0 +1,362 @@ +"""Closed, deterministic description grammar; no profile selection or composition.""" + +import re +from fractions import Fraction +from typing import TypeVar + +from pydantic import TypeAdapter, ValidationError +from pydantic_core import PydanticSerializationError + +from riff_groove_builder.errors import InvalidRequestError, UnsupportedDescriptionError +from riff_groove_builder.hybrid import attach, extract, fail, has_lanes +from riff_groove_builder.schemas import ( + ContractModel, + GenerateMusicRequest, + Key, + MusicalIntent, + Part, + PhrasePlan, + PositiveBeat, + RationalBeat, + TimedNote, + TimeSignature, + UniqueText, +) + +_PARTS: tuple[Part, ...] = ("lead", "bass", "drums") +_PART_WORD = r"(?:lead(?:\s+guitar)?|guitar|bass(?:\s+guitar)?(?:\s+(?:riff|groove))?|drums?|riff)" +_PART_LIST = rf"{_PART_WORD}(?:\s*(?:,|and\b|&|\+)\s*{_PART_WORD})*" +_SELECTION = re.compile( + rf"\b(?Ponly\s+|no\s+|without\s+|exclude\s+)?" + rf"(?P{_PART_LIST})\b(?P\s+only\b)?" +) +_NUMBER = r"[+-]?(?:\d+(?:\.\d+)?|\.\d+)" +_KEY = TypeAdapter(Key, config={"regex_engine": "python-re", "strict": True}) +_FILLER = { + "please", + "create", + "produce", + "generate", + "make", + "write", + "a", + "an", + "the", + "some", + "simple", + "music", + "pattern", + "groove", + "for", + "with", + "and", + "at", + "in", + "of", + "on", + "notes", + "note", + "key", + "tempo", + "meter", + "straight", +} +_CONTENT_FILLER = {"music", "pattern", "groove"} +T = TypeVar("T") +_PALM = r"palm[ -]mut(?:e|ed|ing)" +_RANGE = re.compile( + rf"\b(?:chugging\s+)?{_PALM}\s+(?:eighth|8th)(?:[ -]notes?)?\s+" + r"from\s+(?P\d+\s*&?)\s+to\s+(?P\d+\s*&?)(?![\w&])" +) +_TRIPLET_HOLD = re.compile( + r"\btriplets\s+on\s+(?P\d+)\s*&\s*a\s+with\s+the\s+a\s+as\s+a\s+" + r"pinch[ -]harmonic\s+that\s+carries\s+over\s+a\s+whole\s+note\s+" + r"in\s+the\s+(?:2nd|second)\s+measure\b" +) + + +class DescriptionConflictError(UnsupportedDescriptionError): + public_message = "Resolve contradictory text or supply the identified structured override." + + +class DescriptionResolution(ContractModel): + intent: MusicalIntent + assumptions: UniqueText + overrides: UniqueText + + +def _unsupported(reason: str, field: str = "description") -> UnsupportedDescriptionError: + return UnsupportedDescriptionError(details={"reason": reason, "field": field}) + + +def _distinct(values: list[T]) -> list[T]: + return list(dict.fromkeys(values)) + + +def _phrase(text: str) -> tuple[str, PhrasePlan | None]: + """Consume only complete bounded clauses, leaving all other instructions for rejection.""" + ranges = list(_RANGE.finditer(text)) + triplets = list(_TRIPLET_HOLD.finditer(text)) + if not ranges and not triplets: + return text, None + if len(ranges) != 1 or len(triplets) != 1: + raise _unsupported("phrase_requires_one_eighth_range_and_one_triplet_hold") + + def position(label: str) -> Fraction: + number = int(label.replace("&", "").strip()) + if not 1 <= number <= 4: + raise _unsupported("phrase_beat_labels_must_be_1_to_4") + return Fraction(number - 1) + (Fraction(1, 2) if "&" in label else 0) + + first, last = (position(ranges[0][name]) for name in ("first", "last")) + if last < first: + raise _unsupported("phrase_range_is_reversed") + beat = position(triplets[0]["beat"]) + notes = [ + TimedNote( + start=RationalBeat(numerator=offset.numerator, denominator=offset.denominator), + duration=PositiveBeat(numerator=1, denominator=2), + technique="palm_mute", + ) + for offset in ( + first + index * Fraction(1, 2) for index in range(int((last - first) * 2) + 1) + ) + ] + for index in range(3): + start = beat + Fraction(index, 3) + duration = Fraction(8) - start if index == 2 else Fraction(1, 3) + notes.append( + TimedNote( + start=RationalBeat(numerator=start.numerator, denominator=start.denominator), + duration=PositiveBeat( + numerator=duration.numerator, denominator=duration.denominator + ), + technique="pinch_harmonic" if index == 2 else "palm_mute", + ) + ) + try: + plan = PhrasePlan(part="lead", duration=PositiveBeat(numerator=8), notes=notes) + except ValidationError: + raise _unsupported("phrase_notes_overlap_or_exceed_duration") from None + return _TRIPLET_HOLD.sub(" ", _RANGE.sub(" ", text)), plan + + +def resolve_description(request: GenerateMusicRequest) -> DescriptionResolution: + """Resolve only the documented grammar; structured fields win, never unknown material.""" + try: + request = GenerateMusicRequest.model_validate( + request.model_dump(mode="python", warnings="error") + ) + except (ValidationError, PydanticSerializationError, AttributeError): + raise InvalidRequestError(details={"reason": "invalid_request_model"}) from None + + if has_lanes(request.description): + document = extract(request.description) + # A structured meter cannot reinterpret already labeled exact positions. + text_meters = re.findall(r"(? list[str]: + nonlocal text, recognized + matches = [match.group(1) for match in re.finditer(pattern, text)] + if matches: + recognized = True + text = re.sub(pattern, " ", text) + return matches + + def choose(field: str, values: list[T], explicit: T | None, default: T) -> T: + values = _distinct(values) + if explicit is not None: + overrides.append(f"{field}: structured {explicit!s} overrides text {values!s}.") + return explicit + if len(values) > 1: + raise DescriptionConflictError(details={"reason": "contradictory_text", "field": field}) + if values: + return values[0] + assumptions.append(f"{field}: omitted; using {default!s}.") + return default + + text, phrase = _phrase(text) + if phrase is not None: + recognized = True + assumptions.extend( + [ + "count-A: beat & A means three eighth-note triplets; " + "A is the final count, not a pitch.", + "hold: final PH is one continuous note through all of measure 2, " + "without retrigger.", + "register: low tonic nearest MIDI40 within profile range/tuning; " + "default Em is E2/MIDI40.", + ] + ) + # Only complete supported timing clauses bypass the changes/sequences guard. + if re.search( + r"\b(?:accelerando|ritardando|rallentando|ramp|changes?|changing|" + r"speed\s+up|slow\s+down|from|then|to)\b", + text, + ): + raise _unsupported("changes_and_sequences_not_supported") + + tempos = [Fraction(value) for value in take(rf"(? dict[str, JsonValue]: + """Expose only known locations, static reasons and authored corrections.""" + fields = FIELD_GUIDANCE.keys() | { + "lead", + "bass", + "drums", + "part", + "numerator", + "denominator", + "beat", + "controller", + "value", + } + issues: list[JsonValue] = [] + for issue in error.errors(include_url=False, include_context=False, include_input=False): + location = [ + str(item) if isinstance(item, int) or item in fields else "" + for item in issue["loc"] + ] + reason = issue["type"] + custom_field, custom_correction = REQUEST_ISSUES.get(reason, ("", "")) + field = custom_field or ".".join(location) or "$request" + root = field.split(".")[0] + correction = custom_correction or FIELD_GUIDANCE.get( + root, "Send only the declared tool fields; remove unknown properties." + ) + if "" in location: + correction = "Remove unknown properties; send only the declared fields for this object." + elif reason == "missing": + correction = "Supply this required field. " + correction + issues.append({"field": field, "reason": reason, "correction": correction}) + return {"issues": issues} + + +class DomainError(Exception): + """Only explicitly supplied, public-safe context may cross the tool boundary.""" + + code: ClassVar[ErrorCode] + public_message: ClassVar[str] + + def __init__(self, *, details: dict[str, JsonValue] | None = None) -> None: + self.details = _DETAILS.validate_python(details if details is not None else {}) + super().__init__(self.public_message) + + +class InvalidRequestError(DomainError): + code = "INVALID_REQUEST" + public_message = "Correct the invalid request fields identified in details and retry." + + +class UnsupportedDescriptionError(DomainError): + code = "UNSUPPORTED_DESCRIPTION" + public_message = DESCRIPTION_GUIDANCE + + +class ProfileRequiredError(DomainError): + code = "PROFILE_REQUIRED" + public_message = ( + "Select an available instrument or Standard MIDI profile for each affected part. " + + PROFILE_GUIDANCE + ) + + +class ProfileNotFoundError(ProfileRequiredError): + public_message = ( + "The requested profile is missing; list profiles with list_instrument_profiles({}) " + "and select an available ID for that part, or omit profiles for defaults. " + "Never invent profile IDs." + ) + + +class UnsupportedArticulationError(DomainError): + code = "UNSUPPORTED_ARTICULATION" + public_message = "Choose an articulation supported by the selected profile." + + +class NativeFormatUnavailableError(DomainError): + code = "NATIVE_FORMAT_UNAVAILABLE" + public_message = "Request MIDI fallback or select a profile with verified native support." + + +class OutputExistsError(DomainError): + code = "OUTPUT_EXISTS" + public_message = "Choose a different basename; the destination already exists." + + +class OutputIOError(DomainError): + code = "OUTPUT_IO_ERROR" + public_message = "Check output-root permissions and free space, then retry." + + +class SerializationError(DomainError): + code = "SERIALIZATION_ERROR" + public_message = "Output serialization failed; check the selected format and profile support." diff --git a/src/riff_groove_builder/formats/__init__.py b/src/riff_groove_builder/formats/__init__.py new file mode 100644 index 0000000..2107f3e --- /dev/null +++ b/src/riff_groove_builder/formats/__init__.py @@ -0,0 +1,16 @@ +"""Native capability values, not a serializer registry or artifact API.""" + +from dataclasses import dataclass +from typing import Literal + +from riff_groove_builder.schemas import Part + + +@dataclass(frozen=True, slots=True) +class NativeCapability: + """Internal check result; reason is a fixed public-safe code, never raw input.""" + + part: Part + format: Literal["agp", "sdp", "griff", "briff", "sd3p"] + available: bool + reason: str diff --git a/src/riff_groove_builder/formats/agp.py b/src/riff_groove_builder/formats/agp.py new file mode 100644 index 0000000..6fe8608 --- /dev/null +++ b/src/riff_groove_builder/formats/agp.py @@ -0,0 +1,497 @@ +"""Ample Riffer XML 2.1 codec; AGP is a legacy request/API alias only.""" + +import os +import stat +import xml.etree.ElementTree as ET +from collections import Counter +from collections.abc import Callable +from dataclasses import dataclass, replace +from fractions import Fraction +from pathlib import Path +from typing import cast + +from pydantic_core import PydanticSerializationError + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.errors import ( + InvalidRequestError, + NativeFormatUnavailableError, + OutputExistsError, + OutputIOError, + SerializationError, +) +from riff_groove_builder.formats import NativeCapability +from riff_groove_builder.midi import beats_to_ticks, validate_event_plan +from riff_groove_builder.profiles import ( + InstrumentProfile, + ProfilePartMismatchError, + RifferSettings, + checked_profile, +) +from riff_groove_builder.schemas import ( + ControlChangeEvent, + EventPlan, + NoteOffEvent, + NoteOnEvent, + Part, + PitchedNote, +) + +PPQ = 480 +_MAX_BYTES = 16 * 1024 * 1024 + + +def _fail(reason: str) -> SerializationError: + return SerializationError(details={"format": "riffer", "reason": reason}) + + +def check_agp_capability(part: Part, profile: InstrumentProfile) -> NativeCapability: + """Check a lead/bass profile without paths, filesystem IO, or serialization.""" + if part not in ("lead", "bass"): + raise InvalidRequestError(details={"format": "agp", "reason": "unsupported_agp_part"}) + checked = checked_profile(profile) + if checked.summary.part != part: + raise ProfilePartMismatchError( + details={"format": "agp", "part": part, "reason": "wrong_part"} + ) + settings = checked.riffer + supported = settings is not None and ( + settings.instrument, + checked.summary.product_version, + settings.layout_version, + settings.ppq, + ) in (("AME", "4.0.1", "2.1", PPQ), ("AMR", "4.1.0", "2.1", PPQ)) + return NativeCapability( + part=part, + format="agp", + available=supported, + reason="riffer_xml_2_1" if supported else "riffer_profile_not_supported", + ) + + +def require_agp_capability(part: Part, profile: InstrumentProfile) -> NativeCapability: + """Require native support before the caller prepares or touches any output path.""" + capability = check_agp_capability(part, profile) + if not capability.available: + raise NativeFormatUnavailableError( + details={ + "format": capability.format, + "part": capability.part, + "reason": capability.reason, + } + ) + return capability + + +check_riffer_capability = check_agp_capability +require_riffer_capability = require_agp_capability + + +@dataclass(frozen=True, slots=True) +class RifferNote: + pitch: int + begin: int + end: int + velocity: int + off_velocity: int + articulation: str + string: int = 0 + fret: int = 0 + + @property + def musical(self) -> tuple[int, int, int, int, int, str]: + return ( + self.pitch, + self.begin, + self.end, + self.velocity, + self.off_velocity, + self.articulation, + ) + + +@dataclass(frozen=True, slots=True) +class RifferReadback: + """Parsed saved content, not serializer output or an application acceptance claim.""" + + notes: tuple[RifferNote, ...] + cc1: tuple[tuple[int, int], ...] + end_tick: int + + +def _event_signature(event: NoteOnEvent | NoteOffEvent) -> tuple[int, str, str, int, int]: + return ( + event.tick, + event.kind, + event.role, + event.note, + event.velocity if isinstance(event, NoteOnEvent) else 0, + ) + + +def _content( + plan: EventPlan, part: Part, profile: InstrumentProfile +) -> tuple[EventPlan, RifferSettings, list[RifferNote], list[tuple[int, int]]]: + require_riffer_capability(part, profile) + profile = checked_profile(profile) + settings = profile.riffer + assert settings is not None + try: + if not isinstance(plan, EventPlan): + raise ValueError("Not an event plan.") + plan = EventPlan.model_validate(plan.model_dump(mode="python", warnings="error")) + except (ValueError, PydanticSerializationError): + raise _fail("invalid_event_plan") from None + validate_event_plan(plan) + if plan.musical_start_tick != 0 or plan.end_tick != plan.musical_end_tick: + raise _fail("preroll_or_tail_not_representable") + if part not in plan.score.intent.parts: + raise _fail("missing_requested_part") + index = plan.score.intent.parts.index(part) + track = plan.score.tracks[index] + # Independently recompile the selected score part to account for every MIDI switch. + isolated = plan.score.model_copy( + update={ + "intent": plan.score.intent.model_copy(update={"parts": [part]}), + "tracks": [track], + } + ) + expected = compile_score(isolated, {part: profile}, ppq=plan.ticks_per_quarter) + events = sorted(plan.tracks[index].events, key=lambda e: e.ordering_key) + if any(event.channel != profile.channel for event in events): + raise _fail("wrong_channel") + if [_event_signature(e) for e in events if isinstance(e, NoteOnEvent | NoteOffEvent)] != [ + _event_signature(e) + for e in expected.tracks[0].events + if isinstance(e, NoteOnEvent | NoteOffEvent) + ]: + raise _fail("score_event_plan_mismatch") + off = { + (e.note, e.tick): e.velocity + for e in events + if isinstance(e, NoteOffEvent) and e.role == "musical_note" + } + notes: list[RifferNote] = [] + for logical in track.notes: + if not isinstance(logical, PitchedNote): + raise _fail("unsupported_note_kind") + art = profile.resolve_articulation(logical.articulation) + if art.name not in settings.articulations: + raise _fail("unsupported_native_articulation") + begin = logical.start.value - plan.score.start.value + finish = begin + logical.duration.value + notes.append( + RifferNote( + logical.pitch, + beats_to_ticks(begin, PPQ), + beats_to_ticks(finish, PPQ), + art.velocity(logical.intensity), + off[(logical.pitch, beats_to_ticks(finish, plan.ticks_per_quarter))], + settings.articulations[art.name], + ) + ) + points: list[tuple[int, int]] = [] + for event in events: + if isinstance(event, ControlChangeEvent): + if event.controller not in settings.controllers: + raise _fail("unsupported_native_controller") + tick = beats_to_ticks(Fraction(event.tick, plan.ticks_per_quarter), PPQ) + if points and tick == points[-1][0]: + raise _fail("ambiguous_simultaneous_cc") + points.append((tick, event.value)) + beats_to_ticks(plan.score.intent.duration_beats, PPQ) + return plan, settings, notes, points + + +def _assign(notes: list[RifferNote], settings: RifferSettings) -> list[RifferNote]: + """Bounded backtracking, not greedy truncation; exhaustion is an explicit error.""" + candidates = { + n.pitch: sorted( + ( + (i, n.pitch - string.open_note) + for i, string in enumerate(settings.strings) + if 0 <= n.pitch - string.open_note <= string.max_fret + ), + key=lambda item: (item[1], item[0]), + ) + for n in notes + } + ordered = sorted( + notes, key=lambda n: (n.begin, len(candidates[n.pitch]), -n.end, n.pitch, n.articulation) + ) + states = [[0] * len(settings.strings)] + choices: list[list[tuple[int, int]]] = [] + assigned: list[RifferNote] = [] + index = attempts = 0 + while index < len(ordered): + attempts += 1 + if attempts > 200_000: + raise _fail("string_assignment_search_limit") + note = ordered[index] + if len(choices) == index: + choices.append( + [(i, fret) for i, fret in candidates[note.pitch] if states[index][i] <= note.begin] + ) + if not choices[index]: + choices.pop() + if index == 0: + raise _fail("no_physical_string_assignment") + states.pop() + assigned.pop() + index -= 1 + continue + string_index, fret = choices[index].pop(0) + assigned.append(replace(note, string=settings.strings[string_index].id, fret=fret)) + state = states[index].copy() + state[string_index] = note.end + states.append(state) + index += 1 + return assigned + + +def _native_key(key: str) -> str: + pitch, mode = key.split() + return pitch + ("m" if mode == "minor" else "") + + +def _serialize( + plan: EventPlan, + settings: RifferSettings, + notes: list[RifferNote], + points: list[tuple[int, int]], +) -> bytes: + intent = plan.score.intent + meter = intent.time_signature + root = ET.Element( + "Riff", + { + "Author": "Riff Groove Builder", + "Category": "Metal", + "Measures": str(intent.bars), + "Time-Signature": f"{meter.numerator}/{meter.denominator}", + "Quantize": "1/32", + "Tempo": str(intent.tempo_bpm), + "Type": "Riff", + "Rating": "0", + "numStr": str(len(settings.strings)), + "Inst": settings.instrument, + "Ver": settings.layout_version, + "PPQBase": str(PPQ), + "loopMode": "true", + "loopStart": "0", + "loopEnd": str(beats_to_ticks(intent.duration_beats, PPQ)), + "Key": _native_key(intent.key), + "ccName-1": "1.Mod", + "ccVisibility-1": "1", + }, + ) + for string in settings.strings: + child = ET.SubElement(root, "String", {"ID": str(string.id)}) + for note in sorted((n for n in notes if n.string == string.id), key=lambda n: n.begin): + ET.SubElement( + child, + "Note", + { + "NoteID": str(note.pitch), + "Fret": str(note.fret), + "Begin": str(note.begin), + "End": str(note.end), + "Velocity": str(note.velocity), + "Off-Velocity": str(note.off_velocity), + "Articulation": note.articulation, + "Legato": "No Legato", + "Muted": "False", + }, + ) + if points: + lane = ET.SubElement(root, "cc-1.Mod") + for tick, value in points: + ET.SubElement(lane, "p", {"tick": str(tick), "value": str(value), "curveType": "stair"}) + ET.indent(root) + return cast(bytes, ET.tostring(root, encoding="utf-8", xml_declaration=True)) + + +def _path(path: Path, settings: RifferSettings) -> None: + if not isinstance(path, Path) or path.suffix != "." + settings.extension: + raise _fail("wrong_native_suffix") + + +def _integer(value: str) -> int: + if not value.isascii() or not value.isdecimal(): + raise ValueError("Expected a nonnegative integer.") + return int(value) + + +def validate_riffer_file( + path: Path, plan: EventPlan, part: Part, profile: InstrumentProfile +) -> RifferReadback: + """Read saved XML independently and compare musical fields to score and event plan.""" + plan, settings, expected, points = _content(plan, part, profile) + _path(path, settings) + try: + info = path.lstat() + if ( + not stat.S_ISREG(info.st_mode) + or info.st_size > _MAX_BYTES + or getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT + ): + raise ValueError("Not a bounded regular native file.") + with path.open("rb") as stream: + raw = stream.read(_MAX_BYTES + 1) + except OSError: + raise OutputIOError(details={"reason": "riffer_read_failed"}) from None + except ValueError: + raise _fail("invalid_saved_riffer") from None + try: + # UTF-8 only: reject declarations/entities before the XML parser sees them. + text = raw.decode("utf-8") + if len(raw) > _MAX_BYTES or " string.max_fret + or not previous_end <= note.begin < note.end <= end + or not 1 <= note.velocity <= 127 + or not 0 <= note.off_velocity <= 127 + or note.articulation not in settings.articulations.values() + or attrs["Legato"] != "No Legato" + or attrs["Muted"] != "False" + ): + raise ValueError("Invalid physical note.") + previous_end = note.end + parsed.append(note) + if points: + lane = root[-1] + if lane.attrib or (lane.text or "").strip(): + raise ValueError("Unsupported CC lane.") + for node in lane: + if ( + node.tag != "p" + or set(node.attrib) != {"tick", "value", "curveType"} + or node.get("curveType") != "stair" + or len(node) + or (node.text or "").strip() + or (node.tail or "").strip() + ): + raise ValueError("Unsupported CC representation.") + tick = _integer(node.attrib["tick"]) + value = _integer(node.attrib["value"]) + if not 0 <= tick <= end or not 0 <= value <= 127: + raise ValueError("CC outside bounds.") + parsed_points.append((tick, value)) + if ( + any((c.tail or "").strip() for c in root) + or Counter(n.musical for n in parsed) != Counter(n.musical for n in expected) + or parsed_points != points + ): + raise ValueError("Saved notes or CC do not match the request.") + return RifferReadback(tuple(parsed), tuple(parsed_points), end) + except (ET.ParseError, ValueError, KeyError, UnicodeError, OverflowError): + raise _fail("invalid_saved_riffer") from None + + +def preflight_riffer(plan: EventPlan, part: Part, profile: InstrumentProfile) -> None: + """Exercise exact content/grid/routing checks without creating output.""" + _, settings, notes, _ = _content(plan, part, profile) + _assign(notes, settings) + + +def write_riffer( + path: Path, + plan: EventPlan, + part: Part, + profile: InstrumentProfile, + *, + on_created: Callable[[os.stat_result], None] | None = None, +) -> Path: + """Exclusively create the supplied staged file, then validate its actual saved bytes.""" + checked, settings, notes, points = _content(plan, part, profile) + _path(path, settings) + raw = _serialize(checked, settings, _assign(notes, settings), points) + if len(raw) > _MAX_BYTES: + raise _fail("riffer_size_limit") + try: + with path.open("xb") as stream: + if on_created is not None: + on_created(os.fstat(stream.fileno())) + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + except FileExistsError: + raise OutputExistsError(details={"reason": "destination_exists"}) from None + except OSError: + raise OutputIOError(details={"reason": "riffer_write_failed"}) from None + validate_riffer_file(path, checked, part, profile) + return path + + +write_agp = write_riffer +validate_agp_file = validate_riffer_file diff --git a/src/riff_groove_builder/formats/sdp.py b/src/riff_groove_builder/formats/sdp.py new file mode 100644 index 0000000..b385f25 --- /dev/null +++ b/src/riff_groove_builder/formats/sdp.py @@ -0,0 +1,744 @@ +"""Bounded SD3 3.4.4 text projects; SDP is a request alias, never a suffix.""" + +import hashlib +import os +import re +import stat +from collections import Counter +from collections.abc import Callable +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path + +from pydantic_core import PydanticSerializationError + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.errors import ( + InvalidRequestError, + NativeFormatUnavailableError, + OutputExistsError, + OutputIOError, + SerializationError, +) +from riff_groove_builder.formats import NativeCapability +from riff_groove_builder.midi import validate_event_plan +from riff_groove_builder.profiles import ( + InstrumentProfile, + ProfilePartMismatchError, + checked_profile, +) +from riff_groove_builder.schemas import ( + ControlChangeEvent, + EventPlan, + NoteOffEvent, + NoteOnEvent, + Part, +) + +MAX_BYTES = 16 * 1024 * 1024 +MAX_DEPTH = 64 +MAX_EVENTS = 100_000 +MAX_TOKENS = 1_000_000 +MAX_BEATS = 16384 +_PADS = {36: "kickR", 38: "snareR", 42: "hatsTP"} +_LEX = re.compile( + r"(?P[ \t]+)|(?P\r\n|\n)|(?P[{}])|" + r'(?P"(?:[^"\\\r\n\x00-\x1f]|\\[^\r\n\x00-\x1f])*")|' + r'(?P[^\s{}"\x00-\x1f]+)' +) +_NUMBER = re.compile(r"-?(?:0|[1-9][0-9]*)(?:\.[0-9]{1,9})?") + + +def _fail(reason: str) -> SerializationError: + return SerializationError(details={"format": "sd3p", "reason": reason}) + + +@dataclass(frozen=True, slots=True) +class _Token: + value: str + start: int + end: int + + +@dataclass(frozen=True, slots=True) +class _Node: + key: str + args: tuple[str, ...] + children: tuple["_Node", ...] | None + start: int + end: int + + +@dataclass(frozen=True, slots=True) +class SdpNote: + """Explicit quarter-note positions and the three independently decoded MIDI bytes.""" + + channel: int + pitch: int + velocity: int + start: Fraction + end: Fraction + + +@dataclass(frozen=True, slots=True) +class SdpProject: + """Read-only parsed snapshot, including exact original non-song text.""" + + text: str + nodes: tuple[_Node, ...] + tracks: tuple[_Node, ...] + source_notes: tuple[SdpNote, ...] + sha256: str + + @property + def non_song_bytes(self) -> bytes: + # Keep segment boundaries independent of song lengths/number of source tracks. + return _without_songs(self.text, self.nodes).encode("utf-8") + + +@dataclass(frozen=True, slots=True) +class SdpTemplateInfo: + version: str + track_count: int + event_count: int + size_bytes: int + sha256: str + non_song_sha256: str + + +@dataclass(frozen=True, slots=True) +class SdpReadback: + notes: tuple[SdpNote, ...] + tempo_bpm: Fraction + meter: tuple[int, int] + start: Fraction + end: Fraction + non_song_sha256: str + + +def _tokens(text: str) -> list[_Token]: + result: list[_Token] = [] + position = 0 + while position < len(text): + match = _LEX.match(text, position) + if match is None: + raise _fail("malformed_sd3_text") + if match.lastgroup != "space": + result.append(_Token(match[0], position, match.end())) + if len(result) > MAX_TOKENS: + raise _fail("sd3_token_limit") + position = match.end() + return result + + +def _tree(tokens: list[_Token]) -> tuple[_Node, ...]: + index = 0 + + def records(depth: int) -> tuple[_Node, ...]: + nonlocal index + if depth > MAX_DEPTH: + raise _fail("sd3_nesting_limit") + result: list[_Node] = [] + while index < len(tokens): + if tokens[index].value in ("\n", "\r\n"): + index += 1 + continue + if tokens[index].value == "}": + if depth == 0: + raise _fail("unbalanced_sd3_blocks") + return tuple(result) + first = tokens[index] + if first.value == "{": + raise _fail("invalid_sd3_record") + words: list[str] = [] + while index < len(tokens) and tokens[index].value not in ("{", "}", "\n", "\r\n"): + words.append(tokens[index].value) + index += 1 + end = tokens[index - 1].end + children = None + if index < len(tokens) and tokens[index].value == "{": + index += 1 + children = records(depth + 1) + if index == len(tokens) or tokens[index].value != "}": + raise _fail("unbalanced_sd3_blocks") + end = tokens[index].end + index += 1 + if index < len(tokens) and tokens[index].value not in ("\n", "\r\n", "}"): + raise _fail("invalid_sd3_record") + result.append(_Node(words[0], tuple(words[1:]), children, first.start, end)) + if depth: + raise _fail("unbalanced_sd3_blocks") + return tuple(result) + + return records(0) + + +def _children(node: _Node) -> tuple[_Node, ...]: + if node.children is None: + raise _fail("expected_sd3_block") + return node.children + + +def _one(nodes: tuple[_Node, ...], key: str) -> _Node: + matches = [n for n in nodes if n.key == key] + if len(matches) != 1: + raise _fail("missing_or_duplicate_sd3_field") + return matches[0] + + +def _field(nodes: tuple[_Node, ...], key: str) -> tuple[str, ...]: + node = _one(nodes, key) + if node.children is not None: + raise _fail("expected_sd3_field") + return node.args + + +def _number(value: str) -> Fraction: + if len(value) > 30 or not _NUMBER.fullmatch(value): + raise _fail("invalid_sd3_number") + result = Fraction(value) + if abs(result) > MAX_BEATS: + raise _fail("sd3_number_out_of_range") + return result + + +def _scalar(nodes: tuple[_Node, ...], key: str) -> Fraction: + args = _field(nodes, key) + if len(args) != 1: + raise _fail("invalid_sd3_scalar") + return _number(args[0]) + + +def _integer(value: str, maximum: int) -> int: + if len(value) > 10 or not re.fullmatch(r"0|[1-9][0-9]*", value): + raise _fail("invalid_sd3_integer") + result = int(value) + if result > maximum: + raise _fail("sd3_integer_out_of_range") + return result + + +def _metadata(fields: tuple[_Node, ...]) -> None: + tempo = _field(fields, "Tempo") + meter = _field(fields, "TimeSig") + if ( + len(tempo) != 3 + or not 20 <= _number(tempo[0]) <= 300 + or tempo[1:] != ("0", "0") + or len(meter) != 3 + or not 1 <= _integer(meter[0], 16) <= 16 + or _integer(meter[1], 16) not in (1, 2, 4, 8, 16) + or meter[2] != "0" + ): + raise _fail("unsupported_sd3_tempo_or_meter_map") + + +def _decode_events(node: _Node) -> tuple[SdpNote, ...]: + fields = _children(node) + _metadata(fields) + end = _scalar(fields, "EndTime") + if end <= 0: + raise _fail("invalid_sd3_end") + args = _field(fields, "Events") + if len(args) % 3 or len(args) // 3 > MAX_EVENTS: + raise _fail("invalid_sd3_event_triples") + notes: list[SdpNote] = [] + previous = Fraction(-1) + for index in range(0, len(args), 3): + packed = _integer(args[index], 0x7F7FFF) + status, pitch, velocity = packed & 255, (packed >> 8) & 255, packed >> 16 + if status & 0xF0 != 0x90 or pitch > 127 or not 1 <= velocity <= 127: + raise _fail("unsupported_sd3_midi_message") + begin, finish = _number(args[index + 1]), _number(args[index + 2]) + if not 0 <= begin < finish <= end or begin < previous: + raise _fail("invalid_sd3_note_timing") + previous = begin + notes.append(SdpNote(status & 15, pitch, velocity, begin, finish)) + return tuple(notes) + + +def _walk(nodes: tuple[_Node, ...]) -> list[_Node]: + result: list[_Node] = [] + for node in nodes: + result.append(node) + if node.children is not None: + result.extend(_walk(node.children)) + return result + + +def _song_spans(text: str, nodes: tuple[_Node, ...]) -> list[tuple[int, int]]: + spans: list[tuple[int, int]] = [] + for node in nodes: + if node.key in ("SongTrack", "SetCurrentSongTrack"): + # Consume only the record's newline, never following unrelated state. + end = node.end + while end < len(text) and text[end] in " \t": + end += 1 + if text[end : end + 2] == "\r\n": + end += 2 + elif text[end : end + 1] == "\n": + end += 1 + spans.append((node.start, end)) + return spans + + +def _without_songs(text: str, nodes: tuple[_Node, ...]) -> str: + previous = 0 + pieces: list[str] = [] + for start, end in _song_spans(text, nodes): + pieces.append(text[previous:start]) + previous = end + return "".join([*pieces, text[previous:]]) + + +def parse_sdp_project(raw: bytes) -> SdpProject: + """Parse bounded native text, not JSON/MIDI/opaque tracker payloads.""" + if not isinstance(raw, bytes) or not 0 < len(raw) <= MAX_BYTES: + raise _fail("sd3_size_limit") + try: + text = raw.decode("utf-8") + except UnicodeError: + raise _fail("invalid_sd3_encoding") from None + # Genuine 3.4.4 saves have one terminal NUL. Also accept unterminated UTF-8 fixtures. + body = text[:-1] if text.endswith("\0") else text + nodes = _tree(_tokens(body)) + if not nodes or nodes[0].key != "PlugVersion": + raise _fail("missing_sd3_version") + if _field(nodes, "PlugVersion") != ("3.4.4",): + raise _fail("unsupported_sd3_version") + _children(_one(nodes, "SAMPLER")) + if _field(nodes, "ClearTracksFirst"): + raise _fail("invalid_sd3_clear_tracks") + tracks = tuple(n for n in nodes if n.key == "SongTrack") + if not 1 <= len(tracks) <= 32: + raise _fail("ambiguous_sd3_tracks") + ids = [n.args for n in tracks] + if ids != [(str(i),) for i in range(len(tracks))]: + raise _fail("ambiguous_sd3_tracks") + current = _field(nodes, "SetCurrentSongTrack") + if len(current) != 1 or current not in ids: + raise _fail("ambiguous_sd3_tracks") + if nodes.index(_one(nodes, "ClearTracksFirst")) > nodes.index(tracks[0]): + raise _fail("invalid_sd3_track_order") + if nodes.index(_one(nodes, "SetCurrentSongTrack")) < nodes.index(tracks[-1]): + raise _fail("invalid_sd3_track_order") + all_nodes = _walk(nodes) + if sum(n.key == "SongTrack" for n in all_nodes) != len(tracks): + raise _fail("nested_sd3_song_track") + notes: list[SdpNote] = [] + song_event_blocks = 0 + song_loops = 0 + for track in tracks: + fields = _children(track) + if _field(fields, "ClearTrackFirst") or _field(fields, "ClearSongParts"): + raise _fail("invalid_sd3_clear_song") + length = _scalar(fields, "TrackLength") + if length <= 0: + raise _fail("invalid_sd3_track_length") + _metadata(fields) + loops = [n for n in fields if n.key == "MidiLoop"] + if [n.args for n in loops] != [(str(i),) for i in range(len(loops))]: + raise _fail("ambiguous_sd3_clips") + event_blocks = [n for n in _walk(fields) if n.key == "MidiEvents"] + if len(event_blocks) != len(loops): + raise _fail("ambiguous_sd3_event_blocks") + song_event_blocks += len(event_blocks) + song_loops += len(loops) + for loop in loops: + clip = _children(loop) + start, end, real, offset = ( + _scalar(clip, key) for key in ("StartTime", "EndTime", "RealEndTime", "Offset") + ) + if not 0 <= start < end <= real or offset < 0 or offset + end - start > length: + raise _fail("invalid_sd3_clip_bounds") + events = _one(clip, "MidiEvents") + if events.args: + raise _fail("invalid_sd3_event_block") + if _field(clip, "ClearNotes") or _scalar(_children(events), "EndTime") != real: + raise _fail("invalid_sd3_clip_events") + notes.extend(_decode_events(events)) + if len(notes) > MAX_EVENTS: + raise _fail("sd3_event_limit") + if ( + sum(n.key == "MidiEvents" for n in all_nodes) != song_event_blocks + or sum(n.key == "MidiLoop" for n in all_nodes) != song_loops + ): + raise _fail("sd3_music_outside_song") + return SdpProject(text, nodes, tracks, tuple(notes), hashlib.sha256(raw).hexdigest()) + + +def _read(path: Path, *, template: bool) -> bytes: + if not isinstance(path, Path) or path.suffix != ".sd3p": + raise _fail("wrong_sd3_suffix") + try: + with path.open("rb") as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or not 0 < info.st_size <= MAX_BYTES: + raise _fail("sd3_size_limit") + raw = stream.read(MAX_BYTES + 1) + except OSError: + raise OutputIOError( + details={"reason": "sd3_template_read_failed" if template else "sd3_read_failed"} + ) from None + if not 0 < len(raw) <= MAX_BYTES: + raise _fail("sd3_size_limit") + return raw + + +def _mapping(project: SdpProject) -> None: + sampler = _children(_one(project.nodes, "SAMPLER")) + if _field(_children(_one(sampler, "HQ")), "soundlib") != ('"SL-DFH"',): + raise _fail("unsupported_sd3_sound_library") + aliases: dict[int, list[str]] = {note: [] for note in _PADS} + for node in _walk(sampler): + if node.key != "xpad": + continue + xpad = _children(node) + for container in xpad: + if container.key != "pads": + continue + fields = _children(container) + for alias in fields: + if alias.key != "alias" or not alias.args or alias.children is not None: + continue + for value in alias.args[1:]: + if value not in {str(n) for n in _PADS}: + continue + pad = alias.args[0] + if ( + node.args != ("0", "SL-DFH") + or len( + [ + p + for p in fields + if p.key == "pad" and p.args == (pad,) and p.children is not None + ] + ) + != 1 + ): + raise _fail("sd3_core_mapping_mismatch") + aliases[int(value)].append(pad) + if any(aliases[n] != [pad] for n, pad in _PADS.items()): + raise _fail("sd3_core_mapping_mismatch") + # An active global MIDI-learn remap is outside the evidenced subset. + for node in _walk(sampler): + if node.key == "midilearn" and _children(node): + raise _fail("unsupported_sd3_midi_learn") + if _field(project.nodes, "MidiInChannel") not in (("-1",), ("9",)): + raise _fail("sd3_input_channel_mismatch") + + +def inspect_sdp_template(path: Path) -> SdpTemplateInfo: + """Read-only preflight; supplied corrupt/unreadable files are errors, not fallback.""" + raw = _read(path, template=True) + project = parse_sdp_project(raw) + _mapping(project) + return SdpTemplateInfo( + "3.4.4", + len(project.tracks), + len(project.source_notes), + len(raw), + project.sha256, + hashlib.sha256(project.non_song_bytes).hexdigest(), + ) + + +def check_sdp_capability( + part: Part, profile: InstrumentProfile, *, template: Path | None = None +) -> NativeCapability: + if part != "drums": + raise InvalidRequestError(details={"format": "sdp", "reason": "unsupported_sdp_part"}) + checked = checked_profile(profile) + if checked.summary.part != part: + raise ProfilePartMismatchError( + details={"format": "sdp", "part": part, "reason": "wrong_part"} + ) + if template is not None: + inspect_sdp_template(template) + supported = checked.sdp is not None + reason = ( + "sdp_profile_not_supported" + if not supported + else ("sdp_template_required" if template is None else "sd3_3_4_4_template_song") + ) + return NativeCapability(part, "sdp", supported and template is not None, reason) + + +def require_sdp_capability( + part: Part, profile: InstrumentProfile, *, template: Path | None = None +) -> NativeCapability: + capability = check_sdp_capability(part, profile, template=template) + if not capability.available: + raise NativeFormatUnavailableError( + details={"format": "sdp", "part": part, "reason": capability.reason} + ) + return capability + + +def _decimal(value: Fraction) -> str: + # A bounded finite decimal is exact; no float conversion or tick rounding. + scaled = value * 1_000_000 + if value < 0 or value > MAX_BEATS or scaled.denominator != 1: + raise _fail("sd3_timing_not_representable") + whole, fraction = divmod(scaled.numerator, 1_000_000) + return f"{whole}.{fraction:06d}".rstrip("0").rstrip(".") + + +def _content( + plan: EventPlan, part: Part, profile: InstrumentProfile +) -> tuple[EventPlan, tuple[SdpNote, ...]]: + try: + if not isinstance(plan, EventPlan): + raise ValueError + plan = EventPlan.model_validate(plan.model_dump(mode="python", warnings="error")) + except (ValueError, PydanticSerializationError): + raise _fail("invalid_event_plan") from None + validate_event_plan(plan) + if plan.musical_start_tick or plan.end_tick != plan.musical_end_tick: + raise _fail("sd3_preroll_or_tail_not_representable") + if part not in plan.score.intent.parts: + raise _fail("missing_requested_part") + index = plan.score.intent.parts.index(part) + score = plan.score.model_copy( + update={ + "intent": plan.score.intent.model_copy(update={"parts": [part]}), + "tracks": [plan.score.tracks[index]], + } + ) + expected = compile_score(score, {part: profile}, ppq=plan.ticks_per_quarter) + + def signature(event: NoteOnEvent | NoteOffEvent) -> tuple[str, int, int, int, str, int]: + return event.kind, event.tick, event.channel, event.note, event.role, event.velocity + + events = sorted(plan.tracks[index].events, key=lambda e: e.ordering_key) + if any( + e.channel != profile.channel + or (not isinstance(e, ControlChangeEvent) and e.role != "musical_note") + or (isinstance(e, NoteOffEvent) and e.velocity != 0) + for e in events + ): + raise _fail("unsupported_sd3_event_semantics") + actual = [signature(e) for e in events if isinstance(e, NoteOnEvent | NoteOffEvent)] + wanted = [ + signature(e) for e in expected.tracks[0].events if isinstance(e, NoteOnEvent | NoteOffEvent) + ] + if actual != wanted: + raise _fail("score_event_plan_mismatch") + # Only valid CCs on an otherwise exact drum plan are known unavailability. + # Routing, note/role/release corruption above must never become MIDI fallback. + if any(isinstance(e, ControlChangeEvent) for e in events): + raise _fail("sd3_native_controller_not_supported") + active: dict[tuple[int, int], NoteOnEvent] = {} + notes: list[SdpNote] = [] + for event in events: + if isinstance(event, NoteOnEvent): + active[event.channel, event.note] = event + elif isinstance(event, NoteOffEvent): + begin = active.pop((event.channel, event.note)) + note = SdpNote( + event.channel, + event.note, + begin.velocity, + Fraction(begin.tick, plan.ticks_per_quarter), + Fraction(event.tick, plan.ticks_per_quarter), + ) + _decimal(note.start) + _decimal(note.end) + notes.append(note) + _decimal(plan.score.intent.duration_beats) + _decimal(Fraction(str(plan.score.intent.tempo_bpm))) + if not notes or len(notes) > MAX_EVENTS: + raise _fail("sd3_event_limit") + ordered = sorted(notes, key=lambda n: (n.start, n.pitch, n.channel, n.end, n.velocity)) + return plan, tuple(ordered) + + +def _song(plan: EventPlan, notes: tuple[SdpNote, ...]) -> str: + intent = plan.score.intent + end = _decimal(intent.duration_beats) + tempo = _decimal(Fraction(str(intent.tempo_bpm))) + meter = f"{intent.time_signature.numerator} {intent.time_signature.denominator}" + triples = " ".join( + f"{0x90 | n.channel | (n.pitch << 8) | (n.velocity << 16)} " + f"{_decimal(n.start)} {_decimal(n.end)}" + for n in notes + ) + return ( + "SongTrack 0 {\n" + "Minimized 0\nClearTrackFirst\n" + f"TrackLength {end}\nVisibleArea 0 {end}\nZoom 10\nTempo {tempo} 0 0\n" + f"TimeSig {meter} 0\nKeySign 0 1 0 0 0\n" + 'TrackName "Original generated drums"\nMutedCCs\nClearSongParts\n' + f"GridRes 32\nLoopArea 0 {end}\nLoopActive 0\nStartNumber 1\nPlayHeadPos 0\n" + 'MidiLoop 0 {\nName "Original generated drums"\n' + f"RealEndTime {end}\nStartTime 0\nEndTime {end}\nOffset 0\n" + f"tapQuantize 0\nVelocity 0\nClearNotes\nTimeSig {meter}\n" + f"MidiEvents {{\nEndTime {end}\nEvents {triples}\n" + f"KeySign 0 1 0 0 0\nTimeSig {meter} 0\nTempo {tempo} 0 0\n" + "}\nPercussionLoop 0 0\nType 1\nMute 0\nSelected 0\n}\n}\n" + ) + + +def _replace_song(project: SdpProject, song: str) -> bytes: + pieces: list[str] = [] + previous = 0 + inserted = False + newline = "\r\n" if "\r\n" in project.text else "\n" + for start, end in _song_spans(project.text, project.nodes): + pieces.append(project.text[previous:start]) + if not inserted: + pieces.append((song + "SetCurrentSongTrack 0\n").replace("\n", newline)) + inserted = True + previous = end + pieces.append(project.text[previous:]) + return "".join(pieces).encode("utf-8") + + +def _expect_fields( + nodes: tuple[_Node, ...], expected: dict[str, tuple[str, ...]], blocks: set[str] +) -> None: + if Counter(n.key for n in nodes) != Counter([*expected, *blocks]): + raise _fail("unsupported_saved_sd3_content") + for key, value in expected.items(): + if _field(nodes, key) != value: + raise _fail("saved_sd3_field_mismatch") + + +def validate_sdp_file( + path: Path, + plan: EventPlan, + part: Part, + profile: InstrumentProfile, + *, + template: Path | None = None, +) -> SdpReadback: + """Independently decode actual saved triples and prove non-song state unchanged.""" + require_sdp_capability(part, profile, template=template) + checked, expected = _content(plan, part, checked_profile(profile)) + assert template is not None + source = parse_sdp_project(_read(template, template=True)) + saved = parse_sdp_project(_read(path, template=False)) + _mapping(saved) + if len(saved.tracks) != 1 or _field(saved.nodes, "SetCurrentSongTrack") != ("0",): + raise _fail("saved_sd3_extra_tracks") + if saved.non_song_bytes != source.non_song_bytes: + raise _fail("sd3_non_song_state_changed") + intent = checked.score.intent + end = _decimal(intent.duration_beats) + tempo = _decimal(Fraction(str(intent.tempo_bpm))) + meter = (str(intent.time_signature.numerator), str(intent.time_signature.denominator)) + fields = _children(saved.tracks[0]) + _expect_fields( + fields, + { + "Minimized": ("0",), + "ClearTrackFirst": (), + "TrackLength": (end,), + "VisibleArea": ("0", end), + "Zoom": ("10",), + "Tempo": (tempo, "0", "0"), + "TimeSig": (*meter, "0"), + "KeySign": ("0", "1", "0", "0", "0"), + "TrackName": ('"Original generated drums"',), + "MutedCCs": (), + "ClearSongParts": (), + "GridRes": ("32",), + "LoopArea": ("0", end), + "LoopActive": ("0",), + "StartNumber": ("1",), + "PlayHeadPos": ("0",), + }, + {"MidiLoop"}, + ) + loop = _one(fields, "MidiLoop") + if loop.args != ("0",): + raise _fail("saved_sd3_clip_id_mismatch") + clip = _children(loop) + _expect_fields( + clip, + { + "Name": ('"Original generated drums"',), + "RealEndTime": (end,), + "StartTime": ("0",), + "EndTime": (end,), + "Offset": ("0",), + "tapQuantize": ("0",), + "Velocity": ("0",), + "ClearNotes": (), + "TimeSig": meter, + "PercussionLoop": ("0", "0"), + "Type": ("1",), + "Mute": ("0",), + "Selected": ("0",), + }, + {"MidiEvents"}, + ) + event_fields = _children(_one(clip, "MidiEvents")) + # Event payload is decoded above, not compared to the writer's serialized line. + _expect_fields( + event_fields, + { + "EndTime": (end,), + "Events": _field(event_fields, "Events"), + "KeySign": ("0", "1", "0", "0", "0"), + "TimeSig": (*meter, "0"), + "Tempo": (tempo, "0", "0"), + }, + set(), + ) + if Counter(saved.source_notes) != Counter(expected): + raise _fail("saved_sd3_notes_mismatch") + return SdpReadback( + saved.source_notes, + Fraction(tempo), + (int(meter[0]), int(meter[1])), + Fraction(0), + intent.duration_beats, + hashlib.sha256(saved.non_song_bytes).hexdigest(), + ) + + +def preflight_sdp(plan: EventPlan, part: Part, profile: InstrumentProfile) -> None: + """Exercise exact song/event/decimal checks without creating output.""" + _content(plan, part, checked_profile(profile)) + + +def write_sdp( + path: Path, + plan: EventPlan, + part: Part, + profile: InstrumentProfile, + *, + template: Path | None = None, + on_created: Callable[[os.stat_result], None] | None = None, +) -> Path: + """Exclusively write a staged .sd3p; the operator template is never modified.""" + require_sdp_capability(part, profile, template=template) + checked, notes = _content(plan, part, checked_profile(profile)) + if not isinstance(path, Path) or path.suffix != ".sd3p": + raise _fail("wrong_sd3_suffix") + assert template is not None + source = parse_sdp_project(_read(template, template=True)) + _mapping(source) + raw = _replace_song(source, _song(checked, notes)) + if not 0 < len(raw) <= MAX_BYTES: + raise _fail("sd3_size_limit") + try: + with path.open("xb") as stream: + if on_created is not None: + on_created(os.fstat(stream.fileno())) + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + except FileExistsError: + raise OutputExistsError(details={"reason": "destination_exists"}) from None + except OSError: + raise OutputIOError(details={"reason": "sd3_write_failed"}) from None + if hashlib.sha256(_read(template, template=True)).hexdigest() != source.sha256: + raise _fail("sd3_template_changed") + validate_sdp_file(path, checked, part, profile, template=template) + return path + + +write_sd3p = write_sdp +validate_sd3p_file = validate_sdp_file diff --git a/src/riff_groove_builder/hybrid.py b/src/riff_groove_builder/hybrid.py new file mode 100644 index 0000000..7b1b751 --- /dev/null +++ b/src/riff_groove_builder/hybrid.py @@ -0,0 +1,459 @@ +"""Bounded hybrid lanes: exact denominator-beat grids, never visual columns.""" + +import re +from dataclasses import dataclass, field +from fractions import Fraction +from typing import Literal + +from pydantic import ValidationError + +from riff_groove_builder.errors import UnsupportedDescriptionError +from riff_groove_builder.pitch import parse_chord, parse_pitch, resolve_voicing, tokenize_notation +from riff_groove_builder.profiles import InstrumentProfile +from riff_groove_builder.schemas import ( + ExplicitAttack, + ExplicitAttackPlan, + HybridPlan, + HybridSlot, + MusicalIntent, + Part, + PositiveBeat, + RationalBeat, + TimeSignature, +) + +_LABEL = re.compile(r"^\s*(Counts|Events|Chords|Notes|Grid|Subdivision)\s*:\s*(.*)$", re.I) +_BAR = re.compile(r"^\s*(?:bar|measure)\s+(\d+)\s*:\s*(.*)$", re.I) +_HOLD = re.compile( + r"\b(?:hold|tie)\s+the\s+final\s+(note|chord|[A-G][#b]?[+-]?\d{1,2})\s+" + r"(?:through|to)\s+(?:the\s+)?end\s+of\s+(?:bar|measure)\s+(\d+)" + r"(?:\s+without\s+retriggering)?[.!]?", + re.I, +) +_CONTINUE = re.compile(r"hold\s+(?:the\s+)?previous\s+(?:note|chord)\s+to\s+bar\s+end[.!]?", re.I) +_TECHNIQUES = {"o": "normal", "x": "palm_mute", "^": "pinch_harmonic"} +_GRIDS = { + "eighths": "eighths", + "eighth": "eighths", + "sixteenths": "sixteenths", + "sixteenth": "sixteenths", + "eighth-triplets": "triplets", + "eighth triplets": "triplets", +} + + +def fail(reason: str, field_name: str = "description") -> UnsupportedDescriptionError: + return UnsupportedDescriptionError(details={"reason": reason, "field": field_name}) + + +def beat(value: Fraction) -> RationalBeat: + return RationalBeat(numerator=value.numerator, denominator=value.denominator) + + +def duration(value: Fraction) -> PositiveBeat: + return PositiveBeat(numerator=value.numerator, denominator=value.denominator) + + +@dataclass +class HybridDocument: + context: str + bars: dict[int, dict[str, str]] + grid: str | None + continuation: set[int] = field(default_factory=set) + hold_bar: int | None = None + hold_pitch: str | None = None + global_technique: str | None = None + claimed_pitch: str | None = None + + +def has_lanes(text: str) -> bool: + return any(_LABEL.match(line) for line in text.splitlines()) + + +def extract(text: str) -> HybridDocument: + """Separate recognized lane/hold clauses before the legacy prose sequence guard.""" + if len(text) > 4000: + raise fail("hybrid_description_exceeds_4000_characters") + bars: dict[int, dict[str, str]] = {} + current = 1 + context = [] + grids = [] + continuation: set[int] = set() + spans: dict[int, list[int]] = {} + last_header = 0 + for line in text.splitlines(): + bar_match = _BAR.fullmatch(line) + if bar_match: + current = int(bar_match[1]) + if not last_header < current <= 256 or current in bars or current in continuation: + raise fail("bar_labels_must_be_unique_and_in_range") + last_header = current + line = bar_match[2] + if _CONTINUE.fullmatch(line): + continuation.add(current) + continue + if not line.strip(): + bars[current] = {} + continue + raise fail("bar_header_requires_rows_or_hold_previous_note_to_bar_end") + match = _LABEL.fullmatch(line) + if match is None: + context.append(line) + continue + label, value = match[1].lower(), match[2] + if label in ("grid", "subdivision"): + grid = _GRIDS.get(value.strip().lower()) + if grid is None: + raise fail("unsupported_grid_use_eighths_sixteenths_or_eighth_triplets") + grids.append(grid) + continue + if current in continuation: + raise fail("continuation_bar_cannot_also_have_rows") + segments = value.split("|") + if segments and not segments[0].strip(): + segments.pop(0) + if segments and not segments[-1].strip(): + segments.pop() + if not segments or any(not segment.strip() for segment in segments): + raise fail("empty_bar_segment") + spans.setdefault(current, []).append(len(segments)) + for index, segment in enumerate(segments, current): + rows = bars.setdefault(index, {}) + if label in rows: + raise fail("duplicate_lane_in_bar") + rows[label] = segment + if any(len(set(lengths)) > 1 for lengths in spans.values()): + raise fail("lane_slot_counts_and_bar_spans_must_match") + if len(set(grids)) > 1: + raise fail("conflicting_grid_directives") + prose = "\n".join(context) + holds = list(_HOLD.finditer(prose)) + if len(holds) > 1: + raise fail("one_final_hold_directive_only") + hold_bar = int(holds[0][2]) if holds else None + hold_pitch = holds[0][1] if holds and holds[0][1].lower() not in ("note", "chord") else None + # Note spellings stay case-sensitive, including accidentals. + if hold_pitch is not None and not re.fullmatch(r"[A-G][#b]?[+-]?\d{1,2}", hold_pitch): + raise fail("hold_pitch_requires_conventional_capitalization") + prose = _HOLD.sub(" ", prose) + prose = re.sub( + r"\b(one|two|three|four)\s+(bars?|measures?)\b", + lambda m: str({"one": 1, "two": 2, "three": 3, "four": 4}[m[1].lower()]) + " bars", + prose, + flags=re.I, + ) + prose = re.sub(r"\b(\d+)\s+measures?\b", r"\1 bars", prose, flags=re.I) + prose = re.sub( + r"\b(?:low[ -]register\s+chord\s+voicings|aggressive|tight|style|" + r"bounded\s+velocity\s+variation)\b", + " ", + prose, + flags=re.I, + ) + claims = list( + re.finditer(r"\b(?:play|all\s+notes(?:\s+are)?)\s+([A-G][#b]?[+-]?\d{1,2})\b", prose) + ) + if len({m[1] for m in claims}) > 1: + raise fail("conflicting_prose_pitch_claims") + claimed = claims[0][1] if claims else None + prose = re.sub(r"\b(?:play|all\s+notes(?:\s+are)?)\s+[A-G][#b]?[+-]?\d{1,2}\b", " ", prose) + technique_pattern = r"\b(palm[ -]mut(?:e|ed|ing)|pinch[ -]harmonic|PM|PH|normal|sustain)\b" + techniques = re.findall(technique_pattern, prose, re.I) + canonical = { + "palm_mute" + if t.lower().startswith("palm") or t.lower() == "pm" + else "pinch_harmonic" + if t.lower().startswith("pinch") or t.lower() == "ph" + else "normal" + for t in techniques + } + if len(canonical) > 1: + # A specifically stated ordered contrast is not a global technique claim. + ordered = re.search( + r"\bfirst\s+(?:palm[ -]mut(?:e|ed|ing)|PM)\s+then\s+" + r"(?:pinch[ -]harmonic|PH)\b", + prose, + re.I, + ) + if ordered is None: + raise fail("conflicting_global_techniques") + remaining = prose[: ordered.start()] + " " + prose[ordered.end() :] + if re.search(technique_pattern, remaining, re.I): + raise fail("conflicting_global_techniques") + events = "".join(rows.get("events", "") for rows in bars.values()) + if ( + re.sub(r"[\s\[\]]", "", events) + != "x" * (len(re.sub(r"[\s\[\]]", "", events)) - 1) + "^" + ): + raise fail("ordered_technique_prose_conflicts_with_events") + prose = remaining + canonical.clear() + prose = re.sub(technique_pattern, " ", prose, flags=re.I) + return HybridDocument( + prose, + bars, + grids[0] if grids else None, + continuation, + hold_bar, + hold_pitch, + next(iter(canonical), None), + claimed, + ) + + +def count_grid( + text: str, meter: TimeSignature, grid: str | None = None +) -> list[tuple[Fraction, Fraction]]: + """Return starts/lengths in quarter beats; numbers count denominator units.""" + groups = re.findall(r"\[[^\[\]]*\]|\d+[^\d\[\]]*", text) + if re.sub(r"\s+", "", "".join(groups)) != re.sub(r"\s+", "", text): + raise fail("malformed_counts") + result = [] + previous = 0 + unit = Fraction(4, meter.denominator) + for group in groups: + bracketed = group.startswith("[") + token = re.sub(r"\s+", "", group.strip("[]")).lower() + match = re.fullmatch(r"(\d+)(.*)", token) + if match is None: + raise fail("malformed_count_label") + number, suffix = int(match[1]), match[2] + if not previous < number <= meter.numerator: + raise fail("counts_must_be_ordered_unique_and_within_meter") + previous = number + if bracketed: + if suffix != "triplet" or grid not in (None, "triplets"): + raise fail("triplet_brackets_require_number_trip_let_and_compatible_grid") + offsets = [Fraction(i, 3) for i in range(3)] + elif suffix == "": + offsets = [Fraction(0)] + elif suffix == "&" and grid in (None, "eighths", "sixteenths"): + offsets = [Fraction(0), Fraction(1, 2)] + elif suffix == "e&a" and grid in (None, "sixteenths"): + offsets = [Fraction(i, 4) for i in range(4)] + elif suffix == "&a" and grid in ("triplets", "sixteenths"): + offsets = ( + [Fraction(0), Fraction(1, 3), Fraction(2, 3)] + if grid == "triplets" + else [Fraction(0), Fraction(1, 2), Fraction(3, 4)] + ) + elif suffix == "&a": + raise fail("ambiguous_1_and_a_use_explicit_grid_or_triplet_brackets") + else: + raise fail("unsupported_count_subdivision") + for index, offset in enumerate(offsets): + end = offsets[index + 1] if index + 1 < len(offsets) else Fraction(1) + result.append(((number - 1 + offset) * unit, (end - offset) * unit)) + if not result: + raise fail("counts_required") + return result + + +def _pitches(text: str, kind: Literal["note", "chord"]) -> list[str | None]: + if kind == "note": + # Notes brackets group successive atoms, never simultaneous notes. + text = re.sub(r"\[([^\[\]]*)\]", r" \1 ", text) + if "[" in text or "]" in text: + raise fail("nested_or_unmatched_note_brackets") + result: list[str | None] = [] + # Chord voicings remain whole atoms. A '-' inside a signed octave is not a rest. + chunks = re.findall(r"\[[^\[\]]*\]|[^\s\[\]]+", text) + if re.sub(r"\s+", "", "".join(chunks)) != re.sub(r"\s+", "", text): + raise fail("malformed_pitch_brackets") + try: + for chunk in chunks: + pieces = [chunk] if chunk.startswith("[") else re.split(r"(-+(?!\d))", chunk) + for piece in pieces: + if not piece: + continue + if set(piece) == {"-"}: + result.extend([None] * len(piece)) + else: + result.extend(atom.text for atom in tokenize_notation(piece, kind=kind)) + except (ValueError, IndexError): + raise fail("invalid_pitch_lane_use_notes_or_major_minor_add4_slash_voicing") from None + return result + + +def attach(intent: MusicalIntent, doc: HybridDocument) -> MusicalIntent: + if len(intent.parts) != 1 or intent.parts == ["drums"]: + raise fail("hybrid_requires_one_pitched_part", "parts") + slots = [] + for number in sorted(set(doc.bars) | doc.continuation): + if not 1 <= number <= intent.bars: + raise fail("explicit_bar_exceeds_resolved_bars", "bars") + offset = (number - 1) * intent.time_signature.beats_per_bar + if number in doc.continuation: + slots.append( + HybridSlot( + start=beat(offset), + duration=duration(intent.time_signature.beats_per_bar), + event="~", + ) + ) + continue + rows = doc.bars[number] + if "counts" not in rows or "events" not in rows: + raise fail("each_bar_requires_counts_and_events") + positions = count_grid(rows["counts"], intent.time_signature, doc.grid) + events = re.sub(r"\s+", "", rows["events"]) + if "/" in events or "\\" in events: + raise fail("unsupported_slide_use_evidenced_origin_destination_timing_not_events_slash") + events = re.sub(r"\[[ox^\-~]+\]", lambda m: m[0][1:-1], events, flags=re.I) + if re.search(r"[^ox^\-~]", events, re.I): + raise fail("events_require_o_x_caret_dash_or_tilde") + events = events.lower() + notes = _pitches(rows["notes"], "note") if "notes" in rows else [None] * len(positions) + chords = _pitches(rows["chords"], "chord") if "chords" in rows else [None] * len(positions) + if not len(events) == len(notes) == len(chords) == len(positions): + raise fail("lane_slot_counts_and_bar_spans_must_match") + for (start, length), event, note, chord in zip( + positions, events, notes, chords, strict=True + ): + if note is not None and chord is not None: + raise fail("one_pitch_source_per_slot_not_both_notes_and_chords") + if event in "-~" and (note is not None or chord is not None): + raise fail("rests_and_continuations_cannot_specify_new_pitch") + slots.append( + HybridSlot.model_validate( + { + "start": beat(start + offset), + "duration": duration(length), + "event": event, + "pitch": note or chord, + "pitch_kind": "note" if note else "chord", + } + ) + ) + if not slots: + raise fail("hybrid_requires_notated_bar") + hold_end = ( + doc.hold_bar * intent.time_signature.beats_per_bar if doc.hold_bar is not None else None + ) + if hold_end is not None and not 0 < hold_end <= intent.duration_beats: + raise fail("hold_target_exceeds_resolved_bars", "bars") + plan = HybridPlan.model_validate( + { + "slots": slots, + "hold_end": duration(hold_end) if hold_end is not None else None, + "hold_pitch": doc.hold_pitch, + "global_technique": doc.global_technique, + "claimed_pitch": doc.claimed_pitch, + } + ) + return MusicalIntent.model_validate( + { + **intent.model_dump(), + "rhythm_terms": [], + "techniques": [], + "hybrid_plan": plan, + } + ) + + +def materialize(intent: MusicalIntent, profiles: dict[Part, InstrumentProfile]) -> MusicalIntent: + """Resolve pitch policy once against the selected profile, then reuse Step14 attacks.""" + hybrid = intent.hybrid_plan + if hybrid is None: + return intent + profile = profiles[intent.parts[0]] + part = profile.summary.part + assert part in ("lead", "bass") + attacks: list[ExplicitAttack] = [] + assumptions = [ + "hybrid: count labels use meter-denominator beats; whitespace width has no timing.", + "hybrid: exact pitches/techniques are not changed by key or style; no implicit CC.", + "velocity: existing bounded seed policy, one draw per attack shared by chord tones.", + ] + for slot in hybrid.slots: + if slot.event == "-": + continue + if slot.event == "~": + if ( + not attacks + or attacks[-1].start.value + attacks[-1].duration.value != slot.start.value + ): + raise fail("continuation_requires_adjacent_previous_sound_not_silence") + attacks[-1].duration = duration( + slot.start.value + slot.duration.value - attacks[-1].start.value + ) + continue + technique = _TECHNIQUES[slot.event] + if hybrid.global_technique is not None and technique != hybrid.global_technique: + raise fail("global_technique_conflicts_with_explicit_events") + text = slot.pitch + if text is None: + root = intent.key.split()[0] + text = root + assumptions.append( + "pitch: empty attack source uses disclosed low tonic context default." + ) + try: + value = ( + parse_chord(text) + if slot.pitch is not None and slot.pitch_kind == "chord" + else parse_pitch(text) + ) + resolved = resolve_voicing(value, profile) + if hybrid.claimed_pitch is not None and resolved.pitches != ( + resolve_voicing(parse_pitch(hybrid.claimed_pitch), profile).pitches + ): + raise fail("prose_pitch_conflicts_with_explicit_lane") + except ValueError: + raise fail("pitch_or_voicing_outside_selected_profile_or_invalid_bass") from None + assumptions.extend(resolved.assumptions) + attacks.append( + ExplicitAttack.model_validate( + { + "start": slot.start, + "duration": slot.duration, + "technique": technique, + "pitches": list(resolved.pitches), + } + ) + ) + if not attacks: + raise fail("hybrid_requires_at_least_one_attack") + if hybrid.hold_end is not None: + end = hybrid.hold_end.value + boundary = end - intent.time_signature.beats_per_bar + candidates = [attack for attack in attacks if attack.start.value < boundary] + final = candidates[-1] if candidates else attacks[-1] + if final is not attacks[-1]: + raise fail("hold_conflicts_with_explicit_rest_or_attack") + if end < final.start.value + final.duration.value: + raise fail("hold_target_precedes_final_sound_end") + if any( + slot.start.value >= final.start.value + final.duration.value + and slot.start.value < end + and slot.event != "~" + for slot in hybrid.slots + ): + raise fail("hold_conflicts_with_explicit_rest_or_attack") + if hybrid.hold_pitch is not None: + try: + matches = final.pitches == [parse_pitch(hybrid.hold_pitch).midi] + except ValueError: + matches = False + if not matches: + raise fail("hold_pitch_must_match_final_note") + final.duration = duration(end - final.start.value) + assumptions.append( + "hold: final attack extends continuously to the stated bar end, no retrigger." + ) + try: + plan = ExplicitAttackPlan( + part=part, + duration=duration(intent.duration_beats), + attacks=attacks, + assumptions=list(dict.fromkeys(assumptions)), + ) + return MusicalIntent.model_validate( + { + **intent.model_dump(), + "hybrid_plan": None, + "explicit_plan": plan, + } + ) + except ValidationError: + raise fail("hybrid_attacks_exceed_timeline_or_event_budget") from None diff --git a/src/riff_groove_builder/midi.py b/src/riff_groove_builder/midi.py new file mode 100644 index 0000000..32392cc --- /dev/null +++ b/src/riff_groove_builder/midi.py @@ -0,0 +1,310 @@ +"""Exact, profile-agnostic SMF writing from already compiled event plans.""" + +import os +import struct +from collections.abc import Callable +from fractions import Fraction +from io import BytesIO +from math import isfinite +from pathlib import Path +from typing import TypeAlias + +import mido # type: ignore[import-untyped] +from pydantic import ValidationError +from pydantic_core import PydanticSerializationError + +from riff_groove_builder.errors import OutputExistsError, OutputIOError, SerializationError +from riff_groove_builder.schemas import ( + TICKS_PER_QUARTER, + ControlChangeEvent, + EventPlan, + NoteOffEvent, + NoteOnEvent, + Part, + RationalBeat, + TimeSignature, +) + +MAX_PPQ = 0x7FFF +MAX_DELTA = 0x0FFFFFFF +_NAMES: dict[Part, str] = {"lead": "Lead", "bass": "Bass", "drums": "Drums"} +_Message: TypeAlias = mido.Message | mido.MetaMessage +_AbsoluteTrack: TypeAlias = list[tuple[int, _Message]] + + +def _check_ppq(ppq: int) -> None: + if type(ppq) is not int or not 1 <= ppq <= MAX_PPQ: + raise SerializationError(details={"reason": "invalid_ppq"}) + + +def beats_to_ticks(beats: Fraction | RationalBeat | int, ppq: int = TICKS_PER_QUARTER) -> int: + """Convert nonnegative quarter-note beats exactly; never round a sub-tick.""" + _check_ppq(ppq) + if isinstance(beats, RationalBeat): + try: + beats = type(beats).model_validate(beats.model_dump()).value + except ValidationError: + raise SerializationError(details={"reason": "invalid_beats"}) from None + if type(beats) is int: + beats = Fraction(beats) + if not isinstance(beats, Fraction) or beats < 0: + raise SerializationError(details={"reason": "invalid_beats"}) + ticks = beats * ppq + if ticks.denominator != 1: + raise SerializationError(details={"reason": "off_grid_beats"}) + return ticks.numerator + + +def bar_ticks(meter: TimeSignature, bars: int = 1, ppq: int = TICKS_PER_QUARTER) -> int: + """Return bars * numerator * 4 / denominator in exact ticks.""" + if type(bars) is not int or bars <= 0: + raise SerializationError(details={"reason": "invalid_bars"}) + try: + checked = TimeSignature.model_validate(meter.model_dump()) + except ValidationError: + raise SerializationError(details={"reason": "invalid_meter"}) from None + return beats_to_ticks(checked.beats_per_bar * bars, ppq) + + +def quarter_tempo(tempo_bpm: float) -> int: + """Nearest integer microseconds/quarter, ties to even; BPM is not meter beats.""" + if ( + type(tempo_bpm) not in (int, float) + or (isinstance(tempo_bpm, float) and not isfinite(tempo_bpm)) + or tempo_bpm <= 0 + ): + raise SerializationError(details={"reason": "invalid_tempo"}) + tempo = round(Fraction(60_000_000) / Fraction(str(tempo_bpm))) + if not 1 <= tempo <= 0xFFFFFF: + raise SerializationError(details={"reason": "unrepresentable_tempo"}) + return tempo + + +def _checked_plan(plan: EventPlan) -> EventPlan: + # Models contain mutable lists; revalidate the entire graph, not just its root. + if not isinstance(plan, EventPlan): + raise SerializationError(details={"reason": "invalid_event_plan"}) + try: + return EventPlan.model_validate(plan.model_dump(mode="python", warnings="error")) + except (ValidationError, PydanticSerializationError): + raise SerializationError(details={"reason": "invalid_event_plan"}) from None + + +def _expected_tracks(plan: EventPlan) -> list[_AbsoluteTrack]: + _check_ppq(plan.ticks_per_quarter) + # With no artificial conductor filler, its final delta spans the entire plan. + if plan.end_tick > MAX_DELTA: + raise SerializationError(details={"reason": "delta_out_of_range"}) + quarter = quarter_tempo(plan.score.intent.tempo_bpm) + for score_track in plan.score.tracks: + for note in score_track.notes: + beats_to_ticks(note.start.value - plan.score.start.value, plan.ticks_per_quarter) + beats_to_ticks(note.duration, plan.ticks_per_quarter) + + meter = plan.score.intent.time_signature + conductor: _AbsoluteTrack = [ + (0, mido.MetaMessage("track_name", name="Conductor")), + (0, mido.MetaMessage("set_tempo", tempo=quarter)), + ( + 0, + mido.MetaMessage( + "time_signature", numerator=meter.numerator, denominator=meter.denominator + ), + ), + (plan.end_tick, mido.MetaMessage("end_of_track")), + ] + tracks = [conductor] + owners: dict[int, Part] = {} + for track in plan.tracks: + output: _AbsoluteTrack = [(0, mido.MetaMessage("track_name", name=_NAMES[track.part]))] + active: dict[tuple[int, int], NoteOnEvent] = {} + for event in sorted(track.events, key=lambda event: event.ordering_key): + owner = owners.setdefault(event.channel, track.part) + if owner != track.part: + raise SerializationError( + details={ + "reason": "shared_channel", + "part": track.part, + "channel": event.channel, + } + ) + if isinstance(event, ControlChangeEvent): + message = mido.Message( + "control_change", + channel=event.channel, + control=event.controller, + value=event.value, + ) + else: + key = event.channel, event.note + context = { + "part": track.part, + "channel": event.channel, + "note": event.note, + "role": event.role, + "tick": event.tick, + } + if isinstance(event, NoteOnEvent): + if key in active: + raise SerializationError( + details={ + **context, + "reason": "same_pitch_overlap", + "active_role": active[key].role, + } + ) + active[key] = event + elif isinstance(event, NoteOffEvent): + if key not in active: + raise SerializationError(details={**context, "reason": "orphan_note_off"}) + onset = active[key] + if event.role != onset.role: + raise SerializationError( + details={**context, "reason": "note_role_mismatch"} + ) + if event.tick <= onset.tick: + raise SerializationError( + details={**context, "reason": "nonpositive_note_duration"} + ) + del active[key] + message = mido.Message( + event.kind, channel=event.channel, note=event.note, velocity=event.velocity + ) + output.append((event.tick, message)) + if active: + onset = next(iter(active.values())) + raise SerializationError( + details={ + "reason": "dangling_note", + "part": track.part, + "channel": onset.channel, + "note": onset.note, + "role": onset.role, + } + ) + output.append((plan.end_tick, mido.MetaMessage("end_of_track"))) + tracks.append(output) + return tracks + + +def validate_event_plan(plan: EventPlan) -> None: + """Check strict models, grid, SMF limits, pairing, and channel independence.""" + _expected_tracks(_checked_plan(plan)) + + +def _serialize(tracks: list[_AbsoluteTrack], ppq: int) -> bytes: + try: + midi = mido.MidiFile(type=1, ticks_per_beat=ppq) + for absolute in tracks: + track = mido.MidiTrack() + previous = 0 + for tick, message in absolute: + delta = tick - previous + if not 0 <= delta <= MAX_DELTA: + raise SerializationError(details={"reason": "delta_out_of_range"}) + track.append(message.copy(time=delta)) + previous = tick + midi.tracks.append(track) + buffer = BytesIO() + midi.save(file=buffer) + return buffer.getvalue() + except (ValueError, TypeError, OverflowError, struct.error): + raise SerializationError(details={"reason": "smf_encoding_failed"}) from None + + +def _payload(message: _Message) -> dict[str, object]: + data: dict[str, object] = message.dict() + del data["time"] + return data + + +def _validate_bytes(data: bytes, tracks: list[_AbsoluteTrack], ppq: int) -> None: + if len(data) < 14: + raise SerializationError(details={"reason": "invalid_smf_header"}) + header = struct.unpack(">4sIHHH", data[:14]) + if header != (b"MThd", 6, 1, len(tracks), ppq): + raise SerializationError(details={"reason": "smf_header_mismatch"}) + stream = BytesIO(data) + try: + midi = mido.MidiFile(file=stream, clip=False) + except (OSError, EOFError, ValueError, KeyError, IndexError, struct.error): + raise SerializationError(details={"reason": "invalid_smf_data"}) from None + if stream.read(1): + raise SerializationError(details={"reason": "trailing_smf_data"}) + if midi.type != 1 or midi.ticks_per_beat != ppq or len(midi.tracks) != len(tracks): + raise SerializationError(details={"reason": "smf_header_mismatch"}) + for index, (actual, expected) in enumerate(zip(midi.tracks, tracks, strict=True)): + observed: list[tuple[int, dict[str, object]]] = [] + tick = 0 + for message in actual: + if type(message.time) is not int or not 0 <= message.time <= MAX_DELTA: + raise SerializationError(details={"reason": "invalid_saved_delta", "track": index}) + tick += message.time + observed.append((tick, _payload(message))) + if observed != [(tick, _payload(message)) for tick, message in expected]: + raise SerializationError(details={"reason": "smf_content_mismatch", "track": index}) + + +def _read_and_validate(path: Path, tracks: list[_AbsoluteTrack], ppq: int) -> None: + try: + data = path.read_bytes() + except (OSError, ValueError): + raise OutputIOError(details={"reason": "midi_read_failed"}) from None + _validate_bytes(data, tracks, ppq) + + +def validate_midi_file(path: Path, plan: EventPlan) -> None: + """Read actual disk bytes and compare all SMF content with the supplied plan.""" + checked = _checked_plan(plan) + tracks = _expected_tracks(checked) + _read_and_validate(path, tracks, checked.ticks_per_quarter) + + +def _cleanup_owned(path: Path, identity: tuple[int, int] | None) -> None: + try: + current = path.stat() + if identity is None or (current.st_dev, current.st_ino) != identity: + raise OutputIOError(details={"reason": "midi_cleanup_ownership_changed"}) + path.unlink() + except FileNotFoundError: + return + except (OSError, ValueError): + raise OutputIOError(details={"reason": "midi_cleanup_failed"}) from None + + +def write_midi( + path: Path, plan: EventPlan, *, on_created: Callable[[os.stat_result], None] | None = None +) -> Path: + """Exclusively create one validated file; never create directories or overwrite.""" + checked = _checked_plan(plan) + tracks = _expected_tracks(checked) + data = _serialize(tracks, checked.ticks_per_quarter) + _validate_bytes(data, tracks, checked.ticks_per_quarter) + try: + if path.exists(): + raise OutputExistsError(details={"reason": "midi_destination_exists"}) + handle = path.open("xb") + except FileExistsError: + raise OutputExistsError(details={"reason": "midi_destination_exists"}) from None + except (OSError, ValueError): + raise OutputIOError(details={"reason": "midi_create_failed"}) from None + + identity: tuple[int, int] | None = None + succeeded = False + try: + try: + with handle: + owned = os.fstat(handle.fileno()) + identity = owned.st_dev, owned.st_ino + if on_created is not None: + on_created(owned) + if handle.write(data) != len(data): + raise OutputIOError(details={"reason": "midi_short_write"}) + except OSError: + raise OutputIOError(details={"reason": "midi_write_failed"}) from None + _read_and_validate(path, tracks, checked.ticks_per_quarter) + succeeded = True + return path + finally: + if not succeeded: + _cleanup_owned(path, identity) diff --git a/src/riff_groove_builder/pitch.py b/src/riff_groove_builder/pitch.py new file mode 100644 index 0000000..fc6bdd9 --- /dev/null +++ b/src/riff_groove_builder/pitch.py @@ -0,0 +1,219 @@ +"""Strict reusable notation atoms, not a lane or prose parser. C4 is MIDI 60.""" + +import re +from dataclasses import dataclass +from typing import Literal, TypeAlias + +from riff_groove_builder.profiles import InstrumentProfile, checked_profile + +_NATURALS = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11} +_OFFSETS = {"": 0, "#": 1, "b": -1} +_NOTE = r"[A-G][#b]?(?:[+-]?[0-9]{1,2})?" +_PITCH = re.compile(r"([A-G])([#b]?)([+-]?[0-9]{1,2})?") +_CHORD = re.compile( + r"([A-G][#b]?)(min|m)?([+-]?[0-9]{1,2})?(\(add4\))?" + rf"(?:(?:Over|/)({_NOTE}))?" +) +_ATOM = re.compile(rf"\[[^\[\]\r\n]*\]|{_CHORD.pattern}") +_MAX_TEXT = 4000 + + +@dataclass(frozen=True) +class PitchToken: + letter: str + accidental: str = "" + octave: int | None = None + + def __post_init__(self) -> None: + if self.letter not in _NATURALS or self.accidental not in _OFFSETS: + raise ValueError("Use A-G and at most one ASCII # or b.") + if self.octave is not None and (type(self.octave) is not int or not 0 <= self.midi <= 127): + raise ValueError("The explicit pitch must be within MIDI 0-127.") + + @property + def pitch_class(self) -> int: + return (_NATURALS[self.letter] + _OFFSETS[self.accidental]) % 12 + + @property + def midi(self) -> int: + if self.octave is None: + raise ValueError("An octave-free pitch needs an explicit register/profile policy.") + return 12 * (self.octave + 1) + _NATURALS[self.letter] + _OFFSETS[self.accidental] + + +@dataclass(frozen=True) +class ChordSymbol: + root: PitchToken + quality: Literal["major", "minor"] = "major" + add4: bool = False + bass: PitchToken | None = None + + def __post_init__(self) -> None: + if ( + not isinstance(self.root, PitchToken) + or (self.bass is not None and not isinstance(self.bass, PitchToken)) + or self.quality not in ("major", "minor") + or type(self.add4) is not bool + ): + raise ValueError("Only major, m/min and parenthesized (add4) are supported.") + + @property + def intervals(self) -> tuple[int, ...]: + third = 3 if self.quality == "minor" else 4 + return (0, third, 5, 7) if self.add4 else (0, third, 7) + + +@dataclass(frozen=True) +class ExplicitVoicing: + notes: tuple[PitchToken, ...] + + def __post_init__(self) -> None: + if ( + not isinstance(self.notes, tuple) + or not self.notes + or len(self.notes) > 128 + or any(not isinstance(note, PitchToken) for note in self.notes) + ): + raise ValueError("An explicit voicing needs 1-128 octave-qualified pitches.") + pitches = [note.midi for note in self.notes] + if len(set(pitches)) != len(pitches): + raise ValueError("Explicit voicing pitches must be unique, including enharmonics.") + + +PitchInput: TypeAlias = PitchToken | ChordSymbol | ExplicitVoicing + + +@dataclass(frozen=True) +class NotationToken: + value: PitchInput + text: str + start: int + end: int + leading_space: str + + +@dataclass(frozen=True) +class ResolvedVoicing: + pitches: tuple[int, ...] + assumptions: tuple[str, ...] = () + + +def parse_pitch(text: str) -> PitchToken: + """Parse one note; an absent octave remains unresolved.""" + match = _PITCH.fullmatch(text) + if match is None: + raise ValueError("Expected A-G, optional #/b and optional signed octave (C4=MIDI60).") + letter, accidental, octave = match.groups() + return PitchToken(letter, accidental, None if octave is None else int(octave)) + + +def parse_chord(text: str) -> ChordSymbol | ExplicitVoicing: + """Parse a major/minor/add4/slash symbol or a whitespace-delimited pitch set.""" + if len(text) > _MAX_TEXT: + raise ValueError("Notation exceeds the 4000-character bound.") + if text.startswith("[") and text.endswith("]"): + return ExplicitVoicing(tuple(parse_pitch(note) for note in text[1:-1].split())) + match = _CHORD.fullmatch(text) + if match is None: + raise ValueError("Use a bare major root, m/min, (add4), / or Over bass, or [C3 E3 G3].") + root, quality, octave, add4, bass = match.groups() + return ChordSymbol( + root=parse_pitch(root + (octave or "")), + quality="minor" if quality else "major", + add4=add4 is not None, + bass=parse_pitch(bass) if bass is not None else None, + ) + + +def tokenize_notation(text: str, *, kind: Literal["note", "chord"]) -> tuple[NotationToken, ...]: + """Lex compact atoms, retaining offsets and exact gaps, never inferring timing.""" + if kind not in ("note", "chord") or not text.strip() or len(text) > _MAX_TEXT: + raise ValueError("Choose note/chord and provide 1-4000 characters of notation.") + tokens: list[NotationToken] = [] + position = 0 + while position < len(text): + gap_start = position + while position < len(text) and text[position].isspace(): + position += 1 + if position == len(text): + break + match = (_PITCH if kind == "note" else _ATOM).match(text, position) + if match is None: + raise ValueError(f"Unsupported or ambiguous notation at character {position}.") + atom = match.group() + value = parse_pitch(atom) if kind == "note" else parse_chord(atom) + tokens.append(NotationToken(value, atom, position, match.end(), text[gap_start:position])) + position = match.end() + return tuple(tokens) + + +def validate_voicing(pitches: tuple[int, ...], profile: InstrumentProfile) -> None: + """Reject any missing tone; physical simultaneous-string allocation is native preflight.""" + playable = profile.playable_range + if not pitches or playable is None: + raise ValueError("A pitched profile and a nonempty voicing are required.") + for pitch in pitches: + if type(pitch) is not int or not 0 <= pitch <= 127: + raise ValueError("Explicit pitches must be MIDI integers 0-127.") + if not playable.low <= pitch <= playable.high: + raise ValueError(f"Explicit pitch MIDI{pitch} is outside the selected profile range.") + if profile.riffer is not None and not any( + 0 <= pitch - string.open_note <= string.max_fret for string in profile.riffer.strings + ): + raise ValueError(f"Explicit pitch MIDI{pitch} is outside the selected tuning.") + + +def resolve_voicing(value: PitchInput, profile: InstrumentProfile) -> ResolvedVoicing: + """Resolve register once, then validate without key correction, dropping or revoicing.""" + profile = checked_profile(profile) + assumptions: list[str] = [] + if isinstance(value, ExplicitVoicing): + pitches = tuple(sorted(note.midi for note in value.notes)) + else: + root = value.root if isinstance(value, ChordSymbol) else value + if root.octave is None: + playable = profile.playable_range + if playable is None: + raise ValueError("Register resolution needs a pitched profile.") + candidates = [ + pitch + for pitch in range(playable.low, playable.high + 1) + if pitch % 12 == root.pitch_class + and ( + profile.riffer is None + or any( + 0 <= pitch - string.open_note <= string.max_fret + for string in profile.riffer.strings + ) + ) + ] + if not candidates: + raise ValueError("No playable root matches the requested pitch class.") + anchor = min(candidates, key=lambda pitch: (abs(pitch - 40), pitch)) + assumptions.append( + f"Root octave omitted: using MIDI{anchor}, playable root nearest MIDI40 " + f"(lower wins ties), profile {profile.id}." + ) + else: + anchor = root.midi + pitches = ( + tuple(anchor + interval for interval in value.intervals) + if isinstance(value, ChordSymbol) + else (anchor,) + ) + if isinstance(value, ChordSymbol) and value.bass is not None: + bass = value.bass + if bass.octave is None: + bass_pitch = anchor - 1 - (anchor - 1 - bass.pitch_class) % 12 + assumptions.append( + f"Slash/Over bass octave omitted: using MIDI{bass_pitch}, " + "nearest matching bass strictly below the upper chord." + ) + else: + bass_pitch = bass.midi + if bass_pitch >= min(pitches): + raise ValueError("Slash/Over bass must be strictly below every upper chord tone.") + pitches = (bass_pitch, *pitches) + pitches = tuple(sorted(set(pitches))) + validate_voicing(pitches, profile) + return ResolvedVoicing(pitches, tuple(assumptions)) diff --git a/src/riff_groove_builder/profiles.py b/src/riff_groove_builder/profiles.py new file mode 100644 index 0000000..0c81e97 --- /dev/null +++ b/src/riff_groove_builder/profiles.py @@ -0,0 +1,613 @@ +"""Versioned declarative maps; synthetic data never enters production discovery.""" + +import json +import re +from collections.abc import Sequence +from importlib import resources +from typing import Annotated, Literal, Self, TypeAlias + +from pydantic import Field, ValidationError, model_validator +from pydantic_core import PydanticSerializationError + +from riff_groove_builder.data.profiles import PROFILE_RESOURCES +from riff_groove_builder.errors import ( + PROFILE_GUIDANCE, + ProfileNotFoundError, + ProfileRequiredError, + SerializationError, +) +from riff_groove_builder.schemas import ( + Channel, + ContractModel, + MidiData, + Nonblank, + Part, + PositiveBeat, + ProfileSelection, + ProfileSummary, + RationalBeat, +) + +Identifier: TypeAlias = Annotated[str, Field(pattern=r"^[a-z0-9][a-z0-9._-]*(?![\s\S])")] +Velocity: TypeAlias = Annotated[int, Field(ge=1, le=127)] +Intensity: TypeAlias = Annotated[float, Field(ge=0, le=1)] +EvidenceAspect: TypeAlias = Literal[ + "identity", "range_or_voices", "channels", "actions", "state_reset", "timing", "velocity" +] +_ASPECTS: set[EvidenceAspect] = { + "identity", + "range_or_voices", + "channels", + "actions", + "state_reset", + "timing", + "velocity", +} + + +class InvalidProfileError(SerializationError): + public_message = ( + "The profile is invalid; repair its versioned mapping and evidence before retrying." + ) + + +class ProfileRegistryError(SerializationError): + public_message = "Profile resources failed validation; repair the installed profile package." + + +class AmbiguousProfileError(ProfileRequiredError): + public_message = ( + "Select an explicit production profile ID; no unique default is available. " + "Call list_instrument_profiles({}) and use an exact available ID for the part." + ) + + +class ProfilePartMismatchError(ProfileRequiredError): + public_message = ( + "Select a production profile that belongs to the requested part. " + PROFILE_GUIDANCE + ) + + +def normalize_name(name: str) -> str: + """Case-fold and collapse ASCII spaces, hyphens and underscores, not arbitrary text.""" + normalized = re.sub(r"[ _-]+", "_", name.strip().casefold()) + if not re.fullmatch(r"[a-z0-9]+(?:_[a-z0-9]+)*", normalized): + raise ValueError("Use ASCII articulation or voice names.") + return normalized + + +class EvidenceSource(ContractModel): + kind: Literal["official_public", "lawful_local", "standard_public", "generator_policy"] + reference: Nonblank + aspects: Annotated[list[EvidenceAspect], Field(min_length=1)] + + @model_validator(mode="after") + def source(self) -> Self: + if len(set(self.aspects)) != len(self.aspects): + raise ValueError("Evidence aspects must be unique.") + if self.kind in ("official_public", "standard_public") and not self.reference.startswith( + "https://" + ): + raise ValueError("Public evidence needs an exact HTTPS source.") + if self.kind == "generator_policy" and not self.reference.startswith("docs/"): + raise ValueError("Generator policy needs a repository documentation reference.") + return self + + +class Provenance(ContractModel): + status: Literal["test_only", "verified", "verified_subset", "standard_midi"] + product_version: Nonblank + mapping_version: Nonblank + target_build: Nonblank + mapping_preset: Nonblank + sources: list[EvidenceSource] + limitations: Annotated[list[Nonblank], Field(min_length=1)] + + @model_validator(mode="after") + def evidence(self) -> Self: + coverage = {aspect for source in self.sources for aspect in source.aspects} + if self.status == "verified" and coverage != _ASPECTS: + raise ValueError("Verified profiles require evidence for every mapping aspect.") + if self.status == "verified" and any( + source.kind not in ("official_public", "lawful_local") for source in self.sources + ): + raise ValueError("Standard facts and generator policy do not verify vendor maps.") + if self.status == "standard_midi": + facts = {a for s in self.sources if s.kind == "standard_public" for a in s.aspects} + policy = {a for s in self.sources if s.kind == "generator_policy" for a in s.aspects} + if ( + any(s.kind not in ("standard_public", "generator_policy") for s in self.sources) + or not {"identity", "range_or_voices"} <= facts + or not (_ASPECTS - {"identity", "range_or_voices"}) <= policy + ): + raise ValueError( + "Standard MIDI requires separate public facts and generator policy." + ) + if self.status == "test_only" and self.sources: + raise ValueError("Synthetic fixtures must not present vendor evidence.") + if self.status == "verified_subset": + facts = { + a + for s in self.sources + if s.kind in ("official_public", "lawful_local") + for a in s.aspects + } + policy = {a for s in self.sources if s.kind == "generator_policy" for a in s.aspects} + if ( + not {"identity", "range_or_voices", "actions", "velocity"} <= facts + or not {"channels", "state_reset", "timing"} <= policy + or any(s.kind == "standard_public" for s in self.sources) + ): + raise ValueError( + "Verified subsets need vendor facts and separate generator policy." + ) + return self + + +class PlayableRange(ContractModel): + low: MidiData + high: MidiData + + @model_validator(mode="after") + def ordered(self) -> Self: + if self.low > self.high: + raise ValueError("Playable range is reversed.") + return self + + +class DrumVoice(ContractModel): + name: Nonblank + aliases: list[Nonblank] + note: MidiData + + +class VelocityLayer(ContractModel): + """Intensity intervals are [low, high), except the final interval includes 1.""" + + low: Intensity + high: Intensity + velocity_low: Velocity + velocity_high: Velocity + + @model_validator(mode="after") + def ordered(self) -> Self: + if self.low >= self.high or self.velocity_low > self.velocity_high: + raise ValueError("Layer bounds must be ordered.") + return self + + +class KeyswitchAction(ContractModel): + kind: Literal["keyswitch"] + note: MidiData + velocity: Velocity + behavior: Literal["pulse", "hold"] + lead: RationalBeat + gate: PositiveBeat + release_offset: RationalBeat + + @model_validator(mode="after") + def release(self) -> Self: + if self.behavior == "pulse" and self.release_offset.value: + raise ValueError("Pulse duration uses gate, not release_offset.") + return self + + +class CCAction(ContractModel): + kind: Literal["cc"] + controller: MidiData + value: MidiData + reset_value: MidiData | None + lead: RationalBeat + release_offset: RationalBeat + + +Action: TypeAlias = Annotated[KeyswitchAction | CCAction, Field(discriminator="kind")] + + +class Articulation(ContractModel): + name: Nonblank + aliases: list[Nonblank] + mode: Literal["latched", "momentary"] + actions: list[Action] + layers: Annotated[list[VelocityLayer], Field(min_length=1)] + + @model_validator(mode="after") + def mechanics(self) -> Self: + if self.layers[0].low != 0 or self.layers[-1].high != 1: + raise ValueError("Layers must cover the complete intensity range.") + for left, right in zip(self.layers, self.layers[1:], strict=False): + if left.high != right.low or left.velocity_high >= right.velocity_low: + raise ValueError("Layer intervals must be contiguous and velocities monotonic.") + controls: set[tuple[str, int]] = set() + for action in self.actions: + key = ( + action.kind, + action.note if isinstance(action, KeyswitchAction) else action.controller, + ) + if key in controls: + raise ValueError("An articulation cannot set the same physical control twice.") + controls.add(key) + if isinstance(action, CCAction): + if self.mode == "momentary" and action.reset_value is None: + raise ValueError("Momentary CC actions require explicit resets.") + if self.mode == "latched" and ( + action.reset_value is not None or action.release_offset.value + ): + raise ValueError("Latched CC actions cannot declare momentary resets.") + elif self.mode == "latched" and action.behavior != "pulse": + raise ValueError("Latched switches require positive pulse gates.") + return self + + def velocity(self, intensity: float) -> int: + if type(intensity) not in (int, float) or not 0 <= intensity <= 1: + raise InvalidProfileError(details={"reason": "invalid_intensity"}) + for layer in self.layers: + if layer.low <= intensity < layer.high or intensity == layer.high == 1: + fraction = (intensity - layer.low) / (layer.high - layer.low) + return round( + layer.velocity_low + fraction * (layer.velocity_high - layer.velocity_low) + ) + raise InvalidProfileError(details={"reason": "uncovered_intensity"}) + + +def _names(items: Sequence[Articulation | DrumVoice]) -> dict[str, int]: + names: dict[str, int] = {} + for index, item in enumerate(items): + for name in [item.name, *item.aliases]: + normalized = normalize_name(name) + if normalized in names: + raise ValueError("Names and aliases collide after normalization.") + names[normalized] = index + return names + + +class RifferString(ContractModel): + id: Annotated[int, Field(ge=1, le=6)] + open_note: MidiData + max_fret: Annotated[int, Field(ge=0, le=24)] + + @model_validator(mode="after") + def range(self) -> Self: + if self.open_note + self.max_fret > 127: + raise ValueError("String frets must stay in the MIDI pitch range.") + return self + + +class RifferSettings(ContractModel): + """Declarative supported subset, never a template or executable codec.""" + + layout_version: Literal["2.1"] + ppq: Literal[480] + instrument: Literal["AME", "AMR"] + extension: Literal["griff", "briff"] + strings: Annotated[list[RifferString], Field(min_length=5, max_length=6)] + articulations: dict[ + Literal["normal", "palm_mute", "pinch_harmonic"], Literal["Sus", "PM", "PMP", "PH"] + ] + controllers: list[Literal[1]] + + @model_validator(mode="before") + @classmethod + def numeric_literals(cls, value: object) -> object: + if isinstance(value, dict) and ( + ("ppq" in value and type(value["ppq"]) is not int) + or ( + isinstance(value.get("controllers"), list) + and any(type(c) is not int for c in value["controllers"]) + ) + ): + raise ValueError("PPQ and controller numbers must be integers, not booleans.") + return value + + @model_validator(mode="after") + def representations(self) -> Self: + count = 6 if self.instrument == "AME" else 5 + if ( + type(self.ppq) is not int + or [s.id for s in self.strings] != list(range(count, 0, -1)) + or self.extension != ("griff" if self.instrument == "AME" else "briff") + or self.articulations + != { + "normal": "Sus", + "palm_mute": "PM" if self.instrument == "AME" else "PMP", + **({"pinch_harmonic": "PH"} if self.instrument == "AME" else {}), + } + or self.controllers not in ([], [1]) + or any(type(c) is not int for c in self.controllers) + ): + raise ValueError("Unsupported Riffer string, articulation, or CC representation.") + tuning, fret_limit = ( + ([36, 43, 48, 53, 57, 62], 22) + if self.instrument == "AME" + else ([35, 40, 45, 50, 55], 19) + ) + if [s.open_note for s in self.strings] != tuning or any( + s.max_fret != fret_limit for s in self.strings + ): + raise ValueError( + "Only the evidenced default tuning and conservative fret policy apply." + ) + return self + + +class SdpSettings(ContractModel): + """Only the locally evidenced SD3 build/library subset, not a generic GM map.""" + + layout_version: Literal["3.4.4"] + extension: Literal["sd3p"] + sound_library: Literal["SL-DFH"] + + +class InstrumentProfile(ContractModel): + schema_version: Literal["1"] + id: Identifier + summary: ProfileSummary + provenance: Provenance + default: bool + channel: Channel + playable_range: PlayableRange | None + drum_voices: list[DrumVoice] + normal_articulation: Nonblank + articulations: Annotated[list[Articulation], Field(min_length=1)] + riffer: RifferSettings | None = None + sdp: SdpSettings | None = None + + @model_validator(mode="after") + def mapping(self) -> Self: + if ( + self.id != self.summary.id + or self.summary.product_version != self.provenance.product_version + or self.summary.mapping_version != self.provenance.mapping_version + or self.summary.supported_articulations != [art.name for art in self.articulations] + or not self.summary.midi_available + or self.summary.native_available != (self.riffer is not None or self.sdp is not None) + or self.summary.limitations != self.provenance.limitations + ): + raise ValueError("Identity/capabilities/provenance metadata must agree.") + if self.sdp is not None: + if ( + self.riffer is not None + or (self.summary.part, self.summary.product_version, self.summary.native_format) + != ("drums", "3.4.4", "sd3p") + or self.provenance.status != "verified_subset" + or self.summary.mapping_kind != "instrument" + or self.channel != 9 + or self.normal_articulation != "normal" + or len(self.articulations) != 1 + or self.articulations[0].name != "normal" + or self.articulations[0].mode != "latched" + or self.articulations[0].actions + or len(self.articulations[0].layers) != 1 + or ( + self.articulations[0].layers[0].velocity_low, + self.articulations[0].layers[0].velocity_high, + ) + != (1, 127) + or [(v.name, v.note) for v in self.drum_voices] + != [("kick", 36), ("snare", 38), ("closed_hat", 42)] + ): + raise ValueError("SD3 requires its evidence-backed core subset.") + if self.riffer is not None: + expected = ( + ("lead", "4.0.1", "griff") + if self.riffer.instrument == "AME" + else ("bass", "4.1.0", "briff") + ) + if ( + (self.summary.part, self.summary.product_version, self.summary.native_format) + != expected + or self.provenance.status != "verified_subset" + or self.summary.mapping_kind != "instrument" + or self.normal_articulation != "normal" + or self.playable_range is None + or set(self.summary.supported_articulations) != set(self.riffer.articulations) + or self.playable_range.low != min(s.open_note for s in self.riffer.strings) + or self.playable_range.high + != max(s.open_note + s.max_fret for s in self.riffer.strings) + ): + raise ValueError("Riffer requires a matching evidence-backed subset.") + for art in self.articulations: + switch = ( + {"normal": 24, "palm_mute": 26, "pinch_harmonic": 31}[art.name] + if self.riffer.instrument == "AME" + else 24 + ) + bounds = ( + (64, 126) + if art.name == "normal" + else ((1, 127) if self.riffer.instrument == "AME" else (32, 63)) + ) + if ( + art.mode != "latched" + or len(art.actions) != 1 + or not isinstance(art.actions[0], KeyswitchAction) + or art.actions[0].note != switch + or art.actions[0].behavior != "pulse" + or art.actions[0].lead.value != 0 + or art.actions[0].gate.value != RationalBeat(numerator=1, denominator=32).value + or len(art.layers) != 1 + or (art.layers[0].velocity_low, art.layers[0].velocity_high) != bounds + ): + raise ValueError( + "Native subsets must preserve the evidenced technique mapping." + ) + if self.provenance.status == "test_only": + if ( + not self.id.startswith("test.") + or not self.summary.product_name.startswith("SYNTHETIC ") + or self.default + ): + raise ValueError("Synthetic profiles require test identity and cannot be defaults.") + elif self.id.startswith("test.") or self.summary.product_name.startswith("SYNTHETIC "): + raise ValueError("Test identity cannot be promoted to a production profile.") + if (self.summary.mapping_kind == "standard_midi") != ( + self.provenance.status == "standard_midi" + ): + raise ValueError("Standard MIDI mapping kind and provenance must agree.") + if self.summary.mapping_kind == "standard_midi" and ( + not self.summary.product_name.startswith(("Standard MIDI ", "General MIDI ")) + or self.normal_articulation != "normal" + or len(self.articulations) != 1 + or self.articulations[0].name != "normal" + or self.articulations[0].aliases != ["sustain"] + or self.articulations[0].mode != "latched" + or self.articulations[0].actions + ): + raise ValueError( + "Standard MIDI declares only action-free normal/sustain, not vendor controls." + ) + names = _names(self.articulations) + if ( + self.normal_articulation not in [art.name for art in self.articulations] + or normalize_name(self.normal_articulation) not in names + ): + raise ValueError("Normal technique must be a declared canonical articulation.") + normal = self.resolve_articulation(self.normal_articulation) + controlled = any(art.actions for art in self.articulations) + if normal.mode != "latched" or ( + controlled and any(not art.actions for art in self.articulations) + ): + raise ValueError("Stateful profiles need explicit selection/restoration actions.") + if self.summary.part == "drums": + if self.playable_range is not None or not self.drum_voices: + raise ValueError("Drums require explicit voices, not a pitched range.") + _names(self.drum_voices) + pitches = {voice.note for voice in self.drum_voices} + if len(pitches) != len(self.drum_voices): + raise ValueError("Drum voices need unambiguous physical notes.") + else: + if self.playable_range is None or self.drum_voices: + raise ValueError("Pitched parts require a range and no drum voices.") + pitches = set(range(self.playable_range.low, self.playable_range.high + 1)) + switches = { + action.note + for art in self.articulations + for action in art.actions + if isinstance(action, KeyswitchAction) + } + if pitches & switches: + raise ValueError("Musical pitches cannot collide with keyswitches.") + # Every latched state must set the same controls; omitted controls otherwise leak state. + latched = [art for art in self.articulations if art.mode == "latched"] + footprints = [ + { + (a.kind, a.note if isinstance(a, KeyswitchAction) else a.controller) + for a in art.actions + if isinstance(a, CCAction) + } + for art in latched + ] + if any(footprint != footprints[0] for footprint in footprints): + raise ValueError("Latched techniques must explicitly set all latched CC controls.") + return self + + def resolve_articulation(self, name: str) -> Articulation: + return self.articulations[_names(self.articulations)[normalize_name(name)]] + + def resolve_voice(self, name: str) -> int: + return self.drum_voices[_names(self.drum_voices)[normalize_name(name)]].note + + +def parse_profile(data: str | bytes) -> InstrumentProfile: + try: + # Reject duplicate JSON object keys instead of silently taking the final value. + def pairs(items: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in items: + if key in result: + raise ValueError("duplicate key") + result[key] = value + return result + + return InstrumentProfile.model_validate(json.loads(data, object_pairs_hook=pairs)) + except (ValueError, UnicodeError): + raise InvalidProfileError(details={"reason": "invalid_profile_document"}) from None + + +def checked_profile(profile: InstrumentProfile) -> InstrumentProfile: + if not isinstance(profile, InstrumentProfile): + raise InvalidProfileError(details={"reason": "invalid_profile_model"}) + try: + return InstrumentProfile.model_validate(profile.model_dump(mode="python", warnings="error")) + except (ValidationError, PydanticSerializationError): + raise InvalidProfileError(details={"reason": "invalid_profile_model"}) from None + + +class ProfileRegistry: + """Verified instrument maps or labeled standard MIDI; never upgraded test data.""" + + def __init__(self, profiles: list[InstrumentProfile]) -> None: + checked = [checked_profile(profile) for profile in profiles] + if any(p.provenance.status == "test_only" for p in checked): + raise ProfileRegistryError(details={"reason": "synthetic_production_leakage"}) + if len({p.id for p in checked}) != len(checked): + raise ProfileRegistryError(details={"reason": "duplicate_profile_id"}) + defaults = [p.summary.part for p in checked if p.default] + if len(set(defaults)) != len(defaults): + raise ProfileRegistryError(details={"reason": "duplicate_default"}) + self._profiles = {p.id: p for p in sorted(checked, key=lambda p: p.id)} + + def summaries(self) -> list[ProfileSummary]: + return [ + ProfileSummary.model_validate(p.summary.model_dump()) for p in self._profiles.values() + ] + + def select( + self, parts: list[Part], selection: ProfileSelection + ) -> dict[Part, InstrumentProfile]: + explicit = ProfileSelection.model_validate(selection.model_dump()).selected() + if ( + not parts + or any(part not in ("lead", "bass", "drums") for part in parts) + or len(set(parts)) != len(parts) + or any(part not in parts for part in explicit) + ): + raise ProfilePartMismatchError(details={"reason": "profile_selection_parts"}) + result: dict[Part, InstrumentProfile] = {} + for part in parts: + choices = [p for p in self._profiles.values() if p.summary.part == part] + if part in explicit: + profile = self._profiles.get(explicit[part]) + if profile is None: + raise ProfileNotFoundError(details={"part": part, "reason": "missing_profile"}) + if profile.summary.part != part: + raise ProfilePartMismatchError(details={"part": part, "reason": "wrong_part"}) + else: + defaults = [p for p in choices if p.default] + if len(defaults) == 1: + profile = defaults[0] + elif choices: + raise AmbiguousProfileError( + details={ + "part": part, + "reason": "select_explicit_id", + "available_ids": [p.id for p in choices], + } + ) + else: + raise ProfileRequiredError( + details={"part": part, "reason": "verified_mapping_required"} + ) + result[part] = checked_profile(profile) + return result + + +def load_profile_registry( + *, + package: str = "riff_groove_builder.data.profiles", + declared: tuple[str, ...] = PROFILE_RESOURCES, +) -> ProfileRegistry: + """Load exactly the declared resources; never hide missing or undeclared maps.""" + if len(set(declared)) != len(declared) or any( + not re.fullmatch(r"[a-z0-9][a-z0-9._-]*\.json", name) for name in declared + ): + raise ProfileRegistryError(details={"reason": "invalid_resource_manifest"}) + try: + root = resources.files(package) + present = {entry.name for entry in root.iterdir() if entry.name.endswith(".json")} + if present != set(declared): + raise ProfileRegistryError(details={"reason": "resource_manifest_mismatch"}) + profiles = [parse_profile(root.joinpath(name).read_bytes()) for name in declared] + except (OSError, ImportError, TypeError, UnicodeError): + raise ProfileRegistryError(details={"reason": "profile_resource_load_failed"}) from None + return ProfileRegistry(profiles) diff --git a/src/riff_groove_builder/schemas.py b/src/riff_groove_builder/schemas.py new file mode 100644 index 0000000..5d74458 --- /dev/null +++ b/src/riff_groove_builder/schemas.py @@ -0,0 +1,919 @@ +"""Authoritative tool/domain contracts. No inference, scheduling, or filesystem IO.""" + +import re +from fractions import Fraction +from math import gcd +from pathlib import PurePosixPath, PureWindowsPath +from typing import Annotated, Literal, Self, TypeAlias, TypeVar + +from pydantic import ( + AfterValidator, + BaseModel, + ConfigDict, + Field, + JsonValue, + TypeAdapter, + field_validator, + model_validator, +) +from pydantic.json_schema import JsonSchemaValue +from pydantic_core import PydanticCustomError + +from riff_groove_builder.errors import ( + FIELD_GUIDANCE, + REQUEST_ISSUES, + DomainError, + ErrorCode, +) + +Part: TypeAlias = Literal["lead", "bass", "drums"] +MappingKind: TypeAlias = Literal["instrument", "standard_midi"] +OutputFormat: TypeAlias = Literal["mid", "agp", "sdp", "griff", "briff", "sd3p"] +ArtifactFormat: TypeAlias = Literal["mid", "griff", "briff", "sd3p"] +ToolName: TypeAlias = Literal["list_instrument_profiles", "generate_music"] +TICKS_PER_QUARTER = 960 +MAX_SCHEDULED_EVENTS = 100_000 + + +T = TypeVar("T") + + +def _unique(values: list[T]) -> list[T]: + if any(value in values[:index] for index, value in enumerate(values)): + raise PydanticCustomError("unique_items", "List members must be unique; remove duplicates.") + return values + + +Nonblank: TypeAlias = Annotated[str, Field(min_length=1, pattern=r"\S")] +Parts: TypeAlias = Annotated[ + list[Part], + Field(min_length=1, json_schema_extra={"uniqueItems": True}), + AfterValidator(_unique), +] +Formats: TypeAlias = Annotated[ + list[OutputFormat], + Field(min_length=1, json_schema_extra={"uniqueItems": True}), + AfterValidator(_unique), +] +UniqueText: TypeAlias = Annotated[ + list[Nonblank], Field(json_schema_extra={"uniqueItems": True}), AfterValidator(_unique) +] +Tempo: TypeAlias = Annotated[float, Field(ge=20, le=300)] +Bars: TypeAlias = Annotated[int, Field(ge=1, le=256)] +Seed: TypeAlias = Annotated[int, Field(ge=0, le=2_147_483_647)] +MidiData: TypeAlias = Annotated[int, Field(ge=0, le=127)] +Channel: TypeAlias = Annotated[int, Field(ge=0, le=15)] +Tick: TypeAlias = Annotated[int, Field(ge=0)] +PositiveInt: TypeAlias = Annotated[int, Field(gt=0)] + +BASENAME_PATTERN = ( + r"^(?!(?:[Cc][Oo][Nn]|[Pp][Rr][Nn]|[Aa][Uu][Xx]|[Nn][Uu][Ll]|" + r"[Cc][Oo][Mm][1-9]|[Ll][Pp][Tt][1-9])$)[A-Za-z0-9][A-Za-z0-9_-]{0,63}(?![\s\S])" +) +KEY_PATTERN = ( + r"^ *[A-Ga-g](?:#|b)?(?: +(?:[Mm][Aa][Jj][Oo][Rr]|[Mm][Ii][Nn][Oo][Rr])|m) *(?![\s\S])" +) + + +def _normalize_key(value: str) -> str: + match = re.fullmatch( + r" *([A-Ga-g])([#b]?)(?: +([Mm][Aa][Jj][Oo][Rr]|[Mm][Ii][Nn][Oo][Rr])|(m)) *", + value, + ) + if match is None: + raise ValueError("Use a pitch class and major/minor, for example 'F# minor' or 'Bb major'.") + letter, accidental, full_mode, _minor_suffix = match.groups() + mode = full_mode or "minor" + # The grammar accepts lowercase b only, not an uppercase accidental. + if not re.fullmatch(KEY_PATTERN, value): + raise ValueError("Use one conventional '#' or 'b' accidental and major/minor.") + natural = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}[letter.upper()] + offset = {"": 0, "#": 1, "b": -1}[accidental] + pitch_classes = ("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B") + return f"{pitch_classes[(natural + offset) % 12]} {mode.lower()}" + + +Key: TypeAlias = Annotated[ + str, + Field( + pattern=KEY_PATTERN, + description=FIELD_GUIDANCE["key"], + examples=["E minor", "E Minor", "Em", "F#m", "Bb major"], + ), + AfterValidator(_normalize_key), +] +Basename: TypeAlias = Annotated[ + str, + Field( + min_length=1, + max_length=64, + pattern=BASENAME_PATTERN, + description="ASCII basename only; no paths, extensions, or Windows device names.", + ), +] + + +class ContractModel(BaseModel): + model_config = ConfigDict( + extra="forbid", + strict=True, + allow_inf_nan=False, + validate_default=True, + regex_engine="python-re", + ) + + +class TimeSignature(ContractModel): + numerator: Annotated[int, Field(ge=1, le=16)] + denominator: Literal[1, 2, 4, 8, 16] + + @field_validator("denominator", mode="before") + @classmethod + def strict_denominator(cls, value: object) -> object: + if type(value) is not int: + raise PydanticCustomError( + "int_type", "Meter denominator must be an integer: 1, 2, 4, 8, or 16." + ) + return value + + @property + def beats_per_bar(self) -> Fraction: + return Fraction(self.numerator * 4, self.denominator) + + +class ProfileSelection(ContractModel): + lead: Nonblank | None = None + bass: Nonblank | None = None + drums: Nonblank | None = None + + def selected(self) -> dict[Part, str]: + pairs: tuple[tuple[Part, str | None], ...] = ( + ("lead", self.lead), + ("bass", self.bass), + ("drums", self.drums), + ) + return {part: profile for part, profile in pairs if profile is not None} + + +def _request_conditions() -> list[JsonSchemaValue]: + conditions: list[JsonSchemaValue] = [] + for output_format, applicable in ( + ("agp", ["lead", "bass"]), + ("sdp", ["drums"]), + ("griff", ["lead"]), + ("briff", ["bass"]), + ("sd3p", ["drums"]), + ): + conditions.append( + { + "if": { + "required": ["parts", "formats"], + "properties": { + "parts": {"type": "array"}, + "formats": {"type": "array", "contains": {"const": output_format}}, + }, + }, + "then": {"properties": {"parts": {"contains": {"enum": applicable}}}}, + } + ) + for part in ("lead", "bass", "drums"): + conditions.append( + { + "if": { + "required": ["parts", "cc_events"], + "properties": { + "cc_events": {"contains": {"properties": {"part": {"const": part}}}} + }, + }, + "then": {"properties": {"parts": {"contains": {"const": part}}}}, + } + ) + conditions.append( + { + "if": { + "required": ["parts", "profiles"], + "properties": { + "parts": {"type": "array"}, + "profiles": { + "type": "object", + "required": [part], + "properties": {part: {"type": "string"}}, + }, + }, + }, + "then": {"properties": {"parts": {"contains": {"const": part}}}}, + } + ) + return conditions + + +def _request_schema(schema: JsonSchemaValue) -> None: + schema["allOf"] = _request_conditions() + + +def _profile_schema(schema: JsonSchemaValue) -> None: + schema["allOf"] = [ + { + "if": {"properties": {"part": {"const": part}}}, + "then": { + "properties": { + "instrument": {"const": instrument}, + "native_format": {"const": native}, + } + }, + } + for part, instrument, native in ( + ("lead", "eclips", "griff"), + ("bass", "ray", "briff"), + ("drums", "sd3", "sd3p"), + ) + ] + [ + { + "if": { + "required": ["mapping_kind"], + "properties": {"mapping_kind": {"const": "standard_midi"}}, + }, + "then": { + "properties": { + "native_available": {"const": False}, + "supported_articulations": {"const": ["normal"]}, + } + }, + }, + { + "if": { + "anyOf": [ + {"properties": {"midi_available": {"const": False}}}, + {"properties": {"native_available": {"const": False}}}, + ] + }, + "then": {"properties": {"limitations": {"minItems": 1}}}, + }, + ] + + +def _artifact_schema(schema: JsonSchemaValue) -> None: + schema["allOf"] = [ + { + "if": {"properties": {"format": {"const": extension}}}, + "then": { + "properties": { + "parts": {"const": [part]}, + "fallback_for": {"maxItems": 0}, + } + }, + } + for extension, part in (("griff", "lead"), ("briff", "bass"), ("sd3p", "drums")) + ] + [ + { + "if": {"properties": {"format": {"const": extension}}}, + "then": { + "properties": { + "path": {"pattern": rf"\.{extension}$"}, + } + }, + } + for extension in ("mid", "griff", "briff", "sd3p") + ] + + +def _result_schema(schema: JsonSchemaValue) -> None: + schema["allOf"] = [ + { + "if": {"properties": {"status": {"const": "complete"}}}, + "then": { + "properties": { + "artifacts": {"items": {"properties": {"fallback_for": {"maxItems": 0}}}}, + "warnings": { + "items": { + "properties": {"code": {"not": {"const": "NATIVE_FORMAT_UNAVAILABLE"}}} + } + }, + } + }, + "else": { + "properties": { + "artifacts": { + "contains": { + "properties": { + "format": {"const": "mid"}, + "fallback_for": {"minItems": 1}, + } + } + }, + "warnings": { + "contains": { + "properties": { + "code": {"const": "NATIVE_FORMAT_UNAVAILABLE"}, + "part": {"enum": ["lead", "bass", "drums"]}, + } + } + }, + } + }, + } + ] + + +class ListInstrumentProfilesRequest(ContractModel): + pass + + +class RationalBeat(ContractModel): + """Nonnegative quarter-note beats, serialized as a reduced integer ratio.""" + + numerator: Annotated[int, Field(ge=0)] + denominator: PositiveInt = 1 + + @model_validator(mode="after") + def reduce(self) -> Self: + divisor = gcd(self.numerator, self.denominator) + self.numerator //= divisor + self.denominator //= divisor + return self + + @property + def value(self) -> Fraction: + return Fraction(self.numerator, self.denominator) + + +class ScheduledControl(ContractModel): + """An exact CC point relative to musical start, not an inferred technique.""" + + part: Part + beat: RationalBeat + controller: MidiData + value: MidiData + + +class GenerateMusicRequest(ContractModel): + model_config = ConfigDict(json_schema_extra=_request_schema) + + description: Annotated[ + str, + Field( + min_length=1, + max_length=4000, + pattern=r"\S", + description=FIELD_GUIDANCE["description"], + ), + ] + basename: Basename + parts: Parts | None = Field(default=None, description=FIELD_GUIDANCE["parts"]) + formats: Formats | None = Field(default=None, description=FIELD_GUIDANCE["formats"]) + tempo_bpm: Tempo | None = Field(default=None, description=FIELD_GUIDANCE["tempo_bpm"]) + bars: Bars | None = Field(default=None, description=FIELD_GUIDANCE["bars"]) + time_signature: TimeSignature | None = Field( + default=None, description=FIELD_GUIDANCE["time_signature"] + ) + key: Key | None = None + profiles: ProfileSelection | None = Field(default=None, description=FIELD_GUIDANCE["profiles"]) + seed: Seed = 0 + allow_midi_fallback: bool = True + cc_events: Annotated[list[ScheduledControl], Field(max_length=MAX_SCHEDULED_EVENTS)] = Field( + default_factory=list, + description=FIELD_GUIDANCE["cc_events"], + ) + + @model_validator(mode="after") + def explicit_combinations(self) -> Self: + points = [(cc.part, cc.beat.value, cc.controller) for cc in self.cc_events] + if len(set(points)) != len(points): + raise PydanticCustomError("cc_duplicates", REQUEST_ISSUES["cc_duplicates"][1]) + if any((cc.beat.value * TICKS_PER_QUARTER).denominator != 1 for cc in self.cc_events): + raise PydanticCustomError("cc_grid", REQUEST_ISSUES["cc_grid"][1]) + if self.parts is not None: + if any(cc.part not in self.parts for cc in self.cc_events): + raise PydanticCustomError("cc_parts", REQUEST_ISSUES["cc_parts"][1]) + if self.profiles is not None and set(self.profiles.selected()) - set(self.parts): + raise PydanticCustomError("profile_parts", REQUEST_ISSUES["profile_parts"][1]) + if self.formats is not None: + if "agp" in self.formats and not {"lead", "bass"}.intersection(self.parts): + raise PydanticCustomError("format_parts", REQUEST_ISSUES["format_parts"][1]) + if "sdp" in self.formats and "drums" not in self.parts: + raise PydanticCustomError("format_parts", REQUEST_ISSUES["format_parts"][1]) + for extension, part in (("griff", "lead"), ("briff", "bass"), ("sd3p", "drums")): + if extension in self.formats and part not in self.parts: + raise PydanticCustomError("format_parts", REQUEST_ISSUES["format_parts"][1]) + return self + + +class ProfileSummary(ContractModel): + model_config = ConfigDict(json_schema_extra=_profile_schema) + + id: Nonblank + part: Part + mapping_kind: MappingKind = "instrument" + instrument: Literal["eclips", "ray", "sd3"] + product_name: Nonblank + product_version: Nonblank + mapping_version: Nonblank + midi_available: bool + native_format: Literal["griff", "briff", "sd3p"] + native_available: bool + supported_articulations: UniqueText + limitations: UniqueText + + @model_validator(mode="after") + def capabilities(self) -> Self: + expected = { + "lead": ("eclips", "griff"), + "bass": ("ray", "briff"), + "drums": ("sd3", "sd3p"), + } + if (self.instrument, self.native_format) != expected[self.part]: + raise ValueError("Use Eclipse/griff for lead, Ray5/briff for bass, or SD3/sd3p.") + if (not self.midi_available or not self.native_available) and not self.limitations: + raise ValueError("Unavailable capabilities require explicit public limitations.") + if self.mapping_kind == "standard_midi" and ( + self.native_available or self.supported_articulations != ["normal"] + ): + raise ValueError("Standard MIDI supports normal only and has no native capability.") + return self + + +class ProfileListResult(ContractModel): + profiles: list[ProfileSummary] + + @model_validator(mode="after") + def unique_ids(self) -> Self: + _unique([profile.id for profile in self.profiles]) + return self + + +class PositiveBeat(RationalBeat): + numerator: PositiveInt + + +class TimedNote(ContractModel): + """Exact score-relative timing and technique, independent of a subdivision grid.""" + + start: RationalBeat + duration: PositiveBeat + technique: Literal["normal", "palm_mute", "pinch_harmonic"] + intensity: Annotated[float, Field(ge=0, le=1)] | None = None + + +class PhrasePlan(ContractModel): + """A monophonic pitched phrase; silence outside its notes is intentional.""" + + part: Literal["lead", "bass"] + register_policy: Literal["low_tonic"] = "low_tonic" + duration: PositiveBeat + notes: Annotated[list[TimedNote], Field(min_length=1, max_length=MAX_SCHEDULED_EVENTS // 2)] + + @model_validator(mode="after") + def timeline(self) -> Self: + end = Fraction(0) + for note in self.notes: + if note.start.value < end: + raise ValueError("Phrase notes must be ordered and must not overlap.") + end = note.start.value + note.duration.value + if end > self.duration.value: + raise ValueError("Phrase notes must fit the phrase duration.") + return self + + +class ExplicitAttack(TimedNote): + """One independent attack with simultaneous authoritative MIDI pitches.""" + + pitches: Annotated[ + list[MidiData], + Field(min_length=1, max_length=128, json_schema_extra={"uniqueItems": True}), + AfterValidator(_unique), + ] + + +class ExplicitAttackPlan(ContractModel): + """Polyphonic exact attacks; gaps are silence, duration sustains without retrigger.""" + + part: Literal["lead", "bass"] + duration: PositiveBeat + attacks: Annotated[ + list[ExplicitAttack], Field(min_length=1, max_length=MAX_SCHEDULED_EVENTS // 2) + ] + assumptions: UniqueText = Field(default_factory=list) + + @model_validator(mode="after") + def timeline(self) -> Self: + if self.duration.value > 256 * 16 * 4: + raise ValueError("Explicit plan exceeds the maximum supported score timeline.") + previous = Fraction(0) + pitch_ends: dict[int, Fraction] = {} + technique_ends: dict[str, Fraction] = {} + count = 0 + for attack in self.attacks: + start = attack.start.value + end = start + attack.duration.value + if start < previous or end > self.duration.value: + raise ValueError("Attacks must be start-ordered and fit the plan duration.") + if any(pitch_ends.get(pitch, Fraction(0)) > start for pitch in attack.pitches): + raise ValueError("Independent same-pitch attacks must not overlap.") + if any( + technique != attack.technique and active_end > start + for technique, active_end in technique_ends.items() + ): + raise ValueError("Overlapping attacks require compatible shared technique.") + for pitch in attack.pitches: + pitch_ends[pitch] = end + technique_ends[attack.technique] = max( + end, technique_ends.get(attack.technique, Fraction(0)) + ) + previous = start + count += len(attack.pitches) * 2 + if count > MAX_SCHEDULED_EVENTS: + raise ValueError("Expanded chord tones exceed the note-pair event budget.") + return self + + +class HybridSlot(ContractModel): + start: RationalBeat + duration: PositiveBeat + event: Literal["o", "x", "^", "-", "~"] + pitch: Nonblank | None = None + pitch_kind: Literal["note", "chord"] = "note" + + +class HybridPlan(ContractModel): + """Profile-independent, exact lane positions; pitches resolve only after routing.""" + + slots: Annotated[list[HybridSlot], Field(min_length=1, max_length=4000)] + hold_end: PositiveBeat | None = None + hold_pitch: Nonblank | None = None + global_technique: Literal["normal", "palm_mute", "pinch_harmonic"] | None = None + claimed_pitch: Nonblank | None = None + + @model_validator(mode="after") + def timeline(self) -> Self: + previous = Fraction(0) + for slot in self.slots: + if slot.start.value < previous: + raise ValueError("Hybrid slots must be ordered and nonoverlapping.") + previous = slot.start.value + slot.duration.value + if slot.event in ("-", "~") and slot.pitch is not None: + raise ValueError("Rest/continuation cannot specify a new pitch.") + return self + + +class MusicalIntent(ContractModel): + description: Annotated[str, Field(min_length=1, max_length=4000, pattern=r"\S")] + parts: Parts + tempo_bpm: Tempo + bars: Bars + time_signature: TimeSignature + key: Key + seed: Seed + rhythm_terms: UniqueText = Field(default_factory=list) + techniques: UniqueText = Field(default_factory=list) + phrase_plan: PhrasePlan | None = None + explicit_plan: ExplicitAttackPlan | None = None + hybrid_plan: HybridPlan | None = None + + @model_validator(mode="after") + def phrase_bounds(self) -> Self: + if ( + sum( + plan is not None + for plan in (self.phrase_plan, self.explicit_plan, self.hybrid_plan) + ) + > 1 + ): + raise ValueError("Use one phrase, explicit attack or hybrid plan.") + if self.hybrid_plan is not None and ( + len(self.parts) != 1 + or self.parts == ["drums"] + or self.rhythm_terms + or self.techniques + or any( + slot.start.value + slot.duration.value > self.duration_beats + for slot in self.hybrid_plan.slots + ) + or ( + self.hybrid_plan.hold_end is not None + and self.hybrid_plan.hold_end.value > self.duration_beats + ) + ): + raise ValueError("Hybrid lanes need one pitched part and no competing globals.") + if self.explicit_plan is not None and ( + self.parts != [self.explicit_plan.part] + or self.explicit_plan.duration.value > self.duration_beats + or self.rhythm_terms + or self.techniques + ): + raise ValueError( + "An explicit attack plan needs its sole part, sufficient length, no globals." + ) + if self.phrase_plan is not None and ( + self.parts != [self.phrase_plan.part] + or self.phrase_plan.duration.value > self.duration_beats + or self.rhythm_terms + or self.techniques + ): + raise ValueError( + "An explicit phrase needs its sole part, sufficient length, no globals." + ) + return self + + @property + def duration_beats(self) -> Fraction: + return self.bars * self.time_signature.beats_per_bar + + +class _LogicalNoteBase(ContractModel): + start: RationalBeat + duration: PositiveBeat + intensity: Annotated[float, Field(ge=0, le=1)] + articulation: Nonblank + + +class PitchedNote(_LogicalNoteBase): + kind: Literal["pitched"] = "pitched" + part: Literal["lead", "bass"] + pitch: MidiData + + +class DrumNote(_LogicalNoteBase): + kind: Literal["drum"] = "drum" + part: Literal["drums"] = "drums" + voice: Nonblank + + +LogicalNote: TypeAlias = Annotated[PitchedNote | DrumNote, Field(discriminator="kind")] + + +class ScoreTrack(ContractModel): + part: Part + notes: list[LogicalNote] + + @model_validator(mode="after") + def note_parts(self) -> Self: + if any(note.part != self.part for note in self.notes): + raise ValueError("Every logical note must belong to its enclosing part track.") + return self + + +class Score(ContractModel): + intent: MusicalIntent + start: RationalBeat + end: RationalBeat + tracks: Annotated[list[ScoreTrack], Field(min_length=1)] + + @model_validator(mode="after") + def timeline(self) -> Self: + if [track.part for track in self.tracks] != self.intent.parts: + raise ValueError("Provide exactly one track per selected part, in selected-part order.") + if self.end.value - self.start.value != self.intent.duration_beats: + raise ValueError("The shared positive score duration must match bars and meter.") + for track in self.tracks: + for note in track.notes: + if ( + note.start.value < self.start.value + or note.start.value + note.duration.value > self.end.value + ): + raise ValueError("Logical notes must fit within the shared score timeline.") + return self + + +class _EventBase(ContractModel): + tick: Tick + part: Part + channel: Channel + priority: Tick + sequence: Tick + + @property + def ordering_key(self) -> tuple[int, int, int]: + return self.tick, self.priority, self.sequence + + +class NoteOnEvent(_EventBase): + kind: Literal["note_on"] = "note_on" + role: Literal["musical_note", "keyswitch"] + note: MidiData + velocity: Annotated[int, Field(ge=1, le=127)] + + +class NoteOffEvent(_EventBase): + kind: Literal["note_off"] = "note_off" + role: Literal["musical_note", "keyswitch"] + note: MidiData + velocity: MidiData = 0 + + +class ControlChangeEvent(_EventBase): + kind: Literal["control_change"] = "control_change" + role: Literal["articulation_control"] = "articulation_control" + controller: MidiData + value: MidiData + + +ScheduledEvent: TypeAlias = Annotated[ + NoteOnEvent | NoteOffEvent | ControlChangeEvent, Field(discriminator="kind") +] + + +class EventTrack(ContractModel): + part: Part + events: list[ScheduledEvent] + + @model_validator(mode="after") + def valid_events(self) -> Self: + if any(event.part != self.part for event in self.events): + raise ValueError("Scheduled events must belong to their enclosing part track.") + keys = [event.ordering_key for event in self.events] + if len(set(keys)) != len(keys): + raise ValueError("Event ordering keys must be unique within a part track.") + return self + + +class EventPlan(ContractModel): + score: Score + ticks_per_quarter: PositiveInt = TICKS_PER_QUARTER + musical_start_tick: Tick + musical_end_tick: Tick + end_tick: Tick + tracks: Annotated[list[EventTrack], Field(min_length=1)] + + @model_validator(mode="after") + def shared_timeline(self) -> Self: + if [track.part for track in self.tracks] != self.score.intent.parts: + raise ValueError("Provide exactly one event track per selected score part, in order.") + duration = self.score.intent.duration_beats * self.ticks_per_quarter + if duration.denominator != 1 or self.musical_end_tick - self.musical_start_tick != duration: + raise ValueError("The musical tick duration must exactly represent the score duration.") + if self.end_tick < self.musical_end_tick: + raise ValueError("Event-plan end must include the musical end and any control tail.") + if sum(len(track.events) for track in self.tracks) > MAX_SCHEDULED_EVENTS: + raise ValueError("The scheduled-event budget is 100,000 events.") + for track in self.tracks: + for event in track.events: + if event.tick > self.end_tick: + raise ValueError("Events must not extend beyond the shared event-plan end.") + if isinstance(event, NoteOnEvent | NoteOffEvent) and event.role == "musical_note": + if not self.musical_start_tick <= event.tick <= self.musical_end_tick: + raise ValueError( + "Musical events must fit within the musical tick timeline." + ) + if isinstance(event, NoteOnEvent) and event.tick == self.musical_end_tick: + raise ValueError("Musical note-ons must precede the musical end.") + return self + + +class ResolvedGeneration(ContractModel): + parts: Parts + tempo_bpm: Tempo + bars: Bars + time_signature: TimeSignature + key: Key + seed: Seed + profile_ids: ProfileSelection + assumptions: UniqueText + overrides: UniqueText + musical_start_tick: Tick + musical_end_tick: Tick + ticks_per_quarter: PositiveInt + interpretation: list["InterpretedAttack"] = Field(default_factory=list) + + @model_validator(mode="after") + def resolved_fields(self) -> Self: + profiles = self.profile_ids.selected() + if set(profiles) != set(self.parts): + raise ValueError("Resolved profile IDs must cover exactly the selected parts.") + _unique(list(profiles.values())) + if self.musical_end_tick < self.musical_start_tick: + raise ValueError("Musical end tick must be at or after musical start tick.") + return self + + +class InterpretedAttack(ExplicitAttack): + part: Literal["lead", "bass"] + held: bool = False + + +def _absolute_path(value: str) -> str: + if not (PureWindowsPath(value).is_absolute() or PurePosixPath(value).is_absolute()): + raise ValueError("Artifact path must be an absolute local published-file path.") + if any(character in value for character in ("\x00", "\n", "\r")): + raise ValueError("Artifact path must not contain nulls or line breaks.") + return value + + +class Artifact(ContractModel): + model_config = ConfigDict(json_schema_extra=_artifact_schema) + + format: ArtifactFormat + parts: Parts + path: Annotated[Nonblank, AfterValidator(_absolute_path)] + size_bytes: PositiveInt + profile_ids: Annotated[UniqueText, Field(min_length=1)] + fallback_for: Annotated[ + list[Part], Field(json_schema_extra={"uniqueItems": True}), AfterValidator(_unique) + ] + + @model_validator(mode="after") + def applicable_format(self) -> Self: + expected_part = {"griff": "lead", "briff": "bass", "sd3p": "drums"}.get(self.format) + if expected_part is not None and self.parts != [expected_part]: + raise ValueError("Native artifacts must contain exactly their corresponding part.") + if not self.path.endswith(f".{self.format}"): + raise ValueError("Artifact format must be its actual saved-file suffix, not an alias.") + if self.fallback_for and ( + self.format != "mid" or not set(self.fallback_for).issubset(self.parts) + ): + raise ValueError("Only MIDI can substitute for its own included native-target parts.") + return self + + +class GenerationWarning(ContractModel): + code: Nonblank + part: Part | None + message: Nonblank + + +class GenerationResult(ContractModel): + model_config = ConfigDict(json_schema_extra=_result_schema) + + status: Literal["complete", "midi_fallback"] + resolved: ResolvedGeneration + artifacts: Annotated[list[Artifact], Field(min_length=1)] + warnings: list[GenerationWarning] + + @model_validator(mode="after") + def claimed_outputs(self) -> Self: + ids = self.resolved.profile_ids.selected() + seen: set[tuple[ArtifactFormat, Part]] = set() + fallback: set[Part] = set() + native_parts: set[Part] = set() + for artifact in self.artifacts: + if not set(artifact.parts).issubset(self.resolved.parts): + raise ValueError("Artifact parts must be selected in the resolved request.") + if set(artifact.profile_ids) != {ids[part] for part in artifact.parts}: + raise ValueError("Artifact profile IDs must match their resolved part profiles.") + if artifact.format == "mid" and set(artifact.parts) != set(self.resolved.parts): + raise ValueError( + "The single combined MIDI artifact must include all selected parts." + ) + for part in artifact.parts: + key = artifact.format, part + if key in seen: + raise ValueError( + "Do not duplicate a format/part artifact or the combined MIDI." + ) + seen.add(key) + if artifact.format != "mid": + native_parts.update(artifact.parts) + fallback.update(artifact.fallback_for) + if any(warning.part is not None and warning.part not in ids for warning in self.warnings): + raise ValueError("Warning parts must refer to selected parts.") + native_warnings = [ + warning for warning in self.warnings if warning.code == "NATIVE_FORMAT_UNAVAILABLE" + ] + if self.status == "complete" and (fallback or native_warnings): + raise ValueError("Complete results cannot claim native fallback or unavailability.") + if self.status == "midi_fallback": + warned = {warning.part for warning in native_warnings} + if not fallback or not fallback.issubset(warned): + raise ValueError("MIDI fallback requires substituted parts and a warning per part.") + if fallback.intersection(native_parts): + raise ValueError("A native part cannot be both produced and substituted.") + if any(warning.part not in fallback for warning in native_warnings): + raise ValueError("Native unavailability warnings must identify substituted parts.") + return self + + +class GenerationError(ContractModel): + code: ErrorCode + message: Nonblank + details: dict[str, JsonValue] + + @classmethod + def from_domain(cls, error: DomainError) -> Self: + return cls(code=error.code, message=error.public_message, details=error.details) + + +GenerationOutput: TypeAlias = GenerationResult | GenerationError +ProfileListOutput: TypeAlias = ProfileListResult | GenerationError +GENERATION_OUTPUT = TypeAdapter(GenerationOutput) +PROFILE_LIST_OUTPUT = TypeAdapter(ProfileListOutput) + + +def tool_input_schema(tool: ToolName) -> JsonSchemaValue: + """Fresh schemas prevent a caller mutating the authoritative model contract.""" + if tool == "list_instrument_profiles": + return ListInstrumentProfilesRequest.model_json_schema() + if tool == "generate_music": + return GenerateMusicRequest.model_json_schema() + raise ValueError(f"Unknown tool: {tool}") + + +def tool_output_schema(tool: ToolName) -> JsonSchemaValue: + """MCP-compatible object root with explicit, mutually exclusive result/error branches.""" + if tool == "list_instrument_profiles": + schema = PROFILE_LIST_OUTPUT.json_schema(mode="serialization") + elif tool == "generate_music": + schema = GENERATION_OUTPUT.json_schema(mode="serialization") + else: + raise ValueError(f"Unknown tool: {tool}") + schema["oneOf"] = schema.pop("anyOf") + schema["type"] = "object" + return schema diff --git a/src/riff_groove_builder/server.py b/src/riff_groove_builder/server.py new file mode 100644 index 0000000..80f89eb --- /dev/null +++ b/src/riff_groove_builder/server.py @@ -0,0 +1,169 @@ +"""SDK-backed stdio lifecycle and operational generation handlers.""" + +import json +import logging +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from pathlib import Path + +from mcp import types +from mcp.server.lowlevel import Server +from mcp.server.stdio import stdio_server +from pydantic import ValidationError + +from riff_groove_builder import __version__ +from riff_groove_builder.errors import ( + DESCRIPTION_GUIDANCE, + FIELD_GUIDANCE, + DomainError, + InvalidRequestError, + request_validation_details, +) +from riff_groove_builder.schemas import ( + GenerateMusicRequest, + GenerationError, + GenerationResult, + ListInstrumentProfilesRequest, + ProfileListResult, + tool_input_schema, + tool_output_schema, +) +from riff_groove_builder.service import GenerationService +from riff_groove_builder.service import validate_output_root as validate_output_root + +logger = logging.getLogger(__name__) + + +def _validation_error(error: ValidationError) -> GenerationError: + return GenerationError.from_domain( + InvalidRequestError(details=request_validation_details(error)) + ) + + +def _tool_result( + result: ProfileListResult | GenerationResult | GenerationError, +) -> types.CallToolResult: + public = result.model_dump(mode="json") + return types.CallToolResult( + content=[ + types.TextContent( + type="text", text=json.dumps(public, ensure_ascii=False, allow_nan=False) + ) + ], + structuredContent=public, + isError=isinstance(result, GenerationError), + ) + + +def create_server(output_root: Path, *, sd3_template: Path | None = None) -> Server[Path]: + """Use one root-pinned service for both concrete tools.""" + service = GenerationService(output_root, sd3_template=sd3_template) + + @asynccontextmanager + async def lifespan(_server: Server[Path]) -> AsyncIterator[Path]: + yield output_root + + server = Server[Path]("riff-groove-builder", version=__version__, lifespan=lifespan) + + # MCP 1.30's decorators are untyped; keep the ignores at this SDK boundary. + @server.list_tools() # type: ignore[no-untyped-call, untyped-decorator] + async def list_tools() -> list[types.Tool]: + return [ + types.Tool( + name="list_instrument_profiles", + description=( + "List exact profile IDs, parts, standard/vendor identity, capabilities and " + "limitations. Use these IDs unchanged in generate_music.profiles, or omit " + "profiles for defaults; never invent IDs. Takes an empty object." + ), + inputSchema=tool_input_schema("list_instrument_profiles"), + outputSchema=tool_output_schema("list_instrument_profiles"), + ), + types.Tool( + name="generate_music", + description=( + "Generate real Riffer/SD3 native files and combined MIDI; " + "explicit MIDI fallback only for known unavailable native capabilities. " + "Omit formats for automatic correct per-part output plus MIDI: guitar " + "lead -> griff (agp alias), bass -> briff (agp alias), drums -> sd3p " + "(sdp alias); mid works for all. Omit profiles for defaults or use exact " + "IDs from list_instrument_profiles; never invent profile IDs. " + "Never add CC events without user intent. " + DESCRIPTION_GUIDANCE + ), + inputSchema=tool_input_schema("generate_music"), + outputSchema=tool_output_schema("generate_music"), + ), + ] + + # SDK schema-validation messages echo values and miss strict Python-type rules. + # Authoritative models validate instead; complete CallToolResults preserve isError. + @server.call_tool(validate_input=False) # type: ignore[untyped-decorator] + async def call_tool(name: str, arguments: dict[str, object]) -> types.CallToolResult: + try: + if name == "list_instrument_profiles": + request: ListInstrumentProfilesRequest | GenerateMusicRequest = ( + ListInstrumentProfilesRequest.model_validate(arguments) + ) + elif name == "generate_music": + request = GenerateMusicRequest.model_validate(arguments) + else: + raise ValueError("Unknown tool.") + except ValidationError as error: + return _tool_result(_validation_error(error)) + try: + if isinstance(request, ListInstrumentProfilesRequest): + return _tool_result(service.list_instrument_profiles()) + return _tool_result(service.generate_music(request)) + except DomainError as error: + public = GenerationError.from_domain(error) + field = public.details.get("field") + if ( + public.code == "INVALID_REQUEST" + and isinstance(field, str) + and field in FIELD_GUIDANCE + ): + public = GenerationError( + code=public.code, + message=public.message, + details={**public.details, "correction": FIELD_GUIDANCE[field]}, + ) + return _tool_result(public) + except Exception as error: + # The SDK otherwise converts unexpected exceptions to text silently. + logger.error("Unexpected tool execution failure (%s).", type(error).__name__) + raise RuntimeError( + "Internal tool execution failure; consult stderr diagnostics." + ) from None + + return server + + +class _ProtocolDiagnosticFilter(logging.Filter): + """Remove SDK validation dumps without changing SDK protocol behavior.""" + + def filter(self, record: logging.LogRecord) -> bool: + message = record.getMessage() + if record.name == "root" and message.startswith( + ("Failed to validate request:", "Failed to validate notification:") + ): + record.msg = "SDK rejected invalid protocol parameters." + record.args = () + elif record.name.startswith("mcp.") and message.startswith( + ("Received exception from stream:", "Tool '") + ): + record.msg = "SDK rejected malformed protocol input or an unlisted tool." + record.args = () + return True + + +def configure_logging() -> None: + """Only the CLI configures logging; importing this module is silent.""" + handler = logging.StreamHandler() + handler.addFilter(_ProtocolDiagnosticFilter()) + logging.basicConfig(level=logging.WARNING, handlers=[handler]) + + +async def run_stdio(output_root: Path, sd3_template: Path | None = None) -> None: + server = create_server(output_root, sd3_template=sd3_template) + async with stdio_server() as (read_stream, write_stream): + await server.run(read_stream, write_stream, server.create_initialization_options()) diff --git a/src/riff_groove_builder/service.py b/src/riff_groove_builder/service.py new file mode 100644 index 0000000..cd2d9a6 --- /dev/null +++ b/src/riff_groove_builder/service.py @@ -0,0 +1,564 @@ +"""Native/MIDI generation with explicit capability fallback and owned atomic publication.""" + +import ctypes +import hashlib +import os +import re +import stat +import uuid +from dataclasses import dataclass, field, replace +from itertools import islice +from pathlib import Path, PureWindowsPath + +from pydantic import ValidationError +from pydantic_core import PydanticSerializationError + +from riff_groove_builder.articulations import apply_scheduled_controls, compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.errors import ( + DomainError, + InvalidRequestError, + NativeFormatUnavailableError, + OutputExistsError, + OutputIOError, + SerializationError, + request_validation_details, +) +from riff_groove_builder.formats import NativeCapability +from riff_groove_builder.formats.agp import ( + check_agp_capability, + preflight_riffer, + validate_riffer_file, + write_riffer, +) +from riff_groove_builder.formats.sdp import ( + check_sdp_capability, + inspect_sdp_template, + preflight_sdp, + validate_sdp_file, + write_sdp, +) +from riff_groove_builder.hybrid import materialize +from riff_groove_builder.midi import validate_midi_file, write_midi +from riff_groove_builder.profiles import ProfileRegistry, load_profile_registry +from riff_groove_builder.schemas import ( + Artifact, + ArtifactFormat, + GenerateMusicRequest, + GenerationResult, + GenerationWarning, + InterpretedAttack, + Part, + ProfileListResult, + ProfileSelection, + ResolvedGeneration, +) + +_MAX_ARTIFACT_BYTES = 16 * 1024 * 1024 +_Identity = tuple[int, int] +_Fingerprint = tuple[_Identity, int, int, str] + + +def _fingerprint(path: Path) -> _Fingerprint: + before = path.lstat() + if ( + _linked(before) + or not stat.S_ISREG(before.st_mode) + or before.st_nlink != 1 + or not 0 < before.st_size <= _MAX_ARTIFACT_BYTES + ): + raise OutputIOError(details={"reason": "unsafe_artifact"}) + with path.open("rb") as stream: + opened = os.fstat(stream.fileno()) + if _identity(opened) != _identity(before): + raise OutputIOError(details={"reason": "staged_content_changed"}) + digest = hashlib.sha256(stream.read(_MAX_ARTIFACT_BYTES + 1)).hexdigest() + after = path.lstat() + if ( + (_identity(before), before.st_size, before.st_mtime_ns) + != (_identity(after), after.st_size, after.st_mtime_ns) + or _linked(after) + or after.st_nlink != 1 + ): + raise OutputIOError(details={"reason": "staged_content_changed"}) + return _identity(after), after.st_size, after.st_mtime_ns, digest + + +def _identity(info: os.stat_result) -> _Identity: + return info.st_dev, info.st_ino + + +def _linked(info: os.stat_result) -> bool: + return stat.S_ISLNK(info.st_mode) or bool( + getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT + ) + + +def _directory_identity(path: Path) -> _Identity: + info = path.lstat() + if _linked(info) or not stat.S_ISDIR(info.st_mode): + raise ValueError("Unsafe directory.") + return _identity(info) + + +def _root_chain(root: Path) -> tuple[tuple[Path, _Identity], ...]: + return tuple((path, _directory_identity(path)) for path in (*reversed(root.parents), root)) + + +def validate_output_root(value: str) -> Path: + """Reject nonlocal syntax and existing links/reparse points before resolving.""" + message = "Output root must be an existing local directory, not a URI or network/device path." + if ( + not value + or value != value.strip() + or any(ord(character) < 32 for character in value) + or value.startswith(("\\", "//")) + or (":" in value and re.match(r"^[A-Za-z]:[\\/][^:]*$", value) is None) + or (PureWindowsPath(value).drive and not PureWindowsPath(value).is_absolute()) + or ".." in Path(value).parts + ): + raise ValueError(message) + try: + root = Path(value).absolute() + _root_chain(root) + if root.resolve(strict=True) != root or str(root).startswith(("\\", "//")): + raise ValueError(message) + if os.name == "nt": + # A mapped network drive has local-looking syntax, but is not local storage. + drive_type = ctypes.windll.kernel32.GetDriveTypeW(ctypes.c_wchar_p(root.anchor)) + if drive_type not in (2, 3, 6): # removable, fixed, RAM disk + raise ValueError(message) + except (OSError, RuntimeError, ValueError): + raise ValueError(message) from None + return root + + +@dataclass(frozen=True) +class _Stage: + path: Path + identity: _Identity + filenames: tuple[str, ...] + owned: dict[str, _Identity] = field(default_factory=dict) + validated: dict[str, _Fingerprint] = field(default_factory=dict) + + +class GenerationService: + """One configured root and packaged registry; no tool-controlled output paths.""" + + def __init__( + self, + output_root: Path, + *, + registry: ProfileRegistry | None = None, + sd3_template: Path | None = None, + ) -> None: + self.output_root = validate_output_root(str(output_root)) + self._chain = _root_chain(self.output_root) + self._registry = registry if registry is not None else load_profile_registry() + self.sd3_template = sd3_template.absolute() if sd3_template is not None else None + self._template_fingerprint: _Fingerprint | None = None + if self.sd3_template is not None: + inspect_sdp_template(self.sd3_template) + try: + self._template_fingerprint = _fingerprint(self.sd3_template) + except OSError: + raise OutputIOError(details={"reason": "sd3_template_read_failed"}) from None + + def _check_template(self) -> None: + if self.sd3_template is not None: + try: + if _fingerprint(self.sd3_template) != self._template_fingerprint: + raise SerializationError(details={"reason": "sd3_template_changed"}) + except OSError: + raise OutputIOError(details={"reason": "sd3_template_read_failed"}) from None + + def list_instrument_profiles(self) -> ProfileListResult: + # Revalidate whole maps, not just their mutable public summaries. + summaries = self._registry.summaries() + self._check_template() + result = [] + for summary in summaries: + profile = self._registry.select( + [summary.part], ProfileSelection(**{summary.part: summary.id}) + )[summary.part] + capability = ( + check_sdp_capability(summary.part, profile, template=self.sd3_template) + if summary.part == "drums" + else check_agp_capability(summary.part, profile) + ) + limitations = list(profile.summary.limitations) + limitations.append( + f"Runtime native .{summary.native_format}: {capability.reason}. " + + ("Default profile. " if profile.default else "Explicit profile selection. ") + + "Saved-content validation is not plugin/DAW playback certification." + ) + result.append( + profile.summary.model_copy( + update={"native_available": capability.available, "limitations": limitations} + ) + ) + return ProfileListResult(profiles=result) + + def _check_root(self) -> None: + try: + if _root_chain(self.output_root) != self._chain: + raise ValueError("Root identity changed.") + except (OSError, ValueError): + raise OutputIOError(details={"reason": "output_root_changed"}) from None + + def _check_stage(self, stage: _Stage) -> None: + self._check_root() + try: + if ( + stage.path.parent != self.output_root + or _directory_identity(stage.path) != stage.identity + or stage.path.resolve(strict=True).parent != self.output_root + ): + raise ValueError("Stage identity changed.") + except (OSError, ValueError, RuntimeError): + raise OutputIOError(details={"reason": "stage_ownership_changed"}) from None + + def _new_stage(self, basename: str, filenames: tuple[str, ...] | None = None) -> _Stage: + for _ in range(3): + self._check_root() + path = self.output_root / f".riff-stage-{uuid.uuid4().hex}" + try: + path.mkdir(mode=0o700) + except FileExistsError: + continue + except OSError: + raise OutputIOError(details={"reason": "stage_create_failed"}) from None + try: + identity = _directory_identity(path) + except (OSError, ValueError): + # Ownership was never established: do not delete a replacement. + raise OutputIOError(details={"reason": "stage_ownership_unestablished"}) from None + return _Stage(path, identity, filenames or (f"{basename}.mid",)) + raise OutputIOError(details={"reason": "stage_name_collisions"}) + + def _cleanup(self, stage: _Stage) -> None: + try: + self._check_stage(stage) + entries = list(islice(stage.path.iterdir(), len(stage.filenames) + 1)) + if any(entry.name not in stage.owned for entry in entries): + raise ValueError("Unowned stage content.") + for entry in entries: + info = entry.lstat() + if ( + _linked(info) + or not stat.S_ISREG(info.st_mode) + or info.st_nlink != 1 + or _identity(info) != stage.owned[entry.name] + ): + raise ValueError("Unsafe stage content.") + for entry in entries: + self._check_stage(stage) + if _identity(entry.lstat()) != stage.owned[entry.name] or _linked(entry.lstat()): + raise ValueError("Stage file identity changed.") + entry.unlink() + self._check_stage(stage) + stage.path.rmdir() + except (OSError, ValueError, DomainError): + raise OutputIOError(details={"reason": "stage_cleanup_failed"}) from None + + def _publish(self, stage: _Stage, destination: Path) -> None: + self._check_stage(stage) + if os.path.lexists(destination): + raise OutputExistsError(details={"reason": "destination_exists"}) + self._check_files(stage) + try: + # os.rename on Windows refuses even an existing empty destination. + # Do not substitute POSIX rename, which can replace empty directories. + if os.name != "nt": + raise OutputIOError(details={"reason": "no_replace_publication_requires_windows"}) + stage.path.rename(destination) + except FileExistsError: + raise OutputExistsError(details={"reason": "destination_exists"}) from None + except OSError: + if os.path.lexists(destination): + raise OutputExistsError(details={"reason": "destination_exists"}) from None + raise OutputIOError(details={"reason": "publication_failed"}) from None + + def _claim(self, stage: _Stage, path: Path, info: os.stat_result) -> None: + self._check_stage(stage) + if ( + path.parent != stage.path + or path.name not in stage.filenames + or path.name in stage.owned + or _linked(info) + or not stat.S_ISREG(info.st_mode) + or info.st_nlink != 1 + or _identity(path.lstat()) != _identity(info) + ): + raise OutputIOError(details={"reason": "stage_file_ownership_changed"}) + stage.owned[path.name] = _identity(info) + + def _check_files(self, stage: _Stage) -> None: + self._check_stage(stage) + self._check_template() + try: + entries = list(islice(stage.path.iterdir(), len(stage.filenames) + 1)) + if ( + {entry.name for entry in entries} != set(stage.filenames) + or set(stage.validated) != set(stage.filenames) + or any( + _fingerprint(entry) != stage.validated[entry.name] + or stage.owned[entry.name] != stage.validated[entry.name][0] + for entry in entries + ) + ): + raise OutputIOError(details={"reason": "staged_content_changed"}) + except OSError: + raise OutputIOError(details={"reason": "staged_content_changed"}) from None + + def generate_music(self, request: GenerateMusicRequest) -> GenerationResult: + try: + if not isinstance(request, GenerateMusicRequest): + raise ValueError("Not a request.") + request = GenerateMusicRequest.model_validate( + request.model_dump(mode="python", warnings="error") + ) + except (ValidationError, PydanticSerializationError, ValueError): + raise InvalidRequestError(details={"reason": "invalid_request_model"}) from None + resolution = resolve_description(request) + intent = resolution.intent + native_suffix: dict[Part, ArtifactFormat] = { + "lead": "griff", + "bass": "briff", + "drums": "sd3p", + } + formats = ( + list(request.formats) + if request.formats is not None + else ["mid", *(native_suffix[part] for part in intent.parts)] + ) + # Re-run associations now that previously omitted parts are resolved. + try: + GenerateMusicRequest.model_validate( + {**request.model_dump(), "parts": intent.parts, "formats": formats} + ) + except ValidationError as error: + raise InvalidRequestError( + details={"reason": "resolved_part_association", **request_validation_details(error)} + ) from None + profiles = self._registry.select(intent.parts, request.profiles or ProfileSelection()) + hybrid = intent.hybrid_plan + intent = materialize(intent, profiles) + interpretation = [] + if hybrid is not None: + assert intent.explicit_plan is not None + resolution.assumptions = list( + dict.fromkeys(resolution.assumptions + intent.explicit_plan.assumptions) + ) + for attack in intent.explicit_plan.attacks: + interpretation.append( + InterpretedAttack( + **attack.model_dump(), + part=intent.explicit_plan.part, + held=any( + slot.event == "~" + and attack.start.value + < slot.start.value + < attack.start.value + attack.duration.value + for slot in hybrid.slots + ) + or ( + hybrid.hold_end is not None + and attack is intent.explicit_plan.attacks[-1] + ), + ) + ) + self._check_template() + score = compose_score(intent, profiles) + plan = apply_scheduled_controls(compile_score(score, profiles), request.cc_events, profiles) + unavailable: list[NativeCapability] = [] + available: list[Part] = [] + for part in intent.parts: + native = profiles[part].summary.native_format + alias = "sdp" if part == "drums" else "agp" + if native not in formats and alias not in formats: + continue + capability = ( + check_sdp_capability(part, profiles[part], template=self.sd3_template) + if part == "drums" + else check_agp_capability(part, profiles[part]) + ) + capability = replace(capability, part=part, format=native) + if capability.available: + # Only these exact, pre-write representation failures can fall back. + # Corruption, map/plan mismatch, routing bugs and IO never do. + try: + if part == "drums": + preflight_sdp(plan, part, profiles[part]) + else: + preflight_riffer(plan, part, profiles[part]) + except SerializationError as error: + if error.details.get("reason") not in { + "preroll_or_tail_not_representable", + "sd3_preroll_or_tail_not_representable", + "off_grid_beats", + "sd3_timing_not_representable", + "unsupported_native_controller", + "sd3_native_controller_not_supported", + "no_physical_string_assignment", + }: + raise + capability = replace( + capability, available=False, reason=str(error.details["reason"]) + ) + if capability.available: + available.append(part) + else: + unavailable.append(capability) + if unavailable and not request.allow_midi_fallback: + capability = unavailable[0] + raise NativeFormatUnavailableError( + details={ + "part": capability.part, + "format": capability.format, + "reason": capability.reason, + } + ) + warnings = [ + GenerationWarning( + code="STANDARD_MIDI_MAPPING", + part=part, + message=( + f"{profiles[part].id} uses Standard MIDI only; " + "not a verified Eclips/Ray/SD3 mapping or vendor compatibility claim." + ), + ) + for part in intent.parts + if profiles[part].summary.mapping_kind == "standard_midi" + ] + warnings.extend( + GenerationWarning( + code="VERIFIED_SUBSET_LIMITS", + part=part, + message=" ".join(profiles[part].summary.limitations), + ) + for part in intent.parts + if profiles[part].provenance.status == "verified_subset" + ) + warnings.extend( + GenerationWarning( + code="NATIVE_FORMAT_UNAVAILABLE", + part=capability.part, + message=( + f"{capability.format}: {capability.reason}; " + "the combined Standard MIDI substitutes for this native target." + ), + ) + for capability in unavailable + ) + if os.name != "nt": + raise OutputIOError(details={"reason": "no_replace_publication_requires_windows"}) + self._check_root() + destination = self.output_root / request.basename + if os.path.lexists(destination): + raise OutputExistsError(details={"reason": "destination_exists"}) + outputs: list[tuple[str, ArtifactFormat, list[Part]]] = [] + if "mid" in formats or unavailable: + outputs.append((f"{request.basename}.mid", "mid", intent.parts)) + outputs.extend( + (f"{request.basename}_{part}.{native_suffix[part]}", native_suffix[part], [part]) + for part in available + ) + stage = self._new_stage(request.basename, tuple(name for name, _, _ in outputs)) + try: + artifacts = [] + for filename, output_format, parts in outputs: + self._check_stage(stage) + path = stage.path / filename + + def claim(info: os.stat_result, path: Path = path) -> None: + self._claim(stage, path, info) + + if output_format == "mid": + write_midi(path, plan, on_created=claim) + elif output_format == "sd3p": + write_sdp( + path, + plan, + "drums", + profiles["drums"], + template=self.sd3_template, + on_created=claim, + ) + else: + write_riffer(path, plan, parts[0], profiles[parts[0]], on_created=claim) + self._check_stage(stage) + before = _fingerprint(path) + if stage.owned.get(filename) != before[0]: + raise OutputIOError(details={"reason": "stage_file_ownership_changed"}) + if output_format == "mid": + validate_midi_file(path, plan) + elif output_format == "sd3p": + validate_sdp_file( + path, plan, "drums", profiles["drums"], template=self.sd3_template + ) + else: + validate_riffer_file(path, plan, parts[0], profiles[parts[0]]) + if _fingerprint(path) != before: + raise OutputIOError(details={"reason": "staged_content_changed"}) + stage.validated[filename] = before + artifacts.append( + Artifact( + format=output_format, + parts=parts, + path=str(destination / filename), + size_bytes=before[1], + profile_ids=[profiles[part].id for part in parts], + fallback_for=( + [capability.part for capability in unavailable] + if output_format == "mid" + else [] + ), + ) + ) + ids = ProfileSelection(**{part: profiles[part].id for part in intent.parts}) + try: + result = GenerationResult( + status="midi_fallback" if unavailable else "complete", + resolved=ResolvedGeneration( + parts=intent.parts, + tempo_bpm=intent.tempo_bpm, + bars=intent.bars, + time_signature=intent.time_signature, + key=intent.key, + seed=intent.seed, + profile_ids=ids, + assumptions=resolution.assumptions, + overrides=resolution.overrides, + musical_start_tick=plan.musical_start_tick, + musical_end_tick=plan.musical_end_tick, + ticks_per_quarter=plan.ticks_per_quarter, + interpretation=interpretation, + ), + artifacts=artifacts, + warnings=warnings, + ) + result = GenerationResult.model_validate( + result.model_dump(mode="python", warnings="error") + ) + result.model_dump(mode="json", warnings="error") + except (ValidationError, PydanticSerializationError): + raise SerializationError(details={"reason": "invalid_generation_result"}) from None + self._publish(stage, destination) + except BaseException as error: + try: + self._cleanup(stage) + except OutputIOError: + raise OutputIOError( + details={ + "reason": "stage_cleanup_failed", + "original_code": ( + error.code if isinstance(error, DomainError) else "internal" + ), + } + ) from None + if isinstance(error, OSError): + raise OutputIOError(details={"reason": "staging_io_failed"}) from None + raise + return result diff --git a/tests/fixtures/profiles/synthetic-bass.json b/tests/fixtures/profiles/synthetic-bass.json new file mode 100644 index 0000000..3b89f30 --- /dev/null +++ b/tests/fixtures/profiles/synthetic-bass.json @@ -0,0 +1,56 @@ +{ + "schema_version": "1", "id": "test.bass.v1", + "summary": { + "id": "test.bass.v1", "part": "bass", "instrument": "ray", + "product_name": "SYNTHETIC bass mechanics, NOT a Ray map", + "product_version": "test-1", "mapping_version": "synthetic-1", + "midi_available": true, "native_format": "briff", "native_available": false, + "supported_articulations": ["normal", "slide", "trigger"], + "limitations": ["TEST ONLY: arbitrary values; no vendor compatibility or native support."] + }, + "provenance": { + "status": "test_only", "product_version": "test-1", "mapping_version": "synthetic-1", + "target_build": "synthetic", "mapping_preset": "synthetic", "sources": [], + "limitations": ["TEST ONLY: arbitrary values; no vendor compatibility or native support."] + }, + "default": false, "channel": 5, + "playable_range": {"low": 28, "high": 64}, "drum_voices": [], + "normal_articulation": "normal", + "articulations": [ + { + "name": "normal", "aliases": ["sustain"], "mode": "latched", + "actions": [ + {"kind": "keyswitch", "note": 3, "velocity": 60, "behavior": "pulse", + "lead": {"numerator": 0}, "gate": {"numerator": 1, "denominator": 16}, + "release_offset": {"numerator": 0}}, + {"kind": "cc", "controller": 21, "value": 0, "reset_value": null, + "lead": {"numerator": 0}, "release_offset": {"numerator": 0}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 20, "velocity_high": 100}] + }, + { + "name": "slide", "aliases": ["legato slide"], "mode": "momentary", + "actions": [ + {"kind": "keyswitch", "note": 4, "velocity": 60, "behavior": "hold", + "lead": {"numerator": 1, "denominator": 8}, + "gate": {"numerator": 1, "denominator": 16}, + "release_offset": {"numerator": 1, "denominator": 16}}, + {"kind": "cc", "controller": 21, "value": 90, "reset_value": 0, + "lead": {"numerator": 1, "denominator": 8}, + "release_offset": {"numerator": 1, "denominator": 16}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 20, "velocity_high": 100}] + }, + { + "name": "trigger", "aliases": [], "mode": "momentary", + "actions": [ + {"kind": "keyswitch", "note": 5, "velocity": 60, "behavior": "pulse", + "lead": {"numerator": 0}, "gate": {"numerator": 1, "denominator": 16}, + "release_offset": {"numerator": 0}}, + {"kind": "cc", "controller": 21, "value": 70, "reset_value": 0, + "lead": {"numerator": 0}, "release_offset": {"numerator": 0}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 20, "velocity_high": 100}] + } + ] +} diff --git a/tests/fixtures/profiles/synthetic-drums.json b/tests/fixtures/profiles/synthetic-drums.json new file mode 100644 index 0000000..2ed810d --- /dev/null +++ b/tests/fixtures/profiles/synthetic-drums.json @@ -0,0 +1,40 @@ +{ + "schema_version": "1", "id": "test.drums.v1", + "summary": { + "id": "test.drums.v1", "part": "drums", "instrument": "sd3", + "product_name": "SYNTHETIC percussion mechanics, NOT an SD3 or GM map", + "product_version": "test-1", "mapping_version": "synthetic-1", + "midi_available": true, "native_format": "sd3p", "native_available": false, + "supported_articulations": ["normal", "accent"], + "limitations": ["TEST ONLY: arbitrary values; no vendor compatibility or native support."] + }, + "provenance": { + "status": "test_only", "product_version": "test-1", "mapping_version": "synthetic-1", + "target_build": "synthetic", "mapping_preset": "synthetic", "sources": [], + "limitations": ["TEST ONLY: arbitrary values; no vendor compatibility or native support."] + }, + "default": false, "channel": 12, "playable_range": null, + "drum_voices": [ + {"name": "low_hit", "aliases": ["low"], "note": 36}, + {"name": "high_hit", "aliases": ["high"], "note": 40} + ], + "normal_articulation": "normal", + "articulations": [ + { + "name": "normal", "aliases": [], "mode": "latched", + "actions": [ + {"kind": "cc", "controller": 22, "value": 0, "reset_value": null, + "lead": {"numerator": 0}, "release_offset": {"numerator": 0}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 1, "velocity_high": 127}] + }, + { + "name": "accent", "aliases": ["hard hit"], "mode": "momentary", + "actions": [ + {"kind": "cc", "controller": 22, "value": 100, "reset_value": 0, + "lead": {"numerator": 0}, "release_offset": {"numerator": 1, "denominator": 16}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 80, "velocity_high": 120}] + } + ] +} diff --git a/tests/fixtures/profiles/synthetic-lead.json b/tests/fixtures/profiles/synthetic-lead.json new file mode 100644 index 0000000..5e29e4c --- /dev/null +++ b/tests/fixtures/profiles/synthetic-lead.json @@ -0,0 +1,50 @@ +{ + "schema_version": "1", + "id": "test.lead.v1", + "summary": { + "id": "test.lead.v1", "part": "lead", "instrument": "eclips", + "product_name": "SYNTHETIC lead mechanics, NOT an Eclips map", + "product_version": "test-1", "mapping_version": "synthetic-1", + "midi_available": true, "native_format": "griff", "native_available": false, + "supported_articulations": ["normal", "palm_mute"], + "limitations": ["TEST ONLY: arbitrary values; no vendor compatibility or native support."] + }, + "provenance": { + "status": "test_only", "product_version": "test-1", "mapping_version": "synthetic-1", + "target_build": "synthetic", "mapping_preset": "synthetic", + "sources": [], + "limitations": ["TEST ONLY: arbitrary values; no vendor compatibility or native support."] + }, + "default": false, "channel": 2, + "playable_range": {"low": 48, "high": 84}, "drum_voices": [], + "normal_articulation": "normal", + "articulations": [ + { + "name": "normal", "aliases": ["sustain"], "mode": "latched", + "actions": [ + {"kind": "keyswitch", "note": 1, "velocity": 64, "behavior": "pulse", + "lead": {"numerator": 1, "denominator": 8}, + "gate": {"numerator": 1, "denominator": 16}, + "release_offset": {"numerator": 0}}, + {"kind": "cc", "controller": 20, "value": 0, "reset_value": null, + "lead": {"numerator": 1, "denominator": 8}, "release_offset": {"numerator": 0}} + ], + "layers": [{"low": 0.0, "high": 1.0, "velocity_low": 1, "velocity_high": 127}] + }, + { + "name": "palm_mute", "aliases": ["pm"], "mode": "latched", + "actions": [ + {"kind": "keyswitch", "note": 2, "velocity": 64, "behavior": "pulse", + "lead": {"numerator": 1, "denominator": 8}, + "gate": {"numerator": 1, "denominator": 16}, + "release_offset": {"numerator": 0}}, + {"kind": "cc", "controller": 20, "value": 64, "reset_value": null, + "lead": {"numerator": 1, "denominator": 8}, "release_offset": {"numerator": 0}} + ], + "layers": [ + {"low": 0.0, "high": 0.5, "velocity_low": 30, "velocity_high": 50}, + {"low": 0.5, "high": 1.0, "velocity_low": 80, "velocity_high": 100} + ] + } + ] +} diff --git a/tests/fixtures/riffer/original-bass.briff b/tests/fixtures/riffer/original-bass.briff new file mode 100644 index 0000000..ed5250e --- /dev/null +++ b/tests/fixtures/riffer/original-bass.briff @@ -0,0 +1,18 @@ + + + + + + + + + + + + + +

+

+

+ + \ No newline at end of file diff --git a/tests/fixtures/riffer/original-lead.griff b/tests/fixtures/riffer/original-lead.griff new file mode 100644 index 0000000..874da91 --- /dev/null +++ b/tests/fixtures/riffer/original-lead.griff @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + +

+

+

+ + \ No newline at end of file diff --git a/tests/fixtures/sd3/original-score.json b/tests/fixtures/sd3/original-score.json new file mode 100644 index 0000000..452793a --- /dev/null +++ b/tests/fixtures/sd3/original-score.json @@ -0,0 +1,36 @@ +{ + "intent": { + "description": "Original three-hit SD3 native codec verification.", + "parts": ["drums"], + "tempo_bpm": 137.5, + "bars": 1, + "time_signature": {"numerator": 7, "denominator": 8}, + "key": "E minor", + "seed": 19 + }, + "start": {"numerator": 8}, + "end": {"numerator": 23, "denominator": 2}, + "tracks": [ + { + "part": "drums", + "notes": [ + { + "kind": "drum", "part": "drums", "voice": "kick", + "start": {"numerator": 8}, "duration": {"numerator": 1, "denominator": 8}, + "intensity": 0.0, "articulation": "normal" + }, + { + "kind": "drum", "part": "drums", "voice": "closed_hat", + "start": {"numerator": 33, "denominator": 4}, + "duration": {"numerator": 1, "denominator": 8}, + "intensity": 0.5, "articulation": "normal" + }, + { + "kind": "drum", "part": "drums", "voice": "snare", + "start": {"numerator": 11}, "duration": {"numerator": 1, "denominator": 8}, + "intensity": 1.0, "articulation": "normal" + } + ] + } + ] +} diff --git a/tests/fixtures/sd3/original-template.sd3p b/tests/fixtures/sd3/original-template.sd3p new file mode 100644 index 0000000..2a99120 --- /dev/null +++ b/tests/fixtures/sd3/original-template.sd3p @@ -0,0 +1,81 @@ +PlugVersion 3.4.4 +SAMPLER { +HQ { +soundlib "SL-DFH" +} +instbox 0 { +xpad 0 SL-DFH { +pos "Original test kick" +pads { +pad kickR { +maxpoly 4 +} +alias kickR 36 +} +} +} +instbox 1 { +xpad 0 SL-DFH { +pos "Original test snare" +pads { +pad snareR { +maxpoly 4 +} +alias snareR 38 +} +} +} +instbox 2 { +xpad 0 SL-DFH { +pos "Original test hat" +pads { +pad hatsTP { +maxpoly 4 +} +alias hatsTP 42 +} +} +} +mixer { +OriginalLabel "Original {state} \"quoted\" \\ text" +OriginalGain 0.375 +} +midilearn { +} +} +ClearTracksFirst +SongTrack 0 { +ClearTrackFirst +ClearSongParts +TrackLength 16 +Tempo 100 0 0 +TimeSig 4 4 0 +TrackName "Original source song to remove" +MidiLoop 0 { +Name "Original source clip to remove" +RealEndTime 4 +StartTime 0 +EndTime 4 +Offset 2 +ClearNotes +MidiEvents { +EndTime 4 +Events 4203664 0 0.25 +Tempo 100 0 0 +TimeSig 4 4 0 +} +FileName "original-source.mid" +} +} +SetCurrentSongTrack 0 +editorVars { +OriginalLabel "Not song data" +} +Drumtracker { +Track 0 { +trackstuff "b3JpZ2luYWwtb3BhcXVlLXRlc3Q=" +tempoMap "PG9yaWdpbmFsLz4=" +} +} +SyncToHost 1 +MidiInChannel -1 diff --git a/tests/integration/test_agp_capability.py b/tests/integration/test_agp_capability.py new file mode 100644 index 0000000..ea42861 --- /dev/null +++ b/tests/integration/test_agp_capability.py @@ -0,0 +1,136 @@ +"""Real registry/capability/MIDI boundary checks, not native application acceptance.""" + +import shutil +import uuid +from collections.abc import Iterator +from dataclasses import asdict +from pathlib import Path +from unittest.mock import Mock + +import pytest + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.errors import NativeFormatUnavailableError +from riff_groove_builder.formats.agp import check_agp_capability, require_agp_capability +from riff_groove_builder.midi import validate_midi_file, write_midi +from riff_groove_builder.profiles import InvalidProfileError, load_profile_registry +from riff_groove_builder.schemas import GenerateMusicRequest, Part, ProfileSelection + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = pytest.mark.integration + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"agp-capability-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +@pytest.mark.parametrize("part", ["lead", "bass"]) +def test_checks_and_require_perform_no_output_io( + workspace: Path, monkeypatch: pytest.MonkeyPatch, part: Part +) -> None: + profile = load_profile_registry().select( + [part], ProfileSelection(**{part: f"standard.{part}.v1"}) + )[part] + sentinel = workspace / f"existing_{part}.agp" + sentinel.write_bytes(b"operator-owned sentinel; not an AGP fixture") + before = sentinel.stat() + missing_parent = workspace / "never-created" + io = Mock(side_effect=AssertionError("Capability boundary attempted filesystem IO")) + with monkeypatch.context() as guard: + for method in ( + "open", + "mkdir", + "touch", + "write_bytes", + "write_text", + "read_bytes", + "read_text", + "stat", + "rename", + "replace", + "unlink", + ): + guard.setattr(Path, method, io) + guard.setattr("builtins.open", io) + guard.setattr("os.open", io) + capability = check_agp_capability(part, profile) + with pytest.raises(NativeFormatUnavailableError) as caught: + require_agp_capability(part, profile) + io.assert_not_called() + assert capability.available is False + assert set(asdict(capability)) == {"part", "format", "available", "reason"} + assert caught.value.code == "NATIVE_FORMAT_UNAVAILABLE" + assert caught.value.details == { + "format": "agp", + "part": part, + "reason": capability.reason, + } + assert not missing_parent.exists() + assert list(workspace.iterdir()) == [sentinel] + assert sentinel.read_bytes() == b"operator-owned sentinel; not an AGP fixture" + after = sentinel.stat() + assert (after.st_ino, after.st_size, after.st_mtime_ns) == ( + before.st_ino, + before.st_size, + before.st_mtime_ns, + ) + + +def test_lead_and_bass_native_preflight_leaves_empty_output(workspace: Path) -> None: + selected = load_profile_registry().select( + ["lead", "bass"], ProfileSelection(lead="standard.lead.v1", bass="standard.bass.v1") + ) + for part, profile in selected.items(): + with pytest.raises(NativeFormatUnavailableError): + require_agp_capability(part, profile) + assert list(workspace.iterdir()) == [] + + +@pytest.mark.parametrize("part", ["lead", "bass"]) +def test_explicit_independent_midi_remains_available_without_fake_agp( + workspace: Path, part: Part +) -> None: + request = GenerateMusicRequest( + description=f"{part} only 1 bar quarter", + basename="explicit-midi", + formats=["mid"], + ) + resolved = resolve_description(request) + selected = load_profile_registry().select( + resolved.intent.parts, ProfileSelection(**{part: f"standard.{part}.v1"}) + ) + with pytest.raises(NativeFormatUnavailableError) as caught: + require_agp_capability(part, selected[part]) + assert caught.value.details["part"] == part + assert list(workspace.iterdir()) == [] + score = compose_score(resolved.intent, selected) + plan = compile_score(score, selected) + midi = workspace / "explicit-midi.mid" + assert write_midi(midi, plan) == midi + validate_midi_file(midi, plan) + assert midi.read_bytes().startswith(b"MThd") + assert list(workspace.iterdir()) == [midi] + assert not list(workspace.rglob("*.agp")) + assert check_agp_capability(part, selected[part]).available is False + + +def test_corrupted_profile_leaves_existing_output_untouched(workspace: Path) -> None: + sentinel = workspace / "existing_lead.agp" + sentinel.write_bytes(b"existing operator data") + profile = load_profile_registry().select(["lead"], ProfileSelection(lead="standard.lead.v1"))[ + "lead" + ] + profile.summary.native_available = True + with pytest.raises(InvalidProfileError) as caught: + require_agp_capability("lead", profile) + assert caught.value.code == "SERIALIZATION_ERROR" + assert sentinel.read_bytes() == b"existing operator data" + assert list(workspace.iterdir()) == [sentinel] diff --git a/tests/integration/test_articulation_midi.py b/tests/integration/test_articulation_midi.py new file mode 100644 index 0000000..cd5c006 --- /dev/null +++ b/tests/integration/test_articulation_midi.py @@ -0,0 +1,565 @@ +"""Real MIDI and wheel checks of synthetic mechanics and standard fallback, not vendors.""" + +import json +import os +import shutil +import subprocess +import sys +import uuid +from collections.abc import Iterator +from fractions import Fraction +from pathlib import Path + +import mido # type: ignore[import-untyped] +import pytest + +from riff_groove_builder.articulations import ArticulationCompileError, compile_score +from riff_groove_builder.errors import UnsupportedArticulationError +from riff_groove_builder.midi import validate_midi_file, write_midi +from riff_groove_builder.profiles import load_profile_registry, parse_profile +from riff_groove_builder.schemas import ( + ControlChangeEvent, + DrumNote, + EventPlan, + MusicalIntent, + Part, + PitchedNote, + PositiveBeat, + ProfileSelection, + RationalBeat, + Score, + ScoreTrack, + TimeSignature, +) + +ROOT = Path(__file__).resolve().parents[2] +FIXTURES = ROOT / "tests" / "fixtures" / "profiles" +pytestmark = pytest.mark.integration +Event = tuple[int, str, int, int] + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"articulation-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +def ratio(value: Fraction | int) -> RationalBeat: + value = Fraction(value) + return RationalBeat(numerator=value.numerator, denominator=value.denominator) + + +def synthetic_score() -> Score: + # Explicit independent score, common logical origin 2; no compiler helpers. + def pitched( + part: Part, + start: Fraction | int, + length: Fraction | int, + pitch: int, + articulation: str, + intensity: float = 0.5, + ) -> PitchedNote: + assert part in ("lead", "bass") + return PitchedNote( + part=part, + start=ratio(start), + duration=PositiveBeat.model_validate(ratio(length).model_dump()), + pitch=pitch, + articulation=articulation, + intensity=intensity, + ) + + def drum( + start: Fraction | int, + length: Fraction | int, + voice: str, + art: str, + intensity: float, + ) -> DrumNote: + return DrumNote( + part="drums", + start=ratio(start), + duration=PositiveBeat.model_validate(ratio(length).model_dump()), + voice=voice, + articulation=art, + intensity=intensity, + ) + + return Score( + intent=MusicalIntent( + description="SYNTHETIC three-part articulated test", + parts=["lead", "bass", "drums"], + tempo_bpm=120, + bars=1, + time_signature=TimeSignature(numerator=4, denominator=4), + key="C major", + seed=0, + ), + start=ratio(2), + end=ratio(6), + tracks=[ + ScoreTrack( + part="lead", + notes=[ + pitched("lead", 2, 1, 60, "Palm Mute"), + pitched("lead", Fraction(5, 2), 1, 64, "pm", 1), + pitched("lead", 4, 1, 60, "normal"), + pitched("lead", 5, 1, 60, "sustain"), + ], + ), + ScoreTrack( + part="bass", + notes=[ + pitched("bass", 2, Fraction(1, 2), 40, "normal"), + pitched("bass", 3, Fraction(1, 2), 43, "slide"), + pitched("bass", Fraction(13, 4), Fraction(3, 4), 45, "slide"), + pitched("bass", Fraction(17, 4), Fraction(7, 4), 40, "normal"), + ], + ), + ScoreTrack( + part="drums", + notes=[ + drum(2, Fraction(1, 2), "low", "accent", 0.5), + drum(Fraction(9, 4), Fraction(1, 2), "high_hit", "hard hit", 1), + drum(3, 1, "low_hit", "normal", 0), + drum(Fraction(11, 2), Fraction(1, 2), "high", "accent", 0), + ], + ), + ], + ) + + +def expected() -> list[list[Event]]: + # Hand-derived absolute ticks/payloads; never iterate production events to build expectations. + return [ + [ + (0, "note_on", 2, 64), + (0, "control_change", 20, 64), + (60, "note_off", 2, 0), + (120, "note_on", 60, 80), + (600, "note_on", 64, 100), + (1080, "note_off", 60, 0), + (1560, "note_off", 64, 0), + (1920, "note_on", 1, 64), + (1920, "control_change", 20, 0), + (1980, "note_off", 1, 0), + (2040, "note_on", 60, 64), + (3000, "note_off", 60, 0), + (3000, "note_on", 60, 64), + (3960, "note_off", 60, 0), + ], + [ + (120, "note_on", 3, 60), + (120, "control_change", 21, 0), + (120, "note_on", 40, 60), + (180, "note_off", 3, 0), + (600, "note_off", 40, 0), + (960, "note_on", 4, 60), + (960, "control_change", 21, 90), + (1080, "note_on", 43, 60), + (1200, "control_change", 21, 90), + (1320, "note_on", 45, 60), + (1560, "note_off", 43, 0), + (2040, "note_off", 45, 0), + (2100, "note_off", 4, 0), + (2100, "control_change", 21, 0), + (2100, "note_on", 3, 60), + (2100, "control_change", 21, 0), + (2160, "note_off", 3, 0), + (2280, "note_on", 40, 60), + (3960, "note_off", 40, 0), + ], + [ + (120, "control_change", 22, 0), + (120, "control_change", 22, 100), + (120, "note_on", 36, 100), + (360, "control_change", 22, 100), + (360, "note_on", 40, 120), + (600, "note_off", 36, 0), + (840, "note_off", 40, 0), + (900, "control_change", 22, 0), + (900, "control_change", 22, 0), + (1080, "note_on", 36, 1), + (2040, "note_off", 36, 0), + (3480, "control_change", 22, 100), + (3480, "note_on", 40, 80), + (3960, "note_off", 40, 0), + (4020, "control_change", 22, 0), + (4020, "control_change", 22, 0), + ], + ] + + +def compiled() -> EventPlan: + return compile_score( + synthetic_score(), + { + part: parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) + for part in synthetic_score().intent.parts + }, + ) + + +def test_three_part_exact_events_saved_readback_and_shared_tail(workspace: Path) -> None: + plan = compiled() + assert (plan.musical_start_tick, plan.musical_end_tick, plan.end_tick) == (120, 3960, 4020) + for track, independent in zip(plan.tracks, expected(), strict=True): + observed = [ + ( + e.tick, + e.kind, + e.controller if isinstance(e, ControlChangeEvent) else e.note, + e.value if isinstance(e, ControlChangeEvent) else e.velocity, + ) + for e in track.events + ] + assert observed == independent + path = write_midi(workspace / "synthetic.mid", plan) + validate_midi_file(path, plan) + midi = mido.MidiFile(path) + assert midi.type == 1 and midi.ticks_per_beat == 960 and len(midi.tracks) == 4 + for track, independent, channel in zip(midi.tracks[1:], expected(), [2, 5, 12], strict=True): + tick = 0 + events: list[Event] = [] + active: dict[int, int] = {} + for message in track: + tick += message.time + if message.is_meta: + continue + assert message.channel == channel + if message.type == "control_change": + events.append((tick, message.type, message.control, message.value)) + else: + events.append((tick, message.type, message.note, message.velocity)) + if message.type == "note_on": + assert message.note not in active + active[message.note] = tick + else: + assert tick > active.pop(message.note) + assert events == independent + assert active == {} and tick == 4020 + assert track[-1].type == "end_of_track" + assert sum(m.time for m in midi.tracks[0]) == 4020 + assert midi.tracks[0][1].tempo == 500000 + other = write_midi(workspace / "repeat.mid", compiled()) + assert other.read_bytes() == path.read_bytes() + + +def test_shared_channels_rejected_including_empty_selected_parts() -> None: + source = synthetic_score() + selected = { + part: parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) + for part in source.intent.parts + } + source.tracks[1].notes = [] + selected["bass"].channel = selected["lead"].channel + with pytest.raises(ArticulationCompileError) as error: + compile_score(source, selected) + assert error.value.details["reason"] == "shared_channel" + + +def test_unsupported_voice_never_guesses_gm_map() -> None: + source = synthetic_score() + drum = source.tracks[2].notes[0] + assert isinstance(drum, DrumNote) + drum.voice = "acoustic_bass_drum" + with pytest.raises(ArticulationCompileError) as error: + compile_score( + source, + { + part: parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) + for part in source.intent.parts + }, + ) + assert error.value.details["reason"] == "unsupported_drum_voice" + + +def standard_score() -> Score: + return Score( + intent=MusicalIntent( + description="Standard MIDI fallback, no verified vendor mapping", + parts=["lead", "bass", "drums"], + tempo_bpm=120, + bars=1, + time_signature=TimeSignature(numerator=4, denominator=4), + key="C major", + seed=0, + ), + start=ratio(0), + end=ratio(4), + tracks=[ + ScoreTrack( + part="lead", + notes=[ + PitchedNote( + part="lead", + start=ratio(0), + duration=PositiveBeat(numerator=1), + pitch=0, + articulation="normal", + intensity=0, + ), + PitchedNote( + part="lead", + start=ratio(1), + duration=PositiveBeat(numerator=1), + pitch=127, + articulation="sustain", + intensity=1, + ), + ], + ), + ScoreTrack( + part="bass", + notes=[ + PitchedNote( + part="bass", + start=ratio(0), + duration=PositiveBeat(numerator=2), + pitch=40, + articulation="sustain", + intensity=0.5, + ), + ], + ), + ScoreTrack( + part="drums", + notes=[ + DrumNote( + part="drums", + start=ratio(0), + duration=PositiveBeat(numerator=1), + voice="kick", + articulation="normal", + intensity=0.25, + ), + DrumNote( + part="drums", + start=ratio(1), + duration=PositiveBeat(numerator=1), + voice="snare", + articulation="sustain", + intensity=0.75, + ), + DrumNote( + part="drums", + start=ratio(2), + duration=PositiveBeat(numerator=1), + voice="closed_hat", + articulation="normal", + intensity=0.5, + ), + ], + ), + ], + ) + + +def test_standard_fallback_compiles_and_roundtrips_real_midi(workspace: Path) -> None: + score = standard_score() + profiles = load_profile_registry().select( + score.intent.parts, + ProfileSelection( + lead="standard.lead.v1", bass="standard.bass.v1", drums="standard.gm-drums.v1" + ), + ) + plan = compile_score(score, profiles) + assert plan == compile_score(score, profiles) + assert (plan.musical_start_tick, plan.musical_end_tick, plan.end_tick) == (0, 3840, 3840) + independent: list[list[Event]] = [ + [ + (0, "note_on", 0, 1), + (960, "note_off", 0, 0), + (960, "note_on", 127, 127), + (1920, "note_off", 127, 0), + ], + [(0, "note_on", 40, 64), (1920, "note_off", 40, 0)], + [ + (0, "note_on", 36, 32), + (960, "note_off", 36, 0), + (960, "note_on", 38, 96), + (1920, "note_off", 38, 0), + (1920, "note_on", 42, 64), + (2880, "note_off", 42, 0), + ], + ] + assert [{event.channel for event in track.events} for track in plan.tracks] == [{0}, {1}, {9}] + for track, expected_events in zip(plan.tracks, independent, strict=True): + assert all(e.role == "musical_note" for e in track.events) + assert [ + (e.tick, e.kind, e.note, e.velocity) + for e in track.events + if not isinstance(e, ControlChangeEvent) + ] == expected_events + path = write_midi(workspace / "standard-fallback.mid", plan) + validate_midi_file(path, plan) + midi = mido.MidiFile(path) + assert midi.type == 1 and midi.ticks_per_beat == 960 and len(midi.tracks) == 4 + assert [m.tempo for m in midi.tracks[0] if m.type == "set_tempo"] == [500000] + assert [(m.numerator, m.denominator) for m in midi.tracks[0] if m.type == "time_signature"] == [ + (4, 4) + ] + for track, channel, expected_events in zip( + midi.tracks[1:], [0, 1, 9], independent, strict=True + ): + tick = 0 + events: list[Event] = [] + for message in track: + tick += message.time + if not message.is_meta: + assert message.type in ("note_on", "note_off") + assert message.channel == channel + events.append((tick, message.type, message.note, message.velocity)) + assert events == expected_events + assert tick == 3840 and track[-1].type == "end_of_track" + + +@pytest.mark.parametrize( + ("part", "technique"), [("lead", "palm_mute"), ("bass", "slide"), ("drums", "accent")] +) +def test_standard_fallback_rejects_unsupported_techniques(part: Part, technique: str) -> None: + score = standard_score() + track = next(track for track in score.tracks if track.part == part) + track.notes[0].articulation = technique + profiles = load_profile_registry().select( + score.intent.parts, + ProfileSelection( + lead="standard.lead.v1", bass="standard.bass.v1", drums="standard.gm-drums.v1" + ), + ) + with pytest.raises(UnsupportedArticulationError) as error: + compile_score(score, profiles) + assert error.value.code == "UNSUPPORTED_ARTICULATION" + assert "verified profile" not in error.value.public_message + + +def test_standard_fallback_rejects_unknown_voice() -> None: + score = standard_score() + note = score.tracks[2].notes[0] + assert isinstance(note, DrumNote) + note.voice = "sd3_custom_voice" + profiles = load_profile_registry().select( + score.intent.parts, + ProfileSelection( + lead="standard.lead.v1", bass="standard.bass.v1", drums="standard.gm-drums.v1" + ), + ) + with pytest.raises(ArticulationCompileError) as error: + compile_score(score, profiles) + assert error.value.details["reason"] == "unsupported_drum_voice" + + +def test_built_wheel_standard_registry_installed_and_zip_resources_outside_repo( + workspace: Path, +) -> None: + scratch = workspace / "scratch" + scratch.mkdir() + env = os.environ.copy() + for name in ("PYTHONPATH", "PYTHONHOME"): + env.pop(name, None) + env.update( + { + "TEMP": str(scratch), + "TMP": str(scratch), + "TMPDIR": str(scratch), + "PIP_NO_INDEX": "1", + "PIP_NO_CACHE_DIR": "1", + "PYTHONDONTWRITEBYTECODE": "1", + "PIP_DISABLE_PIP_VERSION_CHECK": "1", + } + ) + + def run(args: list[str], *, outside: bool = False) -> str: + result = subprocess.run( + [sys.executable, "-I", "-B", *args], + cwd=ROOT.parent if outside else ROOT, + env=env, + capture_output=True, + text=True, + timeout=180, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + return result.stdout + + # Build the wheel from the sdist so build intermediates stay in this workspace. + run(["-m", "build", "--no-isolation", "--outdir", str(workspace / "dist")]) + wheel = next((workspace / "dist").glob("*.whl")) + installed = workspace / "installed" + run( + [ + "-m", + "pip", + "install", + "--no-deps", + "--no-index", + "--no-cache-dir", + "--target", + str(installed), + str(wheel), + ] + ) + probe = """ +import json +import pathlib +import sys +sys.path.insert(0, sys.argv[1]) +import riff_groove_builder.profiles as profiles +from importlib.resources import files +from riff_groove_builder.data.profiles import PROFILE_RESOURCES +from riff_groove_builder.schemas import ProfileListResult, ProfileSelection +assert str(profiles.__file__).startswith(sys.argv[1]) +assert set(PROFILE_RESOURCES) == { + "standard-midi-lead-v1.json", "standard-midi-bass-v1.json", + "general-midi-percussion-v1.json", + "ample-metal-eclipse-4.0.1-riffer-v1.json", + "ample-metal-ray5-4.1.0-riffer-v1.json", + "toontrack-sd3-3.4.4-core-v1.json", +} +root = files("riff_groove_builder.data.profiles") +assert root.joinpath("__init__.py").is_file() +assert {p.name for p in root.iterdir() if p.name.endswith(".json")} == set(PROFILE_RESOURCES) +registry = profiles.load_profile_registry() +summaries = registry.summaries() +assert [p.id for p in summaries] == [ + "ample.ame.4.0.1.riffer.v1", "ample.amr.4.1.0.riffer.v1", + "standard.bass.v1", "standard.gm-drums.v1", "standard.lead.v1", + "toontrack.sd3.3.4.4.core.v1" +] +assert ProfileListResult(profiles=summaries).profiles == summaries +defaults = registry.select(["lead", "bass", "drums"], ProfileSelection()) +assert all(p.default and p.provenance.status == "verified_subset" for p in defaults.values()) +selected = registry.select(["lead", "bass", "drums"], ProfileSelection( + lead="standard.lead.v1", bass="standard.bass.v1", drums="standard.gm-drums.v1" +)) +assert {part: p.channel for part, p in selected.items()} == {"lead": 0, "bass": 1, "drums": 9} +for p in selected.values(): + assert p.summary.mapping_kind == p.provenance.status == "standard_midi" + assert not p.default and not p.summary.native_available + assert "NOT a verified" in p.summary.product_name + assert not p.id.startswith("test.") and not p.summary.product_name.startswith("SYNTHETIC") + assert p.summary.supported_articulations == ["normal"] + assert p.resolve_articulation("sustain").actions == [] +assert selected["drums"].resolve_voice("kick") == 36 +assert selected["drums"].resolve_voice("snare") == 38 +assert selected["drums"].resolve_voice("closed_hat") == 42 +print(json.dumps({"module": str(profiles.__file__), "cwd": str(pathlib.Path.cwd()), + "profiles": [p.id for p in summaries], "isolated": sys.flags.isolated})) +""" + for location in [installed, wheel]: + evidence = json.loads(run(["-c", probe, str(location)], outside=True)) + assert evidence["profiles"] == [ + "ample.ame.4.0.1.riffer.v1", + "ample.amr.4.1.0.riffer.v1", + "standard.bass.v1", + "standard.gm-drums.v1", + "standard.lead.v1", + "toontrack.sd3.3.4.4.core.v1", + ] + assert evidence["isolated"] == 1 + assert Path(evidence["cwd"]) == ROOT.parent + print(f"Wheel profile-resource evidence: {evidence}") diff --git a/tests/integration/test_cc_stdio.py b/tests/integration/test_cc_stdio.py new file mode 100644 index 0000000..1fd5988 --- /dev/null +++ b/tests/integration/test_cc_stdio.py @@ -0,0 +1,332 @@ +"""Real stdio control acceptance, shared verbatim with installed-wheel acceptance.""" + +import asyncio +import hashlib +import json +import shutil +import sys +import uuid +import xml.etree.ElementTree as ET +from collections.abc import Iterator +from pathlib import Path +from unittest.mock import patch + +import anyio +import mido # type: ignore[import-untyped] +import pytest +from jsonschema import Draft202012Validator +from test_native_service import TEMPLATE, job, plan_for, validate_saved +from test_stdio import TIMEOUT, RawStdio, _environment + +from riff_groove_builder.errors import InvalidRequestError, SerializationError +from riff_groove_builder.schemas import ( + MAX_SCHEDULED_EVENTS, + GenerationError, + GenerationResult, + NoteOffEvent, + NoteOnEvent, + Part, + tool_input_schema, + tool_output_schema, +) +from riff_groove_builder.service import GenerationService + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = pytest.mark.integration + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +@pytest.fixture +def controls_workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"cc-controls-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +def control(part: Part, tick: int, controller: int, value: int) -> dict[str, object]: + return { + "part": part, + "beat": {"numerator": tick, "denominator": 960}, + "controller": controller, + "value": value, + } + + +PITCHED = [ + control("lead", 0, 1, 11), + control("lead", 480, 1, 73), + control("lead", 6720, 1, 0), + control("bass", 0, 1, 21), + control("bass", 960, 1, 127), + control("bass", 6720, 1, 0), +] +DRUMS = [control("drums", 320, 4, 96), control("drums", 6720, 4, 0)] +OTHER = [control("lead", 320, 74, 127), control("lead", 6720, 74, 0)] + + +def independent_controls( + result: GenerationResult, expected: dict[Part, list[tuple[int, int, int]]] +) -> None: + """Use raw Mido deltas/bytes and XML stair points, not the scheduled-plan helper.""" + for artifact in result.artifacts: + if artifact.format == "mid": + midi = mido.MidiFile(artifact.path) + assert midi.ticks_per_beat == 960 + for part, track in zip(result.resolved.parts, midi.tracks[1:], strict=True): + tick = 0 + observed = [] + channels = {"lead": 0, "bass": 1, "drums": 9} + absolute = [] + for msg in track: + tick += msg.time + absolute.append((tick, msg.type)) + if msg.type == "control_change": + assert msg.channel == channels[part] + assert msg.bytes() == [0xB0 | channels[part], msg.control, msg.value] + observed.append((tick, msg.control, msg.value)) + assert observed == expected.get(part, []) + for onset, kind in absolute: + if kind == "control_change": + same_tick = [k for t, k in absolute if t == onset] + if "note_on" in same_tick: + assert same_tick.index("control_change") < same_tick.index("note_on") + assert tick == 6720 + elif artifact.format in ("griff", "briff"): + xml = ET.parse(artifact.path).getroot() + assert xml.attrib["PPQBase"] == "480" + points = xml.findall("./cc-1.Mod/p") + assert [(int(p.attrib["tick"]), int(p.attrib["value"])) for p in points] == [ + (tick // 2, value) + for tick, controller, value in expected.get(artifact.parts[0], []) + if controller == 1 + ] + assert all(p.attrib["curveType"] == "stair" for p in points) + + +async def exercise_control_stdio( + client: RawStdio, outputs: Path, template: Path, *, prefix: str +) -> list[str]: + listed = (await client.request(f"{prefix}-schemas", "tools/list"))["result"]["tools"] + schema = next(tool["inputSchema"] for tool in listed if tool["name"] == "generate_music") + assert schema == tool_input_schema("generate_music") + assert "cc_events" in schema["properties"] and "cc_events" not in schema["required"] + assert next( + tool["outputSchema"] for tool in listed if tool["name"] == "generate_music" + ) == tool_output_schema("generate_music") + expected: dict[Part, list[tuple[int, int, int]]] = { + "lead": [(0, 1, 11), (480, 1, 73), (6720, 1, 0)], + "bass": [(0, 1, 21), (960, 1, 127), (6720, 1, 0)], + } + published = [] + evidence = [] + cases: list[tuple[str, dict[str, object], list[str], list[Part]]] = [ + ( + "pitched", + {"parts": ["lead", "bass"], "cc_events": PITCHED, "allow_midi_fallback": False}, + ["mid", "griff", "briff"], + [], + ), + ("drums", {"cc_events": [*PITCHED, *DRUMS]}, ["mid", "griff", "briff"], ["drums"]), + ("other", {"cc_events": [*PITCHED, *OTHER]}, ["mid", "briff", "sd3p"], ["lead"]), + ( + "midi", + { + "formats": ["mid"], + "cc_events": [*PITCHED, *DRUMS, *OTHER], + "allow_midi_fallback": False, + }, + ["mid"], + [], + ), + ("tick", {"formats": ["mid"], "cc_events": [control("lead", 1, 1, 99)]}, ["mid"], []), + ("omitted", {}, ["mid", "griff", "briff", "sd3p"], []), + ("empty", {"cc_events": []}, ["mid", "griff", "briff", "sd3p"], []), + ] + no_controls: list[list[bytes]] = [] + for label, options, formats, fallback in cases: + basename = f"{prefix}-{label}" + req = job(basename=basename, **options) + arguments = req.model_dump(mode="json", exclude_none=True) + if label == "omitted": + arguments.pop("cc_events") + Draft202012Validator(schema).validate(arguments) + response = await client.request( + basename, "tools/call", {"name": "generate_music", "arguments": arguments} + ) + payload = response["result"] + assert payload["isError"] is False + result = GenerationResult.model_validate(payload["structuredContent"]) + assert result.status == ("midi_fallback" if fallback else "complete") + assert [a.format for a in result.artifacts] == formats + assert result.artifacts[0].fallback_for == fallback + warnings = [w for w in result.warnings if w.code == "NATIVE_FORMAT_UNAVAILABLE"] + assert [w.part for w in warnings] == fallback + if warnings: + assert ( + "sd3_native_controller_not_supported" + if label == "drums" + else "unsupported_native_controller" + ) in warnings[0].message + validate_saved(result, req, template) + wanted = {**expected} if label not in ("tick", "omitted", "empty") else {} + if label in ("drums", "midi"): + wanted["drums"] = [(320, 4, 96), (6720, 4, 0)] + if label in ("other", "midi"): + wanted["lead"] = [(0, 1, 11), (320, 74, 127), (480, 1, 73), (6720, 1, 0), (6720, 74, 0)] + if label == "tick": + wanted["lead"] = [(1, 1, 99)] + independent_controls(result, wanted) + if label in ("omitted", "empty"): + no_controls.append([Path(a.path).read_bytes() for a in result.artifacts]) + evidence.append({"case": label, "formats": formats, "fallback": fallback, "cc": wanted}) + published.append(basename) + assert no_controls[0] == no_controls[1] + # Original fixture/request baseline recorded before cc_events existed (report_9_fix). + assert [hashlib.sha256(raw).hexdigest() for raw in no_controls[0]] == [ + "8fc4cfbe66c0706f223ec33a61692ead046a56a9dba51c6566f967690cee186c", + "fe7a2a5c98d0ae16f6894e681e7f001a658c90d11b3f1beb313d5c98b6c810c9", + "5da9b05e92e6989366f41f8abf22a0f8b88ae14591bc8b544e4c7c0cf47827c4", + "8bee8a86a7e60320d02c4404e36d818639af1d8f4ebce27f6c23a25e7ebd0589", + ] + failures: list[tuple[str, dict[str, object], str, str]] = [ + ( + "disabled-drums", + {"cc_events": DRUMS, "allow_midi_fallback": False}, + "NATIVE_FORMAT_UNAVAILABLE", + "sd3_native_controller_not_supported", + ), + ( + "disabled-lead", + {"cc_events": OTHER, "allow_midi_fallback": False}, + "NATIVE_FORMAT_UNAVAILABLE", + "unsupported_native_controller", + ), + ( + "bad-part", + {"description": "lead only", "cc_events": DRUMS}, + "INVALID_REQUEST", + "resolved_part_association", + ), + ( + "past-end", + {"cc_events": [control("lead", 6721, 1, 1)]}, + "INVALID_REQUEST", + "beat_after_musical_end", + ), + ] + for label, options, code, reason in failures: + before = sorted(outputs.iterdir()) + req = job(basename=f"{prefix}-{label}", **options) + response = await client.request( + label, + "tools/call", + {"name": "generate_music", "arguments": req.model_dump(mode="json", exclude_none=True)}, + ) + assert response["result"]["isError"] is True + Draft202012Validator(tool_output_schema("generate_music")).validate( + response["result"]["structuredContent"] + ) + error = GenerationError.model_validate(response["result"]["structuredContent"]) + assert error.code == code and error.details["reason"] == reason + assert sorted(outputs.iterdir()) == before + assert not list(outputs.glob(".riff-stage-*")) + print(f"CC stdio evidence {prefix}: {json.dumps(evidence, sort_keys=True)}") + return published + + +@pytest.mark.anyio +async def test_real_stdio_exact_controls(controls_workspace: Path) -> None: + outputs = controls_workspace / "outputs" + outputs.mkdir() + outside = controls_workspace / "other-cwd" + outside.mkdir() + template = controls_workspace / "original-template.sd3p" + shutil.copyfile(TEMPLATE, template) + original, info = template.read_bytes(), template.stat() + process = await asyncio.wait_for( + asyncio.create_subprocess_exec( + sys.executable, + "-I", + "-B", + "-m", + "riff_groove_builder", + "--output-dir", + str(outputs), + "--sd3-template", + str(template), + cwd=outside, + env=_environment(), + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ), + TIMEOUT, + ) + client = RawStdio(process) + try: + await client.initialize() + published = await exercise_control_stdio(client, outputs, template, prefix="cc") + finally: + with anyio.CancelScope(shield=True): + await client.close() + assert process.returncode == 0 and client.diagnostics == b"" + assert len(client.lines) == 13 + assert sorted(p.name for p in outputs.iterdir()) == sorted(published) + assert template.read_bytes() == original + assert (template.stat().st_ino, template.stat().st_mtime_ns) == (info.st_ino, info.st_mtime_ns) + + +@pytest.mark.parametrize("corruption", ["channel", "note", "role", "release"]) +def test_service_corrupt_drums_with_cc_never_fallback( + controls_workspace: Path, corruption: str +) -> None: + req = job(cc_events=DRUMS) + base, _ = plan_for(job()) + for event in base.tracks[-1].events: + if corruption == "channel": + event.channel = 8 + if isinstance(event, NoteOnEvent | NoteOffEvent): + if corruption == "note": + event.note += 1 + if corruption == "role": + event.role = "keyswitch" + if corruption == "release" and isinstance(event, NoteOffEvent): + event.velocity = 1 + service = GenerationService(controls_workspace, sd3_template=TEMPLATE) + with patch("riff_groove_builder.service.compile_score", return_value=base): + with pytest.raises(SerializationError) as failure: + service.generate_music(req) + assert failure.value.details["reason"] in { + "unsupported_sd3_event_semantics", + "score_event_plan_mismatch", + } + assert list(controls_workspace.iterdir()) == [] + + +def test_service_inferred_part_pre_stage(controls_workspace: Path) -> None: + service = GenerationService(controls_workspace) + with pytest.raises(InvalidRequestError) as failure: + service.generate_music(job(description="lead only", cc_events=DRUMS)) + assert failure.value.details["reason"] == "resolved_part_association" + assert list(controls_workspace.iterdir()) == [] + + +def test_service_combined_budget_pre_stage(controls_workspace: Path) -> None: + service = GenerationService(controls_workspace) + req = job( + description="lead only 256 bars quarter", + cc_events=[control("lead", tick, 1, 73) for tick in range(MAX_SCHEDULED_EVENTS)], + ) + with patch.object(service, "_new_stage") as staging: + with pytest.raises(InvalidRequestError) as failure: + service.generate_music(req) + assert failure.value.details == {"field": "cc_events", "reason": "event_budget_exceeded"} + staging.assert_not_called() + assert list(controls_workspace.iterdir()) == [] diff --git a/tests/integration/test_contracts.py b/tests/integration/test_contracts.py new file mode 100644 index 0000000..dc40718 --- /dev/null +++ b/tests/integration/test_contracts.py @@ -0,0 +1,363 @@ +"""Model/JSON Schema integration with synthetic in-memory data, never real outputs.""" + +import json +import subprocess +import sys +from fractions import Fraction + +import pytest +from jsonschema import Draft202012Validator +from pydantic import ValidationError + +from riff_groove_builder.schemas import ( + GENERATION_OUTPUT, + PROFILE_LIST_OUTPUT, + EventPlan, + GenerateMusicRequest, + GenerationError, + GenerationResult, + ListInstrumentProfilesRequest, + ProfileListResult, + ToolName, + tool_input_schema, + tool_output_schema, +) + + +@pytest.mark.parametrize( + ("parts", "formats"), + [ + (["lead"], ["mid", "agp"]), + (["bass"], ["agp"]), + (["drums"], ["sdp"]), + (["lead", "bass"], ["mid", "agp"]), + (["lead", "bass", "drums"], ["mid", "agp", "sdp"]), + ], +) +def test_representative_requests(parts: list[str], formats: list[str]) -> None: + data = { + "description": "Synthetic contract example, not interpreted here.", + "basename": "contract-1", + "parts": parts, + "formats": formats, + "tempo_bpm": 120.5, + "profiles": {part: f"synthetic-{part}" for part in parts}, + } + schema = tool_input_schema("generate_music") + Draft202012Validator(schema).validate(data) + model = GenerateMusicRequest.model_validate(data) + serialized = model.model_dump_json(exclude_unset=True) + Draft202012Validator(schema).validate(json.loads(serialized)) + restored = GenerateMusicRequest.model_validate_json(serialized) + assert restored == model + assert restored.model_fields_set == model.model_fields_set + assert restored.bars is None and restored.key is None and restored.time_signature is None + assert "bars" not in json.loads(serialized) + + +@pytest.mark.parametrize("tool", ["list_instrument_profiles", "generate_music"]) +def test_schemas_are_valid_independent_and_explicit(tool: ToolName) -> None: + input_schema = tool_input_schema(tool) + output_schema = tool_output_schema(tool) + Draft202012Validator.check_schema(input_schema) + Draft202012Validator.check_schema(output_schema) + assert input_schema["additionalProperties"] is False + assert output_schema["type"] == "object" + assert len(output_schema["oneOf"]) == 2 + input_schema["additionalProperties"] = True + output_schema.clear() + assert tool_input_schema(tool)["additionalProperties"] is False + assert "oneOf" in tool_output_schema(tool) + + +@pytest.mark.parametrize( + "updates", + [ + {"description": " "}, + {"basename": "con"}, + {"basename": "../bad"}, + {"basename": "valid\n"}, + {"parts": []}, + {"parts": ["bass", "bass"]}, + {"parts": ["guitar"]}, + {"formats": []}, + {"formats": ["mid", "mid"]}, + {"formats": ["wav"]}, + {"tempo_bpm": True}, + {"tempo_bpm": 301}, + {"bars": True}, + {"bars": 0}, + {"seed": -1}, + {"seed": True}, + {"allow_midi_fallback": 1}, + {"time_signature": {"numerator": 4, "denominator": 3}}, + {"key": "C major minor"}, + {"key": "C major\n"}, + {"profiles": {"guitar": "synthetic"}}, + {"parts": ["drums"], "formats": ["agp"]}, + {"parts": ["lead"], "formats": ["sdp"]}, + {"parts": ["lead"], "profiles": {"bass": "synthetic"}}, + {"extra": 1}, + ], +) +def test_request_schema_and_model_reject_representative_bad_payloads( + updates: dict[str, object], +) -> None: + data = {"description": "riff", "basename": "contract", **updates} + assert not Draft202012Validator(tool_input_schema("generate_music")).is_valid(data) + with pytest.raises(ValidationError): + GenerateMusicRequest.model_validate(data) + + +def test_empty_profile_contract_and_error_branch() -> None: + input_validator = Draft202012Validator(tool_input_schema("list_instrument_profiles")) + assert input_validator.is_valid({}) + assert not input_validator.is_valid({"extra": 1}) + assert not input_validator.is_valid([]) + assert ListInstrumentProfilesRequest.model_validate_json("{}").model_dump() == {} + validator = Draft202012Validator(tool_output_schema("list_instrument_profiles")) + for model in ( + ProfileListResult(profiles=[]), + GenerationError(code="PROFILE_REQUIRED", message="Select a verified profile.", details={}), + ): + payload = model.model_dump_json() + validator.validate(json.loads(payload)) + assert PROFILE_LIST_OUTPUT.validate_json(payload) == model + for data in ({}, {"profiles": [], "code": "INVALID_REQUEST", "message": "Bad", "details": {}}): + assert not validator.is_valid(data) + + +def complete_data() -> dict[str, object]: + return { + "status": "complete", + "resolved": { + "parts": ["lead", "bass", "drums"], + "tempo_bpm": 120.25, + "bars": 1, + "time_signature": {"numerator": 7, "denominator": 8}, + "key": "Bb minor", + "seed": 42, + "profile_ids": { + "lead": "synthetic-lead", + "bass": "synthetic-bass", + "drums": "synthetic-drums", + }, + "assumptions": [], + "overrides": ["Explicit key"], + "musical_start_tick": 30, + "musical_end_tick": 3390, + "ticks_per_quarter": 960, + }, + "artifacts": [ + { + "format": "mid", + "parts": ["lead", "bass", "drums"], + "path": r"C:\synthetic\contract.mid", + "size_bytes": 100, + "profile_ids": ["synthetic-lead", "synthetic-bass", "synthetic-drums"], + "fallback_for": [], + }, + { + "format": "griff", + "parts": ["lead"], + "path": r"C:\synthetic\contract_lead.griff", + "size_bytes": 100, + "profile_ids": ["synthetic-lead"], + "fallback_for": [], + }, + { + "format": "briff", + "parts": ["bass"], + "path": r"C:\synthetic\contract_bass.briff", + "size_bytes": 100, + "profile_ids": ["synthetic-bass"], + "fallback_for": [], + }, + { + "format": "sd3p", + "parts": ["drums"], + "path": r"C:\synthetic\contract_drums.sd3p", + "size_bytes": 100, + "profile_ids": ["synthetic-drums"], + "fallback_for": [], + }, + ], + "warnings": [], + } + + +def test_success_fallback_and_error_output_schema_round_trip() -> None: + complete = GenerationResult.model_validate(complete_data()) + data = complete.model_dump() + data["status"] = "midi_fallback" + data["artifacts"] = [data["artifacts"][0]] + data["artifacts"][0]["fallback_for"] = ["lead", "bass", "drums"] + data["warnings"] = [ + {"code": "NATIVE_FORMAT_UNAVAILABLE", "part": part, "message": "Synthetic test limit"} + for part in ("lead", "bass", "drums") + ] + validator = Draft202012Validator(tool_output_schema("generate_music")) + for model in ( + complete, + GenerationResult.model_validate(data), + GenerationError( + code="UNSUPPORTED_DESCRIPTION", + message="Use supported instructions.", + details={"unsupported": ["synthetic-term"]}, + ), + ): + serialized = model.model_dump_json() + validator.validate(json.loads(serialized)) + assert GENERATION_OUTPUT.validate_json(serialized) == model + updates: list[dict[str, object]] = [ + {"status": "unknown"}, + {"artifacts": []}, + {"warnings": [{"code": "NATIVE_FORMAT_UNAVAILABLE", "part": "lead", "message": "Test"}]}, + {"status": "midi_fallback"}, + {"code": "INVALID_REQUEST", "message": "Mixed branch", "details": {}}, + ] + for update in updates: + payload = {**complete.model_dump(), **update} + assert not validator.is_valid(payload) + with pytest.raises(ValidationError): + GenerationResult.model_validate(payload) + + +def test_profile_summary_model_schema_associations() -> None: + validator = Draft202012Validator(tool_output_schema("list_instrument_profiles")) + for part, instrument, native in ( + ("lead", "eclips", "griff"), + ("bass", "ray", "briff"), + ("drums", "sd3", "sd3p"), + ): + summary = { + "id": f"synthetic-{part}", + "part": part, + "instrument": instrument, + "product_name": "Synthetic metadata only", + "product_version": "test", + "mapping_version": "test", + "midi_available": False, + "native_format": native, + "native_available": False, + "supported_articulations": [], + "limitations": ["Not a verified production profile"], + } + model = ProfileListResult.model_validate({"profiles": [summary]}) + assert model.profiles[0].mapping_kind == "instrument" + assert validator.is_valid({"profiles": [summary]}) + validator.validate(json.loads(model.model_dump_json())) + assert PROFILE_LIST_OUTPUT.validate_json(model.model_dump_json()) == model + updates: list[dict[str, object]] = [ + {"instrument": "unknown"}, + {"native_format": "mid"}, + {"limitations": []}, + ] + for update in updates: + bad = {"profiles": [{**summary, **update}]} + assert not validator.is_valid(bad) + with pytest.raises(ValidationError): + ProfileListResult.model_validate(bad) + + +def test_standard_profile_summaries_model_and_schema() -> None: + from riff_groove_builder.profiles import load_profile_registry + + validator = Draft202012Validator(tool_output_schema("list_instrument_profiles")) + model = ProfileListResult(profiles=load_profile_registry().summaries()) + validator.validate(json.loads(model.model_dump_json())) + assert PROFILE_LIST_OUTPUT.validate_json(model.model_dump_json()) == model + for summary in model.profiles: + if summary.mapping_kind == "instrument": + assert summary.native_available and summary.limitations + continue + assert summary.mapping_kind == "standard_midi" + updates: list[dict[str, object]] = [ + {"mapping_kind": "GM"}, + {"native_available": True}, + {"supported_articulations": ["palm_mute"]}, + {"limitations": []}, + ] + for update in updates: + data = {"profiles": [{**summary.model_dump(), **update}]} + assert not validator.is_valid(data) + with pytest.raises(ValidationError): + ProfileListResult.model_validate(data) + + +def test_exact_rational_score_event_serialization_without_profile_map() -> None: + plan = EventPlan.model_validate( + { + "score": { + "intent": { + "description": "Synthetic timing test", + "parts": ["lead", "bass", "drums"], + "tempo_bpm": 120, + "bars": 1, + "time_signature": {"numerator": 1, "denominator": 4}, + "key": "C major", + "seed": 0, + }, + "start": {"numerator": 0}, + "end": {"numerator": 1}, + "tracks": [ + { + "part": part, + "notes": [ + { + "kind": "drum" if part == "drums" else "pitched", + "part": part, + **( + {"voice": "synthetic_voice"} + if part == "drums" + else {"pitch": 60} + ), + "start": {"numerator": 2, "denominator": 6}, + "duration": {"numerator": 1, "denominator": 7}, + "intensity": 0.5, + "articulation": "synthetic", + } + ], + } + for part in ("lead", "bass", "drums") + ], + }, + "musical_start_tick": 24, + "musical_end_tick": 984, + "end_tick": 1000, + "tracks": [{"part": part, "events": []} for part in ("lead", "bass", "drums")], + } + ) + serialized = plan.model_dump_json() + Draft202012Validator.check_schema(EventPlan.model_json_schema()) + Draft202012Validator(EventPlan.model_json_schema()).validate(json.loads(serialized)) + restored = EventPlan.model_validate_json(serialized) + assert restored == plan + for track in restored.score.tracks: + assert track.notes[0].start.value == Fraction(1, 3) + assert track.notes[0].duration.value == Fraction(1, 7) + assert track.notes[0].start.value + track.notes[0].duration.value == Fraction(10, 21) + assert track.notes[0].start.model_dump() == {"numerator": 1, "denominator": 3} + # A sub-tick logical duration is retained, not silently rounded by these models. + assert restored.score.tracks[0].notes[0].duration.value * 960 == Fraction(960, 7) + + +def test_contract_imports_do_not_start_server_or_write_protocol_output() -> None: + result = subprocess.run( + [ + sys.executable, + "-I", + "-B", + "-c", + "import sys; import riff_groove_builder.schemas; " + "import riff_groove_builder.errors; " + "assert 'mcp' not in sys.modules; " + "assert 'riff_groove_builder.server' not in sys.modules", + ], + capture_output=True, + text=True, + timeout=15, + check=False, + ) + assert result.returncode == 0, result.stderr + assert result.stdout == result.stderr == "" diff --git a/tests/integration/test_distribution.py b/tests/integration/test_distribution.py new file mode 100644 index 0000000..8a4e4a4 --- /dev/null +++ b/tests/integration/test_distribution.py @@ -0,0 +1,923 @@ +"""Offline built-wheel import and real stdio acceptance, not plugin certification.""" + +import asyncio +import hashlib +import json +import os +import shutil +import subprocess +import sys +import tarfile +import uuid +import zipfile +from collections.abc import Iterator +from email.parser import Parser +from pathlib import Path + +import anyio +import mido # type: ignore[import-untyped] +import pytest +from jsonschema import Draft202012Validator +from mcp.shared.version import SUPPORTED_PROTOCOL_VERSIONS +from test_cc_stdio import exercise_control_stdio +from test_hybrid_stdio import exercise_hybrid_stdio +from test_native_service import TEMPLATE, job, validate_saved +from test_phrase_stdio import exercise_phrase_stdio +from test_stdio import TIMEOUT, RawStdio +from test_text_feedback import exercise_text_feedback + +from riff_groove_builder.schemas import ( + GenerationError, + GenerationResult, + ProfileListResult, + ToolName, + tool_input_schema, + tool_output_schema, +) + +ROOT = Path(__file__).resolve().parents[2] +EVIDENCE = ROOT / ".test-artifacts" / "step16" / "installed-wheel" +pytestmark = pytest.mark.integration + + +def _distribution_directory(workspace: Path) -> Path: + configured = os.environ.get("RIFF_RELEASE_DIST") + if configured is None: + return workspace / "dist" + directory = Path(configured).resolve(strict=True) + assert directory.is_dir() and directory.is_relative_to(ROOT / "dist") + assert len(list(directory.glob("*.whl"))) == len(list(directory.glob("*.tar.gz"))) == 1 + return directory + + +def _run(command: list[str], *, cwd: Path, env: dict[str, str]) -> str: + result = subprocess.run( + command, + cwd=cwd, + env=env, + capture_output=True, + text=True, + timeout=180, + check=False, + ) + assert result.returncode == 0, ( + f"Command failed: {command!r}\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}" + ) + return result.stdout + + +@pytest.fixture(scope="module") +def distribution_workspace() -> Iterator[tuple[Path, dict[str, str]]]: + workspace = ROOT / ".test-artifacts" / f"distribution-{uuid.uuid4().hex}" + workspace.mkdir(parents=True) + scratch = workspace / "scratch" + scratch.mkdir() + env = os.environ.copy() + for name in ("PYTHONPATH", "PYTHONHOME"): + env.pop(name, None) + env.update( + { + "TEMP": str(scratch), + "TMP": str(scratch), + "TMPDIR": str(scratch), + "PIP_NO_INDEX": "1", + "PIP_NO_CACHE_DIR": "1", + "PIP_DISABLE_PIP_VERSION_CHECK": "1", + "PYTHONDONTWRITEBYTECODE": "1", + } + ) + try: + if os.environ.get("RIFF_RELEASE_DIST") is None: + # Default build makes the wheel from the sdist, exercising both layouts. + _run( + [ + sys.executable, + "-I", + "-B", + "-m", + "build", + "--no-isolation", + "--outdir", + str(workspace / "dist"), + str(ROOT), + ], + cwd=ROOT, + env=env, + ) + _distribution_directory(workspace) + yield workspace, env + finally: + shutil.rmtree(workspace) + + +def test_build_distributions( + distribution_workspace: tuple[Path, dict[str, str]], +) -> None: + workspace, _ = distribution_workspace + directory = _distribution_directory(workspace) + wheels = list(directory.glob("*.whl")) + sdists = list(directory.glob("*.tar.gz")) + assert len(wheels) == len(sdists) == 1 + with zipfile.ZipFile(wheels[0]) as wheel: + assert "riff_groove_builder/__init__.py" in wheel.namelist() + package_files = { + path.relative_to(ROOT / "src").as_posix(): path + for path in (ROOT / "src" / "riff_groove_builder").rglob("*") + if path.is_file() and path.suffix in (".py", ".json") + } + assert { + name for name in wheel.namelist() if name.startswith("riff_groove_builder/") + } == set(package_files) + for name, path in package_files.items(): + assert wheel.read(name) == path.read_bytes() + metadata_names = [name for name in wheel.namelist() if ".dist-info/" in name] + assert sorted(name.rsplit("/", 1)[1] for name in metadata_names) == [ + "METADATA", + "RECORD", + "WHEEL", + "top_level.txt", + ] + assert len(wheel.namelist()) == len(package_files) + len(metadata_names) + metadata = Parser().parsestr( + wheel.read(next(name for name in metadata_names if name.endswith("/METADATA"))).decode( + "utf-8" + ) + ) + assert metadata["Version"] == "0.2.0" + assert str(metadata.get_payload()).replace("\r\n", "\n") == (ROOT / "README.md").read_text( + "utf-8" + ) + with tarfile.open(sdists[0]) as sdist: + names = sdist.getnames() + assert any(name.endswith("/src/riff_groove_builder/__init__.py") for name in names) + assert any(name.endswith("/pyproject.toml") for name in names) + assert not any("/.venv/" in name or "/.test-artifacts/" in name for name in names) + files = { + "/".join(member.name.split("/")[1:]): member + for member in sdist.getmembers() + if member.isfile() + } + for name, path in package_files.items(): + saved = sdist.extractfile(files["src/" + name]) + assert saved is not None and saved.read() == path.read_bytes() + for name in ("README.md", "pyproject.toml"): + saved = sdist.extractfile(files[name]) + assert saved is not None and saved.read() == (ROOT / name).read_bytes() + assert all( + name in ("README.md", "pyproject.toml", "setup.cfg", "PKG-INFO") + or name.removeprefix("src/") in package_files + or name.startswith("src/gaj3t_musicgen_riff_groove_builder.egg-info/") + for name in files + ) + + +def test_wheel_import_outside_checkout( + distribution_workspace: tuple[Path, dict[str, str]], +) -> None: + workspace, env = distribution_workspace + wheel = next(_distribution_directory(workspace).glob("*.whl")) + environment = workspace / "wheel-venv" + outside_checkout = ROOT.parent + assert not outside_checkout.is_relative_to(ROOT) + _run( + [sys.executable, "-I", "-B", "-m", "venv", str(environment)], + cwd=outside_checkout, + env=env, + ) + python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + _run( + [ + str(python), + "-I", + "-B", + "-m", + "pip", + "install", + "--no-index", + "--no-deps", + "--no-cache-dir", + str(wheel), + ], + cwd=outside_checkout, + env=env, + ) + probe = """ +import contextlib +import importlib.metadata +import io +import json +import pathlib +import sys + +stdout, stderr = io.StringIO(), io.StringIO() +with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + import riff_groove_builder as package +assert stdout.getvalue() == stderr.getvalue() == "" +assert "mcp" not in sys.modules +assert "riff_groove_builder.server" not in sys.modules +distribution = importlib.metadata.distribution("gaj3t-musicgen-riff-groove-builder") +module_path = pathlib.Path(package.__file__).resolve() +installed_file = pathlib.Path(distribution.locate_file("riff_groove_builder/__init__.py")).resolve() +assert package.__version__ == distribution.version == "0.2.0" +assert module_path == installed_file +assert module_path.is_relative_to(pathlib.Path(sys.prefix).resolve()) +print(json.dumps({ + "version": package.__version__, + "metadata_version": distribution.version, + "module_path": str(module_path), + "prefix": sys.prefix, + "cwd": str(pathlib.Path.cwd()), + "isolated": sys.flags.isolated, +})) +""" + output = _run( + [str(python), "-I", "-B", "-c", probe], + cwd=outside_checkout, + env=env, + ) + evidence = json.loads(output) + assert evidence["isolated"] == 1 + assert Path(evidence["cwd"]).resolve() == outside_checkout + assert Path(evidence["module_path"]).is_relative_to(environment) + assert not Path(evidence["module_path"]).is_relative_to(ROOT / "src") + print(f"Installed-wheel evidence: {output.strip()}") + + +_WHEEL_BOOTSTRAP = """ +import hashlib +import importlib +import importlib.metadata +import importlib.resources +import json +from pathlib import Path +import runpy +import sys + +target = Path(sys.argv[1]).resolve() +sys.path.insert(0, str(target)) +names = ( + "riff_groove_builder", "riff_groove_builder.server", + "riff_groove_builder.service", "riff_groove_builder.schemas", + "riff_groove_builder.errors", "riff_groove_builder.description", + "riff_groove_builder.hybrid", "riff_groove_builder.pitch", + "riff_groove_builder.compose", "riff_groove_builder.profiles", + "riff_groove_builder.articulations", "riff_groove_builder.midi", + "riff_groove_builder.formats", "riff_groove_builder.formats.agp", + "riff_groove_builder.formats.sdp", "riff_groove_builder.data", + "riff_groove_builder.data.profiles", +) +locations = {} +for name in names: + module = importlib.import_module(name) + path = Path(module.__file__).resolve() + assert path.is_relative_to(target), (name, path) + locations[name] = str(path) +main_path = Path(importlib.util.find_spec("riff_groove_builder.__main__").origin).resolve() +assert main_path.is_relative_to(target) +locations["riff_groove_builder.__main__"] = str(main_path) +distribution = importlib.metadata.distribution("gaj3t-musicgen-riff-groove-builder") +assert Path(distribution.locate_file("")).resolve() == target +assert distribution.version == "0.2.0" +assert not json.loads(distribution.read_text("direct_url.json")).get("dir_info", {}).get("editable") +profiles = importlib.import_module("riff_groove_builder.data.profiles") +resources = importlib.resources.files(profiles) +resource_names = sorted(path.name for path in resources.iterdir() if path.name.endswith(".json")) +assert resource_names == sorted(profiles.PROFILE_RESOURCES) +resource_evidence = {} +for name in resource_names: + resource = resources.joinpath(name) + assert Path(str(resource)).resolve().is_relative_to(target) + assert json.loads(resource.read_text(encoding="utf-8"))["schema_version"] == "1" + resource_evidence[name] = { + "path": str(resource), "sha256": hashlib.sha256(resource.read_bytes()).hexdigest() + } +assert sys.flags.isolated == 1 +if sys.argv[2] == "probe": + from riff_groove_builder.articulations import compile_score + from riff_groove_builder.formats.agp import write_riffer, validate_riffer_file + from riff_groove_builder.profiles import load_profile_registry + from riff_groove_builder.schemas import Score, ProfileSelection, ControlChangeEvent + native_evidence = [] + output = target.parent / "installed-native-readback" + output.mkdir() + for part, identifier, pitch, extension in ( + ("lead", "ample.ame.4.0.1.riffer.v1", 36, "griff"), + ("bass", "ample.amr.4.1.0.riffer.v1", 35, "briff"), + ): + profile = load_profile_registry().select( + [part], ProfileSelection(**{part: identifier}) + )[part] + score = Score.model_validate({ + "intent": { + "description": "Original installed-wheel native verification", + "parts": [part], "tempo_bpm": 120, "bars": 1, + "time_signature": {"numerator": 4, "denominator": 4}, + "key": "C minor", "seed": 0, + }, + "start": {"numerator": 0}, "end": {"numerator": 4}, + "tracks": [{"part": part, "notes": [{ + "kind": "pitched", "part": part, "pitch": pitch, + "start": {"numerator": 0}, "duration": {"numerator": 1}, + "intensity": 0.5, "articulation": "palm_mute", + }]}], + }) + plan = compile_score(score, {part: profile}) + plan.tracks[0].events.append(ControlChangeEvent( + part=part, channel=profile.channel, tick=480, priority=10, + sequence=100, controller=1, value=120, + )) + path = output / ("original." + extension) + write_riffer(path, plan, part, profile) + saved = validate_riffer_file(path, plan, part, profile) + assert len(saved.notes) == 1 and saved.notes[0].pitch == pitch + assert saved.notes[0].articulation == ("PM" if part == "lead" else "PMP") + assert saved.cc1 == ((240, 120),) + native_evidence.append({ + "extension": extension, "notes": len(saved.notes), "cc1": saved.cc1, + "size_bytes": path.stat().st_size, "path": str(path), + }) + from riff_groove_builder.formats.sdp import write_sdp, validate_sdp_file + template = output / "original-template.sd3p" + lines = [ + "PlugVersion 3.4.4", "SAMPLER {", "HQ {", 'soundlib "SL-DFH"', "}", + ] + for index, (pad, pitch) in enumerate((("kickR", 36), ("snareR", 38), ("hatsTP", 42))): + lines.extend([ + f"instbox {index} {{", "xpad 0 SL-DFH {", "pads {", f"pad {pad} {{", + "}", f"alias {pad} {pitch}", "}", "}", "}", + ]) + lines.extend([ + "}", "ClearTracksFirst", "SongTrack 0 {", "ClearTrackFirst", "ClearSongParts", + "TrackLength 4", "Tempo 120 0 0", "TimeSig 4 4 0", "}", + "SetCurrentSongTrack 0", "MidiInChannel -1", + ]) + template.write_bytes(("\\n".join(lines) + "\\n").encode()) + profile = load_profile_registry().select( + ["drums"], ProfileSelection(drums="toontrack.sd3.3.4.4.core.v1") + )["drums"] + score = Score.model_validate({ + "intent": { + "description": "Original installed-wheel SD3 verification", + "parts": ["drums"], "tempo_bpm": 137.5, "bars": 1, + "time_signature": {"numerator": 4, "denominator": 4}, + "key": "E minor", "seed": 19, + }, + "start": {"numerator": 0}, "end": {"numerator": 4}, + "tracks": [{"part": "drums", "notes": [{ + "kind": "drum", "part": "drums", "voice": "snare", + "start": {"numerator": 0}, "duration": {"numerator": 1, "denominator": 8}, + "intensity": 1.0, "articulation": "normal", + }]}], + }) + plan = compile_score(score, {"drums": profile}) + path = output / "original.sd3p" + write_sdp(path, plan, "drums", profile, template=template) + saved = validate_sdp_file(path, plan, "drums", profile, template=template) + assert len(saved.notes) == 1 + assert (saved.notes[0].channel, saved.notes[0].pitch, saved.notes[0].velocity) == (9, 38, 127) + native_evidence.append({ + "extension": "sd3p", "notes": 1, + "size_bytes": path.stat().st_size, "path": str(path), + }) + print(json.dumps({ + "locations": locations, "resources": resource_names, "target": str(target), + "resource_evidence": resource_evidence, + "module_sha256": { + name: hashlib.sha256(Path(path).read_bytes()).hexdigest() + for name, path in locations.items() + }, + "cwd": str(Path.cwd()), "isolated": sys.flags.isolated, + "dependency_mcp": importlib.import_module("mcp").__file__, + "version": distribution.version, + "native_readback": native_evidence, + })) +else: + sys.argv = ["riff_groove_builder", "--output-dir", sys.argv[2], *sys.argv[3:]] + runpy.run_module("riff_groove_builder", run_name="__main__") +""" + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +async def _call( + client: RawStdio, name: ToolName, arguments: dict[str, object] +) -> dict[str, object]: + Draft202012Validator(tool_input_schema(name)).validate(arguments) + response = await client.request(name, "tools/call", {"name": name, "arguments": arguments}) + result = response["result"] + Draft202012Validator(tool_output_schema(name)).validate(result["structuredContent"]) + assert len(result["content"]) == 1 + assert result["content"][0]["type"] == "text" + assert json.loads(result["content"][0]["text"]) == result["structuredContent"] + assert isinstance(result, dict) + return result + + +def _read_published_midi( + result: GenerationResult, outputs: Path, basename: str +) -> dict[str, object]: + assert result.resolved.parts == ["lead", "bass", "drums"] + assert result.resolved.tempo_bpm == 137.5 and result.resolved.bars == 2 + assert result.resolved.time_signature.model_dump() == {"numerator": 7, "denominator": 8} + assert result.resolved.key == "A# minor" and result.resolved.seed == 42 + assert result.resolved.profile_ids.selected() == { + "lead": "standard.lead.v1", + "bass": "standard.bass.v1", + "drums": "standard.gm-drums.v1", + } + assert result.resolved.musical_start_tick == 0 + assert result.resolved.musical_end_tick == 6720 and result.resolved.ticks_per_quarter == 960 + assert result.resolved.assumptions == [ + "template: omitted; using rock.", + "technique: omitted; using normal.", + ] + assert result.resolved.overrides == [] + assert len(result.artifacts) == 1 + artifact = result.artifacts[0] + path = Path(artifact.path) + assert artifact.format == "mid" and artifact.parts == result.resolved.parts + assert artifact.profile_ids == ["standard.lead.v1", "standard.bass.v1", "standard.gm-drums.v1"] + assert path.is_absolute() and path == outputs / basename / f"{basename}.mid" + assert list(path.parent.iterdir()) == [path] + data = path.read_bytes() + assert data.startswith(b"MThd") and len(data) == artifact.size_bytes == path.stat().st_size + midi = mido.MidiFile(path) + assert midi.type == 1 and midi.ticks_per_beat == 960 + assert [track.name for track in midi.tracks] == ["Conductor", "Lead", "Bass", "Drums"] + conductor = midi.tracks[0] + assert [message.type for message in conductor] == [ + "track_name", + "set_tempo", + "time_signature", + "end_of_track", + ] + assert conductor[1].tempo == 436364 and conductor[1].time == 0 + assert (conductor[2].numerator, conductor[2].denominator, conductor[2].time) == (7, 8, 0) + counts = [] + for index, track in enumerate(midi.tracks): + tick = 0 + active: dict[tuple[int, int], int] = {} + onsets = [] + for message in track: + assert isinstance(message.time, int) and message.time >= 0 + tick += message.time + if message.is_meta: + assert message.type in ( + ("track_name", "set_tempo", "time_signature", "end_of_track") + if index == 0 + else ("track_name", "end_of_track") + ) + continue + assert index > 0 and message.type in ("note_on", "note_off") + assert message.channel == (0, 1, 9)[index - 1] + assert 0 <= message.note <= 127 and 0 <= message.velocity <= 127 + key = message.channel, message.note + if message.type == "note_on": + assert message.velocity > 0 and key not in active and tick < 6720 + active[key] = tick + onsets.append(tick) + if index == 3: + assert message.note in (36, 38, 42) + else: + assert key in active and tick - active.pop(key) == (240 if index == 3 else 960) + assert not active and tick == 6720 + assert track[-1].type == "end_of_track" + assert sum(message.type == "end_of_track" for message in track) == 1 + assert onsets == ( + [] + if index == 0 + else [ + tick + for tick in (0, 960, 1920, 3360, 4320, 5280) + for _ in range(2 if index == 3 else 1) + ] + ) + counts.append(len(onsets)) + return { + "path": str(path), + "size": len(data), + "sha256": hashlib.sha256(data).hexdigest(), + "note_counts": counts, + } + + +@pytest.mark.anyio +async def test_built_wheel_real_stdio_generation_outside_checkout( + distribution_workspace: tuple[Path, dict[str, str]], +) -> None: + workspace, env = distribution_workspace + wheel = next(_distribution_directory(workspace).glob("*.whl")) + wheel_sha256 = hashlib.sha256(wheel.read_bytes()).hexdigest() + target = workspace / "installed-server" + outputs = workspace / "server-outputs" + outputs.mkdir() + outside = ROOT.parent + assert not outside.is_relative_to(ROOT) + _run( + [ + sys.executable, + "-I", + "-B", + "-m", + "pip", + "install", + "--no-index", + "--no-deps", + "--no-cache-dir", + "--target", + str(target), + str(wheel), + ], + cwd=outside, + env=env, + ) + with zipfile.ZipFile(wheel) as archive: + resources = [name for name in archive.namelist() if name.endswith(".json")] + assert len(resources) == 6 + assert all(name.startswith("riff_groove_builder/data/profiles/") for name in resources) + for name in resources: + assert target.joinpath(*name.split("/")).read_bytes() == archive.read(name) + command = [sys.executable, "-I", "-B", "-c", _WHEEL_BOOTSTRAP, str(target)] + evidence = json.loads(_run([*command, "probe"], cwd=outside, env=env)) + assert Path(evidence["cwd"]) == outside and evidence["isolated"] == 1 + assert Path(evidence["dependency_mcp"]).is_relative_to(Path(sys.prefix)) + assert len(evidence["locations"]) == 18 + assert [item["extension"] for item in evidence["native_readback"]] == ["griff", "briff", "sd3p"] + assert all( + item["notes"] == 1 + and item["size_bytes"] > 0 + and Path(item["path"]).is_relative_to(workspace) + for item in evidence["native_readback"] + ) + assert all(Path(path).is_relative_to(target) for path in evidence["locations"].values()) + assert all( + not Path(path).is_relative_to(ROOT / "src") for path in evidence["locations"].values() + ) + for name, path in evidence["locations"].items(): + source = ROOT / "src" / Path(path).relative_to(target) + assert hashlib.sha256(source.read_bytes()).hexdigest() == evidence["module_sha256"][name] + for name, resource in evidence["resource_evidence"].items(): + source = ROOT / "src" / "riff_groove_builder" / "data" / "profiles" / name + assert hashlib.sha256(source.read_bytes()).hexdigest() == resource["sha256"] + disk_evidence = [] + for initialized in (True, False): + process = await asyncio.wait_for( + asyncio.create_subprocess_exec( + *command, + str(outputs), + cwd=outside, + env=env, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ), + TIMEOUT, + ) + client = RawStdio(process) + try: + if not initialized: + await client.close() + assert process.returncode == 0 + assert client.lines == [] and client.diagnostics == b"" + evidence["uninitialized_eof_exit_code"] = process.returncode + continue + with anyio.fail_after(60): + handshake = await client.initialize() + assert handshake["result"]["protocolVersion"] in SUPPORTED_PROTOCOL_VERSIONS + assert handshake["result"]["serverInfo"]["name"] == "riff-groove-builder" + tools = (await client.request(1, "tools/list"))["result"]["tools"] + names: tuple[ToolName, ...] = ("list_instrument_profiles", "generate_music") + assert [tool["name"] for tool in tools] == list(names) + for name, tool in zip(names, tools, strict=True): + assert tool["inputSchema"] == tool_input_schema(name) + assert tool["outputSchema"] == tool_output_schema(name) + + listed = await _call(client, "list_instrument_profiles", {}) + assert listed["isError"] is False + profiles = ProfileListResult.model_validate(listed["structuredContent"]).profiles + assert [profile.id for profile in profiles] == [ + "ample.ame.4.0.1.riffer.v1", + "ample.amr.4.1.0.riffer.v1", + "standard.bass.v1", + "standard.gm-drums.v1", + "standard.lead.v1", + "toontrack.sd3.3.4.4.core.v1", + ] + assert all( + profile.mapping_kind == "standard_midi" + and profile.midi_available + and not profile.native_available + and profile.supported_articulations == ["normal"] + and profile.limitations + for profile in profiles + if profile.id.startswith("standard.") + ) + assert [p.native_available for p in profiles] == [ + True, + True, + False, + False, + False, + False, + ] + evidence["text_only_recovery"] = await exercise_text_feedback( + client, outputs, label="installed-wheel" + ) + evidence["handshake"] = handshake["result"] + evidence["tool_names"] = [tool["name"] for tool in tools] + arguments: dict[str, object] = { + "description": "lead bass drums 137.5 BPM 2 bars 7/8 Bb minor quarter rests", + "seed": 42, + "profiles": { + "lead": "standard.lead.v1", + "bass": "standard.bass.v1", + "drums": "standard.gm-drums.v1", + }, + } + for basename, formats in ( + ("explicit", ["mid"]), + ("default", None), + ("native", ["agp", "sdp"]), + ): + extra = {} if formats is None else {"formats": formats} + response = await _call( + client, "generate_music", {**arguments, "basename": basename, **extra} + ) + assert response["isError"] is False + result = GenerationResult.model_validate(response["structuredContent"]) + fallback = [] if basename == "explicit" else ["lead", "bass", "drums"] + assert result.status == ("midi_fallback" if fallback else "complete") + assert result.artifacts[0].fallback_for == fallback + assert [(warning.code, warning.part) for warning in result.warnings] == [ + ("STANDARD_MIDI_MAPPING", "lead"), + ("STANDARD_MIDI_MAPPING", "bass"), + ("STANDARD_MIDI_MAPPING", "drums"), + *(("NATIVE_FORMAT_UNAVAILABLE", part) for part in fallback), + ] + for warning in result.warnings[3:]: + assert ( + "sdp_profile_not_supported" + if warning.part == "drums" + else "riffer_profile_not_supported" + ) in warning.message + disk_evidence.append(_read_published_midi(result, outputs, basename)) + assert len({item["sha256"] for item in disk_evidence}) == 1 + target_request = job(basename="target-no-template") + response = await _call( + client, + "generate_music", + target_request.model_dump(mode="json", exclude_none=True), + ) + target_result = GenerationResult.model_validate(response["structuredContent"]) + assert response["isError"] is False and target_result.status == "midi_fallback" + assert [a.format for a in target_result.artifacts] == ["mid", "griff", "briff"] + assert target_result.artifacts[0].fallback_for == ["drums"] + assert [ + (w.part, w.message) + for w in target_result.warnings + if w.code == "NATIVE_FORMAT_UNAVAILABLE" + ] == [ + ( + "drums", + "sd3p: sdp_template_required; " + "the combined Standard MIDI substitutes for this native target.", + ) + ] + validate_saved(target_result, target_request, None) + before = sorted(outputs.iterdir()) + response = await _call( + client, + "generate_music", + job(basename="target-disabled", allow_midi_fallback=False).model_dump( + mode="json", exclude_none=True + ), + ) + assert response["isError"] is True + error = GenerationError.model_validate(response["structuredContent"]) + assert error.code == "NATIVE_FORMAT_UNAVAILABLE" + assert error.details == { + "format": "sd3p", + "part": "drums", + "reason": "sdp_template_required", + } + assert sorted(outputs.iterdir()) == before + failures: list[tuple[str, str, dict[str, object], str]] = [ + ( + "disabled", + "drums only", + {"allow_midi_fallback": False}, + "NATIVE_FORMAT_UNAVAILABLE", + ), + ( + "unsupported", + "lead only palm mute", + {"formats": ["mid"]}, + "UNSUPPORTED_ARTICULATION", + ), + ( + "disabled_lead", + "lead only", + {"allow_midi_fallback": False}, + "NATIVE_FORMAT_UNAVAILABLE", + ), + ("unicode", "drums only café", {"formats": ["mid"]}, "UNSUPPORTED_DESCRIPTION"), + ("explicit", "drums only", {"formats": ["mid"]}, "OUTPUT_EXISTS"), + ] + for basename, description, error_options, code in failures: + before = sorted(outputs.iterdir()) + response = await _call( + client, + "generate_music", + { + "description": description, + "basename": basename, + "profiles": ( + {"drums": "standard.gm-drums.v1"} + if description.startswith("drums") + else {"lead": "standard.lead.v1"} + ), + **error_options, + }, + ) + assert response["isError"] is True + error = GenerationError.model_validate(response["structuredContent"]) + assert error.code == code + assert sorted(outputs.iterdir()) == before + if basename == "disabled": + assert error.details == { + "format": "sd3p", + "part": "drums", + "reason": "sdp_profile_not_supported", + } + if basename == "disabled_lead": + assert error.details == { + "format": "griff", + "part": "lead", + "reason": "riffer_profile_not_supported", + } + assert "café" not in json.dumps(response, ensure_ascii=False) + assert not list(outputs.glob(".riff-stage-*")) + await client.send('{"private-description": "秘密 café", invalid JSON') + notification = await client.receive() + assert notification["method"] == "notifications/message" + assert notification["params"]["data"] == "Internal Server Error" + assert (await client.request("after-malformed", "ping"))["result"] == {} + await client.assert_quiet() + finally: + with anyio.CancelScope(shield=True): + await client.close() + assert process.returncode == 0 + if initialized: + assert len(client.lines) == 20 + assert b"SDK rejected malformed protocol input" in client.diagnostics + assert "秘密" not in client.diagnostics.decode("utf-8") + assert b"private-description" not in client.diagnostics + evidence["server_pid"] = process.pid + evidence["stdout_lines"] = len(client.lines) + evidence["exit_code"] = process.returncode + else: + assert client.lines == [] and client.diagnostics == b"" + original_template = target.parent / "controls-original-template.sd3p" + shutil.copyfile(TEMPLATE, original_template) + original_bytes = original_template.read_bytes() + original_info = original_template.stat() + process = await asyncio.wait_for( + asyncio.create_subprocess_exec( + *command, + str(outputs), + "--sd3-template", + str(original_template), + cwd=outside, + env=env, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ), + TIMEOUT, + ) + native_client = RawStdio(process) + native_evidence = [] + try: + await native_client.initialize() + listed = await _call(native_client, "list_instrument_profiles", {}) + summaries = ProfileListResult.model_validate(listed["structuredContent"]).profiles + assert all(p.native_available for p in summaries if p.mapping_kind == "instrument") + for basename, formats in ( + ("native-default", None), + ("native-alias", ["agp", "sdp"]), + ("native-actual", ["griff", "briff", "sd3p"]), + ("native-midi", ["mid"]), + ): + request = job(basename=basename, formats=formats, allow_midi_fallback=False) + response = await _call( + native_client, "generate_music", request.model_dump(mode="json", exclude_none=True) + ) + assert response["isError"] is False + result = GenerationResult.model_validate(response["structuredContent"]) + assert result.status == "complete" + assert [a.format for a in result.artifacts] == ( + ["mid", "griff", "briff", "sd3p"] + if formats is None + else ["mid"] + if formats == ["mid"] + else ["griff", "briff", "sd3p"] + ) + native_evidence.append(validate_saved(result, request, original_template)) + before_collision = { + str(path): path.read_bytes() for path in outputs.rglob("*") if path.is_file() + } + response = await _call( + native_client, + "generate_music", + job(basename="native-default").model_dump(mode="json", exclude_none=True), + ) + assert response["isError"] is True + assert GenerationError.model_validate(response["structuredContent"]).code == "OUTPUT_EXISTS" + assert { + str(path): path.read_bytes() for path in outputs.rglob("*") if path.is_file() + } == before_collision + assert not list(outputs.glob(".riff-stage-*")) + control_outputs = await exercise_control_stdio( + native_client, outputs, original_template, prefix="wheel-cc" + ) + await exercise_phrase_stdio(native_client, outputs, label="installed-wheel") + legacy_lines = len(native_client.lines) + finally: + with anyio.CancelScope(shield=True): + await native_client.close() + assert native_client.diagnostics == b"" and process.returncode == 0 + assert legacy_lines == len(native_client.lines) == 23 + process = await asyncio.wait_for( + asyncio.create_subprocess_exec( + *command, + str(outputs), + cwd=outside, + env=env, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ), + TIMEOUT, + ) + hybrid_client = RawStdio(process) + try: + handshake = await hybrid_client.initialize() + assert handshake["result"]["serverInfo"]["version"] == "0.2.0" + hybrid_outputs = await exercise_hybrid_stdio( + hybrid_client, outputs, label="installed-wheel" + ) + finally: + await hybrid_client.close() + assert process.returncode == 0 and hybrid_client.diagnostics == b"" + evidence["hybrid_transport"] = { + "handshake": handshake["result"], + "stdout_lines": len(hybrid_client.lines), + "exit_code": process.returncode, + "stderr": hybrid_client.diagnostics.decode("utf-8"), + "sd3_template": None, + } + assert original_template.read_bytes() == original_bytes + assert (original_template.stat().st_ino, original_template.stat().st_mtime_ns) == ( + original_info.st_ino, + original_info.st_mtime_ns, + ) + assert sorted(path.name for path in outputs.iterdir()) == sorted( + [ + "default", + "explicit", + "native", + "native-alias", + "native-actual", + "native-default", + "native-midi", + "target-no-template", + "text-recovered", + "phrase-original", + "phrase-nearby", + *control_outputs, + *hybrid_outputs, + ] + ) + assert not list(outputs.rglob("*.agp")) and not list(outputs.rglob("*.sdp")) + print(f"Installed-wheel server evidence: {json.dumps(evidence, sort_keys=True)}") + print(f"Installed-wheel disk evidence: {json.dumps(disk_evidence, sort_keys=True)}") + print(f"Installed-wheel native service evidence: {json.dumps(native_evidence, sort_keys=True)}") + assert hashlib.sha256(wheel.read_bytes()).hexdigest() == wheel_sha256 + evidence.update( + { + "wheel_path": str(wheel), + "wheel_sha256": wheel_sha256, + "native_stdout_lines": len(native_client.lines), + "native_exit_code": process.returncode, + "native_stderr": native_client.diagnostics.decode("utf-8"), + "disk": disk_evidence, + "native": native_evidence, + } + ) + EVIDENCE.mkdir(parents=True, exist_ok=True) + (EVIDENCE / "distribution-acceptance.json").write_text( + json.dumps(evidence, indent=2), encoding="utf-8" + ) diff --git a/tests/integration/test_explicit_music.py b/tests/integration/test_explicit_music.py new file mode 100644 index 0000000..1122543 --- /dev/null +++ b/tests/integration/test_explicit_music.py @@ -0,0 +1,251 @@ +"""Actual original MIDI/griff checks; internal resolver injection is NOT a public parser.""" + +import hashlib +import json +import shutil +import uuid +import xml.etree.ElementTree as ET +from collections.abc import Iterator +from fractions import Fraction +from pathlib import Path + +import mido # type: ignore[import-untyped] +import pytest + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.compose import CompositionError, compose_score +from riff_groove_builder.description import DescriptionResolution +from riff_groove_builder.errors import NativeFormatUnavailableError, OutputExistsError +from riff_groove_builder.formats.agp import validate_riffer_file +from riff_groove_builder.midi import validate_midi_file +from riff_groove_builder.pitch import parse_chord, parse_pitch, resolve_voicing +from riff_groove_builder.profiles import load_profile_registry +from riff_groove_builder.schemas import ( + ExplicitAttack, + ExplicitAttackPlan, + GenerateMusicRequest, + MusicalIntent, + PositiveBeat, + ProfileSelection, + TimeSignature, +) +from riff_groove_builder.service import GenerationService + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = pytest.mark.integration + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / "step14" / f"rejection-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +def explicit_intent( + pitches: list[list[int]], assumptions: list[str] | None = None +) -> MusicalIntent: + timings = [ + (Fraction(0), Fraction(2, 3), "normal", 0.5), + (Fraction(1), Fraction(1, 3), "palm_mute", 0.25), + (Fraction(4, 3), Fraction(2, 3), "normal", 0.75), + (Fraction(2), Fraction(2), "pinch_harmonic", 1.0), + ] + attacks = [ + ExplicitAttack.model_validate( + { + "pitches": notes, + "start": {"numerator": start.numerator, "denominator": start.denominator}, + "duration": {"numerator": length.numerator, "denominator": length.denominator}, + "technique": technique, + "intensity": intensity, + } + ) + for notes, (start, length, technique, intensity) in zip(pitches, timings, strict=False) + ] + return MusicalIntent( + description="Original internal explicit chord plan.", + parts=["lead"], + tempo_bpm=120, + bars=1, + time_signature=TimeSignature(numerator=4, denominator=4), + key="D minor", + seed=0, + explicit_plan=ExplicitAttackPlan( + part="lead", + duration=PositiveBeat(numerator=4), + attacks=attacks, + assumptions=assumptions or [], + ), + ) + + +def inject_intent(monkeypatch: pytest.MonkeyPatch, intent: MusicalIntent) -> None: + assert intent.explicit_plan is not None + resolution = DescriptionResolution( + intent=intent, assumptions=intent.explicit_plan.assumptions, overrides=[] + ) + monkeypatch.setattr("riff_groove_builder.service.resolve_description", lambda _: resolution) + + +def midi_notes(path: Path) -> list[tuple[int, int, int, int]]: + midi = mido.MidiFile(path) + assert (midi.type, midi.ticks_per_beat) == (1, 960) + assert [t.name for t in midi.tracks] == ["Conductor", "Lead"] + assert [sum(m.time for m in t) for t in midi.tracks] == [3840, 3840] + assert not any(m.type in ("control_change", "program_change") for t in midi.tracks for m in t) + active: dict[int, tuple[int, int]] = {} + notes = [] + tick = 0 + for message in midi.tracks[1]: + tick += message.time + if message.type == "note_on" and message.velocity: + assert message.channel == 0 and message.note not in active + active[message.note] = (tick, message.velocity) + elif message.type == "note_off": + begin, velocity = active.pop(message.note) + notes.append((begin, tick, message.note, velocity)) + assert not active + return sorted(notes) + + +@pytest.mark.parametrize("symbol", ["Em4/B2", "Em4OverB2", "Em4/B", "Em4OverB"]) +def test_saved_chords_have_actual_independent_tones_times_and_strings( + monkeypatch: pytest.MonkeyPatch, symbol: str +) -> None: + profiles = load_profile_registry().select(["lead"], ProfileSelection()) + profile = profiles["lead"] + slash = resolve_voicing(parse_chord(symbol), profile) + voicings = [ + slash.pitches, + resolve_voicing(parse_chord("[C3 E3 G3]"), profile).pitches, + resolve_voicing(parse_chord("F#4"), profile).pitches, + resolve_voicing(parse_pitch("C4"), profile).pitches, + ] + intent = explicit_intent([list(v) for v in voicings], list(slash.assumptions)) + inject_intent(monkeypatch, intent) + output = ROOT / ".test-artifacts" / "step14" / f"explicit-{uuid.uuid4().hex}" + output.mkdir(parents=True) + service = GenerationService(output) + request = GenerateMusicRequest( + description=intent.description, basename="chords", allow_midi_fallback=False + ) + result = service.generate_music(request) + assert result.status == "complete" + assert [a.format for a in result.artifacts] == ["mid", "griff"] + assert all(a.fallback_for == [] for a in result.artifacts) + assert result.resolved.key == "D minor" + if "2" not in symbol: + assert "MIDI59" in "\n".join(result.resolved.assumptions) + + bass = 47 if "2" in symbol else 59 + expected = sorted( + [(0, 640, pitch, 95) for pitch in (bass, 64, 67, 71)] + + [(960, 1280, pitch, 32) for pitch in (48, 52, 55)] + + [(1280, 1920, pitch, 110) for pitch in (66, 70, 73)] + + [(1920, 3840, 60, 127)] + ) + midi_path = Path(result.artifacts[0].path) + native_path = Path(result.artifacts[1].path) + saved = midi_notes(midi_path) + switches = [(0, 30, 24, 100), (960, 990, 26, 100), (1280, 1310, 24, 100), (1920, 1950, 31, 100)] + assert saved == sorted(expected + switches) + assert len(expected) == 11 and len(saved) == 15 + native = ET.parse(native_path).getroot() + assert native.tag == "Riff" + assert (native.get("Key"), native.get("PPQBase"), native.get("loopEnd")) == ( + "Dm", + "480", + "1920", + ) + tuning = {6: 36, 5: 43, 4: 48, 3: 53, 2: 57, 1: 62} + readback: list[tuple[int, int, int, int]] = [] + assignments = [] + for string in native.findall("String"): + string_id = int(string.attrib["ID"]) + occupied_until = 0 + for note in string.findall("Note"): + begin, end = int(note.attrib["Begin"]), int(note.attrib["End"]) + pitch, fret = int(note.attrib["NoteID"]), int(note.attrib["Fret"]) + assert pitch == tuning[string_id] + fret and 0 <= fret <= 22 + assert begin >= occupied_until and end > begin + occupied_until = end + assert note.get("Articulation") == {0: "Sus", 480: "PM", 640: "Sus", 960: "PH"}[begin] + assert note.get("Legato") == "No Legato" and note.get("Muted") == "False" + readback.append((begin * 2, end * 2, pitch, int(note.attrib["Velocity"]))) + assignments.append((begin, end, pitch, string_id, fret)) + assert sorted(readback) == expected + assert len({row[3] for row in assignments if row[0] == 0}) == 4 + assert not native.findall("cc-1.Mod") + plan = compile_score(compose_score(intent, profiles), profiles) + assert sum(len(t.events) for t in plan.tracks) == 30 + validate_midi_file(midi_path, plan) + assert len(validate_riffer_file(native_path, plan, "lead", profile).notes) == 11 + before = {p: p.read_bytes() for p in (midi_path, native_path)} + with pytest.raises(OutputExistsError): + service.generate_music(request) + assert all(p.read_bytes() == data for p, data in before.items()) + (output / "evidence.json").write_text( + json.dumps( + { + "symbol": symbol, + "key": "D minor", + "musical_notes": expected, + "keyswitches": switches, + "scheduled_events": 30, + "native_assignments_begin_end_pitch_string_fret": sorted(assignments), + "files": [ + {"name": p.name, "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()} + for p, data in before.items() + ], + }, + indent=2, + ), + encoding="utf-8", + ) + + +@pytest.mark.parametrize("fallback", [True, False]) +def test_unassignable_chord_uses_only_existing_truthful_native_fallback( + monkeypatch: pytest.MonkeyPatch, workspace: Path, fallback: bool +) -> None: + intent = explicit_intent([[36, 37, 38]]) + inject_intent(monkeypatch, intent) + request = GenerateMusicRequest( + description=intent.description, basename="impossible", allow_midi_fallback=fallback + ) + service = GenerationService(workspace) + if fallback: + result = service.generate_music(request) + assert result.status == "midi_fallback" + assert len(result.artifacts) == 1 and result.artifacts[0].format == "mid" + assert result.artifacts[0].fallback_for == ["lead"] + assert any(w.code == "NATIVE_FORMAT_UNAVAILABLE" for w in result.warnings) + saved = midi_notes(Path(result.artifacts[0].path)) + assert saved == [(0, 30, 24, 100)] + [(0, 640, p, 95) for p in (36, 37, 38)] + else: + with pytest.raises(NativeFormatUnavailableError) as caught: + service.generate_music(request) + assert caught.value.details["reason"] == "no_physical_string_assignment" + assert list(workspace.iterdir()) == [] + + +@pytest.mark.parametrize("fallback", [True, False]) +def test_out_of_map_tones_fail_before_publication_not_fallback( + monkeypatch: pytest.MonkeyPatch, workspace: Path, fallback: bool +) -> None: + intent = explicit_intent([[35, 60, 64]]) + inject_intent(monkeypatch, intent) + sentinel = workspace / "accepted.txt" + sentinel.write_bytes(b"accepted") + with pytest.raises(CompositionError): + GenerationService(workspace).generate_music( + GenerateMusicRequest( + description=intent.description, basename="out-of-map", allow_midi_fallback=fallback + ) + ) + assert sentinel.read_bytes() == b"accepted" + assert list(workspace.iterdir()) == [sentinel] diff --git a/tests/integration/test_generation_service.py b/tests/integration/test_generation_service.py new file mode 100644 index 0000000..2bf2f26 --- /dev/null +++ b/tests/integration/test_generation_service.py @@ -0,0 +1,421 @@ +"""Real description-to-disk publication, failure injection, competition and junctions.""" + +import os +import shutil +import subprocess +import uuid +from collections.abc import Callable, Iterator +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from threading import Barrier +from unittest.mock import patch + +import mido # type: ignore[import-untyped] +import pytest +from jsonschema import Draft202012Validator +from pydantic import ValidationError + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.errors import ( + DomainError, + NativeFormatUnavailableError, + OutputExistsError, + OutputIOError, + SerializationError, +) +from riff_groove_builder.midi import validate_midi_file, write_midi +from riff_groove_builder.profiles import load_profile_registry +from riff_groove_builder.schemas import ( + EventPlan, + GenerateMusicRequest, + GenerationResult, + Part, + ProfileSelection, + tool_output_schema, +) +from riff_groove_builder.service import GenerationService, _Stage + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = pytest.mark.integration + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"generation-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +def request(**updates: object) -> GenerateMusicRequest: + job = GenerateMusicRequest.model_validate( + { + "description": "lead bass drums 137.5 BPM 2 bars 7/8 Bb minor quarter rests", + "basename": "song", + "seed": 42, + **updates, + } + ) + if job.profiles is None: + job.profiles = ProfileSelection( + **{ + part: "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" + for part in resolve_description(job).intent.parts + } + ) + return job + + +@pytest.mark.parametrize( + "parts", [["lead"], ["bass"], ["drums"], ["lead", "bass", "drums"], ["drums", "bass"]] +) +def test_actual_saved_midi_and_resolved_schema(workspace: Path, parts: list[Part]) -> None: + job = request(parts=parts) + result = GenerationService(workspace).generate_music(job) + Draft202012Validator(tool_output_schema("generate_music")).validate( + result.model_dump(mode="json") + ) + assert GenerationResult.model_validate_json(result.model_dump_json()) == result + resolved = result.resolved + assert resolved.parts == parts + assert resolved.tempo_bpm == 137.5 + assert resolved.bars == 2 + assert resolved.time_signature.model_dump() == {"numerator": 7, "denominator": 8} + assert resolved.key == "A# minor" + assert resolved.seed == 42 + assert resolved.overrides and resolved.assumptions + assert resolved.musical_start_tick == 0 and resolved.musical_end_tick == 6720 + artifact = result.artifacts[0] + assert artifact.parts == artifact.fallback_for == parts + path = Path(artifact.path) + assert path.is_absolute() and path == workspace / "song" / "song.mid" + assert artifact.size_bytes == path.stat().st_size == len(path.read_bytes()) + assert path.read_bytes()[:4] == b"MThd" + midi = mido.MidiFile(path) + assert midi.type == 1 and midi.ticks_per_beat == 960 + assert [track.name for track in midi.tracks] == [ + "Conductor", + *(part.capitalize() for part in parts), + ] + assert [sum(message.time for message in track) for track in midi.tracks] == [6720] * ( + len(parts) + 1 + ) + conductor = midi.tracks[0] + assert next(msg.tempo for msg in conductor if msg.type == "set_tempo") == round( + 60_000_000 / 137.5 + ) + meter = next(msg for msg in conductor if msg.type == "time_signature") + assert (meter.numerator, meter.denominator) == (7, 8) + for part, track in zip(parts, midi.tracks[1:], strict=True): + channel = {"lead": 0, "bass": 1, "drums": 9}[part] + notes = [message for message in track if message.type == "note_on"] + assert notes and all( + note.channel == channel and 1 <= note.velocity <= 127 for note in notes + ) + assert all(message.is_meta or message.type in ("note_on", "note_off") for message in track) + if part == "drums": + assert {note.note for note in notes} == {36, 38, 42} + resolution = resolve_description(job) + assert job.profiles is not None + selected = load_profile_registry().select(parts, job.profiles) + validate_midi_file(path, compile_score(compose_score(resolution.intent, selected), selected)) + assert list(workspace.iterdir()) == [path.parent] + assert list(path.parent.iterdir()) == [path] + assert "description" not in result.model_dump_json() + + +def test_midi_only_is_complete_and_native_only_substitutes_all_parts(workspace: Path) -> None: + service = GenerationService(workspace) + direct = service.generate_music(request(basename="direct", formats=["mid"])) + native = service.generate_music(request(basename="native", formats=["agp", "sdp"])) + assert direct.status == "complete" and direct.artifacts[0].fallback_for == [] + assert native.status == "midi_fallback" + assert native.artifacts[0].fallback_for == ["lead", "bass", "drums"] + assert len(direct.warnings) == 3 and len(native.warnings) == 6 + assert ( + Path(direct.artifacts[0].path).read_bytes() == Path(native.artifacts[0].path).read_bytes() + ) + assert not list(workspace.rglob("*.agp")) and not list(workspace.rglob("*.sdp")) + with pytest.raises(NativeFormatUnavailableError): + service.generate_music(request(basename="disabled", allow_midi_fallback=False)) + assert not (workspace / "disabled").exists() + assert not list(workspace.glob(".riff-stage-*")) + + +@pytest.mark.parametrize( + ("operation", "failure", "code"), + [ + ( + "write_midi", + SerializationError(details={"reason": "serializer_failed"}), + "SERIALIZATION_ERROR", + ), + ("write_midi", OutputIOError(details={"reason": "midi_write_failed"}), "OUTPUT_IO_ERROR"), + ( + "validate_midi_file", + SerializationError(details={"reason": "smf_content_mismatch"}), + "SERIALIZATION_ERROR", + ), + ( + "validate_midi_file", + OutputIOError(details={"reason": "midi_read_failed"}), + "OUTPUT_IO_ERROR", + ), + ("validate_midi_file", PermissionError("private-path"), "OUTPUT_IO_ERROR"), + ], +) +def test_write_read_failures_leave_no_partial_final_or_stage( + workspace: Path, operation: str, failure: Exception, code: str +) -> None: + sentinel = workspace / "sentinel" + sentinel.write_bytes(b"unrelated operator data") + before = sentinel.stat() + with patch(f"riff_groove_builder.service.{operation}", side_effect=failure): + with pytest.raises(DomainError) as captured: + GenerationService(workspace).generate_music(request()) + assert captured.value.code == code + assert list(workspace.iterdir()) == [sentinel] + assert sentinel.read_bytes() == b"unrelated operator data" + assert (sentinel.stat().st_ino, sentinel.stat().st_mtime_ns) == ( + before.st_ino, + before.st_mtime_ns, + ) + + +def test_partial_write_is_cleaned_and_not_reported_as_fallback(workspace: Path) -> None: + def failed_write( + path: Path, _plan: EventPlan, *, on_created: Callable[[os.stat_result], None] + ) -> Path: + with path.open("xb") as stream: + on_created(os.fstat(stream.fileno())) + stream.write(b"partial bytes") + raise OutputIOError(details={"reason": "midi_write_failed"}) + + with ( + patch("riff_groove_builder.service.write_midi", side_effect=failed_write), + pytest.raises(OutputIOError) as captured, + ): + GenerationService(workspace).generate_music(request()) + assert captured.value.details["reason"] == "midi_write_failed" + assert not list(workspace.iterdir()) + + +def test_actual_corruption_fails_readback_and_cleans(workspace: Path) -> None: + def corrupt( + path: Path, plan: EventPlan, *, on_created: Callable[[os.stat_result], None] + ) -> Path: + write_midi(path, plan, on_created=on_created) + path.write_bytes(b"not MIDI") + return path + + with ( + patch("riff_groove_builder.service.write_midi", side_effect=corrupt), + pytest.raises(SerializationError), + ): + GenerationService(workspace).generate_music(request()) + assert not list(workspace.iterdir()) + + +def test_result_model_failure_precedes_publication(workspace: Path) -> None: + with pytest.raises(ValidationError) as captured: + GenerationResult.model_validate({}) + with ( + patch( + "riff_groove_builder.service.GenerationResult.model_validate", + side_effect=captured.value, + ), + pytest.raises(SerializationError) as error, + ): + GenerationService(workspace).generate_music(request()) + assert error.value.details["reason"] == "invalid_generation_result" + assert not list(workspace.iterdir()) + + +def test_unexpected_bug_propagates_but_owned_stage_is_cleaned(workspace: Path) -> None: + with ( + patch("riff_groove_builder.service.validate_midi_file", side_effect=RuntimeError("bug")), + pytest.raises(RuntimeError, match="bug"), + ): + GenerationService(workspace).generate_music(request()) + assert not list(workspace.iterdir()) + + +def test_file_change_during_readback_is_not_published(workspace: Path) -> None: + def change(path: Path, plan: EventPlan) -> None: + validate_midi_file(path, plan) + with path.open("ab") as handle: + handle.write(b"changed after readback") + + with ( + patch("riff_groove_builder.service.validate_midi_file", side_effect=change), + pytest.raises(OutputIOError) as captured, + ): + GenerationService(workspace).generate_music(request()) + assert captured.value.details == {"reason": "staged_content_changed"} + assert not list(workspace.iterdir()) + + +def test_root_change_mid_generation_refuses_unsafe_cleanup(workspace: Path) -> None: + root = workspace / "outputs" + root.mkdir() + service = GenerationService(root) + moved = workspace / "original-root" + + def change_root( + path: Path, plan: EventPlan, *, on_created: Callable[[os.stat_result], None] + ) -> Path: + write_midi(path, plan, on_created=on_created) + root.rename(moved) + root.mkdir() + (root / "sentinel").write_bytes(b"replacement data") + return path + + with ( + patch("riff_groove_builder.service.write_midi", side_effect=change_root), + pytest.raises(OutputIOError) as captured, + ): + service.generate_music(request()) + assert captured.value.details == { + "reason": "stage_cleanup_failed", + "original_code": "OUTPUT_IO_ERROR", + } + assert list(root.iterdir()) == [root / "sentinel"] + assert (root / "sentinel").read_bytes() == b"replacement data" + assert len(list(moved.glob(".riff-stage-*"))) == 1 + assert not (root / "song").exists() and not (moved / "song").exists() + + +def test_publication_failure_is_io_and_cleans_complete_stage(workspace: Path) -> None: + with patch.object(Path, "rename", side_effect=PermissionError("private-path")): + with pytest.raises(OutputIOError) as captured: + GenerationService(workspace).generate_music(request()) + assert captured.value.details == {"reason": "publication_failed"} + assert not list(workspace.iterdir()) + + +def test_cleanup_failure_is_explicit_and_does_not_delete_other_files(workspace: Path) -> None: + sentinel = workspace / "sentinel" + sentinel.write_bytes(b"preserved") + with ( + patch.object(Path, "rename", side_effect=PermissionError("private-path")), + patch.object(Path, "unlink", side_effect=PermissionError("private-cleanup")), + pytest.raises(OutputIOError) as captured, + ): + GenerationService(workspace).generate_music(request()) + assert captured.value.details == { + "reason": "stage_cleanup_failed", + "original_code": "OUTPUT_IO_ERROR", + } + assert not (workspace / "song").exists() + stages = list(workspace.glob(".riff-stage-*")) + assert len(stages) == 1 and (stages[0] / "song.mid").read_bytes().startswith(b"MThd") + assert sentinel.read_bytes() == b"preserved" + shutil.rmtree(stages[0]) + + +def test_concurrent_same_name_has_exactly_one_winner(workspace: Path) -> None: + barrier = Barrier(2) + publish = GenerationService._publish + + def synchronized(self: GenerationService, stage: _Stage, destination: Path) -> None: + barrier.wait(timeout=15) + publish(self, stage, destination) + + def run(service: GenerationService) -> GenerationResult | DomainError: + try: + return service.generate_music(request()) + except DomainError as error: + return error + + services = [GenerationService(workspace), GenerationService(workspace)] + with patch.object(GenerationService, "_publish", synchronized), ThreadPoolExecutor(2) as pool: + results = list(pool.map(run, services)) + assert len([result for result in results if isinstance(result, GenerationResult)]) == 1 + losers = [result for result in results if isinstance(result, DomainError)] + assert len(losers) == 1 and isinstance(losers[0], OutputExistsError) + assert list(workspace.iterdir()) == [workspace / "song"] + assert list((workspace / "song").iterdir()) == [workspace / "song" / "song.mid"] + assert mido.MidiFile(workspace / "song" / "song.mid").type == 1 + + +def junction(link: Path, target: Path) -> None: + result = subprocess.run( + [os.environ["COMSPEC"], "/d", "/c", "mklink", "/J", str(link), str(target)], + capture_output=True, + timeout=15, + check=False, + ) + if result.returncode: + pytest.skip("Windows junction creation unavailable in this environment") + assert link.lstat().st_file_attributes & 0x400 + + +@pytest.mark.skipif(os.name != "nt", reason="Real Windows junction/reparse checks") +@pytest.mark.parametrize("location", ["root", "ancestor", "pinned-root", "destination", "stage"]) +def test_real_windows_junctions_cannot_redirect_generation(workspace: Path, location: str) -> None: + outside = workspace / "outside" + outside.mkdir() + sentinel = outside / "song.mid" + sentinel.write_bytes(b"outside sentinel") + root = workspace / "outputs" + link = workspace / "link" + if location in ("root", "ancestor"): + (outside / "nested").mkdir() + junction(link, outside) + try: + with pytest.raises(ValueError, match="existing local directory"): + GenerationService(link if location == "root" else link / "nested") + finally: + link.rmdir() + else: + root.mkdir() + service = GenerationService(root) + if location == "pinned-root": + root.rename(workspace / "original-root") + junction(root, outside) + try: + with pytest.raises(OutputIOError) as captured: + service.generate_music(request()) + assert captured.value.details["reason"] == "output_root_changed" + finally: + root.rmdir() + elif location == "destination": + link = root / "song" + junction(link, outside) + try: + with pytest.raises(OutputExistsError): + service.generate_music(request()) + finally: + link.rmdir() + else: + links: list[Path] = [] + + def redirect( + path: Path, plan: EventPlan, *, on_created: Callable[[os.stat_result], None] + ) -> Path: + write_midi(path, plan, on_created=on_created) + path.parent.rename(root / "moved-stage") + junction(path.parent, outside) + links.append(path.parent) + return path + + try: + with ( + patch("riff_groove_builder.service.write_midi", side_effect=redirect), + pytest.raises(OutputIOError) as error, + ): + service.generate_music(request()) + assert error.value.details == { + "reason": "stage_cleanup_failed", + "original_code": "OUTPUT_IO_ERROR", + } + assert not (root / "song").exists() + finally: + for item in links: + item.rmdir() + assert sentinel.read_bytes() == b"outside sentinel" + assert not list(outside.glob("*.agp")) and not list(outside.glob("*.sdp")) diff --git a/tests/integration/test_hybrid_stdio.py b/tests/integration/test_hybrid_stdio.py new file mode 100644 index 0000000..edf7a0d --- /dev/null +++ b/tests/integration/test_hybrid_stdio.py @@ -0,0 +1,352 @@ +"""Independent numeric MIDI/native checks over real source and installed MCP stdio.""" + +import asyncio +import hashlib +import json +import shutil +import sys +import uuid +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import Any + +import mido # type: ignore[import-untyped] +import pytest +from jsonschema import Draft202012Validator +from test_stdio import TIMEOUT, RawStdio, _environment + +from riff_groove_builder.schemas import tool_input_schema, tool_output_schema + +ROOT = Path(__file__).resolve().parents[2] +CANONICAL = """Lead guitar, 4/4, 120 BPM, 2 bars. +Bar 1: +Counts: 1 & 2 & 3 & [4 trip let] +Events: x x x x x x [x x ^] +Chords: F#2 F#2 D3 D3 Bb2 Bb2 - - - +Notes: - - - - - - C4 E4 G4 +Hold the final G4 through the end of bar 2 without retriggering.""" +E2 = """Lead guitar in E minor, 4/4, 120 BPM, 2 bars. +Bar 1: +Counts: 1 & 2 & 3 & [4 trip let] +Events: x x x x x x [x x ^] +Notes: E2 E2 E2 E2 E2 E2 E2 E2 E2 +Hold the final E2 through the end of bar 2 without retriggering.""" +STARTS = [0, 480, 960, 1440, 1920, 2400, 2880, 3200, 3520] +ENDS = [480, 960, 1440, 1920, 2400, 2880, 3200, 3520, 7680] +VELOCITIES = [80, 80, 64, 80, 96, 80, 80, 80, 80] + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +def inspect( + public: dict[str, Any], + pitches: list[list[int]], + starts: list[int], + ends: list[int], + techniques: list[str], + *, + native: bool = True, + velocities: list[int] | None = None, + held: list[bool] | None = None, +) -> dict[str, Any]: + assert public["status"] == ("complete" if native else "midi_fallback") + assert [a["format"] for a in public["artifacts"]] == (["mid", "griff"] if native else ["mid"]) + rows = public["resolved"]["interpretation"] + assert len(rows) == len(pitches) + for index, (row, notes, start, end, technique) in enumerate( + zip(rows, pitches, starts, ends, techniques, strict=True) + ): + assert row["pitches"] == notes and row["technique"] == technique and row["part"] == "lead" + assert row["start"]["numerator"] * 960 == start * row["start"]["denominator"] + assert row["duration"]["numerator"] * 960 == (end - start) * row["duration"]["denominator"] + assert row["held"] == (held[index] if held is not None else end - start > 960) + musical: list[tuple[int, int, int, int]] = [] + switches: list[tuple[int, int, int, int]] = [] + midi = mido.MidiFile(public["artifacts"][0]["path"]) + assert midi.type == 1 and midi.ticks_per_beat == 960 + total = public["resolved"]["musical_end_tick"] + assert [sum(m.time for m in track) for track in midi.tracks] == [total, total] + assert not any(m.type in ("control_change", "program_change") for t in midi.tracks for m in t) + active: dict[int, tuple[int, int]] = {} + tick = 0 + for message in midi.tracks[1]: + tick += message.time + if message.type == "note_on" and message.velocity: + assert message.channel == 0 and message.note not in active + active[message.note] = tick, message.velocity + elif message.type == "note_off": + start, velocity = active.pop(message.note) + (switches if message.note in (24, 26, 31) else musical).append( + (start, tick, message.note, velocity) + ) + assert not active + expected = sorted( + (start, end, pitch) + for notes, start, end in zip(pitches, starts, ends, strict=True) + for pitch in notes + ) + assert sorted(n[:3] for n in musical) == expected + if velocities: + assert sorted(musical) == sorted( + (start, end, pitch, velocity) + for notes, start, end, velocity in zip(pitches, starts, ends, velocities, strict=True) + for pitch in notes + ) + expected_switches = [] + previous = None + for start, technique in zip(starts, techniques, strict=True): + if technique != previous: + expected_switches.append( + ( + start, + start + 30, + {"normal": 24, "palm_mute": 26, "pinch_harmonic": 31}[technique], + 100, + ) + ) + previous = technique + assert switches == expected_switches + native_rows = [] + if native: + root = ET.parse(public["artifacts"][1]["path"]).getroot() + assert root.tag == "Riff" and root.get("PPQBase") == "480" + assert int(root.attrib["loopEnd"]) * 2 == total + assert root.get("Measures") == str(public["resolved"]["bars"]) + assert root.get("Time-Signature") == "4/4" + if public["resolved"]["key"] == "E minor": + assert root.get("Key") == "Em" + assert not any(node.tag.startswith("cc-") for node in root) + tuning = {6: 36, 5: 43, 4: 48, 3: 53, 2: 57, 1: 62} + for string in root.findall("String"): + string_id = int(string.attrib["ID"]) + occupied = 0 + for note in string.findall("Note"): + start, end = int(note.attrib["Begin"]), int(note.attrib["End"]) + pitch, fret = int(note.attrib["NoteID"]), int(note.attrib["Fret"]) + assert pitch == tuning[string_id] + fret and 0 <= fret <= 22 + assert start >= occupied and end > start + occupied = end + index = starts.index(start * 2) + assert ( + note.attrib["Articulation"] + == {"normal": "Sus", "palm_mute": "PM", "pinch_harmonic": "PH"}[ + techniques[index] + ] + ) + native_rows.append( + (start * 2, end * 2, pitch, int(note.attrib["Velocity"]), string_id, fret) + ) + assert sorted(n[:4] for n in native_rows) == sorted(musical) + if pitches == [[40]] * 9: + assert all(row[4:] == (6, 4) for row in native_rows) + hashes = { + a["format"]: hashlib.sha256(Path(a["path"]).read_bytes()).hexdigest() + for a in public["artifacts"] + } + return { + "musical": sorted(musical), + "switches": switches, + "native": sorted(native_rows), + "hashes": hashes, + "resolved": public["resolved"], + } + + +async def exercise_hybrid_stdio(client: RawStdio, outputs: Path, *, label: str) -> list[str]: + retained = ROOT / ".test-artifacts" / "step16" / label + retained.mkdir(parents=True, exist_ok=True) + evidence: dict[str, Any] = {} + names = [] + + async def call(name: str, text: str, *, fallback: bool | None = False) -> dict[str, Any]: + arguments: dict[str, Any] = {"description": text, "basename": name} + if fallback is not None: + arguments["allow_midi_fallback"] = fallback + Draft202012Validator(tool_input_schema("generate_music")).validate(arguments) + response = await client.request( + name, + "tools/call", + { + "name": "generate_music", + "arguments": arguments, + }, + ) + result = response["result"] + assert len(result["content"]) == 1 and result["content"][0]["type"] == "text" + public = json.loads(result["content"][0]["text"]) + assert isinstance(public, dict) + assert public == result["structuredContent"] + Draft202012Validator(tool_output_schema("generate_music")).validate(public) + if not result.get("isError"): + names.append(name) + destination = retained / name + if destination.exists(): + shutil.rmtree(destination) + shutil.copytree(outputs / name, destination) + evidence[name + "-transport"] = {"arguments": arguments, "result": result} + return public + + pitches = [[42, 46, 49]] * 2 + [[50, 54, 57]] * 2 + [[46, 50, 53]] * 2 + [[60], [64], [67]] + techniques = ["palm_mute"] * 8 + ["pinch_harmonic"] + for name, text, expected, native in [ + ("hybrid-d3", CANONICAL, pitches, True), + ( + "hybrid-compact", + CANONICAL.replace("x x x x x x [x x ^]", "xxxxxx[xx^]") + .replace("F#2 F#2 D3 D3 Bb2 Bb2 - - -", "F#2F#2 D3D3 Bb2Bb2 ---") + .replace("- - - - - - C4 E4 G4", "-- -- -- C4E4G4"), + pitches, + True, + ), + ( + "hybrid-d2-fallback", + CANONICAL.replace("D3 D3", "D2 D2"), + pitches[:2] + [[38, 42, 45]] * 2 + pitches[4:], + False, + ), + ("hybrid-e2", E2, [[40]] * 9, True), + ( + "hybrid-e2-compact", + E2.replace("1 & 2 & 3 &", "1& 2& 3&") + .replace("x x x x x x [x x ^]", "xxxxxx[xx^]") + .replace("E2 E2 E2 E2 E2 E2 E2 E2 E2", "E2E2E2E2E2E2E2E2E2"), + [[40]] * 9, + True, + ), + ( + "hybrid-e2-tilde", + E2[: E2.index("Hold")] + "\nBar 2:\nCounts: 1 2 3 4\nEvents: ~~~~\nNotes: ----", + [[40]] * 9, + True, + ), + ( + "hybrid-e2-continue", + E2[: E2.index("Hold")] + "\nBar 2: hold previous note to bar end", + [[40]] * 9, + True, + ), + ]: + public = await call(name, text, fallback=None if name == "hybrid-e2" else not native) + evidence[name] = inspect( + public, expected, STARTS, ENDS, techniques, native=native, velocities=VELOCITIES + ) + assert len(evidence[name]["musical"]) == (9 if "e2" in name else 21) + if not native: + assert public["artifacts"][0]["fallback_for"] == ["lead"] + assert any("no_physical_string_assignment" in w["message"] for w in public["warnings"]) + assert ( + evidence[name]["hashes"]["mid"] + == "4ce995ca751590b32cd85c72c3a2d8dad7f478cdf34d3abb12616d121719c3b4" + ) + assert evidence["hybrid-d3"]["hashes"] == evidence["hybrid-compact"]["hashes"] + assert ( + evidence["hybrid-e2"]["hashes"] + == evidence["hybrid-e2-compact"]["hashes"] + == evidence["hybrid-e2-tilde"]["hashes"] + == evidence["hybrid-e2-continue"]["hashes"] + == { + "mid": "c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62", + "griff": "e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c", + } + ) + for index, symbol in enumerate( + ("Em4OverB2", "Em4/B2", "Em4/B", "Em4OverB", "[C3 E3 G3]", "Em4(add4)", "F#") + ): + name = f"hybrid-voicing-{index}" + public = await call(name, f"guitar, D minor, 1 bar\nCounts: 1\nEvents: o\nChords: {symbol}") + expected_notes = ( + [47, 64, 67, 71] + if index < 2 + else [59, 64, 67, 71] + if index < 4 + else [48, 52, 55] + if index == 4 + else [64, 67, 69, 71] + if index == 5 + else [42, 46, 49] + ) + evidence[name] = inspect(public, [expected_notes], [0], [960], ["normal"]) + assert public["resolved"]["key"] == "D minor" + if index in (2, 3, 6): + assert "MIDI" in "\n".join(public["resolved"]["assumptions"]) + public = await call("hybrid-rest", "guitar, 1 bar\nCounts: 1& 2&\nEvents: o-o~\nNotes: E2-E2-") + evidence["hybrid-rest"] = inspect( + public, [[40], [40]], [0, 960], [480, 1920], ["normal"] * 2, held=[False, True] + ) + for name, text, code in [ + ("hybrid-d2-rejected", CANONICAL.replace("D3 D3", "D2 D2"), "NATIVE_FORMAT_UNAVAILABLE"), + ( + "hybrid-ambiguous", + "guitar\nCounts: 1&a\nEvents: xxx\nNotes: E2E2E2", + "UNSUPPORTED_DESCRIPTION", + ), + ("hybrid-mismatch", E2.replace("x x x x x x [x x ^]", "xx"), "UNSUPPORTED_DESCRIPTION"), + ( + "hybrid-slide", + E2.replace("x x x x x x [x x ^]", "xx xx xx x/^"), + "UNSUPPORTED_DESCRIPTION", + ), + ( + "hybrid-hold-conflict", + E2 + "\nBar 2:\nCounts: 1\nEvents: -\nNotes: -", + "UNSUPPORTED_DESCRIPTION", + ), + ("hybrid-private", E2 + "\nPRIVATE_PATH_AND_SECRET_DO_NOT_ECHO", "UNSUPPORTED_DESCRIPTION"), + ]: + before = sorted(outputs.iterdir()) + public = await call(name, text) + assert public["code"] == code + assert sorted(outputs.iterdir()) == before and not (outputs / name).exists() + assert "PRIVATE_PATH_AND_SECRET_DO_NOT_ECHO" not in json.dumps(public) + evidence[name] = public + assert not list(outputs.glob(".riff-stage-*")) + (retained / "evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8") + return names + + +@pytest.mark.anyio +async def test_source_hybrid_real_stdio() -> None: + outputs = ROOT / ".test-artifacts" / f"hybrid-source-{uuid.uuid4().hex}" + outputs.mkdir() + process = await asyncio.wait_for( + asyncio.create_subprocess_exec( + sys.executable, + "-I", + "-B", + "-m", + "riff_groove_builder", + "--output-dir", + str(outputs), + cwd=ROOT, + env=_environment(), + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ), + TIMEOUT, + ) + client = RawStdio(process) + try: + handshake = await client.initialize() + assert handshake["result"]["serverInfo"]["version"] == "0.2.0" + await exercise_hybrid_stdio(client, outputs, label="source") + finally: + await client.close() + shutil.rmtree(outputs) + assert process.returncode == 0 and client.diagnostics == b"" + (ROOT / ".test-artifacts" / "step16" / "source" / "hybrid-transport.json").write_text( + json.dumps( + { + "handshake": handshake["result"], + "exit_code": process.returncode, + "stdout_lines": len(client.lines), + "stderr": client.diagnostics.decode("utf-8"), + "sd3_template": None, + }, + indent=2, + ), + encoding="utf-8", + ) diff --git a/tests/integration/test_midi_files.py b/tests/integration/test_midi_files.py new file mode 100644 index 0000000..4136713 --- /dev/null +++ b/tests/integration/test_midi_files.py @@ -0,0 +1,428 @@ +"""Real disk and independent MIDIUtil evidence with exclusively synthetic maps.""" + +import shutil +import uuid +from collections.abc import Iterator +from fractions import Fraction +from pathlib import Path + +import mido # type: ignore[import-untyped] +import pytest +from midiutil import MIDIFile # type: ignore[import-untyped] + +from riff_groove_builder.errors import SerializationError +from riff_groove_builder.midi import validate_midi_file, write_midi +from riff_groove_builder.schemas import ( + ControlChangeEvent, + DrumNote, + EventPlan, + EventTrack, + MusicalIntent, + NoteOffEvent, + NoteOnEvent, + Part, + PitchedNote, + PositiveBeat, + RationalBeat, + ScheduledEvent, + Score, + ScoreTrack, + TimeSignature, +) + +pytestmark = pytest.mark.integration +Event = tuple[int, str, int, int, int] +PARTS: list[Part] = ["bass", "drums", "lead"] + + +@pytest.fixture +def workspace() -> Iterator[Path]: + root = ( + Path(__file__).resolve().parents[2] / ".test-artifacts" / f"midi-files-{uuid.uuid4().hex}" + ) + root.mkdir(parents=True) + try: + yield root + finally: + shutil.rmtree(root) + + +def synthetic_plan(numerator: int = 4, denominator: int = 4, bpm: float = 137.5) -> EventPlan: + """All pitches/controllers/channels below are arbitrary test-local numbers.""" + signature = TimeSignature.model_validate({"numerator": numerator, "denominator": denominator}) + duration = Fraction(numerator * 4, denominator) + musical_end = 240 + int(duration * 960) + score_end = Fraction(2) + duration + score = Score( + intent=MusicalIntent( + description="Synthetic three-part MIDI interoperability fixture", + parts=PARTS.copy(), + tempo_bpm=bpm, + bars=1, + time_signature=signature, + key="A minor", + seed=0, + ), + start=RationalBeat(numerator=2), + end=RationalBeat(numerator=score_end.numerator, denominator=score_end.denominator), + tracks=[ + ScoreTrack( + part="bass", + notes=[ + PitchedNote( + part="bass", + pitch=45, + start=RationalBeat(numerator=2), + duration=PositiveBeat( + numerator=duration.numerator, denominator=duration.denominator + ), + intensity=0.5, + articulation="synthetic_bass", + ) + ], + ), + ScoreTrack( + part="drums", + notes=[ + DrumNote( + voice="synthetic_hit", + start=RationalBeat(numerator=start, denominator=denom), + duration=PositiveBeat(numerator=1, denominator=8), + intensity=0.5, + articulation="synthetic_drum", + ) + for start, denom in ((2, 1), (5, 2)) + ], + ), + ScoreTrack( + part="lead", + notes=[ + PitchedNote( + part="lead", + pitch=69, + start=RationalBeat(numerator=start, denominator=3), + duration=PositiveBeat(numerator=length, denominator=3), + intensity=0.5, + articulation="synthetic_lead", + ) + for start, length in ((6, 1), (7, 2)) + ], + ), + ], + ) + # tick, kind, channel, data1, data2, role. Kept deliberately out of tick order. + raw: dict[Part, list[tuple[int, str, int, int, int, str]]] = { + "lead": [ + (musical_end + 60, "control_change", 2, 21, 0, "articulation_control"), + (240, "note_on", 2, 69, 97, "musical_note"), + (0, "note_on", 2, 5, 33, "keyswitch"), + (560, "note_on", 2, 69, 88, "musical_note"), + (80, "control_change", 2, 21, 100, "articulation_control"), + (280, "note_off", 2, 5, 33, "keyswitch"), + (1200, "note_off", 2, 69, 88, "musical_note"), + (560, "note_off", 2, 69, 97, "musical_note"), + ], + "bass": [ + (musical_end, "note_off", 5, 45, 83, "musical_note"), + (0, "note_on", 5, 6, 34, "keyswitch"), + (120, "control_change", 5, 22, 88, "articulation_control"), + (240, "note_on", 5, 45, 83, "musical_note"), + (100, "note_off", 5, 6, 34, "keyswitch"), + (musical_end + 80, "control_change", 5, 22, 0, "articulation_control"), + ], + "drums": [ + (musical_end + 120, "control_change", 12, 23, 0, "articulation_control"), + (240, "note_on", 12, 73, 110, "musical_note"), + (20, "note_on", 12, 7, 35, "keyswitch"), + (360, "note_off", 12, 73, 110, "musical_note"), + (120, "control_change", 12, 23, 66, "articulation_control"), + (720, "note_on", 12, 73, 104, "musical_note"), + (100, "note_off", 12, 7, 35, "keyswitch"), + (840, "note_off", 12, 73, 104, "musical_note"), + ], + } + tracks = [] + for part in PARTS: + events: list[ScheduledEvent] = [] + for sequence, (tick, kind, channel, data1, data2, role) in enumerate(raw[part]): + common = { + "tick": tick, + "part": part, + "channel": channel, + "sequence": sequence, + "role": role, + } + if kind == "control_change": + events.append( + ControlChangeEvent.model_validate( + {**common, "priority": 10, "controller": data1, "value": data2} + ) + ) + else: + cls = NoteOnEvent if kind == "note_on" else NoteOffEvent + events.append( + cls.model_validate( + { + **common, + "priority": 20 if kind == "note_on" else 0, + "note": data1, + "velocity": data2, + } + ) + ) + tracks.append(EventTrack(part=part, events=events)) + return EventPlan( + score=score, + musical_start_tick=240, + musical_end_tick=musical_end, + end_tick=musical_end + 120, + tracks=tracks, + ) + + +def normalized(path: Path) -> list[list[Event]]: + result = [] + for track in mido.MidiFile(path).tracks: + events: list[Event] = [] + tick = 0 + for message in track: + assert type(message.time) is int and message.time >= 0 + tick += message.time + if message.is_meta: + continue + assert message.type in ("note_on", "note_off", "control_change") + data1 = message.control if message.type == "control_change" else message.note + data2 = message.value if message.type == "control_change" else message.velocity + events.append((tick, message.type, message.channel, data1, data2)) + result.append(events) + return result + + +def reference(path: Path, numerator: int, denominator: int, bpm: float) -> None: + """Construct independently with MIDIUtil's note/duration and CC APIs.""" + end = 240 + numerator * 4 * 960 // denominator + midi = MIDIFile( + 3, + file_format=1, + ticks_per_quarternote=960, + eventtime_is_ticks=True, + adjust_origin=False, + removeDuplicates=False, + deinterleave=False, + ) + midi.addTempo(0, 0, bpm) + midi.addTimeSignature(0, 0, numerator, {4: 2, 8: 3}[denominator], 24) + for index, name in enumerate(("Bass", "Drums", "Lead")): + midi.addTrackName(index, 0, name) + midi.addNote(0, 5, 6, 0, 100, 34) + midi.addNote(0, 5, 45, 240, end - 240, 83) + midi.addControllerEvent(0, 5, 120, 22, 88) + midi.addControllerEvent(0, 5, end + 80, 22, 0) + midi.addNote(1, 12, 7, 20, 80, 35) + midi.addNote(1, 12, 73, 240, 120, 110) + midi.addNote(1, 12, 73, 720, 120, 104) + midi.addControllerEvent(1, 12, 120, 23, 66) + midi.addControllerEvent(1, 12, end + 120, 23, 0) + midi.addNote(2, 2, 5, 0, 280, 33) + midi.addNote(2, 2, 69, 240, 320, 97) + midi.addNote(2, 2, 69, 560, 640, 88) + midi.addControllerEvent(2, 2, 80, 21, 100) + midi.addControllerEvent(2, 2, end + 60, 21, 0) + with path.open("xb") as stream: + midi.writeFile(stream) + + +@pytest.mark.parametrize( + ("numerator", "denominator", "bpm", "tempo"), + [(4, 4, 120.0, 500000), (3, 4, 137.5, 436364), (6, 8, 120.125, 499480), (7, 8, 137.5, 436364)], +) +def test_real_disk_and_independent_reference( + workspace: Path, numerator: int, denominator: int, bpm: float, tempo: int +) -> None: + plan = synthetic_plan(numerator, denominator, bpm) + production = write_midi(workspace / "production.mid", plan) + comparison = workspace / "midiutil.mid" + reference(comparison, numerator, denominator, bpm) + validate_midi_file(production, plan) + observed = normalized(production) + assert observed == normalized(comparison) + end = 240 + numerator * 4 * 960 // denominator + assert observed == [ + [], + [ + (0, "note_on", 5, 6, 34), + (100, "note_off", 5, 6, 34), + (120, "control_change", 5, 22, 88), + (240, "note_on", 5, 45, 83), + (end, "note_off", 5, 45, 83), + (end + 80, "control_change", 5, 22, 0), + ], + [ + (20, "note_on", 12, 7, 35), + (100, "note_off", 12, 7, 35), + (120, "control_change", 12, 23, 66), + (240, "note_on", 12, 73, 110), + (360, "note_off", 12, 73, 110), + (720, "note_on", 12, 73, 104), + (840, "note_off", 12, 73, 104), + (end + 120, "control_change", 12, 23, 0), + ], + [ + (0, "note_on", 2, 5, 33), + (80, "control_change", 2, 21, 100), + (240, "note_on", 2, 69, 97), + (280, "note_off", 2, 5, 33), + (560, "note_off", 2, 69, 97), + (560, "note_on", 2, 69, 88), + (1200, "note_off", 2, 69, 88), + (end + 60, "control_change", 2, 21, 0), + ], + ] + loaded = mido.MidiFile(production) + ref = mido.MidiFile(comparison) + assert production.read_bytes()[:14] == (b"MThd\x00\x00\x00\x06\x00\x01\x00\x04\x03\xc0") + assert loaded.type == ref.type == 1 and loaded.ticks_per_beat == ref.ticks_per_beat == 960 + assert [track.name for track in loaded.tracks] == ["Conductor", "Bass", "Drums", "Lead"] + assert len(ref.tracks) == 4 # MIDIUtil inserts its own conductor ahead of three user tracks. + assert [track.name for track in ref.tracks[1:]] == ["Bass", "Drums", "Lead"] + assert [(message.type, message.time) for message in loaded.tracks[0]] == [ + ("track_name", 0), + ("set_tempo", 0), + ("time_signature", 0), + ("end_of_track", end + 120), + ] + assert loaded.tracks[0][1].tempo == tempo + assert tempo == round(Fraction(60_000_000) / Fraction(str(bpm))) + # MIDIUtil 1.2.1 truncates, unlike the production nearest-integer policy. + assert [message.tempo for message in ref.tracks[0] if message.type == "set_tempo"] == [ + int(60_000_000 / bpm) + ] + for file in (loaded, ref): + signatures = [message for message in file.tracks[0] if message.type == "time_signature"] + assert len(signatures) == 1 + assert (signatures[0].numerator, signatures[0].denominator) == (numerator, denominator) + for track in loaded.tracks: + assert sum(message.time for message in track) == end + 120 + assert sum(message.type == "end_of_track" for message in track) == 1 + assert track[-1].type == "end_of_track" + # Reference EOTs are local last-event positions, not the production shared tail. + assert [sum(message.time for message in track) for track in ref.tracks] == [ + 0, + end + 80, + end + 120, + end + 60, + ] + + +def test_repeated_input_is_byte_deterministic(workspace: Path) -> None: + plan = synthetic_plan() + first = write_midi(workspace / "first.mid", plan) + second = write_midi(workspace / "second.mid", plan) + for track in plan.tracks: + track.events.reverse() + third = write_midi(workspace / "reordered-input.mid", plan) + assert first.read_bytes() == second.read_bytes() == third.read_bytes() + validate_midi_file(third, plan) + + +@pytest.mark.parametrize("damage", ["empty", "header", "truncated", "trailing", "track_size"]) +def test_corrupt_files_fail_without_deletion(workspace: Path, damage: str) -> None: + plan = synthetic_plan() + path = write_midi(workspace / "damaged.mid", plan) + data = path.read_bytes() + if damage == "empty": + broken = b"" + elif damage == "header": + broken = b"XXXX" + data[4:] + elif damage == "truncated": + broken = data[:-3] + elif damage == "trailing": + broken = data + b"unexplained trailing data" + else: + broken = data[:18] + b"\x00\x00\x00\x01" + data[22:] + path.write_bytes(broken) + with pytest.raises(SerializationError): + validate_midi_file(path, plan) + assert path.read_bytes() == broken + + +@pytest.mark.parametrize( + "change", + [ + "type", + "ppq", + "order", + "name", + "pitch", + "velocity", + "channel", + "cc", + "tempo", + "meter", + "timing", + "end", + "missing_release", + "extra_program", + ], +) +def test_readable_but_wrong_content_is_not_success(workspace: Path, change: str) -> None: + plan = synthetic_plan() + path = write_midi(workspace / "wrong.mid", plan) + loaded = mido.MidiFile(path) + if change == "type": + loaded.type = 2 + elif change == "ppq": + loaded.ticks_per_beat = 480 + elif change == "order": + loaded.tracks[1], loaded.tracks[2] = loaded.tracks[2], loaded.tracks[1] + elif change == "name": + loaded.tracks[1][0].name = "Wrong" + elif change in ("pitch", "velocity", "channel"): + attribute = "note" if change == "pitch" else change + setattr(loaded.tracks[1][1], attribute, 11) + elif change == "cc": + next(message for message in loaded.tracks[1] if message.type == "control_change").value = 1 + elif change == "tempo": + loaded.tracks[0][1].tempo = 500000 + elif change == "meter": + loaded.tracks[0][2].numerator = 3 + elif change == "timing": + loaded.tracks[1][1].time += 1 + elif change == "end": + loaded.tracks[1][-1].time += 1 + elif change == "missing_release": + del loaded.tracks[1][2] + else: + loaded.tracks[1].insert(1, mido.Message("program_change", channel=5, program=1)) + loaded.save(path) + assert len(mido.MidiFile(path).tracks) == 4 + with pytest.raises(SerializationError) as failure: + validate_midi_file(path, plan) + assert failure.value.details["reason"] in ("smf_header_mismatch", "smf_content_mismatch") + assert path.exists() + + +def test_writer_checks_actual_saved_content_and_cleans_mismatch( + workspace: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + path = workspace / "changed-on-disk.mid" + sentinel = workspace / "keep" + sentinel.write_bytes(b"unrelated") + read_bytes = Path.read_bytes + observed_disk_read = [] + + def tamper_then_read(self: Path) -> bytes: + assert self == path and path.exists() + loaded = mido.MidiFile(path) + loaded.tracks[1][1].note = 11 + loaded.save(path) + observed_disk_read.append(True) + return read_bytes(path) + + monkeypatch.setattr(Path, "read_bytes", tamper_then_read) + with pytest.raises(SerializationError) as failure: + write_midi(path, synthetic_plan()) + assert failure.value.details == {"reason": "smf_content_mismatch", "track": 1} + assert observed_disk_read == [True] + assert not path.exists() + assert read_bytes(sentinel) == b"unrelated" diff --git a/tests/integration/test_native_service.py b/tests/integration/test_native_service.py new file mode 100644 index 0000000..11e471c --- /dev/null +++ b/tests/integration/test_native_service.py @@ -0,0 +1,740 @@ +"""Real native service transactions, saved content and operator-template acceptance.""" + +import asyncio +import hashlib +import json +import os +import shutil +import sys +import uuid +import xml.etree.ElementTree as ET +from collections.abc import Callable, Iterator +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from threading import Barrier +from unittest.mock import patch + +import anyio +import mido # type: ignore[import-untyped] +import pytest +from jsonschema import Draft202012Validator +from test_stdio import TIMEOUT, RawStdio, _environment + +from riff_groove_builder.articulations import apply_scheduled_controls, compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.errors import ( + DomainError, + NativeFormatUnavailableError, + OutputExistsError, + OutputIOError, + SerializationError, + UnsupportedArticulationError, +) +from riff_groove_builder.formats.agp import validate_riffer_file +from riff_groove_builder.formats.sdp import parse_sdp_project, validate_sdp_file, write_sdp +from riff_groove_builder.midi import validate_midi_file +from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry +from riff_groove_builder.schemas import ( + EventPlan, + GenerateMusicRequest, + GenerationResult, + Part, + ProfileSelection, + tool_output_schema, +) +from riff_groove_builder.service import GenerationService, _Stage + +ROOT = Path(__file__).resolve().parents[2] +TEMPLATE = ROOT / "tests" / "fixtures" / "sd3" / "original-template.sd3p" +TARGETS = { + "lead": "ample.ame.4.0.1.riffer.v1", + "bass": "ample.amr.4.1.0.riffer.v1", + "drums": "toontrack.sd3.3.4.4.core.v1", +} +pytestmark = pytest.mark.integration + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"native-service-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +def job(**updates: object) -> GenerateMusicRequest: + return GenerateMusicRequest.model_validate( + { + "description": "lead bass drums palm mute 137.5 BPM 2 bars 7/8 Bb minor quarter rests", + "basename": "original", + "seed": 42, + **updates, + } + ) + + +def plan_for(request: GenerateMusicRequest) -> tuple[EventPlan, dict[Part, InstrumentProfile]]: + intent = resolve_description(request).intent + profiles = load_profile_registry().select(intent.parts, request.profiles or ProfileSelection()) + return apply_scheduled_controls( + compile_score(compose_score(intent, profiles), profiles), request.cc_events, profiles + ), profiles + + +def validate_saved( + result: GenerationResult, request: GenerateMusicRequest, template: Path | None +) -> dict[str, object]: + """Read actual files with validators plus independent raw MIDI/XML/triple checks.""" + Draft202012Validator(tool_output_schema("generate_music")).validate( + result.model_dump(mode="json") + ) + plan, profiles = plan_for(request) + assert result.resolved.profile_ids.selected() == { + part: profiles[part].id for part in plan.score.intent.parts + } + assert result.resolved.tempo_bpm == plan.score.intent.tempo_bpm + assert result.resolved.time_signature == plan.score.intent.time_signature + assert result.resolved.key == plan.score.intent.key + assert result.resolved.seed == request.seed + evidence: dict[str, object] = {} + for artifact in result.artifacts: + path = Path(artifact.path) + raw = path.read_bytes() + assert path.suffix == f".{artifact.format}" and len(raw) == artifact.size_bytes > 0 + assert artifact.profile_ids == [profiles[part].id for part in artifact.parts] + details: dict[str, object] = { + "parts": artifact.parts, + "profiles": artifact.profile_ids, + "size": len(raw), + "sha256": hashlib.sha256(raw).hexdigest(), + } + if artifact.format == "mid": + validate_midi_file(path, plan) + midi = mido.MidiFile(path) + assert raw.startswith(b"MThd") + assert midi.type == 1 and midi.ticks_per_beat == 960 + assert [sum(message.time for message in track) for track in midi.tracks] == [ + plan.end_tick + ] * (len(result.resolved.parts) + 1) + conductor = midi.tracks[0] + assert next(m.tempo for m in conductor if m.type == "set_tempo") == round( + 60_000_000 / result.resolved.tempo_bpm + ) + sig = next(m for m in conductor if m.type == "time_signature") + assert (sig.numerator, sig.denominator) == ( + result.resolved.time_signature.numerator, + result.resolved.time_signature.denominator, + ) + counts = {} + for part, track in zip(result.resolved.parts, midi.tracks[1:], strict=True): + notes = [m for m in track if m.type == "note_on"] + assert {m.channel for m in notes} == {profiles[part].channel} + controls = [m for m in notes if part != "drums" and m.note in (24, 26)] + musical = [m for m in notes if m not in controls] + assert len(musical) == len( + next(t for t in plan.score.tracks if t.part == part).notes + ) + if request.description.find("palm mute") >= 0 and part != "drums": + assert [m.note for m in controls] == [26 if part == "lead" else 24] + assert {m.velocity for m in controls} == {100} + assert ( + all(32 <= m.velocity <= 63 for m in musical) + if part == "bass" + else all(1 <= m.velocity <= 127 for m in musical) + ) + if part == "drums": + assert {m.note for m in musical} <= {36, 38, 42} + counts[part] = len(musical) + details["musical_note_counts"] = counts + elif artifact.format in ("griff", "briff"): + part = artifact.parts[0] + saved = validate_riffer_file(path, plan, part, profiles[part]) + assert raw.startswith(b" None: + before = TEMPLATE.stat(), TEMPLATE.read_bytes() + request = job(formats=formats, description=description) + result = GenerationService(workspace, sd3_template=TEMPLATE).generate_music(request) + expected = ( + ["mid"] + if formats == ["mid"] + else ["griff", "briff", "sd3p"] + if formats in (["agp", "sdp"], ["griff", "briff", "sd3p"]) + else ["mid", "griff", "briff", "sd3p"] + ) + assert result.status == "complete" + assert [a.format for a in result.artifacts] == expected + assert [w.code for w in result.warnings] == ["VERIFIED_SUBSET_LIMITS"] * 3 + if "palm mute" in description: + assert any( + "drums retain normal" in assumption for assumption in result.resolved.assumptions + ) + validate_saved(result, request, TEMPLATE) + after = TEMPLATE.stat() + assert before[1] == TEMPLATE.read_bytes() + assert (before[0].st_ino, before[0].st_mtime_ns) == (after.st_ino, after.st_mtime_ns) + assert list(workspace.iterdir()) == [workspace / "original"] + + +@pytest.mark.parametrize( + ("part", "alias", "actual"), + [("lead", "agp", "griff"), ("bass", "agp", "briff"), ("drums", "sdp", "sd3p")], +) +def test_single_part_alias_and_actual_are_identical( + workspace: Path, part: Part, alias: str, actual: str +) -> None: + service = GenerationService(workspace, sd3_template=TEMPLATE) + outputs = [] + for name, extension in (("alias", alias), ("actual", actual)): + request = job(basename=name, description=f"{part} only 1 bar quarter", formats=[extension]) + result = service.generate_music(request) + assert len(result.artifacts) == 1 and result.artifacts[0].format == actual + assert result.artifacts[0].parts == [part] + validate_saved(result, request, TEMPLATE) + outputs.append(Path(result.artifacts[0].path).read_bytes()) + assert outputs[0] == outputs[1] + + +def test_missing_template_keeps_real_riffer_and_fallback_only_drums(workspace: Path) -> None: + request = job() + result = GenerationService(workspace).generate_music(request) + assert result.status == "midi_fallback" + assert [a.format for a in result.artifacts] == ["mid", "griff", "briff"] + assert result.artifacts[0].fallback_for == ["drums"] + assert [(w.part, w.code) for w in result.warnings if w.code == "NATIVE_FORMAT_UNAVAILABLE"] == [ + ("drums", "NATIVE_FORMAT_UNAVAILABLE") + ] + assert "sd3p: sdp_template_required" in result.warnings[-1].message + validate_saved(result, request, None) + + +def test_missing_template_fallback_disabled_never_stages(workspace: Path) -> None: + service = GenerationService(workspace) + with ( + patch.object(service, "_new_stage", side_effect=AssertionError), + pytest.raises(NativeFormatUnavailableError) as caught, + ): + service.generate_music(job(allow_midi_fallback=False)) + assert caught.value.details == { + "format": "sd3p", + "part": "drums", + "reason": "sdp_template_required", + } + assert not list(workspace.iterdir()) + + +def test_default_target_midi_only_needs_no_template(workspace: Path) -> None: + request = job(formats=["mid"], allow_midi_fallback=False) + result = GenerationService(workspace).generate_music(request) + assert result.status == "complete" and result.artifacts[0].fallback_for == [] + assert result.resolved.profile_ids.selected() == TARGETS + validate_saved(result, request, None) + + +@pytest.mark.parametrize("allow", [False, True]) +def test_known_native_decimal_limit_is_preflighted(workspace: Path, allow: bool) -> None: + service = GenerationService(workspace, sd3_template=TEMPLATE) + request = job(tempo_bpm=137.1234567, allow_midi_fallback=allow) + if not allow: + with ( + patch.object(service, "_new_stage", side_effect=AssertionError), + pytest.raises(NativeFormatUnavailableError) as caught, + ): + service.generate_music(request) + assert caught.value.details["reason"] == "sd3_timing_not_representable" + assert not list(workspace.iterdir()) + else: + result = service.generate_music(request) + assert result.status == "midi_fallback" + assert [a.format for a in result.artifacts] == ["mid", "griff", "briff"] + assert result.artifacts[0].fallback_for == ["drums"] + validate_saved(result, request, None) + + +@pytest.mark.parametrize("allow", [False, True]) +def test_common_preroll_is_never_silently_removed(workspace: Path, allow: bool) -> None: + request = job(allow_midi_fallback=allow) + plan, _ = plan_for(request) + plan.musical_start_tick += 120 + plan.musical_end_tick += 120 + plan.end_tick += 120 + for track in plan.tracks: + for event in track.events: + event.tick += 120 + with patch("riff_groove_builder.service.compile_score", return_value=plan): + if allow: + result = GenerationService(workspace, sd3_template=TEMPLATE).generate_music(request) + assert [a.format for a in result.artifacts] == ["mid"] + assert result.artifacts[0].fallback_for == ["lead", "bass", "drums"] + assert result.resolved.musical_start_tick == 120 + validate_midi_file(Path(result.artifacts[0].path), plan) + else: + with pytest.raises(NativeFormatUnavailableError): + GenerationService(workspace, sd3_template=TEMPLATE).generate_music(request) + assert not list(workspace.iterdir()) + + +def test_plan_mismatch_is_not_capability_fallback(workspace: Path) -> None: + request = job() + plan, _ = plan_for(request) + event = next( + e for e in plan.tracks[0].events if e.kind == "note_on" and e.role == "musical_note" + ) + assert event.kind == "note_on" + event.velocity -= 1 + with ( + patch("riff_groove_builder.service.compile_score", return_value=plan), + pytest.raises(SerializationError) as caught, + ): + GenerationService(workspace, sd3_template=TEMPLATE).generate_music(request) + assert caught.value.details["reason"] == "score_event_plan_mismatch" + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize("kind", ["corrupt", "version", "missing", "library"]) +def test_explicit_bad_template_is_visible_not_fallback(workspace: Path, kind: str) -> None: + template = workspace / "operator.sd3p" + raw = TEMPLATE.read_bytes() + if kind == "corrupt": + template.write_bytes(b"private malformed project {") + elif kind == "version": + template.write_bytes(raw.replace(b"3.4.4", b"3.4.5")) + elif kind == "library": + template.write_bytes(raw.replace(b"SL-DFH", b"SL-OTHER")) + with pytest.raises(OutputIOError if kind == "missing" else SerializationError): + GenerationService(workspace, sd3_template=template).generate_music(job()) + assert not list(workspace.glob(".riff-stage-*")) and not (workspace / "original").exists() + + +def test_runtime_summaries_reflect_template_and_subset_without_mutating_registry( + workspace: Path, +) -> None: + registry = load_profile_registry() + for template, ready in ((None, False), (TEMPLATE, True)): + listed = GenerationService( + workspace, registry=registry, sd3_template=template + ).list_instrument_profiles() + for summary in listed.profiles: + assert ( + summary.native_format + == {"lead": "griff", "bass": "briff", "drums": "sd3p"}[summary.part] + ) + if summary.id.startswith("standard."): + assert not summary.native_available + else: + assert summary.native_available == (summary.part != "drums" or ready) + assert "Default profile" in summary.limitations[-1] + assert "certification" in summary.limitations[-1] + if summary.part == "drums": + assert summary.product_version == "3.4.4" + assert ( + "sdp_template_required" in summary.limitations[-1] + if not ready + else ("sd3_3_4_4_template_song" in summary.limitations[-1]) + ) + assert all(s.native_available for s in registry.summaries() if not s.id.startswith("standard.")) + assert not list(workspace.iterdir()) + + +def test_standard_profiles_stay_explicit_and_do_not_approximate_palm_mute(workspace: Path) -> None: + with pytest.raises(UnsupportedArticulationError): + GenerationService(workspace).generate_music( + job(description="lead only palm mute", profiles={"lead": "standard.lead.v1"}) + ) + with pytest.raises(UnsupportedArticulationError) as caught: + GenerationService(workspace).generate_music(job(description="drums only palm mute")) + assert caught.value.details["reason"] == "pitched_parts_required" + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize( + "operation", + [ + "write_riffer", + "write_sdp", + "validate_riffer_file", + "validate_sdp_file", + ], +) +@pytest.mark.parametrize("error_type", [SerializationError, OutputIOError]) +def test_native_faults_never_fallback_or_publish( + workspace: Path, operation: str, error_type: type[DomainError] +) -> None: + sentinel = workspace / "sentinel" + sentinel.write_bytes(b"operator sentinel") + before = sentinel.stat() + with ( + patch( + f"riff_groove_builder.service.{operation}", + side_effect=error_type(details={"reason": "injected_failure"}), + ), + pytest.raises(error_type), + ): + GenerationService(workspace, sd3_template=TEMPLATE).generate_music(job()) + assert list(workspace.iterdir()) == [sentinel] + assert (sentinel.stat().st_ino, sentinel.stat().st_mtime_ns) == ( + before.st_ino, + before.st_mtime_ns, + ) + + +def test_last_native_partial_write_cleans_all_owned_files(workspace: Path) -> None: + def fail( + path: Path, + plan: EventPlan, + part: Part, + profile: InstrumentProfile, + *, + template: Path | None, + on_created: Callable[[os.stat_result], None], + ) -> Path: + with path.open("xb") as stream: + on_created(os.fstat(stream.fileno())) + stream.write(b"partial native bytes") + assert {p.suffix for p in path.parent.iterdir()} == {".mid", ".griff", ".briff", ".sd3p"} + raise OutputIOError(details={"reason": "last_native_short_write"}) + + with ( + patch("riff_groove_builder.service.write_sdp", side_effect=fail), + pytest.raises(OutputIOError) as caught, + ): + GenerationService(workspace, sd3_template=TEMPLATE).generate_music(job()) + assert caught.value.details["reason"] == "last_native_short_write" + assert not list(workspace.iterdir()) + + +def test_actual_saved_sd3_corruption_fails_and_cleans_complete_set(workspace: Path) -> None: + def corrupt( + path: Path, + plan: EventPlan, + part: Part, + profile: InstrumentProfile, + *, + template: Path | None, + on_created: Callable[[os.stat_result], None], + ) -> Path: + write_sdp(path, plan, part, profile, template=template, on_created=on_created) + raw = path.read_bytes() + assert b"TrackLength 7" in raw + path.write_bytes(raw.replace(b"TrackLength 7", b"TrackLength 8")) + return path + + with ( + patch("riff_groove_builder.service.write_sdp", side_effect=corrupt), + pytest.raises(SerializationError), + ): + GenerationService(workspace, sd3_template=TEMPLATE).generate_music(job()) + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize("cleanup_denied", [False, True]) +def test_multi_artifact_publication_and_cleanup_failure( + workspace: Path, cleanup_denied: bool +) -> None: + sentinel = workspace / "user-sentinel" + sentinel.write_bytes(b"preserved") + with ( + patch.object(Path, "rename", side_effect=PermissionError), + pytest.raises(OutputIOError) as caught, + ): + if cleanup_denied: + with patch.object(Path, "unlink", side_effect=PermissionError): + GenerationService(workspace, sd3_template=TEMPLATE).generate_music(job()) + else: + GenerationService(workspace, sd3_template=TEMPLATE).generate_music(job()) + assert caught.value.details["reason"] == ( + "stage_cleanup_failed" if cleanup_denied else "publication_failed" + ) + assert sentinel.read_bytes() == b"preserved" and not (workspace / "original").exists() + stages = list(workspace.glob(".riff-stage-*")) + assert len(stages) == (1 if cleanup_denied else 0) + if cleanup_denied: + assert {p.suffix for p in stages[0].iterdir()} == {".mid", ".griff", ".briff", ".sd3p"} + + +@pytest.mark.parametrize("injection", ["unexpected", "same-name-replacement", "late-corruption"]) +def test_multi_file_ownership_and_last_writer_mutation(workspace: Path, injection: str) -> None: + def inject( + path: Path, + plan: EventPlan, + part: Part, + profile: InstrumentProfile, + *, + template: Path | None, + on_created: Callable[[os.stat_result], None], + ) -> Path: + write_sdp(path, plan, part, profile, template=template, on_created=on_created) + lead = path.parent / "original_lead.griff" + if injection == "unexpected": + (path.parent / "user-sentinel").write_bytes(b"unowned") + elif injection == "same-name-replacement": + # Keep the old inode allocated, so the new inode cannot reuse it. + lead.rename(workspace / "original-owned.griff") + lead.write_bytes(b"unowned replacement") + else: + before = lead.stat() + raw = lead.read_bytes() + lead.write_bytes(raw.replace(b"PM", b"XX")) + os.utime(lead, ns=(before.st_atime_ns, before.st_mtime_ns)) + return path + + with ( + patch("riff_groove_builder.service.write_sdp", side_effect=inject), + pytest.raises(OutputIOError) as caught, + ): + GenerationService(workspace, sd3_template=TEMPLATE).generate_music(job()) + assert not (workspace / "original").exists() + if injection == "late-corruption": + assert caught.value.details["reason"] == "staged_content_changed" + assert not list(workspace.iterdir()) + else: + assert caught.value.details["reason"] == "stage_cleanup_failed" + stages = list(workspace.glob(".riff-stage-*")) + assert len(stages) == 1 + preserved = stages[0] / ( + "user-sentinel" if injection == "unexpected" else "original_lead.griff" + ) + assert preserved.read_bytes().startswith(b"unowned") + + +def test_template_changed_after_configuration_is_error_before_staging(workspace: Path) -> None: + template = workspace / "operator.sd3p" + template.write_bytes(TEMPLATE.read_bytes()) + service = GenerationService(workspace, sd3_template=template) + template.write_bytes(template.read_bytes() + b"\n") + with pytest.raises(SerializationError) as caught: + service.generate_music(job()) + assert caught.value.details["reason"] == "sd3_template_changed" + assert list(workspace.iterdir()) == [template] + + +def test_multifile_concurrent_publication_has_one_winner(workspace: Path) -> None: + barrier = Barrier(2) + publish = GenerationService._publish + + def synchronized(self: GenerationService, stage: _Stage, destination: Path) -> None: + barrier.wait(timeout=30) + publish(self, stage, destination) + + def run(service: GenerationService) -> GenerationResult | DomainError: + try: + return service.generate_music(job()) + except DomainError as error: + return error + + with patch.object(GenerationService, "_publish", synchronized), ThreadPoolExecutor(2) as pool: + results = list( + pool.map( + run, + [ + GenerationService(workspace, sd3_template=TEMPLATE), + GenerationService(workspace, sd3_template=TEMPLATE), + ], + ) + ) + winners = [r for r in results if isinstance(r, GenerationResult)] + assert len(winners) == 1 and sum(isinstance(r, OutputExistsError) for r in results) == 1 + validate_saved(winners[0], job(), TEMPLATE) + assert list(workspace.iterdir()) == [workspace / "original"] + + +def test_genuine_local_template_readonly_acceptance_when_configured(workspace: Path) -> None: + """Ordinary portable runs need no private template; an explicit local run records evidence.""" + configured = os.environ.get("RIFF_SD3_TEMPLATE") + if configured is None: + return + template = Path(configured) + before = template.stat(), template.read_bytes() + request = job(basename="genuine-original") + if os.environ.get("RIFF_NATIVE_EVIDENCE") == "1": + workspace = ROOT / ".test-artifacts" / f"step9-genuine-{uuid.uuid4().hex}" + workspace.mkdir() + result = GenerationService(workspace, sd3_template=template).generate_music(request) + evidence = validate_saved(result, request, template) + after = template.stat() + assert template.read_bytes() == before[1] + assert (before[0].st_ino, before[0].st_size, before[0].st_mtime_ns) == ( + after.st_ino, + after.st_size, + after.st_mtime_ns, + ) + record = { + "source_sha256": hashlib.sha256(before[1]).hexdigest(), + "source_inode": before[0].st_ino, + "source_size": before[0].st_size, + "source_mtime_ns": before[0].st_mtime_ns, + "result": result.model_dump(mode="json"), + "artifacts": evidence, + } + if os.environ.get("RIFF_NATIVE_EVIDENCE") == "1": + (workspace / "evidence.json").write_text(json.dumps(record, indent=2), encoding="utf-8") + print(json.dumps(record, sort_keys=True)) + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +@pytest.mark.anyio +async def test_real_stdio_all_native_default_alias_actual_and_midi(workspace: Path) -> None: + if os.environ.get("RIFF_NATIVE_EVIDENCE") == "1": + workspace = ROOT / ".test-artifacts" / f"step9-stdio-{uuid.uuid4().hex}" + workspace.mkdir() + outputs, cwd = workspace / "outputs", workspace / "other-cwd" + outputs.mkdir() + cwd.mkdir() + template = workspace / "original-template.sd3p" + template.write_bytes(TEMPLATE.read_bytes()) + before = template.stat(), template.read_bytes() + process = await asyncio.wait_for( + asyncio.create_subprocess_exec( + sys.executable, + "-I", + "-B", + "-m", + "riff_groove_builder", + "--output-dir", + str(outputs), + "--sd3-template", + str(template), + cwd=cwd, + env=_environment(), + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ), + TIMEOUT, + ) + client = RawStdio(process) + records = [] + try: + with anyio.fail_after(60): + await client.initialize() + tools = (await client.request(1, "tools/list"))["result"]["tools"] + assert len(tools) == 2 + assert "--sd3-template" not in json.dumps(tools) + for tool in tools: + Draft202012Validator.check_schema(tool["inputSchema"]) + Draft202012Validator.check_schema(tool["outputSchema"]) + listed = await client.request( + 2, "tools/call", {"name": "list_instrument_profiles", "arguments": {}} + ) + summaries = listed["result"]["structuredContent"]["profiles"] + assert all( + s["native_available"] for s in summaries if s["mapping_kind"] == "instrument" + ) + for name, formats in ( + ("default", None), + ("aliases", ["agp", "sdp"]), + ("actual", ["griff", "briff", "sd3p"]), + ("midi", ["mid"]), + ): + request = job(basename=name, formats=formats, allow_midi_fallback=False) + arguments = request.model_dump(mode="json", exclude_none=True) + response = await client.request( + name, "tools/call", {"name": "generate_music", "arguments": arguments} + ) + assert response["result"]["isError"] is False + result = GenerationResult.model_validate(response["result"]["structuredContent"]) + assert result.status == "complete" + assert [a.format for a in result.artifacts] == ( + ["mid", "griff", "briff", "sd3p"] + if formats is None + else ["mid"] + if formats == ["mid"] + else ["griff", "briff", "sd3p"] + ) + records.append( + { + "request": arguments, + "result": result.model_dump(mode="json"), + "saved": validate_saved(result, request, template), + } + ) + response = await client.request( + "untrusted-template", + "tools/call", + { + "name": "generate_music", + "arguments": { + "description": "music", + "basename": "bad", + "sd3_template": "private-user-path", + }, + }, + ) + assert response["result"]["isError"] + assert response["result"]["structuredContent"]["code"] == "INVALID_REQUEST" + assert "private-user-path" not in json.dumps(response) + finally: + with anyio.CancelScope(shield=True): + await client.close() + assert process.returncode == 0 and client.diagnostics == b"" + assert template.read_bytes() == before[1] + assert (template.stat().st_ino, template.stat().st_mtime_ns) == ( + before[0].st_ino, + before[0].st_mtime_ns, + ) + assert not list(outputs.glob(".riff-stage-*")) + assert len(client.lines) == 8 + if os.environ.get("RIFF_NATIVE_EVIDENCE") == "1": + (workspace / "evidence.json").write_text(json.dumps(records, indent=2), encoding="utf-8") + print(f"Native stdio evidence: {json.dumps(records, sort_keys=True)}") diff --git a/tests/integration/test_phrase_stdio.py b/tests/integration/test_phrase_stdio.py new file mode 100644 index 0000000..ca2687e --- /dev/null +++ b/tests/integration/test_phrase_stdio.py @@ -0,0 +1,239 @@ +"""Original request verbatim via real text-only source and installed-wheel transports.""" + +import asyncio +import hashlib +import json +import shutil +import sys +import uuid +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import Any + +import mido # type: ignore[import-untyped] +import pytest +from jsonschema import Draft202012Validator +from test_stdio import TIMEOUT, RawStdio, _environment + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.formats.agp import validate_riffer_file +from riff_groove_builder.profiles import load_profile_registry +from riff_groove_builder.schemas import GenerateMusicRequest, ProfileSelection, tool_output_schema + +ROOT = Path(__file__).resolve().parents[2] +ORIGINAL = ( + "Please produce a 4/4 riff in Em. With Chugging palm muting 8th notes from 1 to 3&;\n" + "and triplets on 4&A with the A as a pinch harmonic that carries over a whole note\n" + "in the 2nd measure." +) +MIDI_STARTS = [0, 480, 960, 1440, 1920, 2400, 2880, 3200, 3520] +MIDI_ENDS = [480, 960, 1440, 1920, 2400, 2880, 3200, 3520, 7680] + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +def inspect_saved(public: dict[str, Any], description: str, *, variant: bool) -> dict[str, Any]: + """Assert numeric expected music first, independently of the producer's score/serializers.""" + resolved = public["resolved"] + assert resolved["parts"] == ["lead"] and resolved["bars"] == 2 + assert resolved["key"] == "E minor" and resolved["tempo_bpm"] == 120 + assert resolved["musical_start_tick"] == 0 and resolved["musical_end_tick"] == 7680 + assert resolved["profile_ids"]["lead"] == "ample.ame.4.0.1.riffer.v1" + assert not resolved["profile_ids"]["bass"] and not resolved["profile_ids"]["drums"] + assert "count-A" in "\n".join(resolved["assumptions"]) + assert [a["format"] for a in public["artifacts"]] == ["mid", "griff"] + starts, ends = (MIDI_STARTS[2:], MIDI_ENDS[2:]) if variant else (MIDI_STARTS, MIDI_ENDS) + musical: list[tuple[int, int, int, int]] = [] + switches: list[tuple[int, int, int, int]] = [] + files = [] + for artifact in public["artifacts"]: + assert artifact["fallback_for"] == [] and artifact["parts"] == ["lead"] + path = Path(artifact["path"]) + data = path.read_bytes() + assert len(data) == artifact["size_bytes"] + if not variant: + assert ( + hashlib.sha256(data).hexdigest() + == { + "mid": "c1967e698a50b8c22a22e458c3e2dd02d04407d1ad1d61f8a462d790b0810e62", + "griff": "e8195e74c60ac93b1a4c92967a0834a64b2a2ebd74f453d6d3640ea465c4104c", + }[artifact["format"]] + ) + files.append( + {"name": path.name, "sha256": hashlib.sha256(data).hexdigest(), "size_bytes": len(data)} + ) + if artifact["format"] != "mid": + continue + midi = mido.MidiFile(path) + assert midi.ticks_per_beat == 960 and midi.type == 1 + assert [track.name for track in midi.tracks] == ["Conductor", "Lead"] + assert [sum(m.time for m in track) for track in midi.tracks] == [7680, 7680] + assert not any(m.type == "control_change" for t in midi.tracks for m in t) + assert not any(m.type == "program_change" for t in midi.tracks for m in t) + assert [m.tempo for t in midi.tracks for m in t if m.type == "set_tempo"] == [500000] + assert [ + (m.numerator, m.denominator) + for t in midi.tracks + for m in t + if m.type == "time_signature" + ] == [(4, 4)] + active: dict[int, tuple[int, int]] = {} + tick = 0 + event_order = [] + for message in midi.tracks[1]: + tick += message.time + if message.type == "note_on" and message.velocity: + assert message.channel == 0 and message.note not in active + active[message.note] = (tick, message.velocity) + event_order.append((tick, message.note)) + elif message.type == "note_off" or ( + message.type == "note_on" and message.velocity == 0 + ): + begin, velocity = active.pop(message.note) + target = musical if message.note == 40 else switches + target.append((begin, tick, message.note, velocity)) + assert not active + assert [(n[0], n[1], n[2]) for n in musical] == [ + (begin, end, 40) for begin, end in zip(starts, ends, strict=True) + ] + assert [(n[0], n[1], n[2]) for n in switches] == [ + (starts[0], starts[0] + 30, 26), + (3520, 3550, 31), + ] + assert event_order.index((3520, 31)) < event_order.index((3520, 40)) + assert all(1 <= n[3] <= 127 for n in musical) + assert not any(n[0] == 3840 for n in musical) + native_path = Path(public["artifacts"][1]["path"]) + root = ET.fromstring(native_path.read_bytes()) + assert root.tag == "Riff" + assert (root.attrib["PPQBase"], root.attrib["Measures"], root.attrib["loopEnd"]) == ( + "480", + "2", + "3840", + ) + assert root.attrib["Time-Signature"] == "4/4" + assert root.attrib["Inst"] == "AME" and root.attrib["Key"] == "Em" + assert not any(node.tag.startswith("cc-") for node in root) + native = sorted( + [ + ( + int(n.attrib["Begin"]), + int(n.attrib["End"]), + int(n.attrib["NoteID"]), + int(n.attrib["Velocity"]), + n.attrib["Articulation"], + int(s.attrib["ID"]), + int(n.attrib["Fret"]), + ) + for s in root.findall("String") + for n in s.findall("Note") + ], + key=lambda n: n[0], + ) + assert native == [ + (begin // 2, end // 2, 40, musical[i][3], "PH" if i == len(starts) - 1 else "PM", 6, 4) + for i, (begin, end) in enumerate(zip(starts, ends, strict=True)) + ] + request = GenerateMusicRequest(description=description, basename="compare") + intent = resolve_description(request).intent + profiles = load_profile_registry().select(intent.parts, ProfileSelection()) + plan = compile_score(compose_score(intent, profiles), profiles) + readback = validate_riffer_file(native_path, plan, "lead", profiles["lead"]) + assert len(readback.notes) == len(starts) and readback.end_tick == 3840 + assert readback.notes[-1].articulation == "PH" + return { + "musical_midi": musical, + "switches": switches, + "native": native, + "artifacts": files, + "resolved": resolved, + } + + +async def exercise_phrase_stdio(client: RawStdio, outputs: Path, *, label: str) -> None: + evidence: dict[str, Any] = {} + before = sorted(outputs.iterdir()) + for name, text in ( + ("phrase-original", ORIGINAL), + ("phrase-nearby", ORIGINAL.replace("1 to 3&", "2 to 3&")), + ("phrase-overlap", ORIGINAL.replace("1 to 3&", "1 to 4")), + ("phrase-too-short", ORIGINAL + " 1 bar"), + ): + arguments: dict[str, object] = {"description": text, "basename": name} + if name != "phrase-original": + arguments["allow_midi_fallback"] = False + response = await client.request( + name, "tools/call", {"name": "generate_music", "arguments": arguments} + ) + result = response["result"] + assert len(result["content"]) == 1 + public = json.loads(result["content"][0]["text"]) + assert public == result["structuredContent"] + Draft202012Validator(tool_output_schema("generate_music")).validate(public) + if name in ("phrase-overlap", "phrase-too-short"): + assert result["isError"] and public["code"] == "UNSUPPORTED_DESCRIPTION" + assert not (outputs / name).exists() + evidence[name] = public + else: + assert not result["isError"] and public["status"] == "complete" + evidence[name] = inspect_saved(public, text, variant=name == "phrase-nearby") + assert sorted(outputs.iterdir()) == sorted( + [*before, outputs / "phrase-original", outputs / "phrase-nearby"] + ) + assert not list(outputs.glob(".riff-stage-*")) + retained = ROOT / ".test-artifacts" / "step16" / label / "phrase-original" + retained.mkdir(parents=True, exist_ok=True) + for artifact in (outputs / "phrase-original").iterdir(): + shutil.copyfile(artifact, retained / artifact.name) + (retained / "evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8") + print(f"Exact phrase {label}: " + json.dumps(evidence, sort_keys=True)) + + +@pytest.mark.anyio +async def test_original_source_stdio_and_nearby_range() -> None: + outputs = ROOT / ".test-artifacts" / f"phrase-source-{uuid.uuid4().hex}" + outputs.mkdir() + process = await asyncio.wait_for( + asyncio.create_subprocess_exec( + sys.executable, + "-I", + "-B", + "-m", + "riff_groove_builder", + "--output-dir", + str(outputs), + cwd=ROOT, + env=_environment(), + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ), + TIMEOUT, + ) + client = RawStdio(process) + try: + handshake = await client.initialize() + await exercise_phrase_stdio(client, outputs, label="source") + finally: + await client.close() + shutil.rmtree(outputs) + assert process.returncode == 0 and client.diagnostics == b"" + retained = ROOT / ".test-artifacts" / "step16" / "source" + (retained / "phrase-transport.json").write_text( + json.dumps( + { + "handshake": handshake["result"], + "exit_code": process.returncode, + "stdout_lines": len(client.lines), + "stderr": client.diagnostics.decode("utf-8"), + "original_arguments": {"description": ORIGINAL, "basename": "phrase-original"}, + }, + indent=2, + ), + encoding="utf-8", + ) diff --git a/tests/integration/test_riffer_files.py b/tests/integration/test_riffer_files.py new file mode 100644 index 0000000..fdbd986 --- /dev/null +++ b/tests/integration/test_riffer_files.py @@ -0,0 +1,92 @@ +"""Retained generated originals: native XML read-back is not plugin load acceptance.""" + +from pathlib import Path + +import pytest + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.formats.agp import validate_riffer_file, write_riffer +from riff_groove_builder.profiles import load_profile_registry +from riff_groove_builder.schemas import ( + ControlChangeEvent, + NoteOffEvent, + Part, + ProfileSelection, + Score, +) + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = pytest.mark.integration + + +@pytest.mark.parametrize("part", ["lead", "bass"]) +def test_generated_original_fixture_and_retained_native_evidence(part: Part) -> None: + identifier = "ample.ame.4.0.1.riffer.v1" if part == "lead" else "ample.amr.4.1.0.riffer.v1" + profile = load_profile_registry().select([part], ProfileSelection(**{part: identifier}))[part] + low, high = (36, 84) if part == "lead" else (35, 74) + score = Score.model_validate( + { + "intent": { + "description": "Original native fixture verification.", + "parts": [part], + "tempo_bpm": 123.5, + "bars": 1, + "time_signature": {"numerator": 4, "denominator": 4}, + "key": "C minor", + "seed": 17, + }, + "start": {"numerator": 0}, + "end": {"numerator": 4}, + "tracks": [ + { + "part": part, + "notes": [ + { + "kind": "pitched", + "part": part, + "pitch": pitch, + "start": {"numerator": start}, + "duration": {"numerator": 1}, + "intensity": intensity, + "articulation": technique, + } + for pitch, start, intensity, technique in ( + (low, 0, 0.0, "normal"), + (high, 0, 1.0, "normal"), + (low + 2, 2, 0.5, "palm_mute"), + ) + ], + } + ], + } + ) + plan = compile_score(score, {part: profile}) + for tick, value in ((0, 0), (960, 120), (2880, 0)): + plan.tracks[0].events.append( + ControlChangeEvent( + tick=tick, + part=part, + channel=profile.channel, + priority=10, + sequence=100 + tick, + controller=1, + value=value, + ) + ) + plan.tracks[0].events.sort(key=lambda e: e.ordering_key) + for event in plan.tracks[0].events: + if isinstance(event, NoteOffEvent) and event.role == "musical_note": + event.velocity = 45 + fixture = ( + ROOT / "tests" / "fixtures" / "riffer" / f"original-{part}.{profile.summary.native_format}" + ) + original = validate_riffer_file(fixture, plan, part, profile) + output = ROOT / ".test-artifacts" / "native-riffer-evidence-v1" + output.mkdir(parents=True, exist_ok=True) + path = output / fixture.name + if not path.exists(): + write_riffer(path, plan, part, profile) + saved = validate_riffer_file(path, plan, part, profile) + assert saved == original + assert path.read_bytes() == fixture.read_bytes() + assert len(saved.notes) == 3 and len(saved.cc1) == 3 diff --git a/tests/integration/test_sd3p_files.py b/tests/integration/test_sd3p_files.py new file mode 100644 index 0000000..d9c4bcc --- /dev/null +++ b/tests/integration/test_sd3p_files.py @@ -0,0 +1,60 @@ +"""Native saved-file evidence; local templates are opt-in and never redistributed.""" + +import hashlib +import os +from pathlib import Path + +import pytest + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.formats.sdp import ( + inspect_sdp_template, + parse_sdp_project, + validate_sdp_file, + write_sdp, +) +from riff_groove_builder.profiles import load_profile_registry +from riff_groove_builder.schemas import ProfileSelection, Score + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = pytest.mark.integration + + +def test_retained_generated_original_and_optional_read_only_local_template() -> None: + fixtures = ROOT / "tests" / "fixtures" / "sd3" + profile = load_profile_registry().select( + ["drums"], ProfileSelection(drums="toontrack.sd3.3.4.4.core.v1") + )["drums"] + score = Score.model_validate_json((fixtures / "original-score.json").read_bytes()) + plan = compile_score(score, {"drums": profile}) + sources = [("synthetic-original", fixtures / "original-template.sd3p")] + configured = os.environ.get("RIFF_SD3_TEMPLATE") + if configured is not None: + sources.append(("operator-local", Path(configured))) + for label, template in sources: + before = template.stat() + raw = template.read_bytes() + source = parse_sdp_project(raw) + info = inspect_sdp_template(template) + directory = ROOT / ".test-artifacts" / "native-sd3-evidence-v1" / label + directory.mkdir(parents=True, exist_ok=True) + path = directory / "original-drums.sd3p" + if not path.exists(): + write_sdp(path, plan, "drums", profile, template=template) + readback = validate_sdp_file(path, plan, "drums", profile, template=template) + output = path.read_bytes() + saved = parse_sdp_project(output) + assert len(saved.tracks) == 1 and len(readback.notes) == 3 + assert saved.non_song_bytes == source.non_song_bytes + assert template.read_bytes() == raw + after = template.stat() + assert (before.st_ino, before.st_size, before.st_mtime_ns) == ( + after.st_ino, + after.st_size, + after.st_mtime_ns, + ) + assert readback.non_song_sha256 == info.non_song_sha256 + print( + f"{label}: bytes={len(output)}, sha256={hashlib.sha256(output).hexdigest()}, " + f"source_notes_replaced={info.event_count}, saved={readback}" + ) diff --git a/tests/integration/test_sdp_capability.py b/tests/integration/test_sdp_capability.py new file mode 100644 index 0000000..549ec75 --- /dev/null +++ b/tests/integration/test_sdp_capability.py @@ -0,0 +1,231 @@ +"""Real registry/preflight/MIDI checks, not SDP serialization or SD3 acceptance.""" + +import shutil +import uuid +from collections.abc import Iterator +from dataclasses import asdict +from pathlib import Path +from unittest.mock import Mock + +import pytest +from mido import MidiFile # type: ignore[import-untyped] + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.errors import ( + DomainError, + InvalidRequestError, + NativeFormatUnavailableError, +) +from riff_groove_builder.formats.sdp import check_sdp_capability, require_sdp_capability +from riff_groove_builder.midi import validate_midi_file, write_midi +from riff_groove_builder.profiles import ( + InstrumentProfile, + InvalidProfileError, + ProfilePartMismatchError, + load_profile_registry, +) +from riff_groove_builder.schemas import GenerateMusicRequest, Part, ProfileSelection + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = pytest.mark.integration + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"sdp-capability-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +def test_checks_and_require_perform_no_output_io( + workspace: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + profile = load_profile_registry().select( + ["drums"], ProfileSelection(drums="standard.gm-drums.v1") + )["drums"] + sentinel = workspace / "existing_drums.sdp" + content = b"operator-owned sentinel; NOT an SDP fixture" + sentinel.write_bytes(content) + before = sentinel.stat() + missing_parent = workspace / "never-created" + io = Mock(side_effect=AssertionError("Capability boundary attempted filesystem IO")) + with monkeypatch.context() as guard: + for method in ( + "open", + "mkdir", + "touch", + "write_bytes", + "write_text", + "read_bytes", + "read_text", + "stat", + "rename", + "replace", + "unlink", + ): + guard.setattr(Path, method, io) + guard.setattr("builtins.open", io) + guard.setattr("os.open", io) + capability = check_sdp_capability("drums", profile) + with pytest.raises(NativeFormatUnavailableError) as caught: + require_sdp_capability("drums", profile) + io.assert_not_called() + assert asdict(capability) == { + "part": "drums", + "format": "sdp", + "available": False, + "reason": "sdp_profile_not_supported", + } + assert caught.value.details == { + "format": "sdp", + "part": "drums", + "reason": capability.reason, + } + assert not missing_parent.exists() + assert list(workspace.iterdir()) == [sentinel] + assert sentinel.read_bytes() == content + after = sentinel.stat() + assert (after.st_ino, after.st_size, after.st_mtime_ns) == ( + before.st_ino, + before.st_size, + before.st_mtime_ns, + ) + + +def test_native_preflight_leaves_empty_output(workspace: Path) -> None: + profile = load_profile_registry().select( + ["drums"], ProfileSelection(drums="standard.gm-drums.v1") + )["drums"] + with pytest.raises(NativeFormatUnavailableError): + require_sdp_capability("drums", profile) + assert list(workspace.iterdir()) == [] + + +@pytest.mark.parametrize( + ("description", "parts"), + [ + ("drums only 1 bar quarter", ["drums"]), + ("lead and bass and drums 1 bar quarter", ["lead", "bass", "drums"]), + ], +) +def test_explicit_independent_standard_midi_remains_available_without_sdp( + workspace: Path, description: str, parts: list[Part] +) -> None: + request = GenerateMusicRequest( + description=description, basename="explicit-midi", formats=["mid"] + ) + resolved = resolve_description(request) + assert resolved.intent.parts == parts + selected = load_profile_registry().select( + resolved.intent.parts, + ProfileSelection( + **{ + part: "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" + for part in parts + } + ), + ) + drums = selected["drums"] + assert drums.id == "standard.gm-drums.v1" + assert drums.summary.mapping_kind == "standard_midi" + with pytest.raises(NativeFormatUnavailableError) as caught: + require_sdp_capability("drums", drums) + assert caught.value.code == "NATIVE_FORMAT_UNAVAILABLE" + assert caught.value.details["part"] == "drums" + assert list(workspace.iterdir()) == [] + + score = compose_score(resolved.intent, selected) + plan = compile_score(score, selected) + midi = workspace / "explicit-midi.mid" + assert write_midi(midi, plan) == midi + validate_midi_file(midi, plan) + assert midi.read_bytes().startswith(b"MThd") + saved = MidiFile(midi) + assert saved.type == 1 + assert saved.ticks_per_beat == 960 + assert [track.name for track in saved.tracks] == ["Conductor"] + [p.title() for p in parts] + drum_track = saved.tracks[-1] + hits = [message for message in drum_track if message.type == "note_on"] + assert len(hits) == 8 + assert {message.note for message in hits} == {36, 38, 42} + assert {message.channel for message in hits} == {9} + assert all(1 <= message.velocity <= 127 for message in hits) + assert all(sum(message.time for message in track) == 3840 for track in saved.tracks) + assert list(workspace.iterdir()) == [midi] + assert not list(workspace.rglob("*.sdp")) + assert not list(workspace.rglob("*.agp")) + assert check_sdp_capability("drums", drums).available is False + + +@pytest.mark.parametrize( + ("case", "expected_error", "details"), + [ + ( + "lead_request", + InvalidRequestError, + {"format": "sdp", "reason": "unsupported_sdp_part"}, + ), + ( + "wrong_profile", + ProfilePartMismatchError, + {"format": "sdp", "part": "drums", "reason": "wrong_part"}, + ), + ("wrong_target", InvalidProfileError, {"reason": "invalid_profile_model"}), + ("deep_mutation", InvalidProfileError, {"reason": "invalid_profile_model"}), + ("native_flag", InvalidProfileError, {"reason": "invalid_profile_model"}), + ("unchecked_model", InvalidProfileError, {"reason": "invalid_profile_model"}), + ], +) +def test_invalid_input_is_not_fallback_and_leaves_existing_output_untouched( + workspace: Path, + monkeypatch: pytest.MonkeyPatch, + case: str, + expected_error: type[DomainError], + details: dict[str, str], +) -> None: + sentinel = workspace / "existing_drums.sdp" + sentinel.write_bytes(b"existing operator data, NOT a native fixture") + before = sentinel.stat() + registry = load_profile_registry() + profile = registry.select(["drums"], ProfileSelection(drums="standard.gm-drums.v1"))["drums"] + part: Part = "drums" + if case == "lead_request": + part = "lead" + elif case == "wrong_profile": + profile = registry.select(["bass"], ProfileSelection(bass="standard.bass.v1"))["bass"] + elif case == "wrong_target": + profile.summary.instrument = "ray" + elif case == "deep_mutation": + profile.drum_voices[0].note = 128 + elif case == "native_flag": + profile.summary.native_available = True + else: + profile = InstrumentProfile.model_construct(id="incomplete") + + io = Mock(side_effect=AssertionError("Invalid input attempted filesystem IO")) + with monkeypatch.context() as guard: + guard.setattr(Path, "open", io) + guard.setattr(Path, "mkdir", io) + guard.setattr(Path, "stat", io) + guard.setattr("builtins.open", io) + guard.setattr("os.open", io) + for boundary in (check_sdp_capability, require_sdp_capability): + with pytest.raises(expected_error) as caught: + boundary(part, profile) + assert type(caught.value) is expected_error + assert caught.value.details == details + assert caught.value.code != "NATIVE_FORMAT_UNAVAILABLE" + io.assert_not_called() + assert sentinel.read_bytes() == b"existing operator data, NOT a native fixture" + after = sentinel.stat() + assert (after.st_ino, after.st_size, after.st_mtime_ns) == ( + before.st_ino, + before.st_size, + before.st_mtime_ns, + ) + assert list(workspace.iterdir()) == [sentinel] diff --git a/tests/integration/test_stdio.py b/tests/integration/test_stdio.py new file mode 100644 index 0000000..e73909b --- /dev/null +++ b/tests/integration/test_stdio.py @@ -0,0 +1,595 @@ +"""Real installed-module processes; raw framing here is test-client code only.""" + +import asyncio +import json +import os +import shutil +import subprocess +import sys +import uuid +from collections.abc import AsyncIterator, Iterator +from datetime import timedelta +from importlib.metadata import distribution +from pathlib import Path +from typing import Any + +import anyio +import mido # type: ignore[import-untyped] +import pytest +from jsonschema import Draft202012Validator +from mcp import ClientSession, types +from mcp.client.stdio import StdioServerParameters, stdio_client +from mcp.shared.version import SUPPORTED_PROTOCOL_VERSIONS +from pydantic import JsonValue + +from riff_groove_builder import __version__ +from riff_groove_builder.schemas import ( + GenerationError, + GenerationResult, + ProfileListResult, + ToolName, + tool_input_schema, + tool_output_schema, +) + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = pytest.mark.anyio +TIMEOUT = 15 + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"stdio-{uuid.uuid4().hex}" + path.mkdir(parents=True) + (path / "outputs").mkdir() + (path / "other-cwd").mkdir() + try: + yield path + finally: + shutil.rmtree(path) + + +def _environment() -> dict[str, str]: + env = os.environ.copy() + for key in ("PYTHONPATH", "PYTHONHOME"): + env.pop(key, None) + env["PYTHONDONTWRITEBYTECODE"] = "1" + return env + + +async def test_official_client_handshake_and_both_tools(workspace: Path) -> None: + direct_url = distribution("gaj3t-musicgen-riff-groove-builder").read_text("direct_url.json") + assert direct_url is not None and json.loads(direct_url)["dir_info"]["editable"] is True + parameters = StdioServerParameters( + command=sys.executable, + args=["-I", "-B", "-m", "riff_groove_builder", "--output-dir", str(workspace / "outputs")], + cwd=workspace / "other-cwd", + env=_environment(), + ) + with (workspace / "client-stderr.log").open("w+", encoding="utf-8") as diagnostics: + with anyio.fail_after(45): + async with stdio_client(parameters, errlog=diagnostics) as (read, write): + async with ClientSession( + read, write, read_timeout_seconds=timedelta(seconds=TIMEOUT) + ) as session: + initialized = await session.initialize() + assert initialized.protocolVersion in SUPPORTED_PROTOCOL_VERSIONS + assert initialized.serverInfo.name == "riff-groove-builder" + assert initialized.serverInfo.version == __version__ + assert initialized.capabilities.tools is not None + assert initialized.capabilities.resources is None + assert initialized.capabilities.prompts is None + assert initialized.capabilities.logging is None + listed = await session.list_tools() + assert [tool.name for tool in listed.tools] == [ + "list_instrument_profiles", + "generate_music", + ] + names: tuple[ToolName, ...] = ("list_instrument_profiles", "generate_music") + for name, tool in zip(names, listed.tools, strict=True): + assert tool.inputSchema == tool_input_schema(name) + assert tool.outputSchema == tool_output_schema(name) + arguments = ( + {} + if name == "list_instrument_profiles" + else { + "description": "lead bass drums 137.5 BPM 2 bars 7/8 quarter", + "basename": "example", + } + ) + result = await session.call_tool(name, arguments) + assert result.content and isinstance(result.content[0], types.TextContent) + assert json.loads(result.content[0].text) == result.structuredContent + Draft202012Validator(tool.outputSchema).validate(result.structuredContent) + if name == "list_instrument_profiles": + assert not result.isError + profiles = ProfileListResult.model_validate(result.structuredContent) + assert len(profiles.profiles) == 6 + assert [p.native_available for p in profiles.profiles] == [ + True, + True, + False, + False, + False, + False, + ] + else: + assert not result.isError + generated = GenerationResult.model_validate(result.structuredContent) + assert generated.status == "midi_fallback" + assert generated.resolved.tempo_bpm == 137.5 + assert generated.resolved.musical_end_tick == 6720 + artifact = generated.artifacts[0] + assert artifact.fallback_for == ["drums"] + assert [a.format for a in generated.artifacts] == [ + "mid", + "griff", + "briff", + ] + path = Path(artifact.path) + assert path.parent == workspace / "outputs" / "example" + assert path.stat().st_size == artifact.size_bytes + assert path.read_bytes().startswith(b"MThd") + midi = mido.MidiFile(path) + assert midi.type == 1 and midi.ticks_per_beat == 960 + assert [track.name for track in midi.tracks] == [ + "Conductor", + "Lead", + "Bass", + "Drums", + ] + assert [sum(msg.time for msg in track) for track in midi.tracks] == [ + 6720 + ] * 4 + diagnostics.seek(0) + assert diagnostics.read() == "" + assert list((workspace / "outputs").iterdir()) == [workspace / "outputs" / "example"] + + +class RawStdio: + def __init__(self, process: asyncio.subprocess.Process) -> None: + self.process = process + self.lines: list[bytes] = [] + self.diagnostics = b"" + assert process.stderr is not None + self._stderr = asyncio.create_task(process.stderr.read()) + + async def send(self, message: dict[str, Any] | str) -> None: + assert self.process.stdin is not None + text = message if isinstance(message, str) else json.dumps(message, ensure_ascii=False) + self.process.stdin.write((text + "\n").encode("utf-8")) + await asyncio.wait_for(self.process.stdin.drain(), TIMEOUT) + + async def receive(self, timeout: float = TIMEOUT) -> dict[str, Any]: + assert self.process.stdout is not None + line = await asyncio.wait_for(self.process.stdout.readline(), timeout) + assert line, "Unexpected EOF from server" + self.lines.append(line) + assert line.endswith(b"\n") + types.JSONRPCMessage.model_validate_json(line) + result = json.loads(line.decode("utf-8")) + assert isinstance(result, dict) + return result + + async def request( + self, identifier: str | int, method: str, params: dict[str, Any] | None = None + ) -> dict[str, Any]: + message: dict[str, Any] = {"jsonrpc": "2.0", "id": identifier, "method": method} + if params is not None: + message["params"] = params + await self.send(message) + response = await self.receive() + assert response["id"] == identifier + return response + + async def initialize(self, version: str = "2025-11-25") -> dict[str, Any]: + response = await self.request( + "initialize-string-id", + "initialize", + { + "protocolVersion": version, + "capabilities": {}, + "clientInfo": {"name": "raw-test-client", "version": "0"}, + }, + ) + await self.send({"jsonrpc": "2.0", "method": "notifications/initialized"}) + assert response["result"]["serverInfo"]["version"] == __version__ + return response + + async def assert_quiet(self) -> None: + with pytest.raises(TimeoutError): + await self.receive(timeout=0.2) + + async def close(self) -> None: + if self.process.returncode is None: + assert self.process.stdin is not None + self.process.stdin.close() + try: + await asyncio.wait_for(self.process.wait(), TIMEOUT) + except BaseException: + if self.process.returncode is None: + self.process.kill() + await asyncio.wait_for(self.process.wait(), TIMEOUT) + raise + assert self.process.stdout is not None + remainder = await asyncio.wait_for(self.process.stdout.read(), TIMEOUT) + self.lines.extend(remainder.splitlines(keepends=True)) + self.diagnostics = await asyncio.wait_for(self._stderr, TIMEOUT) + for line in self.lines: + assert line.endswith(b"\n") + types.JSONRPCMessage.model_validate_json(line) + json.loads(line.decode("utf-8")) + assert self.process.returncode == 0, self.diagnostics.decode("utf-8") + + +@pytest.fixture +async def raw(workspace: Path) -> AsyncIterator[RawStdio]: + process = await asyncio.wait_for( + asyncio.create_subprocess_exec( + sys.executable, + "-I", + "-B", + "-m", + "riff_groove_builder", + "--output-dir", + str(workspace / "outputs"), + cwd=workspace / "other-cwd", + env=_environment(), + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ), + TIMEOUT, + ) + client = RawStdio(process) + try: + yield client + finally: + await client.close() + assert not list((workspace / "outputs").glob(".riff-stage-*")) + for published in (workspace / "outputs").iterdir(): + assert published.name in ("one", "midi", "native") + assert list(published.iterdir()) == [published / f"{published.name}.mid"] + assert mido.MidiFile(published / f"{published.name}.mid").type == 1 + + +async def test_raw_ids_notifications_outputs_and_eof(raw: RawStdio) -> None: + initialized = await raw.initialize() + assert initialized["result"]["protocolVersion"] in SUPPORTED_PROTOCOL_VERSIONS + await raw.assert_quiet() + listed = await raw.request(73, "tools/list") + tools = listed["result"]["tools"] + assert [tool["name"] for tool in tools] == ["list_instrument_profiles", "generate_music"] + for tool in tools: + name = tool["name"] + assert name in ("list_instrument_profiles", "generate_music") + assert tool["inputSchema"] == tool_input_schema(name) + assert tool["outputSchema"] == tool_output_schema(name) + for index, arguments in enumerate( + [ + { + "description": "lead only 1 bar quarter", + "basename": "one", + "profiles": {"lead": "standard.lead.v1"}, + }, + { + "description": "drums only 1 bar quarter", + "basename": "two", + "parts": ["drums"], + "formats": ["sdp"], + "allow_midi_fallback": False, + "time_signature": {"numerator": 7, "denominator": 8}, + "key": "Bb major", + }, + ] + ): + response = await raw.request( + f"generation-{index}", "tools/call", {"name": "generate_music", "arguments": arguments} + ) + result = response["result"] + if index == 0: + assert result["isError"] is False + generated = GenerationResult.model_validate(result["structuredContent"]) + assert generated.status == "midi_fallback" + assert Path(generated.artifacts[0].path).read_bytes().startswith(b"MThd") + else: + assert result["isError"] is True + error = GenerationError.model_validate(result["structuredContent"]) + assert error.code == "NATIVE_FORMAT_UNAVAILABLE" + assert error.details == { + "format": "sd3p", + "part": "drums", + "reason": "sdp_template_required", + } + Draft202012Validator(tool_output_schema("generate_music")).validate( + result["structuredContent"] + ) + profiles = await raw.request( + 74, "tools/call", {"name": "list_instrument_profiles", "arguments": {}} + ) + assert profiles["result"]["isError"] is False + summaries = ProfileListResult.model_validate(profiles["result"]["structuredContent"]).profiles + assert len(summaries) == 6 + Draft202012Validator(tool_output_schema("list_instrument_profiles")).validate( + profiles["result"]["structuredContent"] + ) + await raw.send( + { + "jsonrpc": "2.0", + "method": "notifications/progress", + "params": { + "progressToken": "unused", + "progress": 1, + }, + } + ) + assert (await raw.request("ping-barrier", "ping"))["result"] == {} + await raw.assert_quiet() + await raw.close() + assert raw.diagnostics == b"" + + +@pytest.mark.parametrize("version", ["2024-11-05", "unsupported-client-version"]) +async def test_sdk_negotiation(raw: RawStdio, version: str) -> None: + response = await raw.initialize(version) + negotiated = response["result"]["protocolVersion"] + assert negotiated in SUPPORTED_PROTOCOL_VERSIONS + if version in SUPPORTED_PROTOCOL_VERSIONS: + assert negotiated == version + await raw.assert_quiet() + + +async def test_real_stdio_midi_native_only_collision_and_resolved_errors(raw: RawStdio) -> None: + await raw.initialize() + for basename, formats, status, fallback in [ + ("midi", ["mid"], "complete", []), + ("native", ["agp", "sdp"], "midi_fallback", ["lead", "bass", "drums"]), + ]: + response = await raw.request( + basename, + "tools/call", + { + "name": "generate_music", + "arguments": { + "description": "lead bass drums 1 bar quarter", + "basename": basename, + "formats": formats, + "profiles": { + "lead": "standard.lead.v1", + "bass": "standard.bass.v1", + "drums": "standard.gm-drums.v1", + }, + }, + }, + ) + result = response["result"] + assert not result["isError"] + generated = GenerationResult.model_validate(result["structuredContent"]) + assert generated.status == status + artifact = generated.artifacts[0] + assert artifact.fallback_for == fallback + assert Path(artifact.path).stat().st_size == artifact.size_bytes + assert Path(artifact.path).read_bytes().startswith(b"MThd") + assert [ + warning.part + for warning in generated.warnings + if warning.code == "STANDARD_MIDI_MAPPING" + ] == ["lead", "bass", "drums"] + Draft202012Validator(tool_output_schema("generate_music")).validate( + result["structuredContent"] + ) + cases: list[tuple[dict[str, JsonValue], str]] = [ + ({"description": "drums only", "basename": "x", "formats": ["agp"]}, "INVALID_REQUEST"), + ( + { + "description": "lead only palm mute", + "basename": "x", + "profiles": {"lead": "standard.lead.v1"}, + }, + "UNSUPPORTED_ARTICULATION", + ), + ({"description": "lead only", "basename": "midi"}, "OUTPUT_EXISTS"), + ({"description": "private-description", "basename": "x"}, "UNSUPPORTED_DESCRIPTION"), + ] + for index, (arguments, code) in enumerate(cases): + response = await raw.request( + f"error-{index}", "tools/call", {"name": "generate_music", "arguments": arguments} + ) + result = response["result"] + assert result["isError"] + assert result["structuredContent"]["code"] == code + assert "private-" not in json.dumps(result) + Draft202012Validator(tool_output_schema("generate_music")).validate( + result["structuredContent"] + ) + await raw.close() + assert raw.diagnostics == b"" + + +async def test_invalid_arguments_and_unknown_tools(raw: RawStdio) -> None: + await raw.initialize() + cases: list[tuple[ToolName, dict[str, JsonValue]]] = [ + ("list_instrument_profiles", {"private-property": "secret"}), + ("generate_music", {}), + ("generate_music", {"description": "private-description", "basename": "x", "bars": 4.0}), + ( + "generate_music", + { + "description": "private-description", + "basename": "x", + "parts": ["lead"], + "formats": ["sdp"], + }, + ), + ] + for index, (name, arguments) in enumerate(cases): + response = await raw.request(index, "tools/call", {"name": name, "arguments": arguments}) + result = response["result"] + assert result["isError"] is True + assert result["structuredContent"]["code"] == "INVALID_REQUEST" + assert result["structuredContent"]["details"]["issues"] + assert "private-" not in json.dumps(response) + assert "secret" not in json.dumps(response) + Draft202012Validator(tool_output_schema(name)).validate(result["structuredContent"]) + unknown = await raw.request( + "unknown-tool", "tools/call", {"name": "private-unknown-tool", "arguments": {}} + ) + assert unknown["result"]["isError"] is True + assert "Unknown tool." in unknown["result"]["content"][0]["text"] + assert "structuredContent" not in unknown["result"] + await raw.close() + assert b"private-" not in raw.diagnostics + assert b"secret" not in raw.diagnostics + + +async def test_sdk_unknown_methods_and_invalid_request_parameters(raw: RawStdio) -> None: + await raw.initialize() + # Unknown union methods fail SDK request validation; recognized but unregistered + # methods reach SDK dispatch and receive METHOD_NOT_FOUND. + cases: list[tuple[str | int, str, dict[str, Any], int]] = [ + ("unknown-method", "private-unknown-method", {}, types.INVALID_PARAMS), + (202, "tools/call", {"arguments": {"private-property": "secret"}}, types.INVALID_PARAMS), + ( + "wrong-args-type", + "tools/call", + {"name": "generate_music", "arguments": "secret"}, + types.INVALID_PARAMS, + ), + ("unregistered", "resources/list", {}, types.METHOD_NOT_FOUND), + ] + for identifier, method, params, code in cases: + response = await raw.request(identifier, method, params) + assert response["error"]["code"] == code + assert "private-" not in json.dumps(response) + assert "secret" not in json.dumps(response) + await raw.send( + { + "jsonrpc": "2.0", + "method": "private-unknown-notification", + "params": {"private-property": "secret"}, + } + ) + await raw.assert_quiet() + assert (await raw.request("still-alive", "ping"))["result"] == {} + await raw.close() + assert b"SDK rejected invalid protocol parameters." in raw.diagnostics + assert b"private-" not in raw.diagnostics and b"secret" not in raw.diagnostics + + +@pytest.mark.parametrize( + "malformed", + [ + '{"private-description": "secret", invalid JSON', + '["private-description", "secret"]', + '{"jsonrpc":"2.0","id":7,"params":{"private-value":"secret"}}', + ], +) +async def test_sdk_malformed_input_logs_notification_then_recovers( + raw: RawStdio, malformed: str +) -> None: + await raw.initialize() + await raw.send(malformed) + notification = await raw.receive() + assert notification["method"] == "notifications/message" + assert "id" not in notification + assert notification["params"]["data"] == "Internal Server Error" + assert "private-" not in json.dumps(notification) + assert "secret" not in json.dumps(notification) + assert (await raw.request("after-malformed", "ping"))["result"] == {} + await raw.close() + assert b"SDK rejected malformed protocol input" in raw.diagnostics + assert b"private-" not in raw.diagnostics and b"secret" not in raw.diagnostics + + +async def test_sdk_null_id_is_classified_as_notification(raw: RawStdio) -> None: + await raw.initialize() + await raw.send( + {"jsonrpc": "2.0", "id": None, "method": "private-method", "params": {"value": "secret"}} + ) + await raw.assert_quiet() + assert (await raw.request("after-null-id", "ping"))["result"] == {} + await raw.close() + assert b"SDK rejected invalid protocol parameters." in raw.diagnostics + assert b"private-" not in raw.diagnostics and b"secret" not in raw.diagnostics + + +async def test_eof_without_initialization_is_clean(raw: RawStdio) -> None: + await raw.close() + assert raw.lines == [] + assert raw.diagnostics == b"" + + +@pytest.mark.parametrize("kind", ["missing", "nonexistent", "file", "uri", "unc", "device"]) +def test_bad_startup_has_no_protocol_stdout(workspace: Path, kind: str) -> None: + arguments = [sys.executable, "-I", "-B", "-m", "riff_groove_builder"] + sentinel = workspace / "sentinel" + sentinel.write_text("preserved", encoding="utf-8") + roots = { + "nonexistent": str(workspace / "does-not-exist"), + "file": str(sentinel), + "uri": "https://example.invalid/music", + "unc": r"\\server\share", + "device": r"\\.\NUL", + } + if kind != "missing": + arguments.extend(["--output-dir", roots[kind]]) + result = subprocess.run( + arguments, + cwd=workspace / "other-cwd", + env=_environment(), + input=b"", + capture_output=True, + timeout=TIMEOUT, + check=False, + ) + assert result.returncode != 0 + assert result.stdout == b"" + assert result.stderr + assert ( + b"--output-dir" in result.stderr + if kind == "missing" + else b"local directory" in result.stderr + ) + assert sentinel.read_text(encoding="utf-8") == "preserved" + assert not (workspace / "does-not-exist").exists() + assert not list((workspace / "outputs").iterdir()) + + +@pytest.mark.parametrize("kind", ["missing", "corrupt", "unsupported"]) +def test_bad_explicit_sd3_template_startup_is_visible_and_private( + workspace: Path, kind: str +) -> None: + template = workspace / "operator.sd3p" + if kind == "corrupt": + template.write_bytes(b"private-project-bytes {") + elif kind == "unsupported": + raw = (ROOT / "tests" / "fixtures" / "sd3" / "original-template.sd3p").read_bytes() + template.write_bytes(raw.replace(b"3.4.4", b"3.4.5")) + result = subprocess.run( + [ + sys.executable, + "-I", + "-B", + "-m", + "riff_groove_builder", + "--output-dir", + str(workspace / "outputs"), + "--sd3-template", + str(template), + ], + cwd=workspace / "other-cwd", + env=_environment(), + input=b"", + capture_output=True, + timeout=TIMEOUT, + check=False, + ) + assert result.returncode != 0 and result.stdout == b"" + assert (b"OUTPUT_IO_ERROR" if kind == "missing" else b"SERIALIZATION_ERROR") in result.stderr + assert b"private-project-bytes" not in result.stderr and b"Traceback" not in result.stderr + assert not list((workspace / "outputs").iterdir()) diff --git a/tests/integration/test_text_feedback.py b/tests/integration/test_text_feedback.py new file mode 100644 index 0000000..deb5631 --- /dev/null +++ b/tests/integration/test_text_feedback.py @@ -0,0 +1,217 @@ +"""Text-only recovery through real stdio, also reused by the installed wheel.""" + +import asyncio +import hashlib +import json +import shutil +import sys +import uuid +import xml.etree.ElementTree as ET +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import mido # type: ignore[import-untyped] +import pytest +from jsonschema import Draft202012Validator +from test_stdio import TIMEOUT, RawStdio, _environment + +from riff_groove_builder.schemas import ToolName, tool_output_schema + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +@pytest.fixture +def feedback_workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"text-feedback-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +async def exercise_text_feedback(client: RawStdio, outputs: Path, *, label: str) -> dict[str, Any]: + """Make recovery decisions only from decoded TextContent, never structuredContent.""" + + async def call(name: ToolName, arguments: dict[str, object]) -> dict[str, Any]: + response = await client.request( + "text-feedback", "tools/call", {"name": name, "arguments": arguments} + ) + result = response["result"] + assert len(result["content"]) == 1 and result["content"][0]["type"] == "text" + public = json.loads(result["content"][0]["text"]) + assert isinstance(public, dict) + assert public == result["structuredContent"] + assert result["isError"] == ("code" in public) + Draft202012Validator(tool_output_schema(name)).validate(public) + return public + + listed = await call("list_instrument_profiles", {}) + profiles = listed["profiles"] + lead = next( + profile for profile in profiles if profile["part"] == "lead" and profile["native_available"] + ) + assert lead["native_format"] == "griff" + before = sorted(outputs.iterdir()) + bad: dict[str, object] = { + "description": "lead only 1 bar quarter", + "basename": "text-recovered", + "parts": ["lead"], + "formats": ["sd3p", "mid"], + "key": "E minor", + "profiles": {"lead": "aggressive_rock"}, + "cc_events": [{"part": "lead", "beat": {"numerator": 0}, "controller": 91, "value": 64}], + } + wrong_format = await call("generate_music", bad) + assert wrong_format["code"] == "INVALID_REQUEST" + issue = wrong_format["details"]["issues"][0] + assert issue["field"] == "formats" and issue["reason"] == "format_parts" + assert "sd3p/sdp requires drums" in issue["correction"] + assert "Guitar lead uses griff/agp or mid" in issue["correction"] + assert "Omit formats" in issue["correction"] + assert sorted(outputs.iterdir()) == before + + # CC91 was not user-requested; remove it rather than silently generating a vendor effect. + repaired = {key: value for key, value in bad.items() if key not in ("formats", "cc_events")} + wrong_profile = await call("generate_music", repaired) + assert wrong_profile["code"] == "PROFILE_REQUIRED" + assert "list_instrument_profiles({})" in wrong_profile["message"] + assert "omit profiles for defaults" in wrong_profile["message"] + assert "aggressive_rock" not in json.dumps(wrong_profile) + assert sorted(outputs.iterdir()) == before + + unsupported = await call( + "generate_music", + {"description": "lead only detailed eighth triplet melody", "basename": "unsupported"}, + ) + assert unsupported["code"] == "UNSUPPORTED_DESCRIPTION" + assert "Arbitrary triplet patterns" in unsupported["message"] + assert sorted(outputs.iterdir()) == before + + generated = await call( + "generate_music", {**repaired, "profiles": {"lead": lead["id"]}, "key": "Em"} + ) + assert generated["status"] == "complete" + assert generated["resolved"]["key"] == "E minor" + assert generated["resolved"]["profile_ids"]["lead"] == lead["id"] + assert generated["resolved"]["musical_end_tick"] == 3840 + assert [artifact["format"] for artifact in generated["artifacts"]] == ["mid", "griff"] + assert generated["warnings"] + artifacts = [] + for artifact in generated["artifacts"]: + path = Path(artifact["path"]) + assert path.parent == outputs / "text-recovered" + data = path.read_bytes() + assert len(data) == artifact["size_bytes"] > 0 + # Step 11's independently recorded baseline remains byte-identical. + assert ( + hashlib.sha256(data).hexdigest() + == { + "mid": "922d4c30e4618b6cce61a2ecebb36193773ca3884e56db80f7c18fe18e813f26", + "griff": "213adde1c4785dccd2289e6888328c16bca720fb8d2786edb4df34f3863d1c2f", + }[artifact["format"]] + ) + assert artifact["fallback_for"] == [] + if artifact["format"] == "mid": + midi = mido.MidiFile(path) + assert midi.type == 1 and midi.ticks_per_beat == 960 + assert [track.name for track in midi.tracks] == ["Conductor", "Lead"] + assert [sum(message.time for message in track) for track in midi.tracks] == [3840, 3840] + note_ons = [ + message.note + for track in midi.tracks + for message in track + if message.type == "note_on" and message.velocity > 0 + ] + assert len(note_ons) == 5 and note_ons.count(24) == 1 + assert len([note for note in note_ons if note >= 36]) == 4 + assert not any( + message.type == "control_change" and message.control == 91 + for track in midi.tracks + for message in track + ) + else: + root = ET.fromstring(data) + assert root.tag == "Riff" and len(root.findall("./String/Note")) == 4 + assert not any(node.tag.startswith("cc-") for node in root) + artifacts.append( + { + "format": artifact["format"], + "size_bytes": len(data), + "sha256": hashlib.sha256(data).hexdigest(), + } + ) + assert sorted(outputs.iterdir()) == sorted([*before, outputs / "text-recovered"]) + assert not list(outputs.glob(".riff-stage-*")) + evidence = { + "visible_ids": [profile["id"] for profile in profiles], + "wrong_format": wrong_format, + "wrong_profile": wrong_profile, + "unsupported_code": unsupported["code"], + "recovered": { + "status": generated["status"], + "key": generated["resolved"]["key"], + "profile": generated["resolved"]["profile_ids"]["lead"], + "artifacts": artifacts, + "warning_codes": [w["code"] for w in generated["warnings"]], + "midi_note_ons": 5, + "midi_musical_note_ons": 4, + "midi_keyswitch_note_ons": 1, + "native_notes": 4, + "cc91_events": 0, + }, + } + print("Text-only recovery evidence: " + json.dumps(evidence, sort_keys=True)) + retained = ROOT / ".test-artifacts" / "step16" / label / "text-recovered" + retained.mkdir(parents=True, exist_ok=True) + for artifact in (outputs / "text-recovered").iterdir(): + shutil.copyfile(artifact, retained / artifact.name) + (retained / "evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8") + return evidence + + +@pytest.mark.anyio +async def test_real_stdio_text_only_wrong_call_to_native_midi(feedback_workspace: Path) -> None: + process = await asyncio.wait_for( + asyncio.create_subprocess_exec( + sys.executable, + "-I", + "-B", + "-m", + "riff_groove_builder", + "--output-dir", + str(feedback_workspace), + cwd=ROOT, + env=_environment(), + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ), + TIMEOUT, + ) + client = RawStdio(process) + try: + handshake = await client.initialize() + await exercise_text_feedback(client, feedback_workspace, label="source") + finally: + await client.close() + assert process.returncode == 0 and client.diagnostics == b"" + retained = ROOT / ".test-artifacts" / "step16" / "source" + (retained / "text-transport.json").write_text( + json.dumps( + { + "handshake": handshake["result"], + "exit_code": process.returncode, + "stdout_lines": len(client.lines), + "stderr": client.diagnostics.decode("utf-8"), + }, + indent=2, + ), + encoding="utf-8", + ) diff --git a/tests/integration/test_text_to_midi.py b/tests/integration/test_text_to_midi.py new file mode 100644 index 0000000..6a96e48 --- /dev/null +++ b/tests/integration/test_text_to_midi.py @@ -0,0 +1,261 @@ +"""Real standard-profile text -> intent -> score -> compiled SMF -> disk read-back.""" + +import shutil +import uuid +from collections.abc import Iterator +from fractions import Fraction +from pathlib import Path + +import mido # type: ignore[import-untyped] +import pytest + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.errors import UnsupportedArticulationError, UnsupportedDescriptionError +from riff_groove_builder.midi import validate_midi_file, write_midi +from riff_groove_builder.profiles import load_profile_registry +from riff_groove_builder.schemas import GenerateMusicRequest, Part, ProfileSelection, Score + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = pytest.mark.integration +Event = tuple[int, str, int, int, int] + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"text-midi-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +def generate(text: str, path: Path, seed: int = 0) -> Score: + request = GenerateMusicRequest(description=text, basename=path.stem, seed=seed) + resolved = resolve_description(request) + selected = load_profile_registry().select( + resolved.intent.parts, + ProfileSelection( + **{ + part: "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" + for part in resolved.intent.parts + } + ), + ) + assert all(profile.provenance.status == "standard_midi" for profile in selected.values()) + assert all(profile.summary.mapping_kind == "standard_midi" for profile in selected.values()) + assert {part: profile.id for part, profile in selected.items()} == { + part: { + "lead": "standard.lead.v1", + "bass": "standard.bass.v1", + "drums": "standard.gm-drums.v1", + }[part] + for part in resolved.intent.parts + } + score = compose_score(resolved.intent, selected) + plan = compile_score(score, selected) + assert write_midi(path, plan) == path + validate_midi_file(path, plan) + return score + + +def events(path: Path) -> list[list[Event]]: + result: list[list[Event]] = [] + for track in mido.MidiFile(path).tracks[1:]: + tick = 0 + part: list[Event] = [] + for message in track: + tick += message.time + if not message.is_meta: + assert message.type in ("note_on", "note_off") + part.append((tick, message.type, message.channel, message.note, message.velocity)) + result.append(part) + return result + + +@pytest.mark.parametrize( + ("text", "parts", "tempo", "bars", "meter", "root", "minor"), + [ + ("lead only 90 BPM 2 bars 3/4 D major quarter", ["lead"], 90, 2, (3, 4), 2, False), + ("bass only 72.5 BPM 3 bars 6/8 Bb minor eighth", ["bass"], 72.5, 3, (6, 8), 10, True), + ("drums only 155 BPM 2 bars 7/8 sixteenth", ["drums"], 155, 2, (7, 8), 4, True), + ( + "lead bass drums 137.5 BPM 4 bars 4/4 F# minor eighth", + ["lead", "bass", "drums"], + 137.5, + 4, + (4, 4), + 6, + True, + ), + ( + "no drums 111 BPM 1 bar 7/8 Eb major quarter rests", + ["lead", "bass"], + 111, + 1, + (7, 8), + 3, + False, + ), + ], +) +def test_real_disk_tempo_meter_parts_pitch_timing_and_pairing( + workspace: Path, + text: str, + parts: list[Part], + tempo: float, + bars: int, + meter: tuple[int, int], + root: int, + minor: bool, +) -> None: + path = workspace / "description.mid" + score = generate(text, path) + assert score.intent.parts == parts + midi = mido.MidiFile(path) + assert midi.type == 1 + assert midi.ticks_per_beat == 960 + assert len(midi.tracks) == len(parts) + 1 + expected_end = Fraction(bars * meter[0] * 4 * 960, meter[1]) + assert expected_end.denominator == 1 + conductor = midi.tracks[0] + assert [(msg.tempo, msg.time) for msg in conductor if msg.type == "set_tempo"] == [ + (round(60_000_000 / tempo), 0) + ] + assert [ + (msg.numerator, msg.denominator, msg.time) + for msg in conductor + if msg.type == "time_signature" + ] == [(*meter, 0)] + assert abs(midi.length - float(expected_end / 960) * round(60_000_000 / tempo) / 1e6) < 1e-9 + for track in midi.tracks: + assert sum(msg.time for msg in track) == expected_end + assert track[-1].type == "end_of_track" + scale = {0, 2, 3, 5, 7, 8, 10} if minor else {0, 2, 4, 5, 7, 9, 11} + for part, track, actual in zip(parts, midi.tracks[1:], events(path), strict=True): + assert track[0].name == part.capitalize() + channel = {"lead": 0, "bass": 1, "drums": 9}[part] + active: dict[int, int] = {} + onsets = 0 + for tick, kind, ch, pitch, velocity in actual: + assert ch == channel + assert 0 <= tick <= expected_end + if kind == "note_on": + assert pitch not in active + assert tick < expected_end and 1 <= velocity <= 127 + active[pitch] = tick + onsets += 1 + if part == "drums": + assert pitch in {36, 38, 42} # Independently known GM kick/snare/hat. + else: + assert 0 <= pitch <= 127 + assert (pitch - root) % 12 in (scale if part == "lead" else {0, 7}) + assert (58 <= pitch <= 80) if part == "lead" else (34 <= pitch <= 53) + else: + assert pitch in active and active.pop(pitch) < tick + assert not active + assert onsets > 0 + + +def test_precise_independent_bass_events(workspace: Path) -> None: + path = workspace / "bass.mid" + generate("bass only 1 bar C major quarter", path) + assert events(path) == [ + [ + (0, "note_on", 1, 36, 64), + (960, "note_off", 1, 36, 0), + (960, "note_on", 1, 43, 96), + (1920, "note_off", 1, 43, 0), + (1920, "note_on", 1, 36, 64), + (2880, "note_off", 1, 36, 0), + (2880, "note_on", 1, 43, 80), + (3840, "note_off", 1, 43, 0), + ] + ] + + +def test_precise_independent_drum_events(workspace: Path) -> None: + path = workspace / "drums.mid" + generate("drums only 1 bar quarter", path) + assert events(path) == [ + [ + (0, "note_on", 9, 36, 64), + (0, "note_on", 9, 42, 64), + (240, "note_off", 9, 36, 0), + (240, "note_off", 9, 42, 0), + (960, "note_on", 9, 38, 64), + (960, "note_on", 9, 42, 64), + (1200, "note_off", 9, 38, 0), + (1200, "note_off", 9, 42, 0), + (1920, "note_on", 9, 36, 64), + (1920, "note_on", 9, 42, 64), + (2160, "note_off", 9, 36, 0), + (2160, "note_off", 9, 42, 0), + (2880, "note_on", 9, 38, 80), + (2880, "note_on", 9, 42, 80), + (3120, "note_off", 9, 38, 0), + (3120, "note_off", 9, 42, 0), + ] + ] + + +def test_seeded_byte_determinism_and_changed_seed_content(workspace: Path) -> None: + paths = [workspace / f"seed-{index}.mid" for index in range(3)] + for path, seed in zip(paths, (123, 123, 124), strict=True): + generate("lead bass drums 2 bars 7/8 metal sixteenth", path, seed) + assert paths[0].read_bytes() == paths[1].read_bytes() + assert events(paths[0]) == events(paths[1]) + assert events(paths[0]) != events(paths[2]) + + +def test_text_changes_measurable_rhythm_and_duration(workspace: Path) -> None: + descriptions = ("quarter", "eighth", "sixteenth", "eighth rests", "eighth metal") + counts: list[list[int]] = [] + onsets: list[list[list[int]]] = [] + for index, text in enumerate(descriptions): + path = workspace / f"rhythm-{index}.mid" + generate(f"bass drums 1 bar {text}", path) + actual = events(path) + starts = [[tick for tick, kind, _, _, _ in track if kind == "note_on"] for track in actual] + onsets.append(starts) + counts.append([len(track) for track in starts]) + assert all(sum(msg.time for msg in track) == 3840 for track in mido.MidiFile(path).tracks) + assert counts == [[4, 8], [8, 12], [16, 20], [7, 11], [8, 16]] + assert onsets[0][0] == [0, 960, 1920, 2880] + assert onsets[1][0] == list(range(0, 3840, 480)) + assert onsets[2][0] == list(range(0, 3840, 240)) + assert onsets[3][0] == list(range(0, 3360, 480)) + + +def test_scalar_text_changes_survive_disk_readback(workspace: Path) -> None: + variants = ( + "bass 1 bar C major quarter", + "bass 1 bar D minor quarter", + "bass 1 bar C major quarter 90 bpm", + "bass 2 bars C major quarter", + "bass 1 bar C major quarter 3/4", + ) + paths = [workspace / f"scalar-{index}.mid" for index in range(len(variants))] + for text, path in zip(variants, paths, strict=True): + generate(text, path) + assert events(paths[0]) != events(paths[1]) # Key changes actual pitches. + assert events(paths[0]) == events(paths[2]) # Tempo changes metadata, not tick positions. + assert paths[0].read_bytes() != paths[2].read_bytes() + assert [sum(msg.time for msg in mido.MidiFile(path).tracks[0]) for path in paths] == [ + 3840, + 3840, + 3840, + 7680, + 2880, + ] + + +@pytest.mark.parametrize( + "text", ["lead palm mute", "bass palm mute", "drums palm mute", "lead slide", "guitar audio"] +) +def test_unsupported_material_fails_before_any_artifact(workspace: Path, text: str) -> None: + with pytest.raises((UnsupportedArticulationError, UnsupportedDescriptionError)): + generate(text, workspace / "must-not-exist.mid") + assert list(workspace.iterdir()) == [] diff --git a/tests/unit/test_agp.py b/tests/unit/test_agp.py new file mode 100644 index 0000000..436072e --- /dev/null +++ b/tests/unit/test_agp.py @@ -0,0 +1,233 @@ +"""AGP capability contracts only; synthetic mapping data is not a native fixture.""" + +from collections.abc import Callable +from dataclasses import FrozenInstanceError, asdict +from pathlib import Path +from typing import cast + +import pytest + +from riff_groove_builder.errors import ( + DomainError, + InvalidRequestError, + NativeFormatUnavailableError, +) +from riff_groove_builder.formats import NativeCapability +from riff_groove_builder.formats.agp import check_agp_capability, require_agp_capability +from riff_groove_builder.profiles import ( + InstrumentProfile, + InvalidProfileError, + ProfilePartMismatchError, + load_profile_registry, + parse_profile, +) +from riff_groove_builder.schemas import Part, ProfileSelection + +Boundary = Callable[[Part, InstrumentProfile], NativeCapability] +BOUNDARIES: list[Boundary] = [check_agp_capability, require_agp_capability] +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "profiles" + + +def standard(part: Part) -> InstrumentProfile: + identifier = "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" + return load_profile_registry().select([part], ProfileSelection(**{part: identifier}))[part] + + +@pytest.mark.parametrize("part", ["lead", "bass"]) +def test_standard_profiles_return_explicit_typed_unavailable(part: Part) -> None: + profile = standard(part) + before = profile.model_dump() + capability: NativeCapability = check_agp_capability(part, profile) + assert type(capability) is NativeCapability + assert asdict(capability) == { + "part": part, + "format": "agp", + "available": False, + "reason": "riffer_profile_not_supported", + } + assert profile.summary.mapping_kind == "standard_midi" + assert profile.summary.native_available is False + assert profile.model_dump() == before + assert check_agp_capability(part, profile) == capability + for field, value in ( + ("part", "drums"), + ("format", "sdp"), + ("available", True), + ("reason", "forged"), + ): + with pytest.raises(FrozenInstanceError): + setattr(capability, field, value) + + +@pytest.mark.parametrize("part", ["lead", "bass"]) +def test_instrument_mapping_does_not_establish_a_codec(part: Part) -> None: + profile = parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) + assert profile.summary.mapping_kind == "instrument" + capability = check_agp_capability(part, profile) + assert capability.available is False + assert capability.reason == "riffer_profile_not_supported" + assert profile.provenance.status == "test_only" + + +@pytest.mark.parametrize("part", ["lead", "bass"]) +@pytest.mark.parametrize("boundary", BOUNDARIES) +def test_native_metadata_alone_cannot_enable_instrument_support( + part: Part, boundary: Boundary +) -> None: + profile = parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) + profile.summary.native_available = True + with pytest.raises(InvalidProfileError) as caught: + boundary(part, profile) + assert caught.value.details == {"reason": "invalid_profile_model"} + + +def test_mapping_attestation_and_product_version_are_not_native_evidence() -> None: + data = parse_profile((FIXTURES / "synthetic-lead.json").read_bytes()).model_dump() + data["id"] = data["summary"]["id"] = "harness.mapping.only" + data["summary"]["product_name"] = "TEST HARNESS mapping attestation, NOT vendor evidence" + data["summary"]["product_version"] = data["provenance"]["product_version"] = "unknown-build" + data["provenance"]["status"] = "verified" + data["provenance"]["sources"] = [ + { + "kind": "lawful_local", + "reference": "TEST-HARNESS-NOT-VENDOR-EVIDENCE", + "aspects": [ + "identity", + "range_or_voices", + "channels", + "actions", + "state_reset", + "timing", + "velocity", + ], + } + ] + profile = InstrumentProfile.model_validate(data) + assert check_agp_capability("lead", profile).available is False + with pytest.raises(NativeFormatUnavailableError) as caught: + require_agp_capability("lead", profile) + assert caught.value.details["reason"] == "riffer_profile_not_supported" + + +@pytest.mark.parametrize("part", ["lead", "bass"]) +def test_require_raises_named_error_with_safe_complete_context(part: Part) -> None: + with pytest.raises(NativeFormatUnavailableError) as caught: + require_agp_capability(part, standard(part)) + assert caught.value.code == "NATIVE_FORMAT_UNAVAILABLE" + assert caught.value.details == { + "format": "agp", + "part": part, + "reason": "riffer_profile_not_supported", + } + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +@pytest.mark.parametrize("invalid", ["drums", "ray", "LEAD", "", None, 1, True, [], {}]) +def test_invalid_parts_are_bad_requests_not_unavailable( + boundary: Boundary, invalid: object +) -> None: + with pytest.raises(InvalidRequestError) as caught: + boundary(cast(Part, invalid), standard("lead")) + assert caught.value.code == "INVALID_REQUEST" + assert caught.value.details == {"format": "agp", "reason": "unsupported_agp_part"} + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +@pytest.mark.parametrize( + ("part", "profile_part"), + [("lead", "bass"), ("bass", "lead"), ("lead", "drums"), ("bass", "drums")], +) +def test_valid_wrong_part_profiles_are_selection_errors( + boundary: Boundary, part: Part, profile_part: Part +) -> None: + with pytest.raises(ProfilePartMismatchError) as caught: + boundary(part, standard(profile_part)) + assert caught.value.code == "PROFILE_REQUIRED" + assert caught.value.details == {"format": "agp", "part": part, "reason": "wrong_part"} + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +@pytest.mark.parametrize( + "mutation", + [ + "instrument", + "part", + "format", + "native_flag", + "channel", + "range", + "aliases", + "provenance", + "schema", + "unchecked_copy", + "unchecked_construct", + ], +) +def test_mutated_profiles_are_invalid_not_native_unavailable( + boundary: Boundary, mutation: str +) -> None: + profile = standard("lead") + if mutation == "instrument": + profile.summary.instrument = "ray" + elif mutation == "part": + profile.summary.part = "bass" + elif mutation == "format": + profile.summary.native_format = "sd3p" + elif mutation == "native_flag": + profile.summary.native_available = True + elif mutation == "channel": + profile.channel = 128 + elif mutation == "range": + assert profile.playable_range is not None + profile.playable_range.low = 128 + elif mutation == "aliases": + profile.articulations[0].aliases.append("slide") + elif mutation == "provenance": + profile.provenance.sources.clear() + elif mutation == "schema": + profile = profile.model_copy(update={"schema_version": "unknown-private-value"}) + elif mutation == "unchecked_copy": + profile = profile.model_copy(update={"channel": "private-invalid-value"}) + else: + profile = InstrumentProfile.model_construct(id="private-incomplete-profile") + with pytest.raises(InvalidProfileError) as caught: + boundary("lead", profile) + assert caught.value.code == "SERIALIZATION_ERROR" + assert caught.value.details == {"reason": "invalid_profile_model"} + assert "private" not in str(caught.value) + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +@pytest.mark.parametrize("invalid", [None, {}, "not a profile"]) +def test_wrong_profile_model_type_is_corrupted_input(boundary: Boundary, invalid: object) -> None: + with pytest.raises(InvalidProfileError) as caught: + boundary("lead", cast(InstrumentProfile, invalid)) + assert caught.value.code == "SERIALIZATION_ERROR" + + +def test_mutating_a_profile_after_check_cannot_authorize_require() -> None: + profile = standard("lead") + capability = check_agp_capability("lead", profile) + profile.summary.native_available = True + with pytest.raises(InvalidProfileError): + require_agp_capability("lead", profile) + assert capability.available is False + + +def test_unexpected_validation_errors_are_not_fallback( + monkeypatch: pytest.MonkeyPatch, +) -> None: + profile = standard("lead") + + def broken_check(profile: InstrumentProfile) -> InstrumentProfile: + raise RuntimeError("test-only unexpected programming failure") + + monkeypatch.setattr("riff_groove_builder.formats.agp.checked_profile", broken_check) + with pytest.raises(RuntimeError): + require_agp_capability("lead", profile) + + +def test_invalid_request_takes_precedence_over_invalid_profile() -> None: + with pytest.raises(DomainError) as caught: + require_agp_capability("drums", cast(InstrumentProfile, None)) + assert type(caught.value) is InvalidRequestError diff --git a/tests/unit/test_articulations.py b/tests/unit/test_articulations.py new file mode 100644 index 0000000..40a87d0 --- /dev/null +++ b/tests/unit/test_articulations.py @@ -0,0 +1,529 @@ +"""Synthetic compiler tests; numbers here are not vendor instrument mappings.""" + +from fractions import Fraction +from pathlib import Path +from typing import Literal + +import pytest + +from riff_groove_builder.articulations import ArticulationCompileError, compile_score +from riff_groove_builder.errors import SerializationError, UnsupportedArticulationError +from riff_groove_builder.midi import validate_event_plan +from riff_groove_builder.profiles import ( + CCAction, + InstrumentProfile, + InvalidProfileError, + KeyswitchAction, + parse_profile, +) +from riff_groove_builder.schemas import ( + ControlChangeEvent, + DrumNote, + EventPlan, + MusicalIntent, + NoteOffEvent, + NoteOnEvent, + Part, + PitchedNote, + PositiveBeat, + RationalBeat, + Score, + ScoreTrack, + TimeSignature, +) + +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "profiles" + + +def profile(part: Part = "lead") -> InstrumentProfile: + return parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) + + +def beat(value: Fraction | int) -> RationalBeat: + value = Fraction(value) + return RationalBeat(numerator=value.numerator, denominator=value.denominator) + + +def note( + start: Fraction | int = 0, + duration: Fraction | int = 1, + *, + pitch: int = 60, + art: str = "normal", + intensity: float = 0.5, + part: Literal["lead", "bass"] = "lead", +) -> PitchedNote: + return PitchedNote( + part=part, + pitch=pitch, + articulation=art, + intensity=intensity, + start=beat(start), + duration=PositiveBeat.model_validate(beat(duration).model_dump()), + ) + + +def score(notes: list[PitchedNote], *, origin: Fraction | int = 0) -> Score: + part: Part = notes[0].part if notes else "lead" + return Score( + intent=MusicalIntent( + description="SYNTHETIC compiler test", + parts=[part], + tempo_bpm=120, + bars=1, + time_signature=TimeSignature(numerator=4, denominator=4), + key="C major", + seed=0, + ), + start=beat(origin), + end=beat(Fraction(origin) + 4), + tracks=[ScoreTrack(part=part, notes=[*notes])], + ) + + +def controls(plan: EventPlan) -> list[tuple[int, str, int, int]]: + return [ + ( + e.tick, + e.kind, + e.controller if isinstance(e, ControlChangeEvent) else e.note, + e.value if isinstance(e, ControlChangeEvent) else e.velocity, + ) + for e in plan.tracks[0].events + if isinstance(e, ControlChangeEvent) or e.role == "keyswitch" + ] + + +def test_combined_latched_dedup_polyphony_and_restore() -> None: + source = score( + [ + note(0, 1, art="Palm Mute", intensity=0), + note(Fraction(1, 2), 1, pitch=64, art="pm", intensity=1), + note(2, 1, art="normal"), + note(3, 1, art="sustain"), + ] + ) + plan = compile_score(source, {"lead": profile()}) + assert (plan.musical_start_tick, plan.musical_end_tick, plan.end_tick) == (120, 3960, 3960) + assert controls(plan) == [ + (0, "note_on", 2, 64), + (0, "control_change", 20, 64), + (60, "note_off", 2, 0), + (1920, "note_on", 1, 64), + (1920, "control_change", 20, 0), + (1980, "note_off", 1, 0), + ] + assert [ + e.velocity + for e in plan.tracks[0].events + if isinstance(e, NoteOnEvent) and e.role == "musical_note" + ] == [30, 100, 64, 64] + assert source.tracks[0].notes[0].articulation == "Palm Mute" + validate_event_plan(plan) + + +@pytest.mark.parametrize("mechanism", ["keyswitch", "cc", "velocity"]) +def test_individual_action_mechanisms(mechanism: str) -> None: + selected = profile() + for art in selected.articulations: + art.actions = [a for a in art.actions if a.kind == mechanism] + plan = compile_score(score([note(art="pm")]), {"lead": selected}) + assert plan.musical_start_tick == (0 if mechanism == "velocity" else 120) + observed = controls(plan) + if mechanism == "keyswitch": + assert observed == [(0, "note_on", 2, 64), (60, "note_off", 2, 0)] + elif mechanism == "cc": + assert observed == [(0, "control_change", 20, 64)] + else: + assert observed == [] + + +def test_momentary_reference_counted_hold_and_resets() -> None: + source = score( + [ + note(0, 1, pitch=40, art="slide", part="bass"), + note(Fraction(1, 2), 1, pitch=43, art="legato slide", part="bass"), + ] + ) + plan = compile_score(source, {"bass": profile("bass")}) + # Normal is explicitly established before the first momentary control. + assert plan.musical_start_tick == 180 + assert controls(plan) == [ + (0, "note_on", 3, 60), + (0, "control_change", 21, 0), + (60, "note_off", 3, 0), + (60, "note_on", 4, 60), + (60, "control_change", 21, 90), + (540, "control_change", 21, 90), + (1680, "note_off", 4, 0), + (1680, "control_change", 21, 0), + (1680, "note_on", 3, 60), + (1680, "control_change", 21, 0), + (1740, "note_off", 3, 0), + ] + assert not any( + e.tick == 1140 and isinstance(e, NoteOffEvent) and e.note == 4 + for e in plan.tracks[0].events + ) + + +def test_momentary_pulse_preserves_per_note_retrigger() -> None: + plan = compile_score( + score( + [ + note(0, 1, pitch=40, art="trigger", part="bass"), + note(Fraction(1, 2), 1, pitch=43, art="trigger", part="bass"), + ] + ), + {"bass": profile("bass")}, + ) + pulses = [e.tick for e in plan.tracks[0].events if isinstance(e, NoteOnEvent) and e.note == 5] + assert pulses == [60, 540] + assert ( + len( + [ + e + for e in plan.tracks[0].events + if isinstance(e, ControlChangeEvent) and e.value == 70 + ] + ) + == 2 + ) + + +def test_overlapping_physical_switch_retriggers_rejected() -> None: + with pytest.raises(SerializationError) as error: + compile_score( + score( + [ + note(0, 1, pitch=40, art="trigger", part="bass"), + note(Fraction(1, 32), 1, pitch=43, art="trigger", part="bass"), + ] + ), + {"bass": profile("bass")}, + ) + assert error.value.details["reason"] == "same_pitch_overlap" + + +def test_exact_physical_switch_boundary_retrigger_is_preserved() -> None: + plan = compile_score( + score( + [ + note(0, 1, pitch=40, art="trigger", part="bass"), + note(Fraction(1, 16), 1, pitch=43, art="trigger", part="bass"), + ] + ), + {"bass": profile("bass")}, + ) + at_boundary = [ + (e.kind, e.note) + for e in plan.tracks[0].events + if isinstance(e, NoteOnEvent | NoteOffEvent) and e.tick == 120 and e.note == 5 + ] + assert at_boundary == [("note_off", 5), ("note_on", 5)] + validate_event_plan(plan) + + +def test_boundary_retrigger_causal_order() -> None: + selected = profile() + for art in selected.articulations: + for action in art.actions: + action.lead = beat(0) + plan = compile_score(score([note(0, 1, art="pm"), note(1, 1)]), {"lead": selected}) + at_boundary = [e for e in plan.tracks[0].events if e.tick == 960] + assert [(e.kind, e.role) for e in at_boundary] == [ + ("note_off", "musical_note"), + ("note_on", "keyswitch"), + ("control_change", "articulation_control"), + ("note_on", "musical_note"), + ] + validate_event_plan(plan) + + +def test_boundary_momentary_reset_then_normal_actions_then_onset() -> None: + selected = profile("drums") + source = Score( + intent=MusicalIntent( + description="SYNTHETIC drums", + parts=["drums"], + tempo_bpm=120, + bars=1, + time_signature=TimeSignature(numerator=4, denominator=4), + key="C major", + seed=0, + ), + start=beat(0), + end=beat(4), + tracks=[ + ScoreTrack( + part="drums", + notes=[ + DrumNote( + part="drums", + start=beat(0), + duration=PositiveBeat(numerator=1), + intensity=1, + articulation="accent", + voice="low", + ), + DrumNote( + part="drums", + start=beat(1), + duration=PositiveBeat(numerator=1), + intensity=0, + articulation="normal", + voice="low", + ), + ], + ) + ], + ) + for action in selected.articulations[1].actions: + action.release_offset = beat(0) + plan = compile_score(source, {"drums": selected}) + assert [ + (e.kind, e.value if isinstance(e, ControlChangeEvent) else e.note) + for e in plan.tracks[0].events + if e.tick == 960 + ] == [ + ("note_off", 36), + ("control_change", 0), + ("control_change", 0), + ("note_on", 36), + ] + + +@pytest.mark.parametrize( + ("notes", "reason"), + [ + ([note(0, 2), note(1, 1, pitch=64, art="pm")], "incompatible_articulation_overlap"), + ([note(0, 1), note(1, 1, art="pm")], "control_lead_overlaps_active_notes"), + ], +) +def test_incompatible_state_and_lead(notes: list[PitchedNote], reason: str) -> None: + with pytest.raises(ArticulationCompileError) as error: + compile_score(score(notes), {"lead": profile()}) + assert error.value.details == {"reason": reason} + + +def test_momentary_tail_cannot_corrupt_following_note() -> None: + with pytest.raises(ArticulationCompileError) as error: + compile_score( + score( + [ + note(0, 1, pitch=40, art="slide", part="bass"), + note(1, 1, pitch=43, art="normal", part="bass"), + ] + ), + {"bass": profile("bass")}, + ) + assert error.value.details["reason"] == "restoration_overlaps_next_note" + + +def test_normal_initialization_requires_gap_after_other_latched_state() -> None: + selected = profile("bass") + # Introduce another fully explicit latched state for this synthetic case. + other = selected.articulations[0].model_copy(deep=True) + other.name, other.aliases = "other", [] + switch = other.actions[0] + assert isinstance(switch, KeyswitchAction) + switch.note = 6 + selected.articulations.append(other) + selected.summary.supported_articulations.append("other") + with pytest.raises(ArticulationCompileError) as error: + compile_score( + score( + [ + note(0, 1, pitch=40, art="other", part="bass"), + note(Fraction(9, 8), 1, pitch=43, art="slide", part="bass"), + ] + ), + {"bass": selected}, + ) + assert error.value.details["reason"] == "normal_setup_overlaps_active_notes" + + +def test_nonzero_origin_not_extra_preroll_and_empty_track() -> None: + plan = compile_score(score([note(2, 1, art="pm")], origin=2), {"lead": profile()}) + assert plan.musical_start_tick == 120 + assert plan.musical_end_tick == 3960 + empty = compile_score(score([], origin=7), {"lead": profile()}) + assert empty.musical_start_tick == 0 and empty.end_tick == 3840 + assert empty.tracks[0].events == [] + + +@pytest.mark.parametrize("field", ["lead", "gate", "release_offset"]) +def test_all_profile_timing_must_be_on_grid_even_unused(field: str) -> None: + selected = profile("bass") + switch = selected.articulations[1].actions[0] + assert isinstance(switch, KeyswitchAction) + setattr(switch, field, PositiveBeat(numerator=1, denominator=7)) + with pytest.raises(SerializationError) as error: + compile_score(score([note(part="bass", pitch=40)]), {"bass": selected}) + assert error.value.details["reason"] == "off_grid_beats" + + +def test_score_grid_and_ppq_rejection() -> None: + for source in [ + score([note(0, Fraction(1, 7))]), + score([note(Fraction(1, 7), 1)]), + ]: + with pytest.raises(SerializationError): + compile_score(source, {"lead": profile()}) + for ppq in [0, 32768, True]: + with pytest.raises(SerializationError): + compile_score(score([note()]), {"lead": profile()}, ppq=ppq) + assert compile_score(score([note()]), {"lead": profile()}, ppq=480).musical_start_tick == 60 + + +@pytest.mark.parametrize("pitch", [47, 85]) +def test_playable_range_rejection(pitch: int) -> None: + with pytest.raises(ArticulationCompileError) as error: + compile_score(score([note(pitch=pitch)]), {"lead": profile()}) + assert error.value.details["reason"] == "pitch_outside_profile_range" + + +@pytest.mark.parametrize("pitch", [48, 84]) +def test_playable_range_endpoints(pitch: int) -> None: + assert compile_score(score([note(pitch=pitch)]), {"lead": profile()}) + + +def test_missing_unsupported_mutated_and_wrong_part_content() -> None: + with pytest.raises(UnsupportedArticulationError) as error: + compile_score(score([note(art="private unsupported text")]), {"lead": profile()}) + assert "private" not in str(error.value.details) + with pytest.raises(ArticulationCompileError): + compile_score(score([note()]), {}) + with pytest.raises(ArticulationCompileError): + compile_score(score([note()]), {"lead": profile("bass")}) + selected = profile() + selected.playable_range = None + with pytest.raises(InvalidProfileError): + compile_score(score([note()]), {"lead": selected}) + source = score([note()]) + source.tracks[0].notes[0].intensity = float("nan") + with pytest.raises(ArticulationCompileError): + compile_score(source, {"lead": profile()}) + + +def test_no_silent_same_pitch_polyphony_merge() -> None: + with pytest.raises(SerializationError) as error: + compile_score(score([note(0, 2), note(1, 1)]), {"lead": profile()}) + assert error.value.details["reason"] == "same_pitch_overlap" + + +def test_deterministic_note_order_and_no_input_mutation() -> None: + source = score([note(1, 1, pitch=64, art="pm"), note(0, 1, art="pm")]) + selected = profile() + before = source.model_dump_json(), selected.model_dump_json() + plan = compile_score(source, {"lead": selected}) + assert plan == compile_score(source, {"lead": selected}) + source.tracks[0].notes.reverse() + reverse = compile_score(source, {"lead": selected}) + assert reverse.tracks == plan.tracks + source.tracks[0].notes.reverse() + assert (source.model_dump_json(), selected.model_dump_json()) == before + + +def test_hold_gate_rejects_short_notes_without_clamping() -> None: + selected = profile("bass") + hold = selected.articulations[1].actions[0] + assert isinstance(hold, KeyswitchAction) + hold.gate = PositiveBeat(numerator=2) + with pytest.raises(ArticulationCompileError) as error: + compile_score(score([note(0, 1, art="slide", part="bass", pitch=40)]), {"bass": selected}) + assert error.value.details["reason"] == "hold_shorter_than_declared_gate" + + +def test_event_budget_boundary_and_overflow() -> None: + selected = profile() + for art in selected.articulations: + art.actions = [] + # 50,000 positive-duration adjacent notes: exactly 100,000 events. + source = score([note(Fraction(index, 12500), Fraction(1, 12500)) for index in range(50_000)]) + # 25,000 PPQ makes each note exactly two ticks. + plan = compile_score(source, {"lead": selected}, ppq=25000) + assert len(plan.tracks[0].events) == 100_000 + source.tracks[0].notes.append(note(0, Fraction(1, 12500), pitch=64)) + with pytest.raises(ArticulationCompileError) as error: + compile_score(source, {"lead": selected}, ppq=25000) + assert error.value.details["reason"] == "event_budget_exceeded" + + +def test_compiler_calls_reviewed_validator(monkeypatch: pytest.MonkeyPatch) -> None: + def reject(_: EventPlan) -> None: + raise SerializationError(details={"reason": "validator_probe"}) + + monkeypatch.setattr("riff_groove_builder.articulations.validate_event_plan", reject) + with pytest.raises(SerializationError) as error: + compile_score(score([note()]), {"lead": profile()}) + assert error.value.details["reason"] == "validator_probe" + + +def test_release_tail_and_exact_common_end() -> None: + plan = compile_score( + score([note(3, 1, part="bass", art="slide", pitch=40)]), {"bass": profile("bass")} + ) + assert plan.musical_start_tick == 0 + assert plan.musical_end_tick == 3840 + assert plan.end_tick == 3960 + assert controls(plan)[-1] == (3960, "note_off", 3, 0) + + +def test_cc_only_velocity_only_polyphony_without_control_state() -> None: + selected = profile() + for art in selected.articulations: + art.actions = [] + plan = compile_score( + score( + [ + note(0, 2), + note(1, 1, pitch=64, art="pm"), + ] + ), + {"lead": selected}, + ) + assert controls(plan) == [] + assert len(plan.tracks[0].events) == 4 + + +def test_release_reset_offset_is_explicit() -> None: + selected = profile("bass") + action = selected.articulations[1].actions[1] + assert isinstance(action, CCAction) + action.release_offset = beat(Fraction(1, 4)) + plan = compile_score( + score([note(3, 1, part="bass", art="slide", pitch=40)]), {"bass": selected} + ) + assert plan.end_tick == 4140 + + +def test_control_tail_can_extend_after_musical_end_for_latched_pulse() -> None: + selected = profile() + for art in selected.articulations: + for action in art.actions: + action.lead = beat(0) + if isinstance(action, KeyswitchAction): + action.gate = PositiveBeat(numerator=2) + plan = compile_score(score([note(3, 1, art="pm")]), {"lead": selected}) + assert plan.musical_start_tick == 0 + assert plan.musical_end_tick == 3840 and plan.end_tick == 4800 + + +def test_normal_restoration_leads_add_exact_tail() -> None: + selected = profile("bass") + for action in selected.articulations[0].actions: + action.lead = beat(Fraction(1, 8)) + plan = compile_score( + score([note(3, 1, part="bass", pitch=40, art="slide")]), {"bass": selected} + ) + # The reset is at 3900; normal starts there and is ready 120 ticks later. + # EOT includes readiness at 4020, not only the last physical release at 3960. + assert plan.musical_end_tick == 3840 + assert plan.end_tick == 4020 + + +def test_fractional_origin_is_not_an_absolute_tick_requirement() -> None: + origin = Fraction(1, 7) + plan = compile_score(score([note(origin, 1, art="pm")], origin=origin), {"lead": profile()}) + assert plan.musical_start_tick == 120 diff --git a/tests/unit/test_cc_controls.py b/tests/unit/test_cc_controls.py new file mode 100644 index 0000000..a2ab122 --- /dev/null +++ b/tests/unit/test_cc_controls.py @@ -0,0 +1,247 @@ +"""Strict explicit CC requests and exact application; no vendor-effect inference.""" + +from fractions import Fraction + +import pytest +from jsonschema import Draft202012Validator +from pydantic import ValidationError +from test_articulations import note, profile, score + +from riff_groove_builder.articulations import apply_scheduled_controls, compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.errors import InvalidRequestError, SerializationError +from riff_groove_builder.formats.sdp import preflight_sdp +from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry +from riff_groove_builder.schemas import ( + MAX_SCHEDULED_EVENTS, + ControlChangeEvent, + GenerateMusicRequest, + NoteOffEvent, + NoteOnEvent, + Part, + ProfileSelection, + RationalBeat, + ScheduledControl, + tool_input_schema, +) + + +def point(**updates: object) -> ScheduledControl: + return ScheduledControl.model_validate( + {"part": "lead", "beat": {"numerator": 0}, "controller": 1, "value": 73, **updates} + ) + + +def request(**updates: object) -> GenerateMusicRequest: + return GenerateMusicRequest.model_validate( + {"description": "lead only 1 bar quarter", "basename": "controls", **updates} + ) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("part", "guitar"), + ("part", None), + ("beat", 0.5), + ("beat", "1/2"), + ("beat", {"numerator": True}), + ("beat", {"numerator": 1.0}), + ("beat", {"numerator": -1}), + ("beat", {"numerator": 1, "denominator": 0}), + ("beat", {"numerator": 1, "denominator": False}), + ("beat", {"numerator": 1, "extra": 2}), + ("controller", True), + ("controller", 1.0), + ("controller", "1"), + ("controller", -1), + ("controller", 128), + ("controller", None), + ("value", False), + ("value", 1.0), + ("value", "1"), + ("value", -1), + ("value", 128), + ("value", None), + ("filename", "unsafe"), + ("code", "unsafe"), + ], +) +def test_strict_item(field: str, value: object) -> None: + with pytest.raises(ValidationError): + point(**{field: value}) + + +def test_schema_optional_empty_normalized_and_boundaries() -> None: + assert request().cc_events == request(cc_events=[]).cc_events == [] + invalid_values: list[object] = [None, {}, "cc", True] + for invalid in invalid_values: + with pytest.raises(ValidationError): + request(cc_events=invalid) + controls = [ + point(beat={"numerator": 2, "denominator": 6}, controller=0, value=127), + point(controller=127, value=0), + ] + model = request(cc_events=[cc.model_dump() for cc in controls]) + assert model.cc_events[0].beat.value == Fraction(1, 3) + assert model.cc_events[0].beat.model_dump() == {"numerator": 1, "denominator": 3} + schema = tool_input_schema("generate_music") + Draft202012Validator.check_schema(schema) + Draft202012Validator(schema).validate(model.model_dump(mode="json")) + assert "cc_events" not in schema["required"] + assert schema["properties"]["cc_events"]["maxItems"] == MAX_SCHEDULED_EVENTS + assert schema["$defs"]["ScheduledControl"]["additionalProperties"] is False + assert set(schema["$defs"]["ScheduledControl"]["required"]) == { + "part", + "beat", + "controller", + "value", + } + assert GenerateMusicRequest.model_validate_json(model.model_dump_json()) == model + + +def test_duplicates_part_grid_and_input_budget() -> None: + for controls in ( + [point().model_dump(), point(value=0).model_dump()], + [ + point(beat={"numerator": 1, "denominator": 2}).model_dump(), + point(beat={"numerator": 2, "denominator": 4}).model_dump(), + ], + [point(part="bass").model_dump()], + [point(beat={"numerator": 1, "denominator": 7}).model_dump()], + [point().model_dump()] * (MAX_SCHEDULED_EVENTS + 1), + ): + with pytest.raises(ValidationError): + request(parts=["lead"], cc_events=controls) + + +def test_exact_offset_order_multiple_controllers_reset_and_unchanged_events() -> None: + selected: dict[Part, InstrumentProfile] = {"lead": profile()} + base = compile_score(score([note(7, art="pm")], origin=7), selected) + assert base.musical_start_tick == 120 + controls = [ + point(), + point(controller=74, value=127), + point(beat={"numerator": 1, "denominator": 3}, value=91), + point(beat={"numerator": 4}, value=0), + ] + changed = apply_scheduled_controls(base, controls, selected) + original = [e.model_dump() for e in base.tracks[0].events] + assert [ + e.model_dump() for e in changed.tracks[0].events if e.sequence < len(original) + ] == original + added = [e for e in changed.tracks[0].events if e.sequence >= len(original)] + assert [ + (e.tick, e.channel, e.controller, e.value) + for e in added + if isinstance(e, ControlChangeEvent) + ] == [ + (120, selected["lead"].channel, 1, 73), + (120, selected["lead"].channel, 74, 127), + (440, selected["lead"].channel, 1, 91), + (3960, selected["lead"].channel, 1, 0), + ] + assert len({e.ordering_key for e in changed.tracks[0].events}) == len(original) + 4 + at_start = [e for e in changed.tracks[0].events if e.tick == 120] + assert [e.kind for e in at_start] == ["control_change", "control_change", "note_on"] + assert changed.score == base.score + assert (changed.musical_start_tick, changed.musical_end_tick, changed.end_tick) == ( + base.musical_start_tick, + base.musical_end_tick, + base.end_tick, + ) + assert apply_scheduled_controls(base, [], selected) is base + no_reset = apply_scheduled_controls(base, [point()], selected) + assert len(no_reset.tracks[0].events) == len(original) + 1 + + +def test_conflict_even_identical_value_is_actionable() -> None: + selected: dict[Part, InstrumentProfile] = {"lead": profile()} + for action in selected["lead"].articulations[0].actions: + if action.kind == "cc": + action.lead = RationalBeat(numerator=0) + base = compile_score(score([note(art="normal")]), selected) + existing = next(e for e in base.tracks[0].events if isinstance(e, ControlChangeEvent)) + assert existing.tick == base.musical_start_tick + with pytest.raises(InvalidRequestError) as failure: + apply_scheduled_controls( + base, [point(controller=existing.controller, value=existing.value)], selected + ) + assert failure.value.details == { + "field": "cc_events", + "reason": "articulation_control_conflict", + "part": "lead", + "tick": existing.tick, + "controller": existing.controller, + "action": "Remove or move this CC point; the articulation owns it.", + } + + +@pytest.mark.parametrize( + ("cc", "reason"), + [ + (point(part="drums"), "unselected_part"), + (point(beat={"numerator": 5}), "beat_after_musical_end"), + (point(beat={"numerator": 1, "denominator": 7}), "off_grid_beats"), + ], +) +def test_application_validation(cc: ScheduledControl, reason: str) -> None: + selected: dict[Part, InstrumentProfile] = {"lead": profile()} + base = compile_score(score([note()]), selected) + with pytest.raises(InvalidRequestError) as failure: + apply_scheduled_controls(base, [cc], selected) + assert failure.value.details["reason"] == reason + with pytest.raises(InvalidRequestError, match="Correct"): + apply_scheduled_controls(base, [point(), point(value=0)], selected) + + +def test_real_combined_100000_event_budget() -> None: + selected: dict[Part, InstrumentProfile] = {"lead": profile()} + source = score([note()]) + source.intent.bars = 256 + source.end = RationalBeat(numerator=1024) + base = compile_score(source, selected) + # Exactly 100,000 explicit points are individually allowed, but notes/switches count too. + controls = [ + point(beat={"numerator": tick, "denominator": 960}) for tick in range(MAX_SCHEDULED_EVENTS) + ] + with pytest.raises(InvalidRequestError) as failure: + apply_scheduled_controls(base, controls, selected) + assert failure.value.details["reason"] == "event_budget_exceeded" + remaining = MAX_SCHEDULED_EVENTS - sum(len(t.events) for t in base.tracks) + assert len(apply_scheduled_controls(base, controls[:remaining], selected).tracks[0].events) == ( + MAX_SCHEDULED_EVENTS + ) + + +@pytest.mark.parametrize("corruption", ["none", "channel", "note", "role", "release"]) +def test_sd3_precise_controller_limit_does_not_mask_corruption(corruption: str) -> None: + req = request(description="drums only 1 bar") + intent = resolve_description(req).intent + selected = load_profile_registry().select(intent.parts, req.profiles or ProfileSelection()) + plan = apply_scheduled_controls( + compile_score(compose_score(intent, selected), selected), [point(part="drums")], selected + ) + if corruption == "channel": + for e in plan.tracks[0].events: + e.channel = 8 + elif corruption == "note": + for e in plan.tracks[0].events: + if isinstance(e, NoteOnEvent | NoteOffEvent): + e.note += 1 + elif corruption == "role": + for e in plan.tracks[0].events: + if isinstance(e, NoteOnEvent | NoteOffEvent): + e.role = "keyswitch" + elif corruption == "release": + next(e for e in plan.tracks[0].events if isinstance(e, NoteOffEvent)).velocity = 1 + with pytest.raises(SerializationError) as failure: + preflight_sdp(plan, "drums", selected["drums"]) + assert failure.value.details["reason"] == ( + "sd3_native_controller_not_supported" + if corruption == "none" + else "score_event_plan_mismatch" + if corruption == "note" + else "unsupported_sd3_event_semantics" + ) diff --git a/tests/unit/test_compose.py b/tests/unit/test_compose.py new file mode 100644 index 0000000..89e1997 --- /dev/null +++ b/tests/unit/test_compose.py @@ -0,0 +1,266 @@ +"""Exact timeline, profile facts, local randomness, and bounded resource tests.""" + +from fractions import Fraction +from pathlib import Path +from random import getstate + +import pytest + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.compose import CompositionError, compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.errors import SerializationError, UnsupportedArticulationError +from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry, parse_profile +from riff_groove_builder.schemas import ( + DrumNote, + GenerateMusicRequest, + MusicalIntent, + Part, + PitchedNote, + ProfileSelection, +) + + +def intent(text: str = "music", seed: int = 0) -> MusicalIntent: + return resolve_description( + GenerateMusicRequest(description=text, basename="compose", seed=seed) + ).intent + + +def profiles(value: MusicalIntent) -> dict[Part, InstrumentProfile]: + return load_profile_registry().select( + value.parts, + ProfileSelection( + **{ + part: "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" + for part in value.parts + } + ), + ) + + +@pytest.mark.parametrize("meter", ["3/4", "6/8", "7/8", "1/16", "16/1"]) +@pytest.mark.parametrize("rhythm", ["quarter", "eighth", "sixteenth"]) +def test_exact_meter_end_bar_truncation_and_no_overlap(meter: str, rhythm: str) -> None: + value = intent(f"lead bass drums 3 bars in {meter} {rhythm}") + selected = profiles(value) + score = compose_score(value, selected) + assert score.start.value == 0 + assert score.end.value == value.duration_beats + for track in score.tracks: + previous: dict[int | str, Fraction] = {} + for note in track.notes: + end = note.start.value + note.duration.value + assert end <= value.duration_beats + bar_index = note.start.value // value.time_signature.beats_per_bar + assert end <= (bar_index + 1) * value.time_signature.beats_per_bar + pitch = note.pitch if isinstance(note, PitchedNote) else note.voice + assert note.start.value >= previous.get(pitch, Fraction(0)) + previous[pitch] = end + plan = compile_score(score, selected) + assert plan.musical_start_tick == 0 + assert plan.musical_end_tick == plan.end_tick == value.duration_beats * 960 + + +@pytest.mark.parametrize("text", ["lead", "bass", "drums", "music"]) +def test_seed_reproducibility_variation_and_global_state(text: str) -> None: + value = intent(text) + selected = profiles(value) + state = getstate() + score = compose_score(value, selected) + assert score == compose_score(value, selected) + assert state == getstate() + changed = compose_score(intent(text, seed=10), selected) + assert score.tracks != changed.tracks + assert state == getstate() + + +@pytest.mark.parametrize("key", ["C major", "F# minor", "Bb major", "Eb minor", "Cb major"]) +def test_independent_scale_classes_and_registers(key: str) -> None: + value = intent(f"lead bass 4 bars {key}") + score = compose_score(value, profiles(value)) + roots = {"C": 0, "F#": 6, "A#": 10, "D#": 3, "B": 11} + name, mode = value.key.split() + root = roots[name] + scale = {0, 2, 4, 5, 7, 9, 11} if mode == "major" else {0, 2, 3, 5, 7, 8, 10} + for track in score.tracks: + for note in track.notes: + assert isinstance(note, PitchedNote) + assert (note.pitch - root) % 12 in scale + if track.part == "bass": + assert (note.pitch - root) % 12 in {0, 7} + assert 34 <= note.pitch <= 53 + else: + assert 58 <= note.pitch <= 80 + + +def test_requested_subdivision_rests_and_template_change_real_notes() -> None: + values = [ + intent(f"bass drums 1 bar {term}") + for term in ("quarter", "eighth", "sixteenth", "eighth rests", "eighth metal") + ] + scores = [compose_score(value, profiles(value)) for value in values] + assert [len(score.tracks[0].notes) for score in scores] == [4, 8, 16, 7, 8] + assert [len(score.tracks[1].notes) for score in scores] == [8, 12, 20, 11, 16] + assert scores[1].tracks[0].notes != scores[4].tracks[0].notes + assert all(score.end.value == 4 for score in scores) + assert all( + note.start.value < Fraction(7, 2) for track in scores[3].tracks for note in track.notes + ) + + +def test_partial_slot_and_all_rest_bar_policy() -> None: + value = intent("bass 1 bar in 7/8 quarter") + notes = compose_score(value, profiles(value)).tracks[0].notes + assert [note.duration.value for note in notes] == [1, 1, 1, Fraction(1, 2)] + value = intent("music 2 bars 1/16 quarter rests") + score = compose_score(value, profiles(value)) + assert all(track.notes == [] for track in score.tracks) + assert compile_score(score, profiles(value)).end_tick == 480 + + +@pytest.mark.parametrize("technique", ["normal", "sustain"]) +def test_standard_supported_techniques(technique: str) -> None: + value = intent(f"lead bass drums {technique}") + score = compose_score(value, profiles(value)) + assert {note.articulation for track in score.tracks for note in track.notes} == {"normal"} + assert compile_score(score, profiles(value)).musical_start_tick == 0 + + +@pytest.mark.parametrize("part", ["lead", "bass", "drums"]) +def test_standard_palm_mute_fails_without_approximation(part: str) -> None: + value = intent(f"{part} palm mute") + with pytest.raises(UnsupportedArticulationError) as caught: + compose_score(value, profiles(value)) + assert caught.value.details["technique"] == "palm_mute" + assert caught.value.details["part"] == part + + +def test_synthetic_switch_profile_uses_real_compiler_not_vendor_claims() -> None: + path = Path(__file__).resolve().parents[1] / "fixtures" / "profiles" / "synthetic-lead.json" + profile = parse_profile(path.read_bytes()) + value = intent("lead palm mute 1 bar quarter") + score = compose_score(value, {"lead": profile}) + plan = compile_score(score, {"lead": profile}) + assert profile.provenance.status == "test_only" + assert any(event.role == "keyswitch" for event in plan.tracks[0].events) + assert plan.musical_start_tick > 0 + + +@pytest.mark.parametrize(("part", "low", "high"), [("lead", 0, 10), ("bass", 100, 105)]) +def test_narrow_maps_fail_instead_of_clamping(part: Part, low: int, high: int) -> None: + value = intent(f"{part} C major") + selected = profiles(value) + data = selected[part].model_dump() + data["playable_range"] = {"low": low, "high": high} + selected[part] = InstrumentProfile.model_validate(data) + with pytest.raises(CompositionError, match="intent cannot be composed") as caught: + compose_score(value, selected) + assert caught.value.details["reason"] == "range_cannot_fit_root_fifth_or_complete_lead_scale" + + +def test_nonpreferred_but_viable_range_is_respected() -> None: + value = intent("lead C major") + selected = profiles(value) + data = selected["lead"].model_dump() + data["playable_range"] = {"low": 84, "high": 95} + selected["lead"] = InstrumentProfile.model_validate(data) + score = compose_score(value, selected) + assert all( + isinstance(note, PitchedNote) and 84 <= note.pitch <= 95 for note in score.tracks[0].notes + ) + + +def test_drum_alias_required_and_physical_notes_never_guessed() -> None: + value = intent("drums") + selected = profiles(value) + data = selected["drums"].model_dump() + for voice in data["drum_voices"]: + if "snare" in voice["aliases"]: + voice["aliases"].remove("snare") + selected["drums"] = InstrumentProfile.model_validate(data) + with pytest.raises(CompositionError) as caught: + compose_score(value, selected) + assert caught.value.details["voice"] == "snare" + data = profiles(value)["drums"].model_dump() + for voice in data["drum_voices"]: + voice["note"] += 1 + selected["drums"] = InstrumentProfile.model_validate(data) + score = compose_score(value, selected) + assert {note.voice for note in score.tracks[0].notes if isinstance(note, DrumNote)} == { + "kick", + "snare", + "closed_hat", + } + plan = compile_score(score, selected) + assert {event.note for event in plan.tracks[0].events if hasattr(event, "note")} == {37, 39, 43} + + +def test_unrepresentable_grid_fails_without_rounding() -> None: + value = intent("lead eighth") + with pytest.raises(SerializationError) as caught: + compose_score(value, profiles(value), ppq=3) + assert caught.value.details["reason"] == "off_grid_beats" + compose_score(intent("bass quarter"), profiles(intent("bass")), ppq=3) + + +def test_event_budget_precedes_note_construction(monkeypatch: pytest.MonkeyPatch) -> None: + value = intent("lead bass drums 256 bars in 16/1 sixteenth") + + def forbidden(*args: object, **kwargs: object) -> None: + pytest.fail("note allocation must not begin") + + monkeypatch.setattr("riff_groove_builder.compose.PitchedNote", forbidden) + monkeypatch.setattr("riff_groove_builder.compose.DrumNote", forbidden) + with pytest.raises(CompositionError) as caught: + compose_score(value, profiles(value)) + assert caught.value.details["reason"] == "note_pair_event_budget_exceeded" + + +@pytest.mark.parametrize("terms", [["swing"], ["quarter", "eighth"], ["rests", "no_rests"]]) +def test_direct_intent_cannot_smuggle_unsupported_rhythm(terms: list[str]) -> None: + value = intent("lead") + value.rhythm_terms = terms + with pytest.raises(CompositionError): + compose_score(value, profiles(value)) + + +def test_direct_intent_technique_and_profile_validation() -> None: + value = intent("lead") + with pytest.raises(CompositionError): + compose_score(value, {}) + value.techniques = ["normal", "slide"] + with pytest.raises(UnsupportedArticulationError): + compose_score(value, profiles(value)) + value.bars = 0 + with pytest.raises(CompositionError): + compose_score(value, profiles(intent("lead"))) + + +def test_structured_part_order_and_unrelated_part_seed_independence() -> None: + request = GenerateMusicRequest( + description="music", basename="order", parts=["drums", "bass", "lead"], seed=77 + ) + value = resolve_description(request).intent + score = compose_score(value, profiles(value)) + assert [track.part for track in score.tracks] == ["drums", "bass", "lead"] + for track in score.tracks: + solo = intent(track.part, seed=77) + assert compose_score(solo, profiles(solo)).tracks[0].notes == track.notes + + +def test_wrong_part_shared_channel_and_mutated_profile_rejected() -> None: + value = intent("lead bass") + selected = profiles(value) + with pytest.raises(CompositionError) as caught: + compose_score(value, {"lead": selected["bass"], "bass": selected["lead"]}) + assert caught.value.details["reason"] == "profile_part_mismatch" + selected["bass"].channel = selected["lead"].channel + with pytest.raises(CompositionError) as caught: + compose_score(value, selected) + assert caught.value.details["reason"] == "shared_channel" + selected = profiles(value) + assert selected["lead"].playable_range is not None + selected["lead"].playable_range.low = 128 + with pytest.raises(SerializationError): + compose_score(value, selected) diff --git a/tests/unit/test_description.py b/tests/unit/test_description.py new file mode 100644 index 0000000..536891e --- /dev/null +++ b/tests/unit/test_description.py @@ -0,0 +1,308 @@ +"""Closed grammar, scalar resolution, disclosure, and refusal tests.""" + +import pytest +from pydantic import ValidationError + +from riff_groove_builder.description import ( + DescriptionConflictError, + resolve_description, +) +from riff_groove_builder.errors import InvalidRequestError, UnsupportedDescriptionError +from riff_groove_builder.schemas import GenerateMusicRequest, Part + + +def request(description: str, **kwargs: object) -> GenerateMusicRequest: + return GenerateMusicRequest.model_validate( + {"description": description, "basename": "description", **kwargs} + ) + + +def test_defaults_and_disclosures() -> None: + resolved = resolve_description(request("Please create simple music.")) + intent = resolved.intent + assert intent.parts == ["lead", "bass", "drums"] + assert (intent.tempo_bpm, intent.bars, intent.key, intent.seed) == (120, 4, "E minor", 0) + assert intent.time_signature.model_dump() == {"numerator": 4, "denominator": 4} + assert intent.rhythm_terms == ["eighth", "rock", "no_rests"] + assert intent.techniques == ["normal"] + assert len(resolved.assumptions) == 9 + assert resolved.overrides == [] + assert {line.split(":")[0] for line in resolved.assumptions} == { + "tempo_bpm", + "bars", + "key", + "time_signature", + "parts", + "subdivision", + "template", + "rests", + "technique", + } + + +def test_text_case_spacing_and_enharmonic_normalization() -> None: + resolved = resolve_description( + request( + " GENERATE\tGUITAR, bass AND DRUMS at 137.5 BPM, 3 bars in 7 / 8, " + "bB MAJOR, straight sixteenth-notes with rests, metal, SUSTAIN! " + ) + ) + intent = resolved.intent + assert intent.parts == ["lead", "bass", "drums"] + assert (intent.tempo_bpm, intent.bars, intent.key) == (137.5, 3, "A# major") + assert intent.time_signature.model_dump() == {"numerator": 7, "denominator": 8} + assert intent.rhythm_terms == ["sixteenth", "metal", "rests"] + assert intent.techniques == ["normal"] + assert not resolved.assumptions + + +@pytest.mark.parametrize( + ("text", "parts"), + [ + ("lead", ["lead"]), + ("guitar only", ["lead"]), + ("riff", ["lead"]), + ("bass riff", ["bass"]), + ("bass groove", ["bass"]), + ("drum groove", ["drums"]), + ("bass guitar", ["bass"]), + ("bass guitar riff", ["bass"]), + ("bass guitar groove only", ["bass"]), + ("only bass and drums", ["bass", "drums"]), + ("drums, lead guitar and bass", ["lead", "bass", "drums"]), + ("lead and bass only, without drums", ["lead", "bass"]), + ("no drums", ["lead", "bass"]), + ("without bass and drums", ["lead"]), + ("exclude lead, bass", ["drums"]), + ("lead, no drums", ["lead"]), + ("bass + guitar", ["lead", "bass"]), + ], +) +def test_part_selection(text: str, parts: list[Part]) -> None: + assert resolve_description(request(text)).intent.parts == parts + + +@pytest.mark.parametrize( + "text", + ["lead no lead", "bass only, lead", "only bass and only drums", "no lead, bass and drums"], +) +def test_conflicting_or_empty_part_selections(text: str) -> None: + with pytest.raises(UnsupportedDescriptionError): + resolve_description(request(text)) + + +@pytest.mark.parametrize( + ("text", "field"), + [ + ("120 BPM and 121 BPM", "tempo_bpm"), + ("slow fast", "tempo_bpm"), + ("fast 120 bpm", "tempo_bpm"), + ("4 bars 3 bars", "bars"), + ("in 4/4 and 7/8", "time_signature"), + ("E minor C major", "key"), + ("quarter eighth", "subdivision"), + ("rock metal", "template"), + ("rests no rests", "rests"), + ("normal palm mute", "technique"), + ], +) +def test_conflicts_have_actionable_fields(text: str, field: str) -> None: + with pytest.raises(DescriptionConflictError) as caught: + resolve_description(request(text)) + assert caught.value.details == {"reason": "contradictory_text", "field": field} + + +def test_repeated_equivalent_values_are_not_conflicts() -> None: + resolved = resolve_description( + request("120 BPM 120.0 bpm 4 bars 4 bars 4/4 4/4 Bb major A# major lead normal sustain") + ) + assert resolved.intent.key == "A# major" + assert resolved.intent.parts == ["lead"] + + +def test_all_structured_overrides_win_even_over_contradictory_text() -> None: + resolved = resolve_description( + request( + "120 bpm 140 bpm slow 4 bars 2 bars 4/4 7/8 E minor C major lead no lead bass only", + tempo_bpm=90.5, + bars=6, + time_signature={"numerator": 3, "denominator": 4}, + key="Db major", + parts=["drums", "bass"], + seed=123, + ) + ) + intent = resolved.intent + assert (intent.tempo_bpm, intent.bars, intent.key, intent.seed) == (90.5, 6, "C# major", 123) + assert intent.parts == ["drums", "bass"] + assert intent.time_signature.numerator == 3 + assert len(resolved.overrides) == 5 + assert all("structured" in record and "text" in record for record in resolved.overrides) + assert len(resolved.assumptions) == 4 + assert resolved == resolve_description( + request( + "120 bpm 140 bpm slow 4 bars 2 bars 4/4 7/8 E minor C major lead no lead bass only", + tempo_bpm=90.5, + bars=6, + time_signature={"numerator": 3, "denominator": 4}, + key="Db major", + parts=["drums", "bass"], + seed=123, + ) + ) + + +@pytest.mark.parametrize(("text", "tempo"), [("slow riff", 80), ("fast rock", 160)]) +def test_qualitative_tempo_is_a_fixed_policy(text: str, tempo: int) -> None: + assert resolve_description(request(text)).intent.tempo_bpm == tempo + + +@pytest.mark.parametrize( + "text", + [ + "piano", + "violin", + "keyboard", + "leader", + "bassoon", + "drumstick", + "leadership", + "C dorian", + "A harmonic minor", + "E blues", + "F# lydian", + "lead swing", + "lead triplets", + "lead polyrhythm", + "guitar 3 against 4", + "lead audio", + "lead wav", + "record guitar", + "lead hammer on", + "guitar legato", + "bass slap", + "lead slide", + "guitar bend", + "guitar vibrato", + "guitar tremolo", + "no palm mute lead", + "not drums", + "lead without distortion", + "lead chorus", + "lead 120 bpm then 140 bpm", + "lead tempo changes 120 bpm", + "lead 120 bpm to 140 bpm", + "accelerando guitar", + "lead slow down", + "please", + "!!!", + "lead 1/2 bars", + "lead 120/2 bpm", + "lead 120e2 bpm", + "lead 4.0.0 bars", + "lead 4//4", + "lead 4/4/4", + "lead 4/4bars", + "lead eclips", + "bass ray", + "drums sd3", + "lead E minor with piano", + ], +) +def test_unknown_material_never_disappears(text: str) -> None: + with pytest.raises(UnsupportedDescriptionError): + resolve_description(request(text)) + + +@pytest.mark.parametrize( + "text", + [ + "lead 19 bpm", + "lead 301 bpm", + "lead -120 bpm", + "lead 0 bpm", + "lead 0 bars", + "lead 257 bars", + "lead -1 bars", + "lead 1.5 bars", + "lead 0/4", + "lead 17/4", + "lead 4/3", + "lead 4/0", + "lead 3/32", + ], +) +def test_text_bounds_are_named_errors(text: str) -> None: + with pytest.raises(UnsupportedDescriptionError): + resolve_description(request(text)) + + +@pytest.mark.parametrize( + "text", + [ + "20 bpm 1 bar 1/16 C major", + "300 bpm 256 bars 16/1 Cb minor", + "+120.25 bpm 2 bars 6/8 F# minor", + ], +) +def test_text_boundaries(text: str) -> None: + resolve_description(request(text)) + + +@pytest.mark.parametrize("text", ["", " ", "x" * 4001]) +def test_invalid_descriptions_fail_existing_contract(text: str) -> None: + with pytest.raises(ValidationError): + request(text) + + +def test_mutated_request_revalidated() -> None: + value = request("lead") + value.description = "" + with pytest.raises(InvalidRequestError): + resolve_description(value) + + +def test_overrides_do_not_authorize_unknown_material_or_tempo_changes() -> None: + for text in ("piano", "C dorian", "120 bpm then 140 bpm"): + with pytest.raises(UnsupportedDescriptionError): + resolve_description(request(text, tempo_bpm=120, key="E minor", parts=["lead"])) + + +def test_palm_mute_canonical_phrase_is_retained_for_profile_validation() -> None: + for text in ("palm mute guitar", "palm-muted bass", "palm muted riff"): + assert resolve_description(request(text)).intent.techniques == ["palm_mute"] + + +def test_extreme_numeric_text_is_bounded_without_float_overflow() -> None: + with pytest.raises(UnsupportedDescriptionError): + resolve_description(request("9" * 3500 + " BPM")) + assert resolve_description(request("9" * 3500 + " BPM", tempo_bpm=120)).intent.tempo_bpm == 120 + + +def test_structured_override_without_text_is_disclosed_not_an_assumption() -> None: + resolved = resolve_description( + request( + "music", + parts=["bass"], + tempo_bpm=20, + bars=256, + time_signature={"numerator": 1, "denominator": 16}, + key="Cb minor", + ) + ) + assert len(resolved.overrides) == 5 + assert len(resolved.assumptions) == 4 + + +def test_structured_override_can_replace_out_of_bounds_scalar_text() -> None: + resolved = resolve_description( + request( + "lead 999 bpm 999 bars in 99/3", + tempo_bpm=120, + bars=4, + time_signature={"numerator": 4, "denominator": 4}, + ) + ) + assert resolved.intent.tempo_bpm == 120 + assert resolved.intent.bars == 4 + assert resolved.intent.time_signature.numerator == 4 diff --git a/tests/unit/test_errors.py b/tests/unit/test_errors.py new file mode 100644 index 0000000..f5634ca --- /dev/null +++ b/tests/unit/test_errors.py @@ -0,0 +1,88 @@ +"""Stable, deliberately public failure information.""" + +import json +import math + +import pytest +from pydantic import ValidationError + +from riff_groove_builder.errors import ( + DomainError, + InvalidRequestError, + NativeFormatUnavailableError, + OutputExistsError, + OutputIOError, + ProfileNotFoundError, + ProfileRequiredError, + SerializationError, + UnsupportedArticulationError, + UnsupportedDescriptionError, +) +from riff_groove_builder.schemas import GenerationError + + +@pytest.mark.parametrize( + ("error_type", "code", "action"), + [ + (InvalidRequestError, "INVALID_REQUEST", "Correct"), + (UnsupportedDescriptionError, "UNSUPPORTED_DESCRIPTION", "supported"), + (ProfileRequiredError, "PROFILE_REQUIRED", "Select"), + (ProfileNotFoundError, "PROFILE_REQUIRED", "list profiles"), + (UnsupportedArticulationError, "UNSUPPORTED_ARTICULATION", "Choose"), + (NativeFormatUnavailableError, "NATIVE_FORMAT_UNAVAILABLE", "fallback"), + (OutputExistsError, "OUTPUT_EXISTS", "basename"), + (OutputIOError, "OUTPUT_IO_ERROR", "permissions"), + (SerializationError, "SERIALIZATION_ERROR", "profile"), + ], +) +def test_stable_public_domain_errors(error_type: type[DomainError], code: str, action: str) -> None: + error = error_type(details={"part": "lead", "choices": ["synthetic-only"]}) + assert isinstance(error, DomainError) + assert error.code == code + assert action in str(error) + result = GenerationError.from_domain(error) + assert result.code == code + assert result.details == {"part": "lead", "choices": ["synthetic-only"]} + assert GenerationError.model_validate_json(result.model_dump_json()) == result + + +def test_private_exception_cause_is_never_automatically_exposed() -> None: + try: + try: + raise OSError(r"C:\private\licensed-content: confidential") + except OSError as cause: + raise OutputIOError(details={"operation": "publish"}) from cause + except OutputIOError as error: + payload = GenerationError.from_domain(error).model_dump_json() + assert "private" not in payload + assert "confidential" not in payload + assert "Traceback" not in payload + assert json.loads(payload)["details"] == {"operation": "publish"} + assert InvalidRequestError().details == {} + + +@pytest.mark.parametrize("value", [math.nan, math.inf, -math.inf]) +def test_error_details_require_finite_json(value: float) -> None: + with pytest.raises(ValidationError): + InvalidRequestError(details={"value": value}) + with pytest.raises(ValidationError): + GenerationError( + code="INVALID_REQUEST", message="Correct the field.", details={"value": value} + ) + + +@pytest.mark.parametrize( + "updates", + [ + {"code": "UNEXPECTED"}, + {"message": ""}, + {"message": " "}, + {"details": []}, + {"traceback": "private"}, + ], +) +def test_malformed_public_errors(updates: dict[str, object]) -> None: + with pytest.raises(ValidationError): + GenerationError.model_validate( + {"code": "INVALID_REQUEST", "message": "Correct the field.", "details": {}, **updates} + ) diff --git a/tests/unit/test_explicit_plan.py b/tests/unit/test_explicit_plan.py new file mode 100644 index 0000000..c0852a4 --- /dev/null +++ b/tests/unit/test_explicit_plan.py @@ -0,0 +1,212 @@ +"""Reusable polyphonic attack plans, exact timing, strict bounds and compiler budgets.""" + +from fractions import Fraction +from typing import Literal + +import pytest +from pydantic import ValidationError + +from riff_groove_builder.articulations import ArticulationCompileError, compile_score +from riff_groove_builder.compose import CompositionError, compose_score +from riff_groove_builder.errors import SerializationError, UnsupportedArticulationError +from riff_groove_builder.profiles import load_profile_registry +from riff_groove_builder.schemas import ( + ExplicitAttack, + ExplicitAttackPlan, + MusicalIntent, + PitchedNote, + PositiveBeat, + ProfileSelection, + RationalBeat, + TimeSignature, +) + + +def attack( + pitches: list[int], + start: Fraction = Fraction(0), + duration: Fraction = Fraction(1), + technique: Literal["normal", "palm_mute", "pinch_harmonic"] = "normal", + intensity: float | None = None, +) -> ExplicitAttack: + return ExplicitAttack( + pitches=pitches, + start=RationalBeat(numerator=start.numerator, denominator=start.denominator), + duration=PositiveBeat(numerator=duration.numerator, denominator=duration.denominator), + technique=technique, + intensity=intensity, + ) + + +def intent_for(attacks: list[ExplicitAttack]) -> MusicalIntent: + return MusicalIntent( + description="Original explicit polyphonic plan; no public text parsing.", + parts=["lead"], + tempo_bpm=120, + bars=1, + time_signature=TimeSignature(numerator=4, denominator=4), + key="D minor", + seed=0, + explicit_plan=ExplicitAttackPlan( + part="lead", duration=PositiveBeat(numerator=4), attacks=attacks + ), + ) + + +def test_polyphonic_exact_plan_sustains_and_silence() -> None: + intent = intent_for( + [ + attack([60, 64, 67], duration=Fraction(4, 3), intensity=0.25), + attack([71], start=Fraction(1, 3), duration=Fraction(2, 3)), + attack([47, 64, 67, 71], start=Fraction(2), technique="palm_mute"), + attack([66], start=Fraction(3), technique="pinch_harmonic"), + ] + ) + assert MusicalIntent.model_validate_json(intent.model_dump_json()) == intent + profiles = load_profile_registry().select(["lead"], ProfileSelection()) + score = compose_score(intent, profiles) + assert score == compose_score(intent, profiles) + notes = score.tracks[0].notes + assert len(notes) == 9 + assert [n.pitch for n in notes if isinstance(n, PitchedNote)] == [ + 60, + 64, + 67, + 71, + 47, + 64, + 67, + 71, + 66, + ] + assert [n.intensity for n in notes[:3]] == [0.25] * 3 + assert len({n.intensity for n in notes[4:8]}) == 1 + assert notes[3].start.value == Fraction(1, 3) + assert notes[0].duration.value == Fraction(4, 3) + assert score.end.value == 4 + assert [n.articulation for n in notes] == ["normal"] * 4 + ["palm_mute"] * 4 + [ + "pinch_harmonic" + ] + assert compile_score(score, profiles).musical_end_tick == 3840 + assert score != compose_score(intent.model_copy(update={"seed": 8}), profiles) + + +@pytest.mark.parametrize( + "data", + [ + {"pitches": []}, + {"pitches": [60, 60]}, + {"pitches": [60, True]}, + {"pitches": [60.0]}, + {"pitches": ["60"]}, + {"pitches": [-1]}, + {"pitches": [128]}, + {"duration": {"numerator": 0}}, + {"start": {"numerator": -1}}, + {"technique": "slide"}, + {"intensity": float("nan")}, + {"intensity": 1.1}, + {"continuation": True}, + {"rest": True}, + ], +) +def test_strict_attack(data: dict[str, object]) -> None: + values = attack([60]).model_dump() + values.update(data) + with pytest.raises(ValidationError): + ExplicitAttack.model_validate(values) + + +@pytest.mark.parametrize( + "attacks", + [ + [], + [attack([60]), attack([60], Fraction(1, 2))], + [attack([60, 64]), attack([64, 67], Fraction(1, 2))], + [attack([60], Fraction(1)), attack([62])], + [attack([60], Fraction(4))], + [attack([60], duration=Fraction(5))], + [attack([60]), attack([62], Fraction(1, 2), technique="palm_mute")], + ], +) +def test_invalid_timelines(attacks: list[ExplicitAttack]) -> None: + with pytest.raises(ValidationError): + intent_for(attacks) + + +def test_half_open_adjacent_repeated_pitches_and_disjoint_polyphony() -> None: + intent_for([attack([60]), attack([60], Fraction(1))]) + intent_for([attack([60]), attack([62], Fraction(1, 2))]) + intent_for([attack([60]), attack([62])]) + with pytest.raises(ValidationError): + ExplicitAttackPlan( + part="lead", duration=PositiveBeat(numerator=16385), attacks=[attack([60])] + ) + + +@pytest.mark.parametrize( + "update", + [ + {"parts": ["bass"]}, + {"parts": ["lead", "bass"]}, + {"rhythm_terms": ["quarter"]}, + {"techniques": ["normal"]}, + {"bars": 1, "time_signature": {"numerator": 1, "denominator": 4}}, + ], +) +def test_intent_coverage_and_globals(update: dict[str, object]) -> None: + data = intent_for([attack([60])]).model_dump() + data.update(update) + with pytest.raises(ValidationError): + MusicalIntent.model_validate(data) + + +def test_legacy_and_explicit_plans_cannot_compete() -> None: + data = intent_for([attack([60])]).model_dump() + data["phrase_plan"] = { + "part": "lead", + "duration": {"numerator": 4}, + "notes": [{"start": {"numerator": 0}, "duration": {"numerator": 1}, "technique": "normal"}], + } + with pytest.raises(ValidationError): + MusicalIntent.model_validate(data) + + +@pytest.mark.parametrize("pitches", [[35], [60, 64, 85]]) +def test_no_hidden_transpose_or_dropped_out_of_map_tone(pitches: list[int]) -> None: + intent = intent_for([attack(pitches)]) + profiles = load_profile_registry().select(["lead"], ProfileSelection()) + with pytest.raises(CompositionError, match="composed safely"): + compose_score(intent, profiles) + + +def test_exact_grid_and_profile_technique_are_required() -> None: + profiles = load_profile_registry().select(["lead"], ProfileSelection()) + with pytest.raises(SerializationError): + compose_score(intent_for([attack([60], duration=Fraction(1, 7))]), profiles) + standard = load_profile_registry().select(["lead"], ProfileSelection(lead="standard.lead.v1")) + with pytest.raises(UnsupportedArticulationError): + compose_score(intent_for([attack([60], technique="palm_mute")]), standard) + + +def test_expanded_tones_and_controls_share_budget(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("riff_groove_builder.schemas.MAX_SCHEDULED_EVENTS", 12) + monkeypatch.setattr("riff_groove_builder.articulations.MAX_SCHEDULED_EVENTS", 12) + intent = intent_for([attack([60, 64, 67]), attack([62, 66, 69], Fraction(1))]) + standard = load_profile_registry().select(["lead"], ProfileSelection(lead="standard.lead.v1")) + assert len(compose_score(intent, standard).tracks[0].notes) == 6 + native = load_profile_registry().select(["lead"], ProfileSelection()) + with pytest.raises(ArticulationCompileError) as caught: + compose_score(intent, native) + assert caught.value.details["reason"] == "event_budget_exceeded" + with pytest.raises(ValidationError, match="Expanded chord"): + intent_for([attack([60, 64, 67]), attack([61, 65, 68, 72], Fraction(1))]) + + +def test_composer_revalidates_mutated_attack_models() -> None: + intent = intent_for([attack([60, 64, 67])]) + assert intent.explicit_plan is not None + intent.explicit_plan.attacks[0].pitches.append(60) + profiles = load_profile_registry().select(["lead"], ProfileSelection()) + with pytest.raises(CompositionError): + compose_score(intent, profiles) diff --git a/tests/unit/test_hybrid.py b/tests/unit/test_hybrid.py new file mode 100644 index 0000000..35426db --- /dev/null +++ b/tests/unit/test_hybrid.py @@ -0,0 +1,377 @@ +"""Public generic hybrid parser: exact grids, preserved pitches and honest failures.""" + +import re +from fractions import Fraction + +import pytest +from pydantic import ValidationError + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.errors import DomainError, UnsupportedDescriptionError +from riff_groove_builder.hybrid import count_grid, materialize +from riff_groove_builder.profiles import load_profile_registry +from riff_groove_builder.schemas import ( + ExplicitAttackPlan, + GenerateMusicRequest, + MusicalIntent, + ProfileSelection, + TimeSignature, +) + +CANONICAL = """Lead guitar, 4/4, 120 BPM, 2 bars. +Bar 1: +Counts: 1 & 2 & 3 & [4 trip let] +Events: x x x x x x [x x ^] +Chords: F#2 F#2 D3 D3 Bb2 Bb2 - - - +Notes: - - - - - - C4 E4 G4 +Hold the final G4 through the end of bar 2 without retriggering.""" + +ORIGINAL_LANES = """Lead guitar, E minor, 4/4, 120 BPM, 2 bars. +Bar 1: +Counts: 1& 2& 3& [4 trip let] +Events: xx xx xx xx^ +Notes: E2E2 E2E2 E2E2 E2E2E2 +Hold the final E2 through the end of bar 2 without retriggering.""" + + +def resolve(text: str, **overrides: object) -> MusicalIntent: + request = GenerateMusicRequest.model_validate( + {"description": text, "basename": "hybrid", **overrides} + ) + intent = resolve_description(request).intent + profiles = load_profile_registry().select(intent.parts, request.profiles or ProfileSelection()) + return materialize(intent, profiles) + + +def plan(text: str, **overrides: object) -> ExplicitAttackPlan: + result = resolve(text, **overrides).explicit_plan + assert result is not None + return result + + +def lane( + counts: str = "1 & 2 & 3 & 4 &", + events: str = "oooooooo", + notes: str = "E2E2E2E2E2E2E2E2", + context: str = "guitar, 4/4, 1 bar", +) -> str: + return f"{context}\nCounts: {counts}\nEvents: {events}\nNotes: {notes}" + + +def test_corrected_canonical_exact_expanded_attacks() -> None: + result = plan(CANONICAL) + assert [a.pitches for a in result.attacks] == [ + [42, 46, 49], + [42, 46, 49], + [50, 54, 57], + [50, 54, 57], + [46, 50, 53], + [46, 50, 53], + [60], + [64], + [67], + ] + assert [a.start.value * 960 for a in result.attacks] == [ + 0, + 480, + 960, + 1440, + 1920, + 2400, + 2880, + 3200, + 3520, + ] + assert [a.duration.value * 960 for a in result.attacks] == [480] * 6 + [320, 320, 4160] + assert [a.technique for a in result.attacks] == ["palm_mute"] * 8 + ["pinch_harmonic"] + assert sum(len(a.pitches) for a in result.attacks) == 21 + + +@pytest.mark.parametrize( + "mutate", + [ + lambda s: ( + s.replace("Counts:", "cOuNtS:") + .replace("Events:", "EVENTS:") + .replace("Notes:", "notes:") + ), + lambda s: s.replace(" ", "\t"), + lambda s: ( + s.replace("x x x x x x [x x ^]", "xxxxxx[xx^]") + .replace("F#2 F#2 D3 D3 Bb2 Bb2 - - -", "F#2F#2 D3D3 Bb2Bb2 ---") + .replace("- - - - - - C4 E4 G4", "-- -- -- [C4E4G4]") + ), + ], +) +def test_width_case_compact_invariance(mutate: object) -> None: + assert callable(mutate) + assert plan(mutate(CANONICAL)).attacks == plan(CANONICAL).attacks + + +@pytest.mark.parametrize( + ("counts", "grid", "offsets", "lengths"), + [ + ("1", None, [0], [1]), + ("1&", None, [0, Fraction(1, 2)], [Fraction(1, 2)] * 2), + ( + "1 E & A", + None, + [0, Fraction(1, 4), Fraction(1, 2), Fraction(3, 4)], + [Fraction(1, 4)] * 4, + ), + ("[1 trip let]", None, [0, Fraction(1, 3), Fraction(2, 3)], [Fraction(1, 3)] * 3), + ("1&a", "triplets", [0, Fraction(1, 3), Fraction(2, 3)], [Fraction(1, 3)] * 3), + ( + "1&a", + "sixteenths", + [0, Fraction(1, 2), Fraction(3, 4)], + [Fraction(1, 2), Fraction(1, 4), Fraction(1, 4)], + ), + ], +) +@pytest.mark.parametrize("denominator", [2, 4, 8, 16]) +def test_reusable_denominator_count_math( + counts: str, + grid: str | None, + offsets: list[Fraction], + lengths: list[Fraction], + denominator: int, +) -> None: + unit = Fraction(4, denominator) + assert count_grid( + counts, TimeSignature.model_validate({"numerator": 3, "denominator": denominator}), grid + ) == [ + (Fraction(start) * unit, Fraction(length) * unit) + for start, length in zip(offsets, lengths, strict=True) + ] + + +@pytest.mark.parametrize("directive", ["Grid", "Subdivision"]) +@pytest.mark.parametrize( + ("grid", "counts", "size"), + [ + ("eighths", "1&", 2), + ("sixteenths", "1e&a", 4), + ("eighth-triplets", "1&a", 3), + ], +) +def test_public_grid_directives(directive: str, grid: str, counts: str, size: int) -> None: + assert ( + len(plan(lane(counts, "o" * size, "E2" * size) + f"\n{directive}: {grid}").attacks) == size + ) + + +def test_three_four_and_second_explicit_bar() -> None: + text = lane("1& 2& 3&", "oooooo", "E2" * 6, "bass, 3/4, two bars") + text += "\nBar 2:\nCounts: 1 2 3\nEvents: ooo\nNotes: A2B2C3" + result = plan(text) + assert [a.start.value for a in result.attacks][-3:] == [3, 4, 5] + assert result.part == "bass" and result.duration.value == 6 + + +def test_bar_boundaries_and_empty_lane_vs_global_rest() -> None: + result = plan( + "guitar, 2 bars\nCounts: 1 2 | 1 2\nEvents: o- | oo\nNotes: E2- | -G3\nChords: -- | D3-" + ) + assert [a.pitches for a in result.attacks] == [[40], [50, 54, 57], [55]] + assert [a.start.value for a in result.attacks] == [0, 4, 5] + + +@pytest.mark.parametrize( + "continuation", + [ + "\nBar 2: hold previous note to bar end", + "\nBar 2:\nCounts: 1 2 3 4\nEvents: ~~~~\nNotes: ----", + ], +) +def test_continuation_matches_prose_tie(continuation: str) -> None: + tied = ORIGINAL_LANES[: ORIGINAL_LANES.index("Hold")] + continuation + assert plan(tied).attacks == plan(ORIGINAL_LANES).attacks + + +@pytest.mark.parametrize( + ("symbol", "expected"), + [ + ("Em4OverB2", [47, 64, 67, 71]), + ("Em4/B2", [47, 64, 67, 71]), + ("Em4/B", [59, 64, 67, 71]), + ("Em4OverB", [59, 64, 67, 71]), + ("[C3 E3 G3]", [48, 52, 55]), + ("Em4(add4)", [64, 67, 69, 71]), + ("D3", [50, 54, 57]), + ("D2", [38, 42, 45]), + ("F#4", [66, 70, 73]), + ("Bb2", [46, 50, 53]), + ("F#", [42, 46, 49]), + ], +) +def test_public_chord_resolution_no_key_retune(symbol: str, expected: list[int]) -> None: + result = plan(f"guitar, D minor, 1 bar\nCounts: 1\nEvents: o\nChords: {symbol}") + assert result.attacks[0].pitches == expected + if symbol in ("F#", "Em4/B", "Em4OverB"): + assert "MIDI" in "\n".join(result.assumptions) + + +def test_original_seed_and_compiler_controls_unchanged() -> None: + intent = resolve(ORIGINAL_LANES) + profiles = load_profile_registry().select(intent.parts, ProfileSelection()) + compiled = compile_score(compose_score(intent, profiles), profiles) + musical = [e for t in compiled.tracks for e in t.events if e.kind == "note_on" and e.note == 40] + assert len(musical) == 9 + + +@pytest.mark.parametrize( + "text", + [ + lane("1&a", "ooo", "E2" * 3), + lane("1&", "o", "E2E2"), + lane("1&", "oo", "E2"), + lane("2 1", "oo", "E2E2"), + lane("1 1", "oo", "E2E2"), + lane("0", "o", "E2"), + lane("5", "o", "E2"), + lane("[4 trip nope]", "ooo", "E2" * 3), + lane("[[4 trip let]]", "ooo", "E2" * 3), + lane("1", "/", "E2"), + lane("1", "\\", "E2"), + lane("1", "?", "E2"), + lane("1", "~", "-"), + lane("1 2 3", "o-~", "E2--"), + lane("1", "-", "E2"), + lane("1", "~", "E2"), + lane("1", "o", "E2") + "\nChords: D3", + lane("1", "o", "[[E2]]"), + lane("1", "o", "H2"), + "guitar\nCounts: 1\nNotes: E2", + "guitar\nEvents: o\nNotes: E2", + lane("1", "o", "E2") + "\nNotes: E2", + lane("1", "o", "E2") + "\nGrid: quintuplets", + lane("1", "o", "E2") + "\nGrid: eighths\nSubdivision: sixteenths", + lane("1", "o", "E2", "guitar all notes G2"), + lane("1", "x", "E2", "guitar normal"), + lane("1", "o", "E2", "guitar palm mute"), + lane("1", "o", "E2", "guitar pinch harmonic"), + lane("1", "o", "E2", "guitar in H minor"), + lane("1", "o", "E2", "guitar accelerando from 100 to 120 BPM"), + lane("1", "o", "E2") + "\nInvent an orchestral bridge.", + "guitar\nCounts: 1 | 1\nEvents: o | o\nNotes: E2", + "guitar\nBar 2:\nCounts: 1\nEvents: o\nNotes: E2\nBar 1:", + "guitar\nBar 1:\nCounts: 1\nEvents: o\nChords: Em4/B4", + ORIGINAL_LANES.replace("final E2", "final G4"), + ORIGINAL_LANES.replace("2 bars", "1 bar"), + ORIGINAL_LANES.replace("end of bar 2", "end of bar 0"), + ORIGINAL_LANES.replace( + "Lead guitar", "Lead guitar normal, first palm muted then pinch harmonic" + ), + ORIGINAL_LANES + "\nBar 2:\nCounts: 1 2 3 4\nEvents: ----\nNotes: ----", + ORIGINAL_LANES + "\nBar 2:\nCounts: 1\nEvents: o\nNotes: G4", + ], +) +def test_actionable_errors_never_approximate(text: str) -> None: + with pytest.raises(DomainError): + resolve(text) + + +@pytest.mark.parametrize( + "overrides", + [ + {"bars": 1}, + {"time_signature": {"numerator": 3, "denominator": 4}}, + {"parts": ["lead", "bass"]}, + {"parts": ["drums"]}, + ], +) +def test_incompatible_structured_overrides_fail(overrides: dict[str, object]) -> None: + with pytest.raises(UnsupportedDescriptionError): + resolve(ORIGINAL_LANES, **overrides) + + +def test_bass_ph_requires_actual_capability() -> None: + intent = resolve(lane("1", "^", "E2", "bass")) + profiles = load_profile_registry().select(intent.parts, ProfileSelection()) + with pytest.raises(DomainError) as error: + compose_score(intent, profiles) + assert error.value.code == "UNSUPPORTED_ARTICULATION" + + +def test_default_low_tonic_is_disclosed_and_not_used_over_precise_source() -> None: + result = plan("guitar, 1 bar\nCounts: 1 2\nEvents: oo\nChords: -D3") + assert [a.pitches for a in result.attacks] == [[40], [50, 54, 57]] + assert "low tonic" in "\n".join(result.assumptions) + + +def test_rests_stop_ties_and_unknown_material_remains_private() -> None: + private = "PRIVATE_UNRECOGNIZED_LANE_MATERIAL" + with pytest.raises(DomainError) as error: + resolve(lane("1", "o", private)) + assert private not in str(error.value) + str(error.value.details) + + +@pytest.mark.parametrize("techniques", ["first palm muted then pinch harmonic", "first PM then PH"]) +def test_ordered_prose_techniques_not_mistaken_for_global_conflict(techniques: str) -> None: + assert ( + plan(ORIGINAL_LANES.replace("Lead guitar", f"Lead guitar, {techniques}")).attacks + == plan(ORIGINAL_LANES).attacks + ) + + +@pytest.mark.parametrize("suffix", ["", " without retriggering."]) +@pytest.mark.parametrize("verb", ["Hold", "Tie"]) +@pytest.mark.parametrize("connector", ["through", "to"]) +@pytest.mark.parametrize("target", ["bar", "measure"]) +def test_natural_hold_aliases(suffix: str, verb: str, connector: str, target: str) -> None: + text = ORIGINAL_LANES[: ORIGINAL_LANES.index("Hold")] + text += f"{verb} the final note {connector} the end of {target} 2{suffix}" + assert plan(text).attacks == plan(ORIGINAL_LANES).attacks + + +def test_chord_hold_and_tilde_preserve_whole_voicing() -> None: + base = "guitar, 2 bars\nCounts: 1 2 3 4\nEvents: ---x\nChords: ---D3\n" + prose = plan(base + "Tie the final chord to the end of measure 2.") + tilde = plan(base + "Bar 2:\nCounts: 1 2 3 4\nEvents: ~~~~") + assert prose.attacks == tilde.attacks + assert prose.attacks[0].pitches == [50, 54, 57] + assert prose.attacks[0].duration.value == 5 + + +@pytest.mark.parametrize("notes", ["E2-E2", "E2--E2", "--E2", "E2--"]) +def test_compact_empty_lane_boundaries(notes: str) -> None: + size = notes.count("E2") + notes.count("-") + events = "".join("o" if atom == "E2" else "-" for atom in re.findall(r"E2|-", notes)) + counts = " ".join(str(i) for i in range(1, size + 1)) + result = plan(lane(counts, events, notes)) + assert len(result.attacks) == notes.count("E2") + + +def test_style_context_is_disclosed_not_an_instruction_to_change_precise_notes() -> None: + text = CANONICAL.replace( + "Lead guitar", + "Lead guitar, low-register chord voicings, aggressive tight metal style, " + "bounded velocity variation", + ) + assert plan(text).attacks == plan(CANONICAL).attacks + + +def test_large_malformed_and_overlength_inputs_are_bounded() -> None: + with pytest.raises(ValidationError): + GenerateMusicRequest(description="Counts: " + "[" * 4000, basename="huge") + with pytest.raises(DomainError): + resolve("guitar\nCounts: " + "[" * 3900) + + +def test_expanded_tones_and_articulation_controls_share_public_budget( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr("riff_groove_builder.schemas.MAX_SCHEDULED_EVENTS", 12) + monkeypatch.setattr("riff_groove_builder.articulations.MAX_SCHEDULED_EVENTS", 12) + text = "guitar, 1 bar\nCounts: 1 2\nEvents: oo\nChords: C3 D3" + intent = resolve(text) + profiles = load_profile_registry().select(intent.parts, ProfileSelection()) + with pytest.raises(DomainError) as error: + compose_score(intent, profiles) + assert error.value.details["reason"] == "event_budget_exceeded" + standard_intent = resolve(text, profiles={"lead": "standard.lead.v1"}) + standard = load_profile_registry().select(["lead"], ProfileSelection(lead="standard.lead.v1")) + assert len(compose_score(standard_intent, standard).tracks[0].notes) == 6 diff --git a/tests/unit/test_midi.py b/tests/unit/test_midi.py new file mode 100644 index 0000000..31b7089 --- /dev/null +++ b/tests/unit/test_midi.py @@ -0,0 +1,683 @@ +"""Synthetic SMF mechanics only; no plugin mappings or application claims.""" + +import math +import shutil +import struct +import uuid +from collections.abc import Iterator +from fractions import Fraction +from pathlib import Path +from typing import Literal, cast +from unittest.mock import MagicMock + +import mido # type: ignore[import-untyped] +import pytest + +from riff_groove_builder import midi +from riff_groove_builder.errors import OutputExistsError, OutputIOError, SerializationError +from riff_groove_builder.schemas import ( + MAX_SCHEDULED_EVENTS, + ControlChangeEvent, + EventPlan, + EventTrack, + MusicalIntent, + NoteOffEvent, + NoteOnEvent, + Part, + PitchedNote, + PositiveBeat, + RationalBeat, + ScheduledEvent, + Score, + ScoreTrack, + TimeSignature, +) + +Role = Literal["musical_note", "keyswitch"] + + +@pytest.fixture +def workspace() -> Iterator[Path]: + root = Path(__file__).resolve().parents[2] / ".test-artifacts" / f"midi-unit-{uuid.uuid4().hex}" + root.mkdir(parents=True) + try: + yield root + finally: + shutil.rmtree(root) + + +def on( + tick: int = 120, + note: int = 60, + *, + part: Part = "lead", + channel: int = 2, + role: Role = "musical_note", + priority: int = 30, + sequence: int = 0, +) -> NoteOnEvent: + return NoteOnEvent( + tick=tick, + part=part, + channel=channel, + role=role, + note=note, + velocity=91, + priority=priority, + sequence=sequence, + ) + + +def off( + tick: int = 1080, + note: int = 60, + *, + part: Part = "lead", + channel: int = 2, + role: Role = "musical_note", + priority: int = 10, + sequence: int = 0, +) -> NoteOffEvent: + return NoteOffEvent( + tick=tick, + part=part, + channel=channel, + role=role, + note=note, + velocity=17, + priority=priority, + sequence=sequence, + ) + + +def cc( + tick: int = 120, + *, + part: Part = "lead", + channel: int = 2, + priority: int = 20, + sequence: int = 0, + value: int = 63, +) -> ControlChangeEvent: + return ControlChangeEvent( + tick=tick, + part=part, + channel=channel, + controller=21, + value=value, + priority=priority, + sequence=sequence, + ) + + +def make_plan( + events: list[ScheduledEvent] | None = None, + *, + parts: list[Part] | None = None, + ppq: int = 960, + musical_start: int = 120, + tail: int = 30, + meter: TimeSignature | None = None, + bpm: float = 120, + score_start: Fraction = Fraction(0), +) -> EventPlan: + selected: list[Part] = parts if parts is not None else ["lead"] + signature = meter if meter is not None else TimeSignature(numerator=4, denominator=4) + duration = signature.beats_per_bar + end = score_start + duration + score = Score( + intent=MusicalIntent( + description="Synthetic writer test, not an instrument profile", + parts=selected, + tempo_bpm=bpm, + bars=1, + time_signature=signature, + key="E minor", + seed=0, + ), + start=RationalBeat(numerator=score_start.numerator, denominator=score_start.denominator), + end=RationalBeat(numerator=end.numerator, denominator=end.denominator), + tracks=[ScoreTrack(part=part, notes=[]) for part in selected], + ) + musical_end = musical_start + int(duration * ppq) + return EventPlan( + score=score, + ticks_per_quarter=ppq, + musical_start_tick=musical_start, + musical_end_tick=musical_end, + end_tick=musical_end + tail, + tracks=[ + EventTrack(part=part, events=[event for event in events or [] if event.part == part]) + for part in selected + ], + ) + + +@pytest.mark.parametrize( + ("numerator", "denominator", "expected"), + [(4, 4, 3840), (3, 4, 2880), (6, 8, 2880), (7, 8, 3360), (5, 16, 1200)], +) +def test_bar_math(numerator: int, denominator: int, expected: int) -> None: + meter = TimeSignature.model_validate({"numerator": numerator, "denominator": denominator}) + assert midi.bar_ticks(meter) == expected + assert midi.bar_ticks(meter, bars=3) == expected * 3 + + +@pytest.mark.parametrize( + ("beats", "expected"), + [ + (Fraction(0), 0), + (Fraction(1), 960), + (Fraction(1, 2), 480), + (Fraction(1, 4), 240), + (Fraction(1, 3), 320), + (Fraction(2, 3), 640), + (Fraction(7, 12), 560), + ], +) +def test_exact_beats(beats: Fraction, expected: int) -> None: + assert midi.beats_to_ticks(beats) == expected + assert ( + midi.beats_to_ticks(RationalBeat(numerator=beats.numerator, denominator=beats.denominator)) + == expected + ) + + +def test_ppq_and_fraction_boundaries() -> None: + assert midi.beats_to_ticks(1, 1) == 1 + assert midi.beats_to_ticks(1, midi.MAX_PPQ) == 32767 + assert midi.beats_to_ticks(Fraction(1, 960)) == 1 + assert midi.beats_to_ticks(Fraction(1, 7), 7) == 1 + for beats in (Fraction(1, 7), Fraction(1, 1920)): + with pytest.raises(SerializationError, match="serialization") as failure: + midi.beats_to_ticks(beats) + assert failure.value.details["reason"] == "off_grid_beats" + with pytest.raises(SerializationError): + midi.bar_ticks(TimeSignature(numerator=3, denominator=8), ppq=1) + + +@pytest.mark.parametrize("value", [True, False, 1.0, "1", -1, math.nan, math.inf]) +def test_strict_beats(value: object) -> None: + with pytest.raises(SerializationError): + midi.beats_to_ticks(cast(Fraction, value)) + + +@pytest.mark.parametrize("value", [0, -1, True, 960.0, "960", 32768, 65535]) +def test_illegal_ppq(value: object) -> None: + with pytest.raises(SerializationError): + midi.beats_to_ticks(1, cast(int, value)) + + +@pytest.mark.parametrize("bars", [0, -1, True, 1.0, "1"]) +def test_strict_bars(bars: object) -> None: + with pytest.raises(SerializationError): + midi.bar_ticks(TimeSignature(numerator=4, denominator=4), cast(int, bars)) + + +@pytest.mark.parametrize( + ("bpm", "expected"), + [ + (120.0, 500000), + (120.125, 499480), + (137.5, 436364), + (300.0, 200000), + (102.4, 585938), + (61.44, 976562), + ], +) +def test_quarter_tempo(bpm: float, expected: int) -> None: + assert midi.quarter_tempo(bpm) == expected + + +@pytest.mark.parametrize( + "bpm", [True, "120", 0, -1, math.nan, math.inf, 0.001, 200_000_000, 10**400] +) +def test_invalid_or_unrepresentable_tempo(bpm: object) -> None: + with pytest.raises(SerializationError): + midi.quarter_tempo(cast(float, bpm)) + + +def test_priority_sequence_preserved_not_pitch_sorted(workspace: Path) -> None: + events: list[ScheduledEvent] = [ + off(1080, 60), + on(note=60, priority=9), + cc(priority=8, sequence=2, value=2), + cc(priority=8, sequence=1, value=1), + off(1080, 72, sequence=1), + on(note=72, priority=7), + ] + path = midi.write_midi(workspace / "ordered.mid", make_plan(events)) + loaded = mido.MidiFile(path) + assert [(message.type, message.time) for message in loaded.tracks[1]] == [ + ("track_name", 0), + ("note_on", 120), + ("control_change", 0), + ("control_change", 0), + ("note_on", 0), + ("note_off", 960), + ("note_off", 0), + ("end_of_track", 2910), + ] + assert [message.value for message in loaded.tracks[1] if message.type == "control_change"] == [ + 1, + 2, + ] + assert [message.note for message in loaded.tracks[1] if message.type == "note_on"] == [72, 60] + assert events[0].tick == 1080 # Input list is not sorted or mutated in place. + + +@pytest.mark.parametrize("role", ["musical_note", "keyswitch"]) +def test_off_on_retrigger(workspace: Path, role: Role) -> None: + plan = make_plan([on(role=role), off(role=role), on(1080, role=role), off(2040, role=role)]) + path = midi.write_midi(workspace / "retrigger.mid", plan) + assert [message.type for message in mido.MidiFile(path).tracks[1]][1:-1] == [ + "note_on", + "note_off", + "note_on", + "note_off", + ] + + +@pytest.mark.parametrize( + ("events", "reason"), + [ + ([off()], "orphan_note_off"), + ([on()], "dangling_note"), + ([on(role="keyswitch")], "dangling_note"), + ([off(role="keyswitch")], "orphan_note_off"), + ([on(), on(480), off(1080), off(2040)], "same_pitch_overlap"), + ([on(), on(480, role="keyswitch"), off()], "same_pitch_overlap"), + ([on(role="keyswitch"), on(480), off()], "same_pitch_overlap"), + ([on(), off(role="keyswitch")], "note_role_mismatch"), + ([on(role="keyswitch"), off()], "note_role_mismatch"), + ([on(), off(channel=3)], "orphan_note_off"), + ([on(), off(120, priority=31)], "nonpositive_note_duration"), + ([on(), on(1080, priority=1), off(), off(2040)], "same_pitch_overlap"), + ([on(), off(120)], "orphan_note_off"), + ], +) +def test_unsafe_pairing(events: list[ScheduledEvent], reason: str) -> None: + with pytest.raises(SerializationError) as failure: + midi.validate_event_plan(make_plan(events)) + assert failure.value.details["reason"] == reason + assert failure.value.details["part"] == "lead" + assert failure.value.details["role"] in ("musical_note", "keyswitch") + + +def test_roles_may_reuse_pitch_only_after_release() -> None: + midi.validate_event_plan( + make_plan([on(0, role="keyswitch"), off(120, role="keyswitch"), on(), off()]) + ) + + +def test_polyphony_and_channel_independence() -> None: + midi.validate_event_plan( + make_plan([on(note=60), on(note=64, sequence=1), off(note=60), off(note=64, sequence=1)]) + ) + midi.validate_event_plan( + make_plan([on(), on(channel=3, sequence=1), off(), off(channel=3, sequence=1)]) + ) + + +@pytest.mark.parametrize("control_only", [False, True]) +def test_distinct_parts_cannot_share_channel_even_at_different_times(control_only: bool) -> None: + bass: list[ScheduledEvent] = ( + [cc(2040, part="bass")] if control_only else [on(2040, part="bass"), off(3000, part="bass")] + ) + with pytest.raises(SerializationError) as failure: + midi.validate_event_plan(make_plan([on(), off(), *bass], parts=["lead", "bass"])) + assert failure.value.details["reason"] == "shared_channel" + + +def test_empty_tracks_metadata_and_shared_tail(workspace: Path) -> None: + plan = make_plan(parts=["drums", "lead", "bass"], bpm=137.5) + path = midi.write_midi(workspace / "rests.mid", plan) + loaded = mido.MidiFile(path) + assert loaded.type == 1 + assert loaded.ticks_per_beat == 960 + assert [track.name for track in loaded.tracks] == ["Conductor", "Drums", "Lead", "Bass"] + assert [message.tempo for message in loaded.tracks[0] if message.type == "set_tempo"] == [ + 436364 + ] + for track in loaded.tracks: + assert sum(message.time for message in track) == 3990 + assert sum(message.type == "end_of_track" for message in track) == 1 + assert track[-1].type == "end_of_track" + assert [message.type for message in loaded.tracks[1]] == ["track_name", "end_of_track"] + + +def test_keyswitch_release_may_use_shared_tail(workspace: Path) -> None: + plan = make_plan( + [ + on(0, note=5, role="keyswitch"), + off(3990, note=5, role="keyswitch"), + on(), + off(3960), + cc(3990), + ] + ) + path = midi.write_midi(workspace / "tail.mid", plan) + track = mido.MidiFile(path).tracks[1] + assert [(message.type, message.time) for message in track][-3:] == [ + ("note_off", 30), + ("control_change", 0), + ("end_of_track", 0), + ] + + +def test_mutable_beat_and_meter_helpers_revalidate() -> None: + beat = RationalBeat(numerator=1) + beat.denominator = 0 + with pytest.raises(SerializationError): + midi.beats_to_ticks(beat) + meter = TimeSignature(numerator=4, denominator=4) + meter.numerator = True + with pytest.raises(SerializationError): + midi.bar_ticks(meter) + + +def test_nonzero_score_origin_is_not_an_extra_part_shift(workspace: Path) -> None: + plan = make_plan([on(), off()], score_start=Fraction(11, 3)) + plan.score.tracks[0].notes.append( + PitchedNote( + part="lead", + pitch=60, + start=RationalBeat(numerator=11, denominator=3), + duration=PositiveBeat(numerator=1), + intensity=0.5, + articulation="synthetic", + ) + ) + path = midi.write_midi(workspace / "origin.mid", plan) + assert mido.MidiFile(path).tracks[1][1].time == 120 + assert plan.score.start.value == Fraction(11, 3) + assert plan.musical_end_tick - plan.musical_start_tick == 3840 + + +def test_logical_note_offsets_and_durations_must_be_on_grid() -> None: + plan = make_plan() + note = PitchedNote( + part="lead", + pitch=60, + start=RationalBeat(numerator=1, denominator=7), + duration=PositiveBeat(numerator=1), + intensity=0.5, + articulation="synthetic", + ) + plan.score.tracks[0].notes.append(note) + with pytest.raises(SerializationError) as failure: + midi.validate_event_plan(plan) + assert failure.value.details["reason"] == "off_grid_beats" + note.start = RationalBeat(numerator=0) + note.duration = PositiveBeat(numerator=1, denominator=7) + with pytest.raises(SerializationError) as failure: + midi.validate_event_plan(plan) + assert failure.value.details["reason"] == "off_grid_beats" + + +def test_maximum_conductor_delta_and_overflow(workspace: Path) -> None: + plan = make_plan(musical_start=midi.MAX_DELTA - 3840, tail=0) + path = midi.write_midi(workspace / "max-delta.mid", plan) + assert mido.MidiFile(path).tracks[0][-1].time == midi.MAX_DELTA + plan.end_tick += 1 + with pytest.raises(SerializationError) as failure: + midi.validate_event_plan(plan) + assert failure.value.details["reason"] == "delta_out_of_range" + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("tick", -1), + ("tick", 120.0), + ("tick", True), + ("note", 128), + ("velocity", 0), + ("channel", 16), + ("priority", -1), + ("sequence", True), + ("kind", "program_change"), + ("role", "unknown"), + ("part", "bass"), + ], +) +def test_mutated_event_graph_is_revalidated(field: str, value: object) -> None: + plan = make_plan([on(), off()]) + setattr(plan.tracks[0].events[0], field, value) + with pytest.raises(SerializationError) as failure: + midi.validate_event_plan(plan) + assert failure.value.details["reason"] == "invalid_event_plan" + + +@pytest.mark.parametrize( + "mutation", + ["end_on", "early_on", "late_off", "late_control", "bad_span", "bad_ppq", "tempo", "keys"], +) +def test_shared_timeline_and_schema_guards(mutation: str) -> None: + plan = make_plan([on(), off()]) + if mutation == "end_on": + plan.tracks[0].events[0].tick = plan.musical_end_tick + elif mutation == "early_on": + plan.tracks[0].events[0].tick = 0 + elif mutation == "late_off": + plan.tracks[0].events[1].tick = plan.musical_end_tick + 1 + elif mutation == "late_control": + plan.tracks[0].events.append(cc(plan.end_tick + 1)) + elif mutation == "bad_span": + plan.musical_end_tick += 1 + elif mutation == "bad_ppq": + plan.ticks_per_quarter = True + elif mutation == "tempo": + plan.score.intent.tempo_bpm = math.nan + else: + plan.tracks[0].events.append(on()) + with pytest.raises(SerializationError) as failure: + midi.validate_event_plan(plan) + assert failure.value.details["reason"] == "invalid_event_plan" + + +def test_ppq_header_limit_is_stricter_than_internal_positive_resolution() -> None: + with pytest.raises(SerializationError) as failure: + midi.validate_event_plan(make_plan(ppq=32768)) + assert failure.value.details["reason"] == "invalid_ppq" + + +@pytest.mark.parametrize("ppq", [1, 32767]) +def test_legal_ppq_limits_survive_disk_header(workspace: Path, ppq: int) -> None: + path = midi.write_midi(workspace / "ppq.mid", make_plan(ppq=ppq, musical_start=0, tail=0)) + loaded = mido.MidiFile(path) + assert loaded.ticks_per_beat == ppq + assert loaded.tracks[0][-1].time == 4 * ppq + + +@pytest.mark.parametrize(("channel", "note", "velocity"), [(0, 0, 1), (15, 127, 127)]) +def test_midi_payload_limits_survive_disk( + workspace: Path, channel: int, note: int, velocity: int +) -> None: + onset = on(channel=channel, note=note) + onset.velocity = velocity + release = off(channel=channel, note=note) + release.velocity = 127 + control = cc(channel=channel, value=127) + control.controller = 0 + path = midi.write_midi(workspace / "payloads.mid", make_plan([onset, release, control])) + messages = [message for message in mido.MidiFile(path).tracks[1] if not message.is_meta] + assert messages[0].type == "control_change" + assert (messages[0].channel, messages[0].control, messages[0].value) == (channel, 0, 127) + assert (messages[1].channel, messages[1].note, messages[1].velocity) == ( + channel, + note, + velocity, + ) + assert (messages[2].channel, messages[2].note, messages[2].velocity) == (channel, note, 127) + + +def test_event_budget_exact_boundary() -> None: + events: list[ScheduledEvent] = [cc(sequence=index) for index in range(MAX_SCHEDULED_EVENTS - 1)] + plan = make_plan(events) + midi.validate_event_plan(plan) + plan.tracks[0].events.append(cc(sequence=MAX_SCHEDULED_EVENTS - 1)) + midi.validate_event_plan(plan) + plan.tracks[0].events.append(cc(sequence=MAX_SCHEDULED_EVENTS)) + with pytest.raises(SerializationError) as failure: + midi.validate_event_plan(plan) + assert failure.value.details["reason"] == "invalid_event_plan" + + +def test_no_overwrite_or_directory_creation(workspace: Path) -> None: + path = workspace / "existing.mid" + path.write_bytes(b"unrelated original data") + with pytest.raises(OutputExistsError): + midi.write_midi(path, make_plan()) + assert path.read_bytes() == b"unrelated original data" + with pytest.raises(OutputExistsError): + midi.write_midi(workspace, make_plan()) + missing = workspace / "not-created" / "song.mid" + with pytest.raises(OutputIOError) as failure: + midi.write_midi(missing, make_plan()) + assert failure.value.details == {"reason": "midi_create_failed"} + assert not missing.parent.exists() + + +def test_exclusive_create_protects_against_collision_after_precheck( + workspace: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + path = workspace / "raced.mid" + path.write_bytes(b"keep") + monkeypatch.setattr(Path, "exists", lambda self: False) + with pytest.raises(OutputExistsError): + midi.write_midi(path, make_plan()) + assert path.read_bytes() == b"keep" + + +def test_invalid_path_fails_with_safe_named_error(workspace: Path) -> None: + with pytest.raises(OutputIOError) as failure: + midi.write_midi(workspace / "invalid\0.mid", make_plan()) + assert failure.value.details == {"reason": "midi_create_failed"} + assert not list(workspace.iterdir()) + + +def test_serialization_failure_is_explicit_before_creation( + workspace: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def fail_save(self: object, **kwargs: object) -> None: + raise struct.error("private detail") + + monkeypatch.setattr(mido.MidiFile, "save", fail_save) + path = workspace / "bad.mid" + with pytest.raises(SerializationError) as failure: + midi.write_midi(path, make_plan()) + assert failure.value.details == {"reason": "smf_encoding_failed"} + assert not path.exists() + assert "private detail" not in str(failure.value) + + +@pytest.mark.parametrize("short_write", [False, True]) +def test_write_failure_removes_only_new_file( + workspace: Path, monkeypatch: pytest.MonkeyPatch, short_write: bool +) -> None: + path = workspace / "failed.mid" + sentinel = workspace / "sentinel" + sentinel.write_bytes(b"keep") + original_open = Path.open + + def failing_open(self: Path, mode: str = "r", **kwargs: object) -> object: + assert self == path and mode == "xb" + real = original_open(self, "xb") + proxy = MagicMock() + proxy.__enter__.return_value = proxy + proxy.__exit__.side_effect = real.__exit__ + proxy.fileno.return_value = real.fileno() + if short_write: + proxy.write.return_value = 1 + else: + proxy.write.side_effect = OSError("private disk failure") + return proxy + + monkeypatch.setattr(Path, "open", failing_open) + with pytest.raises(OutputIOError) as failure: + midi.write_midi(path, make_plan()) + assert failure.value.details == { + "reason": "midi_short_write" if short_write else "midi_write_failed" + } + assert not path.exists() + monkeypatch.undo() + assert sentinel.read_bytes() == b"keep" + + +@pytest.mark.parametrize("read_failure", [True, False]) +def test_readback_failure_cleans_owned_file( + workspace: Path, monkeypatch: pytest.MonkeyPatch, read_failure: bool +) -> None: + path = workspace / "failed.mid" + + def fail_read(self: Path) -> bytes: + assert self == path + if read_failure: + raise PermissionError("private read error") + return b"truncated" + + monkeypatch.setattr(Path, "read_bytes", fail_read) + error = OutputIOError if read_failure else SerializationError + with pytest.raises(error): + midi.write_midi(path, make_plan()) + assert not path.exists() + + +def test_cleanup_failure_is_not_hidden(workspace: Path, monkeypatch: pytest.MonkeyPatch) -> None: + path = workspace / "failed.mid" + + def fail_read(self: Path) -> bytes: + raise OSError("read failed") + + def fail_unlink(self: Path, missing_ok: bool = False) -> None: + raise PermissionError("cannot delete") + + monkeypatch.setattr(Path, "read_bytes", fail_read) + monkeypatch.setattr(Path, "unlink", fail_unlink) + with pytest.raises(OutputIOError) as failure: + midi.write_midi(path, make_plan()) + assert failure.value.details == {"reason": "midi_cleanup_failed"} + monkeypatch.undo() + assert path.exists() + path.unlink() + + +def test_replaced_file_is_not_deleted(workspace: Path, monkeypatch: pytest.MonkeyPatch) -> None: + path = workspace / "song.mid" + replacement = workspace / "foreign" + replacement.write_bytes(b"not ours") + read_bytes = Path.read_bytes + + def replace_and_fail(self: Path) -> bytes: + replacement.replace(path) + raise OSError("read failed") + + monkeypatch.setattr(Path, "read_bytes", replace_and_fail) + with pytest.raises(OutputIOError) as failure: + midi.write_midi(path, make_plan()) + assert failure.value.details == {"reason": "midi_cleanup_ownership_changed"} + assert read_bytes(path) == b"not ours" + + +def test_unexpected_failure_is_not_silently_translated_or_published( + workspace: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def fail_read(self: Path) -> bytes: + raise RuntimeError("programming defect") + + monkeypatch.setattr(Path, "read_bytes", fail_read) + path = workspace / "unexpected.mid" + with pytest.raises(RuntimeError, match="programming defect"): + midi.write_midi(path, make_plan()) + assert not path.exists() + + +def test_validator_does_not_delete_its_input(workspace: Path) -> None: + path = workspace / "not-midi.mid" + path.write_bytes(b"not MIDI") + with pytest.raises(SerializationError): + midi.validate_midi_file(path, make_plan()) + assert path.read_bytes() == b"not MIDI" + with pytest.raises(OutputIOError): + midi.validate_midi_file(workspace / "missing.mid", make_plan()) diff --git a/tests/unit/test_native_contracts.py b/tests/unit/test_native_contracts.py new file mode 100644 index 0000000..7b6095b --- /dev/null +++ b/tests/unit/test_native_contracts.py @@ -0,0 +1,67 @@ +"""Aliases belong to requests; artifacts and profile metadata expose actual suffixes.""" + +import json + +import pytest +from jsonschema import Draft202012Validator +from pydantic import ValidationError + +from riff_groove_builder.schemas import ( + Artifact, + GenerateMusicRequest, + tool_input_schema, +) + + +@pytest.mark.parametrize( + ("part", "extension"), [("lead", "griff"), ("bass", "briff"), ("drums", "sd3p")] +) +def test_actual_native_artifact_suffix_schema_and_model(part: str, extension: str) -> None: + data = { + "format": extension, + "parts": [part], + "path": rf"C:\original\test.{extension}", + "size_bytes": 100, + "profile_ids": ["original.profile"], + "fallback_for": [], + } + validator = Draft202012Validator(Artifact.model_json_schema()) + validator.validate(data) + model = Artifact.model_validate(data) + assert json.loads(model.model_dump_json()) == data + for update in ( + {"format": "agp" if part != "drums" else "sdp"}, + {"parts": ["bass" if part != "bass" else "lead"]}, + {"path": r"C:\original\test.mid"}, + {"fallback_for": [part]}, + ): + assert not validator.is_valid({**data, **update}) + with pytest.raises(ValidationError): + Artifact.model_validate({**data, **update}) + + +@pytest.mark.parametrize( + ("part", "extension", "alias"), + [("lead", "griff", "agp"), ("bass", "briff", "agp"), ("drums", "sd3p", "sdp")], +) +def test_request_alias_and_actual_suffix_share_part_associations( + part: str, extension: str, alias: str +) -> None: + validator = Draft202012Validator(tool_input_schema("generate_music")) + for output_format in (extension, alias): + data = { + "description": "Original native contract", + "basename": "original", + "parts": [part], + "formats": [output_format], + } + validator.validate(data) + assert GenerateMusicRequest.model_validate(data) + if output_format == alias == "agp": + wrong = "drums" + else: + wrong = "lead" if part != "lead" else "bass" + data["parts"] = [wrong] + assert not validator.is_valid(data) + with pytest.raises(ValidationError): + GenerateMusicRequest.model_validate(data) diff --git a/tests/unit/test_package.py b/tests/unit/test_package.py new file mode 100644 index 0000000..ec439d2 --- /dev/null +++ b/tests/unit/test_package.py @@ -0,0 +1,53 @@ +"""Smoke tests for the installed package's public, side-effect-free import.""" + +import subprocess +import sys +from importlib.metadata import version + +import anyio +import pytest +from packaging.version import Version + +import riff_groove_builder + + +def test_package_import() -> None: + assert riff_groove_builder.__name__ == "riff_groove_builder" + + +def test_release_version_matches_distribution() -> None: + public_version = riff_groove_builder.__version__ + assert public_version == "0.2.0" + parsed = Version(public_version) + assert not parsed.is_prerelease + assert not parsed.is_devrelease + assert parsed.local is None + assert public_version == version("gaj3t-musicgen-riff-groove-builder") + + +def test_import_is_silent_and_does_not_start_a_server() -> None: + result = subprocess.run( + [ + sys.executable, + "-I", + "-B", + "-c", + "import sys; import riff_groove_builder; " + "assert 'riff_groove_builder.server' not in sys.modules; " + "assert 'mcp' not in sys.modules", + ], + capture_output=True, + text=True, + timeout=15, + check=False, + ) + assert result.returncode == 0, result.stderr + assert result.stdout == "" + assert result.stderr == "" + + +@pytest.mark.anyio +@pytest.mark.parametrize("anyio_backend", ["asyncio"]) +async def test_async_test_support(anyio_backend: str) -> None: + assert anyio_backend == "asyncio" + await anyio.sleep(0) diff --git a/tests/unit/test_phrase_timing.py b/tests/unit/test_phrase_timing.py new file mode 100644 index 0000000..dbe96b9 --- /dev/null +++ b/tests/unit/test_phrase_timing.py @@ -0,0 +1,340 @@ +"""Original authored phrases, exact rational math and strict technique boundaries.""" + +from fractions import Fraction + +import pytest +from pydantic import ValidationError + +from riff_groove_builder.articulations import apply_scheduled_controls, compile_score +from riff_groove_builder.compose import CompositionError, compose_score +from riff_groove_builder.description import DescriptionResolution, resolve_description +from riff_groove_builder.errors import ( + SerializationError, + UnsupportedArticulationError, + UnsupportedDescriptionError, +) +from riff_groove_builder.profiles import ( + InstrumentProfile, + InvalidProfileError, + KeyswitchAction, + load_profile_registry, +) +from riff_groove_builder.schemas import ( + ControlChangeEvent, + GenerateMusicRequest, + NoteOnEvent, + Part, + PhrasePlan, + PitchedNote, + PositiveBeat, + ProfileSelection, + RationalBeat, + ScheduledControl, + TimedNote, + TimeSignature, +) + +ORIGINAL = ( + "Please produce a 4/4 riff in Em. With Chugging palm muting 8th notes from 1 to 3&;\n" + "and triplets on 4&A with the A as a pinch harmonic that carries over a whole note\n" + "in the 2nd measure." +) +STARTS = [ + Fraction(0), + Fraction(1, 2), + Fraction(1), + Fraction(3, 2), + Fraction(2), + Fraction(5, 2), + Fraction(3), + Fraction(10, 3), + Fraction(11, 3), +] + + +def resolve(text: str = ORIGINAL, /, **kwargs: object) -> DescriptionResolution: + return resolve_description( + GenerateMusicRequest.model_validate({"description": text, "basename": "phrase", **kwargs}) + ) + + +def test_original_plan_and_disclosed_assumptions() -> None: + resolved = resolve() + intent = resolved.intent + assert (intent.parts, intent.bars, intent.key, intent.tempo_bpm) == ( + ["lead"], + 2, + "E minor", + 120, + ) + phrase = intent.phrase_plan + assert phrase is not None + assert phrase.duration.value == 8 + assert [n.start.value for n in phrase.notes] == STARTS + assert [n.duration.value for n in phrase.notes] == [Fraction(1, 2)] * 6 + [ + Fraction(1, 3), + Fraction(1, 3), + Fraction(13, 3), + ] + assert [n.technique for n in phrase.notes] == ["palm_mute"] * 8 + ["pinch_harmonic"] + assumptions = "\n".join(resolved.assumptions) + assert "120" in assumptions and "E2/MIDI40" in assumptions + assert "A is the final count, not a pitch" in assumptions + assert "without retrigger" in assumptions and "bars: omitted; using 2" in assumptions + assert intent.techniques == intent.rhythm_terms == [] + + +@pytest.mark.parametrize( + "text", + [ + ORIGINAL.replace("4&A", "4 & A"), + ORIGINAL.replace("Em", "E minor"), + ORIGINAL.replace("palm muting 8th", "palm-muted eighth"), + ORIGINAL.replace("palm muting 8th", "palm mute eighth").replace("2nd", "second"), + ORIGINAL.replace("1 to 3&", "2 to 3&"), + ORIGINAL.replace("Em", "F#m"), + ], +) +def test_wording_aliases_and_numeric_range_variant(text: str) -> None: + phrase = resolve(text).intent.phrase_plan + assert phrase is not None + expected = STARTS[2:] if "2 to 3&" in text else STARTS + assert [n.start.value for n in phrase.notes] == expected + assert phrase.notes[-1].duration.value == Fraction(13, 3) + + +@pytest.mark.parametrize( + "text", + [ + ORIGINAL.replace("1 to 3&", "1 to 4"), + ORIGINAL.replace("1 to 3&", "4 to 3"), + ORIGINAL.replace("1 to 3&", "0 to 3&"), + ORIGINAL.replace("4&A", "5&A"), + ORIGINAL.replace("4/4", "3/4"), + ORIGINAL.replace("riff", "bass riff"), + ORIGINAL + " with legato", + ORIGINAL + " then 140 bpm", + ORIGINAL + " from 120 bpm to 140 bpm", + ORIGINAL + " add a melodic flourish", + ORIGINAL + " quarter", + ORIGINAL.replace("triplets", "sixteenths"), + ORIGINAL.replace("3&", "3&&"), + ORIGINAL.replace("3&", "3.5"), + ORIGINAL.replace("4&A", "0&A"), + ORIGINAL + " triplets on 4&A with the A as a pinch harmonic that carries over " + "a whole note in the second measure", + ], +) +def test_invalid_or_unsupported_prose_is_not_approximated(text: str) -> None: + with pytest.raises(UnsupportedDescriptionError): + resolve(text) + + +@pytest.mark.parametrize( + "overrides", + [ + {"bars": 1}, + {"time_signature": {"numerator": 7, "denominator": 8}}, + {"parts": ["bass"]}, + {"parts": ["lead", "drums"]}, + ], +) +def test_scalar_overrides_cannot_erase_phrase_semantics(overrides: dict[str, object]) -> None: + with pytest.raises(UnsupportedDescriptionError): + resolve(**overrides) + + +def test_exact_composition_and_keyswitches_are_not_musical_notes() -> None: + intent = resolve().intent + profiles = load_profile_registry().select(intent.parts, ProfileSelection()) + score = compose_score(intent, profiles) + assert score == compose_score(intent, profiles) + assert score.end.value == 8 + notes = score.tracks[0].notes + assert all(isinstance(n, PitchedNote) and n.pitch == 40 for n in notes) + assert [n.start.value for n in notes] == STARTS + assert [n.articulation for n in notes] == ["palm_mute"] * 8 + ["pinch_harmonic"] + assert notes[-1].start.value + notes[-1].duration.value == 8 + plan = compile_score(score, profiles) + musical = [ + e for e in plan.tracks[0].events if isinstance(e, NoteOnEvent) and e.role == "musical_note" + ] + switches = [ + e for e in plan.tracks[0].events if isinstance(e, NoteOnEvent) and e.role == "keyswitch" + ] + assert [e.tick for e in musical] == [0, 480, 960, 1440, 1920, 2400, 2880, 3200, 3520] + assert [(e.tick, e.note) for e in switches] == [(0, 26), (3520, 31)] + assert all(1 <= e.velocity <= 127 for e in musical) + assert plan.end_tick == plan.musical_end_tick == 7680 + assert all(e.kind != "control_change" for e in plan.tracks[0].events) + changed = resolve(seed=12).intent + assert compose_score(changed, profiles).tracks != score.tracks + + +def test_reusable_plan_per_note_intensity_and_longer_score() -> None: + intent = resolve(bars=3).intent + assert intent.phrase_plan is not None + intent.phrase_plan.notes[0].intensity = 0.25 + profiles = load_profile_registry().select(intent.parts, ProfileSelection()) + score = compose_score(intent, profiles) + assert score.tracks[0].notes[0].intensity == 0.25 + assert score.end.value == 12 + assert score.tracks[0].notes[-1].start.value + score.tracks[0].notes[-1].duration.value == 8 + with pytest.raises(CompositionError): + compose_score(intent.model_copy(update={"bars": 1}), profiles) + + +def test_generic_timing_plan_is_not_a_prompt_specific_template() -> None: + intent = resolve().intent.model_copy( + update={ + "parts": ["bass"], + "bars": 1, + "time_signature": TimeSignature(numerator=3, denominator=4), + "phrase_plan": PhrasePlan( + part="bass", + duration=PositiveBeat(numerator=3), + notes=[ + TimedNote( + start=RationalBeat(numerator=1, denominator=3), + duration=PositiveBeat(numerator=2, denominator=3), + technique="normal", + intensity=0.25, + ), + TimedNote( + start=RationalBeat(numerator=2), + duration=PositiveBeat(numerator=1), + technique="palm_mute", + intensity=0.75, + ), + ], + ), + } + ) + profiles = load_profile_registry().select(["bass"], ProfileSelection()) + score = compose_score(intent, profiles) + assert [ + (n.start.value, n.duration.value, n.articulation, n.intensity) + for n in score.tracks[0].notes + ] == [ + (Fraction(1, 3), Fraction(2, 3), "normal", 0.25), + (Fraction(2), Fraction(1), "palm_mute", 0.75), + ] + assert compile_score(score, profiles).musical_end_tick == 2880 + + +def test_second_numeric_range_and_triplet_beat_are_computed() -> None: + phrase = resolve(ORIGINAL.replace("3&", "2&").replace("4&A", "3 & A")).intent.phrase_plan + assert phrase is not None + assert [n.start.value for n in phrase.notes] == [ + Fraction(0), + Fraction(1, 2), + Fraction(1), + Fraction(3, 2), + Fraction(2), + Fraction(7, 3), + Fraction(8, 3), + ] + assert phrase.notes[-1].duration.value == Fraction(16, 3) + + +def test_plan_rejects_overlaps_and_nonfinite_intensity() -> None: + note = TimedNote( + start=RationalBeat(numerator=0), duration=PositiveBeat(numerator=1), technique="normal" + ) + with pytest.raises(ValidationError): + PhrasePlan(part="lead", duration=PositiveBeat(numerator=2), notes=[note, note]) + with pytest.raises(ValidationError): + TimedNote.model_validate({**note.model_dump(), "intensity": float("nan")}) + + +@pytest.mark.parametrize("part", ["lead", "bass", "drums"]) +def test_no_ph_promotion_to_other_maps(part: Part) -> None: + registry = load_profile_registry() + for profile in registry.select([part], ProfileSelection()).values(): + if part != "lead": + with pytest.raises(KeyError): + profile.resolve_articulation("pinch_harmonic") + standard = registry.select(["lead"], ProfileSelection(lead="standard.lead.v1")) + with pytest.raises(UnsupportedArticulationError): + compose_score(resolve().intent, standard) + + +def test_ph_map_and_native_guard_reject_fabrication() -> None: + profile = load_profile_registry().select(["lead"], ProfileSelection())["lead"] + art = profile.resolve_articulation("PH") + assert art.name == "pinch_harmonic" + assert profile.summary.mapping_version == "riffer-subset-2" + assert profile.riffer is not None and profile.riffer.articulations["pinch_harmonic"] == "PH" + data = profile.model_dump() + data["articulations"][-1]["actions"][0]["note"] = 30 + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + invalid = profile.model_copy(deep=True) + action = invalid.articulations[-1].actions[0] + assert isinstance(action, KeyswitchAction) + action.note = 30 + with pytest.raises(InvalidProfileError): + compose_score(resolve().intent, {"lead": invalid}) + + +def test_phrase_budget_checked_before_allocation(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("riff_groove_builder.compose.MAX_SCHEDULED_EVENTS", 17) + profiles = load_profile_registry().select(["lead"], ProfileSelection()) + with pytest.raises(CompositionError) as error: + compose_score(resolve().intent, profiles) + assert error.value.details["reason"] == "note_pair_event_budget_exceeded" + + +def test_phrase_budget_includes_keyswitch_events(monkeypatch: pytest.MonkeyPatch) -> None: + intent = resolve().intent + profiles = load_profile_registry().select(intent.parts, ProfileSelection()) + score = compose_score(intent, profiles) + monkeypatch.setattr("riff_groove_builder.articulations.MAX_SCHEDULED_EVENTS", 20) + with pytest.raises(SerializationError): + compile_score(score, profiles) + + +@pytest.mark.parametrize("mutation", ["native_label", "unknown_label", "bass_ph"]) +def test_only_evidenced_native_ph_representation_is_permitted(mutation: str) -> None: + part: Part = "bass" if mutation == "bass_ph" else "lead" + profile = load_profile_registry().select([part], ProfileSelection())[part] + data = profile.model_dump() + if mutation == "unknown_label": + data["riffer"]["articulations"]["pinch_harmonic"] = "PH2" + elif mutation == "native_label": + data["riffer"]["articulations"]["pinch_harmonic"] = "Sus" + else: + data["riffer"]["articulations"]["pinch_harmonic"] = "PH" + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +def test_phrase_low_tonic_must_fit_profile_without_clamping() -> None: + profile = load_profile_registry().select(["lead"], ProfileSelection(lead="standard.lead.v1"))[ + "lead" + ] + data = profile.model_dump() + data["playable_range"] = {"low": 0, "high": 2} + with pytest.raises(CompositionError) as error: + compose_score(resolve().intent, {"lead": InstrumentProfile.model_validate(data)}) + assert error.value.details["reason"] == "range_cannot_fit_low_tonic" + + +def test_explicit_cc_on_held_phrase_is_preserved_not_inferred() -> None: + intent = resolve().intent + profiles = load_profile_registry().select(intent.parts, ProfileSelection()) + base = compile_score(compose_score(intent, profiles), profiles) + controls = [ + ScheduledControl(part="lead", beat=RationalBeat(numerator=4), controller=1, value=73), + ScheduledControl(part="lead", beat=RationalBeat(numerator=5), controller=91, value=64), + ] + actual = apply_scheduled_controls(base, controls, profiles) + assert [e for e in actual.tracks[0].events if not isinstance(e, ControlChangeEvent)] == ( + base.tracks[0].events + ) + assert [ + (e.tick, e.controller, e.value) + for e in actual.tracks[0].events + if isinstance(e, ControlChangeEvent) + ] == [(3840, 1, 73), (4800, 91, 64)] + assert actual.end_tick == base.end_tick == 7680 diff --git a/tests/unit/test_pitch.py b/tests/unit/test_pitch.py new file mode 100644 index 0000000..72da72e --- /dev/null +++ b/tests/unit/test_pitch.py @@ -0,0 +1,225 @@ +"""Notation atoms and register policy, with independent numeric pitch expectations.""" + +from typing import Literal + +import pytest + +from riff_groove_builder.pitch import ( + ChordSymbol, + ExplicitVoicing, + PitchToken, + parse_chord, + parse_pitch, + resolve_voicing, + tokenize_notation, +) +from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry +from riff_groove_builder.schemas import ProfileSelection + + +@pytest.fixture +def lead() -> InstrumentProfile: + return load_profile_registry().select(["lead"], ProfileSelection())["lead"] + + +@pytest.mark.parametrize( + ("text", "midi"), + [ + ("C4", 60), + ("E4", 64), + ("G4", 67), + ("F#3", 54), + ("Gb3", 54), + ("Bb2", 46), + ("Cb4", 59), + ("B#3", 60), + ("E#4", 65), + ("Fb4", 64), + ("C-1", 0), + ("C+4", 60), + ("G9", 127), + ], +) +def test_explicit_pitch_arithmetic(text: str, midi: int) -> None: + assert parse_pitch(text).midi == midi + assert parse_pitch(text).pitch_class == midi % 12 + + +@pytest.mark.parametrize( + "text", + [ + "", + "c4", + "H4", + "C##4", + "Dbb3", + "Fx4", + "C♯4", + "C 4", + " C4", + "C4 ", + "C4.0", + "C--1", + "C+-1", + "C10", + "C-2", + "G#9", + "Cb-1", + "A4junk", + "C4/E4", + ], +) +def test_invalid_pitch_symbols(text: str) -> None: + with pytest.raises(ValueError): + parse_pitch(text) + + +@pytest.mark.parametrize("text", ["F#", "D", "Bb", "Cb", "B#"]) +def test_octave_free_notes_are_unresolved(text: str) -> None: + note = parse_pitch(text) + assert note.octave is None + with pytest.raises(ValueError, match="register"): + _ = note.midi + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("F#", (42, 46, 49)), + ("D", (38, 42, 45)), + ("Bb", (46, 50, 53)), + ("Em4", (64, 67, 71)), + ("Emin4", (64, 67, 71)), + ("F#3", (54, 58, 61)), + ("Bb2", (46, 50, 53)), + ("Em4OverB", (59, 64, 67, 71)), + ("Em4/B", (59, 64, 67, 71)), + ("Em4OverB2", (47, 64, 67, 71)), + ("Em4/B2", (47, 64, 67, 71)), + ("Em(add4)", (40, 43, 45, 47)), + ("Em4(add4)", (64, 67, 69, 71)), + ("E4(add4)", (64, 68, 69, 71)), + ("Em4(add4)/B2", (47, 64, 67, 69, 71)), + ("[C3 E3 G3]", (48, 52, 55)), + ("[G3 C3 E3]", (48, 52, 55)), + ("[Cb4 F#4]", (59, 66)), + ], +) +def test_chord_voicings(lead: InstrumentProfile, text: str, expected: tuple[int, ...]) -> None: + resolved = resolve_voicing(parse_chord(text), lead) + assert resolved.pitches == expected + assert len(set(resolved.pitches)) == len(resolved.pitches) + + +def test_octave_and_bass_defaults_are_reported(lead: InstrumentProfile) -> None: + assert resolve_voicing(parse_pitch("E"), lead).pitches == (40,) + assert "nearest MIDI40" in resolve_voicing(parse_chord("F#"), lead).assumptions[0] + assert "MIDI42" in resolve_voicing(parse_chord("F#"), lead).assumptions[0] + default_bass = resolve_voicing(parse_chord("Em4OverB"), lead) + assert len(default_bass.assumptions) == 1 + assert "MIDI59" in default_bass.assumptions[0] + assert "strictly below" in default_bass.assumptions[0] + assert resolve_voicing(parse_chord("Em4OverB2"), lead).assumptions == () + assert resolve_voicing(parse_chord("[C4 E4 G4]"), lead).assumptions == () + + +@pytest.mark.parametrize( + "text", + [ + "", + "Emaj4", + "Emajor", + "Eminor4", + "Em7", + "E7", + "Esus4", + "Eadd4", + "Emadd4", + "Em4add4", + "Em(add2)", + "Em4(add4)(add4)", + "Eaug", + "Edim", + "Em4/B2junk", + "Em4/BB2", + "Em4Over", + "Em4/", + "[C E G]", + "[C4 C4]", + "[C4 B#3]", + "[]", + "[C4,E4,G4]", + "[C4 E4 G4", + "C4 E4", + "Em4//B2", + "E##4", + "C10", + "Cm-2", + ], +) +def test_invalid_or_unsupported_chords(lead: InstrumentProfile, text: str) -> None: + with pytest.raises(ValueError): + resolve_voicing(parse_chord(text), lead) + + +@pytest.mark.parametrize("text", ["Em4/B4", "Em4/E4", "Em4OverC5"]) +def test_contradictory_bass_is_not_revoiced(lead: InstrumentProfile, text: str) -> None: + with pytest.raises(ValueError, match="strictly below"): + resolve_voicing(parse_chord(text), lead) + + +@pytest.mark.parametrize("text", ["C7", "Em6", "Em4/B1", "[C2 E4 G7]", "G9"]) +def test_whole_voicing_must_fit_map_without_dropping(lead: InstrumentProfile, text: str) -> None: + with pytest.raises(ValueError): + resolve_voicing(parse_chord(text), lead) + + +@pytest.mark.parametrize("text", ["F#F#", "DD", "BbBb", "CEG"]) +@pytest.mark.parametrize("kind", ["note", "chord"]) +def test_deterministic_compact_runs(text: str, kind: Literal["note", "chord"]) -> None: + tokens = tokenize_notation(text, kind=kind) + expected = ["C", "E", "G"] if text == "CEG" else [text[: len(text) // 2]] * 2 + assert [token.text for token in tokens] == expected + assert "".join(token.text for token in tokens) == text + assert all(token.leading_space == "" for token in tokens) + + +def test_tokens_preserve_boundaries_and_spacing_without_guessing_time() -> None: + text = " F# F#\tDD BbBb Em4/B2[C3 E3 G3]" + tokens = tokenize_notation(text, kind="chord") + assert [t.text for t in tokens] == ["F#", "F#", "D", "D", "Bb", "Bb", "Em4/B2", "[C3 E3 G3]"] + assert [t.leading_space for t in tokens] == [" ", " ", "\t", "", " ", "", " ", ""] + assert all(text[t.start : t.end] == t.text for t in tokens) + assert isinstance(tokens[-1].value, ExplicitVoicing) + assert isinstance(tokens[-2].value, ChordSymbol) + assert [t.text for t in tokenize_notation("C4E4G4", kind="note")] == ["C4", "E4", "G4"] + assert [t.text for t in tokenize_notation("Emin4Em4(add4)", kind="chord")] == [ + "Emin4", + "Em4(add4)", + ] + + +@pytest.mark.parametrize( + "text", + ["F##F#", "D7x", "BbBbb", "Em4/B2/", "Em4(add)", "CEGX", "Em4?", "D-d", "C4~", "C4->E4"], +) +def test_compact_leftovers_are_errors(text: str) -> None: + with pytest.raises(ValueError): + tokenize_notation(text, kind="chord") + + +@pytest.mark.parametrize("text", ["", " \t ", "C" * 4001]) +def test_tokenizer_is_bounded(text: str) -> None: + with pytest.raises(ValueError): + tokenize_notation(text, kind="note") + + +def test_typed_tokens_reject_invalid_construction() -> None: + with pytest.raises(ValueError): + PitchToken("C", octave=True) + with pytest.raises(ValueError): + PitchToken("H") + with pytest.raises(ValueError): + ExplicitVoicing((parse_pitch("C4"), parse_pitch("B#3"))) + with pytest.raises(ValueError): + ExplicitVoicing((parse_pitch("C"),)) diff --git a/tests/unit/test_profiles.py b/tests/unit/test_profiles.py new file mode 100644 index 0000000..69eef43 --- /dev/null +++ b/tests/unit/test_profiles.py @@ -0,0 +1,444 @@ +"""Synthetic mechanics and registry-policy tests, never production mapping evidence.""" + +import json +from pathlib import Path +from typing import Any +from unittest.mock import Mock + +import pytest +from pydantic import ValidationError + +from riff_groove_builder.errors import ProfileNotFoundError, ProfileRequiredError +from riff_groove_builder.profiles import ( + AmbiguousProfileError, + InstrumentProfile, + InvalidProfileError, + ProfilePartMismatchError, + ProfileRegistry, + ProfileRegistryError, + checked_profile, + load_profile_registry, + normalize_name, + parse_profile, +) +from riff_groove_builder.schemas import Part, ProfileSelection + +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "profiles" + + +def payload(part: str = "lead") -> dict[str, Any]: + data: dict[str, Any] = json.loads((FIXTURES / f"synthetic-{part}.json").read_text()) + return data + + +def attested(identifier: str = "fixture.one", *, default: bool = False) -> InstrumentProfile: + """In-memory policy fixture only: this attestation is NOT real mapping evidence.""" + data = payload() + data["id"] = data["summary"]["id"] = identifier + data["summary"]["product_name"] = "In-memory registry policy fixture" + data["provenance"]["status"] = "verified" + data["provenance"]["sources"] = [ + { + "kind": "lawful_local", + "reference": "TEST-HARNESS-NOT-VENDOR-EVIDENCE", + "aspects": [ + "identity", + "range_or_voices", + "channels", + "actions", + "state_reset", + "timing", + "velocity", + ], + } + ] + data["default"] = default + return InstrumentProfile.model_validate(data) + + +@pytest.mark.parametrize("part", ["lead", "bass", "drums"]) +def test_synthetic_json_roundtrip(part: str) -> None: + profile = parse_profile((FIXTURES / f"synthetic-{part}.json").read_bytes()) + assert profile.provenance.status == "test_only" + assert profile.summary.product_name.startswith("SYNTHETIC ") + assert not profile.summary.native_available + assert parse_profile(profile.model_dump_json()) == profile + with pytest.raises(ProfileRegistryError, match="resources failed"): + ProfileRegistry([profile]) + + +@pytest.mark.parametrize( + "document", + [ + "{", + "null", + "[]", + '{"schema_version":"1","schema_version":"2"}', + b"\xff", + ], +) +def test_bad_documents(document: str | bytes) -> None: + with pytest.raises(InvalidProfileError) as error: + parse_profile(document) + assert error.value.details == {"reason": "invalid_profile_document"} + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("schema_version", "2"), + ("schema_version", 1), + ("schema_version", True), + ("channel", 16), + ("channel", -1), + ("channel", True), + ("channel", 2.0), + ("default", "false"), + ("id", "../bad"), + ("id", "bad\n"), + ("unknown", 1), + ("playable_range", None), + ("normal_articulation", "undeclared"), + ], +) +def test_strict_profile_fields(field: str, value: object) -> None: + data = payload() + data[field] = value + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +@pytest.mark.parametrize( + ("section", "field", "value"), + [ + ("summary", "id", "wrong"), + ("summary", "part", "bass"), + ("summary", "midi_available", False), + ("summary", "native_available", True), + ("summary", "product_version", "different"), + ("summary", "mapping_version", "other"), + ("summary", "supported_articulations", ["normal"]), + ("summary", "limitations", []), + ("provenance", "status", "verified"), + ("provenance", "target_build", ""), + ("provenance", "mapping_preset", ""), + ("provenance", "limitations", []), + ], +) +def test_inconsistent_identity_and_provenance(section: str, field: str, value: object) -> None: + data = payload() + data[section][field] = value + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +def test_no_accidental_test_promotion() -> None: + data = payload() + data["default"] = True + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + policy_fixture = attested().model_dump() + policy_fixture["id"] = policy_fixture["summary"]["id"] = "test.promoted" + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(policy_fixture) + data = payload() + data["provenance"]["sources"] = attested().provenance.model_dump()["sources"] + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +@pytest.mark.parametrize("name", ["Palm Mute", "PALM-MUTE", " palm__mute ", "palm_mute"]) +def test_alias_normalization(name: str) -> None: + profile = InstrumentProfile.model_validate(payload()) + assert normalize_name(name) == "palm_mute" + assert profile.resolve_articulation(name).name == "palm_mute" + + +@pytest.mark.parametrize("alias", ["NORMAL", "palm mute", "PM", "bad\tname", "é", ""]) +def test_alias_collisions_and_bad_names(alias: str) -> None: + data = payload() + data["articulations"][0]["aliases"].append(alias) + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("note", -1), + ("note", 128), + ("velocity", 0), + ("velocity", True), + ("behavior", "unknown"), + ("gate", {"numerator": 0}), + ("lead", {"numerator": -1}), + ("release_offset", {"numerator": 1}), + ], +) +def test_switch_validation(field: str, value: object) -> None: + data = payload() + data["articulations"][0]["actions"][0][field] = value + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("controller", 128), + ("value", -1), + ("reset_value", 0), + ("release_offset", {"numerator": 1}), + ], +) +def test_latched_cc_validation(field: str, value: object) -> None: + data = payload() + data["articulations"][0]["actions"][1][field] = value + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +def test_controls_and_state_validation() -> None: + data = payload("bass") + data["articulations"][1]["actions"][1]["reset_value"] = None + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + data = payload() + data["articulations"][0]["actions"].append(data["articulations"][0]["actions"][0]) + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + data = payload() + data["articulations"][0]["actions"] = [] + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + data = payload() + data["articulations"][1]["actions"] = data["articulations"][1]["actions"][:1] + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +@pytest.mark.parametrize( + ("index", "field", "value"), + [ + (0, "low", 0.1), + (1, "high", 0.9), + (0, "high", 0.6), + (0, "high", 0.4), + (0, "high", 0.0), + (0, "velocity_low", 0), + (0, "velocity_high", 128), + (0, "velocity_low", 60), + (0, "velocity_high", 90), + (0, "velocity_high", 80), + ], +) +def test_layer_gaps_overlap_and_ranges(index: int, field: str, value: object) -> None: + data = payload() + data["articulations"][1]["layers"][index][field] = value + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +@pytest.mark.parametrize( + ("intensity", "velocity"), + [ + (0.0, 30), + (0.25, 40), + (0.499999, 50), + (0.5, 80), + (0.75, 90), + (1.0, 100), + ], +) +def test_layer_endpoints(intensity: float, velocity: int) -> None: + art = InstrumentProfile.model_validate(payload()).resolve_articulation("pm") + assert art.velocity(intensity) == velocity + + +@pytest.mark.parametrize(("intensity", "expected"), [(0.25, 32), (0.75, 96)]) +def test_velocity_rounds_complete_interpolation_ties_to_even( + intensity: float, + expected: int, +) -> None: + art = InstrumentProfile.model_validate(payload()).resolve_articulation("normal") + assert art.velocity(intensity) == expected + + +@pytest.mark.parametrize("intensity", [-1.0, 1.01, float("inf"), float("nan"), True]) +def test_invalid_intensities(intensity: float) -> None: + art = InstrumentProfile.model_validate(payload()).resolve_articulation("pm") + with pytest.raises(InvalidProfileError): + art.velocity(intensity) + + +def test_ranges_voices_and_switch_collisions() -> None: + data = payload() + data["playable_range"] = {"low": 90, "high": 48} + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + data["playable_range"] = {"low": 1, "high": 84} + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + drums = InstrumentProfile.model_validate(payload("drums")) + assert drums.resolve_voice("LOW") == 36 + for field, value in [("aliases", ["high"]), ("note", 40), ("note", 128)]: + data = payload("drums") + data["drum_voices"][0][field] = value + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + data = payload("drums") + data["drum_voices"] = [] + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +def test_registry_selection_and_copies() -> None: + registry = ProfileRegistry([attested(default=True), attested("fixture.two")]) + assert registry.select(["lead"], ProfileSelection())["lead"].id == "fixture.one" + assert registry.select(["lead"], ProfileSelection(lead="fixture.two"))["lead"].id == ( + "fixture.two" + ) + summaries = registry.summaries() + assert [p.id for p in summaries] == ["fixture.one", "fixture.two"] + summaries[0].product_name = "modified outside registry" + assert registry.summaries()[0].product_name != summaries[0].product_name + with pytest.raises(ProfileNotFoundError): + registry.select(["lead"], ProfileSelection(lead="test.lead.v1")) + with pytest.raises(ProfilePartMismatchError): + registry.select(["bass"], ProfileSelection(bass="fixture.one")) + with pytest.raises(ProfilePartMismatchError): + registry.select(["bass"], ProfileSelection(lead="fixture.one")) + with pytest.raises(ProfileRequiredError) as error: + registry.select(["drums"], ProfileSelection()) + assert error.value.details["reason"] == "verified_mapping_required" + + +def test_ambiguous_and_duplicate_registry_entries() -> None: + for entries, reason in [ + ([attested(), attested()], "duplicate_profile_id"), + ([attested(default=True), attested("fixture.two", default=True)], "duplicate_default"), + ]: + with pytest.raises(ProfileRegistryError) as error: + ProfileRegistry(entries) + assert error.value.details["reason"] == reason + for entries in [[attested()], [attested(), attested("fixture.two")]]: + with pytest.raises(AmbiguousProfileError) as ambiguous: + ProfileRegistry(entries).select(["lead"], ProfileSelection()) + assert ambiguous.value.details["available_ids"] == [p.id for p in entries] + invalid_parts: list[list[Part]] = [[], ["lead", "lead"]] + for parts in invalid_parts: + with pytest.raises(ProfilePartMismatchError): + ProfileRegistry([]).select(parts, ProfileSelection()) + + +def test_mutated_models_revalidated() -> None: + profile = InstrumentProfile.model_validate(payload()) + profile.channel = 99 + with pytest.raises(InvalidProfileError): + checked_profile(profile) + with pytest.raises(InvalidProfileError): + ProfileRegistry([profile]) + + +@pytest.mark.parametrize( + "missing_aspect", + [ + "identity", + "range_or_voices", + "channels", + "actions", + "state_reset", + "timing", + "velocity", + ], +) +def test_verified_attestation_requires_complete_coverage(missing_aspect: str) -> None: + data = attested().model_dump() + data["provenance"]["sources"][0]["aspects"].remove(missing_aspect) + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +def test_source_identity_cannot_satisfy_native_gate() -> None: + data = attested().model_dump() + data["summary"]["native_available"] = True + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + data = attested().model_dump() + source = data["provenance"]["sources"][0] + source["kind"], source["reference"] = "official_public", "http://example.invalid" + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + source["reference"] = "https://example.invalid/TEST-ONLY-NOT-EVIDENCE" + source["aspects"].append("timing") + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +def test_packaged_registry_has_target_defaults_and_explicit_standard_fallbacks() -> None: + registry = load_profile_registry() + assert [summary.id for summary in registry.summaries()] == [ + "ample.ame.4.0.1.riffer.v1", + "ample.amr.4.1.0.riffer.v1", + "standard.bass.v1", + "standard.gm-drums.v1", + "standard.lead.v1", + "toontrack.sd3.3.4.4.core.v1", + ] + assert [summary.mapping_kind for summary in registry.summaries()] == [ + "instrument", + "instrument", + "standard_midi", + "standard_midi", + "standard_midi", + "instrument", + ] + selected = registry.select(["lead", "bass", "drums"], ProfileSelection()) + assert {part: p.channel for part, p in selected.items()} == {"lead": 0, "bass": 1, "drums": 9} + for part, profile in selected.items(): + assert profile.default and profile.provenance.status == "verified_subset" + assert profile.summary.native_available + assert registry.select([part], ProfileSelection(**{part: profile.id}))[part] == profile + standard_id = "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" + standard = registry.select([part], ProfileSelection(**{part: standard_id}))[part] + assert not standard.default and standard.provenance.status == "standard_midi" + assert not standard.summary.native_available + assert "NOT a verified" in standard.summary.product_name + with pytest.raises(ProfileNotFoundError): + registry.select(["lead"], ProfileSelection(lead="test.lead.v1")) + with pytest.raises(ProfilePartMismatchError): + registry.select(["bass"], ProfileSelection(bass="standard.lead.v1")) + + +@pytest.mark.parametrize("declared", [("missing.json",), ("../bad.json",), ("x.json", "x.json")]) +def test_missing_and_invalid_resource_manifests(declared: tuple[str, ...]) -> None: + with pytest.raises(ProfileRegistryError): + load_profile_registry(declared=declared) + + +def test_resource_access_failure_is_not_empty(monkeypatch: pytest.MonkeyPatch) -> None: + with pytest.raises(ProfileRegistryError) as error: + load_profile_registry(package="riff_groove_builder.no_such_package") + assert error.value.details["reason"] == "profile_resource_load_failed" + monkeypatch.setattr("riff_groove_builder.profiles.resources.files", Mock(side_effect=OSError)) + with pytest.raises(ProfileRegistryError): + load_profile_registry() + + +def test_loaded_resources_corrupt_or_synthetic(monkeypatch: pytest.MonkeyPatch) -> None: + root = Mock() + root.iterdir.return_value = [Mock(name="entry")] + root.iterdir.return_value[0].name = "fixture.json" + monkeypatch.setattr("riff_groove_builder.profiles.resources.files", lambda _: root) + with pytest.raises(ProfileRegistryError) as error: + load_profile_registry() + assert error.value.details["reason"] == "resource_manifest_mismatch" + root.joinpath.return_value.read_bytes.return_value = b"{" + with pytest.raises(InvalidProfileError): + load_profile_registry(declared=("fixture.json",)) + root.joinpath.return_value.read_bytes.return_value = ( + FIXTURES / "synthetic-lead.json" + ).read_bytes() + with pytest.raises(ProfileRegistryError) as error: + load_profile_registry(declared=("fixture.json",)) + assert error.value.details["reason"] == "synthetic_production_leakage" diff --git a/tests/unit/test_readme.py b/tests/unit/test_readme.py new file mode 100644 index 0000000..0a9cfb8 --- /dev/null +++ b/tests/unit/test_readme.py @@ -0,0 +1,125 @@ +"""Keep the public JSON examples executable against the current typed contracts.""" + +import json +import os +import re +from pathlib import Path +from typing import Any + +import pytest +from jsonschema import Draft202012Validator + +from riff_groove_builder.articulations import apply_scheduled_controls, compile_score +from riff_groove_builder.compose import compose_score +from riff_groove_builder.description import resolve_description +from riff_groove_builder.profiles import load_profile_registry +from riff_groove_builder.schemas import ( + GenerateMusicRequest, + GenerationError, + GenerationResult, + ProfileSelection, + tool_input_schema, + tool_output_schema, +) + +README = Path(__file__).resolve().parents[2] / "README.md" +EXAMPLES: list[dict[str, Any]] = [ + json.loads(block) + for block in re.findall(r"```json\n(.*?)\n```", README.read_text("utf-8"), re.S) +] + + +def test_readme_json_example_inventory() -> None: + assert len(EXAMPLES) == 7 + assert sum("description" in example for example in EXAMPLES) == 4 + + +def test_restart_prompt_exact_original_hybrid_description() -> None: + text = README.read_text("utf-8") + expected = ( + "Lead guitar in E minor, 4/4, 120 BPM, 2 bars.\n" + "Bar 1:\nCounts: 1 & 2 & 3 & [4 trip let]\n" + "Events: x x x x x x [x x ^]\n" + "Notes: E2 E2 E2 E2 E2 E2 E2 E2 E2\n" + "Hold the final E2 through the end of bar 2 without retriggering." + ) + description = re.search(r"\nBEGIN DESCRIPTION\n(.*?)\nEND DESCRIPTION\n", text, re.S) + assert description is not None and description.group(1) == expected + assert f"```text\n{expected}\n```" in text + arguments = { + "description": description.group(1), + "basename": "em_e2_hybrid_20261020_fresh_chat_01", + "allow_midi_fallback": False, + } + Draft202012Validator(tool_input_schema("generate_music")).validate(arguments) + request = GenerateMusicRequest.model_validate(arguments) + resolution = resolve_description(request) + assert resolution.intent.parts == ["lead"] and resolution.intent.key == "E minor" + assert request.seed == 0 and request.cc_events == [] and request.formats is None + + +def test_current_documentation_local_links() -> None: + root = README.parent + for path in [README, *(root / "docs").rglob("*.md")]: + for link in re.findall(r"(? None: + if "mcpServers" in example: + assert set(example) == {"mcpServers"} + server = example["mcpServers"]["riff-groove-builder"] + assert set(server) == {"command", "args"} + assert server["args"][:3] == ["-m", "riff_groove_builder", "--output-dir"] + assert all(isinstance(arg, str) for arg in [server["command"], *server["args"]]) + assert Path(server["command"]).is_absolute() + assert Path(server["args"][3]).is_absolute() + elif "description" in example: + Draft202012Validator(tool_input_schema("generate_music")).validate(example) + request = GenerateMusicRequest.model_validate(example) + resolution = resolve_description(request) + profiles = load_profile_registry().select( + resolution.intent.parts, request.profiles or ProfileSelection() + ) + plan = apply_scheduled_controls( + compile_score(compose_score(resolution.intent, profiles), profiles), + request.cc_events, + profiles, + ) + assert plan.musical_start_tick == 0 + if request.basename == "phrase-original": + assert set(example) == {"description", "basename"} + assert request.description == ( + "Please produce a 4/4 riff in Em. With Chugging palm muting " + "8th notes from 1 to 3&;\n" + "and triplets on 4&A with the A as a pinch harmonic " + "that carries over a whole note\n" + "in the 2nd measure." + ) + assert resolution.intent.parts == ["lead"] + assert profiles["lead"].id == "ample.ame.4.0.1.riffer.v1" + assert plan.musical_end_tick == 7680 + assert request.cc_events == [] and request.formats is None + else: + assert plan.musical_end_tick == 6720 + else: + payload = example.get("structuredContent", example) + Draft202012Validator(tool_output_schema("generate_music")).validate(payload) + if "code" in payload: + assert GenerationError.model_validate(payload).code == "NATIVE_FORMAT_UNAVAILABLE" + else: + result = GenerationResult.model_validate(payload) + assert result.status == "complete" and result.artifacts[0].size_bytes == 324 diff --git a/tests/unit/test_riffer.py b/tests/unit/test_riffer.py new file mode 100644 index 0000000..fc93a01 --- /dev/null +++ b/tests/unit/test_riffer.py @@ -0,0 +1,512 @@ +"""Original content only: independent native read-back, never factory sequence fixtures.""" + +import shutil +import uuid +import xml.etree.ElementTree as ET +from collections.abc import Iterator +from pathlib import Path +from unittest.mock import Mock + +import pytest +from pydantic import ValidationError + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.errors import ( + NativeFormatUnavailableError, + OutputExistsError, + OutputIOError, + SerializationError, +) +from riff_groove_builder.formats.agp import ( + check_riffer_capability, + validate_riffer_file, + write_riffer, +) +from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry, parse_profile +from riff_groove_builder.schemas import ( + ControlChangeEvent, + EventPlan, + MusicalIntent, + NoteOffEvent, + Part, + PitchedNote, + PositiveBeat, + ProfileSelection, + RationalBeat, + Score, + ScoreTrack, + TimeSignature, +) + +ROOT = Path(__file__).resolve().parents[2] + + +def target(part: Part) -> InstrumentProfile: + identifier = "ample.ame.4.0.1.riffer.v1" if part == "lead" else "ample.amr.4.1.0.riffer.v1" + return load_profile_registry().select([part], ProfileSelection(**{part: identifier}))[part] + + +def original_plan(part: Part, *, ppq: int = 960) -> tuple[EventPlan, InstrumentProfile]: + assert part in ("lead", "bass") + profile = target(part) + assert profile.playable_range is not None + low = profile.playable_range.low + high = profile.playable_range.high + score = Score( + intent=MusicalIntent( + description="Original codec verification chord and palm mute, not a factory sequence.", + parts=[part], + tempo_bpm=123.5, + bars=1, + time_signature=TimeSignature(numerator=4, denominator=4), + key="C minor", + seed=17, + ), + start=RationalBeat(numerator=0), + end=RationalBeat(numerator=4), + tracks=[ + ScoreTrack( + part=part, + notes=[ + PitchedNote( + part=part, + pitch=pitch, + start=RationalBeat(numerator=start), + duration=PositiveBeat(numerator=1), + intensity=intensity, + articulation=articulation, + ) + for pitch, start, intensity, articulation in ( + (low, 0, 0.0, "normal"), + (high, 0, 1.0, "normal"), + (low + 2, 2, 0.5, "palm_mute"), + ) + ], + ) + ], + ) + plan = compile_score(score, {part: profile}, ppq=ppq) + for tick, value in ((0, 0), (ppq, 120), (ppq * 3, 0)): + plan.tracks[0].events.append( + ControlChangeEvent( + tick=tick, + part=part, + channel=profile.channel, + priority=10, + sequence=100 + tick, + controller=1, + value=value, + ) + ) + plan.tracks[0].events.sort(key=lambda e: e.ordering_key) + for event in plan.tracks[0].events: + if isinstance(event, NoteOffEvent) and event.role == "musical_note": + event.velocity = 45 + return plan, profile + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"riffer-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +@pytest.mark.parametrize("part", ["lead", "bass"]) +def test_target_profiles_are_real_default_subsets(part: Part) -> None: + profile = target(part) + assert profile.default + assert profile.provenance.status == "verified_subset" + assert profile.summary.native_available and profile.summary.midi_available + assert check_riffer_capability(part, profile).available + assert profile.riffer is not None + assert profile.riffer.layout_version == "2.1" + assert profile.summary.native_format == profile.riffer.extension + assert parse_profile(profile.model_dump_json()) == profile + assert load_profile_registry().select([part], ProfileSelection())[part].summary.native_available + assert all( + "\\" not in source.reference and not source.reference.startswith(("C:", "D:")) + for source in profile.provenance.sources + ) + + +@pytest.mark.parametrize("part", ["lead", "bass"]) +@pytest.mark.parametrize("intensity", [0.0, 0.25, 0.5, 0.75, 1.0]) +def test_evidenced_keyswitches_and_velocity_bands(part: Part, intensity: float) -> None: + profile = target(part) + for name, switch in (("normal", 24), ("palm_mute", 26 if part == "lead" else 24)): + art = profile.resolve_articulation(name) + assert art.actions[0].kind == "keyswitch" and art.actions[0].note == switch + bounds = (64, 126) if name == "normal" else ((1, 127) if part == "lead" else (32, 63)) + assert art.velocity(intensity) == round(bounds[0] + (bounds[1] - bounds[0]) * intensity) + + +@pytest.mark.parametrize( + "mutation", + [ + "version", + "layout", + "ppq", + "ppq_bool", + "extension", + "instrument", + "order", + "tuning", + "frets", + "controller", + "controller_bool", + "articulation", + "default_type", + "range", + "provenance", + "policy", + "velocity", + "switch", + "lead", + "gate", + "normal", + ], +) +def test_native_subset_settings_are_strict(mutation: str) -> None: + data = target("lead").model_dump() + native = data["riffer"] + if mutation == "version": + data["summary"]["product_version"] = data["provenance"]["product_version"] = "4.0.2" + elif mutation == "layout": + native["layout_version"] = "2.2" + elif mutation == "ppq": + native["ppq"] = 960 + elif mutation == "ppq_bool": + native["ppq"] = True + elif mutation == "extension": + native["extension"] = "briff" + elif mutation == "instrument": + native["instrument"] = "AMR" + elif mutation == "order": + native["strings"].reverse() + elif mutation == "tuning": + native["strings"][0]["open_note"] = 37 + elif mutation == "frets": + native["strings"][0]["max_fret"] = 23 + elif mutation == "controller": + native["controllers"] = [2] + elif mutation == "controller_bool": + native["controllers"] = [True] + elif mutation == "articulation": + native["articulations"]["normal"] = "PM" + elif mutation == "default_type": + data["default"] = "yes" + elif mutation == "range": + data["playable_range"]["high"] = 100 + elif mutation == "provenance": + data["provenance"]["status"] = "standard_midi" + elif mutation == "policy": + data["provenance"]["sources"].pop() + elif mutation == "velocity": + data["articulations"][0]["layers"][0]["velocity_low"] = 2 + elif mutation == "switch": + data["articulations"][0]["actions"][0]["note"] = 25 + elif mutation == "lead": + data["articulations"][0]["actions"][0]["lead"]["numerator"] = 1 + elif mutation == "gate": + data["articulations"][0]["actions"][0]["gate"]["denominator"] = 64 + else: + data["normal_articulation"] = "palm_mute" + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +@pytest.mark.parametrize("part", ["lead", "bass"]) +@pytest.mark.parametrize("ppq", [480, 960, 1920]) +def test_real_xml_writer_and_independent_readback(workspace: Path, part: Part, ppq: int) -> None: + plan, profile = original_plan(part, ppq=ppq) + path = workspace / f"original.{profile.summary.native_format}" + before = plan.model_dump() + assert write_riffer(path, plan, part, profile) == path + result = validate_riffer_file(path, plan, part, profile) + assert len(result.notes) == 3 and result.end_tick == 1920 + assert result.cc1 == ((0, 0), (480, 120), (1440, 0)) + assert {n.articulation for n in result.notes} == {"Sus", "PM" if part == "lead" else "PMP"} + assert {n.off_velocity for n in result.notes} == {45} + assert all(n.begin in (0, 960) and n.end in (480, 1440) for n in result.notes) + root = ET.parse(path).getroot() + assert root.tag == "Riff" and root.get("Inst") == ("AME" if part == "lead" else "AMR") + assert root.get("Ver") == "2.1" and root.get("PPQBase") == "480" + assert plan.model_dump() == before + assert list(workspace.iterdir()) == [path] + + +@pytest.mark.parametrize( + "mutation", + [ + "version", + "ppq", + "target", + "tempo", + "meter", + "key", + "bars", + "loop", + "pitch", + "fret", + "begin", + "end", + "velocity", + "off_velocity", + "articulation", + "legato", + "muted", + "string", + "delete_note", + "extra_note", + "extra_child", + "cc_value", + "cc_tick", + "cc_curve", + "cc_delete", + "cc_duplicate", + "root_text", + "note_text", + "doctype", + ], +) +def test_saved_file_validator_detects_corruption_independently( + workspace: Path, mutation: str +) -> None: + plan, profile = original_plan("lead") + path = workspace / "original.griff" + write_riffer(path, plan, "lead", profile) + tree = ET.parse(path) + root = tree.getroot() + string = root.find("String") + note = root.find("String/Note") + point = root.find("cc-1.Mod/p") + assert string is not None and note is not None and point is not None + header_changes = { + "version": ("Ver", "2.2"), + "ppq": ("PPQBase", "960"), + "target": ("Inst", "AMR"), + "tempo": ("Tempo", "121"), + "meter": ("Time-Signature", "3/4"), + "key": ("Key", "Am"), + "bars": ("Measures", "2"), + "loop": ("loopEnd", "100"), + } + note_changes = { + "pitch": ("NoteID", "37"), + "fret": ("Fret", "1"), + "begin": ("Begin", "1"), + "end": ("End", "479"), + "velocity": ("Velocity", "2"), + "off_velocity": ("Off-Velocity", "44"), + "articulation": ("Articulation", "PM"), + "legato": ("Legato", "Legato Slide"), + "muted": ("Muted", "True"), + } + if mutation in header_changes: + root.set(*header_changes[mutation]) + elif mutation in note_changes: + note.set(*note_changes[mutation]) + elif mutation == "string": + string.set("ID", "1") + elif mutation == "delete_note": + string.remove(note) + elif mutation == "extra_note": + ET.SubElement(string, "Note", note.attrib) + elif mutation == "extra_child": + ET.SubElement(root, "Chord") + elif mutation == "cc_value": + point.set("value", "1") + elif mutation == "cc_tick": + point.set("tick", "2") + elif mutation == "cc_curve": + point.set("curveType", "curve") + elif mutation == "cc_delete": + root.remove(root[-1]) + elif mutation == "cc_duplicate": + ET.SubElement(root[-1], "p", point.attrib) + elif mutation == "root_text": + root.text = "unexpected content" + elif mutation == "note_text": + note.text = "unexpected content" + tree.write(path, encoding="utf-8", xml_declaration=True) + if mutation == "doctype": + path.write_bytes(b']>' + path.read_bytes()) + with pytest.raises(SerializationError) as error: + validate_riffer_file(path, plan, "lead", profile) + assert error.value.details["reason"] == "invalid_saved_riffer" + + +@pytest.mark.parametrize( + "mutation", + ["preroll", "tail", "note_missing", "switch_missing", "wrong_channel", "cc2", "cc_same_tick"], +) +def test_unsupported_or_mismatched_plan_is_not_silently_dropped( + workspace: Path, mutation: str +) -> None: + plan, profile = original_plan("lead") + if mutation == "preroll": + plan.musical_start_tick += 2 + plan.musical_end_tick += 2 + plan.end_tick += 2 + for event in plan.tracks[0].events: + event.tick += 2 + elif mutation == "tail": + plan.end_tick += 2 + elif mutation in ("note_missing", "switch_missing"): + role = "musical_note" if mutation == "note_missing" else "keyswitch" + pitch = 36 if mutation == "note_missing" else 24 + plan.tracks[0].events = [ + e + for e in plan.tracks[0].events + if not (e.kind != "control_change" and e.role == role and e.note == pitch) + ] + elif mutation == "wrong_channel": + for event in plan.tracks[0].events: + event.channel = 3 + else: + point = next(e for e in plan.tracks[0].events if isinstance(e, ControlChangeEvent)) + if mutation == "cc2": + point.controller = 2 + else: + duplicate = point.model_copy(update={"sequence": 999}) + plan.tracks[0].events.append(duplicate) + path = workspace / "must-not-exist.griff" + with pytest.raises(SerializationError): + write_riffer(path, plan, "lead", profile) + assert not path.exists() + + +@pytest.mark.parametrize("suffix", [".agp", ".mid", ".briff", ".GRIFF", ""]) +def test_wrong_suffix_fails_before_io(workspace: Path, suffix: str) -> None: + plan, profile = original_plan("lead") + path = workspace / "never-created" / ("wrong" + suffix) + with pytest.raises(SerializationError) as error: + write_riffer(path, plan, "lead", profile) + assert error.value.details["reason"] == "wrong_native_suffix" + assert not path.parent.exists() + + +def test_writer_exclusive_creation_and_no_parent_creation(workspace: Path) -> None: + plan, profile = original_plan("lead") + path = workspace / "existing.griff" + path.write_bytes(b"operator-owned") + with pytest.raises(OutputExistsError): + write_riffer(path, plan, "lead", profile) + assert path.read_bytes() == b"operator-owned" + with pytest.raises(OutputIOError): + write_riffer(workspace / "absent" / "original.griff", plan, "lead", profile) + assert list(workspace.iterdir()) == [path] + + +def test_no_codec_from_standard_profile_and_no_io(workspace: Path) -> None: + plan, _ = original_plan("lead") + profile = load_profile_registry().select(["lead"], ProfileSelection(lead="standard.lead.v1"))[ + "lead" + ] + with pytest.raises(NativeFormatUnavailableError): + write_riffer(workspace / "original.griff", plan, "lead", profile) + assert not list(workspace.iterdir()) + + +def test_no_fake_success_if_serializer_loses_notes( + workspace: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + plan, profile = original_plan("lead") + monkeypatch.setattr("riff_groove_builder.formats.agp._serialize", Mock(return_value=b"")) + with pytest.raises(SerializationError): + write_riffer(workspace / "broken.griff", plan, "lead", profile) + + +def test_rational_grid_rejected_instead_of_rounded(workspace: Path) -> None: + plan, profile = original_plan("lead", ppq=6720) + plan.score.tracks[0].notes[2].start = RationalBeat(numerator=13, denominator=7) + # The logical score compiles exactly at 6720 PPQ, but not at native PPQ 480. + plan = compile_score(plan.score, {"lead": profile}, ppq=6720) + with pytest.raises(SerializationError) as error: + write_riffer(workspace / "off-grid.griff", plan, "lead", profile) + assert error.value.details["reason"] == "off_grid_beats" + + +@pytest.mark.parametrize("impossible", [False, True]) +def test_physical_assignment_backtracks_or_rejects_without_dropping( + workspace: Path, impossible: bool +) -> None: + plan, profile = original_plan("lead") + notes = plan.score.tracks[0].notes + assert isinstance(notes[0], PitchedNote) and isinstance(notes[1], PitchedNote) + notes[0].pitch = 36 if impossible else 62 + notes[0].duration = PositiveBeat(numerator=2) + notes[1].pitch = 37 if impossible else 84 + notes[1].start = RationalBeat(numerator=1) + notes.pop() + plan = compile_score(plan.score, {"lead": profile}) + path = workspace / "assignment.griff" + if impossible: + with pytest.raises(SerializationError) as error: + write_riffer(path, plan, "lead", profile) + assert error.value.details["reason"] == "no_physical_string_assignment" + assert not path.exists() + else: + write_riffer(path, plan, "lead", profile) + readback = validate_riffer_file(path, plan, "lead", profile) + assert len(readback.notes) == 2 + assert next(n for n in readback.notes if n.pitch == 62).string != 1 + assert next(n for n in readback.notes if n.pitch == 84).string == 1 + assert readback.cc1 == () + + +@pytest.mark.parametrize("empty", [False, True]) +def test_exact_triplets_score_origin_and_empty_score(workspace: Path, empty: bool) -> None: + plan, profile = original_plan("bass") + plan.score.start = RationalBeat(numerator=8) + plan.score.end = RationalBeat(numerator=12) + for note in plan.score.tracks[0].notes: + note.start.numerator += 8 + if empty: + plan.score.tracks[0].notes.clear() + else: + plan.score.tracks[0].notes.pop() + for note in plan.score.tracks[0].notes: + note.start = RationalBeat(numerator=25, denominator=3) + note.duration = PositiveBeat(numerator=1, denominator=3) + plan = compile_score(plan.score, {"bass": profile}) + path = workspace / "triplets.briff" + write_riffer(path, plan, "bass", profile) + readback = validate_riffer_file(path, plan, "bass", profile) + assert len(readback.notes) == (0 if empty else 2) + assert all((n.begin, n.end) == (160, 320) for n in readback.notes) + assert readback.end_tick == 1920 + + +def test_saved_reader_rejects_physical_overlap_even_with_all_musical_notes( + workspace: Path, +) -> None: + plan, profile = original_plan("lead") + notes = plan.score.tracks[0].notes + assert isinstance(notes[0], PitchedNote) + notes[0].pitch = 62 + notes[0].duration = PositiveBeat(numerator=2) + notes[1].start = RationalBeat(numerator=1) + notes.pop() + plan = compile_score(plan.score, {"lead": profile}) + path = workspace / "overlap.griff" + write_riffer(path, plan, "lead", profile) + tree = ET.parse(path) + strings = tree.getroot().findall("String") + moved: ET.Element | None = None + for string in strings[:-1]: + for note in list(string): + if note.get("NoteID") == "62": + string.remove(note) + note.set("Fret", "0") + moved = note + assert moved is not None + strings[-1].insert(0, moved) + tree.write(path, encoding="utf-8", xml_declaration=True) + with pytest.raises(SerializationError) as error: + validate_riffer_file(path, plan, "lead", profile) + assert error.value.details["reason"] == "invalid_saved_riffer" diff --git a/tests/unit/test_schemas.py b/tests/unit/test_schemas.py new file mode 100644 index 0000000..ab8c624 --- /dev/null +++ b/tests/unit/test_schemas.py @@ -0,0 +1,821 @@ +"""Synthetic contracts only: no instrument map, file publication, or music generation.""" + +import math +from fractions import Fraction + +import pytest +from jsonschema import Draft202012Validator +from pydantic import BaseModel, TypeAdapter, ValidationError + +from riff_groove_builder.schemas import ( + MAX_SCHEDULED_EVENTS, + Artifact, + ControlChangeEvent, + DrumNote, + EventPlan, + EventTrack, + GenerateMusicRequest, + GenerationResult, + ListInstrumentProfilesRequest, + MusicalIntent, + NoteOffEvent, + NoteOnEvent, + PitchedNote, + PositiveBeat, + ProfileListResult, + ProfileSelection, + ProfileSummary, + RationalBeat, + ResolvedGeneration, + ScheduledEvent, + Score, + ScoreTrack, + TimeSignature, + tool_input_schema, +) + + +def request(**updates: object) -> GenerateMusicRequest: + return GenerateMusicRequest.model_validate( + {"description": "A supported riff", "basename": "test_riff-1", **updates} + ) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("description", "x"), + ("description", "x" * 4000), + ("basename", "a"), + ("basename", "A" * 64), + ("parts", ["lead"]), + ("parts", ["bass"]), + ("parts", ["drums"]), + ("parts", ["lead", "bass", "drums"]), + ("formats", ["mid"]), + ("formats", ["agp"]), + ("formats", ["sdp"]), + ("formats", ["mid", "agp", "sdp"]), + ("tempo_bpm", 20), + ("tempo_bpm", 300), + ("tempo_bpm", 120.125), + ("bars", 1), + ("bars", 256), + ("time_signature", {"numerator": 1, "denominator": 1}), + ("time_signature", {"numerator": 16, "denominator": 16}), + ("key", "E minor"), + ("profiles", {}), + ( + "profiles", + {"lead": "synthetic-lead", "bass": "synthetic-bass", "drums": "synthetic-drums"}, + ), + ("seed", 0), + ("seed", 2_147_483_647), + ("allow_midi_fallback", False), + ("allow_midi_fallback", True), + ], +) +def test_request_valid_boundaries(field: str, value: object) -> None: + model = request(**{field: value}) + assert GenerateMusicRequest.model_validate_json(model.model_dump_json()) == model + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("description", ""), + ("description", " \t\n"), + ("description", "x" * 4001), + ("description", 10), + ("description", None), + ("basename", ""), + ("basename", "a" * 65), + ("basename", 1), + ("basename", None), + ("parts", []), + ("parts", ["lead", "lead"]), + ("parts", ["guitar"]), + ("parts", "lead"), + ("formats", []), + ("formats", ["mid", "mid"]), + ("formats", ["wav"]), + ("formats", "mid"), + ("tempo_bpm", 19.999), + ("tempo_bpm", 300.001), + ("tempo_bpm", True), + ("tempo_bpm", False), + ("tempo_bpm", "120"), + ("tempo_bpm", math.nan), + ("tempo_bpm", math.inf), + ("tempo_bpm", -math.inf), + ("bars", 0), + ("bars", 257), + ("bars", True), + ("bars", 4.0), + ("bars", "4"), + ("bars", math.nan), + ("bars", math.inf), + ("time_signature", {"numerator": 0, "denominator": 4}), + ("time_signature", {"numerator": 17, "denominator": 4}), + ("time_signature", {"numerator": True, "denominator": 4}), + ("time_signature", {"numerator": 4.0, "denominator": 4}), + ("time_signature", {"numerator": 4, "denominator": 3}), + ("time_signature", {"numerator": 4, "denominator": True}), + ("time_signature", {"numerator": 4, "denominator": 4.0}), + ("time_signature", {"numerator": 4, "denominator": "4"}), + ("time_signature", {"numerator": 4}), + ("time_signature", {"numerator": 4, "denominator": 4, "extra": 1}), + ("profiles", {"lead": ""}), + ("profiles", {"bass": " "}), + ("profiles", {"drums": 1}), + ("profiles", {"guitar": "unknown"}), + ("profiles", []), + ("seed", -1), + ("seed", 2_147_483_648), + ("seed", True), + ("seed", 0.0), + ("seed", "0"), + ("seed", None), + ("allow_midi_fallback", 0), + ("allow_midi_fallback", "true"), + ("allow_midi_fallback", None), + ("output_root", r"C:\private"), + ], +) +def test_request_invalid_boundaries(field: str, value: object) -> None: + with pytest.raises(ValidationError): + request(**{field: value}) + + +@pytest.mark.parametrize( + "basename", + [ + "CON", + "con", + "CoN", + "PRN", + "aux", + "NUL", + "COM1", + "com9", + "LPT1", + "lPt9", + "../escape", + r"..\escape", + "/absolute", + r"C:\absolute", + r"\\host\share", + "a/b", + "a\\b", + ".", + "..", + "a.", + "a ", + " a", + "a..b", + "a:b", + "a\n", + "_riff", + "-riff", + "é", + "CON.txt", + "CONIN$", + "COM¹", + "a\x00", + ], +) +def test_unsafe_basenames(basename: str) -> None: + with pytest.raises(ValidationError): + request(basename=basename) + + +@pytest.mark.parametrize("basename", ["CON_1", "con-riff", "COM0", "COM10", "LPT0", "NULx", "9"]) +def test_safe_reserved_name_neighbors(basename: str) -> None: + assert request(basename=basename).basename == basename + + +@pytest.mark.parametrize( + ("raw", "normalized"), + [ + ("C major", "C major"), + (" db MINOR ", "C# minor"), + ("Bb major", "A# major"), + ("f# mAjOr", "F# major"), + ("Cb minor", "B minor"), + ("B# major", "C major"), + ("E# minor", "F minor"), + ("Fb major", "E major"), + ("gb major", "F# major"), + ("Ab minor", "G# minor"), + ("E minor", "E minor"), + ("E Minor", "E minor"), + ("Em", "E minor"), + ("em", "E minor"), + (" F#m ", "F# minor"), + ("Bbm", "A# minor"), + ("Am", "A minor"), + ("Cbm", "B minor"), + ], +) +def test_key_normalization(raw: str, normalized: str) -> None: + Draft202012Validator(tool_input_schema("generate_music")).validate( + {"description": "riff", "basename": "x", "key": raw} + ) + assert request(key=raw).key == normalized + + +@pytest.mark.parametrize( + "key", + [ + "C", + "EM", + "E m", + "Emin", + "Em major", + "F##m", + "BBm", + "H major", + "C dorian", + "C major minor", + "C major D minor", + "C## major", + "Dbb minor", + "C#b major", + "DB major", + "D♭ major", + "C\tmajor", + "C\nmajor", + "Cmajor", + "C major\n", + ], +) +def test_invalid_keys(key: str) -> None: + assert not Draft202012Validator(tool_input_schema("generate_music")).is_valid( + {"description": "riff", "basename": "x", "key": key} + ) + with pytest.raises(ValidationError): + request(key=key) + + +def test_advertised_key_examples_match_schema_and_runtime() -> None: + from riff_groove_builder.schemas import KEY_PATTERN + + schema = tool_input_schema("generate_music") + key_schema = schema["properties"]["key"]["anyOf"][0] + assert key_schema["pattern"] == KEY_PATTERN + for example in key_schema["examples"]: + assert request(key=example).key is not None + Draft202012Validator(schema).validate( + {"description": "riff", "basename": "x", "key": example} + ) + + +def test_omissions_do_not_resolve_intent_or_choose_profiles() -> None: + minimal = request() + assert minimal.model_fields_set == {"description", "basename"} + assert minimal.model_dump(exclude_unset=True) == { + "description": "A supported riff", + "basename": "test_riff-1", + } + for field in ("parts", "formats", "tempo_bpm", "bars", "time_signature", "key", "profiles"): + assert getattr(minimal, field) is None + assert getattr(request(**{field: None}), field) is None + assert minimal.seed == 0 + assert minimal.allow_midi_fallback is True + assert ProfileSelection().selected() == {} + assert request(formats=["sdp"]).parts is None + assert request(profiles={"drums": "synthetic"}).parts is None + + +@pytest.mark.parametrize( + "updates", + [ + {"parts": ["drums"], "formats": ["agp"]}, + {"parts": ["bass"], "formats": ["sdp"]}, + {"parts": ["lead"], "profiles": {"bass": "synthetic"}}, + {"parts": ["bass", "drums"], "profiles": {"lead": "synthetic"}}, + ], +) +def test_explicit_incompatible_requests(updates: dict[str, object]) -> None: + with pytest.raises(ValidationError, match="requires|selected parts"): + request(**updates) + + +@pytest.mark.parametrize("denominator", [1, 2, 4, 8, 16]) +def test_exact_meter(denominator: int) -> None: + assert TimeSignature.model_validate( + {"numerator": 7, "denominator": denominator} + ).beats_per_bar == Fraction(28, denominator) + + +def summary(**updates: object) -> ProfileSummary: + return ProfileSummary.model_validate( + { + "id": "synthetic-only", + "part": "lead", + "instrument": "eclips", + "product_name": "Synthetic test metadata", + "product_version": "test", + "mapping_version": "test", + "midi_available": False, + "native_format": "griff", + "native_available": False, + "supported_articulations": [], + "limitations": ["No verified map or native capability."], + **updates, + } + ) + + +def test_profile_list_empty_and_unavailable_summaries() -> None: + assert ListInstrumentProfilesRequest.model_validate({}).model_dump() == {} + assert ProfileListResult(profiles=[]).model_dump() == {"profiles": []} + unavailable = summary() + assert unavailable.mapping_kind == "instrument" + assert unavailable.model_dump()["mapping_kind"] == "instrument" + assert ProfileSummary.model_json_schema()["properties"]["mapping_kind"]["default"] == ( + "instrument" + ) + available = summary( + id="other-synthetic", + midi_available=True, + native_available=True, + supported_articulations=["sustain"], + limitations=[], + ) + assert len(ProfileListResult(profiles=[unavailable, available]).profiles) == 2 + with pytest.raises(ValidationError, match="unique"): + ProfileListResult(profiles=[unavailable, unavailable]) + with pytest.raises(ValidationError): + ListInstrumentProfilesRequest.model_validate({"extra": 1}) + + +@pytest.mark.parametrize( + "updates", + [ + {"part": "bass"}, + {"instrument": "sd3"}, + {"native_format": "sdp"}, + {"limitations": []}, + {"midi_available": 1}, + {"native_available": "false"}, + {"id": " "}, + {"supported_articulations": ["sustain", "sustain"]}, + {"limitations": ["same", "same"]}, + {"private_path": "must not be exposed"}, + {"mapping_kind": "gm"}, + {"mapping_kind": True}, + {"mapping_kind": "standard_midi", "supported_articulations": ["slide"]}, + { + "mapping_kind": "standard_midi", + "supported_articulations": ["normal"], + "native_available": True, + }, + ], +) +def test_invalid_profile_summaries(updates: dict[str, object]) -> None: + with pytest.raises(ValidationError): + summary(**updates) + + +def intent() -> MusicalIntent: + return MusicalIntent.model_validate( + { + "description": "Synthetic score only", + "parts": ["lead"], + "tempo_bpm": 120, + "bars": 1, + "time_signature": {"numerator": 7, "denominator": 8}, + "key": "E minor", + "seed": 0, + } + ) + + +def note(**updates: object) -> PitchedNote: + return PitchedNote.model_validate( + { + "part": "lead", + "pitch": 60, + "start": {"numerator": 1, "denominator": 3}, + "duration": {"numerator": 1, "denominator": 3}, + "intensity": 0.5, + "articulation": "synthetic", + **updates, + } + ) + + +def score() -> Score: + return Score( + intent=intent(), + start=RationalBeat(numerator=0), + end=RationalBeat(numerator=7, denominator=2), + tracks=[ScoreTrack(part="lead", notes=[note()])], + ) + + +def test_rational_beats_and_score_round_trip() -> None: + assert RationalBeat(numerator=2, denominator=6).model_dump() == { + "numerator": 1, + "denominator": 3, + } + assert RationalBeat(numerator=0, denominator=17).value == 0 + model = score() + assert model.intent.duration_beats == Fraction(7, 2) + restored = Score.model_validate_json(model.model_dump_json()) + assert restored == model + logical = restored.tracks[0].notes[0] + assert logical.start.value + logical.duration.value == Fraction(2, 3) + assert sum((logical.duration.value for _ in range(300)), Fraction()) == 100 + assert ( + DrumNote.model_validate( + { + "voice": "synthetic_voice", + "start": {"numerator": 0}, + "duration": {"numerator": 1}, + "intensity": 1, + "articulation": "synthetic", + } + ).part + == "drums" + ) + + +@pytest.mark.parametrize( + ("model", "payload"), + [ + (RationalBeat, {"numerator": -1}), + (RationalBeat, {"numerator": True}), + (RationalBeat, {"numerator": 1.0}), + (RationalBeat, {"numerator": 1, "denominator": 0}), + (RationalBeat, {"numerator": 1, "denominator": -3}), + (RationalBeat, {"numerator": 1, "denominator": False}), + (RationalBeat, {"numerator": 1, "denominator": 3.0}), + (RationalBeat, {"value": "1/3"}), + (PositiveBeat, {"numerator": 0}), + ], +) +def test_invalid_rational_timing(model: type[BaseModel], payload: dict[str, object]) -> None: + with pytest.raises(ValidationError): + model.model_validate(payload) + + +@pytest.mark.parametrize( + "updates", + [ + {"pitch": -1}, + {"pitch": 128}, + {"pitch": True}, + {"pitch": 60.0}, + {"part": "drums"}, + {"voice": "kick"}, + {"articulation": " "}, + {"start": 0.5}, + {"duration": {"numerator": 0}}, + {"intensity": -0.01}, + {"intensity": 1.01}, + {"intensity": True}, + {"intensity": math.nan}, + {"intensity": math.inf}, + {"intensity": -math.inf}, + ], +) +def test_invalid_logical_notes(updates: dict[str, object]) -> None: + with pytest.raises(ValidationError): + note(**updates) + + +@pytest.mark.parametrize("pitch", [0, 127]) +@pytest.mark.parametrize("intensity", [0, 1]) +def test_logical_midi_range_not_instrument_certification(pitch: int, intensity: int) -> None: + assert note(pitch=pitch, intensity=intensity).pitch == pitch + + +def test_invalid_score_invariants() -> None: + data = score().model_dump() + updates: list[dict[str, object]] = [ + {"tracks": []}, + {"tracks": [score().tracks[0].model_dump()] * 2}, + {"end": {"numerator": 0}}, + {"end": {"numerator": 4}}, + {"start": {"numerator": 1}}, + {"tracks": [{"part": "bass", "notes": [note().model_dump()]}]}, + {"tracks": [{"part": "lead", "notes": [note(start={"numerator": 4}).model_dump()]}]}, + ] + for update in updates: + with pytest.raises(ValidationError): + Score.model_validate({**data, **update}) + with pytest.raises(ValidationError): + MusicalIntent.model_validate({**intent().model_dump(), "parts": []}) + + +def event(**updates: object) -> NoteOnEvent: + return NoteOnEvent.model_validate( + { + "tick": 0, + "part": "lead", + "channel": 0, + "priority": 2, + "sequence": 0, + "role": "musical_note", + "note": 60, + "velocity": 100, + **updates, + } + ) + + +@pytest.mark.parametrize( + "updates", + [ + {"tick": -1}, + {"tick": True}, + {"tick": 0.0}, + {"channel": -1}, + {"channel": 16}, + {"channel": True}, + {"channel": 1.0}, + {"priority": -1}, + {"priority": False}, + {"sequence": -1}, + {"note": -1}, + {"note": 128}, + {"note": True}, + {"velocity": 0}, + {"velocity": 128}, + {"velocity": True}, + {"velocity": 1.0}, + {"role": "articulation_control"}, + {"kind": "control_change"}, + {"controller": 1}, + {"value": 2}, + {"part": "guitar"}, + ], +) +def test_invalid_note_on_events(updates: dict[str, object]) -> None: + with pytest.raises(ValidationError): + event(**updates) + + +def test_discriminated_events_and_ranges() -> None: + adapter = TypeAdapter(ScheduledEvent) + for channel in (0, 15): + for number in (0, 127): + on = event(channel=channel, note=number, velocity=127, role="keyswitch") + assert adapter.validate_json(on.model_dump_json()) == on + base = {"tick": 0, "part": "lead", "channel": 0, "priority": 0, "sequence": 1} + off = NoteOffEvent.model_validate({**base, "role": "keyswitch", "note": 0}) + assert off.velocity == 0 + for number in (0, 127): + cc = ControlChangeEvent.model_validate({**base, "controller": number, "value": number}) + assert adapter.validate_json(cc.model_dump_json()) == cc + for update in ( + {"controller": -1}, + {"controller": 128}, + {"controller": True}, + {"value": -1}, + {"value": 128}, + {"value": True}, + {"note": 2}, + {"velocity": 1}, + {"role": "keyswitch"}, + ): + with pytest.raises(ValidationError): + ControlChangeEvent.model_validate({**cc.model_dump(), **update}) + for velocity in (-1, 128, True, 0.0): + with pytest.raises(ValidationError): + NoteOffEvent.model_validate({**off.model_dump(), "velocity": velocity}) + with pytest.raises(ValidationError): + adapter.validate_python({**event().model_dump(), "kind": "unknown"}) + with pytest.raises(ValidationError): + EventTrack(part="bass", events=[event()]) + with pytest.raises(ValidationError, match="ordering keys"): + EventTrack(part="lead", events=[event(), event()]) + + +def plan(**updates: object) -> EventPlan: + return EventPlan.model_validate( + { + "score": score(), + "musical_start_tick": 24, + "musical_end_tick": 3384, + "end_tick": 3400, + "tracks": [ + { + "part": "lead", + "events": [ + event(tick=0, role="keyswitch").model_dump(), + event(tick=24, sequence=1).model_dump(), + ], + } + ], + **updates, + } + ) + + +def test_event_plan_metadata_not_a_scheduler() -> None: + model = plan() + assert model.tracks[0].events[0].ordering_key == (0, 2, 0) + assert model.musical_end_tick - model.musical_start_tick == 3360 + assert EventPlan.model_validate_json(model.model_dump_json()) == model + + +@pytest.mark.parametrize( + "updates", + [ + {"musical_start_tick": -1}, + {"musical_end_tick": 20}, + {"musical_end_tick": 3385}, + {"end_tick": 3383}, + {"end_tick": True}, + {"ticks_per_quarter": 0}, + {"ticks_per_quarter": True}, + {"tracks": []}, + {"tracks": [{"part": "bass", "events": []}]}, + {"tracks": [{"part": "lead", "events": [event(tick=3401).model_dump()]}]}, + {"tracks": [{"part": "lead", "events": [event(tick=0).model_dump()]}]}, + {"tracks": [{"part": "lead", "events": [event(tick=3384).model_dump()]}]}, + ], +) +def test_invalid_event_plans(updates: dict[str, object]) -> None: + with pytest.raises(ValidationError): + plan(**updates) + + +def test_event_budget_boundary() -> None: + payload = plan().model_dump() + events = [event(tick=24, sequence=index).model_dump() for index in range(MAX_SCHEDULED_EVENTS)] + tracks = [{"part": "lead", "events": events}] + assert len(EventPlan.model_validate({**payload, "tracks": tracks}).tracks[0].events) == 100_000 + events.append(event(tick=24, sequence=MAX_SCHEDULED_EVENTS).model_dump()) + with pytest.raises(ValidationError, match="100,000"): + EventPlan.model_validate({**payload, "tracks": tracks}) + + +def result_data() -> dict[str, object]: + return { + "status": "complete", + "resolved": { + "parts": ["lead"], + "tempo_bpm": 120, + "bars": 1, + "time_signature": {"numerator": 4, "denominator": 4}, + "key": "E minor", + "seed": 0, + "profile_ids": {"lead": "synthetic-only"}, + "assumptions": [], + "overrides": [], + "musical_start_tick": 0, + "musical_end_tick": 3840, + "ticks_per_quarter": 960, + }, + "artifacts": [ + { + "format": "mid", + "parts": ["lead"], + "path": r"C:\synthetic\test.mid", + "size_bytes": 64, + "profile_ids": ["synthetic-only"], + "fallback_for": [], + } + ], + "warnings": [], + } + + +def test_success_and_fallback_result_invariants() -> None: + complete = GenerationResult.model_validate(result_data()) + assert GenerationResult.model_validate_json(complete.model_dump_json()) == complete + data = complete.model_dump() + data["status"] = "midi_fallback" + data["artifacts"][0]["fallback_for"] = ["lead"] + data["warnings"] = [ + {"code": "NATIVE_FORMAT_UNAVAILABLE", "part": "lead", "message": "Synthetic limitation."} + ] + fallback = GenerationResult.model_validate(data) + assert GenerationResult.model_validate_json(fallback.model_dump_json()) == fallback + assert ( + GenerationResult.model_validate( + { + **complete.model_dump(), + "warnings": [{"code": "ASSUMPTION", "part": None, "message": "Test"}], + } + ).status + == "complete" + ) + assert Artifact.model_validate( + { + **complete.artifacts[0].model_dump(), + "format": "griff", + "path": r"C:\synthetic\test.griff", + } + ).parts == ["lead"] + assert Artifact.model_validate( + { + **complete.artifacts[0].model_dump(), + "format": "sd3p", + "path": r"C:\synthetic\test.sd3p", + "parts": ["drums"], + "profile_ids": ["synthetic-drums"], + } + ).parts == ["drums"] + + +@pytest.mark.parametrize( + "updates", + [ + {"format": "wav"}, + {"size_bytes": 0}, + {"size_bytes": -1}, + {"size_bytes": True}, + {"size_bytes": 64.0}, + {"parts": []}, + {"parts": ["lead", "lead"]}, + {"format": "agp", "parts": ["lead", "bass"]}, + {"format": "agp", "parts": ["drums"]}, + {"format": "sdp", "parts": ["lead"]}, + {"format": "agp", "fallback_for": ["lead"]}, + {"fallback_for": ["drums"]}, + {"fallback_for": ["lead", "lead"]}, + {"path": "relative.mid"}, + {"path": r"C:relative.mid"}, + {"path": r"\relative.mid"}, + {"path": "C:\\file\n.mid"}, + {"profile_ids": []}, + {"profile_ids": ["synthetic-only", "synthetic-only"]}, + ], +) +def test_invalid_artifacts(updates: dict[str, object]) -> None: + artifact = GenerationResult.model_validate(result_data()).artifacts[0] + with pytest.raises(ValidationError): + Artifact.model_validate({**artifact.model_dump(), **updates}) + + +def test_invalid_claimed_results() -> None: + good = GenerationResult.model_validate(result_data()) + artifact = good.artifacts[0].model_dump() + resolved = good.resolved.model_dump() + warning = {"code": "NATIVE_FORMAT_UNAVAILABLE", "part": "lead", "message": "Synthetic"} + updates: list[dict[str, object]] = [ + {"status": "success"}, + {"artifacts": []}, + {"artifacts": [artifact, artifact]}, + {"artifacts": [{**artifact, "profile_ids": ["wrong"]}]}, + {"artifacts": [{**artifact, "parts": ["bass"]}]}, + {"artifacts": [{**artifact, "fallback_for": ["lead"]}]}, + {"warnings": [warning]}, + {"warnings": [{**warning, "part": "bass", "code": "OTHER"}]}, + {"status": "midi_fallback"}, + {"status": "midi_fallback", "warnings": [warning]}, + {"status": "midi_fallback", "artifacts": [{**artifact, "fallback_for": ["lead"]}]}, + {"resolved": {**resolved, "musical_end_tick": -1}}, + {"resolved": {**resolved, "musical_start_tick": 5000}}, + {"resolved": {**resolved, "profile_ids": {}}}, + {"resolved": {**resolved, "profile_ids": {"lead": "synthetic-only", "bass": "other"}}}, + { + "resolved": { + **resolved, + "parts": ["lead", "bass"], + "profile_ids": {"lead": "synthetic-only", "bass": "other"}, + } + }, + { + "status": "midi_fallback", + "warnings": [warning], + "artifacts": [{**artifact, "fallback_for": ["lead"]}, {**artifact, "format": "agp"}], + }, + { + "status": "midi_fallback", + "warnings": [{**warning, "part": None}], + "artifacts": [{**artifact, "fallback_for": ["lead"]}], + }, + ] + for update in updates: + with pytest.raises(ValidationError): + GenerationResult.model_validate({**good.model_dump(), **update}) + assert ( + ResolvedGeneration.model_validate({**resolved, "musical_start_tick": 3840}).musical_end_tick + == 3840 + ) + + +@pytest.mark.parametrize( + "model", + [ + request(), + summary(), + score(), + note(), + plan(), + event(), + TimeSignature(numerator=4, denominator=4), + ProfileSelection(), + ProfileListResult(profiles=[]), + GenerationResult.model_validate(result_data()), + ], +) +def test_unknown_fields_forbidden_on_all_contract_layers(model: BaseModel) -> None: + with pytest.raises(ValidationError, match="Extra inputs"): + type(model).model_validate({**model.model_dump(), "unsupported": True}) diff --git a/tests/unit/test_sd3p.py b/tests/unit/test_sd3p.py new file mode 100644 index 0000000..951ffe7 --- /dev/null +++ b/tests/unit/test_sd3p.py @@ -0,0 +1,454 @@ +"""Original generated fixtures only; no installed kit, factory song or network needed.""" + +import hashlib +import os +import shutil +import uuid +from collections.abc import Iterator +from fractions import Fraction +from pathlib import Path +from unittest.mock import Mock + +import pytest +from pydantic import ValidationError + +from riff_groove_builder.articulations import compile_score +from riff_groove_builder.errors import ( + NativeFormatUnavailableError, + OutputExistsError, + OutputIOError, + SerializationError, +) +from riff_groove_builder.formats import sdp +from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry +from riff_groove_builder.schemas import ( + ControlChangeEvent, + EventPlan, + NoteOffEvent, + NoteOnEvent, + ProfileSelection, + Score, +) + +ROOT = Path(__file__).resolve().parents[2] +TEMPLATE = ROOT / "tests" / "fixtures" / "sd3" / "original-template.sd3p" + + +def original_plan(*, ppq: int = 960) -> tuple[EventPlan, InstrumentProfile]: + profile = load_profile_registry().select( + ["drums"], ProfileSelection(drums="toontrack.sd3.3.4.4.core.v1") + )["drums"] + score = Score.model_validate_json(TEMPLATE.with_name("original-score.json").read_bytes()) + return compile_score(score, {"drums": profile}, ppq=ppq), profile + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"sd3p-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +def test_real_writer_and_independent_packed_readback_preserve_operator_state( + workspace: Path, +) -> None: + plan, profile = original_plan() + before = TEMPLATE.stat() + raw = TEMPLATE.read_bytes() + template = sdp.parse_sdp_project(raw) + assert len(template.source_notes) == 1 + info = sdp.inspect_sdp_template(TEMPLATE) + assert info.version == "3.4.4" and info.track_count == info.event_count == 1 + assert info.sha256 == hashlib.sha256(raw).hexdigest() + assert sdp.check_sdp_capability("drums", profile, template=TEMPLATE).available + path = workspace / "original.sd3p" + assert sdp.write_sdp(path, plan, "drums", profile, template=TEMPLATE) == path + saved = sdp.validate_sdp_file(path, plan, "drums", profile, template=TEMPLATE) + assert (saved.tempo_bpm, saved.meter, saved.start, saved.end) == ( + Fraction(275, 2), + (7, 8), + Fraction(0), + Fraction(7, 2), + ) + assert [(n.channel, n.pitch, n.velocity, n.start, n.end) for n in saved.notes] == [ + (9, 36, 1, Fraction(0), Fraction(1, 8)), + (9, 42, 64, Fraction(1, 4), Fraction(3, 8)), + (9, 38, 127, Fraction(3), Fraction(25, 8)), + ] + actual = path.read_bytes() + # Independent arithmetic, not the codec's packer/decoder. + events = next( + line.split()[1:] for line in actual.decode().splitlines() if line.startswith("Events ") + ) + assert [int(events[i]) for i in range(0, len(events), 3)] == [0x012499, 0x402A99, 0x7F2699] + assert int(events[6]) & 255 == 0x99 + assert 8332944 == 0x7F2690 # Independently verified genuine message, not its sequence. + assert ((8332944 >> 8) & 127, (8332944 >> 16) & 127) == (38, 127) + assert sdp.parse_sdp_project(actual).non_song_bytes == template.non_song_bytes + assert b"original-source.mid" not in actual + assert b"Original source song" not in actual + assert b"Offset 0" in actual and b"Offset 2" not in actual + assert TEMPLATE.read_bytes() == raw + after = TEMPLATE.stat() + assert (before.st_ino, before.st_size, before.st_mtime_ns) == ( + after.st_ino, + after.st_size, + after.st_mtime_ns, + ) + assert sorted(p.name for p in workspace.iterdir()) == ["original.sd3p"] + + +def test_optional_missing_template_is_the_only_target_capability_limitation( + workspace: Path, +) -> None: + plan, profile = original_plan() + assert sdp.check_sdp_capability("drums", profile).reason == "sdp_template_required" + for operation in ( + lambda: sdp.require_sdp_capability("drums", profile), + lambda: sdp.write_sdp(workspace / "absent.sd3p", plan, "drums", profile), + ): + with pytest.raises(NativeFormatUnavailableError) as error: + operation() + assert error.value.details["reason"] == "sdp_template_required" + with pytest.raises(OutputIOError): + sdp.check_sdp_capability("drums", profile, template=workspace / "absent.sd3p") + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize("ending", [b"", b"\0"]) +@pytest.mark.parametrize("crlf", [False, True]) +def test_quotes_braces_escapes_unicode_nul_and_line_endings( + workspace: Path, ending: bytes, crlf: bool +) -> None: + raw = TEMPLATE.read_bytes().replace(b"\r\n", b"\n") + raw = raw.replace(b"Not song data", "Original café {state}".encode()) + if crlf: + raw = raw.replace(b"\n", b"\r\n") + raw += ending + template = workspace / "template.sd3p" + template.write_bytes(raw) + plan, profile = original_plan() + output = workspace / "new.sd3p" + sdp.write_sdp(output, plan, "drums", profile, template=template) + assert sdp.parse_sdp_project(output.read_bytes()).non_song_bytes == ( + sdp.parse_sdp_project(raw).non_song_bytes + ) + assert output.read_bytes().endswith(ending or (b"\r\n" if crlf else b"\n")) + + +def test_replace_all_contiguous_source_tracks_and_clips(workspace: Path) -> None: + raw = TEMPLATE.read_bytes() + project = sdp.parse_sdp_project(raw) + fields = project.tracks[0].children + assert fields is not None + loop = next(n for n in fields if n.key == "MidiLoop") + old_loop = project.text[loop.start : loop.end].encode() + raw = raw.replace( + old_loop, + old_loop + + b"\n" + + old_loop.replace(b"MidiLoop 0", b"MidiLoop 1").replace(b"Offset 2", b"Offset 8"), + ) + project = sdp.parse_sdp_project(raw) + track = project.tracks[0] + old = project.text[track.start : track.end].encode() + raw = raw.replace(old, old + b"\n" + old.replace(b"SongTrack 0", b"SongTrack 1")) + raw = raw.replace(b"SetCurrentSongTrack 0", b"SetCurrentSongTrack 1") + template = workspace / "multi.sd3p" + template.write_bytes(raw) + assert sdp.inspect_sdp_template(template).track_count == 2 + assert sdp.inspect_sdp_template(template).event_count == 4 + plan, profile = original_plan() + path = workspace / "single.sd3p" + sdp.write_sdp(path, plan, "drums", profile, template=template) + saved = sdp.parse_sdp_project(path.read_bytes()) + assert len(saved.tracks) == 1 and len(saved.source_notes) == 3 + assert saved.non_song_bytes == sdp.parse_sdp_project(raw).non_song_bytes + + +@pytest.mark.parametrize( + ("old", "new"), + [ + (b"3.4.4", b"3.4.5"), + (b"3.4.4", b"4.0.0"), + (b"PlugVersion", b"UnknownVersion"), + (b"SongTrack 0", b"SongTrack 1"), + (b"SetCurrentSongTrack 0", b"SetCurrentSongTrack 2"), + (b"ClearTracksFirst\n", b""), + (b"ClearTrackFirst\n", b""), + (b"Tempo 100 0 0", b"Tempo 100 1 0"), + (b"Tempo 100 0 0", b"Tempo nan 0 0"), + (b"TimeSig 4 4 0", b"TimeSig 4 3 0"), + (b"TrackLength 16", b"TrackLength -1"), + (b"Offset 2", b"Offset -2"), + (b"StartTime 0", b"StartTime 5"), + (b"Events 4203664 0 0.25", b"Events 4203664 0"), + (b"Events 4203664 0 0.25", b"Events 4203664 -1 0.25"), + (b"Events 4203664 0 0.25", b"Events 4203664 0 0"), + (b"Events 4203664 0 0.25", b"Events 4203664 0 5"), + (b"Events 4203664 0 0.25", b"Events 4203664 0 1/4"), + (b"Events 4203664 0 0.25", b"Events 4203696 0 0.25"), # CC. + (b"Events 4203664 0 0.25", b"Events 4203648 0 0.25"), # Explicit note-off. + (b"Events 4203664 0 0.25", b"Events 9360 0 0.25"), # Zero on-velocity. + (b"Events 4203664 0 0.25", b"Events 8388752 0 0.25"), # Velocity 128. + (b"Events 4203664 0 0.25", b"Events 4227216 0 0.25"), # Pitch 128. + (b"Events 4203664 0 0.25", b"Events 4203664 0 0.1234567890"), + (b"TrackLength 16", b"TrackLength 16\nTrackLength 16"), + (b"MidiEvents {", b"MidiEvents 1 {"), + (b'OriginalLabel "Not song data"', b'OriginalLabel "unterminated'), + (b'OriginalLabel "Not song data"', b"SongTrack 0 {\n}"), + (b"SyncToHost 1", b"}\nSyncToHost 1"), + (b"SyncToHost 1", b"{\nSyncToHost 1"), + (b"SyncToHost 1", b"SyncToHost \0 1"), + (b"SyncToHost 1", b"SyncToHost \xff 1"), + ], +) +def test_corrupt_unsupported_and_ambiguous_project_inputs(old: bytes, new: bytes) -> None: + with pytest.raises(SerializationError): + raw = TEMPLATE.read_bytes().replace(b"\r\n", b"\n") + assert old in raw + sdp.parse_sdp_project(raw.replace(old, new)) + + +@pytest.mark.parametrize( + ("old", "new"), + [ + (b'"SL-DFH"', b'"other-library"'), + (b"alias kickR 36", b"alias kickR 35"), + (b"alias snareR 38", b"alias snareSL 38"), + (b"alias hatsTP 42", b"alias hatsTP 42\nalias other 42"), + (b"pad kickR {", b"pad other {"), + (b"MidiInChannel -1", b"MidiInChannel 0"), + (b"midilearn {", b"midilearn {\nOriginalRemap 36 37"), + ], +) +def test_template_mapping_mismatch_errors_not_fallback( + workspace: Path, old: bytes, new: bytes +) -> None: + path = workspace / "bad.sd3p" + path.write_bytes(TEMPLATE.read_bytes().replace(old, new)) + _, profile = original_plan() + with pytest.raises(SerializationError): + sdp.check_sdp_capability("drums", profile, template=path) + + +@pytest.mark.parametrize("bound", ["bytes", "depth", "events", "tokens"]) +def test_parser_resource_bounds(monkeypatch: pytest.MonkeyPatch, bound: str) -> None: + raw = TEMPLATE.read_bytes() + if bound == "bytes": + monkeypatch.setattr(sdp, "MAX_BYTES", 10) + elif bound == "depth": + monkeypatch.setattr(sdp, "MAX_DEPTH", 2) + elif bound == "events": + monkeypatch.setattr(sdp, "MAX_EVENTS", 0) + else: + monkeypatch.setattr(sdp, "MAX_TOKENS", 10) + with pytest.raises(SerializationError): + sdp.parse_sdp_project(raw) + + +@pytest.mark.parametrize( + "case", + ["cc", "off_velocity", "wrong_channel", "plan_pitch", "preroll", "tail", "mutated"], +) +def test_unrepresentable_plan_semantics_fail_before_write(workspace: Path, case: str) -> None: + plan, profile = original_plan() + if case == "cc": + plan.tracks[0].events.append( + ControlChangeEvent( + part="drums", + channel=9, + tick=0, + priority=10, + sequence=100, + controller=4, + value=127, + ) + ) + elif case == "off_velocity": + next(e for e in plan.tracks[0].events if isinstance(e, NoteOffEvent)).velocity = 10 + elif case == "wrong_channel": + for event in plan.tracks[0].events: + event.channel = 0 + elif case == "plan_pitch": + for event in plan.tracks[0].events: + if isinstance(event, NoteOnEvent | NoteOffEvent) and event.note == 36: + event.note = 35 + elif case == "preroll": + plan.musical_start_tick = 1 + elif case == "tail": + plan.end_tick += 1 + else: + plan.score.intent.tempo_bpm = float("nan") + with pytest.raises(SerializationError): + sdp.write_sdp(workspace / "bad.sd3p", plan, "drums", profile, template=TEMPLATE) + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize("ppq", [960, 480, 96]) +def test_exact_quarter_beats_not_assumed_ppq(workspace: Path, ppq: int) -> None: + plan, profile = original_plan(ppq=ppq) + path = workspace / "original.sd3p" + sdp.write_sdp(path, plan, "drums", profile, template=TEMPLATE) + assert sdp.validate_sdp_file(path, plan, "drums", profile, template=TEMPLATE).notes[ + 1 + ].start == (Fraction(1, 4)) + + +@pytest.mark.parametrize("denominator", [3, 128]) +def test_nonterminating_or_overprecision_timing_is_rejected( + workspace: Path, denominator: int +) -> None: + plan, profile = original_plan() + data = plan.score.model_dump() + data["tracks"][0]["notes"][0]["duration"] = {"numerator": 1, "denominator": denominator} + plan = compile_score(Score.model_validate(data), {"drums": profile}, ppq=3840) + with pytest.raises(SerializationError) as error: + sdp.write_sdp(workspace / "bad.sd3p", plan, "drums", profile, template=TEMPLATE) + assert error.value.details["reason"] == "sd3_timing_not_representable" + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize( + ("old", "new"), + [ + (b"OriginalGain 0.375", b"OriginalGain 0.5"), + (b'trackstuff "', b'trackstuff "corrupt-'), + (b"TrackLength 3.5", b"TrackLength 4"), + (b"Offset 0", b"Offset 1"), + (b"Velocity 0", b"Velocity 1"), + (b"Mute 0", b"Mute 1"), + (b"137.5", b"140"), + (b"TimeSig 7 8", b"TimeSig 4 4"), + (b"Events 74905", b"Events 140441"), + (b"74905 0 0.125", b"74905 0 0.25"), + (b"ClearNotes", b'ClearNotes\nFileName "unexpected-source.mid"'), + (b'TrackName "', b'UnknownTrackName "'), + (b"Type 1", b"Type 2"), + (b"ClearSongParts", b"ClearSongParts\nMidiLoop 1 {\n}"), + ], +) +def test_saved_file_corruption_is_a_named_serialization_failure( + workspace: Path, old: bytes, new: bytes +) -> None: + plan, profile = original_plan() + path = workspace / "saved.sd3p" + sdp.write_sdp(path, plan, "drums", profile, template=TEMPLATE) + raw = path.read_bytes() + assert old in raw + path.write_bytes(raw.replace(old, new)) + with pytest.raises(SerializationError): + sdp.validate_sdp_file(path, plan, "drums", profile, template=TEMPLATE) + + +def test_suffix_exclusive_writes_template_identity_and_io_errors( + workspace: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + plan, profile = original_plan() + for suffix in ("sdp", "mid", "SD3P"): + with pytest.raises(SerializationError): + sdp.write_sdp(workspace / f"wrong.{suffix}", plan, "drums", profile, template=TEMPLATE) + copy = workspace / "operator.sd3p" + copy.write_bytes(TEMPLATE.read_bytes()) + before = copy.read_bytes() + with pytest.raises(OutputExistsError): + sdp.write_sdp(copy, plan, "drums", profile, template=copy) + assert copy.read_bytes() == before + with pytest.raises(OutputIOError): + sdp.write_sdp(workspace / "missing" / "out.sd3p", plan, "drums", profile, template=copy) + with monkeypatch.context() as guard: + guard.setattr(Path, "open", Mock(side_effect=PermissionError("private path"))) + with pytest.raises(OutputIOError) as error: + sdp.inspect_sdp_template(copy) + assert "private" not in str(error.value.details) + with monkeypatch.context() as guard: + guard.setattr(os, "fsync", Mock(side_effect=OSError)) + with pytest.raises(OutputIOError): + sdp.write_sdp(workspace / "io.sd3p", plan, "drums", profile, template=copy) + + +def test_writer_checks_actual_saved_bytes_not_only_its_buffer( + workspace: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + plan, profile = original_plan() + actual = sdp._replace_song + monkeypatch.setattr( + sdp, + "_replace_song", + lambda project, song: actual(project, song).replace(b"Offset 0", b"Offset 1"), + ) + with pytest.raises(SerializationError): + sdp.write_sdp(workspace / "bad.sd3p", plan, "drums", profile, template=TEMPLATE) + + +@pytest.mark.parametrize("channel", [0, 15]) +@pytest.mark.parametrize("pitch", [0, 127]) +@pytest.mark.parametrize("velocity", [1, 127]) +def test_packed_message_byte_boundaries(channel: int, pitch: int, velocity: int) -> None: + packed = (velocity * 65536) + (pitch * 256) + 144 + channel + raw = TEMPLATE.read_bytes().replace(b"4203664 0 0.25", f"{packed} 0 0.25".encode()) + (note,) = sdp.parse_sdp_project(raw).source_notes + assert (note.channel, note.pitch, note.velocity) == (channel, pitch, velocity) + + +def test_template_change_during_write_is_detected( + workspace: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + template = workspace / "operator.sd3p" + raw = TEMPLATE.read_bytes() + template.write_bytes(raw) + plan, profile = original_plan() + + def changed(_: int) -> None: + template.write_bytes(raw.replace(b"OriginalGain 0.375", b"OriginalGain 0.5")) + + monkeypatch.setattr(os, "fsync", changed) + with pytest.raises(SerializationError) as error: + sdp.write_sdp(workspace / "failed.sd3p", plan, "drums", profile, template=template) + assert error.value.details["reason"] == "sd3_template_changed" + + +def test_empty_non_regular_and_versioned_templates_never_create_output(workspace: Path) -> None: + plan, profile = original_plan() + path = workspace / "invalid.sd3p" + output = workspace / "never-created.sd3p" + for raw in (b"", TEMPLATE.read_bytes().replace(b"3.4.4", b"3.5.0"), b"MThd"): + path.write_bytes(raw) + with pytest.raises(SerializationError): + sdp.write_sdp(output, plan, "drums", profile, template=path) + assert not output.exists() + path.unlink() + path.mkdir() + with pytest.raises(OutputIOError): + sdp.write_sdp(output, plan, "drums", profile, template=path) + assert not output.exists() + + +@pytest.mark.parametrize( + "field", + ["version", "voices", "library", "channel", "default_type", "actions", "velocity", "status"], +) +def test_subset_profile_rejects_unsupported_promotions(field: str) -> None: + _, profile = original_plan() + data = profile.model_dump() + if field == "version": + data["sdp"]["layout_version"] = "3.4.5" + elif field == "voices": + data["drum_voices"][0]["note"] = 35 + elif field == "library": + data["sdp"]["sound_library"] = "SL-SD3" + elif field == "channel": + data["channel"] = 0 + elif field == "default_type": + data["default"] = "yes" + elif field == "actions": + data["articulations"][0]["mode"] = "momentary" + elif field == "velocity": + data["articulations"][0]["layers"][0]["velocity_high"] = 126 + else: + data["provenance"]["status"] = "verified" + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) diff --git a/tests/unit/test_sdp.py b/tests/unit/test_sdp.py new file mode 100644 index 0000000..f4c7c9d --- /dev/null +++ b/tests/unit/test_sdp.py @@ -0,0 +1,250 @@ +"""SDP capability contracts; mapping fixtures are not native files or vendor evidence.""" + +from collections.abc import Callable +from dataclasses import FrozenInstanceError, asdict +from pathlib import Path +from typing import cast + +import pytest + +from riff_groove_builder.errors import ( + DomainError, + InvalidRequestError, + NativeFormatUnavailableError, +) +from riff_groove_builder.formats import NativeCapability +from riff_groove_builder.formats.sdp import check_sdp_capability, require_sdp_capability +from riff_groove_builder.profiles import ( + InstrumentProfile, + InvalidProfileError, + ProfilePartMismatchError, + load_profile_registry, + parse_profile, +) +from riff_groove_builder.schemas import Part, ProfileSelection + +Boundary = Callable[[Part, InstrumentProfile], NativeCapability] +BOUNDARIES: list[Boundary] = [check_sdp_capability, require_sdp_capability] +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "profiles" + + +def standard(part: Part = "drums") -> InstrumentProfile: + identifier = "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" + return load_profile_registry().select([part], ProfileSelection(**{part: identifier}))[part] + + +def test_gm_profile_returns_explicit_typed_immutable_unavailable() -> None: + profile = standard() + before = profile.model_dump() + capability: NativeCapability = check_sdp_capability("drums", profile) + assert type(capability) is NativeCapability + assert asdict(capability) == { + "part": "drums", + "format": "sdp", + "available": False, + "reason": "sdp_profile_not_supported", + } + assert profile.id == "standard.gm-drums.v1" + assert profile.summary.mapping_kind == "standard_midi" + assert profile.summary.native_available is False + assert profile.provenance.status == "standard_midi" + assert profile.model_dump() == before + assert check_sdp_capability("drums", profile) == capability + assert not hasattr(capability, "__dict__") + for field, value in ( + ("part", "lead"), + ("format", "agp"), + ("available", True), + ("reason", "forged"), + ): + with pytest.raises(FrozenInstanceError): + setattr(capability, field, value) + + +def test_synthetic_instrument_mapping_does_not_establish_a_codec() -> None: + profile = parse_profile((FIXTURES / "synthetic-drums.json").read_bytes()) + assert profile.summary.mapping_kind == "instrument" + assert profile.provenance.status == "test_only" + assert check_sdp_capability("drums", profile) == check_sdp_capability("drums", standard()) + + +def test_mapping_attestation_and_product_version_are_not_native_evidence() -> None: + data = parse_profile((FIXTURES / "synthetic-drums.json").read_bytes()).model_dump() + data["id"] = data["summary"]["id"] = "harness.mapping.only" + data["summary"]["product_name"] = "TEST HARNESS mapping attestation, NOT vendor evidence" + data["summary"]["product_version"] = data["provenance"]["product_version"] = "unknown-build" + data["provenance"]["status"] = "verified" + data["provenance"]["sources"] = [ + { + "kind": "lawful_local", + "reference": "TEST-HARNESS-NOT-VENDOR-EVIDENCE", + "aspects": [ + "identity", + "range_or_voices", + "channels", + "actions", + "state_reset", + "timing", + "velocity", + ], + } + ] + profile = InstrumentProfile.model_validate(data) + assert check_sdp_capability("drums", profile).available is False + with pytest.raises(NativeFormatUnavailableError) as caught: + require_sdp_capability("drums", profile) + assert caught.value.details["reason"] == "sdp_profile_not_supported" + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +def test_native_metadata_cannot_enable_instrument_support(boundary: Boundary) -> None: + profile = parse_profile((FIXTURES / "synthetic-drums.json").read_bytes()) + profile.summary.native_available = True + with pytest.raises(InvalidProfileError) as caught: + boundary("drums", profile) + assert caught.value.details == {"reason": "invalid_profile_model"} + + +def test_require_raises_named_error_with_safe_complete_context() -> None: + with pytest.raises(NativeFormatUnavailableError) as caught: + require_sdp_capability("drums", standard()) + assert caught.value.code == "NATIVE_FORMAT_UNAVAILABLE" + assert caught.value.details == { + "format": "sdp", + "part": "drums", + "reason": "sdp_profile_not_supported", + } + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +@pytest.mark.parametrize( + "invalid", ["lead", "bass", "sd3", "drum", "DRUMS", "", None, 1, True, [], {}] +) +def test_invalid_parts_are_bad_requests_not_unavailable( + boundary: Boundary, invalid: object +) -> None: + with pytest.raises(InvalidRequestError) as caught: + boundary(cast(Part, invalid), standard()) + assert caught.value.code == "INVALID_REQUEST" + assert caught.value.details == {"format": "sdp", "reason": "unsupported_sdp_part"} + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +@pytest.mark.parametrize("profile_part", ["lead", "bass"]) +def test_valid_wrong_part_profiles_are_selection_errors( + boundary: Boundary, profile_part: Part +) -> None: + with pytest.raises(ProfilePartMismatchError) as caught: + boundary("drums", standard(profile_part)) + assert caught.value.code == "PROFILE_REQUIRED" + assert caught.value.details == {"format": "sdp", "part": "drums", "reason": "wrong_part"} + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +@pytest.mark.parametrize( + "mutation", + [ + "instrument", + "part", + "format", + "native_flag", + "channel", + "voice_note", + "duplicate_note", + "voice_alias", + "empty_voices", + "range", + "aliases", + "layer", + "provenance", + "mapping_kind", + "version", + "schema", + "unchecked_copy", + "unchecked_construct", + ], +) +def test_mutated_profiles_are_invalid_not_native_unavailable( + boundary: Boundary, mutation: str +) -> None: + profile = standard() + if mutation == "instrument": + profile.summary.instrument = "eclips" + elif mutation == "part": + profile.summary.part = "lead" + elif mutation == "format": + profile.summary.native_format = "griff" + elif mutation == "native_flag": + profile.summary.native_available = True + elif mutation == "channel": + profile.channel = 128 + elif mutation == "voice_note": + profile.drum_voices[0].note = 128 + elif mutation == "duplicate_note": + profile.drum_voices[1].note = profile.drum_voices[0].note + elif mutation == "voice_alias": + profile.drum_voices[0].aliases.append(profile.drum_voices[1].name) + elif mutation == "empty_voices": + profile.drum_voices.clear() + elif mutation == "range": + profile.playable_range = standard("lead").playable_range + elif mutation == "aliases": + profile.articulations[0].aliases.append("slide") + elif mutation == "layer": + profile.articulations[0].layers[0].velocity_high = 128 + elif mutation == "provenance": + profile.provenance.sources[0].aspects.clear() + elif mutation == "mapping_kind": + profile.summary.mapping_kind = "instrument" + elif mutation == "version": + profile.provenance.mapping_version = "private-inconsistent-version" + elif mutation == "schema": + profile = profile.model_copy(update={"schema_version": "private-invalid-version"}) + elif mutation == "unchecked_copy": + profile = profile.model_copy(update={"drum_voices": ["private-invalid-voice"]}) + else: + profile = InstrumentProfile.model_construct(id="private-incomplete-profile") + with pytest.raises(InvalidProfileError) as caught: + boundary("drums", profile) + assert caught.value.code == "SERIALIZATION_ERROR" + assert caught.value.details == {"reason": "invalid_profile_model"} + assert "private" not in str(caught.value) + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +@pytest.mark.parametrize("invalid", [None, {}, "not a profile"]) +def test_wrong_profile_model_type_is_corrupted_input(boundary: Boundary, invalid: object) -> None: + with pytest.raises(InvalidProfileError) as caught: + boundary("drums", cast(InstrumentProfile, invalid)) + assert caught.value.code == "SERIALIZATION_ERROR" + assert caught.value.details == {"reason": "invalid_profile_model"} + + +def test_mutating_a_profile_after_check_cannot_authorize_require() -> None: + profile = standard() + capability = check_sdp_capability("drums", profile) + profile.drum_voices.clear() + with pytest.raises(InvalidProfileError): + require_sdp_capability("drums", profile) + assert capability.available is False + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +def test_unexpected_validation_errors_are_not_fallback( + monkeypatch: pytest.MonkeyPatch, boundary: Boundary +) -> None: + profile = standard() + + def broken_check(profile: InstrumentProfile) -> InstrumentProfile: + raise RuntimeError("test-only unexpected programming failure") + + monkeypatch.setattr("riff_groove_builder.formats.sdp.checked_profile", broken_check) + with pytest.raises(RuntimeError): + boundary("drums", profile) + + +@pytest.mark.parametrize("boundary", BOUNDARIES) +def test_invalid_request_takes_precedence_over_invalid_profile(boundary: Boundary) -> None: + with pytest.raises(DomainError) as caught: + boundary("lead", cast(InstrumentProfile, None)) + assert type(caught.value) is InvalidRequestError diff --git a/tests/unit/test_server.py b/tests/unit/test_server.py new file mode 100644 index 0000000..555c8d1 --- /dev/null +++ b/tests/unit/test_server.py @@ -0,0 +1,550 @@ +"""Concrete tool handlers, public-safe failures, root validation, and import safety.""" + +import json +import logging +import shutil +import subprocess +import sys +import uuid +from collections.abc import Iterator +from pathlib import Path +from unittest.mock import patch + +import pytest +from jsonschema import Draft202012Validator +from mcp import types +from mcp.server.lowlevel import Server +from pydantic import JsonValue, ValidationError + +from riff_groove_builder.errors import OutputIOError +from riff_groove_builder.schemas import ( + GenerationError, + GenerationResult, + ProfileListResult, + ToolName, + tool_input_schema, + tool_output_schema, +) +from riff_groove_builder.server import create_server, validate_output_root + +ROOT = Path(__file__).resolve().parents[2] +pytestmark = pytest.mark.anyio + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +@pytest.fixture +def output_root() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"server-unit-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +async def _call( + server: Server[Path], name: str, arguments: dict[str, JsonValue] +) -> types.CallToolResult: + result = await server.request_handlers[types.CallToolRequest]( + types.CallToolRequest(params=types.CallToolRequestParams(name=name, arguments=arguments)) + ) + assert isinstance(result, types.ServerResult) + assert isinstance(result.root, types.CallToolResult) + if result.root.structuredContent is not None: + assert len(result.root.content) == 1 + assert isinstance(result.root.content[0], types.TextContent) + assert json.loads(result.root.content[0].text) == result.root.structuredContent + return result.root + + +async def test_exact_tools_and_schemas(output_root: Path) -> None: + server = create_server(output_root) + response = await server.request_handlers[types.ListToolsRequest]( + types.ListToolsRequest(method="tools/list") + ) + assert isinstance(response.root, types.ListToolsResult) + tools = response.root.tools + assert [tool.name for tool in tools] == ["list_instrument_profiles", "generate_music"] + names: tuple[ToolName, ...] = ("list_instrument_profiles", "generate_music") + for name, tool in zip(names, tools, strict=True): + assert tool.inputSchema == tool_input_schema(name) + assert tool.outputSchema == tool_output_schema(name) + guidance = tools[1].description or "" + for phrase in ( + "Omit formats", + "lead -> griff", + "bass -> briff", + "drums -> sd3p", + "mid works for all", + "Omit profiles", + "never invent profile IDs", + "Never add CC events without user intent", + "triplet", + "preserve user intent", + ): + assert phrase in guidance + async with server.lifespan(server) as stored_root: + assert stored_root == output_root + capabilities = server.create_initialization_options().capabilities + assert capabilities.tools is not None + assert capabilities.resources is None + assert capabilities.prompts is None + assert capabilities.logging is None + + +@pytest.mark.parametrize( + ("name", "arguments"), + [ + ("list_instrument_profiles", {"private-property": "private-value"}), + ("generate_music", {}), + ("generate_music", {"description": "private-description", "basename": "../private-path"}), + ("generate_music", {"description": "private-description", "basename": "x", "bars": True}), + ("generate_music", {"description": "private-description", "basename": "x", "bars": 4.0}), + ("generate_music", {"description": "private-description", "basename": "x", "seed": "4"}), + ( + "generate_music", + {"description": "private-description", "basename": "x", "tempo_bpm": True}, + ), + ( + "generate_music", + { + "description": "private-description", + "basename": "x", + "time_signature": {"numerator": 4, "denominator": 4.0}, + }, + ), + ( + "generate_music", + { + "description": "private-description", + "basename": "x", + "parts": ["lead"], + "formats": ["sdp"], + }, + ), + ( + "generate_music", + { + "description": "private-description", + "basename": "x", + "parts": ["lead"], + "profiles": {"drums": "private-profile"}, + }, + ), + ( + "generate_music", + {"description": "private-description", "basename": "x", "parts": ["lead", "lead"]}, + ), + ( + "generate_music", + {"description": "private-description", "basename": "x", "private-property": "secret"}, + ), + ( + "generate_music", + { + "description": "private-description", + "basename": "x", + "profiles": {"private-property": "private-value"}, + }, + ), + ], +) +async def test_authoritative_validation_is_public_safe( + output_root: Path, + name: ToolName, + arguments: dict[str, JsonValue], + caplog: pytest.LogCaptureFixture, +) -> None: + result = await _call(create_server(output_root), name, arguments) + assert result.isError + assert result.structuredContent is not None + error = GenerationError.model_validate(result.structuredContent) + assert error.code == "INVALID_REQUEST" + assert error.details["issues"] + Draft202012Validator(tool_output_schema(name)).validate(result.structuredContent) + assert "private-" not in result.model_dump_json() + caplog.text + assert "secret" not in result.model_dump_json() + caplog.text + assert not list(output_root.iterdir()) + + +async def test_real_registry_and_generation(output_root: Path) -> None: + server = create_server(output_root) + profiles = await _call(server, "list_instrument_profiles", {}) + assert not profiles.isError + summaries = ProfileListResult.model_validate(profiles.structuredContent).profiles + assert len(summaries) == 6 + assert [profile.mapping_kind for profile in summaries] == [ + "instrument", + "instrument", + "standard_midi", + "standard_midi", + "standard_midi", + "instrument", + ] + assert [profile.native_available for profile in summaries] == [ + True, + True, + False, + False, + False, + False, + ] + assert isinstance(profiles.content[0], types.TextContent) + assert json.loads(profiles.content[0].text)["profiles"][0]["id"] == ( + "ample.ame.4.0.1.riffer.v1" + ) + result = await _call( + server, "generate_music", {"description": "lead only 1 bar quarter", "basename": "example"} + ) + assert not result.isError + generated = GenerationResult.model_validate(result.structuredContent) + assert generated.status == "complete" + assert generated.artifacts[0].fallback_for == [] + assert [artifact.format for artifact in generated.artifacts] == ["mid", "griff"] + assert Path(generated.artifacts[0].path).read_bytes().startswith(b"MThd") + assert isinstance(result.content[0], types.TextContent) + assert json.loads(result.content[0].text)["artifacts"][0]["path"] == ( + generated.artifacts[0].path + ) + Draft202012Validator(tool_output_schema("generate_music")).validate(result.structuredContent) + assert list(output_root.iterdir()) == [output_root / "example"] + + +@pytest.mark.parametrize("name", ["list_instrument_profiles", "generate_music"]) +async def test_domain_error_preserves_public_contract_only( + output_root: Path, caplog: pytest.LogCaptureFixture, name: ToolName +) -> None: + error = OutputIOError(details={"reason": "public_reason"}) + error.__cause__ = OSError("private-fixture-path secret") + with patch(f"riff_groove_builder.server.GenerationService.{name}", side_effect=error): + result = await _call( + create_server(output_root), + name, + {} + if name == "list_instrument_profiles" + else {"description": "private-description", "basename": "x"}, + ) + assert result.isError + assert result.structuredContent == { + "code": error.code, + "message": error.public_message, + "details": {"reason": "public_reason"}, + } + assert "private-" not in result.model_dump_json() + caplog.text + + +async def test_unexpected_failure_is_diagnostic_not_silent( + output_root: Path, caplog: pytest.LogCaptureFixture +) -> None: + with ( + caplog.at_level(logging.ERROR), + patch( + "riff_groove_builder.server.GenerationService.generate_music", + side_effect=OSError("private-fixture-path secret"), + ), + ): + result = await _call( + create_server(output_root), "generate_music", {"description": "riff", "basename": "x"} + ) + assert result.isError + assert result.structuredContent is None + assert "Unexpected tool execution failure (OSError)." in caplog.text + assert "private-" not in result.model_dump_json() + caplog.text + assert "secret" not in result.model_dump_json() + caplog.text + assert not list(output_root.iterdir()) + + +async def test_wrong_format_with_valid_key_identifies_formats(output_root: Path) -> None: + result = await _call( + create_server(output_root), + "generate_music", + { + "description": "lead only 1 bar quarter", + "basename": "wrong", + "parts": ["lead"], + "formats": ["sd3p", "mid"], + "key": "E minor", + "profiles": {"lead": "aggressive_rock"}, + "cc_events": [ + {"part": "lead", "beat": {"numerator": 0}, "controller": 91, "value": 64} + ], + }, + ) + assert result.isError + error = GenerationError.model_validate(result.structuredContent) + issues = error.details["issues"] + assert isinstance(issues, list) and len(issues) == 1 + issue = issues[0] + assert isinstance(issue, dict) + assert issue["field"] == "formats" and issue["reason"] == "format_parts" + assert "sd3p/sdp requires drums" in str(issue["correction"]) + assert "Guitar lead uses griff/agp or mid" in str(issue["correction"]) + assert "aggressive_rock" not in result.model_dump_json() + assert not list(output_root.iterdir()) + + +@pytest.mark.parametrize( + ("updates", "field", "guidance"), + [ + ({"key": "private-mode"}, "key", "Em, F#m, Bbm"), + ({"time_signature": "4/4"}, "time_signature", "integer numerator 1-16"), + ( + {"time_signature": {"numerator": 4, "denominator": True}}, + "time_signature.denominator", + "integer denominator", + ), + ({"parts": ["guitar"]}, "parts.0", "guitar is lead"), + ({"formats": ["wav"]}, "formats.0", "griff/agp or mid"), + ({"parts": ["lead", "lead"]}, "parts", "duplicate"), + ({"profiles": {"lead": 123}}, "profiles.lead", "list_instrument_profiles({})"), + ({"bars": True}, "bars", "1 through 256"), + ({"tempo_bpm": 301}, "tempo_bpm", "20 through 300"), + ({"private-property": "private-value"}, "", "Remove unknown"), + ( + { + "cc_events": [ + {"part": "guitar", "beat": {"numerator": 0}, "controller": 1, "value": 2} + ] + }, + "cc_events.0.part", + "part must be selected", + ), + ( + {"cc_events": [{"part": "lead", "beat": 0, "controller": 1, "value": 2}]}, + "cc_events.0.beat", + "quarter-note beats", + ), + ( + { + "cc_events": [ + {"part": "lead", "beat": {"numerator": 0}, "controller": True, "value": 2} + ] + }, + "cc_events.0.controller", + "integers 0-127", + ), + ( + { + "cc_events": [ + { + "part": "lead", + "beat": {"numerator": 1, "denominator": 7}, + "controller": 1, + "value": 2, + } + ] + }, + "cc_events", + "960", + ), + ( + { + "cc_events": [ + { + "part": "lead", + "beat": {"numerator": 0}, + "controller": 1, + "value": 2, + "private-property": "private-value", + } + ] + }, + "cc_events.0.", + "Remove unknown", + ), + ], +) +async def test_field_guidance_is_safe_and_actionable( + output_root: Path, updates: dict[str, JsonValue], field: str, guidance: str +) -> None: + result = await _call( + create_server(output_root), + "generate_music", + {"description": "private-description", "basename": "x", **updates}, + ) + error = GenerationError.model_validate(result.structuredContent) + assert result.isError and error.code == "INVALID_REQUEST" + issues = error.details["issues"] + assert isinstance(issues, list) + assert any( + isinstance(issue, dict) and issue["field"] == field and guidance in str(issue["correction"]) + for issue in issues + ) + assert "private-" not in result.model_dump_json() + assert not list(output_root.iterdir()) + + +async def test_missing_fields_and_cross_field_cc_corrections(output_root: Path) -> None: + server = create_server(output_root) + missing = await _call(server, "generate_music", {}) + error = GenerationError.model_validate(missing.structuredContent) + issues = error.details["issues"] + assert isinstance(issues, list) + assert {issue["field"] for issue in issues if isinstance(issue, dict)} == { + "description", + "basename", + } + assert all( + isinstance(issue, dict) and "Supply this required field" in str(issue["correction"]) + for issue in issues + ) + cc: dict[str, JsonValue] = { + "part": "lead", + "beat": {"numerator": 0}, + "controller": 1, + "value": 2, + } + cases: list[tuple[dict[str, JsonValue], str, str]] = [ + ({"cc_events": [cc, cc]}, "cc_duplicates", "cc_events"), + ({"parts": ["drums"], "cc_events": [cc]}, "cc_parts", "cc_events"), + ( + {"parts": ["lead"], "profiles": {"drums": "private-profile"}}, + "profile_parts", + "profiles", + ), + ] + for updates, reason, field in cases: + result = await _call( + server, + "generate_music", + {"description": "private-description", "basename": "x", **updates}, + ) + failure = GenerationError.model_validate(result.structuredContent) + assert result.isError + actual = failure.details["issues"] + assert isinstance(actual, list) and isinstance(actual[0], dict) + assert actual[0]["field"] == field and actual[0]["reason"] == reason + assert actual[0]["correction"] + assert "private-" not in result.model_dump_json() + assert not list(output_root.iterdir()) + + +@pytest.mark.parametrize( + ("updates", "code", "guidance"), + [ + ( + {"profiles": {"lead": "private-invented-id"}}, + "PROFILE_REQUIRED", + "omit profiles for defaults", + ), + ( + {"profiles": {"lead": "standard.bass.v1"}}, + "PROFILE_REQUIRED", + "list_instrument_profiles({})", + ), + ( + {"description": "private-description triplet melody"}, + "UNSUPPORTED_DESCRIPTION", + "Arbitrary triplet patterns", + ), + ( + { + "cc_events": [ + {"part": "lead", "beat": {"numerator": 5}, "controller": 1, "value": 2} + ] + }, + "INVALID_REQUEST", + "within the musical duration", + ), + ], +) +async def test_real_domain_errors_offer_text_only_recovery( + output_root: Path, updates: dict[str, JsonValue], code: str, guidance: str +) -> None: + result = await _call( + create_server(output_root), + "generate_music", + {"description": "lead only 1 bar quarter", "basename": "x", **updates}, + ) + assert result.isError + assert result.structuredContent is not None + assert result.structuredContent["code"] == code + assert isinstance(result.content[0], types.TextContent) + assert guidance in result.content[0].text + assert "private-" not in result.content[0].text + assert not list(output_root.iterdir()) + + +async def test_internal_model_failure_is_not_blame_on_input( + output_root: Path, caplog: pytest.LogCaptureFixture +) -> None: + with pytest.raises(ValidationError) as captured: + ProfileListResult.model_validate({"private-property": "secret"}) + with patch( + "riff_groove_builder.server.GenerationService.generate_music", side_effect=captured.value + ): + result = await _call( + create_server(output_root), "generate_music", {"description": "riff", "basename": "x"} + ) + assert result.isError + assert result.structuredContent is None + assert "Unexpected tool execution failure (ValidationError)." in caplog.text + assert "private-" not in result.model_dump_json() + caplog.text + assert "secret" not in result.model_dump_json() + caplog.text + + +@pytest.mark.parametrize( + "value", + [ + "", + " ", + ".\n", + "https://example.invalid/root", + "file:///C:/music", + r"\\server\share", + "//server/share", + r"\\?\C:\music", + r"\\.\NUL", + r"\rooted-on-current-drive", + "C:relative", + "C:\\music:stream", + "\x00", + ], +) +def test_reject_unsafe_roots(value: str) -> None: + with pytest.raises(ValueError, match="existing local directory"): + validate_output_root(value) + + +def test_root_must_exist_and_be_directory(output_root: Path) -> None: + assert validate_output_root(str(output_root)) == output_root.resolve() + assert validate_output_root(".") == ROOT + with pytest.raises(ValueError): + validate_output_root(str(output_root / "missing")) + file = output_root / "sentinel" + file.write_text("existing unrelated data", encoding="utf-8") + with pytest.raises(ValueError): + validate_output_root(str(file)) + assert file.read_text(encoding="utf-8") == "existing unrelated data" + assert not (output_root / "missing").exists() + + +@pytest.mark.parametrize( + "module", ["riff_groove_builder", "riff_groove_builder.server", "riff_groove_builder.__main__"] +) +def test_import_is_silent_without_cli(module: str, output_root: Path) -> None: + result = subprocess.run( + [sys.executable, "-I", "-B", "-c", f"import {module}"], + cwd=output_root, + capture_output=True, + timeout=15, + check=False, + ) + assert result.returncode == 0, result.stderr + assert result.stdout == result.stderr == b"" + assert not list(output_root.iterdir()) + + +def test_required_cli_argument(capsys: pytest.CaptureFixture[str]) -> None: + from riff_groove_builder.__main__ import main + + with pytest.raises(SystemExit) as error: + main([]) + assert error.value.code == 2 + captured = capsys.readouterr() + assert captured.out == "" + assert "--output-dir" in captured.err diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py new file mode 100644 index 0000000..71e93ed --- /dev/null +++ b/tests/unit/test_service.py @@ -0,0 +1,508 @@ +"""Service policy, defensive contracts and ownership/failure boundaries.""" + +import os +import shutil +import uuid +from collections.abc import Iterator +from pathlib import Path +from unittest.mock import patch + +import pytest +from pydantic import ValidationError + +from riff_groove_builder.description import resolve_description +from riff_groove_builder.errors import ( + DomainError, + InvalidRequestError, + NativeFormatUnavailableError, + OutputExistsError, + OutputIOError, + SerializationError, + UnsupportedArticulationError, +) +from riff_groove_builder.formats import NativeCapability +from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry +from riff_groove_builder.schemas import GenerateMusicRequest, Part, ProfileSelection +from riff_groove_builder.service import GenerationService, _Stage, validate_output_root + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest.fixture +def workspace() -> Iterator[Path]: + path = ROOT / ".test-artifacts" / f"service-unit-{uuid.uuid4().hex}" + path.mkdir(parents=True) + try: + yield path + finally: + shutil.rmtree(path) + + +def request(**updates: object) -> GenerateMusicRequest: + job = GenerateMusicRequest.model_validate( + {"description": "lead bass drums 1 bar quarter", "basename": "music", **updates} + ) + if job.profiles is None: + parts = resolve_description(job).intent.parts + job.profiles = ProfileSelection( + **{ + part: "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" + for part in parts + } + ) + return job + + +@pytest.mark.parametrize( + ("parts", "formats", "fallback"), + [ + (["lead"], None, ["lead"]), + (["bass"], None, ["bass"]), + (["drums"], None, ["drums"]), + (["lead", "bass", "drums"], None, ["lead", "bass", "drums"]), + (["drums", "lead", "bass"], ["mid"], []), + (["lead", "bass", "drums"], ["agp"], ["lead", "bass"]), + (["lead", "bass", "drums"], ["sdp"], ["drums"]), + (["lead", "bass", "drums"], ["mid", "agp"], ["lead", "bass"]), + (["lead", "bass", "drums"], ["sdp", "agp"], ["lead", "bass", "drums"]), + ], +) +def test_formats_status_warning_and_artifact_coverage( + workspace: Path, parts: list[Part], formats: list[str] | None, fallback: list[Part] +) -> None: + result = GenerationService(workspace).generate_music(request(parts=parts, formats=formats)) + assert result.status == ("midi_fallback" if fallback else "complete") + assert result.resolved.parts == parts + assert result.resolved.musical_start_tick == 0 + assert result.resolved.musical_end_tick == 3840 + assert result.resolved.ticks_per_quarter == 960 + assert len(result.artifacts) == 1 + artifact = result.artifacts[0] + assert ( + artifact.format == "mid" and artifact.parts == parts and artifact.fallback_for == fallback + ) + assert artifact.profile_ids == [result.resolved.profile_ids.selected()[part] for part in parts] + assert artifact.path == str(workspace / "music" / "music.mid") + assert artifact.size_bytes == Path(artifact.path).stat().st_size > 0 + assert [ + warning.part for warning in result.warnings if warning.code == "STANDARD_MIDI_MAPPING" + ] == (parts) + assert [ + warning.part for warning in result.warnings if warning.code == "NATIVE_FORMAT_UNAVAILABLE" + ] == fallback + assert list(workspace.iterdir()) == [workspace / "music"] + + +@pytest.mark.parametrize( + "updates", + [ + {"description": "drums only", "formats": ["agp"]}, + {"description": "lead only", "formats": ["sdp"]}, + {"description": "lead only", "profiles": {"drums": "standard.gm-drums.v1"}}, + ], +) +def test_resolved_parts_cannot_bypass_associations( + workspace: Path, updates: dict[str, object] +) -> None: + with pytest.raises(InvalidRequestError) as error: + GenerationService(workspace).generate_music(request(**updates)) + assert error.value.details["reason"] == "resolved_part_association" + issues = error.value.details["issues"] + assert isinstance(issues, list) and len(issues) == 1 + assert isinstance(issues[0], dict) + expected_field = "profiles" if "profiles" in updates else "formats" + assert issues[0]["field"] == expected_field + assert issues[0]["correction"] + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize("part", ["lead", "bass", "drums"]) +def test_no_fallback_means_exact_native_error_without_stage(workspace: Path, part: Part) -> None: + service = GenerationService(workspace) + with ( + patch.object(service, "_new_stage", side_effect=AssertionError("Must preflight")), + pytest.raises(NativeFormatUnavailableError) as captured, + ): + service.generate_music(request(parts=[part], allow_midi_fallback=False)) + native = {"drums": "sd3p", "lead": "griff", "bass": "briff"}[part] + assert captured.value.details == { + "part": part, + "format": native, + "reason": ( + "sdp_profile_not_supported" if part == "drums" else "riffer_profile_not_supported" + ), + } + assert not list(workspace.iterdir()) + + +def test_explicit_midi_disables_native_preflight_and_needs_no_fallback(workspace: Path) -> None: + with ( + patch("riff_groove_builder.service.check_agp_capability", side_effect=AssertionError), + patch("riff_groove_builder.service.check_sdp_capability", side_effect=AssertionError), + ): + result = GenerationService(workspace).generate_music( + request(formats=["mid"], allow_midi_fallback=False) + ) + assert result.status == "complete" + assert result.artifacts[0].fallback_for == [] + + +@pytest.mark.parametrize( + ("part", "formats"), + [("lead", ["griff"]), ("bass", ["briff"]), ("drums", ["sd3p"])], +) +def test_actual_suffix_requests_preserve_default_midi_fallback( + workspace: Path, part: Part, formats: list[str] +) -> None: + result = GenerationService(workspace).generate_music(request(parts=[part], formats=formats)) + assert result.status == "midi_fallback" + assert result.artifacts[0].format == "mid" + assert result.artifacts[0].fallback_for == [part] + + +@pytest.mark.parametrize("output_format", ["agp", "griff"]) +def test_explicit_native_target_is_service_wired(workspace: Path, output_format: str) -> None: + result = GenerationService(workspace).generate_music( + request( + parts=["lead"], + formats=[output_format], + profiles={"lead": "ample.ame.4.0.1.riffer.v1"}, + ) + ) + assert result.status == "complete" + assert len(result.artifacts) == 1 + assert result.artifacts[0].format == "griff" + assert Path(result.artifacts[0].path).read_bytes().startswith(b" None: + result = GenerationService(workspace).generate_music( + request( + description="drums only 1 bar quarter", + parts=["drums"], + formats=["mid"], + profiles={"drums": "toontrack.sd3.3.4.4.core.v1"}, + allow_midi_fallback=False, + ) + ) + assert result.status == "complete" + assert result.artifacts[0].profile_ids == ["toontrack.sd3.3.4.4.core.v1"] + assert result.artifacts[0].format == "mid" + assert [(warning.code, warning.part) for warning in result.warnings] == [ + ("VERIFIED_SUBSET_LIMITS", "drums") + ] + + +def test_sd3_native_service_preflight_requires_optional_template_without_staging( + workspace: Path, +) -> None: + with pytest.raises(NativeFormatUnavailableError) as error: + GenerationService(workspace).generate_music( + request( + description="drums only 1 bar quarter", + parts=["drums"], + formats=["sd3p"], + profiles={"drums": "toontrack.sd3.3.4.4.core.v1"}, + allow_midi_fallback=False, + ) + ) + assert error.value.details["reason"] == "sdp_template_required" + assert not list(workspace.iterdir()) + + +def test_profile_listing_is_real_defensive_and_honest(workspace: Path) -> None: + service = GenerationService(workspace) + profiles = service.list_instrument_profiles().profiles + assert {profile.id for profile in profiles} == { + "ample.ame.4.0.1.riffer.v1", + "ample.amr.4.1.0.riffer.v1", + "standard.lead.v1", + "standard.bass.v1", + "standard.gm-drums.v1", + "toontrack.sd3.3.4.4.core.v1", + } + assert all( + profile.mapping_kind == "standard_midi" + and profile.midi_available + and not profile.native_available + and profile.supported_articulations == ["normal"] + and "NOT verified Eclips/Ray/SD3" in profile.limitations[0] + for profile in profiles + if profile.id.startswith("standard.") + ) + assert all( + p.native_available + and p.supported_articulations + == ( + ["normal", "palm_mute", "pinch_harmonic"] + if p.part == "lead" + else ["normal", "palm_mute"] + ) + for p in profiles + if p.id.startswith("ample.") + ) + profiles[0].limitations.clear() + assert service.list_instrument_profiles().profiles[0].limitations + assert not list(workspace.iterdir()) + + +def test_wrong_profile_id_for_part_is_not_fallback(workspace: Path) -> None: + with pytest.raises(DomainError) as error: + GenerationService(workspace).generate_music( + request(parts=["lead"], profiles={"lead": "standard.bass.v1"}) + ) + assert error.value.code == "PROFILE_REQUIRED" + assert error.value.details["reason"] == "wrong_part" + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize("formats", [None, ["mid"], ["agp"]]) +def test_palm_mute_is_never_dropped(workspace: Path, formats: list[str] | None) -> None: + with pytest.raises(UnsupportedArticulationError): + GenerationService(workspace).generate_music( + request(description="lead only palm mute", formats=formats) + ) + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize( + "updates", + [ + {"basename": "../escape"}, + {"basename": "NUL"}, + {"parts": ["lead", "lead"]}, + {"bars": True}, + {"time_signature": {"numerator": 4, "denominator": 4.0}}, + {"profiles": {"drums": "wrong"}, "parts": ["lead"]}, + ], +) +def test_unchecked_request_copies_are_revalidated( + workspace: Path, updates: dict[str, object] +) -> None: + bad = request().model_copy(update=updates) + with pytest.raises(InvalidRequestError): + GenerationService(workspace).generate_music(bad) + assert not list(workspace.iterdir()) + + +def test_deep_request_mutation_is_revalidated(workspace: Path) -> None: + bad = request(time_signature={"numerator": 4, "denominator": 4}) + assert bad.time_signature is not None + bad.time_signature.numerator = 99 + with pytest.raises(InvalidRequestError): + GenerationService(workspace).generate_music(bad) + assert not list(workspace.iterdir()) + + +def test_corrupt_map_is_error_not_fallback(workspace: Path) -> None: + registry = load_profile_registry() + original = registry.select + + def corrupt(parts: list[Part], selection: ProfileSelection) -> dict[Part, InstrumentProfile]: + selected = original(parts, selection) + selected[parts[0]].channel = 99 + return selected + + with ( + patch.object(registry, "select", side_effect=corrupt), + pytest.raises(SerializationError), + ): + GenerationService(workspace, registry=registry).generate_music(request()) + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize("call", ["check_agp_capability", "check_sdp_capability"]) +@pytest.mark.parametrize( + "failure", + [SerializationError(details={"reason": "corrupt_map"}), RuntimeError("private-bug")], +) +def test_only_known_unavailability_can_fallback( + workspace: Path, call: str, failure: Exception +) -> None: + with ( + patch(f"riff_groove_builder.service.{call}", side_effect=failure), + pytest.raises(type(failure)), + ): + GenerationService(workspace).generate_music(request()) + assert not list(workspace.iterdir()) + + +def test_future_capability_flag_cannot_create_fake_native_success(workspace: Path) -> None: + with ( + patch( + "riff_groove_builder.service.check_agp_capability", + return_value=NativeCapability( + part="lead", format="agp", available=True, reason="test_flag_not_a_codec" + ), + ), + pytest.raises(NativeFormatUnavailableError) as error, + ): + GenerationService(workspace).generate_music(request(parts=["lead"])) + assert error.value.details["reason"] == "riffer_profile_not_supported" + assert not list(workspace.iterdir()) + + +def test_event_budget_failure_does_not_stage(workspace: Path) -> None: + with pytest.raises(SerializationError): + GenerationService(workspace).generate_music( + request(description="lead bass drums 256 bars 16/1 sixteenth", formats=["mid"]) + ) + assert not list(workspace.iterdir()) + + +@pytest.mark.parametrize("existing", ["empty", "nonempty", "file"]) +def test_destinations_are_never_replaced(workspace: Path, existing: str) -> None: + destination = workspace / "music" + if existing == "file": + destination.write_bytes(b"operator sentinel") + else: + destination.mkdir() + if existing == "nonempty": + (destination / "sentinel").write_bytes(b"operator sentinel") + before = destination.stat() + with pytest.raises(OutputExistsError): + GenerationService(workspace).generate_music(request()) + after = destination.stat() + assert (before.st_ino, before.st_mtime_ns) == (after.st_ino, after.st_mtime_ns) + assert not list(workspace.glob(".riff-stage-*")) + if existing == "file": + assert destination.read_bytes() == b"operator sentinel" + elif existing == "nonempty": + assert (destination / "sentinel").read_bytes() == b"operator sentinel" + else: + assert not list(destination.iterdir()) + + +def test_root_replacement_is_rejected_without_touching_replacement(workspace: Path) -> None: + root = workspace / "outputs" + root.mkdir() + service = GenerationService(root) + root.rename(workspace / "original") + root.mkdir() + sentinel = root / "sentinel" + sentinel.write_bytes(b"preserved") + with pytest.raises(OutputIOError) as error: + service.generate_music(request()) + assert error.value.details["reason"] == "output_root_changed" + assert list(root.iterdir()) == [sentinel] + + +def test_ancestor_replacement_is_rejected(workspace: Path) -> None: + parent = workspace / "parent" + root = parent / "outputs" + root.mkdir(parents=True) + service = GenerationService(root) + parent.rename(workspace / "original-parent") + root.mkdir(parents=True) + with pytest.raises(OutputIOError) as error: + service.generate_music(request()) + assert error.value.details["reason"] == "output_root_changed" + assert not list(root.iterdir()) + + +def test_cleanup_refuses_changed_directory_identity(workspace: Path) -> None: + service = GenerationService(workspace) + stage = service._new_stage("music") + stage.path.rename(workspace / "moved-owned-stage") + stage.path.mkdir() + sentinel = stage.path / stage.filenames[0] + sentinel.write_bytes(b"unowned") + with pytest.raises(OutputIOError, match="permissions") as error: + service._cleanup(stage) + assert error.value.details == {"reason": "stage_cleanup_failed"} + assert sentinel.read_bytes() == b"unowned" + + +def test_cleanup_rejects_unrelated_stage_content(workspace: Path) -> None: + service = GenerationService(workspace) + stage = service._new_stage("music") + sentinel = stage.path / "unrelated" + sentinel.write_bytes(b"unowned") + with pytest.raises(OutputIOError): + service._cleanup(stage) + assert sentinel.read_bytes() == b"unowned" + + +def test_cleanup_refuses_path_outside_root(workspace: Path) -> None: + root = workspace / "outputs" + root.mkdir() + sentinel = workspace / "music.mid" + sentinel.write_bytes(b"preserved") + info = workspace.stat() + stage = _Stage(workspace, (info.st_dev, info.st_ino), ("music.mid",)) + with pytest.raises(OutputIOError): + GenerationService(root)._cleanup(stage) + assert sentinel.read_bytes() == b"preserved" + + +def test_root_reparse_detection_does_not_depend_only_on_symlink_mode(workspace: Path) -> None: + with patch("riff_groove_builder.service._linked", return_value=True): + with pytest.raises(ValueError, match="existing local directory"): + validate_output_root(str(workspace)) + + +@pytest.mark.parametrize("basename", ["CON", "a.mid", "a/b", "a\\b", "..", "a.", "a ", "x:y"]) +def test_safe_basename_contract(workspace: Path, basename: str) -> None: + with pytest.raises(ValidationError): + request(basename=basename) + assert not list(workspace.iterdir()) + + +def test_unimplemented_portable_publication_is_explicit(workspace: Path) -> None: + service = GenerationService(workspace) + with ( + patch("riff_groove_builder.service.os.name", "posix"), + pytest.raises(OutputIOError) as error, + ): + service.generate_music(request(formats=["mid"])) + assert error.value.details["reason"] == "no_replace_publication_requires_windows" + assert not list(workspace.iterdir()) + + +def test_bounded_stage_name_attempts(workspace: Path) -> None: + service = GenerationService(workspace) + with patch.object(Path, "mkdir", side_effect=FileExistsError) as mkdir: + with pytest.raises(OutputIOError) as error: + service.generate_music(request()) + assert error.value.details["reason"] == "stage_name_collisions" + assert mkdir.call_count == 3 + assert not list(workspace.iterdir()) + + +def test_directory_creation_failure_is_named(workspace: Path) -> None: + service = GenerationService(workspace) + with patch.object(Path, "mkdir", side_effect=PermissionError): + with pytest.raises(OutputIOError) as error: + service.generate_music(request()) + assert error.value.details["reason"] == "stage_create_failed" + assert not list(workspace.iterdir()) + + +@pytest.mark.skipif(os.name != "nt", reason="Windows local volume classification") +@pytest.mark.parametrize("drive_type", [0, 1, 4, 5]) +def test_nonlocal_or_unusable_volumes_are_rejected(workspace: Path, drive_type: int) -> None: + with patch( + "riff_groove_builder.service.ctypes.windll.kernel32.GetDriveTypeW", + return_value=drive_type, + ): + with pytest.raises(ValueError, match="existing local directory"): + validate_output_root(str(workspace)) + + +def test_incomplete_constructed_request_is_rejected(workspace: Path) -> None: + with pytest.raises(InvalidRequestError): + GenerationService(workspace).generate_music(GenerateMusicRequest.model_construct()) + assert not list(workspace.iterdir()) + + +@pytest.mark.skipif(os.name != "nt", reason="Windows no-replace directory rename contract") +def test_real_publish_refuses_existing_empty_directory(workspace: Path) -> None: + service = GenerationService(workspace) + stage = service._new_stage("music") + destination = workspace / "music" + destination.mkdir() + with pytest.raises(OutputExistsError): + service._publish(stage, destination) + assert destination.is_dir() and not list(destination.iterdir()) + assert stage.path.is_dir() + service._cleanup(stage) diff --git a/tests/unit/test_standard_profiles.py b/tests/unit/test_standard_profiles.py new file mode 100644 index 0000000..33e20e2 --- /dev/null +++ b/tests/unit/test_standard_profiles.py @@ -0,0 +1,180 @@ +"""Standard MIDI facts and generator policy, not installed vendor compatibility.""" + +import pytest +from pydantic import ValidationError + +from riff_groove_builder.profiles import ( + InstrumentProfile, + ProfileRegistry, + load_profile_registry, + parse_profile, +) +from riff_groove_builder.schemas import Part, ProfileSelection + + +def standard(part: Part = "lead") -> InstrumentProfile: + identifier = "standard.gm-drums.v1" if part == "drums" else f"standard.{part}.v1" + return load_profile_registry().select([part], ProfileSelection(**{part: identifier}))[part] + + +@pytest.mark.parametrize("part", ["lead", "bass", "drums"]) +def test_standard_identity_policy_and_roundtrip(part: Part) -> None: + profile = standard(part) + assert profile.provenance.status == profile.summary.mapping_kind == "standard_midi" + assert profile.summary.mapping_version == "standard-fallback-1" + assert profile.summary.limitations == profile.provenance.limitations + assert "NOT verified Eclips/Ray/SD3" in profile.summary.limitations[0] + assert not profile.id.startswith("test.") + assert not profile.summary.product_name.startswith("SYNTHETIC") + assert profile.summary.supported_articulations == ["normal"] + assert profile.normal_articulation == "normal" + assert profile.resolve_articulation("sustain") == profile.resolve_articulation("normal") + assert profile.resolve_articulation("NORMAL").actions == [] + assert profile.resolve_articulation("normal").mode == "latched" + assert parse_profile(profile.model_dump_json()) == profile + assert ProfileRegistry([profile]).summaries() == [profile.summary] + assert {s.kind for s in profile.provenance.sources} == {"standard_public", "generator_policy"} + assert all( + s.reference.startswith("https://") + if s.kind == "standard_public" + else s.reference == "docs/articulation-profiles.md#standard-fallback-policy-v1" + for s in profile.provenance.sources + ) + if part != "drums": + assert profile.playable_range is not None + assert profile.playable_range.model_dump() == {"low": 0, "high": 127} + assert profile.drum_voices == [] + + +def test_complete_gm_level_1_percussion_numbers() -> None: + # Independently transcribed numeric/name facts from the public teaching table: + # https://computermusicresource.com/GM.Percussion.KeyMap.html + names = ( + "acoustic_bass_drum bass_drum_1 side_stick acoustic_snare hand_clap electric_snare " + "low_floor_tom closed_hi_hat high_floor_tom pedal_hi_hat low_tom open_hi_hat " + "low_mid_tom hi_mid_tom crash_cymbal_1 high_tom ride_cymbal_1 chinese_cymbal " + "ride_bell tambourine splash_cymbal cowbell crash_cymbal_2 vibraslap ride_cymbal_2 " + "hi_bongo low_bongo mute_hi_conga open_hi_conga low_conga high_timbale low_timbale " + "high_agogo low_agogo cabasa maracas short_whistle long_whistle short_guiro " + "long_guiro claves hi_wood_block low_wood_block mute_cuica open_cuica " + "mute_triangle open_triangle" + ).split() + profile = standard("drums") + assert len(names) == len(profile.drum_voices) == 47 + assert [(v.note, v.name) for v in profile.drum_voices] == list( + zip(range(35, 82), names, strict=True) + ) + assert profile.playable_range is None + assert profile.channel == 9 + assert { + name: profile.resolve_voice(name) + for name in ("kick", "snare", "closed hat", "open-hat", "pedal_hat", "crash", "ride") + } == { + "kick": 36, + "snare": 38, + "closed hat": 42, + "open-hat": 46, + "pedal_hat": 44, + "crash": 49, + "ride": 51, + } + assert {s.reference for s in profile.provenance.sources if s.kind == "standard_public"} == { + "https://midi.org/general-midi-level-1", + "https://computermusicresource.com/GM.Percussion.KeyMap.html", + } + + +@pytest.mark.parametrize("part", ["lead", "bass", "drums"]) +@pytest.mark.parametrize( + ("intensity", "velocity"), [(0.0, 1), (0.25, 32), (0.5, 64), (0.75, 96), (1.0, 127)] +) +def test_single_linear_velocity_policy(part: Part, intensity: float, velocity: int) -> None: + art = standard(part).resolve_articulation("normal") + assert len(art.layers) == 1 + assert art.layers[0].model_dump() == { + "low": 0.0, + "high": 1.0, + "velocity_low": 1, + "velocity_high": 127, + } + assert art.velocity(intensity) == velocity + + +@pytest.mark.parametrize( + ("section", "field", "value"), + [ + ("summary", "mapping_kind", "instrument"), + ("summary", "product_name", "Verified Eclips map"), + ("summary", "supported_articulations", ["normal", "slide"]), + ("provenance", "status", "verified"), + ("provenance", "status", "test_only"), + ("provenance", "sources", []), + ], +) +def test_no_standard_to_vendor_or_test_promotion(section: str, field: str, value: object) -> None: + data = standard().model_dump() + data[section][field] = value + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +@pytest.mark.parametrize("mutation", ["actions", "aliases", "mode", "name", "normal"]) +def test_standard_cannot_invent_techniques_or_controls(mutation: str) -> None: + data = standard().model_dump() + art = data["articulations"][0] + if mutation == "actions": + art["actions"] = [ + { + "kind": "cc", + "controller": 20, + "value": 0, + "reset_value": None, + "lead": {"numerator": 0}, + "release_offset": {"numerator": 0}, + } + ] + elif mutation == "aliases": + art["aliases"].append("slide") + elif mutation == "mode": + art["mode"] = "momentary" + elif mutation == "name": + art["name"] = "sustain" + else: + data["normal_articulation"] = "sustain" + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +@pytest.mark.parametrize( + "mutation", + ["no_facts", "no_policy", "missing_range", "missing_velocity", "http", "vendor", "bad_policy"], +) +def test_standard_provenance_requires_facts_and_separate_policy(mutation: str) -> None: + data = standard().model_dump() + sources = data["provenance"]["sources"] + if mutation == "no_facts": + sources.pop(0) + elif mutation == "no_policy": + sources.pop(1) + elif mutation == "missing_range": + sources[0]["aspects"].remove("range_or_voices") + elif mutation == "missing_velocity": + sources[1]["aspects"].remove("velocity") + elif mutation == "http": + sources[0]["reference"] = "http://example.invalid" + elif mutation == "vendor": + sources[0]["kind"] = "official_public" + else: + sources[1]["reference"] = "not a policy reference" + with pytest.raises(ValidationError): + InstrumentProfile.model_validate(data) + + +def test_standard_selection_returns_defensive_copies() -> None: + registry = load_profile_registry() + selected = registry.select(["lead"], ProfileSelection(lead="standard.lead.v1")) + selected["lead"].summary.mapping_kind = "instrument" + selected["lead"].articulations[0].aliases.append("slide") + fresh = registry.select(["lead"], ProfileSelection(lead="standard.lead.v1"))["lead"] + assert fresh.summary.mapping_kind == "standard_midi" + assert fresh.articulations[0].aliases == ["sustain"]