# SynthOS v2 → v3 Migration Rules

This document covers the migration from SynthOS v2 format to v3 (FluentLM-based).

---

## 1. Theme Migration

### Overview

In v2, theme files (~800 lines each) define **both** CSS custom properties and all shell component styles (chat panel, modals, forms, scrollbars, etc.).

In v3, component styles live in `fluentlm.css`. Theme files **only** override FluentLM palette variables and set semantic color tokens. This brings each theme down to ~170 lines.

### Structure of a v3 Theme File

```
:root, .theme-class {
  /* 1. Palette overrides  — rebrand FluentLM's default blue to your theme ramp */
  /* 2. Semantic tokens     — map palette vars to UI roles (same sections as theme-light/dark.css) */
}
```

Zero component CSS. No selectors for `.chat-panel`, `.modal-*`, `.brainstorm-*`, scrollbars, etc.

### Palette Variable Mapping (v2 → v3)

#### Brand / Theme Colors

| v2 variable | v3 palette variable | Notes |
|---|---|---|
| `--accent-primary` | `--themePrimary` | Primary brand color |
| `--accent-secondary` | `--themeDark` | Darker accent |
| `--accent-tertiary` | `--themeSecondary` | Secondary accent |
| — | `--themeDarkAlt` | Interpolated from brand ramp |
| — | `--themeDarker` | Interpolated from brand ramp |
| — | `--themeTertiary` | Interpolated from brand ramp |
| — | `--themeLight` | Interpolated from brand ramp |
| — | `--themeLighter` | Interpolated from brand ramp |
| — | `--themeLighterAlt` | Interpolated from brand ramp |

#### Neutral Colors — Light Theme

| v2 variable | v3 palette variable | Notes |
|---|---|---|
| `--bg-tertiary` | `--neutralLighterAlt` | Lightest background |
| `--bg-primary` | `--neutralLighter` | Primary background |
| `--bg-secondary` | `--neutralLight` | Secondary background |
| `--text-secondary` | `--neutralSecondary` | Secondary text |
| `--text-primary` | `--neutralPrimary` | Primary text |
| `--white` | `--white` | White |

#### Neutral Colors — Dark Theme

| v2 variable | v3 palette variable | Notes |
|---|---|---|
| `--bg-primary` | `--neutralPrimary` | Dark primary background |
| `--bg-secondary` | `--neutralDark` | Dark secondary background |
| `--bg-tertiary` | `--neutralDarker` (custom) | Darkest background |
| `--text-primary` | `--neutralLighter` | Light text on dark |
| `--text-secondary` | `--neutralTertiaryAlt` | Secondary text on dark |

### Variables Without FluentLM Equivalents

The following v2 variables have **no** FluentLM palette equivalent. If a page uses them, the page author must define them in a page-level `<style>` block:

| v2 variable | Typical value (Dawn) | Typical value (Dusk) |
|---|---|---|
| `--accent-glow` | `rgba(118,75,162,0.15)` | `rgba(138,43,226,0.3)` |
| `--border-color` | `rgba(118,75,162,0.25)` | `rgba(138,43,226,0.3)` |
| `--header-min-height` | `58px` | `58px` |
| `--header-padding-vertical` | `14px` | `14px` |
| `--header-padding-horizontal` | `20px` | `20px` |
| `--header-line-height` | `1.25` | `1.25` |

### Semantic Tokens

v3 themes set semantic tokens (e.g. `--bodyBackground`, `--bodyText`, `--link`) by referencing the overridden palette variables. The token assignments follow FluentLM's reference themes:

- **Light themes** → follow `static-files/theme-light.css`
- **Dark themes** → follow `static-files/theme-dark.css`

### What to Remove

All CSS rules targeting component selectors. The full list from v2 themes that are now handled by `fluentlm.css`:

- Base resets: `*`, `body`, `html`
- Chat: `.chat-panel`, `.chat-header`, `.chat-messages`, `.chat-message`, etc.
- Viewer: `.viewer-panel`, `.viewer-panel::before`, `.viewer-panel.full-viewer`
- Loading: `.loading-overlay`, `.spinner`, `#loadingOverlay`
- Toggle: `.chat-toggle`, `.chat-toggle-dots`, `.chat-toggle-dot`, etc.
- Modals: `.modal-overlay`, `.modal-content`, `.modal-header`, etc.
- Forms: `.form-group`, `.form-label`, `.form-input`, etc.
- Brainstorm: All `.brainstorm-*` selectors
- Animations: `@keyframes spin`, `@keyframes nebula-pulse`
- Scrollbars: All `::-webkit-scrollbar*` rules
- Attachments: `.attach-btn`, `.attach-menu`, `.attachment-pill*`
- Save line: `.save-line`, `.save-line-label`
- Screenshot: `.screenshot-overlay`, `.screenshot-rect`

