# Architecture Overview

The WYSIWYG plugin uses a snapshot-driven architecture where all content modifications flow through nav snapshots and a declarative save planner before reaching disk.

## Cardinal Rules

Cardinal rules are cross-cutting constraints that apply across multiple subsystems. Every cardinal rule defined in any design document must also appear in this global registry. When a cardinal rule is added, updated, or removed in a design document, this registry must be updated to match.

| # | Rule | Authoritative Source | Summary |
|---|------|---------------------|---------|
| 1 | **Registry Consistency** | This document | When a cardinal rule is added or updated in any design document, the global registry in this section must be updated to match. |
| 2 | **Cursor & Selection Preservation** | `cursor-selection-preservation.mdc` | Every mode transition must preserve the user's cursor position and text selection. A transition that loses the cursor is a regression. |
| 3 | **Cautions Rule A — No Direct Disk I/O** | `DESIGN-cautions.md` | Caution action handlers must resolve changes through the snapshot system only, via the Declarative Save Planner. No caution handler may perform disk I/O directly. |
| 4 | **Cautions Rule B — Snapshot State for Warnings** | `DESIGN-cautions.md` | mkdocs.yml warnings must always and only come from active snapshot state. |
| 5 | **Cautions Rule C — Snapshot-Only mkdocs.yml Changes** | `DESIGN-cautions.md` | Applying mkdocs.yml changes only affects snapshot state — deferred to the Declarative Save Planner on Save. |
| 6 | **Exclusive Disk I/O in Focus Mode** | `DESIGN-declarative-save-planner.md` Invariant 10 | In Focus Mode (Layer 2+), all disk-writing operations flow exclusively through the Declarative Save Planner batch executor. Does not apply to Unfocused Mode (Layer 1). |
| 7 | **In-Place Extension Replacement** | `DESIGN-changing-mkdocs-yml.md` | When upgrading a `markdown_extensions` list item from bare string to dict form (e.g., `pymdownx.superfences` to `pymdownx.superfences: {custom_fences: [...]}`), replace the item in-place at its current index. Never add a new entry alongside the old one. |
| 8 | **In-Place Plugin Replacement** | `DESIGN-changing-mkdocs-yml.md` | When upgrading a `plugins` list item from bare string to dict form (e.g., `mkdocs-nav-weight` to `mkdocs-nav-weight: {default_page_weight: 1000}`), replace the item in-place at its current index. Never add a new entry alongside the old one. |
| 9 | **Layer-Level Mutual Exclusion for Editor Modes** | `DESIGN-modes-of-operation.md` | Editor modes at the same layer are mutually exclusive. They share a single z-index value and entry into one must be blocked while another at the same layer is active. This applies only to editor modes, not to non-modal UI elements (dropdowns, toasts, popups, progress bars). |
| 10 | **Public Registry Dependencies** | `DESIGN-vscode-extension-subsystem.md` | All Node.js dependency manifests (`package.json`, `package-lock.json`) must resolve from public registries only. No private or corporate registry URLs may appear in committed files. |

## High-Level Pipeline

```mermaid
flowchart LR
    ContentMod["Content Modification<br>and saving..."]
    NavSnaps["will update<br>Nav Snapshots."]
    SavePlanner["will use the<br>Declarative Save Planner"]

    subgraph Backend ["Backend disk"]
        WysiwygAPI["via<br>wysiwyg plugin API<br>rest server"]
        LiveEditAPI["or via<br>live edit plugin API<br>websocket server"]
    end

    ContentMod -->|"via Nav Ctrl+S"| NavSnaps
    ContentMod -->|"via auto-save or Ctrl+S"| SavePlanner
    NavSnaps -->|"Differences"| SavePlanner
    SavePlanner -->|"which writes to"| Backend
```



## Snapshot-Driven Architecture

