# X0X projects

The **Projects** companion page saves, loads and resets the keyboard’s live
project, and exports or imports `.x0xproject` files. Connect the keyboard by USB
with compatible X0X firmware running. Stop playback, recording and performance
mode before a transfer. Close other editors while using the page.

The page is included at `projects/` in the site generated by
`tools/make_pages.py`. For local development, serve the repository over localhost
and open `web/x0x_projects.html`; its JavaScript modules work without a build step.
Web MIDI needs a browser that supports SysEx, such as Chrome or Edge, and HTTPS or
localhost. Project handling does not install firmware.

## On the keyboard

**Save on keyboard** stores the live project through the same persistence path
used by the firmware. **Load saved project** replaces the live project with that
saved state. **Reset live project** resets sequencers, sounds and project settings
to the firmware defaults. Load and reset ask before discarding live changes.
These operations leave the sample slots in place.

Import replaces the live project after validation. Import and reset do not
immediately invoke Save; the firmware’s autosave setting also applies. Use
**Save on keyboard** to store the new state immediately. Existing flash
persistence writes several objects; this feature does not turn saving into a
power-failure-atomic transaction.

## Export and import

Export defaults to a portable file containing the project and every populated
user sample slot. The complete active image of each slot is preserved: its
original 512-byte header area and encoded sample data. There is no decoding,
re-encoding, trimming, normalization, resampling or slot remapping. Unused flash
space after an active image is not part of the file. An empty slot is explicitly
recorded as empty.

Uncheck **Include original samples** to export a smaller project-only file. It
still contains the identity of every source slot, including empty slots. Import
checks those identities against the connected keyboard and refuses a mismatch.
Project-only import never sends sample erase or write commands. Raw inner project
files cannot be imported through the page because they have no sample identity
manifest.

To import a portable file:

1. Choose the file and press **Prepare import**. The page checks the file, reads
   the current project and samples, and prepares a verified recovery backup.
2. Review the slot table. Identical slots are kept. Empty destination slots are
   filled in their original positions. A different occupied slot is shown as a
   replacement. An occupied destination where the source was empty is shown as a
   clear operation.
3. Before replacing or clearing any occupied slot, download the recovery backup
   and confirm that it is saved. Then press **Import project** and confirm replacing
   the live project.
4. Keep USB connected until the page reports completion. Use **Save on keyboard**
   if the imported project should be stored immediately.

X0X numbers user break zones across populated slots. Keeping extra destination
samples, moving a source slot to another free slot, or changing the empty slots
could change those references. The importer therefore preserves the complete
slot ordering. It refuses a different slot count or an image that does not fit
the same destination slot.

Preparation leaves the live project and samples unchanged. Before applying the
preview, the page checks that the keyboard still matches its recovery snapshot.
Firmware validates the staged project, including semantic constraints and pattern
capacity, before the first sample change. After writing, the page reads the
samples back and compares every active byte before adopting the new project.

If a transfer fails after sample writes begin, the page attempts to restore the
changed slots from the verified recovery backup and checks their bytes again. If
the final adoption reply is lost, it also restores the previous live project,
because adoption may already have occurred. A failed recovery is reported
explicitly. Its recovery download stays available after closing the preview or
choosing another file. The rollback keeps the runtime hold while restoring sample
bytes; it does not abort the import and briefly resume the keyboard first.

### Recover an interrupted sample transfer

If the original sample images have not been restored, the firmware keeps audio
and controls held and reports **recovery mode**. The hold also survives transfer
timeout and closing or reloading the browser page. Reconnect, choose the portable
recovery backup, and press **Prepare recovery**. The page checks the file and slot
capacities without trying to read or back up partially written sample payloads.
Confirm **Restore recovery project** to restore all slots in their original
positions, verify their exact bytes, and adopt the project from that file.

A project-only file cannot repair sample slots and is refused in recovery mode.
Save, Load, Reset and Export are disabled while recovery is required. If another
recovery attempt fails, the hold remains until the firmware can verify the
original sample images again or a complete validated project is adopted. A
successful recovery re-enables the normal project controls.

This is a coordinated transfer with backup, readback and attempted rollback.
Sample flash replacement is **not power-failure atomic**: an unplugged or powered
off keyboard may need the recovery file. The page does not claim restoration when
the keyboard cannot be reached or verification fails.

## Portable file format, version 1

All binary integers in the files are little endian. CRC values use the standard
CRC-32 implementation shared with `web/x0x_breaks.js` and `.x0xslots` archives.

| Offset | Size | Field |
| --- | --- | --- |
| 0 | 8 | ASCII `X0XPROJ` followed by one zero byte |
| 8 | 2 | Container version, `1` |
| 10 | 2 | Flags: `1` includes samples; `0` is project-only |
| 12 | 4 | Length of UTF-8 JSON metadata |
| 16 | Metadata length | JSON object described below |
| After metadata | Variable | Inner project, then optional `.x0xslots` archive |
| Last 4 bytes | 4 | CRC-32 of every preceding byte |

The file is limited to 4 MiB and JSON metadata to 16 KiB. Unknown versions,
unsupported flags, incompatible schemas, invalid sizes, missing or duplicate
slots, overlapping or unreferenced component ranges, bad CRCs and incorrect sample
identities are rejected.

The metadata has exactly these fields:

- `format`: `"x0xproject"`.
- `version`: `1`.
- `name`: a nonblank project name of at most 80 characters.
- `created`: a date string, normally an ISO 8601 UTC timestamp.
- `project`: `{offset, length, crc32}` for the inner project. Offset is `0`,
  measured from the beginning of the binary body after the JSON.
