# Win11Debloat Administrator & Developer Guide

This guide is for system administrators, IT deployers, and developers who need to understand how Win11Debloat works internally: its architecture, the configuration files that drive it, the registry-application engine, how to deploy it at scale, its security model, and where to extend it. For day-to-day usage and the full option reference, see the User Guide.

---

## 1. Executive Summary

Win11Debloat is a **config-driven PowerShell + WPF application** for debloating and customizing Windows 11/10. Its defining architectural trait is that **the behavior lives in data, not code**: a small, generic PowerShell engine reads JSON configuration files and `.reg` registry files to decide what to do. Adding a new tweak usually means adding a `.reg` file and a JSON entry — not writing PowerShell.

| Aspect | Summary |
|---|---|
| **Language / stack** | Windows PowerShell (5.1+) with a WPF (XAML) graphical front end. No compiled binaries, no external runtime. |
| **Distribution** | A GitHub release `.ZIP`, or a one-line `irm | iex`-style downloader (`https://debloat.raphi.re/`). |
| **Entry point** | `Win11Debloat.ps1` — a parameter block (~100 switches) plus an orchestrator that dot-sources every module under `Scripts/`. |
| **Ground truth** | `Config/Apps.json` (removable apps), `Config/Features.json` (tweak catalog), `Config/DefaultSettings.json` (default preset), and the `Regfiles/` tree. |
| **How tweaks apply** | Each tweak maps to a `.reg` file imported via `reg import`, with a hand-rolled PowerShell fallback parser if that fails. |
| **Safety model** | Per-run JSON registry backup of only the touched values, optional System Restore point, and a paired "undo" `.reg` for every tweak. |
| **Privileges** | Requires Administrator; refuses to run in Constrained Language Mode. |
| **Version** | Stamped in-script as `$script:Version` (currently `2026.05.20`). |

---

## 2. Architecture

### 2.1 High-level component map

```text
                         Run.bat ──► elevates ──► Win11Debloat.ps1
  irm debloat.raphi.re ──────────────────────────────┘
                                                      │
                       ┌──────────────────────────────┴───────────────────────────┐
                       │              Win11Debloat.ps1 (orchestrator)               │
                       │  • param block = the full CLI/feature surface              │
                       │  • admin + language-mode guards                            │
                       │  • dot-sources every Scripts/**/*.ps1                      │
                       │  • loads Config/Features.json into $script:Features        │
                       │  • routes: GUI ▸ CLI ▸ Config/Defaults/SavedSettings       │
                       └───────┬───────────────────────┬───────────────────────────┘
                               │                       │
              ┌────────────────▼─────┐       ┌─────────▼──────────────┐
              │  Scripts/GUI (WPF)   │       │  Scripts/CLI (text)    │
              │  Schemas/*.xaml      │       │  menu / pending changes │
              └────────────────┬─────┘       └─────────┬──────────────┘
                               └───────────┬───────────┘
                                           ▼
                        ┌──────────────────────────────────────────┐
                        │   ExecuteAllChanges (Scripts/Features)     │
                        │   1. registry backup (JSON snapshot)       │
                        │   2. optional restore point                │
                        │   3. ExecuteParameter per selected key     │
                        └───────────────┬───────────────────────────┘
                                        ▼
        ┌───────────────────────────────┼─────────────────────────────────┐
        ▼                               ▼                                   ▼
  ImportRegistryFile             RemoveApps                         EnableWindowsFeature
  (Regfiles/*.reg → reg import,  (Appx + provisioned;               (DISM via
   PS fallback writer)           winget for OneDrive/Edge)           Enable-WindowsOptionalFeature)
```

### 2.2 The data-driven principle

Win11Debloat separates **what** from **how**:

- **What** to do is described declaratively in `Config/*.json` and the `Regfiles/` tree.
- **How** to do it is a generic interpreter in `Scripts/`. The central dispatcher, `ExecuteParameter`, looks up each selected option in `$script:Features` (loaded from `Features.json`). If the feature carries a `RegistryKey`, it simply imports that `.reg` file. Only options with non-registry behavior (app removal, enabling Windows features, clearing the Start menu) have bespoke code branches.

