> ## Documentation Index
> Fetch the complete documentation index at: https://musicready.org/llms.txt
> Use this file to discover all available pages before exploring further.

# MRS: Music Representation

## RFC 0001 — Version 1.0

**Status:** Draft\
**Created:** 2025-12-12\
**Updated:** 2026-01-17\
**Authors:** MRS Working Group\
**License:** CC BY 4.0

***

## Abstract

<a id="abstract" />

This document specifies MRS (Music Representation), a model and protocol suite for encoding and safely editing musical scores in AI-assisted composition and orchestration workflows at professional scale.

MRS is built on three core architectural principles:

1. **Separation of storage and mutation formats**: MRS-S is the canonical storage format; MRS-Ops is the typed operation protocol for agent mutations
2. **Player-Instrument-Staff model**: Professional orchestration semantics with instrument doubling and switching
3. **Task-adaptive context**: Dynamic context views tailored to specific editing tasks, not fixed reduction rings

The key insight is that reliable AI-assisted composition requires different optimizations for *reading* scores (complete, archival MRS-S) versus *writing* changes (typed, validated operations). Agents read MRS-S fragments with task-appropriate context views; agents write typed operations that the orchestrator validates progressively and applies deterministically.

Every musical object carries a stable UUID identifier. The orchestrator is the sole authority for UUID minting, derived field computation, and canonical state management. This eliminates entire classes of agent errors (hallucinated references, calculation mismatches, accidental deletions) while maintaining full semantic fidelity.

***

## Table of Contents

