Timeline document model
Choose the surface
- Use MCP for agent-driven project inspection, command application, diff,
undo/redo, validation, explanation, render, export, and import. Its ten
operations are
pulp_timeline_project_open, pulp_timeline_command_apply,
pulp_timeline_diff, pulp_timeline_undo, pulp_timeline_redo,
pulp_timeline_validate, pulp_timeline_explain,
pulp_timeline_render, pulp_timeline_export, and pulp_timeline_import.
Seven operations retain stateless pulp::tool-timeline entry points; diff,
undo, and redo are MCP-local operations backed by a live DocumentSession.
Three further read-projection tools —
pulp_timeline_view_outline, pulp_timeline_view_region, and
pulp_timeline_view_diff — sit alongside that catalog rather than inside
it, because the generated ten-tool manifest is pinned to the editing verbs
it describes (see "The view projection is published outside the generated
ten-tool catalog").
- Use
/seqfor the agent-guided inspect, validate, edit, explain, import, and
consent-gated export workflow. Use pulp seq and pulp render directly for
shell scripts, CI, and human-operated headless workflows. Prefer seq apply
with typed command envelopes over inventing one-off mutation flags.
- Use the C++ SDK when embedding an editor, transport, compiler, renderer,
recorder, or durable session. Keep document mutation in DocumentSession,
playback derivation in PlaybackProgramCompiler, realtime rendering behind
immutable programs and transport snapshots, and capture publication as
ordinary timeline commands. A ProgramCompileRequest must declare its exact
sample_rate explicitly and carry a CompiledTempoMap built at the same
normalized RationalRate; omission or disagreement is a synchronous invalid
request rather than an inferred default.
- Link
Pulp::timeline-agent-viewwhen an agent or remote client needs a
bounded, deterministic projection of one pinned DocumentView. AgentView
exposes a committed outline, cursor-paged clip regions, and a projection of
one adjacent commit's DirtySet without widening the dependency-minimal
Pulp::timeline model.
- Link the optional
Pulp::dawproject-importSDK target only when ingesting
DAWproject XML, and Pulp::smf-interop only when reading or writing Standard
MIDI Files; keep the dependency-minimal model on Pulp::timeline.
- DAWproject import seals media by its bytes and checks
<Audio duration>, so
it refuses a WAV the reader could only recover (inspect_wav(...)->truncated)
with "truncated WAV", before the duration comparison would report a
misleading mismatch.
- Use the generated schema surfaces to discover command/document shapes; do
not hand-copy schema vocabularies into a client.
- Use the live control plane when the sequencer you need to read or edit is
already running inside a host, rather than sitting on disk as a document. The
timeline surfaces above all open a project; dev.pulp.sequencer/state.read@1
and dev.pulp.sequencer/state.edit@1 reach a live SequencerStateChannel in
a running instance and open nothing. See "Live sequencer control operations".
Start with project_open or seq validate when the source is unfamiliar.
MCP project_open returns a bounded process-local session_id; use that
identifier for apply, diff, undo, and redo. A session keeps the real
DocumentSession undo stack and latest canonical DirtySet; session handles
expire when that server process exits and may expire after it reaches its
bounded session capacity, so preserve the returned project snapshot as the
durable handoff.
Apply edits as one expected-revision transaction, validate the result, use
explain to inspect playback lowering/PDC, then render only when an audio
artifact is needed. Never modify canonical project JSON text directly.
A render ends at the sequence end unless you ask for more. pulp render's
--tail-frames <n> and pulp_timeline_render's tail_frames render n frames
after the transport stops; both default to zero, which is the length every
render produced before the option existed. The default is the trap, not the
option: a program whose last event feeds a delay, reverb, or release envelope
renders with that tail cut at the last note, and nothing reports it — the file
is well-formed and the JSON says ok. If a bounce sounds like it ends abruptly,
suspect the missing tail before suspecting the DSP. The tail is charged against
the same in-memory render budget as the sequence and is refused with its own
message when it does not fit, so a tail is never silently truncated to make one.
command_apply carries both halves of that sentence as optional arguments,
and both are session-only — a stateless apply opens its own document and
keeps no retry record, so it refuses them rather than accepting and ignoring
them. expected_revision is the revision you last read; supply it and an
interleaved write is reported as stale_revision instead of being
overwritten. idempotency_key names the write itself, for the case where the
response was lost rather than the write: retrying under the same token
re-submits the identities the first attempt allocated, so a still-cached
result comes back verbatim and one that has aged out is refused as
already_applied_result_expired. That refusal means the write landed and the
result is no longer readable — it does not mean the write failed, and
re-issuing the commands under a fresh token would apply them twice.
A retry token is only honoured for the request it first named. Reusing one
with different commands, or with a different expected_revision, is refused
as transaction_id_collision, because the alternative is answering a
different request with an earlier result.
Live sequencer control operations
A running host's step grid is reachable through the same unified control
platform as every other Pulp capability -- no bespoke sequencer verb, no new
transport. Four typed operations are registered, each gated on its own
capability and all bound to the host-main executor:
| Operation | Capability | Result | Profiles |
|---|---|---|---|
| dev.pulp.sequencer/state.read@1 | sequencer.state.read | response | observe, develop |
| dev.pulp.sequencer/state.edit@1 | sequencer.state.edit | receipt | develop |
| dev.pulp.sequencer/transport.loop.read@1 | sequencer.transport.loop.read | response | observe, develop |
| dev.pulp.sequencer/transport.loop.write@1 | sequencer.transport.loop.write | receipt | develop |
state.read copies the UI-side published snapshot and the seqlock playhead out
of the channel; pattern, include_snapshot, and include_playhead bound what
comes back, and the response carries epoch, engine_sequence, and
resync_required_epoch so a client can tell a fresh read from a stale one.
state.edit encodes exactly one typed step-grid command -- set-cell, clear
(scoped cell/lane/pattern/all), randomize-lane, set-pattern-length,
or switch-pattern -- and submits it to the single-producer command FIFO,
returning receipt_id, applied, and client_sequence. gesture_phase groups
a drag into one undoable gesture the way a parameter gesture does.
transport.loop.read@1 takes no parameters and returns the whole loop cell at
once -- enabled, start_tick, end_tick, playing, and the monotonic
sequence that stamps it. transport.loop.write@1 carries exactly one
action: set-range moves the boundaries, set-enabled toggles the loop and
requires an expected_sequence so a toggle raced against another writer is
refused rather than applied to a cell the caller never saw. Both actions require
an idempotency_key, and the receipt echoes the resulting cell alongside
receipt_id and applied, so a replayed key is answerable without a second
read.
Three things about these operations are not obvious from their schemas:
- The host-main binding is load-bearing, not incidental.
SequencerStateChannel
is strictly single-producer/single-consumer per side and exactly one UI-side
consumer may own the applied-echo queue. Called off the host main thread both
operations refuse with HostUnavailable rather than racing that cursor, and
the refused edit never reaches the FIFO. A background binding would compile
and pass every functional test.
- A full command FIFO is a typed refusal, never a drop.
state.editreturns
ResourceExhausted with an after-backoff retry hint when the queue is full;
draining a slot makes the next submission succeed. Treat it as backpressure,
not as failure.
- These are not timeline-document operations. They edit live in-process
state, so there is no revision, no undo stack, and no expected_revision
concurrency token -- the epoch/engine_sequence pair is the staleness
instrument instead. Nothing here is persisted by pulp seq.
Reaching them needs no live instance to discover: pulp control capabilities
prints the frozen registry offline, and --json emits the canonical
dev.pulp.control/registry@1 projection with both JSON Schema bodies. Listing
an operation is never a grant. To call one, use `pulp control call --instance ID
dev.pulp.sequencer/state.read@1 --params JSON`; through MCP the registry derives
one tool per row -- pulp_control_sequencer_state_read,
pulp_control_sequencer_state_edit,
pulp_control_sequencer_transport_loop_read, and
pulp_control_sequencer_transport_loop_write -- so Forge Sequencer and
Forge Modular reach the grid and its loop with no bespoke surface. Grants and consent are
broker authority.
Adding a sequencer control operation means updating this section too:
tools/scripts/sequencer_control_skill_check.py derives every
dev.pulp.sequencer/ operation from the frozen registry and fails when one is
missing here or carries the wrong result kind.
Contracts
Project,Sequence,Track, andClipare immutable snapshots. Validate
once in their create() factories; reads must not repair, sort, or rebuild
indexes.
Projectowns its sample-rate-independentTempoMapandMeterMap. Every
path-copy rebuild, ID remap, journal comparison, and replay must preserve
both maps.
- Every owned identity excludes zero and
UINT64_MAX; the latter is the
allocator's explicit exhausted sentinel. A project may store that sentinel
after owning UINT64_MAX - 1; otherwise next_item_id is strictly larger
than every owned ID. Allocation is monotonic and IDs are never reused.
ItemLocationownership is exactly(kind, parent_id), whereparent_idis
the immediate owner. sequence_id, track_id, and clip_id are retained
ancestor-navigation caches and must not become additional ownership keys.
Add new item kinds by extending immediate_parent_id() rather than adding a
new owner-specific field. Legacy identity records without parent_id derive
it from their validated navigation fields during decode.
- Tracks are sparse non-overlapping lanes. Their canonical clip order is
(anchor, start, ItemId). Timeline and ID indexes are persistent AVL trees;
replace_clip() path-copies only search paths and shares untouched subtrees.
- Initial
Track::create,Project::create, and identity restoration must
validate and sort complete input sets, then bulk-build balanced persistent
AVL indexes with exactly one node per final entry. Do not feed bulk state
through the per-edit insertion path: its transient path copies turn initial
construction into allocator-heavy O(n log n) work. Ordinary edits still use
path-copy insertion/replacement so prior snapshots share untouched subtrees.
- A Track owns an ordered
DevicePlacementchain split into pre-fader and
post-fader stages. Each placement carries a format-neutral DeviceKind and
binding key, a typed event-to-event/event-to-audio/audio-to-audio slot,
bypass, canonical finite wet/dry bits, and an optional content-addressed
state reference. Pre-fader placements must precede post-fader placements;
post-fader slots are audio-to-audio, and adjacent signal domains must match.
Runtime instances, graph nodes, plugin formats, paths, inline state bytes,
and platform metadata do not belong in Timeline. InsertDevice,
RemoveDevice, MoveDevice, RetargetDevice, and SetDeviceState use exact
optimistic positions/values and participate in ordinary inverse undo/redo.
Removing a placement still referenced by automation or modulation fails
closed; it never silently cascades.
- Typed device declarations describe authored topology only. They do not lower
note effects or instantiate hosts. The event-stream delay-compensation
contract they will eventually be lowered against is settled in
docs/policies/event-stream-pdc.md: latency is samples, discovered once on
the control thread, and compensation shifts the scheduling window rather than
the event data. Event-to-event device execution is still open, so every
chain the runtime admits today resolves to a zero shift. Never put a latency
field in the Timeline document; the shift is a host fact and belongs to the
binding.
ClipTimeAnchor::Musicalfollows tempo in ticks.Absoluteuses
SamplePosition, an integer sample count, and a normalized RationalRate,
remaining fixed as tempo changes. Phase 1 rejects mixed anchors within one
Track until a context-owned tempo/rate projection can compare them safely.
TimeConformis clip-level document intent:Noneis the default and keeps
legacy behavior, Resample requests pitch-coupled varispeed, and Stretch
requests tempo-preserving stretch. Non-default intent is valid only on a
musical MediaRef; absolute clips and every non-media content alternative
fail with InvalidTimeConform. Clip schema v2 persists the required lowercase
spelling; v1 loads as None, and v2→v1 refuses either non-default value.
Playback consumes Resample as pitch-coupled varispeed by mapping source
phase across the authored musical tick interval, including tempo ramps and
precise host beat mapping. None retains native-rate playback. Stretch
compiles a timeline-rate immutable artifact off the audio thread with exactly
the authored frame count, then plays it 1:1. A missing, over-capacity, or
length-mismatched Stretch artifact fails compilation; it never degrades to
native-rate playback.
MidiContentis a flat POD array sorted by(start, ItemId). Note durations
are positive, pitch is MIDI 0-127, and channel is 0-15. Beside the notes it
carries MidiExpressionLane controller streams, each an owned identity with
points in (position, id) order and at most one lane per address. The document
side is complete — authoring, persistence, id remap, and copy all carry lanes —
but playback refuses to compile a lane-bearing clip rather than dropping the
lanes silently, so a document that authors one cannot be played until the note
program can carry controller values. See the playback skill for the two refusal
codes and which of them the renderer is allowed to delete.
SequenceRefmakes a musical clip a non-owning placement of another
sequence. Its source window begins at source_start; project construction
rejects missing targets, cycles, and nesting deeper than eight reference
edges. Sequence
identity remains project-owned, so removing a referenced sequence fails.
Playback expands references off the audio thread into immutable root-track
programs. Stage 1 accepts child note/audio clips and rejects child devices,
automation, takes, freeze, record-arm state, absolute clips, and non-neutral
reference gain/fades. A source window that cuts into a leaf clip's own
fade shortens that fade to the new clip edge rather than refusing — the
answer an unnested clip gives when it is dragged shorter — and a trim that
swallows a fade whole leaves none. A fade authored on the SequenceRef
placement itself is a different mechanism: flattening records that ramp as a
window of fade progress in owner-timeline ticks, and every leaf the window
reaches evaluates its own position inside it, so one ramp composes across the
leaves flattening cut it into and multiplies with each leaf's own fade. It
refuses only when a ramp actually reaches a leaf whose content no renderer
scales by clip gain, because dropping that ramp would be silently wrong. A complete
nested media clip preserves its TimeConform intent. A source window that
trims a Resample clip maps onto the matching sub-span of the source under
the same conform function, so it lowers; one that trims a Stretch clip
lowers as well, by keeping the artifact keyed to the authored tick range and
reading back only the frames of that render the window covers. Nothing
refuses a trimmed conforming leaf any more, so NestedConformedTrimUnsupported
is no longer raised. A nested child track
carrying a device chain fails with NestedDeviceChainUnsupported; one
automating its pan fails with NestedAutomationPanUnsupported, and one
automating its gain with NestedAutomationGainEventLeafUnsupported or
NestedAutomationGainMediaUnsupported according to whether the leaf that
curve reaches consumes clip gain. An
absolute-anchored leaf inside a nested sequence fails with
NestedAbsoluteChildUnsupported; each names its own cause rather than
sharing one umbrella code. Expansion
is bounded by ProgramCompileRequest::max_expanded_note_events and
ProgramCompileRequest::max_expanded_clips across materialized clips,
reference traversal, and reused track programs. The independent
audio_limits.max_clips ceiling counts compiled audio regions only.
- Shared edits affect every placement. Use
build_diverge_transaction()for
eager copy-on-edit: it emits a complete-ID CloneSequence followed by
SetClipSequenceRef. Pass two command IDs allocated from the session
WriterToken; the helper consumes item IDs from Project::next_item_id
before publication but never synthesizes writer-scoped IDs.
- For incremental compilation, construct
ProgramCompileRequest::invalidation
from the shared context registry and exact CommitResult; submit()
builds and resolves the snapshot-scoped index against that same request. It
maps direct edits, child dirtiness, built-in MIDI groove reads, and nested
context readers to root tracks. The input pins that result's snapshot,
revision, exact predecessor snapshot, and an immutable registry copy. If the
predecessor is not the currently published project, sparse reuse is refused
and the cumulative target snapshot is rebuilt in full. A later registry
generation also forces a full compile without fabricating a document revision.
AutomationCurveis a position-ordered immutable point sequence. Point IDs
and positions are unique within a curve; values are finite; curvature is in
[-1, 1]. Continuous segments use a monotonic quadratic blend, while Hold
segments retain the left value until the next point. value_at() is for
control-thread or compile-time queries, never the audio-thread scheduler.
AutomationLaneis an immutable value that binds one curve to a
format-neutral device-placement ItemId and opaque 32-bit parameter ID. Its
standalone factory validates only the value identities. Once attached, Track
owns lanes in canonical identity order, requires their target placements to
exist in its device chain, and permits only one lane per placement/parameter
pair. Lane and point IDs are Project identities owned by that Track; host
delivery remains a separate contract.
- A
Sequenceowns two annotation lists:SequenceMarker(a named point) and
SequenceRegion (a named span). They are sequence-owned, not
project-owned: a Project holds many sequences, so a project-level list could
not say which timeline it annotates. Both are canonical-ticks values, carry an
optional packed 0xRRGGBBAA colour (a float colour type would live outside
this module's dependency floor, and exact bytes are what a document model
needs), share one identity space (a marker may not reuse a region's ItemId in
the same sequence), and are stored sorted — markers by (position, id), regions by
(position, duration, id). Regions may overlap and nest by design: named
sections contain sub-sections, so disjointness is deliberately not an
invariant. What Sequence::create does enforce is a positive region length, a
non-negative position, and containment inside the sequence's musical duration
when it declares one — an absolute-only sequence bounds nothing above.
Sequenceis built throughcreate(), not aggregate init. Existing
partial overloads stay source-compatible; the full-fidelity path takes
SequenceInput, so new owned collections extend a named input rather than an
unbounded chain of positional overloads. Sequence remains pimpl'd behind
shared_ptr<const Data>.
- **The
pulp.timeline.sequenceandpulp.timeline.projectschemas are both
versioned; the encoder must not hard-code either version.**
sequence_schema_policy and project_schema_policy (mirroring
track_schema_policy) own the type name, current version, oldest readable
version, and the predicates — requires_annotations(version),
requires_scenes(version), and supports_session_start(version) — that
decode and preflight both consult. A
literal version in write_sequence, walk_sequence, walk_project, or
structural_registry_validation is how these drift apart — route every one
through the policy. pulp.timeline.project being versioned at all is easy to
miss: it sat at v1 long enough that several call sites reached for the
fixed-version data_for() helper instead of data_for_versions().
- A required member and an optional one need different migration shapes.
Sequence markers/regions are required arrays, so v1→v2 splices [] in at the
canonical position and v2→v1 refuses when either is non-empty. The project's
session_start is optional, so its migration pair only moves the version
number — nothing is inserted — and the downgrade refuses only when the member
is actually present. Copy the shape that matches the field, not the nearest
migration.
- **
Project::Datais brace-initialized positionally inappend_assetand
remove_asset.** Appending a field to the struct there fails open: those
sites keep compiling and silently leave the new field default, dropping
document state on any asset edit. Those two sites now use designated
initializers; keep them that way, and put any new field where a stale
positional init cannot type-check.
- Markers and regions are command-addressable:
InsertMarker/RemoveMarker/
InsertRegion / RemoveRegion reduce through
transaction_marker_internal, which plans an ItemKind::Marker or
ItemKind::Region identity parented by the sequence (not a track), so
DirtyItem::owner_track is legitimately zero for these commands. They emit
inverse commands, so undo, redo, and journal replay restore the annotation and
its tombstone ownership exactly.
- Scenes are sequence-owned in authored order, and each scene owns its ordered
slots. A non-empty slot must name a clip in that sequence; a Jump follow
action must name an existing slot, while other kinds carry no target.
Sequence-owned launcher state is an immutable persistent store: scene and
slot identity indexes, authored-order links, and reverse clip/Jump references
live together in sequence_scene_internal.cpp. Ordinary scene/slot edits
path-copy only affected AVL paths; unrelated Sequence edits must retain the
launcher store unchanged. Never replace this with scene-vector rebuilding or
validate deletions by scanning every scene.
InsertScene / RemoveScene and InsertSlot / RemoveSlot reduce through
transaction_scene_internal with exact inverse and tombstone ownership.
- **A track owns eight identity kinds across four levels, and an incomplete
owned set cannot fail at remove time.** InsertTrack / RemoveTrack reduce
through transaction_track_internal. plan_identity_deactivate validates
nothing — it emits one Deactivate per identity handed to it — so a missed
kind leaks an identity that stays active with its owner gone, and only
surfaces later as an unrelated IdentityNotAvailable, or as undo failing
because tombstone restore requires each id to exist and be inactive. The two
that get missed are the lane-parented pair, AutomationPoint and Take.
Never hand-write the list: visit_track_owned_identities() in
owned_identity_traversal.hpp is the single enumeration, and
visit_sequence_owned_identities() calls it, so the two cannot diverge.
has_same_owner compares only kind and parent while target_error compares
all four coordinates, so right ids with a wrong coordinate cache survive both
undo and redo and reject the next command two edits later — assert the
complete ItemLocation of every level, not just active.
RemoveTrack's inverse is InsertTrack{sequence_id, removed, following};
following is what restores authored position exactly instead of appending.
- Automation lanes are command-addressable:
InsertAutomationLane/
RemoveAutomationLane reduce through the shared transaction pipeline
(transaction_reduction_support + transaction_automation_internal),
validating the target sequence/track/placement, allocating lane and point
identities as owned Project identities, and emitting inverse commands so undo,
redo, and journal replay restore the lane and its tombstone ownership exactly.
Command equivalence compares lane payloads bit-exactly (float bits), so a
re-authored point differing only in a signed zero is not treated as equal.
- Keep automation responsibilities separated: curve data belongs in
automation_curve.*, logical target binding belongs in automation_lane.*,
RT cursor/coalescing belongs in core/playback, and graph delivery belongs in
core/host.
- A
Takeis one recorded region referencing a sealed media asset, anchored to
absolute sample time (its timeline length is the media frame count). A
TakeLane is an immutable, identity-ordered set of takes owned by a Track,
and a Track carries a record_armed document-intent flag the capture engine
reads but never mutates here. A take's parent is its lane — the second
lane-owned exception alongside AutomationPoint, so immediate_parent_id()
returns the supplied lane_id for ItemKind::Take and it is excluded from
coordinate-based parent recompute; a lane's parent is its Track. Take
identities must be disjoint from every other track-owned id, and a take whose
MediaRef asset is missing or out of range is rejected at Project::create,
exactly like a clip MediaRef.
- Take lanes and record-arm are command-addressable:
InsertTakeLane/
RemoveTakeLane / SetRecordArm reduce through the shared pipeline
(transaction_reduction_support + transaction_take_internal, dispatched like
automation), allocating lane+take identities as owned Project identities and
emitting inverse commands so undo/redo/journal-replay restore lane and
tombstone ownership exactly. InsertTakeLane re-validates each take's asset
reference against the project (the recorder emits CreateAsset first, so the
asset already exists when the take command reduces); SetRecordArm is an
optimistic expected/replacement gate on a non-identity flag. InsertTake /
RemoveTake edit one lane-owned take and preserve its tombstone parent.
SetActiveTakeLane optimistically selects one existing lane as the active
playlist/comp; zero selects the arrangement. Removing an active lane is
rejected, so clearing selection and removing the lane must be one explicit
transaction. SetTakeComp carries exact expected/replacement segment lists.
Each segment names a take and an in-bounds, normalized absolute sample range;
lane construction canonicalizes by timeline start and rejects missing takes,
mixed/wrong rates, empty or overlapping ranges. Removing a take selected by
the comp fails closed. Playback may flatten this source data into a derived
cache, but the cache is never document truth.
- A
TrackFreezeis an optional immutable selection of one sealed media
artifact plus its absolute placement/rate and a ContentHash fingerprint of
the exact render plan. It does not remove or mutate authored clips, takes,
automation, or device placements. Publish with one transaction ordered as
CreateAsset then SetTrackFreeze; the latter is an exact
expected/replacement gate dispatched through
transaction_track_state_internal. Undo clears the selection before
removing the artifact, asset removal fails while selected, and replay selects
the sealed artifact without re-rendering. Construction and mutation validate
that the asset exists, the media range is in bounds, and the artifact rate
matches. ID remap fixes the external artifact reference through
ExternalIdFixup; the render-plan hash is content metadata, not an owned
identity.
Project::DataandTrack::Datamutations rebuild by copy-and-modify
(auto next = *data_; next.field = ...; make_shared<const Data>(move(next))),
never positional brace-init — adding a field must not silently shift an
unrelated mutation site. create() factories build from input with designated
initializers.
MediaRefranges are checked locally for overflow and against their asset at
project construction.
- A media asset's SHA-256
ContentHashis its durable identity. Locators are
optional late-resolution hints; representations have distinct hashes and
unique roles. Missing local media is valid document state.
AudioLoopInfois optional typed metadata on a sealed media asset: musical
length and meter, one-shot intent, MIDI root note, half-open frame markers,
manual or analyzer-suggested loop points, and canonical tags. Derive tempo
from musical length, asset frame count, and sample rate; do not persist a
duplicate BPM value that can disagree. This is descriptive authoring state,
not clip repetition, sample traversal, or a comp-selection model.
- Persistence uses canonical JSON envelopes with
data,type_name, and
integer version. All 64-bit IDs, positions, counts, durations, and rate
components are canonical decimal JSON strings; never encode them as JSON
numbers or floating point.
- Schema-v1 project persistence writes canonical
tempo_mapandmeter_map
arrays. BPM is stored by exact IEEE-754 bits; older v1 snapshots without map
fields remain readable as 120 BPM and 4/4, then canonicalize on save.
- Track schema v2 introduced the required device-chain field; v3 adds required
attached automation lanes; v4 adds the required take_lanes array and
record_armed flag; v5 adds the required active_take_lane_id ("0" means
arrangement). Adjacent downgrades succeed only when the field being removed
is empty/default (v5→v4 requires zero selection; v4→v3 requires empty takes
and record_armed false), so
neither placement, automation, nor take identity can be discarded. Placements,
lanes, lane targets, take lanes, and takes remain separately versioned
structural envelopes. Take-lane schema v2 adds required comp_segments; its
v1 upgrade adds an empty comp, while v2→v1 succeeds only for an empty comp.
Track schema v6 adds optional freeze; v5→v6 is version-only because absence
means unfrozen, while v6→v5 succeeds only when freeze is absent. Never
silently discard a selected artifact during downgrade.
- Clip schema v2 adds required
time_conform. Its v1 upgrade insertsnone;
its v2 downgrade succeeds only for none, and a v1 envelope that illegally
carries the field is rejected rather than normalized.
- Asset schema v2 adds optional
loop_info. Its v2 to v1 downgrade succeeds
only when that field is absent, and a v1 envelope that illegally contains
the field is rejected rather than silently normalized.
- **A command schema is widened with optional fields at its current version —
never by bumping it.** Document schemas walk registered upgrades /
downgrades chains, but decode_command gates on exact version equality and
has no upgrade hook, and no command schema declares a migration edge. Raising
a command's version therefore rejects every envelope already written with
UnsupportedSchemaVersion. Declare the new field required = false in
schema_registry.cpp, read it with JsonValue::find in
serialize_command_decode.cpp, and make absence decode to what the payload
meant before the field existed (replace_note_content's modifier arrays and
set_clip_playback_properties's fade_shape both do this). Command decode
never validates a payload against schema->fields, so the registry entry is
documentation and generated-artifact input, not the gate — the decoder is.
Widening a command payload also means updating equivalent() (the
idempotency cache answers a repeated transaction id with its first result, so
a field it ignores lets a retry apply one payload and report another's
outcome) and retained_size() (it falls through to sizeof(T), so a field it
forgets is under-counted rather than refused).
- **A brand-new command type is a different case: register it at version 1 with
every field required.** Nothing has ever written an envelope naming it, so
there is no older meaning to preserve and an omitted field is a malformed
payload rather than a legacy spelling. The exact-equality gate still applies to
it from then on, which is what pins it at 1 for good.
schema_release.hpprecords exact shipped structural type/version sets,
including v0.736.0 (Track v1), v0.744.0 (Track v2), v0.748.0
(Track v3), and v0.750.0 (Track v4, before SequenceRef content and sequence
mutation commands).
serialize_project_for_release() applies the registry's
downgrade callbacks parent-first, then rewrites reachable child envelopes.
It fails closed when a removed feature is populated, an encountered
extension has no explicit target, or the target map names a type/version the
supplied registry cannot provide. Do not infer release compatibility from
the current schema version or preserve an opaque extension in an older
release export.
- Release export also projects the project identity table. Identity kinds
unknown to the target release fail when active; inactive tombstones of those
kinds are removed only after confirming their IDs remain below
next_item_id, which preserves the no-reuse boundary an older reader will
carry forward.
- Build a
SchemaRegistryexplicitly withSchemaRegistryBuilder; there is no
global mutable registry. Registered content codecs are typed, noexcept, and
own no hidden ItemIds in Phase 1. Migration callbacks must return and verify
each complete intermediate envelope.
- Unknown or future extension content is retained as exact validated envelope
bytes. Saving may splice those bytes unchanged and reports
has_opaque_objects; ID remapping must fail closed for any opaque subtree.
- **Adding a field to a persisted entity touches more than encode and decode, and
the sites people miss lose data silently.** Beyond serialize_encode.cpp /
serialize_project_decode.cpp you must also update the schema policy header
(current_version plus an <field>_introduced_version predicate),
schema_registry.cpp (declare the field, register BOTH migrations),
structural_registry_validation.cpp (its own expected-field list, or the
registry self-check fails), sequence_schema_migrations.{hpp,cpp} (the
vN_members list plus BOTH raw-splice migrations), and
schema_json_preflight.cpp. Then two
more that no gate points at: id_remap.cpp, or every copy/paste/import
quietly resets the field to its default, and snapshot_equivalence.cpp, or
the journal-replay checkpoint guard treats documents differing only in that
field as identical — and it is also the round-trip oracle, so a round-trip test
asserted through equivalent() passes even when the field was never persisted.
Grow the oracle in the same change, and prove a round-trip test fails with the
encode disabled before trusting it.
- **A sequence-owned context lane is not persisted just because the model
carries it.** DynamicsLane shipped with validation, interpolation, compile
resolution, and id-remap tests all green while the encoder, every decoder,
the preflight, and the schema registry knew nothing about it — a save
silently dropped an authored lane. The lane now rides sequence schema v8 as
dynamics_lane (between chord_scale_lane and groove), each event as
{"intensity_bits","interpolation","position"} with the intensity spelled
as its IEEE bit pattern the way an automation point spells value_bits, so
a reload is bit-exact rather than nearest-decimal. The v8→v7 downgrade
refuses a lane with any authored event, exactly as the scene, track-order,
and chord-detail downgrades refuse. When adding a lane like it, the
round-trip test is the one test the feature cannot ship without: assert the
reloaded lane == the authored one (float bits included) and that a re-save
reproduces the first save, then prove that test fails with the encode line
removed.
- **Field order in the canonical JSON is alphabetical, so a new field renumbers
its neighbours.** track_order sorts before tracks (_ < s), which moved
tracks from member index 9 to 10 in the preflight walk. A wrong index
compiles and silently reads the neighbouring member. Re-derive every index
after inserting a field rather than appending to the end of the list.
- A migration that adds an optional collection should write it empty rather
than materializing a default, when the model already normalizes empty to the
default: Sequence::create turns an empty track_order into identity order, so
the v5→v6 upgrade writes [] and every upgraded document loads correctly
without bloating. The downgrade is the asymmetric half — it must fail closed
with MigrationFailed when the value is not equivalent to the default, exactly
as the v5→v4 scenes downgrade refuses a non-empty scene list.
- Versioned persistence fixtures live under
test/fixtures/timeline/vN/and
remain permanent compatibility inputs. Exercise unknown envelopes from those
files instead of rebuilding equivalent JSON inside a test so whitespace,
escapes, and member order cover the exact-byte re-save contract.
- The
vNdirectory names thepulp.timeline.sequenceschema version its
fixtures were authored at (nested envelopes carry their own contemporaneous
versions), and **every version in the migration chain must carry at least one
indexed document fixture** — a schema bump that lands without one leaves a
version the corpus can never exercise. tools/scripts/timeline_fixture_coverage_check.py
enforces that: registered as the timeline-fixture-coverage ctest beside a
-selftest that proves it reddens on a synthetic gap, and as a job in
timeline-hardening.yml. Coverage reads corpus.index, not the tree — a
version dir whose fixtures are not indexed as documents does not count.
- Not every
.jsonundertest/fixtures/timeline/is a project. The corpus
holds three shapes and nothing in the files distinguishes them: complete
pulp.timeline.project envelopes; single-entity fragments such as
v4/sequence-before-scenes.json, a bare pulp.timeline.sequence at v4 used to
drive registry.migrate() directly; and raw payloads such as
v1/unknown-content-envelope.json, which is never parsed as timeline JSON at
all — it is embedded as OpaqueContent to prove unknown bytes survive a round
trip. Decoding a fragment or a payload as a project fails InvalidSchema, and
that is correct refusal, not a broken fixture. test/fixtures/timeline/corpus.index
declares each entry's kind so the distinction is stated rather than guessed;
a new fixture must be listed there with its kind.
pulp-fixture-runnervalidates everydocumententry against a sibling
<path>.expect manifest: schema envelope version, identity, structural counts
from peek_project_summary(), the interchange concept census, and the ordered
identities of every collection in the arrangement spine. Regenerate
manifests with pulp-fixture-runner --corpus test/fixtures/timeline --update;
generation is deterministic, so a regeneration that dirties the tree means a
document actually changed. The manifest is checked in both directions — an
entry declared but not observed fails too, because a document that lost an
entity would otherwise pass with every observed value still matching.
- **
test/fixtures/timeline/is exhaustively indexed: every file must appear in
corpus.index, and a host-side sweep enforces it.** Adding a fixture without an
index line reddens that sweep on a file your diff never mentions. Two
consequences worth knowing before you merge anything touching that tree. First,
a .expect manifest is excluded from the sweep, so an unindexed fixture with a
manifest is dead weight no gate can see. Second, and the one that actually bites:
any branch cut before the index existed cannot index its own fixture, so the
breakage appears only when the two branches meet on main — neither PR's CI can
see it alone. Check corpus.index covers the tree before merging a
fixture-adding branch.
- The corpus runs twice per PR: natively under ctest, and compiled to WASM.
core/interchange/wasm/CMakeLists.txt is an Emscripten-only root that builds
the runner from the portable sources, and tools/ci/wasm-fixture-lane.sh
drives it (job Timeline fixture corpus (WASM) in web-plugins.yml). Two
things follow. The wasm root hand-lists its sources, because linking
pulp::timeline would drag in pulp::runtime's mbedTLS/HTTP — so a source
the desktop build gains is one the wasm build can silently miss; the root
fails its configure when core/interchange/src drifts from its list, but the
timeline list it borrows from PulpTimelineSources.cmake is shared and stays
honest on its own. And the lane deliberately runs the corpus a second time
against a broken copy and requires red, so a wasm build that validated
nothing cannot pass. Run it locally with
source ~/emsdk/emsdk_env.sh && tools/ci/wasm-fixture-lane.sh <build-dir> 6.
- A new
ProjectSnapshotCountsfield is asserted by the corpus only if it is
also emitted by collect_summary() in
core/interchange/tools/fixture_runner_main.cpp, which lists the counts one by
one and is not generated. Add the count and skip that list and every manifest
regenerates clean while the new entity goes uncounted in every fixture — the
corpus reports green on a document whose new structure it never looked at.
- **A count cannot see an ordering, so a new ordered collection needs a line in
collect_identity_orders() too** — same file, same hazard as the counts list
above. The order.* manifest keys exist because counts plus idempotence are
jointly blind to a lost order: dropping a sequence's authored track_order
leaves counts.tracks intact, and an empty order re-serializes consistently,
so a round trip agrees with itself on the wrong answer. Two classes are worth
recording — authored orders (track_order, scenes, device_chain),
which exist only in the document, and value-derived orders (markers,
regions, clips), whose sort makes identity order a proxy for the positions
behind it. Leaf content below a track stays on counts by design.
- **An order assertion only bites while the fixture's order is not the identity
order.** Sequence::track_order() presents the identity order of tracks()
for a sequence that never recorded one, so a manifest cannot distinguish "no
authored order" from "authored order equals identity order" — a fixture in
either state stays green when the order is dropped.
v6/sequence-track-order.json is deliberately built with a non-identity order
so the check can fail at all, and a case in test/test_fixture_runner_cli.cpp
asserts its two orders still differ. Do not "fix" a red order assertion by
rerunning --update; that regenerates from observed output without comparing
and bakes the regression in as the new baseline.
- The census the runner records is
pulp::interchange::census(), which lives in
core/interchange, not core/timeline. Anything reaching for it takes an
interchange dependency; that is on the portable floor, but it is a dependency
edge worth knowing before adding one. That call is also why the runner binary
is owned by core/interchange/CMakeLists.txt rather than by the test tree —
see the placement convention below.
- Decode through
DecodeLimits. Keep input size, depth, value/member/array and
domain object limits enforced before growth. Duplicate object keys, malformed
UTF-8/surrogates, noncanonical wide integers, and non-normalized rates fail.
- Use
peek_project_summary()for project browsers and admission checks that
need identity, name, root, or structural counts without constructing the
immutable document. Pass the same SchemaRegistry intended for load so
registered content is distinguished from opaque content. The peek still
scans the complete structural envelope and enforces every DecodeLimits
quota, including take lanes and takes, but does not resolve item or media
references.
serialize_project()anddeserialize_project()do not implement a ZIP or
package container. Asset locators describe possible package-relative bytes.
Use pulp::project-package to hash-verify, fence, and no-replace publish
content-addressed blobs before atomically replacing the stable package root's
validated project.json generation. Generic file and directory publication
is also no-replace, and unpublished staging remains unreachable; archive
formats and interchange policy stay in their format/tooling layers.
- Project and subtree remapping are two-pass: allocate all owned IDs first, then
rebuild the snapshot and fix references. MediaRef::asset_id is external to
Clip/Track/Sequence remaps and is translated by ExternalIdFixup; failure is
atomic and does not advance the caller's allocator. Preflight the complete
owned subtree for duplicate IDs before allocating; this includes parent IDs,
cross-track collisions, clips, note events, automation lanes, and automation
points. Lane and point IDs remap as owned identities, target placement IDs
remap as internal references, and opaque parameter IDs remain unchanged.
- Fallible public APIs return
pulp::runtime::Result; do not throw.
AgentView is a bounded projection of one immutable pin
pulp::timeline_agent_view::AgentView is created from one non-null
DocumentView and never follows a live DocumentSession. Every read therefore
requires the pin's exact revision; a caller that needs freshness must pin the
session again after a commit. outline() returns deterministic sequence,
track, and clip rows plus the complete ProjectSnapshotCounts census. Bounded
details are fail-closed commitments, not silent truncation: each omitted row
set carries a count and SHA-256, and the outline carries a commitment to the
canonical project snapshot.
region() pages clips in canonical (start, ItemId) order over one half-open
start-position window [start, end). A continuation cursor is valid only for
the exact version, revision, sequence, anchor, and original window that issued
it; changing either bound while retaining an in-range cursor key is still
InvalidCursor. The request limit must be non-zero and no larger than
Limits::max_page_items.
diff() projects an already-produced DirtySet into deterministic outline
changes. Its DirtyRevisionRange must be exactly one adjacent transition ending
at the pin (after != 0, before == after - 1); stale, non-adjacent, and
underflow-shaped ranges fail with InvalidProvenance. This adjacency check does
not authenticate the DirtySet: the public type has no session-issued origin
token, so callers must pair it with the exact CommitResult that produced it.
Do not present AgentView as an arbitrary since-revision diff or as a substitute
for session provenance.
The view projection is published outside the generated ten-tool catalog
AgentView reaches CLI and MCP through one shared encoder in
tools/timeline/src/timeline_agent_view.cpp, so pulp seq view and the
pulp_timeline_view_* tools emit byte-identical payloads by construction
rather than by review. A Forge consumer therefore has a single shape to pin,
and every payload carries a version field so it can pin it explicitly.
The MCP registration deliberately does not extend the generated catalog.
tools/mcp/CMakeLists.txt raises FATAL_ERROR unless the generated timeline
tool JSON holds exactly ten tools, and mcp_timeline_tools.cpp carries a
matching static_assert(bindings.size() == kTimelineMcpToolNames.size()).
Adding a read verb there would mean widening a cap that exists to keep the
editing catalog honest against its schema. So the view tools follow the
control_mcp_tools_json_fragment() precedent instead: a hand-written
descriptor fragment plus a separate binding array, both appended alongside the
generated ten. Because that fragment is a hand-built string, its
well-formedness is asserted rather than assumed — test_mcp_timeline_sessions.cpp
parses it and the whole tools/list catalog, since a stray comma there would
break tool discovery for every client at once.
Note the input asymmetry, which is intentional. The MCP tools take a
session_id, like every other MCP timeline tool, and read the live session's
current revision — that is the Forge-facing live read. The CLI takes a project
path, because a one-shot CLI invocation has no session. view diff on either
surface applies the commands to an in-memory copy and writes nothing, but that
copy is a real transaction, so the diff carries the same authority apply
does: a proposal writer is refused a removal by name rather than reporting a
change it would not admit.
Widening `ClipContent` is guarded, and the two guards are not interchangeable
ClipContent decides what a clip is, so nearly every consumer dispatches on
it — and the default failure of a new alternative is silence, not an error. A
consumer written as an if/if constexpr chain keeps compiling and treats the
new kind as absent: a clip that renders nothing, an export manifest that reports
no loss while dropping data, a remap that carries stale ItemIds into a copy. No
test catches that, because nothing wrote a test for a kind that did not exist.
So the variant carries two guards, and which one a site gets is a judgement, not
a style preference:
- Visit through
ClipContentCaseswhen the site is genuinely dispatching —
the encoder, content equality, the journal's retained-size accounting, the
interchange census, the id-remap walk, and the playback compiler's content
classifier. The overload set has no generic fallback, so widening the variant
fails overload resolution right there.
static_assert(kClipContentAlternativeCount == N)when the site cannot
be a visit but is only correct for today's alternatives — the decoder, which
dispatches on envelope type names rather than on the variant, and the two
asset referential-integrity scans, which reach assets through MediaRef
alone. Each message names the decision that site owes.
A site that reads one alternative and is correct for every other one (a note
lookup, a MediaRef range check at construction) needs neither; do not add
noise there. And note that -fno-exceptions makes a bare std::get on a
mismatched alternative call std::terminate rather than throw, so a fallthrough
std::get is a process abort, not a caught error — that is why the encoder is a
visit and not a chain ending in std::get<OpaqueContent>.
MIDI content stores the wire's numbers, and cannot reach `core/midi` to name them
MidiContent carries notes, their deterministic modifiers, and the clip's
controller/expression lanes. It is tempting — and specs sometimes ask — to type
a lane's controller family against core/midi's UMP/MPE/RPN declarations so the
document model and the wire cannot disagree. **core/timeline cannot include
pulp/midi/* at all.** MODULE_FLOORS in
tools/scripts/timeline_engine_dependency_floor_check.py gives timeline the
floor {timeline, timebase, platform, runtime}; midi belongs to playback's
floor, one layer up. The check scans every include under core/timeline/ and
fails the build gate, so this is discovered late if it is discovered by
compiling.
The resolution is not a parallel enum either — it is to store the wire's own
numeric domain and name nothing. MidiLaneAddress is five raw bytes (UMP group,
channel, status nibble, controller bank, controller index) and a lane point's
value is the full 32-bit channel-voice width that 7-bit and 14-bit MIDI 1.0
values scale into. NoteEvent set this precedent already with bare pitch /
channel / velocity integers. Only bounds the wire itself imposes are
validated here (group, channel, and status are 4-bit fields); which addresses
carry meaning is a playback question and does not belong in the document model.
The per-stream layout is also load-bearing rather than incidental. Lanes are
sorted by (address, id) and each lane's points by (position, id), because
the question asked on every seek is "what did this one stream last say at or
before t" — two binary searches against that layout, versus a scan over every
event of every stream if lanes were flattened into one interleaved list.
Flattening them is the change that quietly makes seeking O(n).
A new owned identity is added to the traversal, and nowhere else
id_remap.cpp enumerates what a clip, a track, and a sequence own only
through owned_identity_traversal.hpp. Both passes each level runs go through
it: owned_ids() collects for preflight's validity/duplicate check, and
allocate_owned_subtree() issues the destination identities. The same traversal
also feeds the identity index that Project::create and serialization build,
and the size check in the carried-id remap_ids(Sequence, carried_ids, fixups)
overload. So a kind added to the traversal reaches every one of those at once,
and the compiler is not what keeps them in step — not restating the list is.
Do not hand-write an owned-set walk at a call site, even when the level you are
adding to already has an obvious loop. Both ways of getting it wrong are quiet
and land far from the cause: an allocation walk that misses a kind returns a
copy without those objects, and a collection walk that misses one lets the new
identities skip validation entirely and then fails a later carried-id transfer
with InvalidIdentityTransition naming a size mismatch, which names no kind
at all.
Three cases pin this down, one per level, and each asserts a hand-counted
identity total — a distinctness or agreement check alone passes when a walk
silently emits fewer identities:
Copying a clip issues fresh identities for its lanes and points and
A sequence copy and its carried-id transfer agree on the whole owned set
(test_timeline_midi_content.cpp), and
A track copy issues a fresh identity for every kind a track owns
(test_timeline_take_comp.cpp), which carries every kind a track can own at
once because a per-kind case passes while a sibling kind goes missing.
One sharp edge remains: rebuild_*() dereferences table.find(id) for every id
it rewrites, assuming the allocation walk covered it. A kind dropped from the
traversal therefore reaches an empty-optional dereference — undefined behaviour,
not a checked error. In practice the garbage id it reads is refused by the next
create() and the remap fails, which is what the cases above observe, but the
diagnostic points at the rebuilt object and never at the walk.
Two more places a new ItemKind must land, neither of which the compiler will
point at: restore_identities() in model.cpp recomputes parent_id from
(sequence, track, clip) for every kind except an explicit
AutomationPoint / Take / Slot list, so any kind whose parent is a lane has to
join that list or every document carrying it fails to deserialize with
ModelRejected at /data/identities — an error that names no kind at all. And
item_kind_name() / the decode parser are two hand-maintained tables that must
gain the same spelling; the encoder's switch is exhaustive and will complain,
but the decoder's if-chain silently returns a failure for the unknown name.
Editing contracts
- The bounded mutation vocabulary is exactly the
Command-domain verbs of
core/timeline/schema/timeline_cli_verbs.json — 64 of them, catalogued in
full under Command catalog below with the wire type each one carries. A
hand-kept subset drifts from the model as soon as a command lands, so the
catalog is derived from that artifact and the timeline-command-doc-coverage
ctest fails when a declared command is missing from it. Automation commands
attach or tombstone complete Track-owned lanes; map commands carry exact
expected/replacement document values and participate in the same transaction,
journal, undo, and replay machinery. reduce_transaction() is pure: it
returns a new snapshot, exact canonical dirty set, and reverse-ordered inverse
commands.
NoteTransformRegistryis the control-thread apply-time extension point for
pure (note span, canonical params JSON, seed) -> note array functions.
ApplyNoteTransform is a typed preparation request, not a durable Command:
preview() invokes extension code once, assigns fresh IDs only to outputs
whose ID is invalid, and lowers the result to one ReplaceNoteContent
transaction. The returned snapshot is speculative and the authoritative
session is unchanged. Commit by submitting the exact returned transaction;
a changed revision rejects it as stale instead of rerunning the transform.
The journal therefore contains only canonical note data, never a callback,
and undo/redo use the ordinary expected/replacement inverse while preserving
note identity tombstones. A transform may retain an input ID, but a foreign
or duplicate output ID is refused. Parameters must be a JSON object, are
parsed under a 1 MiB bound, and are canonicalized before callback invocation.
The expected plus output arrays share the durable command's five-million-note
quota.
CreateAsset/RemoveAssetare the asset-table mirror pair (shaped like
InsertClip/RemoveClip). CreateAsset carries the whole MediaAsset by
value — the ContentHash is the sealed durable identity. The reducer plans
the ItemKind::Asset identity and appends the asset by reference to that hash
through Project::append_asset; **replay never re-captures or re-hashes media
bytes**, so the same checkpoint plus journal reproduce a byte-identical asset
table (the sealed-content contract). An invalid/empty ContentHash is
rejected before the asset can enter the document. RemoveAsset fails closed
while any clip's MediaRef still points at the asset, tombstones the identity
like a clip removal, and its inverse re-creates the sealed asset — so undo/redo
stays whole. Asset validation and identity-mutation application live in shared
model.cpp helpers so construction, sequence replacement, and asset mutation
enforce one sealed-identity and one identity-transition path.
DocumentSessionis the sole authoritative writer. Multiple control-thread
callers serialize through it; readers atomically pin immutable snapshots.
Every transaction declares its expected revision. Stale revisions and typed
value/owner preconditions reject the whole transaction without publication.
- Command and transaction IDs are writer-scoped monotonic idempotency keys.
UndoGroupId is the separate, explicit gesture-coalescing identity; different
writers never coalesce.
WriterTokenis a move-only, session-bound capability. Its ID allocators are
thread-safe and saturate permanently at exhaustion; never copy or synthesize
writer-local ID streams.
- Gesture phases form one serialized session state machine:
Beginopens a
writer/group, only matching Update/End may follow, and other writers plus
undo/redo receive GestureState until the group closes.
- Use
timeline_editor::EditGestureIdentityAllocatorfor construction-safe
continuous editor input. It owns one group and one opaque pending ticket,
binds tickets to the real session/writer provenance, lowers the issued phase
internally for both clip and validated note intents, and derives transitions only from its own call to
DocumentSession::submit(). Validation/lowering errors preserve the ticket;
an actual submission consumes it while a rejected transaction preserves the
confirmed state for a fresh-ID retry. Keep it on one control thread and route
every submission for its writer/group through it; concurrent direct
same-group submission is outside the contract. If a pending ticket is
abandoned without submission, discard that allocator instance.
- A cached successful Begin is not necessarily the current publication. The
allocator checks the exact CommitResult with
DocumentSession::is_current_publication() and, on mismatch, asks the session
whether its opaque writer/group still owns the authoritative open gesture.
An intervening Update keeps the allocator Open so End/Cancel remains
possible; an intervening End/Cancel returns it to AwaitingBegin. Never scan
the journal, reconstruct this from numeric writer IDs, or accept
caller-declared acknowledgement state.
- Project identity lookup is a persistent AVL directory. Deletion tombstones
IDs forever; inverse insertion may reactivate the exact identity and parent
chain. Never scan the whole project or reuse an ID to implement undo.
- The in-memory command journal is bounded and fail-closed. A full journal
rejects before publication; it never ring-evicts committed entries.
checkpoint() truncates only a caller-confirmed durable prefix.
- A session may attach a
JournalSink. It publishes a transaction only after
append_batch() reports the complete batch durable, and truncates a
checkpoint only after the sink installs its reconstructed snapshot. A sink
error is ambiguous, so it permanently poisons new durable writes for that
session; already-cached idempotent results retain their normal semantics.
Both callbacks run under the session writer lock and must not call
lock-taking APIs on the originating DocumentSession.
FileJournalis the native crash-consistent sink. Its frames contain
canonical snapshots, a revision, and checksums; append success follows the
platform durability fence. Recovery truncates only a torn final frame and
fails closed on corruption earlier in the file. Checkpointing the current
revision uses a synced temporary sibling plus atomic rename, while
checkpointing an older prefix leaves newer durable frames intact. Restored
sessions attach only after an exact, read-only canonical-bytes/revision
validation; restoration never rewrites or truncates the recovered journal.
Symlink paths canonicalize to one lock identity; multiply linked journal
files are rejected because atomic checkpoint replacement cannot preserve
hard-link identity.
- Journal mutation and tombstone restoration are session-internal. Public
reduce_transaction() never revives tombstones, and replay rejects a
checkpoint snapshot/revision mismatch or cross-entry writer-ID reuse.
- Undo and redo submit fresh ordinary transactions. They append to the journal;
they do not delete or rewrite history.
Command catalog
Every durable mutation the document model accepts, with the exact type string
a caller writes. The wire type is the operative half: the C++ spelling is what
an agent guesses from the model, while the wire type is what
pulp seq apply, the pulp_timeline_command_apply MCP tool, and
DocumentSession actually decode, and a type the manifest does not carry is
refused before it reaches a reducer.
Rows are derived from core/timeline/schema/timeline_cli_verbs.json and their
descriptions from the declarations in
core/timeline/include/pulp/timeline/command.hpp. Regenerate the artifact after
a manifest change, then add the row here — timeline-command-doc-coverage
fails a command that exists in the artifact and not in this table.
| Command | Wire type | What it does |
|---|---|---|
| CloneSequence | pulp.timeline.command.clone_sequence | Clones a sequence using an explicit, complete owned-identity mapping. |
| CreateAsset | pulp.timeline.command.create_asset | Adds one sealed recorded or imported media asset. |
| InsertAutomationLane | pulp.timeline.command.insert_automation_lane | Inserts an automation lane into a track. |
| InsertClip | pulp.timeline.command.insert_clip | Inserts an identity-bearing clip into a track. |
| InsertDevice | pulp.timeline.command.insert_device | Inserts a typed device declaration into a track's authored chain. |
| InsertMacro | pulp.timeline.command.insert_macro | Inserts a track-owned macro control. |
| InsertMarker | pulp.timeline.command.insert_marker | Inserts a sequence-owned marker identity. |
| InsertMidiExpressionLane | pulp.timeline.command.insert_midi_expression_lane | Inserts a controller/expression lane into a MIDI clip. |
| InsertModulationRoute | pulp.timeline.command.insert_modulation_route | Inserts one authored source-to-parameter connection. |
| InsertModulator | pulp.timeline.command.insert_modulator | Inserts a track-owned modulation source. |
| InsertNotes | pulp.timeline.command.insert_notes | Inserts a set of identity-bearing notes into one MIDI clip. |
| InsertRegion | pulp.timeline.command.insert_region | Inserts a sequence-owned region identity. |
| InsertScene | pulp.timeline.command.insert_scene | Inserts a scene at an authored position in a sequence. |
| InsertSequence | pulp.timeline.command.insert_sequence | Inserts a complete sequence and its owned identity subtree. |
| InsertSlot | pulp.timeline.command.insert_slot | Inserts a slot at an authored position in a scene. |
| InsertTake | pulp.timeline.command.insert_take | Inserts one take into an existing take lane. |
| InsertTakeLane | pulp.timeline.command.insert_take_lane | Inserts one take lane and its owned take-identity subtree. |
| InsertTrack | pulp.timeline.command.insert_track | Inserts a track and its complete owned identity subtree at an authored position. |
| MoveClip | pulp.timeline.command.move_clip | Replaces a clip's time range under an exact optimistic-value gate. |
| MoveDevice | pulp.timeline.command.move_device | Moves a device under an exact optimistic authored-position gate. |
| MoveTrack | pulp.timeline.command.move_track | Moves a track in authored order under an exact optimistic-position gate. |
| RemoveAsset | pulp.timeline.command.remove_asset | Removes a project-owned media asset by identity. |
| RemoveAutomationLane | pulp.timeline.command.remove_automation_lane | Removes an automation lane by identity. |
| RemoveClip | pulp.timeline.command.remove_clip | Removes a clip by its owning coordinates and identity. |
| RemoveDevice | pulp.timeline.command.remove_device | Removes a device declaration by identity. |
| RemoveMacro | pulp.timeline.command.remove_macro | Removes a track-owned macro control by identity. |
| RemoveMarker | pulp.timeline.command.remove_marker | Removes a sequence-owned marker by identity. |
| RemoveMidiExpressionLane | pulp.timeline.command.remove_midi_expression_lane | Removes a controller/expression lane from a MIDI clip by identity. |
| RemoveModulationRoute | pulp.timeline.command.remove_modulation_route | Removes one authored connection by identity. |
| RemoveModulator | pulp.timeline.command.remove_modulator | Removes a track-owned modulation source by identity. |
| RemoveNotes | pulp.timeline.command.remove_notes | Removes a named set of notes under an exact optimistic-value gate. |
| RemoveRegion | pulp.timeline.command.remove_region | Removes a sequence-owned region by identity. |
| RemoveScene | pulp.timeline.command.remove_scene | Removes a scene and its owned slots by identity. |
| RemoveSequence | pulp.timeline.command.remove_sequence | Removes a sequence and its owned identity subtree. |
| RemoveSlot | pulp.timeline.command.remove_slot | Removes a slot from a scene by identity. |
| RemoveTake | pulp.timeline.command.remove_take | Removes one take from an existing take lane. |
| RemoveTakeLane | pulp.timeline.command.remove_take_lane | Removes a take lane and its owned take identities. |
| RemoveTrack | pulp.timeline.command.remove_track | Removes a track and its complete owned identity subtree by identity. |
| ReplaceNoteContent | pulp.timeline.command.replace_note_content | Replaces the complete note event set of one note clip. |
| RetargetDevice | pulp.timeline.command.retarget_device | Replaces device kind, binding, slot, stage, bypass, and wet/dry atomically. |
| SetActiveTakeLane | pulp.timeline.command.set_active_take_lane | Selects the arrangement or an existing take lane under an exact value gate. |
| SetChordScaleLane | pulp.timeline.command.set_chord_scale_lane | Replaces a sequence's complete chord/scale lane under an exact value gate. |
| SetClipPlaybackProperties | pulp.timeline.command.set_clip_playback_properties | Replaces clip-level gain and fade controls under an exact value gate. |
| SetClipSequenceRef | pulp.timeline.command.set_clip_sequence_ref | Retargets a sequence-reference clip under an exact optimistic-value gate. |
| SetDeviceState | pulp.timeline.command.set_device_state | Replaces the optional content-addressed opaque state reference. |
| SetDynamicsLane | pulp.timeline.command.set_dynamics_lane | Replaces a sequence's complete dynamics lane under an exact value gate. |
| SetGroove | pulp.timeline.command.set_groove | Replaces a sequence's complete groove under an exact value gate. |
| SetMacro | pulp.timeline.command.set_macro | Replaces a macro control's declaration under an exact value gate. |
| SetMacroValue | pulp.timeline.command.set_macro_value | Replaces only a macro's authored position under an exact value gate. |
| SetMeterMap | pulp.timeline.command.set_meter_map | Replaces the complete project meter map under an exact value gate. |
| SetMidiExpressionLanePoints | pulp.timeline.command.set_midi_expression_lane_points | Replaces one lane's authored points under an exact optimistic-value gate. |
| SetModulationRoute | pulp.timeline.command.set_modulation_route | Replaces a route's source, target, depth, and bypass under an exact gate. |
| SetModulator | pulp.timeline.command.set_modulator | Replaces a modulation source's declaration under an exact value gate. |
| SetNoteEvents | pulp.timeline.command.set_note_events | Replaces the values of a named subset of one note clip's notes. |
| SetNoteVelocity | pulp.timeline.command.set_note_velocity | Replaces one note velocity under an exact optimistic-value gate. |
| SetProjectTuning | pulp.timeline.command.set_project_tuning | Replaces the project-wide tuning statement under an exact value gate. |
| SetRecordArm | pulp.timeline.command.set_record_arm | Replaces record-arm document intent under an exact optimistic-value gate. |
| SetRegion | pulp.timeline.command.set_region | Replaces one sequence-owned region under an exact value gate. |
| SetTakeComp | pulp.timeline.command.set_take_comp | Replaces a take lane's canonical comp segments under an exact value gate. |
| SetTempoMap | pulp.timeline.command.set_tempo_map | Replaces the complete project tempo map under an exact value gate. |
| SetTrackFreeze | pulp.timeline.command.set_track_freeze | Publishes or clears a pre-rendered track artifact under an exact value gate. |
| SetTrackMixer | pulp.timeline.command.set_track_mixer | Replaces track gain and pan under an exact optimistic-value gate. |
| SetTrackName | pulp.timeline.command.set_track_name | Replaces a track's authored name under an exact optimistic-value gate. |
| SetTrackTuning | pulp.timeline.command.set_track_tuning | Replaces one track's tuning override under an exact value gate. |
Modulation sources, macros, and routes are track-owned and caller-identified
A track carries three modulation members, and they are inserted rather than
minted: InsertModulator
(pulp.timeline.command.insert_modulator), InsertMacro
(pulp.timeline.command.insert_macro), and InsertModulationRoute
(pulp.timeline.command.insert_modulation_route) each carry a complete
declaration bearing its own identity, so a source and the route that reads it
can be stated in one transaction instead of requiring a round trip to learn
what identity the model chose.
Removal is refused by the model rather than by the command. A source a route
still reads cannot leave: RemoveModulator
(pulp.timeline.command.remove_modulator) and RemoveMacro
(pulp.timeline.command.remove_macro) produce a track whose routes name a
member it does not hold, and the model refuses that track — so the failure
arrives as a rejected transaction, not as a document that quietly loses its
routing. RemoveModulationRoute
(pulp.timeline.command.remove_modulation_route) is the one modulation removal
nothing can refuse, because no other member reads a route.
The three Set forms pin identity. SetModulator
(pulp.timeline.command.set_modulator), SetMacro
(pulp.timeline.command.set_macro), and SetModulationRoute
(pulp.timeline.command.set_modulation_route) each require the addressed id,
expected.id, and replacement.id to be equal. An unpinned identity would let
a Modify swap one member for another — a removal and a creation wearing a
signature that declares neither — which hands a writer holding only Modify the
operation its capability mask refuses. SetModulationRoute gates the whole
route including enabled, because a bypassed route keeps its depth and target
so re-enabling restores what was there.
SetMacroValue (pulp.timeline.command.set_macro_value) is the narrow command
beside the broad one, the same shape SetNoteVelocity has beside
SetNoteEvents. It gates the normalized position alone, so a performer moving
a macro need not also supply its current name and a concurrent rename cannot
abort an edit that did not conflict with it. The float compares exactly rather
than within a tolerance, which is safe because the persisted spelling is the
IEEE-754 bit pattern. The overlap with SetMacro is deliberate: an edit that
rewrites the whole macro should gate on the whole macro.
A MIDI expression lane is addressed, not note-keyed
InsertMidiExpressionLane (pulp.timeline.command.insert_midi_expression_lane)
delivers a lane whole — identity, MidiLaneAddress, and every authored point —
and MidiContent::create is the single authority on whether it may join the
clip, enforcing identity distinctness across notes, points, and lanes plus one
lane per address. RemoveMidiExpressionLane
(pulp.timeline.command.remove_midi_expression_lane) is separate because
abandoning a stream is the destructive intent a capability mask denies by
default: a writer that may edit a lane's values does not thereby gain the right
to discard it.
SetMidiExpressionLanePoints
(pulp.timeline.command.set_midi_expression_lane_points) changes what a stream
says, never which stream it is — the lane keeps both its identity and its
address, and the gate compares the full point array in canonical order.
Re-addressing a lane is a remove and an insert, because the two things a caller
means by it carry different authority.
Whole-sequence and region commands
InsertSequence (pulp.timeline.command.insert_sequence) and RemoveSequence
(pulp.timeline.command.remove_sequence) carry a complete sequence and its
owned identity subtree, the sequence-level pair beside InsertTrack /
RemoveTrack. CloneSequence is the third member and the one that needs an
explicit complete old-to-new id mapping.
SetRegion (pulp.timeline.command.set_region) completes the region trio
beside InsertRegion and RemoveRegion, and pins identity the way the
modulation Set commands do: expected.id and replacement.id must be equal
and must name a region the sequence owns. That pinning is what makes correcting
a region's SectionRole reachable for a writer profile that may modify but may
not remove.
Rebuilding a `MidiContent` from its notes alone silently drops everything else
A MidiContent carries four things, not one: the note array, a sparse
NoteModifier companion array keyed by note identity (probability, every-Nth /
first / fill condition, ratchet count), the modifier_seed those probability
draws are derived from, and the clip's controller/expression lanes.
MidiContent::create is overloaded, and the shorter overloads default away
exactly the state a rebuild means to keep — they **compile wherever the
four-argument overload does**. So any path that rebuilds a clip's content by
handing the notes back to create erases authored document state with no error
and no diagnostic. Reach for the four-argument overload on every rebuild path.
Re-attachment is not uniform across the three companions, and making it
uniform is its own bug:
- Filter the modifier array to the surviving note ids. Modifiers key on
note_id, and create rejects one that names a note the content does not
carry (MissingItem), so a blind pass-through converts an ordinary note
deletion into a hard model failure. Dropping the orphan is the right answer,
not an error: the modifier has no identity left to key to, and the same edit
already tombstones that note's identity.
- Carry the seed verbatim, even when no modifier survives. It is authored
document state that selects the replay, not a cache — zeroing it changes which
notes sound as soon as a modifier is authored again.
- Pass the lanes through unfiltered. A
MidiExpressionLanekeys on a
MidiLaneAddress — {group, channel, status, bank, index}, a channel-voice
stream address that references no note at all. Applying the surviving-note-id
filter to lanes as well is the reflexive "keep these consistent" edit, and
because no lane identity is ever a note identity it deletes the clip's
controller streams the moment an edit removes a note. Only a test that
authors lanes and shrinks the note set catches it.
The rebuild paths that must each handle all three independently are
reduce_replace_note_content (transaction_note_internal.cpp), rebuild_clip
(id_remap.cpp, which additionally rewrites each note_id, lane id, and point
id through the remap table while leaving the address alone), and
finish_pending_leaf (core/playback/src/sequence_content_lowerer.cpp, where a
nested clip trimmed to its audible window filters modifiers to the retained
notes and refuses a clip with lanes outright — trimming has no defined answer
for a point that sits before the retained window yet still sounds inside it).
ReplaceNoteContent carries the modifiers as well as the notes, in optional
expected_modifiers / replacement_modifiers arrays. An authoring caller leaves
both empty and the reducer derives the surviving set from the clip; a
reducer-built inverse fills them in, which is what makes undo exact for an edit
that removes a modifier-bearing note — the dropped modifier is gone from the
content the inverse reduces against, so no filter over live state can recover it.
Lanes need no such treatment: they never leave the clip.
Choosing between the note-set commands
SetNoteEvents, InsertNotes, RemoveNotes, and ReplaceNoteContent rewrite
note content, and the difference is what each one gates on.
SetNoteEventsnames a subset and cannot change the note set.
replacement[i] must name the same note as expected[i], so the reduction
allocates no identity and tombstones none. Reach for it for any edit that moves,
resizes, or retunes notes that already exist — a drag, a nudge, a velocity
sweep. It carries only the notes under the gesture, so its journal cost tracks
the selection rather than the clip.
InsertNotesadds an identity-bearing subset. Every note identity must be
available. Its optional modifier payload may reference only notes inserted by
that same command; reducer-built undo uses it to restore complete authored
behavior after a removal.
RemoveNotesremoves a subset under an exact whole-note CAS. Each expected
note must match the current note with the same identity in every field. The
reducer captures attached modifiers in the generated InsertNotes inverse,
preserves controller lanes and the clip modifier seed, and tombstones only
the removed note identities.
ReplaceNoteContentgates on the clip's entire current note array and is
the legacy whole-set replacement. Its expected is rejected unless it equals
the whole note set, so a one-note edit in a 10,000-note clip still costs
10,000 notes twice over.
All four emit exactly one command per transaction regardless of how many notes
they touch. JournalLimits::max_commands is a count ceiling, so a per-note
command shape would exhaust it far sooner than the byte ceiling it would
relieve — which is why the subset commands are plural.
A whole-content note edit is affordable per gesture, not per frame
ReplaceNoteContent carries both note arrays, so DocumentSession charges one
edit retained_size(forward) + retained_size(inverse) — roughly 128 * N bytes
for an N-note clip against an 8 MiB UndoLimits default. That number is what
makes "a note editor cannot use this command" look obvious, and it is only true
for one shape: an open gesture group.
candidate.closed is set for Single, End and Cancel, and the eviction loop
in document_session.cpp advances only while the oldest group is closed. So:
- A
Single-phase edit is charged once, closes on admission, and is
immediately evictable. Any number of commit-on-release edits succeed; the only
cost is undo depth (8 MiB / 128N groups). A single edit larger than the whole
budget — past roughly 65k notes at the default — is still refused outright,
because nothing can be evicted to make room for it.
- A
Begin/Update/.../Enddrag coalesces every step into one group that
stays open, and an open group is not evictable by anything. The charge
accumulates per frame and the gesture dies partway through with
ConflictCode::UndoFull — an in-progress drag that stops responding.
So a piano roll that commits on release persists through this command today; one
that streams Update per frame needs granular note commands first. Test the
distinction as a pair — the same command at the same size against the same
budget, reaching opposite outcomes — since either case alone passes against a
session with no budget at all
(test_timeline_undo.cpp).
Sizing a session's real ceiling, note that the journal binds before the undo
stack: JournalLimits defaults to 16 MiB / 1024 transactions and has **no
automatic eviction at all**, only an explicit checkpoint(). A test that means
to exercise the undo budget must widen the journal explicitly or it will measure
JournalFull instead.
An identity rewrite must copy the source input, not re-enumerate it
remap_ids is the copy / paste / import path: it rewrites every owned
ItemId and carries authored value state across untouched. rebuild_track
used to express that as a designated-initializer TrackInput{...} naming every
field. A designated initializer does not warn on an omitted member — unlike
positional aggregate init, which -Wmissing-field-initializers catches — so the
omitted field takes its default and the rebuild compiles clean. That is how a
track's authored mixer came to be reset to unity gain and centre pan on every
copy, paste, and import, with no error and no diagnostic.
The shape that fails closed is copy-and-mutate over the source's own input:
detail::track_input_of(track) (track_input_access.hpp, implemented beside
Track::Data in track.cpp) returns the complete authored TrackInput, and
the rewrite then assigns only the identity-bearing fields over it. A newly
authored value field is carried by construction; the one place that must stay
exhaustive sits next to the storage it reads. Enumerate identity, inherit value.
The same reasoning applies to any rebuild of a model struct from a source
value. SequenceInput and ProjectInput in id_remap.cpp are still
enumerated in full — audit them against model.hpp whenever either struct
grows, because nothing in the compiler will.
Sequence-owned context and the compile-context subscription contract
A Sequence owns a ChordScaleLane — an ordered set of ChordScaleEvents
(position, chord root + quality, scale root + mode) that other items read while
compiling. That cross-entity read is what the compile-context subscription
contract exists for, and the contract is what keeps the compiler's dirty set
exact:
CompileContextKind(compile_context.hpp) is the vocabulary; a renderer
declares the kinds it reads as a CompileContextSubscriptions set.
- The read side is
CompileContextView, constructed with that declaration.
An undeclared kind reads as null. Do not add an accessor that bypasses the
declaration — the whole point is that a hook cannot depend on context the
compiler does not know to invalidate it for.
- The invalidate side lives in
core/playback(see the playback skill):
CompileInvalidationIndex bundles the nested dependency and context-reader
reverse indices, and resolve_dirty_tracks() turns a DirtySet into an
exact DirtyTrackSet.
- A
RegisteredContentvalue is valid only under its exact schema identity and
codec provenance. Build one immutable SchemaRegistry with built-ins plus
the application's content schemas, use it to create or load the payload, and
pass it when declaring the matching ContentRendererRegistration in
playback. The declaration and its hook are process-local capabilities, not
serialized Timeline state. An exact content value without an exact renderer
must fail compilation as UnresolvedRegisteredContent; it must not become
opaque silence.
- A context edit emits two things: a
DirtyContext{sequence, kind}(which
names what changed) and a companion DirtyItem flagged DirtyFlags::Context
with no owning track (so an item-scanning consumer still sees the transaction
changed something rather than silently seeing an empty dirty set). A
trackless item that is not Context-flagged means a structural sequence edit.
Adding a context kind is a data change here plus a reverse-index case in the
compiler. It is never a reason to widen an invalidation.
The runnable cross-module contract is
examples/timeline-sdk-consumer/registered_chord_renderer.cpp. It registers the
chord-pattern schema and renderer, establishes a baseline compile, commits a
SetChordScaleLane, constructs CompileInvalidationInput from that exact
CommitResult, waits for the submission epoch, and proves that only the
context-reading generated track changes while an ordinary MIDI track reuses its
compiled owner. It also pins deterministic values and hash, unresolved and
bounded quota diagnostics, and weakest production aggregation. Update and run
that installed consumer whenever schema identity, registered content, context
dirty semantics, or playback hook declarations change.
The current compiler contract is notes-only, reset-state-only, and capped at
4096 fragment notes per clip. A nested SequenceRef that trims registered
content compiles: the hook generates over the authored clip and the compiler
windows the fragment to the retained span. Renderer production declarations live with the process;
ProgramWire refuses nondefault declarations instead of transporting a claim
without its trusted hook.
Adding a field to `pulp.timeline.sequence` touches two silent mirrors
Beyond the documented recipe (model → registry → version + both migrations →
encode/decode → regenerate codegen → web source closure → tests), two files
mirror the registry with no reference pointing at them from it, and both fail
with an error that does not name them:
structural_registry_validation.cppcarries an exact expected field list,
order, kind, required-ness, and version range per structural type. Miss it and
serialize_project() returns a bare InvalidSchema before writing a byte.
schema_json_preflight.cpp'swalk_*functions re-validate the envelope
independently of the decoder, pinning [oldest_readable, current] versions per
type. Miss it and every v2 document fails to load even though the decoder
handles it. New optional/versioned array fields also need their own
governed_array count so a hostile document cannot allocate unbounded.
The paired version policy header (sequence_schema_policy.hpp, alongside
track_schema_policy.hpp and asset_schema_policy.hpp) is what keeps those
three call sites agreeing about which version introduced which field. Add one
rather than spelling version numbers inline.
`GrooveTemplate` composes two transforms that behave differently
A groove is a timebase swing warp plus a repeating offset table. The warp is
continuous and monotone (its contract and its round-trip bound live in the
timebase skill); the table is a per-step displacement and can reorder
material where adjacent steps lean opposite ways. Offsets are bounded to less
than a step, which limits that but does not forbid it — so assert monotonicity
of the swing half only, never of the composition.
The table is indexed by the authored position, not the swung one, so
changing the swing setting never re-assigns notes to different steps. A test for
that has to pick a position swing carries across a step boundary; most positions
land in the same step under either order and a test using one of those passes
whichever way the code is written.
Playback applies this context to built-in MIDI at compile time. The owning
sequence's groove moves onset and release by one shared delta, scales velocity
at the original onset, and is inherited unchanged by ratchets. Nested MIDI reads
the child groove exactly once rather than composing it with the parent. A
trimmed nested MIDI leaf with authored groove is currently refused because the
source-window chase rule for displaced notes is intentionally undefined.
Timing transforms are two halves, and zero depth is not bypass
More than one stage moves a sequenced note, and the ordering is a contract: