# PLANNING.md — MEI Score Editor
Each phase ends in something usable day-to-day; nothing in a later phase is required for an earlier phase to be useful. Phase estimates assume solo development with heavy Claude Code assistance and reuse of midi-stroke's Verovio/Pixi/Tone experience. Exit criteria are the gate for moving on — resist starting the next phase before they hold.
> **Phases 0–8 are complete and released: 0.0.1 (2026-08-08), 0.0.2
> (2026-08-30, the score tempo, on-screen keyboard, import/export,
> session restore and the distribution pipeline) and 0.0.3 (2026-09-12,
> the quality-of-life round — lyrics, staff groups, the mouse-free
> context bar, playback to MIDI devices).** Plans, exit criteria,
> triage and progress notes live in [CHANGELOG.md](CHANGELOG.md).
> **Phase 9 below shipped as 1.0.0, Phase 10 — tablets — as 1.2.0,
> Phase 11 — the stylus — as 1.3.0. Phase 12 — hardening — is the open
> one.** Still carried into Phase 9 from earlier
> rounds: live (rather than save-time) file watching, which ships in
> the folder-view slice; splice-at-caret and overlay-as-new-layer paste
> policies; split view; MusicXML *export* (no Verovio support — needs
> another engine); and the possible Rust/WASM core rewrite, which the
> API package sits above.
## Phase 12 — Hardening (decided 2026-11-20)
No feature. A review of 1.3.0 (2026-11-20) found the editor's own
promises broken in places the gates did not look: redo that loses an edit,
a revert that is not byte-identical, saves that can lose work, a property
suite that never ran in CI, and files from other tools read slightly
wrong. This phase closes them, in the order below — each slice lands with
the test that would have caught it, and the test is written first and
seen to fail. The tablets follow the desktop here as everywhere: they are
a companion for small fixes, not the main audience (the user, 2026-11-20).
**Rules of the phase.** *API may grow*: nothing — no slice adds to
`@battuta/api`, and no version moves until the phase is released. A
failing test is never loosened to pass: what it finds beyond its slice is
written down as a finding. Slices 2 and 5 change how the core and the
shell work inside; their design is the user's, proposed before it is
built.
### Slice 1 — The corpus in the repository, the properties in CI
The four sample-encodings scores the tests read (Bach chorale, Beethoven
quartet, Hymn to Joy, Brandenburg 2 — public-domain encodings, 5 MB) are
committed, and the corpus tests stop skipping without them: on a clean
checkout the round-trip sweep ran on one hand-made file and the three
property tests not at all. The property suite is made to mean what it
says: the generator reaches every case, the snapshot is the whole score
and not its measures, the commands it never built are added, redo is a
property of its own (execute, undo, redo: the same document, ids
included), and it counts what each kind actually applied.
**Gates.** The core suite on a clean checkout skips nothing. Every command
kind in the pool is applied at least once per run, or the test says which
was not.
**Documents.** `fixtures/README.md`; the CHANGELOG.
**Done when.** `test.yml` runs the corpus and the properties, and they
fail for the reasons slices 2 and 3 fix — and no other.
### Slice 2 — Redo is the same edit
`apply()` mints new ids each time it runs, so a redo rebuilds the element
under another id and the commands after it miss their target: a note
entered and then sharpened, undone twice and redone twice, comes back
without its sharp. Each command that creates elements keeps the IDS it
minted on its first apply and gives them, in the same order, to what it
builds on the next (`MintedIds`, internal to core — the elements are
rebuilt, the ids are kept; built this way and shown to the user on
2026-11-20, whose answer was "looks good to me") — redo is then the edit
it was, ids included; and a command
identifies everything it creates itself, so nothing is left for the
session to name differently the second time. A command that throws while
being redone stays on the redo stack instead of leaving both.
**Gates.** The redo property of slice 1; a session-level test through
`session.execute` (enter or paste, edit the new content, undo twice, redo
twice — the same document); the browser check of the sharp.
**Done when.** Both hold for every command kind in the pool.
### Slice 3 — Revert restores the order of attributes
Five commands delete an attribute on apply and add it back at the end on
revert — `ToggleRepeat`, `ToggleEndRepeat`, `ToggleVolta` (its barlines),
`ToggleArtic`, `SetTempo(null)` — so the undone document differs from the
original in attribute order. They restore the attributes as they were.
**Gates.** One example test per command, the toggled attribute first in
source order; the unwind property of slice 1.
### Slice 4 — Saving does not lose work
- A restored tab knows the file's time on disk when it was last read or
written, so the external-change guard holds across a restart.
- A save writes beside the file and renames over it.
- The session is restored document by document: one that no longer parses
is reported and the others come back.
- A session the storage refuses is said, not swallowed.
- A file is open once: the open dialog and a launch argument focus the
tab that already has it.
- A save marks the tab clean for the state it wrote, not for the state at
the moment the write returns.
**Decided (the user, 2026-11-20).** A restored tab whose file changed
while battuta was closed is settled AT RESTORE, not at its first save;
the stored session stays `v1` with the file's time added to each
document — not a breaking change.
A tab with unsaved changes asks; a tab with nothing unsaved takes the
file's content WITHOUT a question, there being nothing to lose (built on
a reading of "at restore", confirmed by the user the same day).
**Gates.** The browser tests of the review, kept: each case above, the
shell's file commands replaced by an in-memory stand-in; Rust tests for
the write.
### Slice 5 — What the editor renders, and what the shell accepts
The rendered score goes through an allow-list before it reaches the page,
the shell gets a content security policy, the file commands accept only
what the user opened, saved or picked — the set kept in Rust — and the
bench and test hooks leave release builds.
**Direction (the user, 2026-11-20).** As VS Code does it: nobody working
in a cloned folder of hundreds of scores is blocked or interrupted. A
grant is the act of picking — a dialog, a launch argument, a folder picked
once and remembered — and everything inside a picked folder is then read
and saved without a question. The design, proposed and accepted the same
day: the shell keeps, in its own data folder, the folders picked and the
files opened or saved through a dialog or a launch argument; a path on
neither list falls back to the save-as dialog; the rendered SVG is
filtered once, where the render pool receives it; the policy is drafted
and tried in the desktop shell.
**As built (2026-11-20).** The record is the DESKTOP's: the tablets'
commands are as they were, the system's sandbox and pickers being the
scope there. The policy was the desktop's too until the tablet pass at
the end of the phase tried it in both tablets' WebViews; it is every
platform's since. The record starts empty, so
the first launch after this version asks once for the folder view's
folder and for each restored tab's file at its first save.
**Gates.** A test that renders a score carrying foreign markup and finds
none of it live in the output; Rust tests that the file commands refuse a
path never granted.
### Slice 6 — The loader keeps what it reads
Whitespace between inline elements (`in C`), element prefixes
(``), and control characters that would make the saved file
unreadable. The round-trip sweep compares the saved file with its SOURCE,
not with a second parse of itself.
**As built (2026-11-20; built without a proposal at the user's word — "a
now mandatory change" — and described here after).** What every open and
save now does differently:
- *Whitespace.* A text node that is only whitespace is TEXT when it is
under `xml:space="preserve"`; when its parent or any element above it
has text of its own (mixed content — a line break there separates words
too); or when it holds no line break (two inline elements on one line).
Whitespace with a line break between elements is indentation, dropped as
before. In the music's own structure (measure, staff, layer, beam,
chord, note … — the list is `STRUCTURE` in `xml.ts`) whitespace is never
text, whatever the file says — `xml:space="preserve"` included, which
passes through such an element to what is below it: the commands address
children by position.
Only XML's four whitespace characters count: a no-break space is text.
- *Prefixes.* A file that writes MEI with a prefix is read with plain tag
names as any other, and saved with MEI as the DEFAULT namespace: its
spelling changes on the first save, its meaning does not. An element of
another namespace keeps its prefix; one of none says `xmlns=""`.
- *Characters.* What XML 1.0 cannot carry (control characters, half a
surrogate pair, U+FFFE/U+FFFF) is not written. A carriage return is
written as `
`, and in an attribute a line feed and a tab as
references too.
- A comment or a processing instruction no longer counts as an element
needing an id.
**Gates.** `source-fidelity.test.ts`: the five corpus scores, saved,
against their SOURCE, read by a parser that is not the core's — it found a
loss in three of them before the change (words run together in the
header) — and a case per rule; `session-fidelity.test.ts` through the
session.
**Not in it.** A DOCTYPE and `standalone` are still dropped, a comment
after the root still moves before it, and inside editorial containers in
the music (`app`, `rdg`, `supplied`) a single space on one line is now
kept as text.
### Slice 7 — The gates CI does not have, and the documents
`cargo test` for the shell; one browser e2e in `test.yml`; the README's
layout, packaging and signing sections brought to what the repository
does; DESIGN.md's record of this phase.
**Decided (the user, 2026-11-20).** `verify-save.mjs` and
`verify-render.mjs` go into CI; `verify-overlays.mjs` is fixed, or removed
if it cannot be — the overlays need a verification of some kind; the
generated `gen/schemas/acl-manifests.json` stops being tracked; the README
is restructured: not a development log but a welcome for everyone who
wants to launch battuta.
**As built.** `test.yml` runs the three browser checks (the overlays one
too: its two failing checks were stale, not a fault of the editor) and a
`shell` job with `cargo test --lib`. The README is the welcome; what it
held for builders is `BUILDING.md`. The Windows installer is said to be
unsigned, as it is.
DESIGN.md's record was written after the tablet pass (*What the editor
does not take on trust*).
### Slice 8 — Two findings of the phase (the user, 2026-11-20: here)
Found by the review's reruns and by slice 1's suite, outside the slices
above. `ChangeContext`, given a clef on a staff that does not exist with a
key or meter in the same change, writes the key, throws, and leaves
nothing to undo: the plan refuses it, and a command that throws leaves the
document as it found it. A tile is not drawn again after a staff-group
change — the tile's XML differs (`bar.thru`) and its cache key does not.
**Gates.** An example test each; the properties refuse a kind that throws
after changing the document.
**Held for the phase after.** Durations of `fTrem`, `graceGrp`, `app`,
`choice` and `multiRest`; `metcon="false"` in paste; key and meter
changes written inline in a layer; a context change at measure 1 behind a
leading `scoreDef`. They are about files from other tools, which is where
that phase begins.
## Phase 11 — The stylus (decided 2026-10-29 and 2026-11-01)
battuta's first native plugin: the Apple Pencil and the S Pen, captured by
the iOS and Android shells and handed to the core read against the score,
and the plugin `battuta.stylus` on top of `@battuta/api`. Three parts, as
the user set them out on 2026-10-29: notes with the pen — the cross at its
tip, shipped in the unreleased 1.3.0 with API 1.3.0–1.3.4 (the CHANGELOG
has every decision); ABC music by hand with ML Kit and PencilKit, dropped
on 2026-11-01 after feedback; and symbols written by hand and read by
**granita**, battuta's own glyph classifier (vibetuned/granita) — the open
part, planned on 2026-11-01.
**granita.** granitanet v7: 51 classes (fingerings, ornaments,
articulations, accidentals, dynamics, pedal, notes by duration, rests,
clefs, the barline), 2.0 M parameters, a 16-feature context — where the
mark sits: the staff zone, the place in the measure, the nearest
notehead's offset and side, the size, all in staff spaces — exported to
Core ML (fp16, iOS 16+) and LiteRT. Its test shells (`granita/apps/ios`,
`apps/android`) proved both exports on both tablets and calibrated the size
rule by hand: 3.0 staff spaces fill the model's canvas.
**Decisions (the user, 2026-11-01).**
- **The mode**: a status-bar item the plugin contributes, cross ↔
handwriting; no pen gesture.
- **Writing**: one message, `core.mark { eventId, mark }`, a closed union
the host maps to the session's marks; the caret goes to the event, as it
does for `core.enterNote`.
- **The model**: its files copied into `battuta-mobile` and tracked (iOS
resources, Android assets, the sidecar), a script copying a named granita
release, the CHANGELOG saying which.
- **Unsure** — the best guess under the threshold, or no class passing its
placement rule: a chooser of the top three at the symbol, tapped with the
pen.
- **The context comes from the API**, not from overlay props the plugin
caches.
- **Heuristics the model cannot learn**, the user's brief: the augmentation
dot is right of a note and a staccato above or below one; accidentals are
left of a note; fingerings and dynamics are never inside the staff
(fingerings above, dynamics and pedal below); clefs and rests only inside
it, a clef at the measure's start.
**M1 — the API (1.3.5, approved on 2026-11-01 as the ceiling).**
`StylusScorePoint` gains `staff { space, middleY }`, `measure { left,
right }` and `nearestNote { eventId, x, y } | null`, in page px, the
notehead within 8 spaces; `ctx.stylus.at(x, y)` resolves any page point;
`ctx.stylus.recognize({ strokes, staffSpace, context })` answers
`[{ label, confidence }]`, the host forwarding to the shell, which builds
granita's vector from the raw facts (no TypeScript port of `context.py`);
`core.mark`. A patch bump per approved change while unpublished. Done when
the host tests cover each, `api-report.d.ts` agrees, and a plugin can read
a drawn symbol's whole context from one `at` call.
**M2 — the model in the shell.** `StrokeRaster` and `GranitaModel` lifted
from granita's shells into `battuta-mobile` (Swift, Kotlin); a `classify`
command — strokes in page px, the staff space, the context facts — answering
the top five; Core ML and LiteRT 2.3.2 on the CPU; the model files and the
sidecar in the crate. Done when granita's `fixtures.json` passes through the
shell on both tablets with the shells' numbers.
**M3 — the plugin's handwriting mode.** The status-bar item; a symbol is
the strokes that follow each other within ~600 ms and two staff spaces; on
the timeout, `at` for the context, `recognize`, the heuristics over the top
five by confidence, the first passing class written through `core.mark` (a
drawn note: `core.enterNote` with the class's duration at the head's
pitch); a fading label at the symbol; the chooser when unsure; the cross
untouched. The pure functions — grouping, the rule table, class → mark —
unit-tested; the plugin's README and BUILDING.
**M4 — docs and release.** The guide's stylus page, the CHANGELOG, then
1.3.0 for the stores and the desktop.
**Exit criteria.** On both tablets, every class that has a mark in the
editor, written by hand at natural size on a staff beside a note, lands as
the right mark or offers it in the top three; the cross unchanged; one undo
step per symbol; nothing on the desktop or in a browser
(`ctx.stylus.available` is false there).
**Decided on 2026-11-02, after the class review.** The ornaments by name
(API 1.3.7: `Mark`'s `ornament` kind; the turn added to the core and the
`w` cycle); the quarter rest as **the eraser** (`nearestMark`,
`core.erase`), no other rest by hand; the classes granita drops: the
barline, the pedal, the double flat, `m` and `z` alone, every rest but the
quarter — the user retrains; **coda classes** are coming to the model, a
repeat-mark kind for `core.mark` to approve when they do. **Done the same
day**: granita v8's battuta variant (43 classes; the double sharp and the
32nd/64th notes out too, the repeat marks in) copied into the shell; its
context measures the note's body — API 1.3.8: `nearestNote.box`,
`StylusSymbolContext.noteW/noteH`, `Mark`'s `repeatMark` kind. **Slurs
and ties** (the user, the same day): a third mode, a bow from note to
note, a tie for the same note and a slur otherwise — API 1.3.9: `Mark`'s
`tie` and `slur` kinds, `nearestNote.pitch`.
**The replies and the training (the user, 2026-11-02; API 1.3.10).**
granita's shells proved it first: a reply saved in musicset's contribution
format, and the model's last layer retrained on the tablet from the
replies (a tiny replay buffer, the anchors' answers held, an L2 anchor).
In battuta: a reply is **explicit only** — ✓ tapped, a chooser's pick, ✗
then a pick; never the silent ✓, never a bow; the replies in **the app's
private data, with a share action**; the training as **plugin commands**
(train, reset, share). API 1.3.10: `ctx.stylus.reply`, `train`,
`resetTraining`, `shareReplies`, `StylusReply`, `StylusTraining` — and
nothing else. **battuta's iOS floor rises to 18** (from 15): the
multi-function Core ML package — its `personal` function takes the layer
as inputs — needs it. **Then (the user, on trying it; API 1.3.11):** the ✎
item in the header **with the other plugins' buttons**; the replies'
numbers and a train button **in the plugins page, as the plugin's
settings** — the `pluginSettings` slot, an item under the plugin's own
row; `ctx.stylus.replies()`, `deleteReplies()` (a delete button, asking
first) — and nothing else.
**The end of the score (the user, 2026-11-05; API 1.3.12).** The editor
appends a measure when a note from the keyboard or MIDI lands on the last
event of the score, so the writing flows; and a plugin, **Add measure**,
draws a gray measure with a + after the last one — a button for the pen,
which writes where it touches. API 1.3.12: the overlays point's `end`
tile and `core.appendMeasure` — and nothing else; the host presses a
`data-pen-tap` button under a pen tap on nothing of the score.
**Out of v1, to decide later.** The pedal (two signs); the double flat
(the editor has none); the 32nd and 64th notes by hand (the cross writes
notes exactly); handwriting on the desktop.
## Phase 10 — Tablets: iPadOS and Android (decided 2026-10-20)
battuta on tablets, from this codebase: the same frontend in the system
WebView (WKWebView, Android WebView), the same Rust shell built as a
library, published by Vibetuned — a nonprofit for music and arts
education — as `com.vibetuned.battuta`, and **open source like the
desktop** (AGPL-3.0). Tablets first: an iPad and an Android tablet are the
reference devices (iPad Air 11" M4; Galaxy Tab S8 Ultra); phones later.
**Licensing.** Verovio (LGPLv3) runs unmodified as WebAssembly inside the
WebView and is never linked into the app binary — the case Verovio's own
[licensing page](https://book.verovio.org/introduction/licensing.html)
allows. What that asks of us: **credit Verovio** in both store listings and
in an in-app licence notice (with the other bundled licences — pdf.js
Apache-2.0, Noto Music OFL, the MPL-2.0 crates Tauri pulls in, the
MIT/BSD ones). Contributions from outside come under a **CLA** — the
Apache ICLA with Vibetuned in the Foundation's place ([CLA.md](CLA.md),
signed on the first pull request as [CONTRIBUTING.md](CONTRIBUTING.md)
says).
**M0 — it runs.** The shell is a library (`lib.rs`; `main.rs` launches it
on desktop); native dialogs, MIDI and folder watching are desktop-only;
the page is told which shell it runs in before it loads; a desktop
window's title and size stay desktop-only. Generated Android and Xcode
projects (`src-tauri/gen/`), one identifier for every platform
(`com.vibetuned.battuta`), the iOS signing team and floor in
`tauri.ios.conf.json`, and `npm run android -- …` / `npm run ios -- …`. Done when both tablets open
the editor, render, edit and play, checked by a device smoke.
**M1 — files.** Working drafts in the app's storage
(`BaseDirectory.AppLocalData` or `BaseDirectory.Document`, through
`@tauri-apps/plugin-fs`); the OS document picker and share sheet to import
and export `.mei`. Built (2026-10-20) on `Document` — the one the user can
see (the Files app on iPadOS): it is battuta's folder, the folder view
shows it with nothing to choose, a first save goes into it; the document
picker opens, the save sheet sends copies and exports out. Then, at the
user's request, any folder on both tablets and a share sheet proper,
through battuta's own native plugin (`src-tauri/plugins/battuta-mobile`,
Swift and Kotlin): iPadOS folders by security-scoped bookmark, Android
document trees under path-shaped addresses the shell resolves; the api's
`workspace.home()` (1.2.0) tells the folder view which folder is battuta's.
**M2 — touch and the tablet layout.**
- The virtual keyboard made perfectly usable on a tablet. Begun
2026-10-20 with the user's first two: a backspace (⌫) pinned under
the ×, and two lines in portrait (the playing line over the groups).
- Taps are far less precise than a cursor: instead of binding
pointerdown to the tiny ``, hit-test with
`document.elementsFromPoint(x, y)` or the nearest notehead box within a
24 px touch radius. Moved out (2026-10-21, the user): it comes later,
as a plugin.
- Narrow viewports (`window.innerWidth < 768`): Verovio's options switch
to `adjustPageHeight: true`, smaller `pageMarginLeft`/`pageMarginRight`,
and a `pageWidth` computed from `window.innerWidth`, so one or two
measures fill the width cleanly. Done 2026-10-20 (in M4, for the
iPhone) in the page view — the only view Verovio lays out in pages; the
edit view's tiles take no page width, and their size is the zoom.
**M3 — MIDI.** Android's WebView already offers Web MIDI (found in M0: the
tablet's USB port and a networked device listed); iPadOS's WebKit has
none, so the shell brings CoreMIDI there (`midir` supports iOS). Begun
2026-10-20: the shell's MIDI bridge builds for iOS too, with the "battuta"
virtual source (the background-audio mode iPadOS asks for, the user's
choice); Android's input is proven end to end; Bluetooth MIDI is paired
from the MIDI list on both (after midi-stroke's working version). Verified
the same day: Android's input and output end to end against the Mac, and
Bluetooth pairing on both tablets by the user.
**M4 — the stores.** Icons and launch screens, the licence notice and the
Verovio credit in the listings, release signing, Apple's privacy manifest.
Open for then: iPad-only or universal (the App Store allows adding iPhone
later, never removing it), and the PDF reference on iPadOS before 17.4
(pdf.js uses `Promise.withResolvers`; the app's floor is iPadOS 15, the
oldest Xcode 27 builds for). Begun 2026-10-20, the user settling the
first: **universal** — "let's also build Iphone" — with the store listings
and the stores' questions. Built that day: the iPhone (run in the
simulator) with what a phone needs — side safe-area insets, the side
panel over the score under 600 px, the page view's narrow page; the
listings and every form's answers (`apps/editor/store/`) and the privacy
page for the phone and tablet apps; the licence notice (battuta menu →
*about battuta*, generated by `npm run licences`); the export-compliance
key and the privacy manifest; Android release signing from
`keystore.properties`. Then (2026-10-21): the screenshots, Google Play's
feature graphic and icon, made from the app (`npm run store:screenshots`);
the PDF reference before iOS 26.2 — the user's choice, a message rather
than a fix (pdf.js 6.4 needs Safari 26.2, not 17.4 as first read: see the
plugin's BUILDING). The phones' edit view — each tile row's top margin —
is the user's to decide from the screenshots; Android's missing 🌣 glyph
stays. The stores' records and the first uploads are the user's, from
Xcode and Android Studio once main is pushed and tagged.
## Phase 9 — Extension architecture (v0.1.0, ≈4–6 weeks in slices)
**Decision (2026-09-12): features that would weigh the editor down
become plugins; the editor becomes a host.** The 0.0.3 request stream
has two kinds of item: quality-of-life fixes that belong in the core,
and features (reference layers, OMR, more playback, more formats) that
each add weight every user carries whether or not they use it. The
0.0.3 round also showed where the weight really lands: `App.tsx` is
3,300 lines with a 33-branch key dispatcher and 81 hooks, and every
feature since 0.0.1 has grown it. Bundle weight is mostly under control
already (the piano loads on play, the Humdrum converter spawns lazily);
the host is what needs protecting.
The model is VSCode's, cut down to what a solo project can carry:
- **Contribution points** declared in a manifest — battuta already has
declarative ones (the keymap, the format table, the status-bar
selects, the export menu); this phase makes them the *only* way
features attach.
- **Activation events** — a plugin's code is not loaded, let alone run,
until something it declared happens (`onCommand:`, `onLane:`,
`onFormat:`, `onDocument:hasFacsimile`, `onView:page`, `onPlay`).
This is the lightweight lever: a disabled or never-triggered plugin
costs one JSON manifest entry.
- **A narrow, versioned API** (`@battuta/api`) instead of App internals.
Everything a plugin can see or do goes through it; plugins never
touch the DOM, the SVG, the React tree, or `CoreScore` mutably.
*Not* adopted: a separate extension-host process, and a marketplace.
Both cost real engineering for first-party plugins and buy nothing yet.
The API is kept message-passing-friendly (serializable commands, id
and model coordinates, no callbacks that close over app state) so a
worker host and third-party loading remain a deferral, not a rewrite —
the same stance DESIGN.md takes on Rust.
### Extension points, mapped to existing seams
| Point | What a plugin contributes | Exists today as |
|---|---|---|
| `commands` | `Command` factories (apply/revert, dirty regions) reached by id | `packages/core/src/commands.ts` `Command` interface, executed via `DocumentSession.stack` |
| `keybindings` | `KeyBinding` entries with default keys per layout | `keymap.ts` `defaultKeymap()` — becomes core map ∪ plugin contributions; **ShortcutEditor and VirtualKeyboard already generate from the keymap**, so plugin actions appear in both for free |
| `lanes` | a typed text lane at the caret: grammar, suggestions, commit → command, advance rule | harmony + lyrics lanes in `App.tsx` (the "harm-lane mechanism"), generalised |
| `formats` | exports (`contributes.exports` + `registerExport`, since 7a) and imports (`contributes.imports` — extensions, text-or-bytes, root elements for a shared `.xml` — + `registerImport`, since 8a): the menu row and the open dialog's accept list exist before the plugin loads, `onFormat:` wakes it, detection is the host's | `host/formats.ts` (the registry); the App's Verovio converters as internal registrations until 8b moves them, with `formats.ts`' table and its pinning test |
| `overlays` | a per-tile draw hook on the interaction overlay, given the tile's bbox, id → bbox map, effective context and timemap | the caret/selection overlay; **this is the point Phases 6 and 7 need** (ghost piano roll, facsimile strips, confidence tint) |
| `header` / `docHeader` / `statusBar` / `menu` | items in the four UI slots, added at runtime or **declared in the manifest** (the host renders a declared item before the plugin's code loads; the click activates it — decided 2026-09-14 for the 🎹) | the six status-bar selects, the battuta menu, the player row (`docHeader` is where slice 7's controls go) |
| `panels` | a side/bottom panel (React node behind a slot). The side area is on the LEFT, below the header, and pushes the score right while a panel is up (decided 2026-09-16 with the first side consumer) | the on-screen keyboard (bottom, 4b), the folder view (side, 9b); later reference-track solo/mute, flagged-element lists |
| `playback` | nothing to contribute: a player is a plugin that SCHEDULES — it reads the timemap and the notation facts, decides the performance (ties, gates, clones, speed — there can be several players), and plays it with its own instrument on the host's audio context, or on the host's MIDI out (below) | `player.ts`, `midiExport.ts`; the performance logic in `core/playback.ts` (which leaves core for the player: decided 2026-09-15) |
| `documentHooks` | `onOpen` / `beforeSave` / `onExternalChange` | session restore, external-change guard in `session.ts` |
| `workspace` | `openFolder()` (native dialog), `readDir`, `openDocument(path)` — routed through the same open path as ctrl+o so imports convert and the session records it — and `watch(path)` | `open_score`/`file_mtime`/`initial_score` in `main.rs`; live watching is the still-open item from 0.0.2 (a `notify` watcher). Access is **scoped to the folder the user picked** (Tauri 2 capability scopes); the browser build reports "not available" since WebKit has no File System Access API |
| `shell` | Rust-side capability behind a JS facade | Tauri commands in `main.rs` — native-needing plugins ship as **Tauri 2 plugins** with a JS guest binding; the JS side is the contract, so the browser build gets a graceful "not available" |
### Host services, not plugins
The cut between host and plugin is: **a platform capability with a
browser backend and a shell backend, consumed by features, is a host
service; a feature is a plugin.** Host services are always present in
every build (possibly reporting "nothing available") and reachable
through `@battuta/api`:
- **MIDI devices** — inputs and outputs, hot-plug, dedupe by port
name, the virtual "battuta" source, `panic()`; backends are Web MIDI
in browsers and the midir bridge in the shell (exactly today's code,
moved behind one interface). Consumers: the entry path (core), the
playback sink (plugin), the status-bar indicator (host). Plugins may
**register virtual inputs** — the on-screen piano is one, named
"on-screen piano" — so any future input surface (chord pad, step
sequencer, Bluetooth bridge) feeds the same entry path and no plugin
ever asks whether "the MIDI plugin" is installed.
- **Audio context** — the one Web Audio context of the app behind
`ctx.audio`: `unlock()` (created and resumed inside a user gesture —
the autoplay policy binds it to the click), `context()` (the shared
`AudioContext`, to connect a synth or sampler to) and `timeAt(ms)`
(wall clock → audio clock, so attacks scheduled from timers land
sample-accurately). The host owns the CONTEXT, not an instrument: a
plugin brings its own synth or sampler (the playback plugin brings
Tone.js and the Salamander subset, lazily, in its own chunk). Web Audio
in browsers and the shell's WebKit alike. Consumers: the playback
plugin; later a metronome, a note preview on entry, a reference-track
player — each on the same context, none fighting for the autoplay
unlock. Decided 2026-09-15: the context is a platform capability, so it
is a service; the instrument and HOW a score is performed are not, so
they are the plugin's.
- **Workspace / files** — dialogs, read/write, mtime, watch (scoped).
- **Clipboard, settings, storage, notices/confirm, session.**
- **Rendering** — tiles, page view, timemaps (read-only to plugins).
Corollary: **no plugin-to-plugin runtime dependencies in v1.** A
manifest declares the host *capabilities* it needs (`midi`,
`workspace`, `playback`, …) and the host guarantees they exist. Shared
code between plugins is either a build-time library package or a
candidate for a new host service — never a runtime lookup of another
plugin (VSCode's `extensionDependencies` is the cautionary example).
Cost accepted: a few hundred lines of device code live in the host
permanently; they carry no assets, so the weight budget is unaffected.
### The host API (`@battuta/api`)
One package, semver'd separately from the app, `engines.battuta`
declared by every plugin, **standalone — it imports nothing from core
or the editor** (decided 2026-09-14 after the first slice-2 attempt
imported core; see the CHANGELOG) — refined 2026-09-15: core owns the
document's data types (caret, block, pitch, syllable, harmony kind) and
`document.ts` re-exports exactly those, type-only; nothing else of core
reaches the api or a plugin, each type is declared once, the surface
report prints the shapes it re-exports, and the api's build is a project
reference to core. Read side: a document snapshot
(`id`, `version`, counts, title, tempo), caret and selections with a
subscribe, and a **query facade** answered by the host as data
(`pitchEventsIn(block)`, `blockOf(ids)`; tile geometry and timemaps
join it when the overlay slice needs them). Write side:
`execute(message)` — **commands as data**: a serializable message the
host maps to the real core command, the only mutation path, so undo
integrity and the byte-identical-revert property hold for plugin edits
exactly as for core ones (and a plugin cannot mutate in any way the
host has not published) — plus `notice()`, `confirm()`, a settings
namespace, a storage namespace (persisted with the session), and an
`activate(ctx)` / `deactivate()` lifecycle with disposables. No render-pool access in v1 (plugins draw on the overlay
or contribute MEI; they never engrave — DESIGN.md's rule extends to
them).
**Plugins own no document state.** Anything a plugin wants to persist
about a score goes in MEI (``, `@facs`, an ``) or a
declared sidecar file; anything else in its storage namespace. This is
what makes "disable all plugins" a safe operation and lets the property
fuzzer cover plugin commands unchanged.
### Migration: strangler fig, one slice at a time
Features leave `App.tsx` for `packages/plugins/*` in the order below.
The slices run **strictly one at a time**: a slice opens only when the
previous one has closed, and a slice closes only when its *Done when*
holds, the documents it owes (next section) exist, and CHANGELOG.md
carries its bullet with the `App.tsx` line count before → after
(baseline, 2026-09-12: **3,330 lines**). Each slice is written to be a
complete brief on its own: a fresh session — a person or an agent —
takes the slice text plus the previous plugin's `BUILDING.md` and
starts. Every extraction is behaviour-neutral, gated by the suites
that already cover the feature: the unit suites (`packages/core/test`,
`apps/editor/test`), the browser e2e scripts (`spikes/verify-app.mjs`,
`verify-phase2.mjs` … `verify-phase5.mjs`) and the shell smoke
(`spikes/verify-tauri.sh`), all passing unchanged. Where no committed
e2e drives a feature yet, the slice adds one *before* extracting, so
the extraction has something to be neutral against.
Two of the original eight slices are split so that every slice proves
exactly one thing: the MIDI service leaves the host skeleton (nothing
needs it before the on-screen keyboard, and a host-service extraction
should be judged on its own), and the two lanes become two slices
(lyrics defines the point, harmony confirms it and deletes the old
path). The keyboard slice split again after its first attempt (below):
a host slice, *core actions by id*, precedes the plugin — and from
slice 5 on that is the pattern: the host half of a plugin slice (the
point, the message, the query) is an in-house *a* slice that lands
first, the plugin is the *b* slice with *API may grow: none*. Every
slice carries the same six blocks plus two added on 2026-09-14:
- **API may grow.** The exact api exports the slice may add — and, for
a host slice, the host modules. Anything not listed is not the
slice's to add: the api's surface and the host's module list are the
user's (`apps/editor/test/host-boundaries.test.ts` fails a new host
module; `api-report.mjs` refuses a surface change without an approved
version bump). *None* means none.
- **Stop when.** The condition under which the slice is left OPEN with
the gap written into BUILDING.md §7 and the CHANGELOG, and reported.
An open slice with a precise gap is a success; a closed slice with a
widened contract is a failure. Stopping must be the cheapest
compliant action.
**Who does which slice.** Host slices — the skeleton (1), the MIDI
service (3), core actions by id (4a), the `lanes` point (5a), the
playback services (7a), and the host halves built before 6–10 — are done
in-house, with the user.
Plugin slices (2, 4b, 5b, 6–10) are handed to context-free sessions on
purpose, to test the briefs; a plugin slice never adds a host module or
a host service.
**Progress.** Slice 1 closed 2026-09-12, **slice 2 closed 2026-09-14**,
**slice 3 closed 2026-09-14** (their bullets in CHANGELOG.md under
0.1.0 — unreleased). **Slice 4 was attempted by a context-free agent on
2026-09-14 and rolled back**: every gate green, and a host service, an
event-forging `press()`, fourteen api exports and a new binding the
brief never named — plus the conventions file edited to admit them.
`packages/plugins/onscreen-keyboard/POSTMORTEM-2026-09-14.md` is the
account and the review; the measures it asked for are in place (the
*API may grow* / *Stop when* blocks above, the host boundary test, the
keymap snapshot, `--unpublished` withdrawn). Its e2e script survived,
restored to the in-App panel: `verify-onscreen-keyboard.mjs`, 24 checks.
**Slice 4a closed 2026-09-14** (in-house): the dispatcher is a table,
`ctx.keymap` and `ctx.actions.run(id)` / `ids` are the door.
**Slice 4b closed 2026-09-14** — after stopping first, which is the
result the slice was run to test. Its entry point was decided and built
before it: slots belong to the host, the 🎹 is a manifest-declared item in
the header slot, and the second header row has a slot of its own
(`docHeader`) for the player when slice 7 moves it. The plugin ships the
panel as a projection of the union keymap with `ctx.actions.run(id)`
behind every button, the piano as slice 3's virtual MIDI input, and the
coverage suite over the union keymap in both layouts. Built against
0.1.2 it reached 23 of its 24 e2e checks and **stopped**: the panel sees
plugin-contributed bindings in the union keymap and `run(id)` did not
carry them, so it would have had to caption a button it could not press.
It invented nothing, left the check failing, and reported three gaps
(`packages/plugins/onscreen-keyboard/BUILDING.md` §7.1–§7.3). All three
were then decided and built in-house as **api 0.1.3** — `run(id)` means
*this action*; `ctx.actions.ids` is a store; `ctx.activatedBy` and
`onSettings:` exist; a runtime slot item overrides a declared one's
face (and, at 0.1.4 after review, a declared one may ask to be dimmed
until its plugin runs) — and the plugin consumed them: 24 of 24, the
union keymap snapshot
unchanged, `App.tsx` 3,248 → 3,227, the initial chunk 601.4 → 593.0 kB.
**A slice that stops with a precise gap and a slice that closes are the
same slice, one day apart; a slice that invents its way past the gap is a
rollback.**
**Slice 5 was split on 2026-09-14 into 5a and 5b**, the 4a/4b pattern:
5a (in-house) lifts the harm-lane mechanism into the host as the `lanes`
point with both lanes running on it as internal specs, and builds the
host halves 5b needs (`contributes.lanes`, `onLane:` firing,
`ctx.lanes.register` / `open`, the `core.setSyl` message,
`ctx.query.lyricAt`), after writing the lyrics e2e the plan said was
missing; 5b (a context-free agent) moves the lyrics body into
`packages/plugins/lyrics` with *API may grow: none*. Slice 6 follows the
same pattern, its two halves built in-house before it runs. **Slice 5a
closed 2026-09-14** (in-house): `host/lanes.tsx` is the point, both lanes
run on it as internal specs, `contributes.lanes` + `onLane:` + `ctx.lanes`
+ `core.setSyl` + `lyricAt` are on the api at 0.1.5, and
`verify-lyrics.mjs` (26 checks) gates the lyrics lane — written first,
it caught a hyphen-stripping bug in 0.0.3. **Slice 5b closed
2026-09-14**: `packages/plugins/lyrics` declares the lane, registers a
spec that leaves harmony's four grammar fields unset, holds no state at
all, and needed **no api addition and no host change** — the first slice
of the phase to hit no gap, because 5a's additions each named 5b as
their consumer and the list was right. The e2e's assertions and both its
design hooks are unchanged; the union keymap snapshot changes by exactly
one entry, the `l` binding moving from core to the plugin. **A point
designed against two consumers before either leaves costs a plugin slice
a day instead of a rollback.** **Slice 6's host half landed 2026-09-14**
(api 0.1.6: `core.setHarm`, `harmAt`, `harmValid`; the status bar's
anchoring rule, the lanes select as its boundary, the `.sbsel` look as a
class — the CHANGELOG bullet has the account), and the grammar split is
decided in its brief: validity stays in core and is asked through
`harmValid`, the editor affordances move into the plugin. **Slice 6 closed
2026-09-15**: `packages/plugins/harmony` declares both lanes and
registers them as one function of `kind`, and the `lanes` point took
**no change at all** for its second consumer — not a field, not a query.
Between 5b and 6 every `LaneSpec` field has a consumer and none has a
third state, so **the point is frozen for the phase**. `App.tsx` has no
lane code left (3,109 → 3,091; what remains is the adapter, the
document's own view of the caret path), the union keymap snapshot is
byte-identical (harmony is picked, never pressed), and the grammar split
landed on its second reading: the brief split the grammar by validity
(regexes in core, because `SetHarmCommand` refused on them) and that
justification was circular — the command refused because core owned
them. The whole grammar went to the plugin, core kept only the ELEMENT,
and `ctx.query.harmValid` left the api (0.1.6 → 0.1.8). **Reversed the
same day, on the third reading**: a second writer is coming (a generator
plugin that reads a measure and writes its harmony), every writer must be
refused the same text, and if the api validates it validates every time
— so validity is core's again, `SetHarmCommand` refuses on it, `harmValid`
is back on the api (0.1.10), and the plugin keeps the affordances
(charset, transform, suggestions) and asks the question instead of
copying the answer.
**Slice 7 was split on 2026-09-15 into 7a and 7b**, the pattern since 5:
7a (in-house) builds what a player needs from the host and cannot make
itself — the app's one AudioContext as a service (unlock in the gesture,
the shared context, a clock conversion; the host owns the context, not
an instrument), the timemap and the notation facts as read-only queries,
the highlight as a view service, `onView:` fired, the export half of
`formats` — and rewrites the in-App player onto them first, taking the
performance logic (ties, gates, clones) OUT of core into the player,
because how a score is performed is a player's decision and there can be
several players. 7b (a context-free agent) moves the player, its row, the
export, Tone.js and the samples into `packages/plugins/playback` with
*API may grow: none*, and the budget ceiling drops there. **Slice 7a
closed 2026-09-15** (in-house): `ctx.audio`, `ctx.query.timemap()` and
`notation()`, `ctx.view`, `onView:` fired, the export half of `formats`
— and the in-App player rewritten onto them as a wall-clock scheduler
with its own performance, the interpretation out of core; api 0.1.11;
phase 5's playback section green unchanged. **Slice 7b closed
2026-09-15**: `packages/plugins/playback` holds the player, the row, the
export, Tone.js and the samples; the api did not grow (0.1.11 unchanged),
the initial chunk fell 596.0 → 360.8 kB and its ceiling to 377,000 bytes,
and `App.tsx` is 3,133 → 2,945. Two things the slice would not resolve
itself, both written into its BUILDING.md §7 and the CHANGELOG: the
export can no longer be named `-playback.mid`, because
`DocumentInfo` carries the score's TITLE and not the open file's name
(the addition to consider is `DocumentInfo.name`, with this export and
slice 9's folder view as its two consumers), and the shell's mp3-decode
probe is inert now that `window.__SAMPLE_URL__` — a DOM global a plugin
may not set — is gone. One host edit beyond the brief's list, named
rather than passed over: Vite's `__vitePreload` helper had to be named in
`manualChunks`, the third module the host and a plugin share (after core
and React) and the first that is Vite's own. Its two gaps closed in-house
the same day (api 0.1.12: `DocumentInfo.name`, so the export is
`-playback.mid` again; the shell's playback probe revived through
the real UI and asserted; the DOM-global rule tightened). **Slice 8 was
split into 8a and 8b the same day, and 8a closed** (in-house, api
0.1.13): `contributes.imports` and `ctx.formats.registerImport`, detection
as the host's (`.xml` told from MEI by declared root elements), the open
dialog's accept list and the shell's filter fed by the registry,
multi-file export payloads for the SVG pages, and the App's five Verovio
imports and four exports running as internal registrations —
`verify-formats.mjs` (14 checks) written first and green unchanged after.
**8b was attempted on 2026-09-16 and stopped**, the good way: nothing
delivered half-way (the budget is the slice's point, and a half-moved
worker would have shipped as two byte-identical copies Vite deduplicates
until the first edit), the gap written up — an export producer had no
way to read the document, because 8a's rehearsal had it by closure — and
closed in-house the same day: `ctx.query.mei()` (api 0.1.14), the App's
own registrations rewritten to read through it. **8b closed on its second
attempt, 2026-09-16**: `packages/plugins/formats` holds the five imports,
the three Verovio exports, the table and the worker; the api did not grow
(0.1.14 unchanged), the 13.45 MB `convertWorker` asset is reached only
from the plugin's chunk, and `App.tsx` is 2,946 → 2,935. **Slice 9 was
split into 9a and 9b on 2026-09-16, and 9a closed** (in-house, api
0.1.15): checked before the handoff, the `panels` side area existed and
nothing else did — so `ctx.workspace` (pick, re-admit, list, open, watch;
scoped to the folders the user picked, a `notify` watcher in the shell,
unavailable in a browser), `ctx.documents` with `path` and `dirty` on
every snapshot, and the external-change guard gone live; the shell
smoke's eighth check picks a folder without a dialog, lists it, refuses
an outside read and sees a change. **9b closed 2026-09-16, and it is the
measurement the phase was built to take**: `packages/plugins/folder-view`
is a whole feature that never lived in the editor, and `App.tsx` is
**2,991 → 2,991** — the host's entire diff is the two lines in
`plugins.ts` every plugin costs. The api did not grow (0.1.15 unchanged),
because 9a built every call against this panel as its named consumer.
Four findings the e2e made and no unit test could, all in its BUILDING.md
§7: the side panel area starts under the app header (its first consumer
in five slices), a declared entry point has two DOM hooks over its life,
an error state has to carry its way out, and `openFolder` answers the
same `false` for "no shell" and "no folder". Its three host gaps closed
in-house the same day, with the user's four changes to the panel: the
side area starts below the header, sits on the left and pushes the score
right; the live guard accepts `created` as well as `modified` (macOS);
`.mei` only stays; the rows lose their dot and bold and the active tab's
score is highlighted. Slice 10a (2026-09-18) built the last point the
phase names, `overlays`, against a rehearsal plugin that holds only
`ctx`: the host measures each tile and a plugin draws in its pixels;
geometry only, time stays in the timemap (api 0.1.16; `App.tsx` 3,017).
Slice 10b (2026-09-18) closed the phase's last plugin the same day:
`packages/plugins/pitch-reference` — a recording decoded by the host's
context, plain YIN, an offset and a rate against the score's own tempo,
the trace on every tile through the overlays point and fitted onto the
noteheads — with `App.tsx` and core untouched, which is the claim the
phase was run to test. **1.0.0 was released on 2026-09-18** — one number
for everything: the application, core, the docs, `@battuta/api` (every
plugin asking for `^1.0.0`) and the eight plugins. The plan below says
0.1.0 for the application; the user chose to align it with the contract
at release. DESIGN.md's *Host and plugins* section is written, and the
phase's documents are closed.
From here on slices are
handed to sessions without the surrounding context, on purpose, to test
whether the briefs and `packages/plugins/README.md` hold on their own.
The browser e2e scripts were found rotten at slice 1's close (a lost
fixture, UI removed in 0.0.2) and repaired the same day: five scripts,
347 checks, green — run them one at a time, after
`sh spikes/fetch-fixtures.sh`; `packages/plugins/README.md` has the
commands. They gate every extraction from here on.
Slice 2 was attempted by a context-free agent on 2026-09-12 and rolled
back: the plugin worked but imported `@battuta/core`, and the rule
against it — a README sentence — was rewritten twice to fit the code
(`packages/plugins/reflection/POSTMORTEM-2026-09-12.md`). Hardened on
2026-09-14 before the second attempt: `@battuta/api` (still 0.1.0,
never published) is standalone, commands are messages, reads are a query facade, and the
boundary test fails the build on any core import. Slice 2 was rebuilt on
that footing and **closed 2026-09-14**: zero core imports, no API change
(0.1.0 unchanged — the point of the exercise), `App.tsx` 3,364 → 3,321,
all 347 e2e checks green. Its `BUILDING.md` is the worked example slice 3
onward copies; its §7 carries the new dead ends (no vitest config,
extensionless imports, the generated keyboard reference that silently
dropped the moved binding, and the bundle ledger running the other way
for a feature this small).
#### Slice 1 — Host skeleton (≈4 days)
**Delivers.** `@battuta/api` 0.1 — a new workspace package, semver'd
separately from the app, `engines.battuta` checked at registration —
with the manifest format, the registry, activation events, the keymap
as a **reactive store** (core map ∪ contributions, with a subscribe: a
panel activated late must see bindings registered later still),
`execute`, `notice`, `confirm`, the settings and storage namespaces,
the `activate(ctx)` / `deactivate()` lifecycle with disposables, and
empty `header` / `statusBar` / `menu` / `panels` slot components. A
**Plugins tab in the 🌣 editor** lists every installed plugin with an
on/off toggle persisted in `battuta.settings.v1`: off = `deactivate()`
runs and its disposables fire — bindings leave the keymap store (the
on-screen keyboard and shortcut editor follow live), panels close,
status-bar and menu items vanish — with no document change and no
reload. Keymap overrides for a disabled plugin's bindings are kept, so
re-enabling restores the user's rebinds. The toggle is the user-facing
face of the `--no-plugins` CI mode.
**Proves.** The host runs with an empty registry. Nothing user-visible
changes.
**Leaves `App.tsx`.** Keymap loading and merging; the notice and
confirm plumbing (they become host services the host itself calls).
**Gates.** Every existing suite unchanged. New in `test.yml`: an API
snapshot test (a change to `@battuta/api`'s public types fails until
the version is bumped); the **host bundle budget** on the Vite
manifest, with today's initial chunk as the ceiling that later slices
lower; the `--no-plugins` property (open → save with plugins on and
off → identical bytes) — trivially true today, load-bearing from
slice 2.
**Documents.** `packages/plugins/README.md` — the conventions and the
two templates every plugin fills in (next section); a
`reference/plugins` page in the user guide (the tab, what "off"
means; one row per plugin from slice 2 on); the DESIGN.md note gains
the layer list; the CHANGELOG bullet.
**Done when.** The editor opens, edits, undoes and saves with the
registry empty; every e2e script and the shell smoke are green; the
three new CI checks run; the plugins tab reads "no plugins installed".
#### Slice 2 — Reflection cycle (days)
**Delivers.** `packages/plugins/reflection`: the smallest
self-contained feature — one binding (`shift+R`), one message
(`core.setPitches`, already in the api), one notice. The serial-form
maths (`reflectionForm`, `REFLECTION_CYCLE`, `REFLECTION_LABELS`,
`arityPalindromic`) has no MEI knowledge and **moves out of core into
the plugin** with its tests; core keeps `SetPitchesCommand` and
`collectPitchEvents` (reached as `core.setPitches` and
`query.pitchEventsIn`). The cycle's base form and step, which `App.tsx`
holds in a ref today, become the plugin's transient state — the first
example of state a plugin may own (nothing document-shaped), keyed on
`DocumentInfo.id`. No fuzz harness leaves core: plugins define no
commands, the mapped core command is covered by core's own tests.
**Proves.** `commands` + `keybindings`, and the whole plugin lifecycle
end to end: manifest → activation on `onCommand:` → binding in the
store → shortcut editor and on-screen keyboard showing it → toggle off
removes it live.
**Leaves `App.tsx`.** The `reflect` branch of the key dispatcher and
the `reflectCycle` ref.
**Gates.** `packages/core/test/reflect.test.ts` keeps the
`SetPitchesCommand` and `collectPitchEvents` cases, the form tests move
with the maths into the plugin's suite; the reflection checks in
`verify-phase5.mjs`; the boundary test scans the new package; the
`--no-plugins` property now has a plugin to be off.
**Documents.** The plugin's `README.md` and `BUILDING.md` — the worked
example every later plugin copies (the two precedents are already
decided and enforced: `exports` at `src/`, no core import — the
boundary test in `apps/editor/test/plugin-boundaries.test.ts` is the
rule). Read `packages/plugins/reflection/POSTMORTEM-2026-09-12.md` §7
first: the first attempt's dead ends, including the one that cannot
be seen from the API (a plugin cannot observe its own `execute`
synchronously — subscribe to `ctx.document`). A **Writing a plugin**
guide in the docs site walks through this plugin.
**Done when.** `shift+R` on a block behaves byte-identically to 0.0.3
with the plugin on; with it off the key does nothing, the shortcut
editor and the on-screen keyboard no longer show it, and the document
is unchanged.
#### Slice 3 — MIDI service, a host service (≈2 days)
**Delivers.** The device code lifted out of `App.tsx` and `midiOut.ts`
behind one interface on `@battuta/api`: inputs and outputs, hot-plug,
dedupe by port name, the virtual "battuta" source, `panic()`, and
`registerInput()` for virtual inputs. Backends unchanged: Web MIDI in
browsers, the midir bridge in the shell (the shell's MIDI commands
become the service's shell backend). No plugin.
**Proves.** The host-service cut: a platform capability with two
backends, consumed by features, lives in the host. Consumers after this
slice: the entry path and the status-bar indicator (host), the play
sink (still in `App.tsx` until slice 7).
**Leaves `App.tsx`.** Web MIDI access, device listing, the shell
bridge listeners.
**Gates.** `apps/editor/test/midiOut.test.ts`; `verify-phase4.mjs`
(the Web MIDI entry path) and `verify-phase5.mjs` (the MIDI
indicator); `verify-tauri.sh` (bridge devices and notes).
**Documents.** DESIGN.md's host-services list; the api surface grows
`MidiService` (still 0.1.0 — never published; the report is rewritten
with `--unpublished`); the CHANGELOG bullet.
**Done when.** Hardware entry, the status-bar indicator and the shell
bridge behave as in 0.0.3, and `App.tsx` no longer imports Web MIDI or
the bridge.
#### Slice 4a — Core actions by id (host, in-house; ≈3 days)
**Delivers.** The App's key dispatcher becomes a table `actionId →
handler`. Every keymap action already has an id; every locked physical
and system key gets one (`nav.left`, `nav.home`, `edit.delete`,
`edit.backspace`, `edit.escape`, `file.save`, `file.open`, `undo`,
`redo`, `clipboard.copy`, `clipboard.paste`, `zoom.in`, `duration.4`,
`pitch.c`, `chord.e`, `finger.3`, `volta.2`, `measure.insert`, …), so
the keymap maps keys to actions the way VSCode maps keybindings to
commands. `keyMatches` selects the id; the table runs it. Plugin
commands already run by id (`runCommand`); this gives core actions the
same door. The api grows two published, finite things: `ctx.keymap`
(read-only store: id, label, group, when, keys, locked, plugin) and
`ctx.actions.run(id)`. No `press()`, nothing that forges events — an
input surface that runs ids cannot do anything the host has not named.
**Proves.** That the on-screen keyboard needs no pass-through, and that
the phase's metric can move for real: the dispatcher's matching leaves
`App.tsx` for the host; the branch bodies follow in later slices.
**Leaves `App.tsx`.** The `hit(id) && …` matching chain (the bodies
become table entries; the table lives in the host).
**API may grow.** `ctx.keymap`, `ctx.actions.run(id)`; host module
`actions.ts` (added to `HOST_MODULES`). Nothing else. *(As built:
`ctx.actions.ids()` was added too, so a projection can check its buttons
against the live list; recorded in the CHANGELOG.)*
**Stop when.** An action cannot be given an id without changing what a
key does. (None is expected; the locked groups are finite.)
**Gates.** Every e2e script unchanged, including
`verify-onscreen-keyboard.mjs` (24 checks, against the in-App panel);
the union keymap snapshot byte-identical; host tests for the table (every
keymap id and every locked key has a handler; `run(id)` takes the same
path as the key).
**Documents.** CHANGELOG bullet; DESIGN.md note (keys bind actions);
the conventions' data-contract table gains the two rows.
**Done when.** Every key the App handles goes through the table, and
`ctx.actions.run(id)` runs the same code as the key would.
**Closed 2026-09-14.** Both hold; all six e2e scripts and the shell
smoke green, the keymap snapshot unchanged. `App.tsx` 3,274 → 3,241.
The CHANGELOG bullet has the vocabulary and the one addition beyond the
brief (`ids()`).
#### Slice 4b — On-screen keyboard (plugin; ≈1 week)
**Delivers.** `packages/plugins/onscreen-keyboard`: the panel
(`VirtualKeyboard.tsx`, `virtualKeys.ts`) as a `panels` consumer, a
projection of `ctx.keymap`: buttons run `ctx.actions.run(id)`, latched
modifiers select the *variant* id (`MOD_VARIANTS` already maps base →
variant), ctrl chords are ids, and the piano is the virtual MIDI input
slice 3 registered (`ctx.midi.registerInput("on-screen piano")`). Its
coverage test moves into the plugin's suite and runs against the union
keymap, so an unreachable binding from *any* plugin fails CI. Opens on
`onPointer:coarse` (the host fires it) and from the 🎹 toggle.
**Proves.** `panels`, `header`, activation on a pointer event, the two
doors from 4a and 3 — and that a UI plugin needs no service.
**Leaves `App.tsx`.** The keyboard's mount, the `vkeys` setting (moved
once into the plugin's namespace by a dated list in `settings.ts`), the
coarse-pointer default, the 🎹 button.
**API may grow.** **None from the plugin.** The entry point is decided
and built (2026-09-14, in-house): the 🎹 is a manifest-declared slot
item in the `header` slot — `contributes.slotItems: [{ id, slot:
"header", label: "🎹", command }]` — which the host renders before the
plugin's code loads; the click runs the command, which activates the
plugin. No keyboard service, no new binding (the union keymap snapshot
must not change), no new host module. The panel opens on
`onPointer:coarse` — which the HOST fires at startup on a coarse pointer
— and from the toggle; whether it is open is the plugin's own setting.
*Amended 2026-09-14, in-house, after the plugin stopped on three gaps
(its BUILDING.md §7.1–7.4), api 0.1.2 → 0.1.3:* `ctx.actions.run(id)`
reaches an enabled plugin's command when no core rule has the id, past
the same gates its key would meet, and `ctx.actions.ids` is a
`Store` (core rules ∪ enabled plugins' commands,
republished on every install and every on/off); `ctx.activatedBy` names
the event that woke the plugin (`onStartup`, `onPointer:coarse`,
`onCommand:`, `onSettings:`, or null from the Plugins tab);
`onSettings:` is a new activation event the host fires at startup
for a plugin whose OWN setting under `` is truthy; and a runtime
`ctx.slots.add` item with the same `id` as a declared slot item replaces
its face while the plugin is active (the declared face returns on
deactivate), so the 🎹 can be a real toggle that shows its state. Each
was decided here, not in the slice, and each names its consumer.
*Amended again after review, api 0.1.3 → 0.1.4:* a declared slot item may
carry `dimUntilActive`, drawn de-emphasised until its plugin is active —
per item, because "not active" means "not showing" only for an entry
point that opens something.
**Stop when.** The panel needs any capability beyond `ctx.keymap`,
`ctx.actions.run` / `ids`, `ctx.midi.registerInput`, `ctx.panels`,
`ctx.settings`, `ctx.editor` and the declared slot item. Write the gap;
do not resolve it.
**Gates.** The coverage suite over the union keymap;
`verify-onscreen-keyboard.mjs` with only its two design-dependent hooks
changed (the toggle's selector, the open flag's location) — every
assertion identical; the keymap snapshot unchanged; the boundary tests;
`verify-phase4.mjs` and `verify-phase5.mjs` unchanged.
**Documents.** The plugin's two documents (its BUILDING.md §7 starts
from `onscreen-keyboard/POSTMORTEM-2026-09-14.md`'s traps); the guide's
virtual-keyboard page unchanged in content plus its plugins-page row;
the CHANGELOG bullet.
**Done when.** Every coverage test passes against the union keymap;
turning the plugin off removes the panel and the 🎹 live; touch entry is
byte-identical to 0.0.3.
#### Slice 5a — The `lanes` point (host, in-house; ≈2 days)
**Delivers.** The harm-lane mechanism becomes a host module, `lanes.ts`
(added to `HOST_MODULES`), with both existing lanes running on it as
INTERNAL specs and their bodies still in `App.tsx` — the 4a move,
applied to lanes. What the mechanism is, read off the two modals: a
buffer at the caret, (re)loaded from the document when the caret or the
version moves; one modal step that owns the keyboard while a lane is
open — Escape commits and leaves, the lane's *advance keys* commit and
move the caret on (to the next event, or to the next NOTE with rests
skipped), arrows commit and step, Backspace edits, Tab takes the first
suggestion when the lane suggests, a printable character is admitted by
the lane's charset and mapped by its transform (`o` → `°` in numerals) —
and a commit that turns the buffer into ONE command, refusing with a
notice when the lane says the text is incomplete or the caret is not on
what the lane attaches to. A `LaneSpec` is exactly those fields: `id`,
`label`, `place: "above" | "below"`, `attachesTo: "note" | "event"`,
`advance: "event" | "note"`, `advanceOn: string[]`, optional
`accepts(ch)`, `transform(ch)`, `complete(buffer)`, `suggest(buffer)`,
and `read(eventId)` / `commit({ eventId, buffer, key, prevEventId })` —
the last returning a `CommandMessage` (or null for "nothing changed") and
throwing a string to refuse. The floating editor (`data-harm-input`,
`data-valid`, the ♪ / ♩ / RN prefix, the suggestions) becomes a host
component fed from the lane store; the status-bar select lists the
internal lanes and every lane DECLARED in a manifest (`contributes.lanes:
[{ id, label, place }]`) — the slot-item lesson applied: the entry point
renders before the plugin's code loads, and picking a declared lane
whose plugin is not active fires `onLane:` (the prefix has existed
since slice 1, unfired), waits for the plugin to register the spec, then
opens it. `ctx.lanes.register(spec)` (the id must be declared, as
`registerCommand` demands a declared command) and `ctx.lanes.open(id)`
(for a plugin's own key) are the door. In-house too, the host halves 5b
will need and could not add: the `core.setSyl` message (`{ eventId,
value: SylValue, label }` → `SetSylCommand`) and
`ctx.query.lyricAt(eventId)`. Slice 6's halves (`core.setHarm`,
`harmAt`) wait for slice 6.
Before any of it: a lyrics e2e, `spikes/verify-lyrics.mjs`, written
against the App as it is — `l` at a note opens the lane below the
staff; "hel" then `-` writes `` and advances to
the next NOTE over a rest; "lo" then space writes `wordpos="t"`; a whole
word writes neither; an empty commit on a rest is allowed and on a note
clears; Escape commits and leaves; the buffer reloads when the caret
returns to a note that has a syllable; undo unwinds every step and the
MEI is byte-identical; save and re-parse. Green first, then the
extraction keeps it green.
**Proves.** `lanes` by extraction with two consumers already on it, so
5b and 6 find the shape and move bodies — and that a text lane needs
the host to know nothing about the text: no grammar, no MEI shape, no
`HarmKind` in `lanes.ts`.
**Leaves `App.tsx`.** The two modals' key protocol, the `harmLane` /
`harmBuffer` state with its ref and its reload effect, the floating
editor, the select's option list. Stays for now: `commitSyl`'s value
logic and the harmony grammar calls, as the two internal specs.
**API may grow.** `LaneContribution` (`contributes.lanes`, validated:
ids unique across plugins, `place` one of two), `LaneSpec` and
`LaneCommit`, `ctx.lanes: { register, open }`, `onLane:` fired;
`SetSylMessage` + `SylValue`; `DocumentQueries.lyricAt`; host module
`lanes.ts`. Consumers named: every one is 5b's, except the `chord` /
`rna` internal specs, which are slice 6's rehearsal. Nothing else: no
`ctx.lanes.active` store (no consumer), no navigation query (the host
hands `commit` the previous event of the lane's kind), no `when`
evaluation for plugin bindings (a handler declines on `ctx.editor`
state — the slice-2 convention). api 0.1.4 → 0.1.5.
**Stop when.** A lane needs the host to know what KIND of text it holds
— a grammar, a validator or an MEI shape in `lanes.ts` is the harmony
lane not leaving. (A spec field only one lane uses is expected and is
not this: `accepts` / `transform` / `suggest` are harmony's, `advance:
"note"` and `-` are lyrics'.)
**Gates.** `verify-lyrics.mjs` green before and after, assertions
unchanged; `verify-phase5.mjs` §7i unchanged (`data-harm-input`,
`data-valid` and the select's option values `chord` / `rna` / `lyrics`
keep their names — they are the internal ids); every other e2e script;
host tests for `lanes.ts` on a fake adapter (register demands a
declaration; every key of the protocol; advance over a rest for
`"note"`; a refusal is a notice and no command; `onLane:` fires for a
declared lane and the lane opens once registered; a declared lane
leaves the select when its plugin is off); the union keymap snapshot
byte-identical (no binding moves); the boundary tests with `lanes.ts`
allowed; the budget.
**Documents.** CHANGELOG bullet with the point's final field list and
why each field exists; DESIGN.md note; the conventions' data-contract
rows (`contributes.lanes`, `ctx.lanes.register` / `open`, `core.setSyl`,
`ctx.query.lyricAt`, `onLane:`); the api doc comments.
**Done when.** Both lanes run through `host.lanes` with their bodies in
`App.tsx`, every harmony and lyrics check green, `App.tsx` down by the
mechanism.
**Closed 2026-09-14.** Both hold; all six e2e scripts green, the keymap
snapshot unchanged, `App.tsx` 3,227 → 3,145, api 0.1.5. *As built,
beyond the brief:* the spec carries `name`, `glyph` and `hint` (the UI
strings the two lanes kept in three places), `commit` returns `{ refuse }`
rather than throwing, and the internal lyrics spec already commits
through `core.setSyl`. The lyrics e2e found and the slice fixed one 0.0.3
bug (Escape over a hyphenated syllable dropped its hyphen). The CHANGELOG
bullet has the field-by-field account.
#### Slice 5b — Lyrics lane (plugin; ≈2 days)
**Delivers.** `packages/plugins/lyrics`: a manifest declaring one lane
(`{ id: "battuta.lyrics.verse1", label: "lyrics (verse 1, l)", name:
"lyrics", glyph: "♪", place: "below" }`), one command
(`battuta.lyrics.open`) and its keybinding (`l`, group `entry`, the
existing label), activating on `onLane:battuta.lyrics.verse1` and
`onCommand:battuta.lyrics.open`; `activate` registers the spec —
`attachesTo: "note"`, `advance: "note"`, `advanceOn: [" ", "Enter",
"-"]`, `read` = `ctx.query.lyricAt(eventId)?.text ?? ""`, `commit` =
today's `commitSyl` as a pure function: unchanged text and hyphen state
→ null; `-` → `con: "d"` with `wordpos` `m` when the previous note's
syllable continues (`lyricAt(prevEventId)?.con === "d"`), else `i`; a
plain commit after a continuing syllable → `wordpos: "t"`; otherwise a
whole word; `""` clears — returned as `{ type: "core.setSyl", eventId,
value }` (the command labels itself); unchanged text keeps its
hyphenation (5a's fix — `hyphen = key === "-" ? true : textChanged ?
false : wasHyphen`). The command handler is `ctx.lanes.open(…)`, declining
when `ctx.editor.get().entryMode` (in 0.0.3 `l` does nothing in entry
mode; the select still opens the lane from entry mode because the HOST
leaves entry mode first — do not copy that into the key). The internal
lyrics spec and `commitSyl` leave `App.tsx`; the `lyrics` entry leaves
`keymap.ts` as `reflect` did in slice 2.
**Proves.** The point holds for a plugin with no access to the model:
the wordpos/con table — the only logic lyrics has — is computed from two
`lyricAt` answers and the key that committed.
**Leaves `App.tsx`.** The lyrics spec, `commitSyl`, the `lyrics` rule
and its notice text; the `lyrics` binding from `keymap.ts`.
**API may grow.** **None.** Everything is in 5a.
**Stop when.** The lane needs anything beyond `ctx.lanes.register` /
`open`, `core.setSyl`, `ctx.query.lyricAt`, `ctx.editor`, `ctx.notice`,
the declared lane and the keybinding. Write the gap in BUILDING.md §7
and the CHANGELOG; do not resolve it. (5a's spec fields exist because
two lanes ran on them; a third state of a field is a gap, not a tweak.)
**Gates.** `verify-lyrics.mjs` with only its design-dependent hooks
changed (the select option's value, if the lane id replaces `lyrics`) —
every assertion identical; `verify-phase5.mjs` unchanged; the union
keymap snapshot changes by exactly one entry — `lyrics` (core) leaves,
`battuta.lyrics.open` (plugin, `l`) arrives: regenerate with `npm run
keymap:snapshot -w @battuta/editor` and put the diff in the CHANGELOG
bullet; the boundary tests; the plugin's suite (the wordpos/con table as
pure tests over `lyricAt` fakes, the refusal on a rest, `l` declining in
entry mode); `packages/core/test/lyrics.test.ts` unchanged.
**Documents.** The plugin's two documents (BUILDING.md §7 starts from
`onscreen-keyboard/BUILDING.md` §7's traps); the guide's harmony page:
lyrics section unchanged in content, ``
following the binding to its new id — the reflection plugin's
BUILDING.md §7 records the generated reference silently losing a moved
binding; the plugins-page row; the CHANGELOG bullet.
**Done when.** Typing lyrics is byte-identical to 0.0.3 through the
point; turning the plugin off removes the `l` key, the select's option
and the lane together; `App.tsx` has no lyrics code.
#### Slice 6 — Harmony lane (≈2 days)
**Delivers.** `packages/plugins/harmony` on 5a's `lanes` point: two
declared lanes (`{ id: "battuta.harmony.chord", label: "chord symbols
(above)", name: "chords", glyph: "♩", place: "above" }` and `{ id:
"battuta.harmony.rna", label: "roman numerals (below)", name:
"numerals", glyph: "RN", place: "below" }`), activating on `onLane:` of
each; `activate` registers both specs — `attachesTo: "event"`, `advance:
"event"`, `advanceOn: ["Enter"]`, the hint text verbatim from `App.tsx`,
`read` = `ctx.query.harmAt(eventId, kind)`, `commit` = `{ type:
"core.setHarm", eventId, kind, text }` when the buffer differs from
`harmAt`, null otherwise. **Where the grammar goes (decided 2026-09-14,
in-house):** VALIDITY stays in core — `SetHarmCommand` refuses text its
regexes reject, so core must own them — and the plugin asks through
`ctx.query.harmValid(kind, text)`: that is `complete`. The editor
affordances move into the plugin: the charsets (`HARM_CHARS`, →
`accepts`), the numeral key mapping (`o` → `°`, `0` → `ø`, →
`transform`), and the suggestion lists with their prefix rule
(`CHORD_QUALITIES`, `RNA_BASES`, `harmSuggestions`, → `suggest`; its
"add a `/` continuation once the head is complete" asks `harmValid`
too). Core's `harm.ts` keeps the regexes, `isHarmText`, `harmTextAt` and
the command, and loses `HARM_CHARS` and `harmSuggestions` (with their
core tests moving into the plugin's suite). The two internal harmony
specs and the last of the lane code leave `App.tsx`, and with them the
`isHarmText` / `harmSuggestions` / `HARM_CHARS` / `HarmKind` imports.
**Proves.** The rule of three, near enough: a third consumer confirms
the point's shape. Whatever harmony needs that the internal spec did not
is the point's last change before it is frozen for the phase.
**Leaves `App.tsx`.** The two internal harmony specs — the last lane
code.
**API may grow.** **None.** Built in-house on 2026-09-14, api 0.1.5 →
0.1.6: the `core.setHarm` message (`{ eventId, kind, text }`; the command
labels itself), `HarmKind` on the api, `ctx.query.harmAt(eventId, kind)`
and `ctx.query.harmValid(kind, text)`. The internal `chord` / `rna` specs
already commit through `core.setHarm`, so the message runs end to end
before the plugin exists, and every spec field harmony uses is in the
point because 5a ran those specs on it. Also in-house, before the slice,
the status bar itself: **host controls are anchored; contributions grow
into the free space to their left.** The `statusBar` slot sits right
after the bar's spacer, so a plugin item appearing or leaving moves no
host control; the lanes select is the boundary — first of the host
group, present only while some lane is on offer (`data-lanes`,
placeholder "lanes", a title listing the lanes), hiding without shifting
anything; and the bar's control look is the `.sbsel` class alone, so a
plugin's own `