Repository Public License
1<!-- ORIX Clean / File: docs/architecture/cleanup.md / Author: Simon-Pierre Boucher / Contact: contact@spboucher.ai -->2# Cleanup34Everything between "this could be removed" and "this was moved to the Trash". Sources: `CleanupPlanner/`5(`CleanupModel`, `CleanupCatalog`, `DownloadsAndTrash`), `SafeDeletion/` (`SafetyPolicy`, `DeletionEngine`),6`Applications/AppInventory.swift`, `Actions/Workflow.swift`, and `AppModel` plus `CleanupPreviewSheet` in the7application.89## The chain1011```mermaid12flowchart LR13 Sources[Catalogue, downloads, Trash, duplicates, similar images, applications, leftovers, manual selection] --> Item[CleanupItem]14 Item --> Basket[Selection ticked by the user]15 Basket --> Plan[CleanupPlan]16 Plan --> Preview[Cleanup preview sheet]17 Preview -->|Cancel| Nothing[nothing happens]18 Preview -->|Confirm| Auth[CleanupAuthorization]19 Auth --> Engine[DeletionEngine.execute]20 Engine --> Policy[SafetyPolicy.evaluate]21 Engine --> Reval[revalidation against the disk]22 Engine --> Trasher[Trasher: trashItem or removeItem]23 Engine --> Report[DeletionReport, one record per item]24 Report --> Store[HistoryStore]25 Report --> Results[Results sheet with Put Back]26```2728| Type | Role | Key fields |29|---|---|---|30| `CleanupItem` | One proposal | `path`, `category`, `risk`, `reason`, `consequence`, `measurement`, `owner`, `regeneration`, `closeFirst`, `verifyAgainst`, `confidenceNote` |31| `CleanupPlan` | The set shown in the preview | De-duplicated items sorted by allocated size; totals, `recoverable`, `highestRisk`, `byRisk`, `appsToClose` |32| `CleanupAuthorization` | Consent for a precise list | `confirmedPaths`, `highRiskAcknowledged`, `confirmedAt` |33| `DeletionEngine` | Executes | `execute(plan:authorization:mode:runningBundleIDs:)`, `restore(_:)`, `cancel()` |34| `DeletionReport` | Outcome | `records`, `mode`, `cancelled`, `freeBefore`, `freeAfter` |3536`CleanupPlan.init` keeps a path once and drops any item that lies inside another listed directory, so nested37selections are not counted twice.3839`Risk` has three levels: `low` (recreatable data in a documented location), `review` (may hold something the40user wants) and `high` (potentially important application or system data).4142`CleanupAuthorization` can only be built from a plan. In the application it is created in one place,43`AppModel.confirm`, which is called by the confirm button of the preview. (A Debug-only screenshot helper,44`runDemo`, also creates one; it requires a substitute home folder and is not compiled into Release builds.)4546## Where candidates come from4748| Source | Items | Risk |49|---|---|---|50| `CleanupCatalog.discover(.caches)` | Each entry of `~/Library/Caches` and `~/Library/Logs`, crash reports, eight browser caches | low |51| same | Items in the user temporary folder not modified for 7 days | review |52| `CleanupCatalog.discover(.developer)` | 23 documented locations: DerivedData per project, device support, previews, SwiftPM, CocoaPods, Carthage, Homebrew, npm, Yarn, pip, Gradle, Cargo, Go build, Playwright, and others | low; review for Xcode archives, pnpm store, uv cache, Maven repository, Go module cache |53| `CleanupCatalog.buildArtifacts` | `node_modules`, `.build`, `target`, `.gradle` next to their manifest; `DerivedData`, `__pycache__`; 20 MB or more; not under a `Library` folder | review |54| `DownloadsAnalyzer` | Top-level items of Downloads, classified as installer, disk image, archive, incomplete download, other | review |55| `TrashAnalyzer` | Items of `~/.Trash` and of `.Trashes/<uid>` on other volumes | review |56| Duplicates, similar images | See `duplicates.md` | review |57| `AppInventory.uninstallItems` | Application bundle and chosen associated files | review; high when the association is not an exact identifier match |58| `LeftoverFinder` | Library items named after an identifier with no matching application | review, with a confidence note |59| Storage map and Large Files | Any node the user ticks | review |6061Catalogue exclusions: names in `excludedCacheNames`, anything starting with `com.apple.`, `.DS_Store`, items62under 64 KiB, and paths claimed by a more specific rule. Every rule has a reason, a consequence and a63regeneration note (test `everyRuleIsDocumented`). Simulator devices, simulator runtimes and the Docker disk64image are `ManualHint` values: measured and explained, never candidates.6566## SafetyPolicy deny rules6768`SafetyPolicy.evaluate(path)` is the last check and applies whatever produced the item. Paths are normalized69first (`/tmp`, `/var`, `/etc` to `/private/...`; a `/System/Volumes/Data` prefix removed).7071| Rule | Denied |72|---|---|73| Form | Relative paths; any path containing a `..` component; `/` |74| System areas | `/System`, `/usr`, `/bin`, `/sbin`, `/private/etc`, `/private/var/db`, `/private/var/root`, `/Library/Apple`, `/cores`, `/dev`, `/opt`, `/Library/Developer/CommandLineTools`, `~/Library/Keychains`, and everything below them |75| `/private/var` | Everything except items deep inside `/private/var/folders/` and items in `/private/var/tmp/` |76| System folders themselves | `/private`, `/private/tmp`, `/private/var/tmp` |77| Top-level folders themselves | `/Applications`, `/Applications/Utilities`, `/Library`, `/Users`, `/Users/Shared`, `/Volumes`, the home folder, `~/Library`, `~/Applications` |78| Structural children | Direct children of `/Library`, `~/Library` and `/Users`; in the home folder, the standard folders Desktop, Documents, Downloads, Movies, Music, Pictures, Public, Library, Applications and `.Trash` |79| Volumes | The root of any volume under `/Volumes`; its `.Trashes`, `.Spotlight-V100` and `.fseventsd` folders |80| Inside bundles | Any path with an `.app` component above the last one: remove the whole application or nothing |81| Inside libraries | Any path inside a `photoslibrary`, `musiclibrary`, `tvlibrary`, `aplibrary`, `imovielibrary`, `fcpbundle`, `logicx`, `sparsebundle`, `pvm`, `vmwarevm` or `utm` package |8283The policy is a deny list on location. It does not make a judgement about value: a whole application, a84whole photo library, a non-standard folder or a dotfile folder in the home directory is allowed if the user85selects and confirms it.8687## Execution and revalidation8889For each item of the plan, in order, the engine stops at the first check that fails and writes one record.9091```mermaid92flowchart TD93 A[next item] --> B{cancelled}94 B -->|yes| S[skipped]95 B -->|no| C{path in confirmedPaths}96 C -->|no| S97 C -->|yes| D{high risk and not acknowledged}98 D -->|yes| S99 D -->|no| E{SafetyPolicy allows}100 E -->|no| S101 E -->|yes| F{permanent mode and category not trash}102 F -->|yes| S103 F -->|no| G{lstat: exists, same inode, same size for a file}104 G -->|no| S105 G -->|yes| H{owning application running}106 H -->|yes| M[requiresManualAction]107 H -->|no| I{duplicate: kept copy exists, other inode, identical bytes, not selected}108 I -->|no| S109 I -->|yes| J[trash or remove]110 J -->|ok| K[movedToTrash or permanentlyDeleted]111 J -->|volume has no Trash| M112 J -->|read-only volume or permission denied or other error| X[failed]113```114115Revalidation uses what was measured when the item was listed: the inode number (`measurement.fileID`, when116known) and, for a regular file, the logical size. An item that vanished, was replaced by another file or117changed size is skipped with the reason in the record. A directory is checked by inode only.118119### Statuses120121| Status | Meaning |122|---|---|123| `movedToTrash` | In the Trash of its volume; `trashPath` records where, when the system reported it |124| `permanentlyDeleted` | Removed with `FileManager.removeItem`; only possible for Trash items |125| `skipped` | Not attempted; `detail` says why (cancelled, not confirmed, protected, gone, replaced, changed, verification failed) |126| `failed` | Attempted and refused by the system (read-only volume, permission denied, other error text) |127| `requiresManualAction` | The user must do something first: quit an application, or remove the item in Finder because the volume has no Trash |128129Every item ends with exactly one record. A partial failure never aborts the run.130131## Trash versus permanent132133- `moveToTrash` is the default and the only mode for everything that is not already in the Trash. It uses134 `FileManager.trashItem`, which places the item in the Trash of its own volume. It is a rename, so it works on135 a full volume and frees nothing by itself; the preview and the results say so.136- `permanent` is used only by "Empty Trash" and "Delete Permanently" in the Trash section. The engine refuses137 it for any item whose category is not `trash`. The preview then requires typing `DELETE`.138- If a volume has no Trash (`NSFeatureUnsupportedError`), the item is left in place with139 `requiresManualAction`; the engine never falls back to permanent deletion.140141## Undo142143`DeletionEngine.restore(record)` moves an item from its recorded Trash path back to its original path. It144returns `notInTrash` when the item is no longer there, `destinationOccupied` when something now exists at the145original path (nothing is overwritten), or `failed` with the system message. The application marks the record146`restored`, saves the updated report and refreshes the Trash. Restoration is offered in the results sheet and147from the cleanup log in History for as long as the item stays in the Trash. Permanently deleted items have no148undo.149150## Workflows: removal only right after review151152`Workflow.validate()` walks the steps with a `reviewed` flag: scan and collection steps clear it, `review` sets153it, `moveToTrash` requires it and clears it. A workflow with a removal that does not directly follow a review154(reports aside) throws `removalWithoutReview` and does not start. At run time `WorkflowRunner` passes the155collected plan to the `WorkflowReviewer`; a nil answer ends the run with "Nothing was removed", and only the156plan and authorization returned by the reviewer reach the engine. Built-in collection steps keep low-risk157catalogue items only; duplicate steps keep the first path of each group and verify the others against it.158159## Invariants160161- No authorization, no removal; an item outside `confirmedPaths` is skipped even if it is in the plan.162- High-risk items need `highRiskAcknowledged`, set by a separate checkbox in the preview.163- The policy is evaluated on every item regardless of its source.164- Nothing is permanently deleted unless it was already in the Trash and the user typed the confirmation.165- A duplicate is removed only while an identical, distinct copy remains.166167## Not handled168169- Root-owned or otherwise unwritable items: reported as `failed`; there is no elevation.170- Time-of-check to time-of-use gaps: an item can still change between revalidation and the move. The window is171 one item wide and the result is a Trash move, not a deletion.172- Home dot-folders other than the credential stores the policy names (`.ssh`, `.gnupg`, `.aws`, `.kube`,173 `.config/gcloud`, `.password-store`) are allowed when the user ticks them in the map or in Large Files.174- Free space before and after is read on the volume of the first item only.175- Directory contents are not re-measured at removal; a folder is identified by inode.176