```mermaid
flowchart TD
    navData["navData"]
    NavSnaps["Nav Snapshots.<br>Saving snapshot differences"]
    UndoRedo["undo-redo index"]
    NavRenderer["Nav Renderer"]
    SavePlanner["will use<br>Declarative Save Planner"]
    ComputeDiff["Compute content<br>differences,"]
    MinDisk["Minimal disk writes"]
    MigrateAll["Migrate all content"]
    SavingDocs["Saving Documents"]
    ContentWarnings["Content warnings"]
    NavWeightMigration["mkdocs-nav-weight migrate"]

    navData -->|"commits as"| NavSnaps
    UndoRedo -->|"tracks active"| NavSnaps
    NavRenderer -->|"renders from"| NavSnaps
    NavRenderer -->|"get active"| UndoRedo
    NavSnaps -->|"via Nav Ctrl+S"| SavePlanner
    SavePlanner -->|"which will"| ComputeDiff
    ComputeDiff -->|"write to disk with"| MinDisk
    MinDisk -->|"creates a snapshot diff to be written to disk"| MigrateAll
    MigrateAll -.- |"rewrites markdown content so there are no broken cross-document links"| MigrateAll
    SavingDocs -->|"via content Ctrl+S"| SavePlanner
    ContentWarnings -->|"display from"| NavSnaps
    ContentWarnings --> navData
    NavWeightMigration --> navData
    NavWeightMigration -->|"from mkdocs.yml nav"| NavSnaps
```



## Save Execution Pipeline

```mermaid
flowchart LR
    SavePlanner["Declarative Save Planner"]

    subgraph ExecGroup ["Execute saving content"]
        direction TB
        ComputeDiff["Compute content<br>differences,"]
        MinDisk["minimal disk writes,"]
        MigrateAll["Migrate all content"]

        ComputeDiff --> MinDisk
        MinDisk --> MigrateAll
    end

    subgraph BackendGroup ["Backend"]
        WysiwygAPI["wysiwyg plugin API server"]
        LiveEditAPI["live edit plugin API websocket server"]
    end

    SavePlanner -->|"write to disk with"| ExecGroup
    ComputeDiff -.- |"plans movement from current to desired state on disk"| ComputeDiff
    MinDisk -.- |"reorganizes files as fast as possible to desired state on disk"| MinDisk
    MigrateAll -.- |"rewrites markdown content so there are no broken cross-document links"| MigrateAll
    MinDisk --> BackendGroup
    MigrateAll --> BackendGroup
    BackendGroup -.- |"read and write content to disk"| BackendGroup
```



## Source of Truth

`liveWysiwygNavData` (and the snapshots derived from it) is the sole source of truth for all navigation operations — item positioning, movement, sibling lookup, weight computation, and save planning. The DOM is a rendering target rebuilt from the active snapshot on every change; it is never queried for item position, parent–child relationships, or ordering. DOM attributes (`data-nav-uid`, `data-nav-src-path`) exist only for event-to-data bridging (mapping click targets back to navData items) and post-operation visual focus (scrolling a moved item into view).

## Subsystem Directory

### Hierarchy Overview

```
UI Subsystem
  |-- Modes of Operation
  |     |-- Readonly Mode (Layer 0)
  |     |-- Unfocused Mode (Layer 1)
  |     |-- Focus Mode (Layer 2)
  |     |-- Mermaid Mode (Layer 3)
  |     |-- Help Mode (Layer 5)
  |-- Mermaid Subsystem
  |     |-- Mermaid Mode (UI, Layer 3 in mode hierarchy)
  |     |-- Vendor Subsystem (mermaid.js + mermaid-live-editor)
  |     |-- Monaco Subsystem (embedded code editor API + runtime discovery)
  |     |-- Mermaid Diagram Selection (SVG click-to-select + load monitor)
  |     |-- MkDocs YAML Mermaid Config (server-side detection + client-side auto-fix)
  |-- Toolbars
  |-- Content Editing
  |     |-- Editor Core
  |     |-- Cursor & Selection
  |     |-- Content History
  |     |     |-- History Mode (UI, Layer 4 in mode hierarchy)
  |     |-- Keyboard
  |     |-- Progressive Select All
  |     |-- Markdown Awareness
  |     |-- Tables
  |     |-- Dialog UX
  |     |-- Table of Contents
  |     |-- Heading Migration (rename detection, anchor rewriting, dead link anchor validation)
  |     |-- Help System (Layer 5 modal, context-sensitive shortcut reference)
  |-- Nav Menu
  |     |-- Navigation Menu (data model, snapshots, batch editing)
  |     |-- Nav Renderer (exclusive DOM update authority)
  |     |-- File & Page Management
  |     |-- Nav Migration
  |-- Theming & Layout
  |     |-- Theme
  |     |-- Layout
  |-- Browser Compatibility

Backend Subsystem
  |-- Changing mkdocs.yml (transforms, dual-write, cardinal rules)
  |-- MkDocs YAML Mermaid Config (config detection in plugin.py)
  |-- Save Pipeline (= Declarative Save Planner)
  |     |-- Snapshot Diff
  |     |-- Write Planner
  |     |-- Content Refactoring
  |-- Content Scanning
  |-- Cautions
  |-- API Server (wysiwyg plugin REST API)
  |     |-- Mermaid Session Server (session-based content brokering)
  |-- WebSocket Server (upstream live-edit-plugin)
  |-- Application Storage

VS Code Extension Subsystem
  |-- Binary Download Engine (TS port of yml-install-files)
  |-- Environment Manager (venv, packages, upgrade, uninstall)
  |-- Configuration Generator (mkdocs.yml generation via js-yaml)
  |-- Port Manager (cross-platform port availability)
  |-- Server Manager (mkdocs serve lifecycle)
  |-- Auto-Docs Manager (temp docs, frontmatter, asset detection)
  |-- Build / Init Managers
  |-- UI (commands, context menus, status bar, sidebar panel)

Development Workflow (project conventions)
```

