Skip to main content

RFC 0001 — Version 0.3

Status: Draft
Created: 2025-12-12
Authors: MRS Working Group
License: CC BY 4.0

Abstract

This document specifies MRS (Music Representation Syntax), a format for encoding musical scores optimized for AI-assisted composition workflows. MRS uses a single canonical syntax (MRS-S) for complete, archival-quality score encoding, combined with a Working Set Envelope protocol that enables machine agents to operate on bounded fragments of scores with appropriate surrounding context. The key insight is that agents need context management—the ability to focus on specific regions while understanding their musical surroundings. The Working Set Envelope extracts a self-contained MRS-S fragment with explicit boundaries, graduated context rings providing surrounding material at reduced detail, and access to a structural synopsis of the full score. Agents receive valid MRS-S, return valid MRS-S, and the orchestrator performs replacement with full validation. Every measure carries a stable UUID identifier; measure numbers are display properties for human navigation. All internal references—scopes, spans, overlays—use UUIDs, ensuring structural stability through insertions, deletions, and reorderings. The specification prioritizes semantic completeness, deterministic parsing, structural stability, and lossless extract-replace round-trips. MRS serves as a universal interchange format and as the native representation for AI-assisted and agent-driven workflows over full scores at professional scale.

Table of Contents

  1. Introduction
  2. Design Principles
  3. Architecture Overview
  4. MRS-S: The Canonical Format
  5. Working Set Envelope
  6. Synopsis Format
  7. Analytical Overlays
  8. Data Model
  9. Extract-Replace Protocol
  10. Agent Operations
  11. Query Resolution
  12. Validation Rules
  13. Extension Mechanisms
  14. MIME Types and File Extensions
  15. Security Considerations
  16. Appendix A: Complete Grammar
  17. Appendix B: Quick Reference
  18. Appendix C: Comparison with Existing Formats
  19. Appendix D: Glossary

1. Introduction

1.1 Motivation

Existing music notation formats fall into two categories: Interchange formats (MusicXML, MEI) prioritize completeness but are verbose, difficult to parse, and hostile to both human editing and machine learning workflows. A simple four-bar melody may require hundreds of lines of XML. Compact formats (ABC notation, LilyPond) optimize for human entry but sacrifice semantic precision, lack formal grammars, and cannot represent the full complexity of professional scores. Neither category addresses two fundamental challenges: Scale: A full orchestral score contains too much information for any single context window, human or machine. Editing measure 847 should not require loading measures 1-846 into memory. Context: Musical decisions require understanding surrounding material. An agent writing a countermelody needs to know what it’s responding to—not just the target measures, but phrase boundaries, harmonic rhythm, and thematic relationships. MRS solves this through a single canonical format combined with a context-aware extraction protocol:
  • MRS-S provides complete, unambiguous encoding of any score with stable UUID identifiers
  • Working Set Envelopes extract bounded MRS-S fragments with graduated context rings
  • Synopsis provides compressed structural views for global awareness
  • Agents receive and return valid MRS-S—no second syntax, no parsing ambiguity
  • A formal extract-replace protocol guarantees lossless round-trips

1.2 Goals

  1. Semantic completeness: Encode everything a professional engraver needs
  2. Deterministic parsing: One input → one parse tree, always
  3. Structural stability: UUIDs survive insertions, deletions, and reorderings
  4. Context-aware operations: Agents work with appropriate surrounding context
  5. Machine-friendly: Predictable patterns for reliable LLM/agent generation
  6. Human-auditable: People can review and debug outputs
  7. Diff-friendly: Line-based changes produce meaningful diffs
  8. Renderer-agnostic: Describe what, not how to draw

1.3 Non-Goals

  1. Encoding visual layout (page breaks, staff spacing, collision avoidance)
  2. Providing a programming language (no loops, conditionals, macros)
  3. Defining audio synthesis or playback behavior
  4. Replacing domain-specific formats (MIDI, audio, engraving source)

1.4 Terminology

The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119.
TermDefinition
ScoreA complete musical work in MRS format
PartA single instrument or voice throughout a score
StaffA visual grouping of five lines; parts may have multiple staves
VoiceAn independent melodic/rhythmic stream within a staff
MeasureA metrical unit bounded by barlines, identified by UUID
EventAn atomic musical occurrence (note, rest, chord), identified by UUID
SpanA relation connecting multiple events (slur, beam, hairpin)
SynopsisA compressed structural view of the full score
Working SetA subset of a score extracted for editing with context
OverlayAnalytical metadata attached to score regions

2. Design Principles

2.1 Explicit Over Implicit

Every musical element has an explicit representation. Position in the measure is stated, not inferred from accumulated durations. Voice assignment is declared, not guessed from stem direction. Rationale: Implicit state creates cascading errors. If an LLM miscounts one duration, all subsequent events are misaligned. Explicit positions are independently verifiable.

2.2 Stable Identity Over Positional Reference

Measures and events carry stable UUIDv7 identifiers. Measure numbers are display properties for human navigation, not structural identity. All internal references use UUIDs. Rationale: Positional references break when content is inserted or deleted. UUID references survive structural changes, enabling fluid compositional workflows where form evolves during the creative process.

2.3 Semantic Over Visual

MRS encodes musical meaning, not visual appearance. A crescendo is marked with start/end points and type, not with specific hairpin coordinates. Rationale: Visual rendering is context-dependent (page size, staff spacing, font). Semantic encoding remains valid across all rendering contexts.

2.4 Predictable Over Clever

The format uses regular patterns even when more compact alternatives exist. Every note uses the same syntax regardless of context. Rationale: LLMs generate more reliably when patterns are consistent. A 10% size reduction is not worth a 50% increase in generation errors.

2.5 Context Over Isolation

Working Sets include graduated context rings—surrounding material at reduced detail levels. Agents operate on focused regions while understanding their musical surroundings. Rationale: Musical decisions are contextual. A countermelody responds to what precedes and follows it. Phrase boundaries, harmonic rhythm, and thematic relationships inform compositional choices.

2.6 One Format, Scoped Extraction

MRS uses a single syntax (MRS-S) for all operations. Working sets are not a different format—they are bounded MRS-S fragments wrapped in an extraction envelope with context. Rationale: Maintaining two syntaxes creates parsing complexity, abbreviation ambiguity, and merge conflicts. A single syntax means agents receive what they return: valid MRS-S.

3. Architecture Overview

MRS enables context-aware agent operations on full-scope scores: tools and machine agents operate on focused regions with appropriate surrounding context, while the orchestrator maintains the full score and handles structural coordination.

3.1 Core Components

┌─────────────────────────────────────────────────────────────────────┐
│                         MRS ECOSYSTEM                                │
│                                                                      │
│   ┌────────────────────────────────────────────────────────────┐    │
│   │                        MRS-S                                │    │
│   │                The Single Canonical Format                  │    │
│   │                                                             │    │
│   │ • Complete, hierarchical, self-documenting                  │    │
│   │ • Measures and events indexed by stable UUIDs               │    │
│   │ • Spans as typed edges between event UUIDs                  │    │
│   │ • Used for storage, interchange, AND agent I/O              │    │
│   └────────────────────────────────────────────────────────────┘    │
│                              │                                       │
│              ┌───────────────┼───────────────┐                      │
│              ▼               ▼               ▼                      │
│   ┌──────────────┐  ┌──────────────┐  ┌──────────────┐             │
│   │   SYNOPSIS   │  │ WORKING SET  │  │   OVERLAYS   │             │
│   │              │  │   ENVELOPE   │  │              │             │
│   │ • Structural │  │              │  │ • Harmonic   │             │
│   │   overview   │  │ • Scoped     │  │   analysis   │             │
│   │ • Read-only  │  │   content    │  │ • Motivic    │             │
│   │ • Derived    │  │ • Context    │  │   tracking   │             │
│   │              │  │   rings      │  │ • Typed,     │             │
│   │              │  │ • Scope      │  │   optional   │             │
│   │              │  │   negotiation│  │              │             │
│   └──────────────┘  └──────────────┘  └──────────────┘             │
└─────────────────────────────────────────────────────────────────────┘

