The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Rebuild Score for real composition workflows and relist it (#134)
Deeafff73eb5d99
diff --git a/.github/workflows/experience-checks.yml b/.github/workflows/experience-checks.ymlindex 803eac0f5..5cdb7ca9b 100644--- a/.github/workflows/experience-checks.yml+++ b/.github/workflows/experience-checks.yml@@ -33,6 +33,8 @@ jobs:run: node store/tools/catalog.mjs- name: Check FreeCAD contracts and delivery (native suite is opt-in)run: node --test store/agents/freecad/test/*.test.mjs+ - name: Check Score contracts, MIDI and delivery (native suite is opt-in)+ run: node --test store/agents/score/test/*.test.mjsauthoring-browser:runs-on: ubuntu-latestdiff --git a/store/agents/score/AGENTS.md b/store/agents/score/AGENTS.mdindex 486c1b472..30d90e0cd 100644--- a/store/agents/score/AGENTS.md+++ b/store/agents/score/AGENTS.md@@ -1,16 +1,25 @@# Score harness-Read the `score` skill. Compose in `score.ly` and run:+Read the `score` skill. No real instruments or music-reading experience are+required: help the user describe a musical idea, hear it, revise it and keep+usable files. Capture the brief and player limits in `ensemble.json`; compose+concert-pitch music variables in `score.ly`. Run:```shsh "$SCORE_SKILLS/score/scripts/render-score.sh"```-The live artifact is `score.html`; preserve PDF, MIDI and editable source.-Inspect every PDF page and check MIDI timing plus the actual playback controls.-Report the difference between clean engraving and musical correctness. Never-count literal bar characters as measures or call a synthesized sketch a recording.+The live artifact is `score.html`. Deliver the full score, individual parts,+solo/minus-one practice MIDI and `score-project.zip`. The page can export a+synthetic WAV of the selected mix without any instruments.-Use trusted LilyPond input only; it can execute Scheme. Do not silently substitute-a MuseScore CLI. Fresh builds must produce PDF, SVG and MIDI; a failure must clear-readiness even if old artifacts remain. Browser tempo changes do not edit source.+Do not relax the saved limits merely to make a revision pass. Inspect every PDF+page and exercise playback in the real viewer. Mechanical range, duration and+transposition checks are not musician validation or proof of musical quality.+Never count literal bar characters as measures or call synthesized audio a+recording. State what was tested and what still needs the user's ear.++Only compile trusted LilyPond; it can execute Scheme. Source exports use the+explicit allowlist, not a workspace scan. A failed build remains unready and+preserves the last successful handoff. Do not run a generic browser probe that+overwrites the measured verdict. Listening settings do not edit the composition.diff --git a/store/agents/score/PROVENANCE.md b/store/agents/score/PROVENANCE.mdindex 795d5fb21..e937651be 100644--- a/store/agents/score/PROVENANCE.md+++ b/store/agents/score/PROVENANCE.md@@ -1,10 +1,16 @@# Provenance-The Folio viewer, MIDI parser, wrapper instructions and “Lighthouse at Dusk”-composition are original OpenHarness work under the included MIT license.+The Folio viewer, MIDI parser/writer, ensemble checks, archive builder, workflow+instructions and original compositions “After the Rain” and “A Small Beginning”+are OpenHarness work under the included MIT license. The earlier “Lighthouse+at Dusk” starter was also original OpenHarness work.[LilyPond](https://lilypond.org) is the separately installed notation engine,licensed GPL-3.0-or-later. Tested with the official 2.26.0 macOS Intel distribution.No LilyPond code, binary, font or sample library is redistributed in this package.The viewer displays user-generated engraving as images and uses native Web Audiooscillators; no external music, soundfont or audio service is used.++The portable project includes the wrapper tools under their own MIT license.+User composition and arrangement rights are not established by successful+engraving or mechanical checks.diff --git a/store/agents/score/README.md b/store/agents/score/README.mdindex 8bbfd23e1..97501b90c 100644--- a/store/agents/score/README.md+++ b/store/agents/score/README.md@@ -1,51 +1,104 @@# Score · Folio-Compose in text; read and hear the result. Folio combines LilyPond's real-engraving with a local MIDI sketch: play/pause, seek, change playback speed,-adjust volume and zoom the score. Download the printable PDF or the MIDI.+Describe a musical idea. Hear it, change it and keep the result. You do not need+an instrument or music-reading experience: Score turns your brief into editable+music, an audible sketch, printable parts and a portable practice pack.-The starter, **Lighthouse at Dusk**, is an original 16-bar piano study in E minor,-6/8. It engraves to one page and 142 MIDI notes (about 35.6 seconds).+Try: “Make a gentle, hopeful piece with a flute melody, clarinet reply and warm+cello. Let me hear each voice. Then make the ending quieter.”++## What you can do++- Compose and revise original music in plain language through the agent.+- Listen, isolate a player, mute a line, slow down or loop complete bars.+- Save the current mix as a **WAV sketch** you can play outside Harness.+- Get a full score and individual PDF/MIDI parts, including written transposition.+- Download slower solo and minus-one practice MIDI with a count-in.+- Keep the saved brief, editable music and standalone rebuild tools in one ZIP.++The original starter, **After the Rain**, is a 16-bar flute, B-flat clarinet and+cello miniature in 6/8. It is a starting point, not a required instrument setup.+Independent acceptance also covers an eight-bar flute/piano duet and an easier+flute revision that leaves the piano MIDI unchanged.## First runInstall `autonomous/score` from the Harness Store and install-[LilyPond](https://lilypond.org/download.html) separately. Tested with 2.26.0;-the source targets 2.24.3 or later. Set `LILYPOND_BIN` if it is not on PATH.-The managed helper finds Node 20+ without a global npm installation.+[LilyPond](https://lilypond.org/download.html) separately (tested 2.26.0).+Set `LILYPOND_BIN` if it is not on PATH. The managed helper finds Node 20+;+no global npm packages or audio service are needed.++Describe the music you want. The agent edits `ensemble.json` (brief and limits)+and `score.ly` (concert-pitch music), then runs:```shsh "$SCORE_SKILLS/score/scripts/render-score.sh"```-Ask: “Turn the opening into a gentle duet, keep the 6/8 pulse, and render a-score I can print and listen through.” Edit `score.ly`, then rebuild. The pane-shows `score.html`; the durable outputs are `score.pdf`, `score.midi` and the-editable source. Browser tempo/volume/position changes are listening controls,-not saved changes to the composition.+Open `score.html`. Listening needs no instruments. The synth is intentionally a+note sketch, not a sampled instrument or human performance. If you just want to+explore, start with Listen, Solo and the speed slider; you do not need to+understand the notation.++## Keep and share the result++`score-project.zip` includes:++- Full PDF and original native MIDI.+- Individual PDF/MIDI parts and slower solo/minus-one practice MIDI.+- The brief, allowlisted editable sources, and measured checks with source hashes.+- Standalone rebuild scripts and their license.++Extract it and run `node rebuild/build.mjs .` with Node and LilyPond installed.+No Harness account, npm dependency or Python installation is needed to rebuild.+The delivered HTML opens in a modern browser outside Harness.++Browser WAV exports use the **current** loop, speed, mix and optional count-in.+The prebuilt practice MIDIs use `practice` in `ensemble.json`. Neither changes+the composition. Save/restore a listening setup as JSON; it is tied to the source+revision and rejected after the source changes.++## What gets checked++The saved brief is independent of generated notes. The native build measures:++- Every staff's duration, including rests, against the requested complete bars.+- Constant meter/tempo, actual written range and maximum simultaneous notes.+- Optional limits on successive-note leaps and attacks per bar.+- Written versus concert-pitch transposition, and agreement between the full+ score, individual parts and independent concert-pitch proofs.+- Re-parsed practice exports, source hashes and identical MIDI across PDF/SVG passes.++A failed revision clears readiness and preserves the last successful handoff.+Previous generated files remain under `.harness/history/`; logs and receipts are+in `.harness/`. A literal LilyPond bar character is not used as a measure count.+See [acceptance evidence](test/ACCEPTANCE.md) and the+[contract reference](skills/score/references/ensemble.md).++## Limits-## Verification and limits+Mechanical checks do not certify musical quality, comfort, fingering, breathing+or physical playability. There has been no real-player validation. The original+native MIDI is retained, but browser audio and practice exports ignore pedal,+bends and other expressive controllers and use fixed synthetic timbres.-Each build starts unready, invokes LilyPond twice for fresh PDF and SVG pages,-treats warnings as errors, and parses MIDI note timing. Missing output or bad-source fails without claiming an old score is new. Inspect `.harness/render.log`-and `.harness/score.json`. Actual engraving and desktop/mobile browser controls-were checked; unit fixtures also cover note timing and failure handling.+The checked workflow supports 1–8 players, at most 15 pitched staves, 1–128+complete bars, constant meter/tempo and 10,000 notes within an hour. No pickup,+meter/tempo changes, unexpanded repeats, unpitched percussion or zero-time grace+notes. Up to 40 engraved pages per document; WAV export up to 3 minutes;+portable ZIP up to 32 MiB. MuseScore conversion is not implemented.-Playback is a simple triangle-wave sketch, not a sampled piano or a human-performance. It ignores sustain pedal, instrument changes and expressive-controllers. MIDI type 0/1 with PPQ timing is supported; maximum preview is-10,000 notes, one hour and 40 engraved pages. It does not prove a piece is-playable, musically correct or licensed for use. A `|` in LilyPond is a bar-**check**, not an instruction that ends a bar; no literal-character measure-count is reported.+Only compile trusted LilyPond: it can execute Scheme and read local files.+The explicit source allowlist is for portable delivery, not a Scheme sandbox.+Do not export secrets or unrelated workspace files.-This workflow supports LilyPond sources with layout and MIDI blocks.-MuseScore conversion is not implemented. LilyPond source can execute Scheme;-only render trusted sources.+Existing full-score LilyPond sources can still engrave without `ensemble.json`,+but remain unready for checked delivery. Upgrading requires preserving the music+and extracting its concert-pitch variables, not overwriting it with the starter.## Credit and stewardshipLilyPond is the LilyPond project's separately installed GPL notation engine.-The MIT-licensed Folio wrapper, viewer, MIDI inspector and starter composition-are original OpenHarness work. No LilyPond binary or source is vendored.+The MIT-licensed Folio wrapper, viewer, MIDI tooling and original starter/test+compositions are OpenHarness work. No LilyPond binary, font or sound library is+vendored. See [LICENSE](LICENSE) and [PROVENANCE](PROVENANCE.md).diff --git a/store/agents/score/harness.json b/store/agents/score/harness.jsonindex bfded0a2e..3b58d882f 100644--- a/store/agents/score/harness.json+++ b/store/agents/score/harness.json@@ -4,7 +4,7 @@"name": "Score","category": "Music","author": "OpenHarness contributors",- "description": "Compose editable LilyPond music, engrave a real PDF, and explore its MIDI notes with a local playback and score viewer.",+ "description": "Turn a musical idea into editable music, checked instrument parts and a practice pack. Listen, isolate voices, reshape phrases and save a WAV sketch—no instruments required.","engine": "claude","workspace": {"template": "template",diff --git a/store/agents/score/skills/score/SKILL.md b/store/agents/score/skills/score/SKILL.mdindex 531ed86eb..61a07b1d8 100644--- a/store/agents/score/skills/score/SKILL.md+++ b/store/agents/score/skills/score/SKILL.md@@ -1,40 +1,81 @@---name: score-description: Compose trusted LilyPond source, engrave real PDF/SVG pages, inspect MIDI timing and audition notes in the Folio preview. Use for Score harness work.+description: Turn a musical brief into editable concert-pitch music, checked instrument parts and a listenable practice pack in the Score harness. Use for composing, arranging and revising trusted LilyPond projects.----# Compose, engrave, audition+# From a musical idea to something the user can keep-1. Read `score.ly`. Keep key, meter, tempo, voices, dynamics and instrument names- explicit. The original piano study is a starting point, not a musical constraint.-2. Keep both `\layout { }` and `\midi { }` blocks. Run:+The user does not need instruments or notation vocabulary. If they want to+listen, start with mood, purpose, duration and a useful instrumentation; state+assumptions and offer an audible first version. If they have real players,+capture each player's instrument, written range and experience. Do not turn the+starter trio or any particular difficulty limit into a universal requirement.- ```sh- sh "$SCORE_SKILLS/score/scripts/render-score.sh"- ```+Read [the ensemble contract](references/ensemble.md) before changing player+setup, timing, difficulty or source exports.-3. LilyPond runs with warnings treated as errors. Correct bar checks, syntax and- collisions rather than suppressing warnings. A `|` checks bar position; it- does not end a bar. Count musical durations, not literal characters.-4. Inspect all PDF pages for spacing, collisions, page turns, staff labels and- legibility. The fresh receipt reports engraved pages and MIDI notes, not a- fabricated measure count.-5. Use Folio play/pause, seeking, slowdown and the pitch timeline to inspect the- actual exported notes. Make compositional edits in source and rebuild.-6. Hand off `score.pdf`, `score.midi` and `score.ly`. State which checks ran.+## Compose and revise++- Save the actual brief, assumptions, timing, instrument transpositions and+ difficulty limits in `ensemble.json`. These are requirements, not values to+ infer from whatever the generated notes happen to contain.+- Compose reusable **concert-pitch** variables in `score.ly`; the builder adds+ the initial key, meter, tempo, printed score, parts and MIDI proofs. Do not+ transpose the source again for a B-flat part or override staff transposition.+- Give the music a deliberate shape: phrases, breathing space, contrast,+ accompaniment and an ending appropriate to the request. A successful compiler+ does not supply those decisions.+- Run:++ ```sh+ sh "$SCORE_SKILLS/score/scripts/render-score.sh"+ ```++- Inspect `.harness/score.json` and every printed PDF page, including individual+ parts. Check collisions, readability, instrument labels and sensible breaks.+ LilyPond warnings are errors. Correct the music or layout, not the warning policy.+- On a failed requirement, read `.harness/failed-score.json`. Fix the music while+ retaining the user's limits. Change a requirement only when the request+ genuinely changes; explain a conflict instead of quietly widening a range.+- For a targeted revision, verify the requested change and compare unaffected+ parts. Keep a useful previous version; generated handoffs are retained under+ `.harness/history/`.++## Hear and hand off++Use `score.html` in the actual viewer. Exercise play/pause, seeking into a held+note, player mute/solo, slowdown, bar loops and part selection. No instrument+is needed. The browser can save a WAV of the current mix/loop (up to 3 minutes).+Save/restore listening setup as JSON; no local storage is required.++The source-backed delivery is `score-project.zip`: full PDF/MIDI, individual+parts, slower solo/minus-one MIDI, the saved brief, allowlisted sources and+standalone rebuild tools. Test important downloads. Browser controls and WAV+exports do not change `score.ly` or the prebuilt practice MIDIs. To change the+composition, edit the sources and rebuild.++Report the version, checks and listening/visual review actually performed.+Offer concrete revisions in the user's language (“make the ending warmer,”+“remove the busy line”), not a requirement to learn notation first.## BoundariesRequires LilyPond (tested 2.26.0) and Node 20+. `LILYPOND_BIN` overrides the-binary. This workflow does not implement MuseScore export. Only trusted input:-LilyPond can execute Scheme and read local files.--Fresh staged builds preserve old artifacts on compilation failure and set-`ready: false`. See `.harness/render.log`. Do not treat previous output as a-successful new render. Ready means engraving plus MIDI parsing, not proof of-musical correctness, performability or playback fidelity.--The browser uses a deliberately simple local synth. Pedal/controllers,-instrument timbres and human expression are not reproduced. Listening controls-do not persist. The parser supports type 0/1 PPQ MIDI, not SMPTE timing; preview-limits are 10,000 notes, one hour and 40 SVG pages.+binary. Only compile trusted input: LilyPond can execute Scheme and read local+files. The source allowlist makes delivery explicit; it is not a Scheme sandbox.+Do not add unrelated files, credentials or recordings to the portable project.++Ready means fresh engraving and the saved **mechanical** requirements passed,+not proof of musical quality, comfort, breath control, fingering, physical+playability or permission to use an arrangement. A synthesized sketch is not+a recording or sampled performance. No real-player testing is implied.++This checked workflow supports constant meter/tempo, complete bars and pitched+staves. See the contract for limits and excluded cases. Original native MIDI+is retained; practice exports and browser audio ignore pedal, bends and other+expressive controllers. The browser uses simple oscillators, not a sound library.++Legacy `score.ly` projects containing full layout/MIDI blocks still engrave+without an ensemble contract, but remain unready for checked delivery. Preserve+their source and extract music variables deliberately when upgrading. Do not+blindly replace a user's composition with the template.diff --git a/store/agents/score/skills/score/references/ensemble.md b/store/agents/score/skills/score/references/ensemble.mdnew file mode 100644index 000000000..dbe888cfd--- /dev/null+++ b/store/agents/score/skills/score/references/ensemble.md@@ -0,0 +1,113 @@+# Ensemble contract++`ensemble.json` is the saved musical brief; `score.ly` defines reusable music+variables in concert pitch. Do not derive or loosen requested constraints merely+to match a generated score.++## Fields++| Field | Meaning |+| --- | --- |+| `spec` | `1` |+| `title`, `composer` | Printed title and composition/arrangement credit |+| `brief`, `assumptions` | User intent and explicit assumptions; assumptions may be `[]` |+| `meter` | `[numerator, denominator]`; numerator 1–12, denominator 2/4/8/16 |+| `quarterBpm`, `bars` | Constant quarter-note tempo 20–240; 1–128 complete bars |+| `key` | Initial **concert** key: `{"tonic":"c","mode":"major"}` |+| `sourceFiles` | Explicit relative paths, including `score.ly` and `ensemble.json` |+| `practice` | `{"speed":0.75,"countInBars":1}`; speed .25–1.5, count-in 0–2 bars |+| `players` | 1–8 players; 1–2 staves per player, at most 15 staves total |++Key tonics use LilyPond's default Dutch spelling: c/cis/des/d/dis/ees/e/f/fis/+ges/g/gis/aes/a/ais/bes/b; mode is major or minor. The contract sets an initial+key signature, not a test that every note belongs to a scale.++A player:++```json+{+ "id": "clarinet",+ "label": "B-flat clarinet",+ "instrument": "B-flat clarinet",+ "midiInstrument": "clarinet",+ "soundingC": "Bb3",+ "staves": [+ {+ "id": "clarinet-line",+ "music": "clarinetMusic",+ "clef": "treble",+ "writtenRange": ["C4", "G5"],+ "maxPolyphony": 1,+ "maxLeapSemitones": 7,+ "maxAttacksPerBar": 4+ }+ ]+}+```++`soundingC` means **the concert pitch heard when this instrument reads C4**.+C instruments use C4; B-flat clarinet uses Bb3. Scientific pitch C4 is MIDI 60.+Transposition may be within two octaves. Confirm unusual instrument/register+choices rather than guessing. `midiInstrument` must be a LilyPond-recognized+pitched General MIDI instrument. Percussion, octave clefs and unpitched notation+are outside this checked workflow.++Player and staff IDs are unique lowercase names with letters/digits/hyphens;+`score` is reserved for the full-score selection. Music-variable names contain+letters only and are unique. Supported clefs: treble/bass/alto/tenor. A two-staff+player prints with a PianoStaff bracket.++Each staff has a required **written** range and maximum simultaneous notes+(1–10). Optional `maxLeapSemitones` (1–24) requires monophony and measures+successive notes, including across rests; it does not assess fingering.+Optional `maxAttacksPerBar` (1–64) counts distinct MIDI onsets, not tied notes or+individual notes within a chord. These are editable limits, not skill ratings.++## Source and timing++The builder places the initial key/meter/tempo before each variable. Clefs are+fixed per staff in this workflow; set them in the contract. Do not put+book/score blocks in a new checked source, pretranspose written parts, change+MIDI instrument within a staff, or override `\transposition`. Dynamics, slurs,+rests, chord voicings and breaks belong in the music variables.++The supported time grid is constant: no pickup, mid-piece meter/tempo change,+unexpanded repeat structure, cadenza or zero-duration grace notes. If needed,+write an explicitly expanded complete-bar version (including \repeat unfold)+and explain the change, or+keep it as legacy engraving without claiming checked readiness. The source guard+rejects literal pickups, folded repeats, cadenzas and wrapper-owned commands;+it is not a parser or security boundary for arbitrary Scheme.++The builder measures end-of-track duration including rests against+`bars × numerator × 4/denominator` quarter notes. A literal `|` is a LilyPond+bar check, not a bar counter. Each staff gets independent concert and written+MIDI proofs; actual written pitches are range-checked. Each sounding part and+the full MIDI are compared with the concert proofs. A second native pass must+produce identical MIDI before the SVG preview is accepted.++## Portable files and failure handling++List every local `\include` dependency. Use relative paths, no symlinks, at most+32 sources of 1 MiB each; allowed source extensions are `.ly`, `.ily`, `.json`,+`.txt`, `.md`. `score-assets/`, `rebuild/` and `REBUILD.md` are reserved. The+portable ZIP is bounded to 32 MiB. Trusted Scheme can still read arbitrary+files; the allowlist is not isolation.++Fresh builds snapshot sources, hash-check them before publication, and acquire+`.harness/score-build.lock`. Do not remove a lock until its owner has stopped.+Staged output is installed with rollback; previous generated files are retained+under `.harness/history/`. Compilation or failed requirements keep the last+successful handoff and clear readiness. See `.harness/render.log`,+`.harness/failed-score.json` and the successful `.harness/score.json`.++The practice pack keeps one program per staff, reserves MIDI channel 10 for+count-in percussion, and checks the exported pitched notes after re-parsing.+Count-in uses denominator beats, or dotted-quarter pulses in compound 6/8,+9/8 and 12/8. Browser count-in follows the same pulse convention.++Preview limits: 10,000 notes, one hour, 40 pages per document. WAV export is a+mono 22.05 kHz PCM synthetic sketch, limited to 3 minutes including count-in.+It uses the current loop/speed/mix; the prebuilt MIDI practice pack uses+`practice` in the saved contract. Listening setup JSON is tied to the exact+source revision, so a stale setup is rejected after a composition change.diff --git a/store/agents/score/skills/score/scripts/LICENSE b/store/agents/score/skills/score/scripts/LICENSEnew file mode 100644index 000000000..d3eab18ed--- /dev/null+++ b/store/agents/score/skills/score/scripts/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 OpenHarness contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/store/agents/score/skills/score/scripts/archive.mjs b/store/agents/score/skills/score/scripts/archive.mjsnew file mode 100644index 000000000..c272a8548--- /dev/null+++ b/store/agents/score/skills/score/scripts/archive.mjs@@ -0,0 +1,34 @@+// Small, bounded, deterministic ZIP writer. No global npm or Python dependency.+import {deflateRawSync} from 'node:zlib';+const table=Uint32Array.from({length:256},(_,value)=>{+ for (let i=0;i<8;i++) value=value&1 ? 0xedb88320^(value>>>1) : value>>>1;+ return value>>>0;+});+function crc32(bytes) {+ let crc=0xffffffff;+ for (const byte of bytes) crc=table[(crc^byte)&255]^(crc>>>8);+ return (crc^0xffffffff)>>>0;+}+export function zip(files) {+ if (!files.length || files.length>256) throw new Error('Archive needs 1–256 files.');+ const chunks=[], central=[], names=new Set(); let offset=0, total=0;+ for (const {name,bytes:input} of files) {+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(name) || name.split('/').some(p=>!p || p==='.' || p==='..') || names.has(name.toLowerCase())) throw new Error('Unsafe or duplicate archive path: '+name);+ names.add(name.toLowerCase());+ const bytes=Buffer.from(input), filename=Buffer.from(name), compressed=deflateRawSync(bytes), crc=crc32(bytes);+ total+=bytes.length;+ if (total>32*1024*1024) throw new Error('Portable project exceeds 32 MiB uncompressed.');+ const header=Buffer.alloc(30);+ header.writeUInt32LE(0x04034b50,0); header.writeUInt16LE(20,4); header.writeUInt16LE(0x800,6); header.writeUInt16LE(8,8);+ header.writeUInt16LE(33,12); header.writeUInt32LE(crc,14); header.writeUInt32LE(compressed.length,18); header.writeUInt32LE(bytes.length,22); header.writeUInt16LE(filename.length,26);+ const entry=Buffer.alloc(46);+ entry.writeUInt32LE(0x02014b50,0); entry.writeUInt16LE(20,4); entry.writeUInt16LE(20,6); entry.writeUInt16LE(0x800,8); entry.writeUInt16LE(8,10); entry.writeUInt16LE(33,14);+ entry.writeUInt32LE(crc,16); entry.writeUInt32LE(compressed.length,20); entry.writeUInt32LE(bytes.length,24); entry.writeUInt16LE(filename.length,28); entry.writeUInt32LE(offset,42);+ chunks.push(header,filename,compressed); central.push(entry,filename); offset+=header.length+filename.length+compressed.length;+ }+ const directory=Buffer.concat(central), end=Buffer.alloc(22);+ end.writeUInt32LE(0x06054b50,0); end.writeUInt16LE(files.length,8); end.writeUInt16LE(files.length,10); end.writeUInt32LE(directory.length,12); end.writeUInt32LE(offset,16);+ const output=Buffer.concat([...chunks,directory,end]);+ if (output.length>32*1024*1024) throw new Error('Portable project exceeds the 32 MiB download limit.');+ return output;+}diff --git a/store/agents/score/skills/score/scripts/build.mjs b/store/agents/score/skills/score/scripts/build.mjsindex ea5a04dfa..0baa1ba01 100644--- a/store/agents/score/skills/score/scripts/build.mjs+++ b/store/agents/score/skills/score/scripts/build.mjs@@ -1,33 +1,198 @@-import {readFile,writeFile,mkdir,mkdtemp,readdir,rename,rm,copyFile,access} from 'node:fs/promises';-import {spawnSync} from 'node:child_process';import {resolve,join} from 'node:path';import {pathToFileURL} from 'node:url';-import {parseMidi} from './midi.mjs';-const ws=resolve(process.env.HARNESS_WORKSPACE||process.cwd()),meta=join(ws,'.harness');await mkdir(meta,{recursive:true});-const verdict=async(ready,summary,findings=[])=>writeFile(join(meta,'verdict.json'),JSON.stringify({spec:1,ready,summary,findings,artifact:ready?'score.html':null,updatedAt:new Date().toISOString()},null,2)+'\n');-await verdict(false,'Engraving source and checking note timing…');let stage,log='';-try{- const source=await readFile(join(ws,'score.ly'),'utf8');if(source.length>1024*1024)throw new Error('Score source exceeds 1 MiB.');- const bin=process.env.LILYPOND_BIN||'lilypond';stage=await mkdtemp(join(meta,'score-'));- const run=args=>{const r=spawnSync(bin,args,{cwd:ws,encoding:'utf8',timeout:120000,maxBuffer:8*1024*1024});log+=(r.stdout||'')+(r.stderr||'');if(r.error||r.status!==0)throw new Error(r.error?.message||'LilyPond rejected the score; inspect .harness/render.log.');};- const prefix=join(stage,'score');run(['-dwarning-as-error','--pdf','-o',prefix,join(ws,'score.ly')]);- const pdf=await readFile(prefix+'.pdf');if(pdf.length<100||pdf.subarray(0,5).toString()!=='%PDF-')throw new Error('LilyPond produced no fresh PDF.');- let midiFile=(await readdir(stage)).find(name=>/^score\.(midi|mid)$/.test(name));if(!midiFile)throw new Error('Add a MIDI block to the score: no fresh MIDI was produced.');- const midi=parseMidi(await readFile(join(stage,midiFile)));if(midi.notes.length>10000||midi.duration>3600)throw new Error('Playback preview is limited to 10,000 notes and one hour.');- run(['-dwarning-as-error','--svg','-o',prefix,join(ws,'score.ly')]);- const svg=(await readdir(stage)).filter(name=>/^score(?:-\d+)?\.svg$/.test(name)).sort((a,b)=>a.localeCompare(b,undefined,{numeric:true}));if(!svg.length||svg.length>40)throw new Error('Expected 1–40 SVG score pages.');- const pages=[];for(const name of svg){const content=await readFile(join(stage,name),'utf8');if(content.length<100||!content.includes('<svg'))throw new Error('Invalid engraved SVG page.');pages.push(name);}- const title=source.match(/\btitle\s*=\s*"([^"]+)"/)?.[1]||'Untitled score';- const data={title,pages:pages.map(name=>'score-assets/'+name),midi};- const template=await readFile(new URL('preview.html',import.meta.url),'utf8'),app=await readFile(new URL('preview.js',import.meta.url),'utf8');- const safe=JSON.stringify(data).replace(/</g,'\\u003c').replace(/\u2028/g,'\\u2028').replace(/\u2029/g,'\\u2029');- await writeFile(join(stage,'score.html'),template.replace('__CONFIG__',()=>safe).replace('/*APP*/',()=>app));- const assets=join(stage,'assets');await mkdir(assets);for(const name of pages)await rename(join(stage,name),join(assets,name));- // Back up only the generated assets directory; never remove source files.- const destination=join(ws,'score-assets'),backup=join(stage,'previous-assets');let hadOld=false;- try{await rename(destination,backup);hadOld=true;}catch(error){if(error.code!=='ENOENT')throw error;}- try{await rename(assets,destination);}catch(error){if(hadOld)await rename(backup,destination);throw error;}- await rename(prefix+'.pdf',join(ws,'score.pdf'));await copyFile(join(stage,midiFile),join(ws,'score.midi'));await rename(join(stage,'score.html'),join(ws,'score.html'));- await writeFile(join(meta,'score.json'),JSON.stringify({pages:pages.length,notes:midi.notes.length,durationSeconds:midi.duration},null,2)+'\n');- await verdict(true,pages.length+' engraved page'+(pages.length===1?'':'s')+' · '+midi.notes.length+' MIDI notes',[{severity:'info',kind:'playback',message:'Simple synthesized MIDI preview, not a performance or proof of musical correctness.'}]);- console.log('ok LilyPond → score.pdf + score.midi + score.html');-}catch(error){await verdict(false,'Score render failed',[{severity:'error',kind:'render',message:error.message}]);console.error(error.message);process.exitCode=1;}-finally{await writeFile(join(meta,'render.log'),log);if(stage)await rm(stage,{recursive:true,force:true});}+import {readFile,writeFile,mkdir,mkdtemp,readdir,rename,rm,copyFile,lstat,realpath} from 'node:fs/promises';+import {spawnSync} from 'node:child_process';+import {resolve,join,dirname,basename,sep,posix} from 'node:path';+import {fileURLToPath} from 'node:url';+import {createHash} from 'node:crypto';+import {parseMidi,writePracticeMidi} from './midi.mjs';+import {validateEnsemble,validateMusicSources,makeWrapper,checkEnsemble,sameNotes} from './ensemble.mjs';+import {zip} from './archive.mjs';++const sha=bytes=>createHash('sha256').update(bytes).digest('hex');+const json=value=>JSON.stringify(value,null,2)+'\n';+async function exists(path) {+ try { await lstat(path); return true; } catch (error) { if (error.code==='ENOENT') return false; throw error; }+}+async function regularSource(workspace,name) {+ let path=workspace;+ for (const component of name.split('/')) {+ path=join(path,component);+ if ((await lstat(path)).isSymbolicLink()) throw new Error('Source symlinks are not portable: '+name);+ }+ const info=await lstat(path);+ if (!info.isFile() || info.size>1024*1024) throw new Error('Each source must be a regular file no larger than 1 MiB: '+name);+ if (!(await realpath(path)).startsWith(await realpath(workspace)+sep)) throw new Error('Source escapes workspace: '+name);+ return readFile(path);+}+export async function snapshotSources(workspace,spec) {+ const files=[];+ for (const name of spec.sourceFiles) files.push({name,bytes:await regularSource(workspace,name)});+ const allowed=new Set(files.map(file=>file.name));+ for (const file of files.filter(file=>/\.(ly|ily)$/i.test(file.name))) {+ for (const match of file.bytes.toString('utf8').matchAll(/\\include\s+"([^"]+)"/g)) {+ const included=posix.normalize(posix.join(posix.dirname(file.name),match[1]));+ if (match[1].startsWith('/') || !allowed.has(included)) throw new Error('Add the trusted include to sourceFiles: '+match[1]);+ }+ }+ return files;+}+async function unchanged(workspace,files) {+ for (const file of files) if (sha(await regularSource(workspace,file.name))!==sha(file.bytes)) throw new Error('Source changed during build; rebuild the saved project: '+file.name);+}+async function publish(workspace,state,stage,names) {+ const history=join(state,'history',basename(stage)); await mkdir(history,{recursive:true});+ const saved=[],installed=[];+ try {+ if (await exists(join(state,'score.json'))) await copyFile(join(state,'score.json'),join(history,'score.json'));+ for (const name of names) {+ if (await exists(join(workspace,name))) { await rename(join(workspace,name),join(history,name)); saved.push(name); }+ await rename(join(stage,name),join(workspace,name)); installed.push(name);+ }+ return history;+ } catch (error) {+ const failures=[];+ for (const name of installed.reverse()) try { await rename(join(workspace,name),join(stage,name)); } catch (error) { failures.push(error.message); }+ for (const name of saved.reverse()) try { await rename(join(history,name),join(workspace,name)); } catch (error) { failures.push(error.message); }+ if (failures.length) throw new Error('Publication failed; recover previous files from '+history+': '+failures.join('; '));+ throw error;+ }+}+export async function build(workspace,{bin=process.env.LILYPOND_BIN||'lilypond'}={}) {+ workspace=resolve(workspace);+ const meta=join(workspace,'.harness');+ if (await exists(meta) && (await lstat(meta)).isSymbolicLink()) throw new Error('.harness must not be a symlink.');+ await mkdir(meta,{recursive:true});+ const lock=join(meta,'score-build.lock');+ try { await mkdir(lock); } catch (error) {+ if (error.code==='EEXIST') throw new Error('Another build owns .harness/score-build.lock. Confirm its process has stopped before removing a stale lock.');+ throw error;+ }+ const atomic=async(path,value)=>{ const tmp=path+'.'+process.pid+'.tmp'; await writeFile(tmp,value); await rename(tmp,path); };+ const verdict=(ready,summary,findings=[],artifact=null)=>atomic(join(meta,'verdict.json'),json({spec:1,ready,summary,findings,artifact,updatedAt:new Date().toISOString()}));+ let stage,log='',report;+ try {+ await writeFile(join(lock,'owner.json'),json({pid:process.pid,startedAt:new Date().toISOString()}));+ await verdict(false,'Engraving fresh music, checking the player brief and preparing practice files');+ const contract=await exists(join(workspace,'ensemble.json')) ? await regularSource(workspace,'ensemble.json') : null;+ const spec=contract?validateEnsemble(JSON.parse(contract)):null;+ const files=await snapshotSources(workspace,spec||{sourceFiles:['score.ly']});+ if (spec) validateMusicSources(files);+ if (contract && !contract.equals(files.find(file=>file.name==='ensemble.json').bytes)) throw new Error('Ensemble brief changed while reading sources.');+ const sources=Object.fromEntries(files.map(file=>[file.name,sha(file.bytes)]).sort(([a],[b])=>a.localeCompare(b)));+ const sourceRevision=sha(JSON.stringify(sources));+ stage=await mkdtemp(join(meta,'score-')); const native=join(stage,'native'); await mkdir(native);+ for (const file of files) { const path=join(native,'source',file.name); await mkdir(dirname(path),{recursive:true}); await writeFile(path,file.bytes); }+ const run=args=>{+ const result=spawnSync(bin,args,{cwd:native,encoding:'utf8',timeout:120000,maxBuffer:8*1024*1024});+ log+=(result.stdout||'')+(result.stderr||'');+ if (result.error || result.status!==0) throw new Error('LilyPond failed: '+(result.error?.message||'exit '+result.status)+'. See .harness/render.log.');+ return result.stdout;+ };+ const version=run(['--version']).split('\n')[0];+ const render=async svg=>{+ const input=spec?join(native,'render.ly'):join(native,'source','score.ly');+ if (spec) await writeFile(input,makeWrapper(spec,{svg}));+ run(['-dwarning-as-error','-dno-point-and-click',svg?'--svg':'--pdf','-o',spec?native+sep:join(native,'score'),input]);+ await unchanged(workspace,files);+ };+ await render(false);+ const readMidi=async name=>{+ const file=(await readdir(native)).find(file=>file===name+'.midi'||file===name+'.mid');+ if (!file) throw new Error('Missing fresh MIDI for '+name+'.');+ const bytes=await readFile(join(native,file));+ return {bytes,data:parseMidi(bytes,{allowEmpty:true})};+ };+ const full=await readMidi('score');+ if (!full.data.notes.length || full.data.notes.length>10000 || full.data.duration>3600) throw new Error('Preview requires 1–10,000 notes and at most one hour.');+ let measured={checks:[],staves:[],notes:full.data.notes.map(note=>({...note,player:'music',staff:'track-'+note.track}))};+ const parts={};+ if (spec) {+ const proofs={};+ for (const player of spec.players) {+ parts[player.id]=(await readMidi('part-'+player.id));+ for (const staff of player.staves) proofs[staff.id]={concert:(await readMidi('concert-'+staff.id)).data,written:(await readMidi('written-'+staff.id)).data};+ }+ measured=checkEnsemble(spec,full.data,proofs,Object.fromEntries(Object.entries(parts).map(([id,part])=>[id,part.data])));+ }+ report={spec:1,checked:!!spec,title:spec?.title||files[0].bytes.toString().match(/\btitle\s*=\s*"([^"]+)"/)?.[1]||'Untitled score',+ sourceRevision,sources,engine:version,checks:measured.checks,staves:measured.staves,notes:full.data.notes.length,durationSeconds:full.data.duration,+ limitations:['Mechanical checks do not certify playability or musical quality. No real-player validation is implied.','Playback and practice MIDI are note-only sketches: no pedal, bend, sampled instruments or human performance.']};+ const failures=measured.checks.filter(check=>!check.passed);+ if (failures.length) {+ await atomic(join(meta,'failed-score.json'),json(report));+ throw new Error(failures.map(check=>check.id+': '+check.detail).join('\n')+'\nSee .harness/failed-score.json. The last successful score and practice pack are unchanged.');+ }+ await render(true);+ for (const [name,first] of [['score',full],...Object.entries(parts).map(([id,part])=>['part-'+id,part])]) {+ if (!first.bytes.equals((await readMidi(name)).bytes)) throw new Error('PDF and SVG passes produced different MIDI: '+name+'. Remove nondeterministic source and rebuild.');+ }+ const assets=join(stage,'score-assets'); await mkdir(assets);+ const documents=[];+ for (const item of [{id:'score',name:'score',label:'Full score'},...(spec?.players||[]).map(player=>({id:player.id,name:'part-'+player.id,label:player.label}))]) {+ const pdf=await readFile(join(native,item.name+'.pdf'));+ if (pdf.length<100 || pdf.subarray(0,5).toString()!=='%PDF-') throw new Error('Invalid fresh PDF: '+item.name);+ const names=(await readdir(native)).filter(name=>new RegExp('^'+item.name+'(?:-\\d+)?\\.svg$').test(name)).sort((a,b)=>a.localeCompare(b,undefined,{numeric:true}));+ if (!names.length || names.length>40) throw new Error('Expected 1–40 engraved pages for '+item.name);+ for (const name of names) {+ const content=await readFile(join(native,name),'utf8');+ if (!content.includes('<svg') || content.length<100) throw new Error('Invalid SVG '+name);+ await writeFile(join(assets,name),content);+ }+ const target=item.id==='score'?join(stage,'score.pdf'):join(assets,item.name+'.pdf');+ await writeFile(target,pdf);+ documents.push({...item,pages:names.map(name=>'score-assets/'+name),pdf:item.id==='score'?'score.pdf':'score-assets/'+item.name+'.pdf'});+ if (item.id!=='score') await writeFile(join(assets,item.name+'.midi'),parts[item.id].bytes);+ }+ await writeFile(join(stage,'score.midi'),full.bytes);+ const practice=[];+ if (spec) {+ const exportPractice=async(name,label,selected)=>{+ const bytes=writePracticeMidi({notes:selected,division:full.data.division,endTick:full.data.endTick,quarterBpm:spec.quarterBpm,meter:spec.meter,...spec.practice});+ const parsed=parseMidi(bytes,{allowEmpty:true}), offset=spec.practice.countInBars*full.data.division*spec.meter[0]*4/spec.meter[1];+ const pitched={division:parsed.division,notes:parsed.notes.filter(note=>note.channel!==9).map(note=>({...note,startTick:note.startTick-offset,endTick:note.endTick-offset}))};+ if (!sameNotes({notes:selected,division:full.data.division},pitched) || parsed.endTick!==full.data.endTick+offset || Math.abs(parsed.tempos[0].tempo-60e6/(spec.quarterBpm*spec.practice.speed))>1.1) throw new Error('Practice MIDI round-trip failed: '+name);+ await writeFile(join(assets,name+'.midi'),bytes);+ practice.push({label,path:'score-assets/'+name+'.midi',notes:selected.length});+ };+ await exportPractice('practice-full','Slow ensemble + count-in',measured.notes);+ for (const player of spec.players) {+ await exportPractice('solo-'+player.id,player.label+' only',measured.notes.filter(note=>note.player===player.id));+ await exportPractice('minus-'+player.id,'Without '+player.label,measured.notes.filter(note=>note.player!==player.id));+ }+ }+ report.documents=documents.map(doc=>({id:doc.id,pdf:doc.pdf,pages:doc.pages.length}));+ report.practice=practice; report.ensemble=spec;+ await writeFile(join(assets,'checks.json'),json(report));+ const data={...report,documents,practice,midi:{...full.data,notes:measured.notes},players:spec?.players||[{id:'music',label:'Music'}]};+ const template=await readFile(new URL('preview.html',import.meta.url),'utf8'),app=await readFile(new URL('preview.js',import.meta.url),'utf8');+ const safe=JSON.stringify(data).replace(/</g,'\\u003c').replace(/\u2028/g,'\\u2028').replace(/\u2029/g,'\\u2029');+ await writeFile(join(stage,'score.html'),template.replace('__CONFIG__',()=>safe).replace('/*APP*/',()=>app));+ const outputs=['score.pdf','score.midi','score.html','score-assets'];+ if (spec) {+ const bundle=[...files];+ for (const name of ['build.mjs','ensemble.mjs','archive.mjs','midi.mjs','preview.html','preview.js','LICENSE']) bundle.push({name:'rebuild/'+name,bytes:await readFile(new URL(name,import.meta.url))});+ bundle.push({name:'REBUILD.md',bytes:Buffer.from('# '+spec.title+'\n\nInstall Node 20+ and LilyPond (tested '+version+'). From this extracted folder run:\n\n node rebuild/build.mjs .\n\nSet LILYPOND_BIN if LilyPond is not on PATH. No Harness account or npm packages required.\nEdit ensemble.json for the saved brief, players and checks; edit score.ly for concert-pitch music variables. Only compile trusted LilyPond: it can execute Scheme.\n\nOpen score.html in a browser. The PDF, MIDI, player parts and practice files work outside Harness. Checks and source hashes are in score-assets/checks.json. A checked export is not a real-player endorsement.\n\nPractice exports use '+spec.practice.speed+'x tempo and '+spec.practice.countInBars+' count-in bar(s). These are note-only synthetic sketches, not recordings. Files in rebuild/ are MIT-licensed tools; see rebuild/LICENSE. Composition credit: '+spec.composer+'. Source permissions remain the creator’s responsibility.\n')});+ for (const name of outputs.filter(name=>name!=='score-assets')) bundle.push({name,bytes:await readFile(join(stage,name))});+ for (const name of await readdir(assets)) bundle.push({name:'score-assets/'+name,bytes:await readFile(join(assets,name))});+ await writeFile(join(stage,'score-project.zip'),zip(bundle)); outputs.push('score-project.zip');+ }+ await unchanged(workspace,files);+ report.previousArtifacts=await publish(workspace,meta,stage,outputs);+ await atomic(join(meta,'score.json'),json(report));+ await verdict(!!spec,spec?spec.players.length+' players · '+measured.checks.length+' checks passed · score, parts and practice pack ready':'Legacy score engraved; add ensemble.json to verify the player brief',+ [{severity:spec?'info':'warning',kind:'music',message:report.limitations.join(' ')}],'score.html');+ return report;+ } catch (error) {+ await verdict(false,'Score build failed',[{severity:'error',kind:'build',message:error.message}]);+ throw error;+ } finally {+ await atomic(join(meta,'render.log'),log);+ if (stage) await rm(stage,{recursive:true,force:true});+ await rm(lock,{recursive:true,force:true});+ }+}+if (process.argv[1] && resolve(process.argv[1])===fileURLToPath(import.meta.url)) {+ try {+ const report=await build(process.argv[2]||process.env.HARNESS_WORKSPACE||process.cwd());+ console.log(report.checked?'Ready: '+report.checks.length+' measured checks; open score.html or download score-project.zip.':'Legacy engraving available; player requirements have not been checked.');+ } catch (error) { console.error(error.message); process.exitCode=1; }+}diff --git a/store/agents/score/skills/score/scripts/ensemble.mjs b/store/agents/score/skills/score/scripts/ensemble.mjsnew file mode 100644index 000000000..bf6cd95a6--- /dev/null+++ b/store/agents/score/skills/score/scripts/ensemble.mjs@@ -0,0 +1,179 @@+// A saved player brief, independent of the music it is meant to constrain.+const fail = message => { throw new Error(message); };+const integer = (value, min, max, label) => Number.isInteger(value) && value >= min && value <= max || fail(label+' must be an integer from '+min+' to '+max+'.');+const string = (value, max, label) => typeof value === 'string' && value.trim() && value.length <= max && !/[\x00-\x1f]/.test(value) || fail('Invalid '+label+'.');+const keys = new Set('c cis des d dis ees e f fis ges g gis aes a ais bes b'.split(' '));+const idPattern = /^[a-z][a-z0-9-]{0,31}$/;+function fields(value, allowed, label) {+ if (!value || typeof value!=='object' || Array.isArray(value)) fail(label+' must be an object.');+ for (const key of Object.keys(value)) if (!allowed.includes(key)) fail('Unknown '+label+' field: '+key);+}+export function pitch(value) {+ const match = /^([A-G])([b#]?)(-1|[0-9])$/.exec(value);+ if (!match) fail('Use scientific pitches such as C4 or Bb3: '+value);+ const midi = (Number(match[3])+1)*12 + {C:0,D:2,E:4,F:5,G:7,A:9,B:11}[match[1]] + (match[2]==='#'?1:match[2]==='b'?-1:0);+ if (midi<0 || midi>127) fail('Pitch outside MIDI range: '+value);+ return midi;+}+export function pitchName(midi) {+ return ['C','C#','D','Eb','E','F','F#','G','Ab','A','Bb','B'][midi%12]+(Math.floor(midi/12)-1);+}+function lilyPitch(value) {+ const [,note,accidental,octave] = /^([A-G])([b#]?)(-1|[0-9])$/.exec(value);+ const suffix = accidental==='#'?'is':accidental==='b'?'es':'';+ return note.toLowerCase()+suffix+(Number(octave)>=3?"'".repeat(Number(octave)-3):','.repeat(3-Number(octave)));+}+export function validateEnsemble(raw) {+ const spec = structuredClone(raw);+ fields(spec,['spec','title','brief','composer','assumptions','meter','quarterBpm','bars','key','sourceFiles','practice','players'],'ensemble');+ if (!spec || spec.spec!==1) fail('ensemble.json requires spec: 1.');+ string(spec.title,100,'title'); string(spec.brief,2000,'brief');+ string(spec.composer,100,'composer / credit');+ if (!Array.isArray(spec.assumptions) || spec.assumptions.length>20) fail('List assumptions explicitly, even if empty.');+ for (const text of spec.assumptions) string(text,400,'assumption');+ if (!Array.isArray(spec.meter) || spec.meter.length!==2) fail('meter must be [numerator, denominator].');+ integer(spec.meter[0],1,12,'Meter numerator');+ if (![2,4,8,16].includes(spec.meter[1])) fail('Meter denominator must be 2, 4, 8 or 16.');+ integer(spec.bars,1,128,'Bars'); integer(spec.quarterBpm,20,240,'Quarter-note tempo');+ fields(spec.key,['tonic','mode'],'key');+ if (!keys.has(spec.key?.tonic) || !['major','minor'].includes(spec.key?.mode)) fail('Specify a concert key, using LilyPond pitch spelling.');+ if (!Array.isArray(spec.sourceFiles) || !spec.sourceFiles.includes('score.ly') || !spec.sourceFiles.includes('ensemble.json') || spec.sourceFiles.length>32) fail('sourceFiles must include score.ly and ensemble.json, with at most 32 files.');+ const paths=new Set();+ for (const name of spec.sourceFiles) {+ if (typeof name!=='string' || name.length>160 || !/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(name) || name.split('/').some(part=>!part || part==='.' || part==='..' || part.startsWith('.')) || !/\.(ly|ily|json|txt|md)$/i.test(name)) fail('Unsafe or unsupported source filename: '+name);+ if (paths.has(name.toLowerCase()) || /^(score-assets|rebuild|\.harness)(\/|$)/i.test(name) || name.toLowerCase()==='rebuild.md') fail('Duplicate or reserved source path: '+name);+ paths.add(name.toLowerCase());+ }+ if (!Array.isArray(spec.players) || !spec.players.length || spec.players.length>8) fail('Use 1–8 players.');+ const ids=new Set(), music=new Set();+ const unique = id => {+ if (typeof id!=='string' || !idPattern.test(id) || ids.has(id)) fail('Player and staff IDs must be unique, lowercase filename-safe names: '+id);+ ids.add(id);+ };+ let staffCount=0;+ for (const player of spec.players) {+ fields(player,['id','label','instrument','midiInstrument','soundingC','staves'],'player');+ unique(player.id); if (player.id==='score') fail('score is a reserved player ID.');+ string(player.label,60,'player label'); string(player.instrument,100,'instrument');+ string(player.midiInstrument,60,'MIDI instrument');+ player.writtenShift=60-pitch(player.soundingC);+ if (Math.abs(player.writtenShift)>24) fail('Transposition is limited to two octaves.');+ if (!Array.isArray(player.staves) || !player.staves.length || player.staves.length>2) fail('Each player needs one or two staves.');+ for (const staff of player.staves) {+ fields(staff,['id','music','clef','writtenRange','maxPolyphony','maxLeapSemitones','maxAttacksPerBar'],'staff');+ unique(staff.id); staffCount++;+ if (!/^[a-zA-Z]+$/.test(staff.music) || staff.music.length>60 || music.has(staff.music)) fail('Each staff needs a distinct letter-only music variable.');+ music.add(staff.music);+ if (!['treble','bass','alto','tenor'].includes(staff.clef)) fail('Supported clefs: treble, bass, alto, tenor.');+ if (!Array.isArray(staff.writtenRange) || staff.writtenRange.length!==2) fail('Each staff needs a writtenRange.');+ staff.range=staff.writtenRange.map(pitch);+ if (staff.range[0]>staff.range[1]) fail('Written range is reversed.');+ integer(staff.maxPolyphony,1,10,'Maximum polyphony');+ if (staff.maxLeapSemitones!==undefined) {+ integer(staff.maxLeapSemitones,1,24,'Maximum leap');+ if (staff.maxPolyphony!==1) fail('Leap checks apply only to monophonic staves.');+ }+ if (staff.maxAttacksPerBar!==undefined) integer(staff.maxAttacksPerBar,1,64,'Maximum attacks per bar');+ }+ }+ if (staffCount>15) fail('At most 15 pitched staves are supported.');+ fields(spec.practice,['speed','countInBars'],'practice');+ if (!Number.isFinite(spec.practice.speed) || spec.practice.speed<.25 || spec.practice.speed>1.5) fail('Practice speed must be from 0.25 to 1.5.');+ integer(spec.practice.countInBars,0,2,'Count-in bars');+ return spec;+}++export function validateMusicSources(files) {+ // This is a supported-workflow guard, not a sandbox for LilyPond/Scheme.+ const owned=new Set(['time','tempo','key','clef','transposition','score','book','bookpart','layout','midi','paper','header']);+ for (const {name,bytes} of files.filter(file=>/\.(ly|ily)$/i.test(file.name))) {+ const code=bytes.toString('utf8').replace(/%\{[\s\S]*?%\}|%[^\n]*|"(?:\\.|[^"\\])*"/g,' ');+ for (const match of code.matchAll(/\\([a-zA-Z]+)\b/g)) {+ const command=match[1];+ if (owned.has(command)) throw new Error(name+': \\'+command+' is owned by ensemble.json/the generated wrapper. Checked sources contain concert-pitch music variables only.');+ if (['partial','cadenzaOn','cadenzaOff'].includes(command) || command==='repeat' && !/^\s+unfold\b/.test(code.slice(match.index+match[0].length))) {+ throw new Error(name+': \\'+command+' is outside the complete-bar checked workflow. Expand repeats and remove pickups/cadenzas deliberately, or use legacy engraving without checked readiness.');+ }+ }+ }+}++// The same written-music expression feeds the printed part and the written MIDI+// proof. A separate concert proof makes incorrect or double transposition visible.+export function makeWrapper(spec, {svg=false}={}) {+ const quote = value => JSON.stringify(value);+ const global = '\\key '+spec.key.tonic+' \\'+spec.key.mode+' \\time '+spec.meter.join('/')+' \\tempo 4 = '+spec.quarterBpm;+ const staff = (player, item, mode='sounding', labeled=true) => {+ const transpose = mode==='concert' ? '' : '\\transpose '+lilyPitch(player.soundingC)+" c' ";+ const tuning = mode==='sounding' ? lilyPitch(player.soundingC) : "c'";+ return '\\new Staff = '+quote(item.id)+' \\with { instrumentName = '+quote(labeled&&player.staves.length===1?player.label:'')+' midiInstrument = '+quote(player.midiInstrument)+' } { \\clef '+quote(item.clef)+' \\transposition '+tuning+' '+transpose+' { '+global+' \\'+item.music+' } }';+ };+ const group = (player,labeled=true) => player.staves.length===1 ? staff(player,player.staves[0],'sounding',labeled) :+ '\\new PianoStaff \\with { instrumentName = '+quote(labeled?player.label:'')+' } << '+player.staves.map(item=>staff(player,item,'sounding',labeled)).join('\n')+' >>';+ const header = subtitle => '\\header { title = '+quote(spec.title)+' subtitle = '+quote(subtitle)+' composer = '+quote(spec.composer)+' tagline = ##f }';+ const book = (name, content, subtitle, printed=true) => '\\book { \\bookOutputName '+quote(name)+' '+(printed?header(subtitle):'')+' \\score { '+content+(printed?' \\layout { indent = '+(name==='score'?30:0)+'\\mm short-indent = 4\\mm }':'')+' \\midi { } } }';+ const books=[book('score','<< '+spec.players.map(player=>group(player)).join('\n')+' >>','Full score - written pitches')];+ for (const player of spec.players) {+ books.push(book('part-'+player.id,group(player,false),player.label===player.instrument?player.label:player.label+' ('+player.instrument+')'));+ // Proof MIDI is generated during the PDF pass; SVG need not duplicate it.+ if (!svg) for (const item of player.staves) for (const mode of ['concert','written']) books.push(book(mode+'-'+item.id,staff(player,item,mode),'',false));+ }+ return '\\version "2.24.3"\n\\include "source/score.ly"\n\\paper { #(set-paper-size "a4") top-margin = 16\\mm bottom-margin = 16\\mm left-margin = 18\\mm right-margin = 18\\mm print-page-number = ##t }\n'+books.join('\n')+'\n';+}++function noteKey(note, division, shift=0) {+ return [note.pitch+shift,Math.round(note.startTick/division*1e6),Math.round(note.endTick/division*1e6)].join(':');+}+export function sameNotes(a, b, shift=0) {+ return JSON.stringify(a.notes.map(n=>noteKey(n,a.division,shift)).sort())===JSON.stringify(b.notes.map(n=>noteKey(n,b.division)).sort());+}+export function checkEnsemble(spec, full, proofs, parts) {+ const checks=[], notes=[], staves=[];+ const add=(id,passed,detail)=>checks.push({id,passed:!!passed,detail});+ const length = midi => Math.abs(midi.endTick/midi.division-spec.bars*spec.meter[0]*4/spec.meter[1])<1e-7;+ const timing = (name,midi) => {+ add(name+':duration',length(midi),spec.bars+' complete bars, measured from MIDI end-of-track (including rests)');+ add(name+':tempo',midi.tempos.length===1 && Math.abs(midi.tempos[0].tempo-60e6/spec.quarterBpm)<1.1,'Constant quarter-note tempo '+spec.quarterBpm);+ add(name+':meter',midi.meters.length>0 && midi.meters.every(m=>m.tick===0 && m.numerator===spec.meter[0] && m.denominator===spec.meter[1]),'Constant '+spec.meter.join('/')+' meter; pickups and meter changes need a different workflow');+ };+ timing('score',full);+ for (const player of spec.players) {+ const playerNotes=[];+ for (const staff of player.staves) {+ const {concert,written}=proofs[staff.id];+ timing(staff.id,concert); timing(staff.id+'-written',written);+ add(staff.id+':transposition',sameNotes(concert,written,player.writtenShift),'Written pitches = concert pitches '+(player.writtenShift>=0?'+':'')+player.writtenShift+' semitones');+ const pitches=written.notes.map(n=>n.pitch), low=pitches.length?Math.min(...pitches):null, high=pitches.length?Math.max(...pitches):null;+ add(staff.id+':range',pitches.every(n=>n>=staff.range[0] && n<=staff.range[1]),'Written '+(low===null?'rests only':pitchName(low)+'–'+pitchName(high))+'; allowed '+staff.writtenRange.join('–'));+ let active=0, maximum=0;+ const events=written.notes.flatMap(n=>[{tick:n.startTick,delta:1},{tick:n.endTick,delta:-1}]).sort((a,b)=>a.tick-b.tick || a.delta-b.delta);+ for (const event of events) { active+=event.delta; maximum=Math.max(maximum,active); }+ add(staff.id+':polyphony',maximum<=staff.maxPolyphony,'Maximum simultaneous notes '+maximum+'; allowed '+staff.maxPolyphony);+ add(staff.id+':note-duration',written.notes.every(n=>n.endTick>n.startTick),'Every note has positive MIDI duration; zero-time grace notes are not supported');+ if (staff.maxLeapSemitones!==undefined) {+ const leaps=written.notes.slice(1).map((n,i)=>Math.abs(n.pitch-written.notes[i].pitch)), largest=Math.max(0,...leaps);+ add(staff.id+':leaps',largest<=staff.maxLeapSemitones,'Largest successive-note leap '+largest+' semitones; allowed '+staff.maxLeapSemitones);+ }+ if (staff.maxAttacksPerBar!==undefined) {+ const bars=new Map();+ for (const note of written.notes) {+ const bar=Math.floor(note.startTick/written.division/(spec.meter[0]*4/spec.meter[1])+1e-8);+ if (!bars.has(bar)) bars.set(bar,new Set());+ bars.get(bar).add(note.startTick);+ }+ const maximum=Math.max(0,...[...bars.values()].map(set=>set.size));+ add(staff.id+':attacks',maximum<=staff.maxAttacksPerBar,'Most distinct attacks in a bar '+maximum+'; allowed '+staff.maxAttacksPerBar);+ }+ add(staff.id+':program',new Set(concert.notes.map(n=>n.program)).size<=1,'Practice exports use one instrument program per staff');+ for (const note of concert.notes) {+ const item={...note,staff:staff.id,player:player.id,startTick:Math.round(note.startTick/concert.division*full.division),endTick:Math.round(note.endTick/concert.division*full.division)};+ notes.push(item); playerNotes.push(item);+ }+ staves.push({id:staff.id,player:player.id,range:[low,high],allowed:staff.writtenRange,notes:pitches.length,maxPolyphony:maximum,writtenShift:player.writtenShift});+ }+ timing('part-'+player.id,parts[player.id]);+ add(player.id+':part-sounds',sameNotes({notes:playerNotes,division:full.division},parts[player.id]),'Separate part MIDI agrees with the independent concert-pitch source');+ }+ add('score:notes',sameNotes({notes,division:full.division},full),'Full-score MIDI equals every independent concert-pitch staff, with no missing or extra notes');+ return {checks,staves,notes:notes.sort((a,b)=>a.startTick-b.startTick || a.pitch-b.pitch)};+}diff --git a/store/agents/score/skills/score/scripts/midi.mjs b/store/agents/score/skills/score/scripts/midi.mjsindex 74a645841..6e8b3bf53 100644--- a/store/agents/score/skills/score/scripts/midi.mjs+++ b/store/agents/score/skills/score/scripts/midi.mjs@@ -1,30 +1,146 @@-// Standard MIDI File reader for note timing and a deliberately simple synth preview.-export function parseMidi(input){- const b=Buffer.from(input);let p=0;- const need=n=>{if(p+n>b.length)throw new Error('Truncated MIDI.');};- const u8=()=>{need(1);return b[p++];},u16=()=>u8()*256+u8(),u32=()=>u16()*65536+u16();- const tag=()=>String.fromCharCode(u8(),u8(),u8(),u8());- if(tag()!=='MThd'||u32()!==6)throw new Error('Invalid MIDI header.');- const format=u16(),count=u16(),division=u16();if(format>1||!count||count>64||!division||(division&0x8000))throw new Error('Only type 0/1 PPQ MIDI is supported.');- const events=[],tempos=[{tick:0,tempo:500000}];let maxTick=0;- const vlq=()=>{let v=0;for(let i=0;i<4;i++){const n=u8();v=v*128+(n&127);if(!(n&128))return v;}throw new Error('Invalid MIDI variable length.');};- for(let track=0;track<count;track++){- if(tag()!=='MTrk')throw new Error('Missing MIDI track.');const length=u32(),end=p+length;need(length);let tick=0,running=0;- while(p<end){tick+=vlq();maxTick=Math.max(maxTick,tick);let status=u8();if(status<128){if(!running)throw new Error('Missing MIDI running status.');p--;status=running;}else if(status<240)running=status;- if(status===255){const type=u8(),len=vlq();need(len);if(type===81&&len===3)tempos.push({tick,tempo:b[p]*65536+b[p+1]*256+b[p+2]});p+=len;continue;}- if(status===240||status===247){const len=vlq();need(len);p+=len;running=0;continue;}- const kind=status>>4,ch=status&15;if(kind<8||kind>14)throw new Error('Unsupported MIDI status.');- const a=u8(),v=kind===12||kind===13?0:u8();if(a>127||v>127)throw new Error('Invalid MIDI data byte.');- if(kind===8||kind===9)events.push({tick,track,ch,pitch:a,velocity:v,on:kind===9&&v>0});- if(events.length>100000)throw new Error('MIDI preview is limited to 100,000 note events.');- }if(p!==end)throw new Error('MIDI event exceeds its track.');+// Standard MIDI File timing, track identity and note-only practice exports.+// Controllers/pedal/bend are deliberately not presented as a faithful performance.+export function tickSeconds(tick, midi) {+ let tempo = midi.tempos[0];+ for (const item of midi.tempos) { if (item.tick > tick) break; tempo = item; }+ return tempo.seconds + (tick - tempo.tick) * tempo.tempo / midi.division / 1e6;+}++export function parseMidi(input, {allowEmpty=false}={}) {+ const bytes = Buffer.from(input);+ if (bytes.length > 16 * 1024 * 1024) throw new Error('MIDI exceeds 16 MiB.');+ let p=0, limit=bytes.length, eventCount=0;+ const need = n => { if (p+n > limit) throw new Error('Truncated MIDI or event exceeds its track.'); };+ const u8 = () => { need(1); return bytes[p++]; };+ const u16 = () => u8()*256+u8();+ const u32 = () => u16()*65536+u16();+ const tag = () => String.fromCharCode(u8(),u8(),u8(),u8());+ const vlq = () => {+ let value=0;+ for (let i=0;i<4;i++) { const byte=u8(); value=value*128+(byte&127); if (!(byte&128)) return value; }+ throw new Error('Invalid MIDI variable length.');+ };+ if (tag() !== 'MThd' || u32() !== 6) throw new Error('Invalid MIDI header.');+ const format=u16(), count=u16(), division=u16();+ if (format>1 || !count || count>64 || !division || division&0x8000 || format===0 && count!==1) throw new Error('Only type 0/1 PPQ MIDI is supported.');+ const events=[], rawTempos=[{tick:0,tempo:500000}], meters=[], trackInfo=[];+ let maxTick=0;+ for (let track=0;track<count;track++) {+ if (tag() !== 'MTrk') throw new Error('Missing MIDI track.');+ const length=u32(); need(length); const end=p+length; limit=end;+ let tick=0, running=0, ended=false;+ const programs=new Map(), info={index:track,name:'Track '+track,endTick:0};+ while (p<end) {+ if (++eventCount>200000) throw new Error('MIDI exceeds 200,000 events.');+ tick+=vlq(); maxTick=Math.max(maxTick,tick);+ let status=u8();+ if (status<128) { if (!running) throw new Error('Missing MIDI running status.'); p--; status=running; }+ else if (status<240) running=status;+ if (status===255) {+ running=0;+ const type=u8(), len=vlq(); need(len);+ if (type===81) {+ if (len!==3) throw new Error('Invalid MIDI tempo event.');+ rawTempos.push({tick,tempo:bytes[p]*65536+bytes[p+1]*256+bytes[p+2]});+ if (rawTempos.length>1024) throw new Error('Too many MIDI tempo changes.');+ }+ if (type===88) {+ if (len!==4 || !bytes[p] || bytes[p+1]>7) throw new Error('Invalid MIDI meter.');+ meters.push({tick,numerator:bytes[p],denominator:2**bytes[p+1]});+ }+ if (type===3) info.name=bytes.subarray(p,p+len).toString('utf8');+ if (type===47) {+ if (len!==0 || p!==end) throw new Error('Invalid MIDI end-of-track.');+ ended=true;+ }+ p+=len; continue;+ }+ if (status===240 || status===247) { const len=vlq(); need(len); p+=len; running=0; continue; }+ const kind=status>>4, channel=status&15;+ if (kind<8 || kind>14) throw new Error('Unsupported MIDI status.');+ const a=u8(), b=kind===12 || kind===13 ? 0 : u8();+ if (a>127 || b>127) throw new Error('Invalid MIDI data byte.');+ if (kind===12) programs.set(channel,a);+ if (kind===8 || kind===9) events.push({tick,track,channel,pitch:a,velocity:b,on:kind===9 && b>0,program:programs.get(channel)||0});+ }+ if (!ended) throw new Error('MIDI track has no end event.');+ info.endTick=tick; trackInfo.push(info); limit=bytes.length;+ }+ if (p!==bytes.length) throw new Error('Unexpected bytes after MIDI tracks.');+ // At the same tick the last encoded tempo wins, replacing the implicit default.+ const tempos=[...new Map(rawTempos.map(t=>[t.tick,t])).values()].sort((a,b)=>a.tick-b.tick);+ let last=0, seconds=0, tempo=500000;+ for (const item of tempos) {+ if (!item.tempo) throw new Error('Invalid MIDI tempo.');+ seconds+=(item.tick-last)*tempo/division/1e6;+ last=item.tick; tempo=item.tempo; item.seconds=seconds;+ }+ const timing={tempos,division}, time=tick=>tickSeconds(tick,timing);+ events.sort((a,b)=>a.tick-b.tick);+ const active=new Map(), notes=[];+ for (const event of events) {+ const key=event.track+':'+event.channel+':'+event.pitch;+ if (event.on) {+ if (!active.has(key)) active.set(key,[]);+ active.get(key).push(event);+ } else {+ const start=active.get(key)?.shift();+ if (start) notes.push({pitch:event.pitch,velocity:start.velocity,track:event.track,+ channel:event.channel,program:start.program,startTick:start.tick,endTick:event.tick,+ start:time(start.tick),duration:time(event.tick)-time(start.tick)});+ }+ }+ if ([...active.values()].some(list=>list.length)) throw new Error('MIDI contains unterminated notes.');+ if (!allowEmpty && !notes.length) throw new Error('MIDI contains no notes.');+ return {notes:notes.sort((a,b)=>a.startTick-b.startTick || a.pitch-b.pitch),duration:time(maxTick),+ tracks:count,trackInfo,division,endTick:maxTick,tempos,meters,tempoChanges:tempos.length-1};+}++function variable(value) {+ if (!Number.isInteger(value) || value<0 || value>0x0fffffff) throw new Error('MIDI delta is out of range.');+ const bytes=[value&127];+ while ((value=Math.floor(value/128))) bytes.unshift((value&127)|128);+ return bytes;+}+function chunk(name, data) {+ const header=Buffer.alloc(8); header.write(name); header.writeUInt32BE(data.length,4);+ return Buffer.concat([header,Buffer.from(data)]);+}++export function writePracticeMidi({notes,division,endTick,quarterBpm,meter,countInBars=0,speed=1}) {+ if (!Number.isInteger(division) || division<1 || division>32767) throw new Error('Invalid PPQ.');+ if (!Number.isFinite(quarterBpm) || !(quarterBpm>=20 && quarterBpm<=240) || !Number.isFinite(speed) || !(speed>=.25 && speed<=1.5)) throw new Error('Invalid practice tempo.');+ if (!Array.isArray(meter) || meter.length!==2 || !Number.isInteger(meter[0]) || meter[0]<1 || meter[0]>12 || ![2,4,8,16].includes(meter[1])) throw new Error('Invalid practice meter.');+ if (!Number.isInteger(countInBars) || countInBars<0 || countInBars>2 || !Number.isInteger(endTick) || endTick<=0 || endTick>0x0fffffff || !Array.isArray(notes) || notes.length>10000) throw new Error('Invalid practice length or note count.');+ const barTicks=division*meter[0]*4/meter[1], offset=Math.round(countInBars*barTicks);+ const tempo=Math.round(60e6/(quarterBpm*speed));+ const groups=[...new Set(notes.map(note=>note.staff || String(note.track)))];+ if (groups.length>15) throw new Error('Practice MIDI supports at most 15 pitched staves.');+ const channels=[0,1,2,3,4,5,6,7,8,10,11,12,13,14,15];+ const list=[{tick:0,order:0,bytes:[255,81,3,tempo>>16&255,tempo>>8&255,tempo&255]},+ {tick:0,order:0,bytes:[255,88,4,meter[0],Math.log2(meter[1]),24,8]}];+ for (const [i,group] of groups.entries()) {+ const voice=notes.filter(note=>(note.staff || String(note.track))===group), channel=channels[i];+ list.push({tick:0,order:0,bytes:[192|channel,voice[0].program||0]});+ for (const note of voice) {+ if (!Number.isInteger(note.pitch) || note.pitch<0 || note.pitch>127 ||+ !Number.isInteger(note.startTick) || !Number.isInteger(note.endTick) ||+ note.startTick<0 || note.endTick<=note.startTick || note.endTick>endTick ||+ !Number.isInteger(note.velocity) || note.velocity<1 || note.velocity>127 ||+ !Number.isInteger(note.program) || note.program<0 || note.program>127) throw new Error('Invalid practice note.');+ list.push({tick:note.startTick+offset,order:2,bytes:[144|channel,note.pitch,note.velocity||64]},+ {tick:note.endTick+offset,order:1,bytes:[128|channel,note.pitch,0]});+ }+ }+ const pulse=division*4/meter[1]*(meter[1]===8 && meter[0]>=6 && meter[0]%3===0 ? 3 : 1);+ for (let tick=0;tick<offset;tick+=pulse) {+ list.push({tick:Math.round(tick),order:2,bytes:[153,tick%barTicks===0?76:77,85]},+ {tick:Math.round(tick+Math.min(division/8,pulse/3)),order:1,bytes:[137,tick%barTicks===0?76:77,0]});}- tempos.sort((a,b)=>a.tick-b.tick);let last=0,seconds=0,tempo=500000;- for(const t of tempos){seconds+=(t.tick-last)*tempo/division/1e6;last=t.tick;tempo=t.tempo;if(!tempo)throw new Error('Invalid MIDI tempo.');t.seconds=seconds;}- const time=tick=>{let t=tempos[0];for(const item of tempos){if(item.tick>tick)break;t=item;}return t.seconds+(tick-t.tick)*t.tempo/division/1e6;};- events.sort((a,b)=>a.tick-b.tick);const active=new Map(),notes=[];- for(const event of events){const key=event.track+':'+event.ch+':'+event.pitch;if(event.on){if(!active.has(key))active.set(key,[]);active.get(key).push(event);}else{const start=active.get(key)?.shift();if(start)notes.push({pitch:event.pitch,velocity:start.velocity,track:event.track,start:time(start.tick),duration:Math.max(.01,time(event.tick)-time(start.tick))});}}- if([...active.values()].some(a=>a.length))throw new Error('MIDI contains unterminated notes.');- if(!notes.length)throw new Error('MIDI contains no notes.');- return {notes:notes.sort((a,b)=>a.start-b.start),duration:Math.max(time(maxTick),...notes.map(n=>n.start+n.duration)),tracks:count,tempoChanges:tempos.length-1};+ list.push({tick:endTick+offset,order:3,bytes:[255,47,0]});+ list.sort((a,b)=>a.tick-b.tick || a.order-b.order);+ let previous=0; const encoded=[];+ for (const event of list) { encoded.push(...variable(event.tick-previous),...event.bytes); previous=event.tick; }+ const header=Buffer.alloc(6); header.writeUInt16BE(0,0); header.writeUInt16BE(1,2); header.writeUInt16BE(division,4);+ return Buffer.concat([chunk('MThd',header),chunk('MTrk',encoded)]);}diff --git a/store/agents/score/skills/score/scripts/preview.html b/store/agents/score/skills/score/scripts/preview.htmlindex 1f93aa126..a701ad8a0 100644--- a/store/agents/score/skills/score/scripts/preview.html+++ b/store/agents/score/skills/score/scripts/preview.html@@ -1,9 +1,31 @@-<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Folio · Score studio</title><link rel="icon" href="data:,">+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Folio · Score</title><link rel="icon" href="data:,"><style>-*{box-sizing:border-box}body{margin:0;background:#ecebe4;color:#253c38;font-family:Arial,sans-serif}header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #cdd1c7;padding:22px 32px}.brand{font:28px Georgia,serif;letter-spacing:-1px}.brand span{margin-right:12px;color:#af774a}.mono{font:10px monospace;letter-spacing:1.5px;color:#76867c}main{max-width:1460px;margin:auto;padding:28px 32px}.intro{display:flex;justify-content:space-between;align-items:end;gap:20px;margin-bottom:26px}h1{font:normal 36px Georgia,serif;margin:10px 0}p{font-size:12px;line-height:1.7;color:#6b7a71;margin:0}a{color:inherit;font-size:12px;text-decoration:none;border:1px solid #aebbad;padding:11px 14px;border-radius:6px;display:inline-block}.downloads{display:flex;gap:8px}.layout{display:grid;grid-template-columns:minmax(0,1fr) 280px;gap:26px;align-items:start}.paper-wrap{background:#d9ddd3;border:1px solid #cad0c4;border-radius:12px;padding:24px;overflow:auto;max-height:760px}.pages{margin:auto;min-width:0}.pages img{display:block;width:100%;background:white;box-shadow:0 3px 15px #203c3814;margin-bottom:20px}.pages img:last-child{margin-bottom:0}.card{background:#f9f9f3;border:1px solid #d0d6c9;border-radius:10px;padding:21px}.card h2{font:22px Georgia,serif;margin:0 0 9px}.transport{display:flex;gap:8px;margin:21px 0}button{font:12px Arial,sans-serif;padding:12px 18px;border:1px solid #b3c1b1;border-radius:6px;background:#eaf0e4;color:#263f37;cursor:pointer}#play{background:#284c40;color:#fff;flex:1}button:focus-visible,a:focus-visible,input:focus-visible{outline:2px solid #a66f44;outline-offset:3px}label{display:block;font:10px monospace;letter-spacing:.8px;color:#60766a;margin:19px 0 8px}input[type=range]{width:100%;accent-color:#55795b}input[type=number]{width:70px;padding:8px;border:1px solid #b8c5b6;background:#fff;border-radius:5px;color:#284c40}.time{display:flex;justify-content:space-between;font:12px monospace;margin-top:8px}.stats{border-top:1px solid #d5ddce;margin-top:25px;padding-top:15px;display:grid;grid-template-columns:1fr 1fr;gap:18px}.stats b{font:24px Georgia,serif;display:block;margin-top:7px}.note{padding-top:20px;font-size:11px;line-height:1.7;color:#798577}.roll{margin-top:24px;padding:18px 20px;background:#203e35;border-radius:10px;color:#cfdecf}.roll canvas{display:block;width:100%;height:120px;margin-top:12px}.roll .mono{color:#9bb5a0}footer{padding-top:20px;font:10px monospace;display:flex;justify-content:space-between;gap:12px;color:#839080}#error{color:#9e372d;font-size:12px}#status{font:10px monospace;color:#6b826b;text-transform:uppercase;letter-spacing:1px}@media(max-width:850px){.layout{grid-template-columns:1fr 245px}.paper-wrap{padding:12px}main,header{padding:22px}h1{font-size:30px}}@media(max-width:620px){.intro{align-items:start;flex-direction:column}.layout{grid-template-columns:1fr}.paper-wrap{max-height:630px}.card{order:-1}.stats{grid-template-columns:repeat(3,1fr)}.note{padding-top:14px}h1{font-size:28px}.mono{font-size:8px}.transport{margin:14px 0}}-</style>-<header><div class="brand"><span>♮</span>Folio</div><span class="mono">SCORE / ENGRAVE · LISTEN · REFINE</span></header>-<main><div class="intro"><div><div class="mono">FROM AN IDEA TO THE MUSIC STAND</div><h1 id="title"></h1><p>A real engraved score, with an audible sketch of the notes it contains.</p></div><div class="downloads"><a href="score.pdf" download>Score PDF ↓</a><a href="score.midi" download>MIDI ↓</a></div></div>-<div class="layout"><section class="paper-wrap" aria-label="Engraved score"><div class="pages" id="pages"></div></section><aside class="card"><h2>Hear the shape.</h2><p>Listen, slow down, and find the phrase you want to change.</p><div class="transport"><button id="play" aria-pressed="false">Play sketch</button><button id="restart" aria-label="Restart playback">↺</button></div><div id="status" role="status">Ready to play</div><label for="seek">POSITION</label><input id="seek" type="range" min="0" step=".05" value="0"><div class="time"><span id="position">0:00</span><span id="duration"></span></div><label for="speed">PLAYBACK SPEED <span id="speed-value">1.00×</span></label><input id="speed" type="range" min=".5" max="1.5" step=".05" value="1"><label for="volume">VOLUME</label><input id="volume" type="range" min="0" max="1" step=".05" value=".35"><label for="zoom">SCORE ZOOM</label><input id="zoom" type="range" min="80" max="160" value="100"><div class="stats"><div><span class="mono">PAGES</span><b id="page-count"></b></div><div><span class="mono">MIDI NOTES</span><b id="note-count"></b></div></div><p class="note">Playback is a simple synthesized MIDI sketch, not a piano recording. Sustain pedal, sound libraries and expressive phrasing are not reproduced. The engraving and downloads come from LilyPond.</p><p id="error" role="alert"></p></aside></div>-<section class="roll"><span class="mono">PITCH OVER TIME · LIVE PLAYHEAD</span><canvas id="roll" role="img" aria-label="MIDI note timeline with playback position"></canvas></section><footer><span>LOCAL ENGRAVING · NO AUDIO SERVICE</span><span>EDIT SCORE.LY TO COMPOSE</span></footer></main>-<script type="application/json" id="config">__CONFIG__</script><script>/*APP*/</script></html>+[hidden]{display:none!important}+:root{color-scheme:light;--ink:#233e35;--muted:#65766a;--line:#ccd4c5;--paper:#fffef9;--green:#284e3c;--gold:#b47737}+*{box-sizing:border-box}body{margin:0;background:#eceee5;color:var(--ink);font:14px/1.5 system-ui,sans-serif}header{padding:22px 32px;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;gap:16px}.brand{font:30px Georgia,serif;letter-spacing:-1px}.brand span{color:var(--gold);margin-right:10px}.eyebrow{font:10px/1.6 ui-monospace,monospace;letter-spacing:1.6px;color:var(--muted);text-transform:uppercase}main{max-width:1500px;margin:auto;padding:28px 32px 38px}h1{font:normal 40px/1.15 Georgia,serif;margin:10px 0 12px}h2{font:normal 25px Georgia,serif;margin:0 0 8px}h3{font:600 14px system-ui;margin:0 0 12px}p{margin:0;color:var(--muted);font-size:13px;line-height:1.7}.intro{display:flex;justify-content:space-between;align-items:end;gap:30px;margin-bottom:25px}.intro p{max-width:700px}.downloads{display:flex;gap:8px;flex-wrap:wrap;align-items:center}a,button,.file-button{font:12px system-ui;color:var(--ink);padding:10px 13px;border:1px solid #aebfac;border-radius:6px;background:transparent;text-decoration:none;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:6px;white-space:normal}a:hover,button:hover,.file-button:hover{background:#dde6d6}button:disabled{opacity:.55;cursor:wait}button[aria-pressed=true]{background:#315d47;color:white}.primary,#play{background:var(--green);color:#fff;border-color:var(--green)}.primary:hover,#play:hover{background:#376449}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible{outline:3px solid var(--gold);outline-offset:3px}.badge{display:inline-flex;align-items:center;gap:7px;border-radius:30px;background:#dbe6d5;color:#355b40;padding:7px 11px;font:11px ui-monospace;margin-top:15px}.badge::before{content:"";width:6px;height:6px;background:#658655;border-radius:50%}.workspace{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:24px;align-items:start}.score-view{min-width:0}.toolbar{display:flex;justify-content:space-between;align-items:center;gap:15px;padding:13px 16px;background:#f9faf3;border:1px solid var(--line);border-radius:10px 10px 0 0}.toolbar label{font:11px system-ui;display:flex;align-items:center;gap:10px}.toolbar select{max-width:220px}.paper-wrap{background:#d8dfd0;border:1px solid #c5cebe;border-top:0;border-radius:0 0 10px 10px;padding:24px;overflow:auto;max-height:820px}.pages{margin:auto;min-width:0}.pages img{display:block;width:100%;background:#fff;box-shadow:0 4px 15px #183e3514;margin-bottom:22px}.pages img:last-child{margin-bottom:0}.card{padding:23px;background:var(--paper);border:1px solid var(--line);border-radius:12px}.transport{display:flex;gap:9px;margin:20px 0 10px}#play{flex:1;font-size:14px;padding:14px}#status{font:11px ui-monospace;color:#62765e;min-height:17px}label.control{display:block;font:10px ui-monospace;letter-spacing:.8px;color:var(--muted);margin:19px 0 6px}input[type=range]{width:100%;accent-color:#5b8157}input[type=number],select{font:12px system-ui;padding:8px;color:var(--ink);background:#fffef9;border:1px solid #b5c2ac;border-radius:5px}input[type=number]{width:59px}input[type=checkbox]{accent-color:var(--green)}.time{display:flex;justify-content:space-between;font:11px ui-monospace;color:var(--muted);margin:6px 0}.divider{border-top:1px solid var(--line);padding-top:18px;margin-top:20px}.loop-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px}.check-row{display:flex;align-items:center;gap:7px;font-size:12px;margin-top:12px}.player{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:7px;margin-top:13px}.player b{font-size:12px;font-weight:500}.player button{font-size:10px;padding:6px 9px}.player input{grid-column:1/-1;margin:0}.dot{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:7px}.small{font-size:11px;line-height:1.7}.roll{margin-top:20px;padding:18px 20px;background:#203e35;border-radius:10px;color:#d1dfce}.roll .eyebrow{color:#aac19f}.roll canvas{display:block;width:100%;height:110px;margin-top:12px}.roll-head{display:flex;justify-content:space-between;gap:10px}#bar-position{font:11px ui-monospace;color:#e0dfbb}.below{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-top:24px}.practice-links{display:flex;gap:8px;flex-wrap:wrap;margin-top:15px}.checks{margin-top:15px;display:grid;gap:8px}.check{font-size:12px;padding:9px 0;border-bottom:1px solid #e1e6da}.check b{font-weight:600;display:block}.check span{color:var(--muted)}details{margin-top:16px}summary{cursor:pointer;font-size:12px}.assumptions{padding-left:18px;color:var(--muted);font-size:12px}.settings{display:flex;gap:8px;margin-top:15px;flex-wrap:wrap}.settings input{display:none}.full{width:100%;margin-top:14px}#error{color:#993d32;font-size:12px;white-space:pre-wrap;margin-top:10px}footer{display:flex;justify-content:space-between;gap:15px;margin-top:24px;font:10px ui-monospace;letter-spacing:.6px;color:#7d8b76}+@media(max-width:1000px){.workspace{grid-template-columns:minmax(0,1fr) 310px}.intro{align-items:start;flex-direction:column;gap:16px}.paper-wrap{padding:13px}main,header{padding-left:22px;padding-right:22px}}+@media(max-width:700px){main,header{padding-left:16px;padding-right:16px}header .eyebrow{max-width:160px;text-align:right}h1{font-size:32px}.workspace,.below{grid-template-columns:1fr}.controls{grid-row:1}.paper-wrap{max-height:650px}.toolbar{flex-wrap:wrap}.toolbar select{max-width:200px}.card{padding:19px}.below{gap:16px}footer{flex-direction:column}.intro{margin-bottom:20px}.toolbar label{flex-wrap:wrap}}+</style></head><body>+<header><div class="brand"><span>♮</span>Folio</div><div class="eyebrow">An idea. A piece of music.<br>Yours to shape.</div></header>+<main>+<section class="intro"><div><div class="eyebrow">Compose · hear · change · share</div><h1 id="title"></h1><p id="brief"></p><div class="badge" id="badge"></div></div><div class="downloads"><a class="primary" id="project" href="score-project.zip" download>Editable project ↓</a><a href="score.midi" download>Original MIDI ↓</a></div></section>+<div class="workspace">+<section class="score-view"><div class="toolbar"><label for="document">VIEW <select id="document"></select></label><a id="pdf" href="score.pdf" download>Print this score ↓</a><label for="zoom">ZOOM <select id="zoom"><option value="100">100%</option><option value="125">125%</option><option value="150">150%</option></select></label></div><div class="paper-wrap" aria-label="Engraved music"><div id="pages" class="pages"></div></div>+<section class="roll"><div class="roll-head"><span class="eyebrow">Sounding pitches · live playhead</span><span id="bar-position"></span></div><canvas id="roll" role="img" aria-label="Colored note timeline with playback position"></canvas></section>+</section>+<aside class="card controls"><h2>Make it yours.</h2><p>No instruments needed. Hear each voice, find a phrase, then ask the agent to reshape it.</p>+<div class="transport"><button id="play" aria-pressed="false">▶ Listen</button><button id="restart" aria-label="Return to beginning">↺</button></div><div id="status" role="status">Ready to listen</div>+<label class="control" for="seek">POSITION</label><input id="seek" type="range" min="0" step=".01" value="0"><div class="time"><span id="position">0:00</span><span id="duration"></span></div>+<label class="control" for="speed">SPEED <span id="speed-value">1.00×</span></label><input id="speed" type="range" min=".25" max="1.5" step=".05" value="1">+<div id="loop-controls" class="divider"><div class="loop-row"><label><input type="checkbox" id="loop"> Loop bars</label><input id="loop-start" type="number" min="1" value="1" aria-label="First loop bar"><span>to</span><input id="loop-end" type="number" min="1" value="4" aria-label="Last loop bar"></div><label class="check-row"><input id="count-in" type="checkbox"> One-bar count-in</label></div>+<div class="divider"><h3>Hear the arrangement</h3><div id="players"></div><label class="control" for="volume">MASTER VOLUME</label><input id="volume" type="range" min="0" max="1" step=".05" value=".65"></div>+<button id="audio-export" class="full">Save this mix as WAV ↓</button><p class="small" style="margin-top:9px">Synthetic note sketch, not a recording. Exports the selected loop (or whole piece), speed and mix. Up to 3 minutes.</p>+<div class="settings"><button id="save-settings">Save listening setup</button><button id="restore-settings">Restore setup</button><input id="load-settings" type="file" accept=".json,application/json" hidden></div>+<p id="error" role="alert"></p></aside></div>+<div class="below">+<section class="card"><div class="eyebrow">Take it with you</div><h2 style="margin-top:8px">A practice pack, not a preview.</h2><p id="practice-description"></p><div id="practice" class="practice-links"></div><p class="small divider">The project ZIP includes editable music, the saved brief, printed parts, all practice files and standalone rebuild tools. Node and LilyPond are needed to rebuild; listening in this page needs neither.</p></section>+<section class="card"><div class="eyebrow">What we actually checked</div><h2 id="checks-title" style="margin-top:8px"></h2><div id="ranges" class="checks"></div><details><summary>All measured checks & assumptions</summary><ul id="assumptions" class="assumptions"></ul><div id="checks" class="checks"></div><a href="score-assets/checks.json" download style="margin-top:12px">Checks & source hashes ↓</a></details><p class="small divider">These checks cover exported notes, timing and the saved limits. They do not certify musical quality or real-world playability. No live-player testing is implied.</p></section>+</div>+<footer><span>LOCAL ENGRAVING · LOCAL AUDIO · NO SOUND SERVICE</span><span id="revision"></span></footer>+</main><script type="application/json" id="config">__CONFIG__</script><script>/*APP*/</script></body></html>diff --git a/store/agents/score/skills/score/scripts/preview.js b/store/agents/score/skills/score/scripts/preview.jsindex 112d66da6..ddbb1dc8f 100644--- a/store/agents/score/skills/score/scripts/preview.js+++ b/store/agents/score/skills/score/scripts/preview.js@@ -1,24 +1,223 @@-const $=id=>document.getElementById(id),data=JSON.parse($('config').textContent),midi=data.midi;-$('title').textContent=data.title;$('page-count').textContent=data.pages.length;$('note-count').textContent=midi.notes.length;-for(const [i,page]of data.pages.entries()){const img=document.createElement('img');img.src=page;img.alt='Engraved score, page '+(i+1);$('pages').append(img);}-const fmt=s=>Math.floor(s/60)+':'+String(Math.floor(s%60)).padStart(2,'0');-$('duration').textContent=fmt(midi.duration);$('seek').max=midi.duration;-let audio,master,playing=false,position=0,origin=0,originTime=0,speed=1,index=0,voices=new Set();-const now=()=>playing?Math.min(midi.duration,origin+(audio.currentTime-originTime)*speed):position;-function silence(){for(const voice of voices){try{voice.stop();}catch{}}voices.clear();}-function pause(){position=now();playing=false;silence();$('play').textContent='Play sketch';$('play').setAttribute('aria-pressed','false');$('status').textContent='Paused';draw();}-async function play(){- try{if(!audio){audio=new AudioContext();master=audio.createGain();master.gain.value=Number($('volume').value);master.connect(audio.destination);}await audio.resume();if(position>=midi.duration)position=0;origin=position;originTime=audio.currentTime;index=midi.notes.findIndex(n=>n.start>=position-.001);if(index<0)index=midi.notes.length;playing=true;$('play').textContent='Pause';$('play').setAttribute('aria-pressed','true');$('status').textContent='Playing MIDI sketch';$('error').textContent='';}- catch(error){$('error').textContent='Audio unavailable: '+error.message;pause();}-}-function sound(note,when,duration){- const oscillator=audio.createOscillator(),gain=audio.createGain();oscillator.type='triangle';oscillator.frequency.value=440*2**((note.pitch-69)/12);- const peak=Math.min(.1,note.velocity/127*.09),end=when+Math.max(.03,duration);gain.gain.setValueAtTime(0,when);gain.gain.linearRampToValueAtTime(peak,when+.012);gain.gain.exponentialRampToValueAtTime(Math.max(.0001,peak*.35),Math.max(when+.02,end-.03));gain.gain.linearRampToValueAtTime(0,end+.07);oscillator.connect(gain);gain.connect(master);oscillator.start(when);oscillator.stop(end+.08);voices.add(oscillator);oscillator.onended=()=>{voices.delete(oscillator);oscillator.disconnect();gain.disconnect();};-}-function seek(value){const was=playing;if(was)pause();position=Math.max(0,Math.min(midi.duration,Number(value)));if(was)void play();draw();}-$('play').onclick=()=>playing?pause():void play();$('restart').onclick=()=>seek(0);$('seek').oninput=()=>seek($('seek').value);$('speed').oninput=()=>{const was=playing;if(was)pause();speed=Number($('speed').value);$('speed-value').textContent=speed.toFixed(2)+'×';if(was)void play();};$('volume').oninput=()=>{if(master)master.gain.setTargetAtTime(Number($('volume').value),audio.currentTime,.03);};$('zoom').oninput=()=>{$('pages').style.width=$('zoom').value+'%';};+const $=id=>document.getElementById(id), data=JSON.parse($('config').textContent), midi=data.midi, spec=data.ensemble;+const colors=['#8eaf80','#deb375','#82acbe','#ba97bd','#bf907d','#a5aa6a','#93abb8','#c39797'];+const mixes=new Map(data.players.map(player=>[player.id,{muted:false,solo:false,gain:1}]));+const fmt=seconds=>Math.floor(seconds/60)+':'+String(Math.floor(seconds%60)).padStart(2,'0');+const barSeconds=spec?spec.meter[0]*4/spec.meter[1]*60/spec.quarterBpm:null;+const text=(tag,value,className)=>{const node=document.createElement(tag);node.textContent=value;if(className)node.className=className;return node;};+$('title').textContent=data.title; document.title=data.title+' · Folio';+$('brief').textContent=spec?.brief||'A local engraved score and a synthetic sketch of its exported notes.';+$('badge').textContent=data.checked?spec.bars+' bars · '+data.players.length+' players · '+data.checks.length+' checks passed':'Legacy engraving · player brief not checked';+$('duration').textContent=fmt(Math.round(midi.duration)); $('seek').max=midi.duration;+$('revision').textContent='SOURCE '+data.sourceRevision.slice(0,12);+$('project').hidden=!data.checked; $('loop-controls').hidden=!spec;+$('checks-title').textContent=data.checked?'The brief meets the notes.':'Engraving only.';+$('practice-description').textContent=spec?'Download note-only MIDI at '+spec.practice.speed+'× speed, with '+spec.practice.countInBars+' count-in bar(s). “Without” leaves room for the missing player. Browser mix changes do not alter these files.':'Add ensemble.json to prepare checked individual parts and practice exports.';+for (const doc of data.documents) {+ const option=text('option',doc.label); option.value=doc.id; $('document').append(option);+}+function showDocument() {+ const doc=data.documents.find(item=>item.id===$('document').value);+ $('pages').replaceChildren(); $('pdf').href=doc.pdf;+ $('pdf').textContent=doc.id==='score'?'Print full score ↓':'Print this part ↓';+ for (const [i,path] of doc.pages.entries()) {+ const image=document.createElement('img'); image.src=path; image.alt=doc.label+', engraved page '+(i+1); $('pages').append(image);+ }+ $('pages').dataset.document=doc.id;+}+$('document').onchange=showDocument; showDocument();+$('zoom').onchange=()=>{$('pages').style.width=$('zoom').value+'%';};+for (const item of data.practice) {+ const link=text('a',item.label+' ↓'); link.href=item.path; link.download=''; $('practice').append(link);+}+for (const item of data.staves) {+ const player=data.players.find(p=>p.id===item.player), row=document.createElement('div'); row.className='check';+ row.append(text('b',player.label+' · '+item.allowed.join('–')),text('span',item.notes+' notes · '+(item.writtenShift?'written '+(item.writtenShift>0?'+':'')+item.writtenShift+' semitones from concert pitch':'concert-pitch notation')));+ $('ranges').append(row);+}+for (const check of data.checks) {+ const row=document.createElement('div'); row.className='check';+ row.append(text('b',(check.passed?'✓ ':'✕ ')+check.id),text('span',check.detail)); $('checks').append(row);+}+for (const assumption of spec?.assumptions||[]) $('assumptions').append(text('li',assumption));+if(spec){$('loop-start').max=spec.bars;$('loop-end').max=spec.bars;$('loop-end').value=Math.min(4,spec.bars);}+function audible(id) {+ const mix=mixes.get(id); return !mix.muted && (![...mixes.values()].some(item=>item.solo) || mix.solo);+}+function color(id){return colors[data.players.findIndex(player=>player.id===id)%colors.length];}+for (const player of data.players) {+ const row=document.createElement('div'); row.className='player'; row.dataset.player=player.id;+ const label=text('b',player.label), dot=document.createElement('span'); dot.className='dot'; dot.style.background=color(player.id); label.prepend(dot); row.append(label);+ for (const [key,title] of [['muted','Mute'],['solo','Solo']]) {+ const button=text('button',title); button.dataset.control=key; button.setAttribute('aria-label',title+' '+player.label); button.setAttribute('aria-pressed','false');+ button.onclick=()=>{mixes.get(player.id)[key]=!mixes.get(player.id)[key];syncMix();rearm();}; row.append(button);+ }+ const gain=document.createElement('input'); gain.type='range';gain.min=0;gain.max=1;gain.step=.05;gain.value=1;gain.setAttribute('aria-label',player.label+' volume');+ gain.oninput=()=>{mixes.get(player.id).gain=Number(gain.value);rearm();}; row.append(gain); $('players').append(row);+}+function syncMix() {+ for(const row of $('players').children){+ const mix=mixes.get(row.dataset.player);+ for(const button of row.querySelectorAll('button'))button.setAttribute('aria-pressed',String(mix[button.dataset.control]));+ row.querySelector('input').value=mix.gain;+ row.dataset.audible=String(audible(row.dataset.player));+ }+ draw();+}+let audio,master,playing=false,position=0,origin=0,originTime=0,speed=1,index=0,voices=new Set(),held=[];+const rawTime=()=>playing?origin+(audio.currentTime-originTime)*speed:position;+const bounds=()=>spec&&$('loop').checked?[(Number($('loop-start').value)-1)*barSeconds,Number($('loop-end').value)*barSeconds]:[0,midi.duration];+const now=()=>Math.max(originTime&&playing?origin:0,Math.min(bounds()[1],rawTime()));+function silence() { for(const voice of voices){try{voice.stop();}catch{}} voices.clear(); }+function pause() {+ position=now(); playing=false; silence(); $('play').textContent='▶ Listen'; $('play').setAttribute('aria-pressed','false'); $('status').textContent='Paused'; draw();+}+function output(context,volume) {+ const gain=context.createGain(),compressor=context.createDynamicsCompressor();+ gain.gain.value=volume; compressor.threshold.value=-8;compressor.knee.value=8;compressor.ratio.value=12;+ gain.connect(compressor);compressor.connect(context.destination);return gain;+}+function tone(context,destination,note,when,duration,level,live=false) {+ if(duration<=0 || level<=0)return;+ const oscillator=context.createOscillator(),gain=context.createGain(),end=when+duration;+ oscillator.type='triangle'; oscillator.frequency.value=440*2**((note.pitch-69)/12);+ const peak=note.velocity/127*.10*level,attack=Math.min(.012,duration/4),release=Math.min(.03,duration/3);+ gain.gain.setValueAtTime(0,when); gain.gain.linearRampToValueAtTime(peak,when+attack);+ gain.gain.linearRampToValueAtTime(peak*.6,Math.max(when+attack,end-release));gain.gain.linearRampToValueAtTime(0,end);+ oscillator.connect(gain);gain.connect(destination);oscillator.start(when);oscillator.stop(end+.002);+ if(live)voices.add(oscillator);+ oscillator.onended=()=>{voices.delete(oscillator);oscillator.disconnect();gain.disconnect();};+}+function click(context,destination,when,accent,live=false) {+ tone(context,destination,{pitch:accent?91:86,velocity:100},when,.055,.8,live);+}+function countIn(context,destination,start,tempoSpeed,live=false) {+ if(!spec)return;+ const compound=spec.meter[1]===8 && spec.meter[0]>=6 && spec.meter[0]%3===0, pulses=spec.meter[0]/(compound?3:1);+ for(let beat=0;beat<pulses;beat++)click(context,destination,start+beat*barSeconds/pulses/tempoSpeed,beat===0,live);+}+function arm(at,time) {+ silence();origin=position=at;originTime=time;+ index=midi.notes.findIndex(note=>note.start>=at-1e-8);if(index<0)index=midi.notes.length;+ held=midi.notes.filter(note=>note.start<at-1e-8 && note.start+note.duration>at);+ for(const note of held)if(audible(note.player))tone(audio,master,note,time,Math.min(note.start+note.duration-at,bounds()[1]-at)/speed,mixes.get(note.player).gain,true);+}+async function play(withCountIn=true) {+ try {+ if(!audio){audio=new AudioContext();master=output(audio,Number($('volume').value));}+ await audio.resume();+ const [start,end]=bounds(); if(position<start || position>=end)position=start;+ const count=withCountIn&&spec&&$('count-in').checked?barSeconds/speed:0;+ arm(position,audio.currentTime+.025+count);+ if(count)countIn(audio,master,audio.currentTime+.025,speed,true);+ playing=true;$('play').textContent='Ⅱ Pause';$('play').setAttribute('aria-pressed','true');$('error').textContent='';+ schedule();draw();+ }catch(error){$('error').textContent='Audio unavailable: '+error.message;if(playing)pause();}+}+function rearm() {+ if(playing){const at=now();arm(at,audio.currentTime+.015);}draw();+}+function seek(value) {+ const [start,end]=bounds();position=Math.max(start,Math.min(end,Number(value)));+ if(playing)arm(position,audio.currentTime+.015);draw();+}+function loopChanged() {+ const a=Number($('loop-start').value), b=Number($('loop-end').value);+ if(!Number.isInteger(a)||!Number.isInteger(b)||a<1||b<a||b>spec.bars){+ $('error').textContent='Choose complete bars from 1 to '+spec.bars+', with the last bar at or after the first.';+ $('loop').checked=false;rearm();return;+ }+ $('error').textContent=''; const at=now(), [start,end]=bounds();seek(at<start||at>=end?start:at);+}+$('play').onclick=()=>playing?pause():void play();+$('restart').onclick=()=>seek(bounds()[0]);+$('seek').oninput=()=>seek($('seek').value);+$('speed').oninput=()=>{const at=now();speed=Number($('speed').value);$('speed-value').textContent=speed.toFixed(2)+'×';if(playing)arm(at,audio.currentTime+.015);};+$('volume').oninput=()=>{if(master)master.gain.setTargetAtTime(Number($('volume').value),audio.currentTime,.02);};+for(const id of ['loop','loop-start','loop-end'])$(id).onchange=loopChanged;+function schedule() {+ if(!playing)return;+ const [start,end]=bounds(), raw=rawTime();+ if(raw>=end) {+ if(spec&&$('loop').checked){arm(start,audio.currentTime+.01);}+ else{pause();position=midi.duration;$('status').textContent='Finished';draw();return;}+ }+ $('status').textContent=rawTime()<origin?'Count-in…':'Playing synthetic sketch';+ while(index<midi.notes.length && midi.notes[index].start<Math.min(end,rawTime()+.15*speed)){+ const note=midi.notes[index++];if(!audible(note.player))continue;+ const when=Math.max(audio.currentTime,originTime+(note.start-origin)/speed),until=originTime+(Math.min(note.start+note.duration,end)-origin)/speed;+ tone(audio,master,note,when,until-when,mixes.get(note.player).gain,true);+ }+}+setInterval(schedule,25);const canvas=$('roll'),g=canvas.getContext('2d'),low=Math.min(...midi.notes.map(n=>n.pitch))-2,high=Math.max(...midi.notes.map(n=>n.pitch))+2;-function draw(){const w=canvas.clientWidth,h=canvas.clientHeight,ratio=Math.min(devicePixelRatio||1,2);canvas.width=w*ratio;canvas.height=h*ratio;g.scale(ratio,ratio);g.fillStyle='#27493d';for(let i=0;i<9;i++)g.fillRect(i*w/8,0,1,h);const t=now();for(const n of midi.notes){g.fillStyle=n.start<=t&&n.start+n.duration>t?'#f3cc8e':n.track%2?'#97bba1':'#d7d7a2';g.fillRect(n.start/midi.duration*w,(high-n.pitch)/(high-low)*h,Math.max(2,n.duration/midi.duration*w-1),Math.max(2,h/(high-low)-1));}g.fillStyle='#fff6d8';g.fillRect(t/midi.duration*w,0,1.5,h);$('position').textContent=fmt(t);$('seek').value=t;canvas.dataset.position=t.toFixed(3);canvas.dataset.playing=String(playing);}-setInterval(()=>{if(!playing)return;const t=now();while(index<midi.notes.length&&midi.notes[index].start<t+.16*speed){const n=midi.notes[index++];sound(n,Math.max(audio.currentTime,originTime+(n.start-origin)/speed),n.duration/speed);}if(t>=midi.duration){pause();position=midi.duration;$('status').textContent='Finished';}},40);-function frame(){if(playing)draw();requestAnimationFrame(frame);}new ResizeObserver(draw).observe(canvas);draw();requestAnimationFrame(frame);+function draw() {+ const w=canvas.clientWidth,h=canvas.clientHeight,ratio=Math.min(devicePixelRatio||1,2);+ canvas.width=w*ratio;canvas.height=h*ratio;g.scale(ratio,ratio);+ const t=now();+ if(spec&&$('loop').checked){const [a,b]=bounds();g.fillStyle='#345643';g.fillRect(a/midi.duration*w,0,(b-a)/midi.duration*w,h);}+ g.fillStyle='#4a6452';const divisions=spec?.bars||8;+ for(let i=0;i<divisions;i++)g.fillRect(i*w/divisions,0,1,h);+ for(const note of midi.notes){+ g.globalAlpha=audible(note.player)?1:.15;+ g.fillStyle=note.start<=t&¬e.start+note.duration>t?'#f7ddb0':color(note.player);+ g.fillRect(note.start/midi.duration*w,(high-note.pitch)/(high-low)*h,Math.max(2,note.duration/midi.duration*w-1),Math.max(2,h/(high-low)-1));+ }+ g.globalAlpha=1;g.fillStyle='#fff5dc';g.fillRect(t/midi.duration*w,0,1.5,h);+ $('position').textContent=fmt(t);$('seek').value=t;+ $('bar-position').textContent=spec?'BAR '+Math.min(spec.bars,Math.floor(t/barSeconds)+1)+' / '+spec.bars:'';+ canvas.dataset.position=t.toFixed(3);canvas.dataset.playing=String(playing);canvas.dataset.voices=voices.size;canvas.dataset.held=held.length;+}+function download(blob,name){+ const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=name;document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),30000);+}+function settings(){+ return {spec:1,sourceRevision:data.sourceRevision,speed,volume:Number($('volume').value),position:now(),loop:!!spec&&$('loop').checked,firstBar:Number($('loop-start').value),lastBar:Number($('loop-end').value),countIn:!!spec&&$('count-in').checked,document:$('document').value,mix:Object.fromEntries(mixes)};+}+$('save-settings').onclick=()=>download(new Blob([JSON.stringify(settings(),null,2)+'\n'],{type:'application/json'}),'folio-listening.json');+$('restore-settings').onclick=()=>$('load-settings').click();+$('load-settings').onchange=async()=>{+ try{+ const file=$('load-settings').files[0];if(!file)return;if(file.size>32768)throw new Error('Setup file is too large.');+ const saved=JSON.parse(await file.text());+ if(saved.spec!==1||saved.sourceRevision!==data.sourceRevision)throw new Error('This listening setup belongs to a different source revision.');+ if(!Number.isFinite(saved.speed)||saved.speed<.25||saved.speed>1.5||!Number.isFinite(saved.volume)||saved.volume<0||saved.volume>1||!Number.isFinite(saved.position)||saved.position<0||saved.position>midi.duration)throw new Error('Invalid listening values.');+ if(!data.documents.some(doc=>doc.id===saved.document)||typeof saved.loop!=='boolean'||typeof saved.countIn!=='boolean')throw new Error('Invalid score selection.');+ if(spec&&(!Number.isInteger(saved.firstBar)||!Number.isInteger(saved.lastBar)||saved.firstBar<1||saved.lastBar<saved.firstBar||saved.lastBar>spec.bars))throw new Error('Invalid loop range.');+ for(const player of data.players){+ const mix=saved.mix?.[player.id];+ if(!mix||typeof mix.muted!=='boolean'||typeof mix.solo!=='boolean'||!Number.isFinite(mix.gain)||mix.gain<0||mix.gain>1)throw new Error('Invalid player mix.');+ }+ if(playing)pause();speed=saved.speed;position=saved.position;+ $('speed').value=speed;$('speed-value').textContent=speed.toFixed(2)+'×';$('volume').value=saved.volume;+ if(master)master.gain.value=saved.volume;+ $('loop').checked=saved.loop;$('count-in').checked=saved.countIn;+ $('loop-start').value=saved.firstBar;$('loop-end').value=saved.lastBar;$('document').value=saved.document;+ for(const player of data.players)mixes.set(player.id,{...saved.mix[player.id]});+ showDocument();syncMix();seek(position);$('status').textContent='Listening setup restored';$('error').textContent='';+ }catch(error){$('error').textContent=error.message;}finally{$('load-settings').value='';}+};+$('audio-export').onclick=async()=>{+ const button=$('audio-export');button.disabled=true;$('error').textContent='';+ try{+ const [start,end]=bounds(),factor=speed,count=spec&&$('count-in').checked?barSeconds/factor:0,duration=(end-start)/factor+count;+ if(duration>180)throw new Error('WAV exports are limited to 3 minutes. Select a shorter bar loop or a faster speed.');+ if(![...mixes.keys()].some(id=>audible(id)&&mixes.get(id).gain>0)||Number($('volume').value)===0)throw new Error('The mix is silent. Unmute a voice and raise its volume.');+ const context=new OfflineAudioContext(1,Math.ceil((duration+.01)*22050),22050),destination=output(context,Number($('volume').value));+ for(const note of midi.notes){+ if(!audible(note.player)||note.start>=end||note.start+note.duration<=start)continue;+ const from=Math.max(start,note.start),to=Math.min(end,note.start+note.duration);+ tone(context,destination,note,(from-start)/factor+count,(to-from)/factor,mixes.get(note.player).gain);+ }+ if(count)countIn(context,destination,0,factor);+ button.textContent='Rendering audio…';+ const rendered=await context.startRendering(),samples=rendered.getChannelData(0),bytes=new ArrayBuffer(44+samples.length*2),view=new DataView(bytes);+ const ascii=(offset,value)=>{for(let i=0;i<value.length;i++)view.setUint8(offset+i,value.charCodeAt(i));};+ ascii(0,'RIFF');view.setUint32(4,36+samples.length*2,true);ascii(8,'WAVE');ascii(12,'fmt ');view.setUint32(16,16,true);view.setUint16(20,1,true);view.setUint16(22,1,true);view.setUint32(24,22050,true);view.setUint32(28,44100,true);view.setUint16(32,2,true);view.setUint16(34,16,true);ascii(36,'data');view.setUint32(40,samples.length*2,true);+ for(let i=0;i<samples.length;i++)view.setInt16(44+i*2,Math.round(Math.max(-1,Math.min(1,samples[i]))*32767),true);+ download(new Blob([bytes],{type:'audio/wav'}),(data.title.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'folio')+'-sketch.wav');+ $('status').textContent='WAV sketch saved';+ }catch(error){$('error').textContent=error.message;}finally{button.disabled=false;button.textContent='Save this mix as WAV ↓';}+};+function frame(){if(playing)draw();requestAnimationFrame(frame);}+new ResizeObserver(draw).observe(canvas);syncMix();draw();requestAnimationFrame(frame);document.addEventListener('visibilitychange',()=>{if(document.hidden&&playing)pause();});diff --git a/store/agents/score/store.json b/store/agents/score/store.jsonindex 9090db32e..1a4c453c5 100644--- a/store/agents/score/store.json+++ b/store/agents/score/store.json@@ -1,17 +1,22 @@{- "listed": false,+ "listed": true,"homepage": "https://lilypond.org","upstream": "https://github.com/lilypond/lilypond","license": "MIT",- "tagline": "Music notation for everyone",+ "tagline": "Your musical idea, ready to hear and share","screenshots": [- "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/score/starter.jpg"+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/score/ensemble.jpg"],"examples": [{- "prompt": "Engrave Lighthouse at Dusk and give me a printable score plus a MIDI playback sketch.",- "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/score/starter.jpg",- "caption": "Folio · original piano study, PDF and MIDI"+ "prompt": "I don't play an instrument. Make a gentle, hopeful piece with a flute melody, clarinet reply and warm cello. Let me hear each voice and save an audio sketch.",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/score/ensemble.jpg",+ "caption": "Hear, isolate and loop the actual exported notes; save your mix as WAV"+ },+ {+ "prompt": "Write a beginner flute and piano duet. Keep the flute between C5 and E5 with at most three attacks per bar, keep the piano unchanged when revising, and give me separate parts plus a slower practice pack.",+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/score/parts.jpg",+ "caption": "Measured player limits, printable parts and an editable project ZIP"}]}diff --git a/store/agents/score/template/ensemble.json b/store/agents/score/template/ensemble.jsonnew file mode 100644index 000000000..917f8864e--- /dev/null+++ b/store/agents/score/template/ensemble.json@@ -0,0 +1,49 @@+{+ "spec": 1,+ "title": "After the Rain",+ "composer": "OpenHarness",+ "brief": "A gentle, hopeful miniature that I can hear and reshape without owning any instruments. Let a flute melody rise above a warm clarinet reply and an unhurried cello foundation.",+ "assumptions": [+ "Original illustrative music, not an arrangement of an existing song.",+ "Listening comes first: no instruments or music-reading experience are required.",+ "The ranges and difficulty limits below are starting assumptions, not a real player's assessment."+ ],+ "meter": [6, 8],+ "quarterBpm": 90,+ "bars": 16,+ "key": {"tonic": "c", "mode": "major"},+ "sourceFiles": ["score.ly", "ensemble.json"],+ "practice": {"speed": 0.75, "countInBars": 1},+ "players": [+ {+ "id": "flute",+ "label": "Flute",+ "instrument": "Flute in C",+ "midiInstrument": "flute",+ "soundingC": "C4",+ "staves": [+ {"id": "flute-line", "music": "fluteMusic", "clef": "treble", "writtenRange": ["C5", "A5"], "maxPolyphony": 1, "maxLeapSemitones": 7, "maxAttacksPerBar": 6}+ ]+ },+ {+ "id": "clarinet",+ "label": "B-flat clarinet",+ "instrument": "B-flat clarinet",+ "midiInstrument": "clarinet",+ "soundingC": "Bb3",+ "staves": [+ {"id": "clarinet-line", "music": "clarinetMusic", "clef": "treble", "writtenRange": ["C4", "G5"], "maxPolyphony": 1, "maxLeapSemitones": 7, "maxAttacksPerBar": 4}+ ]+ },+ {+ "id": "cello",+ "label": "Cello",+ "instrument": "Cello",+ "midiInstrument": "cello",+ "soundingC": "C4",+ "staves": [+ {"id": "cello-line", "music": "celloMusic", "clef": "bass", "writtenRange": ["C2", "G3"], "maxPolyphony": 1, "maxLeapSemitones": 12, "maxAttacksPerBar": 2}+ ]+ }+ ]+}diff --git a/store/agents/score/template/score.ly b/store/agents/score/template/score.lyindex 0d224c85f..b994607b5 100644--- a/store/agents/score/template/score.ly+++ b/store/agents/score/template/score.ly@@ -1,47 +1,25 @@\version "2.24.3"-\header {- title = "Lighthouse at Dusk"- subtitle = "A small study in motion"- composer = "OpenHarness"- tagline = ##f+% All music is in CONCERT pitch. The builder makes written instrument parts.+% The saved brief, meter, key, tempo and difficulty checks live in ensemble.json.+fluteMusic = \relative c'' {+ c4.\p( e8 d c) | d4.( e4 g8) |+ g4.( e4 d8) | e2. \breathe \break |+ f4.\mp( a8 g f) | e4.( g4 e8) |+ d4( e8 f4 d8) | c2. \breathe \break |+ e4.\mf( g8 a g) | f4.( e4 d8) |+ e4( f8 g4 e8) | d2. \breathe \break |+ c4.\mp( e8 d c) | d4.( f4 e8) |+ d4.\>( e4 d8) | c2.\pp \bar "|."}-\paper {- #(set-paper-size "a4")- top-margin = 16\mm- bottom-margin = 16\mm- left-margin = 18\mm- right-margin = 18\mm- system-system-spacing.basic-distance = #21+clarinetMusic = \relative c' {+ e4.\p g | f4. g | e4. g | g2. \breathe \break |+ a4.\mp f | g4. c | a4. f | e2. \breathe \break |+ g4.\mf c | a4. f | g4. e | f2. \breathe \break |+ e4.\mp g | f4. a | g4.\> f | e2.\pp}-global = { \key e \minor \time 6/8 \tempo "Quietly, with space" 4. = 54 }-right = \relative c'' {- \global- b4.\p( e8 fis g) | fis4.( e4 d8) |- e4( b8) g4( a8) | b2. \breathe \break |- g'4.\mp( fis8 e d) | e4.( b4 a8) |- g4( a8 b4 d8) | fis2. \breathe \break |- e4.\mf( g8 fis e) | d4.( fis8 e d) |- c4( e8) b4( d8) | a2. \breathe \break |- b4.\mp( e8 fis g) | fis4( e8) d4( b8) |- e4.\>( fis4 d8) | e2.\pp\fermata \bar "|."-}-left = \relative c {- \global \clef bass- e8 b' e g e b | d, a' d fis d a |- c, g' c e c g | b, fis' b dis b fis |- e b' e g e b | c, g' c e c g |- a, e' a c a e | b fis' b dis b fis |- e b' e g e b | d, a' d fis d a |- c, g' c e c g | a, e' a c a e |- e b' e g e b | d, a' d fis d a |- b, fis' b dis b fis | <e, b' e>2.\fermata-}-\score {- \new PianoStaff \with { instrumentName = "Piano" }- <<- \new Staff = "right" \with { midiInstrument = "acoustic grand" } \right- \new Staff = "left" \with { midiInstrument = "acoustic grand" } \left- >>- \layout { indent = 10\mm }- \midi { }+celloMusic = \relative c {+ c2.\p | g2. | c2. | c2. \break |+ f,2.\mp | c'2. | g2. | c2. \break |+ c2.\mf | f,2. | c'2. | g2. \break |+ c2.\mp | f,2. | g2.\> | c2.\pp}diff --git a/store/agents/score/test/ACCEPTANCE.md b/store/agents/score/test/ACCEPTANCE.mdnew file mode 100644index 000000000..2761f56db--- /dev/null+++ b/store/agents/score/test/ACCEPTANCE.md@@ -0,0 +1,96 @@+# Score acceptance evidence++Validated 2026-09-20, macOS Intel, Node 22.23.2 and official LilyPond 2.26.0.+No physical instruments or real-player evaluation were used. This is software+validation of a composition/edit/export workflow, not a musical-quality rating.++## Two complete briefs++| Job | Requirements and substantive revision | Evidence |+| --- | --- | --- |+| After the Rain | An original 16-bar 6/8 flute, B-flat clarinet and cello miniature, for a user who owns no instruments | 55 checks; four one-page PDFs; actual clarinet written range F#4–D5, concert range E4–C5; full score equals independent concert proofs |+| A Small Beginning | An independent eight-bar 4/4 beginner flute/piano duet; then lower flute ceiling from G5 to E5 and reduce attacks to three per bar while keeping the piano unchanged | 49 checks; three one-page PDFs; stricter brief rejects the original flute; corrected music passes; piano MIDI hash is unchanged; length remains eight bars |++The initial duet also caught a piano voicing below the requested C4 right-hand+floor. The chord was inverted into range; the requirement was not widened.++Both jobs deliver a full PDF/MIDI, separate player PDF/MIDI, slower full/solo/+minus-one MIDI with count-in, editable sources, saved brief and standalone tools.+An extracted trio ZIP was independently checked with `unzip -t` and rebuilt+using its own scripts. Source revision and exported notes matched the original;+no Harness account, Python or npm package was required for rebuilding.++## Native and unit checks++```sh+LILYPOND_BIN=/path/to/lilypond node --test store/agents/score/test/*.test.mjs+```++**15/15 passed**, including four opt-in native tests. Without `LILYPOND_BIN`,+the native cases are explicitly skipped, not counted as native proof.++Coverage includes:++- MIDI event bounds, running status, timing, incomplete notes and end-of-track.+- Contract validation, scientific pitch, transposition, range, polyphony,+ successive-note leaps, note attacks and measured duration including rests.+- Fifteen pitched MIDI channels without consuming channel 10; simple and+ compound count-in; tempo changes and note-preserving export round trips.+- Source allowlisting, omitted includes, traversal, symlinks and exclusive lock.+- Rejection of literal pickups, folded repeats, cadenzas and wrapper overrides+ that would make complete-bar loop claims ambiguous.+- Native wrong-transposition, wrong-length and chord/polyphony failures.+- Native source mutation during rendering; failed revisions preserve good output.+- Strict revision that leaves unaffected piano bytes unchanged; prior handoff+ remains recoverable in history.+- Real ZIP extraction and standalone native rebuild.+- The earlier self-contained Lighthouse at Dusk source still engraves its+ 142-note piano study, while reporting `ready: false` without a checked brief.++## Real viewer, audio and downloads++```sh+PLAYWRIGHT_MODULE=/path/to/playwright/index.mjs \+ node store/agents/score/test/browser.mjs /path/to/built-workspace /path/to/evidence+```++Passed separately for trio and revised duet in the shared **opaque-origin**+viewer, at 1600×1100 and 390×844. The acceptance helper does not overwrite the+builder's readiness verdict.++- Play/pause advances real AudioContext time; a live analyser measures nonzero+ audio, not just a moving animation.+- Seeking resumes notes already held at the selected time.+- Mute/solo changes the actual mix; selected complete-bar loops repeat.+- Listening setup survives a JSON save/restore; wrong source revisions are rejected.+- WAV export produces nonzero, unclipped 22.05 kHz mono PCM with expected+ loop/speed/count-in duration: approximately 5.343 s for trio and 8.010 s for duet.+- An all-muted WAV export is rejected with a useful message.+- All score/part PDF, practice MIDI and project ZIP downloads match on-disk bytes.+- All document images load; no browser errors or mobile horizontal overflow.++Every page of the trio, revised duet and legacy PDF was rasterized with Poppler+and visually inspected. The printed clarinet key/transposition, labels, slurs,+dynamics and breaks were checked. Browser desktop, part and mobile views were+also inspected. Store images are captures of those real workflows.++## Release checks and retained local evidence++Package conformance, skill validation, generated experience/branding checks,+`git diff --check` and the 433 registry/store/catalog/publisher tests passed.++Local QA root for this run: `/private/tmp/harness-score-workflows.HyXxOL`.+Final guard/native fixtures are in `guard-native/`; earlier fixtures with the+same engraved music are in `release-native/`. Browser receipts, WAVs, downloaded+files and screenshots are in `release-browser-trio/` and+`release-browser-duet/`. These temporary local paths are evidence locations for+this workstation, not files shipped in the Store package.++## Limits that remain++No claim of performer-approved playability, musical quality, breath/fingering+suitability, sampled sound quality or rights clearance. Browser audio and+practice exports are note-only synthetic sketches. The checked workflow is+bounded to constant meter/tempo, complete bars and pitched staves; see the+[contract](../skills/score/references/ensemble.md) for exact limits. Source+allowlisting is not a sandbox for trusted LilyPond Scheme.diff --git a/store/agents/score/test/browser.mjs b/store/agents/score/test/browser.mjsnew file mode 100644index 000000000..f0388cb9a--- /dev/null+++ b/store/agents/score/test/browser.mjs@@ -0,0 +1,122 @@+// Opt-in acceptance through the same opaque-origin viewer used in Harness.+// Does not overwrite the builder's readiness verdict.+import assert from 'node:assert/strict';+import {once} from 'node:events';+import {readFile,writeFile,mkdir} from 'node:fs/promises';+import {resolve,join} from 'node:path';+import {pathToFileURL} from 'node:url';+import {createHash} from 'node:crypto';+import {createHtmlViewer} from '../../../viewers/isolated-web-viewer/viewer.mjs';++const workspace=resolve(process.argv[2]),out=resolve(process.argv[3]);+await mkdir(out,{recursive:true});+const {chromium}=await import(process.env.PLAYWRIGHT_MODULE?pathToFileURL(resolve(process.env.PLAYWRIGHT_MODULE)).href:'playwright');+const server=await createHtmlViewer(workspace);server.listen(0,'127.0.0.1');await once(server,'listening');+const browser=await chromium.launch({headless:true});+const errors=[],report={workspace,passed:false,downloads:[],screenshots:[]};+try {+ const page=await browser.newPage({viewport:{width:1600,height:1100},acceptDownloads:true});+ page.on('pageerror',error=>errors.push(error.message));+ page.on('console',message=>{if(message.type()==='error')errors.push(message.text());});+ page.on('response',response=>{if(response.status()>=400)errors.push(response.status()+' '+response.url());});+ await page.goto('http://127.0.0.1:'+server.address().port+'/?file=score.html');+ const frame=page.frameLocator('#preview');+ await frame.locator('#title').waitFor();+ await frame.locator('#pages img').evaluateAll(images=>Promise.all(images.map(img=>img.decode())));+ assert.match(await page.locator('#preview').getAttribute('sandbox'),/allow-downloads/);+ await frame.locator('#play').click();await page.waitForTimeout(450);+ assert.equal(await frame.locator('#play').getAttribute('aria-pressed'),'true');+ assert.ok(Number(await frame.locator('#roll').getAttribute('data-position'))>.2);+ const signal=await frame.locator('body').evaluate(async()=>{+ const analyser=audio.createAnalyser();master.connect(analyser);+ await new Promise(resolve=>setTimeout(resolve,120));+ const values=new Float32Array(analyser.fftSize);analyser.getFloatTimeDomainData(values);master.disconnect(analyser);+ return {state:audio.state,rms:Math.sqrt(values.reduce((sum,x)=>sum+x*x,0)/values.length)};+ });+ assert.equal(signal.state,'running');assert.ok(signal.rms>1e-6);report.liveAudio=signal;+ await frame.locator('#seek').fill('1.25');await frame.locator('#seek').dispatchEvent('input');+ await page.waitForTimeout(100);+ assert.ok(Number(await frame.locator('#roll').getAttribute('data-held'))>0,'Seeking resumes sustained notes');+ await frame.locator('#play').click();+ const first=frame.locator('.player').first(),id=await first.getAttribute('data-player');+ await first.locator('[data-control=solo]').click();+ assert.equal(await first.getAttribute('data-audible'),'true');+ for(const row of await frame.locator('.player').all())if(await row.getAttribute('data-player')!==id)assert.equal(await row.getAttribute('data-audible'),'false');+ await first.locator('[data-control=solo]').click();+ await first.locator('[data-control=muted]').click();assert.equal(await first.getAttribute('data-audible'),'false');+ await first.locator('[data-control=muted]').click();+ await frame.locator('#speed').fill('0.75');await frame.locator('#speed').dispatchEvent('input');+ assert.equal(await frame.locator('#speed-value').textContent(),'0.75×');+ await frame.locator('#loop-start').fill('2');await frame.locator('#loop-end').fill('2');await frame.locator('#loop-end').dispatchEvent('change');await frame.locator('#loop').check();+ await frame.locator('#count-in').check();+ const downloaded=async(selector,name)=>{+ const event=page.waitForEvent('download');await frame.locator(selector).click();const download=await event;+ assert.equal(await download.failure(),null);await download.saveAs(join(out,name));return readFile(join(out,name));+ };+ const settings=await downloaded('#save-settings','listening.json');+ assert.equal(JSON.parse(settings).speed,.75);+ await frame.locator('#speed').fill('1.25');await frame.locator('#speed').dispatchEvent('input');+ await frame.locator('#load-settings').setInputFiles(join(out,'listening.json'));+ await frame.locator('#status').filter({hasText:'Listening setup restored'}).waitFor();+ assert.equal(await frame.locator('#speed-value').textContent(),'0.75×');+ assert.equal(await frame.locator('#loop').isChecked(),true);+ const bad={...JSON.parse(settings),sourceRevision:'wrong'};await writeFile(join(out,'wrong-setup.json'),JSON.stringify(bad));+ await frame.locator('#load-settings').setInputFiles(join(out,'wrong-setup.json'));+ await frame.locator('#error').filter({hasText:'different source revision'}).waitFor();+ assert.equal(await frame.locator('#speed-value').textContent(),'0.75×');+ const config=await frame.locator('#config').textContent(),data=JSON.parse(config);+ const bar=data.ensemble.meter[0]*4/data.ensemble.meter[1]*60/data.ensemble.quarterBpm;+ await frame.locator('#play').click();+ await page.waitForTimeout(Math.ceil(2*bar/.75*1000+300));+ const loopPosition=Number(await frame.locator('#roll').getAttribute('data-position'));+ assert.equal(await frame.locator('#play').getAttribute('aria-pressed'),'true');+ assert.ok(loopPosition>=bar && loopPosition<=2*bar,'Playback loops within selected bars');+ await frame.locator('#play').click();report.loopPosition=loopPosition;+ const wav=await downloaded('#audio-export','mix.wav');+ assert.equal(wav.subarray(0,4).toString(),'RIFF');assert.equal(wav.subarray(8,12).toString(),'WAVE');+ const wavSeconds=wav.readUInt32LE(40)/2/22050;+ assert.ok(Math.abs(wavSeconds-(2*bar/.75+.01))<1/22050);+ let energy=0,peak=0;for(let p=44;p<wav.length;p+=2){const v=wav.readInt16LE(p);energy+=v*v;peak=Math.max(peak,Math.abs(v));}+ assert.ok(energy>0);assert.ok(peak<32767);report.wav={seconds:wavSeconds,peak,rms:Math.sqrt(energy/((wav.length-44)/2))};+ const hash=bytes=>createHash('sha256').update(bytes).digest('hex');+ const project=await downloaded('#project','project.zip');assert.equal(hash(project),hash(await readFile(join(workspace,'score-project.zip'))));+ report.downloads.push('score-project.zip');+ for(const doc of data.documents){+ await frame.locator('#document').selectOption(doc.id);await frame.locator('#pages img').evaluateAll(images=>Promise.all(images.map(img=>img.decode())));+ assert.equal(await frame.locator('#pages').getAttribute('data-document'),doc.id);+ const bytes=await downloaded('#pdf',doc.id+'.pdf');assert.equal(hash(bytes),hash(await readFile(join(workspace,doc.pdf))));report.downloads.push(doc.pdf);+ }+ for(const item of data.practice){+ const bytes=await downloaded('a[href="'+item.path+'"]',item.path.split('/').at(-1));+ assert.equal(hash(bytes),hash(await readFile(join(workspace,item.path))));report.downloads.push(item.path);+ }+ // WAV must reflect the mix, not silently export muted parts.+ for(const button of await frame.locator('.player [data-control=muted]').all())await button.click();+ await frame.locator('#audio-export').click();await frame.locator('#error').filter({hasText:'mix is silent'}).waitFor();+ for(const button of await frame.locator('.player [data-control=muted]').all())await button.click();+ await frame.locator('#document').selectOption('score');await frame.locator('#loop').uncheck();await frame.locator('#count-in').uncheck();await frame.locator('#restart').click();+ await frame.locator('#pages img').evaluateAll(images=>Promise.all(images.map(img=>img.decode())));+ await frame.locator('body').evaluate(()=>window.scrollTo(0,0));+ await page.screenshot({path:join(out,'desktop.png'),fullPage:true});report.screenshots.push('desktop.png');+ await page.screenshot({path:join(out,'store.jpg'),type:'jpeg',quality:88,fullPage:false});report.screenshots.push('store.jpg');+ await frame.locator('#document').selectOption(data.documents[1].id);+ await frame.locator('#pages img').evaluateAll(images=>Promise.all(images.map(img=>img.decode())));+ await frame.locator('body').evaluate(()=>window.scrollTo(0,0));+ await page.screenshot({path:join(out,'part.png'),fullPage:false});report.screenshots.push('part.png');+ await page.screenshot({path:join(out,'part.jpg'),type:'jpeg',quality:88,fullPage:false});report.screenshots.push('part.jpg');+ await page.setViewportSize({width:390,height:844});+ await frame.locator('#title').waitFor();+ const overflow=await frame.locator('body').evaluate(()=>document.documentElement.scrollWidth>innerWidth+1);+ assert.equal(overflow,false,'No mobile horizontal overflow');+ await frame.locator('#play').click();await page.waitForTimeout(350);assert.equal(await frame.locator('#play').getAttribute('aria-pressed'),'true');await frame.locator('#play').click();+ await frame.locator('body').evaluate(()=>window.scrollTo(0,0));+ await page.screenshot({path:join(out,'mobile.png'),fullPage:true});report.screenshots.push('mobile.png');+ await frame.locator('.score-view').scrollIntoViewIfNeeded();+ await page.screenshot({path:join(out,'mobile-score.png'),fullPage:false});report.screenshots.push('mobile-score.png');+ await frame.locator('.below').evaluate(node=>node.scrollIntoView({block:'start'}));+ await page.screenshot({path:join(out,'mobile-pack.png'),fullPage:false});report.screenshots.push('mobile-pack.png');+ assert.deepEqual(errors,[]);report.passed=true;console.log(JSON.stringify(report,null,2));+} finally {+ await browser.close();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));+ report.errors=errors;await writeFile(join(out,'browser-proof.json'),JSON.stringify(report,null,2)+'\n');+}diff --git a/store/agents/score/test/ensemble.test.mjs b/store/agents/score/test/ensemble.test.mjsnew file mode 100644index 000000000..d9e2d6088--- /dev/null+++ b/store/agents/score/test/ensemble.test.mjs@@ -0,0 +1,111 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {readFile,mkdtemp,writeFile,mkdir,symlink,rm} from 'node:fs/promises';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {validateEnsemble,validateMusicSources,pitch,makeWrapper,checkEnsemble} from '../skills/score/scripts/ensemble.mjs';+import {parseMidi,writePracticeMidi} from '../skills/score/scripts/midi.mjs';+import {snapshotSources,build} from '../skills/score/scripts/build.mjs';+import {zip} from '../skills/score/scripts/archive.mjs';++const template=JSON.parse(await readFile(new URL('../template/ensemble.json',import.meta.url)));+const single=()=>{+ const value=structuredClone(template);value.players=[value.players[1]];value.meter=[4,4];value.bars=1;value.quarterBpm=80;+ return validateEnsemble(value);+};+const note={pitch:60,startTick:0,endTick:384,velocity:80,program:71,staff:'clarinet-line',track:1};+const midi=(notes=[note],endTick=1536)=>parseMidi(writePracticeMidi({notes,division:384,endTick,quarterBpm:80,meter:[4,4]}),{allowEmpty:true});+const checked=(concert,written,part=concert,full=concert)=>checkEnsemble(single(),full,{'clarinet-line':{concert,written}},{clarinet:part});+test('pitch spelling, octave and transposition contract are explicit',()=>{+ assert.equal(pitch('C4'),60);assert.equal(pitch('Bb3'),58);assert.equal(pitch('F#5'),78);+ assert.throws(()=>pitch('B#9'),/outside/);+ const spec=validateEnsemble(template);assert.equal(spec.players[1].writtenShift,2);+ const wrapper=makeWrapper(spec);+ assert.match(wrapper,/\\transposition bes \\transpose bes c'/);+ assert.match(wrapper,/\\bookOutputName "written-clarinet-line"/);+});+test('bad limits, duplicate IDs, source traversal and reserved paths are rejected',()=>{+ for(const mutate of [+ s=>s.players[1].id=s.players[0].id,+ s=>s.players[0].id='score',+ s=>s.players[0].staves[0].music='foo }',+ s=>s.players[0].staves[0].writtenRange=['G5','C4'],+ s=>s.players[0].staves[0].maxPolyphony=0,+ s=>s.players[0].staves[0].maxPolyphony=2,+ s=>s.sourceFiles.push('../private.json'),+ s=>s.sourceFiles.push('Score.ly'),+ s=>s.sourceFiles.push('REBUILD.md'),+ s=>s.sourceFiles.push('rebuild/build.mjs'),+ s=>s.meter=[4,3],+ s=>s.practice.countInBars=3,+ s=>s.players[0].staves[0].maxAtacksPerBar=2,+ s=>s.title='title\n\\include "private"'+ ]){const candidate=structuredClone(template);mutate(candidate);assert.throws(()=>validateEnsemble(candidate));}+});+test('measured range, polyphony, attacks, leap and duration failures do not relax the brief',()=>{+ const concert=midi(),written=midi([{...note,pitch:62}]);+ assert.ok(checked(concert,written).checks.every(check=>check.passed));+ assert.ok(checked(concert,concert).checks.some(check=>check.id.endsWith(':transposition')&&!check.passed));+ const high=midi([{...note,pitch:90}]);assert.ok(checked(high,midi([{...note,pitch:92}])).checks.some(check=>check.id.endsWith(':range')&&!check.passed));+ const chord=midi([note,{...note,pitch:64}]),writtenChord=midi([{...note,pitch:62},{...note,pitch:66}]);+ assert.ok(checked(chord,writtenChord).checks.some(check=>check.id.endsWith(':polyphony')&&!check.passed));+ assert.ok(checked(midi([note],768),written).checks.some(check=>check.id.endsWith(':duration')&&!check.passed));+ const leap=[note,{...note,pitch:72,startTick:768,endTick:1152}];+ assert.ok(checked(midi(leap),midi(leap.map(n=>({...n,pitch:n.pitch+2})))).checks.some(check=>check.id.endsWith(':leaps')&&!check.passed));+ const busy=Array.from({length:5},(_,i)=>({...note,startTick:i*96,endTick:i*96+48}));+ assert.ok(checked(midi(busy),midi(busy.map(n=>({...n,pitch:n.pitch+2})))).checks.some(check=>check.id.endsWith(':attacks')&&!check.passed));+ assert.ok(checked(concert,written,midi([{...note,pitch:61}])).checks.some(check=>check.id==='clarinet:part-sounds'&&!check.passed));+});+test('slow practice preserves notes, changes tempo, shifts for count-in and reserves percussion channel',()=>{+ const notes=Array.from({length:15},(_,i)=>({...note,staff:'staff-'+i,pitch:50+i}));+ const bytes=writePracticeMidi({notes,division:384,endTick:1536,quarterBpm:80,meter:[4,4],countInBars:1,speed:.5}),parsed=parseMidi(bytes);+ assert.equal(parsed.endTick,3072);assert.equal(parsed.tempos[0].tempo,1500000);+ assert.equal(parsed.notes.filter(n=>n.channel===9).length,4);+ const pitched=parsed.notes.filter(n=>n.channel!==9);+ assert.equal(new Set(pitched.map(n=>n.channel)).size,15);assert.equal(pitched.length,15);+ assert.deepEqual(pitched.map(n=>[n.pitch,n.startTick,n.endTick,n.program]),notes.map(n=>[n.pitch,1536,1920,71]));+ const compound=parseMidi(writePracticeMidi({notes:[note],division:384,endTick:1152,quarterBpm:90,meter:[6,8],countInBars:1}));+ assert.equal(compound.notes.filter(n=>n.channel===9).length,2);+ assert.throws(()=>writePracticeMidi({notes:[{...note,velocity:200}],division:384,endTick:1536,quarterBpm:80,meter:[4,4]}),/note/);+ assert.throws(()=>writePracticeMidi({notes,division:384,endTick:1536,quarterBpm:80,meter:[4,3]}),/meter/);+ const silence=parseMidi(writePracticeMidi({notes:[],division:384,endTick:1536,quarterBpm:80,meter:[4,4]}),{allowEmpty:true});+ assert.equal(silence.notes.length,0);assert.equal(silence.duration,3);+});+test('checked source rejects ambiguous bar grids and wrapper overrides, without treating comments or strings as commands',()=>{+ const validate=code=>validateMusicSources([{name:'score.ly',bytes:Buffer.from(code)}]);+ for(const command of ['\\partial 4','\\repeat volta 2 { c1 }','\\cadenzaOn','\\time 3/4','\\tempo 4 = 99','\\clef "treble_8"','\\transposition c','\\score { c1 }'])assert.throws(()=>validate('music = { '+command+' }'),/owned|complete-bar/);+ assert.doesNotThrow(()=>validate('% \\partial 4\nmusic = { \\repeat unfold 2 { c1 } ^"A caption about \\\\time" }\n%{ \\repeat volta 2 %}'));+});+test('MIDI rejects events that escape a track, missing end events and trailing bytes',()=>{+ const bytes=writePracticeMidi({notes:[note],division:384,endTick:1536,quarterBpm:80,meter:[4,4]});+ const shortened=Buffer.from(bytes);shortened.writeUInt32BE(2,18);+ assert.throws(()=>parseMidi(shortened),/Truncated/);+ assert.throws(()=>parseMidi(Buffer.concat([bytes,Buffer.from([0])])),/Unexpected/);+ const aligned=writePracticeMidi({notes:[{...note,endTick:1536}],division:384,endTick:1536,quarterBpm:80,meter:[4,4]});+ const noEnd=aligned.subarray(0,-4);noEnd.writeUInt32BE(noEnd.length-22,18);+ assert.throws(()=>parseMidi(noEnd),/end event/);+});+test('source allowlist rejects omitted includes and symlinks; build lock remains owned',async()=>{+ const root=await mkdtemp(join(tmpdir(),'score-source-'));+ try {+ await writeFile(join(root,'score.ly'),'\\include "private.ily"\n');+ await assert.rejects(snapshotSources(root,{sourceFiles:['score.ly']}),/sourceFiles/);+ await writeFile(join(root,'voice.ILY'),'\\include "private.ily"\n');+ await assert.rejects(snapshotSources(root,{sourceFiles:['voice.ILY']}),/sourceFiles/);+ await writeFile(join(root,'private.ily'),'music = { c1 }');+ assert.equal((await snapshotSources(root,{sourceFiles:['score.ly','private.ily']})).length,2);+ await symlink(join(root,'private.ily'),join(root,'linked.ily'));+ await assert.rejects(snapshotSources(root,{sourceFiles:['linked.ily']}),/symlink/);+ await mkdir(join(root,'.harness','score-build.lock'),{recursive:true});+ await writeFile(join(root,'.harness','verdict.json'),'owned');+ await assert.rejects(build(root),/Another build/);+ assert.equal(await readFile(join(root,'.harness','verdict.json'),'utf8'),'owned');+ } finally {await rm(root,{recursive:true,force:true});}+});+test('ZIP builder rejects traversal and case collisions and writes real ZIP headers',()=>{+ const bytes=zip([{name:'score.ly',bytes:Buffer.from('music')},{name:'parts/flute.pdf',bytes:Buffer.from('%PDF-')}]);+ assert.equal(bytes.readUInt32LE(0),0x04034b50);assert.equal(bytes.readUInt32LE(bytes.length-22),0x06054b50);+ assert.equal(bytes.readUInt16LE(bytes.length-12),2);+ assert.throws(()=>zip([{name:'../secret',bytes:Buffer.from('bad')}]),/Unsafe/);+ assert.throws(()=>zip([{name:'A',bytes:Buffer.alloc(0)},{name:'a',bytes:Buffer.alloc(0)}]),/duplicate/);+});diff --git a/store/agents/score/test/fixtures/duet/ensemble.json b/store/agents/score/test/fixtures/duet/ensemble.jsonnew file mode 100644index 000000000..946a74844--- /dev/null+++ b/store/agents/score/test/fixtures/duet/ensemble.json@@ -0,0 +1,30 @@+{+ "spec": 1,+ "title": "A Small Beginning",+ "composer": "OpenHarness",+ "brief": "An original eight-bar beginner flute melody with a quiet piano accompaniment, playable as a computer sketch with no real instruments. Leave breathing space and give each player a printable part.",+ "assumptions": ["Flute written C5-G5, no more than four attacks per bar, steps or thirds; piano is intermediate, not assessed by a player."],+ "meter": [4, 4],+ "quarterBpm": 80,+ "bars": 8,+ "key": {"tonic": "c", "mode": "major"},+ "sourceFiles": ["score.ly", "ensemble.json"],+ "practice": {"speed": 0.7, "countInBars": 1},+ "players": [+ {+ "id": "flute", "label": "Flute", "instrument": "Beginner flute in C",+ "midiInstrument": "flute", "soundingC": "C4",+ "staves": [+ {"id": "flute-line", "music": "fluteMusic", "clef": "treble", "writtenRange": ["C5", "G5"], "maxPolyphony": 1, "maxLeapSemitones": 4, "maxAttacksPerBar": 4}+ ]+ },+ {+ "id": "piano", "label": "Piano", "instrument": "Piano, two hands",+ "midiInstrument": "acoustic grand", "soundingC": "C4",+ "staves": [+ {"id": "piano-right", "music": "pianoRight", "clef": "treble", "writtenRange": ["C4", "C6"], "maxPolyphony": 3, "maxAttacksPerBar": 4},+ {"id": "piano-left", "music": "pianoLeft", "clef": "bass", "writtenRange": ["C2", "C4"], "maxPolyphony": 2, "maxAttacksPerBar": 2}+ ]+ }+ ]+}diff --git a/store/agents/score/test/fixtures/duet/score.ly b/store/agents/score/test/fixtures/duet/score.lynew file mode 100644index 000000000..33dab6108--- /dev/null+++ b/store/agents/score/test/fixtures/duet/score.ly@@ -0,0 +1,18 @@+\version "2.24.3"+% Concert-pitch variables only. ensemble.json owns the player brief and timing.+fluteMusic = \relative c'' {+ c2\p( d4 e) | e2( d4) r4 |+ d2( e4 f) | f2( e4) r4 \breathe \break |+ e4\mp( f g2) | f2( e4 d) |+ d2( e4 d) | c1\pp \bar "|."+}+pianoRight = \relative c' {+ <c e g>2\p <c e g> | <c e a>2 <c e a> |+ <d f a>2 <d f a> | <c f a>2 <c e g> |+ <c e g>2\mp <d g b> | <c f a>2 <c e a> |+ <d g b>2 <d g b> | <c e g>1\pp+}+pianoLeft = \relative c {+ c1\p | a1 | d1 | f2 c |+ c1\mp | f1 | g,1 | c1\pp+}diff --git a/store/agents/score/test/fixtures/legacy/score.ly b/store/agents/score/test/fixtures/legacy/score.lynew file mode 100644index 000000000..0d224c85f--- /dev/null+++ b/store/agents/score/test/fixtures/legacy/score.ly@@ -0,0 +1,47 @@+\version "2.24.3"+\header {+ title = "Lighthouse at Dusk"+ subtitle = "A small study in motion"+ composer = "OpenHarness"+ tagline = ##f+}+\paper {+ #(set-paper-size "a4")+ top-margin = 16\mm+ bottom-margin = 16\mm+ left-margin = 18\mm+ right-margin = 18\mm+ system-system-spacing.basic-distance = #21+}+global = { \key e \minor \time 6/8 \tempo "Quietly, with space" 4. = 54 }+right = \relative c'' {+ \global+ b4.\p( e8 fis g) | fis4.( e4 d8) |+ e4( b8) g4( a8) | b2. \breathe \break |+ g'4.\mp( fis8 e d) | e4.( b4 a8) |+ g4( a8 b4 d8) | fis2. \breathe \break |+ e4.\mf( g8 fis e) | d4.( fis8 e d) |+ c4( e8) b4( d8) | a2. \breathe \break |+ b4.\mp( e8 fis g) | fis4( e8) d4( b8) |+ e4.\>( fis4 d8) | e2.\pp\fermata \bar "|."+}+left = \relative c {+ \global \clef bass+ e8 b' e g e b | d, a' d fis d a |+ c, g' c e c g | b, fis' b dis b fis |+ e b' e g e b | c, g' c e c g |+ a, e' a c a e | b fis' b dis b fis |+ e b' e g e b | d, a' d fis d a |+ c, g' c e c g | a, e' a c a e |+ e b' e g e b | d, a' d fis d a |+ b, fis' b dis b fis | <e, b' e>2.\fermata+}+\score {+ \new PianoStaff \with { instrumentName = "Piano" }+ <<+ \new Staff = "right" \with { midiInstrument = "acoustic grand" } \right+ \new Staff = "left" \with { midiInstrument = "acoustic grand" } \left+ >>+ \layout { indent = 10\mm }+ \midi { }+}diff --git a/store/agents/score/test/native.test.mjs b/store/agents/score/test/native.test.mjsnew file mode 100644index 000000000..c12d2b80f--- /dev/null+++ b/store/agents/score/test/native.test.mjs@@ -0,0 +1,102 @@+import {test} from 'node:test';+import assert from 'node:assert/strict';+import {cp,readFile,writeFile,mkdir,mkdtemp,rm} from 'node:fs/promises';+import {spawnSync} from 'node:child_process';+import {join} from 'node:path';+import {tmpdir} from 'node:os';+import {fileURLToPath} from 'node:url';+import {createHash} from 'node:crypto';+import {build} from '../skills/score/scripts/build.mjs';+import {parseMidi} from '../skills/score/scripts/midi.mjs';+const bin=process.env.LILYPOND_BIN, root=fileURLToPath(new URL('..',import.meta.url));+const retained=process.env.SCORE_QA_ROOT;+async function workspace(t,name,source) {+ if(retained)await mkdir(retained,{recursive:true});+ const ws=await mkdtemp(join(retained||tmpdir(),'score-'+name+'-'));+ await cp(source,ws,{recursive:true});+ if(!retained)t.after(()=>rm(ws,{recursive:true,force:true}));+ else t.diagnostic('Retained native fixture: '+ws);+ return ws;+}+const readJson=async path=>JSON.parse(await readFile(path,'utf8'));+const digest=async path=>createHash('sha256').update(await readFile(path)).digest('hex');+test('native trio: printed parts, written Bb range, full/solo/minus-one exports and portable rebuild',{skip:!bin},async t=>{+ const ws=await workspace(t,'trio',join(root,'template'));+ const result=await build(ws,{bin});+ assert.equal(result.checked,true);assert.equal(result.checks.length,55);+ assert.ok(result.checks.every(check=>check.passed));assert.equal(result.documents.length,4);+ assert.equal(result.staves.find(staff=>staff.id==='clarinet-line').writtenShift,2);+ assert.deepEqual(result.staves.find(staff=>staff.id==='clarinet-line').range,[66,74]);+ assert.equal(result.durationSeconds,31.999968);+ const config=JSON.parse((await readFile(join(ws,'score.html'),'utf8')).match(/id="config">([^<]+)<\/script>/)[1]);+ const full=parseMidi(await readFile(join(ws,'score.midi')));+ for(const player of result.ensemble.players){+ const part=parseMidi(await readFile(join(ws,'score-assets','part-'+player.id+'.midi')));+ assert.equal(part.notes.length,config.midi.notes.filter(n=>n.player===player.id).length);+ for(const [prefix,selected] of [['solo-',config.midi.notes.filter(n=>n.player===player.id)],['minus-',config.midi.notes.filter(n=>n.player!==player.id)]]){+ const exported=parseMidi(await readFile(join(ws,'score-assets',prefix+player.id+'.midi')),{allowEmpty:true});+ assert.deepEqual(exported.notes.filter(n=>n.channel!==9).map(n=>n.pitch).sort((a,b)=>a-b),selected.map(n=>n.pitch).sort((a,b)=>a-b));+ assert.equal(exported.notes.filter(n=>n.channel===9).length,2);+ }+ }+ const extracted=join(ws,'.harness','extracted');await mkdir(extracted);+ const unzip=spawnSync('unzip',['-q',join(ws,'score-project.zip'),'-d',extracted],{encoding:'utf8'});+ assert.equal(unzip.status,0,unzip.stderr);+ assert.equal(await digest(join(ws,'score.ly')),await digest(join(extracted,'score.ly')));+ const run=spawnSync(process.execPath,[join(extracted,'rebuild','build.mjs'),extracted],{env:{...process.env,LILYPOND_BIN:bin},encoding:'utf8',timeout:120000});+ assert.equal(run.status,0,run.stdout+run.stderr);+ assert.equal((await readJson(join(extracted,'.harness','score.json'))).sourceRevision,result.sourceRevision);+ assert.deepEqual(parseMidi(await readFile(join(extracted,'score.midi'))).notes,full.notes);+ const zipCheck=spawnSync('unzip',['-t',join(ws,'score-project.zip')],{encoding:'utf8'});+ assert.equal(zipCheck.status,0,zipCheck.stdout+zipCheck.stderr);+});+test('native duet: easier flute revision, failed candidate, preserved piano, rebuild and history',{skip:!bin},async t=>{+ const ws=await workspace(t,'duet',join(root,'test','fixtures','duet'));+ const original=await build(ws,{bin}), originalMidi=parseMidi(await readFile(join(ws,'score.midi')));+ assert.equal(original.checks.length,49);assert.equal(original.documents.length,3);+ const piano=await digest(join(ws,'score-assets','part-piano.midi')),zip=await digest(join(ws,'score-project.zip'));+ const contract=await readJson(join(ws,'ensemble.json'));+ contract.brief='Keep the piano and eight-bar shape; lower the flute ceiling to E5 and use at most three attacks per bar.';+ const flute=contract.players[0].staves[0];flute.writtenRange=['C5','E5'];flute.maxAttacksPerBar=3;+ await writeFile(join(ws,'ensemble.json'),JSON.stringify(contract,null,2)+'\n');+ await assert.rejects(build(ws,{bin}),/flute-line:range/);+ assert.equal((await readJson(join(ws,'.harness','verdict.json'))).ready,false);+ assert.equal(await digest(join(ws,'score-project.zip')),zip);+ assert.equal(await digest(join(ws,'score-assets','part-piano.midi')),piano);+ const source=await readFile(join(ws,'score.ly'),'utf8');+ const revised=source.replace(/fluteMusic = [\s\S]*?\n}/,'fluteMusic = \\relative c\'\' {\n c2\\p( d4 e) | e2( d4) r4 |\n d2( e4 d) | e2( d4) r4 \\breathe \\break |\n c2\\mp( d4 e) | e2( d4 c) |\n d2( e4 d) | c1\\pp \\bar "|."\n}');+ assert.notEqual(revised,source);await writeFile(join(ws,'score.ly'),revised);+ const result=await build(ws,{bin});assert.ok(result.checks.every(check=>check.passed));+ assert.notEqual(result.sourceRevision,original.sourceRevision);+ assert.equal(await digest(join(ws,'score-assets','part-piano.midi')),piano);+ assert.equal(parseMidi(await readFile(join(ws,'score.midi'))).endTick,originalMidi.endTick);+ assert.equal(await digest(join(result.previousArtifacts,'score-project.zip')),zip);+ assert.equal((await readJson(join(ws,'ensemble.json'))).players[0].staves[0].writtenRange[1],'E5');+});+test('native rejects overridden transposition, wrong length, polyphony and source mutation without replacing good output',{skip:!bin},async t=>{+ const ws=await workspace(t,'negative',join(root,'template'));+ await build(ws,{bin});+ const source=await readFile(join(ws,'score.ly'),'utf8'),good=await digest(join(ws,'score.pdf'));+ for(const [name,candidate,pattern] of [+ ['transposition',source.replace("clarinetMusic = \\relative c' {","clarinetMusic = \\relative c' { \\set Staff.instrumentTransposition = #(ly:make-pitch 0 0)"),/part-sounds|score:notes/],+ ['length',source.replace('c2.\\pp \\bar "|."','c2.\\pp c2. \\bar "|."'),/duration/],+ ['polyphony',source.replace('c4.\\p( e8 d c)','<c e>4.\\p( e8 d c)'),/polyphony/]+ ]){+ await writeFile(join(ws,'score.ly'),candidate);await assert.rejects(build(ws,{bin}),pattern,name);+ assert.equal(await digest(join(ws,'score.pdf')),good);+ assert.equal((await readJson(join(ws,'.harness','verdict.json'))).ready,false);+ }+ const mutation='\n#(call-with-output-file '+JSON.stringify(join(ws,'score.ly'))+' (lambda (port) (display "% changed during native build" port)))\n';+ await writeFile(join(ws,'score.ly'),source+mutation);+ await assert.rejects(build(ws,{bin}),/Source changed/);+ assert.equal(await digest(join(ws,'score.pdf')),good);+});+test('native legacy score remains audible and printable without claiming the ensemble brief was checked',{skip:!bin},async t=>{+ const ws=await workspace(t,'legacy',join(root,'test','fixtures','legacy'));+ const result=await build(ws,{bin});+ assert.equal(result.checked,false);assert.equal(result.title,'Lighthouse at Dusk');+ assert.equal(result.notes,142);assert.equal(result.documents.length,1);+ const verdict=await readJson(join(ws,'.harness','verdict.json'));+ assert.equal(verdict.ready,false);assert.equal(verdict.artifact,'score.html');+ assert.equal((await readFile(join(ws,'score.pdf'))).subarray(0,5).toString(),'%PDF-');+});diff --git a/store/agents/score/toolchain/setup.sh b/store/agents/score/toolchain/setup.shindex c3ee1029a..407abceec 100755--- a/store/agents/score/toolchain/setup.sh+++ b/store/agents/score/toolchain/setup.sh@@ -2,4 +2,9 @@set -euHERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)bash "$HERE/node.sh" --version-if [ -n "${LILYPOND_BIN:-}" ]; then "$LILYPOND_BIN" --version; else lilypond --version; fi+SCORE_LILYPOND=${LILYPOND_BIN:-lilypond}+if ! command -v "$SCORE_LILYPOND" >/dev/null 2>&1; then+ printf '%s\n' 'Score needs LilyPond for engraving. Install it from https://lilypond.org/download.html, or set LILYPOND_BIN to its executable. No musical instruments are needed.' >&2+ exit 1+fi+"$SCORE_LILYPOND" --versiondiff --git a/store/showcase/score/ensemble.jpg b/store/showcase/score/ensemble.jpgnew file mode 100644index 000000000..ec1dae477Binary files /dev/null and b/store/showcase/score/ensemble.jpg differdiff --git a/store/showcase/score/parts.jpg b/store/showcase/score/parts.jpgnew file mode 100644index 000000000..f4b98d98bBinary files /dev/null and b/store/showcase/score/parts.jpg differdiff --git a/store/tools/REAL-WORKFLOWS.md b/store/tools/REAL-WORKFLOWS.mdindex 778eb85ed..23345d3a6 100644--- a/store/tools/REAL-WORKFLOWS.md+++ b/store/tools/REAL-WORKFLOWS.md@@ -18,7 +18,7 @@ catalog workflow and verify the live catalog after each accepted release.| Order | Package | Intended complete workflow | Status || --- | --- | --- | --- || 1 | freecad | Measurements and fit requirements → checked assembly, individual parts, editable native/source project and handoff | Implemented and validated; relisted in this change. See [acceptance evidence](../agents/freecad/test/ACCEPTANCE.md). |-| 2 | score | Musical brief and player constraints → revised score, individual parts and practice exports | Not started; unlisted |+| 2 | score | Musical brief and player constraints → revised score, audible mix, individual parts and practice exports | Implemented and validated; relisted in this change. See [acceptance evidence](../agents/score/test/ACCEPTANCE.md). || 3 | openscad | Dimensions and fabrication constraints → parametric parts, verified variants and usable exports | Not started; unlisted || 4 | orca-slicer | User mesh and explicit machine/material profiles → compared slicing options and reviewed toolpath handoff | Not started; unlisted || 5 | data-studio | User data and a question → saved analysis, source-linked results and repeatable report | Not started; unlisted |