Skip to content

Developer Guide

chaython edited this page Nov 15, 2026 · 1 revision

Developer guide

This page is for people who want to run WMT from source, build the executable, understand the code layout, or contribute changes. It describes the repository as it exists at version 6.9. User-facing behavior is covered on the feature pages; this page focuses on the development and release workflow.

Repository layout

Path Purpose
WMT-GUI.ps1 The entire application: a single Windows PowerShell script containing the WPF UI, feature logic, background workers, and settings management
Start_WMT_GUI.bat Recommended launcher; checks for launcher/script updates, validates the script, and starts it elevated
PS2EXE\Build-Exe.ps1 Local and CI build script that wraps WMT-GUI.ps1 into dist\WindowsMaintenanceTool.exe
PS2EXE\WMT.ico Application icon embedded in the EXE
.github\workflows\validate-powershell.yml Parse checks plus an extensive set of inline smoke and contract tests
.github\workflows\release-ps2exe.yml Builds, attests, and publishes rolling and stable releases; optionally submits package-manager updates
README.md Feature list, launch instructions, output locations, and user documentation
PRIVACY.md Authoritative privacy policy
CONTRIBUTING.md Contributor credits and project history
LICENSE MIT license
data\ Runtime data created next to the script or EXE; ignored by Git
dist\ Build output; ignored by Git

.gitignore excludes only /data/ and /dist/. Do not commit generated data, logs, backups, credentials, or build output.

How the application is put together

WMT is deliberately a single-file application. There is no solution file, compiled library, or separate UI project. At version 6.9, WMT-GUI.ps1 is several megabytes and contains more than 500 functions named with the Verb-WmtNoun convention.

Startup sequence

At a high level, the script:

  1. Declares param() switches used by internal worker modes (-AutoCleanWorker, -CleanerRefreshWorker, and their result-path parameters) and the -Debug theme diagnostic switch.
  2. Sets $AppVersion, which is the single source of truth for the build and release version.
  3. Resolves the script or EXE path and the data folder next to it.
  4. Loads WPF assemblies and initializes the theme, settings, logging, and main window.
  5. Builds the page navigation and loads page content on demand.
  6. Starts background timers and workers according to the saved settings.

Most of the UI is defined as XAML strings that are parsed into WPF windows and controls. Pages are hosted in a shared content area and switched by the sidebar buttons. Tool windows (Startup Manager, Restore Manager, Compact Compression, Disk Usage Analyzer, and various dialogs) are separate WPF windows created from their own XAML.

Background work

Long operations do not run on the UI thread. The script uses PowerShell runspace pools and child PowerShell processes, coordinated by a centralized background-operation manager. Some work is delegated back to the same script with internal switches, such as the automatic-clean worker and the cleaner-definition refresh worker.

When changing background code, preserve these patterns:

  • Report completion and failure through the existing operation manager so the UI can re-enable controls.
  • Do not update WPF controls directly from a worker thread; marshal back to the UI thread.
  • Keep cancellation and timeout behavior intact.
  • Log enough context to diagnose a failure without logging credentials.

Settings and data

Settings are stored in data\settings.json and saved atomically with a settings.json.bak backup. Missing keys are filled from defaults, and invalid JSON falls back to the backup. Feature-specific files (cleaner caches, registry backups, driver exports, library caches, and provider logs) also live under data. See Settings and Data for the full list.

When adding a setting:

  1. Add the key and default to the settings defaults table.
  2. Add a typed getter/setter if the value needs validation or coercion.
  3. Read the saved value during initialization, not at first use.
  4. Save through the existing settings save path so the atomic write and backup behavior are preserved.
  5. Document the setting on the relevant feature page.

Logging and diagnostics

  • The Activity Log in the main window is in-memory and is cleared on exit.
  • Write-GuiLog writes to that log and, when enabled, to debug output.
  • data\last-crash.txt is written by the crash handler with context and recent log lines.
  • Provider install transcripts are written under data\package-install-logs.
  • -Debug enables theme/DWM diagnostics only. The Debug Logs toggle enables broader internal diagnostic logging.