3.2 The Context Problem

A full orchestral score is fundamentally too large for efficient manipulation:
Score TypePartsMeasuresEventsMRS-S SizeTokens
Lead sheet132~200~8 KB~2K
Piano sonata2300~5,000~150 KB~40K
String quartet4400~8,000~250 KB~65K
Choral + piano6100~3,000~100 KB~25K
Chamber orchestra25500~50,000~1.5 MB~400K
Full orchestra901000~200,000~6 MB~1.5M
No LLM context window can hold a full orchestral score. More importantly, it shouldn’t have to. But editing the clarinet part in measures 45-52 requires more than just those measures—it requires understanding:
  • What melodic material the clarinet responds to
  • The harmonic context (what chords are sounding)
  • Where phrase boundaries fall
  • What comes before and after the edit region
The Solution: Context-Aware Extraction The Working Set Envelope extracts:
  1. Content: Full-detail MRS-S for the edit region (writable)
  2. Context rings: Surrounding material at reduced detail (read-only)
  3. Synopsis access: Structural overview of the entire score (read-only)
Full Score (MRS-S)                    Working Set Envelope
┌─────────────────────────┐           ┌─────────────────────────────────┐
│ 90 parts × 1000 measures│  extract  │ (working-set                    │
│ ~200,000 events         │ ────────► │   :scope (:measures #uuid "..."  │
│ ~6 MB                   │           │                    #uuid "...")  │
│                         │           │          (:parts [clarinet-1])  │
└─────────────────────────┘           │                                 │
                                      │   :content (measures ...)       │
                                      │   :context-near (measures ...)  │
                                      │   :context-far (measures ...)   │
                                      │   :synopsis-ref "sha256:...")   │
                                      └─────────────────────────────────┘

3.3 Stable Identifiers

Every Measure, Event, and Span in an MRS-S score MUST carry a stable identifier in the form of a UUIDv7 (monotonic + random) under the key :id. Measure identifiers:
(measure 
  :id #uuid "018c3f40-1234-7890-abcd-ef1234567890"
  :number 45
  :beat-start 487+1/4
  ...)
  • :id — Stable identity, survives insertions/deletions, used for all internal references
  • :number — Display property for human navigation, can change when bars are inserted/deleted
Event identifiers:
(: 0 C5.q :dyn p :id #uuid "018c3f2a-1234-7890-abcd-ef1234567890" :at 487+1/4)
Span identifiers:
(slur 
  :id #uuid "018c3f2c-9abc-def0-1234-567890abcdef"
  :from #uuid "018c3f2a-1234-7890-abcd-ef1234567890"
  :to #uuid "018c3f2b-5678-9012-cdef-0123456789ab"
  :style legato)
All references (Working Set scopes, span endpoints, overlay regions) MUST use UUID references. Measure numbers appear only in :display-hint fields for human readability; they are never used for structural reference. Once assigned, an :id is immutable for the lifetime of the score.

3.4 Dual Positioning Model

Every part MUST contain a parallel absolute time spine expressed in two units:
  • Beats – exact rational number of quarter-notes since the start of the part (using the rational syntax in this document, e.g., 487+1/2).
  • Seconds – floating-point seconds since start (optional, but REQUIRED if any tempo automation exists).
Every event and span endpoint MUST carry both:
  • Structural position within measure (beat index) for human readability
  • Absolute position :at (beats) for meter-agnostic reasoning
Example with dual positioning:
(measure 
  :id #uuid "018c3f40-1234-7890-abcd-ef1234567890"
  :number 12
  :beat-start 487+1/4
  :sec-start 121.5
  
  (violin-1
    (v1
      (: 0 C5.q 
        :at 487+1/4
        :id #uuid "018c3f2a-...")
      (: 1 D5.q 
        :at 487+1/2
        :id #uuid "018c3f2b-..."))))
This makes the format safe for metric modulations, polymeter, pickup bars, and agents that reason in continuous time rather than measure grids.

3.5 Sequential Composition Model

Composition is fundamentally sequential at the structural level. Form, phrase lengths, and section boundaries are discovered through the compositional process. MRS supports:
  • Sequential agent operations with full structural flexibility
  • Insertion and deletion as first-class operations
  • UUID stability ensuring references survive structural changes
  • Structural checkpoints when appropriate (optional)
Scores MAY declare structural stability:
(checkpoint :id "form-locked"
  :structure-stable true
  :measures-finalized [#uuid "018c3f40-..." #uuid "018c3f48-..."])
This signals that measure boundaries in the specified range are stable, enabling certain optimizations. It is not required.

4. MRS-S: The Canonical Format

4.1 Overview

MRS-S is an S-expression-based format optimized for:
  • Complete semantic fidelity
  • Clear hierarchical structure
  • Self-documenting readability
  • Straightforward parsing
  • Stable identity via UUIDs

4.2 Document Structure

(mrs-s <version>
  (meta <metadata>)
  (parts <part-definitions>)
  (measures <measure-content>)      ; OR (movements <movement-content>)
  (spans <span-definitions>)
  (overlays <overlay-content>)      ; OPTIONAL (analytical metadata)
  (alternatives <alt-content>)      ; OPTIONAL (ossia, variants, editorials)
  (layout <layout-hints>))          ; OPTIONAL
All top-level sections except overlays, alternatives, and layout are REQUIRED. Sections MUST appear in the order shown.

4.3 Version Declaration

(mrs-s 1.0
  ...)
The version number follows semantic versioning (MAJOR.MINOR). Parsers MUST reject documents with unsupported major versions and SHOULD warn on unknown minor versions.

4.3.1 Version Domains

This RFC uses three distinct version identifiers:
  1. RFC version (e.g., “RFC 0001 — Version 0.3”) — the editorial version of this document.
  2. MRS-S format version — the value in (mrs-s <version> ...) that governs parsing/validation of score documents.
  3. Working Set Envelope protocol version — the :version field inside (working-set ...) and (working-set-response ...).
Implementations MUST treat these as separate version domains.

4.4 Metadata Section

(meta
  :title "Symphony No. 5 in C Minor"
  :subtitle "Fate Knocking at the Door"
  :composers ["Ludwig van Beethoven"]
  :arrangers []
  :lyricists []
  :copyright "Public Domain"
  :created "1808"
  :modified "2025-12-12T10:30:00Z"
  :source "Breitkopf & Härtel, 1862"
  :language "de"
  :tags ["symphony" "classical" "orchestral"]
  
  ; Score-wide defaults
  :key C :mode minor
  :time 2/4
  :tempo 108
  :tempo-text "Allegro con brio")

4.4.1 Required Metadata Fields

FieldTypeDescription
:titlestringPrimary title of the work

4.4.2 Optional Metadata Fields

FieldTypeDescription
:subtitlestringSecondary title
:composers[string]List of composer names
:arrangers[string]List of arranger names
:lyricists[string]List of lyricist names
:copyrightstringCopyright notice
:createdstringOriginal creation date
:modifiedISO 8601Last modification timestamp
:sourcestringSource edition reference
:languageISO 639-1Primary language for lyrics
:tags[string]Classification tags
:keypitch-classDefault key (A-G with optional #/b)
:modekeywordmajor, minor, dorian, etc.
:timefractionDefault time signature
:tempointegerDefault tempo in BPM
:tempo-textstringTempo marking text

4.5 Parts Section

(parts
  (part flute-1
    :name "Flute 1"
    :abbr "Fl. 1"
    :staves [treble]
    :section woodwinds
    :midi-program 73
    :transposition none
    :range [C4 D7])
  
  (part clarinet-bb
    :name "Clarinet in B♭"
    :abbr "Cl."
    :staves [treble]
    :section woodwinds
    :midi-program 71
    :transposition (down M2)
    :range [D3 Bb6])
  
  (part piano
    :name "Piano"
    :abbr "Pno."
    :staves [treble bass]
    :section keyboards
    :midi-program 0
    :transposition none
    :range [A0 C8]
    :staff-connect brace)
    
  (part soprano
    :name "Soprano"
    :abbr "S"
    :staves [treble]
    :section voices
    :has-lyrics true
    :range [C4 C6]))

4.5.1 Part Identifier

The part identifier (e.g., flute-1, clarinet-bb) MUST be unique within the score and MUST match the regex [a-z][a-z0-9-]*.

4.5.2 Part Attributes

AttributeRequiredTypeDescription
:nameYESstringFull display name
:abbrYESstringAbbreviated name for systems
:stavesYES[clef]List of staff clefs
:sectionNOkeywordInstrument family grouping
:midi-programNO0-127General MIDI program number
:transpositionNOintervalTransposition from written to sounding
:rangeNO[pitch pitch]Playable range (written pitch)
:has-lyricsNObooleanWhether part carries lyrics
:staff-connectNOkeywordbrace, bracket, line, none

4.5.3 Clef Values

treble      ; G clef, line 2
bass        ; F clef, line 4  
alto        ; C clef, line 3
tenor       ; C clef, line 4
treble-8va  ; G clef, octave up
treble-8vb  ; G clef, octave down
bass-8vb    ; F clef, octave down
percussion  ; Neutral clef
tab-6       ; 6-string tablature
tab-4       ; 4-string tablature

4.5.4 Section Values

woodwinds brass strings percussion
keyboards voices choir other

4.5.5 Transposition Specification

none                    ; Concert pitch (no transposition)
(up <interval>)         ; Sounds higher than written
(down <interval>)       ; Sounds lower than written

; Interval format: quality + number
; Quality: P (perfect), M (major), m (minor), A (augmented), d (diminished)
; Number: 1-15

; Examples:
(down M2)     ; Bb clarinet: written C sounds Bb
(up P5)       ; Horn in F (old notation): written C sounds G
(down m3)     ; A clarinet: written C sounds A
(down P8)     ; Double bass: sounds octave lower

4.6 Measures Section

(measures
  (measure 
    :id #uuid "018c3f40-0001-7890-abcd-ef1234567890"
    :number 1
    :beat-start 0
    :sec-start 0.0
    :time 2/4
    :key C :mode minor
    :tempo 108
    :tempo-text "Allegro con brio"
    :rehearsal "A"
    :barline-left none
    :barline-right single
    
    ; Part content
    (flute-1 ...)
    (clarinet-bb ...)
    (piano ...))
  
  (measure
    :id #uuid "018c3f40-0002-7890-abcd-ef1234567890"
    :number 2
    :beat-start 2
    ; Inherits time, key, tempo from measure 1
    (flute-1 ...)
    ...))

4.6.1 Measure Attributes

AttributeRequiredTypeDescription
:idYESUUIDv7Stable identifier for all references
:numberYESpositive intDisplay number (1-indexed)
:beat-startYESrationalAbsolute beat position since part start
:sec-startCONDITIONALfloatAbsolute seconds (REQUIRED if tempo automation)
:timeNOfractionTime signature change
:keyNOpitch-classKey signature change
:modeNOkeywordMode specification
:tempoNOintegerTempo change in BPM
:tempo-textNOstringTempo marking text
:rehearsalNOstringRehearsal mark
:barline-leftNObarline-typeLeft barline style
:barline-rightNObarline-typeRight barline style
:pickupNOdurationPickup/anacrusis duration

4.6.2 Barline Types

none single double final
repeat-start repeat-end repeat-both
dashed tick short

4.6.3 Attribute Inheritance

Measure attributes inherit from previous measures unless overridden:
  • :time — persists until changed
  • :key, :mode — persist until changed
  • :tempo, :tempo-text — persist until changed
  • :rehearsal — does NOT inherit (single-measure)
  • :barline-* — do NOT inherit (per-measure)

4.7 Part Content Within Measures

(measure 
  :id #uuid "018c3f40-002d-7890-abcd-ef1234567890"
  :number 45
  :beat-start 487+1/4
  
  (violin-1
    :clef treble
    :staff 1
    
    ; Voice 1 (primary)
    (v1
      (: 0 G5.q :dyn f :id #uuid "018c3f2a-..." :at 487+1/4)
      (: 1 A5.e :id #uuid "018c3f2b-..." :at 488+1/4)
      (: 1.5 B5.e :id #uuid "018c3f2c-..." :at 488+3/4)
      (: 2 C6.h :id #uuid "018c3f2d-..." :at 489+1/4))
    
    ; Voice 2 (secondary, if polyphonic)
    (v2
      (: 0 D5.h :id #uuid "018c3f2e-..." :at 487+1/4)
      (: 2 E5.h :id #uuid "018c3f2f-..." :at 489+1/4)))
  
  ; Piano with multiple staves
  (piano
    (:rh
      (: 0 [C4 E4 G4].q :id #uuid "018c3f30-..." :at 487+1/4)
      (: 1 [C4 E4 G4].q :id #uuid "018c3f31-..." :at 488+1/4)
      (: 2 [C4 E4 G4].h :id #uuid "018c3f32-..." :at 489+1/4))
    (:lh
      (: 0 C3.q :id #uuid "018c3f33-..." :at 487+1/4)
      (: 1 G2.q :id #uuid "018c3f34-..." :at 488+1/4)
      (: 2 C3.h :id #uuid "018c3f35-..." :at 489+1/4))))

4.7.1 Voice Naming

For single-staff parts:
  • v1 through v4 for independent voices
  • Voice v1 is the primary voice; higher numbers are secondary
For multi-staff parts (piano, organ, harp):
  • :rh / :lh for right/left hand
  • Or :staff1 / :staff2 for numbered staves
  • Each staff may contain multiple voices: (:rh (v1 ...) (v2 ...))
Layers (Same-Rhythm Sub-Structure)
Within a voice, layers MAY be used to represent same-rhythm content:
(v1
  (layer 1
    (: 0 C4.q :id #uuid "..." :at 0) (: 1 D4.q :id #uuid "..." :at 1))
  (layer 2
    (: 0 E4.q :id #uuid "..." :at 0) (: 1 F4.q :id #uuid "..." :at 1)))

4.8 Event Syntax

4.8.1 The Beat-Position Event

(: <beat> <pitch-expr> <properties>*)
ComponentDescription
:Event marker (always present)
<beat>Beat position within measure (0-indexed, exact rational)
<pitch-expr>Pitch with duration, chord, or rest
<properties>Zero or more :keyword value pairs
Required Properties:
  • :id — Stable UUIDv7 identifier (REQUIRED)
  • :at — Absolute beat position as rational number (REQUIRED)
Example:
(: 0 C5.q 
  :id #uuid "018c3f2a-1234-7890-abcd-ef1234567890"
  :at 487+1/4
  :dyn p)

4.8.2 Beat Position

Beat positions are zero-indexed exact rationals relative to the measure start. They MUST be representable without approximation. Implementations MUST treat these values as exact numbers (no floating point tolerance).
4/4 time:
  Beat 0    = Downbeat (beat 1 in musician terms)
  Beat 1    = Beat 2
  Beat 2    = Beat 3
  Beat 3    = Beat 4
  Beat 0+1/2  = "And" of beat 1
  Beat 1+3/4 = Fourth sixteenth of beat 2

6/8 time (compound):
  Beat 0    = Downbeat
  Beat 1    = Dotted quarter 2
  Beat 0+1/3 = First eighth subdivision
Canonical numeric form:
  • Integers MAY be written as 0, 1, 2, …
  • Non-integers SHOULD be written in the same rational syntax used elsewhere in this spec (e.g., 0+1/3, 1+3/4).
Consistency with absolute positioning: For any event E within a measure M, the following MUST hold:
E.:at = M.:beat-start + E.<beat>

4.8.3 Pitch Expression

Single Note:
C4.q        ; C4 quarter note
Eb5.h       ; E-flat 5 half note
F#3.e       ; F-sharp 3 eighth note
Bbb4.w      ; B double-flat 4 whole note
Cx4.s       ; C double-sharp 4 sixteenth note
Chord (simultaneous pitches):
[C4 E4 G4].q      ; C major triad, quarter note
[D3 F#3 A3 C4].h  ; D7 chord, half note
Rest:
r.q         ; Quarter rest
r.h         ; Half rest
r.w         ; Whole rest

4.8.4 Pitch Format

<pitch> ::= <step><accidental>?<octave>

<step>       ::= A | B | C | D | E | F | G
<accidental> ::= # | ## | x | b | bb
<octave>     ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

; Middle C = C4
; A440 = A4

4.8.5 Duration Format

SymbolNameRelative Value
wWhole4 beats
hHalf2 beats
qQuarter1 beat
eEighth0.5 beats
sSixteenth0.25 beats
tThirty-second0.125 beats
xSixty-fourth0.0625 beats
Dotted durations: Append . for dotted values
SymbolNameRelative Value
w.Dotted whole6 beats
h.Dotted half3 beats
q.Dotted quarter1.5 beats
e.Dotted eighth0.75 beats
Double-dotted: Append ..
SymbolNameRelative Value
h..Double-dotted half3.5 beats
q..Double-dotted quarter1.75 beats

4.8.6 Event Properties

(: 0 G4.q 
  :id #uuid "018c3f2a-..."
  :at 487+1/4
  :dyn ff
  :art staccato
  :orn trill
  :lyrics [{:verse 1 :text "Hal-" :syllabic :begin}]
  :tech pizz
  :stem up
  :staff piano-rh
  :voice 2
  :grace true
  :grace-slash true
  :cue true
  :hidden true
  :editorial true
  :ossia true
  :accidental :courtesy
  :notehead :diamond
  :fingering "2"
  :string "II"
  :harmonic natural
  :color "#FF0000")

4.8.7 Dynamic Values

pppp ppp pp p mp mf f ff fff ffff
sfz sfp sffz fz rf rfz fp sf sff
n niente

4.8.8 Articulation Values

staccato staccatissimo tenuto accent marcato
portato stress unstress
fermata fermata-short fermata-long
breath caesura

4.8.9 Ornament Values

trill trill-flat trill-sharp
mordent mordent-inverted
turn turn-inverted turn-slash
tremolo tremolo-1 tremolo-2 tremolo-3
arpeggio arpeggio-up arpeggio-down
glissando slide

4.8.10 Technique Values (String)

arco pizz pizz-snap pizz-nail
legno legno-batt legno-tratto
pont tasto normale
harm harm-natural harm-artificial
trem trem-measured trem-unmeasured
spicc detache martele
sul-g sul-d sul-a sul-e

4.8.11 Technique Values (Wind)

tongue double-tongue triple-tongue flutter
overblow undertone multiphonic
cuivre stopped open mute-straight mute-cup mute-harmon

4.9 Tuplet Syntax

(tuplet 3:2 q                    ; Triplet: 3 in the space of 2 quarters
  (: 0 C4.e :id #uuid "..." :at 0)
  (: 0+1/3 D4.e :id #uuid "..." :at 0+1/3)
  (: 0+2/3 E4.e :id #uuid "..." :at 0+2/3))

(tuplet 5:4 q                    ; Quintuplet: 5 in the space of 4 quarters  
  (: 0 C4.s :id #uuid "..." :at 0)
  (: 0+1/5 D4.s :id #uuid "..." :at 0+1/5)
  (: 0+2/5 E4.s :id #uuid "..." :at 0+2/5)
  (: 0+3/5 F4.s :id #uuid "..." :at 0+3/5)
  (: 0+4/5 G4.s :id #uuid "..." :at 0+4/5))
Tuplet Syntax:
(tuplet <ratio> <base-duration>
  <events>*)

<ratio> ::= <actual>:<normal> | :<actual>:<normal>

4.10 Grace Notes

(grace 
  :type acciaccatura
  :slash true
  :beat 2
  (: 0 F#5.s :id #uuid "..." :at 489)
  (: 0.5 G5.s :id #uuid "..." :at 489))

; Main note that graces attach to
(: 2 A5.q :id #uuid "..." :at 489+1/4)

4.11 Spans Section

Spans define relationships between events that cross event boundaries. All span endpoints use UUID references.
(spans
  ; Slur
  (slur
    :id #uuid "018c3f2c-9abc-def0-1234-567890abcdef"
    :from #uuid "018c3f2a-1234-7890-abcd-ef1234567890"
    :to #uuid "018c3f2b-5678-9012-cdef-0123456789ab"
    :placement above
    :style solid)
  
  ; Tie (must connect identical pitches)
  (tie
    :id #uuid "018c3f2d-1234-5678-9abc-def012345678"
    :from #uuid "018c3f2e-5678-9abc-def0-123456789abc"
    :to #uuid "018c3f2f-9abc-def0-1234-567890abcdef"
    :voice 1)
  
  ; Beam group
  (beam
    :id #uuid "018c3f30-1234-5678-9abc-def012345679"
    :events [#uuid "018c3f31-..." #uuid "018c3f32-..." 
             #uuid "018c3f33-..." #uuid "018c3f34-..."]
    :level 1
    :feather accelerando)
  
  ; Hairpin (crescendo/diminuendo)
  (hairpin
    :id #uuid "018c3f39-5678-9abc-def0-123456789abf"
    :from #uuid "018c3f3a-..."
    :to #uuid "018c3f3b-..."
    :type crescendo
    :placement below
    :niente false)
  
  ; Ottava
  (ottava
    :id #uuid "018c3f3c-..."
    :from #uuid "018c3f3d-..."
    :to #uuid "018c3f3e-..."
    :type 8va
    :placement above)
  
  ; Pedal
  (pedal
    :id #uuid "018c3f3f-..."
    :from #uuid "018c3f40-..."
    :to #uuid "018c3f41-..."
    :type sustain
    :style bracket)
  
  ; Glissando/portamento
  (gliss
    :id #uuid "018c3f42-..."
    :from #uuid "018c3f43-..."
    :to #uuid "018c3f44-..."
    :style wavy
    :text "gliss.")
  
  ; Volta brackets
  (volta
    :id #uuid "018c3f45-..."
    :from #uuid "018c3f46-..."
    :to #uuid "018c3f47-..."
    :number 1
    :text "1."))

4.11.1 Reference Format

All span endpoints MUST use stable UUID identifiers:
:from #uuid "018c3f2a-1234-7890-abcd-ef1234567890"
:to #uuid "018c3f2b-5678-9012-cdef-0123456789ab"

4.11.2 Span Types

TypeFrom/ToDescription
slurYESPhrase marking
tieYESConnects identical pitches
beamevents listConnects note flags
hairpinYESDynamic wedge
ottavaYESOctave transposition
pedalYESPiano pedal marking
trill-spanYESExtended trill line
glissYESGlissando line
cross-beamevents listBeam across staves
voltaYESEnding bracket
bracketYESAnalysis/grouping bracket
lineYESGeneric line (8va, etc.)

4.12 Cross-Boundary Spans and Envelope Safety

When extracting a Working Set Envelope, spans that cross envelope boundaries MUST be handled according to these rules:

4.12.1 Boundary Marking

  1. Span exits envelope: Any span starting inside and ending outside MUST be included with :boundary-exit:
(slur
  :id #uuid "018c3f2a-..."
  :from #uuid "018c3f1a-..."
  :to #uuid "018c3f2b-..."
  :boundary-exit :to)
  1. Span enters envelope: Any span starting outside and ending inside MUST be included with :boundary-entry:
(hairpin
  :id #uuid "018c3f2c-..."
  :from #uuid "018c3f1b-..."
  :to #uuid "018c3f2d-..."
  :type crescendo
  :boundary-entry :from)
  1. Span crosses envelope: Any span that starts before and ends after MUST have both markers.
Semantics:
  • :boundary-entry and :boundary-exit indicate which endpoint UUID lies outside the envelope.
  • A boundary-marked span MAY reference out-of-envelope event UUIDs at the marked endpoint(s).
  • Boundary markers are REQUIRED for any span that would otherwise reference an out-of-envelope event UUID.

4.12.2 Write Protection

Cross-boundary spans are write-protected at their boundary endpoints. On replacement, orchestrators MUST enforce:
  • Immutable semantic fields: :from, :to, and any event endpoint lists (e.g., :events for beams) MUST NOT change.
  • Allowed modifications: agents MAY change only rendering/editorial properties:
    • keys in the render:* namespace
    • keys in the edit:* namespace
    • keys with x- prefix
Any change to immutable semantic fields on a boundary-marked span MUST be rejected (fatal).

4.13 Directions

(measure 
  :id #uuid "018c3f40-..." :number 45 :beat-start 487+1/4
  
  (dir :type tempo :beat 0 :text "Più mosso" :tempo 132)
  (dir :type dynamic :beat 0 :text "ff" :scope all)
  (dir :type rehearsal :beat 0 :text "B")
  (dir :type text :beat 2 :text "poco rit." :placement above)
  (dir :type segno :beat 0)
  (dir :type coda :beat 0)
  (dir :type fine :beat 0)
  (dir :type dc :beat 0 :text "D.C. al Coda")
  (dir :type ds :beat 0 :text "D.S. al Fine")
  
  (violin-1
    (dir :type text :beat 0 :text "sul G" :placement above)
    ...))

4.14 Layout Hints (Optional)

Layout hints are NON-NORMATIVE suggestions for rendering engines.
(layout
  :bar-numbers (every 5)
  :multi-rest-style consolidated
  
  (break :type system :after #uuid "018c3f40-0008-...")
  (break :type page :after #uuid "018c3f40-0020-...")
  
  (spacing 
    :measures [#uuid "..." #uuid "..."]
    :stretch 1.2)
  
  (hide-empty-staves true)
  (condense 
    :parts [flute-1 flute-2]
    :measures [#uuid "..." #uuid "..."]
    :label "Fl. 1, 2"))

4.15 Alternatives: Ossia, Variants, and Editorials

(alternatives
  (ossia
    :measures [#uuid "..." #uuid "..."]
    :part violin-1
    :label "easier version"
    :content
      (measure :id #uuid "..." :number 123 ...))
  (variant
    :measures [#uuid "..."]
    :label "ms. variant"
    :content ...))

4.16 Score Structure: Movements

(movements
  (movement 1 :title "Allegro" :key C :mode major :time 4/4
    (measures
      (measure :id #uuid "..." :number 1 ...) ...))
  (movement 2 :title "Adagio" :key F :mode major :time 3/4
    (measures
      (measure :id #uuid "..." :number 1 ...) ...)))

5. Working Set Envelope

5.1 Overview

A Working Set Envelope wraps a bounded MRS-S fragment with context for focused agent operations. The key design principles:
  • Agents receive valid MRS-S and return valid MRS-S—no second syntax
  • Scopes use UUIDs—not measure numbers—for structural stability
  • Context rings provide surrounding material at reduced detail
  • Scope negotiation enables flexible conversational workflows

5.2 Envelope Structure

(working-set
  :version 1.0
  :source-hash "sha256:a3f2c1b9e4d7..."
  
  :scope
    (:measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0034-...")
    (:parts [clarinet-1])
    (:voices [v1])
  :display-hint (:measures 45 52)
  
  :context "String counterpoint, development section. Add clarinet countermelody."
  
  :constraints
    ((range clarinet-1 E3 G6)
     (avoid parallel-fifths violin-1))
  
  :content
    (meta
      :time 4/4
      :key C :mode minor
      :tempo 132)
    
    (parts
      (part clarinet-1 :name "Clarinet" :abbr "Cl." :staves [treble]))
    
    (measures
      (measure 
        :id #uuid "018c3f40-002d-..."
        :number 45
        :beat-start 487+1/4
        :time 4/4 :key C :mode minor
        
        (clarinet-1
          (v1
            (: 0 r.w :id #uuid "..." :at 487+1/4))))
      
      (measure 
        :id #uuid "018c3f40-002e-..."
        :number 46
        ...))
    
    (spans ...)
  
  :context-near
    (:measures #uuid "018c3f40-0029-..." #uuid "018c3f40-002c-...")
    :display-hint (:measures 41 44)
    :reduction :melodic-skeleton
    :content (measures ...)
  
  :context-far
    (:measures #uuid "018c3f40-0001-..." #uuid "018c3f40-0028-...")
    :display-hint (:measures 1 40)
    :reduction :harmonic-rhythm
    :content (measures ...)
  
  :synopsis-ref "sha256:abc123...")

5.3 Envelope Fields

5.3.1 Required Fields

FieldTypeDescription
:versiondecimalEnvelope version (currently 1.0)
:scopescope-specUUID-based extraction boundaries
:contentMRS-SThe actual score fragment (writable)

5.3.2 Scope Specification

:scope
  (:measures #uuid "..." #uuid "...")  ; UUID range (inclusive)
  (:parts [<part-id>...])               ; List of included parts
  (:voices [<voice-id>...])             ; Optional: specific voices
:display-hint (:measures 45 52)         ; Human-readable, informational only
Measure numbers appear ONLY in :display-hint—never for structural reference.

5.3.3 Optional Fields

FieldTypeDescription
:source-hashstringSHA-256 hash for conflict detection
:contextstringHuman-readable task description
:constraintslistValidation rules agent must satisfy
:context-nearcontext-specAdjacent measures at reduced detail
:context-farcontext-specDistant measures at further reduced detail
:synopsis-refstringHash reference to score synopsis

5.4 Context Rings

Context rings provide graduated detail levels for surrounding material. All context ring content is read-only.
:context-near
  (:measures #uuid "..." #uuid "...")
  :display-hint (:measures 41 44)
  :reduction :melodic-skeleton
  :content (measures ...)

:context-far
  (:measures #uuid "..." #uuid "...")
  :display-hint (:measures 1 40)
  :reduction :harmonic-rhythm
  :content (measures ...)

5.4.1 Reduction Levels

LevelContent
:fullEverything (no reduction)
:melodic-skeletonDownbeats, phrase boundaries, structural tones
:harmonic-rhythmChord roots, key changes, bass line
:structuralRehearsal marks, tempo changes, texture shifts only

5.5 Agent Response Format

Agents return a replacement fragment:
(working-set-response
  :version 1.0
  :source-hash "sha256:a3f2c1b9e4d7..."
  
  :scope
    (:measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0034-...")
    (:parts [clarinet-1])
  :display-hint (:measures 45 52)
  
  :content
    (measures
      (measure 
        :id #uuid "018c3f40-002d-..."
        :number 45
        :beat-start 487+1/4
        
        (clarinet-1
          (v1
            (: 0 Eb4.q :dyn mp :id #uuid "018c3f50-..." :at 487+1/4)
            (: 1 D4.q :id #uuid "018c3f51-..." :at 488+1/4)
            (: 2 Eb4.e :id #uuid "018c3f52-..." :at 489+1/4)
            (: 2.5 F4.e :id #uuid "018c3f53-..." :at 489+3/4)
            (: 3 G4.q :id #uuid "018c3f54-..." :at 490+1/4))))
      
      (measure 
        :id #uuid "018c3f40-002e-..."
        :number 46
        ...))
    
    (spans
      (slur :id #uuid "018c3f55-..." 
            :from #uuid "018c3f50-..." 
            :to #uuid "018c3f54-..."))
  
  :rationale "Created contrary motion against violin line. Chord tones on downbeats.")

5.6 Scope Negotiation Protocol

Agents can request scope adjustments when the current scope is insufficient:
(scope-request
  :reason "Phrase extends beyond current boundary"
  :current 
    (:measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0034-...")
  :requested 
    (:measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0038-...")
  :justification "Slur endpoint at beat 487+3/4 in measure 56")
The orchestrator can:
  • Grant: Provide expanded Working Set
  • Deny: Return error with reason
  • Offer alternative: Suggest different scope
(scope-response
  :status :granted
  :scope
    (:measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0038-...")
  :content ...)

; OR

(scope-response
  :status :denied
  :reason "Requested scope overlaps with active lock"
  :alternative
    (:measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0035-..."))

5.7 Self-Containment Principle

Every Working Set Envelope MUST be self-contained: the :content can be parsed and validated independently. This means:
  • Part definitions MUST be included
  • Time/key/tempo state at extraction start MUST be declared
  • Spans MUST have both endpoints within scope (or be marked with boundary markers)

6. Synopsis Format

6.1 Overview

The Synopsis is a compressed structural view that provides global context without full detail. It is:
  • Derived: Computed from full MRS-S
  • Read-only: Agents cannot modify it
  • Lossy by design: Context, not content

6.2 Synopsis Structure

(synopsis
  :hash "sha256:abc123..."
  :source-hash "sha256:def456..."
  
  :structure
    (movement 1 :title "Allegro" 
      :first-measure #uuid "018c3f40-0001-..." 
      :last-measure #uuid "018c3f40-0144-..."
      :display-range [1 324]
      :key C :mode minor)
    (movement 2 :title "Andante"
      :first-measure #uuid "018c3f40-0145-..."
      :last-measure #uuid "018c3f40-0200-..."
      :display-range [1 89]
      :key Ab :mode major)
  
  :parts
    (part violin-1 :section strings :range [G3 E7])
    (part violin-2 :section strings :range [G3 D7])
    (part viola :section strings :range [C3 A6])
    (part cello :section strings :range [C2 G5])
    (part clarinet-1 :section woodwinds :transposition (down M2) :range [E3 G6])
  
  :harmonic-spine
    ((:measures #uuid "018c3f40-0001-..." #uuid "018c3f40-0008-..."
      :key Cm :function i :display-range [1 8])
     (:measures #uuid "018c3f40-0009-..." #uuid "018c3f40-0016-..."
      :key Eb :function III :display-range [9 16])
     (:measures #uuid "018c3f40-0017-..." #uuid "018c3f40-0024-..."
      :key Gm :function v :display-range [17 24]))
  
  :thematic-regions
    ((theme-a 
      :first-appearance #uuid "018c3f40-0001-..."
      :display-measure 1
      :parts [violin-1] 
      :recurrences [#uuid "018c3f40-0040-..." #uuid "018c3f40-0100-..."]
      :recurrence-measures [64 160])
     (theme-b 
      :first-appearance #uuid "018c3f40-0020-..."
      :display-measure 32
      :parts [cello]))
  
  :density-profile
    ((:measures #uuid "018c3f40-0001-..." #uuid "018c3f40-0010-..."
      :display-range [1 16]
      :avg-events-per-beat 2.3 
      :active-parts 4)
     (:measures #uuid "018c3f40-0011-..." #uuid "018c3f40-0020-..."
      :display-range [17 32]
      :avg-events-per-beat 4.1 
      :active-parts 8))
  
  :rehearsal-map
    ((A #uuid "018c3f40-0001-..." :display 1)
     (B #uuid "018c3f40-0020-..." :display 32)
     (C #uuid "018c3f40-0040-..." :display 64)
     (D #uuid "018c3f40-0080-..." :display 128)))

6.3 Synopsis Fields

FieldDescription
:hashSHA-256 of the synopsis itself
:source-hashSHA-256 of the MRS-S it was derived from
:structureMovement/section boundaries
:partsPart summary (section, range, transposition)
:harmonic-spineChord progression and key areas
:thematic-regionsTheme appearances and recurrences
:density-profileTexture information by region
:rehearsal-mapRehearsal marks with UUID/measure mappings

6.4 Synopsis Access

Working Set Envelopes reference the synopsis by hash:
(working-set
  ...
  :synopsis-ref "sha256:abc123...")
Agents can query the orchestrator for the synopsis:
(query
  :type synopsis
  :ref "sha256:abc123..."
  :response (synopsis ...))

7. Analytical Overlays

7.1 Overview

Overlays attach analytical metadata to scores. They are:
  • Typed: Different analysis types have different schemas
  • Attributable: Track provenance (author, timestamp)
  • Optional: Renderers ignore them; agents can use them
  • Separable: Can be recomputed without touching musical content

7.2 Overlay Structure

(overlays
  (overlay :id harmonic-analysis :author "analysis-agent"
    :created "2025-12-12T10:30:00Z"
    
    (region 
      :from #uuid "018c3f40-0001-..." 
      :to #uuid "018c3f40-0004-..." 
      :chord Cm :function i :cadence none)
    (region 
      :from #uuid "018c3f40-0005-..." 
      :to #uuid "018c3f40-0008-..."
      :chord Fm :function iv)
    (region 
      :from #uuid "018c3f40-0009-..." 
      :to #uuid "018c3f40-0012-..."
      :chord G7 :function V7 :cadence half))
  
  (overlay :id motivic-analysis :author "theme-tracker"
    :created "2025-12-12T11:00:00Z"
    
    (motive :id theme-a 
      :signature [0 2 4 5 7] 
      :contour [up up up down])
    (motive :id theme-b
      :signature [7 5 4 2 0]
      :contour [down down down down])
    
    (occurrence 
      :measure #uuid "018c3f40-0001-..." 
      :part violin-1 :voice v1 :beat 0 
      :motive theme-a :transform original)
    (occurrence 
      :measure #uuid "018c3f40-0020-..." 
      :part viola :voice v1 :beat 2
      :motive theme-a :transform inversion)
    (occurrence 
      :measure #uuid "018c3f40-0040-..." 
      :part cello :voice v1 :beat 0
      :motive theme-a :transform retrograde))
  
  (overlay :id form-analysis :author "form-agent"
    (section :type exposition
      :from #uuid "018c3f40-0001-..." 
      :to #uuid "018c3f40-0064-...")
    (section :type development
      :from #uuid "018c3f40-0065-..." 
      :to #uuid "018c3f40-0120-...")
    (section :type recapitulation
      :from #uuid "018c3f40-0121-..." 
      :to #uuid "018c3f40-0180-...")))

7.3 Overlay Types

TypeContent
harmonic-analysisChord symbols, Roman numerals, cadences
motivic-analysisTheme definitions and occurrences
form-analysisStructural sections
voice-leadingPart writing analysis
orchestrationDoubling and texture analysis

7.4 Overlay Operations

Overlays can be:
  • Created: Agent analyzes score, produces overlay
  • Queried: Agent requests specific overlay
  • Merged: Multiple overlays combined
  • Recomputed: Overlay regenerated after score changes

8. Data Model

8.1 Overview

MRS-S and Working Set Envelopes serialize the same underlying data model.

8.2 Core Entities

Score
├── Metadata: Map<String, Value>
├── Parts: OrderedMap<PartId, Part>
├── Measures: OrderedMap<UUID, Measure>
├── Spans: Set<Span>
├── Overlays: Set<Overlay> (optional)
└── Layout: LayoutHints (optional)

Part
├── id: PartId (e.g., "violin-1")
├── name: String
├── abbreviation: String
├── staves: List<Clef>
├── section: Section?
├── transposition: Interval?
├── range: (Pitch, Pitch)?
└── attributes: Map<String, Value>

Measure
├── id: UUIDv7 (stable identity)
├── number: PositiveInt (display property)
├── beat-start: Rational (absolute position)
├── sec-start: Float? (REQUIRED if tempo automation)
├── time: TimeSignature?
├── key: KeySignature?
├── tempo: Tempo?
├── rehearsal: String?
├── barlines: (BarlineType, BarlineType)
├── directions: List<Direction>
└── content: Map<PartId, PartContent>

Event
├── id: UUIDv7 (stable identity)
├── beat: Decimal (position in measure)
├── at: Rational (absolute position)
├── pitches: List<Pitch> (empty for rest)
├── duration: Duration
└── properties: Map<String, Value>

Span
├── id: UUIDv7 (stable identity)
├── type: slur | tie | beam | hairpin | ...
├── from: UUIDv7 (event reference)
├── to: UUIDv7 (event reference)
├── events: List<UUIDv7>? (for beam groups)
├── boundary-entry: UUIDv7? (if span enters envelope)
├── boundary-exit: UUIDv7? (if span exits envelope)
├── placement: above | below?
└── properties: Map<String, Value>

Overlay
├── id: OverlayId
├── type: OverlayType
├── author: String
├── created: Timestamp
└── content: List<OverlayElement>

8.3 Invariants

  1. Unique identifiers: No two measures, events, or spans may share a UUID
  2. Display numbers: Measure numbers must be positive; may have gaps
  3. Beat bounds: Event beat positions must be ≥ 0 and < measure duration
  4. Duration sum: Sum of durations in a voice should not exceed measure duration
  5. Tie pitch match: Tied notes must have identical pitch
  6. Span validity: Span endpoints must reference existing events by UUID
  7. Voice consistency: Events in a voice should not overlap temporally
  8. UUID immutability: Once assigned, an :id is immutable
  9. Dual positioning: Every event MUST have both beat and :at
  10. Measure identity: Every measure MUST have :id and :number

8.4 Temporal Model

MRS uses a dual positioning model: Structural positioning (measure-relative):
  • Beat 0 is the first beat of the measure
  • Beat positions are exact rationals
  • Used for human readability
Absolute positioning:
  • :at — Rational quarter-notes since part start
  • :sec — Seconds since start (if tempo automation)
  • Used for meter-agnostic reasoning
All validation involving timing MUST use absolute positions.

9. Extract-Replace Protocol

9.1 Overview

The Extract-Replace Protocol defines how to create Working Set Envelopes and apply agent responses.
┌─────────────────┐         extract         ┌─────────────────────────┐
│     MRS-S       │ ──────────────────────► │  Working Set Envelope   │
│    (Source)     │                         │  (scoped MRS-S + context)│
│                 │ ◄────────────────────── │                         │
└─────────────────┘         replace         └─────────────────────────┘

9.2 Extraction (MRS-S → Working Set)

9.2.1 Extraction Parameters

ExtractParams {
  measures: Range<UUID>              ; Required: measure UUID range
  parts: Set<PartId>                 ; Required: parts to include
  voices: Set<VoiceId>?              ; Optional: filter voices
  context_near_measures: Int?        ; Adjacent context measures
  context_far_measures: Int?         ; Distant context measures
  context_reductions: ReductionLevel ; Reduction for context rings
  task_context: String?              ; Task description
  constraints: List<Constraint>?     ; Validation rules
}

9.2.2 Extraction Algorithm

function extract(source: MRS-S, params: ExtractParams) -> WorkingSetEnvelope:
  
  1. Validate params
     - All requested measure UUIDs exist
     - All requested parts exist
  
  2. Compute source hash (SHA-256)
  
  3. Resolve inherited state at extraction start
  
  4. Build content
     - Copy measures in UUID range
     - Copy relevant spans (mark boundary crossings)
     - Apply reduction to context rings
  
  5. Build envelope with scope, context, synopsis reference
  
  6. Return WorkingSetEnvelope

9.3 Replacement (Working Set → MRS-S)

9.3.1 Replacement Algorithm

function replace(source: MRS-S, response: WorkingSetResponse) -> Result<MRS-S>:

  1. Verify source hash (conflict detection)
  
  2. Validate response scope (UUID range, parts)
  
  3. Parse response content as MRS-S
  
  4. Assign UUIDs to new objects lacking them
  
  5. For each measure UUID in scope:
     a) Locate the corresponding measure in source by :id
     b) For each scoped part in (:parts [...]):
        DELETE existing content for that part within that measure
        INSERT response content for that part within that measure
     c) Preserve all unscoped parts in that measure unchanged
     d) Preserve measure-level attributes unchanged (except orchestrator-managed fields during insertion operations)
  
  6. Handle spans (update/insert/delete)
  
  7. Full validation
  
  8. Return updated MRS-S

9.3.2 Measure Attribute Rules (Determinism)

To keep replacement deterministic and safe for partial scopes:
  • A working-set-response MUST include the target measures by :id.
  • For any measure replaced, :id MUST match the source measure :id.
  • For any measure replaced, :beat-start MUST match the source value.
  • :number is a display hint and MAY differ; orchestrators MAY normalize it.
  • Other measure-level attributes (:time, :key, :tempo, barlines, etc.) MUST NOT be changed via scoped replacement in v1.0. If provided in the response, they MUST exactly match the source or replacement MUST be rejected.
Measure insertions/structural changes MUST use the insertion mechanism defined in §9.5.

9.4 Round-Trip Guarantee

For any valid MRS-S document S and extraction parameters P:
replace(S, identity(extract(S, P))) ≡ S

9.5 Insertion Operations

When agents need to insert new measures:
(working-set-response
  :scope
    (:measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0034-...")
    (:parts [clarinet-1])
  
  :insertions
    ((after #uuid "018c3f40-0030-..."
      (measure :id #uuid "018c3f50-new1-..." :number :auto ...)))
  
  :content ...)
The orchestrator:
  1. Assigns :number values based on position
  2. Updates :beat-start and :sec-start for subsequent measures
  3. Preserves all UUID references

10. Agent Operations

10.1 Overview

MRS supports AI-assisted composition through context-aware agent operations. Agents receive Working Set Envelopes with appropriate context and return valid MRS-S fragments.

10.2 Task Definition

Task {
  id: TaskId
  type: TaskType
  instruction: String
  working_set: WorkingSetEnvelope
  synopsis: Synopsis?
  context: Map<String, Value>
}

TaskType {
  compose      ; Create new content
  arrange      ; Adapt existing content
  harmonize    ; Add harmony to melody
  orchestrate  ; Assign to instruments
  analyze      ; Extract information
  correct      ; Fix errors
  transform    ; Apply transformation
  extend       ; Continue existing material
}

10.3 Sequential Workflow Model

Composition proceeds through sequential agent operations. Form and structure emerge through the creative process:
1. Initial sketch (melody agent)
   → orchestrator replaces
   
2. Harmonic elaboration (harmony agent)
   → orchestrator replaces
   
3. Structural extension (form agent)
   → may insert measures
   → orchestrator handles UUID assignment
   
4. Orchestration (orchestration agent)
   → orchestrator replaces
   
5. Refinement passes...
Each agent:
  • Receives current state in Working Set Envelope
  • Has context rings for surrounding material
  • Has synopsis access for global awareness
  • Returns valid MRS-S fragment
  • May request scope expansion via negotiation

10.4 Constraint Language

; Range constraint
(range <part> <low-pitch> <high-pitch>)

; Avoidance constraint
(avoid <violation-type> <reference-part>?)
; Types: parallel-fifths, parallel-octaves, voice-crossing, etc.

; Preference constraint
(prefer <feature> <location>)
; Features: chord-tones, consonance, stepwise, contrary-motion
; Locations: downbeats, strong-beats, phrase-start

; Interval constraint
(max-interval <interval>)
(min-interval <interval>)

; Density constraint
(note-density <min> <max>)
(rest-ratio <min> <max>)

10.5 Validation Pipeline

function validate_result(task: Task, result: WorkingSetResponse):
  1. Parse as MRS-S
  2. Verify scope bounds
  3. Check constraints
  4. Check musical rules (ties, durations)
  5. Return ValidationResult

11. Query Resolution

11.1 Overview

The orchestrator translates human-friendly references to UUIDs. Agents always receive and work with UUIDs.

11.2 Query Types

Measure number resolution:
(query
  :type resolve
  :human-ref (:measure-number 45)
  :response (:id #uuid "018c3f40-002d-..." :number 45))
Rehearsal mark resolution:
(query
  :type resolve
  :human-ref (:rehearsal "B")
  :response (:id #uuid "018c3f40-0020-..." :number 32))
Rehearsal mark with offset:
(query
  :type resolve
  :human-ref (:rehearsal "B" :offset 4)
  :response (:id #uuid "018c3f40-0024-..." :number 36))
Range resolution:
(query
  :type resolve-range
  :human-ref (:measures 45 52)
  :response (:from #uuid "018c3f40-002d-..."
             :to #uuid "018c3f40-0034-..."
             :display-range [45 52]))

11.3 Reverse Resolution

UUID to display information:
(query
  :type display-info
  :id #uuid "018c3f40-002d-..."
  :response (:number 45 :rehearsal "C" :beat-start 487+1/4))

12. Validation Rules

12.1 Syntax Validation

  • Document matches grammar
  • All required sections present
  • Version is supported

12.2 Structural Validation

RuleSeverityDescription
STRUCT-001ERRORDuplicate UUIDs
STRUCT-002ERRORInvalid measure numbers (non-positive)
STRUCT-003ERRORInvalid beat position
STRUCT-004ERRORReference to non-existent UUID (except boundary-marked span endpoints)
STRUCT-005ERRORMissing required :id or :at
STRUCT-006WARNINGGap in measure numbering
STRUCT-007WARNINGEmpty measure

12.3 Musical Validation

RuleSeverityDescription
MUSIC-001ERRORTie connects different pitches
MUSIC-002ERRORDuration overflow
MUSIC-003WARNINGExtreme pitch
MUSIC-004WARNINGParallel fifths/octaves
MUSIC-005WARNINGVoice crossing
MUSIC-006WARNINGLarge melodic leap

12.4 Span Validation

RuleSeverityDescription
SPAN-001ERRORSpan references non-existent UUID
SPAN-002ERRORSlur from/to identical
SPAN-003WARNINGSlur spans more than 8 measures
SPAN-004WARNINGOverlapping slurs
SPAN-005FATALBoundary-anchored span endpoint modified

13. Extension Mechanisms

13.1 Custom Properties

Events, spans, and directions support custom properties with x- prefix:
(: 0 C4.q 
  :id #uuid "..."
  :at 0
  :dyn f
  :x-source "manuscript-page-47"
  :x-confidence 0.85)

13.2 Namespace Extensions

(: 0 C4.q
  :id #uuid "..." :at 0
  :analysis:roman-numeral "I"
  :analysis:function "tonic"
  :mei:xml-id "note-001")
NamespacePurpose
x-*Unregistered extensions
analysis:*Music theory analysis
mei:*MEI compatibility
midi:*MIDI-specific data
render:*Rendering hints
edit:*Editorial metadata

14. MIME Types and File Extensions

14.1 MIME Types

FormatMIME Type
MRS-Sapplication/vnd.mrs+sexpr
Working Set Envelope / Responseapplication/vnd.mrs-work+sexpr

14.2 File Extensions

FormatExtension
MRS-S.mrs or .mrs-s
Working Set Envelope.mrs-work (typically ephemeral)

14.3 Encoding

MRS documents MUST be encoded in UTF-8. BOM SHOULD NOT be used.

15. Security Considerations

15.1 Input Validation

Parsers MUST validate:
  • Maximum document size
  • Maximum nesting depth
  • Maximum event count per measure
  • Valid Unicode in strings

15.2 Denial of Service Protection

Implementations SHOULD protect against:
  • Deeply nested structures
  • Very large measure numbers
  • Excessive span counts
  • Malformed UTF-8

15.3 Information Disclosure

Working Set Envelopes may expose:
  • Source document structure
  • Source document hash
  • Creator/modifier identity
Implementations SHOULD allow redaction of sensitive metadata.

Appendix A: Complete Grammar

A.1 MRS-S Key Productions

document  <- '(' 'mrs-s' version meta parts measures spans? overlays? layout? ')'
measure   <- '(' 'measure' ':id' uuid ':number' INT measure-attrs* part-content* ')'
event     <- '(' ':' beat pitch-expr ':id' uuid ':at' rational properties* ')'
pitch     <- STEP ACCIDENTAL? OCTAVE '.' DURATION
chord     <- '[' pitch+ ']' '.' DURATION
span      <- '(' span-type ':id' uuid ':from' uuid ':to' uuid attributes* ')'
uuid      <- '#uuid' '"' UUID-STRING '"'
rational  <- INT (('+' INT '/' INT) | ('/' INT))?
beat      <- rational

A.2 Working Set Envelope Key Productions

envelope  <- '(' 'working-set' version scope context? constraints? 
             ':content' mrs-s-fragment context-rings* ')'
response  <- '(' 'working-set-response' version scope 
             ':content' mrs-s-fragment rationale? ')'
scope     <- ':scope' '(' ':measures' uuid uuid ')' '(' ':parts' '[' part-id* ']' ')'

Appendix B: Quick Reference

B.1 Duration Codes

CodeDurationBeats
wWhole4
hHalf2
qQuarter1
eEighth0.5
sSixteenth0.25
t32nd0.125

B.2 Required Event Properties

PropertyDescription
:idStable UUIDv7 identifier
:atAbsolute beat position

B.3 Required Measure Properties

PropertyDescription
:idStable UUIDv7 identifier
:numberDisplay number (human navigation)
:beat-startAbsolute beat position

Appendix C: Comparison with Existing Formats

AspectMRS-SMusicXMLABCLilyPond
SyntaxS-expressionXMLCustomCustom
Formal grammarYesYes (XSD)PartialNo
UUID identifiersYesNoNoNo
Context-aware extractionYesNoNoNo
Agent-friendlyYesNoPartialNo
Semantic precisionHighHighLowMedium

Appendix D: Glossary

TermDefinition
AgentAn AI system that operates on MRS documents
Context RingSurrounding material at reduced detail
EventAn atomic musical occurrence with UUID identity
MeasureA metrical unit with UUID identity
OrchestratorSystem coordinating agents and the full score
OverlayAnalytical metadata attached to score regions
ScopeUUID-based boundaries of a Working Set
SynopsisCompressed structural view of the full score
Working SetA subset of a score extracted for editing

End of Specification