Free, open-source Windows optimization tool for performance, privacy, and simplicity.
C# csharpdebloatdotnetgamingopen-sourceoptimizationoptimizeroptimizerduckperformanceprivacytweakertweakswindowswinui
Repository Guidelines
Windows-only WPF desktop app that optimizes Windows. Read this before changing code.
Hard rules
- Windows only.
optimizerDucktargetsnet10.0-windowswithUseWPF=trueand deliberately no Windows SDK version in the TFM: a versioned one makes the SDK reference the CsWinRT projection and ships a 50 MBMicrosoft.Windows.SDK.NET.dllfor WinRT APIs this app never calls.CA1416is silent because every path is Windows-only. (optimizerDuck.Testdoes carry10.0.17763.0.) - Elevated.
app.manifestrequestsrequireAdministrator. A test that writes the registry, a service or a scheduled task needs an elevated shell too. - Two projects, nothing else.
optimizerDuck/(the app) andoptimizerDuck.Test/, inoptimizerDuck.slnx(not.sln). Never create a top-level directory outside them. - One implementation per Windows operation. Fix behaviour in the owner, never in a copy. See Providers.
- One execution path. Every system-changing run goes through
OperationRunner. Never add a second framework. - No hardcoded UI strings.
Loc.Instance["Key"]in C#,Translations.KeyNamein XAML. Add keys toResources/Languages/Translations.resx. - A warning fails the build (
TreatWarningsAsErrors+EnforceCodeStyleInBuildin both project files; the severity table in.editorconfigdecides).AnalysisMode=Allis deliberately off.
Commands
dotnet restore optimizerDuck.slnxdotnet build optimizerDuck.slnx --configuration Release --no-restore— the CI-aligned gate.dotnet run --project optimizerDuck.Test/optimizerDuck.Test.csproj --configuration Release -- -longRunning 30— all tests through the xUnit console runner (non-zero exit on failure). Add-class <Name>or-method <Name>for one. The project is a Microsoft.Testing.Platform app, sodotnet test --project optimizerDuck.Test/optimizerDuck.Test.csprojalso works where the runner's pipe transport is available (global.jsonselects it); it is not used in CI.dotnet run --project optimizerDuck/optimizerDuck.csproj— run locally (needs admin).publish.bat portable|single [--skip-tests] [--no-pause]— release artifacts; runs the tests first unless skipped.csharpier format ./csharpier check .— global tool, CI pins 1.3.0. Run it ascsharpier, neverdotnet csharpier(that fails as "command not found", which reads like a missing tool). The editor reformats on save, so a touched file may come back with unrelated lines reflowed; that is the formatter, not your edit.- Full gate before push: build, test,
csharpier check .. CI (.github/workflows/ci.yml) = restore, Release build, tests with-longRunning 30, format check.
Layout
optimizerDuck/— the WPF app.Domain/— models, contracts, records. No UI dependencies.Abstractions/—IOptimization,IOptimizationCategory,ICustomizeSetting,ICustomizeCategory,IRevertStep,RevertContext,IWindowAttributes/—[Optimization],[OptimizationCategory],[CustomizeSetting],[CustomizeCategory]Conditions/+BuiltIn/— compatibility gatingExecution/—OpCall,ChangeSet+Change+ChangeKind,ChangeDetail+ChangeDetailCodec,OpResult,OperationSubject,OperationRequest,ToolSubjects,ChangeRecordOptimizations/Categories/— Performance, SecurityAndPrivacy, Gpu, PowerManagement, BloatwareAndServices, UserExperience, AI, plusDebug(DEBUG-only, excluded from release)Optimizations/Models/—BaseOptimization,ApplyResult,OptimizationContext,OptimizationResultand the per-feature item modelsCustomize/Categories/— Desktop, Gaming, Preferences, SystemFeaturesCustomize/Models/—BaseCustomizeSetting,RegistryToggle,RegistryBinding,SettingOption,CustomizeControlType,RecommendationStateRevert/+Revert/Steps/— revert data and the persistable stepsUI/— UI-facing types only: risk/tag/order enums,OptimizationState,SupportedLanguages,ChangeKindPresentation,ChangeDetailPresentationConfiguration/AppSettings.cs— settings persisted toappsettings.json(ShellTimeoutMsdefault 120000)
Services/— business logic:Conditions/ConditionEvaluator,Configuration/{ConfigManager,LanguageManager},Customize/{CustomizeRegistry,CustomizationExecutor},Optimization/{OptimizationRegistry,OptimizationService,OperationRunner,OptimizationValidation},Revert/RevertManager,History/ChangeRecordStore,System/*,System/Primitives/*,UI/*UI/— XAML pages, ViewModels, windows, dialogs, controls, stylesCommon/—Helpers/(Shared,ReflectionHelper,CategoryDiscovery,WmiHelper,UserErrorSurface, ...),Converters/,Extensions/ApplicationServiceCollectionExtensions.cs—AddOptimizerApplication(IConfiguration), the whole graph;App.xaml.csonly builds the hostResources/Languages/—Translations.resx(neutral English) + one file per locale
optimizerDuck.Test/— xUnit v3, one project,InternalsVisibleTo.- Data directory
%LocalAppData%\optimizerDuck\:Revert/,History/,Resources/{Downloads,Assets}/,Crashes/,optimizerDuck.log,appsettings.json. - Version lives in
optimizerDuck.csproj(<Version>). Read it there; never hardcode it.
Adding an optimization or customize setting
Reflection discovery, no registration array to update.
- Optimization: a nested class in the relevant
Domain/Optimizations/Categories/*.csfile, extendingBaseOptimization, decorated[Optimization(Id = "guid", Risk = ..., Tags = ..., Condition = typeof(...)?)]. That is the only path. - Customize setting: same nesting in
Domain/Customize/Categories/, extendingBaseCustomizeSetting, decorated[CustomizeSetting(Section = ..., Icon = ..., Recommendation = ..., Condition = typeof(...)?)].Iconis required (SymbolRegular);RecommendationisOn|Off|Depends|Experimental|None. - Category class:
[OptimizationCategory(typeof(PageClass))]or[CustomizeCategory(PageType = typeof(PageClass))]. Category pages auto-register viaAddAllOptimizationPages()/AddAllCustomizeCategoryPages(). - Discovery:
ReflectionHelper.FindImplementationsInLoadedAssemblies<T>()scans assemblies whose name starts withoptimizerDuck;CategoryDiscoverybuilds the categories and instantiates their nested items, skipping empty categories. Results are cached.OptimizationValidationfails fast on a duplicate or malformed Id during discovery. - Preloading:
OptimizationRegistry.PreloadOptimizationsAsync()/EnsurePreloadedAsync()andCustomizeRegistry.PreloadCategoriesAsync()/EnsurePreloadedAsync()run discovery on a background thread;App.xaml.cspreloads at startup and the pages awaitEnsurePreloadedAsync()before binding. - DI: register through
AddOptimizerApplication(configuration). The host setsValidateOnBuild/ValidateScopes, so a broken or scoped-into-singleton registration fails at startup, not at apply time. Keep it that way. - Results: an optimization ends
ApplyAsyncwithreturn context.Changes.ToApplyResult();. Only an early-out failure constructsApplyResultby hand.
Execution model
OpCallis the explicit per-operation context:Changes,Logger,CancellationToken.OptimizationContextextends it withSnapshot,StreamService,Shell,PowerPlans.- Providers record into
call.Changesand returnOpResult. Never both throw and record. ChangeKindsays what a step did:Change(modified, carries compensation),Skip(already correct),NotApplicable(nothing here to act on),Refused(Windows refused; not a failure),Irreversible(no way back).DidApplyAnything=Changeonly, and gates revert persistence.ModifiedSystem=Change+Irreversible, and tells a change from nothing to do. So a run whose only step was irreversible is a success, and a run that recorded nothing is "nothing to do", not a failure.OperationRunneris the one lifecycle: run the work, classify the outcome from the recorded steps, write the record, persist revert data when the subject asks for it.OperationSubject(Id + Key + English log name) identifies a run and its record; built-in tool ids live inToolSubjects.- Skip policy: a provider whose mutation needs a privilege it may not have, has a side effect beyond the value it sets, or can be refused on a second call reads the current state first and records a
Skipwhen the machine already matches, without calling the mutation (RegistryService,ServiceProcessService,ScheduledTaskService,PowerPlanChanges, and the PowerManagement category for hibernation/USB). An item never decides this on its own: a skip recorded at the item level drops the step from the record. - Failure policy: a provider records a failed
Changewith an error and, when a retry can help, a retry action — it does not throw. Only unrecoverable state throws; the runner turns that into a failed step named for the user. Partial work is persisted withCancellationToken.None. - Retry:
OptimizationService.RetryFailedStepsWithResultsAsync()(static) re-invokes the stored retry action with a freshOpCalland appends the recovered steps. The optimize page's dialog andToolRunPresenterboth call it. Reverting passes aRevertManager, a tool passes none, so a retried tool step writes no revert data. - The record:
OperationRunnerwrites%LocalAppData%\optimizerDuck\History\{id}.json(one file per subject, atomic, best effort, never part of the revert data).ChangeRecordStore.TryWrite/TryReadis the only accessor; the details view, the applied badge summary and a retry's attempt counts read it. - Tool actions:
ToolRunPresenter.RunAsync(OperationRequest)runs an action under the progress dialog,ReportAsyncreports it (retry dialog for failed steps, snackbar for a failure with no retry). Every tool page uses it, so an action is run and reported one way.
Providers
RegistryService,ServiceProcessService,ScheduledTaskService— static, stateless; call directly.ShellService+ProcessRunner— DI singletons, reached from optimizations ascontext.Shell.PowerPlanService— DI singleton, the only owner of power-scheme interop; lean: reads take ids, writes takeILogger? = nulland record nothing.PowerPlanChangesis the single edge that turns those results intoChange+ revert step + retry.SystemRestoreService— the only owner of every System Restore WMI call.RecycleBinService,HibernationService,UsbPowerService— static, one Windows operation each (shell Recycle Bin APIs, the documented power information callback,root\wmidevice power); they fail open instead of throwing. The PowerManagement category records their steps.
Conditions (compatibility gating)
Domain/Conditions/:ICondition,ConditionBase,ConditionResult,ConditionState,ConditionValidation,WindowsBuilds,BuiltIn/— Windows 10, Windows 11, Windows 11 24H2+, CPU brand, GPU brand, minimum RAM, registry key exists, service exists, Recall installed.- Evaluated by the static
Services/Conditions/ConditionEvaluator. Both[Optimization]and[CustomizeSetting]accept an optionalCondition = typeof(T)whereT : IConditionwith a public parameterless constructor. ConditionResult.Available/.Unsupported(title, description)/.Error(). Note the two providers are factory delegates (() => Loc.Instance[...]), so text is localized lazily.Errorand an unknownSystemInfofail open (never hide).- Only
Unsupportedblocks, and only when the item is neither applied nor hidden by the user.ConditionValidation.Validate(...)fails fast on misconfigured metadata.
Revert system
- One JSON file per subject:
%LocalAppData%\optimizerDuck\Revert\{id}.json. Applied state is inferred from file presence. RevertManageris the API:SaveRevertDataAsync,RevertAsync,AppendRevertStepAsync,RemoveRevertStepAtIndexAsync,RemoveRevertStepsAtIndexesAsync,RemoveRevertData, plus staticIsAppliedAsync,GetRevertDataAsync,ClearAllRevertData,RemoveOrphanedTempFiles.- Atomic writes: temp file via
FileStream(WriteThrough)+Flush(flushToDisk: true), thenFile.Replace. Stale.tmpfiles are swept at startup. - Concurrency: a per-file
SemaphoreSlim(30 s timeout) inRevertManager.FileLocks. A lock entry is never disposed while another thread holds or waits on it. - Compact layout: only successful steps persist, re-indexed with no gaps. Re-apply appends; a recovered retry step appends (never overwrites), so LIFO revert still ends at the original backup.
- Step registry:
_stepRegistryis a lazily built name →Func<JObject, IRevertStep>map; a new step auto-registers by implementingIRevertStepwith a public staticFromData(JObject). Persisted data with an unknown type becomes a failing step with a clear message, never a silent skip. - Steps (
Domain/Revert/Steps/):RegistryRevertStep,ServiceRevertStep,ScheduledTaskRevertStep,ShellRevertStep,UsbPowerRevertStep,PowerPlanRevertStep,PowerSettingRevertStep,HibernationRevertStep. Each verifies its own effect inExecuteAsync(read-back, re-query, re-check, re-read). Access denied is failure, never success; missing required state throws (fail closed). IRevertStep.ExecuteAsync(RevertContext, ILogger):RevertContextcarriesShell,PowerPlansand the logger, so undo runs through the same DI services and the configured shell timeout.RegistryRevertStepactions:RestorePrevious,NoPreviousValue,RestoreKey,RestoreKeyTree; it tracks the subkeys it created so cleanup can remove them.
Customize setting API
RegistryToggletakesOnValues/OffValues(lists;nullentry = key absent),DefaultValue,IsOptional,ValueKind. There is noOnValue/OffValue/TreatMissingAsDefault.- Dropdown settings override
ControlType => CustomizeControlType.DropdownandGetOptions()returningSettingOptions built withOption(key, regPath, regName, value)orOption(key, value, params RegistryBinding[]). The base class auto-reads and auto-writes through the bindings and shows a "Custom" / "Not set" fallback for values outside the options. - When you override
ApplyAsync, callawait ExecutePostActionAsync()yourself (it is guarded byNeedsPostAction). - Setting writes go through
CustomizationExecutor.ApplyWithDebounceAsync(value, applyAction, debounceMs = 400): it debounces, then runs one queued apply at a time, so a burst of toggles applies only the last value.CustomizeItemViewModelis the caller.
Localization
Domain/UI/SupportedLanguages.csis the single source of truth for the language list (17 entries, currentlyen-US…id-ID); the UI bindsSupportedLanguages.All. A language exists only when itsResources/Languages/Translations.{culture}.resxalso exists, andLanguageManagerTests.EveryNeutralKey_ResolvesInEverySupportedLanguageenforces that every neutral key resolves in every locale. Do not hardcode a language list anywhere else.Translations.resx(English) is the key source. Preserve{0}placeholders verbatim and in order, escape XML specials, keepxml:space="preserve".- Goal is natural localization, not word-for-word translation; each locale must read as if written by a native speaker who knows Windows, PC hardware and optimization software.
- Keep technical terms in English where that locale's users expect it (e.g. Vietnamese: SSD, HDD, RAM, CPU, GPU, Driver, Registry, BIOS, UEFI, PowerShell — never "Trình điều khiển" for Driver), and translate the concepts with a natural localized equivalent where one exists (e.g. vi "Memory Integrity" → "Tính toàn vẹn bộ nhớ"). Decide per locale; conventions differ per language.
- Never copy English sentence structure that sounds wrong in the target language, and never pad to match the source length. No em dashes in any locale — restructure with commas, periods, colons or parentheses natural to the language.
- Consistency order: correct meaning, then natural language, then established terminology, then cross-app consistency. The same source term may need different wording per context ("Startup" as manager vs. at startup).
Tests (xUnit v3, integration style)
- No mocking libraries. Test doubles are hand-written (
StubOptimization,TestShell,TestRunner,EveryOperationDetail, ...) implementing the real interfaces. - Real I/O: real filesystem (revert JSON), real registry under
HKCU\Software\TestOptimizerDuck*, real CMD/PowerShell processes. - STA: a WPF-touching test uses a
private static RunInStaThreadAsynchelper (STA thread +TaskCompletionSource). There is no shared helper — the test class defines its own, so copy the existing one when a new class needs it. - Logging:
NullLogger<T>.Instance/NullLoggerFactory.Instance. - Naming:
{Method}_{Scenario}_{ExpectedResult}, e.g.ApplyAsync_Success_PersistsRevertDataFile. - Cleanup:
try/finallyorIDisposable(AppDataCleanupFixture); a test that writes revert data removes both{id}.jsonand{id}.json.tmp. - No coverage gate — cover the changed logic meaningfully, and add or update tests for what you change even when nobody asked.
- CI runs the console runner with
-longRunning 30: no test may hang longer than 30 s.
Style
- Nullable enabled, file-scoped namespaces, implicit usings. 4-space indent, max line length 100.
- PascalCase types and members,
_camelCaseprivate fields,camelCaselocals and parameters. - Comments are sparse in this codebase; do not add unnecessary ones.
- DI and MVVM via
Microsoft.Extensions.Hosting+CommunityToolkit.Mvvm; pages and ViewModels are singletons. WmiHelper.Initialize()registers WMI cleanup for abnormal termination; keep the call on the startup path.- Environment:
net10.0-windows, WPF,WPF-UI+WPF-UI.DependencyInjection4.3.0,CommunityToolkit.Mvvm8.4.2,Microsoft.Extensions.*10.0.12,Newtonsoft.Json13.0.4,Serilog4.4.0 (+Serilog.Extensions.Hosting10.0.0,Serilog.Sinks.File7.0.0),System.Management.Automation7.6.6,TaskScheduler2.12.2. Tests:xunit.v34.0.1 (Microsoft.Testing.Platform based;Microsoft.NET.Test.Sdk,xunit.runner.visualstudioandcoverlet.collectorare VSTest-only and deliberately absent). Versions live in the two csproj files — check there rather than trusting this list.
Commits and PRs
- Conventional Commits:
feat:,fix:,refactor:,docs:,test:,i18n:,chore:. - Branch from
master:feature/<name>orfix/<issue-id>. - Run
csharpier format ., then build and test, before committing. Never commit secrets or machine-specific paths. - PR: clear description, linked issue (
Closes #123), passing CI, screenshot for UI changes.
RTK — Always Prefix Shell Commands with rtk
Every shell command must be prefixed with rtk (RTK = Rust Token Killer). This filters and compresses output before it reaches the LLM context, saving 60-90% tokens. RTK passes through any command it doesn't recognize.
In a command chain, prefix each command individually:
rtk git add . && rtk git commit -m "msg" && rtk git push
Meta commands: rtk gain (savings stats), rtk discover (find missed opportunities), rtk proxy <cmd> (run raw for debugging).