---

## 2. Shell Chrome Removal (iframe Viewer Panel)

### Overview

In the iframe viewer panel architecture, **shell chrome is no longer part of page HTML**. The shell (toolbar, chat panel, loading overlay) lives in a parent frame (`required-pages/_shell/page.html`), and page content renders inside an `<iframe>`. Pages are pure content — they should not contain any shell markup.

### What to remove from page HTML

All of the following elements are now provided by the parent shell frame and must be removed from page HTML templates. The v2→v3 migration in `src/migrations.ts` strips every selector listed here via the `V2_SHELL_SELECTORS` table — keep that array in sync with this list.

| Selector | What it is in v2 | Who provides it in v3 |
|---|---|---|
| `.shell-toolbar` | Toolbar div (builderToggle, pagesBtn, saveBtn, settingsBtn) | Parent shell frame |
| `.chat-panel` | Header, `#chatMessages`, `#chatForm` with `#chatInput`, `.link-group`, inline chat history, `#defaultGreeting`, `#firstRunGreeting` | Parent shell frame |
| `.chat-toggle` | Collapsed-chat toggle button | Parent shell frame (if kept) |
| `#loadingOverlay` | Spinner overlay inside `.viewer-panel` | Parent shell frame (blueprint overlay) |
| `<script id="idle-animation">` | v2 inline script declaring top-level `hideIdleAnimation`/`showIdleAnimation` | Parent shell frame (no-op stubs injected at serve time) |
| `<script id="first-run-check">` | v2 inline script that toggles `#defaultGreeting`/`#firstRunGreeting` via `?firstRun=true` | Parent shell frame (greeting flow) |
| `<script id="page-helpers">` | Legacy `/api/page-helpers.js?v=2` tag | Server re-injects the cache-busted v3 URL at serve time |
| `<script id="page-script">` | Legacy `/api/page-script.js?v=2` tag | Server re-injects the cache-busted v3 URL at serve time |
| `<script id="synthos-error-capture">` | Error-capture bootstrap | Server injects when needed |

The `first-run-check` script in particular MUST be stripped — it references `#defaultGreeting` and `#firstRunGreeting`, both of which live inside `.chat-panel`. Leaving it behind after the panel is removed produces spurious `missing-element` validator warnings.

### Before (v2/early v3)

```html
<body>
    <div class="shell-toolbar" data-locked="true">
        <!-- toolbar buttons -->
    </div>
    <div class="chat-panel" data-locked="true">
        <div class="chat-header" data-locked="true">...</div>
        <div class="chat-messages" id="chatMessages" data-locked="true">...</div>
        <form action="/" method="POST" id="chatForm" data-locked="true">
            <textarea class="chat-input" id="chatInput" ...></textarea>
        </form>
    </div>
    <div class="viewer-panel" id="viewerPanel">
        <!-- page content -->
        <div id="loadingOverlay" class="loading-overlay"><div class="spinner"></div></div>
    </div>
    <script id="page-helpers" src="/api/page-helpers.js?v=3" data-locked="true"></script>
    <script id="page-script" src="/api/page-script.js?v=3" data-locked="true"></script>
</body>
```

### After (iframe-ready)

```html
<body>
    <div class="viewer-panel" id="viewerPanel">
        <!-- page content only -->
    </div>
    <div id="instructions" style="display: none;" data-locked="true"></div>
    <div id="thoughts" style="display: none;" data-locked="true"></div>
</body>
```

### Runtime safety net

The server's `stripShellMarkup()` function removes shell elements at serve time even if they're still present in the HTML source. It also injects hidden stub elements (`chatForm`, `chatInput`, `chatMessages`, `loadingOverlay`) so legacy inline scripts that reference these IDs don't crash with null-reference errors.

In addition, `stripShellMarkup()` removes the v2-legacy `<script id="idle-animation">` block and injects no-op `window.hideIdleAnimation` / `window.showIdleAnimation` globals. The v2 block declares those functions as top-level statements, which the server's `wrapInlineScriptsInIIFE` transform traps inside an IIFE — leaving cross-script call sites (e.g. `hideIdleAnimation()` in `#qb-app`) hitting `ReferenceError` and aborting the rest of the page boot. The stubs keep those call sites no-op-safe without having to rewrite each migrated page.

However, source templates should be cleaned proactively — the runtime stripping is a fallback, not a substitute for clean templates.

### Automated cleanup

Run the cleanup script to strip shell markup from all page templates:

```bash
node scripts/cleanup-shell-markup.mjs          # modify files
node scripts/cleanup-shell-markup.mjs --dry-run # preview only
```

This script processes all `page.html` files under `default-pages/` and `.synthos/pages/`, removing the 5 element types listed above.

### Migration rules for the LLM

When creating or migrating pages:

