# SPEC — scorpiox-scorpioplayer-item-store (`spis_`)

What the player remembers about a user's library: settings, playlists, bookmarks, favourites,
per-item properties, subtitle delays. The C twin of five TPlayer services. Citations are
`tplayer @ 71ca80f6` unless noted (`Core` = `bosxixi.toolkit/bosxixi.ScorpioPlayer.Core`).

| Source | Lines |
|---|---|
| `TPlayer/Services/SettingService.cs` | 256 |
| `TPlayer/Services/FavoritesService.cs` | 224 |
| `TPlayer/Services/PlaylistService.cs` | 84 (+ `Models/Playlist.cs` 232) |
| `TPlayer/Services/BookmarkService.cs` | 79 (+ `Models/Bookmark.cs` 109) |
| `TPlayer/Services/PlayListItemPropertiesStore.cs` | 45 |
| `TPlayer/Services/AppGlobalSettings.cs` | 288 `public static` members → `schema/settings-manifest.json` |

The storage layer (`Windows.Storage.ApplicationData`, `StorageApplicationPermissions.FutureAccessList`)
is UWP-only and is **not** ported. The data model and the rules are.

---

## 1. Decisions

**D1 — The library never opens a file. The host injects the backend.**
`spis_set_backend(const spis_backend *)` supplies `load(scope) -> bytes` and
`save(scope, bytes)`: one blob per scope. The engine owns structure, the host owns bytes on disk.
There is no `fopen` in `src/` (checked by `make test`, `tests/check_no_fs.sh`). The reasons:
(a) the same engine runs on UWP `ApplicationData`, iOS `NSUbiquitousKeyValueStore`/files and
Android `DataStore`, (b) tests run on the built-in memory backend (`spis_use_memory_backend`),
and (c) `--test` physically cannot reach a real store. Only the CLI (`src/cli.c`) does file I/O.

**D2 — Two scopes, LOCAL (0) and ROAMING (1).** C#: `useRoaming ? RoamingSettings : LocalSettings`
(`SettingService.cs:114,137,172`). Every generic key carries a scope. Fixed placements, as in the C#:
- ROAMING: playlists + membership (`PlaylistService.cs:17`), bookmarks (`BookmarkService.cs:17,65,74`).
- LOCAL: subtitle delays (`SettingService.cs:76`), favourites (the FutureAccessList is per-device),
  and per-item properties.

The host decides what "roaming" means. On iOS it is `NSUbiquitousKeyValueStore` (1 MB cap) or an
iCloud document. On Android it is Auto Backup / Block Store, or nothing. On UWP it is `RoamingSettings`.

