Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,40 @@ All notable changes to StorageMaster are documented here.

## [Unreleased]

### Added

- **The Duplicates page says why a selected file was not deleted.** After a
deletion, a warning lists every selected file that is still in place, with the
reason: it changed after the analysis, it could not be read again, it no longer
matches the file being kept, Windows refused (for example because it is open
in another program), Windows cannot recycle it there, the file being kept could
not be verified, or the scan recorded no stable identity for it. Before, the
status line only showed a lower count and the file stayed listed. In English,
German and Spanish.
- **Items the Recycle Bin refused get a second question.** Recycle Bin mode still
never deletes permanently on its own. Duplicates, Cleanup, Smart Cleaner and the
Results page now follow a refusal with "Delete these N item(s) permanently?",
listing the items, with No as the default. Only a yes deletes them, through the
same checks as any other deletion, and nothing that was not listed. Scheduled
cleanup has no one to ask and keeps the refusal.

### Changed

- **Hard links count once in sizes.** A file with several hard links is one file
on disk, but every name added its size to folder, category and scan totals.
Windows links most of WinSxS this way, so a system drive looked fuller than it
is. Every name is still listed with its own size; only the first one a scan
reaches adds to the totals. This applies to new scans: comparing one with an
older scan shows such folders shrinking once. Database schema v16.
- **Image duplicates are decoded by Windows.** The perceptual image hash and the
duplicate preview now use the Windows Imaging Component, the decoders File
Explorer uses, which Windows Update keeps patched. That removes ImageSharp
3.1.12 and its five security advisories (the fix exists only in 4.x, which needs
a commercial license key). Formats Windows has a codec for, such as HEIC with the
HEIF extension, now work. Video frames come out of FFmpeg as raw grey pixels and
need no decoder. Image and video fingerprints are recomputed on the next
analysis.

### Fixed

- **Recycle Bin mode could delete files permanently.** Windows has no Recycle Bin
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,8 @@ Schema migrations run on the first database access after an upgrade, each level
sqlite3 "$env:LOCALAPPDATA\StorageMaster\storagemaster.db" "SELECT MAX(Version) FROM SchemaVersion;"
```

<!-- schema-version: 15 -->
The expected value is `DatabaseSchema.CurrentVersion` for the build you are running — schema v15 at the time of writing. A lower number means migration has not run yet; it happens on first database access after an upgrade, not at install time.
<!-- schema-version: 16 -->
The expected value is `DatabaseSchema.CurrentVersion` for the build you are running — schema v16 at the time of writing. A lower number means migration has not run yet; it happens on first database access after an upgrade, not at install time.

Uninstall keeps `%LOCALAPPDATA%\StorageMaster` by default, so the database and settings survive reinstall/upgrade cycles.

Expand Down
9 changes: 5 additions & 4 deletions docs/public/ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# StorageMaster — Architecture Overview

<!-- schema-version: 15 -->
<!-- schema-version: 16 -->

> **Version:** 2.2.1 | **Current-state review:** 2026-08-18 | **Framework:** .NET 8 / WinUI 3 / Windows App SDK 1.6
> **Current-state note:** StorageMaster uses schema v15, independent pooled SQLite connection leases, persisted scan-time file identity, a managed/Rust scanner boundary, dedicated duplicate recovery, and fail-closed deletion guards. `DatabaseSchema.CurrentVersion` is authoritative for the schema number; a test asserts this document agrees with it. See `RELIABILITY_AUDIT_2026-08-18.md` for verified hardening and remaining limits (that audit is a dated snapshot and describes the schema as of v12).
> **Current-state note:** StorageMaster uses schema v16, independent pooled SQLite connection leases, persisted scan-time file identity, a managed/Rust scanner boundary, dedicated duplicate recovery, and fail-closed deletion guards. `DatabaseSchema.CurrentVersion` is authoritative for the schema number; a test asserts this document agrees with it. See `RELIABILITY_AUDIT_2026-08-18.md` for verified hardening and remaining limits (that audit is a dated snapshot and describes the schema as of v12).

---

Expand Down Expand Up @@ -137,7 +137,7 @@ Pure SQLite persistence:
| `CleanupLogRepository` | Append-only audit log |
| `SettingsRepository` | JSON-serialized `AppSettings` as a key-value row |

Schema v8 adds `DuplicateOperationJournal`; v9 adds generic-quarantine restore support; v10 repairs the quarantine-member foreign key; v11 normalizes folder identity and collapses Windows case variants conservatively; v12 persists nullable volume/file identity for scan rows; v13 materializes `FolderEntries.ParentNormalizedPath` plus a `(SessionId, ParentNormalizedPath, TotalSizeBytes DESC)` index so parent/child lookups stop deriving the relationship inside the predicate; v14 adds `ScanSessions.OwnerProcessId` / `OwnerProcessStartedUtc` so a session left `Running` by a crash can be told apart from a live scan; v15 indexes the `FileEntries(Id)` cascade referrers (`DuplicateGroupMembers`, `DuplicateGroups`, `DuplicateErrors`, `DuplicateSignatures`) and adds `DuplicateErrors(RunId, FileEntryId)`.
Schema v8 adds `DuplicateOperationJournal`; v9 adds generic-quarantine restore support; v10 repairs the quarantine-member foreign key; v11 normalizes folder identity and collapses Windows case variants conservatively; v12 persists nullable volume/file identity for scan rows; v13 materializes `FolderEntries.ParentNormalizedPath` plus a `(SessionId, ParentNormalizedPath, TotalSizeBytes DESC)` index so parent/child lookups stop deriving the relationship inside the predicate; v14 adds `ScanSessions.OwnerProcessId` / `OwnerProcessStartedUtc` so a session left `Running` by a crash can be told apart from a live scan; v15 indexes the `FileEntries(Id)` cascade referrers (`DuplicateGroupMembers`, `DuplicateGroups`, `DuplicateErrors`, `DuplicateSignatures`) and adds `DuplicateErrors(RunId, FileEntryId)`; v16 adds `FileEntries.IsAdditionalHardLink`, set on every name of a hard-linked file after the first the scan reached, so the category breakdown counts the shared data once (folder and session totals already skip it during the scan).

Historical identity-less rows remain readable for analysis but cannot authorize scan-backed deletion until rescanned. Duplicate deletion writes intent before filesystem operations and records final state afterward, so interrupted or partial duplicate operations can be inspected after restart.

Expand Down Expand Up @@ -384,7 +384,7 @@ SmartCleanerService.CleanAsync(groups, method, progress)

## 8. Database architecture

### Schema (v15 current)
### Schema (v16 current)

```sql
SchemaVersion (Version INTEGER, AppliedUtc TEXT)
Expand All @@ -399,6 +399,7 @@ FileEntries (Id PK, SessionId FK→CASCADE, FullPath, FileName, Extension,
Attributes, Category, IsReparsePoint,
NormalizedFullPath NULL,
IdentityVolumeSerial NULL, IdentityFileIndex NULL,
IsAdditionalHardLink,
UNIQUE(SessionId, NormalizedFullPath))