1. **Do NOT include** shell toolbar, chat panel, loading overlay, or page-helpers/page-script tags in page HTML
2. **Do NOT include** chatForm submit handlers or chatInput event listeners — the shell handles all chat interaction
3. **The `<body>` should start with** the `.viewer-panel` div containing only page content
4. **Keep** `#instructions` and `#thoughts` divs (used for LLM context, not shell chrome)
5. **Keep** page-specific inline scripts and styles — only remove shell-related code
6. **If a page script references** `chatInput` or `chatForm` (e.g., tutorial link handlers), the runtime stubs prevent crashes, but ideally migrate these to use `window.__synthOSNavigateTo()` or `parent.postMessage()` via the page bridge

---

## 3. Page Migration

### Overview

v2 pages reference legacy CSS tokens (`var(--bg-primary)`, `var(--accent-primary)`, `var(--text-primary)`, etc.) that v2 themes used to supply as hardcoded colors. In v3, themes only define FluentLM semantic tokens (`--bodyBackground`, `--themePrimary`, `--bodyText`, etc.). When migrating a v2 page, we inject a `<style id="v2-compat">` block that **aliases** each legacy v2 token onto the closest v3 semantic token — so the page inherits whatever v3 theme is active instead of being frozen on the old nebula-dusk palette.

### What the framework handles (NOT inlined)

The shell chrome CSS (chat panel, modals, toggle, brainstorm, attachments, etc.) is provided by the parent shell frame's stylesheet plus FluentLM. Pages do NOT need to carry these rules:

- `.chat-panel`, `.chat-header`, `.chat-messages`, `.chat-message`, `.chat-message p`, `.chat-message p strong`, `.chat-message p code`
- `.link-group`, `.link-group a`
- `form` (chat form layout), `.chat-input`, `.chat-submit`
- `.chat-toggle`, `.chat-toggle-dots`, `.chat-toggle-dot`, `body.chat-collapsed *`
- `.chat-input-wrapper`, `.brainstorm-icon-btn`, `.brainstorm-*`
- `.modal-overlay`, `.modal-content`, `.modal-header`, `.modal-body`, `.modal-footer`, `.modal-footer-right`
- `.modal-btn`, `.modal-btn-primary`, `.modal-btn-secondary`, `.modal-btn-danger`
- `.form-group`, `.form-label`, `.form-input`, `.checkbox-label`
- `.loading-overlay`, `.spinner`, `#loadingOverlay`
- `.save-line`, `.save-line-label`
- `.attach-btn`, `.attach-menu`, `.attach-menu-item`, `.attachment-pill*`
- `.screenshot-overlay`, `.screenshot-rect`

The shell also injects the iframe viewport height chain (`html,body,.viewer-panel{height:100%;margin:0}`), so the compat block does NOT carry global resets or layout rules.

### The v2 → v3 token mapping

Each v2 token is aliased to a v3 **semantic** token (not a palette token). Semantic tokens are already defined per-theme and resolve correctly under light, dark, and high-contrast themes, so the mapping is theme-agnostic.

#### Color tokens

Backgrounds must alias to **semantic** role tokens (`--bodyBackground`, `--bodyStandoutBackground`, `--bodyBackgroundHovered`), not palette tokens (`--neutralPrimaryAlt`, `--neutralDark`, etc.). Palette tokens encode a FIXED color value and stay dark even under light themes — so a v2 page that used `--bg-secondary` / `--bg-tertiary` for component backgrounds renders as hard-coded black blobs under nebula-dawn, aurora-dawn, high-contrast-light, etc. if aliased to palette. Semantic tokens flip correctly across light/dark variants.

| v2 token | → v3 binding | Fallback | Role |
|---|---|---|---|
| `--bg-primary` | `var(--bodyBackground, #ffffff)` | `#ffffff` | Main surface background (white in dawn, dark in dusk) |
| `--bg-secondary` | `var(--defaultStateBackground, #faf9f8)` | `#faf9f8` | Component surface (near-white in dawn, darker in dusk) |
| `--bg-tertiary` | `var(--bodyBackgroundHovered, #f3f2f1)` | `#f3f2f1` | Third distinct surface (light gray in dawn, mid-dark in dusk) |
| `--accent-primary` | `var(--themePrimary, #0078d4)` | `#0078d4` | Active theme's primary brand color |
| `--accent-secondary` | `var(--themeDarkAlt, #106ebe)` | `#106ebe` | Darker brand variant |
| `--accent-tertiary` | `var(--themeSecondary, #2b88d8)` | `#2b88d8` | Lighter brand variant |
| `--accent-glow` | `rgba(0,0,0,0.3)` | — | Subtle shadow; theme-neutral |
| `--text-primary` | `var(--bodyText, #333333)` | `#333333` | Primary text color |
| `--text-secondary` | `var(--bodySubtext, #605e5c)` | `#605e5c` | Secondary / subtitle text |
| `--border-color` | `var(--bodyDivider, #edebe9)` | `#edebe9` | Borders, dividers, outlines |

