Cubase-MCP-GAJ3T.MusicGen.R.../prompts/plan.md

956 lines
52 KiB
Markdown

# GAJ3T.MusicGen.Riff-Groove-Builder: Architecture and Execution Plan
Status: approved for execution by the owner ("Go for it", 2026-10-19).
Issue and review one worker step at a time; all evidence gates remain in force.
Execution review log:
- Step 1 accepted on 2026-10-19 after reading `report_1.md`, checking scaffold,
tests and compatibility inventory, and independently running Release
build/test: 8 passed, 0 failed, 0 skipped. Editor test discovery was unavailable;
CLI validation succeeded. Native evidence gates remain open.
- Step 2 accepted on 2026-10-19 after reading `report_2.md`, reviewing transport,
dispatch, lifecycle and tool contracts, and independently running Release
build/test: 130 passed, 0 failed, 0 skipped. Production tools remain empty.
- Step 3 accepted on 2026-10-19 after reading `report_3.md`, checking the text
contract, exact-rational model, parser, planner and validator, and independently
running Release build/test: 318 passed, 0 failed, 0 skipped. Step 4 may implement
generic infrastructure, but production readiness still requires real mappings.
- Step 4 infrastructure reviewed on 2026-10-19 after reading `report_4.md`,
checking profile/catalog validation, event planning and ordering, and
independently running Release build/test: 485 passed, 0 failed, 0 skipped.
Independent locked restore also passed. Full Step 4 is BLOCKED, not accepted:
no authorized production mappings or exact installed-product evidence exists.
The embedded production catalog is deliberately empty.
- Scope revision approved by the owner on 2026-10-20: include ABJ, AGLP, AGM,
AGT, AME and AMR as the initial Ample target set, and make instrument expansion
data-driven. The current `step_4_fix.md` implements this catalog extension
without pretending missing mappings are available. No Step 5 prompt had been
issued at that review; later sequencing is recorded below. Full production
mapping readiness remains a separate review gate.
- Step 4 catalog correction iteration 2 accepted on 2026-10-20 after reading
the appended `report_4.md`, reviewing identity/profile binding, strict catalog
loading, selection, availability and data-only extension tests, and
independently running Release build/test: 566 passed, 0 failed, 0 skipped.
Locked restore and whitespace checks also passed. Seven identities are
declared (six Ample plus SD3); zero production mapping profiles are admitted.
This accepts the catalog extension, not the unresolved full Step 4 gate.
- Sequencing decision on 2026-10-20, following the owner's "now what?":
proceed with generic Step 5 MIDI generation using accepted Step 4
infrastructure and test-only profiles. The decision form was unavailable;
MIDI-engine-first was selected autonomously as the pragmatic next milestone.
No scope or production compatibility gate is waived. Real profile admission
and native/plugin acceptance remain separate outstanding work.
- Step 5 format writer accepted on 2026-10-20 after reading `report_5.md` and
reviewing conversion, file construction, actual read-back tests and staged
no-overwrite output. Worker Release validation passed all 663 tests.
Independent MIDI/shared-pipeline validation passed 106 tests; independent
locked restore also passed. No synthetic profile was admitted to production.
Documented pinned-library limits include unsupported writer meter /256 and
the standard four-byte delta maximum. Native schemas, real profiles, public
generation tools and application acceptance remain outstanding; no Step 6
prompt has been issued.
- Continuation on 2026-10-20: the owner requested documentation-backed
profiles, native-format investigation and usable tool/deployment work.
`step_4_fix.md`, correction iteration 3, now handles profile sources and
explicitly separates documented default mappings from installation-tested
mappings. Native-format investigation is independent read-only research;
no native writer is authorized without its own evidence.
- Correction iteration 3 accepted for its bounded source-backed subset:
AGLP and AME now have Documented profiles, genuine absolute-number anchors
from official demo MIDI, and disclosed writer policies. Worker Release/full
validation passed 714 tests; independent source/catalog/MIDI validation
passed 299 tests. Five target mappings and all real-plugin acceptance remain
unresolved. This is not full requested-product readiness.
- Native investigation found no authorized AGP/SDP codec or fixture sufficient
for implementation. SD3's shared manual still requires login; indexed
vendor-domain references to SD3P raise an extension question but do not
establish a substitute or an SDP schema. Native outputs remain unavailable.
- Next sequencing: Step 8 may integrate the accepted MIDI writer and admitted
profiles now, exercising the already planned explicit MIDI-fallback policy.
Steps 6/7 are blocked, not completed. Advertise unavailable native capabilities
truthfully, reject disabled fallback, never rename MIDI as a native file,
and fail unavailable selected roles rather than silently dropping them.
- Step 8 supported MIDI/fallback slice accepted after reading `report_8.md`,
reviewing production registration, schemas, selection, generation and output
safety, and independently running the 272 targeted tests. Worker Release
full validation passed 868 tests. Actual stdio calls produce readable MIDI
using the AGLP/AME Documented profiles; unavailable roles/native formats fail
or fall back explicitly. This is not completion of native Steps 6/7.
- Step 9 may now publish and smoke-test this usable local supported slice.
No runtime-free machine or licensed application acceptance is implied by
a successful development-machine publish/smoke check.
- Step 9 supported publication accepted after reading `report_9.md`, reviewing
the publish profile/lock, isolated published-process tests and deployment
guide, and independently passing all 14 published-process checks. Both
ordinary and publication locked restores passed independently. Worker full
validation passed 882 tests. The retained executable and newly generated
example exist with hashes matching the report; runtime-free Windows and
licensed application acceptance remain pending, native Steps 6/7 blocked.
- A bounded read-only follow-up is checking the vendor's other public demo
archives for remaining product-specific numeric anchors. It does not mutate
the accepted published payload or claim additional mappings supported.
- That follow-up established AGM 24/26 from official AGM demo MIDI and ABJ
numeric evidence from a vendor demo explicitly advertised for ABJ/ABP.
The missing dedicated PalmMute threshold does not invalidate an evidenced
Sustain-only bass capability. Correction iteration 4 will integrate those
supported subsets, investigate only the concrete AGT tab-play anchor lead,
and refresh all affected MCP/publish tests, disclosures and publication.
AMR/SD3 and native codecs remain unavailable unless genuine evidence changes.
- Correction iteration 4 and its publication refresh are accepted for the
documented subset after reading both report appends and reviewing the new
facts/capabilities, profile data and actual MIDI/RPC/publication evidence.
AGM and ABJ Sustain-only anchors are established; AGT's vendor-documented
A6 tab control plus official note105 demo establishes its numeric anchor.
Five profiles now ship: AGLP/AGM/AGT/AME Sustain+PalmMute and ABJ Sustain-only.
Worker full validation passed 936 tests; independent focused validation
passed 521, including refreshed published-process checks. Both locked
restore graphs passed independently. Published executable SHA256 is
`921AADE7FB75222E8A7E5E81151F3DC73747CD8036EE751555A613A5DBDD308E`;
the existing AME example remains byte-identical to its accepted report.
AMR, SD3, ABJ PalmMute, native exporters, licensed-application and
runtime-free-host acceptance remain unresolved, not silently completed.
## 1. Scope and completion criteria
Build a .NET 10 console application that an MCP client launches as a local process.
It accepts text descriptions through MCP tools over JSON-RPC/stdin/stdout and
generates musical data for:
| Role | Target | Required native output |
| --- | --- | --- |
| Lead/guitar slot | Ample Guitar LP (AGLP), Ample Guitar M (AGM), Ample Guitar T (AGT), Ample Metal Eclipse (AME) | `.agp`, subject to per-product verification |
| Bass | Ample Bass J (ABJ), Ample Metal Ray5 (AMR) | `.agp`, subject to per-product verification |
| Drums | Superior Drummer 3, using the owner's exact installed version and MIDI mapping | `.sdp` |
| All selected roles | Cubase MIDI import and instrument routing | Standard MIDI `.mid` |
Use `Melanchall.DryWetMidi` **8.0.3** for every MIDI construction, read, write, and
manipulation operation. Native container serialization is a separate concern:
DryWetMIDI does not establish the proprietary `.agp` or `.sdp` schemas.
Deliver a self-contained, locally launched executable. Do not add HTTP endpoints,
containers, audio analysis, audio rendering, playback/device control, a GUI,
cloud services, an external LLM dependency, or Cubase `.cpr` generation.
"Cubase-compatible" means that MIDI imports into Cubase and native files open
through the corresponding instrument's supported load/import workflow. It does
not mean that Cubase opens `.agp` or `.sdp` as Cubase project files.
Full completion requires verified native outputs for the requested Ample targets and SD3,
MIDI fallback, articulation correctness, passing automated tests, and documented
application-level import checks. A MIDI-only milestone is useful but is not full
completion of this scope.
## 2. Current repository and evidence gates
At initial planning, `src`, `docs`, and `prompts` were empty. Steps 1-3 and the
generic Step 4 infrastructure now exist, as recorded above. The layout below
describes the complete intended solution, not a claim that all modules exist.
### Verified baseline
- MCP stdio uses UTF-8, newline-delimited JSON-RPC messages, not LSP
`Content-Length` framing. Stdout must contain protocol messages only.
- The MCP lifecycle includes `initialize`, version/capability negotiation, and
`notifications/initialized`.
- The NuGet page for `Melanchall.DryWetMidi` 8.0.3 documents Standard MIDI File
support. This is not evidence of proprietary native-format support.
- .NET supports RID-specific, self-contained, single-file publication.
### Native-format and articulation gate
Do not assume `.agp` or `.sdp` is MIDI, XML, JSON, ZIP, or any other container.
Do not guess note numbers from product names or octave labels.
For profile admission, distinguish source verification from application
acceptance. A `Documented` mapping may encode published vendor defaults whose
numeric mapping facts are supported by cited sources; any timing/routing
engineering policy and version limitations must be explicit compatibility
notes, not invented vendor requirements. It is not an assertion about the
owner's installed configuration. `Verified` remains the application-verified
stage; `Unverified` and `Synthetic` are not production-selectable. Both
selectable stages must retain provenance, correct catalog binding and strict
numeric/state validation. Public generation with a merely documented mapping
must disclose that distinction and its compatibility assumptions.
If documentation omits a necessary mapping fact, leave that capability/profile
unavailable. Do not fill it with test values. Native schema/template/import
acceptance is a separate gate and is not established by either profile stage.
Before implementing a production profile or native writer, obtain:
1. Exact installed product names, versions, and relevant settings for the
selected Ample targets, SD3, and the Cubase version used for acceptance.
2. Lawfully usable vendor documentation or owner-created native fixtures, with
their versions and provenance recorded. Fixtures must not contain audio
libraries, licensed sample content, credentials, or unrelated user projects.
3. Minimal files saved by the target applications: empty/short pattern, one
note/hit, changed pitch, duration, velocity, tempo, and each supported
articulation/control. Change one property at a time.
4. Confirmation of the exact `.agp` and `.sdp` extensions and whether each
represents a riff, groove, preset, or project in that product/version.
5. Verified MIDI mappings: playable ranges, keyswitches, velocity-layer rules,
controller numbers/values, switch timing, persistence, reset behavior,
channel behavior, and the chosen SD3 drum map.
6. A repeatable import procedure and evidence that generated test files reopen
with the intended musical data in the actual target application.
The public Ample manual URL did not expose a usable format specification during
planning. The SD3 manual page required login. Consequently, no native schema,
specific keyswitch number, or SD3 extension semantics are asserted here.
If the target application does not support the requested extension or no
validated generation route can be established, stop that step and report the
blocker. Seek an owner decision; do not silently substitute another native
extension, fabricate a file, automate undocumented GUI actions, or declare the
native requirement complete. MIDI fallback is an explicitly reported degraded
result, not proof that the native writer works.
## 3. Solution layout
Use three production projects and two xUnit test projects. Avoid one project per
writer or interface.
```text
GAJ3T.MusicGen.Riff-Groove-Builder.Net\
GAJ3T.MusicGen.RiffGrooveBuilder.slnx
global.json
Directory.Build.props
Directory.Packages.props
NuGet.config
.gitignore
README.md
src\
GAJ3T.MusicGen.RiffGrooveBuilder.Core\
GAJ3T.MusicGen.RiffGrooveBuilder.Core.csproj
Composition\ # Models, validation, supported text grammar/planner
Instruments\ # Vendor-neutral instrument identity metadata
Articulations\ # Profile models, validation, event planning
Generation\ # Request/result types and writer contracts
GAJ3T.MusicGen.RiffGrooveBuilder.Generation\
GAJ3T.MusicGen.RiffGrooveBuilder.Generation.csproj
Midi\ # DryWetMIDI event construction and SMF writer
Native\ # Separately verified AGP and SDP serializers
Instruments\ # Embedded declarative instrument catalog
Profiles\ # Embedded, versioned, evidence-backed mappings
Output\ # File staging, publication, cleanup
GenerationService.cs # Shared pipeline and explicit fallback policy
GAJ3T.MusicGen.RiffGrooveBuilder.Server\
GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj
Program.cs
Protocol\ # Stdio framing, JSON-RPC, MCP lifecycle
Tools\ # Input/output schemas and handlers
Properties\
PublishProfiles\
win-x64.pubxml
tests\
GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\
GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj
Composition\
Articulations\
Midi\
Native\
Protocol\
GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\
GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.csproj
Stdio\
Generation\
Publishing\
Fixtures\
agp\ # Only permitted, provenance-recorded fixtures
sdp\
docs\
text-description-contract.md
format-compatibility.md
articulation-mappings.md
acceptance-tests.md
local-deployment.md
prompts\
plan.md
step_N.md # Created one at a time, after approval
report_N.md # Written by the worker
step_N_fix.md # Created only when correction is needed
```
References: Core has no project dependencies; Generation references Core;
Server references Core and Generation. Tests reference only the projects they
exercise. Core models use musical values and typed event intentions rather than
DryWetMIDI types; Generation translates these intentions through DryWetMIDI.
Use `System.Text.Json` and .NET base libraries for protocol/configuration work.
Pin DryWetMIDI exactly to 8.0.3 in central package management. Use xUnit, its
compatible test runner, and `Microsoft.NET.Test.Sdk`, selecting and pinning stable
.NET 10-compatible versions during scaffolding. Do not guess package versions.
Record the installed .NET 10 SDK in `global.json` with patch roll-forward.
### Instrument identity versus mapping profiles
The owner-requested initial catalog is:
| Stable instrument ID | Vendor code | Product | Existing role |
| --- | --- | --- | --- |
| `ample-abj` | ABJ | Ample Bass J | bass |
| `ample-aglp` | AGLP | Ample Guitar LP | lead |
| `ample-agm` | AGM | Ample Guitar M | lead |
| `ample-agt` | AGT | Ample Guitar T | lead |
| `ample-ame` | AME | Ample Metal Eclipse | lead |
| `ample-amr` | AMR | Ample Metal Ray5 | bass |
| `toontrack-sd3` | SD3 | Superior Drummer 3 | drums |
The six Ample library folders identify requested targets, not installed plugin
versions or verified MIDI/native capabilities. Product names and manual links
are confirmed against the vendor's documentation index. The existing lead slot
can hold one selected acoustic or electric guitar; this scope revision does not
add rhythm/strumming patterns, extra simultaneous guitar slots, or new track roles.
Use a small vendor-neutral `InstrumentDefinition` for stable ID, vendor,
product code/name, role and documentation link. Store the initial definitions
in an embedded JSON catalog, separately from verified `InstrumentProfile`
data. Every profile references its instrument by `InstrumentId`; an instrument
can have multiple versioned mappings without changing the composition planner.
Declared targets without verified profiles remain visible as
`mapping_unavailable`, never as playable or natively supported. Catalog/profile
validation checks references, role and product identity. Selection must
distinguish unknown instruments, known instruments without mappings, wrong-role
profiles and ambiguous profile choices. Do not choose the first guitar/bass by
folder order or silently substitute a different product.
Adding another instrument with existing articulation mechanisms means adding a
catalog definition and an evidence-backed mapping profile, not a subclass,
product-name switch or MIDI engine change. Initially this data is embedded:
changes require build/publish. Runtime profile directories, VST scanning,
binary loading, hot reload and a dynamic plugin framework are not included.
Different mechanisms or unverified native formats still require explicit work.
Keep export behavior behind format-level contracts when the corresponding
writers are implemented. Share an AGP writer across products only where native
evidence permits; do not add per-instrument writer classes speculatively.
## 4. Modules and execution flow
```text
MCP client
-> stdio transport / JSON-RPC dispatcher / MCP lifecycle
-> tool schema validation
-> description parser and composition planner
-> validated, instrument-neutral Composition
-> verified instrument profiles and articulation event planner
-> DryWetMIDI MIDI construction
-> requested native serializers and/or Standard MIDI writer
-> staged files, collision-safe publication, structured tool result
```
### Core
- `Composition`: global tempo, meter, key, bar count, and selected role tracks.
- `TrackPlan`: role, profile ID, logical channel, musical notes/hits, and
articulation/control intentions. Keep control notes separate from played notes.
- `MusicalNote`: MIDI pitch, rational beat start/duration, velocity, articulation.
Use integer/rational timing, never cumulative floating-point beat additions.
- `DescriptionParser` / `CompositionPlanner`: deterministic interpretation,
minimal musical pattern construction, and explicit diagnostics.
- `CompositionValidator`: representable timing/tempo, positive duration, valid
MIDI ranges, valid tracks and profiles, checked arithmetic, and actionable
field-level errors. Reject invalid requests rather than silently clamp.
- `InstrumentProfile` / `ArticulationPlanner`: versioned mapping rules and typed
note/CC/switch event intentions.
- Generation contracts describe requested formats, artifacts, warnings,
per-target outcomes, and typed failures.
### Generation
- `MidiEventBuilder` / `MidiFileWriter`: the only layer constructing MIDI events
or writing/reading MIDI, always through DryWetMIDI 8.0.3.
- `AgpWriter`: native Ample serialization, with per-instrument capability checks;
share a codec only if evidence establishes the same format.
- `SdpWriter`: native SD3 serialization for the verified product version/type.
- `GenerationService`: preflight, shared composition/event planning, writer
selection, explicit fallback decisions, and result assembly.
- `OutputPublisher`: temporary staging under the chosen output filesystem,
no-overwrite publication, and cleanup of only files created by this request.
A request never reports success before its output files exist.
### Server
- `StdioTransport`: newline framing, UTF-8, serialized stdout writes, stderr-only
diagnostics, EOF/cancellation handling, and bounded message handling.
- `JsonRpcDispatcher`: preserve numeric/string request IDs, distinguish requests
from notifications, and map protocol errors correctly.
- `McpSession`: initialization/version/capability state, ping, and shutdown by
stream closure. Advertise only implemented capabilities.
- Tool handlers validate inputs and call the application service; no music
generation logic inside transport handlers.
Use a small explicit MCP implementation rather than introducing another runtime
SDK dependency. Target MCP version `2025-11-25`; do not imply support for other
versions until tested. If a client requests an unsupported version, respond with
the server's supported version as specified by MCP and let the client decide
whether to disconnect.
Support `initialize`, `notifications/initialized`, `ping`, `tools/list`,
`tools/call`, and `notifications/cancelled`. Do not introduce HTTP, resources,
sampling, prompts, or asynchronous task capabilities. Read cancellation
notifications while work runs and propagate cancellation to that request;
keep output writes serialized. Notifications receive no JSON-RPC response.
Do not invent an MCP `shutdown` method.
Use standard JSON-RPC errors for malformed JSON, invalid envelopes, unknown
methods, invalid tool selection/arguments, and unexpected internal failures.
Represent expected generation failures as MCP tool results with `isError: true`
and actionable diagnostics. Log internal details to stderr, not into stdout or
success-shaped results.
## 5. Text-to-composition contract
Proposed initial interpretation approach for owner review: a deterministic,
documented English musical-description subset, not an unrestricted language
model. The MCP host can phrase user intent in this supported vocabulary, but
the server must itself transform the supplied text into musical structure.
It must not require an unimplemented external model or hidden network service.
The first supported vocabulary covers:
- Tempo, meter, bar count, and key/root, with documented defaults when omitted.
- Lead, bass, and drum role selection.
- Explicit basic note patterns such as eighth-note root riffs, sustained bass
roots, and drum hit placement/subdivision.
- Only articulations supported by the selected verified profile, including
palm mute where the target actually supports it.
An acceptance description, once corresponding mappings are verified:
> Generate 4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead guitar,
> sustained root-note bass, kick on beats 1 and 3, snare on beats 2 and 4, and
> closed hi-hat eighth notes.
Document the accepted grammar and representative paraphrases before writing
the parser. Explicit choices override documented defaults; contradictory or
unsupported instructions return diagnostics rather than being ignored.
Genre labels alone must not imply invented musical semantics.
This bounded interpretation is a review decision, not a claim to understand
arbitrary prose. If unrestricted natural-language interpretation is required,
resolve that design with the owner before implementation without adding an
external LLM service beyond the approved scope.
For repeatability, identical text, profiles, and options produce the same
composition. No randomization, training, or audio-derived data is required.
Return the interpreted settings and applied defaults so the client can inspect
what was actually generated.
## 6. MCP tool contracts
Keep the public surface to two tools. Publish JSON Schema input and output
contracts with explicit required fields, enum values, and
`additionalProperties: false` for fixed request objects.
### `list_instrument_profiles`
Purpose: expose exact target versions, verified mappings, and real writer
capabilities before generation.
Parameters:
| Name | Type | Required | Meaning |
| --- | --- | --- | --- |
| `role` | `"lead"`, `"bass"`, or `"drums"` | No | Filter profiles; omit for all |
Return `ProfileCatalogResult`:
- `instruments`: declared identities `{ id, vendor, productCode, displayName,
role, documentationUrl, availability }`, including targets with no mappings.
Availability is `mapping_unavailable` or `profile_available`; neither implies
native-writer or local-plugin acceptance.
- `profiles`: array of `{ id, instrumentId, role, productName, productVersion, mappingVersion,
playableRange, articulations, nativeFormats, nativeStatus }`.
- Each articulation identifies supported mechanisms (`keyswitch`, `velocity`,
`cc`, or a verified combination), constraints, and mapping provenance.
- `nativeStatus` is `verified`, `unverified`, or `unsupported`, not a
hard-coded success flag. Never expose guessed profile values as usable.
### `generate_project`
Parameters:
| Name | Type | Required | Meaning |
| --- | --- | --- | --- |
| `description` | Nonempty string | Yes | Supported musical text |
| `outputDirectory` | Absolute local filesystem path | Yes | Destination chosen by caller |
| `projectName` | Safe filename stem | Yes | Shared artifact filename prefix |
| `formats` | Nonempty unique array of `"agp"`, `"sdp"`, `"mid"` | No | Default: applicable native formats for selected roles plus MIDI |
| `profiles` | Object with optional `lead`, `bass`, `drums` profile IDs | No | Override verified defaults for roles present in the description |
| `fallbackToMidi` | Boolean | No | Default: true; explicit degraded output when a requested native writer cannot represent the composition |
`agp` applies only to selected lead/bass tracks; `sdp` only to a selected drum
track; `mid` includes all selected tracks. Reject an explicit request for a
format with no applicable selected role rather than returning nothing.
Profile IDs resolve their instrument and must match the corresponding roles.
Multiple guitars/basses do not create new role slots. If no unique verified
default exists, return an error identifying the required profile selection;
never choose an instrument by catalog position.
Return `GenerationResult`:
```text
status: "complete" | "fallback" | "failed"
interpretedComposition: { tempoBpm, meter, key, bars, roles, defaultsApplied }
artifacts: [{ format, roles, absolutePath, byteCount, profileIds }]
targets: [{
role, instrumentId, profileId, requestedFormat,
outcome: "written" | "fallback" | "failed",
artifactPaths, reasonCode?, message?
}]
warnings: [{ code, message, role?, requestedFormat? }]
errors: [{ code, message, field?, role? }]
timing: { ticksPerQuarterNote, leadInTicks }
```
Represent early parse failures with `interpretedComposition: null` and
`timing: null`; schemas must allow this only for failed results. Success outputs
have non-null values and existing, nonempty files.
Expected names are `<projectName>.lead.agp`, `<projectName>.bass.agp`,
`<projectName>.drums.sdp`, and `<projectName>.mid`, as applicable. The combined
MIDI file has named tracks and distinct channels; drums use MIDI channel 10
(DryWetMIDI zero-based channel 9), subject to the verified target mapping.
MCP `tools/call` wraps this object in `structuredContent` and also supplies
serialized JSON in a text `content` entry for client compatibility.
`isError` is false for complete or explicitly requested fallback results and
true for failed results. Each tool's `outputSchema` must match its emitted
structured content.
### Fallback and filesystem semantics
- Preflight requested native formats and articulation representability.
Native unavailability or unrepresentable native features may trigger MIDI
fallback only when `fallbackToMidi` is true.
- MIDI fallback must retain the complete selected arrangement and mapped
articulations, not just the part that failed. Reuse the same validated event
plan; produce one combined MIDI artifact, not duplicate copies.
- Native failure must be visible per target and in warnings, even when the
MIDI artifact was explicitly requested already.
- Fallback does not excuse an unknown MIDI mapping, invalid input, corrupt
serializer output, unexpected exception, cancellation, or I/O failure.
These are failures with diagnostics.
- With fallback disabled, an unavailable requested native output fails
preflight without publishing partial outputs.
- Validate `projectName` as a filename stem, not a path. Reject traversal,
reserved names, conflicting destinations, and existing final files.
Do not interpret user text as shell commands.
- Stage and validate every planned artifact before publication. Publish with
no-overwrite operations. Multi-file publication is not inherently atomic:
if a later move fails, remove only this request's published files, report
failure, and explicitly report any cleanup failure and remaining paths.
- Cancellation cleans up only request-owned temporary/output files.
Unexpected errors must not become successful fallback results.
## 7. MIDI and native format handling
### Standard MIDI
- Use Standard MIDI File type 1, 960 ticks per quarter note, a conductor track
containing tempo/time signature, and one named track per selected role.
- Convert rational musical positions to ticks using checked arithmetic.
Validate exact representability; do not accumulate floating-point drift.
- Respect MIDI pitch, velocity, channel, and CC ranges. Use explicit note-off
events; generated musical notes have positive duration and velocity.
- Give simultaneous events deterministic ordering: applicable previous
note-offs/resets, state-changing controls/keyswitches, then musical note-ons.
Target-specific exceptions must be evidence-backed and tested.
- Do not derive pitch numbers from ambiguous octave labels. Store absolute
MIDI numbers and document any user-facing octave naming convention.
- Ensure every track ends after its final note-off/control reset, with proper
End-of-Track events and no stuck keyswitch or musical notes.
- Read generated MIDI back with DryWetMIDI and validate semantic content.
Never implement a handwritten parallel MIDI encoder.
### `.agp`
- Establish the versioned container and fields using authorized evidence.
- Determine which musical fields and articulation mechanisms the format can
actually express. Preserve necessary structural/version metadata, not
unrelated user state.
- Serialize a new file or modify a permitted minimal template only when that
route is verified. Never distribute arbitrary vendor project assets.
- If the native format embeds MIDI, build/read that payload with DryWetMIDI.
If it stores native note records instead, serialize the native records from
the same validated composition/event plan; do not mislabel them as MIDI.
- Validate each selected Ample product separately. Round-trip or golden tests
are necessary but cannot replace opening generated files in the actual targets.
### `.sdp`
- First verify that SD3 supports `.sdp` for the required musical content and
identify its exact load/import workflow and relevant library/map settings.
- Implement only the validated structure and version, following the same
evidence, metadata, MIDI-payload, and template rules as the AGP writer.
- Do not substitute a MIDI file with an `.sdp` extension or substitute another
SD3 file type without owner approval.
- Confirm timing, drum voices/articulations, and velocity in SD3 after import;
record any target limitation instead of silently dropping information.
Both native writers implement a small common contract for capability checks
and staged output. Share composition and MIDI construction, not speculative
binary-format abstractions.
## 8. Articulation mapping
Embed versioned profile data with the published application. No new runtime
profile editor or user plugin system is needed.
A profile records:
- Stable ID, role, product/version, mapping version, provenance, and verification
status.
- Playable pitch range, channel allocation, and initial instrument state.
- Canonical articulations and text aliases, such as `palm mute` -> `palm_mute`.
- For each articulation, the verified ordered actions: keyswitch note and
velocity, switch advance/duration, velocity range/layer constraints,
controller number/value, latch/release/reset behavior, and native support.
- Drum voice/articulation notes and any verified CC-dependent state, such as
hi-hat behavior. Do not assume GM matches the installed SD3 configuration.
Example transformation, deliberately without invented vendor numbers:
```text
"palm-muted eighth-note lead"
-> canonical articulation "palm_mute"
-> selected Eclips profile lookup
-> verified keyswitch and/or CC actions
-> velocity chosen within the requested/verified layer
-> musical note at its intended position
-> required release/reset actions
```
Tests may use clearly labeled synthetic profiles with concrete values.
Production mappings may contain only verified values. A synthetic profile
must never be returned as a supported Eclips, Ray, or SD3 profile.
Some switches must precede the first musical note. Compute one shared
nonnegative lead-in offset for all tracks from the largest required advance;
shift the whole arrangement consistently and return `leadInTicks`. Do not
clamp negative switch times to zero or shift only one instrument. If a native
format cannot preserve the required timing, report the limitation and apply
the explicit fallback policy.
Resolve articulation state transitions deterministically. Emit latched changes
when needed; preserve momentary switch semantics; restore state only where
the verified profile requires it. A track-wide keyswitch/CC state cannot express
conflicting simultaneous articulations: reject or use a verified alternative,
never pretend per-note independence.
Validate unsupported articulations, velocity-layer conflicts, keyswitch/playable
note collisions, and out-of-range notes before writing files. Velocity layering
controls the receiving plugin's samples; the server does not synthesize audio.
## 9. Test strategy and acceptance
Use xUnit. All tests are deterministic, isolate temporary output directories,
and clean up only paths they own. Prefer semantic assertions over fragile
whole-file binary comparisons where native metadata is variable.
### Unit tests
- Description grammar, paraphrases, defaults, contradictory/unsupported text,
role selection, and the full documented example.
- Musical validation, rational beat-to-tick conversion, bar boundaries,
invalid ranges, representability, and checked overflow.
- Every supported production articulation rule, plus synthetic tests for
keyswitch, velocity-only, CC-only, combined mechanisms, state transitions,
simultaneous conflicts, and shared lead-in.
- DryWetMIDI-read assertions for file type, resolution, tempo, time signature,
note pitch/start/end/velocity/channel, CC values, event ordering, track names,
matching note-offs, and end positions. For a four-bar 4/4 test at 960 PPQ,
the musical extent must be exactly 15,360 ticks plus the stated lead-in.
- Native structural/golden fixtures, version checks, representability failures,
malformed inputs, and no renamed-MIDI shortcuts.
- MCP envelope validation, request IDs, notification behavior, protocol state,
advertised tool schemas, and schema/result agreement.
- Filename validation, collisions, explicit fallback, disabled fallback,
publication/cleanup failures, and cancellation.
### Integration tests
- Launch the actual console process; perform initialization, initialized
notification, profile listing, generation, ping, and clean EOF exit.
- Verify each stdout line is a valid protocol message; logs go only to stderr.
Test malformed input, unknown methods/tools, invalid parameters, cancellation,
and multiple requests without response interleaving.
- Generate the documented lead/bass/drum example through MCP, verify returned
files exist and reopen them; check that target outcomes match actual outputs.
- Exercise all requested formats, selected-role combinations, native fallback,
a request already containing MIDI, and failure with fallback disabled.
- Ensure failed/cancelled operations do not leave undisclosed partial files.
- Run the same handshake/generation checks against the published executable
using a working directory unrelated to the repository.
### Native and Cubase acceptance
Record product versions, mapping settings, exact reproduction steps, results,
and test-file identifiers in the acceptance document:
1. Load generated lead and bass AGP files in the corresponding Ample products.
2. Load the generated SDP file in the verified SD3 workflow.
3. Confirm note counts, positions, lengths, tempo/meter where represented,
velocity layers, and articulation switching.
4. Import the MIDI arrangement into Cubase; check track separation, timing,
tempo/meter import settings, and correct instrument/channel routing.
5. Confirm the intended articulation behavior with the installed plugins.
Application checks are explicit owner/worker-assisted acceptance, not silently
skipped CI tests. If the licensed applications are unavailable, automated tests
may pass, but native compatibility remains pending and must not be reported as
verified.
## 10. Build and local publication
All production projects target `net10.0`, enable nullable reference types and
implicit usings, and treat compiler warnings as errors. Keep package versions
centralized, pin DryWetMIDI 8.0.3, and commit dependency lock files once generated.
The server uses `Microsoft.NET.Sdk` and `OutputType=Exe`, not a web SDK.
Keep runtime-specific settings in the publish profile:
```xml
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>true</PublishSingleFile>
<PublishTrimmed>false</PublishTrimmed>
<PublishAot>false</PublishAot>
<UseAppHost>true</UseAppHost>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
</PropertyGroup>
</Project>
```
`win-x64` is the initial reviewable deployment target for this Windows workspace,
not a claim that one executable runs on every architecture. Other RIDs require
separate publication and validation if later requested. Do not add a platform
matrix beyond the approved deployment target.
Disable trimming/AOT initially to avoid unverified reflection/serialization or
library incompatibilities. DryWetMIDI device/playback APIs are not used. Verify
the pinned package's deployment behavior instead of assuming a dependency-free
publish. Any native extraction requirement must be documented and smoke-tested.
Expected commands after implementation:
```powershell
dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx
dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore
dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build
dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 -o .\artifacts\publish\win-x64
```
Document an MCP client configuration with the absolute executable command and
stdio transport; do not launch via HTTP or assume the client's working
directory. Embedded profiles must load independently of the current directory.
The executable must launch on a matching Windows machine without a separately
installed .NET runtime; verify this on a runtime-free test environment or record
that acceptance as pending. Merely running it on the SDK development machine
does not prove runtime independence.
## 11. Phased worker sequence
This sequence describes future prompts. Do not create `step_1.md` until this
plan has been reviewed. Each step includes implementation, directly related
documentation, tests, and a worker report. Do not launch all steps together.
### Step 1: Bootstrap the .NET 10 solution and compatibility inventory
- Create the solution, three production projects, two test projects, central
build/package settings, SDK pin, ignore rules, and minimal README.
- Add DryWetMIDI 8.0.3 and the pinned test dependencies; create only minimal
executable behavior, not a placeholder generation success response.
- Create the compatibility inventory and record required native/profile
evidence as verified, missing, or blocked, without inventing values.
- Tests: solution restore/build, xUnit discovery and one meaningful smoke
assertion, and process startup/EOF with no stdout pollution.
- Exit: reproducible .NET 10 build/test and an explicit evidence inventory.
Missing native evidence remains visible as a future gate, not a scaffold
failure or a reason to fabricate fixtures.
### Step 2: Implement stdio JSON-RPC and MCP lifecycle
- Implement framing, envelope validation, dispatch, initialization/version
negotiation, ping, notification rules, stderr diagnostics, and clean exit.
- Establish the tool registry and schema infrastructure; do not advertise an
unimplemented generation tool.
- Tests: protocol units and real subprocess handshake, invalid-message
handling, ID preservation, notification silence, serialized writes, EOF.
- Exit: a protocol-correct stdio server, not just a JSON-reading console loop.
### Step 3: Implement the composition model and text planner
- Define request/result models, rational musical timing, composition validation,
documented text grammar/defaults, and deterministic basic patterns.
- Keep parser behavior within the reviewed natural-language contract.
- Tests: documented example, paraphrases, defaults, conflicts, unsupported
requests, timing/range failures, and a planner-to-composition integration test.
- Exit: validated lead/bass/drum compositions from supported descriptions,
with no file-format assumptions.
### Step 4: Implement verified instrument profiles and articulation planning
- Implement profile loading/validation and switch/velocity/CC event planning.
- Add the six requested Ample instrument definitions and SD3 to a data-driven
catalog, bind versioned profiles by instrument ID, and keep mapping
availability distinct from target identity. No per-product subclasses.
- Add actual selected-instrument mappings only after their evidence gates pass.
- Tests: each supported mapping and all three mechanisms, combined actions,
state changes, layer boundaries, collision/conflict rejection, and shared
lead-in across a multi-track arrangement.
- Exit: tested event plans and evidence-backed production mappings.
If evidence is missing, synthetic tests do not satisfy the production exit
gate. Accepted generic infrastructure may feed Step 5 under the sequencing
decision above; no real instrument support is implied.
### Step 5: Implement complete Standard MIDI generation
- Build the shared DryWetMIDI event pipeline and type-1 writer, including
conductor metadata, role tracks, channels, controls, and output staging.
- Tests: exact read-back assertions, long/repeated patterns without timing
drift, switch timing, note-off ordering, invalid input, and multi-role file
generation in isolated temporary directories.
- Exit: valid articulated MIDI covering the complete selected arrangement,
demonstrated with clearly synthetic profiles through the actual file writer.
Format-writer acceptance does not establish production mapping compatibility.
Do not populate guessed profiles or expose production generation tools to
satisfy this milestone.
### Step 6: Implement and verify Ample AGP generation
- Require verified schema/template rights and fixtures before writer work.
- Implement the smallest evidence-backed writer route for the selected Ample products,
including representability checks and version handling.
- Tests: native fixture/structure tests, generated-file semantic checks,
unsupported data failures, and integration with the shared composition plan.
- Exit: generated AGP files reopen correctly in the selected target products, with
acceptance evidence. Structural tests alone do not close this step.
### Step 7: Implement and verify Superior Drummer SDP generation
- Require confirmation of `.sdp` semantics, schema, and the installed drum map.
- Implement the supported native writer route without inventing its structure.
- Tests: fixtures/structure, drum mapping, timing/velocity/articulation content,
unsupported features, and integration with the composition/event plan.
- Exit: a generated SDP file reopens correctly in SD3 with recorded acceptance.
An extension mismatch is a scope blocker requiring owner resolution.
### Step 8: Wire production MCP tools and explicit MIDI fallback
- Expose the final two tool contracts and connect the full generation service.
- Complete preflight, per-target results, publication rollback/cleanup,
cancellation, profile discovery, and explicit fallback policies.
- Tests: real stdio calls covering all roles/formats, complete/fallback/failed
output shapes, no-overwrite behavior, native unavailability, I/O errors,
cleanup failures, and cancellation.
- Exit: working text-to-files MCP workflow with truthful, schema-valid results.
The MIDI/fallback slice can be accepted while native codecs remain
unavailable; that does not complete Steps 6/7 or the full product scope.
### Step 9: Publish and complete Cubase/plugin acceptance
- Add the publish profile, local MCP configuration instructions, and release
acceptance procedures; embed/load profiles without working-directory
assumptions.
- Tests: Release build/test, self-contained publish, published-process
handshake/generation from another directory, runtime-free deployment check,
and the documented Cubase/Ample/SD3 acceptance matrix.
- Exit: reproducible local deployment and all full-scope completion criteria.
Record unavailable manual/environment checks as pending, never as passes.
Dependencies: 2 and 3 require the scaffold in 1; Step 4 infrastructure requires
3, while its production acceptance also requires verified mapping evidence.
Step 5 requires 3 and accepted Step 4 infrastructure, not completed production
mapping admission. Steps 6 and 7 require 5 plus their applicable production
profiles and native evidence. Step 8's MIDI/fallback slice requires 2, 5,
admitted selected profiles and truthful native-capability preflight; native
success paths require 6/7. Step 9 may publish the usable supported slice,
while full-scope application acceptance still requires the missing native
and product evidence. The orchestration workflow still issues and reviews
only one worker step at a time. Do not bypass production gates; document any
sequencing decision before issuing the affected prompt.
## 12. Worker prompt and report protocol
For each approved step, write only that step's detailed worker prompt to
`prompts\step_N.md`. Include:
1. Objective, scope boundaries, prerequisites, and exact plan exit criteria.
2. Explicit files to create/modify, expanded from the modules listed here.
3. Implementation details, public contracts, verified evidence, and forbidden
assumptions. Instruct the worker to read existing code and preserve others'
work before editing.
4. Required unit and integration test cases, exact validation commands, and
objective expected outputs. Use the smallest covering test selection during
development and appropriate build/integration checks at completion.
5. Documentation changes and any required owner-assisted acceptance.
6. This exact instruction:
> When complete, write your end-of-step report to ./prompts/report_N.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step
Replace `N` with the actual step number in the issued prompt. Also require
changed files, commands/exit codes, test counts, unrun/skipped checks and reasons,
compatibility evidence, and explicit blockers. Reports must distinguish
automated results from application-level/manual acceptance. Put the end-of-step
report entirely inside one plain triple-backtick fence, without outside prose.
After issuing a prompt, wait for the worker's report. Do not implement the
worker's step concurrently or issue a later step in advance.
### Orchestrator review gate
Read `prompts\report_N.md` before deciding anything about progression:
- Compare actual changes and tests with the step objective, contracts, and exit
criteria; a worker's "ready" statement is not sufficient.
- Check actual test evidence and perform focused code/test verification where
needed. Do not infer compatibility from compilation or fixture comparisons.
- Check for scope expansion, placeholder native formats, guessed mappings,
ignored requirements, silent fallbacks, or misleading result statuses.
- Treat failing tests, missing required tests, unrun acceptance, unresolved
blockers, and contradictory reports as not ready.
If accepted, record the review decision and then create only the next prompt.
If not accepted, create `prompts\step_N_fix.md` with precise findings, bounded
corrections, regression tests, and a requirement to update the corresponding
report with correction evidence. Review that report again before progressing.
If another correction is needed, revise the same fix prompt with a clearly
identified iteration rather than skipping ahead.
For missing proprietary evidence or product incompatibility, request an owner
decision and adjust the plan only with approval. Do not ask the worker to
"make the tests pass" by weakening assertions, inventing a native schema, or
reclassifying a blocked requirement as complete.
## 13. Review checklist before execution
- Approve the three-project architecture, two-tool contract, and sequential
worker/report gates.
- Confirm the deterministic supported-language approach and initial vocabulary.
- Confirm the initial `win-x64` local self-contained deployment target.
- Supply or arrange authorized native-format fixtures, exact product versions,
articulation maps, and access for application-level acceptance.
- Resolve any `.sdp` extension/workflow mismatch before native implementation.
The owner has approved execution. Create and review worker prompts sequentially,
starting with `prompts\step_1.md`; approval does not waive native evidence gates.
## 14. Primary references consulted
- [MCP 2025-11-25 stdio transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports)
- [MCP lifecycle and version negotiation](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle)
- [MCP tools and schemas](https://modelcontextprotocol.io/specification/2025-11-25/server/tools)
- [Melanchall.DryWetMidi 8.0.3 on NuGet](https://www.nuget.org/packages/Melanchall.DryWetMidi/8.0.3)
- [DryWetMIDI documentation](https://melanchall.github.io/drywetmidi/)
- [.NET single-file and self-contained publication](https://learn.microsoft.com/en-us/dotnet/core/deploying/single-file/overview)
- [Ample Sound manual entry point](https://www.amplesound.net/en/manual.asp)
(no usable native schema obtained during planning)
- [Superior Drummer 3 manual entry point](https://www.toontrack.com/manual/superior-drummer-3/)
(login required during planning)