**D3 — Containers are namespaces, not files.** An explicit `container` argument. `NULL` means
`"settings"` (the C# default, `SettingService.cs:128,165`). Names are 1–65,536 bytes of valid UTF-8.

**D4 — Keys.** 1–65,536 bytes of valid UTF-8. An empty key is `SPIS_ERR_INVALID_ARG`; the C# returned
silently (`:130-133,167-170`). UWP's own limit (255 chars per setting name) is the host's concern.
The engine is tested at 1, 255, 1,024 and 65,536, and 65,537 is rejected.

**D5 — Four value types: STR, I64, F64, BOOL.** Each is stored with an explicit type tag. There is
no guessing from JSON number syntax. A NaN or Inf `f64` is rejected (JSON cannot hold it). The
manifest's `timespan_ms` is stored as I64 milliseconds, and `datetime_yyyyMMddHHmmss` is stored
as STR, as `SetDateTime` does (`:240-243`).

**D6 — A type mismatch on read is an error, not a deletion.** C# `Get<T>` catches the
`InvalidCastException` and **removes the key**, then returns the default (`:186-201`). **Finding F2.**
Here `spis_get_*` returns `SPIS_ERR_TYPE_MISMATCH` and the value is left intact.

**D7 — Missing is distinguishable from zero.** `GetDelay` returns `0` both for "no delay" and a real
zero (`:110`). Every `spis_get_*` and `spis_delay_get` returns a status code and writes through an
out-parameter: `SPIS_ERR_NO_SUCH_KEY` (or `NO_SUCH_CONTAINER`) vs `SPIS_OK` + 0.

**D8 — The change callback replaces `MainView.Instance?.UpdateAppsettingGroup()`** (`:140-150`).
`spis_set_change_cb(fn, ctx)` fires after every successful mutation with
`(scope, container, key, op)`. The C# skipped `LASTPLAYBACKFILEPOSITION` writes; the engine fires for
all of them and leaves filtering to the host. A UI refresh inside the storage layer is a layering bug;
a callback is not.

**D9 — Migrations are expressible, not baked in.** The static constructor deletes the roaming
`LASTPLAYBACKFILEPOSITION` container on first touch (`:19-25`, commit `05c6e402` "sync"). The engine
has no static side effects; a host migration is `spis_arm_destructive(1)` +
`spis_reset_container(ROAMING, "LASTPLAYBACKFILEPOSITION")`.

**D10 — Delay is keyed by whatever the caller passes.** `SetDelay(fileName, …)` keys by **file name**
(`:68-88`), so two different files called `movie.mkv` share one subtitle delay. **Finding F5.**
`spis_delay_set(key, ms)` takes any key; pass a content hash. The storage is the C# layout: LOCAL
container `delayContainer`, I64.

**D11 — Playlists: a name table plus a file→playlist reverse index.** `PlaylistService`
(`id → {Id, Name}`) and `PlaylistServiceContent` (`fileHash → playlistId`), both ROAMING
(`PlaylistService.cs:13-17,49-71`). `spis_playlist_assign(file, pid)` **overwrites**, so one file maps
to at most one playlist in the index, which is what the C# stores. Read that together with **F3**:
the C#'s *real* membership lives in FutureAccessList tokens `"{StableHash(fileHash)}_{playlistId}"`
(`Models/Playlist.cs:121,139,162,183`), which permit many-to-many on the device of origin. Only the
roaming index is one-per-file, so on a second device only the *last* playlist survives. The engine
stores the index and exposes `spis_playlist_token(file, pid)`, which builds the capability-token
string the host needs.

**D12 — Removing a playlist cascades to its index entries.** The C# `Remove(pl)` leaves dangling
`fileHash → pid` rows (`PlaylistService.cs:55-59`), and `RecoverPlaylist` then feeds them to F1.
This is a deliberate divergence.

**D13 — Bookmarks are indexed by file hash, not scanned.** `GetBookmarks(fileHash)` enumerates every
bookmark ever made and filters `Id == fileHash` (`BookmarkService.cs:15-39`). The engine keeps
`key → bookmark` and `file → [keys]`. The results equal the scan (proof in `tests/test_spis.c`,
`bookmark_index_equals_scan`, at 10,000 bookmarks over 500 files).

**D14 — Bookmark labels are generated, never stored.** `Bookmark.Name` is formatted once at
construction with `CONSTANTS.TIMESPANFORMAT = hh\:mm\:ss` (`Models/Bookmark.cs:28-35,69-85`;
`Core/CONSTANTS.cs:33`) and persisted. So changing the format never updates old bookmarks, and the
label cannot follow the UI language. The engine stores the times only, and `spis_bookmark_label(key, fmt)`
formats on demand: `[hh:mm:ss]` for a point, `[hh:mm:ss - hh:mm:ss]` for AB. With `fmt == NULL` the
output is byte-identical to the C#. **This divergence is deliberate.** Tokens: `hh` hours 00-23
(C# `hh` drops whole days, **F6**), `HH` total hours (no wrap), `mm`, `ss`, `fff`, `d` days.
Anything else is a literal.

**D15 — Bookmark type numbering is on disk: `AB = 0`, `Point = 1`** (`Models/Bookmark.cs:93-97`).
A zero-initialised C# bookmark is AB. The engine never relies on a default: `add_point` and `add_ab` set
the type explicitly. A point's `end_ms` is 0 (the C# `EndTime` default). Times are `int64` ms, which
is safe beyond 2^31 (24.8 days). `add_ab` rejects `end < start` and negatives. **Load** accepts a stored
`end < start` with a warning, so old data is never dropped.

**D16 — Bookmark keys come from an injected UUID source.** `Guid.NewGuid()` (`:75,84`). The options:
`spis_uuid_set_cb(fn, ctx)`, or `spis_uuid_use_counter(n)` for deterministic tests
(`00000000-0000-4000-8000-<n:012x>`). With neither, it uses an OS CSPRNG (`getentropy` / `rand_s`),
because keys roam and must not collide across devices. That is not the filesystem. A caller may also
pass an explicit key.

**D17 — Favourites are opaque capability tokens, never paths.** FutureAccessList hands the app a token
for a user-picked folder, and the token is the only way back (`FavoritesService.cs:24-29`). The engine
stores `(token, metadata, display_name)` and never interprets the token. iOS security-scoped bookmarks
and Android SAF persisted URIs have the same shape. `metadata` is a type tag
(`"folder"`, `"file"`, `"playlist"`, `"ms"`: `FavoritesService.cs:22,114`, `Models/Playlist.cs:162`,
`MediaServerDevicesDialog.xaml.cs:55`), and `spis_fav_count("folder")` is `GetFoldersCount()`.

**D18 — Two-form favourite lookup.** `Contains(folder)` tries `folder.Name`, then
`folder.Name.GetStableHashCode().ToString()` (`FavoritesService.cs:59-63`). `AddFolder` falls back to
the hash form when FAL rejects the raw name with `ArgumentException` (`:112-119`, commit `2ca5d067`
2018-06-04 "fix root folder"). **Both forms exist on users' machines.** `spis_fav_contains` and
`spis_fav_remove` try the raw token, then its stable-hash form. `spis_stable_hash(s)` returns the
decimal form for the host.

**D19 — StableHash is reimplemented, not linked (tracker rule 3).** It uses the definition that
`scorpiox-scorpioplayer-media-hash` owns (`Core/Toolkit/Extension.cs:129-153`): DJB2 pair over **UTF-16
code units** decoded from UTF-8, `Math.Abs`, and `int.MinValue → 0` (the C# `OverflowException` is
caught → 0). Invalid UTF-8 → `SPIS_ERR_INVALID_ARG`. Cross-checked against the media-hash vectors in
the unit tests (ASCII, CJK, emoji surrogate pair, empty string).

**D20 — The per-item key is unambiguous.** C# `_file_hash_key = $"{Name}{Uri ?? ""}{Size}"`
(`PlayListItemPropertiesStore.cs:17`) **collides**: `("movie", "", 12)` and `("movie1", "", 2)` both
give `movie12`. **Finding F4.** Its consumer is commented out (`:19-43`), so nothing on disk depends on
it. `spis_item_hash_key` returns `v1:<len>:<name>|<len>:<uri>|<size>`. Pair it with
`spis_item_prop_set/get` (LOCAL) to memoise the expensive content hash; that is the whole point of the
file.

**D21 — Destructive exports refuse unless armed.** `spis_arm_destructive(1)` is explicit. Unarmed →
`SPIS_ERR_NOT_ARMED`, nothing mutated:

| Export | C# | Blast radius |
|---|---|---|
| `spis_reset_scope(scope)` | `SettingService.Reset` / `Clear(bool)` (`:27-67`) | every container in the scope; ROAMING also drops playlists + bookmarks, LOCAL also drops item props. **Not** favourites (separate in the C#, `Utils.cs:809-818`) |
| `spis_reset_container(scope, c)` | `ClearAll` (`:226-238`), static-ctor migration | one container |
| `spis_clear_where(scope, c, prefix)` | `Clear(Func<string,bool>, …)` (`:112-127`), used as `StartsWith` in `AI.cs:861-892` | the keys with that prefix. A prefix, not a callback: every real caller is a prefix, and a callback across P/Invoke is a footgun |
| `spis_playlists_reset()` | `PlaylistService.Crash()` (`:31-48`) | all playlists + index |
| `spis_favourites_reset(confirm)` | `FutureAccessList.Clear()` (`FavoritesService.cs:16-19`) | ☢️ every folder permission. Also needs `confirm == "REVOKE-ALL-FAVOURITES"` |
| `spis_migration_apply(plan)` | (no C# twin — the C# never migrated) | copies legacy-keyed rows to v2 keys for `unique` entries; deletes nothing (D26–D28) |

`spis_remove`, `spis_playlist_remove`, `spis_bookmark_remove`, `spis_fav_remove` delete one named
thing and are not armed, the same as the C#'s single `Remove` calls.
`spis_migration_plan` and `spis_migration_resolve_on_open` are not armed either: the former is
pure and read-only; the latter copies one user-named file's rows on a user action and deletes
nothing (D28).

**D22 — Load is atomic and a corrupt store is never overwritten.** Each scope is parsed into a fresh
state and swapped in only on success. If the blob is not JSON, not our format, or a **newer**
`version`, then `spis_load` returns `SPIS_ERR_SERIALIZE`, the scope is flagged (`spis_scope_load_failed`),
and `spis_save` **refuses to write that scope** until it loads cleanly or is reset (armed). A bad
*entry* inside a good file (wrong type tag, missing field, a duplicate key, a record in the wrong scope)
is moved into `quarantine` with a warning. The rest loads, and the quarantined raw JSON is written back on
save. Unknown top-level keys are preserved verbatim, which gives forward compatibility.

**D23 — Schema is a generated manifest, not 288 accessors.** `tools/gen_schema.py` reads
`AppGlobalSettings.cs` + `Models/DefaultValue.cs` (Release branch of `#if DEBUG`) and writes
`schema/settings-manifest.json`. All 288 members are accounted for: 254 settings + 34 excluded, each
with a reason. The script asserts the sum. 62 settings are roaming, 235 have literal defaults and 19
have platform defaults (the host supplies those). **1 resisted**: `IsCurrentVersionUpdateInfoShowed`,
whose key is `AppInfo.PackageVersion`, a runtime value. 5 developer-LAN defaults were emptied.
Settings are addressed by **name**, because storage keys are not unique (`FFmpegVersion` is shared by
3 names in `InAppDefaultSettingAccessor`). The same file is the artifact `template-parse` consumes for
RuntimeConfig defaults.

**D24 — All JSON goes through vendored yyjson 0.12.0.** Both the on-disk format and every JSON return
value. There is no hand-rolled scanner.

**D25 — Threading: single-threaded, all state global.** The host serialises calls. Every returned
`const char *` is library-owned and valid until the next string-returning `spis_*` call. This matches
the fleet convention (template-parse).

**D26 — Migration is plan-then-apply, and the plan is pure (v1.1.0).** Existing users' stores
key user state by the *colliding* legacy id: bookmarks by `GetStableHashCode(file name)`
(`BookmarkService.cs:23`), last position by the same id in ROAMING `LASTPLAYBACKFILEPOSITION`
(`Events.cs:192,451`, `PlayListItem.cs:528`), last file by `Base64(folder name)` in ROAMING
`LASTPLAYBACKFILENAME` (`LoadFolderAsync.cs:241-242`, `Events.cs:930-933`), subtitle delay by
**file name** in LOCAL `delayContainer` (F5), and per-item properties by the F4/D4 legacy item
key. v2 keys are unambiguous (`playlist-folder-model` §9: `stable(backend \u0001 path \u0001 name)`),
and one legacy key maps to **N** v2 keys (one per folder the file was seen in) — the stored data
cannot say which folder it came from, so the engine must not guess silently.

`spis_migration_plan(listings_json)` is pure and read-only: no arm flag, no mutation, no save.
The listings are the `playlist-folder-model` item JSON the shell has already loaded (its
`result_json` carries `id` and `legacy_id` per item, both byte-exact — §9 of that SPEC, 666/666
vectors against the real C#). Accepted shapes: a root array of listings; a root object with a
`listings` array; one listing (an object with an `items` array, or a bare array of items). Each
item is `{"name":…,"id":"<v2>","legacy_id":"<legacy>","delay_v2":"<content hash, optional>"}`;
items missing `id`/`legacy_id` are skipped and counted (`bad_items`). The plan groups:

- **id entries** `(legacy_id → {v2 id})`: for every legacy id present in *any* id slot of the
  store (bookmark file_hash, `LASTPLAYBACKFILEPOSITION`, `LASTPLAYBACKFILENAME`,
  `LASTPLAYBACKPLAYLISTFILENAME`, `item_props`), the distinct v2 candidates across **all**
  listings. `unique` (1) / `ambiguous` (>1) / `orphan` (0). Legacy ids present in the listings
  but in no store slot are `skipped`.
- **delay entries** `(name → {delay_v2})`: the delay container is keyed by file *name* (F5), a
  different keyspace, so it plans on `name` → the optional `delay_v2` content hash. Only names
  present in `delayContainer` are classified; the rest are `skipped`.

Plan JSON: `{"version":1,"counters":{…},"items":[{legacy,v2[],status}…],"delay":[…]}`,
deterministically sorted by legacy key, candidates deduped and sorted.

**D27 — Apply is armed, copy-only, idempotent, and never deletes.**
`spis_migration_apply(plan_json)` refuses `SPIS_ERR_NOT_ARMED` unless
`spis_arm_destructive(1)`. For each **unique** entry (id group *and* delay group) it copies:

| Slot | Scope | Legacy key | Copy rule |
|---|---|---|---|
| bookmark | ROAMING | legacy id | new bookmark under the v2 file hash, new key from the uuid source, same type/start/end; skipped if an equal (type,start,end) bookmark already exists for the v2 file (content-dedup) |
| `LASTPLAYBACKFILEPOSITION` | ROAMING | legacy id | copied **only if the v2 key is absent** (a newer v2 position is never clobbered) |
| `LASTPLAYBACKFILENAME` | ROAMING | legacy id | same (value may be a name or an id, per source) |
| `LASTPLAYBACKPLAYLISTFILENAME` | ROAMING | legacy id | same |
| `delayContainer` | LOCAL | file name (delay group) | i64 copied only if the v2 (content-hash) key is absent |
| `item_props` | LOCAL | legacy id | the whole property map copied if the v2 key is absent |

Ambiguous and orphan entries are **not** copied by apply. **Legacy rows are never deleted or
modified** (the shell owns deletion, via the armed destructive exports, once it has verified the
v2 copies). Idempotency follows from the copy rules: a second `apply` copies 0 and the blob is
byte-identical. On success the marker LOCAL `spis_migration` / `"legacy-v2"` = 1 (I64) is written
if absent; `spis_migration_version()` reports 0 (never) / 1 (migrated).

**D28 — Ambiguous entries resolve lazily, one file at a time (decision).** The alternative —
copying an ambiguous legacy value to *every* candidate — was rejected: it duplicates user data
N-fold, the copies go stale independently the moment the user edits one of the files, and any
"only if the position is small" heuristic (e.g. ≤ 5 min) is backwards (a long position is the
*more* identifying one) and the store does not know file durations anyway. So:
`spis_migration_resolve_on_open(legacy_key, v2_key)` is what the shell calls when the user opens
the exact file — the shell then knows both the legacy key and the v2 key for *this* file, and
the guess is no longer a guess. It runs the same `copy_slots` rules as apply (content-dedup for
bookmarks, absent-only for everything else) and returns the number of rows copied; it is
idempotent and needs **no arm** — it copies one user-named file's rows on a user action and
deletes nothing, the same class as `spis_playlist_assign`. Orphans need no action: the legacy
row simply stays until a future listing finds a candidate. Delay entries resolve the same way:
the shell opens the file, computes the content hash (memoised via `spis_item_prop_set`, D20) and
passes it as the v2 key.

## 2. On-disk format (one blob per scope)

```json
{"format":"scorpiox-item-store","version":1,"scope":"roaming",
 "containers":{"settings":{"Volume":{"t":"f64","v":0.5},"Muted":{"t":"bool","v":false}}},
 "playlists":{"<pid>":{"name":"Road trip"}},
 "playlist_members":{"<fileHash>":"<pid>"},
 "bookmarks":{"<key>":{"file":"<fileHash>","type":1,"start_ms":1234,"end_ms":0}},
 "quarantine":[{"path":"bookmarks/<key>","why":"…","raw":{…}}]}
```
LOCAL holds `containers`, `favourites` (`{"<token>":{"metadata":"folder","name":"Movies"}}`)
and `item_props` (`{"<itemKey>":{"<prop>":"<value>"}}`). `t` ∈ `str|i64|f64|bool`.

## 3. Error taxonomy

`SPIS_OK 0` · `NO_SUCH_KEY -1` · `NO_SUCH_CONTAINER -2` · `TYPE_MISMATCH -3` · `NOT_ARMED -4` ·
`NO_BACKEND -5` · `SERIALIZE -6` · `INVALID_ARG -7` · `OOM -8` · `BACKEND -9` · `NO_SCHEMA -10`.
`spis_last_error()` holds the message.

## 4. Findings in the C#

| # | Sev | Where | What |
|---|---|---|---|
| F1 | **P1** | `Views/LoadFolderAsync.cs:257-282` (`867c5f3e` 2018-06-03) | `RecoverPlaylist` intersects the mapped file hashes with the folder, then adds **every** mapped file to **every** playlist (`foreach pls × foreach inter → item.Add`). The `playlistId` in the map is never read. Opening a folder that holds one file of playlist A puts it into B, C… too, and each `Add` rewrites the roaming map to whichever playlist came last |
| F2 | **P1** | `SettingService.cs:186-201` | A type mismatch on `Get<T>` **deletes the stored value**. One code path that reads a key with the wrong `T` (e.g. `SettingsAccessor` string vs `SettingService` bool for the same key) silently erases the user's setting |
| F3 | P2 | `Models/Playlist.cs:121-228` vs `PlaylistService.cs:62-71` | Membership has two sources of truth: FAL tokens (many-to-many) and the roaming index (one-per-file). `Remove(item, fh)` deletes the index row whichever playlist it pointed to |
| F4 | P2 | `PlayListItemPropertiesStore.cs:17` | `Name+Uri+Size` concatenation collides (`movie`,12 vs `movie1`,2). Latent: the consumer is commented out |
| F5 | P2 | `SettingService.cs:68-110` | Subtitle delay is keyed by file *name*, shared across different files of the same name |
| F6 | P3 | `Models/Bookmark.cs:21,30` | `TimeSpan.ToString("hh\:mm\:ss")` drops days: a bookmark at 25:00:00 displays `[01:00:00]` |
| F7 | P3 | `FavoritesService.cs:65-76,89-100,124-137` | Favourites only work for `LocalStorage` (+`BluRay` for files); `ScorpioServerItem/Ftp/Http/Smb/WebDav` cases are empty and return `false` |
| F8 | P3 | `FavoriteContentDialog.xaml.cs:301`, `Features/Favorite.cs:50` | The 10-folder favourites cap is UI policy, not storage. The engine does not enforce it; `spis_fav_count("folder")` lets a shell do so |

## 5. Open questions (not guessed)

- Q1: The UWP roaming quota (100 KB) will not hold 10,000 bookmarks. Whether the host should shard
  roaming, or move bookmarks to local plus a sync endpoint, is a product call.
- Q2: Migrating existing UWP `ApplicationData` into this format needs a UWP-side exporter, which is out of scope here.
- Q3: `TryMigrateBookmark` (`BookmarkService.cs:40-61`, obsolete since 2018-09) is not reproduced.