**Why `--defaultStateBackground` for `--bg-secondary`:** That's the v3 token v3-authored pages use for component surfaces (cards, panels, tiles). It's defined in every shipped theme (dawn: `--neutralLighterAlt`, dusk: `--neutralDark`) and flips correctly. `--bodyStandoutBackground` resolves to the same values but `--defaultStateBackground` is the role-correct semantic choice.

**Why hex fallbacks:** If any v3 token doesn't resolve (theme CSS fails to load, token spelling mismatch, browser quirks in iframe context), the outer `var()` falls back to the hex. Without the fallback the whole declaration becomes `initial` and the property reverts to its CSS default (transparent for background, `canvasText` for color) — which can surface as black component backgrounds under some OS/browser combos. The light-mode fallbacks are safe under dusk because the outer `--bodyBackground` etc. DO resolve (to dark values) and the fallback never fires.

#### Layout constants (kept as literals)

These values are layout geometry, not theme color — they stay fixed across themes:

| v2 token | Value |
|---|---|
| `--header-min-height` | `58px` |
| `--header-padding-vertical` | `14px` |
| `--header-padding-horizontal` | `20px` |
| `--header-line-height` | `1.25` |

#### The full compat block

```html
<style id="v2-compat">
/* --- v2 → v3 token aliases ---
   Each legacy v2 var resolves to a v3 SEMANTIC token (role-based) so the page
   re-themes automatically between light and dark variants. Do NOT use palette
   tokens (--neutralDark, --neutralPrimaryAlt, etc.) here — those encode a
   FIXED color value and stay dark under light themes, producing hard-coded
   black backgrounds on v2 pages.

   Component-surface tokens use --defaultStateBackground / --defaultHoverBackground
   (the v3 tokens v3 pages use for card/panel surfaces) instead of the
   body*Background tokens. Every alias has a hex fallback so the compat block
   still produces sensible light defaults even if the theme CSS fails to load
   or a token isn't defined (otherwise the chain resolves to `initial` and
   backgrounds go transparent). Header geometry stays literal because it's
   layout, not color. */
:root {
    --bg-primary:       var(--bodyBackground, #ffffff);
    --bg-secondary:     var(--defaultStateBackground, #faf9f8);
    --bg-tertiary:      var(--bodyBackgroundHovered, #f3f2f1);

    --accent-primary:   var(--themePrimary, #0078d4);
    --accent-secondary: var(--themeDarkAlt, #106ebe);
    --accent-tertiary:  var(--themeSecondary, #2b88d8);
    --accent-glow:      rgba(0,0,0,0.3);

    --text-primary:     var(--bodyText, #333333);
    --text-secondary:   var(--bodySubtext, #605e5c);

    --border-color:     var(--bodyDivider, #edebe9);

    --header-min-height: 58px;
    --header-padding-vertical: 14px;
    --header-padding-horizontal: 20px;
    --header-line-height: 1.25;
}
</style>
```

### Legacy color mapping (hardcoded RGB / hex → theme tokens)

v2 pages were hand-matched to the v2 nebula-dusk palette and are full of literal `rgba(102,126,234,0.15)`, `#dc3545`, etc. Under a v3 light theme those colors stand out as dark purple-blue/red blobs because they never existed as variables — they were baked directly into the CSS. The migration therefore also rewrites these specific numeric triples (and their hex equivalents) in the full HTML output (covers `<style>` blocks, inline `style=""` attrs, and color strings inside JS template literals).

| v2 hardcoded color | Source in v2 | → v3 binding |
|---|---|---|
| `rgba(102,126,234,*)` / `#667eea` | `--accent-primary` (purple-blue) | `var(--themePrimary)` |
| `rgba(118,75,162,*)` / `#764ba2` | `--accent-secondary` | `var(--themeDarkAlt)` |
| `rgba(138,43,226,*)` / `#8a2be2` | `--accent-glow` (blueviolet) | `var(--themeDarker)` |
| `rgba(75,0,130,*)` / `#4b0082` | indigo inset-shadow | `var(--themeDarker)` |
| `rgba(240,147,251,*)` / `#f093fb` | magenta accent | `var(--themeSecondary)` |
| `rgba(183,148,246,*)` / `#b794f6` | light purple | `var(--themeTertiary)` |
| `rgba(26,26,46,*)` / `#1a1a2e` | `--bg-primary` | `var(--bodyBackground)` |
| `rgba(22,33,62,*)` / `#16213e` | `--bg-secondary` | `var(--bodyStandoutBackground)` |
| `rgba(15,15,35,*)` / `#0f0f23` | `--bg-tertiary` | `var(--bodyBackgroundHovered)` |
| `rgba(220,53,69,*)` / `#dc3545` | Bootstrap danger red | `var(--red)` |
| `rgba(40,167,69,*)` / `#28a745` | Bootstrap success green | `var(--green)` |
| `rgba(255,193,7,*)` / `#ffc107` | Bootstrap warning yellow | `var(--yellow)` |
| `rgba(0,0,0,*)` | Black shadows | *(unchanged — theme-neutral)* |

