Repository Public License
1<!-- ORIX Clean / File: docs/architecture/overview.md / Author: Simon-Pierre Boucher / Contact: contact@spboucher.ai -->2# Architecture overview34ORIX Clean is a SwiftUI application on top of one Swift package, `ORIXCleanCore`, which holds every engine and5has no UI dependency. This document describes the split, the data flow and the parts that have no document of6their own: recommendations, reporting and Actions. Similar-image analysis is in `duplicates.md`.78## Layout910| Part | Location | Role |11|---|---|---|12| Core library | `Packages/ORIXCleanCore/Sources/ORIXCleanCore/` | Scanner, accounting, duplicates, image similarity, cleanup planning, deletion, applications, recommendations, persistence, reporting, workflows |13| Bench and fixture CLI | `Packages/ORIXCleanCore/Sources/orix-bench/` | `scan`, `dupes`, `similar`, `treemap`, `sample`, `fixture` |14| Core tests | `Packages/ORIXCleanCore/Tests/ORIXCleanCoreTests/` | Swift Testing suites on temporary folders and disk images |15| Application | `App/Sources/` | `App/` (model, root view, entry point), `DesignSystem/`, `Features/*` |16| UI tests | `UITests/ORIXCleanUITests.swift` | XCUITest scenarios on a disposable disk image |17| Project | `project.yml` | XcodeGen definition; the `.xcodeproj` is generated |1819Build settings that shape the architecture: Swift 6 language mode with complete strict concurrency, the20application target defaulting to `MainActor` isolation, macOS 15.0 minimum, Hardened Runtime, no sandbox, empty21entitlements, universal Release build.2223## Components2425```mermaid26flowchart TD27 subgraph App[Application - SwiftUI, main actor]28 Views[Feature views]29 Model[AppModel]30 Preview[CleanupPreviewSheet]31 end32 subgraph Core[ORIXCleanCore - no UI]33 Scanner[FileScanner]34 Tree[ScanTree]35 Queries[TreeQuery and Treemap]36 Dup[DuplicateFinder]37 Sim[SimilarImageFinder]38 Catalog[CleanupCatalog, Downloads, Trash, AppInventory]39 Plan[CleanupPlan]40 Auth[CleanupAuthorization]41 Engine[DeletionEngine]42 Policy[SafetyPolicy]43 Reco[RecommendationEngine]44 Store[HistoryStore]45 Report[Report and ReportBuilder]46 Flow[WorkflowRunner]47 end48 Views --> Model49 Model --> Scanner --> Tree50 Tree --> Queries --> Views51 Tree --> Dup52 Tree --> Sim53 Model --> Catalog54 Dup --> Plan55 Sim --> Plan56 Catalog --> Plan57 Plan --> Preview --> Auth --> Engine58 Engine --> Policy59 Engine --> Store60 Model --> Reco61 Store --> Reco62 Model --> Report63 Flow --> Preview64 Flow --> Engine65```6667## State and threading6869`AppModel` is a single `@Observable` object on the main actor. It owns the current `ScanResult`, the results of70each analysis, the cleanup selection (`basket`, keyed by path), the open preview request and the history71arrays. Views read it through the SwiftUI environment.7273Engines are blocking classes marked `@unchecked Sendable` with their own lock. The model runs them on74`DispatchQueue.global(qos: .userInitiated)` through a checked continuation and never blocks the main thread.75Progress is polled, not pushed: a 0.12 s timer copies `scanner.progress`, `duplicateFinder.progress` and76`similarFinder.progress` into observable properties and stops itself when nothing is running. Every counter77shown during a scan is a real counter from the engine.7879| Engine | Threads | Cancellation |80|---|---|---|81| `FileScanner` | 3 dedicated threads by default (1 under thermal pressure or Low Power Mode) | `cancel()`, `pause()`, `resume()` |82| `DuplicateFinder` | 2 to 6 dedicated threads, half the active cores | `cancel()`; a cancelled run returns no groups |83| `SimilarImageFinder` | `DispatchQueue.concurrentPerform` for fingerprints, serial comparison | `cancel()`; a cancelled run returns no groups |84| `DeletionEngine` | caller's thread, one item at a time | `cancel()`; remaining items are recorded as skipped |8586`treeVersion` is an integer the model increments whenever the tree changes (new scan, items removed) so that87views that draw from the tree recompute.8889## Lifecycle of a session9091```mermaid92sequenceDiagram93 participant U as User94 participant M as AppModel95 participant S as FileScanner96 participant A as Analyses97 participant P as Preview98 participant E as DeletionEngine99 participant H as HistoryStore100 U->>M: Scan a folder101 M->>S: run on a background queue102 S-->>M: ScanResult with tree and issues103 M->>H: record volume sample104 U->>M: Find duplicates, open Caches, ...105 M->>A: run on the tree or on disk106 A-->>M: candidates107 U->>M: tick items108 U->>P: Review109 P-->>M: confirmed plan110 M->>E: execute with authorization111 E-->>M: DeletionReport112 M->>H: save report113 M->>M: mark removed nodes, refresh lists114```115116After a cleanup, `AppModel.absorb` removes the affected paths from every list, calls `ScanTree.markRemoved` so117totals stay consistent without a rescan, reloads the Trash and records a new volume sample.118119## Recommendations120121`RecommendationEngine.evaluate(Findings)` is a pure function. `Findings` holds optional results; nil means122"not analysed yet" and produces nothing. Each recommendation carries its evidence sentence, paths, measured123size, risk, consequence and destination section. Results are sorted by measured size.124125| Id | Condition in the code | Risk |126|---|---|---|127| `low-space-<volume>` | writable volume with less than 10 % free | low |128| `growth-<volume>` | at least 3 samples over 6 hours, slope above 0.5 GB per day, projected under 60 days of free space | low |129| `duplicates` | redundant content of 200 MB or more | review |130| `deriveddata` | DerivedData candidates total 5 GB or more | low |131| `old-archives` | Xcode archives older than 180 days total 1 GB or more | review |132| `caches` | low-risk cache and log candidates total 2 GB or more | low |133| `old-installers` | installers and disk images added more than 90 days ago total 500 MB or more | review |134| `partial-downloads` | incomplete downloads total 100 MB or more | review |135| `trash` | Trash content of 1 GB or more | review |136137The growth figure is a least-squares slope (`Trend.bytesPerDay`) over samples that exist only while the138application was open; the text says it is a projection, not a forecast.139140## Reporting141142`Report` is a `Codable` value: title, generation date, scope, limitations and sections of facts and rows.143`ReportBuilder` produces sections from engine results (overview, largest files, duplicates, similar images,144candidates, cleanup results, trends) and `limitations(issues:fullDiskAccess:sharingMeasured:)` writes what the145scan could not see. Renderers:146147| Format | Implementation | Notes |148|---|---|---|149| Markdown | string builder | Escapes `\|` and newlines in table cells |150| CSV | string builder, CRLF | Every field quoted; a leading `=`, `+`, `-`, `@`, tab or CR is prefixed with `'` to neutralize spreadsheet formulas |151| JSON | `JSONEncoder`, sorted keys, ISO 8601 dates | The `Report` value itself |152| PDF | Core Graphics and Core Text | US Letter (612 by 792 points), paginated text with a footer; table rows are text lines, not drawn grids |153154Exports go through `NSSavePanel`, or to the directory given by `-ORIXExportDir` in tests.155156## Actions157158An Action is a saved `Workflow`: an ordered list of `WorkflowStep` values (`scanFolder`, `findDuplicates`,159`collectCaches`, `collectDeveloperData`, `collectDownloads`, `review`, `moveToTrash`, `report`). Four are built160in; user workflows are stored as JSON documents in the history database.161162`Workflow.validate()` enforces the product rule that removal happens only right after review: a `moveToTrash`163step is valid only if a `review` step precedes it with no scan or collection step in between, and each review164covers one removal. `WorkflowRunner` executes the steps, hands the plan to a `WorkflowReviewer` at each review165step, and removes only what that reviewer returned. In the application the reviewer is the cleanup preview166sheet; declining it ends the workflow with nothing removed. Collection steps in a workflow keep only low-risk167catalogue items. Details are in `cleanup.md`.168169## Localization170171Every UI string is written as `L("English")` (`StorageAccounting/Support.swift`); the English text is the key.172`Scripts/localize.py` extracts the keys from both source trees and writes `App/Resources/Localizable.xcstrings`173with `en` and `fr-CA` from `Scripts/translations-fr.json` (683 keys), failing when a key has no translation or174when placeholders differ. Numbers, sizes and dates are formatted through `ByteFormat` with the current locale.175176## Invariants177178- The core package imports no UI framework and contains no network code.179- Nothing is removed without a `CleanupAuthorization` created by the preview's confirm action.180- Every figure shown or exported comes from a measurement or a deletion record.181- The scan tree is the only copy of scan results and lives in memory.182183## Not handled184185- No background agent, scheduler or menu-bar item: nothing runs when the window is closed.186- No incremental rescan or filesystem-event monitoring; a rescan walks the whole root again.187- One scan at a time; a new scan replaces the previous tree and clears duplicate and similar-image results.188- No automatic updater, no crash reporter, no telemetry.189- Errors of the history store are swallowed (`AppModel.store` is optional and writes are best effort).190