Local development setup

Requirements

  • Windows 10 or Windows 11
  • Windows PowerShell 5.1 (the supported runtime)
  • Administrator rights for most maintenance actions
  • PowerShell Gallery access only if you want the build script to install PS2EXE
  • Optional provider tools only for the features you intend to test

CI also runs isolated runtime tests under PowerShell 7 (pwsh), but the application is designed around Windows PowerShell 5.1 and WPF.

Get the source

git clone https://github.com/Chaython/Windows-Maintenance-Tool.git
cd Windows-Maintenance-Tool

The repository has origin at the Chaython fork and an upstream remote for the original ios12checker project. Confirm which remote you are expected to target before opening a pull request.

Run from source

The recommended launcher is:

Start_WMT_GUI.bat

Keep the batch file and WMT-GUI.ps1 in the same folder. The launcher:

  1. Checks its own version against the BAT_URL constant and replaces itself if a newer launcher exists.
  2. Checks the local $AppVersion against the SCRIPT_URL constant, parses a newer script before accepting it, and keeps a .launcher-backup copy.
  3. Rejects an HTML page mistakenly saved as WMT-GUI.ps1.
  4. Starts PowerShell elevated with Start-Process -Verb RunAs.
  5. Shows an error dialog if elevation is declined or launch fails.

The update URLs are constants at the top of the batch file. If you work in a fork or mirror, verify or change BAT_URL and SCRIPT_URL so the launcher does not pull code from an unintended repository.

To run the script directly without the launcher:

powershell -NoProfile -ExecutionPolicy Bypass -File .\WMT-GUI.ps1

Direct launch does not self-update and does not automatically elevate. Some actions will fail or prompt separately if the session is not elevated.

Test on a disposable system or VM snapshot. Many features change services, drivers, firewall rules, registry values, disk layout, or boot configuration. Do not exercise destructive paths on a production machine.

Build the EXE

.\PS2EXE\Build-Exe.ps1 -InstallPS2EXE

Default output:

dist\WindowsMaintenanceTool.exe

The build script:

  • Requires PS2EXE 1.0.18 exactly. -InstallPS2EXE installs that version for the current user from PSGallery.
  • Parses WMT-GUI.ps1 and fails on syntax errors before building.
  • Reads $AppVersion from the script and derives the tag and four-part file version.
  • Removes comments with the PowerShell AST and builds from the minified temporary copy.
  • Produces a staging EXE, checks that it is non-empty and has the expected file version, then atomically replaces the output.
  • Embeds the icon and product metadata.

The generated EXE uses these PS2EXE options when supported by the installed module:

Option Effect
RequireAdmin EXE manifest always requests administrator rights
STA Single-threaded apartment, required for WPF and clipboard/dialog behavior
NoConsole No console window
DPIAware Per-monitor DPI awareness
LongPaths Long-path support

Optional build parameters:

.\PS2EXE\Build-Exe.ps1 `
  -InputFile .\WMT-GUI.ps1 `
  -OutputFile .\dist\WindowsMaintenanceTool.exe `
  -IconFile .\PS2EXE\WMT.ico `
  -InstallPS2EXE

Because comments are stripped, line numbers in an EXE stack trace do not match the source file. Reproduce the problem by running WMT-GUI.ps1 directly when you need accurate line numbers.

Theme diagnostics

-Debug writes theme/DWM diagnostics. For the compiled EXE, PS2EXE reserves -Debug for its own debugger, so pass script arguments after -end:

.\dist\WindowsMaintenanceTool.exe -end -Debug

Versioning and release flow

$AppVersion in WMT-GUI.ps1 is the only version that needs to be edited. The build and release workflows derive the file version and tag from it.

  • Stable tags use v<version>, for example v6.9.
  • Stable versions are immutable. The release workflow refuses to publish a tag or release that already exists; bump $AppVersion instead.
  • Stable releases must be dispatched from the Main branch.
  • A push to Main publishes the moving rolling prerelease after a successful build.