**How alpha is preserved:** `rgba(R,G,B,A)` is rewritten to `color-mix(in srgb, var(--token) A*100%, transparent)`, which is widely supported in modern browsers (since 2023). Solid `rgb(R,G,B)` / `rgba(R,G,B,1)` / bare hex collapse to `var(--token)` directly.

**Hex boundary safety:** hex replacements are guarded by `(?<![0-9a-fA-F])` / `(?![0-9a-fA-F])` lookarounds, so `#667eea` inside an 8-digit `#667eeaff` is not split.

**Result:** the same migrated page now renders with the active theme's primary color where there used to be baked purple-blue, and with the shared red/green/yellow tokens for danger/success/warning instead of Bootstrap's literals. Switching between nebula-dawn, aurora-dusk, high-contrast-light, etc. re-themes the page automatically.

### Migration rules (runtime)

The v2→v3 migration is applied automatically by `migrateV2toV3` in `src/migrations.ts`. It:

1. **Injects the `<style id="v2-compat">` block** into `<head>` as the first child. Idempotent — skipped if a block with `id="v2-compat"` is already present. Runs AFTER `postProcessV2` (which strips `:root` rules from style blocks), not before — otherwise the block's aliases get shredded silently.

2. **Remaps hardcoded v2-palette RGB/hex colors** throughout the HTML per the table above. Runs LAST so the compat block (which uses a theme-neutral `rgba(0,0,0,0.3)` for `--accent-glow`) is in the output but untouched by the remap (the rule table intentionally excludes `0,0,0`).

3. **Does NOT modify** existing page structure, classes, or non-color inline styles inside `.viewer-panel`. The page's own CSS keeps working — its `var(--bg-primary)` / `var(--accent-primary)` / etc. now resolve through the aliases to whatever the active v3 theme provides, and literal colors get remapped to shared tokens.

4. **Does NOT convert** v2 class names to FluentLM `flm-*` classes. That's a separate opt-in redesign (see §4), not part of version migration.

5. **Does NOT remove** any existing `<style>` blocks the page already has. The compat block supplements them, it doesn't replace.

### What migrated pages look like under different v3 themes

Because the compat block aliases to semantic tokens AND the legacy color remap routes literals through shared tokens, the same migrated page renders differently under each theme:

- **nebula-dusk** — purple primary, dark neutrals
- **nebula-dawn** — purple primary, light neutrals *(previously looked broken — now themes correctly)*
- **aurora-dawn** — aurora accent, light neutrals
- **cosmos-dusk** — cosmos primary, dark neutrals
- **high-contrast-light / dark** — high-contrast palette

### Known limitations

- **Non-palette hex colors** (e.g. `#fafafa`, `#cccccc`, or any hex not in the rule table) are left as-is. If a page uses an unusual color, add it to the rule table in `src/migrations.ts`.
- **Color-named literals** (`purple`, `red`, `black`) are not remapped. These are rare in v2 pages but, if present, would need a separate named-color rule.
- **Gradients** that combine remapped colors work correctly (each stop is rewritten independently), but the aesthetic may shift — a `linear-gradient(purple → indigo)` that was two v2 accent colors now becomes a gradient between `themePrimary` and `themeDarker`, which reads correctly under any theme but may not match the original nebula-dusk glow exactly.

---

## 4. Component Migration

### Overview

Component migration (v2 classes → FluentLM `flm-*` classes) is **not** part of the automatic v2→v3 page migration. It is an optional, manual redesign step.

### Why not auto-convert?

v2 pages use custom HTML structures with v2-specific classes. FluentLM components have different HTML structures, attributes, and JS wiring. A class-name find-and-replace would break layouts. Instead:

- **Migrated v2 pages** keep working as-is via the v2-compat inline styles
- **New v3 pages** are built fresh using FluentLM components
- **Manual redesign** can optionally convert a v2 page to use FluentLM components

### Key differences

| Aspect | v2 | v3 (FluentLM) |
|---|---|---|
| Button | `<button class="modal-btn modal-btn-primary">` | `<button class="flm-button flm-button--primary">` |
| Input | `<input class="form-input">` | `<input class="flm-textfield-input">` wrapped in `<div class="flm-textfield">` |
| Modal | `.modal-overlay > .modal-content > .modal-header` | `<div class="flm-dialog">` with `flm-dialog-header` etc. |
| Colors | `var(--accent-primary)`, `var(--bg-primary)` | `var(--themePrimary)`, `var(--bodyBackground)` |
| Icons | Manual SVG / emoji | `data-icon="Name"` attribute, auto-injected by FluentLM JS |
| Theme mode | `.light-mode` / `.dark-mode` on `<html>` | `FluentLM.setTheme('light'/'dark')` or `.fluent-dark` class |