### UI Subsystem

#### Modes of Operation

- [DESIGN-modes-of-operation.md](ui/DESIGN-modes-of-operation.md) -- Mode lifecycle and transition contracts.
- [DESIGN-unfocused-mode.md](ui/DESIGN-unfocused-mode.md) -- Inline editing on the readonly page.
- [DESIGN-focus-mode.md](ui/DESIGN-focus-mode.md) -- Fullscreen editing overlay.
- [DESIGN-mermaid-mode.md](mermaid/DESIGN-mermaid-mode.md) -- Mermaid diagram editor (Layer 3 mode).

#### Mermaid Subsystem

Mermaid-related design documents are organized under `docs/design/mermaid/` while the architecture overview preserves the conceptual hierarchy.

- [DESIGN-mermaid-mode.md](mermaid/DESIGN-mermaid-mode.md) -- Layer 3 UI mode for mermaid diagram editing.
- [DESIGN-vendor-subsystem.md](mermaid/DESIGN-vendor-subsystem.md) -- Vendored mermaid.js and mermaid-live-editor.
- [DESIGN-monaco-subsystem.md](mermaid/DESIGN-monaco-subsystem.md) -- Embedded Monaco code editor API, runtime discovery, and content access paths.
- [DESIGN-mermaid-diagram-selection.md](mermaid/DESIGN-mermaid-diagram-selection.md) -- SVG click-to-select heuristics, text normalization, initial load monitor.
- [DESIGN-mkdocs-yml-mermaid-config.md](mermaid/DESIGN-mkdocs-yml-mermaid-config.md) -- Server-side config detection and client-side auto-fix.

#### Toolbars

- [DESIGN-toolbars.md](ui/DESIGN-toolbars.md) -- WYSIWYG toolbar drawer and controls.

#### Content Editing

- [DESIGN-enter-bubble-navigation.md](ui/DESIGN-enter-bubble-navigation.md) -- Enter key block container exit.
- [DESIGN-targeted-markdown-revert.md](ui/DESIGN-targeted-markdown-revert.md) -- Backspace revert behavior.
- [DESIGN-raw-html-preservation.md](ui/DESIGN-raw-html-preservation.md) -- Raw HTML and comment preservation.
- [DESIGN-image-insertion-resize.md](ui/DESIGN-image-insertion-resize.md) -- Image insertion, resize, and settings.
- [DESIGN-readonly-selection-heuristics.md](ui/DESIGN-readonly-selection-heuristics.md) -- Read-only to edit mode text selection.
- [DESIGN-unified-content-undo.md](ui/DESIGN-unified-content-undo.md) -- DAG-based content undo/redo.
- [DESIGN-history-mode.md](ui/DESIGN-history-mode.md) -- History Mode (Layer 4) — visual DAG history UI with branch picker, overlay, and preview.
- [DESIGN-uninterrupted-content-save.md](ui/DESIGN-uninterrupted-content-save.md) -- Auto-save and persistent content history.
- [DESIGN-centralized-keyboard.md](ui/DESIGN-centralized-keyboard.md) -- Three-tier keyboard handling.
- [DESIGN-progressive-select-all.md](ui/DESIGN-progressive-select-all.md) -- Progressive Ctrl+A selection and cut/copy auto-expansion.
- [DESIGN-markdown-awareness.md](ui/DESIGN-markdown-awareness.md) -- Preprocess/postprocess round-trip and DOM enhancement contract.
- [DESIGN-tables.md](ui/DESIGN-tables.md) -- Table editing, formatting pipeline, alignment, width management, and settings popover.
- [DESIGN-popup-dialog-ux.md](ui/DESIGN-popup-dialog-ux.md) -- Unified dialog interaction model.
- [DESIGN-table-of-contents.md](ui/DESIGN-table-of-contents.md) -- Right sidebar TOC panel.
- [DESIGN-heading-migration.md](ui/DESIGN-heading-migration.md) -- Heading rename detection, anchor link migration, dead link anchor validation.
- [DESIGN-help-system.md](ui/DESIGN-help-system.md) -- Layer 5 help modal, context-sensitive shortcut reference.