Release workflow

The Build PS2EXE Release workflow can be started manually with these inputs:

Input Default Purpose
prerelease false Marks the GitHub release as a prerelease
submit_winget true Submits a WinGet manifest update after a stable release
push_chocolatey true Pushes a Chocolatey package update; requires CHOCOLATEY_API_KEY
push_scoop true Submits a Scoop Extras update; requires SCOOP_TOKEN and an approved issue
scoop_issue empty Approved ScoopInstaller/Extras package-request issue number
scoop_issue_approved false Confirms a Scoop maintainer approved the linked issue

The main build job:

  1. Checks out the exact commit.
  2. Reads and validates $AppVersion.
  3. For stable releases, verifies the branch is Main and that the tag/release does not already exist.
  4. Runs PS2EXE\Build-Exe.ps1 -InstallPS2EXE.
  5. Computes WindowsMaintenanceTool.exe.sha256.
  6. Creates a GitHub/Sigstore attestation for the EXE.
  7. Verifies the attestation against the workflow, artifact hash, and source commit before publishing.
  8. Publishes the rolling prerelease or the immutable stable release.
  9. Optionally runs the WinGet, Chocolatey, and Scoop submission jobs.

The release assets are:

  • WindowsMaintenanceTool.exe
  • WindowsMaintenanceTool.exe.sha256
  • WindowsMaintenanceTool.exe.sigstore.json

Neither channel is Authenticode-signed. Verification steps are on Security and Updates and Releases.

Package-manager jobs run only for a manual, non-prerelease stable release when their input is enabled. They use repository secrets and are independent: a WinGet failure does not imply that the Chocolatey or Scoop job failed.

Release checklist

  1. Bump $AppVersion in WMT-GUI.ps1.
  2. Update user-facing docs and the wiki for behavior changes.
  3. Run the validation workflow and fix failures.
  4. Build locally and smoke-test the EXE on a clean Windows 10 and Windows 11 system where possible.
  5. Commit and push to Main if you also want a rolling build.
  6. Dispatch Build PS2EXE Release from Main with the desired package-manager inputs.
  7. Verify the published checksum and attestation from a separate machine.
  8. Do not reuse or move a published stable tag.

Validation and testing

The Validate PowerShell workflow runs on:

  • Manual dispatch
  • Pushes to Main that touch WMT-GUI.ps1, PS2EXE/**/*.ps1, or the workflow file
  • Pull requests to Main that touch the same paths

It has two jobs:

Job Runner Timeout Purpose
syntax windows-latest 10 minutes Parse checks and a large suite of Windows PowerShell smoke tests
runtime-safety windows-2022 and windows-2025 matrix 15 minutes Isolated runtime contracts plus implementation integration tests under pwsh

The syntax job is broader than its name. It parses every PowerShell source and then runs inline tests for areas such as:

  • Quick Find button hosting, restoration, and natural-language matching
  • Tweak-state snapshot validation and legacy import migration
  • Optional-feature startup and fail-closed behavior
  • Driver supersedence, service-removal guards, ghost-device scans, and unattached-driver enablement
  • Installer, catalogue, import, and process timeouts
  • Settings persistence and corrupt-settings detection
  • Background-operation management, worker error reporting, and cancellation
  • Analyze mode never executing a real deletion
  • Undefined-function calls, BAM path conversion, and startup-pool ordering
  • Network Repair reporting and restart rules
  • Disk Usage Analyzer scanning, navigation, and handler safety
  • Resizable subwindow bounds and state persistence

The runtime-safety job covers runspace cancellation, worker exception visibility, concurrent provider scans, driver-removal eligibility, byte-identical registry backup restore, settings JSON round-trips, and Windows build classification, then imports functions from WMT-GUI.ps1 for integration checks.

