# SPEC — scorpiox-scorpioplayer-template-parse

SCORPIO PLAYER 2027 engine #1: the dynamic UI template engine. The server sends `SetttingsGroup` JSON
templates (settings, context menus, onboarding, paywall, add-server, and the settings screens of dozens of Store apps).
Legacy shells run two passes over each template: `ApplyPlatform<P>` then `Clean`. After that, a hand-written
renderer draws about 23 widget types.
This engine turns a template into a flat render list for one platform, one language and one
set of runtime flags. It works offline and does no rendering or behaviour of its own.

**Legacy code is the spec, not the source.** The C was written from this document. This document
was written from the code and its history, and every rule below was **measured** against the real
`TableView.cs`. `tests/oracle/` compiles that file unmodified against Newtonsoft.Json 13.0.3, and
`tests/diff.sh` compares the two engines on every template.

| Spec source (read-only) | Revision |
|---|---|
| `bosxixi.toolkit/bosxixi.ScorpioPlayer.Core/Toolkit14/TableView.cs` (623 lines, 39 commits) | `820d6c0` (2024-07-24, "2.0.562") |
| `tplayer/TPlayer/Adapters/Utils.cs:678` `CleanGroupInApp` | `71ca80f` |
| `tplayer/TPlayer/App.xaml.cs:371` `Initializer.Run(HasFeatureFlag)` / `Services/RuntimeService.cs` | `71ca80f` |
| `Platform/IOSLegacy/.../IOSMainPage.xaml.cs:210` `CreateContextMenu`, `Adapters/Class1.cs:1829` `GetGroup` | frozen |
| `bosxixi.ScorpioPlayer.Core/Localization/Tool.cs` (`Get`), `TPlayer/Extensions/Extension.cs:33` (`Translate`) | `820d6c0` |
| `bosxixi.ScorpioPlayer.Core/System.cs:414` `FromJSONObject<T>` (Newtonsoft settings) | `820d6c0` |
| Live bundle `POST gcp.scorpioplayer.com/api/AAA/RuntimeTemplates?zip=true` | 2026-09-25: 301 entries / 126 `.json` / 16 languages × 2,799 keys |
| Shipped bundle `TPlayer/Assets/package/runtimetemplatebundle.txt` | 180 entries / 55 `.json` |

---

## 1. Bundle

R1. A bundle is zlib (RFC 1950, wbits 15) or plain JSON: `{ "<file name>": "<content string>" }`. Entries
include `.json` templates, `.html` pages and base64 `.png`s. **Templates are entries whose name ends in `.json`.**
Not every `.json` is a `SetttingsGroup` (`gptmodels.json`, `deviceicons.json`, `strings.json`...). Those
parse as groups with no `Settings` and render empty, exactly as `FromJSONObject<SetttingsGroup>` does.

R2. Any entry whose value is not a string means this is not a bundle (it is probably a single template):
`sptpl_load_bundle_*` returns 1 and **keeps the previous bundle**. Use `sptpl_add_template`.

R3. zlib is detected by header (`CM=8`, `(CMF·256+FLG) % 31 == 0`), inflated with vendored miniz `tinfl`
(adler-32 checked, output capped at 512 MB).

## 2. Data model (verbatim names — the misspellings are load-bearing)

```
SetttingsGroup   Key DisplayName Type UseGrid  Settings[]  Extension  RuntimeSettings{} RuntimeFlags{}
 └ Setting       Key DisplayName DefaultValue  Items[]     Extension
    └ Item       Key DisplayName Type DefaultValue  Group(SetttingsGroup, recursive)  Values[](Item)
                 AdvanceMenu  PlaceHolder{Key,DisplayName}  SubtitleText{Key,DisplayName}  Extension  RuntimeSettings{}
PlatformExtension  Common iOS tvOS UWP Droid SkiaMacOS (PlatformConfigBase)  FallbackIconUrl FallbackIconBase64 FeatureFlag Clean(bool)
PlatformConfigBase Enabled MinVersion MaxVersion Icon TextColor ... (+ UWP: Plat PlatEdition; iOS/tvOS: ~45 UIKit hints)
AdvanceMenu        Url UseWebView UseLanucher AttachUserInfo AttachItemInfo NativeHandlerCode OrderIndex Group IOSIcon ...
```

