Free, open-source macOS cleaner. CleanMyMac alternative with zero telemetry. Native SwiftUI, scheduled auto-cleaning, Xcode/Homebrew/system cache cleanup. MIT licensed.
Swift cache-cleanercleanmymaccleanupdisk-cleanerdisk-spacehomebrewmac-utilitymacosmacos-appmacos-cleanermacosxnativeossosxprivacyswiftswiftuisystem-cleanerxcode-cleaner
cleanup depth: universal binaries, language files, deeper caches; fix wifi.log and Docker cleaning; bump 2.9.0
momenbasel695eb259c955
diff --git a/PureMac/Logic/Scanning/LanguageFilesScanner.swift b/PureMac/Logic/Scanning/LanguageFilesScanner.swiftnew file mode 100644index 0000000..8d2f64c--- /dev/null+++ b/PureMac/Logic/Scanning/LanguageFilesScanner.swift@@ -0,0 +1,214 @@+import Foundation++/// One app bundle with localization folders the user's system does not need.+struct LanguageFileFinding: Sendable {+ /// A single removable localization folder inside Contents/Resources.+ struct Lproj: Sendable {+ /// Full path to the .lproj folder.+ let path: String+ /// Recursive size of the folder in bytes.+ let size: Int64+ }++ /// Bundle name without the .app suffix.+ let appName: String+ /// Full path to the .app bundle.+ let appPath: String+ /// Removable .lproj folders found in the bundle.+ let lprojs: [Lproj]+ /// True when Contents/_MASReceipt is present. An App Store update or+ /// re-download restores stripped localizations anyway, so callers should+ /// leave these findings unselected by default.+ let appStore: Bool++ /// Combined size of all removable folders in the bundle.+ var totalBytes: Int64 { lprojs.reduce(0) { $0 + $1.size } }+}++/// Finds unused .lproj localization folders inside installed app bundles+/// (the CleanMyMac "Language Files" feature). Pure logic - nothing is deleted+/// here. The integrator surfaces each removable .lproj as its own+/// CleanableItem (see `flatten`), and deletion runs through the existing+/// CleaningEngine.removeItem flow.+struct LanguageFilesScanner: Sendable {++ /// Normalized language keys that must never be flagged as removable.+ /// Built from Locale.preferredLanguages - "en-US" keeps "en" plus the+ /// "en-US"/"en_US" variants - and always includes en, English (the legacy+ /// folder name) and Base, which apps rely on as fallbacks.+ var keepLanguages: Set<String> {+ var keep: Set<String> = ["en", "english", "base"]+ for language in Locale.preferredLanguages {+ // "en-us" also keeps plain "en" so regional variants of a+ // preferred language survive.+ Self.insertWithBase(Self.normalize(language), into: &keep)+ }+ return keep+ }++ /// Scans the given application directories (top level plus one nested+ /// level, e.g. /Applications/Utilities) and returns one finding per app+ /// bundle that has removable localizations. Apps under /System and the+ /// PureMac bundle itself are never reported.+ func scan(applicationDirs: [String]) -> [LanguageFileFinding] {+ let fileManager = FileManager.default+ let keep = keepLanguages+ let ownPath = (Bundle.main.bundlePath as NSString).standardizingPath++ var findings: [LanguageFileFinding] = []+ for dir in applicationDirs {+ for appPath in appBundles(in: dir, fileManager: fileManager) {+ if let finding = inspect(appPath: appPath, keep: keep, ownPath: ownPath, fileManager: fileManager) {+ findings.append(finding)+ }+ }+ }++ return findings.sorted { $0.totalBytes > $1.totalBytes }+ }++ /// Expands per-app findings into one entry per removable .lproj so the+ /// integrator can surface each folder as its own CleanableItem. Entries+ /// are named "<App> - <language display name>".+ func flatten(_ findings: [LanguageFileFinding]) -> [(name: String, path: String, size: Int64, appStore: Bool)] {+ findings.flatMap { finding in+ finding.lprojs.map { lproj in+ let code = ((lproj.path as NSString).lastPathComponent as NSString).deletingPathExtension+ let identifier = code.replacingOccurrences(of: "_", with: "-")+ let display = Locale.current.localizedString(forIdentifier: identifier) ?? code+ return (name: "\(finding.appName) - \(display)", path: lproj.path, size: lproj.size, appStore: finding.appStore)+ }+ }+ }++ // MARK: - Private++ /// Lowercases and unifies separators so "pt_BR", "pt-BR" and "pt-br" all+ /// compare equal.+ private static func normalize(_ language: String) -> String {+ language.lowercased().replacingOccurrences(of: "_", with: "-")+ }++ /// Inserts a normalized language plus its base, so "pt-br" also keeps+ /// plain "pt".+ private static func insertWithBase(_ normalized: String, into keep: inout Set<String>) {+ keep.insert(normalized)+ if let base = normalized.split(separator: "-").first {+ keep.insert(String(base))+ }+ }++ /// Lists .app bundles at the top level of `dir` and one nested level+ /// below it. A missing directory (e.g. ~/Applications) is treated as+ /// empty.+ private func appBundles(in dir: String, fileManager: FileManager) -> [String] {+ guard let topLevel = try? fileManager.contentsOfDirectory(atPath: dir) else { return [] }++ var bundles: [String] = []+ for entry in topLevel {+ let path = dir + "/" + entry+ if entry.hasSuffix(".app") {+ bundles.append(path)+ } else if isDirectory(path, fileManager: fileManager) {+ guard let nested = try? fileManager.contentsOfDirectory(atPath: path) else { continue }+ for sub in nested where sub.hasSuffix(".app") {+ bundles.append(path + "/" + sub)+ }+ }+ }+ return bundles+ }++ /// Builds a finding for one bundle, or nil when the bundle is skipped or+ /// has nothing removable.+ private func inspect(appPath: String, keep: Set<String>, ownPath: String, fileManager: FileManager) -> LanguageFileFinding? {+ let standardized = (appPath as NSString).standardizingPath+ // System apps live on the sealed volume and PureMac must never offer+ // to strip itself.+ if standardized.hasPrefix("/System/") { return nil }+ if standardized == ownPath { return nil }+ if (standardized as NSString).lastPathComponent == "PureMac.app" { return nil }++ let resourcesPath = appPath + "/Contents/Resources"+ guard isDirectory(resourcesPath, fileManager: fileManager) else { return nil }++ let contents: [String]+ do {+ contents = try fileManager.contentsOfDirectory(atPath: resourcesPath)+ } catch {+ Logger.shared.log("Cannot read \(resourcesPath): \(error.localizedDescription)", level: .warning)+ return nil+ }++ // A bundle with a single .lproj keeps it regardless of language —+ // it is the app's only (and therefore primary) localization, often+ // holding its nibs and storyboards.+ let lprojCount = contents.filter { $0.lowercased().hasSuffix(".lproj") }.count+ guard lprojCount > 1 else { return nil }++ // Per-bundle keep set: the global set plus this bundle's development+ // region — NSBundle's fallback chain ends there, and for apps+ // developed in a non-English region it is often the only complete+ // localization — and any per-app language override the user set in+ // System Settings > Language & Region > Applications.+ var keep = keep+ let infoPlist = NSDictionary(contentsOfFile: appPath + "/Contents/Info.plist")+ if let region = infoPlist?["CFBundleDevelopmentRegion"] as? String {+ Self.insertWithBase(Self.normalize(region), into: &keep)+ }+ if let bundleID = infoPlist?["CFBundleIdentifier"] as? String,+ let override = CFPreferencesCopyValue(+ "AppleLanguages" as CFString, bundleID as CFString,+ kCFPreferencesCurrentUser, kCFPreferencesAnyHost+ ) as? [String] {+ for language in override {+ Self.insertWithBase(Self.normalize(language), into: &keep)+ }+ }++ var lprojs: [LanguageFileFinding.Lproj] = []+ for entry in contents where entry.lowercased().hasSuffix(".lproj") {+ let language = String(entry.dropLast(".lproj".count))+ guard !keep.contains(Self.normalize(language)) else { continue }++ let lprojPath = resourcesPath + "/" + entry+ // A symlinked .lproj points at content shared elsewhere in the+ // bundle; removing it could break the target, so leave it alone.+ if let type = (try? fileManager.attributesOfItem(atPath: lprojPath))?[.type] as? FileAttributeType,+ type == .typeSymbolicLink { continue }++ lprojs.append(.init(path: lprojPath, size: directorySize(path: lprojPath, fileManager: fileManager)))+ }++ guard !lprojs.isEmpty else { return nil }++ let appStore = fileManager.fileExists(atPath: appPath + "/Contents/_MASReceipt")+ let appName = ((appPath as NSString).lastPathComponent as NSString).deletingPathExtension+ return LanguageFileFinding(appName: appName, appPath: appPath, lprojs: lprojs, appStore: appStore)+ }++ /// Recursive size of one .lproj. Localization folders stay small, so no+ /// entry cap is applied; unreadable entries are skipped, not fatal.+ private func directorySize(path: String, fileManager: FileManager) -> Int64 {+ guard let enumerator = fileManager.enumerator(+ at: URL(fileURLWithPath: path),+ includingPropertiesForKeys: [.fileSizeKey, .isRegularFileKey],+ options: [],+ errorHandler: { _, _ in true }+ ) else { return 0 }++ var totalSize: Int64 = 0+ for case let fileURL as URL in enumerator {+ guard let values = try? fileURL.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey]),+ let isFile = values.isRegularFile, isFile,+ let size = values.fileSize else { continue }+ totalSize += Int64(size)+ }+ return totalSize+ }++ private func isDirectory(_ path: String, fileManager: FileManager) -> Bool {+ var isDir: ObjCBool = false+ return fileManager.fileExists(atPath: path, isDirectory: &isDir) && isDir.boolValue+ }+}diff --git a/PureMac/Logic/Scanning/UniversalBinaryScanner.swift b/PureMac/Logic/Scanning/UniversalBinaryScanner.swiftnew file mode 100644index 0000000..686a634--- /dev/null+++ b/PureMac/Logic/Scanning/UniversalBinaryScanner.swift@@ -0,0 +1,343 @@+import Foundation++/// One fat Mach-O file inside an app bundle, together with the slices that+/// can be stripped on this machine and the bytes doing so would reclaim.+/// `removableArchs` uses lipo's arch spelling ("x86_64", "arm64", ...) so it+/// can be passed straight to `lipo -remove` by BinaryThinner.+struct FatBinary: Sendable {+ let path: String+ let removableArchs: [String]+ let reclaimableBytes: Int64+}++/// A universal-binary discovery for one app bundle: the app's main+/// executable plus every fat framework/dylib found under Contents/Frameworks+/// (where most of the savings live for Electron apps). `appStore` marks apps+/// carrying a _MASReceipt — thinning those can break receipt validation, so+/// the caller should surface them unselected by default.+struct UniversalBinaryFinding: Identifiable, Sendable {+ let id = UUID()+ let appPath: String+ let appName: String+ let executablePath: String+ let nativeArch: String+ /// Union of removable arch names across all fat binaries in the bundle.+ let removableArchs: [String]+ /// Total bytes freed by stripping every foreign slice in the bundle.+ let reclaimableBytes: Int64+ let appStore: Bool+ /// Every fat Mach-O in the bundle with per-file removable archs — the+ /// exact work list BinaryThinner executes.+ let fatBinaries: [FatBinary]+}++/// Finds universal (fat) app binaries carrying a slice for the architecture+/// this Mac does not run natively, and computes how many bytes stripping the+/// foreign slice would reclaim. Pure logic — no mutation, no privileged+/// operations — so it stays a plain Sendable struct rather than an actor.+///+/// The FAT header is parsed by hand from the first 4 KB of each candidate+/// file instead of shelling out to `lipo -info` per file: an /Applications+/// walk touches thousands of framework binaries and process spawns would+/// dominate the scan time.+struct UniversalBinaryScanner: Sendable {++ // MARK: - Mach-O constants (values as they appear byte-swapped from disk)++ private static let fatMagic: UInt32 = 0xcafe_babe+ private static let fatMagic64: UInt32 = 0xcafe_babf+ private static let cpuTypeX86_64: UInt32 = 0x0100_0007+ private static let cpuTypeARM64: UInt32 = 0x0100_000c++ /// lipo arch spelling per (cputype, masked cpusubtype). arm64e and x86_64h+ /// are distinct lipo names, so the subtype matters for `-remove` to hit+ /// the right slice.+ private static func archName(cpuType: UInt32, cpuSubtype: UInt32) -> String? {+ // High byte of cpusubtype carries capability flags (e.g. LIB64,+ // PTRAUTH versioning) — mask them off before matching.+ let subtype = cpuSubtype & 0x00ff_ffff+ switch (cpuType, subtype) {+ case (0x0000_0007, _): return "i386"+ case (Self.cpuTypeX86_64, 8): return "x86_64h"+ case (Self.cpuTypeX86_64, _): return "x86_64"+ case (0x0000_000c, _): return "arm"+ case (Self.cpuTypeARM64, 2): return "arm64e"+ case (Self.cpuTypeARM64, _): return "arm64"+ default: return nil+ }+ }++ /// The machine's native architecture, asked of the kernel at runtime.+ /// A compile-time #if arch check would follow whichever slice PureMac+ /// itself runs as — under Rosetta the x86_64 slice would classify every+ /// app's native arm64/arm64e slices as removable, and thinning would+ /// strip them. hw.optional.arm64 is absent on Intel hardware.+ private static let hostIsARM64: Bool = {+ var value: Int32 = 0+ var size = MemoryLayout<Int32>.size+ guard sysctlbyname("hw.optional.arm64", &value, &size, nil, 0) == 0 else {+ return false+ }+ return value == 1+ }()+ private static var hostCPUType: UInt32 { hostIsARM64 ? cpuTypeARM64 : cpuTypeX86_64 }+ private static var hostArchName: String { hostIsARM64 ? "arm64" : "x86_64" }++ private var fileManager: FileManager { .default }++ // MARK: - Public API++ /// Walks the given application directories (top level plus one nested+ /// level, so apps grouped in subfolders like /Applications/Utilities are+ /// found) and returns one finding per app that has at least one foreign+ /// slice to strip.+ ///+ /// Skipped entirely: anything under /System, and PureMac itself (thinning+ /// the running binary out from under the process is asking for trouble).+ /// App Store apps (Contents/_MASReceipt present) are still reported but+ /// flagged `appStore = true`.+ func scan(+ applicationDirs: [String] = ["/Applications", "\(NSHomeDirectory())/Applications"]+ ) -> [UniversalBinaryFinding] {+ var findings: [UniversalBinaryFinding] = []+ let ownBundlePath = Bundle.main.bundleURL.resolvingSymlinksInPath().path++ for dir in applicationDirs {+ for appPath in appBundles(in: dir) {+ let resolved = URL(fileURLWithPath: appPath).resolvingSymlinksInPath().path+ guard !resolved.hasPrefix("/System"), resolved != ownBundlePath else { continue }+ if let finding = inspectApp(at: appPath) {+ findings.append(finding)+ }+ }+ }++ return findings.sorted { $0.reclaimableBytes > $1.reclaimableBytes }+ }++ /// Rebuilds the finding for a single app bundle. Used by CleaningEngine+ /// to re-derive the lipo work list from a CleanableItem's bundle path+ /// right before thinning, so a stale scan can never strip slices the+ /// bundle no longer has. Same /System and self-bundle guards as scan().+ func finding(forAppAt appPath: String) -> UniversalBinaryFinding? {+ let resolved = URL(fileURLWithPath: appPath).resolvingSymlinksInPath().path+ let ownBundlePath = Bundle.main.bundleURL.resolvingSymlinksInPath().path+ guard !resolved.hasPrefix("/System"), resolved != ownBundlePath else { return nil }+ return inspectApp(at: appPath)+ }++ // MARK: - Enumeration++ /// `.app` bundles at the top level of `dir`, plus one nested level for+ /// subfolders (e.g. /Applications/Utilities/*.app). No deeper recursion —+ /// helper .app bundles nested inside other apps (and PlugIns/XPCServices/+ /// Helpers) are intentionally not walked, so their fat slices are not+ /// counted; savings are under-reported for those, never over-reported.+ private func appBundles(in dir: String) -> [String] {+ guard let entries = try? fileManager.contentsOfDirectory(atPath: dir) else { return [] }+ var apps: [String] = []+ for entry in entries {+ let path = (dir as NSString).appendingPathComponent(entry)+ if entry.hasSuffix(".app") {+ apps.append(path)+ continue+ }+ var isDir: ObjCBool = false+ guard fileManager.fileExists(atPath: path, isDirectory: &isDir), isDir.boolValue else { continue }+ if let nested = try? fileManager.contentsOfDirectory(atPath: path) {+ for sub in nested where sub.hasSuffix(".app") {+ apps.append((path as NSString).appendingPathComponent(sub))+ }+ }+ }+ return apps+ }++ // MARK: - Per-app inspection++ private func inspectApp(at appPath: String) -> UniversalBinaryFinding? {+ let contents = (appPath as NSString).appendingPathComponent("Contents")+ let infoPlistPath = (contents as NSString).appendingPathComponent("Info.plist")++ guard let plist = NSDictionary(contentsOfFile: infoPlistPath),+ let executableName = plist["CFBundleExecutable"] as? String else {+ // Not a readable bundle (broken install, sandbox denial) — skip.+ Logger.shared.log("Universal binary scan: unreadable Info.plist at \(infoPlistPath)", level: .warning)+ return nil+ }++ let executablePath = (contents as NSString)+ .appendingPathComponent("MacOS/\(executableName)")++ var fatBinaries: [FatBinary] = []+ if let main = parseFatFile(at: executablePath) {+ fatBinaries.append(main)+ }+ fatBinaries.append(contentsOf: fatFrameworkBinaries(in: contents))++ guard !fatBinaries.isEmpty else { return nil }++ let totalBytes = fatBinaries.reduce(Int64(0)) { $0 + $1.reclaimableBytes }+ guard totalBytes > 0 else { return nil }++ let appName = (plist["CFBundleDisplayName"] as? String)+ ?? (plist["CFBundleName"] as? String)+ ?? ((appPath as NSString).lastPathComponent as NSString).deletingPathExtension++ let receiptPath = (contents as NSString).appendingPathComponent("_MASReceipt")+ let isAppStore = fileManager.fileExists(atPath: receiptPath)++ let archUnion = Array(Set(fatBinaries.flatMap { $0.removableArchs })).sorted()++ return UniversalBinaryFinding(+ appPath: appPath,+ appName: appName,+ executablePath: executablePath,+ nativeArch: Self.hostArchName,+ removableArchs: archUnion,+ reclaimableBytes: totalBytes,+ appStore: isAppStore,+ fatBinaries: fatBinaries+ )+ }++ /// Fat binaries under Contents/Frameworks: top-level *.dylib files plus+ /// each *.framework's Versions/*/<binary>. One nested level only —+ /// symlinks (Versions/Current, the framework-root binary link) are+ /// skipped so the same file is never counted twice.+ private func fatFrameworkBinaries(in contentsDir: String) -> [FatBinary] {+ let frameworksDir = (contentsDir as NSString).appendingPathComponent("Frameworks")+ guard let entries = try? fileManager.contentsOfDirectory(atPath: frameworksDir) else { return [] }++ var result: [FatBinary] = []+ for entry in entries {+ let entryPath = (frameworksDir as NSString).appendingPathComponent(entry)+ if entry.hasSuffix(".dylib") {+ if isRegularFile(entryPath), let fat = parseFatFile(at: entryPath) {+ result.append(fat)+ }+ } else if entry.hasSuffix(".framework") {+ let versionsDir = (entryPath as NSString).appendingPathComponent("Versions")+ guard let versions = try? fileManager.contentsOfDirectory(atPath: versionsDir) else { continue }+ for version in versions {+ let versionPath = (versionsDir as NSString).appendingPathComponent(version)+ guard isRealDirectory(versionPath),+ let files = try? fileManager.contentsOfDirectory(atPath: versionPath) else { continue }+ for file in files {+ let filePath = (versionPath as NSString).appendingPathComponent(file)+ guard isRegularFile(filePath) else { continue }+ if let fat = parseFatFile(at: filePath) {+ result.append(fat)+ }+ }+ }+ }+ }+ return result+ }++ /// Regular file, not a symlink — framework layouts are full of symlinks+ /// back into Versions/ and following them would double-count slices.+ private func isRegularFile(_ path: String) -> Bool {+ guard let attrs = try? fileManager.attributesOfItem(atPath: path) else { return false }+ return (attrs[.type] as? FileAttributeType) == .typeRegular+ }++ /// Directory reached without following a symlink (filters Versions/Current).+ private func isRealDirectory(_ path: String) -> Bool {+ guard let attrs = try? fileManager.attributesOfItem(atPath: path) else { return false }+ return (attrs[.type] as? FileAttributeType) == .typeDirectory+ }++ // MARK: - FAT header parsing++ /// Reads the first 4 KB of the file and parses the Mach-O FAT header.+ /// Returns nil for thin (single-arch) binaries, non-Mach-O files, and+ /// anything unreadable or malformed (logged, never thrown). All header+ /// fields are big-endian on disk regardless of host, so every field is+ /// byte-swapped on read.+ private func parseFatFile(at path: String) -> FatBinary? {+ guard let handle = FileHandle(forReadingAtPath: path) else {+ // Common for sandbox-restricted bundles; not worth an error.+ Logger.shared.log("Universal binary scan: cannot open \(path)", level: .warning)+ return nil+ }+ defer { try? handle.close() }++ guard let data = try? handle.read(upToCount: 4096), data.count >= 8 else {+ return nil+ }+ let bytes = [UInt8](data)++ func be32(_ offset: Int) -> UInt32? {+ guard offset + 4 <= bytes.count else { return nil }+ return (UInt32(bytes[offset]) << 24) | (UInt32(bytes[offset + 1]) << 16)+ | (UInt32(bytes[offset + 2]) << 8) | UInt32(bytes[offset + 3])+ }+ func be64(_ offset: Int) -> UInt64? {+ guard offset + 8 <= bytes.count,+ let high = be32(offset), let low = be32(offset + 4) else { return nil }+ return (UInt64(high) << 32) | UInt64(low)+ }++ guard let magic = be32(0),+ magic == Self.fatMagic || magic == Self.fatMagic64 else {+ return nil // thin binary, script, or not Mach-O at all+ }+ let is64 = (magic == Self.fatMagic64)++ guard let nfat = be32(4), nfat > 0, nfat <= 16 else {+ // 0xcafebabe also opens Java .class files; an implausible arch+ // count is the tell. Treat as not-a-fat-binary.+ return nil+ }++ // fat_arch is 20 bytes (cputype, cpusubtype, offset, size, align);+ // fat_arch_64 is 32 (64-bit offset/size plus a reserved word).+ let entrySize = is64 ? 32 : 20+ let fileSize = (try? fileManager.attributesOfItem(atPath: path)[.size] as? Int64) ?? nil++ var removableArchs: [String] = []+ var reclaimable: Int64 = 0++ for index in 0..<Int(nfat) {+ let base = 8 + index * entrySize+ guard let cpuType = be32(base), let cpuSubtype = be32(base + 4) else {+ Logger.shared.log("Universal binary scan: truncated FAT header in \(path)", level: .warning)+ return nil+ }+ let sliceSize: Int64+ if is64 {+ guard let size = be64(base + 16) else {+ Logger.shared.log("Universal binary scan: truncated fat_arch_64 in \(path)", level: .warning)+ return nil+ }+ sliceSize = Int64(bitPattern: size)+ } else {+ guard let size = be32(base + 12) else {+ Logger.shared.log("Universal binary scan: truncated fat_arch in \(path)", level: .warning)+ return nil+ }+ sliceSize = Int64(size)+ }++ // Slice must lie inside the file, or the header is garbage+ // (e.g. a Java class file that slipped past the arch-count check).+ if let fileSize, sliceSize <= 0 || sliceSize > fileSize {+ return nil+ }++ guard cpuType != Self.hostCPUType else { continue }+ guard let name = Self.archName(cpuType: cpuType, cpuSubtype: cpuSubtype) else {+ // Foreign slice of an arch lipo can't name for us — leave it.+ Logger.shared.log("Universal binary scan: unknown cputype 0x\(String(cpuType, radix: 16)) in \(path)", level: .debug)+ continue+ }+ removableArchs.append(name)+ reclaimable += sliceSize+ }++ guard !removableArchs.isEmpty else { return nil }+ return FatBinary(path: path, removableArchs: removableArchs, reclaimableBytes: reclaimable)+ }+}diff --git a/PureMac/Logic/Utilities/FileProtection.swift b/PureMac/Logic/Utilities/FileProtection.swiftnew file mode 100644index 0000000..8bb99c1--- /dev/null+++ b/PureMac/Logic/Utilities/FileProtection.swift@@ -0,0 +1,42 @@+import Foundation++/// Shared SIP/immutability check used by both ScanEngine (so protected+/// entries never surface as cleanable items) and CleaningEngine (so a+/// protected survivor is reported as "skipped, protected by macOS" instead+/// of a scary removal error).+enum FileProtection {++ /// True when the entry is SIP-protected or immutable: BSD flags carry+ /// SF_RESTRICTED/SF_IMMUTABLE/UF_IMMUTABLE, or the path has the+ /// com.apple.rootless xattr. Deleting these fails even with admin+ /// privileges.+ static func isProtectedFromDeletion(path: String) -> Bool {+ var sb = stat()+ if lstat(path, &sb) == 0 {+ // SF_RESTRICTED (0x00080000) isn't exported by Darwin's Swift+ // overlay, so spell out the literal; the immutable flags are.+ let protectedFlags: UInt32 = 0x0008_0000 | UInt32(SF_IMMUTABLE) | UInt32(UF_IMMUTABLE)+ if sb.st_flags & protectedFlags != 0 {+ return true+ }+ }++ // SIP also marks paths with the com.apple.rootless xattr, which+ // can be present even when st_flags reads 0.+ let bufSize = listxattr(path, nil, 0, XATTR_NOFOLLOW)+ if bufSize > 0 {+ var buffer = [CChar](repeating: 0, count: bufSize)+ let read = listxattr(path, &buffer, bufSize, XATTR_NOFOLLOW)+ if read > 0 {+ let names = Data(bytes: &buffer, count: read)+ .split(separator: 0)+ .compactMap { String(data: $0, encoding: .utf8) }+ if names.contains("com.apple.rootless") {+ return true+ }+ }+ }++ return false+ }+}diff --git a/PureMac/Models/Models.swift b/PureMac/Models/Models.swiftindex 44bfd43..4101fc9 100644--- a/PureMac/Models/Models.swift+++ b/PureMac/Models/Models.swift@@ -15,6 +15,8 @@ enum CleaningCategory: String, CaseIterable, Identifiable, Codable {case brewCache = "Brew Cache"case nodeCache = "Node Cache"case dockerCache = "Docker Cache"+ case universalBinaries = "Universal Binaries"+ case languageFiles = "Language Files"var id: String { rawValue }@@ -32,6 +34,8 @@ enum CleaningCategory: String, CaseIterable, Identifiable, Codable {case .brewCache: return "mug.fill"case .nodeCache: return "leaf.fill"case .dockerCache: return "shippingbox.fill"+ case .universalBinaries: return "cpu"+ case .languageFiles: return "globe"}}@@ -49,6 +53,8 @@ enum CleaningCategory: String, CaseIterable, Identifiable, Codable {case .brewCache: return "Homebrew download cache"case .nodeCache: return "npm, yarn, and pnpm download caches"case .dockerCache: return "Docker images, containers, and build cache"+ case .universalBinaries: return "Unused CPU architecture slices in app binaries"+ case .languageFiles: return "Unused app localizations"}}@@ -66,6 +72,8 @@ enum CleaningCategory: String, CaseIterable, Identifiable, Codable {case .brewCache: return .mintcase .nodeCache: return .pinkcase .dockerCache: return .indigo+ case .universalBinaries: return .brown+ case .languageFiles: return .gray}}@@ -80,6 +88,15 @@ enum CleaningCategory: String, CaseIterable, Identifiable, Codable {static var scannable: [CleaningCategory] {allCases.filter { $0 != .smartScan && $0 != .purgeableSpace }}++ // Categories that rewrite app bundles in place (binary thinning,+ // localization stripping) instead of deleting junk. Their items always+ // start unselected, and the scheduled autoClean path skips them+ // entirely — re-signing every installed app is never an unattended+ // action.+ static var appModifying: Set<CleaningCategory> {+ [.universalBinaries, .languageFiles]+ }}// MARK: - Scan Statediff --git a/PureMac/Services/BinaryThinner.swift b/PureMac/Services/BinaryThinner.swiftnew file mode 100644index 0000000..2183247--- /dev/null+++ b/PureMac/Services/BinaryThinner.swift@@ -0,0 +1,323 @@+import Foundation++/// Strips foreign-architecture slices from the fat binaries of one app+/// bundle (a UniversalBinaryFinding from UniversalBinaryScanner) and ad-hoc+/// re-signs the bundle so Gatekeeper still accepts it. Also removes .lproj+/// localization folders through the same flow, because deleting sealed+/// resources with a plain unlink breaks the bundle's signature.+///+/// Safety model — the original bundle is never modified in place:+/// 1. Entitlement gate: apps claiming provisioning-backed entitlements+/// (com.apple.developer.*, com.apple.application-identifier) are+/// refused outright. Those entitlements are only honored under an+/// Apple-issued certificate; an ad-hoc signature carrying them is+/// killed by AMFI at spawn.+/// 2. Preflight: the bundle and its parent directory must be writable by+/// the current user (the swap below is two renames in the parent).+/// Otherwise fail with `needsAdmin` before touching anything; there+/// is no admin escalation here.+/// 3. Stage: clone the whole bundle to a hidden sibling directory (APFS+/// makes the copy cheap) and apply every modification — lipo or lproj+/// removal — to the copy only.+/// 4. Sign the staged copy ad-hoc, then verify it with+/// `codesign --verify --deep --strict`. Any failure discards the copy+/// and leaves the original untouched; nothing to roll back, so a+/// failed sign can never leave a mixed Developer ID / ad-hoc bundle.+/// 5. Strip com.apple.quarantine from the verified copy. The re-sign+/// changes the cdhash, so a still-quarantined app would otherwise be+/// re-assessed by Gatekeeper and refused as not notarized.+/// 6. Swap: rename the original aside, rename the staged copy into place,+/// delete the original. If the delete fails (root-owned contents) the+/// swap is undone and `needsAdmin` is returned, so "success" always+/// means the space was actually freed.+actor BinaryThinner {++ enum ThinningError: LocalizedError {+ /// Bundle, its parent directory, or its contents not writable by+ /// this user. Caller decides what to do; this actor never escalates+ /// privileges.+ case needsAdmin(String)+ /// App claims provisioning-backed entitlements that only work under+ /// its original developer signature; re-signing would stop it+ /// launching, so it is refused before anything is staged.+ case restrictedEntitlements(String)+ case lipoFailed(String, String)+ case swapFailed(String, String)+ case codesignFailed(String, String)+ case verificationFailed(String, String)+ case nothingToThin(String)++ var errorDescription: String? {+ switch self {+ case .needsAdmin(let path):+ return "Not writable by current user: \(path)"+ case .restrictedEntitlements(let app):+ return "Cannot modify \(app): its entitlements require the original developer signature"+ case .lipoFailed(let path, let detail):+ return "lipo failed for \(path): \(detail)"+ case .swapFailed(let path, let detail):+ return "Could not swap modified bundle into place at \(path): \(detail)"+ case .codesignFailed(let app, let detail):+ return "Re-signing failed for \(app): \(detail)"+ case .verificationFailed(let app, let detail):+ return "Signature verification failed for \(app): \(detail)"+ case .nothingToThin(let app):+ return "No removable slices in \(app)"+ }+ }+ }++ private let fileManager = FileManager.default++ // MARK: - Public API++ /// Thins every fat binary in the finding and re-signs the bundle.+ /// Success value is the number of bytes actually freed (sum of+ /// before-minus-after file sizes, which can differ slightly from the+ /// scanner's estimate because lipo rewrites the FAT header padding).+ func thin(_ finding: UniversalBinaryFinding) async -> Result<Int64, Error> {+ let binaries = finding.fatBinaries.filter { !$0.removableArchs.isEmpty }+ guard !binaries.isEmpty else {+ return .failure(ThinningError.nothingToThin(finding.appPath))+ }++ let appPath = (finding.appPath as NSString).standardizingPath+ let result = stagedModify(appPath: appPath, appName: finding.appName) { stagedPath in+ var freedBytes: Int64 = 0+ for binary in binaries {+ freedBytes += try self.thinBinary(binary, appPath: appPath, stagedPath: stagedPath)+ }+ return freedBytes+ }++ if case .success(let freed) = result {+ Logger.shared.log("Thinned \(finding.appName): freed \(freed) bytes across \(binaries.count) binaries", level: .info)+ }+ return result+ }++ /// Removes one localization folder from an app bundle through the same+ /// staged clone / re-sign / verify / swap flow as `thin`, so the+ /// bundle's signature seal stays valid after the folder is gone.+ /// `lprojPath` must sit inside `appPath`; the caller is responsible for+ /// validating the .lproj shape and keep-set.+ func removeLproj(at lprojPath: String, fromAppAt appPath: String) async -> Result<Void, Error> {+ let app = (appPath as NSString).standardizingPath+ let lproj = (lprojPath as NSString).standardizingPath+ guard lproj.hasPrefix(app + "/") else {+ return .failure(ThinningError.swapFailed(lprojPath, "localization is outside the app bundle"))+ }++ let appName = ((app as NSString).lastPathComponent as NSString).deletingPathExtension+ let result = stagedModify(appPath: app, appName: appName) { stagedPath in+ let stagedLproj = stagedPath + String(lproj.dropFirst(app.count))+ do {+ try self.fileManager.removeItem(atPath: stagedLproj)+ } catch {+ throw ThinningError.swapFailed(lprojPath, error.localizedDescription)+ }+ return 0+ }+ return result.map { _ in () }+ }++ // MARK: - Staged modification++ /// Clones the bundle, runs `modify` against the clone, re-signs and+ /// verifies the clone, strips quarantine, then atomically swaps it over+ /// the original. Every failure path discards the clone and leaves the+ /// original bundle byte-identical — there is deliberately no in-place+ /// rollback and no re-sign of the original, ever.+ private func stagedModify(+ appPath: String,+ appName: String,+ modify: (String) throws -> Int64+ ) -> Result<Int64, Error> {+ if hasRestrictedEntitlements(appPath) {+ return .failure(ThinningError.restrictedEntitlements(appName))+ }++ let parentDir = (appPath as NSString).deletingLastPathComponent+ let bundleName = (appPath as NSString).lastPathComponent+ guard fileManager.isWritableFile(atPath: appPath),+ fileManager.isWritableFile(atPath: parentDir) else {+ return .failure(ThinningError.needsAdmin(appPath))+ }++ // Hidden sibling so the rename into place stays on the same volume+ // (atomic) and Finder never shows the work-in-progress copy.+ let stagingPath = (parentDir as NSString)+ .appendingPathComponent(".\(bundleName).puremac-staging-\(UUID().uuidString)")+ do {+ try fileManager.copyItem(atPath: appPath, toPath: stagingPath)+ } catch {+ try? fileManager.removeItem(atPath: stagingPath)+ return .failure(ThinningError.swapFailed(appPath, "could not stage a working copy: \(error.localizedDescription)"))+ }++ let freedBytes: Int64+ do {+ freedBytes = try modify(stagingPath)+ } catch {+ try? fileManager.removeItem(atPath: stagingPath)+ return .failure(error)+ }++ // Ad-hoc deep re-sign of the staged copy. --preserve-metadata keeps+ // entitlements/flags/identifier so sandboxed and hardened apps keep+ // behaving; "requirements" is deliberately NOT preserved — the old+ // designated requirement names the original Developer ID authority,+ // which an ad-hoc identity can never satisfy.+ let sign = runProcess("/usr/bin/codesign", [+ "--force", "--deep", "--sign", "-",+ "--preserve-metadata=entitlements,flags,identifier",+ stagingPath,+ ])+ guard sign.status == 0 else {+ try? fileManager.removeItem(atPath: stagingPath)+ return .failure(ThinningError.codesignFailed(appPath, sign.stderr))+ }++ let verify = runProcess("/usr/bin/codesign", ["--verify", "--deep", "--strict", stagingPath])+ guard verify.status == 0 else {+ // Common for Electron-style bundles whose nested helper apps+ // break the outer resource seal. The original is untouched, so+ // the app simply stays un-thinned.+ try? fileManager.removeItem(atPath: stagingPath)+ return .failure(ThinningError.verificationFailed(appPath, verify.stderr))+ }++ // The new signature has a new cdhash, so syspolicyd's stored+ // approval no longer applies. Strip quarantine so Gatekeeper does+ // not re-assess the non-notarized ad-hoc signature and refuse the+ // app as damaged. Exit status is ignored — the attribute is usually+ // absent already.+ let xattr = runProcess("/usr/bin/xattr", ["-rd", "com.apple.quarantine", stagingPath])+ if xattr.status != 0 && !xattr.stderr.isEmpty {+ Logger.shared.log("Quarantine strip note for \(bundleName): \(xattr.stderr)", level: .debug)+ }++ // Swap: park the original, move the verified copy into place, then+ // delete the original. Both renames stay inside parentDir.+ let oldPath = (parentDir as NSString)+ .appendingPathComponent(".\(bundleName).puremac-old-\(UUID().uuidString)")+ do {+ try fileManager.moveItem(atPath: appPath, toPath: oldPath)+ } catch {+ try? fileManager.removeItem(atPath: stagingPath)+ return .failure(ThinningError.swapFailed(appPath, error.localizedDescription))+ }+ do {+ try fileManager.moveItem(atPath: stagingPath, toPath: appPath)+ } catch {+ // Put the original back before reporting; it was only renamed.+ try? fileManager.moveItem(atPath: oldPath, toPath: appPath)+ try? fileManager.removeItem(atPath: stagingPath)+ return .failure(ThinningError.swapFailed(appPath, error.localizedDescription))+ }++ do {+ try fileManager.removeItem(atPath: oldPath)+ } catch {+ // Root-owned contents survive a user-level delete. Undo the+ // swap — keeping both copies frees nothing and would leave a+ // hidden orphan bundle next to the app.+ Logger.shared.log("Could not delete replaced bundle at \(oldPath): \(error.localizedDescription)", level: .warning)+ do {+ try fileManager.removeItem(atPath: appPath)+ try fileManager.moveItem(atPath: oldPath, toPath: appPath)+ } catch {+ Logger.shared.log("Could not undo bundle swap for \(appPath); original remains at \(oldPath): \(error.localizedDescription)", level: .error)+ return .failure(ThinningError.swapFailed(appPath, "original bundle left at \(oldPath)"))+ }+ return .failure(ThinningError.needsAdmin(appPath))+ }++ return .success(freedBytes)+ }++ /// Runs lipo for one fat binary against its counterpart inside the+ /// staged copy. Returns the bytes freed for that file.+ private func thinBinary(_ binary: FatBinary, appPath: String, stagedPath: String) throws -> Int64 {+ let binaryPath = (binary.path as NSString).standardizingPath+ guard binaryPath.hasPrefix(appPath + "/") else {+ throw ThinningError.lipoFailed(binary.path, "binary is outside the app bundle")+ }+ let stagedBinary = stagedPath + String(binaryPath.dropFirst(appPath.count))++ let sizeBefore = fileSize(at: stagedBinary)+ let tmpPath = stagedBinary + ".thin"+ var args = [stagedBinary]+ for arch in binary.removableArchs {+ args += ["-remove", arch]+ }+ args += ["-output", tmpPath]++ let lipo = runProcess("/usr/bin/lipo", args)+ guard lipo.status == 0 else {+ try? fileManager.removeItem(atPath: tmpPath)+ throw ThinningError.lipoFailed(binary.path, lipo.stderr)+ }++ // lipo writes the output with default umask permissions; carry the+ // original mode over so executables stay executable.+ if let attrs = try? fileManager.attributesOfItem(atPath: stagedBinary),+ let mode = attrs[.posixPermissions] {+ try? fileManager.setAttributes([.posixPermissions: mode], ofItemAtPath: tmpPath)+ }++ do {+ try fileManager.removeItem(atPath: stagedBinary)+ try fileManager.moveItem(atPath: tmpPath, toPath: stagedBinary)+ } catch {+ try? fileManager.removeItem(atPath: tmpPath)+ throw ThinningError.swapFailed(binary.path, error.localizedDescription)+ }++ return sizeBefore - fileSize(at: stagedBinary)+ }++ // MARK: - Helpers++ /// True when the app's main executable claims restricted entitlements+ /// (com.apple.developer.*, com.apple.application-identifier). macOS+ /// only honors those when backed by a provisioning profile and an+ /// Apple-issued certificate; preserved into an ad-hoc signature they+ /// get the process killed at spawn, and `codesign --verify` cannot+ /// detect that, so such apps are refused up front.+ private func hasRestrictedEntitlements(_ appPath: String) -> Bool {+ let result = runProcess("/usr/bin/codesign", ["-d", "--entitlements", "-", "--xml", appPath])+ // Unsigned bundle: nothing to preserve, nothing restricted.+ guard result.status == 0 else { return false }+ return result.stdout.contains("com.apple.developer.")+ || result.stdout.contains("com.apple.application-identifier")+ }++ private func fileSize(at path: String) -> Int64 {+ (try? fileManager.attributesOfItem(atPath: path)[.size] as? Int64).flatMap { $0 } ?? 0+ }++ private func runProcess(_ executable: String, _ args: [String]) -> (status: Int32, stdout: String, stderr: String) {+ let task = Process()+ task.executableURL = URL(fileURLWithPath: executable)+ task.arguments = args+ let outPipe = Pipe()+ task.standardOutput = outPipe+ let errPipe = Pipe()+ task.standardError = errPipe+ do {+ try task.run()+ } catch {+ return (-1, "", error.localizedDescription)+ }+ // Drain both pipes before waiting so a chatty child can't dead-lock+ // on a full pipe buffer.+ let outData = outPipe.fileHandleForReading.readDataToEndOfFile()+ let errData = errPipe.fileHandleForReading.readDataToEndOfFile()+ task.waitUntilExit()+ let stdout = String(data: outData, encoding: .utf8) ?? ""+ let stderr = String(data: errData, encoding: .utf8)?+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ return (task.terminationStatus, stdout, stderr)+ }+}diff --git a/PureMac/Services/CleaningEngine.swift b/PureMac/Services/CleaningEngine.swiftindex 5dc3c1b..18b46b1 100644--- a/PureMac/Services/CleaningEngine.swift+++ b/PureMac/Services/CleaningEngine.swift@@ -2,6 +2,7 @@ import Foundationactor CleaningEngine {private let fileManager = FileManager.default+ private let binaryThinner = BinaryThinner()struct CleaningResult {var freedSpace: Int64 = 0@@ -12,6 +13,12 @@ actor CleaningEngine {// EPERM. These are root-owned and need an admin-privileged second// pass via cleanWithAdminPrivileges(items:).var requiresAdmin: [CleanableItem] = []+ // Paths skipped because they are SIP-protected or immutable (see+ // FileProtection). Deleting these fails even as root, so they are+ // recorded here — not in errors — and must never trigger the+ // "Couldn't clean everything" alert.+ var protectedPaths: Set<String> = []+ var skippedProtected: Int { protectedPaths.count }}// MARK: - Public API@@ -36,6 +43,54 @@ actor CleaningEngine {continue}+ if item.category == .universalBinaries {+ // Thinning is a lipo rewrite plus re-sign, not a file unlink,+ // so it bypasses the delete path entirely. The item path is+ // the app bundle; the per-binary work list is re-derived here+ // so a stale scan can't strip slices that no longer exist.+ let thinOutcome = await thinUniversalBinaryItem(item)+ result.freedSpace += thinOutcome.freed+ if thinOutcome.cleaned {+ result.itemsCleaned += 1+ result.cleanedPaths.insert(item.path)+ }+ if let error = thinOutcome.error {+ result.errors.append(error)+ }+ continue+ }++ if item.category == .languageFiles {+ // Localizations are sealed into the bundle's CodeResources; a+ // plain unlink would break the app's code signature, so the+ // folder is removed through BinaryThinner's staged re-sign+ // flow instead of the delete path.+ let lprojOutcome = await removeLanguageFileItem(item)+ result.freedSpace += lprojOutcome.freed+ if lprojOutcome.cleaned {+ result.itemsCleaned += 1+ result.cleanedPaths.insert(item.path)+ }+ if let error = lprojOutcome.error {+ result.errors.append(error)+ }+ continue+ }++ if item.category == .dockerCache && item.path.isEmpty {+ // The virtual "Docker prune" entry (empty path, like+ // purgeableSpace) reclaims space inside the Docker/OrbStack VM+ // via `docker system prune -f` — there is no file to unlink.+ let pruneOutcome = await pruneDockerSystem()+ result.freedSpace += pruneOutcome.freed+ if pruneOutcome.freed > 0 { result.itemsCleaned += 1 }+ result.cleanedPaths.insert(item.path)+ if let error = pruneOutcome.error {+ result.errors.append(error)+ }+ continue+ }+do {let itemURL = URL(fileURLWithPath: item.path)guard fileManager.fileExists(atPath: item.path) else { continue }@@ -54,6 +109,8 @@ actor CleaningEngine {if item.category == .largeFiles {return isExplicitSingleFileDeletable(resolvedPath: resolved)}+ // languageFiles never reaches here — it is handled above+ // via the staged re-sign flow, not the delete path.return isSafeToDelete(resolvedPath: resolved)}()guard pathAccepted else {@@ -87,6 +144,14 @@ actor CleaningEngine {(nsError.domain == NSPOSIXErrorDomain &&(nsError.code == Int(EACCES) || nsError.code == Int(EPERM)))if isPermissionDenied {+ // SIP-protected/immutable entries fail even as root, so+ // escalating them just wastes an auth prompt and produces+ // a bogus "survived admin removal" error. Record and move on.+ if FileProtection.isProtectedFromDeletion(path: item.path) {+ result.protectedPaths.insert(item.path)+ Logger.shared.log("Skipping SIP-protected path: \(item.path)", level: .info)+ continue+ }// Defer to the admin pass — these are typically root-owned// system caches that the user-level process can't unlink.result.requiresAdmin.append(item)@@ -128,6 +193,10 @@ actor CleaningEngine {if item.category == .largeFiles {return isExplicitSingleFileDeletable(resolvedPath: resolved)}+ // languageFiles is deliberately absent: an admin rm -rf of an+ // .lproj would break the bundle's signature seal with no+ // re-sign, so those items never escalate — they only go+ // through the staged BinaryThinner flow in cleanItems.return isSafeToDelete(resolvedPath: resolved) || isSafeUninstallEscalationPath(resolved)}()if !accepted {@@ -144,6 +213,20 @@ actor CleaningEngine {let staged = validated.map(\.resolved).joined(separator: "\u{0}")guard let payload = staged.data(using: .utf8) else { return result }+ // Live daemon logs (e.g. /private/var/log/wifi.log) are recreated by+ // their writer the instant root rm unlinks them. A bare re-stat then+ // misreads the fresh file as "survived admin removal" and raises a+ // bogus "Couldn't clean everything" alert. Capture each path's inode+ // before the delete so the survivor check can tell a recreated file+ // from an untouched one.+ var preDeleteInodes: [String: UInt64] = [:]+ for (_, resolved) in validated {+ if let attrs = try? fileManager.attributesOfItem(atPath: resolved),+ let inode = (attrs[.systemFileNumber] as? NSNumber)?.uint64Value {+ preDeleteInodes[resolved] = inode+ }+ }+let tempFile = FileManager.default.temporaryDirectory.appendingPathComponent("puremac-rm-\(UUID().uuidString)")do {@@ -189,16 +272,109 @@ actor CleaningEngine {result.cleanedPaths.insert(item.path)result.itemsCleaned += 1result.freedSpace += item.size+ } else if FileProtection.isProtectedFromDeletion(path: resolved) {+ // SIP-protected survivors are expected — root rm can't touch+ // them either. Record quietly instead of raising an error.+ result.protectedPaths.insert(item.path)+ Logger.shared.log("Admin pass skipped SIP-protected path: \(item.path)", level: .info)+ } else if let preInode = preDeleteInodes[resolved],+ let nowInode = ((try? fileManager.attributesOfItem(atPath: resolved))?[.systemFileNumber] as? NSNumber)?.uint64Value,+ nowInode != preInode {+ // Different inode: the original WAS deleted and the owning+ // daemon immediately recreated the file. The old bytes are+ // gone, so count it as cleaned rather than a survivor.+ result.cleanedPaths.insert(item.path)+ result.itemsCleaned += 1+ result.freedSpace += item.size+ Logger.shared.log("Deleted and recreated by its daemon (live log): \(item.path)", level: .info)} else {let detail = "\(item.name) at \(item.path) survived admin removal"result.errors.append(detail)Logger.shared.log("Admin pass survivor: \(detail)", level: .error)}}- Logger.shared.log("Admin pass complete: \(result.itemsCleaned) deleted, \(result.errors.count) survived", level: .info)+ Logger.shared.log("Admin pass complete: \(result.itemsCleaned) deleted, \(result.errors.count) survived, \(result.skippedProtected) protected", level: .info)return result}+ // MARK: - Docker++ /// Runs `docker system prune -f` (no -a: tagged images and running+ /// containers survive) and reports the bytes Docker says it reclaimed.+ /// This is the clean action behind the virtual "Docker prune" item —+ /// with a VM-based runtime (Docker Desktop, OrbStack) the junk lives+ /// inside the VM disk, unreachable by any file unlink from the host.+ /// Returns a friendly error when no CLI is installed or the daemon is+ /// not running — common with OrbStack, which only runs on demand.+ func pruneDockerSystem() async -> (freed: Int64, error: String?) {+ let dockerBinPaths = ["/usr/local/bin/docker", "/opt/homebrew/bin/docker"]+ guard let dockerBin = dockerBinPaths.first(where: { fileManager.isExecutableFile(atPath: $0) }) else {+ return (0, "Docker CLI not found — install Docker Desktop or OrbStack")+ }++ let task = Process()+ task.executableURL = URL(fileURLWithPath: dockerBin)+ task.arguments = ["system", "prune", "-f"]+ let stdoutPipe = Pipe()+ let stderrPipe = Pipe()+ task.standardOutput = stdoutPipe+ task.standardError = stderrPipe+ do {+ try task.run()+ } catch {+ Logger.shared.log("docker system prune failed to launch: \(error.localizedDescription)", level: .error)+ return (0, "Couldn't run docker system prune: \(error.localizedDescription)")+ }+ // Drain both pipes BEFORE waiting: prune lists every deleted object+ // and can overflow the 64 KB pipe buffer, deadlocking waitUntilExit.+ let outData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()+ let errData = stderrPipe.fileHandleForReading.readDataToEndOfFile()+ task.waitUntilExit()++ guard task.terminationStatus == 0 else {+ let stderrText = String(data: errData, encoding: .utf8) ?? ""+ if stderrText.contains("Cannot connect") || stderrText.contains("dial unix")+ || stderrText.contains("daemon") {+ return (0, "Docker isn't running — start Docker Desktop or OrbStack, then clean again")+ }+ Logger.shared.log("docker system prune exited \(task.terminationStatus): \(stderrText)", level: .error)+ return (0, "docker system prune failed (exit \(task.terminationStatus))")+ }++ // Final line reads "Total reclaimed space: 1.234GB" ("0B" when idle).+ let output = String(data: outData, encoding: .utf8) ?? ""+ if let line = output.split(separator: "\n").last(where: { $0.contains("Total reclaimed space:") }),+ let raw = line.split(separator: ":").last?.trimmingCharacters(in: .whitespaces),+ let bytes = parseDockerBytes(raw) {+ Logger.shared.log("docker system prune reclaimed \(bytes) bytes", level: .info)+ return (bytes, nil)+ }+ return (0, nil)+ }++ /// Parse Docker's compact size format ("1.23GB", "456MB", "789kB", "0B").+ private func parseDockerBytes(_ s: String) -> Int64? {+ let trimmed = s.trimmingCharacters(in: .whitespaces)+ guard !trimmed.isEmpty else { return nil }+ let units: [(String, Double)] = [+ ("TB", 1_000_000_000_000),+ ("GB", 1_000_000_000),+ ("MB", 1_000_000),+ ("kB", 1_000),+ ("KB", 1_000),+ ("B", 1),+ ]+ for (suffix, multiplier) in units {+ if trimmed.hasSuffix(suffix) {+ let numberPart = String(trimmed.dropLast(suffix.count))+ if let value = Double(numberPart) {+ return Int64(value * multiplier)+ }+ }+ }+ return nil+ }+// MARK: - Purgeable Spacefunc purgePurgeableSpace() async -> Int64 {@@ -272,10 +448,24 @@ actor CleaningEngine {"\(home)/Library/Developer/Xcode/DerivedData","\(home)/Library/Developer/Xcode/Archives","\(home)/Library/Developer/CoreSimulator/Caches",+ "\(home)/Library/Developer/Xcode/iOS DeviceSupport",+ "\(home)/Library/Developer/Xcode/watchOS DeviceSupport",+ "\(home)/Library/Developer/Xcode/tvOS DeviceSupport",+ "\(home)/Library/Developer/XCTestDevices",+ "\(home)/Library/Developer/Xcode/UserData/Previews",+ "\(home)/Library/org.swift.swiftpm","\(home)/.Trash","\(home)/.npm","\(home)/.cache","\(home)/Library/Containers/com.docker.docker",+ // Docker/OrbStack cache + log roots surfaced by scanDockerCache.+ // Without these the items scan fine but every delete is refused+ // as "unsafe path" — the category looked broken. Narrow roots+ // only; ~/.docker itself holds config.json and TLS certs, and+ // ~/.orbstack/data is the VM disk, so neither is allow-listed.+ "\(home)/.docker/cli-plugins/.cache",+ "\(home)/.docker/buildx/cache",+ "\(home)/.orbstack/log","/Library/Caches","/Library/Logs","/private/var/log",@@ -299,6 +489,127 @@ actor CleaningEngine {}}+ /// A removable localization folder inside an installed app bundle:+ /// /Applications/.../<App>.app/Contents/Resources/<lang>.lproj (or the+ /// same shape under ~/Applications), where <lang> is neither in the+ /// scanner's keep-set (user-preferred languages plus en/English/Base)+ /// nor the bundle's development region. Everything else — including any+ /// other path inside an app bundle — stays blocked.+ private func isRemovableLprojPath(_ path: String) -> Bool {+ let normalized = (path as NSString).standardizingPath+ guard (normalized as NSString).pathExtension.lowercased() == "lproj" else { return false }++ let home = fileManager.homeDirectoryForCurrentUser.path+ guard isInside(normalized, root: "/Applications") || isInside(normalized, root: "\(home)/Applications") else {+ return false+ }++ // Must sit exactly at <bundle>.app/Contents/Resources/<lang>.lproj.+ let resources = (normalized as NSString).deletingLastPathComponent+ let contents = (resources as NSString).deletingLastPathComponent+ let bundle = (contents as NSString).deletingLastPathComponent+ guard (resources as NSString).lastPathComponent == "Resources",+ (contents as NSString).lastPathComponent == "Contents",+ (bundle as NSString).lastPathComponent.lowercased().hasSuffix(".app") else {+ return false+ }++ let language = ((normalized as NSString).lastPathComponent as NSString)+ .deletingPathExtension+ .lowercased()+ .replacingOccurrences(of: "_", with: "-")+ // Same keep-set as the scanner (user-preferred languages plus the+ // en/English/Base fallbacks), so a stale or replayed item list can+ // never delete a localization the user's current settings depend on.+ if LanguageFilesScanner().keepLanguages.contains(language) { return false }+ // The bundle's development region is its last-resort fallback+ // localization — often the only complete one. Deleting it leaves+ // NSLocalizedString returning raw keys or breaks nib loading.+ if let plist = NSDictionary(contentsOfFile: bundle + "/Contents/Info.plist"),+ let region = plist["CFBundleDevelopmentRegion"] as? String {+ let normalizedRegion = region.lowercased().replacingOccurrences(of: "_", with: "-")+ if language == normalizedRegion { return false }+ if let base = normalizedRegion.split(separator: "-").first, language == String(base) {+ return false+ }+ }+ return true+ }++ /// Runs BinaryThinner for one .universalBinaries item (path = app+ /// bundle). Re-scans the bundle first so the lipo work list reflects the+ /// bundle's current state, not the possibly stale scan result.+ private func thinUniversalBinaryItem(_ item: CleanableItem) async -> (freed: Int64, cleaned: Bool, error: String?) {+ let resolved = URL(fileURLWithPath: item.path).resolvingSymlinksInPath().path+ guard isAppBundlePath((resolved as NSString).standardizingPath, rootedAt: "/Applications")+ || isAppBundlePath((resolved as NSString).standardizingPath, rootedAt: "\(fileManager.homeDirectoryForCurrentUser.path)/Applications") else {+ let msg = "Skipped unsafe path for thinning: \(item.path) -> \(resolved)"+ Logger.shared.log(msg, level: .warning)+ return (0, false, msg)+ }++ guard let finding = UniversalBinaryScanner().finding(forAppAt: resolved) else {+ // Nothing fat left — the app was thinned or replaced since the+ // scan. Count it handled so it doesn't surface as a failure.+ Logger.shared.log("No removable slices left in \(item.path); marking handled", level: .info)+ return (0, true, nil)+ }++ switch await binaryThinner.thin(finding) {+ case .success(let freed):+ return (freed, true, nil)+ case .failure(let error):+ if case BinaryThinner.ThinningError.needsAdmin = error {+ let msg = "\(item.name): needs administrator access to thin; skipped"+ Logger.shared.log(msg, level: .warning)+ return (0, false, msg)+ }+ let msg = "Couldn't thin \(item.name): \(error.localizedDescription)"+ Logger.shared.log(msg, level: .error)+ return (0, false, msg)+ }+ }++ /// Routes one .languageFiles item (path = .lproj folder) through+ /// BinaryThinner's staged clone / re-sign / verify / swap flow. The+ /// folder is validated against the same .lproj predicate as before,+ /// then removed from a staged copy of the bundle so the signature seal+ /// stays consistent with the bundle's contents.+ private func removeLanguageFileItem(_ item: CleanableItem) async -> (freed: Int64, cleaned: Bool, error: String?) {+ let resolved = URL(fileURLWithPath: item.path).resolvingSymlinksInPath().path+ let normalized = (resolved as NSString).standardizingPath+ guard isRemovableLprojPath(normalized) else {+ let msg = "Skipped symlink or unsafe path: \(item.path) -> \(resolved)"+ Logger.shared.log(msg, level: .warning)+ return (0, false, msg)+ }++ guard fileManager.fileExists(atPath: normalized) else {+ // Already gone (app updated or reinstalled since the scan) —+ // count it handled so it doesn't surface as a failure.+ return (0, true, nil)+ }++ // <lang>.lproj -> Resources -> Contents -> bundle; the shape was+ // just validated by isRemovableLprojPath.+ let bundle = (((normalized as NSString).deletingLastPathComponent as NSString)+ .deletingLastPathComponent as NSString).deletingLastPathComponent++ switch await binaryThinner.removeLproj(at: normalized, fromAppAt: bundle) {+ case .success:+ return (item.size, true, nil)+ case .failure(let error):+ if case BinaryThinner.ThinningError.needsAdmin = error {+ let msg = "\(item.name): needs administrator access to modify the app; skipped"+ Logger.shared.log(msg, level: .warning)+ return (0, false, msg)+ }+ let msg = "Couldn't remove localization \(item.name): \(error.localizedDescription)"+ Logger.shared.log(msg, level: .error)+ return (0, false, msg)+ }+ }+/// Allows the app uninstaller to escalate only the protected roots it owns:/// app bundles, package receipts, and launch plists. This intentionally/// stays narrower than the normal cleaner allow-list.diff --git a/PureMac/Services/ScanEngine.swift b/PureMac/Services/ScanEngine.swiftindex 882cbd6..ea0c1c5 100644--- a/PureMac/Services/ScanEngine.swift+++ b/PureMac/Services/ScanEngine.swift@@ -67,6 +67,10 @@ actor ScanEngine {return scanNodeCache()case .dockerCache:return scanDockerCache()+ case .universalBinaries:+ return scanUniversalBinaries()+ case .languageFiles:+ return scanLanguageFiles()}}@@ -165,6 +169,55 @@ actor ScanEngine {}}+ // Sandboxed apps keep their caches inside per-app containers, not+ // ~/Library/Caches — on modern macOS this is where most of the+ // "user cache" gigabytes actually live. One item per container,+ // skipping near-empty caches (< 1 MB).+ let containerRoots = [+ "\(home)/Library/Containers",+ "\(home)/Library/Group Containers",+ ]+ for root in containerRoots {+ guard let containers = try? fileManager.contentsOfDirectory(atPath: root) else { continue }+ // App containers nest caches under Data/; group containers don't.+ let cacheSubpath = root.hasSuffix("Group Containers")+ ? "Library/Caches"+ : "Data/Library/Caches"+ for container in containers {+ let cachePath = (root as NSString)+ .appendingPathComponent(container)+ .appending("/" + cacheSubpath)+ // Same symlink defense as scanDirectory: an app at this UID+ // could plant Data or Data/Library as a symlink into an+ // allow-listed root and have the target sized here and later+ // deleted. Only accept paths that resolve to themselves.+ let resolvedCachePath = URL(fileURLWithPath: cachePath).resolvingSymlinksInPath().path+ guard normalizePath(resolvedCachePath) == normalizePath(cachePath) else { continue }+ if let item = makeCleanupItem(+ name: "\(container) (sandbox cache)",+ path: cachePath,+ category: .userCache,+ minimumSize: 1024 * 1024+ ) {+ items.append(item)+ }+ }+ }++ // Per-app HTTP cookie/response storage — one entry per app, same+ // non-recursive shape as the top-level Caches pass above. CFNetwork+ // keeps each native app's cookies and HSTS state here, i.e. live+ // login sessions rather than regenerable cache, so these entries+ // start unselected and the user opts in per app.+ let httpStorages = scanDirectory(+ path: "\(home)/Library/HTTPStorages",+ category: .userCache,+ recursive: false,+ maxDepth: 1,+ isSelected: false+ )+ items.append(contentsOf: httpStorages)+let uniqueItems = deduplicatedItems(items)let totalSize = uniqueItems.reduce(0) { $0 + $1.size }return CategoryResult(category: .userCache, items: uniqueItems, totalSize: totalSize)@@ -388,6 +441,18 @@ actor ScanEngine {"\(home)/Library/Developer/Xcode/Archives","\(home)/Library/Developer/CoreSimulator/Caches","\(home)/Library/Caches/com.apple.dt.Xcode",+ // Per-OS symbol caches, regenerated on next device connect.+ // These alone are often tens of GB on active dev machines.+ "\(home)/Library/Developer/Xcode/iOS DeviceSupport",+ "\(home)/Library/Developer/Xcode/watchOS DeviceSupport",+ "\(home)/Library/Developer/Xcode/tvOS DeviceSupport",+ // Simulator clones spun up by xcodebuild test runs+ "\(home)/Library/Developer/XCTestDevices",+ // SwiftUI preview build products+ "\(home)/Library/Developer/Xcode/UserData/Previews",+ // Swift Package Manager download + build caches+ "\(home)/Library/Caches/org.swift.swiftpm",+ "\(home)/Library/org.swift.swiftpm",]for path in xcodePaths {@@ -632,6 +697,14 @@ actor ScanEngine {"\(home)/.docker/cli-plugins/.cache",// Buildx / containerd inline cache"\(home)/.docker/buildx/cache",+ // OrbStack (Docker Desktop alternative) keeps its daemon logs and+ // caches outside ~/Library/Containers. The VM data disk itself+ // (~/.orbstack/data) is intentionally NOT listed — image/container+ // space inside the VM is only reclaimable via `docker system+ // prune`, surfaced as the virtual entry below.+ "\(home)/.orbstack/log",+ "\(home)/Library/Caches/dev.kdrag0n.MacVirt",+ "\(home)/Library/Logs/OrbStack",]for path in dockerDataDirs {@@ -648,17 +721,22 @@ actor ScanEngine {))}- // If the `docker` CLI is available, surface reclaimable space- // reported by `docker system df` as a single virtual entry.- // We don't try to delete it directly — the user runs- // `docker system prune` themselves, which is the safe path.- // We just show how much they can recover.+ // If the `docker` CLI is available and the daemon answers, surface+ // reclaimable space reported by `docker system df` as a single+ // virtual entry. Cleaning it runs `docker system prune -f` (see+ // CleaningEngine.pruneDockerSystem) — stopped containers, dangling+ // images, unused networks, and build cache; running containers and+ // tagged images are untouched. The empty path mirrors the purgeable-+ // space convention: this is an action, not a file unlink, so the UI+ // must not offer reveal-in-Finder or attempt removeItem on it.+ // Works for both Docker Desktop and OrbStack (both ship a docker CLI+ // at these locations).let dockerBinPaths = ["/usr/local/bin/docker", "/opt/homebrew/bin/docker"]for dockerBin in dockerBinPaths where fileManager.fileExists(atPath: dockerBin) {if let reclaimable = reclaimableDockerSpace(dockerBin: dockerBin), reclaimable > 0 {items.append(CleanableItem(- name: "Reclaimable (run `docker system prune -af`)",- path: dockerBin,+ name: "Docker prune (stopped containers, dangling images, build cache)",+ path: "",size: reclaimable,category: .dockerCache,isSelected: false,@@ -672,6 +750,56 @@ actor ScanEngine {return CategoryResult(category: .dockerCache, items: items, totalSize: totalSize)}+ private func scanUniversalBinaries() -> CategoryResult {+ var items: [CleanableItem] = []++ // One item per app bundle. The item path is the BUNDLE path (not the+ // executable) so reveal-in-Finder works; CleaningEngine re-derives+ // the per-binary lipo work list from that path via BinaryThinner.+ // Every finding starts unselected: thinning replaces the app's+ // Developer ID signature with an ad-hoc one (auto-update and+ // keychain impact), so it is per-app opt-in, never part of a+ // default Clean All.+ let findings = UniversalBinaryScanner().scan()+ for finding in findings {+ report(finding.appPath)+ items.append(CleanableItem(+ name: "\(finding.appName) (\(finding.removableArchs.joined(separator: ", ")))",+ path: finding.appPath,+ size: finding.reclaimableBytes,+ category: .universalBinaries,+ isSelected: false,+ lastModified: fileModDate(path: finding.appPath)+ ))+ }++ let totalSize = items.reduce(0) { $0 + $1.size }+ return CategoryResult(category: .universalBinaries, items: items, totalSize: totalSize)+ }++ private func scanLanguageFiles() -> CategoryResult {+ // One item per removable .lproj so the user can keep individual+ // languages. Every finding starts unselected: removal re-signs the+ // bundle ad-hoc (see BinaryThinner), so stripping localizations is+ // per-app opt-in, never part of a default Clean All.+ let scanner = LanguageFilesScanner()+ let findings = scanner.scan(applicationDirs: ["/Applications", "\(home)/Applications"])+ let items = scanner.flatten(findings).map { entry in+ report(entry.path)+ return CleanableItem(+ name: entry.name,+ path: entry.path,+ size: entry.size,+ category: .languageFiles,+ isSelected: false,+ lastModified: nil+ )+ }++ let totalSize = items.reduce(0) { $0 + $1.size }+ return CategoryResult(category: .languageFiles, items: items, totalSize: totalSize)+ }+/// Sum the reclaimable bytes reported by `docker system df --format json`./// Returns nil when Docker isn't running or the command fails — callers/// should treat that as "no reclaimable info available", not as an error.@@ -732,6 +860,7 @@ actor ScanEngine {category: CleaningCategory,recursive: Bool,maxDepth: Int,+ isSelected: Bool = true,excluding excludedPaths: Set<String> = []) -> [CleanableItem] {var items: [CleanableItem] = []@@ -742,6 +871,7 @@ actor ScanEngine {do {let contents = try fileManager.contentsOfDirectory(atPath: path)for item in contents {+ if Task.isCancelled { break }let fullPath = (path as NSString).appendingPathComponent(item)report(fullPath)if excludedPaths.contains(normalizePath(fullPath)) {@@ -758,6 +888,13 @@ actor ScanEngine {continue}+ // Skip SIP-protected/immutable entries — they fail even+ // admin rm and only produce "Couldn't clean everything"+ // alerts (e.g. /private/var/log/wifi.log).+ if FileProtection.isProtectedFromDeletion(path: fullPath) {+ continue+ }+if isDir.boolValue {let size = directorySize(path: fullPath)if size > 1024 { // Skip tiny entries@@ -766,7 +903,7 @@ actor ScanEngine {path: fullPath,size: size,category: category,- isSelected: true,+ isSelected: isSelected,lastModified: fileModDate(path: fullPath)))}@@ -778,7 +915,7 @@ actor ScanEngine {path: fullPath,size: size,category: category,- isSelected: true,+ isSelected: isSelected,lastModified: attrs[.modificationDate] as? Date))}@@ -851,22 +988,31 @@ actor ScanEngine {private func directorySize(path: String) -> Int64 {var totalSize: Int64 = 0+ // errorHandler returns true so unreadable entries are skipped+ // instead of aborting the walk partway through the tree.guard let enumerator = fileManager.enumerator(at: URL(fileURLWithPath: path),- includingPropertiesForKeys: [.fileSizeKey, .isRegularFileKey],- options: [.skipsHiddenFiles]+ includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .fileSizeKey, .isRegularFileKey],+ options: [.skipsHiddenFiles],+ errorHandler: { _, _ in true }) else { return 0 }- var count = 0+ // No entry cap. A 10k cap was here previously and made huge trees+ // like Xcode DerivedData (millions of files) report a fraction of+ // their real size. report() is throttled, so display stays cheap.+ // A DerivedData/DeviceSupport walk can hold this loop for minutes,+ // so honor task cancellation to let an aborted scan stop promptly.for case let fileURL as URL in enumerator {- count += 1- if count > 10000 { break } // Safety limit for very large directories-+ if Task.isCancelled { break }report(fileURL.path)- guard let values = try? fileURL.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey]),- let isFile = values.isRegularFile, isFile,- let size = values.fileSize else { continue }- totalSize += Int64(size)+ guard let values = try? fileURL.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileSizeKey, .isRegularFileKey]),+ let isFile = values.isRegularFile, isFile else { continue }+ // Allocated size counts actual on-disk blocks (accurate for+ // sparse/cloned files); fall back to logical size when the+ // volume doesn't report it.+ if let size = values.totalFileAllocatedSize ?? values.fileSize {+ totalSize += Int64(size)+ }}return totalSizediff --git a/PureMac/ViewModels/AppState.swift b/PureMac/ViewModels/AppState.swiftindex cb62eac..c8544ca 100644--- a/PureMac/ViewModels/AppState.swift+++ b/PureMac/ViewModels/AppState.swift@@ -750,6 +750,7 @@ final class AppState: ObservableObject {result.itemsCleaned += admin.itemsCleanedresult.freedSpace += admin.freedSpaceresult.errors.append(contentsOf: admin.errors)+ result.protectedPaths.formUnion(admin.protectedPaths)}totalFreedSpace = result.freedSpace@@ -777,7 +778,7 @@ final class AppState: ObservableObject {// Route survivors back through the same outcome path the original// cleanup uses. Without this, an FDA revocation between grant and// retry would silently drop errors instead of re-popping the sheet.- let survivors = items.filter { !result.cleanedPaths.contains($0.path) }+ let survivors = survivingItems(from: items, result: result)handleCleanOutcome(errors: result.errors, survivors: survivors)scanState = .cleaned@@ -883,13 +884,14 @@ final class AppState: ObservableObject {result.itemsCleaned += admin.itemsCleanedresult.freedSpace += admin.freedSpaceresult.errors.append(contentsOf: admin.errors)+ result.protectedPaths.formUnion(admin.protectedPaths)}totalFreedSpace = result.freedSpacelastCleanedDate = Date()if result.itemsCleaned > 0 { Haptics.successWithSound() }- let survivors = itemsToClean.filter { !result.cleanedPaths.contains($0.path) }+ let survivors = survivingItems(from: itemsToClean, result: result)for (cat, catResult) in categoryResults {let remaining = catResult.items.filter { !result.cleanedPaths.contains($0.path) }@@ -944,6 +946,7 @@ final class AppState: ObservableObject {cleanResult.itemsCleaned += admin.itemsCleanedcleanResult.freedSpace += admin.freedSpacecleanResult.errors.append(contentsOf: admin.errors)+ cleanResult.protectedPaths.formUnion(admin.protectedPaths)}totalFreedSpace = cleanResult.freedSpace@@ -968,7 +971,7 @@ final class AppState: ObservableObject {}totalJunkSize = categoryResults.values.reduce(0) { $0 + $1.totalSize }- let survivors = selectedItems.filter { !cleanResult.cleanedPaths.contains($0.path) }+ let survivors = survivingItems(from: selectedItems, result: cleanResult)handleCleanOutcome(errors: cleanResult.errors, survivors: survivors)scanState = .cleaned@@ -980,6 +983,20 @@ final class AppState: ObservableObject {}}+ /// Items that neither got cleaned nor were skipped as SIP-protected.+ /// Protected paths can't be removed even as root, so treating them as+ /// failures only produces a "Couldn't clean everything" alert the user+ /// can do nothing about (e.g. /private/var/log/wifi.log) — log and move on.+ private func survivingItems(from items: [CleanableItem], result: CleaningEngine.CleaningResult) -> [CleanableItem] {+ if result.skippedProtected > 0 {+ let protectedList = result.protectedPaths.sorted().joined(separator: ", ")+ Logger.shared.log("Skipped \(result.skippedProtected) macOS-protected item(s): \(protectedList)", level: .info)+ }+ return items.filter {+ !result.cleanedPaths.contains($0.path) && !result.protectedPaths.contains($0.path)+ }+ }+/// Inspect a clean batch's leftovers and either route the user into the/// PermissionSheet (FDA is the most likely cause) or surface a richer/// error alert that lists actual paths instead of "Check the log".@@ -992,14 +1009,19 @@ final class AppState: ObservableObject {}let fdaGranted = FullDiskAccessManager.shared.hasFullDiskAccess- let likelyFDA = !fdaGranted && !survivors.isEmpty+ // App-modifying survivors (thinning, localization stripping) fail on+ // root-owned bundles that Full Disk Access cannot make writable, so+ // they must not steer the user into a Grant Access loop that can+ // never succeed. Only junk-file survivors count toward that hint.+ let fdaFixableSurvivors = survivors.filter { !CleaningCategory.appModifying.contains($0.category) }+ let likelyFDA = !fdaGranted && !fdaFixableSurvivors.isEmptycleanErrorIsFDAFixable = likelyFDApendingPermissionRetryItems = survivorsif likelyFDA {cleanError = String(format: String(localized: "%lld item(s) need Full Disk Access to remove. Tap Grant Access to fix in one step."),- Int64(survivors.count)+ Int64(fdaFixableSurvivors.count))} else if !survivors.isEmpty {let preview = survivors.prefix(2).map { ($0.path as NSString).lastPathComponent }.joined(separator: ", ")@@ -1036,7 +1058,11 @@ final class AppState: ObservableObject {// MARK: - Scheduled Scanprivate func runScheduledScan() async {+ // App-modifying categories (see CleaningCategory.appModifying) never+ // run unattended — a scheduled autoClean must not re-sign or strip+ // installed apps behind the user's back.let categories = scheduler.config.categoriesToScan+ .filter { !CleaningCategory.appModifying.contains($0) }var totalFound: Int64 = 0clearSelectionState()categoryResults = [:]diff --git a/PureMac/ar.lproj/Localizable.strings b/PureMac/ar.lproj/Localizable.stringsindex 06f82d8..e3e95f1 100644--- a/PureMac/ar.lproj/Localizable.strings+++ b/PureMac/ar.lproj/Localizable.strings@@ -219,6 +219,8 @@"Brew Cache" = "ذاكرة Brew المؤقتة";"Node Cache" = "ذاكرة Node المؤقتة";"Docker Cache" = "ذاكرة Docker المؤقتة";+"Universal Binaries" = "الملفات الثنائية المتعددة البنى";+"Language Files" = "ملفات اللغات";/* Cleaning category descriptions */"Scan everything at once" = "فحص كل شيء دفعة واحدة";@@ -233,6 +235,8 @@"Homebrew download cache" = "ذاكرة تنزيلات Homebrew المؤقتة";"npm, yarn, and pnpm download caches" = "ذاكرات تنزيلات npm وyarn وpnpm المؤقتة";"Docker images, containers, and build cache" = "صور Docker والحاويات وذاكرة البناء المؤقتة";+"Unused CPU architecture slices in app binaries" = "شرائح بنى معالج غير مستخدمة في الملفات الثنائية للتطبيقات";+"Unused app localizations" = "ترجمات التطبيقات غير المستخدمة";/* Node Cache subcategories */"npm cache" = "ذاكرة npm المؤقتة";diff --git a/PureMac/en.lproj/Localizable.strings b/PureMac/en.lproj/Localizable.stringsindex 1e154c4..49a77b3 100644--- a/PureMac/en.lproj/Localizable.strings+++ b/PureMac/en.lproj/Localizable.strings@@ -258,6 +258,8 @@"Brew Cache" = "Brew Cache";"Node Cache" = "Node Cache";"Docker Cache" = "Docker Cache";+"Universal Binaries" = "Universal Binaries";+"Language Files" = "Language Files";/* Cleaning category descriptions */"Scan everything at once" = "Scan everything at once";@@ -272,6 +274,8 @@"Homebrew download cache" = "Homebrew download cache";"npm, yarn, and pnpm download caches" = "npm, yarn, and pnpm download caches";"Docker images, containers, and build cache" = "Docker images, containers, and build cache";+"Unused CPU architecture slices in app binaries" = "Unused CPU architecture slices in app binaries";+"Unused app localizations" = "Unused app localizations";/* Node Cache subcategories */"npm cache" = "npm cache";diff --git a/PureMac/es.lproj/Localizable.strings b/PureMac/es.lproj/Localizable.stringsindex 38d9171..8844a69 100644--- a/PureMac/es.lproj/Localizable.strings+++ b/PureMac/es.lproj/Localizable.strings@@ -219,6 +219,8 @@"Brew Cache" = "Caché de Brew";"Node Cache" = "Caché de Node";"Docker Cache" = "Caché de Docker";+"Universal Binaries" = "Binarios universales";+"Language Files" = "Archivos de idioma";/* Cleaning category descriptions */"Scan everything at once" = "Analizar todo a la vez";@@ -233,6 +235,8 @@"Homebrew download cache" = "Caché de descargas de Homebrew";"npm, yarn, and pnpm download caches" = "Cachés de descargas de npm, yarn y pnpm";"Docker images, containers, and build cache" = "Imágenes, contenedores y caché de compilación de Docker";+"Unused CPU architecture slices in app binaries" = "Arquitecturas de CPU sin usar en los binarios de las apps";+"Unused app localizations" = "Localizaciones de apps sin usar";/* Node Cache subcategories */"npm cache" = "Caché de npm";diff --git a/PureMac/ja.lproj/Localizable.strings b/PureMac/ja.lproj/Localizable.stringsindex 9540321..b06b045 100644--- a/PureMac/ja.lproj/Localizable.strings+++ b/PureMac/ja.lproj/Localizable.strings@@ -219,6 +219,8 @@"Brew Cache" = "Brewキャッシュ";"Node Cache" = "Nodeキャッシュ";"Docker Cache" = "Dockerキャッシュ";+"Universal Binaries" = "ユニバーサルバイナリ";+"Language Files" = "言語ファイル";/* Cleaning category descriptions */"Scan everything at once" = "すべてを一度にスキャン";@@ -233,6 +235,8 @@"Homebrew download cache" = "Homebrewのダウンロードキャッシュ";"npm, yarn, and pnpm download caches" = "npm、yarn、pnpm のダウンロードキャッシュ";"Docker images, containers, and build cache" = "Dockerイメージ、コンテナ、ビルドキャッシュ";+"Unused CPU architecture slices in app binaries" = "アプリバイナリ内の未使用CPUアーキテクチャコード";+"Unused app localizations" = "使用されていないアプリのローカライゼーション";/* Node Cache subcategories */"npm cache" = "npmキャッシュ";diff --git a/PureMac/pl.lproj/Localizable.strings b/PureMac/pl.lproj/Localizable.stringsindex 7c4d716..6950dcc 100644--- a/PureMac/pl.lproj/Localizable.strings+++ b/PureMac/pl.lproj/Localizable.strings@@ -258,6 +258,8 @@"Brew Cache" = "Cache Homebrew";"Node Cache" = "Cache Node";"Docker Cache" = "Cache Dockera";+"Universal Binaries" = "Uniwersalne pliki binarne";+"Language Files" = "Pliki językowe";/* Cleaning category descriptions */"Scan everything at once" = "Skanuj wszystko naraz";@@ -272,6 +274,8 @@"Homebrew download cache" = "Cache pobierania Homebrew";"npm, yarn, and pnpm download caches" = "Cache pobierania npm, yarn i pnpm";"Docker images, containers, and build cache" = "Obrazy Dockera, kontenery i cache budowania";+"Unused CPU architecture slices in app binaries" = "Nieużywane architektury CPU w plikach binarnych aplikacji";+"Unused app localizations" = "Nieużywane lokalizacje aplikacji";/* Node Cache subcategories */"npm cache" = "cache npm";diff --git a/PureMac/pt-BR.lproj/Localizable.strings b/PureMac/pt-BR.lproj/Localizable.stringsindex d8f4f6d..e4ac453 100644--- a/PureMac/pt-BR.lproj/Localizable.strings+++ b/PureMac/pt-BR.lproj/Localizable.strings@@ -219,6 +219,8 @@"Brew Cache" = "Cache do Brew";"Node Cache" = "Cache do Node";"Docker Cache" = "Cache do Docker";+"Universal Binaries" = "Binários universais";+"Language Files" = "Arquivos de idioma";/* Cleaning category descriptions */"Scan everything at once" = "Verificar tudo de uma vez";@@ -233,6 +235,8 @@"Homebrew download cache" = "Cache de downloads do Homebrew";"npm, yarn, and pnpm download caches" = "Caches de download do npm, yarn e pnpm";"Docker images, containers, and build cache" = "Imagens, containers e cache de build do Docker";+"Unused CPU architecture slices in app binaries" = "Arquiteturas de CPU não usadas nos binários dos apps";+"Unused app localizations" = "Localizações de apps não usadas";/* Node Cache subcategories */"npm cache" = "Cache do npm";diff --git a/PureMac/zh-Hans.lproj/Localizable.strings b/PureMac/zh-Hans.lproj/Localizable.stringsindex 4e8fbd5..4e71fc5 100644--- a/PureMac/zh-Hans.lproj/Localizable.strings+++ b/PureMac/zh-Hans.lproj/Localizable.strings@@ -219,6 +219,8 @@"Brew Cache" = "Brew 缓存";"Node Cache" = "Node 缓存";"Docker Cache" = "Docker 缓存";+"Universal Binaries" = "通用二进制文件";+"Language Files" = "语言文件";/* Cleaning category descriptions */"Scan everything at once" = "一次扫描所有内容";@@ -233,6 +235,8 @@"Homebrew download cache" = "Homebrew 下载缓存";"npm, yarn, and pnpm download caches" = "npm、yarn 和 pnpm 下载缓存";"Docker images, containers, and build cache" = "Docker 镜像、容器和构建缓存";+"Unused CPU architecture slices in app binaries" = "应用二进制文件中未使用的 CPU 架构代码";+"Unused app localizations" = "未使用的应用本地化文件";/* Node Cache subcategories */"npm cache" = "npm 缓存";diff --git a/PureMac/zh-Hant.lproj/Localizable.strings b/PureMac/zh-Hant.lproj/Localizable.stringsindex f50b81e..df3edf2 100644--- a/PureMac/zh-Hant.lproj/Localizable.strings+++ b/PureMac/zh-Hant.lproj/Localizable.strings@@ -219,6 +219,8 @@"Brew Cache" = "Brew 快取";"Node Cache" = "Node 快取";"Docker Cache" = "Docker 快取";+"Universal Binaries" = "通用二進位檔案";+"Language Files" = "語言檔案";/* Cleaning category descriptions */"Scan everything at once" = "一次掃描所有項目";@@ -233,6 +235,8 @@"Homebrew download cache" = "Homebrew 下載快取";"npm, yarn, and pnpm download caches" = "npm、yarn 與 pnpm 下載快取";"Docker images, containers, and build cache" = "Docker 映像檔、容器與建置快取";+"Unused CPU architecture slices in app binaries" = "應用程式二進位檔中未使用的 CPU 架構程式碼";+"Unused app localizations" = "未使用的應用程式本地化檔案";/* Node Cache subcategories */"npm cache" = "npm 快取";diff --git a/project.yml b/project.ymlindex f698d9d..38b45ed 100644--- a/project.yml+++ b/project.yml@@ -23,8 +23,8 @@ settings:CODE_SIGN_ENTITLEMENTS: "PureMac/PureMac.entitlements"INFOPLIST_FILE: "PureMac/Info.plist"PRODUCT_BUNDLE_IDENTIFIER: "com.puremac.app"- MARKETING_VERSION: "2.8.5"- CURRENT_PROJECT_VERSION: "20"+ MARKETING_VERSION: "2.9.0"+ CURRENT_PROJECT_VERSION: "21"GENERATE_INFOPLIST_FILE: "NO"ASSETCATALOG_COMPILER_APPICON_NAME: "AppIcon"COMBINE_HIDPI_IMAGES: "YES"