### Pages gallery (required-pages/pages.html)

The pages gallery uses FluentLM for dialogs, context menus, search, and pivot tabs, but page links themselves are rendered as **large rounded buttons** (`.page-btn`) rather than `flm-documentcard` cards. This was a deliberate design choice:

- Each page link is an `<a class="page-btn">` with `border-radius: 12px` and a centered `.btn-label` text span (120×20px plus padding)
- Variant classes: `.builder-page` (gradient background), `.pinned` (accent border), `.needs-upgrade` (dashed border + glow animation)
- The grid uses `display: flex; flex-wrap: wrap; gap: 12px` for layout. **Note:** CSS Grid `gap` did not work reliably inside the viewer panel — flexbox `gap` is the proven alternative
- Scrolling text animation on hover for names that overflow the button width
- Context menu uses `flm-contextmenu` + `flm-contextmenu-item`
- Modals use `flm-dialog-overlay` / `flm-dialog` with `flm-dialog-header/body/footer`
- Category filtering uses `flm-pivot--tabs` with `flm-pivot-tab` buttons
- Search uses `flm-searchbox` with `flm-searchbox-input`
- Toast uses `flm-messagebar--success` with fixed positioning

### Dialog overlay visibility class

The `flm-dialog-overlay` is hidden by default (`opacity: 0; pointer-events: none`). To show it programmatically, use `flm-dialog-overlay--open`:

```js
el.classList.add('flm-dialog-overlay--open');    // show
el.classList.remove('flm-dialog-overlay--open'); // hide
```

**Important:** The class is `--open`, not `--visible`. Only `--open` has CSS backing (`opacity: 1; pointer-events: auto`).
For declarative usage, use `data-dialog-open="id"` / `data-dialog-close` attributes.

### Confirmation dialogs

v2 pages use `window.confirm()` or `alert()` for confirmations. v3 pages should use an `flm-dialog-overlay` instead. The pattern:

```html
<div class="flm-dialog-overlay" id="myConfirm" data-light-dismiss>
  <div class="flm-dialog" style="max-width:400px;width:90%;">
    <div class="flm-dialog-header">
      <h2 class="flm-dialog-title">Confirm</h2>
    </div>
    <div class="flm-dialog-body">
      <p class="flm-text">Are you sure?</p>
    </div>
    <div class="flm-dialog-footer">
      <div style="flex:1;"></div>
      <button class="flm-button" id="confirmCancel">Cancel</button>
      <button class="flm-button" id="confirmOk" style="color:var(--errorText);">Confirm</button>
    </div>
  </div>
</div>
```

Open/close programmatically:

```js
document.getElementById('myConfirm').classList.add('flm-dialog-overlay--open');    // show
document.getElementById('myConfirm').classList.remove('flm-dialog-overlay--open'); // hide
```

### Navigation guards (unsaved changes)

When a page tracks dirty state, use a FluentLM confirmation dialog to intercept in-page navigation instead of relying solely on the browser's `beforeunload` prompt.

**Key pitfalls and solutions:**

1. **Shell page-script handlers navigate immediately.** Toolbar buttons (`#pagesBtn`, etc.) and link-group anchors have click handlers registered by the page-script that set `window.location` directly. A simple `e.preventDefault()` is not enough — those handlers still fire. Fix: use `e.stopImmediatePropagation()` **and** register in the **capture phase** (`true` as the third argument) so the guard runs before any bubble-phase handlers:

    ```js
    function guardNavigation(el, url) {
        el.addEventListener('click', function(e) {
            if (!isDirty) return;           // clean — let default behavior through
            e.preventDefault();
            e.stopImmediatePropagation();   // block page-script handlers
            showConfirmDialog(url);
        }, true);                           // capture phase
    }
    ```

2. **Capture the pending URL before closing the dialog.** If your `hideDialog()` helper nulls the pending URL, the leave handler must snapshot it into a local variable first:

    ```js
    leaveBtn.addEventListener('click', function() {
        var url = pendingNavUrl;    // snapshot before hide nulls it
        isDirty = false;            // disarm beforeunload
        hideDialog();
        if (url) window.location.href = url;
    });
    ```

3. **Suppress `beforeunload` while the dialog is open.** Otherwise the browser shows its native prompt on top of the themed one:

    ```js
    window.addEventListener('beforeunload', function(e) {
        if (isDirty && !overlay.classList.contains('flm-dialog-overlay--open')) {
            e.preventDefault();
        }
    });
    ```