`SetttingsGroup` (three t's), `UseLanucher`, `MaxMinVerionCapping` and the `Bookmard`/`Graghic` string keys are
spelled that way in shipped data. Never "fix" them.

Live measurements (126 templates): 3,067 items, max nesting depth 3. Extension slot use: iOS 7,581 · UWP 1,547 ·
tvOS 871 · Droid 147 · SkiaMacOS 61 · FeatureFlag 53.

## 3. Tolerance

The engine never fails a whole template because of one bad node. Every tolerated oddity is a warning
(`sptpl_warning*`):

| Input | Legacy (measured) | Here |
|---|---|---|
| `Type` not a widget: `WhisperUI.Apps.Downloader.Aria2NgPage` (9), `Rating:dioButton` (6), `""` (12) | passes through | passed through verbatim |
| `Settings`/`Items`/`Values`/`Group` absent, `null` or `""` | null | null (absent ≠ empty is kept: see R22) |
| `Items: ["UpdateNotesItems"]` (**live `worldssettings.json`**), `Values: ["WhisperSourceLanguages"]` (**live `transcribeprosettings.json`**). Server-side placeholders that `runtimeconfig/SFSymbolsToSegoeMDL2.cs` failed to substitute | **throws: the whole template fails to load in every legacy client** | element skipped, warning, rest renders. Report finding F1 |
| `null` element in `Settings`/`Items` | NullReferenceException in `Clean` | skipped + warning |
| object/array where a string is expected; non-empty string where an object/list is expected | throws | treated as null + warning |
| invalid JSON, trailing garbage, BOM, NaN/Infinity | throws | invalid → `-1`; the rest tolerated + warning |
| `"$ref"`/`"$id"`/`"$type"` properties | Newtonsoft metadata | ignored (none in either bundle) |
| nesting > 256 levels | Newtonsoft `MaxDepth` 64 throws | truncated at 256 + warning |

## 4. Parsing = Newtonsoft population semantics (measured, 90+ probes in `tests/diff_corpus` + unit tests)

R4. Property names bind **exact first, then ASCII case-insensitive** (`settings`, `ITEMS`, `key` all bind).
There is **no non-ASCII folding**: `ſettings` (U+017F), `Kelvin K` (U+212A), `ıtems` (U+0131) do not bind.

R5. Duplicate properties: a scalar is **last-wins**. An object that already holds an object is **merged**
(Newtonsoft populates the existing instance). A list that already holds a list is **appended to**. An
explicit `null` resets either one, and `""` does the same for object and list properties.

R6. Numbers and booleans read into string properties **keep their JSON text**: `"Key": 1.0` → `"1.0"`,
`1e2` → `"1e2"`, `true` → `"true"`. Big numbers are kept verbatim (`NUMBER_AS_RAW`).
Consequence: `"Enabled": true` is `"true"`, which is not `"True"`, so the item is **hidden** (R16).

R7. `RuntimeSettings`/`RuntimeFlags` are `Dictionary<string,string>`: keys are **ordinal (case-sensitive)**
and values keep their raw JSON text.

R8. JSON5-ish input is accepted like Newtonsoft accepts it: comments, single quotes, unquoted keys and trailing
commas. Empty or whitespace text and the literal `null` give "not a template" (`-1`), as `FromJSONObject`
returns null.

## 5. Visibility — the algorithm (TableView.cs @ 820d6c0)

Legacy mutates the tree. Each pass writes its verdict into **`Extension.iOS.Enabled` on every platform**, and
the final test reads that slot. Here the verdict `V` is computed per item without touching the tree:

R10. **Seed.** `V := item.Extension.iOS.Enabled` from the template itself, which may be null. The iOS slot
does double duty: it is the template's iOS setting *and* the scratch slot. So **an iOS `"False"` hides the item
on UWP, tvOS, Droid and Skia too**, unless something later overwrites `V`. (95 live items set only
`iOS.Enabled="False"`.)

R11. **Platform pass, UWP** (`ApplyPlatformUWP(device, edition, appVersion)`, :14–79). Here `E` is `Extension.UWP`:
1. `E.Enabled == "False"` → `V := "False"` (`EnabledCapping` :154)
2. `E.Enabled == "True"` → `V := "True"`; then `E.Plat != null && E.Plat != device` → `"False"`;
   `E.PlatEdition != null && E.PlatEdition != edition` → `"False"` (:30–48)
3. version capping (R14) with `E.MinVersion`/`E.MaxVersion`
4. `V == "True"` → the Plat/PlatEdition checks again (:52–71). Version capping can revive an item, and this
   re-hides it on the wrong device.

TPlayer calls it as `ApplyPlatformUWP(DeviceFamily, XboxEdition.IsActive ? "XboxEdition" : null,
PackageVersionNumber)` (`Utils.cs:689`).

R12. **Platform pass, tvOS/Droid/SkiaMacOS** (:80, :129, :104): `EnabledCapping` with that platform's `Enabled`,
then version capping with its Min/Max. **There is no `"True"` branch**, so `tvOS.Enabled="True"` never revives
an iOS `"False"`. `Droid.Plat`/`SkiaMacOS.Plat` are **never read**.

R13. **Platform pass, iOS** (:208): version capping only. There is no `EnabledCapping`, because the slot *is*
iOS's own `Enabled`.

R14. **Version capping** (`MaxMinVerionCapping` :166). This only runs if `appVersion` is non-empty **and** parses (R15):
- `MinVersion` non-empty and parseable → `V := app < min ? "False" : "True"`
- **then** `MaxVersion` non-empty and parseable → `V := app > max ? "False" : "True"`

  Consequences, reproduced exactly (see Findings):
  - a satisfied Min/Max **overwrites an explicit `Enabled:"False"`** (50 live UWP items combine version +
    `Enabled:"False"`)
  - when both are present, **Max alone decides** and Min is ignored (live: `settings.json` `FFmpegVersion` ×2,
    `FFMPEG3xAdvanceDecodingSetting`)
  - an unparseable bound is ignored entirely, and so is an unparseable app version

R15. **`System.Version.TryParse`** (.NET 8, 60 probes, table in `tests/test_sptpl.c:test_version`):
- the string has 2–4 components separated by `.`
- each component is `int.TryParse(Integer, Invariant)`: optional `[\t\n\v\f\r ]`, an optional sign, digits,
  optional whitespace, optional trailing `\0`s. The value must be 0 to 2^31−1, and `-0` is valid.
- missing components are **−1**, and comparison is component-wise. So `1.2 < 1.2.0`, `3.3900 > 3.3835`, and
  `" 1.2"`, `"1. 2"`, `"+1.2"`, `"01.02"` all parse.
- `"1"`, `"1.2."`, `"1..2"`, `"1,2"`, NBSP, full-width digits and `2147483648.x` all fail.

R16. **Final verdict** (:282): visible ⇔ `V == "True" || V == null`. **Absent is visible, and anything else hides.**
That covers `"False"`, `"Flase"` (8 live items), `"false"` (2 live), `""`, `"true"` and `"TRUE"`.

R17. **Feature flags** (`Clean` :244–283). These run after the platform pass and **overwrite `V` unconditionally**:
1. if `Extension.FeatureFlag` is non-empty **and** a global predicate is installed
   (`Initializer.CurrentOption.HasFeatureFlag != null`): `V := predicate(ff) ? "True" : "False"`
2. then, if the runtime flag dictionary is non-empty: `V := HasFeatureFlag(ff, runtimeFlags) ? "True" : "False"`

  So a flag **revives a platform-disabled item** (38 live `contextmenu.json` items carry both
  `iOS.Enabled:"False"` and a flag, and the flag is the real switch). Step 2 also **replaces** step 1 whenever
  any runtime flag exists. TPlayer always passes at least `ENDPAD`, so a bare flag like `"SA"` or `"Xbox"` is
  **always hidden in TPlayer**, whatever the global predicate says. Commit history: `26fc044` (2022-10-29)
  introduced `runtimeFlags`. `7a03f8f`/`aebff72`/`52e5dc8`/`f1eb843` (same day) removed the
  `iOS.Enabled == "True"` precondition and made both steps assign True/False rather than only False.

R18. **`HasFeatureFlag(flag, container)`** (:232): the flag is non-empty, `flag.Split(':')` has **exactly 2**
parts, the container is non-empty, and `container.TryGetValue(part0) == part1` is an ordinal, case-sensitive
comparison. `TryGetValue` returns null for a missing or empty key, and null never equals a string. So:
`"SA:true"` ≠ `SA=True`, `":True"` → false, `"a:b:c"` → false, `"K:"` matches only a **present** `K=""`.

R19. **Global predicate.** TPlayer (`App.xaml.cs:373`) answers true for `"Xbox"` on an Xbox, or when
`ConstantValues.FeatureFlags[flag].Value == "true"` (case-insensitive), or when `ffsp.json`'s
`Settings.First(Key==flag).DefaultValue` passes `bool.TryParse`. In C that becomes a set of names
(`sptpl_set_global_flag`), plus `sptpl_use_bundle_feature_flags()` which loads the ffsp part. Clients that do
not install the predicate map to `sptpl_set_global_flags_enabled(0)`; the IOSLegacy `GetGroup` paths are one
example. Default is **on**, matching every legacy app.

R20. **Recursion.** Both passes recurse into `Item.Group` of **every** item, hidden ones included. A hidden
item's group is simply not reachable. `Values` are **not** processed by either pass: shells show `Values` as-is.
The engine returns them unfiltered, with each value's own `enabled` field.

R21. **Empty sections** (:286): with `cleanEmptyContainer` (default true), a Setting whose visible item list is
empty is dropped. That includes `Items` null, `[]` or `""`. Nested groups receive the same flag (`3dfc0df`).

R22. **`Setting` order and item order are preserved.** `AdvanceMenu.OrderIndex` is **not** a sort key in
`TableView.cs`.

## 6. The three mutation defects — decisions

| Legacy behaviour | Decision |
|---|---|
| Both passes **mutate the parsed tree** and return it. Rendering twice gives a different answer (the second `ApplyPlatform` reads the first one's scratch values), so callers `Clone()` with a JSON round-trip | ❌ **not reproduced.** The tree is parsed once and is immutable. `sptpl_render` computes `V` locally and emits a fresh list. Proven by the "render is pure" unit test and by the differential test (which renders every template 16× in one process) |
| `Extension.iOS.Enabled` is the scratch slot for every platform | storage ❌ not reproduced; **outcome ✅ reproduced**, including R10 (an iOS value seeds every platform) |
| Tri-state stringly booleans, null = visible | ✅ reproduced exactly (R16) |

## 7. Translation

R23. `strings.json` in the bundle is `{lang: {key: text}}` (16 languages).

R24. **What is translated is the `Key`, not the `DisplayName`** (`ITranslatable.Translate`, `Extension.cs:33`):
`tl = Key.Translate(); tl != Key ? tl : (DisplayName ?? Key)`. Live data: 3,847 of 9,366 translatables have a
`Key` in `strings.json`. The task draft assumed DisplayName; that was corrected here.

R25. `Key.Translate()` = `Tool.Get(key)`, measured from `Tool.cs`:
`lang` → base of `lang` (`zh-Hant` → `zh`) → **`en-US`** → `en` → the key itself. A present but **empty** text
counts as missing. Platform resource fallbacks (`RL.GetString`, `NSBundle`) are out of scope; they return the
key.

R26. Field `text` = R24 applied to the node. `display` = raw DisplayName. `subtitle`/`placeholder` = R24 applied
to `SubtitleText`/`PlaceHolder`.

## 8. Render list (the contract every shell binds to)

R27. `sptpl_render(template, page)` emits the visible tree **depth-first, in document order**, flattened:
a `section` node for each surviving Setting, followed by its `item` nodes. After each item with a `Group`
come that group's nodes at `depth+1` (`sptpl_set_max_depth` limits this; 0 = page only).
Each node carries `parent` (the index of the owning item, −1 at the page root) and `path`
(`Key/Key/...`, used as the `page_key` to open that sub-page).

R28. `page_key` walks the **raw** tree (the first item with that `Key` and a `Group` at each level), the way
IOSLegacy does it (`Items.FirstOrDefault(c => c.Key == "IMDbId").Group`). If the item is hidden it still
renders, with a warning. The live `contextmenu.json` root item `IMDbId` is `iOS.Enabled:"False"`, and every
client opens it anyway. `sptpl_render_section` keeps only the named Setting(s): this is
`CreateMenusByNode(group, nodeName)`.

R29. `handler`: for `Type` starting with `NativeHandler`, it is `DefaultValue` (`Utils.cs:262`
`ConstantValues.NativeHandlers[selectedItem.DefaultValue]`). Otherwise it is `AdvanceMenu.NativeHandlerCode`.
The engine names handlers and never invokes them; that is row 22, `native-handler-registry`.

R30. `icon` = `Extension.<current platform>.Icon`. Every other hint is available raw through `ext.<P>.<Name>`,
`am.<Name>` and `rs.<Name>`.

## 9. Findings (legacy defects, reproduced unless stated)

| # | Finding | Impact |
|---|---|---|
| F1 | Live `worldssettings.json` and `transcribeprosettings.json` **do not deserialize in any legacy client**: `Items:["UpdateNotesItems"]` and `Values:["WhisperSourceLanguages"]` are unsubstituted placeholders from `runtimeconfig` (`SFSymbolsToSegoeMDL2.cs:153,295`) | those two screens are blank or crash in production. The C engine renders the rest and warns. Fix it in the `runtimeconfig` sync (out of scope, backend) |
| F2 | `MaxMinVerionCapping` Max overrides Min (R14) | an item limited to "2.10.1186–2.10.1211" is visible on **every** version ≤ 2.10.1211, including older than 1186 |
| F3 | Version capping revives explicit `Enabled:"False"` (R14) | 50 live UWP items. `Enabled:"False"` plus a MinVersion means "on from version X", which may be intended |
| F4 | Runtime flags silently replace the global predicate (R17) | a bare `"SA"` flag can never show in TPlayer (it always passes `ENDPAD`) |
| F5 | `"Flase"` ×8, `"false"` ×2, `true` → hidden (R16) | they happen to mean "hidden", so it works by accident |
| F6 | `iOS.Enabled` seeds every platform (R10) | 95 items set only iOS `"False"` and are therefore hidden on UWP/Android too; this looks intended ("False everywhere unless the platform says True") |
| F7 | Plat/PlatEdition are ignored when `UWP.Enabled` is absent and the slot is null (R11) | `{"UWP":{"Plat":"Xbox"}}` shows on Desktop. There are no live occurrences |

## 10. Open questions (not settled by the code — written down, not guessed)

- Q1. Should a native shell honour `Extension.Clean` (IOSLegacy `SettingsUINavigationController.cs:557` runs
  `Clean()` again with **no flags** when opening a PageGroup whose group has `Clean:true`)? Only 2 live uses.
  For now it is exposed as `ext.Clean` and the shell decides.
- Q2. `OrderIndex` on AdvanceMenu (live values 1..n) looks like it was meant to sort menu buttons, but no
  code sorts by it. It is exposed as `am.OrderIndex`.
- Q3. `ENDPAD` (`{device}{!china}{!xbox}`, `Utils.cs:687`) is TPlayer-specific. Shells compute it and pass it
  as a runtime flag. The engine does not know about China or Xbox.

---

# v1.1.0 — the TV form factor: focus graph + remote actions

> **Shipped as v1.1.0, re-published as v1.1.1** — v1.1.0 was published to dist on 2026-11-19, then the fuzz
> run found the `parse_int` overflow (§18). v1.1.1 is v1.1.0 plus that one fix and **nothing else**; every
> measurement below holds for both. `verified/1.1.0` stays on dist so nothing that already bound it breaks.

Additive. Every rule R1-R30 and **the render list are unchanged** (the 12,464-case differential of
v1.0.0 still passes, byte-identical: **12,496/12,496** under exactly the same 16 configs × (55 shipped + 126 live + 600 generated) — v1.0.0 reported 12,464 + 32 legacy-throws, and the 32 are the two `runtimeconfig`-broken live templates that were fixed the next day).
What is new is a second, pure layer **over** the render list: where focus can go, and what a remote
control press means. A shell translates its native event into an action name and calls
`sptpl_focus_apply(name)`; it holds no focus logic of its own.

| Extra spec source (read-only) | What it settles |
|---|---|
| `Platform/TVOSLegacy/MoviesFinder.tvOS/SettingsViewController.cs` (`DidUpdateFocus`, `RowSelected`, `SettingsGridViewController`) | tvOS focus is a table/grid index pair; a `UseGrid` page pushes a grid controller, everything else a list |
| `Platform/IOSLegacy/MoviesFinder/MoviesFinder.Shared/Natives/SettingsUINavigationController.cs:537` | `origin.UseGrid == "True"` → `SettingsGridViewController`, else list. This is **R31's** column rule |
| `Platform/IOSLegacy/DroidLib` (Leanback rows, `KEYCODE_DPAD_*`) | the D-pad row/column semantics of R34 |
| `tplayer/TPlayer/Services/HotkeyService.cs` (`KeyMaps`, `GetHotkeys`, `FindByKey`) | the action vocabulary and the one rule that matters: **on Xbox with a gamepad, the D-pad and the shoulders are focus keys, not hotkeys** (`FindByKey` returns null for `GamepadDPad*` / `Gamepad*Shoulder` when `DeviceFamily.Xbox && !UsePointer`) |
| `tplayer/TPlayer/Features/Hotkey.cs`, `Features/Gestures.cs` | transport/system actions; the `HotkeyAction_*` legacy names reused in R40's table |
| HDMI-CEC 1.4 §CEC 13 **UI Command** table (`linux/cec.h` `CEC_OP_UI_CMD_*`, 0x00-0x76) | the TV remote's own vocabulary, 1:1 into actions |
| `linux/input-event-codes.h` `KEY_*`, `Windows.System.VirtualKey`, `android.view.KeyEvent` | the three OS key-code spaces |

## 11. Form factor (R31)

R31. `sptpl_set_form_factor("tv"|"desktop"|"handheld")` (default `desktop`) selects the layout policy.
The **render list never changes**; only the columns the focus layer computes. Columns, highest
precedence first:
1. `sptpl_set_tv_columns(n>0)` — an explicit shell override.
2. The page group's `UseGrid == "True"` → `Extension.iOS.SuggestColumnCount` when it parses to 1..32, else **5**
   (the Leanback default grid).
3. Otherwise **1** (a list page).
   `sptpl_set_tv_rows(n)` (default 10) is the screenful used by `pageup`/`pagedown`.
   `sptpl_set_tv_safe_inset(pct)` (default 5, clamped 0..25) is **reported, not applied** — a shell owns
   its margins; it is in `sptpl_tv_layout_json()` so a shell has one source for the TV-safe box.
   Measured on the live bundle: **3 of 126** templates are `UseGrid:"True"` pages at the root; every
   entered grid page carries it in its own group.

## 12. What is focusable (R32)

R32. A node is focusable iff it is an **item drawn on the current page** (`kind == item` and `depth == 0` —
deeper nodes belong to a child page and are reached by entering it) and it is not excluded:
- `Extension.<platform>.Focusable` present and not `true` → never focusable (`"True"` forces it);
- `Type` ending in `PreProcess` → a pre-process step, not a control.
  **Neither key occurs in the live bundle**, so this rule is currently a no-op that a server template or a
  shell may use. Bumping it into the live corpus is a server change, not an engine change.

## 13. Focus identity and the graph (R33)

R33. `sptpl_focus_build(template, page)` renders the page **and** builds the graph in one call, so the list
the shell draws and the graph it navigates cannot disagree. The graph is the render list's focusable
items, in render order, each carrying: `rnode` (render index), `sec` (section ordinal on the page),
`row`/`col` inside that section's grid, and `path` (the item `Key` chain — the **focus identity**, the same
string the render list already publishes). A focus index is a focus-graph index, never a render index;
`sptpl_focus_field(i, "index")` gives the render index when a shell needs it.

## 14. Movement (R34-R35)

R34. `up`/`down`: same column, one row; clamped inside the section (a short last row clamps to its last
cell), then the **neighbouring section's** first/last row at the same column. Empty sections are skipped.
R35. `left`/`right`: ±1 cell **inside a grid section only**, and only when the cell stays on the same row.
In a single-column (list) section they do not move — at a TV, left/right is the pane/sidebar gesture and
the shell owns it. `pageup`/`pagedown` = ±(rows×cols) clamped to the section. `first`/`last` = the first/last
focusable node of the page. A move that would leave the graph returns −1 and the focus does not move.
`DefaultFocus`: the first focusable node whose item carries `Extension.<platform>.DefaultFocus == "True"`,
else the first focusable node, else −1 (empty page).

## 15. Refresh (R36-R37)

R36. `Extension.<platform>.DefaultFocus` (see R35). R37. `sptpl_focus_child_page(i)` returns the page key of a
node that owns a `Group`, **root-relative** (`page "About"` + node path `"Privacy"` → `"About/Privacy"`), so
the answer can be handed straight to `sptpl_focus_build(template, key)`. An item with a null/empty `Key` has
**no addressable page** — legacy navigates pages by `Key` (`Items.FirstOrDefault(c => c.Key == …).Group`), so
such a node reports `""` and stays a leaf. Live templates always carry a `Key` on a page item; the
adversarial corpus deliberately does not, and this is the rule that keeps the gate honest.

## 16. Poles and restore-on-back (R38-R39)

R38. `sptpl_focus_unreachable_count()` performs a breadth-first walk over `{up,down,left,right}` from the
default focus and lists every focusable node no D-pad route reaches. **Zero on every page of every live,
shipped and generated template, in every platform × form factor** (see §18).
R39. The navigation stack holds `{template, page, focus_path, focus_index}` per level. `sptpl_focus_enter(i)`
pushes the current page **and the focus index**, renders the child and focuses the child's default.
`sptpl_focus_back()` pops, re-renders the page, and restores the node that was left — by **path**, so a node
that has since disappeared (a flag or a language changed the page) falls back to that page's default focus
rather than to an arbitrary index. `popped_path`/`popped_index` report where focus landed, readable at
`i == sptpl_nav_depth()` after the pop. `sptpl_nav_push`/`sptpl_nav_back` exist for a shell that drives its own
page transitions. `sptpl_focus_apply("home")` pops back to the bottom of the stack.

## 17. The action vocabulary (R40)

R40. **41 actions**, one name each, in one table (`sptpl_action_field`: `name legacy direction family
description`). `direction` is what the focus layer does with it (`up down left right pageup pagedown first
last confirm back home`), or `""` when the action is the shell's (transport, system, digits, colour keys,
search, info, menu). `legacy` is the TPlayer `HotkeyAction_*` name where the semantics are identical.
`sptpl_focus_apply(name)` returns **0 applied, 1 no move / shell-owned, 2 confirm on a leaf (the shell runs
the handler or opens the url), 3 back/home at the root, −1 unknown action**.