This is why the user-facing surface — the ~100 parameters, the tweak catalog, the app list — is best understood by reading the **JSON and `.reg` files**, not the PowerShell.

### 2.3 Directory layout

| Path | Contents |
|---|---|
| `Win11Debloat.ps1` | Entry point: parameter block, guards, module imports, run routing. |
| `Run.bat` | Convenience launcher; finds Windows Terminal or falls back to PowerShell, requests elevation. |
| `Config/` | `Apps.json`, `Features.json`, `DefaultSettings.json`; at runtime also `LastUsedSettings.json` and `CustomAppsList`. |
| `Regfiles/` | The `.reg` files for the **current user / online hive** (one apply + one undo per tweak). |
| `Regfiles/Sysprep/` | The `.reg` files used when targeting an **offline hive** (`-User` / `-Sysprep`), plus `Uninstall_*.reg` scheduled-task installers. |
| `Regfiles/Undo/` | Revert `.reg` files. |
| `Schemas/` | WPF XAML window definitions (MainWindow, AppSelectionWindow, ApplyChangesWindow, AboutWindow, RestoreBackupWindow, SharedStyles, BubbleHint, MessageBoxWindow, ImportExportConfigWindow). |
| `Scripts/AppRemoval/` | App-package removal, WinGet helpers, forceful Edge removal. |
| `Scripts/CLI/` | Text menu, headers, pending-change printout. |
| `Scripts/Features/` | The change-execution engine, registry backup/restore, restore points, Start-menu replacement. |
| `Scripts/FileIO/` | JSON loading/saving, settings persistence, app-list parsing/validation. |
| `Scripts/GUI/` | WPF window controllers and dialogs. |
| `Scripts/Helpers/` | Registry path/operation helpers, user/SID resolution, parameter helpers, the `.reg` parser. |
| `Scripts/Threading/` | `Invoke-NonBlocking` background runspace + `DoEvents` UI pump. |
| `Assets/Start/` | `start2.bin` Start-menu layout template(s). |

### 2.4 Run routing

`Win11Debloat.ps1` decides how to run based on the parameters it receives:

1. **No parameters** → launch the GUI (`Show-MainWindow`). If WPF can't load, fall back to the CLI menu.
2. **`-CLI`, `-User`, `-Sysprep`, or `-AppRemovalTarget`** → use the CLI menu (`launchInCLI` is set true for deployment-oriented runs).
3. **`-RunDefaults` / `-RunDefaultsLite`** → load `DefaultSettings.json` and the chosen app option.
4. **`-RunSavedSettings`** → load `LastUsedSettings.json`.
5. **`-Config <file>`** → import a config JSON into parameters.
6. **Only tweak/app switches given** → apply them directly.

A parameter is classified as a **control parameter** (`$script:ControlParams`: `WhatIf`, `Confirm`, `Verbose`, `Debug`, `LogPath`, `Silent`, `Sysprep`, `User`, `NoRestartExplorer`, `RunDefaults`, `RunDefaultsLite`, `RunSavedSettings`, `Config`, `RunAppsListGenerator`, `CLI`, `AppRemovalTarget`) or an **actionable parameter** (a tweak/app). If only control parameters are present, the script exits without changes (`The script completed without making any changes.`).

### 2.5 Concurrency model

Win11Debloat is single-process, but it must keep the WPF UI responsive during long operations (app removal, DISM, restore points). `Scripts/Threading/Invoke-NonBlocking.ps1` runs work in a **background PowerShell runspace** while the UI thread pumps messages via `DoEvents` (~60 fps). In CLI mode the same function runs the scriptblock inline. Several operations also accept a `-TimeoutSeconds` so a hung call (e.g. `winget list`, `Checkpoint-Computer`) can't freeze the tool.

---

## 3. System Requirements

| Item | Requirement |
|---|---|
| OS | Windows 11 (full feature set) or Windows 10 (subset). Build number gates individual tweaks. |
| Edition | Most features work on Home/Pro. `EnableWindowsSandbox` requires Pro/Enterprise/Workstation. |
| Privileges | Administrator (enforced at startup). |
| PowerShell | 5.1 (in-box) or 7+, in **Full Language** mode. |
| WinGet | Required only for OneDrive/Edge removal (App Installer ≥ recent). |
| .NET / WPF | Desktop WPF assemblies (present on Windows desktop SKUs). Absent on Server Core → automatic CLI fallback. |

