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

# Extract-Replace Protocol

> How Working Set Envelopes are created and how MRS-Ops are applied.

The Extract-Replace Protocol defines how the orchestrator creates Working Set Envelopes from canonical score state (often exported as MRS-S for the Working Set) and how agent operations (MRS-Ops) are validated and applied.

See: [`/MRS-Specification-RFC#7-working-set-envelope`](/MRS-Specification-RFC#7-working-set-envelope)

## Protocol Overview

```
┌─────────────────┐         extract         ┌─────────────────────────┐
│     MRS-S       │ ──────────────────────► │  Working Set Envelope   │
│    (Source)     │                         │  (MRS-S + context)      │
│                 │                         └─────────────────────────┘
│                 │                                    │
│                 │                              agent work
│                 │                                    │
│                 │                                    ▼
│                 │                         ┌─────────────────────────┐
│                 │ ◄────────────────────── │       MRS-Ops           │
│                 │    validate + apply     │  (typed operations)     │
└─────────────────┘                         └─────────────────────────┘
```

## Extraction (MRS-S → Working Set)

### Extraction Parameters

```
ExtractParams {
  measures: Range<UUID>              ; Required: measure UUID range
  instruments: Set<InstrumentId>     ; Required: instruments to include
  voices: Set<VoiceId>?              ; Optional: filter voices
  bundle: BundleId                   ; Lane bundle to grant
  task: String?                      ; Task description
  constraints: List<Constraint>?     ; Validation rules
  context_views: List<ViewType>?     ; Requested context views
}
```

### Extraction Algorithm

```
function extract(source: MRS-S, params: ExtractParams) -> WorkingSetEnvelope:
  
  1. Validate params
     - All requested measure UUIDs exist
     - All requested instruments exist
     - Bundle is valid
  
  2. Compute source hash (SHA-256)
  
  3. Resolve inherited state at extraction start
     - Time signature, key, tempo at first measure
  
  4. Build content
     - Copy measures in UUID range
     - Copy instrument definitions
     - Copy relevant spans (mark boundary crossings)
  
  5. Generate task-adaptive context views
     - Select views based on task type
     - Extract relevant content for each view
  
  6. Build envelope with scope, permissions, context
  
  7. Return WorkingSetEnvelope
```

### Self-Containment

The extracted `:content` MUST be parseable as standalone MRS-S:

* Instrument definitions included
* Time/key/tempo state declared
* Spans have both endpoints or boundary markers

## Application (MRS-Ops → MRS-S)

### Application Algorithm

```
function apply(source: MRS-S, ops: MRS-Ops) -> Result<MRS-S>:

  1. Verify source hash (conflict detection)
     - If hash mismatch → return Conflict error
  
  2. Progressive validation
     a) Syntax validation (all ops well-formed)
     b) Reference validation (all IDs exist or valid tmp-ids)
     c) Permission validation (ops within lanes/scope)
     d) Musical rule validation (constraints satisfied)
  
  3. If validation fails → return ValidationError with details
  
  4. Map tmp-ids to UUIDs
     - Generate UUIDs in deterministic order
     - Build id-mapping
  
  5. Apply operations in order
     - For create-event: add to measure
     - For update-event: modify existing event
     - For delete-event: remove from measure
     - For create-span: add to spans section
     - etc.
  
  6. Compute derived fields
     - Calculate :at for new events
     - Update :beat-start if measures inserted
  
  7. Full validation of result
  
  8. Record transaction in audit trail
  
  9. Return updated MRS-S with id-mapping
```

### Conflict Detection

The orchestrator uses source-hash for conflict detection:

```
1. Working Set created with source-hash H1
2. Agent produces operations (takes time)
3. Before applying, orchestrator checks current hash
4. If current hash ≠ H1 → conflict
```

If hashes don't match, the canonical score changed since extraction → conflict.

### Conflict Resolution Options

| Option     | Description                                              |
| ---------- | -------------------------------------------------------- |
| **Reject** | Return error; agent must request fresh envelope          |
| **Rebase** | Transform operations to apply on new state (if possible) |
| **Merge**  | Combine changes if in disjoint regions/lanes             |

## Progressive Validation

Operations are validated in stages:

### Stage 1: Syntax

* Operation type recognized
* Required fields present
* Field types correct

### Stage 2: References

* All UUIDs exist in source
* All tmp-ids unique within envelope
* Cross-references valid (e.g., span "from" references "e1" that exists)

### Stage 3: Permissions

* Operation type in `:allowed-ops`
* Content within granted `:bundle` lanes
* Scope within granted `:scope`

### Stage 4: Musical Rules

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

## Derived Field Computation

The orchestrator computes derived fields:

### `:at` (Absolute Beat Position)

For each event:

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

Agent never provides `:at`; orchestrator computes it.

### `:beat-start` (Measure Start)

When measures are inserted:

```
1. Compute duration of inserted measure
2. Update :beat-start of all subsequent measures
```

## Operation Ordering

Operations are applied in order. Dependencies must be respected:

* Create measure before creating events in it
* Create events before creating spans referencing 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
    (("e1" #uuid "...")
     ("e2" #uuid "...")
     ("e3" #uuid "...")
     ("e4" #uuid "..."))
  :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 on any failure
* **Partial**: Apply valid ops, report failures
* **Interactive**: Pause for human decision

## Transaction Recording

Every successful application 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
  :id-mapping (...))
```

Transactions enable audit trail, rollback, and state reconstruction.