1. [Introduction](#1-introduction)
2. [Design Principles](#2-design-principles)
3. [Architecture Overview](#3-architecture-overview)
4. [MRS-S: The Canonical Storage Format](#4-mrs-s-the-canonical-storage-format)
5. [MRS-Ops: The Mutation Protocol](#5-mrs-ops-the-mutation-protocol)
6. [Players, Instruments, and Staves](#6-players-instruments-and-staves)
7. [Working Set Envelope](#7-working-set-envelope)
8. [Task-Adaptive Context Views](#8-task-adaptive-context-views)
9. [Structural Index](#9-structural-index)
10. [Analytical Overlays](#10-analytical-overlays)
11. [Data Model](#11-data-model)
12. [Orchestrator Contract](#12-orchestrator-contract)
13. [Progressive Validation](#13-progressive-validation)
14. [Query Resolution](#14-query-resolution)
15. [Extension Mechanisms](#15-extension-mechanisms)
16. [MIME Types and File Extensions](#16-mime-types-and-file-extensions)
17. [Security Considerations](#17-security-considerations)
18. [Appendix A: Complete Grammar](#appendix-a-complete-grammar)
19. [Appendix B: Quick Reference](#appendix-b-quick-reference)
20. [Appendix C: Glossary](#appendix-c-glossary)

***

## 1. Introduction

<a id="1-introduction" />

### 1.1 Motivation

AI cannot currently compose or edit full orchestral scores reliably. Three fundamental challenges block progress:

**Scale**: A full orchestral score (\~1.5M tokens) exceeds any context window. Editing measure 847 should not require loading measures 1-846.

**Context**: Musical decisions require understanding surrounding material. An agent writing a countermelody needs phrase boundaries, harmonic rhythm, and thematic relationships—not just the target measures.

**Reliability**: Existing approaches ask AI to emit complete, structurally-valid score fragments. This creates high failure rates from:

* Accidental omissions (agent returns less than given)
* Calculation errors (duration sums, absolute positions)
* Hallucinated references (IDs that don't exist)
* Format violations (malformed syntax)

MRS solves these through architectural separation:

* **MRS-S** (storage): Complete, archival-quality encoding with stable UUIDs
* **MRS-Ops** (mutation): Typed operation protocol with orchestrator-derived fields
* **Task-adaptive context**: Dynamic views tailored to specific editing tasks
* **Progressive validation**: Operations validated before application
* **Orchestrator authority**: Single source of truth for UUIDs, derived fields, and state

### 1.2 Goals

<a id="1-2-goals" />

1. **Semantic completeness**: Encode everything a professional engraver needs (Dorico-level granularity)
2. **Reliable agent output**: Typed operations with progressive validation minimize repair loops
3. **Structural stability**: UUIDs survive insertions, deletions, and reorderings
4. **Professional orchestration**: Player/instrument model supports doubling, switching, condensing
5. **Task-appropriate context**: Agents receive information relevant to their specific task
6. **Deterministic reconciliation**: Operations produce predictable, auditable results
7. **Human-auditable**: Operations are semantic diffs; humans review intent, not syntax

### 1.3 Non-Goals

<a id="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

<a id="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.

| Term         | Definition                                                            |
| ------------ | --------------------------------------------------------------------- |
| Score        | A complete musical work in MRS-S format                               |
| Player       | A performer who may play multiple instruments                         |
| Instrument   | A specific sound source with fixed transposition and range            |
| Staff        | A visual grouping of five lines; instruments may have multiple staves |
| Voice        | An independent melodic/rhythmic stream within a staff                 |
| Measure      | A metrical unit bounded by barlines, identified by UUID               |
| Event        | An atomic musical occurrence (note, rest, chord), identified by UUID  |
| Span         | A relation connecting multiple events (slur, beam, hairpin)           |
| MRS-S        | The canonical storage format (S-expression based)                     |
| MRS-Ops      | The typed operation protocol for agent mutations                      |
| Working Set  | A bounded MRS-S fragment with task-adaptive context                   |
| Orchestrator | System that owns canonical state and applies validated operations     |

***

## 2. Design Principles

<a id="2-design-principles" />

### 2.1 Separation of Concerns: Storage vs Mutation

MRS uses different representations optimized for different purposes:

| Concern                        | Format  | Optimized For                                 |
| ------------------------------ | ------- | --------------------------------------------- |
| Storage, interchange, archival | MRS-S   | Completeness, human readability, validation   |
| Agent output, mutations        | MRS-Ops | Reliability, minimal surface, explicit intent |

**Rationale**: Asking agents to emit complete, valid score fragments creates high failure rates. Typed operations with orchestrator-derived fields eliminate entire error classes.

### 2.2 Orchestrator Authority

The orchestrator is the sole authority for:

* UUID minting (agents use temporary IDs)
* Derived field computation (`:at`, `:beat-start`, `:sec-start`)
* Canonical state management
* Validation and application of changes

**Rationale**: Centralized authority eliminates coordination failures. Agents cannot create invalid references or miscalculate derived fields.

### 2.3 Stable Identity Over Positional Reference

Every measure, event, and span carries a stable UUIDv7 identifier. Measure numbers are display properties for human navigation, not structural identity.

**Rationale**: Positional references break when content is inserted or deleted. UUID references survive structural changes.

### 2.4 Progressive Validation

Operations are validated in stages before application:

1. **Syntax**: Operation is well-formed
2. **References**: All referenced IDs exist (or are valid tmp-ids)
3. **Permissions**: Operation is within granted lanes/scope
4. **Musical rules**: Content satisfies constraints
5. **Application**: State mutation (guaranteed to succeed after validation)

**Rationale**: Errors caught before state mutation enable specific feedback and partial acceptance.

### 2.5 Task-Adaptive Context

Agents receive context views tailored to their specific task, not fixed "near/far" rings. Context is information needed to make correct decisions, not just nearby measures.

**Rationale**: Fixed rings may include irrelevant content and omit critical content. Task-adaptive views provide what's actually needed.

### 2.6 Professional Orchestration Semantics

The Player → Instrument → Staff model supports:

* Instrument doubling (Flute 2 / Piccolo)
* Mid-score instrument changes
* Transposition handling across changes
* Percussion kits
* Condensing and divisi

**Rationale**: Arrangers and orchestrators work with players and instrument changes constantly. This is not an edge case.

***

## 3. Architecture Overview

<a id="3-architecture-overview" />

### 3.1 System Architecture

```
┌─────────────────────────────────────────────────────────────────────────┐
│                         MRS ARCHITECTURE                                 │
│                                                                          │
│  ┌───────────────────────────────────────────────────────────────────┐  │
│  │                      SEMANTIC MODEL                                │  │
│  │   Players → Instruments → Staves                                   │  │
│  │   Measures → Events (notes, rests, chords)                         │  │
│  │   Spans (slurs, ties, beams, hairpins)                             │  │
│  │   Analytical Overlays                                              │  │
│  │   Structural Index                                                 │  │
│  └───────────────────────────────────────────────────────────────────┘  │
│                      │                         │                         │
│             ┌────────┴────────┐       ┌────────┴────────┐               │
│             │     MRS-S       │       │    MRS-Ops      │               │
│             │   (storage,     │       │   (mutation,    │               │
│             │    reading)     │       │    writing)     │               │
│             └─────────────────┘       └─────────────────┘               │
│                                               │                          │
│  ┌────────────────────────────────────────────┴─────────────────────┐   │
│  │                       ORCHESTRATOR                                │   │
│  │                                                                   │   │
│  │   • UUID minting (tmp-id → UUID mapping)                         │   │
│  │   • Derived field computation (:at, :beat-start)                 │   │
│  │   • Progressive validation pipeline                              │   │
│  │   • Task-adaptive context generation                             │   │
│  │   • Lane bundle management                                       │   │
│  │   • Changeset audit trail                                        │   │
│  └───────────────────────────────────────────────────────────────────┘   │
│                      │                                                   │
│  ┌───────────────────┴───────────────────────────────────────────────┐  │
│  │                  WORKING SET ENVELOPE                              │  │
│  │                                                                    │  │
│  │   :content (MRS-S fragment — agent reads this)                    │  │
│  │   :context-views (task-adaptive, queryable)                       │  │
│  │   :structural-index-ref (global awareness)                        │  │
│  │   :bundle (lane permissions for task type)                        │  │
│  │   :available-queries (what agent can request)                     │  │
│  └────────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────┘
```

### 3.2 Data Flow

```
1. EXTRACTION
   Orchestrator creates Working Set Envelope:
   - Extracts MRS-S fragment for scope
   - Generates task-adaptive context views
   - Grants lane bundle permissions
   - Includes structural index reference

2. AGENT PROCESSING
   Agent receives Working Set Envelope:
   - Reads MRS-S content + context views
   - Produces MRS-Ops (typed operations)
   - Uses tmp-ids for new objects

3. VALIDATION (Progressive)
   Orchestrator validates operations:
   - Syntax validation
   - Reference validation (tmp-ids and UUIDs)
   - Permission validation (lanes, scope)
   - Musical rule validation

4. APPLICATION
   Orchestrator applies validated operations:
   - Maps tmp-ids to UUIDs
   - Computes derived fields
   - Updates canonical score state (and can export MRS-S)
   - Records audit trail

5. RESPONSE
   Orchestrator returns result:
   - Success with applied changes
   - Or rejection with specific errors
```

### 3.3 The Scale Problem

| Score Type        | Parts | Measures | Events    | MRS-S Size | Tokens |
| ----------------- | ----- | -------- | --------- | ---------- | ------ |
| Lead sheet        | 1     | 32       | \~200     | \~8 KB     | \~2K   |
| Piano sonata      | 2     | 300      | \~5,000   | \~150 KB   | \~40K  |
| String quartet    | 4     | 400      | \~8,000   | \~250 KB   | \~65K  |
| Chamber orchestra | 25    | 500      | \~50,000  | \~1.5 MB   | \~400K |
| Full orchestra    | 90    | 1000     | \~200,000 | \~6 MB     | \~1.5M |

No context window can hold a full orchestral score. MRS solves this through bounded extraction with task-adaptive context.

***

## 4. MRS-S: The Canonical Storage Format

<a id="4-mrs-s-the-canonical-storage-format" />

MRS-S is an S-expression format optimized for complete semantic fidelity, human readability, and archival quality.

### 4.1 Document Structure

```clojure theme={null}
(mrs-s 1.0
  (meta <metadata>)
  (players <player-definitions>)
  (instruments <instrument-definitions>)
  (measures <measure-content>)           ; OR (movements <movement-content>)
  (spans <span-definitions>)
  (overlays <overlay-content>)           ; OPTIONAL
  (structural-index <index-content>)     ; OPTIONAL (can be computed)
  (alternatives <alt-content>)           ; OPTIONAL
  (layout <layout-hints>))               ; OPTIONAL
```

All top-level sections except `overlays`, `alternatives`, and `layout` are REQUIRED. Sections MUST appear in the order shown.

### 4.2 Version Declaration

```clojure theme={null}
(mrs-s 1.0
  ...)
```

The version number follows semantic versioning (MAJOR.MINOR). Parsers MUST reject documents with unsupported major versions.

### 4.3 Metadata Section

```clojure theme={null}
(meta
  :title "Symphony No. 5 in C Minor"
  :subtitle "Fate Knocking at the Door"
  :composers ["Ludwig van Beethoven"]
  :arrangers []
  :copyright "Public Domain"
  :created "1808"
  :modified "2026-01-17T10:30:00Z"
  
  ; Score-wide defaults
  :key C :mode minor
  :time 2/4
  :tempo 108
  :tempo-text "Allegro con brio")
```

#### Required Metadata Fields

| Field    | Type   | Description               |
| -------- | ------ | ------------------------- |
| `:title` | string | Primary title of the work |

#### Optional Metadata Fields

| Field         | Type        | Description                         |
| ------------- | ----------- | ----------------------------------- |
| `:subtitle`   | string      | Secondary title                     |
| `:composers`  | \[string]   | List of composer names              |
| `:arrangers`  | \[string]   | List of arranger names              |
| `:copyright`  | string      | Copyright notice                    |
| `:key`        | pitch-class | Default key (A-G with optional #/b) |
| `:mode`       | keyword     | `major`, `minor`, `dorian`, etc.    |
| `:time`       | fraction    | Default time signature              |
| `:tempo`      | integer     | Default tempo in BPM                |
| `:tempo-text` | string      | Tempo marking text                  |

### 4.4 Measures Section

```clojure theme={null}
(measures
  (measure 
    :id #uuid "018c3f40-0001-7890-abcd-ef1234567890"
    :number 1
    :beat-start 0
    :time 4/4
    :key C :mode minor
    :tempo 120
    
    (flute-1
      (v1
        (: 0 C5.q :id #uuid "018c3f2a-0001-...")
        (: 1 D5.q :id #uuid "018c3f2a-0002-...")
        (: 2 E5.h :id #uuid "018c3f2a-0003-...")))
    
    (clarinet-bb
      (v1
        (: 0 r.w :id #uuid "018c3f2a-0010-...")))))
```

#### Measure Attributes

| Attribute     | Required | Type        | Description                                    |
| ------------- | -------- | ----------- | ---------------------------------------------- |
| `:id`         | YES      | UUIDv7      | Stable identifier                              |
| `:number`     | YES      | integer     | Display number (can have gaps)                 |
| `:beat-start` | YES      | rational    | Absolute beat position (orchestrator-computed) |
| `:time`       | NO       | fraction    | Time signature (inherits if omitted)           |
| `:key`        | NO       | pitch-class | Key signature (inherits if omitted)            |
| `:tempo`      | NO       | integer     | Tempo in BPM (inherits if omitted)             |

### 4.5 Event Syntax

```clojure theme={null}
(: <beat> <pitch-expr> :id <uuid> <properties>*)
```

| Component      | Description                                              |
| -------------- | -------------------------------------------------------- |
| `:`            | Event marker                                             |
| `<beat>`       | Beat position within measure (0-indexed, exact rational) |
| `<pitch-expr>` | Pitch with duration, chord, or rest                      |
| `:id`          | Stable UUIDv7 identifier (REQUIRED)                      |
| `<properties>` | Optional `:keyword value` pairs                          |

**Note**: The `:at` field (absolute position) is NOT required in storage. It is computed by the orchestrator when needed:

```
event.:at = measure.:beat-start + event.beat
```

This eliminates a class of calculation errors and reduces storage size.

#### Pitch Expression

```clojure theme={null}
C4.q        ; C4 quarter note
Eb5.h       ; E-flat 5 half note
F#3.e       ; F-sharp 3 eighth note
[C4 E4 G4].q  ; C major triad, quarter note
r.q         ; Quarter rest
```

#### Duration Codes

| Code | Name          | Beats |
| ---- | ------------- | ----- |
| `w`  | Whole         | 4     |
| `h`  | Half          | 2     |
| `q`  | Quarter       | 1     |
| `e`  | Eighth        | 1/2   |
| `s`  | Sixteenth     | 1/4   |
| `t`  | Thirty-second | 1/8   |

Dotted: append `.` (e.g., `q.` = 3/2 beats)
Double-dotted: append `..` (e.g., `q..` = 7/4 beats)

#### Rational Beat Positions

Beat positions MUST be exact rationals. The canonical form is:

```
0           ; Integer
1           ; Integer  
2+1/2       ; Mixed number (two and a half)
0+1/3       ; Fraction (one third)
3+3/4       ; Mixed number (three and three quarters)
```

Decimal literals (e.g., `2.5`) are NOT permitted.

#### Event Properties

```clojure theme={null}
(: 0 G4.q 
  :id #uuid "018c3f2a-..."
  :dyn ff
  :art staccato
  :orn trill
  :tech pizz
  :lyrics [{:text "Hal-" :syllabic begin}])
```

| Property      | Type          | Description               |
| ------------- | ------------- | ------------------------- |
| `:dyn`        | keyword       | Dynamic marking           |
| `:art`        | keyword       | Articulation              |
| `:orn`        | keyword       | Ornament                  |
| `:tech`       | keyword       | Playing technique         |
| `:lyrics`     | list          | Lyric syllables           |
| `:grace`      | boolean       | Grace note flag           |
| `:cue`        | boolean       | Cue note flag             |
| `:cue-source` | instrument-id | Source instrument for cue |

### 4.6 Spans Section

Spans define relationships between events across time.

```clojure theme={null}
(spans
  (slur
    :id #uuid "018c3f2c-0001-..."
    :from #uuid "018c3f2a-0001-..."
    :to #uuid "018c3f2a-0004-...")
  
  (hairpin
    :id #uuid "018c3f2c-0002-..."
    :type crescendo
    :from #uuid "018c3f2a-0001-..."
    :to #uuid "018c3f2a-0008-...")
  
  (beam
    :id #uuid "018c3f2c-0003-..."
    :events [#uuid "018c3f2a-0005-..." 
             #uuid "018c3f2a-0006-..."
             #uuid "018c3f2a-0007-..."]))
```

#### Span Types

| Type         | Endpoint Style | Description              |
| ------------ | -------------- | ------------------------ |
| `slur`       | from/to        | Phrasing slur            |
| `tie`        | from/to        | Tie between same pitches |
| `hairpin`    | from/to        | Crescendo/diminuendo     |
| `beam`       | events list    | Beam grouping            |
| `ottava`     | from/to        | Octave transposition     |
| `pedal`      | from/to        | Piano pedal              |
| `trill-span` | from/to        | Extended trill           |
| `gliss`      | from/to        | Glissando line           |
| `volta`      | from/to        | Ending bracket           |

### 4.7 Tuplet Syntax

```clojure theme={null}
(tuplet 3:2 q
  (: 0 C4.e :id #uuid "...")
  (: 0+1/3 D4.e :id #uuid "...")
  (: 0+2/3 E4.e :id #uuid "..."))
```

### 4.8 Grace Notes

```clojure theme={null}
(grace :type acciaccatura
  (: 0 D5.s :id #uuid "..."))

; Main note that grace attaches to
(: 0 C5.q :id #uuid "...")
```

### 4.9 Directions

```clojure theme={null}
(measure :id #uuid "..." :number 45
  (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)
  
  (flute-1 ...))
```

### 4.10 Movements

```clojure theme={null}
(movements
  (movement 1 :title "Allegro" :key C :mode major :time 4/4
    (measures ...))
  (movement 2 :title "Adagio" :key F :mode major :time 3/4
    (measures ...)))
```

### 4.11 Alternatives (Ossia, Variants)

```clojure theme={null}
(alternatives
  (ossia
    :measures [#uuid "..." #uuid "..."]
    :instrument flute-1
    :label "easier version"
    :content (measures ...))
  (variant
    :measures [#uuid "..."]
    :label "manuscript variant"
    :content ...))
```

### 4.12 Layout Hints (Optional)

Layout hints are NON-NORMATIVE suggestions for rendering engines.

```clojure theme={null}
(layout
  :bar-numbers (every 5)
  
  (break :type system :after #uuid "018c3f40-0008-...")
  (break :type page :after #uuid "018c3f40-0020-...")
  
  (hide-empty-staves true)
  
  (condense 
    :instruments [flute-1 flute-2]
    :measures [#uuid "..." #uuid "..."]
    :label "Fl. 1, 2"))
```

***

## 5. MRS-Ops: The Mutation Protocol

<a id="5-mrs-ops-the-mutation-protocol" />

MRS-Ops is the typed operation protocol for agent mutations. Agents read MRS-S but write MRS-Ops.

### 5.1 Design Rationale

Asking agents to emit complete MRS-S fragments creates failure modes:

* **Accidental omission**: Agent returns less content than given → content deleted
* **Calculation errors**: Miscomputed `:at` values, duration sums
* **Hallucinated references**: IDs that don't exist
* **UUID management**: Agent must generate valid, non-colliding UUIDs

MRS-Ops eliminates these by:

* **Explicit operations**: Create, update, delete are distinct (no omission risk)
* **Orchestrator-derived fields**: Agent provides beat; orchestrator computes `:at`
* **Temporary IDs**: Agent uses tmp-ids; orchestrator assigns UUIDs
* **Minimal surface**: Only changed content in output

### 5.2 Operation Envelope

```clojure theme={null}
(mrs-ops
  :version 1.0
  :scope-hash "sha256:a3f2c1b9e4d7..."
  :base-revision "rev:abc123"
  
  :ops
    (<operation>
     <operation>
     ...))
```

| Field            | Required | Description                                     |
| ---------------- | -------- | ----------------------------------------------- |
| `:version`       | YES      | Protocol version                                |
| `:scope-hash`    | YES      | Hash of source Working Set (conflict detection) |
| `:base-revision` | NO       | Revision ID of source state                     |
| `:ops`           | YES      | List of operations                              |

### 5.3 Operation Types

#### 5.3.1 Create Event

```clojure theme={null}
(create-event
  :tmp-id "e1"
  :measure #uuid "018c3f40-002d-..."
  :instrument flute-1
  :voice v1
  :beat 0
  :pitch C5
  :duration q
  :dyn mp
  :art staccato)
```

| Field            | Required | Description                              |
| ---------------- | -------- | ---------------------------------------- |
| `:tmp-id`        | YES      | Temporary ID (orchestrator maps to UUID) |
| `:measure`       | YES      | Target measure UUID                      |
| `:instrument`    | YES      | Target instrument ID                     |
| `:voice`         | YES      | Target voice                             |
| `:beat`          | YES      | Beat position (rational)                 |
| `:pitch`         | YES      | Pitch or chord or `r` for rest           |
| `:duration`      | YES      | Duration code                            |
| Other properties | NO       | `:dyn`, `:art`, `:orn`, etc.             |

#### 5.3.2 Update Event

```clojure theme={null}
(update-event
  :id #uuid "018c3f2a-0001-..."
  :set
    ((:pitch D5)
     (:dyn f)))
```

| Field  | Required | Description                           |
| ------ | -------- | ------------------------------------- |
| `:id`  | YES      | Existing event UUID                   |
| `:set` | YES      | List of (field value) pairs to update |

#### 5.3.3 Delete Event

```clojure theme={null}
(delete-event
  :id #uuid "018c3f2a-0001-...")
```

#### 5.3.4 Create Span

```clojure theme={null}
(create-span
  :tmp-id "s1"
  :type slur
  :from "e1"        ; Can reference tmp-id or UUID
  :to "e5")
```

Span endpoints can reference:

* Existing UUIDs: `#uuid "018c3f2a-..."`
* Temporary IDs from same operation set: `"e1"`

#### 5.3.5 Update Span

```clojure theme={null}
(update-span
  :id #uuid "018c3f2c-0001-..."
  :set
    ((:style legato)))
```

**Note**: Span endpoints (`:from`, `:to`, `:events`) are immutable after creation. To change endpoints, delete and recreate the span.

#### 5.3.6 Delete Span

```clojure theme={null}
(delete-span
  :id #uuid "018c3f2c-0001-...")
```

#### 5.3.7 Create Measure

```clojure theme={null}
(create-measure
  :tmp-id "m1"
  :after #uuid "018c3f40-0030-..."   ; Insert after this measure
  :time 4/4
  :key C :mode minor)
```

The orchestrator:

* Assigns UUID and `:number`
* Computes `:beat-start` based on position
* Updates subsequent measures if needed

#### 5.3.8 Delete Measure

```clojure theme={null}
(delete-measure
  :id #uuid "018c3f40-0030-...")
```

**Warning**: Deleting a measure deletes all events within it. Spans with endpoints in the deleted measure become invalid.

#### 5.3.9 Instrument Change

```clojure theme={null}
(instrument-change
  :tmp-id "ic1"
  :player woodwind-2
  :measure #uuid "018c3f40-0045-..."
  :beat 0
  :to piccolo)
```

### 5.4 Temporary ID Rules

1. Temporary IDs MUST be strings starting with a letter: `"e1"`, `"span-a"`, `"m1"`
2. Temporary IDs are scoped to a single MRS-Ops envelope
3. Operations within the same envelope MAY reference each other's tmp-ids
4. The orchestrator maps all tmp-ids to UUIDs before application
5. Responses include the tmp-id → UUID mapping

### 5.5 Operation Ordering

Operations are applied in order. Dependencies must be respected:

* Create measure before creating events in it
* Create events before creating spans that reference them

The orchestrator MAY reorder operations to satisfy dependencies if unambiguous.

### 5.6 Example: Add Countermelody

Agent receives Working Set with clarinet part (empty) and violin melody (in context).

Agent returns:

```clojure theme={null}
(mrs-ops
  :version 1.0
  :scope-hash "sha256:a3f2c1b9e4d7..."
  
  :ops
    ((create-event :tmp-id "e1" :measure #uuid "018c3f40-002d-..." 
                   :instrument clarinet-bb :voice v1
                   :beat 0 :pitch Eb4 :duration q :dyn mp)
     (create-event :tmp-id "e2" :measure #uuid "018c3f40-002d-..."
                   :instrument clarinet-bb :voice v1
                   :beat 1 :pitch D4 :duration q)
     (create-event :tmp-id "e3" :measure #uuid "018c3f40-002d-..."
                   :instrument clarinet-bb :voice v1
                   :beat 2 :pitch Eb4 :duration e)
     (create-event :tmp-id "e4" :measure #uuid "018c3f40-002d-..."
                   :instrument clarinet-bb :voice v1
                   :beat 2+1/2 :pitch F4 :duration e)
     (create-event :tmp-id "e5" :measure #uuid "018c3f40-002d-..."
                   :instrument clarinet-bb :voice v1
                   :beat 3 :pitch G4 :duration q)
     
     (create-span :tmp-id "s1" :type slur :from "e1" :to "e5")))
```

Orchestrator response:

```clojure theme={null}
(mrs-ops-result
  :status success
  :id-mapping
    (("e1" #uuid "019b2c3d-0001-...")
     ("e2" #uuid "019b2c3d-0002-...")
     ("e3" #uuid "019b2c3d-0003-...")
     ("e4" #uuid "019b2c3d-0004-...")
     ("e5" #uuid "019b2c3d-0005-...")
     ("s1" #uuid "019b2c3d-0010-..."))
  :applied 6
  :revision "rev:def456")
```

***

## 6. Players, Instruments, and Staves

<a id="6-players-instruments-and-staves" />

MRS uses a three-level model for professional orchestration semantics.

### 6.1 The Model

```
Player (performer)
  └── Instruments (what they can play)
        └── Staves (visual representation)
```

**Player**: A human performer. May play multiple instruments (doubling).

**Instrument**: A specific sound source with fixed transposition, range, and technique set.

**Staff**: Visual representation. An instrument may use multiple staves (piano) or share a staff (condensed scores).

### 6.2 Players Section

```clojure theme={null}
(players
  (player woodwind-2
    :name "Flute 2 / Piccolo"
    :instruments [flute-2 piccolo]
    :default flute-2)
  
  (player clarinet-1
    :name "Clarinet 1"
    :instruments [clarinet-bb clarinet-a]
    :default clarinet-bb)
  
  (player percussion-1
    :name "Percussion 1"
    :instruments [snare timpani triangle]
    :default snare))
```

| Attribute      | Required | Description                             |
| -------------- | -------- | --------------------------------------- |
| `:name`        | YES      | Display name                            |
| `:instruments` | YES      | List of instrument IDs this player uses |
| `:default`     | YES      | Default/starting instrument             |

### 6.3 Instruments Section

```clojure theme={null}
(instruments
  (instrument flute-1
    :name "Flute"
    :abbr "Fl. 1"
    :family woodwinds
    :staves [treble]
    :transposition none
    :range [C4 D7])
  
  (instrument piccolo
    :name "Piccolo"
    :abbr "Picc."
    :family woodwinds
    :staves [treble]
    :transposition (up P8)
    :range [D5 C8])
  
  (instrument clarinet-bb
    :name "Clarinet in Bb"
    :abbr "Cl."
    :family woodwinds
    :staves [treble]
    :transposition (down M2)
    :range [E3 C7])
  
  (instrument clarinet-a
    :name "Clarinet in A"
    :abbr "Cl."
    :family woodwinds
    :staves [treble]
    :transposition (down m3)
    :range [Eb3 B6])
  
  (instrument piano
    :name "Piano"
    :abbr "Pno."
    :family keyboards
    :staves [treble bass]
    :transposition none
    :range [A0 C8]
    :staff-connect brace))
```

| Attribute        | Required | Description                      |
| ---------------- | -------- | -------------------------------- |
| `:name`          | YES      | Full display name                |
| `:abbr`          | YES      | Abbreviated name                 |
| `:family`        | YES      | Instrument family                |
| `:staves`        | YES      | List of staff clefs              |
| `:transposition` | YES      | Transposition interval or `none` |
| `:range`         | NO       | Playable range \[low high]       |
| `:staff-connect` | NO       | `brace`, `bracket`, `line`       |

### 6.4 Transposition Specification

```clojure theme={null}
none                  ; Concert pitch
(up P8)               ; Sounds octave higher (piccolo)
(down M2)             ; Sounds major 2nd lower (Bb clarinet)
(down m3)             ; Sounds minor 3rd lower (A clarinet)
(down P5)             ; Sounds perfect 5th lower (English horn)
```

### 6.5 Instrument Changes

When a player switches instruments mid-score:

```clojure theme={null}
(measure :id #uuid "..." :number 45
  (woodwind-2
    (instrument-change :to piccolo :beat 0)
    (v1
      (: 0 D6.q :id #uuid "...")
      ...)))
```

The orchestrator:

* Validates the player owns the target instrument
* Handles transposition changes automatically
* Updates display (instrument name in score)

### 6.6 Percussion Kits

```clojure theme={null}
(instrument snare-kit
  :name "Snare Drum Kit"
  :abbr "S.D."
  :family percussion
  :staves [percussion]
  :transposition none
  :kit
    ((snare :line 0 :notehead normal)
     (rim :line 0 :notehead x)
     (stick :line 2 :notehead x)))

(instrument drum-kit
  :name "Drum Kit"
  :abbr "Dr."
  :family percussion
  :staves [percussion]
  :transposition none
  :kit
    ((kick :line -2 :notehead normal)
     (snare :line 0 :notehead normal)
     (hi-hat :line 2 :notehead x)
     (crash :line 4 :notehead x-circle)))
```

### 6.7 Referencing in Measures

In measure content, use **instrument ID** (not player ID):

```clojure theme={null}
(measure :id #uuid "..." :number 1
  (flute-1
    (v1 (: 0 C5.q :id #uuid "...")))
  
  (piccolo    ; After instrument change
    (v1 (: 0 D6.q :id #uuid "...")))
  
  (piano
    (:rh (v1 (: 0 [C4 E4 G4].q :id #uuid "...")))
    (:lh (v1 (: 0 C3.q :id #uuid "...")))))
```

***

## 7. Working Set Envelope

<a id="7-working-set-envelope" />

The Working Set Envelope provides agents with bounded MRS-S content plus task-appropriate context.

### 7.1 Envelope Structure

```clojure theme={null}
(working-set
  :version 1.0
  :source-hash "sha256:a3f2c1b9e4d7..."
  
  :scope
    (:measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0034-...")
    (:instruments [clarinet-bb])
    (:voices [v1])
  :display-hint (:measures 45 52)
  
  :bundle orchestrate
  :allowed-ops [create-event update-event delete-event create-span delete-span]
  
  :task "Add clarinet countermelody responding to violin theme"
  
  :constraints
    ((range clarinet-bb E3 C7)
     (avoid parallel-fifths violin-1))
  
  :content
    (meta
      :time 4/4
      :key C :mode minor
      :tempo 132)
    
    (instruments
      (instrument clarinet-bb :name "Clarinet in Bb" :abbr "Cl." 
                  :staves [treble] :transposition (down M2)))
    
    (measures
      (measure 
        :id #uuid "018c3f40-002d-..."
        :number 45
        :beat-start 487
        (clarinet-bb
          (v1))))  ; Empty — target for agent
    
    (spans)
  
  :context-views
    <task-adaptive-context>
  
  :structural-index-ref "sha256:abc123..."
  
  :available-queries
    [:melodic-content :harmonic-analysis :orchestration-density])
```

### 7.2 Envelope Fields

#### Required Fields

| Field          | Type       | Description                                  |
| -------------- | ---------- | -------------------------------------------- |
| `:version`     | decimal    | Envelope version (1.0)                       |
| `:source-hash` | string     | SHA-256 hash of source state                 |
| `:scope`       | scope-spec | What the agent may modify                    |
| `:content`     | MRS-S      | The score fragment (readable, target of ops) |

#### Scope Specification

```clojure theme={null}
:scope
  (:measures #uuid "..." #uuid "...")   ; UUID range (inclusive)
  (:instruments [clarinet-bb flute-1])  ; Instruments included
  (:voices [v1 v2])                     ; Optional: specific voices
:display-hint (:measures 45 52)         ; Human-readable, informational
```

Scope uses UUIDs for structural stability. Display hints are for human orientation only.

#### Permission Fields

| Field          | Description                                |
| -------------- | ------------------------------------------ |
| `:bundle`      | Lane bundle granting permissions           |
| `:allowed-ops` | Explicit list of permitted operation types |

#### Optional Fields

| Field                   | Type   | Description                         |
| ----------------------- | ------ | ----------------------------------- |
| `:task`                 | string | Natural language task description   |
| `:constraints`          | list   | Validation rules agent must satisfy |
| `:context-views`        | list   | Task-adaptive context (see §8)      |
| `:structural-index-ref` | string | Hash reference to structural index  |
| `:available-queries`    | list   | Queries agent may request           |

### 7.3 Content Self-Containment

The `:content` of a Working Set Envelope MUST be parseable as standalone MRS-S:

* Instrument 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

### 7.4 Boundary-Crossing Spans

When a span crosses the envelope boundary:

```clojure theme={null}
(slur
  :id #uuid "018c3f2c-..."
  :from #uuid "018c3f2a-..."    ; Inside scope
  :to #uuid "018c3f2b-..."      ; Outside scope
  :boundary-exit true)          ; Marks endpoint outside
```

Boundary-marked spans are **read-only** at their boundary endpoints. Agents MAY NOT modify `:from`, `:to`, or `:events` of boundary-marked spans.

***

## 8. Task-Adaptive Context Views

<a id="8-task-adaptive-context-views" />

Context views provide task-relevant information beyond the edit scope. Unlike fixed "near/far" rings, views are selected and shaped for the specific task.

### 8.1 Design Rationale

Different tasks need different context:

* **Countermelody**: The melody being responded to, harmonic rhythm
* **Orchestration**: What other instruments are playing, texture density
* **Dynamics**: Phrase structure, existing dynamics, climax points
* **Slur shaping**: Articulation context, phrase groupings

Fixed rings waste tokens on irrelevant content and may omit critical content. Task-adaptive views provide what's actually needed.

### 8.2 Context View Types

#### 8.2.1 Melodic Reference

Provides the melody line(s) the agent should respond to:

```clojure theme={null}
(context-view melodic-reference
  :instruments [violin-1]
  :measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0034-..."
  :reduction melody-only
  :content
    (measures
      (measure :id #uuid "..." :number 45
        (violin-1
          (v1
            (: 0 G5.q :id #uuid "...")
            (: 1 A5.e :id #uuid "...")
            ...)))))
```

#### 8.2.2 Harmonic Context

Provides harmonic information (chord symbols, key areas):

```clojure theme={null}
(context-view harmonic-context
  :measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0034-..."
  :content
    (harmony-events
      (chord :measure #uuid "..." :beat 0 :symbol Cm :function i)
      (chord :measure #uuid "..." :beat 2 :symbol Fm :function iv)
      (chord :measure #uuid "..." :beat 0 :symbol G7 :function V7)))
```

#### 8.2.3 Orchestration Map

Shows what instruments are active and their texture:

```clojure theme={null}
(context-view orchestration-map
  :measures #uuid "018c3f40-002d-..." #uuid "018c3f40-0034-..."
  :content
    (texture-regions
      (region :measures [#uuid "..." #uuid "..."]
              :active [violin-1 violin-2 viola cello]
              :density medium
              :character "lyrical strings")))
```

#### 8.2.4 Phrase Structure

Provides phrase boundaries and form:

```clojure theme={null}
(context-view phrase-structure
  :content
    (phrases
      (phrase :start #uuid "..." :end #uuid "..." :type antecedent)
      (phrase :start #uuid "..." :end #uuid "..." :type consequent)))
```

#### 8.2.5 Dynamics Profile

Provides dynamics trajectory:

```clojure theme={null}
(context-view dynamics-profile
  :measures #uuid "..." #uuid "..."
  :content
    (dynamics-arc
      (point :measure #uuid "..." :beat 0 :level p)
      (point :measure #uuid "..." :beat 0 :level f)
      (point :measure #uuid "..." :beat 0 :level pp)))
```

#### 8.2.6 Thematic References

Provides motif/theme information:

```clojure theme={null}
(context-view thematic-references
  :content
    (themes
      (theme :id theme-a :label "Main theme"
             :exemplar #uuid "018c3f40-0001-..."
             :occurrences [#uuid "..." #uuid "..." #uuid "..."])
      (theme :id theme-b :label "Second theme"
             :exemplar #uuid "018c3f40-0020-...")))
```

### 8.3 View Selection by Task Type

The orchestrator selects context views based on task type:

| Task Type       | Typical Context Views                                   |
| --------------- | ------------------------------------------------------- |
| `compose`       | phrase-structure, harmonic-context, thematic-references |
| `countermelody` | melodic-reference, harmonic-context, phrase-structure   |
| `orchestrate`   | orchestration-map, dynamics-profile, melodic-reference  |
| `harmonize`     | melodic-reference, phrase-structure                     |
| `dynamics`      | phrase-structure, dynamics-profile, orchestration-map   |
| `articulate`    | phrase-structure, melodic-reference                     |

### 8.4 Available Queries

Agents may request additional context via queries:

```clojure theme={null}
:available-queries
  [:melodic-content    ; Request melody from specific instruments
   :harmonic-analysis  ; Request harmony analysis
   :orchestration-density ; Request texture information
   :phrase-boundaries  ; Request phrase structure
   :thematic-occurrences] ; Request theme locations
```

Query request (in agent response):

```clojure theme={null}
(query-request
  :type melodic-content
  :instruments [oboe-1]
  :measures #uuid "..." #uuid "..."
  :reason "Need oboe line to avoid doubling")
```

The orchestrator may grant or deny queries based on scope and permissions.

***

## 9. Structural Index

<a id="9-structural-index" />

The Structural Index provides global awareness without loading the full score.

### 9.1 Index Structure

```clojure theme={null}
(structural-index
  :hash "sha256:abc123..."
  :source-hash "sha256:def456..."
  
  :form
    (sections
      (section :type exposition :measures #uuid "..." #uuid "..." :display [1 64])
      (section :type development :measures #uuid "..." #uuid "..." :display [65 120])
      (section :type recapitulation :measures #uuid "..." #uuid "..." :display [121 180]))
  
  :key-areas
    ((region :key C :mode minor :measures #uuid "..." #uuid "...")
     (region :key Eb :mode major :measures #uuid "..." #uuid "...")
     (region :key G :mode minor :measures #uuid "..." #uuid "..."))
  
  :tempo-map
    ((tempo :bpm 120 :measures #uuid "..." #uuid "...")
     (tempo :bpm 80 :text "Adagio" :measures #uuid "..." #uuid "..."))
  
  :players-summary
    ((player woodwind-2 :instruments [flute-2 piccolo] :active-measures [...])
     (player clarinet-1 :instruments [clarinet-bb] :active-measures [...]))
  
  :rehearsal-marks
    ((mark "A" :measure #uuid "..." :number 16)
     (mark "B" :measure #uuid "..." :number 32))
  
  :total-measures 180
  :total-duration "12:34")
```

### 9.2 Index Fields

| Field              | Description                                         |
| ------------------ | --------------------------------------------------- |
| `:form`            | Structural sections (exposition, development, etc.) |
| `:key-areas`       | Key signature regions                               |
| `:tempo-map`       | Tempo changes                                       |
| `:players-summary` | Players and their activity                          |
| `:rehearsal-marks` | Rehearsal mark locations                            |
| `:total-measures`  | Total measure count                                 |
| `:total-duration`  | Approximate duration                                |

### 9.3 Index Derivation

The structural index can be:

* **Derived automatically** from the score (partial)
* **Enhanced by overlays** (harmonic analysis, thematic analysis)
* **Manually annotated** (form labels, section names)

***

## 10. Analytical Overlays

<a id="10-analytical-overlays" />

Overlays attach analytical metadata to score regions without modifying the score itself.

### 10.1 Overlay Structure

```clojure theme={null}
(overlays
  (overlay :id harmonic-analysis
    :type harmonic
    :author "harmony-agent"
    :created "2026-01-17T10:30:00Z"
    
    :regions
      ((region :measures #uuid "..." #uuid "..."
               :content
                 (chord :beat 0 :symbol Cm :function i)
                 (chord :beat 2 :symbol Fm :function iv))))
  
  (overlay :id motivic-analysis
    :type thematic
    :author "analysis-agent"
    
    :themes
      ((theme :id theme-a :label "Main theme"
              :first-occurrence #uuid "..."
              :characteristics "descending fourth, dotted rhythm"))))
```

### 10.2 Overlay Types

| Type            | Purpose                                       |
| --------------- | --------------------------------------------- |
| `harmonic`      | Chord symbols, Roman numerals, functions      |
| `thematic`      | Motifs, themes, their occurrences             |
| `form`          | Structural analysis (phrase, period, section) |
| `voice-leading` | Part writing analysis                         |
| `performance`   | Performance annotations                       |

### 10.3 Overlay Lifecycle

Overlays may be:

* **Persistent**: Stored with the score
* **Session**: Valid only for current editing session
* **Derived**: Recomputed after score changes

***

## 11. Data Model

<a id="11-data-model" />

### 11.1 Core Types

```
Score
├── meta: Metadata
├── players: List<Player>
├── instruments: List<Instrument>
├── measures: List<Measure>
├── spans: List<Span>
├── overlays: List<Overlay>?
├── structural-index: StructuralIndex?
└── alternatives: List<Alternative>?

Player
├── id: Identifier
├── name: String
├── instruments: List<InstrumentId>
└── default: InstrumentId

Instrument
├── id: Identifier
├── name: String
├── abbr: String
├── family: InstrumentFamily
├── staves: List<Clef>
├── transposition: Interval | none
├── range: [Pitch, Pitch]?
└── kit: List<KitItem>?  (percussion only)

Measure
├── id: UUIDv7
├── number: Integer
├── beat-start: Rational  (orchestrator-computed)
├── time: TimeSignature?
├── key: PitchClass?
├── mode: Mode?
├── tempo: Integer?
├── tempo-text: String?
├── rehearsal: String?
├── barline-left: BarlineType?
├── barline-right: BarlineType?
├── directions: List<Direction>
└── content: Map<InstrumentId, InstrumentContent>

Event
├── beat: Rational
├── pitch: PitchExpr
├── id: UUIDv7
├── dyn: Dynamic?
├── art: Articulation?
├── orn: Ornament?
├── tech: Technique?
├── lyrics: List<LyricSyllable>?
└── ...other properties

Span
├── id: UUIDv7
├── type: SpanType
├── from: UUIDv7?
├── to: UUIDv7?
├── events: List<UUIDv7>?
├── boundary-entry: Boolean?
├── boundary-exit: Boolean?
└── ...type-specific attributes
```

### 11.2 Identifier Rules

1. **UUIDs**: All measures, events, and spans carry UUIDv7 identifiers under `:id`
2. **Instrument IDs**: Match regex `[a-z][a-z0-9-]*` (e.g., `flute-1`, `clarinet-bb`)
3. **Player IDs**: Match regex `[a-z][a-z0-9-]*` (e.g., `woodwind-2`, `percussion-1`)
4. **Voice IDs**: `v1` through `v4`, or `:rh`/`:lh` for keyboard
5. **Temporary IDs**: Strings starting with letter, scoped to operation envelope

### 11.3 Immutability Rules

Once assigned:

* `:id` is immutable for the lifetime of the object
* Span endpoints (`:from`, `:to`, `:events`) are immutable
* Measure `:beat-start` is orchestrator-managed (not directly editable)

### 11.4 Rational Number Representation

All temporal positions use exact rationals:

```
Canonical forms:
  0, 1, 2, ...       (integers)
  2+1/2              (two and a half)
  0+1/3              (one third)
  3+3/4              (three and three quarters)

NOT permitted:
  2.5                (decimal)
  0.333              (decimal)
```

Implementations MUST treat rationals as exact; no floating-point approximation.

***

## 12. Orchestrator Contract

<a id="12-orchestrator-contract" />

The orchestrator is the central coordinator that makes AI-assisted composition and orchestration safe and reliable.

### 12.1 Orchestrator Responsibilities

| Responsibility     | Description                                                |
| ------------------ | ---------------------------------------------------------- |
| UUID minting       | Maps tmp-ids to UUIDs; sole authority for ID creation      |
| Derived fields     | Computes `:beat-start`, reconciles inherited state         |
| Validation         | Progressive validation of all operations                   |
| State management   | Maintains canonical score state; applies validated changes |
| Context generation | Creates task-adaptive context views                        |
| Conflict detection | Uses source-hash to detect concurrent modifications        |
| Audit trail        | Records all changes with attribution                       |

### 12.2 Edit Lanes

Lanes are permission boundaries that determine what an agent may modify.

| Lane          | Owns                              |
| ------------- | --------------------------------- |
| `structure`   | Measure list, sections, movements |
| `temporal`    | Tempo map, time signatures        |
| `harmonyPlan` | Chord symbols, harmonic analysis  |
| `notes`       | Pitches, durations, rests         |
| `expression`  | Dynamics, hairpins, slurs         |
| `technique`   | Articulations, playing techniques |
| `lyrics`      | Lyrics, syllables                 |

### 12.3 Lane Bundles

Common workflows grant multiple related lanes:

```clojure theme={null}
(define-bundle orchestrate
  :lanes [notes expression technique]
  :description "Full orchestration pass")

(define-bundle dynamics-pass
  :lanes [expression]
  :description "Dynamics and phrasing")

(define-bundle notation-cleanup
  :lanes [notes technique]
  :description "Fix notation issues")

(define-bundle full-compose
  :lanes [structure temporal harmonyPlan notes expression technique]
  :description "Full compositional control")
```

### 12.4 Conflict Detection

The orchestrator uses source-hash to detect conflicts:

```
1. Working Set created with source-hash H1
2. Agent produces operations
3. Before applying, orchestrator checks current hash
4. If current hash ≠ H1, conflict detected
5. Options: reject, rebase, merge (policy-dependent)
```

### 12.5 Transaction Model

```clojure theme={null}
(transaction
  :id #uuid "..."
  :timestamp "2026-01-17T10:30:00Z"
  :agent "countermelody-agent"
  :source-hash "sha256:..."
  :result-hash "sha256:..."
  :ops-applied 6
  :scope (:measures #uuid "..." #uuid "..." :instruments [clarinet-bb])
  :bundle orchestrate)
```

All changes are recorded in an append-only transaction log.

### 12.6 Checkpoints and Locks

Lock approved decisions to prevent regression:

```clojure theme={null}
(checkpoint
  :id "harmony-approved"
  :created "2026-01-17T10:30:00Z"
  :approved-by "composer"
  :locks
    ((structure :scope :all)
     (harmonyPlan :scope :all)))
```

After checkpoint, agents cannot modify locked lanes.

***

## 13. Progressive Validation

<a id="13-progressive-validation" />

Operations are validated in stages before application.

### 13.1 Validation Pipeline

```
┌─────────────┐   ┌─────────────┐   ┌─────────────┐   ┌─────────────┐
│   Syntax    │ → │ References  │ → │ Permissions │ → │  Musical    │
│ Validation  │   │ Validation  │   │ Validation  │   │  Rules      │
└─────────────┘   └─────────────┘   └─────────────┘   └─────────────┘
                                                              │
                                                              ▼
                                                      ┌─────────────┐
                                                      │ Application │
                                                      └─────────────┘
```

### 13.2 Validation Stages

#### Stage 1: Syntax Validation

* Operation is well-formed
* Required fields present
* Types correct

#### Stage 2: Reference Validation

* All referenced UUIDs exist in source
* All tmp-ids are unique within envelope
* Cross-references between ops are valid

#### Stage 3: Permission Validation

* Operation within granted lanes
* Operation within granted scope
* Operation type is allowed

#### Stage 4: Musical Rule Validation

* Constraints satisfied (range, avoid parallel fifths, etc.)
* Duration sums correct
* Ties connect same pitches

### 13.3 Validation Results

```clojure theme={null}
(validation-result
  :status rejected
  :stage permissions
  :errors
    ((error :op 3 :code PERM-001 
            :message "Operation modifies 'structure' lane, not granted"
            :detail (:op-type create-measure :granted-lanes [notes expression]))))
```

### 13.4 Partial Application

When some operations fail validation:

```clojure theme={null}
(mrs-ops-result
  :status partial
  :applied 4
  :rejected 2
  :id-mapping (...)
  :errors
    ((error :op 5 :code MUSIC-001 :message "Tie connects different pitches")
     (error :op 6 :code REF-001 :message "Span references non-existent tmp-id 'e99'")))
```

The orchestrator MAY apply valid operations and reject invalid ones, or reject the entire batch (configurable policy).

### 13.5 Validation Rules

#### Structural Rules

| Rule       | Severity | Description                    |
| ---------- | -------- | ------------------------------ |
| STRUCT-001 | ERROR    | Duplicate UUIDs                |
| STRUCT-002 | ERROR    | Invalid measure numbers        |
| STRUCT-003 | ERROR    | Beat position out of bounds    |
| STRUCT-004 | ERROR    | Reference to non-existent UUID |
| STRUCT-005 | WARNING  | Gap in measure numbering       |

#### Musical Rules

| Rule      | Severity | Description                         |
| --------- | -------- | ----------------------------------- |
| MUSIC-001 | ERROR    | Tie connects different pitches      |
| MUSIC-002 | ERROR    | Duration overflow (exceeds measure) |
| MUSIC-003 | WARNING  | Pitch out of instrument range       |
| MUSIC-004 | WARNING  | Parallel fifths/octaves             |
| MUSIC-005 | WARNING  | Voice crossing                      |

#### Permission Rules

| Rule     | Severity | Description                     |
| -------- | -------- | ------------------------------- |
| PERM-001 | ERROR    | Operation outside granted lanes |
| PERM-002 | ERROR    | Operation outside granted scope |
| PERM-003 | ERROR    | Operation type not allowed      |
| PERM-004 | ERROR    | Modifying locked lane           |

***

## 14. Query Resolution

<a id="14-query-resolution" />

The orchestrator translates human-friendly references to UUIDs.

### 14.1 Query Types

**Measure number resolution:**

```clojure theme={null}
(query :type resolve :human-ref (:measure-number 45)
       :response (:id #uuid "018c3f40-002d-..." :number 45))
```

**Rehearsal mark resolution:**

```clojure theme={null}
(query :type resolve :human-ref (:rehearsal "B")
       :response (:id #uuid "018c3f40-0020-..." :number 32))
```

**Rehearsal mark with offset:**

```clojure theme={null}
(query :type resolve :human-ref (:rehearsal "B" :offset 4)
       :response (:id #uuid "018c3f40-0024-..." :number 36))
```

**Range resolution:**

```clojure theme={null}
(query :type resolve-range :human-ref (:measures 45 52)
       :response (:from #uuid "018c3f40-002d-..." :to #uuid "018c3f40-0034-..."))
```

### 14.2 Reverse Resolution

UUID to display information:

```clojure theme={null}
(query :type display-info :id #uuid "018c3f40-002d-..."
       :response (:number 45 :rehearsal "C" :beat-start 487))
```

***

## 15. Extension Mechanisms

<a id="15-extension-mechanisms" />

### 15.1 Custom Properties

Events, spans, and directions support custom properties with `x-` prefix:

```clojure theme={null}
(: 0 C4.q 
  :id #uuid "..."
  :dyn f
  :x-source "manuscript-page-47"
  :x-confidence 0.85)
```

### 15.2 Namespace Extensions

```clojure theme={null}
(: 0 C4.q
  :id #uuid "..."
  :analysis:roman-numeral "I"
  :analysis:function "tonic"
  :mei:xml-id "note-001")
```

| Namespace    | Purpose                 |
| ------------ | ----------------------- |
| `x-*`        | Unregistered extensions |
| `analysis:*` | Music theory analysis   |
| `mei:*`      | MEI compatibility       |
| `midi:*`     | MIDI-specific data      |
| `render:*`   | Rendering hints         |
| `edit:*`     | Editorial metadata      |

***

## 16. MIME Types and File Extensions

<a id="16-mime-types-and-file-extensions" />

### 16.1 MIME Types

| Format               | MIME Type                           |
| -------------------- | ----------------------------------- |
| MRS-S                | `application/vnd.mrs+sexpr`         |
| MRS-Ops              | `application/vnd.mrs-ops+sexpr`     |
| Working Set Envelope | `application/vnd.mrs-workset+sexpr` |

### 16.2 File Extensions

| Format      | Extension                            |
| ----------- | ------------------------------------ |
| MRS-S       | `.mrs` or `.mrs-s`                   |
| MRS-Ops     | `.mrs-ops` (typically ephemeral)     |
| Working Set | `.mrs-workset` (typically ephemeral) |

### 16.3 Encoding

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

***

## 17. Security Considerations

<a id="17-security-considerations" />

### 17.1 Input Validation

Parsers MUST validate:

* Maximum document size
* Maximum nesting depth
* Maximum event count per measure
* Valid Unicode in strings

### 17.2 Denial of Service Protection

Implementations SHOULD protect against:

* Deeply nested structures
* Very large measure numbers
* Excessive span counts
* Malformed UTF-8

### 17.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 id="appendix-a-complete-grammar" />

### A.1 MRS-S Key Productions

```peg theme={null}
document     <- '(' 'mrs-s' version meta players instruments measures spans 
                overlays? structural-index? alternatives? layout? ')'

meta         <- '(' 'meta' metadata-fields ')'
players      <- '(' 'players' player* ')'
instruments  <- '(' 'instruments' instrument* ')'
measures     <- '(' 'measures' measure* ')' | '(' 'movements' movement* ')'
spans        <- '(' 'spans' span* ')'

player       <- '(' 'player' identifier ':name' STRING ':instruments' '[' identifier* ']' 
                ':default' identifier ')'
instrument   <- '(' 'instrument' identifier instrument-attrs ')'

measure      <- '(' 'measure' ':id' uuid ':number' INT measure-attrs* 
                direction* instrument-content* ')'
event        <- '(' ':' beat pitch-expr ':id' uuid properties* ')'

pitch        <- STEP ACCIDENTAL? OCTAVE '.' DURATION DOTS?
chord        <- '[' pitch+ ']' '.' DURATION DOTS?
rest         <- 'r' '.' DURATION DOTS?

span         <- '(' span-type ':id' uuid span-endpoints attributes* ')'

uuid         <- '#uuid' '"' UUID-STRING '"'
rational     <- INT (('+' INT '/' INT) | ('/' INT))?
beat         <- rational
```

### A.2 MRS-Ops Key Productions

```peg theme={null}
ops-envelope <- '(' 'mrs-ops' ':version' DECIMAL ':scope-hash' STRING 
                ':ops' '(' operation* ')' ')'

operation    <- create-event | update-event | delete-event |
                create-span | update-span | delete-span |
                create-measure | delete-measure |
                instrument-change

create-event <- '(' 'create-event' ':tmp-id' STRING 
                ':measure' uuid ':instrument' identifier ':voice' voice-id
                ':beat' rational ':pitch' pitch-expr ':duration' duration
                properties* ')'

update-event <- '(' 'update-event' ':id' uuid ':set' '(' set-pair* ')' ')'
delete-event <- '(' 'delete-event' ':id' uuid ')'

create-span  <- '(' 'create-span' ':tmp-id' STRING ':type' span-type 
                ':from' ref ':to' ref attributes* ')'

ref          <- uuid | STRING  ; UUID or tmp-id
```

***

## Appendix B: Quick Reference

<a id="appendix-b-quick-reference" />

### B.1 Duration Codes

| Code | Name      | Beats |
| ---- | --------- | ----- |
| `w`  | Whole     | 4     |
| `h`  | Half      | 2     |
| `q`  | Quarter   | 1     |
| `e`  | Eighth    | 1/2   |
| `s`  | Sixteenth | 1/4   |
| `t`  | 32nd      | 1/8   |
| `x`  | 64th      | 1/16  |

### B.2 Dynamics

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

### B.3 Articulations

```
staccato staccatissimo tenuto accent marcato
portato stress fermata breath caesura
```

### B.4 Ornaments

```
trill mordent mordent-inverted
turn turn-inverted tremolo
arpeggio glissando
```

### B.5 Lane Bundles

| Bundle             | Lanes                                                          |
| ------------------ | -------------------------------------------------------------- |
| `orchestrate`      | notes, expression, technique                                   |
| `dynamics-pass`    | expression                                                     |
| `notation-cleanup` | notes, technique                                               |
| `full-compose`     | structure, temporal, harmonyPlan, notes, expression, technique |

### B.6 Context View Types

| View                  | Purpose                     |
| --------------------- | --------------------------- |
| `melodic-reference`   | Melody to respond to        |
| `harmonic-context`    | Chord progression           |
| `orchestration-map`   | Active instruments, texture |
| `phrase-structure`    | Phrase boundaries           |
| `dynamics-profile`    | Dynamics trajectory         |
| `thematic-references` | Themes and motifs           |

***

## Appendix C: Glossary

<a id="appendix-c-glossary" />

| Term                       | Definition                                             |
| -------------------------- | ------------------------------------------------------ |
| **Agent**                  | An AI system that operates on MRS documents            |
| **Context View**           | Task-adaptive information beyond the edit scope        |
| **Event**                  | An atomic musical occurrence with UUID identity        |
| **Instrument**             | A specific sound source with fixed transposition/range |
| **Lane**                   | A permission boundary for a category of content        |
| **Lane Bundle**            | A predefined set of lanes for common workflows         |
| **Measure**                | A metrical unit with UUID identity                     |
| **MRS-Ops**                | Typed operation protocol for agent mutations           |
| **MRS-S**                  | Canonical storage format (S-expression based)          |
| **Orchestrator**           | System that owns canonical state and applies changes   |
| **Overlay**                | Analytical metadata attached to score regions          |
| **Player**                 | A performer who may play multiple instruments          |
| **Progressive Validation** | Multi-stage validation before state mutation           |
| **Scope**                  | UUID-based boundaries of a Working Set                 |
| **Span**                   | A relation connecting multiple events                  |
| **Structural Index**       | Compressed global view of the score                    |
| **Temporary ID**           | Agent-assigned ID mapped to UUID by orchestrator       |
| **Working Set**            | Bounded MRS-S fragment with task-adaptive context      |

***

*End of Specification*