FolderEntries (Id PK, SessionId FK→CASCADE, FullPath, NormalizedFullPath,
Expand Down
8 changes: 4 additions & 4 deletions docs/public/CODEMAP.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# StorageMaster — Codemap

<!-- schema-version: 15 -->
<!-- schema-version: 16 -->

> **Version:** 2.2.1 | **Current-state review:** 2026-08-18
> High-level source map for major files, types, methods, and database tables. Source remains authoritative for exhaustive membership.
> **Current-state note:** current source uses schema v15, independent SQLite connection leases, exact UTC timestamp reads, persisted scan-time file identity, indexed folder parent/child lookups, scan-session ownership with startup recovery, managed/Turbo persistence hardening, dedicated duplicate deletion/recovery, fail-closed path/snapshot checks, and strengthened release gates. `DatabaseSchema.CurrentVersion` is authoritative for the schema number. See `RELIABILITY_AUDIT_2026-08-18.md` for evidence and limits as of that dated audit (which describes the schema at v12).
> **Current-state note:** current source uses schema v16, independent SQLite connection leases, exact UTC timestamp reads, persisted scan-time file identity, indexed folder parent/child lookups, scan-session ownership with startup recovery, managed/Turbo persistence hardening, dedicated duplicate deletion/recovery, fail-closed path/snapshot checks, and strengthened release gates. `DatabaseSchema.CurrentVersion` is authoritative for the schema number. See `RELIABILITY_AUDIT_2026-08-18.md` for evidence and limits as of that dated audit (which describes the schema at v12).

---

Expand Down Expand Up @@ -56,7 +56,7 @@

**Project file:** `src/StorageMaster.Core/StorageMaster.Core.csproj`
**Target:** `net8.0`
**Packages:** `CommunityToolkit.Mvvm 8.4.0`, `Microsoft.Extensions.DI.Abstractions 10.0.0`, `Microsoft.Extensions.Logging.Abstractions 10.0.0`, `SixLabors.ImageSharp 3.1.12`
**Packages:** `CommunityToolkit.Mvvm 8.4.0`, `Microsoft.Extensions.DI.Abstractions 10.0.0`, `Microsoft.Extensions.Logging.Abstractions 10.0.0`. Image decoding for the perceptual hash goes through `IImageHashDecoder`, implemented in Platform.Windows on the Windows Imaging Component.

---

Expand Down Expand Up @@ -698,6 +698,7 @@ Internal static class. `CurrentVersion = 15`; each level is a `V<N>Statements` a
| v13 | `FolderEntries.ParentNormalizedPath` + `(SessionId, ParentNormalizedPath, TotalSizeBytes DESC)` index |
| v14 | `ScanSessions.OwnerProcessId` / `OwnerProcessStartedUtc` |
| v15 | Indexes on the `FileEntries(Id)` cascade referrers, plus `DuplicateErrors(RunId, FileEntryId)` |
| v16 | `FileEntries.IsAdditionalHardLink`: further names of a hard-linked file, left out of the category totals |

Path casing is never computed in SQL: SQLite's `upper()` is ASCII-only while the application uses `ToUpperInvariant`. v13's backfill therefore splits the parent off the already-normalized column instead of re-normalizing.

Expand Down Expand Up @@ -1038,7 +1039,6 @@ The suite count changes as regression guards are added. Run the documented Relea
| Core | `CommunityToolkit.Mvvm` | 8.4.0 | MVVM source generators |
| Core | `Microsoft.Extensions.DependencyInjection.Abstractions` | 10.0.0 | DI interfaces |
| Core | `Microsoft.Extensions.Logging.Abstractions` | 10.0.0 | `ILogger<T>` |
| Core | `SixLabors.ImageSharp` | 3.1.12 | Image duplicate decoding and perceptual hashing |
| Platform.Windows | `Microsoft.Extensions.Logging.Abstractions` | 10.0.0 | Logging |
| Platform.Windows | `System.Management` | 9.0.5 | Windows drive-health queries |
| Storage | `Microsoft.Data.Sqlite` | 9.0.4 | SQLite access |
Expand Down
4 changes: 2 additions & 2 deletions docs/public/DOCUMENTATION.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# StorageMaster — Full Technical Documentation

<!-- schema-version: 15 -->
<!-- schema-version: 16 -->

> **Version:** 2.2.1 | **Current-state review:** 2026-08-18 | **.NET 8 / WinUI 3 / Windows App SDK 1.6**
> **Current storage/safety state:** schema v15 uses independent SQLite connection leases, normalized file/folder identity, exact UTC timestamp reads, duplicate recovery journals, nullable stable scan-time file identity, a materialized folder parent path, scan-session ownership with startup recovery, and indexed foreign-key cascade paths. Historical identity-less rows stay readable but require rescan before destructive scan-backed actions. `DatabaseSchema.CurrentVersion` is authoritative for the schema number.
> **Current storage/safety state:** schema v16 uses independent SQLite connection leases, normalized file/folder identity, exact UTC timestamp reads, duplicate recovery journals, nullable stable scan-time file identity, a materialized folder parent path, scan-session ownership with startup recovery, and indexed foreign-key cascade paths. Historical identity-less rows stay readable but require rescan before destructive scan-backed actions. `DatabaseSchema.CurrentVersion` is authoritative for the schema number.

---

Expand Down
4 changes: 2 additions & 2 deletions docs/public/SAFETY_RECOVERY.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ StorageMaster is a storage-management tool. Recoverability and auditability take
## Deletion modes

- Quarantine: preferred for duplicate cleanup. Files are moved into the app quarantine and can be restored.
- Recycle Bin: preferred for general cleanup when Windows supports recycling the target path. Where it does not (network shares, many removable drives, an item larger than the bin's maximum size, a drive whose bin is turned off), the item is left in place and reported as not deleted; Recycle Bin mode never falls back to permanent deletion.
- Recycle Bin: preferred for general cleanup when Windows supports recycling the target path. Where it does not (network shares, many removable drives, an item larger than the bin's maximum size, a drive whose bin is turned off), the item is left in place and reported as not deleted; Recycle Bin mode never falls back to permanent deletion on its own. Where the app is interactive (Duplicates, Cleanup, Smart Cleaner, Results), it then asks a second question, "Delete these N item(s) permanently?", lists the items and defaults to No. Only a yes deletes them permanently, through the same live checks as any other deletion; items the user was not shown are never included. Scheduled cleanup has no one to ask and keeps the refusal.
- Permanent delete: allowed only after explicit user intent and confirmation.

## Recovery journal
Expand Down Expand Up @@ -41,7 +41,7 @@ Recycle Bin and quarantine operations move logical file data but do not normally

- The current journal is inspectable through repository APIs and tests, but the WinUI recovery page still needs a first-class journal view.
- A process or power failure in the narrow interval after a quarantine move but before its transactional/fallback journal write can still leave a moved file requiring manual quarantine-directory reconciliation.
- Files changed after scan are skipped by duplicate cleanup rather than force-deleted.
- Files changed after scan are skipped by duplicate cleanup rather than force-deleted. The Duplicates page lists every selected file it left in place with the reason (changed since the analysis, could not be re-read, no longer matches the kept file, Recycle Bin unavailable, refused by Windows, kept file not verifiable, no stable identity).
- Permanent directory traversal is handle-bound and no-follow. Recycle Bin operations and individual file deletion still cross a final path-based Windows API boundary; snapshots and postchecks reduce risk but cannot mathematically eliminate a malicious last-instruction path swap.
- The program-leftover rule is heuristic. It is disabled, unselected, high-risk, and Recycle-Bin-only by default, but a reviewed directory can still receive new content between analysis and execution.
- Managed scanning resolves and checks reparse targets before enumeration, but Core-only metadata checks cannot close every adversarial junction swap. Turbo uses strong no-follow root-ancestor locks where ACL/sharing permits; protected ancestors and queued descendants retain a documented same-privilege swap window. Persisted identity and downstream deletion validation fail closed on changed files.
50 changes: 50 additions & 0 deletions src/StorageMaster.Core/Cleanup/CleanupEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ private async Task<SuggestionExecution> ExecuteSuggestionAsync(

long totalFreed = 0;
var failedPaths = new List<string>();
var recycleBinRefusedPaths = new List<string>();
var quarantinedPaths = new List<QuarantineMove>();
var processedPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var successfulPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Expand Down Expand Up @@ -188,6 +189,8 @@ private async Task<SuggestionExecution> ExecuteSuggestionAsync(
else
{
failedPaths.Add(outcome.Path);
if (outcome.RecycleBinRefused)
recycleBinRefusedPaths.Add(outcome.Path);
firstError ??= outcome.Error;
_logger.LogWarning("Delete failed: {Path} — {Error}", outcome.Path, outcome.Error);
}
Expand Down Expand Up @@ -232,9 +235,56 @@ private async Task<SuggestionExecution> ExecuteSuggestionAsync(
FailedPaths = failedPaths,
ErrorMessage = firstError,
QuarantinedPaths = quarantinedPaths,
RecycleBinRefusedPaths = recycleBinRefusedPaths,
}, wasCancelled);
}

/// <summary>
/// The suggestions of a finished Recycle Bin run, reduced to the targets the
/// Recycle Bin refused, for a permanent deletion the user has confirmed.
/// <para>
/// Only refusals are carried over: targets that were recycled, failed for another
/// reason, or were never reached stay out, so the retry cannot touch anything the
/// user was not shown. A suggestion that may not be deleted permanently (high
/// risk, or not supported) contributes nothing. The retry itself still goes
/// through every snapshot check of a normal run.
/// </para>
/// </summary>
public static IReadOnlyList<CleanupSuggestion> BuildPermanentRetryForRecycleBinRefusals(
IReadOnlyList<CleanupSuggestion> suggestions,
IReadOnlyList<CleanupResult> results)
{
var retry = new List<CleanupSuggestion>();
foreach (var result in results)
{
if (result.WasDryRun || result.RecycleBinRefusedPaths.Count == 0)
continue;

var suggestion = suggestions.FirstOrDefault(candidate => candidate.Id == result.SuggestionId);
if (suggestion is null)
continue;

var targets = new HashSet<string>(suggestion.TargetPaths, StringComparer.OrdinalIgnoreCase);
var refused = result.RecycleBinRefusedPaths
.Where(targets.Contains)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
if (refused.Length == 0)
continue;

var narrowed = suggestion with
{
TargetPaths = refused,
EstimatedBytes = refused.Sum(path =>
suggestion.ExpectedFileSnapshots.TryGetValue(path, out var snapshot) ? snapshot.SizeBytes : 0L),
};
if (ValidateDeletionPolicy(narrowed, DeletionMethod.Permanent) is null)
retry.Add(narrowed);
}

return retry;
}

/// <summary>
/// Writes a QuarantinedFiles restore record (MemberId=null, generic-cleanup
/// run) so the file shows up in the app's quarantine view. A recording
Expand Down
Loading