Skip to content

WinClean v2.20

Choose a tag to compare

@bivlked bivlked released this 22 Jul 17:41
· 32 commits to main since this release
a73c930

WinClean v2.20

A correctness and honesty release. No new cleanup features. One security fix in the protected-path guard, a fast path that turned out to have been unreachable since it was written, and a long list of places where an operation reported success while doing nothing.

Раунд корректности и честности. Новых функций очистки нет. Одно исправление безопасности в защите путей, быстрый путь очистки, который оказался недостижимым с момента написания, и длинный список мест, где операция рапортовала успех, ничего при этом не сделав.

Security / Безопасность

A junction could be used to clean a protected root. The protected-path check compared text, and GetFullPath does not resolve reparse points, so a link whose visible path looked harmless while pointing at a protected location passed the guard. The cleanup root is now resolved to its real target before the rules are applied, including the case where the link is an ancestor rather than the last path segment. A link that points somewhere harmless is still cleaned normally.

Junction могла использоваться для очистки защищённого корня. Проверка защищённых путей сравнивала текст, а GetFullPath не раскрывает reparse point, поэтому ссылка с безобидным на вид путём, указывающая в защищённое место, проходила проверку. Теперь корень очистки разрешается до настоящей цели перед применением правил, включая случай, когда ссылкой является не последний сегмент, а предок. Ссылка на безобидное место по-прежнему чистится обычным образом.

Highlights / Ключевое

Storage Sense was unreachable / Storage Sense был недостижим

The scheduled task was looked up under a folder where it does not exist, so every run fell back to cleanmgr, which took 901 seconds of an 1101-second run on a real workstation and did not finish. The task is found by name now. Two guards matter as much as the lookup: a task that ran and failed no longer counts as success, and neither does one that exits with code 0 without freeing anything measurable. Either would have suppressed all 23 Disk Cleanup handlers while reporting success.

Задача планировщика искалась в папке, где её нет, поэтому каждый прогон откатывался на cleanmgr, который на реальной рабочей станции занял 901 секунду из 1101 и не успел завершиться. Теперь задача ищется по имени. Не менее важны два предохранителя: задача, которая отработала и упала, больше не считается успехом, как и задача, вернувшая ноль и ничего не освободившая. Любой из этих случаев подавлял все 23 обработчика очистки диска с рапортом об успехе.

Honest reporting / Честность отчётов

  • Several operations reported success while doing nothing: npm cache clean (its exit code was never read), event logs (a failed enumeration produced "cleared (0 logs)", and a partial failure produced a plain success), privacy traces (the success line was appended without checking), and the winget source update (a winget that cannot start left no trace in the log at all).

  • Measurements that could not distinguish "nothing to clean" from "could not measure" no longer invent freed bytes. This covers browser caches, the npm cache and the registry checks.

  • A failed log write is reported once and surfaces as LoggingDegraded in the result JSON, so a run cannot keep deleting files while the log has silently stopped recording.

  • A Disk Cleanup left running past its timeout is a warning with DiskCleanupPending in the result JSON: the totals printed after it are partial.

  • Несколько операций рапортовали успех, ничего не сделав: npm cache clean (код возврата не читался), журналы событий (неудачное перечисление давало «очищено 0», частичное - обычный успех), следы приватности (строка об успехе добавлялась без проверки) и обновление источников winget (незапускающийся winget вообще не оставлял следа в логе).

  • Замеры, которые не отличали «нечего чистить» от «не смогли измерить», больше не выдумывают освобождённые байты. Это касается кэшей браузеров, кэша npm и проверок реестра.

  • Неудачная запись в лог сообщается один раз и попадает в result JSON как LoggingDegraded, поэтому прогон не может продолжать удалять файлы, когда лог молча перестал писаться.

  • Очистка диска, не уложившаяся в таймаут, стала предупреждением с полем DiskCleanupPending: напечатанные после неё итоги неполны.

Added / Добавлено

  • -SkipDiskCleanup skips only the Storage Sense / Disk Cleanup step. Until now the only way to avoid the slowest step was -SkipCleanup, which suppresses every cleanup category. On a machine where Storage Sense itself fails, this flag is what removes the wait.

  • Result JSON fields LoggingDegraded and DiskCleanupPending.

  • -SkipDiskCleanup пропускает только шаг Storage Sense / Disk Cleanup. Раньше избежать самого долгого шага можно было лишь через -SkipCleanup, который гасит очистку целиком. На машине, где сам Storage Sense падает, именно этот флаг убирает ожидание.

  • Поля result JSON LoggingDegraded и DiskCleanupPending.

Fixed / Прочие исправления

  • A thousands separator was read as a decimal point, so "1,234 KB" became 1.234 KB. Sizes taken from the shell fallback were out by a factor of a thousand.

  • The restore-point frequency override could stay applied indefinitely after an interrupted run.

  • -SkipCleanup was ignored by three functions when they were called directly, which contradicted the documented contract.

  • Разделитель тысяч читался как десятичный, поэтому "1,234 KB" превращалось в 1.234 KB. Размеры из shell-фоллбэка занижались в тысячу раз.

  • Изменённая частота создания точек восстановления могла остаться применённой навсегда после прерванного прогона.

  • -SkipCleanup игнорировался тремя функциями при прямом вызове вопреки документированному контракту.

Under the hood / Под капотом

376 to 452 automated tests. This release was reviewed in five rounds, and each of the first four found defects in the previous round's fixes, including one that crashed the whole deep-cleanup phase on any machine where Storage Sense returns an error code. That defect survived a green run on two live test machines, because the test machines only ever execute the success path. The fifth round came back clean.

376 -> 452 автоматических теста. Этот релиз проходил ревью пятью раундами, и каждый из первых четырёх находил дефекты в исправлениях предыдущего, включая тот, что ронял всю фазу глубокой очистки на любой машине, где Storage Sense возвращает код ошибки. Этот дефект пережил зелёный прогон на двух живых тестовых машинах, потому что там выполняется только успешный путь. Пятый раунд вернулся чистым.

Install / Установка

# Run once / Разовый запуск
irm https://raw.githubusercontent.com/bivlked/WinClean/main/get.ps1 | iex

# Install with a desktop shortcut / Установка с ярлыком
irm https://raw.githubusercontent.com/bivlked/WinClean/main/install.ps1 | iex

# PowerShell Gallery
Install-PSResource WinClean

Both bootstrap scripts verify the SHA256 of the release asset and refuse to run on a mismatch.

Оба bootstrap-скрипта сверяют SHA256 ассета релиза и отказываются запускаться при расхождении.