- `slots`: one entry for each sample slot, in ascending, one-based slot order.
- `archive`: `null` for project-only files; otherwise `{offset, length, crc32}`.
  Its offset is exactly the inner project length.

Every slot entry contains `slot`, source `size` in bytes, and Boolean `empty`.
A populated entry additionally contains `length`, `crc32`, lowercase hexadecimal
`sha256`, `name`, `zones`, `samples` and `rates`. CRC-32 and SHA-256 cover the entire
active image, including all 512 header bytes. `samples` and `rates` describe each
zone in header order. The destination capacity may differ, but the active image
and slot identity must match exactly for a project-only import.

The nested sample archive is the existing `.x0xslots` version 1 format produced
by `makeArchive`: `X0XSLOTS`, two-byte version `1`, two reserved zero bytes,
four-byte JSON length, JSON, concatenated active slot images, and a final CRC-32.
The project importer additionally verifies its slot count and order, identity
metadata, contiguous image ranges, exact body length and every image’s data CRC.
It verifies SHA-256 against the outer manifest. The archive contains no
sample-rate conversion or alternate audio representation.

### Inner firmware project

The inner header is 32 bytes. Each field below is an unsigned 32-bit integer.

| Offset | Field | Version 1 value |
| --- | --- | --- |
| 0 | Magic | `0x50583058`, ASCII `X0XP` |
| 4 | File version | `1` |
| 8 | Payload length | Total inner file length minus 32 |
| 12 | Payload CRC-32 | CRC-32 of the payload |
| 16 | Persistent project format | `1` |
| 20 | Pattern stream format | `3` |
| 24 | Sound revision | `4` |
| 28 | Reserved | `0` |

The payload is the firmware’s canonical current persistent project schema:
settings, sounds, patterns, song and motion data. It contains no sample bytes.
The companion queries the firmware for the exact expected file length instead of
hardcoding the payload size. Matching header versions and CRC do not replace
firmware semantic validation. Incompatible firmware formats are rejected; this
version does not convert them.

## USB MIDI project protocol

Requests are `F0 7D 46 4C 09 op args F7`. Replies use the same header, followed by
`op rc data`. Project operation numbers start at 64, outside Felucca’s legacy
project operations. INFO command 1 must identify `X0X ` before any project command
is sent.

`u21` uses three 7-bit bytes, least significant first. `u14` uses two. Binary data
uses the existing `pack78` sample transfer encoding. Each group has a mask of the
high bits followed by up to seven low-bit bytes. Project chunks contain at most
224 raw bytes.

| Op | Action | Request arguments | Successful reply after command 9 |
| --- | --- | --- | --- |
| 64 | Query / keepalive | None | `64 0 1 totalLength:u21 mode` |
| 65 | Begin export | None | `65 0 totalLength:u21` |
| 66 | Read export | `offset:u21 count:u14` | `66 0 offset:u21 packedBytes` |
| 67 | Begin import / restart recovery | `totalLength:u21` | `67 0` |
| 68 | Write import | `offset:u21 packedBytes` | `68 0 nextOffset:u21` |
| 69 | Validate and adopt import | `58 30` hexadecimal | `69 0` |
| 70 | Abort transfer | None | `70 0` |
| 71 | Save live project | None | `71 0` |
| 72 | Load saved project | `58 30` hexadecimal | `72 0` |
| 73 | Reset live project | `58 30` hexadecimal | `73 0` |
| 74 | Validate staged import | None | `74 0` |

Query’s protocol version is `1`. Mode is `0` idle, `1` export, `2` import, or `3`
recovery hold. Before the first sample mutation in an import, the firmware retains
the original active image lengths and CRC-32 values for every slot, including
empty ones. Sample mutation in import mode requires a successful VALIDATE after
the last project IMPORT/WRITE operation.

After 15 seconds idle, an untouched or fully rolled back transfer can expire
normally. If the original sample images do not match, timeout retains the runtime
hold and exposes mode `3`. ABORT similarly returns busy (`2`) and retains mode `3`
until those original images match. IMPORT can restart staging from mode `3`
without releasing the hold or losing the original sample fingerprints.

The companion refreshes the transfer with Query between sample operations and
rejects an unexpected mode. The active transfer keeps the runtime stopped while
samples are changed or restored. It aborts exports in `finally`; after a failed
import, ABORT either releases a verified rollback or retains the recovery hold.

Return codes are `0` success, `1` arguments/version, `2` busy, `3` offset,
`4` CRC, `5` invalid payload, `6` capacity, `7` storage I/O, and `8` confirmation.
Error replies contain only the operation and return code. The companion checks
the exact reply length, operation and echoed transfer offset. Reads, Query,
Abort and exact replay of the last project WRITE chunk may retry. Import/export
BEGIN, sample mutations, Save, Load, Reset and COMMIT do not retry blindly.

Sample transport reuses commands 11–16. The new project-capable firmware accepts
all **512 bytes** in SMP_END, preserving the reserved header padding; legacy
480-byte callers remain supported. The importer always sends the complete
512-byte area and verifies it after writing.

## Host verification

Run `node web/test_projects.mjs` for container validation, protocol replies,
sample identity and preservation, collision refusal, transfer interruption,
semantic rejection, exact readback and rollback. Run
`node web/test_projects_page.mjs` for the page’s connection, confirmation,
download and recovery controls. The tests include holding the runtime throughout
rollback, mode `3` reconnect recovery, refusal of project-only recovery, and
preservation of the hold on another failure. They use controlled host mocks and do not claim
physical MIDI or flash-power-loss testing.
