gabriel / muse public
manifest.py python
383 lines 12.6 KB
bda49bdb feat: redesign .museignore as TOML with domain-scoped sections (#100) Gabriel Cardona <cgcardona@gmail.com> 5d ago
1 """Hierarchical chunk manifests for the Muse MIDI plugin.
2
3 Evolves the flat ``{"files": {"track.mid": "<sha256>"}}`` snapshot beyond
4 a single content hash per file to a rich, per-bar, per-track manifest that
5 enables:
6
7 - **Partial diff** — compare only the bars that changed.
8 - **Query acceleration** — answer note queries without reading full MIDI blobs.
9 - **Targeted merge** — attempt to merge only the bars with conflicts.
10 - **Historical analytics** — aggregate statistics over commit history without
11 re-parsing MIDI bytes on every query.
12
13 Backward compatibility
14 ----------------------
15 The ``MusicManifest.files`` field is identical to the standard
16 ``SnapshotManifest.files`` so that the core Muse engine and all existing
17 commands continue to work unchanged. The ``tracks`` field is additive
18 metadata stored as a sidecar under ``.muse/music_manifests/`` — never
19 replacing the canonical flat manifest.
20
21 Storage layout::
22
23 .muse/music_manifests/
24 <snapshot_id>.json — full MusicManifest for this snapshot
25 (rebuildable from history; add to .museignore [domain.midi] in CI)
26
27 Public API
28 ----------
29 - :class:`BarChunk` — per-bar chunk descriptor.
30 - :class:`TrackManifest` — rich metadata for one MIDI track.
31 - :class:`MusicManifest` — top-level sidecar manifest.
32 - :func:`build_bar_chunk` — build a :class:`BarChunk` from a bar's notes.
33 - :func:`build_track_manifest` — build a :class:`TrackManifest`.
34 - :func:`build_music_manifest` — build the full :class:`MusicManifest`.
35 - :func:`write_music_manifest` — persist to ``.muse/music_manifests/``.
36 - :func:`read_music_manifest` — load from the sidecar store.
37 """
38
39 from __future__ import annotations
40
41 import hashlib
42 import json
43 import logging
44 import pathlib
45 from typing import Literal, TypedDict
46
47 from muse.plugins.midi._query import (
48 NoteInfo,
49 detect_chord,
50 key_signature_guess,
51 notes_by_bar,
52 )
53 from muse.plugins.midi.midi_diff import extract_notes
54
55 logger = logging.getLogger(__name__)
56
57 _MANIFEST_DIR = ".muse/music_manifests"
58
59
60 # ---------------------------------------------------------------------------
61 # Types
62 # ---------------------------------------------------------------------------
63
64
65 class BarChunk(TypedDict):
66 """Descriptor for one bar's worth of note events in a MIDI track.
67
68 ``bar`` 1-indexed bar number (assumes 4/4 time).
69 ``chunk_hash`` SHA-256 of the canonical JSON of all notes in this bar.
70 Used for per-bar change detection without re-parsing MIDI.
71 ``note_count`` Number of notes in this bar.
72 ``chord`` Best-guess chord name for this bar (e.g. ``"Cmaj"``).
73 ``pitch_range`` ``[min_pitch, max_pitch]`` MIDI pitch values in this bar.
74 """
75
76 bar: int
77 chunk_hash: str
78 note_count: int
79 chord: str
80 pitch_range: list[int]
81
82
83 class TrackManifest(TypedDict):
84 """Rich metadata descriptor for one MIDI track at a specific snapshot.
85
86 ``track_id`` Stable identifier for this track (SHA-256 of file path).
87 Stable across renames if you track by content; changes
88 on rename. Use entity IDs in the entity index for
89 true cross-rename continuity.
90 ``file_path`` Workspace-relative MIDI file path.
91 ``content_hash`` SHA-256 of the full MIDI file bytes (same as the flat
92 manifest entry — the canonical content address).
93 ``bars`` Mapping from ``str(bar_number)`` → :class:`BarChunk`.
94 JSON keys are always strings; callers convert to int.
95 ``ticks_per_beat`` MIDI ticks per quarter note for this file.
96 ``note_count`` Total note count across all bars.
97 ``key_guess`` Krumhansl-Schmuckler key estimate (e.g. ``"G major"``).
98 ``bar_count`` Number of bars with at least one note.
99 """
100
101 track_id: str
102 file_path: str
103 content_hash: str
104 bars: dict[str, BarChunk]
105 ticks_per_beat: int
106 note_count: int
107 key_guess: str
108 bar_count: int
109
110
111 class MusicManifest(TypedDict):
112 """Top-level hierarchical manifest for a music snapshot.
113
114 This is the sidecar companion to the standard :class:`~muse.domain.SnapshotManifest`.
115 The ``files`` field is identical to the flat manifest — the core engine
116 reads only ``files`` for content addressing. The ``tracks`` field is
117 additive richness for music-domain queries, diff, and merge.
118
119 ``schema_version`` Always ``2`` for this format.
120 ``snapshot_id`` The snapshot this manifest belongs to.
121 ``files`` Standard flat ``{path: sha256}`` manifest (compat layer).
122 ``tracks`` ``{path: TrackManifest}`` for each MIDI file.
123 """
124
125 domain: Literal["midi"]
126 schema_version: Literal[2]
127 snapshot_id: str
128 files: dict[str, str]
129 tracks: dict[str, TrackManifest]
130
131
132 # ---------------------------------------------------------------------------
133 # Builders
134 # ---------------------------------------------------------------------------
135
136
137 def _bar_chunk_hash(notes: list[NoteInfo]) -> str:
138 """Return a SHA-256 of the canonical JSON of a bar's notes."""
139 payload = json.dumps(
140 [
141 {
142 "pitch": n.pitch,
143 "velocity": n.velocity,
144 "start_tick": n.start_tick,
145 "duration_ticks": n.duration_ticks,
146 "channel": n.channel,
147 }
148 for n in sorted(notes, key=lambda n: (n.start_tick, n.pitch))
149 ],
150 sort_keys=True,
151 separators=(",", ":"),
152 ).encode()
153 return hashlib.sha256(payload).hexdigest()
154
155
156 def build_bar_chunk(bar_num: int, notes: list[NoteInfo]) -> BarChunk:
157 """Build a :class:`BarChunk` descriptor for *bar_num*.
158
159 Args:
160 bar_num: 1-indexed bar number.
161 notes: All notes in this bar.
162
163 Returns:
164 A populated :class:`BarChunk`.
165 """
166 pcs = frozenset(n.pitch_class for n in notes)
167 chord = detect_chord(pcs)
168 pitches = [n.pitch for n in notes]
169 pitch_range: list[int] = [min(pitches), max(pitches)] if pitches else [0, 0]
170 return BarChunk(
171 bar=bar_num,
172 chunk_hash=_bar_chunk_hash(notes),
173 note_count=len(notes),
174 chord=chord,
175 pitch_range=pitch_range,
176 )
177
178
179 def build_track_manifest(
180 notes: list[NoteInfo],
181 file_path: str,
182 content_hash: str,
183 ticks_per_beat: int,
184 ) -> TrackManifest:
185 """Build a :class:`TrackManifest` from a parsed note list.
186
187 Args:
188 notes: All notes extracted from the MIDI file.
189 file_path: Workspace-relative MIDI file path.
190 content_hash: SHA-256 of the MIDI file bytes (from the flat manifest).
191 ticks_per_beat: MIDI timing resolution.
192
193 Returns:
194 A populated :class:`TrackManifest`.
195 """
196 track_id = hashlib.sha256(file_path.encode()).hexdigest()
197 bars_map = notes_by_bar(notes)
198 bars: dict[str, BarChunk] = {}
199 for bar_num, bar_notes in sorted(bars_map.items()):
200 bars[str(bar_num)] = build_bar_chunk(bar_num, bar_notes)
201
202 key_guess = key_signature_guess(notes)
203
204 return TrackManifest(
205 track_id=track_id,
206 file_path=file_path,
207 content_hash=content_hash,
208 bars=bars,
209 ticks_per_beat=ticks_per_beat,
210 note_count=len(notes),
211 key_guess=key_guess,
212 bar_count=len(bars),
213 )
214
215
216 def build_music_manifest(
217 file_manifest: dict[str, str],
218 root: "pathlib.Path",
219 snapshot_id: str = "",
220 ) -> MusicManifest:
221 """Build a :class:`MusicManifest` from a flat file manifest.
222
223 For each ``.mid`` file in *file_manifest*, loads the MIDI bytes from the
224 object store, parses notes, and builds a :class:`TrackManifest`.
225
226 Non-MIDI files appear only in ``files`` — they have no ``TrackManifest``.
227
228 Args:
229 file_manifest: Standard ``{path: sha256}`` manifest.
230 root: Repository root for object store access.
231 snapshot_id: The snapshot ID this manifest belongs to.
232
233 Returns:
234 A populated :class:`MusicManifest`. Tracks whose MIDI bytes are
235 unreadable or unparseable are silently omitted from ``tracks`` but
236 still appear in ``files``.
237 """
238 import pathlib as _pathlib
239 from muse.core.object_store import read_object
240
241 tracks: dict[str, TrackManifest] = {}
242
243 for path, content_hash in sorted(file_manifest.items()):
244 if not path.lower().endswith(".mid"):
245 continue
246 raw = read_object(root, content_hash)
247 if raw is None:
248 logger.debug("⚠️ Object %s for %r not in store — skipping manifest", content_hash[:8], path)
249 continue
250 try:
251 keys, tpb = extract_notes(raw)
252 except ValueError as exc:
253 logger.debug("⚠️ Cannot parse MIDI %r: %s — skipping manifest", path, exc)
254 continue
255 notes = [NoteInfo.from_note_key(k, tpb) for k in keys]
256 tracks[path] = build_track_manifest(notes, path, content_hash, tpb)
257
258 return MusicManifest(
259 domain="midi",
260 schema_version=2,
261 snapshot_id=snapshot_id,
262 files=dict(file_manifest),
263 tracks=tracks,
264 )
265
266
267 # ---------------------------------------------------------------------------
268 # Persistence
269 # ---------------------------------------------------------------------------
270
271
272 def _manifest_path(repo_root: pathlib.Path, snapshot_id: str) -> pathlib.Path:
273 return repo_root / _MANIFEST_DIR / f"{snapshot_id}.json"
274
275
276 def write_music_manifest(
277 repo_root: pathlib.Path,
278 manifest: MusicManifest,
279 ) -> pathlib.Path:
280 """Persist *manifest* to ``.muse/music_manifests/<snapshot_id>.json``.
281
282 Args:
283 repo_root: Repository root.
284 manifest: The manifest to write.
285
286 Returns:
287 Path to the written file.
288 """
289 snapshot_id = manifest.get("snapshot_id", "")
290 if not snapshot_id:
291 raise ValueError("MusicManifest.snapshot_id must be non-empty")
292 path = _manifest_path(repo_root, snapshot_id)
293 path.parent.mkdir(parents=True, exist_ok=True)
294 path.write_text(json.dumps(manifest, indent=2) + "\n")
295 logger.debug(
296 "✅ Music manifest written: %s (%d tracks)",
297 snapshot_id[:8],
298 len(manifest["tracks"]),
299 )
300 return path
301
302
303 def read_music_manifest(
304 repo_root: pathlib.Path,
305 snapshot_id: str,
306 ) -> MusicManifest | None:
307 """Load the music manifest for *snapshot_id*, or ``None`` if absent.
308
309 Args:
310 repo_root: Repository root.
311 snapshot_id: Snapshot ID.
312
313 Returns:
314 The :class:`MusicManifest`, or ``None`` when the sidecar file does
315 not exist.
316 """
317 path = _manifest_path(repo_root, snapshot_id)
318 if not path.exists():
319 return None
320 try:
321 raw: MusicManifest = json.loads(path.read_text())
322 return raw
323 except (json.JSONDecodeError, KeyError) as exc:
324 logger.warning("⚠️ Corrupt music manifest %s: %s", path, exc)
325 return None
326
327
328 # ---------------------------------------------------------------------------
329 # Partial diff helper
330 # ---------------------------------------------------------------------------
331
332
333 def diff_manifests_by_bar(
334 base: MusicManifest,
335 target: MusicManifest,
336 ) -> dict[str, list[int]]:
337 """Return a per-track list of bars that changed between two manifests.
338
339 Uses the per-bar ``chunk_hash`` values to detect changes without
340 loading any MIDI bytes.
341
342 Args:
343 base: Ancestor manifest.
344 target: Newer manifest.
345
346 Returns:
347 ``{track_path: [changed_bar_numbers]}`` for all tracks where at
348 least one bar differs. Tracks added or removed appear with ``[-1]``
349 as a sentinel indicating the whole track changed.
350 """
351 changed: dict[str, list[int]] = {}
352
353 all_tracks = set(base["tracks"]) | set(target["tracks"])
354
355 for track in sorted(all_tracks):
356 base_track = base["tracks"].get(track)
357 target_track = target["tracks"].get(track)
358
359 if base_track is None or target_track is None:
360 changed[track] = [-1]
361 continue
362
363 if base_track["content_hash"] == target_track["content_hash"]:
364 continue
365
366 # Content changed — find which bars.
367 base_bars = base_track["bars"]
368 target_bars = target_track["bars"]
369 all_bar_keys = set(base_bars) | set(target_bars)
370
371 changed_bars: list[int] = []
372 for bar_key in sorted(all_bar_keys, key=lambda k: int(k)):
373 base_chunk = base_bars.get(bar_key)
374 target_chunk = target_bars.get(bar_key)
375 if base_chunk is None or target_chunk is None:
376 changed_bars.append(int(bar_key))
377 elif base_chunk["chunk_hash"] != target_chunk["chunk_hash"]:
378 changed_bars.append(int(bar_key))
379
380 if changed_bars:
381 changed[track] = sorted(changed_bars)
382
383 return changed