Repository navigation
WinClean v2.22
A release about knowing when work is finished, and about the run surviving things that have nothing to do with maintenance. Two of the three defects here are the same mistake in different places: treating "I could not observe it" as an answer.
Раунд про то, как отличить законченную работу от ненаблюдаемой, и про то, чтобы прогон переживал вещи, не имеющие отношения к обслуживанию. Два дефекта из трёх - одна и та же ошибка в разных местах: «я не смог этого увидеть» принималось за ответ.
What changed / Что изменилось
Fixed / Исправлено
Disk Cleanup that had stopped working was reported as still deleting, and cost the full timeout. Measured on a live workstation: cleanmgr /sagerun did its work in about ten seconds, closed its window, and then stayed resident - no CPU, no I/O on any of the three counters, all six threads waiting. Because the wait was written against process exit, the run sat there for the remaining ~890 seconds and then declared its figures partial, having observed nothing happening for most of that time. The wait now also ends on total stillness: no CPU and no I/O across twelve consecutive checks, after activity was seen at least once.
Disk Cleanup, переставший что-либо делать, считался работающим и стоил полного таймаута. Замер на живой машине: cleanmgr /sagerun отработал за ~10 секунд, закрыл окно и остался резидентным - без CPU, без I/O по всем трём счётчикам. Ожидание было написано на выход процесса, поэтому прогон стоял оставшиеся ~890 секунд и после этого объявлял свои цифры неполными. Теперь ожидание завершается и по полной неподвижности: 12 проверок подряд без CPU и I/O, после того как активность была зафиксирована хотя бы раз.
An unusable -LogPath killed the run before any maintenance happened. The log header was written with two bare Out-File calls placed before the block that guarantees the result JSON and the summary. Six of seven bad paths make Out-File throw a terminating error even at the default ErrorActionPreference (missing directory, path is a directory, invalid characters, a colon in the name, an over-long path, an unreachable UNC share), and the exception escaped the whole function. A log that cannot be written is now a degraded run, as it always was everywhere else - never a failed one.
Неработоспособный -LogPath убивал прогон до начала обслуживания. Заголовок лога писался двумя голыми Out-File до блока, гарантирующего result JSON и сводку. Шесть из семи плохих путей заставляют Out-File бросить terminating-ошибку даже при дефолтном ErrorActionPreference (нет каталога, путь это каталог, недопустимые символы, двоеточие в имени, слишком длинный путь, недоступная UNC-шара), и исключение уходило из функции целиком. Ненаписуемый лог теперь деградация прогона, а не его провал.
install.ps1 accepted a PowerShell 7 whose version it could not read. The check was if ($pwshVersion -and $pwshVersion -lt '7.1'), so an unreadable version left the comparison unevaluated and the installer carried on to pin an elevated desktop shortcut to a binary nobody had established was suitable. This is the same fail-open shape as the SHA256 verification that hid inside if ($hashAsset) until v2.17.
install.ps1 принимал PowerShell 7, версию которого не смог прочитать. Проверка была if ($pwshVersion -and $pwshVersion -lt '7.1'), поэтому при нечитаемой версии сравнение просто не выполнялось, и установщик шёл дальше вешать elevated-ярлык на бинарь, пригодность которого никто не установил. Та же fail-open форма, что у проверки SHA256, прятавшейся внутри if ($hashAsset) до v2.17.
The banner's frame depended on the version being four characters long - the title row measured 70 columns only because "2.21" happens to be four characters. The banner is now composed rather than hand-padded.
Рамка баннера держалась на том, что версия занимает ровно четыре символа - строка заголовка была шириной 70 только потому, что в «2.21» оказалось четыре знака. Баннер теперь собирается вычислением, а не выравнивается руками.
Changed / Изменено
-
Console output follows the window. The desktop shortcut opens conhost at its 120-column default while winget's upgrade table needs about 140 on a localised system, so the table wrapped across WinClean's own output. The window is now widened best-effort at startup (never beyond what the screen can show, never failing the run if the host refuses), and frames are derived from the real console width instead of a literal 70 repeated in four places. Bounded: never narrower than the historical 70, never wider than 90.
-
Every run ends through one code path. A successful self-update used to call
exititself, bypassing the block that writes the result JSON, shows the summary and releases the log handle. Exit codes are unchanged. -
Storage Sense: the log now distinguishes "switched off" from "ran and there was nothing left" when it returns success having freed nothing measurable.
-
Вывод следует за окном консоли. Ярлык открывает conhost на дефолтных 120 колонках, а таблице
winget upgradeна локализованной системе нужно около 140 - она переносилась поверх нашего вывода. Окно расширяется best-effort при старте (не шире физически возможного, без падения прогона если хост откажет), рамки считаются от реальной ширины вместо литерала 70 в четырёх местах. Границы: не уже исторических 70, не шире 90. -
Все выходы из прогона идут одним путём. Успешное самообновление вызывало
exitсамо, минуя блок с result JSON, сводкой и освобождением лог-хендла. Коды возврата не изменились. -
Storage Sense: лог различает «выключен» и «отработал, но чистить было нечего», когда он рапортует успех, не освободив измеримого объёма.
Added / Добавлено
-
DiskCleanupStatusin the result JSON - twelve values covering every way that step can end, replacing a boolean that covered two different truths. The oldfailedis split intonot-armed,start-failedandexit-nonzero; only the last means the machine may be partially cleaned. -
SUPPORT.md, a release-notes template indocs/release-process.md, and a section inCONTRIBUTING.mddescribing what gets accepted. -
DiskCleanupStatusв result JSON - 12 значений, покрывающих все способы завершения этого шага, вместо булева поля, покрывавшего две разные правды. Прежнийfailedразделён наnot-armed,start-failedиexit-nonzero; только последнее означает, что машина может быть очищена частично. -
SUPPORT.md, шаблон release notes вdocs/release-process.mdи раздел «что принимается» вCONTRIBUTING.md.
Safety notes / О безопасности
Nothing in this release changes what gets deleted. The one change in that area is deliberately a non-change: Storage Sense now reports which of two situations it is in, but Disk Cleanup still runs regardless. Skipping it on that basis would silently stop cleaning Update Cleanup, memory dumps, Language Pack, old ChkDsk files and Windows Error Reporting - none of which Storage Sense touches.
The new early exit from waiting on Disk Cleanup does not delete anything and does not terminate the process; it stops waiting and says so. It is named idle-resident after what was measured (a process seen working, then completely still), not after the conclusion drawn from it, because that conclusion can be wrong. Not being able to measure activity resets the counter rather than advancing it, so a machine with broken WMI keeps the old, patient behaviour instead of cutting cleanups short.
Ничто в этом релизе не меняет того, что удаляется. Единственное изменение в этой области намеренно является не-изменением: Storage Sense теперь сообщает, в какой из двух ситуаций находится, но Disk Cleanup запускается по-прежнему. Пропуск на этом основании молча прекратил бы чистку Update Cleanup, дампов памяти, Language Pack, старых файлов ChkDsk и Windows Error Reporting - ничего из этого Storage Sense не делает.
Новый ранний выход из ожидания Disk Cleanup ничего не удаляет и не завершает процесс: он перестаёт ждать и говорит об этом. Он назван idle-resident по тому, что измерено (процесс работал, затем полностью замер), а не по выводу из измерения, потому что вывод может быть неверным. Невозможность измерить активность сбрасывает счётчик, а не продвигает его, поэтому машина со сломанным WMI сохраняет прежнее терпеливое поведение.
Verification / Проверка
Run for this release, not quoted from the process:
- release gate
Invoke-ReleaseCheck.ps1: 10/10; - 702 Pester tests, none skipped (573 in v2.21); four mutation runs over the new logic, 79 mutations, all caught - eight survived at first and each exposed a real gap;
- PSScriptAnalyzer clean, smoke test green, CI green on the PR (5/5 checks);
- stand: 4/4 - VM 190 (RU) and VM 191 (EN), each in
FullandReportNoCleanup. RU freed 974.6 MB in 75.7 s, EN freed 2515.4 MB in 200.4 s, zero errors; - end-to-end through the published one-liner after this release was cut.
Honest limit: the stand exercises the path where cleanmgr exits by itself, so the new idle-resident and timeout branches were not executed there. The stand shows the old path is not broken; the new behaviour is held by unit tests and the mutation runs.
Что реально прогонялось для этого релиза:
- релиз-гейт
Invoke-ReleaseCheck.ps1: 10/10; - 702 теста Pester, ни одного пропущенного (в v2.21 было 573); четыре мутационных прогона по новой логике, 79 мутаций, все пойманы - восемь сначала выжили, и каждая вскрыла реальный пробел;
- PSScriptAnalyzer чист, смоук зелёный, CI на PR зелёный (5/5);
- стенд 4/4: VM 190 (RU) и VM 191 (EN), каждая в режимах
FullиReportNoCleanup. RU освободила 974.6 МБ за 75.7 с, EN - 2515.4 МБ за 200.4 с, ноль ошибок; - сквозной прогон через опубликованный one-liner после выпуска.
Честная граница: стенд выполняет путь, где cleanmgr выходит сам, поэтому новые ветки idle-resident и timeout там не выполнялись. Стенд показывает, что прежний путь не сломан; новое поведение держат юнит-тесты и мутационные прогоны.
Assets / Ассеты
WinClean.ps1 and WinClean.ps1.sha256. Both are required: get.ps1 and install.ps1 verify the hash fail-closed and refuse to run without it.
WinClean.ps1 и WinClean.ps1.sha256. Нужны оба: get.ps1 и install.ps1 проверяют хеш fail-closed и отказываются работать без него.
Upgrade / Обновление
| Method / Способ | Action / Действие |
|---|---|
irm ... /get.ps1 | iex |
nothing - always fetches the latest Release / ничего, всегда берёт последний Release |
install.ps1 |
re-run the one-liner / повторить one-liner |
PSGallery (Install-Script) |
the built-in check offers the update / встроенная проверка предложит обновление |
| Manual copy / Ручная копия | download the asset from this Release / скачать ассет из этого Release |
Known limitations / Осознанные ограничения
-
idle-residentdoes not clear the registry flags that arm Disk Cleanup categories, unlike a clean exit. The cost is asymmetric: clearing them on an assumption that turned out wrong would disarm categories for a run that was still working. -
The identity of the observed process is best-effort. It is a process tree walked from our own PID; a PID reused within one polling interval could in principle be misread. The status is named after the observation for exactly this reason.
-
Consoles narrower than 74 columns still cannot fit a frame - the floor of 70 plus borders. Unchanged from before.
-
Show-FinalStatisticscan trigger a restart that bypasses the exit-code path. Pre-existing, not introduced here, and deliberately left alone in a release about exit paths. -
idle-residentне сбрасывает флаги в реестре, вооружающие категории Disk Cleanup, в отличие от штатного выхода. Цена ошибки несимметрична: сброс по предположению, оказавшемуся неверным, разоружил бы категории для прогона, который ещё работал. -
Идентификация наблюдаемого процесса - best-effort. Это дерево процессов от нашего PID; переиспользованный в пределах одного интервала опроса PID теоретически может быть прочитан неверно. Статус назван по наблюдению именно поэтому.
-
Консоли уже 74 колонок по-прежнему не вмещают рамку - нижняя граница 70 плюс бордюры. Как и раньше.
-
Show-FinalStatisticsможет инициировать перезагрузку в обход пути с кодом возврата. Дефект существовал и до этого релиза, оставлен намеренно.