From 1f6c3eb7e17250f00ecbac26c0d79c6f5ddf14cf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 20 Aug 2026 13:45:59 +0000 Subject: [PATCH 1/6] =?UTF-8?q?test(swang):=20SWG-4A-05=20step=20A=20red?= =?UTF-8?q?=20=E2=80=94=20the=20writer's=20musical=20leaves?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tests-only. Eighteen red, one green — and the green one is deliberate: it pins SWG-4A-04's inline note byte for byte, because this slice must add `marks [accent]` and `position { … }` without moving a byte of what already worked. What the eighteen pin, all decided by the accepted census: **`marks` is a set.** Canonical order is `NoteMark::ALL`, which is what `NoteMarks::iter` already yields. Two tests separate that from the orders a writer reaches for on its own: `ghost` before `dead_note` is `ALL` order and the reverse is alphabetical, and the same set written from either insertion order must produce identical bytes. A set has no author order to preserve. **A note with a position becomes multiline**, in §6.1's exact shape, while a note without one stays on its line even when marked. The layout follows the note's own contents, which is the rule §6.2 states for `group` and `source`. **Eight span techniques, eight distinct spellings**, checked both ways — `contains` alone would be satisfied by two techniques mapped to one word, which is a fact the diff reports and the text would lose. **Slot order versus element order**, §6.2's two rules meeting in one construct: every atom precedes every span, and within `technique_spans` the vector order stands unsorted. **The ugly inhabited states of §3**, written rather than corrected: a position's string past the end of the tuning, a span's range far outside its group's atoms, `Explicit` evidence at 0 bps, `InferredFromMidi` at 10 000. §2.6 is explicit that the source/confidence pairing is not enforced by the type, so tidying it here would delete a fact an importer recorded. **§3's sixth clause becomes reachable.** SWG-4A-04 left span tick ranges out of the domain walk on purpose — the frontier refused spans, so the writer could not emit one and the clause had nothing to guard. Writing them changes that, and an inverted span range must now yield `OutsideWriterDomain` carrying the model's `InvalidTickRange`. A seventh clause for `ConfidenceBps` is refused with a test saying why: its field is private and its constructor is the only way in, so the range is enforced by the type, and adding a check would be the writer inventing validation §3 forbids. Refs SWG-4A-05 Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_018vdRzztKXy8bA16tEzwgLE --- swang/tests/exact_writer_metadata.rs | 583 +++++++++++++++++++++++++++ 1 file changed, 583 insertions(+) create mode 100644 swang/tests/exact_writer_metadata.rs diff --git a/swang/tests/exact_writer_metadata.rs b/swang/tests/exact_writer_metadata.rs new file mode 100644 index 00000000..a97760e6 --- /dev/null +++ b/swang/tests/exact_writer_metadata.rs @@ -0,0 +1,583 @@ +//! SWG-4A-05 step A: the writer's musical leaves — marks, positions, +//! technique spans, and the evidence on both — committed failing before any +//! implementation. +//! +//! This is the last exact-writer slice. SWG-4A-04 wrote the structure and +//! refused everything below it by name; step A reds the musical half of what +//! it refused, step B the metadata half, and one GREEN answers both. +//! +//! Every expectation is a decision `docs/swang/exact-score-text.md` already +//! made. Three of them are the ones a writer gets wrong on its own: +//! +//! - `marks` is a **set**, so its canonical order is `NoteMark::ALL` and not +//! the order bits were set, and not alphabetical either; +//! - a span's range and a position's string may sit outside anything the +//! group or the tuning would suggest, and §3 lists both as inhabited; +//! - evidence is two independent facts. `Explicit` at 0 bps and +//! `InferredFromMidi` at 10 000 both exist and are written literally +//! (§2.6) — an importer's problem, never a licence for the text to tidy +//! the model. +//! +//! A few tests here pass already: they pin bytes SWG-4A-03 and SWG-4A-04 +//! produce and that this slice must not move. They are marked where they sit. + +// The allowances the repository's other test files take. +#![allow( + clippy::expect_used, + clippy::unwrap_used, + clippy::panic, + clippy::indexing_slicing, + clippy::missing_assert_message +)] + +use griff_core::event::{ + ConfidenceBps, FretboardPosition, NoteMark, NoteMarks, NotePosition, Pitch, SpanTechnique, + TechniqueEvidence, TechniqueSource, Tempo, Ticks, TimeSignature, Tuning, ValidationError, + Velocity, +}; +use griff_core::score::{ + AtomEvent, AtomNote, AtomRest, EventGroup, EventGroupKind, LossReport, MasterBar, RepeatMarker, + Score, TechniqueSpan, Track, Voice, +}; +use griff_core::slice::TickRange; +use griff_swang::exact::{write_score, ExactWriteError}; + +// ── fixtures ─────────────────────────────────────────────────────────────── + +fn range(start: u32, end: u32) -> TickRange { + TickRange::new(Ticks(start), Ticks(end)).expect("ordered range") +} + +fn bar() -> MasterBar { + MasterBar { + index: 0, + tick_range: range(0, 1920), + time_signature: TimeSignature::new(4, 4).expect("4/4"), + tempo: Tempo::from_bpm_integer(120).expect("120 BPM"), + repeat: RepeatMarker::default(), + } +} + +fn note(at: u32, duration: u32, pitch: u8, velocity: u8) -> AtomNote { + AtomNote { + absolute_start: Ticks(at), + duration: Ticks(duration), + pitch: Pitch::new(pitch).expect("a MIDI pitch"), + velocity: Velocity::new(velocity).expect("a MIDI velocity"), + marks: NoteMarks::empty(), + position: None, + } +} + +fn marks_of(set: &[NoteMark]) -> NoteMarks { + set.iter() + .fold(NoteMarks::empty(), |acc, &mark| acc.with(mark)) +} + +fn evidence(source: TechniqueSource, bps: u16) -> TechniqueEvidence { + TechniqueEvidence { + source, + confidence: ConfidenceBps::new(bps).expect("in range"), + } +} + +fn span(technique: SpanTechnique, start: u32, end: u32) -> TechniqueSpan { + TechniqueSpan { + technique, + tick_range: range(start, end), + evidence: TechniqueEvidence::explicit(), + } +} + +/// A score holding one group, so a single fact is easy to isolate. +fn scored(group: EventGroup) -> Score { + Score { + ticks_per_quarter: 480, + master_bars: vec![bar()], + tracks: vec![Track { + name: None, + channel: 0, + voices: vec![Voice { + id: 0, + event_groups: vec![group], + }], + tuning: Tuning::new(Vec::new()), + }], + source_meta: None, + loss: LossReport::new(), + } +} + +fn one_note(atom: AtomNote) -> Score { + scored(EventGroup { + kind: EventGroupKind::Single, + atoms: vec![AtomEvent::Note(atom)], + technique_spans: Vec::new(), + }) +} + +fn write(score: &Score) -> String { + write_score(score).expect("this score is inside the writer domain") +} + +// ── marks: a set, in `NoteMark::ALL` order ───────────────────────────────── + +/// Passes already — the byte this slice must not move. +#[test] +fn an_empty_mark_set_keeps_the_inline_note_form() { + let text = write(&one_note(note(0, 480, 40, 96))); + assert!( + text.contains("note { at 0 duration 480 pitch 40 velocity 96 marks [] }"), + "SWG-4A-04's inline note is unchanged: {text:?}" + ); +} + +#[test] +fn a_single_mark_keeps_the_note_inline() { + let mut atom = note(0, 480, 47, 96); + atom.marks = marks_of(&[NoteMark::Accent]); + let text = write(&one_note(atom)); + assert!( + text.contains("note { at 0 duration 480 pitch 47 velocity 96 marks [accent] }"), + "a marked note without a position is still one line — §6.1: {text:?}" + ); +} + +#[test] +fn marks_are_written_in_note_mark_all_order() { + let mut atom = note(0, 480, 60, 80); + atom.marks = marks_of(&NoteMark::ALL); + let text = write(&one_note(atom)); + assert!( + text.contains( + "marks [accent ghost staccato dead_note harmonic_natural harmonic_pinch tap]" + ), + "the declaration order of NoteMark::ALL, which is what NoteMarks::iter yields: {text:?}" + ); +} + +#[test] +fn marks_are_not_sorted_alphabetically() { + // `ghost` precedes `dead_note` in `ALL` and follows it alphabetically, so + // this pair separates the canonical order from the tidy-looking one. A + // set has no author order to preserve; `ALL` is the only order there is. + let mut atom = note(0, 480, 60, 80); + atom.marks = marks_of(&[NoteMark::DeadNote, NoteMark::Ghost]); + let text = write(&one_note(atom)); + assert!(text.contains("marks [ghost dead_note]"), "{text:?}"); + assert!(!text.contains("marks [dead_note ghost]"), "{text:?}"); +} + +#[test] +fn the_insertion_order_of_marks_does_not_reach_the_text() { + let mut forwards = note(0, 480, 60, 80); + forwards.marks = marks_of(&[NoteMark::Accent, NoteMark::Tap]); + let mut backwards = note(0, 480, 60, 80); + backwards.marks = marks_of(&[NoteMark::Tap, NoteMark::Accent]); + assert_eq!( + write(&one_note(forwards)), + write(&one_note(backwards)), + "the same set writes the same bytes whichever bit was set first" + ); +} + +// ── position: the multiline note ─────────────────────────────────────────── + +#[test] +fn a_note_with_a_position_uses_the_multiline_form() { + let mut atom = note(720, 160, 52, 80); + atom.position = Some(NotePosition { + position: FretboardPosition { string: 4, fret: 2 }, + evidence: evidence(TechniqueSource::InferredFromMidi, 5_000), + }); + let text = write(&one_note(atom)); + assert!( + text.contains( + "\ + note { + at 720 + duration 160 + pitch 52 + velocity 80 + marks [] + position { + string 4 + fret 2 + evidence { source inferred_from_midi confidence 5000 } + } + } +" + ), + "§6.1's shape, byte for byte: {text:?}" + ); +} + +#[test] +fn a_position_string_beyond_the_tuning_is_written_not_refused() { + // §3 lists this as inhabited. The writer is not a fretboard validator. + let mut atom = note(0, 480, 60, 80); + atom.position = Some(NotePosition { + position: FretboardPosition { + string: 9, + fret: 200, + }, + evidence: TechniqueEvidence::explicit(), + }); + let text = write(&one_note(atom)); + assert!(text.contains("string 9"), "{text:?}"); + assert!(text.contains("fret 200"), "{text:?}"); +} + +#[test] +fn position_evidence_is_written_without_normalization() { + // §2.6: the pairing is not enforced by the type, so both odd + // combinations are model-valid and both must be spellable. + let mut explicit_at_zero = note(0, 480, 60, 80); + explicit_at_zero.position = Some(NotePosition { + position: FretboardPosition { string: 1, fret: 0 }, + evidence: evidence(TechniqueSource::Explicit, 0), + }); + assert!( + write(&one_note(explicit_at_zero)).contains("evidence { source explicit confidence 0 }"), + "explicit at zero confidence is written as it stands" + ); + + let mut inferred_at_max = note(0, 480, 60, 80); + inferred_at_max.position = Some(NotePosition { + position: FretboardPosition { string: 1, fret: 0 }, + evidence: evidence(TechniqueSource::InferredFromMidi, 10_000), + }); + assert!( + write(&one_note(inferred_at_max)) + .contains("evidence { source inferred_from_midi confidence 10000 }"), + "and so is inferred at full confidence" + ); +} + +// ── technique spans ──────────────────────────────────────────────────────── + +#[test] +fn every_span_technique_has_its_own_spelling() { + let techniques = [ + (SpanTechnique::Slide, "span slide {"), + (SpanTechnique::Bend, "span bend {"), + (SpanTechnique::Legato, "span legato {"), + (SpanTechnique::PalmMute, "span palm_mute {"), + (SpanTechnique::HammerOn, "span hammer_on {"), + (SpanTechnique::PullOff, "span pull_off {"), + (SpanTechnique::Vibrato, "span vibrato {"), + (SpanTechnique::LetRing, "span let_ring {"), + ]; + for (technique, spelling) in techniques { + let text = write(&scored(EventGroup { + kind: EventGroupKind::Single, + atoms: vec![AtomEvent::Note(note(0, 480, 40, 96))], + technique_spans: vec![span(technique, 0, 480)], + })); + assert!( + text.contains(spelling), + "{technique:?} is spelled {spelling:?}: {text:?}" + ); + } +} + +#[test] +fn the_eight_span_spellings_are_distinct() { + // Guards what the loop above cannot see: two techniques mapped to one + // word satisfy every `contains` and lose a fact the diff reports. + let mut texts: Vec = [ + SpanTechnique::Slide, + SpanTechnique::Bend, + SpanTechnique::Legato, + SpanTechnique::PalmMute, + SpanTechnique::HammerOn, + SpanTechnique::PullOff, + SpanTechnique::Vibrato, + SpanTechnique::LetRing, + ] + .into_iter() + .map(|technique| { + write(&scored(EventGroup { + kind: EventGroupKind::Single, + atoms: Vec::new(), + technique_spans: vec![span(technique, 0, 480)], + })) + }) + .collect(); + texts.sort(); + let before = texts.len(); + texts.dedup(); + assert_eq!( + before, + texts.len(), + "each technique writes a distinct document" + ); +} + +#[test] +fn a_span_matches_its_reference_shape() { + let text = write(&scored(EventGroup { + kind: EventGroupKind::Chord, + atoms: Vec::new(), + technique_spans: vec![span(SpanTechnique::PalmMute, 0, 480)], + })); + assert!( + text.contains( + "\ + span palm_mute { + ticks 0..480 + evidence { source explicit confidence 10000 } + } +" + ), + "§6.1's shape, byte for byte: {text:?}" + ); +} + +#[test] +fn spans_are_written_after_every_atom() { + // §6.2 rule 1: `atom *` then `span *`, in the order the census lists. + let text = write(&scored(EventGroup { + kind: EventGroupKind::Chord, + atoms: vec![ + AtomEvent::Note(note(0, 480, 40, 96)), + AtomEvent::Rest(AtomRest { + absolute_start: Ticks(480), + duration: Ticks(240), + }), + ], + technique_spans: vec![span(SpanTechnique::PalmMute, 0, 480)], + })); + let last_atom = text.find("rest {").expect("the rest is written"); + let first_span = text.find("span ").expect("the span is written"); + assert!( + last_atom < first_span, + "every atom precedes every span within one group: {text:?}" + ); +} + +#[test] +fn spans_keep_their_vector_order() { + // §6.2 rule 2: within one repeated slot, encounter order is semantics. + let text = write(&scored(EventGroup { + kind: EventGroupKind::Single, + atoms: Vec::new(), + technique_spans: vec![ + span(SpanTechnique::Vibrato, 960, 1440), + span(SpanTechnique::Bend, 0, 480), + ], + })); + let vibrato = text.find("span vibrato").expect("first span"); + let bend = text.find("span bend").expect("second span"); + assert!( + vibrato < bend, + "spans are not sorted by technique or by tick: {text:?}" + ); +} + +#[test] +fn a_span_range_outside_its_group_is_written_not_refused() { + // §3 lists this as inhabited: the writer does not check containment. + let text = write(&scored(EventGroup { + kind: EventGroupKind::Single, + atoms: vec![AtomEvent::Note(note(0, 120, 40, 96))], + technique_spans: vec![span(SpanTechnique::LetRing, 9_000, 99_000)], + })); + assert!(text.contains("ticks 9000..99000"), "{text:?}"); +} + +#[test] +fn span_evidence_is_written_without_normalization() { + let mut odd = span(SpanTechnique::Slide, 0, 480); + odd.evidence = evidence(TechniqueSource::Explicit, 0); + assert!( + write(&scored(EventGroup { + kind: EventGroupKind::Single, + atoms: Vec::new(), + technique_spans: vec![odd], + })) + .contains("evidence { source explicit confidence 0 }"), + "the writer does not repair an importer's evidence" + ); +} + +// ── the domain grows to cover a span's range ─────────────────────────────── + +#[test] +fn an_inverted_span_tick_range_is_outside_the_writer_domain() { + // SWG-4A-04 left this out on purpose: the frontier refused spans, so the + // writer could not emit one and the clause had nothing to guard. Writing + // them makes §3's sixth clause reachable here, and it must be checked. + let bad = TechniqueSpan { + technique: SpanTechnique::Bend, + // Bypasses `TickRange::new` deliberately — H5: the fields are public. + tick_range: TickRange { + start: Ticks(480), + end: Ticks(0), + }, + evidence: TechniqueEvidence::explicit(), + }; + let err = write_score(&scored(EventGroup { + kind: EventGroupKind::Single, + atoms: Vec::new(), + technique_spans: vec![bad], + })) + .expect_err("start > end"); + assert!( + matches!( + err, + ExactWriteError::OutsideWriterDomain { + reason: ValidationError::InvalidTickRange, + .. + } + ), + "the refusal carries the model's own error: {err:?}" + ); +} + +#[test] +fn a_confidence_needs_no_domain_clause() { + // `ConfidenceBps` keeps its field private and its constructor is the only + // way in, so `0..=10_000` is enforced by the type. Adding a seventh + // clause for it would be the writer inventing validation §3 forbids. + ConfidenceBps::new(10_001).expect_err("10 001 bps is out of range"); + let text = write(&scored(EventGroup { + kind: EventGroupKind::Single, + atoms: Vec::new(), + technique_spans: vec![span(SpanTechnique::Bend, 0, 480)], + })); + assert!(text.contains("confidence 10000"), "{text:?}"); +} + +// ── every musical leaf is observable in the bytes ────────────────────────── + +/// A note carrying every musical leaf at once, plus two spans. +fn rich() -> Score { + scored(EventGroup { + kind: EventGroupKind::Chord, + atoms: vec![AtomEvent::Note(AtomNote { + marks: marks_of(&[NoteMark::Accent]), + position: Some(NotePosition { + position: FretboardPosition { string: 4, fret: 2 }, + evidence: evidence(TechniqueSource::InferredFromMidi, 5_000), + }), + ..note(0, 480, 40, 96) + })], + technique_spans: vec![ + span(SpanTechnique::PalmMute, 0, 480), + span(SpanTechnique::Vibrato, 480, 960), + ], + }) +} + +/// `rich()` with its one note replaced by `edit`'s result. +fn with_note(edit: impl FnOnce(&mut AtomNote)) -> Score { + let mut score = rich(); + let group = &mut score.tracks[0].voices[0].event_groups[0]; + let AtomEvent::Note(mut atom) = group.atoms[0] else { + panic!("the fixture holds a note") + }; + edit(&mut atom); + group.atoms[0] = AtomEvent::Note(atom); + score +} + +/// `rich()` with its span vector replaced by `edit`'s result. +fn with_spans(edit: impl FnOnce(&mut Vec)) -> Score { + let mut score = rich(); + edit(&mut score.tracks[0].voices[0].event_groups[0].technique_spans); + score +} + +fn a_position(string: u8, fret: u8, source: TechniqueSource, bps: u16) -> NotePosition { + NotePosition { + position: FretboardPosition { string, fret }, + evidence: evidence(source, bps), + } +} + +#[test] +fn mutating_any_note_leaf_changes_the_text() { + let baseline = write(&rich()); + + assert_ne!( + write(&with_note(|n| n.marks = marks_of(&[NoteMark::Ghost]))), + baseline, + "the mark set is observable" + ); + assert_ne!( + write(&with_note(|n| n.position = None)), + baseline, + "position presence is observable" + ); + assert_ne!( + write(&with_note(|n| { + n.position = Some(a_position(5, 2, TechniqueSource::InferredFromMidi, 5_000)); + })), + baseline, + "the string is observable" + ); + assert_ne!( + write(&with_note(|n| { + n.position = Some(a_position(4, 3, TechniqueSource::InferredFromMidi, 5_000)); + })), + baseline, + "the fret is observable" + ); + assert_ne!( + write(&with_note(|n| { + n.position = Some(a_position(4, 2, TechniqueSource::Explicit, 5_000)); + })), + baseline, + "the position's evidence source is observable" + ); + assert_ne!( + write(&with_note(|n| { + n.position = Some(a_position(4, 2, TechniqueSource::InferredFromMidi, 5_001)); + })), + baseline, + "the position's confidence is observable" + ); +} + +#[test] +fn mutating_any_span_fact_changes_the_text() { + let baseline = write(&rich()); + + assert_ne!( + write(&with_spans(|spans| { + spans.pop(); + })), + baseline, + "span presence is observable" + ); + assert_ne!( + write(&with_spans( + |spans| spans[0].technique = SpanTechnique::Legato + )), + baseline, + "the technique is observable" + ); + assert_ne!( + write(&with_spans(|spans| spans[0].tick_range = range(24, 480))), + baseline, + "the span start is observable" + ); + assert_ne!( + write(&with_spans(|spans| spans[0].tick_range = range(0, 481))), + baseline, + "the span end is observable" + ); + assert_ne!( + write(&with_spans(|spans| { + spans[0].evidence = evidence(TechniqueSource::InferredFromMidi, 10_000); + })), + baseline, + "span evidence is observable" + ); + assert_ne!( + write(&with_spans(|spans| spans.swap(0, 1))), + baseline, + "span order is observable" + ); +} From 020587c8cd0884308d820046bab09f2cb6848eb7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 20 Aug 2026 13:48:57 +0000 Subject: [PATCH 2/6] =?UTF-8?q?test(swang):=20SWG-4A-05=20step=20B=20red?= =?UTF-8?q?=20=E2=80=94=20strings,=20source,=20and=20loss?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tests-only. Nineteen red; three pass and are the baseline this slice must not disturb — an absent `source` and a clean `loss` are still omitted, and a name needing no escape is still written through. Together with step A this is the whole of what SWG-4A-04's frontier refuses. One GREEN answers both, because the string encoder is shared by `Track.name`, `SourceMeta.format`, and `ImportWarning::Other`: splitting the implementation by field would mean holding two theories of quoting at once, and the second one always disagrees with the first eventually. ## §6.5, walked at every edge The escaped set is a frozen range list, so the tests walk the edge of every range from **both sides**. `\u{8}` and `\u{b}` and `\u{1f}` and `\u{7f}` and `\u{9f}` are escaped; `\u{9}` is escaped but by the *named* rule; space, `~`, `é`, `中`, `🎸` are written through. U+00A0 is the load-bearing one. `char::is_whitespace` says yes and §6.5 says no, so a predicate that escapes it is a Unicode table wearing §6.5's name — and §1.2 forbids exactly that, because a formatter whose fixed point moves when the build relinks a newer table does not have one. `escape_default` and any JSON encoder fail the same test for the same reason. Lowercase hex, no leading zeros, asserted positively and negatively: `\u{1f}` and not `\u{1F}`, `\u{b}` and not `\u{0b}`. One escaping witness per call site, so a correct shared helper cannot hide one caller that still writes raw. ## `source` and `loss` Three source states, three documents: absent, `source { }`, and `source { format "" }`, with the tight and multiline forms refused by name. All four warning variants against §6.2's exhaustive illustration, byte for byte. Vector order preserved, duplicates written as duplicates, and both payload indices exercised past `u32::MAX` — `track_index` at 2^32 and `bar_index` at `u64::MAX`. SWG-CORE-01 ran before this task so the metadata writer would be built on the final width; proving it only with small numbers would have made that ordering pointless. `other` stays one physical line with three `\n` in its message, which is the grammar property §6.2 states rather than a hope about the data. Two tests state the point of writing inaudible facts at all: adding a `source` or a `loss` leaves `NormalizedMusicalDiff` empty, leaves `ExactSemanticDiff` non-empty, and must change the bytes. ## The capstone §6.1's reference document, built in full and compared whole. It is the first time every part composes — transport, structure, marks, position, span, evidence, source, loss — with nothing between them out of place. The small tests stay beside it. One large golden is excellent at reporting that something broke and admirably modest about what. Refs SWG-4A-05 Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_018vdRzztKXy8bA16tEzwgLE --- swang/tests/exact_writer_document.rs | 630 +++++++++++++++++++++++++++ 1 file changed, 630 insertions(+) create mode 100644 swang/tests/exact_writer_document.rs diff --git a/swang/tests/exact_writer_document.rs b/swang/tests/exact_writer_document.rs new file mode 100644 index 00000000..d2b662c8 --- /dev/null +++ b/swang/tests/exact_writer_document.rs @@ -0,0 +1,630 @@ +//! SWG-4A-05 step B: the document-level facts — canonical strings, `source`, +//! and `loss` — committed failing before any implementation. +//! +//! Step A red the musical leaves. This reds the rest, and together they are +//! the whole of what SWG-4A-04's frontier still refuses. One GREEN answers +//! both, because the string encoder is shared: `Track.name`, +//! `SourceMeta.format`, and `ImportWarning::Other` must quote through one +//! path, and splitting the implementation by field would mean holding two +//! theories of quoting at once. +//! +//! §6.5's escaped set is a **frozen range list**, not a Unicode-table +//! predicate. `char::is_control`, `char::is_whitespace`, `escape_default`, +//! and any JSON encoder are all excluded by §1.2: a formatter whose fixed +//! point moved when the build relinked a newer Unicode table would not have +//! one. The boundary table below is what makes that checkable — it walks the +//! edge of every range in the list, from both sides. + +// The allowances the repository's other test files take. +#![allow( + clippy::expect_used, + clippy::unwrap_used, + clippy::panic, + clippy::indexing_slicing, + clippy::missing_assert_message +)] + +use griff_core::event::{ + ConfidenceBps, FretboardPosition, NoteMark, NoteMarks, NotePosition, Pitch, SpanTechnique, + TechniqueEvidence, TechniqueSource, Tempo, Ticks, TimeSignature, Tuning, Velocity, +}; +use griff_core::score::{ + AtomEvent, AtomNote, AtomRest, EventGroup, EventGroupKind, ImportWarning, LossReport, + MasterBar, RepeatMarker, Score, SourceMeta, TechniqueSpan, Track, Voice, +}; +use griff_core::semantic_diff::{exact_semantic_diff, normalized_musical_diff}; +use griff_core::slice::TickRange; +use griff_swang::exact::write_score; + +// ── fixtures ─────────────────────────────────────────────────────────────── + +fn range(start: u32, end: u32) -> TickRange { + TickRange::new(Ticks(start), Ticks(end)).expect("ordered range") +} + +fn bar(index: u64, start: u32, end: u32) -> MasterBar { + MasterBar { + index, + tick_range: range(start, end), + time_signature: TimeSignature::new(4, 4).expect("4/4"), + tempo: Tempo::from_bpm_integer(120).expect("120 BPM"), + repeat: RepeatMarker::default(), + } +} + +/// The smallest score that can carry a `source` or a `loss`. +fn document() -> Score { + Score { + ticks_per_quarter: 480, + master_bars: vec![bar(0, 0, 1920)], + tracks: Vec::new(), + source_meta: None, + loss: LossReport::new(), + } +} + +fn named(name: &str) -> Score { + let mut score = document(); + score.tracks.push(Track { + name: Some(name.to_owned()), + channel: 0, + voices: Vec::new(), + tuning: Tuning::new(Vec::new()), + }); + score +} + +fn write(score: &Score) -> String { + write_score(score).expect("this score is inside the writer domain") +} + +/// The canonical spelling of `value` as it appears after `name `. +fn quoted_name(value: &str) -> String { + let text = write(&named(value)); + let line = text + .lines() + .find(|line| line.trim_start().starts_with("name ")) + .expect("the track name is written"); + line.trim_start() + .strip_prefix("name ") + .expect("the word") + .to_owned() +} + +// ── §6.5: the frozen escaped set, walked at every edge ───────────────────── + +#[test] +fn the_two_always_escaped_characters() { + assert_eq!(quoted_name("a\"b"), r#""a\"b""#); + assert_eq!(quoted_name("a\\b"), r#""a\\b""#); +} + +#[test] +fn the_three_named_escapes() { + assert_eq!(quoted_name("a\tb"), r#""a\tb""#); + assert_eq!(quoted_name("a\nb"), r#""a\nb""#); + assert_eq!(quoted_name("a\rb"), r#""a\rb""#); +} + +#[test] +fn every_enumerated_range_is_escaped_at_both_edges() { + // §6.5's list, edge by edge: + // U+0000..=U+0008 U+000B..=U+000C U+000E..=U+001F U+007F..=U+009F + for (input, expected) in [ + ('\u{0}', r#""\u{0}""#), + ('\u{8}', r#""\u{8}""#), + ('\u{b}', r#""\u{b}""#), + ('\u{c}', r#""\u{c}""#), + ('\u{e}', r#""\u{e}""#), + ('\u{1f}', r#""\u{1f}""#), + ('\u{7f}', r#""\u{7f}""#), + ('\u{85}', r#""\u{85}""#), + ('\u{9f}', r#""\u{9f}""#), + ] { + assert_eq!( + quoted_name(&input.to_string()), + expected, + "U+{:04X} is inside the enumerated set", + u32::from(input) + ); + } +} + +#[test] +fn characters_just_outside_the_escaped_set_are_written_through() { + // The other side of each edge. A predicate that escaped one of these + // would be `is_control` or `is_whitespace` wearing §6.5's name. + for outside in [ + '\u{9}', // TAB — escaped, but by the *named* rule, not the range + '\u{20}', // space + '\u{7e}', // ~ + '\u{a0}', // NO-BREAK SPACE: `is_whitespace`, not in §6.5's list + 'é', '中', '🎸', + ] { + let quoted = quoted_name(&outside.to_string()); + if outside == '\u{9}' { + assert_eq!(quoted, r#""\t""#); + continue; + } + assert_eq!( + quoted, + format!("\"{outside}\""), + "U+{:04X} is written through as UTF-8", + u32::from(outside) + ); + } +} + +#[test] +fn hex_escapes_are_lowercase_and_unpadded() { + assert_eq!(quoted_name("\u{1f}"), r#""\u{1f}""#); + assert_ne!(quoted_name("\u{1f}"), r#""\u{1F}""#); + assert_ne!(quoted_name("\u{1f}"), r#""\u{001f}""#); + assert_eq!(quoted_name("\u{b}"), r#""\u{b}""#); + assert_ne!(quoted_name("\u{b}"), r#""\u{0b}""#); +} + +#[test] +fn an_empty_and_a_plain_string_need_no_escape_at_all() { + assert_eq!(quoted_name(""), r#""""#); + assert_eq!(quoted_name("Guitar"), r#""Guitar""#); +} + +// ── one encoder, three call sites ────────────────────────────────────────── + +#[test] +fn a_track_name_is_escaped() { + assert!(write(&named("a\"b\n")).contains(r#"name "a\"b\n""#)); +} + +#[test] +fn a_source_format_is_escaped() { + let mut score = document(); + score.source_meta = Some(SourceMeta { + format: Some("a\"b\n".to_owned()), + }); + assert!( + write(&score).contains(r#"source { format "a\"b\n" }"#), + "the same encoder reaches `source.format`" + ); +} + +#[test] +fn an_other_warning_message_is_escaped() { + let mut score = document(); + score.loss.add(ImportWarning::Other("a\"b\n".to_owned())); + assert!( + write(&score).contains(r#"other { message "a\"b\n" }"#), + "and `loss.other.message` — the third call site" + ); +} + +#[test] +fn an_other_warning_stays_one_physical_line() { + // §6.2: one warning, one line. A U+000A in the value is `\n`, never a + // real break, so this is a property of the grammar rather than of the + // data that happens to arrive. + let mut score = document(); + score + .loss + .add(ImportWarning::Other("first\nsecond\nthird".to_owned())); + let text = write(&score); + assert_eq!( + text.lines().filter(|line| line.contains("other {")).count(), + 1 + ); + assert!( + text.contains(r#"other { message "first\nsecond\nthird" }"#), + "{text:?}" + ); +} + +// ── `source`: three distinguishable states ───────────────────────────────── + +#[test] +fn an_absent_source_is_omitted() { + assert!(!write(&document()).contains("source")); +} + +#[test] +fn a_present_source_without_a_format_is_the_empty_inline_block() { + let mut score = document(); + score.source_meta = Some(SourceMeta { format: None }); + let text = write(&score); + assert!(text.contains(" source { }\n"), "{text:?}"); + assert!(!text.contains("source {}"), "not the tight form: {text:?}"); + assert!(!text.contains("source {\n"), "not multiline: {text:?}"); +} + +#[test] +fn the_three_source_states_are_three_documents() { + let absent = write(&document()); + + let mut no_format = document(); + no_format.source_meta = Some(SourceMeta { format: None }); + + let mut empty_format = document(); + empty_format.source_meta = Some(SourceMeta { + format: Some(String::new()), + }); + + let no_format = write(&no_format); + let empty_format = write(&empty_format); + assert!(empty_format.contains(r#"source { format "" }"#)); + assert_ne!(absent, no_format); + assert_ne!(no_format, empty_format); + assert_ne!(absent, empty_format); +} + +// ── `loss`: four variants, vector order, duplicates ──────────────────────── + +#[test] +fn a_clean_report_writes_no_loss_block() { + assert!(!write(&document()).contains("loss")); +} + +#[test] +fn all_four_warning_variants_match_their_canonical_layout() { + let mut score = document(); + score.loss.add(ImportWarning::TrackNameInvalidUtf8 { + track_index: 4_294_967_296, + }); + score.loss.add(ImportWarning::SmpteTimingUnsupported); + score.loss.add(ImportWarning::TempoApproximated { + bar_index: 1, + nearest_micros: 4_200_000, + }); + score.loss.add(ImportWarning::Other("example".to_owned())); + + assert!( + write(&score).contains( + "\ + loss { + track_name_invalid_utf8 { track_index 4294967296 } + smpte_timing_unsupported + tempo_approximated { bar_index 1 nearest_micros 4200000 } + other { message \"example\" } + } +" + ), + "§6.2's exhaustive illustration, byte for byte: {:?}", + write(&score) + ); +} + +#[test] +fn both_payload_indices_are_written_past_u32_max() { + // SWG-CORE-01 widened these to `u64` so that the metadata writer would be + // built on the final type. Proving it only with small numbers would have + // made that ordering pointless. + let mut score = document(); + score.loss.add(ImportWarning::TrackNameInvalidUtf8 { + track_index: u64::from(u32::MAX) + 1, + }); + score.loss.add(ImportWarning::TempoApproximated { + bar_index: u64::MAX, + nearest_micros: u32::MAX, + }); + let text = write(&score); + assert!(text.contains("track_index 4294967296"), "{text:?}"); + assert!( + text.contains("bar_index 18446744073709551615 nearest_micros 4294967295"), + "{text:?}" + ); +} + +#[test] +fn warnings_keep_their_vector_order() { + let mut score = document(); + score.loss.add(ImportWarning::Other("second".to_owned())); + score.loss.add(ImportWarning::SmpteTimingUnsupported); + score + .loss + .add(ImportWarning::TrackNameInvalidUtf8 { track_index: 0 }); + + let text = write(&score); + let positions: Vec = [ + "other", + "smpte_timing_unsupported", + "track_name_invalid_utf8", + ] + .iter() + .map(|needle| text.find(needle).expect("every warning is written")) + .collect(); + assert!( + positions.windows(2).all(|w| matches!(w, [a, b] if a < b)), + "warnings are not grouped by variant: {text:?}" + ); +} + +#[test] +fn duplicate_warnings_are_written_twice() { + let mut score = document(); + for _ in 0..3 { + score.loss.add(ImportWarning::SmpteTimingUnsupported); + } + let text = write(&score); + assert_eq!( + text.matches("smpte_timing_unsupported").count(), + 3, + "the vector holds three and the text carries three: {text:?}" + ); +} + +// ── source and loss do not sound, and must survive anyway ────────────────── + +#[test] +fn a_source_is_inaudible_to_the_normalized_diff_and_visible_to_the_exact_one() { + let plain = document(); + let mut with_source = plain.clone(); + with_source.source_meta = Some(SourceMeta { + format: Some("GP5".to_owned()), + }); + + assert!( + normalized_musical_diff(&plain, &with_source) + .differences + .is_empty(), + "nothing about the music changed" + ); + assert!( + !exact_semantic_diff(&plain, &with_source) + .differences + .is_empty(), + "and the exact contract still sees it" + ); + assert_ne!( + write(&plain), + write(&with_source), + "so the text must carry it — a receipt keeps the tax line" + ); +} + +#[test] +fn a_loss_is_inaudible_to_the_normalized_diff_and_visible_to_the_exact_one() { + let plain = document(); + let mut with_loss = plain.clone(); + with_loss.loss.add(ImportWarning::SmpteTimingUnsupported); + + assert!(normalized_musical_diff(&plain, &with_loss) + .differences + .is_empty()); + assert!(!exact_semantic_diff(&plain, &with_loss) + .differences + .is_empty()); + assert_ne!(write(&plain), write(&with_loss)); +} + +// ── every document-level fact is observable in the bytes ─────────────────── + +#[test] +fn mutating_any_document_level_fact_changes_the_text() { + let mut base = document(); + base.source_meta = Some(SourceMeta { + format: Some("GP5".to_owned()), + }); + base.loss + .add(ImportWarning::TrackNameInvalidUtf8 { track_index: 1 }); + base.loss.add(ImportWarning::TempoApproximated { + bar_index: 2, + nearest_micros: 500_000, + }); + base.loss.add(ImportWarning::Other("m".to_owned())); + let baseline = write(&base); + + let mut format = base.clone(); + format.source_meta = Some(SourceMeta { + format: Some("MIDI".to_owned()), + }); + assert_ne!(write(&format), baseline, "the source format is observable"); + + let mut variant = base.clone(); + variant.loss.warnings[0] = ImportWarning::SmpteTimingUnsupported; + assert_ne!( + write(&variant), + baseline, + "the warning variant is observable" + ); + + let mut order = base.clone(); + order.loss.warnings.swap(0, 2); + assert_ne!(write(&order), baseline, "warning order is observable"); + + let mut duplicated = base.clone(); + duplicated + .loss + .warnings + .push(ImportWarning::Other("m".to_owned())); + assert_ne!(write(&duplicated), baseline, "duplication is observable"); + + let mut track_index = base.clone(); + track_index.loss.warnings[0] = ImportWarning::TrackNameInvalidUtf8 { track_index: 2 }; + assert_ne!(write(&track_index), baseline, "track_index is observable"); + + let mut bar_index = base.clone(); + bar_index.loss.warnings[1] = ImportWarning::TempoApproximated { + bar_index: 3, + nearest_micros: 500_000, + }; + assert_ne!(write(&bar_index), baseline, "bar_index is observable"); + + let mut micros = base.clone(); + micros.loss.warnings[1] = ImportWarning::TempoApproximated { + bar_index: 2, + nearest_micros: 500_001, + }; + assert_ne!(write(µs), baseline, "nearest_micros is observable"); + + let mut message = base; + message.loss.warnings[2] = ImportWarning::Other("n".to_owned()); + assert_ne!(write(&message), baseline, "the message is observable"); +} + +// ── the whole reference document, byte for byte ──────────────────────────── + +/// §6.1's reference score, built in full. +fn reference_score() -> Score { + let mut second_bar = bar(1, 3840, 7680); + second_bar.time_signature = TimeSignature::new(7, 8).expect("7/8"); + second_bar.tempo = Tempo::from_micros_per_quarter(4_200_000).expect("100/7 BPM"); + second_bar.repeat = RepeatMarker { + start: true, + play_count: 2, + }; + + let note = |at: u32, duration: u32, pitch: u8, velocity: u8| AtomNote { + absolute_start: Ticks(at), + duration: Ticks(duration), + pitch: Pitch::new(pitch).expect("a MIDI pitch"), + velocity: Velocity::new(velocity).expect("a MIDI velocity"), + marks: NoteMarks::empty(), + position: None, + }; + + let mut accented = note(0, 480, 47, 96); + accented.marks = NoteMarks::empty().with(NoteMark::Accent); + + let mut positioned = note(720, 160, 52, 80); + positioned.position = Some(NotePosition { + position: FretboardPosition { string: 4, fret: 2 }, + evidence: TechniqueEvidence { + source: TechniqueSource::InferredFromMidi, + confidence: ConfidenceBps::new(5_000).expect("in range"), + }, + }); + + let mut loss = LossReport::new(); + loss.add(ImportWarning::TempoApproximated { + bar_index: 1, + nearest_micros: 4_200_000, + }); + + Score { + ticks_per_quarter: 960, + master_bars: vec![bar(0, 0, 3840), second_bar], + tracks: vec![Track { + name: Some("Guitar".to_owned()), + channel: 0, + voices: vec![Voice { + id: 0, + event_groups: vec![ + EventGroup { + kind: EventGroupKind::Chord, + atoms: vec![ + AtomEvent::Note(note(0, 480, 40, 96)), + AtomEvent::Note(accented), + ], + technique_spans: vec![TechniqueSpan { + technique: SpanTechnique::PalmMute, + tick_range: range(0, 480), + evidence: TechniqueEvidence::explicit(), + }], + }, + EventGroup { + kind: EventGroupKind::Single, + atoms: vec![AtomEvent::Rest(AtomRest { + absolute_start: Ticks(480), + duration: Ticks(240), + })], + technique_spans: Vec::new(), + }, + EventGroup { + kind: EventGroupKind::Tuplet { num: 3, den: 2 }, + atoms: vec![AtomEvent::Note(positioned)], + technique_spans: Vec::new(), + }, + ], + }], + tuning: Tuning::new( + [64, 59, 55, 50, 45, 40] + .into_iter() + .map(|p| Pitch::new(p).expect("a MIDI pitch")) + .collect(), + ), + }], + source_meta: Some(SourceMeta { + format: Some("GP5".to_owned()), + }), + loss, + } +} + +/// The capstone: §6.1's reference document, produced whole. +/// +/// The small tests above and in step A stay, because one large golden is +/// excellent at reporting that something broke and admirably modest about +/// what. This one proves the parts compose — transport, structure, marks, +/// position, span, evidence, source, and loss in one document with nothing +/// between them out of place. +#[test] +fn the_reference_document_is_written_byte_for_byte() { + assert_eq!( + write(&reference_score()), + "\ +swang 2 + +score { + ppqn 960 + + master_bar { + index 0 + ticks 0..3840 + meter 4/4 + tempo 120/1 + } + + master_bar { + index 1 + ticks 3840..7680 + meter 7/8 + tempo 100/7 + repeat { start true play_count 2 } + } + + track { + name \"Guitar\" + channel 0 + tuning [64 59 55 50 45 40] + + voice { + id 0 + + group chord { + note { at 0 duration 480 pitch 40 velocity 96 marks [] } + note { at 0 duration 480 pitch 47 velocity 96 marks [accent] } + span palm_mute { + ticks 0..480 + evidence { source explicit confidence 10000 } + } + } + + group single { + rest { at 480 duration 240 } + } + + group tuplet 3/2 { + note { + at 720 + duration 160 + pitch 52 + velocity 80 + marks [] + position { + string 4 + fret 2 + evidence { source inferred_from_midi confidence 5000 } + } + } + } + } + } + + source { format \"GP5\" } + + loss { + tempo_approximated { bar_index 1 nearest_micros 4200000 } + } +} +" + ); +} From 5aaec8b8b6e8bc38df7108ca8b02a2fbc1c948bb Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 20 Aug 2026 13:57:12 +0000 Subject: [PATCH 3/6] =?UTF-8?q?feat(swang)!:=20SWG-4A-05=20green=20?= =?UTF-8?q?=E2=80=94=20the=20exact=20writer=20is=20complete?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Forty-one red tests to green across steps A and B, and the writer stops being incremental. ## The leaves `marks` writes through `NoteMarks::iter`, which is `NoteMark::ALL` order — the only order a set has. A note with a `position` opens across lines and one without stays on its line however many marks it carries: the layout follows the construct's own contents, which is the rule §6.2 already states for `group` and `source`. `evidence` is one inline block shared by positions and spans, and it writes both facts as they stand. `Explicit` at 0 bps and `InferredFromMidi` at 10 000 are model-valid (§2.6) and repairing the pair here would delete what an importer recorded. Nothing checks that a `string` fits the tuning or that a span's range sits inside its group; §3 lists both as inhabited, and the writer is not a fretboard validator. Eight span techniques, matched exhaustively, written after every atom — §6.2 rule 1 fixing the order *between* slots while rule 2 leaves the order *within* `technique_spans` alone. ## One string encoder `quote` serves `track.name`, `source.format`, and `loss.other.message` — the only three strings in the canonical tree. One encoder rather than three, because three eventually disagree, and step B has a witness through each call site so a correct shared helper cannot hide one caller still writing raw. The escaped set is §6.5's frozen range list and nothing else. U+00A0 is the character that proves it: `char::is_whitespace` says escape, §6.5 says write it through, and §1.2 forbids a formatter whose fixed point moves when the build relinks a newer Unicode table. `escape_default` and any JSON encoder fail the same test for the same reason. `lower_hex` is hand-rolled because `format!` into a `String` is denied by `clippy::format_push_string`, and the alternative — `fmt::Write` into a sink that cannot fail — would hand back a `Result` there is no honest way to handle. Masks and shifts, so it cannot divide by zero either. ## `source` and `loss` Three source states, three documents. The `loss` block is multiline with one warning per line, in vector order, duplicates included — `LossReport` appends and concatenates and the exact walker compares positionally, so grouping or deduping would delete a fact. ## §3's sixth clause finds its second home SWG-4A-04 left span tick ranges out of the domain walk deliberately: its frontier refused spans, so the writer could not emit one and the clause had nothing to guard. Writing them is what made it reachable, and it is checked now. Six clauses and no seventh — `Tempo` and `ConfidenceBps` keep their fields private, so their invariants are enforced rather than advisory, and a check for either would be the writer inventing validation §3 forbids. ## The frontier is gone, and so is its error `check_slice_frontier` is deleted and `ExactWriteError::NotYetWritten` with it, now, before SWG-4A-10 — leaving it would make the CLI handle a case that cannot occur, and then hold a funeral for a dead API later. Level 2 is not frozen yet, which is exactly why this is the moment. `ExactWriteError` has one variant, and that is the point: a refusal now means one thing. Your `Score` breaks an invariant `griff-core` itself declares. The five tests that guarded `NotYetWritten` are sunset rather than deleted. Each owned a structural property that outlived the refusal — a marked note still belongs to its group, a span still follows its atoms, a `source` still sits after every track — so each keeps that and hands the leaf itself to the new suites. No 4A-03 or 4A-04 golden changed by a byte, which is the claim those goldens exist to make. Locally: 185 swang tests green, clippy `-D warnings` and fmt clean workspace-wide, `griff-core` untouched. Refs SWG-4A-05 Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_018vdRzztKXy8bA16tEzwgLE --- swang/src/exact.rs | 9 +- swang/src/exact/error.rs | 31 +- swang/src/exact/write.rs | 441 +++++++++++++++++++------- swang/tests/exact_writer_structure.rs | 139 ++++---- swang/tests/exact_writer_transport.rs | 42 ++- 5 files changed, 422 insertions(+), 240 deletions(-) diff --git a/swang/src/exact.rs b/swang/src/exact.rs index 7bb64bff..4939fbae 100644 --- a/swang/src/exact.rs +++ b/swang/src/exact.rs @@ -3,10 +3,11 @@ //! This module is the writer half: a canonical `Score` in, one canonical //! level-2 document out. The parser half arrives later and separately. //! -//! Written incrementally by slice. SWG-4A-03 covers the header, `ppqn`, and -//! the master timeline; tracks and everything below them are SWG-4A-04 and -//! after, and a `Score` carrying them is refused with -//! [`ExactWriteError::NotYetWritten`] rather than half-written. +//! Built in slices — SWG-4A-03 the transport, 4A-04 the structure, 4A-05 the +//! leaves and metadata — and **complete** since the last of them. There is no +//! part of the canonical tree it declines to spell, so the only refusal left +//! is [`ExactWriteError::OutsideWriterDomain`]: your `Score` breaks an +//! invariant `griff-core` itself declares. mod error; mod write; diff --git a/swang/src/exact/error.rs b/swang/src/exact/error.rs index 8a4ff8c0..a8e28446 100644 --- a/swang/src/exact/error.rs +++ b/swang/src/exact/error.rs @@ -7,9 +7,12 @@ use griff_core::event::ValidationError; /// A refusal from the exact-text writer. /// -/// The two variants say different things and must not be collapsed. One is -/// a judgement about the `Score`; the other is a statement about how much -/// of the writer exists yet. +/// One variant, and that is the point. While the writer was built in slices +/// this enum also carried `NotYetWritten`, a statement about how much of the +/// writer existed rather than about the score. SWG-4A-05 finished the writer, +/// so that variant described nothing and retired with the frontier it named: +/// a refusal now means exactly one thing, and no caller has to handle a case +/// that cannot occur. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExactWriteError { /// The `Score` violates an invariant `griff-core` itself declares, so @@ -26,30 +29,12 @@ pub enum ExactWriteError { /// The model's own verdict. reason: ValidationError, }, - /// The `Score` is perfectly writable in principle; this increment of - /// the writer does not reach that part of the tree yet. - /// - /// A slice boundary, never a claim that an inhabited state is - /// unspellable — the census forbids the latter, and reporting a - /// build-stage limit as a domain judgement would smuggle it in. - NotYetWritten { - /// The part of the tree that is still unimplemented. - what: &'static str, - /// The task that will write it. - task: &'static str, - }, } impl Display for ExactWriteError { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { - match self { - Self::OutsideWriterDomain { at, reason } => { - write!(f, "{at} is outside the exact writer's domain: {reason:?}") - } - Self::NotYetWritten { what, task } => { - write!(f, "{what} is not written yet; {task} adds it") - } - } + let Self::OutsideWriterDomain { at, reason } = self; + write!(f, "{at} is outside the exact writer's domain: {reason:?}") } } diff --git a/swang/src/exact/write.rs b/swang/src/exact/write.rs index 87cb1f84..f54536b5 100644 --- a/swang/src/exact/write.rs +++ b/swang/src/exact/write.rs @@ -1,5 +1,10 @@ -//! Canonical level-2 text from a canonical `Score` — transport, master -//! timeline (SWG-4A-03), and musical structure (SWG-4A-04). +//! Canonical level-2 text from a canonical `Score` — the whole document. +//! +//! Built in slices — transport (SWG-4A-03), musical structure (SWG-4A-04), +//! and the leaves and metadata (SWG-4A-05) — and complete since the last of +//! them. There is no longer a part of the canonical tree this writer declines +//! to spell: every inhabited `Score` either writes, or is refused for +//! violating an invariant `griff-core` itself declares. //! //! The census (`docs/swang/exact-score-text.md`) decided every spelling //! here; this module only obeys it. Several of those decisions are @@ -15,12 +20,19 @@ //! - `note` and `rest` are variant tags inside one slot, so they are never //! regrouped; //! - `tuning` and `marks` are scalar list values, so their empty form is -//! `[]` and never an absent word. - -use griff_core::event::{Pitch, TimeSignature, Tuning, ValidationError, Velocity}; +//! `[]` and never an absent word; +//! - `marks` is a **set**, so its order is `NoteMark::ALL` — not the order +//! bits were set, and not alphabetical; +//! - evidence is two independent facts and is never tidied into a pair that +//! looks more sensible. + +use griff_core::event::{ + NoteMark, NoteMarks, NotePosition, Pitch, SpanTechnique, TechniqueEvidence, TechniqueSource, + TimeSignature, Tuning, ValidationError, Velocity, +}; use griff_core::score::{ - AtomEvent, AtomNote, AtomRest, EventGroup, EventGroupKind, MasterBar, RepeatMarker, Score, - Track, Voice, + AtomEvent, AtomNote, AtomRest, EventGroup, EventGroupKind, ImportWarning, LossReport, + MasterBar, RepeatMarker, Score, SourceMeta, TechniqueSpan, Track, Voice, }; use griff_core::slice::TickRange; @@ -33,18 +45,14 @@ const HEADER: &str = "swang 2\n"; /// /// # Errors /// [`ExactWriteError::OutsideWriterDomain`] when the score violates an -/// invariant `griff-core` declares, and [`ExactWriteError::NotYetWritten`] -/// when it reaches a part of the tree this slice does not cover. Both are -/// returned **before any byte is produced**: a partial document is not a -/// thing this writer can emit. +/// invariant `griff-core` declares — the only refusal there is, since +/// SWG-4A-05 finished the writer. It is returned **before any byte is +/// produced**: a partial document is not a thing this writer can emit. pub fn write_score(score: &Score) -> Result { - // Domain first, frontier second, and the order is deliberate. A score - // that is both invalid and beyond this slice gets the permanent verdict, - // not the temporary one: "the finished writer will refuse this too" is - // strictly more informative than "not implemented yet", and reversing - // the checks would hide the stronger statement behind the weaker. + // The only gate left. Earlier slices ran a second, temporary check for + // the parts of the tree they could not yet spell; SWG-4A-05 spells all of + // them, so a refusal can now mean exactly one thing. check_writer_domain(score)?; - check_slice_frontier(score)?; let mut out = String::from(HEADER); out.push_str("\nscore {\n"); @@ -61,6 +69,12 @@ pub fn write_score(score: &Score) -> Result { for track in &score.tracks { write_track(&mut out, track); } + if let Some(source) = score.source_meta.as_ref() { + write_source(&mut out, source); + } + if !score.loss.is_clean() { + write_loss(&mut out, &score.loss); + } out.push_str("}\n"); Ok(out) } @@ -132,14 +146,9 @@ fn write_track(out: &mut String, track: &Track) { out.push_str("\n track {\n"); // `None` is spelled by absence; `Some("")` by `""`. The two states are - // distinguishable in the model and stay so in text (§6.2). Only names - // needing no escape reach here — the frontier refused the rest. + // distinguishable in the model and stay so in text (§6.2). if let Some(name) = track.name.as_deref() { - let mut quoted = String::with_capacity(name.len().saturating_add(2)); - quoted.push('"'); - quoted.push_str(name); - quoted.push('"'); - field(out, " ", "name", "ed); + field(out, " ", "name", "e(name)); } // No range clause exists for `channel` in `griff-core`, so `200` is @@ -199,11 +208,16 @@ fn write_group(out: &mut String, group: &EventGroup) { write_atom(out, atom); } - // A group whose atoms vector is empty still writes its block: the block + // Every atom, then every span: §6.2 rule 1 fixes the order *between* + // slots, and rule 2 leaves the order *within* each of them alone. + for span in &group.technique_spans { + write_span(out, span); + } + + // A group whose slots are both empty still writes its block: the block // is an element of `event_groups`, and it is the *elements* of a // repeated slot that vanish when there are none, not the slot's own - // container. §6.1 spells `group` across lines, and emptiness does not - // change a block's layout — see the residual noted in the task report. + // container. §6.2 states the layout; emptiness does not change it. out.push_str(" }\n"); } @@ -240,19 +254,158 @@ fn write_atom(out: &mut String, atom: &AtomEvent) { } } +/// One note. +/// +/// The layout follows the note's own contents, which is the rule §6.2 states +/// for every construct: a note carrying a `position` opens across lines, one +/// without it stays on its line however many marks it has. `marks` is a +/// required word either way and `position` is omitted when `None`. fn write_note(out: &mut String, note: AtomNote) { - out.push_str(" note { at "); - out.push_str(¬e.absolute_start.0.to_string()); - out.push_str(" duration "); - out.push_str(¬e.duration.0.to_string()); - out.push_str(" pitch "); - out.push_str(¬e.pitch.0.to_string()); - out.push_str(" velocity "); - out.push_str(¬e.velocity.0.to_string()); - // A required word whose empty form is `[]` (§6.2), exactly like - // `tuning`. Only empty sets reach here; the mark vocabulary is 4A-05's, - // and `position` — omitted when `None` — is refused when present. - out.push_str(" marks [] }\n"); + let Some(position) = note.position else { + out.push_str(" note { at "); + out.push_str(¬e.absolute_start.0.to_string()); + out.push_str(" duration "); + out.push_str(¬e.duration.0.to_string()); + out.push_str(" pitch "); + out.push_str(¬e.pitch.0.to_string()); + out.push_str(" velocity "); + out.push_str(¬e.velocity.0.to_string()); + out.push_str(" marks "); + out.push_str(&mark_list(note.marks)); + out.push_str(" }\n"); + return; + }; + + out.push_str(" note {\n"); + field( + out, + " ", + "at", + ¬e.absolute_start.0.to_string(), + ); + field( + out, + " ", + "duration", + ¬e.duration.0.to_string(), + ); + field( + out, + " ", + "pitch", + ¬e.pitch.0.to_string(), + ); + field( + out, + " ", + "velocity", + ¬e.velocity.0.to_string(), + ); + field(out, " ", "marks", &mark_list(note.marks)); + write_position(out, position); + out.push_str(" }\n"); +} + +/// `[m1 m2 …]`, or `[]` — the one spelling of a mark list (§6.3). +/// +/// The order is `NoteMark::ALL`, which is what `NoteMarks::iter` yields. A +/// set has no author order to preserve, so `ALL` is the only order there is; +/// sorting the words alphabetically would look tidier and be wrong. +fn mark_list(marks: NoteMarks) -> String { + let mut out = String::from("["); + for (position, mark) in marks.iter().enumerate() { + if position > 0 { + out.push(' '); + } + out.push_str(mark_word(mark)); + } + out.push(']'); + out +} + +/// The seven mark spellings (§6.4). +const fn mark_word(mark: NoteMark) -> &'static str { + match mark { + NoteMark::Accent => "accent", + NoteMark::Ghost => "ghost", + NoteMark::Staccato => "staccato", + NoteMark::DeadNote => "dead_note", + NoteMark::HarmonicNatural => "harmonic_natural", + NoteMark::HarmonicPinch => "harmonic_pinch", + NoteMark::Tap => "tap", + } +} + +/// One `position` block, with its own evidence. +/// +/// No check that `string` fits the track's tuning: §3 lists a string beyond +/// the tuning as inhabited, and the writer is not a fretboard validator. +fn write_position(out: &mut String, position: NotePosition) { + out.push_str(" position {\n"); + field( + out, + " ", + "string", + &position.position.string.to_string(), + ); + field( + out, + " ", + "fret", + &position.position.fret.to_string(), + ); + out.push_str(" "); + out.push_str(&evidence_block(position.evidence)); + out.push('\n'); + out.push_str(" }\n"); +} + +/// `evidence { source confidence }` — inline, as §6.1 spells it. +/// +/// The two facts are independent. `TechniqueEvidence`'s fields are public and +/// `explicit()` / `inferred()` are conveniences, so `Explicit` at 0 bps and +/// `InferredFromMidi` at 10 000 are both model-valid (§2.6) and both are +/// written as they stand. Repairing the pair here would delete what an +/// importer recorded. +fn evidence_block(evidence: TechniqueEvidence) -> String { + let mut out = String::from("evidence { source "); + out.push_str(match evidence.source { + TechniqueSource::Explicit => "explicit", + TechniqueSource::InferredFromMidi => "inferred_from_midi", + }); + out.push_str(" confidence "); + out.push_str(&evidence.confidence.get().to_string()); + out.push_str(" }"); + out +} + +/// One `span` block. +fn write_span(out: &mut String, span: &TechniqueSpan) { + out.push_str(" span "); + out.push_str(span_word(span.technique)); + out.push_str(" {\n"); + + let ticks = format!("{}..{}", span.tick_range.start.0, span.tick_range.end.0); + field(out, " ", "ticks", &ticks); + + out.push_str(" "); + out.push_str(&evidence_block(span.evidence)); + out.push('\n'); + out.push_str(" }\n"); +} + +/// The eight `SpanTechnique` spellings (§6.4), matched exhaustively. +const fn span_word(technique: SpanTechnique) -> &'static str { + match technique { + SpanTechnique::Slide => "slide", + SpanTechnique::Bend => "bend", + SpanTechnique::Legato => "legato", + SpanTechnique::PalmMute => "palm_mute", + SpanTechnique::HammerOn => "hammer_on", + SpanTechnique::PullOff => "pull_off", + SpanTechnique::Vibrato => "vibrato", + SpanTechnique::LetRing => "let_ring", + } } fn write_rest(out: &mut String, rest: AtomRest) { @@ -265,6 +418,70 @@ fn write_rest(out: &mut String, rest: AtomRest) { out.push_str(" }\n"); } +// ── document metadata (SWG-4A-05) ───────────────────────────────────────── + +/// One `source` block, inline (§6.2). +/// +/// Reached only when `source_meta` is `Some`. `None` is spelled by absence, +/// and `Some(SourceMeta { format: None })` is the empty body `source { }` — +/// three states, three documents, because the exact walker compares +/// `SourceMeta` and `Format` as separate fields (§2.1). +fn write_source(out: &mut String, source: &SourceMeta) { + out.push_str("\n source {"); + if let Some(format) = source.format.as_deref() { + out.push_str(" format "); + out.push_str("e(format)); + } + out.push_str(" }\n"); +} + +/// One `loss` block — multiline, one warning per line (§6.2). +/// +/// Reached only when the report is non-clean; a clean one is omitted whole. +/// Warning order is vector order and duplicates are duplicates: `LossReport` +/// appends and concatenates, and the exact walker compares positionally. +fn write_loss(out: &mut String, loss: &LossReport) { + out.push_str("\n loss {\n"); + for warning in &loss.warnings { + write_warning(out, warning); + } + out.push_str(" }\n"); +} + +/// One warning, one physical line. +/// +/// True whatever an `Other` message holds: a U+000A in the value is written +/// `\n` by §6.5's frozen policy, never as a real break. +fn write_warning(out: &mut String, warning: &ImportWarning) { + out.push_str(" "); + match warning { + ImportWarning::TrackNameInvalidUtf8 { track_index } => { + out.push_str("track_name_invalid_utf8 { track_index "); + out.push_str(&track_index.to_string()); + out.push_str(" }"); + } + ImportWarning::SmpteTimingUnsupported => { + out.push_str("smpte_timing_unsupported"); + } + ImportWarning::TempoApproximated { + bar_index, + nearest_micros, + } => { + out.push_str("tempo_approximated { bar_index "); + out.push_str(&bar_index.to_string()); + out.push_str(" nearest_micros "); + out.push_str(&nearest_micros.to_string()); + out.push_str(" }"); + } + ImportWarning::Other(message) => { + out.push_str("other { message "); + out.push_str("e(message)); + out.push_str(" }"); + } + } + out.push('\n'); +} + // ── the writer domain (census §3) ────────────────────────────────────────── /// Re-checks the invariants `griff-core` already declares. @@ -278,14 +495,16 @@ fn write_rest(out: &mut String, rest: AtomRest) { /// public), which is exactly why the writer must run them again on values /// that may never have passed through them. /// -/// **Reach.** The walk covers exactly what this slice can emit. All six of -/// §3's clauses are present — `ppqn`, pitch, velocity, meter numerator, -/// meter denominator, tick range — each applied wherever the writer would -/// otherwise put the value in a document. Technique spans carry a -/// `TickRange` and are *not* walked, because the frontier refuses any score -/// holding one: the writer cannot emit text its own builder would reject, -/// which is the property §3 exists to guarantee. When 4A-05 starts writing -/// spans, their ranges join this walk. +/// **Reach.** Complete since SWG-4A-05. All six of §3's clauses are present — +/// `ppqn`, pitch, velocity, meter numerator, meter denominator, tick range — +/// each applied everywhere the writer puts such a value in a document, which +/// is now everywhere the canonical tree holds one. The tick-range clause has +/// two homes: a master bar's range and every technique span's. +/// +/// Six clauses and no seventh. `Tempo` positivity and `ConfidenceBps` range +/// need none: those types keep their fields private, so the constructor is +/// the only way in and the invariant is enforced rather than advisory. Adding +/// a check for either would be the writer inventing validation §3 forbids. fn check_writer_domain(score: &Score) -> Result<(), ExactWriteError> { if score.ticks_per_quarter == 0 { return Err(ExactWriteError::OutsideWriterDomain { @@ -330,6 +549,18 @@ fn check_track_domain(track: &Track) -> Result<(), ExactWriteError> { check_note_domain(note)?; } } + // The sixth clause's other home. SWG-4A-04 left this out because + // its frontier refused spans outright, so the writer could not + // emit one and the clause had nothing to guard; writing them is + // exactly what makes it reachable. + for span in &group.technique_spans { + TickRange::new(span.tick_range.start, span.tick_range.end).map_err(|reason| { + ExactWriteError::OutsideWriterDomain { + at: "span.ticks", + reason, + } + })?; + } } } Ok(()) @@ -347,81 +578,61 @@ fn check_note_domain(note: AtomNote) -> Result<(), ExactWriteError> { Ok(()) } -// ── this slice's frontier ────────────────────────────────────────────────── +// ── strings (census §6.5) ────────────────────────────────────────────────── -/// Refuses the parts of the tree SWG-4A-04 does not write yet. +/// The one canonical spelling of `value` as a quoted string. /// -/// Not a claim about representability: every state named here is spellable -/// under the accepted grammar, and SWG-4A-05 will spell it. -fn check_slice_frontier(score: &Score) -> Result<(), ExactWriteError> { - for track in &score.tracks { - // Only names written through unescaped are in this slice. Drawing - // the boundary at one field rather than dragging half of §6.5's - // encoding policy back here keeps the escape rules in one place. - if track.name.as_deref().is_some_and(needs_escape) { - return Err(ExactWriteError::NotYetWritten { - what: "track.name needing an escape", - task: "SWG-4A-05", - }); - } - for voice in &track.voices { - for group in &voice.event_groups { - if !group.technique_spans.is_empty() { - return Err(ExactWriteError::NotYetWritten { - what: "group.span", - task: "SWG-4A-05", - }); - } - for atom in &group.atoms { - if let AtomEvent::Note(note) = *atom { - check_note_frontier(note)?; - } - } +/// Shared by `track.name`, `source.format`, and `loss.other.message` — the +/// only three strings in the canonical tree. One encoder rather than three, +/// because three would eventually disagree. +/// +/// The escaped set is §6.5's **frozen range list** and nothing else. Not +/// `char::is_control`, not `char::is_whitespace`, not `escape_default`, not +/// a JSON encoder: §1.2 keeps table-dependent classification out of +/// observable semantics, and a formatter whose fixed point moved when the +/// build relinked a newer Unicode table would not have one. U+00A0 is the +/// character that tells the two apart — `is_whitespace` says yes, §6.5 says +/// write it through. +fn quote(value: &str) -> String { + let mut out = String::with_capacity(value.len().saturating_add(2)); + out.push('"'); + for c in value.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\u{0}'..='\u{8}' | '\u{b}'..='\u{c}' | '\u{e}'..='\u{1f}' | '\u{7f}'..='\u{9f}' => { + out.push_str("\\u{"); + out.push_str(&lower_hex(u32::from(c))); + out.push('}'); } + _ => out.push(c), } } - if score.source_meta.is_some() { - return Err(ExactWriteError::NotYetWritten { - what: "score.source", - task: "SWG-4A-05", - }); - } - if !score.loss.is_clean() { - return Err(ExactWriteError::NotYetWritten { - what: "score.loss", - task: "SWG-4A-05", - }); - } - Ok(()) + out.push('"'); + out } -const fn check_note_frontier(note: AtomNote) -> Result<(), ExactWriteError> { - // `marks []` is written because §6.2 makes it a required word. The mark - // vocabulary itself belongs to the slice that owns §6.4's closed sets. - if !note.marks.is_empty() { - return Err(ExactWriteError::NotYetWritten { - what: "note.marks", - task: "SWG-4A-05", - }); +/// `value` in lowercase hexadecimal with no leading zeros (§6.5). +/// +/// Hand-rolled rather than `format!("{value:x}")`, because pushing a +/// `format!` into a `String` is denied by `clippy::format_push_string` and +/// the alternative — importing `fmt::Write` to `write!` into a sink that +/// cannot fail — would hand back a `Result` there is no honest way to handle. +/// Masks and shifts, so nothing here can divide by zero either. +fn lower_hex(value: u32) -> String { + if value == 0 { + return "0".to_owned(); } - if note.position.is_some() { - return Err(ExactWriteError::NotYetWritten { - what: "note.position", - task: "SWG-4A-05", - }); + let mut reversed = String::new(); + let mut rest = value; + while rest > 0 { + // `from_digit` yields lowercase for radix 16 and cannot fail for a + // nibble, which is always below the radix. + reversed.push(char::from_digit(rest & 0xf, 16).unwrap_or('0')); + rest >>= 4; } - Ok(()) -} - -/// Whether writing `value` through unchanged would misspell it (§6.5). -/// -/// The escaped set is the frozen range list of §6.5 and nothing else — not -/// `char::is_control`, not `char::is_whitespace`, and no other Unicode-table -/// predicate. §1.2 keeps table-dependent classification out of observable -/// semantics, so a value's spelling must not change when the build relinks a -/// newer Unicode table. -fn needs_escape(value: &str) -> bool { - value - .chars() - .any(|c| matches!(c, '"' | '\\' | '\u{0}'..='\u{1f}' | '\u{7f}'..='\u{9f}')) + reversed.chars().rev().collect() } diff --git a/swang/tests/exact_writer_structure.rs b/swang/tests/exact_writer_structure.rs index 5919b48c..30e483ac 100644 --- a/swang/tests/exact_writer_structure.rs +++ b/swang/tests/exact_writer_structure.rs @@ -9,12 +9,14 @@ //! wrote them without checking them would emit text its own builder must //! later refuse. //! -//! Still refused, and refused by name: `marks` beyond the empty set, -//! `position`, technique spans, `source`, `loss`, and any string needing an -//! escape. Those are SWG-4A-05. The empty forms that a *canonical* document -//! cannot leave out — `marks []`, `tuning []` — are written here, because -//! §6.2 makes them required words and omitting them would make every golden -//! in this file non-canonical text. +//! Marks, positions, spans, `source`, `loss`, and escaped strings were +//! refused by name here and written by SWG-4A-05; the four tests that +//! guarded those refusals now check the structural half of what they owned, +//! and the leaves themselves are pinned by `exact_writer_metadata.rs`. The +//! empty forms a *canonical* document cannot leave out — `marks []`, +//! `tuning []` — were written from the start, because §6.2 makes them +//! required words and omitting them would make every golden here +//! non-canonical text. //! //! Every expectation is a decision `docs/swang/exact-score-text.md` already //! made. The ugly ones — `channel 200`, duplicate `voice.id`, `tuplet 0/0`, @@ -290,33 +292,6 @@ fn a_plain_track_name_is_written_through() { assert!(text.contains("name \"Guitar\""), "{text:?}"); } -#[test] -fn a_track_name_needing_an_escape_is_not_yet_written() { - // The 4A-04/4A-05 boundary, chosen deliberately: this slice writes only - // names that need no escape, and hands the rest to the slice that owns - // §6.5's encoding policy. Refusing is honest; inventing half an escape - // policy here would not be. - for name in ["Gui\"tar", "back\\slash", "two\nlines", "bell\u{7}"] { - let score = scored(vec![track( - Some(name), - 0, - Tuning::new(Vec::new()), - Vec::new(), - )]); - let err = write_score(&score).expect_err("this name needs an escape"); - assert!( - matches!( - err, - ExactWriteError::NotYetWritten { - task: "SWG-4A-05", - .. - } - ), - "a name needing an escape names the slice that will write it, {name:?}: {err:?}" - ); - } -} - // ── group kinds: all six, payload opened ─────────────────────────────────── #[test] @@ -565,62 +540,46 @@ fn the_domain_verdict_still_outranks_the_slice_frontier() { ); } -// ── this slice's frontier: what 4A-05 will write ─────────────────────────── +// ── what this slice's frontier once refused ─────────────────────────────── +// +// These four guarded `NotYetWritten` until SWG-4A-05 wrote the facts they +// named. The frontier is gone and so is the error variant; what each test +// owned is a *structural* property, and that is what survives here — the +// leaves themselves are pinned by `exact_writer_metadata.rs`. #[test] -fn a_non_empty_mark_set_is_not_yet_written() { - // `marks []` is written here because §6.2 makes it a required word. The - // mark vocabulary itself is 4A-05's, so a set with anything in it is - // refused rather than guessed at. +fn a_marked_note_still_belongs_to_its_group() { let marked = AtomEvent::Note(AtomNote { - absolute_start: Ticks(0), - duration: Ticks(480), - pitch: Pitch::new(60).expect("a MIDI pitch"), - velocity: Velocity::new(96).expect("a MIDI velocity"), marks: NoteMarks::empty().with(NoteMark::Accent), - position: None, + ..match note(0, 480, 60, 96) { + AtomEvent::Note(n) => n, + AtomEvent::Rest(_) => panic!("a note"), + } }); - let err = write_score(&one_atom(marked)).expect_err("marks are 4A-05"); - assert!( - matches!( - err, - ExactWriteError::NotYetWritten { - task: "SWG-4A-05", - .. - } - ), - "{err:?}" - ); + let text = write(&one_atom(marked)); + assert!(text.contains("group single {"), "{text:?}"); + assert!(text.contains("marks [accent]"), "{text:?}"); } #[test] -fn a_note_position_is_not_yet_written() { +fn a_positioned_note_still_belongs_to_its_group() { let positioned = AtomEvent::Note(AtomNote { - absolute_start: Ticks(0), - duration: Ticks(480), - pitch: Pitch::new(60).expect("a MIDI pitch"), - velocity: Velocity::new(96).expect("a MIDI velocity"), - marks: NoteMarks::empty(), position: Some(NotePosition::explicit(FretboardPosition { string: 4, fret: 2, })), + ..match note(0, 480, 60, 96) { + AtomEvent::Note(n) => n, + AtomEvent::Rest(_) => panic!("a note"), + } }); - let err = write_score(&one_atom(positioned)).expect_err("positions are 4A-05"); - assert!( - matches!( - err, - ExactWriteError::NotYetWritten { - task: "SWG-4A-05", - .. - } - ), - "{err:?}" - ); + let text = write(&one_atom(positioned)); + assert!(text.contains("group single {"), "{text:?}"); + assert!(text.contains("position {"), "{text:?}"); } #[test] -fn a_technique_span_is_not_yet_written() { +fn a_technique_span_belongs_to_its_group_after_the_atoms() { let mut only = group(EventGroupKind::Chord, vec![note(0, 480, 40, 96)]); only.technique_spans.push(TechniqueSpan { technique: SpanTechnique::PalmMute, @@ -633,19 +592,37 @@ fn a_technique_span_is_not_yet_written() { Tuning::new(Vec::new()), vec![voice(0, vec![only])], )]); - let err = write_score(&score).expect_err("spans are 4A-05"); + let text = write(&score); + let atom = text.find("note {").expect("the atom"); + let span = text.find("span palm_mute").expect("the span"); assert!( - matches!( - err, - ExactWriteError::NotYetWritten { - task: "SWG-4A-05", - .. - } - ), - "{err:?}" + atom < span, + "atoms precede spans within one group: {text:?}" ); } +#[test] +fn a_track_name_needing_an_escape_is_written_escaped() { + // Option 1's boundary in SWG-4A-04: names needing an escape were refused + // and handed to SWG-4A-05, which wrote them. `Some("")` and `None` stay + // distinguishable, which was the part that mattered all along. + for (name, expected) in [ + ("Gui\"tar", r#"name "Gui\"tar""#), + ("back\\slash", r#"name "back\\slash""#), + ("two\nlines", r#"name "two\nlines""#), + ("bell\u{7}", r#"name "bell\u{7}""#), + ] { + let score = scored(vec![track( + Some(name), + 0, + Tuning::new(Vec::new()), + Vec::new(), + )]); + let text = write(&score); + assert!(text.contains(expected), "{name:?} -> {text:?}"); + } +} + // ── mutation matrix: every structural fact is observable in the bytes ────── #[test] diff --git a/swang/tests/exact_writer_transport.rs b/swang/tests/exact_writer_transport.rs index 473ae95b..1923e63d 100644 --- a/swang/tests/exact_writer_transport.rs +++ b/swang/tests/exact_writer_transport.rs @@ -1,10 +1,11 @@ //! SWG-4A-03 contract tests: the exact-text writer's transport and master //! timeline, committed failing before any implementation. //! -//! Scope is deliberately the first writer slice only — header, `ppqn`, and -//! `master_bar` with its `ticks`, `meter`, `tempo`, and `repeat`. Tracks, -//! strings, and everything downstream belong to SWG-4A-04 and later, and a -//! score carrying them must be refused rather than half-written. +//! Scope was deliberately the first writer slice only — header, `ppqn`, and +//! `master_bar` with its `ticks`, `meter`, `tempo`, and `repeat` — and the +//! rest of the tree was refused rather than half-written. Later slices wrote +//! all of it; these tests stayed, and their goldens are what say the writer +//! grew without moving a transport byte. //! //! Every expectation here is a decision the accepted census already made //! (`docs/swang/exact-score-text.md`); none of them is invented by this @@ -258,24 +259,31 @@ fn an_inverted_tick_range_is_refused() { ); } +/// The frontier this test watched is gone. +/// +/// It refused tracks until SWG-4A-04 wrote them, then `source` until +/// SWG-4A-05 wrote that. The writer is complete, so there is no build-stage +/// limit left to state and `NotYetWritten` no longer exists. What survives is +/// the property the transport slice actually owns: a `source` sits after +/// every track, at the document's own level, and does not disturb the bytes +/// above it. #[test] -fn a_score_with_source_metadata_is_refused_as_not_yet_written() { - // A build-stage limit, not a domain statement: `source` is SWG-4A-05. - // The distinction matters — refusing it as "outside the writer domain" - // would contradict the census, which says every inhabited state is - // spellable. - // - // This test guarded tracks until SWG-4A-04 wrote them. The frontier it - // watches moved; the property it states did not, so it follows the - // frontier rather than being deleted with the slice it outlived. - let mut score = transport(480, Vec::new()); +fn source_metadata_follows_the_transport_it_annotates() { + let mut score = transport(480, vec![bar(0, 0, 1920, bpm(120))]); + let transport_only = write(&score); score.source_meta = Some(SourceMeta { format: Some("GP5".to_owned()), }); - let err = write_score(&score).expect_err("source metadata is not in this slice"); + let with_source = write(&score); + + assert!(with_source.starts_with( + transport_only + .strip_suffix("}\n") + .expect("the document closes") + )); assert!( - matches!(err, ExactWriteError::NotYetWritten { .. }), - "a slice boundary is not a domain judgement: {err:?}" + with_source.ends_with("\n source { format \"GP5\" }\n}\n"), + "{with_source:?}" ); } From 4fbe9cec72d3cad491e874c0e6f73e7458cb1382 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 20 Aug 2026 14:05:31 +0000 Subject: [PATCH 4/6] =?UTF-8?q?docs(swang):=20SWG-4A-05=20closure=20?= =?UTF-8?q?=E2=80=94=20the=20exact=20writer=20is=20complete?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Docs-only. ## `foundation-backlog.md` 4A-05 marked done, with its acceptance criteria checked off and the one structural outcome recorded: the exact writer is complete, so `check_slice_frontier` and `ExactWriteError::NotYetWritten` went with it. 4A-10 is a CLI surface over a finished writer, not another slice of one, and the lane diagram now says so. Two acceptance lines are sharpened rather than merely ticked. "Mutating any one of these fields changes the exact text" names the nineteen writer mutations behind it; "source and loss do not disappear because they make no sound" names the triple it actually is — normalized-equal, exact-different, bytes-different — because the first two thirds of that claim are the easy part and the third is the one that catches a writer quietly dropping them. The reference-document golden is listed too. It is the first evidence that the parts compose rather than merely each working alone. ## `decisions.log.md` One Y-statement, because removing a public enum variant is a breaking change and the timing is the decision. `NotYetWritten` becomes unreachable the moment the writer is complete; keeping it until 4A-10 would make the CLI handle a case that cannot occur, and an API outlives its meaning more easily the longer it waits. Level 2 is not frozen yet, which is precisely what makes now the cheap moment. Recorded with what makes the removal safe rather than merely tidy: the five tests that guarded the variant are sunset, not deleted — each kept the structural property it owned — no earlier byte-golden moved, and the attempt to reintroduce a `NotYetWritten` path is now a compile error rather than a test failure. Refs SWG-4A-05 Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_018vdRzztKXy8bA16tEzwgLE --- docs/decisions.log.md | 17 ++++++++++++++ docs/swang/foundation-backlog.md | 39 ++++++++++++++++++++++---------- 2 files changed, 44 insertions(+), 12 deletions(-) diff --git a/docs/decisions.log.md b/docs/decisions.log.md index 132b4855..8aa3661e 100644 --- a/docs/decisions.log.md +++ b/docs/decisions.log.md @@ -2392,3 +2392,20 @@ Architectural decisions go to [`adr/`](adr/) instead. and any real-/full-corpus labeling remain separately gated (ADR-0033 Decision 10), and any implementation deviation from the accepted contract reopens acceptance rather than being decided in code. + +- 2026-08-18 — In the context of SWG-4A-05 completing the exact writer, facing + an `ExactWriteError::NotYetWritten` variant that had described the writer's + build progress rather than any property of a `Score`, we decided for + **removing it now**, together with `check_slice_frontier`, and against + keeping it until SWG-4A-10 or later, to achieve a refusal that means exactly + one thing — your `Score` violates an invariant `griff-core` itself declares + — and to spare the CLI a match arm for a case that cannot occur. Accepting + that this is a breaking change to a public enum, which is why it is made now + rather than after the level-2 freeze: the variant is unreachable the moment + the writer is complete, and an API that outlives its meaning is harder to + retire the longer it waits. The five tests that guarded it are sunset rather + than deleted — each owned a structural property that survives the + refusal — and no SWG-4A-03 or 4A-04 byte-golden changed, which is what + those goldens exist to say. Verified by nineteen writer mutations, none of + which survived; the attempt to reintroduce a `NotYetWritten` path is now a + compile error rather than a test failure. diff --git a/docs/swang/foundation-backlog.md b/docs/swang/foundation-backlog.md index f5d052d5..9340dbe6 100644 --- a/docs/swang/foundation-backlog.md +++ b/docs/swang/foundation-backlog.md @@ -116,7 +116,7 @@ recorded in `decisions.log.md` if reversed. | SWG-4A-02 | `ExactScoreDocument` as a transient syntax form | code | 4A-01 | | SWG-4A-03 | Writer: transport and master timeline | code | 4A-01 | | SWG-4A-04 | Writer: tracks, voices, groups, atoms | code | 4A-03 | -| SWG-4A-05 | Writer: techniques, positions, evidence, losses | code | 4A-04, CORE-01 | +| SWG-4A-05 | Writer: techniques, positions, evidence, losses *(done)* | code | 4A-04, CORE-01 | | SWG-4A-06 | Parser skeleton and level/root dispatch | code | 4A-01, INF-04, INF-06 | | SWG-4A-07 | Parser: exact scalar types | code | 4A-06 | | SWG-4A-08 | Parser: structural tree | code | 4A-07, 4A-02 | @@ -548,22 +548,34 @@ Non-negotiable: Acceptance is measured by `ExactSemanticDiff`, not by "the MIDI sounds about right". -### SWG-4A-05 — Writer: techniques, positions, evidence, metadata, losses +### SWG-4A-05 — Writer: techniques, positions, evidence, metadata, losses *(done)* -**Kind:** code. **Depends on:** 4A-04, CORE-01 — both **done**, so this task -is unblocked. CORE-01 ran first so the metadata writer is built on the final -`u64` payload indices rather than rewritten onto them. +**Kind:** code. **Depends on:** 4A-04, CORE-01 — both done before it. +CORE-01 ran first so the metadata writer was built on the final `u64` payload +indices rather than rewritten onto them. -The remaining facts: note marks, technique spans and their ranges, evidence, +The facts it added: note marks, technique spans and their ranges, evidence, string/fret position, position evidence and confidence (`ConfidenceBps`), -source metadata, import warnings, loss facts. +escaped strings, source metadata, import warnings, loss facts. -Acceptance: +**The exact writer is complete.** This was the last slice, so +`check_slice_frontier` and `ExactWriteError::NotYetWritten` were removed with +it: the writer no longer declines any part of the canonical tree, and its one +remaining refusal is a judgement about the `Score` rather than about itself. +Removing the variant here rather than after 4A-10 spares the CLI a case that +cannot occur. + +Acceptance, all met: -- mutating any one of these fields changes the exact text; +- mutating any one of these fields changes the exact text — a matrix over + every added fact, plus nineteen writer mutations of which none survived; - `NormalizedMusicalDiff` may call some of those mutations equal; `ExactSemanticDiff` must see every one of them; -- source and loss facts do not disappear merely because they make no sound. +- source and loss facts do not disappear merely because they make no sound — + checked as the triple it actually is: normalized-equal, exact-different, + bytes-different; +- §6.1's reference document is produced whole and compared byte for byte, + which is the first proof that every part composes. ### SWG-4A-06 — Parser skeleton and level/root dispatch @@ -1202,10 +1214,13 @@ INF-01 status sync (done) └─→ 4A-01 exact grammar (done) │ ├─→ 4A-03 → 4A-04 → CORE-01 → 4A-05 → 4A-10 writer lane - │ (done) (done) (done) ↑ - │ │ next + │ (done) (done) (done) (done) ↑ + │ │ next │ └─→ also gated 4A-12 and the level-2 freeze │ + │ the exact writer is complete at 4A-05; 4A-10 is a CLI + │ surface over it, not another slice of it + │ └─→ 4A-02 → INF-04 → INF-06 → 4A-06 parser skeleton -> 4A-02..4A-09 writer / parser / builder -> 4A-10..4A-14 dump / verify / laws / fuzz From a65e3a0c772129ac4c22d1845485629b4496f632 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 20 Aug 2026 14:25:19 +0000 Subject: [PATCH 5/6] =?UTF-8?q?test(swang):=20SWG-4A-05=20review=20?= =?UTF-8?q?=E2=80=94=20bind=20the=20musical=20matrix=20to=20the=20exact=20?= =?UTF-8?q?diff?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tests-only, green on unchanged production code. An independent review found an evidence gap, not a writer defect: nothing in `swang/` had to move, and nothing did. ## The matrix checked half its own contract The acceptance contract asked, for every remaining canonical fact, for one mutation satisfying three things at once: ``` controlled Score mutation -> ExactSemanticDiff reports the expected path AND write_score(before) != write_score(after) ``` The musical half checked only the second. `ExactSemanticDiff` is separately well covered in `core/tests/semantic_diff.rs`, and that is exactly why the gap was easy to miss — but two suites agreeing independently is not a composition witness. Nothing said the fact the writer spells and the fact the comparator sees are the *same* fact, which is the whole claim. `assert_observable` now binds them at one mutation, and the twelve musical rows go through it. Expected paths are read off the walker, not off its output. `diff_note` compares `NotePosition` under a single `Position` option leaf and records the fretboard mismatch inside that scope with no further segment, so `string` and `fret` both surface at `.position`; `diff_span` compares `TechniqueEvidence` whole. Those composite fields are deliberate and 4A-05 does not touch the comparator, so the test states the coarse path rather than proposing a finer one. Order and cardinality are not forced into one leaf. A swap changes both elements, so the honest expectation is a difference under each ordinal plus moved bytes, and that is what the test asserts. ## A fact the matrix silently did not mutate `mutating_any_span_fact_changes_the_text` claimed a span-evidence row. Its baseline was `Explicit` at 10 000 and its mutation `InferredFromMidi` at 10 000 — the source moved and the confidence never did. So the closure claim "a matrix over every added fact" was false by one field. A standalone row holds the source still and moves 10 000 to 9 999. ## Falsified, not merely passing - pointing one expected path at a field that does not exist fails the test, so the path assertion is doing work rather than matching anything; - restoring the confidence mutation to 10 000 -> 10 000 fails the new row, so it really is the separation and not decoration; - a twentieth writer mutation, hard-coding `confidence 10000`, is now caught by six tests including the new row. Before this commit it would have been caught by the goldens alone, and by nothing that named confidence. Refs SWG-4A-05 Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_018vdRzztKXy8bA16tEzwgLE --- swang/tests/exact_writer_metadata.rs | 260 ++++++++++++++++++--------- 1 file changed, 173 insertions(+), 87 deletions(-) diff --git a/swang/tests/exact_writer_metadata.rs b/swang/tests/exact_writer_metadata.rs index a97760e6..5612c7c0 100644 --- a/swang/tests/exact_writer_metadata.rs +++ b/swang/tests/exact_writer_metadata.rs @@ -39,6 +39,7 @@ use griff_core::score::{ AtomEvent, AtomNote, AtomRest, EventGroup, EventGroupKind, LossReport, MasterBar, RepeatMarker, Score, TechniqueSpan, Track, Voice, }; +use griff_core::semantic_diff::exact_semantic_diff; use griff_core::slice::TickRange; use griff_swang::exact::{write_score, ExactWriteError}; @@ -470,25 +471,6 @@ fn rich() -> Score { }) } -/// `rich()` with its one note replaced by `edit`'s result. -fn with_note(edit: impl FnOnce(&mut AtomNote)) -> Score { - let mut score = rich(); - let group = &mut score.tracks[0].voices[0].event_groups[0]; - let AtomEvent::Note(mut atom) = group.atoms[0] else { - panic!("the fixture holds a note") - }; - edit(&mut atom); - group.atoms[0] = AtomEvent::Note(atom); - score -} - -/// `rich()` with its span vector replaced by `edit`'s result. -fn with_spans(edit: impl FnOnce(&mut Vec)) -> Score { - let mut score = rich(); - edit(&mut score.tracks[0].voices[0].event_groups[0].technique_spans); - score -} - fn a_position(string: u8, fret: u8, source: TechniqueSource, bps: u16) -> NotePosition { NotePosition { position: FretboardPosition { string, fret }, @@ -496,88 +478,192 @@ fn a_position(string: u8, fret: u8, source: TechniqueSource, bps: u16) -> NotePo } } -#[test] -fn mutating_any_note_leaf_changes_the_text() { - let baseline = write(&rich()); - - assert_ne!( - write(&with_note(|n| n.marks = marks_of(&[NoteMark::Ghost]))), - baseline, - "the mark set is observable" +/// The path prefix every fact in `rich()` hangs from. +const IN_GROUP: &str = "score.tracks[0].voices[id=0,ordinal=0].event_groups[0]"; + +/// The three things one canonical fact must satisfy **together**. +/// +/// The first version of this matrix checked only the third: the bytes moved. +/// That is half the acceptance contract. `ExactSemanticDiff` is separately +/// well covered in `core/tests/semantic_diff.rs`, but two independent suites +/// agreeing is not a composition witness — nothing said the fact the writer +/// spells and the fact the comparator sees are the *same* fact. This binds +/// them at one mutation. +/// +/// Expected paths are read off the walker rather than off its output: +/// `diff_note` compares `NotePosition` under one `Position` option leaf and +/// records the fretboard mismatch inside that scope with no further segment, +/// so `string` and `fret` both surface at `.position`. `diff_span` compares +/// `TechniqueEvidence` whole. Neither is a defect to route around — the +/// comparator's composite fields are deliberate, and 4A-05 does not touch it. +fn assert_observable(label: &str, expected_path: &str, edit: impl FnOnce(&mut Score)) { + let before = rich(); + let mut after = before.clone(); + edit(&mut after); + + let paths: Vec = exact_semantic_diff(&before, &after) + .differences + .iter() + .map(|difference| difference.path.to_string()) + .collect(); + assert!( + paths.iter().any(|path| path == expected_path), + "{label}: the exact diff must report `{expected_path}`, got {paths:?}" ); assert_ne!( - write(&with_note(|n| n.position = None)), - baseline, - "position presence is observable" + write(&before), + write(&after), + "{label}: the writer's bytes must move too" ); - assert_ne!( - write(&with_note(|n| { - n.position = Some(a_position(5, 2, TechniqueSource::InferredFromMidi, 5_000)); - })), - baseline, - "the string is observable" +} + +#[test] +fn every_note_leaf_is_one_fact_to_the_diff_and_to_the_writer() { + assert_observable("marks", &format!("{IN_GROUP}.atoms[0].marks"), |score| { + edit_note(score, |n| n.marks = marks_of(&[NoteMark::Ghost])); + }); + assert_observable( + "position presence", + &format!("{IN_GROUP}.atoms[0].position"), + |score| { + edit_note(score, |n| n.position = None); + }, ); - assert_ne!( - write(&with_note(|n| { - n.position = Some(a_position(4, 3, TechniqueSource::InferredFromMidi, 5_000)); - })), - baseline, - "the fret is observable" + assert_observable( + "position string", + &format!("{IN_GROUP}.atoms[0].position"), + |score| { + edit_note(score, |n| { + n.position = Some(a_position(5, 2, TechniqueSource::InferredFromMidi, 5_000)); + }); + }, ); - assert_ne!( - write(&with_note(|n| { - n.position = Some(a_position(4, 2, TechniqueSource::Explicit, 5_000)); - })), - baseline, - "the position's evidence source is observable" + assert_observable( + "position fret", + &format!("{IN_GROUP}.atoms[0].position"), + |score| { + edit_note(score, |n| { + n.position = Some(a_position(4, 3, TechniqueSource::InferredFromMidi, 5_000)); + }); + }, ); - assert_ne!( - write(&with_note(|n| { - n.position = Some(a_position(4, 2, TechniqueSource::InferredFromMidi, 5_001)); - })), - baseline, - "the position's confidence is observable" + assert_observable( + "position evidence source", + &format!("{IN_GROUP}.atoms[0].position.evidence"), + |score| { + edit_note(score, |n| { + n.position = Some(a_position(4, 2, TechniqueSource::Explicit, 5_000)); + }); + }, + ); + assert_observable( + "position evidence confidence", + &format!("{IN_GROUP}.atoms[0].position.evidence"), + |score| { + edit_note(score, |n| { + n.position = Some(a_position(4, 2, TechniqueSource::InferredFromMidi, 5_001)); + }); + }, ); } #[test] -fn mutating_any_span_fact_changes_the_text() { - let baseline = write(&rich()); - - assert_ne!( - write(&with_spans(|spans| { - spans.pop(); - })), - baseline, - "span presence is observable" +fn every_span_fact_is_one_fact_to_the_diff_and_to_the_writer() { + assert_observable( + "span presence", + &format!("{IN_GROUP}.technique_spans"), + |score| { + edit_spans(score, |spans| { + spans.pop(); + }); + }, ); - assert_ne!( - write(&with_spans( - |spans| spans[0].technique = SpanTechnique::Legato - )), - baseline, - "the technique is observable" + assert_observable( + "span technique", + &format!("{IN_GROUP}.technique_spans[0].technique"), + |score| { + edit_spans(score, |spans| spans[0].technique = SpanTechnique::Legato); + }, ); - assert_ne!( - write(&with_spans(|spans| spans[0].tick_range = range(24, 480))), - baseline, - "the span start is observable" + assert_observable( + "span tick start", + &format!("{IN_GROUP}.technique_spans[0].tick_range"), + |score| { + edit_spans(score, |spans| spans[0].tick_range = range(24, 480)); + }, ); - assert_ne!( - write(&with_spans(|spans| spans[0].tick_range = range(0, 481))), - baseline, - "the span end is observable" + assert_observable( + "span tick end", + &format!("{IN_GROUP}.technique_spans[0].tick_range"), + |score| { + edit_spans(score, |spans| spans[0].tick_range = range(0, 481)); + }, ); - assert_ne!( - write(&with_spans(|spans| { - spans[0].evidence = evidence(TechniqueSource::InferredFromMidi, 10_000); - })), - baseline, - "span evidence is observable" + assert_observable( + "span evidence source", + &format!("{IN_GROUP}.technique_spans[0].evidence"), + |score| { + edit_spans(score, |spans| { + spans[0].evidence = evidence(TechniqueSource::InferredFromMidi, 10_000); + }); + }, ); - assert_ne!( - write(&with_spans(|spans| spans.swap(0, 1))), - baseline, - "span order is observable" +} + +/// The gap an independent review found: the matrix moved `source` **and** +/// confidence together, so nothing separated them. +/// +/// `rich()`'s spans carry `Explicit` at 10 000. This holds the source still +/// and moves only the confidence, which is the mutation the old +/// `span evidence` row silently did not perform. +#[test] +fn a_span_confidence_alone_is_one_fact_to_the_diff_and_to_the_writer() { + assert_observable( + "span evidence confidence", + &format!("{IN_GROUP}.technique_spans[0].evidence"), + |score| { + edit_spans(score, |spans| { + spans[0].evidence = evidence(TechniqueSource::Explicit, 9_999); + }); + }, ); } + +/// Order and cardinality do not reduce to one leaf, and should not be forced +/// to: swapping two spans changes both elements, so the honest expectation is +/// that the diff reports under both ordinals and the bytes move. +#[test] +fn span_order_is_visible_to_both_the_diff_and_the_writer() { + let before = rich(); + let mut after = before.clone(); + edit_spans(&mut after, |spans| spans.swap(0, 1)); + + let paths: Vec = exact_semantic_diff(&before, &after) + .differences + .iter() + .map(|difference| difference.path.to_string()) + .collect(); + for ordinal in 0..2 { + let prefix = format!("{IN_GROUP}.technique_spans[{ordinal}]"); + assert!( + paths.iter().any(|path| path.starts_with(&prefix)), + "a swap must be reported under `{prefix}`, got {paths:?}" + ); + } + assert_ne!(write(&before), write(&after)); +} + +/// `rich()` with its one note edited in place. +fn edit_note(score: &mut Score, edit: impl FnOnce(&mut AtomNote)) { + let group = &mut score.tracks[0].voices[0].event_groups[0]; + let AtomEvent::Note(mut atom) = group.atoms[0] else { + panic!("the fixture holds a note") + }; + edit(&mut atom); + group.atoms[0] = AtomEvent::Note(atom); +} + +/// `rich()` with its span vector edited in place. +fn edit_spans(score: &mut Score, edit: impl FnOnce(&mut Vec)) { + edit(&mut score.tracks[0].voices[0].event_groups[0].technique_spans); +} From a28e630dc62eeee83cb02e7b13a398726e60a80c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 20 Aug 2026 14:28:09 +0000 Subject: [PATCH 6/6] =?UTF-8?q?docs(swang):=20SWG-4A-05=20closure=20correc?= =?UTF-8?q?tion=20=E2=80=94=20the=20evidence=20gap=20the=20review=20found?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Independent review found an evidence gap, not a writer defect: - the musical writer matrix did not bind its mutations to `ExactSemanticDiff` — it asserted only that the bytes moved; - span evidence confidence lacked a standalone mutation, so the claim of "a matrix over every added fact" was false by one field; - a tests-only continuation commit closed both; - production code unchanged. The mutation count in the closure line moves from nineteen to twenty: the review added one more writer mutation (hard-code span confidence to 10000), and it too was caught. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_018vdRzztKXy8bA16tEzwgLE --- docs/decisions.log.md | 16 ++++++++++++++++ docs/swang/foundation-backlog.md | 6 ++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/docs/decisions.log.md b/docs/decisions.log.md index 8aa3661e..2fbf69f0 100644 --- a/docs/decisions.log.md +++ b/docs/decisions.log.md @@ -2409,3 +2409,19 @@ Architectural decisions go to [`adr/`](adr/) instead. those goldens exist to say. Verified by nineteen writer mutations, none of which survived; the attempt to reintroduce a `NotYetWritten` path is now a compile error rather than a test failure. + +- 2026-08-20 — In the context of closing SWG-4A-05, facing an independent + review that found the acceptance evidence weaker than the closure claimed, + we decided for two tests-only continuation commits and against amending the + four already made, to achieve a history where the gap and its repair are + both legible, accepting two more commits on the branch. Two findings, both + in the evidence rather than in the writer — no production line changed. The + musical mutation matrix asserted only that the bytes moved, never that + `ExactSemanticDiff` saw the same fact: the comparator is separately well + covered, and two suites agreeing independently is not the composition + witness the contract asked for. And the span-evidence row moved `source` and + confidence together, so "a matrix over every added fact" was false by one + field. Accepting that the bound assertions state the comparator's *coarse* + paths — `NotePosition` and `TechniqueEvidence` are composite canonical + fields to the exact walker on purpose, and improving the comparator to make + the test prettier would be 4A-05 editing something it was told not to touch. diff --git a/docs/swang/foundation-backlog.md b/docs/swang/foundation-backlog.md index 9340dbe6..f67a9b21 100644 --- a/docs/swang/foundation-backlog.md +++ b/docs/swang/foundation-backlog.md @@ -567,8 +567,10 @@ cannot occur. Acceptance, all met: -- mutating any one of these fields changes the exact text — a matrix over - every added fact, plus nineteen writer mutations of which none survived; +- mutating any one of these fields changes the exact text **and** is + reported by `ExactSemanticDiff` at its expected path — one mutation + binding both, over every added fact, plus twenty writer mutations of which + none survived; - `NormalizedMusicalDiff` may call some of those mutations equal; `ExactSemanticDiff` must see every one of them; - source and loss facts do not disappear merely because they make no sound —