Five key maps, each with a forward and a reverse lookup (`sptpl_action_from_key`, `sptpl_action_key_name`):

| map | space | notes |
|---|---|---|
| `keyboard` | `Windows.System.VirtualKey` by **name** (`Up`, `PageDown`, `Enter`…) | includes every `Gamepad*` VK (195-218), so a UWP shell needs one map |
| `xbox` | the same, by **numeric** code or name | 195 `GamepadA`=confirm, 196 `GamepadB`/`GamepadView`=back/menu, 203-206 D-pad, 207 `GamepadMenu`=menu, 199/200 shoulders=next/previous, 201/202 triggers=seek (HotkeyService's `GetHotkeys`) |
| `siri` | `up down left right select/center/click back menu playpause/paly home/tv pageup pagedown info` | the Siri Remote's focus-engine verbs |
| `androidtv` | `android.view.KeyEvent` by **name** (`DPAD_UP`, `DPAD_CENTER`) or numeric | 19-22 D-pad, 23/66/160 confirm, 4/111 back, 82 menu, 92/93 paging, 185-188 colour |
| `cec` | HDMI-CEC 1.4 UI Control `0x00`-`0x76`, hex or decimal | 0x00 select, 0x01-0x04 D-pad, 0x0d back, 0x2b enter, 0x44 play … 0x72-0x74 colour. `0x1e`/`0x1f` (NUMBER_11/12) and the number-entry mode deliberately map to nothing |

Typed wrappers (`sptpl_action_from_virtual_key`, `…_android_keycode`, `…_linux_keycode`,
`sptpl_action_from_cec`) exist so a shell never parses a string.

## 18. Measurements (2026-11-19)

| Gate | Result |
|---|---|
| `make test` (unit) | **299/299** (was 201) — 98 new TV checks, one block per rule |
| ASAN+UBSAN (`make asan`) | clean, no leaks |
| Differential vs the real `TableView.cs` (`make diff`) | **12,496/12,496 identical, 0 differ, 0 legacy-throws** — the *same* 16 configs × (shipped 55 + live 126 + 4×150 generated) as v1.0.0, which reported 12,464 identical + 32 legacy-throws (the two `runtimeconfig`-broken live templates, since fixed). Same scope, and the render list is untouched |
| `make tvcheck` (new gate) | **90 bundle×platform×form-factor configurations, 19,929 pages, 16,896 child-page enter/back round trips, 0 unreachable, 0 restore failures** |
| CLI | new `focus`, `tvcheck`, `action`, `actions`, `layout`, `focusjson` (+ `--form-factor/--tv-columns/--tv-rows/--tv-inset`) · **`tests/cli_check.sh` (`make cli-check`) now asserts the CLI surface**: three defects shipped in v1.1.1 that no other gate could see — `actions` and `action --map` were swallowed by the `load argv[2]` guard (`--map` was opened as a bundle), `action` parsed options from the action name so every `--platform/--form-factor/--page` was dropped, and `actions` printed one value four times because the four `%s` arguments aliased the library's single string buffer. Fixed in `8fc6a4d`; the library was untouched (same `.so` sha256) |
| Symbol surface | **87 exports** = `sptpl.map` == `nm -D` == `exports.json` == header (40 new, the 47 v1.0.0 ones unchanged) |
| Dist `verified/1.1.1` + `latest` (v1.1.1 = v1.1.0 + the `parse_int` fix; `verified/1.1.0` kept) | **6 targets**, every one HTTP 200: `linux-x86_64` 385,472 B · `linux-aarch64` 346,168 B · `windows-x64` 576,174 B (PE32+ x86-64; `release.sh` counts 88 because its objdump awk keeps the table's `Name` header — the 87 sptpl_ exports are all there, no extra symbol) · `android-arm64-v8a` 360,640 B · `android-x86_64` 414,984 B (both LOAD-aligned 16 KB) · `apple-xcframework` 1,261,832 B zip (sha256 `916882de…`) (iOS device/sim, tvOS device/sim, macOS × arm64+x86_64, 87 exports per slice) |
| Console | **98/98** Linux `.so` **and** the dist Windows `.dll` on `.214` (Win11 24H2 · dotnet 10) — 87/87 exports exercised, 0 FAIL |
| Fuzz (mode 3, the TV layer) | 223,094 execs → **one real finding**: `parse_int` overflowed a signed `long` on an arbitrarily long digit string (UBSAN at `tv.c:132`). Fixed — unsigned accumulator, per-step int32 range check, an out-of-range numeric key is refused (−1 → unmapped) instead of wrapping. Two unit checks pin it. Re-run over the same corpus: **711,954 execs, 0 findings** |