4. **Keep `beforeunload` as a fallback.** The themed dialog can only intercept in-page link clicks. Browser close, tab close, and address-bar navigation can only be caught by `beforeunload`.

---

## 5. My Notes Migration — Decisions

This section documents design decisions made during the full FluentLM rewrite of `default-pages/my_notes.html`.

### 1. Sidebar is custom layout

FluentLM does not provide a sidebar component. The sidebar uses custom layout CSS (`.notes-sidebar` with fixed width, flex column, border) while the **items inside** use `flm-list flm-list--bordered` and `flm-list-item` / `flm-list-item--selected`. This keeps the list items visually consistent with other v3 pages.

### 2. Toast UI editor kept as-is

The Toast UI rich text editor is a third-party widget and was not migrated to FluentLM components. Only the **container sizing** (`#editor-container` flex layout) uses layout CSS. The editor's own styles and theme detection (`window.themeInfo.mode`) remain unchanged.

### 3. `confirm()` → `flm-dialog`

The browser `window.confirm()` for note deletion was replaced with an `flm-dialog-overlay` + `flm-dialog` confirmation dialog, following the pattern established in §4 (Component Migration — Confirmation dialogs). The dialog uses `flm-dialog-overlay--open` for visibility toggling.

### 4. Sidebar background uses `--defaultStateBackground`, not `--bodyStandoutBackground`

Initial attempt used `--bodyStandoutBackground` for the sidebar, but in light themes this token is nearly identical to `--bodyBackground`, producing no visible contrast. `--defaultStateBackground` (used by cards and tiles in settings.html/pages.html) provides reliable contrast in both light and dark themes. The sidebar border was also bumped from 1px to 2px for clearer separation.

### 5. Glow and gradient effects dropped

v2 styles used `linear-gradient` backgrounds, `box-shadow` glow effects (`--accent-glow`), and animated hover transforms. These are all removed in the v3 rewrite. FluentLM uses flat semantic tokens (`--bodyBackground`, `--bodyStandoutBackground`, `--neutralLight`) with no glow or gradient effects.

### 6. Button ordering convention

In FluentLM dialog footers and action bars, **primary actions (Save, OK) dock rightmost** and **secondary/destructive actions (Delete, Cancel) go to their left**. This is achieved by placing destructive buttons first in HTML source order with `justify-content: flex-end` on the container. The pattern matches the `flm-dialog-footer` layout used in pages.html and the delete confirmation dialog.

### 7. Full component rewrite, not version-bump migration

This was a **full rewrite** to FluentLM components, not a v2-compat migration. There is no `<style id="v2-compat">` block — all v2 CSS variables and custom classes were removed and replaced with `flm-*` classes and semantic tokens. The `.light-mode` CSS overrides were also removed since FluentLM handles theme switching automatically.

---

## 6. Games, Animations & Visual-Heavy Pages

### Overview

Pages that are primarily canvas-based games, animations, or full-screen visual experiences (e.g. `neon_asteroids`) follow a simplified migration path. These pages typically own all their styling via hardcoded colors and self-contained CSS — they do not depend on v2 theme variables.

### Migration checklist

1. **Add `full-viewer` class** — change `class="viewer-panel"` to `class="viewer-panel full-viewer"` so the content fills the entire viewer area with zero padding. Games and visual pages almost always need this.

2. **Retain all inline styles** — keep the page's existing `<style>` block untouched. These pages use hardcoded colors (e.g. `#0ff`, `#f0f`, `rgba(...)`) and custom fonts, not v2 theme variables. Do not convert them to FluentLM tokens.

3. **No v2-compat block needed** — if the page's `<style>` and inline `style=` attributes do not reference v2 CSS variables (`var(--bg-primary)`, `var(--accent-primary)`, etc.), skip the `<style id="v2-compat">` block entirely. It adds unnecessary weight.

4. **If v2 variables ARE used** — some visual pages may reference a few v2 variables for background or text color. In that case, inject the v2-compat block per §3. But audit first — often only 1–2 variables are used and it may be simpler to replace them with hardcoded values matching the page's aesthetic.

5. **Bump `pageVersion`** — set `"pageVersion": 3` in the page's `page.json`.

6. **Do not convert to FluentLM components** — these pages have no forms, dialogs, or standard UI to migrate. Their content is entirely custom (canvas, SVG, absolute-positioned overlays). Leave the HTML structure and class names as-is.

### Canvas sizing

Games that use `<canvas>` typically size to the viewer panel via JavaScript (`viewerPanel.clientWidth` / `clientHeight`). The `full-viewer` class ensures the panel has `padding: 0`, so the canvas fills edge-to-edge. Verify the resize handler still works after migration — it should, since the panel element and ID are unchanged.

### What NOT to change