Because the tests live inside the workflow, there is no separate tests folder to run. You can run the workflow from the Actions tab, or copy the relevant inline block into a local PowerShell session. The parse step is easy to reproduce locally:

$tokens = $null
$errors = $null
[System.Management.Automation.Language.Parser]::ParseFile(
    (Resolve-Path .\WMT-GUI.ps1),
    [ref]$tokens,
    [ref]$errors
) | Out-Null

if ($errors.Count) {
    $errors | ForEach-Object {
        "{0}:{1}: {2}" -f $_.Extent.StartLineNumber, $_.Extent.StartColumnNumber, $_.Message
    }
    throw "PowerShell parse errors found."
}

"Parse OK"

Manual smoke checklist

Before a release, test at least:

  • Launch from the batch file, from a direct PowerShell session, and from the built EXE.
  • UAC approval and decline paths.
  • Navigation through every page and opening each tool window.
  • One read-only operation per provider (scan or search).
  • Updates Refresh All, Quick Find, and page search.
  • Settings save and restart persistence.
  • Tray behavior if you changed startup or background code.
  • A restore point creation and deletion on a disposable system.
  • A build from a clean checkout with no existing PS2EXE installation.

Debugging

Startup failures

  1. Run WMT-GUI.ps1 directly in a PowerShell window to see parser or assembly-loading errors that the EXE hides.
  2. Check data\last-crash.txt.
  3. Move or rename data\settings.json and try again. WMT falls back to settings.json.bak, then defaults.
  4. Confirm the data folder is writable.
  5. Confirm you are not mixing files from different versions in the same folder.
  6. If the EXE fails but the script works, rebuild with the pinned PS2EXE version.

Runtime failures

  • Reproduce with the script, not the EXE, to keep source line numbers.
  • Enable Debug Logs and repeat the operation.
  • For provider problems, open the provider's Log files and read the full transcript.
  • For background work, confirm Bg Jobs is enabled and check whether the operation was skipped because another scan was already running.
  • For elevation failures, confirm the process is actually elevated and that the operation is not blocked by policy.

Inspecting state

  • data\settings.json shows saved options. Close WMT before editing it.
  • data\settings.json.bak is the previous valid save.
  • Feature-specific JSON files show tracked state, such as compact-tracker.json and cleaner-auto-last.json.
  • Registry, hosts, driver, and firewall backups are under data; see Settings and Data.

Do not paste unredacted settings, logs, or backups into an issue. They can contain usernames, paths, computer names, IP addresses, package IDs, and provider account information.

Code conventions

  • Name functions Verb-WmtNoun, for example Get-WmtDataPath or Show-SystemRestoreManager.
  • Keep the single-file architecture unless a change is large enough to justify a broader restructuring; the build and launcher assume one script.
  • Define UI in XAML strings and use named controls with FindName, matching the surrounding page.
  • Use the theme resource keys and Set-WmtThemedBrush instead of hard-coded colors so dark and light themes both work.
  • Put long work behind the background-operation manager and marshal UI updates back to the dispatcher.
  • Preserve confirmation prompts, dry-run/analyze modes, backups, and rollback paths. Safety behavior is part of the feature, not an optional extra.
  • Add new settings through the defaults table and typed accessors.
  • Keep user-visible labels consistent with the documentation. If you rename a button, update the wiki and README references.
  • Avoid adding a dependency on a module that is not present on a stock Windows 10/11 system unless the feature is optional and fails cleanly.
  • Do not commit data, dist, credentials, tokens, logs, or machine-specific exports.

Pull request checklist

  • The change is scoped and described clearly.
  • WMT-GUI.ps1 parses without errors.
  • The validation workflow passes.
  • New behavior has a smoke test or a documented manual test.
  • Destructive actions still require confirmation and keep a recovery path.
  • Settings changes are backward compatible and default safely.
  • User-facing docs and wiki pages are updated.
  • No secrets, personal data, or generated files are included.
  • The PR targets the correct repository and branch.

Related pages

Clone this wiki locally