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

# Agent Operations

> The MRS-Ops protocol for reliable agent mutations with typed operations.

MRS defines a protocol for agent operations centered on **typed operations** (MRS-Ops), **task-adaptive context**, and **progressive validation**.

**Core Principle**: Agents read MRS-S fragments with task-appropriate context. Agents write typed MRS-Ops operations. The orchestrator validates and applies.

See: [`/MRS-Specification-RFC#5-mrs-ops-the-mutation-protocol`](/MRS-Specification-RFC#5-mrs-ops-the-mutation-protocol)

## Why Typed Operations?

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

* **Accidental omission**: Agent returns less content → content silently 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 design:

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

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

## Operation Types

### Create Event

```clojure theme={null}
(create-event
  :tmp-id "e1"
  :measure #uuid "018c3f40-002d-..."
  :instrument clarinet-bb
  :voice v1
  :beat 0
  :pitch Eb4
  :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, e.g., `0`, `2+1/2`) |
| `:pitch`         | YES      | Pitch or chord or `r` for rest               |
| `:duration`      | YES      | Duration code (`q`, `h`, `e`, etc.)          |
| Other properties | NO       | `:dyn`, `:art`, `:orn`, `:tech`, etc.        |

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

### Delete Event

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

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

### Update Span

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

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

### Delete Span

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

### Create Measure

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

The orchestrator assigns UUID, `:number`, and computes `:beat-start`.

### Delete Measure

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

**Warning**: Deleting a measure deletes all events within it.

### Instrument Change

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

## Temporary ID Rules

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

## Task-Adaptive Context Views

Context views provide task-relevant information beyond the edit scope. Unlike fixed rings, views are selected for the specific task.

### Melodic Reference

```clojure theme={null}
(context-view melodic-reference
  :instruments [violin-1]
  :measures #uuid "..." #uuid "..."
  :content
    (measures
      (measure :id #uuid "..." :number 45
        (violin-1
          (v1
            (: 0 G5.q :id #uuid "...")
            ...)))))
```

### Harmonic Context

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

### Orchestration Map

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

### Phrase Structure

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

### View Selection by Task Type

| Task Type     | Typical Context Views                                   |
| ------------- | ------------------------------------------------------- |
| Compose       | phrase-structure, harmonic-context, thematic-references |
| Countermelody | melodic-reference, harmonic-context                     |
| Orchestrate   | orchestration-map, dynamics-profile                     |
| Harmonize     | melodic-reference, phrase-structure                     |
| Dynamics      | phrase-structure, dynamics-profile                      |

## Example: Add Countermelody

**Working Set Envelope** (agent receives):

```clojure theme={null}
(working-set
  :version 1.0
  :source-hash "sha256:..."
  :scope (:measures #uuid "..." #uuid "...") (:instruments [clarinet-bb])
  :bundle orchestrate
  :task "Add countermelody responding to violin"
  :content (measures ...)
  :context-views
    (context-view melodic-reference :instruments [violin-1] :content ...)
    (context-view harmonic-context :content ...))
```

**Agent Response** (MRS-Ops):

```clojure theme={null}
(mrs-ops
  :version 1.0
  :scope-hash "sha256:..."
  :ops
    ((create-event :tmp-id "e1" :measure #uuid "..." 
                   :instrument clarinet-bb :voice v1
                   :beat 0 :pitch Eb4 :duration q :dyn mp)
     (create-event :tmp-id "e2" :measure #uuid "..."
                   :instrument clarinet-bb :voice v1
                   :beat 1 :pitch D4 :duration q)
     (create-event :tmp-id "e3" :measure #uuid "..."
                   :instrument clarinet-bb :voice v1
                   :beat 2 :pitch Eb4 :duration e)
     (create-event :tmp-id "e4" :measure #uuid "..."
                   :instrument clarinet-bb :voice v1
                   :beat 2+1/2 :pitch F4 :duration e)
     (create-event :tmp-id "e5" :measure #uuid "..."
                   :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")
```

## Lane Bundles

Lane bundles grant permissions for common workflows:

| Bundle             | Lanes                        | Use Case           |
| ------------------ | ---------------------------- | ------------------ |
| `orchestrate`      | notes, expression, technique | Full orchestration |
| `dynamics-pass`    | expression                   | Dynamics only      |
| `notation-cleanup` | notes, technique             | Fix notation       |
| `full-compose`     | all creative lanes           | Full control       |

## Constraint Language

```clojure theme={null}
:constraints
  ((range clarinet-bb E3 C7)
   (avoid parallel-fifths violin-1)
   (prefer chord-tones downbeats)
   (max-interval P8)
   (note-density 2 8))
```

| Constraint     | Description                   |
| -------------- | ----------------------------- |
| `range`        | Notes within instrument range |
| `avoid`        | Prevent voice-leading errors  |
| `prefer`       | Style preferences             |
| `max-interval` | Maximum melodic leap          |
| `note-density` | Notes per measure             |

Constraint violations are caught in progressive validation.