> [!NOTE]
> Win11Debloat ensures `System32` is on `PATH` for its session (it warns and prepends it if missing), because it shells out to `reg`, `powercfg`, `quser`, and `winget`.

---

## 4. Configuration Mastery

All four JSON files share a top-level `Version` field that the loader validates; a mismatch is rejected.

### 4.1 `Config/Apps.json` — the removable-app catalog

Defines every app the tool knows how to remove, plus presets.

```json
{
  "Version": "1.1",
  "Apps": [
    {
      "FriendlyName": "Clipchamp",
      "AppId": "Clipchamp.Clipchamp",
      "Description": "Video editor from Microsoft",
      "SelectedByDefault": true,
      "Recommendation": "safe"
    }
  ],
  "Presets": [
    { "Name": "Xbox Gaming apps", "AppIds": ["Microsoft.GamingApp", "Microsoft.XboxGameOverlay", "Microsoft.XboxGamingOverlay"] }
  ]
}
```

| Field | Meaning |
|---|---|
| `FriendlyName` | Display name in the picker. |
| `AppId` | The package family name. **May be a string or an array** (e.g. Edge is `["Microsoft.Edge", "XPFFTQ037JWMHS"]`). |
| `Description` | Shown in the picker; often notes "Discontinued" or warnings. |
| `SelectedByDefault` | Whether it's checked when "default" removal is chosen. |
| `Recommendation` | `safe`, `optional`, or `unsafe` — drives the colored dot and confirmation prompts. |

> [!IMPORTANT]
> Apps marked `unsafe` (Microsoft Store, Windows Terminal, Xbox Identity Provider, Xbox TCUI/Speech-to-Text, Get Help, Edge) trigger an explicit confirmation dialog (`ConfirmUnsafeAppRemoval`) because removing them can break sign-in, app installation, or the running console.

### 4.2 `Config/Features.json` — the tweak catalog

This is the heart of the data-driven design. Each entry maps a tweak to its `.reg` files and constraints:

```json
{
  "FeatureId": "DisableTelemetry",
  "Label": "Disable telemetry, tracking & targeted ads",
  "ToolTip": "...",
  "Category": "Privacy & Suggested Content",
  "RegistryKey": "Disable_Telemetry.reg",
  "ApplyText": "Disabling telemetry...",
  "RegistryUndoKey": "Enable_Telemetry.reg",
  "MinVersion": null,
  "MaxVersion": null
}
```

| Field | Meaning |
|---|---|
| `FeatureId` | Matches the command-line switch name and the key in `$script:Features`. |
| `Label` / `ToolTip` | UI text and the line shown in the pending-changes summary. |
| `Category` | Groups the tweak in the Tweaks tab (`null` for app-removal pseudo-features). |
| `RegistryKey` | The `.reg` file applied when the tweak is enabled. `null` for tweaks with custom code (e.g. `DisableWidgets`, `EnableWindowsSandbox`, `ClearStart`). |
| `RegistryUndoKey` | The `.reg` file that reverts it. |
| `MinVersion` / `MaxVersion` | Windows build gates. The loader skips a tweak outside this range. |
| `RequiresReboot` | Present and `true` when a reboot is needed (e.g. `DisableAnimations`, `DisableMouseAcceleration`, `DisableStickyKeys`, the optional features). |

`Features.json` also defines `Categories` (with Segoe MDL2 icon glyphs) and `UiGroups` — radio-style groups where several `FeatureIds` are mutually exclusive (taskbar search style, multi-monitor combine modes, Explorer launch location, drive-letter position, Alt+Tab tab count).

> [!TIP]
> To add a tweak: drop `Apply.reg` and `Undo.reg` into `Regfiles/` (and `Regfiles/Sysprep/` if it should support offline application), then add a `Features.json` entry pointing at them. No PowerShell change is needed for a pure registry tweak.

### 4.3 `Config/DefaultSettings.json` — the "Default mode" preset