#### Nav Menu

- [DESIGN-focus-nav-menu.md](ui/DESIGN-focus-nav-menu.md) -- Navigation menu and batch editing.
- [DESIGN-snapshot-nav-architecture.md](ui/DESIGN-snapshot-nav-architecture.md) -- Snapshot-driven nav architecture.
- [DESIGN-file-management.md](ui/DESIGN-file-management.md) -- File management and movement.
- [DESIGN-nav-weight-normalization.md](ui/DESIGN-nav-weight-normalization.md) -- Weight normalization algorithm.
- [DESIGN-nav-migration.md](ui/DESIGN-nav-migration.md) -- Nav-to-weight migration.

#### Theming & Layout

- [DESIGN-theme-detection.md](ui/DESIGN-theme-detection.md) -- Theme detection and CSS variables.
- [DESIGN-layout.md](ui/DESIGN-layout.md) -- Positioning, animation, scroll, z-index, dropdown dismissal, and reparenting contracts.

#### Browser Compatibility

- [DESIGN-browser-compatibility.md](ui/DESIGN-browser-compatibility.md) -- Browser-specific quirks catalog.

### Backend Subsystem

#### Changing mkdocs.yml

- [DESIGN-changing-mkdocs-yml.md](backend/DESIGN-changing-mkdocs-yml.md) -- Centralized mkdocs.yml modification procedures, transform inventory, and cardinal rules.

#### MkDocs YAML Mermaid Config

- [DESIGN-mkdocs-yml-mermaid-config.md](mermaid/DESIGN-mkdocs-yml-mermaid-config.md) -- Config detection in `plugin.py`; client-side warning and auto-fix in integration script.

#### Save Pipeline

- [DESIGN-declarative-save-planner.md](backend/DESIGN-declarative-save-planner.md) -- Declarative two-phase save.

#### Content Scanning

- [DESIGN-content-scanning.md](backend/DESIGN-content-scanning.md) -- Dead link scanning and link rewriting.

#### Cautions

- [DESIGN-cautions.md](backend/DESIGN-cautions.md) -- Per-page warning system.

#### API Server

The WYSIWYG API server (`api_server.py`) exposes the following endpoint groups:

- **Link checking & file operations**: `POST /check-links`, `/file-exists`, `/list-items`, `/rename-folder`, `/delete-folder`, `/move-file`, `/delete-file`, `/unreferenced-files` — documented in [DESIGN-content-scanning.md](backend/DESIGN-content-scanning.md).
- **Build coordination**: `GET /link-index`, `GET /build-epoch`.
- **Mermaid sessions**: `POST|GET|PUT|DELETE /mermaid-session` — documented in [DESIGN-mermaid-session-server.md](backend/DESIGN-mermaid-session-server.md).
- **Mermaid editor assets**: `GET /mermaid-editor/*` — serves vendored mermaid-live-editor static files.
- **Health**: `GET /health` — unified readiness check. Probes the companion MkDocs HTTP server (HTTP HEAD) and WebSocket server (full WebSocket connect, receive `{"action":"connected"}` greeting, clean close with status 1000) and returns a JSON object with per-service status and an aggregate `ready` boolean. Returns `200` when all services are ready, `503` otherwise. Requires `http_port` and `websocket_port` to be passed at server start time; when either is `0` the corresponding check is skipped and reported as `false`.

#### Application Storage

- [DESIGN-application-storage.md](backend/DESIGN-application-storage.md) -- localStorage schema and persistence.

### CLI Utility

- [DESIGN-cli-utility.md](DESIGN-cli-utility.md) -- `techdocs-preview.sh` server lifecycle, configuration generation, dual mkdocs.yml mechanism, and mermaid superfences integration.

### VS Code Extension Subsystem

- [DESIGN-vscode-extension-subsystem.md](DESIGN-vscode-extension-subsystem.md) -- Cross-platform TypeScript extension reimplementing CLI features. Feature parity table, shared contracts, binary download engine, UI surface, build and publishing.

