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

# Orchestrator Contract

> Validation, transactions, conflict detection, and the single-writer pattern.

The orchestrator is the central coordinator that makes AI-assisted composition and orchestration safe and reliable at scale. It maintains the canonical score state and mediates all agent operations through progressive validation and typed operations.

**Core principle**: Agents read MRS-S; agents write MRS-Ops. Only the orchestrator applies changes to canonical state.

See: [`/MRS-Specification-RFC#12-orchestrator-contract`](/MRS-Specification-RFC#12-orchestrator-contract)

## Orchestrator Architecture

```
         ORCHESTRATOR (owns canonical score state)
                │
    ┌───────────┼───────────┬───────────┐
    ▼           ▼           ▼           ▼
 Harmony    Melody      Orch.      Expression
  Agent      Agent      Agent        Agent
    │           │           │           │
    └───────────┴───────────┴───────────┘
                │
         Working Set Envelopes
         (scoped MRS-S + context views + lane bundles)
```

## Orchestrator Responsibilities

| Responsibility                 | Description                                                    |
| ------------------------------ | -------------------------------------------------------------- |
| **UUID minting**               | Maps tmp-ids to UUIDs; sole authority for ID creation          |
| **Derived fields**             | Computes `:beat-start`, `:at`, reconciles inherited state      |
| **Progressive validation**     | Validates operations in stages before application              |
| **Canonical state management** | Maintains canonical score semantics; 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                           |

**Implementation note**: “Canonical state” is a semantic concept. An orchestrator may store it as an MRS-S document, an event log plus snapshots, or a database/graph model with indexes. The contract is about behavior: deterministic application, validation, and exportable/auditable semantics.

## 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                 |

### What Each Lane Controls

| Lane          | Can Create/Modify                            | Cannot Touch       |
| ------------- | -------------------------------------------- | ------------------ |
| `structure`   | Measures, sections, movements, repeats       | Event content      |
| `temporal`    | Tempo, time signatures, metric modulations   | Notes, spans       |
| `harmonyPlan` | Chord symbols, key areas, harmonic rhythm    | Note pitches       |
| `notes`       | Pitches, durations, rests, voice assignment  | Dynamics, slurs    |
| `expression`  | Dynamics, hairpins, slurs, phrasing          | Pitches, technique |
| `technique`   | Articulations, playing techniques, ornaments | Pitches, dynamics  |
| `lyrics`      | Lyric text, syllabification, alignment       | Pitches            |

## 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")

(define-bundle lyrics-pass
  :lanes [lyrics]
  :description "Lyric writing and alignment")
```

### Bundle Selection by Task Type

| Task Type             | Recommended Bundle        |
| --------------------- | ------------------------- |
| Compose melody        | `notes` or `full-compose` |
| Add countermelody     | `orchestrate`             |
| Orchestrate sketch    | `orchestrate`             |
| Add dynamics          | `dynamics-pass`           |
| Shape phrases (slurs) | `expression`              |
| Add articulations     | `technique`               |
| Write lyrics          | `lyrics-pass`             |
| Fix notation          | `notation-cleanup`        |

## Progressive Validation

Operations are validated in stages before application:

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

### 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)
* Duration sums correct
* Ties connect same pitches

See: [`/MRS-Specification-RFC#13-progressive-validation`](/MRS-Specification-RFC#13-progressive-validation)

## Conflict Detection

The orchestrator uses source-hash to detect concurrent modifications:

```
1. Working Set created with source-hash H1
2. Agent produces operations (takes time)
3. Meanwhile, another agent modifies the score
4. Before applying, orchestrator checks current hash
5. Current hash ≠ H1 → conflict detected
```

### Conflict Resolution Options

| Option     | When to Use                                                 |
| ---------- | ----------------------------------------------------------- |
| **Reject** | Default safe behavior; agent must retry with fresh envelope |
| **Rebase** | If operations can be transformed to apply on new state      |
| **Merge**  | If changes are in disjoint regions/lanes                    |

## Transaction Model

Every change is recorded:

```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)
```

Transactions enable:

* **Audit trail**: Who changed what, when
* **Rollback**: Revert to previous state
* **Replay**: Reconstruct state from transactions

## 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
* Validation rejects operations that touch locked content
* Human approval required to unlock

### Typical Checkpoint Flow

```
1. Form sketched → checkpoint structure
2. Harmony planned → checkpoint harmonyPlan
3. Orchestration approved → checkpoint notes
4. Final polish → no locks (expression, technique)
```

## Operation Application

When validation passes, the orchestrator applies operations:

1. **Map tmp-ids to UUIDs** in deterministic order
2. **Compute derived fields** (`:at`, `:beat-start`)
3. **Update canonical score** state (and export MRS-S if needed)
4. **Update structural index** if needed
5. **Record transaction** in audit trail
6. **Return result** with id-mapping

### Application Order

Operations are applied in the order received. Dependencies must be satisfied:

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

The orchestrator MAY reorder to satisfy dependencies if unambiguous.

## 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")))
```

Policy options:

* **All-or-nothing**: Reject entire batch if any operation fails
* **Partial**: Apply valid operations, return errors for invalid
* **Interactive**: Pause for human decision on errors

## Human Review Gates

Certain operations should trigger human review by default:

| Trigger             | Reason                          |
| ------------------- | ------------------------------- |
| Structure changes   | Form is foundational            |
| Temporal changes    | Affects timing across the score |
| Locked lane touched | Checkpoint protection           |
| Conflict detected   | Cannot auto-resolve safely      |

In practice, a “review” is not just textual—musicians also need to **audition**.

Implementations can pair semantic diffs with:

* a rendered excerpt of the affected region, and/or
* a playback preview (e.g., MIDI/rendered audio)

Human approval is recorded:

```clojure theme={null}
(human-review
  :transaction-id #uuid "..."
  :status approved
  :reviewer "arranger"
  :notes "Approved with minor adjustment")
```