A flat list of `{ Name, Value }` settings applied by `-RunDefaults`/`-RunDefaultsLite`. The shipped default enables 17 privacy/quality tweaks (telemetry, suggestions, Edge ads, lock-screen tips, Bing, Store suggestions, Copilot, Recall, Click-to-Do, AI autostart, widgets, chat, known file extensions, drag tray, 3D objects, Modern Standby networking) plus `CreateRestorePoint`.

### 4.4 Runtime files

| File | Written when | Purpose |
|---|---|---|
| `Config/LastUsedSettings.json` | Every run, by `SaveSettings` | Enables `-RunSavedSettings` and the CLI "option 3". Version `1.0`, same schema as DefaultSettings. |
| `Config/CustomAppsList` | App picker "save", by `SaveCustomAppsListToFile` | One app ID per line; consumed by `-RemoveAppsCustom`. Comments (`#`) and blanks ignored. |
| `Backups/Win11Debloat-RegistryBackup-<ts>.json` | Before applying registry tweaks | Pre-change snapshot for **Restore backup**. |
| `Logs/Win11Debloat.log` | Every run (`Start-Transcript`) | Full session transcript. |

### 4.5 The deployment config format (`-Config`)

`ImportConfigToParams` reads a version `1.0` JSON with up to three sections, mapping each to parameters:

| Section | Keys | Becomes |
|---|---|---|
| `Apps` | array of app IDs | `-RemoveApps -Apps "<joined,ids>"` |
| `Tweaks` | `{ Name, Value:true }` | the matching tweak switch (build-gated; incompatible ones skipped) |
| `Deployment` | `CreateRestorePoint` | `-CreateRestorePoint` |
| | `RestartExplorer: false` | `-NoRestartExplorer` |
| | `UserSelectionIndex: 1` + `OtherUsername` | `-User <name>` |
| | `UserSelectionIndex: 2` | `-Sysprep` |
| | `AppRemovalScopeIndex: 0/1/2` (+`OtherUsername`) | `-AppRemovalTarget AllUsers/CurrentUser/<name>` |

This is exactly what the GUI's **Export config** produces, making it the canonical artifact for repeatable deployments.

---

## 5. The Tweak-Application Engine

### 5.1 `ExecuteAllChanges` (orchestrator)

Located in `Scripts/Features/ExecuteChanges.ps1`. The sequence:

1. Build the list of **actionable** parameter keys (excluding control params, `Apps`, `CreateRestorePoint`).
2. If any selected feature is registry-backed, **create a registry backup first** (`New-RegistrySettingsBackup`). A backup failure aborts the run before any change.
3. If `-CreateRestorePoint` was set, create a System Restore point.
4. For each actionable key, call `ExecuteParameter`, reporting progress through `$script:ApplyProgressCallback` (wired to the GUI progress bar).
5. Tally any registry import failures and report them.

### 5.2 `ExecuteParameter` (dispatcher)

For a feature with both `RegistryKey` and `ApplyText`, it calls `ImportRegistryFile`. A few features have **extra logic layered on top**:

| FeatureId | Extra behavior |
|---|---|
| `DisableBing` | Also removes the `Microsoft.BingSearch` app. |
| `DisableCopilot` | Also removes the `Microsoft.Copilot` app. |
| `DisableWidgets` | Stops `*Widget*` processes, then removes 3 widget packages. |
| `RemoveCommApps` / `RemoveW11Outlook` / `RemoveGamingApps` / `RemoveHPApps` | Remove fixed app-ID lists. |
| `ClearStart` / `ReplaceStart` (+AllUsers) | Replace `start2.bin` from a template. |
| `EnableWindowsSandbox` / `EnableWindowsSubsystemForLinux` | DISM `Enable-WindowsOptionalFeature` (Sandbox = `Containers-DisposableClientVM`; WSL = `VirtualMachinePlatform` + `Microsoft-Windows-Subsystem-Linux`). |
| `DisableStoreSearchSuggestions` | Denies the `EVERYONE` group access to the Store's `store.db` (per-user, or all users in Sysprep). |

### 5.3 `ImportRegistryFile` — apply with fallback

`Scripts/Features/ImportRegistryFile.ps1` is the workhorse:

1. Choose the source directory: `Regfiles/` normally, or `Regfiles/Sysprep/` when `-User`/`-Sysprep` is active (offline hive).
2. For offline application, `reg load HKU\Default <NTUSER.DAT>` mounts the target user's hive.
3. Run `reg import <file>` inside `Invoke-NonBlocking`.
4. **If `reg import` fails** (non-zero exit or error), fall back to a hand-rolled PowerShell writer (`Invoke-RegistryOperationsFromRegFile`) that parses the `.reg` and applies each operation via the .NET registry API.
5. Always `reg unload HKU\Default` in a `finally` block.

This dual path is why most "failed to write to the registry" errors self-recover.

### 5.4 The `.reg` parser (`Get-RegFileOperations`)

`Scripts/Helpers/Get-RegFileOperations.ps1` parses a `.reg` file into structured operations, supporting:

- Continuation lines (trailing `\`), comments (`;`), and the editor header.
- `[-Key]` → `DeleteKey`; `"name"=-` → `DeleteValue`; `@=` → default value.
- Value types: `dword:`, `qword:`, `hex:`/`hex(2)`/`hex(7)` (Binary / expandable string / multi-string), and quoted strings.

`Invoke-RegistryOperation` then applies each via `Get-RegistryRootKey` + `Split-RegistryPath` (supports `HKCU/HKLM/HKCR/HKU/HKCC`, normalizes `HKU\.DEFAULT`). Access-denied operations are logged and skipped, and a "could apply nothing" condition throws.

### 5.5 Backup & restore

- **Backup** (`BackupRegistryState.ps1` + `BackupRegistrySnapshotCapture.ps1`): for the selected registry-backed features, it derives a *capture plan* of exactly which keys/values each `.reg` touches, snapshots their current state (value, kind, sub-keys), and writes a JSON payload (`Version`, `Target`, `SelectedFeatures`, `RegistryKeys`) to `Backups/`. Target can be `CurrentUser:<name>`, `User:<name>`, or `DefaultUserProfile`.
- **Restore** (`RestoreRegistryBackup.ps1` + `RestoreRegistryApplyState.ps1`): validates the backup (version, target, and that every snapshot path is *allow-listed* by the recorded `SelectedFeatures` — preventing tampered backups from writing arbitrary keys), then re-applies each snapshot, loading the offline hive when the target is a user/default profile.

> [!NOTE]
> The restore allow-list check is a deliberate integrity control: a backup may only touch registry paths that its declared features are known to modify. Snapshots referencing unexpected paths fail validation.

### 5.6 App removal (`RemoveApps`)

`Scripts/AppRemoval/RemoveApps.ps1` resolves a target scope (`AllUsers` default, `CurrentUser`, or a specific user SID) and then, per app:

- **OneDrive / Edge** → WinGet uninstall. In `-User`/`-Sysprep` (offline) mode it instead imports an `Uninstall_*.reg` that schedules the uninstall for the target user. If WinGet can't remove Edge, it offers `ForceRemoveEdge`.
- **All other apps** → `Get-AppxPackage … | Remove-AppxPackage` (and `Remove-ProvisionedAppxPackage` for AllUsers, so the app doesn't return for new users).

`ForceRemoveEdge` (`Scripts/AppRemoval/ForceRemoveEdge.ps1`) sets `AllowUninstall`, creates a stub, runs Edge's own uninstaller with `--force-uninstall`, removes shortcuts, and cleans `Run` keys.

### 5.7 Finishing up

`RestartExplorer` warns about any selected `RequiresReboot` features, then restarts `explorer.exe` — unless `-User`/`-Sysprep`/`-NoRestartExplorer` is set, or the PowerShell process architecture doesn't match the OS (in which case it asks you to reboot).

---

## 6. Deployment

### 6.1 Single machine, unattended

```powershell
.\Win11Debloat.ps1 -RunDefaults -Silent -CreateRestorePoint
```

### 6.2 Fleet deployment with a shared config

1. Build a config in the GUI → **Export config** → `debloat.json`.
2. Distribute the script folder + `debloat.json` (GPO, Intune, SCCM, MDT, or a setup script).
3. Run per machine:

```powershell
.\Win11Debloat.ps1 -Config "C:\Deploy\debloat.json" -Silent
```

### 6.3 Image / golden-master deployment (Sysprep)

Apply to the **Default** profile so every new user inherits the changes:

```powershell
.\Win11Debloat.ps1 -RunSavedSettings -Sysprep -Silent
```

- Uses `Regfiles/Sysprep/` against the offline `Default\NTUSER.DAT` hive.
- OneDrive/Edge removal is deferred via a per-user scheduled task.
- Explorer is **not** restarted; finalize during image capture / first boot.
- **Not supported on Windows 10.**

### 6.4 Targeting another (signed-out) user

```powershell
.\Win11Debloat.ps1 -RunSavedSettings -User "Alice" -Silent
```

The target must exist and be **signed out** (validated via `quser`); you cannot target your own account this way.

> [!TIP]
> Combine `-LogPath "<share>\logs"` to centralize transcripts across a fleet, and `-NoRestartExplorer` when you'll reboot as part of the deployment anyway.

---

## 7. Operations

| Task | How |
|---|---|
| **Logs** | `Logs\Win11Debloat.log` (per-session transcript). `Run.bat` also writes `Logs\Win11Debloat-Run.log`. |
| **Verify a tweak applied** | Check the log for the `> <ApplyText>...` line and any red error lines; reboot for `RequiresReboot` tweaks. |
| **Roll back a run** | GUI menu → **Restore backup** → choose the `Backups/…json` for that run. |
| **System rollback** | System Restore (if a restore point was created). |
| **Re-run identically** | `-RunSavedSettings` or `-Config`. |
| **Reset to "ask me again"** | Delete `Config/LastUsedSettings.json` (the script auto-removes it if empty). |

> [!NOTE]
> System Restore points are throttled by Windows to one per 24 hours; Win11Debloat detects a recent point and skips creating a duplicate rather than failing.

---

## 8. Security Analysis

| Area | Finding |
|---|---|
| **Execution model** | The Quick method runs remote code: `irm "https://debloat.raphi.re/"` piped into a scriptblock. This is `iex`-style remote execution — only acceptable because the source is trusted and HTTPS-served. For high-assurance environments, **use the Traditional/Advanced method** with a downloaded, reviewed `.ZIP`. |
| **Privilege** | Requires Administrator and self-elevates via `Start-Process -Verb RunAs`. All registry/appx/feature changes run with full rights. |
| **Language-mode guard** | Refuses to run unless `LanguageMode -eq FullLanguage`, so it won't operate where policy has locked PowerShell down. |
| **Registry writes** | Confined to the keys defined in the shipped `.reg` files; the fallback writer skips access-denied operations rather than forcing them. |
| **Backup integrity** | Restore validates that every backed-up registry path is allow-listed by the backup's declared features (prevents a doctored backup from writing arbitrary keys). |
| **Offline hive handling** | `-User`/`-Sysprep` load/unload `HKU\Default` from the target `NTUSER.DAT`; unload always runs in `finally`. |
| **Destructive operations** | `ForceRemoveEdge` and removal of `unsafe` apps (Store, Terminal, Xbox Identity Provider) can break OS functionality — gated behind explicit confirmation outside Silent mode. |
| **No persistence/network** | No services installed, no telemetry, no outbound calls beyond the optional download and `winget` package operations. |
| **Code provenance** | MIT-licensed, open source; `ForceRemoveEdge` credits prior community work, Start-menu replacement credits an external how-to. |

> [!CAUTION]
> Treat `-Silent` carefully: it suppresses **all** confirmations, including the `unsafe`-app warnings. When scripting Silent runs, vet the app list so you don't unintentionally remove sign-in-critical packages.

---

## 9. Code Quality & Patterns

- **Declarative core.** New behavior is data (`.reg` + JSON), not code — low-risk to extend, easy to audit.
- **Single dispatcher.** `ExecuteParameter` centralizes how every option is applied; special cases are explicit `switch` arms.
- **Defensive I/O.** JSON loads validate `Version`; settings/app-list parsing tolerate comments, arrays-vs-strings, and missing files; user/SID resolution (`ResolveUserProfileContext`) tries NTAccount → local lookup → ProfileList registry, with a cache.
- **UI responsiveness as a first-class concern.** `Invoke-NonBlocking` + `DoEvents` keep WPF alive during slow operations; timeouts guard `winget`/restore-point calls.
- **Idempotent, reversible changes.** Every tweak pairs an apply and undo `.reg`; a pre-change snapshot is always taken.
- **Build-aware.** `MinVersion`/`MaxVersion` gates and a Modern-Standby capability check prevent applying inapplicable tweaks.

**Conventions:** `Verb-Noun` for new helper functions (e.g. `Get-RegFileOperations`, `Restore-RegistryKeySnapshot`); older top-level functions use bare names (`RemoveApps`, `ExecuteAllChanges`). Script-scoped state (`$script:Params`, `$script:Features`, `$script:GuiWindow`, `$script:CancelRequested`) is the shared bus between modules.

---

## 10. Module Reference

| Module | Key functions | Responsibility |
|---|---|---|
| `Win11Debloat.ps1` | (param block, routing) | Entry point, guards, imports, mode selection. |
| `Scripts/Features/ExecuteChanges.ps1` | `ExecuteAllChanges`, `ExecuteParameter` | Orchestrate and dispatch all changes. |
| `Scripts/Features/ImportRegistryFile.ps1` | `ImportRegistryFile` | Apply a `.reg` (reg import + PS fallback, offline-hive aware). |
| `Scripts/Features/BackupRegistryState.ps1` | `New-RegistrySettingsBackup`, `Get-SelectedFeatures` | Build & write the pre-change JSON backup. |
| `Scripts/Features/BackupRegistrySnapshotCapture.ps1` | `Get-RegistryBackupCapturePlans`, `Get-RegistryKeySnapshot` | Determine and capture exactly which keys/values to snapshot. |
| `Scripts/Features/RestoreRegistryBackup.ps1` | `Load-RegistryBackupFromFile`, `Normalize-RegistryBackup` | Load & validate a backup. |
| `Scripts/Features/RestoreRegistryApplyState.ps1` | `Restore-RegistryKeySnapshot`, `Invoke-WithLoadedRestoreHive` | Re-apply a validated backup. |
| `Scripts/Features/RegistryBackupValidation.ps1` | `Test-RegistryBackupMatchesSelectedFeatures` | Allow-list integrity check for restores. |
| `Scripts/Features/CreateSystemRestorePoint.ps1` | `CreateSystemRestorePoint` | Enable System Restore (if off) and checkpoint (24 h throttle aware). |
| `Scripts/Features/ReplaceStartMenu.ps1` | `ReplaceStartMenu(ForAllUsers)`, `RestoreStartMenu` | Swap/restore `start2.bin` per user / default profile. |
| `Scripts/Features/EnableWindowsFeature.ps1` | `EnableWindowsFeature` | DISM optional-feature enablement. |
| `Scripts/Features/DisableStoreSearchSuggestions.ps1` | `DisableStoreSearchSuggestions(ForAllUsers)` | ACL-deny on `store.db`. |
| `Scripts/Features/RestartExplorer.ps1` | `RestartExplorer` | Restart Explorer, warn on reboot-required tweaks. |
| `Scripts/AppRemoval/RemoveApps.ps1` | `RemoveApps` | Appx/provisioned removal; WinGet for OneDrive/Edge. |
| `Scripts/AppRemoval/ForceRemoveEdge.ps1` | `ForceRemoveEdge` | Last-resort Edge uninstall. |
| `Scripts/AppRemoval/GetInstalledAppsViaWinget.ps1` | `GetInstalledAppsViaWinget` | `winget list` (timeout-guarded). |
| `Scripts/CLI/*` | `ShowCLIMenuOptions`, `ShowCLIDefaultModeOptions`, `PrintPendingChanges`, `PrintHeader`, `AwaitKeyToExit` | Text-mode interface. |
| `Scripts/FileIO/*` | `LoadJsonFile`, `LoadSettings`, `SaveSettings`, `LoadApps*`, `ValidateAppslist`, `SaveToFile` | Config/settings/app-list persistence. |
| `Scripts/Helpers/*` | `Get-RegFileOperations`, `Invoke-RegistryOperationsFromRegFile`, `Split-RegistryPath`, `ImportConfigToParams`, `GenerateAppsList`, `ResolveUserProfileContext`, `Test-TargetUserName`, `CheckModernStandbySupport`, `AddParameter` | Registry/`.reg` engine, config import, user resolution, parameter plumbing. |
| `Scripts/GUI/*` | `Show-MainWindow`, `Show-AppSelectionWindow`, `Show-ApplyModal`, `Show-RestoreBackupWindow`, `Show-MessageBox`, `Show-ConfigWindow`, `Show-AboutDialog` | WPF windows and dialogs. |
| `Scripts/Threading/*` | `Invoke-NonBlocking`, `DoEvents` | Background runspace + UI message pump. |

---

## 11. Known Issues & Improvement Opportunities

Drawn from the public issue tracker and source review.

| Area | Observation | Suggested action |
|---|---|---|
| `reg import` failures (#542, #590, #591) | Localized "not all data written to registry" errors when keys are locked. The PS fallback writer mitigates most. | Continue to prefer the fallback; surface a clearer per-key message in the log. |
| Removing Windows Terminal mid-run (#600) | Crashes if launched inside Terminal. | Already warned via `ConfirmUnsafeAppRemoval`; consider detecting the parent process and refusing. |
| Microsoft/Xbox sign-in broken (#537) | Caused by removing Xbox Identity Provider (`unsafe`). | Reinforce the unsafe-app warning copy; the recommendation system already flags it. |
| WinGet listing failures (#535) | `winget list` times out or returns nothing. | The timeout guard exists; document App Installer update prominently (done in the User Guide). |
| Restore-point confusion (#584, #576) | Users think restore points were "lost." | This is Windows' 24 h throttle; messaging clarifies it but a tooltip in the GUI would help. |
| `UInt32` conversion (#579) | Edge case parsing a registry value. | Addressed in current releases; keep regression coverage on `Convert-RegValueData`. |
| Localization (#499, open feature request) | UI is English-only. | A resource-string layer (the XAML already uses `AutomationProperties.Name`) would enable translation. |
| Status of applied tweaks (#577, open) | No way to see current state of each tweak. | A read-back layer comparing live registry to feature `.reg` files could power a "current status" column. |

> [!NOTE]
> Feature requests in the tracker (disable service startup, OneDrive/Edge autostart, clear taskbar pins, Win10 Explorer ribbon, "My Computer" on desktop) indicate the natural growth areas — most could ship as new `Features.json` + `.reg` pairs without engine changes.

---

## 12. Quick Reference

```powershell
# Default debloat, unattended, with restore point
.\Win11Debloat.ps1 -RunDefaults -Silent -CreateRestorePoint

# Tweaks only (no app removal)
.\Win11Debloat.ps1 -RunDefaultsLite -Silent

# Re-apply last used settings
.\Win11Debloat.ps1 -RunSavedSettings -Silent

# Apply an exported config
.\Win11Debloat.ps1 -Config "C:\Deploy\debloat.json" -Silent

# Specific tweaks + targeted app removal
.\Win11Debloat.ps1 -DisableTelemetry -DisableBing -EnableDarkMode `
                   -RemoveApps -Apps "Microsoft.BingNews,Microsoft.ZuneVideo" -Silent

# New-user defaults (imaging)
.\Win11Debloat.ps1 -RunSavedSettings -Sysprep -Silent

# Another signed-out user
.\Win11Debloat.ps1 -RunSavedSettings -User "Alice" -Silent
```

| Key file | Role |
|---|---|
| `Win11Debloat.ps1` | Entry point / parameter surface |
| `Config/Features.json` | Tweak catalog (→ `.reg` mappings, build gates) |
| `Config/Apps.json` | Removable-app catalog + presets |
| `Config/DefaultSettings.json` | Default-mode preset |
| `Config/LastUsedSettings.json` | Saved selection (`-RunSavedSettings`) |
| `Config/CustomAppsList` | Custom app picker output (`-RemoveAppsCustom`) |
| `Regfiles/` · `Regfiles/Sysprep/` · `Regfiles/Undo/` | Apply / offline-apply / revert `.reg` files |
| `Backups/*.json` | Per-run registry backups |
| `Logs/Win11Debloat.log` | Session transcript |

---

_Generated June 2026 from Raphire/Win11Debloat at 33b77f1. AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