- Game logic scripts — leave all `<script>` blocks untouched
- Custom fonts (e.g. Google Fonts `<link>` tags) — keep as-is
- CDN library imports (e.g. html2canvas) — keep as-is
- Inline `style=` attributes on game elements (e.g. `style="display: none;"` on overlays) — preserve exactly

---

## 7. Chat History Migration (iframe Viewer Panel)

### Overview

In the iframe viewer panel architecture, chat history is stored as a separate JSON file (`chat-history.json`) alongside each page, instead of being embedded as `<div class="chat-message">` elements inside the page HTML. This decouples chat state from page content and enables the shell/content iframe split.

### What changed

| Before | After |
|--------|-------|
| Chat messages embedded in `#chatMessages` div inside page HTML | Chat messages stored in `<pagesFolder>/pages/<name>/chat-history.json` |
| Server extracts history by scraping `.chat-message` elements with cheerio | Server reads `chat-history.json` directly |
| `appendChatReply()` / `appendChatError()` inject HTML into page | Shell.js displays messages in the parent frame |
| `newBuild` detected by counting `.chat-message` elements | `newBuild` detected by `history.length === 0` |

### File format

`chat-history.json` is a JSON array of `ChatMessage` objects:

```json
[
  { "role": "user", "content": "Make the header blue" },
  { "role": "assistant", "content": "I've updated the header background to blue." }
]
```

An empty array `[]` means no chat history (new or freshly saved page).

### Migration steps for existing pages

1. **Check for embedded chat messages** — look for `#chatMessages .chat-message` elements in `page.html`

2. **Extract messages** — for each `.chat-message` div:
   - Parse the role from `<strong>User:</strong>` or `<strong>SynthOS:</strong>` prefix
   - Strip HTML tags to get plain text content
   - Map to `{ role: 'user' | 'assistant', content: string }`

3. **Write `chat-history.json`** — save the extracted array to `<pageFolder>/chat-history.json`
   - If no chat messages are found, write `[]`
   - If the page only has the default welcome message (`Welcome! How can I help you?`), write `[]` (the welcome is handled by shell.js)

4. **Strip chat markup from page HTML** (optional) — remove `#chatMessages` content and `.chat-panel` div from the page HTML. The iframe viewer panel strips shell markup automatically via `stripShellMarkup()`, so this step is cosmetic cleanup.

### Legacy fallback

The GET handler in `usePageRoutes.ts` has a legacy fallback: if `chat-history.json` doesn't exist, it extracts messages from the page HTML using `extractChatMessages()`. This ensures pre-migration pages still work. Once all pages are migrated, this fallback can be removed.

### What to create for new pages

New pages (both default templates and user-created) should ship with an empty `chat-history.json`:

```json
[]
```

This prevents the legacy fallback from running and establishes the page as using the new format from the start.

### Pages that don't need migration

- **Required pages** (`required-pages/`) — system pages like `builder`, `settings`, `pages` are loaded fresh each time and don't accumulate chat history
- **Pages with no chat markup** — if the page HTML has no `#chatMessages` div or no `.chat-message` elements, just create an empty `chat-history.json`
- **Pages already migrated** — if `chat-history.json` already exists, skip

### Lifecycle

| Event | Chat history behavior |
|-------|----------------------|
| **New page created** | `chat-history.json` created with `[]` |
| **User sends message** | User + assistant messages appended to array |
| **Page saved** | `chat-history.json` cleared (reset to `[]`) |
| **Page undo** | Last user + assistant pair popped from array |
| **Page copied** | `chat-history.json` is NOT copied (new page starts fresh) |
| **Page deleted** | `chat-history.json` deleted with the page folder |

---

## 8. Migration Greeting

### Overview

Pages upgraded by `POST /api/pages/:name/upgrade` (the UI "migrate to v3" action) get an auto-assigned `greeting` on `page.json` so the shell's first assistant message after migration tells the user what happened and invites them to report breakage.

### Behavior

- Any migration from `pageVersion < 3` to the current `PAGE_VERSION` assigns a generic greeting onto the page metadata **only if** the page does not already carry a user-authored greeting (`metadata.greeting` is empty/whitespace).
- The greeting is stored on `page.json` as the `greeting` field. The shell renders it as the first assistant message via `injectShellInit` (see `src/service/usePageRoutes.ts`).
- The actual greeting text lives in `MIGRATED_PAGE_GREETING` in `src/service/useApiRoutes.ts`. Keep updates colocated there — the migration-rules doc does not repeat the copy.

### Why not inline it into the HTML?

The v3 chat-history architecture (§7) keeps greeting text out of page HTML entirely — it lives on `page.json` and is rendered by the shell, not embedded as a `<div class="chat-message">` in the page body. Adding it to HTML during migration would immediately be stripped by `stripShellMarkup()` at serve time.

### Overriding the greeting later

Users can change the greeting through the page definition editor. Whatever they save into `metadata.greeting` replaces the auto-assigned text permanently.
