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
Add interactive CLI selection and storage browser
momenbaself78611aee7d4
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 585ec8d..544e941 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -7,6 +7,18 @@ on:branches: [main]jobs:+ cli:+ name: CLI tests+ runs-on: macos-15+ steps:+ - uses: actions/checkout@v4+ - name: Test CLI+ working-directory: cli+ run: swift test+ - name: Build CLI+ working-directory: cli+ run: swift build -c release+build:runs-on: macos-15steps:diff --git a/README.md b/README.mdindex 6073abc..58b5af2 100644--- a/README.md+++ b/README.md@@ -69,20 +69,21 @@ xcodebuild -project PureMac.xcodeproj -scheme PureMac -configuration Release \open build/Build/Products/Release/PureMac.app```-### Command line (beta)+### Command line-Prefer the terminal? `puremac` is an independent CLI companion with its own-cleanup commands and safety checks. Some commands permanently remove selected-files, so start with `--dry-run`, review every path, and then confirm deliberately.+Open `puremac` for a keyboard-driven workspace. Select individual cache paths,+review project artifacts, or browse your storage by size. Cleanup shows the exact+selection and asks for confirmation before permanently removing it.```bashbrew install momenbasel/tap/puremac-cli-puremac clean dev --dry-run+puremac```-+-See [`cli/README.md`](cli/README.md) for the full command reference.+Use `puremac clean dev --dry-run` for a preview or `--json` for scripts. See+[`cli/README.md`](cli/README.md) for controls, commands, and cleanup boundaries.## How it comparesdiff --git a/cli/README.md b/cli/README.mdindex 9874926..7473c6a 100644--- a/cli/README.md+++ b/cli/README.md@@ -1,88 +1,143 @@# PureMac CLI-Clean developer caches, project artifacts, and disk clutter from the terminal. A-command-line companion to the [PureMac](https://github.com/momenbasel/PureMac) app-that reuses the same cleaning logic and safety rules.+Choose what to clean. See where your space goes.-PureMac scans first and removes only what you approve. Cache and junk removal is-permanent, but cloud state (iCloud, Dropbox, OneDrive) and your config dotfiles-(`~/.ssh`, `~/.aws`, `~/.gnupg`, `~/.docker`, `~/.claude`, ...) are never touched.+A native Swift command-line companion to [PureMac](https://github.com/momenbasel/PureMac), with a keyboard-driven workspace, individual file selection, and an interactive storage explorer. Free, open source, and no telemetry.-+++Captured from the running CLI using sample projects.## Install```bashbrew install momenbasel/tap/puremac-cli+puremac```-Or build from source (requires a Swift 5.9+ toolchain):+++Already installed?```bash-cd cli-swift build -c release-.build/release/puremac --help+brew update+brew upgrade momenbasel/tap/puremac-cli+```++The release contains a universal binary for Apple Silicon and Intel, signed with Developer ID and submitted to Apple for notarization. Standalone command-line executables cannot carry stapled tickets; the release includes Apple's notarization result.++## Select, review, confirm++Run `puremac` to choose a task, or go straight to a scan:++```bash+puremac clean dev+puremac purge ~/Projects+puremac analyze ~/Projects+```++Cleanup opens a selection screen. Nothing is selected when the interactive review begins. Move through the list, choose individual paths, and check the running size total. Press Return to review the selection, then confirm permanent deletion separately.++| Key | Action |+|---|---|+| Up / Down | Move through the results |+| Space | Toggle the focused item |+| A / N | Select matching results / clear the selection |+| / | Search the results |+| Return | Review the selection |+| Esc / Q | Cancel |++Use Left and Right to scroll a long focused path. The final confirmation prints every selected path in full. Selection is by path, including recent project artifacts that earlier versions only displayed.++Prefer an ordinary scrolling terminal? Use `--plain` for numbered selection and a text review:++```bash+puremac purge ~/Projects --plain+```++The interface adapts to terminal size. `NO_COLOR` disables color. Redirected output and `TERM=dumb` use plain output.++## Explore storage++`puremac analyze` opens a read-only browser sorted by size. Move into a folder with Return or Right, go back with Left or Backspace, and quit with Q. Browsing does not remove anything.++```bash+puremac analyze ~/Projects+puremac analyze ~/Library --plain --depth 2+puremac analyze ~/Projects --json```## Commands| Command | What it does ||---|---|-| `puremac clean` | Scan all categories (dev, junk, ai, trash), review, then remove |-| `puremac clean dev` | Package-manager and build-tool caches only |-| `puremac clean junk` | User logs and Xcode-generated junk only |-| `puremac clean ai` | AI-tool caches and logs only |-| `puremac clean trash` | Empty the user Trash and mounted-volume trashes |-| `puremac purge [path]` | Find removable build artifacts inside project folders |-| `puremac analyze [path]` | Show what is taking up disk space, largest first |-| `puremac optimize [ram\|purgeable]` | Free inactive RAM and release purgeable disk space |-| `puremac ignore add\|remove\|list <path>` | Protect paths from every scan |-| `puremac config` | Show or change preferences |--Flags on `clean` and `purge`:--- `--force` removes immediately, skipping the confirmation. Run without it first.-- `--dry-run` scans and reports what it would remove, deleting nothing.-- `--json` prints machine-readable output and never deletes.--## What `clean dev` covers--Homebrew, npm, Yarn, pnpm, pip, Cargo, Go, CocoaPods, VS Code, JetBrains, Maven,-Gradle, Poetry, uv, Bun, Deno, mise, Flutter/Dart, NuGet/.NET, Swift Package-Manager, Docker, and OrbStack. Only precise cache and build directories are-targeted, never a whole config directory such as `~/.cargo` or `~/.docker`.--## What `purge` finds--`node_modules`, `.next`, `.nuxt`, `.turbo`, `.svelte-kit`, `.angular`,-`.parcel-cache`, `target`, `.build`, `DerivedData`, `Pods`, `.venv`, `venv`,-`__pycache__`, `.pytest_cache`, `.mypy_cache`, `.tox`, `.ruff_cache`, `.gradle`,-and `cmake-build-*`, grouped by project. Artifacts older than seven days are-preselected; newer ones are shown but left unchecked.--## Safety--Every deletion passes one gate before it runs:--- Protected roots (`/`, `$HOME`, `~/Library`, and other containers) can be scanned- into but never removed themselves.-- Config and credential directories are on a hard denylist.-- Cloud File Provider state (iCloud, Dropbox, OneDrive, Google Drive) is refused,- checked against both the literal and symlink-resolved path.-- Symlinks are skipped, and no deletion follows a symlinked parent.-- Paths on your ignore list are excluded from every command.-- `clean` and `purge` print the full list of what will be removed and ask for- confirmation before deleting anything.--Protect a path permanently:+| `puremac` | Open the interactive workspace |+| `puremac clean` | Scan developer caches, user junk, AI-tool caches, and Trash |+| `puremac clean dev` | Review package-manager and build-tool caches |+| `puremac clean junk` | Review user logs and generated Xcode files |+| `puremac clean ai` | Review AI-tool caches and logs |+| `puremac clean trash` | Review user and mounted-volume Trash |+| `puremac purge [path]` | Find generated artifacts inside project folders |+| `puremac analyze [path]` | Browse disk usage without modifying files |+| `puremac optimize` | Show factual memory and disk status |+| `puremac ignore add <path>` | Protect a path from cleanup |+| `puremac ignore remove <path>` | Remove that protection |+| `puremac ignore list` | List protected paths |+| `puremac config` | Show settings and their storage locations |++Run `puremac <command> --help` for every option.++## Previews and scripts++`--dry-run` and `--json` never delete files. They do not open the interactive interface, including when combined with `--force`.++```bash+puremac clean dev --dry-run+puremac purge ~/Projects --json+```++`--force` is an explicit unattended cleanup option. It skips selection and confirmation and permanently removes the scanner's default selection. Preview first. For project artifacts, the default selection uses the age threshold, seven days unless configured otherwise; recent artifacts remain excluded.++```bash+puremac purge ~/Projects --older-than 30 --dry-run+puremac purge ~/Projects --older-than 30 --force+```++Without `--force`, a noninteractive cleanup does not delete anything.++## What gets scanned++Developer cleanup covers precise cache locations for Homebrew, npm, Yarn, pnpm, pip, Cargo, Go, CocoaPods, Maven, Gradle, Poetry, uv, Bun, Deno, mise, Flutter/Dart, NuGet, Swift Package Manager, editor caches, and supported Docker/OrbStack cache paths. It does not invoke a broad Docker prune operation.++Project cleanup finds artifacts such as `node_modules`, `.next`, `.nuxt`, `.turbo`, `.svelte-kit`, `target`, `.build`, `DerivedData`, `Pods`, `.venv`, `__pycache__`, and test/tool caches. Source directories are not artifact targets. Review virtual environments and dependencies before removing them; recreating them may require downloads.++The CLI has its own scan engine and safety checks. Its coverage is separate from the Mac app.++## Cleanup boundaries++- Cleanup is permanent. The selection review lists the exact paths before confirmation.+- Critical filesystem roots, credential/configuration roots, and recognized cloud-provider state are protected.+- Symlink checks and ignore-list checks run again before deletion.+- A path containing an ignored descendant is also protected from removal.+- Failures are reported with paths and a nonzero exit status. Scan sizes are estimates, not a guarantee of a matching increase in available disk space.++Protect a project or folder:```bashpuremac ignore add ~/Projects/important```-## Notes+PureMac does not claim to boost RAM or reliably reclaim APFS purgeable space. macOS manages both; `optimize` reports their state without forcing cleanup.++## Build from source++Requires macOS 11 or later and a Swift 5.9+ toolchain.++```bash+cd cli+swift test+swift build -c release+.build/release/puremac+```-- `clean` and `junk` are user-scoped and need no `sudo`.-- `analyze` is read-only; nothing is deleted while browsing.-- An interactive full-screen browser for `analyze` is not built yet; the current- view ranks folders by size like `du -d1 | sort`.+See [the local release script](../scripts/release-cli-local.sh) for universal builds, signing, and Apple notarization. Publishing also requires updating the Homebrew formula to the checksum of the released archive.diff --git a/cli/Sources/puremac/Commands/Analyze.swift b/cli/Sources/puremac/Commands/Analyze.swiftindex fbf172b..a07e2b9 100644--- a/cli/Sources/puremac/Commands/Analyze.swift+++ b/cli/Sources/puremac/Commands/Analyze.swift@@ -8,6 +8,7 @@ struct Analyze: ParsableCommand {Sizes the immediate children of a folder and ranks them, like `du -d1 | sort`.puremac analyze Explore your home folderpuremac analyze ~/Library Explore a specific folder+ puremac analyze --plain Print a report without fullscreen browsingBrowsing never modifies files.""")@@ -15,67 +16,401 @@ struct Analyze: ParsableCommand {@Argument(help: "Folder to analyze. Omit for your home folder.")var path: String?- @Option(name: .shortAndLong, help: "How many levels deep to break down (default 1).")+ @Option(name: .shortAndLong, help: "How many levels deep to print in plain mode (1...8).")var depth: Int = 1@Flag(name: .long, help: "Emit machine-readable JSON and exit.")var json = false- func run() throws {- let target = ((path ?? Safety.home) as NSString).expandingTildeInPath- var isDir: ObjCBool = false- guard FileManager.default.fileExists(atPath: target, isDirectory: &isDir), isDir.boolValue else {- throw ValidationError("Not a folder: \(target)")+ @Flag(name: .long, help: "Print a report instead of opening the fullscreen explorer.")+ var plain = false++ func validate() throws {+ guard (1...8).contains(depth) else {+ throw ValidationError("Depth must be between 1 and 8.")}+ }- let children = sizedChildren(of: target)- let total = children.reduce(Int64(0)) { $0 + $1.size }+ func run() throws {+ let target = ((path ?? Safety.home) as NSString).expandingTildeInPath+ let ignore = try IgnoreStore(fileURL: AppPaths.ignoreFile)+ try validateRoot(target, ignore: ignore)if json {+ let snapshot = scanFolder(target, ignore: ignore)struct Row: Encodable { let path: String; let bytes: Int64 }- let enc = JSONEncoder(); enc.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]- let data = try enc.encode(children.map { Row(path: $0.path, bytes: $0.size) })+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]+ let data = try encoder.encode(snapshot.children.map { Row(path: $0.path, bytes: $0.size) })print(String(decoding: data, as: UTF8.self))return}- let vol = SystemInfo.volume(target)- if vol.total > 0 {+ if Self.usesInteractiveBrowser(plain: plain, depth: depth) {+ try browse(target, ignore: ignore)+ return+ }++ printPlain(target, ignore: ignore)+ }++ static func usesInteractiveBrowser(+ plain: Bool,+ depth: Int,+ terminalSupported: Bool = TerminalSession.isSupported+ ) -> Bool {+ !plain && depth == 1 && terminalSupported+ }++ struct Child: Equatable {+ let path: String+ let size: Int64+ let isDir: Bool+ let isPackage: Bool+ let inaccessibleCount: Int+ let skippedCount: Int++ var isPartial: Bool { inaccessibleCount > 0 || skippedCount > 0 }+ }++ struct FolderSnapshot: Equatable {+ let path: String+ let children: [Child]+ let total: Int64+ let inaccessibleCount: Int+ let skippedCount: Int+ let errors: [String]++ var isPartial: Bool { inaccessibleCount > 0 || skippedCount > 0 }+ }++ private struct MeasureContext {+ var inaccessibleCount = 0+ var skippedCount = 0+ var errors: [String] = []+ }++ struct BrowserLevel {+ let snapshot: FolderSnapshot+ var selected = 0+ var offset = 0+ }++ func scanFolder(_ directory: String, ignore: IgnoreStore = IgnoreStore()) -> FolderSnapshot {+ let standardized = (directory as NSString).standardizingPath+ let directoryURL = URL(fileURLWithPath: standardized, isDirectory: true)+ let names: [String]+ do {+ names = try FileManager.default.contentsOfDirectory(atPath: standardized)+ } catch {+ return FolderSnapshot(+ path: standardized,+ children: [],+ total: 0,+ inaccessibleCount: 1,+ skippedCount: 0,+ errors: ["\(standardized): \(error.localizedDescription)"]+ )+ }++ var context = MeasureContext()+ var children: [Child] = []+ let orderedNames = names.sorted { $0.localizedStandardCompare($1) == .orderedAscending }+ for name in orderedNames {+ let url = directoryURL.appendingPathComponent(name)+ if let child = measureChild(url, ignore: ignore, context: &context) {+ children.append(child)+ }+ }++ children.sort {+ if $0.size == $1.size {+ return URL(fileURLWithPath: $0.path).lastPathComponent+ .localizedStandardCompare(URL(fileURLWithPath: $1.path).lastPathComponent) == .orderedAscending+ }+ return $0.size > $1.size+ }+ return FolderSnapshot(+ path: standardized,+ children: children,+ total: children.reduce(Int64(0)) { $0 + $1.size },+ inaccessibleCount: context.inaccessibleCount,+ skippedCount: context.skippedCount,+ errors: context.errors+ )+ }++ func sizedChildren(of directory: String) -> [Child] {+ scanFolder(directory).children+ }++ private func measureChild(_ topURL: URL, ignore: IgnoreStore, context: inout MeasureContext) -> Child? {+ let path = topURL.path+ if Safety.ignoredPathProtectsCandidate(path, ignore: ignore) {+ context.skippedCount += 1+ return nil+ }+ let measurement = DirSizer.measure(of: path)+ switch measurement.status {+ case .symlink, .cloudOrDataless:+ context.skippedCount += max(1, measurement.skippedEntries)+ return nil+ case .unavailable:+ context.inaccessibleCount += max(1, measurement.skippedEntries)+ if context.errors.count < 20 { context.errors.append("\(path): unavailable") }+ return nil+ case .partial:+ context.skippedCount += max(1, measurement.skippedEntries)+ if context.errors.count < 20 { context.errors.append("\(path): partial measurement") }+ case .complete:+ break+ }++ let values = try? topURL.resourceValues(forKeys: [.isDirectoryKey, .isPackageKey])+ let isDirectory = values?.isDirectory == true+ return Child(+ path: path,+ size: measurement.bytes,+ isDir: isDirectory,+ isPackage: isDirectory && values?.isPackage == true,+ inaccessibleCount: 0,+ skippedCount: measurement.status == .partial ? max(1, measurement.skippedEntries) : 0+ )+ }++ private func validateRoot(_ target: String, ignore: IgnoreStore) throws {+ let standardized = (target as NSString).standardizingPath+ guard !ignore.isIgnored(standardized) else { throw ValidationError("Ignored path: \(standardized)") }+ guard !Safety.hasSymlinkComponent(standardized) else {+ throw ValidationError("Symbolic links are not scanned: \(standardized)")+ }+ guard !Safety.isCloudOrDataless(standardized) else {+ throw ValidationError("Cloud-only folders must be downloaded before scanning: \(standardized)")+ }+ var isDirectory: ObjCBool = false+ guard FileManager.default.fileExists(atPath: standardized, isDirectory: &isDirectory), isDirectory.boolValue else {+ throw ValidationError("Not a folder: \(standardized)")+ }+ }++ private func printPlain(_ target: String, ignore: IgnoreStore) {+ let snapshot = scanFolder(target, ignore: ignore)+ if let volume = try? SystemInfo.volumeStatus(target), volume.total > 0 {print("")- print(Term.bold("\(ByteCount.human(vol.available)) free of \(ByteCount.human(vol.total))"))+ print(Term.bold("\(ByteCount.human(volume.availableNow)) free of \(ByteCount.human(volume.total))"))}- print(Term.dim("\(Render.shorten(target)) — \(ByteCount.human(total))"))+ print(Term.dim("\(Render.shorten(target)) — \(ByteCount.human(snapshot.total))"))print("")- printLevel(children, total: total, indent: " ", depthLeft: max(1, depth) - 1)+ printLevel(snapshot.children, total: snapshot.total, indent: " ", depthLeft: depth - 1, ignore: ignore)+ printDiagnostics(snapshot, indent: " ")+ }++ func printLevel(+ _ children: [Child],+ total: Int64,+ indent: String,+ depthLeft: Int,+ ignore: IgnoreStore = IgnoreStore()+ ) {+ for child in children where child.size > 0 || child.isPartial {+ let fraction = total > 0 ? Double(child.size) / Double(total) : 0+ let percentage = String(format: "%5.1f%%", fraction * 100)+ let size = ByteCount.human(child.size).padding(toLength: 10, withPad: " ", startingAt: 0)+ let suffix = child.isDir && !child.isPackage ? "/" : (child.isPackage ? " [package]" : "")+ let partial = child.isPartial ? Term.yellow(" !") : ""+ let name = URL(fileURLWithPath: child.path).lastPathComponent + suffix+ print("\(indent)\(size) \(Term.dim(percentage)) \(Term.bar(fraction: fraction, width: 20)) \(name)\(partial)")+ if depthLeft > 0 && child.isDir && !child.isPackage {+ let snapshot = scanFolder(child.path, ignore: ignore)+ printLevel(Array(snapshot.children.prefix(10)), total: child.size, indent: indent + " ", depthLeft: depthLeft - 1, ignore: ignore)+ printDiagnostics(snapshot, indent: indent + " ")+ }+ }}- struct Child { let path: String; let size: Int64; let isDir: Bool }+ private func printDiagnostics(_ snapshot: FolderSnapshot, indent: String) {+ if snapshot.skippedCount > 0 {+ print(indent + Term.yellow("\(snapshot.skippedCount) skipped") + Term.dim(" (ignored, linked, or cloud-only)"))+ }+ if snapshot.inaccessibleCount > 0 {+ print(indent + Term.red("\(snapshot.inaccessibleCount) inaccessible"))+ for error in snapshot.errors.prefix(5) { Term.err(indent + "! " + error) }+ }+ }++ private func browse(_ target: String, ignore: IgnoreStore) throws {+ let session = try TerminalSession()+ defer { session.close() }+ session.draw(lines: measuringLines(target, width: session.width))+ var levels = [BrowserLevel(snapshot: scanFolder(target, ignore: ignore))]+ var running = true++ while running {+ let index = levels.index(before: levels.endIndex)+ let visibleRows = Self.visibleRowCount(snapshot: levels[index].snapshot, selected: levels[index].selected, width: session.width, height: session.height)+ levels[index].offset = Self.adjustedOffset(+ levels[index].offset,+ selected: levels[index].selected,+ count: levels[index].snapshot.children.count,+ visibleRows: visibleRows+ )+ session.draw(lines: Self.browserLines(level: levels[index], width: session.width, height: session.height))- func sizedChildren(of dir: String) -> [Child] {- let fm = FileManager.default- guard let names = try? fm.contentsOfDirectory(atPath: dir) else { return [] }- return names.compactMap { name -> Child? in- let full = "\(dir)/\(name)"- if let type = (try? fm.attributesOfItem(atPath: full)[.type]) as? FileAttributeType, type == .typeSymbolicLink {- return nil+ switch session.readKey() {+ case .up:+ levels[index].selected = max(0, levels[index].selected - 1)+ case .down:+ levels[index].selected = min(max(0, levels[index].snapshot.children.count - 1), levels[index].selected + 1)+ case .pageUp:+ levels[index].selected = max(0, levels[index].selected - visibleRows)+ case .pageDown:+ levels[index].selected = min(max(0, levels[index].snapshot.children.count - 1), levels[index].selected + visibleRows)+ case .home:+ levels[index].selected = 0+ case .end:+ levels[index].selected = max(0, levels[index].snapshot.children.count - 1)+ case .enter, .right:+ guard let child = Self.focusedChild(levels[index]), child.isDir, !child.isPackage else { continue }+ session.draw(lines: measuringLines(child.path, width: session.width))+ levels.append(BrowserLevel(snapshot: scanFolder(child.path, ignore: ignore)))+ case .left, .backspace:+ if levels.count > 1 { levels.removeLast() }+ case .escape:+ running = false+ case .character(let character):+ switch character.lowercased() {+ case "q": running = false+ case "o":+ if let child = Self.focusedChild(levels[index]) { Self.revealInFinder(child.path) }+ default: break+ }+ case .delete, .space, .unknown:+ break}- var isDir: ObjCBool = false- fm.fileExists(atPath: full, isDirectory: &isDir)- return Child(path: full, size: DirSizer.size(of: full), isDir: isDir.boolValue)- }.sorted { $0.size > $1.size }+ }}- func printLevel(_ children: [Child], total: Int64, indent: String, depthLeft: Int) {- for child in children where child.size > 0 {- let frac = total > 0 ? Double(child.size) / Double(total) : 0- let pct = String(format: "%5.1f%%", frac * 100)- let size = ByteCount.human(child.size).padding(toLength: 10, withPad: " ", startingAt: 0)- let name = URL(fileURLWithPath: child.path).lastPathComponent + (child.isDir ? "/" : "")- print("\(indent)\(size) \(Term.dim(pct)) \(Term.bar(fraction: frac, width: 20)) \(name)")- if depthLeft > 0 && child.isDir {- let sub = sizedChildren(of: child.path)- printLevel(Array(sub.prefix(10)), total: child.size, indent: indent + " ", depthLeft: depthLeft - 1)+ private func measuringLines(_ path: String, width: Int) -> [String] {+ let safeWidth = max(1, width)+ return [+ Term.bold(Term.cyan(Term.truncate("PureMac Space Explorer", to: safeWidth))),+ "",+ Term.dim(Term.truncate("Measuring allocated space...", to: safeWidth)),+ Term.truncate(path, to: safeWidth, middle: true),+ "",+ Term.dim(Term.truncate("Ctrl+C cancel", to: safeWidth))+ ]+ }++ static func browserLines(level: BrowserLevel, width: Int, height: Int) -> [String] {+ let safeWidth = max(1, width)+ let safeHeight = max(1, height)+ if safeWidth < 40 || safeHeight < 12 {+ let compact = [+ Term.bold(Term.cyan(Term.truncate("PureMac Space Explorer", to: safeWidth))),+ Term.truncate("Terminal too small", to: safeWidth),+ Term.dim(Term.truncate("Resize to at least 40 x 12", to: safeWidth)),+ "",+ Term.dim(Term.truncate("Esc/q exit", to: safeWidth))+ ]+ return Array(compact.prefix(safeHeight))+ }+ let snapshot = level.snapshot+ let pathLines = wrap(focusedChild(level)?.path ?? snapshot.path, width: max(1, safeWidth - 9))+ let visibleRows = visibleRowCount(snapshot: snapshot, selected: level.selected, width: safeWidth, height: safeHeight)+ let upperBound = min(snapshot.children.count, level.offset + visibleRows)+ let rows = level.offset < upperBound+ ? snapshot.children[level.offset..<upperBound].enumerated().map { offset, child in+ row(child, focused: level.offset + offset == level.selected, total: snapshot.total, width: safeWidth)}+ : []++ var lines = [+ Term.bold(Term.cyan("PureMac Space Explorer")),+ Term.truncate(snapshot.path, to: safeWidth, middle: true),+ statusLine(snapshot, width: safeWidth),+ String(repeating: "─", count: safeWidth)+ ]+ lines.append(contentsOf: rows.isEmpty+ ? [snapshot.inaccessibleCount > 0 ? Term.red("Folder contents are inaccessible.") : Term.dim("No measurable items.")]+ : rows)+ lines.append(String(repeating: "─", count: safeWidth))+ lines.append(Term.dim("↑↓ move Enter/→ open O reveal"))+ lines.append(Term.dim("←/⌫ back q/Esc exit"))+ for (index, line) in pathLines.enumerated() {+ lines.append((index == 0 ? Term.dim("Focused: ") : String(repeating: " ", count: 9)) + line)+ }+ if let error = snapshot.errors.first {+ lines.append(Term.red("! ") + Term.truncate(error, to: max(1, safeWidth - 2), middle: true))}+ return Array(lines.prefix(safeHeight))+ }++ static func visibleRowCount(snapshot: FolderSnapshot, selected: Int, width: Int, height: Int) -> Int {+ let focusedPath = snapshot.children.indices.contains(selected) ? snapshot.children[selected].path : snapshot.path+ let pathLines = wrap(focusedPath, width: max(1, max(1, width) - 9)).count+ return max(1, height - 7 - pathLines - (snapshot.errors.isEmpty ? 0 : 1))+ }++ static func adjustedOffset(_ offset: Int, selected: Int, count: Int, visibleRows: Int) -> Int {+ guard count > 0 else { return 0 }+ let selection = min(max(0, selected), count - 1)+ var result = min(max(0, offset), max(0, count - visibleRows))+ if selection < result { result = selection }+ if selection >= result + visibleRows { result = selection - visibleRows + 1 }+ return max(0, result)+ }++ private static func focusedChild(_ level: BrowserLevel) -> Child? {+ guard level.snapshot.children.indices.contains(level.selected) else { return nil }+ return level.snapshot.children[level.selected]+ }++ private static func row(_ child: Child, focused: Bool, total: Int64, width: Int) -> String {+ let fraction = total > 0 ? Double(child.size) / Double(total) : 0+ let size = Render.pad(ByteCount.human(child.size), 10)+ let barWidth = min(20, max(6, (width - 32) / 3))+ let suffix = child.isDir && !child.isPackage ? "/" : (child.isPackage ? " [package]" : "")+ let partial = child.isPartial ? " !" : ""+ let nameWidth = max(1, width - 14 - barWidth - partial.count)+ let name = Term.truncate(URL(fileURLWithPath: child.path).lastPathComponent + suffix, to: nameWidth, middle: true)+ let line = "\(focused ? "›" : " ") \(size) \(Term.bar(fraction: fraction, width: barWidth)) \(name)\(partial)"+ return focused ? Term.inverse(Term.pad(line, to: width)) : line}++ private static func statusLine(_ snapshot: FolderSnapshot, width: Int) -> String {+ var parts = [ByteCount.human(snapshot.total) + " allocated", "\(snapshot.children.count) items"]+ if snapshot.skippedCount > 0 { parts.append("\(snapshot.skippedCount) skipped") }+ if snapshot.inaccessibleCount > 0 { parts.append("\(snapshot.inaccessibleCount) inaccessible") }+ return Term.truncate(parts.joined(separator: " · "), to: width)+ }++ static func wrap(_ string: String, width: Int) -> [String] {+ let safe = Term.sanitize(string)+ guard !safe.isEmpty else { return [""] }+ var lines: [String] = []+ var current = ""+ var used = 0+ for character in safe {+ let value = String(character)+ let characterWidth = max(0, Term.displayWidth(value))+ if used + characterWidth > width && !current.isEmpty {+ lines.append(current)+ current = ""+ used = 0+ }+ current.append(character)+ used += characterWidth+ }+ if !current.isEmpty { lines.append(current) }+ return lines.isEmpty ? [""] : lines+ }++ private static func revealInFinder(_ path: String) {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/usr/bin/open")+ process.arguments = ["-R", path]+ try? process.run()+ }+}diff --git a/cli/Sources/puremac/Commands/Clean.swift b/cli/Sources/puremac/Commands/Clean.swiftindex 6b2f2b2..b791f74 100644--- a/cli/Sources/puremac/Commands/Clean.swift+++ b/cli/Sources/puremac/Commands/Clean.swift@@ -11,13 +11,15 @@ struct Clean: ParsableCommand {puremac clean junk User logs & Xcode-generated junk onlypuremac clean ai AI-tool caches & logs onlypuremac clean trash Empty user + mounted-volume Trash++ Interactive review starts with every item unselected. Finishing the selector only opens an exact deletion review; a separate confirmation defaults to No. --plain uses a numbered selector with ranges, all, and none. --force removes the scanner's standard preselection without either prompt. --dry-run and --json never delete or open a selector.""")@Argument(help: "Category to clean: dev | junk | ai | trash. Omit to clean all.")var category: String?- @Flag(name: .long, help: "Skip the confirmation prompt and remove immediately.")+ @Flag(name: .long, help: "Remove the scanner's standard preselection without review or confirmation.")var force = false@Flag(name: .customLong("dry-run"), help: "Scan and report only; never delete.")@@ -26,6 +28,9 @@ struct Clean: ParsableCommand {@Flag(name: .long, help: "Emit machine-readable JSON and exit (never deletes).")var json = false+ @Flag(name: .long, help: "Use a numbered line-based selector instead of the fullscreen review.")+ var plain = false+static let validIDs = ["dev", "junk", "ai", "trash"]func validate() throws {@@ -35,39 +40,74 @@ struct Clean: ParsableCommand {}func run() throws {+ let mode = CleanupCommandPolicy.mode(+ force: force,+ dryRun: dryRun,+ json: json,+ plain: plain+ )+ guard mode != .unavailable else {+ throw ValidationError("Interactive review requires a terminal. Re-run with --force to remove the preselected items, or use --dry-run or --json for a read-only report.")+ }+let ids = category.map { [$0] } ?? Clean.validIDs- let ignore = IgnoreStore()+ let ignore = try IgnoreStore(fileURL: AppPaths.ignoreFile)+ if !json {+ Term.err(Term.dim("Scanning " + ids.map(Clean.title).joined(separator: ", ") + " …"))+ }let cats = ids.map { id inCategoryScanner.scan(categoryID: id, title: Clean.title(id), ignore: ignore)}.filter { !$0.groups.isEmpty }if json {- print(JSONReport.string(cats))+ print(try JSONReport.string(cats))return}if cats.isEmpty {- print(Term.green("Nothing to clean — you're already tidy."))+ print(Term.green("No cleanup candidates found in readable locations."))return}- Render.scanResults(cats)- Render.selectionLine(cats)+ if dryRun {+ Render.scanResults(cats)+ Render.selectionLine(cats)+ let selected = cats.flatMap { $0.selectedItems }+ let out = Cleaner.remove(selected, ignore: ignore, dryRun: true)+ Render.cleanupSummary(out, dryRun: true)+ return+ }- let selected = cats.flatMap { $0.selectedItems }- if selected.isEmpty {- print(Term.dim("No items selected by default. Nothing removed."))+ let reviewed: [CategoryScan]+ switch mode {+ case .forced:+ reviewed = cats+ Render.scanResults(cats)+ Render.selectionLine(cats)+ case .fullscreen:+ guard let selection = try InteractiveReview.select(cats, title: "Choose items to clean") else {+ print(Term.dim("Cancelled. Nothing removed."))+ return+ }+ reviewed = selection+ case .plain:+ guard let selection = try PlainSelectionReview.select(cats, title: "Choose items to clean") else {+ print(Term.dim("Cancelled. Nothing removed."))+ return+ }+ reviewed = selection+ case .reportOnly, .unavailable:return}- if dryRun {- let out = Cleaner.remove(selected, ignore: ignore, dryRun: true)- Render.cleanupSummary(out, dryRun: true)+ let selected = reviewed.flatMap { $0.selectedItems }+ if selected.isEmpty {+ print(Term.dim("No items selected. Nothing removed."))return}- if !force {- Render.deletionReview(cats)+ if mode != .forced {+ Render.deletionReview(reviewed)let total = ByteCount.human(selected.reduce(Int64(0)) { $0 + $1.sizeBytes })guard Term.confirm("Remove \(selected.count) items (\(total))?", default: false) else {print(Term.dim("Cancelled. Nothing removed."))@@ -77,9 +117,6 @@ struct Clean: ParsableCommand {let out = Cleaner.remove(selected, ignore: ignore, dryRun: false)Render.cleanupSummary(out, dryRun: false)- if !force {- print(Term.dim("Tip: `puremac ignore add <path>` protects a path · `puremac clean --force` skips this prompt"))- }if out.hadFailures { throw ExitCode.failure }}@@ -88,8 +125,108 @@ struct Clean: ParsableCommand {}}+enum CleanupCommandMode: Equatable {+ case reportOnly+ case forced+ case fullscreen+ case plain+ case unavailable+}++enum CleanupCommandPolicy {+ static func mode(+ force: Bool,+ dryRun: Bool,+ json: Bool,+ plain: Bool,+ terminalSupported: Bool = TerminalSession.isSupported,+ inputIsTTY: Bool = isatty(fileno(stdin)) == 1 && isatty(fileno(stdout)) == 1+ ) -> CleanupCommandMode {+ if dryRun || json { return .reportOnly }+ if force { return .forced }+ guard inputIsTTY else { return .unavailable }+ return plain || !terminalSupported ? .plain : .fullscreen+ }+}++enum PlainSelectionReview {+ static func select(_ categories: [CategoryScan], title: String) throws -> [CategoryScan]? {+ print("")+ print(Term.bold(Term.sanitize(title)))+ print(Term.dim("All items start unselected. Enter numbers, ranges, all, none, or q to cancel."))+ var number = 1+ for category in categories {+ print("")+ print(" " + Term.cyan(Term.sanitize(category.title)))+ for group in category.groups {+ for item in group.items {+ print(" \(number). \(Render.sizeCol(item.sizeBytes)) \(Render.pad(Term.sanitize(group.tool), 20)) \(Term.sanitize(item.path))")+ number += 1+ }+ }+ }++ while true {+ print("\nSelect items: ", terminator: "")+ guard let line = readLine() else { return nil }+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)+ if ["q", "quit", "cancel"].contains(trimmed.lowercased()) { return nil }+ do {+ let indices = try parseSelection(trimmed, itemCount: number - 1)+ return applyingSelection(indices, to: categories)+ } catch {+ Term.err(Term.red(Term.sanitize(error.localizedDescription)))+ }+ }+ }++ static func parseSelection(_ input: String, itemCount: Int) throws -> Set<Int> {+ let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ if trimmed.isEmpty || trimmed == "none" { return [] }+ if trimmed == "all" { return itemCount > 0 ? Set(1...itemCount) : [] }++ let parts = trimmed.replacingOccurrences(of: ",", with: " ")+ .split(whereSeparator: { $0.isWhitespace })+ var selected = Set<Int>()+ for partValue in parts {+ let part = String(partValue)+ if part.contains("-") {+ let bounds = part.split(separator: "-", omittingEmptySubsequences: false)+ guard bounds.count == 2,+ let lower = Int(bounds[0]),+ let upper = Int(bounds[1]),+ lower <= upper,+ lower >= 1,+ upper <= itemCount+ else { throw ValidationError("Invalid selection '\(part)'.") }+ selected.formUnion(lower...upper)+ } else {+ guard let index = Int(part), index >= 1, index <= itemCount else {+ throw ValidationError("Invalid selection '\(part)'.")+ }+ selected.insert(index)+ }+ }+ return selected+ }++ static func applyingSelection(_ selected: Set<Int>, to categories: [CategoryScan]) -> [CategoryScan] {+ var result = categories+ var number = 1+ for categoryIndex in result.indices {+ for groupIndex in result[categoryIndex].groups.indices {+ for itemIndex in result[categoryIndex].groups[groupIndex].items.indices {+ result[categoryIndex].groups[groupIndex].items[itemIndex].selected = selected.contains(number)+ number += 1+ }+ }+ }+ return result+ }+}+enum JSONReport {- static func string(_ cats: [CategoryScan]) -> String {+ static func string(_ cats: [CategoryScan]) throws -> String {struct Out: Encodable {struct Cat: Encodable { let id, title: String; let totalBytes, selectedBytes: Int64; let groups: [ToolGroup] }let totalBytes: Int64@@ -102,6 +239,6 @@ enum JSONReport {let enc = JSONEncoder()enc.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]enc.dateEncodingStrategy = .iso8601- return (try? enc.encode(out)).flatMap { String(data: $0, encoding: .utf8) } ?? "{}"+ return String(decoding: try enc.encode(out), as: UTF8.self)}}diff --git a/cli/Sources/puremac/Commands/Config.swift b/cli/Sources/puremac/Commands/Config.swiftindex 7939863..a510e42 100644--- a/cli/Sources/puremac/Commands/Config.swift+++ b/cli/Sources/puremac/Commands/Config.swift@@ -5,33 +5,62 @@ struct Config: ParsableCommand {static let configuration = CommandConfiguration(abstract: "Show or change CLI preferences.",discussion: """- puremac config Show all settings and file locations+ puremac config Show settings and storage locationspuremac config set purge.older_than_days 14- PureMac CLI sends no telemetry — there is nothing to opt out of.+ The age setting controls which project artifacts `puremac purge` preselects.+ PureMac CLI has no telemetry setting because it sends no telemetry.""")- @Argument(help: "'set' to change a value, omit to show all.") var action: String?- @Argument(help: "Key to set.") var key: String?- @Argument(help: "Value to set.") var value: String?+ @Argument(help: "Use 'set' to change a value. Omit to show settings.")+ var action: String?++ @Argument(help: "Setting key.")+ var key: String?++ @Argument(help: "New value.")+ var value: String?++ func validate() throws {+ if action == nil, key == nil, value == nil { return }+ guard action == "set" else {+ throw ValidationError("Unknown action '\(action ?? "")'. Use 'set' or omit all arguments.")+ }+ guard let key, let value else {+ throw ValidationError("Usage: puremac config set <key> <value>")+ }+ do {+ _ = try ConfigStore.normalizedValue(value, for: key)+ } catch {+ throw ValidationError(error.localizedDescription)+ }+ }func run() throws {- var store = ConfigStore()+ var store = try ConfigStore(fileURL: AppPaths.configFile)if action == "set" {- guard let key, let value else { throw ValidationError("Usage: puremac config set <key> <value>") }- guard ConfigStore.knownKeys.contains(key) else {- throw ValidationError("Unknown key '\(key)'. Known: \(ConfigStore.knownKeys.joined(separator: ", "))")+ guard let key, let value else {+ throw ValidationError("Usage: puremac config set <key> <value>")}- store.set(key, value)- print(Term.green("✓ \(key) = \(value)"))+ try store.set(key, value)+ let saved = store.values[key] ?? value+ print(Term.green("✓ Saved \(key) = \(saved)"))+ print(Term.dim(" \(Render.shorten(AppPaths.configFile.path))"))return}- print(Term.bold("PureMac CLI configuration"))- print(Term.dim(" config: ") + Render.shorten(AppPaths.configFile.path))- print(Term.dim(" ignore: ") + Render.shorten(AppPaths.ignoreFile.path))++ print(Term.bold("PureMac CLI settings"))+ print(Term.dim("Values used when a command-line option is omitted"))print("")for key in ConfigStore.knownKeys {- print(" \(key) = \(store.values[key] ?? Term.dim("(default)"))")+ let isSaved = store.values[key] != nil+ let value = store.values[key] ?? ConfigStore.defaultValues[key] ?? ""+ let source = isSaved ? "saved" : "default"+ print(" \(key.padding(toLength: 26, withPad: " ", startingAt: 0)) \(value) days " + Term.dim(source))}+ print("")+ print(Term.bold("Files"))+ print(" \("Settings".padding(toLength: 12, withPad: " ", startingAt: 0)) \(Render.shorten(AppPaths.configFile.path))")+ print(" \("Protected".padding(toLength: 12, withPad: " ", startingAt: 0)) \(Render.shorten(AppPaths.ignoreFile.path))")}}diff --git a/cli/Sources/puremac/Commands/Ignore.swift b/cli/Sources/puremac/Commands/Ignore.swiftindex 374ee0f..8276f42 100644--- a/cli/Sources/puremac/Commands/Ignore.swift+++ b/cli/Sources/puremac/Commands/Ignore.swift@@ -12,7 +12,7 @@ struct Ignore: ParsableCommand {static let configuration = CommandConfiguration(abstract: "Add a path to the ignore list.")@Argument(help: "Path to protect.") var path: Stringfunc run() throws {- var store = IgnoreStore()+ var store = try IgnoreStore(fileURL: AppPaths.ignoreFile)let added = try store.add(path)let shown = Render.shorten(((path as NSString).expandingTildeInPath as NSString).standardizingPath)print(added ? Term.green("✓ Protected ") + shown : Term.dim("Already protected: \(shown)"))@@ -23,7 +23,7 @@ struct Ignore: ParsableCommand {static let configuration = CommandConfiguration(abstract: "Remove a path from the ignore list.")@Argument(help: "Path to stop protecting.") var path: Stringfunc run() throws {- var store = IgnoreStore()+ var store = try IgnoreStore(fileURL: AppPaths.ignoreFile)let removed = try store.remove(path)let shown = Render.shorten(((path as NSString).expandingTildeInPath as NSString).standardizingPath)print(removed ? Term.green("✓ Removed ") + shown : Term.yellow("Not in ignore list: \(shown)"))@@ -33,7 +33,7 @@ struct Ignore: ParsableCommand {struct List: ParsableCommand {static let configuration = CommandConfiguration(abstract: "Show protected paths.")func run() throws {- let store = IgnoreStore()+ let store = try IgnoreStore(fileURL: AppPaths.ignoreFile)if store.roots.isEmpty {print(Term.dim("No protected paths. Add one with `puremac ignore add <path>`."))returndiff --git a/cli/Sources/puremac/Commands/Optimize.swift b/cli/Sources/puremac/Commands/Optimize.swiftindex f260940..eeda248 100644--- a/cli/Sources/puremac/Commands/Optimize.swift+++ b/cli/Sources/puremac/Commands/Optimize.swift@@ -3,61 +3,133 @@ import Foundationstruct Optimize: ParsableCommand {static let configuration = CommandConfiguration(- abstract: "Free inactive RAM and release purgeable disk space.",+ abstract: "Review memory, storage, and local snapshot status.",discussion: """- puremac optimize Run both tasks- puremac optimize ram Ask macOS to release inactive memory- puremac optimize purgeable Release APFS purgeable disk space- macOS manages memory on its own; these are best-effort nudges, not magic.+ puremac optimize Show memory and storage status+ puremac optimize ram Show memory details+ puremac optimize purgeable Explain APFS managed capacity+ puremac optimize snapshots List local Time Machine snapshots+ These checks are read-only. PureMac does not force memory purges or promise+ that APFS managed capacity can be reclaimed on demand.""")- @Argument(help: "Task to run: ram | purgeable. Omit to run both.")+ @Argument(help: "View to show: status | ram | purgeable | snapshots.")var task: String?func validate() throws {- if let t = task, t != "ram", t != "purgeable" {- throw ValidationError("Unknown task '\(t)'. Use 'ram' or 'purgeable'.")+ guard let task else { return }+ guard ["status", "ram", "purgeable", "snapshots"].contains(task) else {+ throw ValidationError(+ "Unknown view '\(task)'. Use 'status', 'ram', 'purgeable', or 'snapshots'."+ )}}func run() throws {- let all = task == nil- var ok = true- if all || task == "ram" { ok = optimizeRAM() && ok }- if all || task == "purgeable" { ok = optimizePurgeable() && ok }- if !ok { throw ExitCode.failure }- }-- @discardableResult- private func optimizeRAM() -> Bool {- let before = SystemInfo.memory()- print(Term.dim("Releasing inactive memory…"))- let r = Shell.run("/usr/sbin/purge", [])- let after = SystemInfo.memory()- if r.status == 0 {- let delta = after.free - before.free- let avail = after.free + after.inactive- print(Term.green("✓ RAM optimized") + " · \(ByteCount.human(max(0, delta))) newly free · \(ByteCount.human(avail)) available")- return true+ switch task ?? "status" {+ case "ram":+ try showMemory(includeHeading: true)+ print("")+ print(Term.dim("No memory was purged. macOS reclaims inactive memory when applications need it."))+ case "purgeable":+ try showStorage(includeHeading: true)+ print("")+ print(Term.dim("No storage was changed. APFS managed capacity is an estimate controlled by macOS."))+ case "snapshots":+ try showSnapshots()+ default:+ print(Term.bold("Mac status"))+ print(Term.dim("Read-only measurements from macOS"))+ print("")+ try showMemory(includeHeading: true)+ print("")+ try showStorage(includeHeading: true)+ print("")+ print(" " + Term.dim("Uptime") + " " + Self.formatUptime(ProcessInfo.processInfo.systemUptime))+ print("")+ print(Term.dim("No maintenance ran. Use `puremac clean --dry-run` to review removable files."))}- print(Term.yellow("• Could not run purge") + Term.dim(" — try: sudo puremac optimize ram"))- print(Term.dim(" macOS already reclaims inactive memory automatically under pressure."))- return false- }-- @discardableResult- private func optimizePurgeable() -> Bool {- let before = SystemInfo.volume("/").available- print(Term.dim("Releasing purgeable disk space…"))- let r = Shell.run("/usr/sbin/diskutil", ["apfs", "purgePurgeable", "/"])- let after = SystemInfo.volume("/").available- if r.status == 0 {- let freed = max(0, after - before)- print(Term.green("✓ Purgeable space released") + " · \(ByteCount.human(freed)) reclaimed")- return true+ }++ static func parseLocalSnapshots(_ output: String) -> [String] {+ let snapshots = output.split(whereSeparator: \Character.isNewline)+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter(isValidLocalSnapshot)+ return Array(Set(snapshots)).sorted(by: >)+ }++ static func isValidLocalSnapshot(_ value: String) -> Bool {+ let prefix = "com.apple.TimeMachine."+ let suffix = ".local"+ guard value.hasPrefix(prefix), value.hasSuffix(suffix) else { return false }+ let start = value.index(value.startIndex, offsetBy: prefix.count)+ let end = value.index(value.endIndex, offsetBy: -suffix.count)+ let timestamp = String(value[start..<end])+ guard timestamp.count == 17 else { return false }++ let formatter = DateFormatter()+ formatter.locale = Locale(identifier: "en_US_POSIX")+ formatter.calendar = Calendar(identifier: .gregorian)+ formatter.timeZone = TimeZone(secondsFromGMT: 0)+ formatter.dateFormat = "yyyy-MM-dd-HHmmss"+ formatter.isLenient = false+ guard let date = formatter.date(from: timestamp) else { return false }+ return formatter.string(from: date) == timestamp+ }++ static func formatUptime(_ interval: TimeInterval) -> String {+ let seconds = max(0, Int(interval))+ let days = seconds / 86_400+ let hours = (seconds % 86_400) / 3_600+ let minutes = (seconds % 3_600) / 60+ if days > 0 { return "\(days)d \(hours)h \(minutes)m" }+ if hours > 0 { return "\(hours)h \(minutes)m" }+ return "\(minutes)m"+ }++ private func showMemory(includeHeading: Bool) throws {+ let status = try SystemInfo.memoryStatus()+ if includeHeading { print(Term.bold("Memory")) }+ printMetric("Installed", ByteCount.human(status.total))+ printMetric("Free now", ByteCount.human(status.free))+ printMetric("Active", ByteCount.human(status.active))+ printMetric("Inactive", ByteCount.human(status.inactive))+ printMetric("Compressed", ByteCount.human(status.compressed))+ printMetric("Wired", ByteCount.human(status.wired))+ }++ private func showStorage(includeHeading: Bool) throws {+ let status = try SystemInfo.volumeStatus("/")+ if includeHeading { print(Term.bold("Storage")) }+ printMetric("Free now", ByteCount.human(status.availableNow))+ printMetric("Total", ByteCount.human(status.total))+ printMetric("Managed by macOS", ByteCount.human(status.systemManagedCapacity))+ if status.systemManagedCapacity > 0 {+ print(Term.dim(" Managed capacity may include purgeable files and is not guaranteed free space."))+ }+ }++ private func showSnapshots() throws {+ let result = Shell.run("/usr/bin/tmutil", ["listlocalsnapshots", "/"])+ guard result.status == 0 else {+ let detail = result.err.trimmingCharacters(in: .whitespacesAndNewlines)+ throw ValidationError(detail.isEmpty ? "Could not list local Time Machine snapshots." : detail)}- print(Term.yellow("• Could not release purgeable space") + Term.dim(" — try: sudo puremac optimize purgeable"))- return false+ let snapshots = Self.parseLocalSnapshots(result.out)+ print(Term.bold("Local Time Machine snapshots"))+ if snapshots.isEmpty {+ print(Term.dim(" None reported by macOS."))+ return+ }+ for snapshot in snapshots {+ print(" \(snapshot) " + Term.dim("size unavailable"))+ }+ print("")+ print(Term.dim("Read-only list. Snapshot storage is managed by Time Machine and macOS."))+ }++ private func printMetric(_ label: String, _ value: String) {+ print(" \(label.padding(toLength: 17, withPad: " ", startingAt: 0)) \(value)")}}diff --git a/cli/Sources/puremac/Commands/Purge.swift b/cli/Sources/puremac/Commands/Purge.swiftindex 53d20eb..8c2cba8 100644--- a/cli/Sources/puremac/Commands/Purge.swift+++ b/cli/Sources/puremac/Commands/Purge.swift@@ -6,19 +6,21 @@ struct Purge: ParsableCommand {abstract: "Find removable build artifacts inside project folders (node_modules, target, .venv, …).",discussion: """With no path, scans ~/Projects, ~/Code, ~/dev, ~/GitHub, ~/Workspace.- Artifacts older than the age threshold are preselected; newer ones are shown unchecked.+ Interactive review starts empty so recent and older artifacts are both selectable.puremac purge Scan the default project folderspuremac purge ~/Work/app Scan a specific folder++ Finishing the selector only opens an exact deletion review; a separate confirmation defaults to No. --plain uses a numbered selector with ranges, all, and none. --force removes only artifacts older than the configured threshold without either prompt. --dry-run and --json never delete or open a selector.""")@Argument(help: "Folder(s) to scan. Omit to scan the default project locations.")var paths: [String] = []- @Option(name: .customLong("older-than"), help: "Preselect artifacts older than N days (default 7, or config).")+ @Option(name: .customLong("older-than"), help: "Age threshold used by --force and read-only reports (default 7, or config).")var olderThanDays: Int = -1- @Flag(name: .long, help: "Skip the confirmation prompt and remove immediately.")+ @Flag(name: .long, help: "Remove age-selected artifacts without review or confirmation.")var force = false@Flag(name: .customLong("dry-run"), help: "Scan and report only; never delete.")@@ -27,6 +29,9 @@ struct Purge: ParsableCommand {@Flag(name: .long, help: "Emit machine-readable JSON and exit (never deletes).")var json = false+ @Flag(name: .long, help: "Use a numbered line-based selector instead of the fullscreen review.")+ var plain = false+func validate() throws {if olderThanDays != -1 && !(0...3650).contains(olderThanDays) {throw ValidationError("--older-than must be between 0 and 3650 days.")@@ -38,47 +43,66 @@ struct Purge: ParsableCommand {}func run() throws {- let ignore = IgnoreStore()- let days = resolvedDays()+ let mode = CleanupCommandPolicy.mode(+ force: force,+ dryRun: dryRun,+ json: json,+ plain: plain+ )+ guard mode != .unavailable else {+ throw ValidationError("Interactive review requires a terminal. Re-run with --force to remove the age-selected artifacts, or use --dry-run or --json for a read-only report.")+ }++ let ignore = try IgnoreStore(fileURL: AppPaths.ignoreFile)+ let days = try resolvedDays()let roots = paths.isEmpty? Purger.defaultRoots- : paths.map { (($0 as NSString).expandingTildeInPath as NSString).standardizingPath }+ : paths.map { Safety.absolutePath($0) }if !json { Term.err(Term.dim("Scanning " + roots.map { Render.shorten($0) }.joined(separator: ", ") + " …")) }let cat = Purger.scan(roots: roots, olderThanDays: days, ignore: ignore)- if json { print(JSONReport.string([cat])); return }+ if json { print(try JSONReport.string([cat])); return }if cat.groups.isEmpty {- print(Term.green("No project artifacts found."))+ print(Term.green("No project artifacts found in readable locations."))return}- let projectCount = cat.groups.count- print("")- print(Term.bold("Found \(ByteCount.human(cat.allBytes)) across \(projectCount) project\(projectCount == 1 ? "" : "s")"))- for group in cat.groups {- print("")- print(" \(Term.cyan(group.tool)) \(Term.dim(ByteCount.human(group.allBytes)))")- for item in group.items {- let mark = item.selected ? Term.green("✓") : Term.dim("·")- let recent = item.selected ? "" : Term.dim(" recent")- print(" \(mark) \(Render.sizeCol(item.sizeBytes)) \(Render.shorten(item.path))\(recent)")- }- }- print("")- print(Term.dim("Artifacts newer than \(days) days are shown but left unchecked."))-- let selected = cat.selectedItems- if selected.isEmpty { print(Term.dim("\nNothing preselected. Nothing removed.")); return }-if dryRun {+ renderScan(cat, days: days)+ let selected = cat.selectedItemslet out = Cleaner.remove(selected, ignore: ignore, dryRun: true)Render.cleanupSummary(out, dryRun: true)return}- if !force {- Render.deletionReview([cat])++ let reviewed: [CategoryScan]+ switch mode {+ case .forced:+ reviewed = [cat]+ renderScan(cat, days: days)+ case .fullscreen:+ guard let selection = try InteractiveReview.select([cat], title: "Choose project artifacts") else {+ print(Term.dim("Cancelled. Nothing removed."))+ return+ }+ reviewed = selection+ case .plain:+ guard let selection = try PlainSelectionReview.select([cat], title: "Choose project artifacts") else {+ print(Term.dim("Cancelled. Nothing removed."))+ return+ }+ reviewed = selection+ case .reportOnly, .unavailable:+ return+ }++ let selected = reviewed.flatMap { $0.selectedItems }+ if selected.isEmpty { print(Term.dim("\nNo artifacts selected. Nothing removed.")); return }++ if mode != .forced {+ Render.deletionReview(reviewed)let total = ByteCount.human(selected.reduce(Int64(0)) { $0 + $1.sizeBytes })guard Term.confirm("Remove \(selected.count) artifacts (\(total))?", default: false) else {print(Term.dim("Cancelled. Nothing removed."))@@ -90,9 +114,27 @@ struct Purge: ParsableCommand {if out.hadFailures { throw ExitCode.failure }}- private func resolvedDays() -> Int {+ private func resolvedDays() throws -> Int {if olderThanDays >= 0 { return olderThanDays }- if let v = ConfigStore().values["purge.older_than_days"], let n = Int(v), (0...3650).contains(n) { return n }+ let config = try ConfigStore(fileURL: AppPaths.configFile)+ if let v = config.values["purge.older_than_days"], let n = Int(v), (0...3650).contains(n) { return n }return 7}++ private func renderScan(_ cat: CategoryScan, days: Int) {+ let projectCount = cat.groups.count+ print("")+ print(Term.bold("Found \(ByteCount.human(cat.allBytes)) across \(projectCount) project\(projectCount == 1 ? "" : "s")"))+ for group in cat.groups {+ print("")+ print(" \(Term.cyan(group.tool)) \(Term.dim(ByteCount.human(group.allBytes)))")+ for item in group.items {+ let mark = item.selected ? Term.green("✓") : Term.dim("·")+ let recent = item.selected ? "" : Term.dim(" recent")+ print(" \(mark) \(Render.sizeCol(item.sizeBytes)) \(Render.shorten(item.path))\(recent)")+ }+ }+ print("")+ print(Term.dim("Artifacts newer than \(days) days are shown but left unchecked."))+ }}diff --git a/cli/Sources/puremac/Core/CategoryScanner.swift b/cli/Sources/puremac/Core/CategoryScanner.swiftindex 51c8008..1a3cf01 100644--- a/cli/Sources/puremac/Core/CategoryScanner.swift+++ b/cli/Sources/puremac/Core/CategoryScanner.swift@@ -15,17 +15,23 @@ enum CategoryScanner {var candidates: [(target: Int, path: String)] = []for (ti, target) in targets.enumerated() {let paths = target.contents- ? target.paths.filter { !Safety.isSymlink($0) }.flatMap(children(of:))+ ? target.paths.filter {+ !Safety.hasSymlinkComponent($0)+ && !Safety.isCloudOrDataless($0)+ && !Safety.isPathIgnored($0, ignore: ignore)+ }.flatMap(children(of:)): target.pathsfor path in paths where passesPreFilter(path, ignore: ignore) {candidates.append((ti, path))}}- let sizes = concurrentSizes(candidates.map { $0.path })+ candidates = uniqueCandidates(candidates)+ let measurements = concurrentMeasurements(candidates.map { $0.path })var itemsByTarget = [Int: [ScanItem]](minimumCapacity: targets.count)- for (i, c) in candidates.enumerated() where sizes[i] >= minSize {- let item = ScanItem(path: c.path, sizeBytes: sizes[i],+ for (i, c) in candidates.enumerated()+ where measurements[i].status == .complete && measurements[i].bytes >= minSize {+ let item = ScanItem(path: c.path, sizeBytes: measurements[i].bytes,modified: DirSizer.modified(of: c.path),selected: targets[c.target].selectedByDefault)itemsByTarget[c.target, default: []].append(item)@@ -44,25 +50,54 @@ enum CategoryScanner {private static func passesPreFilter(_ path: String, ignore: IgnoreStore) -> Bool {let fm = FileManager.defaultguard fm.fileExists(atPath: path) else { return false }- if let type = (try? fm.attributesOfItem(atPath: path)[.type]) as? FileAttributeType, type == .typeSymbolicLink {- return false- }- if Safety.isProviderOwned(path) { return false }- if ignore.isIgnored(path) { return false }+ if Safety.hasSymlinkComponent(path) { return false }+ if Safety.isCloudOrDataless(path) { return false }+ if Safety.ignoredPathProtectsCandidate(path, ignore: ignore) { return false }return true}static func concurrentSizes(_ paths: [String]) -> [Int64] {+ concurrentMeasurements(paths).map(\.bytes)+ }++ static func concurrentMeasurements(_ paths: [String]) -> [DirSizer.Measurement] {guard !paths.isEmpty else { return [] }- var out = [Int64](repeating: 0, count: paths.count)+ var out = [DirSizer.Measurement](+ repeating: DirSizer.Measurement(bytes: 0, status: .unavailable, skippedEntries: 1),+ count: paths.count+ )out.withUnsafeMutableBufferPointer { buf inDispatchQueue.concurrentPerform(iterations: paths.count) { i in- buf[i] = DirSizer.size(of: paths[i])+ buf[i] = DirSizer.measure(of: paths[i])}}return out}+ static func uniqueCandidates(_ candidates: [(target: Int, path: String)]) -> [(target: Int, path: String)] {+ var seenPaths: Set<String> = []+ var seenIdentities: Set<FileIdentity> = []+ var accepted: [(target: Int, path: String, canonical: String)] = []+ let ordered = candidates.enumerated().sorted {+ if $0.element.path.count != $1.element.path.count {+ return $0.element.path.count < $1.element.path.count+ }+ return $0.offset < $1.offset+ }.map(\.element)+ for candidate in ordered {+ let canonical = URL(fileURLWithPath: candidate.path).resolvingSymlinksInPath().standardizedFileURL.path+ guard !accepted.contains(where: {+ canonical == $0.canonical || canonical.hasPrefix($0.canonical + "/")+ }) else { continue }+ guard seenPaths.insert(canonical).inserted else { continue }+ if let identity = Safety.fileIdentity(at: canonical), !seenIdentities.insert(identity).inserted {+ continue+ }+ accepted.append((candidate.target, candidate.path, canonical))+ }+ return accepted.map { ($0.target, $0.path) }+ }+private static func scanTrash(ignore: IgnoreStore) -> [ToolGroup] {let fm = FileManager.defaultvar roots = ["\(Safety.home)/.Trash"]@@ -72,12 +107,15 @@ enum CategoryScanner {}var groups: [ToolGroup] = []- for root in roots where !Safety.isSymlink(root) {+ for root in roots where !Safety.hasSymlinkComponent(root) && !Safety.isCloudOrDataless(root) {guard let children = try? fm.contentsOfDirectory(atPath: root), !children.isEmpty else { continue }let paths = children.map { "\(root)/\($0)" }.filter { passesPreFilter($0, ignore: ignore) }- let sizes = concurrentSizes(paths)- let items = zip(paths, sizes).compactMap { (path, size) -> ScanItem? in- size >= minSize ? ScanItem(path: path, sizeBytes: size, modified: DirSizer.modified(of: path)) : nil+ let unique = uniqueCandidates(paths.map { (target: 0, path: $0) })+ let measurements = concurrentMeasurements(unique.map(\.path))+ let items = zip(unique.map(\.path), measurements).compactMap { (path, measurement) -> ScanItem? in+ measurement.status == .complete && measurement.bytes >= minSize+ ? ScanItem(path: path, sizeBytes: measurement.bytes, modified: DirSizer.modified(of: path))+ : nil}if !items.isEmpty {let label = root.hasPrefix("/Volumes/")diff --git a/cli/Sources/puremac/Core/Cleaner.swift b/cli/Sources/puremac/Core/Cleaner.swiftindex 251c2c5..6c12604 100644--- a/cli/Sources/puremac/Core/Cleaner.swift+++ b/cli/Sources/puremac/Core/Cleaner.swift@@ -5,7 +5,7 @@ struct CleanOutcome {var freedBytes: Int64 = 0var skipped: [(path: String, reason: String)] = []var failed: [(path: String, error: String)] = []- var hadFailures: Bool { !failed.isEmpty }+ var hadFailures: Bool { !failed.isEmpty || !skipped.isEmpty }}enum Cleaner {@@ -13,7 +13,7 @@ enum Cleaner {var out = CleanOutcome()let fm = FileManager.defaultfor item in items {- if Safety.isSymlink(item.path) || parentHasSymlink(item.path) {+ if Safety.hasSymlinkComponent(item.path) {out.skipped.append((item.path, "symlink"))continue}@@ -22,19 +22,38 @@ enum Cleaner {out.skipped.append((item.path, verdict.reason ?? "protected"))continue}+ guard let expectedIdentity = item.identity,+ Safety.fileIdentity(at: item.path) == expectedIdentity else {+ out.skipped.append((item.path, "changed since scan"))+ continue+ }+ let measurement = DirSizer.measure(of: item.path)+ guard measurement.status == .complete else {+ out.skipped.append((item.path, "could not measure safely"))+ continue+ }if dryRun {out.removed += 1- out.freedBytes += item.sizeBytes+ out.freedBytes = adding(measurement.bytes, to: out.freedBytes)continue}- if Safety.isSymlink(item.path) || parentHasSymlink(item.path) {+ if Safety.hasSymlinkComponent(item.path) {out.skipped.append((item.path, "became a symlink"))continue}+ guard Safety.fileIdentity(at: item.path) == expectedIdentity else {+ out.skipped.append((item.path, "changed since scan"))+ continue+ }do {try fm.removeItem(atPath: item.path)- out.removed += 1- out.freedBytes += item.sizeBytes+ let survivingIdentity = Safety.fileIdentity(at: item.path)+ if survivingIdentity == expectedIdentity {+ out.failed.append((item.path, "item survived removal"))+ } else {+ out.removed += 1+ out.freedBytes = adding(measurement.bytes, to: out.freedBytes)+ }} catch {let ns = error as NSErrorlet hint = (ns.code == NSFileWriteNoPermissionError || ns.code == NSFileReadNoPermissionError)@@ -55,4 +74,9 @@ enum Cleaner {}return false}++ private static func adding(_ bytes: Int64, to total: Int64) -> Int64 {+ let (sum, overflow) = total.addingReportingOverflow(bytes)+ return overflow ? .max : sum+ }}diff --git a/cli/Sources/puremac/Core/InteractiveReview.swift b/cli/Sources/puremac/Core/InteractiveReview.swiftnew file mode 100644index 0000000..65c3c21--- /dev/null+++ b/cli/Sources/puremac/Core/InteractiveReview.swift@@ -0,0 +1,447 @@+import Foundation++struct ReviewAddress: Hashable {+ let category: Int+ let group: Int+ let item: Int+}++enum ReviewDisplayRow {+ case category(Int)+ case group(category: Int, group: Int)+ case item(ReviewAddress)+}++struct InteractiveReviewModel {+ var categories: [CategoryScan]+ var query = ""+ var isSearching = false+ var isReviewing = false+ var status = ""+ var pathOffset = 0+ private(set) var focus = 0+ private(set) var reviewFocus = 0++ init(categories: [CategoryScan]) {+ self.categories = categories.map { category in+ var copy = category+ copy.groups = copy.groups.map { group in+ var groupCopy = group+ groupCopy.items = groupCopy.items.map { item in+ var itemCopy = item+ itemCopy.selected = false+ return itemCopy+ }+ return groupCopy+ }+ return copy+ }+ }++ var matchingAddresses: [ReviewAddress] {+ let needle = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ var addresses: [ReviewAddress] = []+ for categoryIndex in categories.indices {+ let category = categories[categoryIndex]+ for groupIndex in category.groups.indices {+ let group = category.groups[groupIndex]+ for itemIndex in group.items.indices {+ let item = group.items[itemIndex]+ let searchable = "\(category.title) \(group.tool) \(item.path)".lowercased()+ if needle.isEmpty || searchable.contains(needle) {+ addresses.append(+ ReviewAddress(+ category: categoryIndex,+ group: groupIndex,+ item: itemIndex+ )+ )+ }+ }+ }+ }+ return addresses+ }++ var selectedAddresses: [ReviewAddress] {+ allAddresses.filter { item(at: $0).selected }+ }++ var selectedCount: Int {+ selectedAddresses.count+ }++ var selectedBytes: Int64 {+ selectedAddresses.reduce(Int64(0)) { $0 + item(at: $1).sizeBytes }+ }++ var allBytes: Int64 {+ categories.reduce(Int64(0)) { $0 + $1.allBytes }+ }++ var focusedAddress: ReviewAddress? {+ let addresses = isReviewing ? selectedAddresses : matchingAddresses+ let index = isReviewing ? reviewFocus : focus+ guard addresses.indices.contains(index) else { return nil }+ return addresses[index]+ }++ mutating func move(_ delta: Int) {+ let count = isReviewing ? selectedAddresses.count : matchingAddresses.count+ guard count > 0 else { return }+ if isReviewing {+ reviewFocus = min(count - 1, max(0, reviewFocus + delta))+ } else {+ focus = min(count - 1, max(0, focus + delta))+ }+ pathOffset = 0+ }++ mutating func moveToStart() {+ if isReviewing {+ reviewFocus = 0+ } else {+ focus = 0+ }+ pathOffset = 0+ }++ mutating func moveToEnd() {+ if isReviewing {+ reviewFocus = max(0, selectedAddresses.count - 1)+ } else {+ focus = max(0, matchingAddresses.count - 1)+ }+ pathOffset = 0+ }++ mutating func toggleFocused() {+ guard !isReviewing, let address = focusedAddress else { return }+ categories[address.category].groups[address.group].items[address.item].selected.toggle()+ }++ mutating func selectAllMatching() {+ for address in matchingAddresses {+ categories[address.category].groups[address.group].items[address.item].selected = true+ }+ status = matchingAddresses.isEmpty ? "No matching items" : "Selected visible items"+ }++ mutating func selectNone() {+ for address in allAddresses {+ categories[address.category].groups[address.group].items[address.item].selected = false+ }+ reviewFocus = 0+ status = "Selection cleared"+ }++ mutating func updateQuery(_ value: String) {+ query = value+ focus = 0+ pathOffset = 0+ status = ""+ }++ mutating func beginReview() -> Bool {+ guard selectedCount > 0 else {+ status = "Select at least one item to continue"+ return false+ }+ isReviewing = true+ reviewFocus = 0+ pathOffset = 0+ status = ""+ return true+ }++ mutating func endReview() {+ isReviewing = false+ pathOffset = 0+ status = ""+ }++ func displayRows(reviewing: Bool) -> [ReviewDisplayRow] {+ let addresses = reviewing ? selectedAddresses : matchingAddresses+ var rows: [ReviewDisplayRow] = []+ var lastCategory: Int?+ var lastGroup: Int?+ for address in addresses {+ if lastCategory != address.category {+ rows.append(.category(address.category))+ lastCategory = address.category+ lastGroup = nil+ }+ if lastGroup != address.group {+ rows.append(.group(category: address.category, group: address.group))+ lastGroup = address.group+ }+ rows.append(.item(address))+ }+ return rows+ }++ func item(at address: ReviewAddress) -> ScanItem {+ categories[address.category].groups[address.group].items[address.item]+ }++ func selectedResult() -> [CategoryScan] {+ categories+ }++ private var allAddresses: [ReviewAddress] {+ var addresses: [ReviewAddress] = []+ for categoryIndex in categories.indices {+ for groupIndex in categories[categoryIndex].groups.indices {+ for itemIndex in categories[categoryIndex].groups[groupIndex].items.indices {+ addresses.append(+ ReviewAddress(+ category: categoryIndex,+ group: groupIndex,+ item: itemIndex+ )+ )+ }+ }+ }+ return addresses+ }+}++enum InteractiveReview {+ static func select(_ categories: [CategoryScan], title: String) throws -> [CategoryScan]? {+ let session = try TerminalSession()+ defer { session.close() }++ var model = InteractiveReviewModel(categories: categories)+ while true {+ session.draw(lines: render(model: model, title: title, width: session.width, height: session.height))+ let key = session.readKey()++ if model.isSearching {+ switch key {+ case .enter:+ model.isSearching = false+ case .escape:+ model.isSearching = false+ model.updateQuery("")+ case .backspace, .delete:+ if !model.query.isEmpty {+ model.updateQuery(String(model.query.dropLast()))+ }+ case .space:+ model.updateQuery(model.query + " ")+ case .character(let character):+ if !character.isASCIIControl {+ model.updateQuery(model.query + String(character))+ }+ default:+ break+ }+ continue+ }++ switch key {+ case .up:+ model.move(-1)+ case .down:+ model.move(1)+ case .pageUp:+ model.move(-max(1, session.height / 2))+ case .pageDown:+ model.move(max(1, session.height / 2))+ case .home:+ model.moveToStart()+ case .end:+ model.moveToEnd()+ case .left:+ model.pathOffset = max(0, model.pathOffset - max(8, session.width / 3))+ case .right:+ model.pathOffset += max(8, session.width / 3)+ case .space:+ model.toggleFocused()+ case .enter:+ if model.isReviewing {+ return model.selectedResult()+ }+ _ = model.beginReview()+ case .escape:+ if model.isReviewing {+ model.endReview()+ } else {+ return nil+ }+ case .character(let character):+ switch character.lowercasedString {+ case "a":+ if !model.isReviewing { model.selectAllMatching() }+ case "n":+ if !model.isReviewing { model.selectNone() }+ case "/":+ if !model.isReviewing {+ model.isSearching = true+ model.status = ""+ }+ case "q":+ return nil+ default:+ break+ }+ default:+ break+ }+ }+ }++ static func render(+ model: InteractiveReviewModel,+ title: String,+ width: Int,+ height: Int+ ) -> [String] {+ let safeWidth = max(1, width)+ let safeHeight = max(1, height)+ if safeWidth < 40 || safeHeight < 12 {+ return compactScreen(width: safeWidth, height: safeHeight)+ }+ let titleText = Term.truncate(title, to: safeWidth - 2)+ let selection = "\(model.selectedCount) selected · \(ByteCount.human(model.selectedBytes))"+ let found = "\(model.matchingAddresses.count) shown · \(ByteCount.human(model.allBytes))"+ var lines = [+ Term.dim("PUREMAC / \(model.isReviewing ? "FINAL REVIEW" : "SELECT ITEMS")"),+ Term.bold(Term.cyan(titleText)),+ statusLine(left: found, right: selection, width: safeWidth)+ ]++ if model.isSearching {+ let query = Term.truncate(model.query, to: max(1, safeWidth - 10))+ lines.append(Term.cyan("Search ") + query + Term.inverse(" "))+ } else if !model.status.isEmpty {+ lines.append(Term.yellow(Term.truncate(model.status, to: safeWidth)))+ } else if model.query.isEmpty {+ lines.append("")+ } else {+ lines.append(Term.dim("Filter ") + Term.truncate(model.query, to: max(1, safeWidth - 9)))+ }++ let footerHeight = 5+ let bodyHeight = max(3, safeHeight - lines.count - footerHeight)+ let rows = model.displayRows(reviewing: model.isReviewing)+ let focusedAddress = model.focusedAddress+ let focusedRow = rows.firstIndex { row in+ if case .item(let address) = row { return address == focusedAddress }+ return false+ } ?? 0+ let start = max(0, min(max(0, rows.count - bodyHeight), focusedRow - bodyHeight / 2))+ let visibleRows = rows.dropFirst(start).prefix(bodyHeight)++ for row in visibleRows {+ switch row {+ case .category(let categoryIndex):+ let category = model.categories[categoryIndex]+ let label = Term.truncate(Term.sanitize(category.title).uppercased(), to: safeWidth - 4)+ lines.append(" " + Term.bold(Term.cyan(label)))+ case .group(let categoryIndex, let groupIndex):+ let group = model.categories[categoryIndex].groups[groupIndex]+ let suffix = "\(group.items.count) \(group.items.count == 1 ? "item" : "items")"+ let available = max(1, safeWidth - 8 - suffix.count)+ lines.append(" " + Term.dim(Term.pad(Term.truncate(group.tool, to: available), to: available) + suffix))+ case .item(let address):+ let item = model.item(at: address)+ let focused = address == focusedAddress+ let mark = item.selected ? Term.cyan("●") : Term.dim("○")+ let pointer = focused ? Term.cyan("›") : " "+ let size = Term.pad(ByteCount.human(item.sizeBytes), to: 10)+ let pathWidth = max(6, safeWidth - 17)+ let path = Term.truncate(Render.shorten(item.path), to: pathWidth, middle: true)+ let content = "\(pointer) \(mark) \(size) \(path)"+ lines.append(focused ? Term.inverse(content) : content)+ }+ }++ while lines.count < safeHeight - footerHeight {+ lines.append("")+ }++ let divider = String(repeating: "─", count: safeWidth)+ lines.append(Term.dim(divider))+ lines.append(focusedPathLine(model: model, width: safeWidth))+ if model.isReviewing {+ lines.append(Term.dim("↑↓ scroll ←→ path"))+ lines.append(Term.dim("Enter confirm Esc edit"))+ lines.append(Term.yellow("q cancel command confirmation follows"))+ } else {+ lines.append(Term.dim("↑↓ move ←→ path Space toggle"))+ lines.append(Term.dim("A all N none / search"))+ lines.append(Term.dim("Enter review Esc/q cancel"))+ }+ return Array(lines.prefix(safeHeight))+ }++ private static func compactScreen(width: Int, height: Int) -> [String] {+ let lines = [+ Term.bold(Term.cyan(Term.truncate("PureMac", to: width))),+ Term.truncate("Terminal too small", to: width),+ Term.dim(Term.truncate("Resize to at least 40 x 12", to: width)),+ "",+ Term.dim(Term.truncate("Esc/q cancel", to: width))+ ]+ return Array(lines.prefix(height))+ }++ static func statusLine(left: String, right: String, width: Int) -> String {+ let available = max(1, width - 2)+ let leftWidth = Term.displayWidth(left)+ let rightWidth = Term.displayWidth(right)+ if leftWidth + rightWidth <= available {+ return Term.pad(left, to: available - rightWidth) + " " + Term.bold(right)+ }++ let rightBudget = min(rightWidth, max(1, available / 2))+ let leftBudget = max(1, available - rightBudget)+ let clippedLeft = Term.truncate(left, to: leftBudget)+ let clippedRight = Term.truncate(right, to: rightBudget)+ return Term.pad(clippedLeft, to: leftBudget) + " " + Term.bold(clippedRight)+ }++ private static func focusedPathLine(model: InteractiveReviewModel, width: Int) -> String {+ guard let address = model.focusedAddress else {+ return Term.dim("Path No matching item")+ }+ let path = Render.shorten(model.item(at: address).path)+ let available = max(1, width - 6)+ let window = horizontalWindow(path, offset: model.pathOffset, width: available)+ return Term.dim("Path ") + window+ }++ static func horizontalWindow(_ value: String, offset: Int, width: Int) -> String {+ let safe = Term.sanitize(value)+ let characters = Array(safe)+ let start = min(max(0, offset), characters.count)+ let prefixMarker = start > 0 ? "‹" : ""+ var output = ""+ var used = Term.displayWidth(prefixMarker)+ var index = start++ while index < characters.count {+ let value = String(characters[index])+ let characterWidth = Term.displayWidth(value)+ let remainingMarker = index + 1 < characters.count ? 1 : 0+ guard used + characterWidth + remainingMarker <= width else { break }+ output.append(characters[index])+ used += characterWidth+ index += 1+ }+ let suffixMarker = index < characters.count ? "›" : ""+ return prefixMarker + output + suffixMarker+ }+}++private extension Character {+ var isASCIIControl: Bool {+ unicodeScalars.allSatisfy { $0.value < 0x20 || $0.value == 0x7F }+ }++ var lowercasedString: String {+ String(self).lowercased()+ }+}diff --git a/cli/Sources/puremac/Core/Purger.swift b/cli/Sources/puremac/Core/Purger.swiftindex 0cae5f7..fac3a8f 100644--- a/cli/Sources/puremac/Core/Purger.swift+++ b/cli/Sources/puremac/Core/Purger.swift@@ -24,8 +24,7 @@ enum Purger {var byProject: [String: [ScanItem]] = [:]var order: [String] = []- for root in roots where Safety.isValidScanRoot(root).ok {- let rootURL = URL(fileURLWithPath: root).resolvingSymlinksInPath()+ for rootURL in scanRoots(roots) {guard let en = fm.enumerator(at: rootURL,includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],options: [.skipsPackageDescendants],@@ -37,16 +36,21 @@ enum Purger {if vals?.isSymbolicLink == true { en.skipDescendants(); continue }guard vals?.isDirectory == true else { continue }if en.level > 8 { en.skipDescendants(); continue }- if Safety.isProviderOwned(url.path) || ignore.isIgnored(url.path) { en.skipDescendants(); continue }+ if Safety.isCloudOrDataless(url.path) || Safety.isPathIgnored(url.path, ignore: ignore) {+ en.skipDescendants()+ continue+ }if isArtifact(name) {en.skipDescendants()- let size = DirSizer.size(of: url.path)- guard size >= CategoryScanner.minSize else { continue }+ if Safety.ignoredPathProtectsCandidate(url.path, ignore: ignore) { continue }+ let measurement = DirSizer.measure(of: url.path)+ guard measurement.status == .complete,+ measurement.bytes >= CategoryScanner.minSize else { continue }let mod = DirSizer.modified(of: url.path)let old = (mod ?? .distantFuture) < cutofflet project = projectLabel(url, level: en.level, root: rootURL)- let item = ScanItem(path: url.path, sizeBytes: size, modified: mod, selected: old)+ let item = ScanItem(path: url.path, sizeBytes: measurement.bytes, modified: mod, selected: old)byProject[project, default: []].append(item)if !order.contains(project) { order.append(project) }}@@ -59,6 +63,20 @@ enum Purger {return CategoryScan(id: "purge", title: "Project Artifacts", groups: groups)}+ static func scanRoots(_ roots: [String]) -> [URL] {+ let candidates = roots.compactMap { root -> URL? in+ guard Safety.isValidScanRoot(root).ok else { return nil }+ return URL(fileURLWithPath: root).resolvingSymlinksInPath().standardizedFileURL+ }.sorted { $0.path.count < $1.path.count }+ var accepted: [URL] = []+ for candidate in candidates where !accepted.contains(where: {+ candidate.path == $0.path || candidate.path.hasPrefix($0.path + "/")+ }) {+ accepted.append(candidate)+ }+ return accepted+ }+private static func projectLabel(_ url: URL, level: Int, root: URL) -> String {guard level > 1 else { return url.lastPathComponent }var u = urldiff --git a/cli/Sources/puremac/Core/Render.swift b/cli/Sources/puremac/Core/Render.swiftindex b0e8394..0d4a6ca 100644--- a/cli/Sources/puremac/Core/Render.swift+++ b/cli/Sources/puremac/Core/Render.swift@@ -1,97 +1,135 @@+import Darwinimport Foundationenum Render {static let rule = String(repeating: "─", count: 60)- static func scanResults(_ cats: [CategoryScan]) {- let grand = cats.reduce(Int64(0)) { $0 + $1.allBytes }+ static func scanResults(_ categories: [CategoryScan]) {+ let total = categories.reduce(Int64(0)) { $0 + $1.allBytes }+ let itemCount = categories.flatMap(\.groups).flatMap(\.items).countprint("")- print(Term.bold("\(ByteCount.human(grand)) of removable items found"))- for cat in cats where !cat.groups.isEmpty {+ print(Term.bold("Scan complete"))+ print(+ Term.bold(ByteCount.human(total))+ + Term.dim(" across \(itemCount) item\(itemCount == 1 ? "" : "s")")+ )++ for category in categories where !category.groups.isEmpty {print("")- print(" \(Term.cyan(cat.title)) \(Term.dim(ByteCount.human(cat.allBytes)))")- for group in cat.groups {+ print(+ Term.cyan(Term.bold(Term.sanitize(category.title)))+ + Term.dim(" \(ByteCount.human(category.allBytes))")+ )+ for group in category.groups {+ print(+ " " + Term.bold(Term.sanitize(group.tool))+ + Term.dim(" \(group.items.count) item\(group.items.count == 1 ? "" : "s")")+ )for item in group.items {- let mark = item.selected ? Term.green("✓") : Term.dim("·")- print(" \(mark) \(sizeCol(item.sizeBytes)) \(pad(group.tool, 22)) \(Term.dim(shorten(item.path)))")+ let mark = item.selected ? Term.cyan("●") : Term.dim("○")+ let path = displayedPath(item.path, available: max(12, outputWidth - 18))+ print(" \(mark) \(sizeCol(item.sizeBytes)) \(path)")}}}}- static func selectionLine(_ cats: [CategoryScan]) {- let items = cats.flatMap { $0.selectedItems }+ static func selectionLine(_ categories: [CategoryScan]) {+ let items = categories.flatMap { $0.selectedItems }let total = items.reduce(Int64(0)) { $0 + $1.sizeBytes }print("")- print(Term.bold("\(items.count) items selected (\(ByteCount.human(total)))"))+ print(+ Term.bold("\(items.count) selected")+ + Term.dim(" \(ByteCount.human(total))")+ )}- static func deletionReview(_ cats: [CategoryScan]) {- let selected = cats.flatMap { $0.selectedItems }+ static func deletionReview(_ categories: [CategoryScan]) {+ let selected = categories.flatMap { $0.selectedItems }let total = selected.reduce(Int64(0)) { $0 + $1.sizeBytes }print("")- print(Term.yellow(rule))- print(" " + Term.bold("The following will be permanently deleted:"))- print(Term.yellow(rule))- for cat in cats {- let catSelected = cat.selectedItems- guard !catSelected.isEmpty else { continue }- print(" " + Term.cyan(cat.title))- for group in cat.groups {+ print(Term.yellow(Term.bold("Permanent deletion review")))+ print(Term.dim(String(repeating: "─", count: min(72, outputWidth))))++ for category in categories {+ let selectedInCategory = category.selectedItems+ guard !selectedInCategory.isEmpty else { continue }+ print(+ Term.cyan(Term.sanitize(category.title))+ + Term.dim(" \(ByteCount.human(selectedInCategory.reduce(0) { $0 + $1.sizeBytes }))")+ )+ for group in category.groups {for item in group.items where item.selected {- print(" \(sizeCol(item.sizeBytes)) \(pad(group.tool, 20)) \(shorten(item.path))")+ print(" \(sizeCol(item.sizeBytes)) \(Term.sanitize(group.tool))")+ print(" \(Term.sanitize(item.path))")}}}- print(Term.yellow(rule))- print(" " + Term.bold("Total: \(ByteCount.human(total))") + Term.dim(" · \(selected.count) items"))- print(Term.yellow(rule))++ print(Term.dim(String(repeating: "─", count: min(72, outputWidth))))+ print(+ Term.bold(ByteCount.human(total))+ + Term.dim(" \(selected.count) item\(selected.count == 1 ? "" : "s")")+ )}- static func cleanupSummary(_ out: CleanOutcome, dryRun: Bool) {+ static func cleanupSummary(_ outcome: CleanOutcome, dryRun: Bool) {print("")- let freed = ByteCount.human(out.freedBytes)if dryRun {- print(Term.bold("Dry run — nothing was deleted."))- print(" " + Term.bold(freed) + " reclaimable across \(out.removed) items")+ print(Term.bold("Dry run complete"))+ print(+ Term.cyan(ByteCount.human(outcome.freedBytes))+ + Term.dim(" reclaimable across \(outcome.removed) item\(outcome.removed == 1 ? "" : "s")")+ )+ print(Term.dim("Nothing was deleted."))} else {- box(title: freed, subtitle: "cleaned!")- print(" " + Term.bold("\(out.removed)") + " items removed")+ print(Term.green(Term.bold("Cleanup complete")))+ print(+ Term.bold(ByteCount.human(outcome.freedBytes))+ + Term.dim(" removed across \(outcome.removed) item\(outcome.removed == 1 ? "" : "s")")+ )}- if !out.skipped.isEmpty {- print(" " + Term.yellow("\(out.skipped.count) skipped") + Term.dim(" (protected/ignored)"))++ if !outcome.skipped.isEmpty {+ print(Term.yellow("\(outcome.skipped.count) skipped") + Term.dim(" protected or ignored"))}- if !out.failed.isEmpty {- print(" " + Term.red("\(out.failed.count) failed"))- for f in out.failed.prefix(10) { Term.err(" ! \(shorten(f.path)) — \(f.error)") }+ if !outcome.failed.isEmpty {+ print(Term.red("\(outcome.failed.count) failed"))+ for failure in outcome.failed.prefix(10) {+ Term.err(" ! \(Term.sanitize(failure.path))")+ Term.err(" \(Term.sanitize(failure.error))")+ }}print("")}- private static func box(title: String, subtitle: String) {- let width = max(title.count, subtitle.count) + 6- let top = "┌" + String(repeating: "─", count: width) + "┐"- let bot = "└" + String(repeating: "─", count: width) + "┘"- print("")- print(" " + Term.green(top))- print(" " + Term.green("│") + center(title, width) + Term.green("│"))- print(" " + Term.green("│") + center(subtitle, width) + Term.green("│"))- print(" " + Term.green(bot))- print("")+ static func sizeCol(_ bytes: Int64) -> String {+ pad(ByteCount.human(bytes), 10)}- private static func center(_ s: String, _ width: Int) -> String {- let pad = max(0, width - s.count)- let left = pad / 2, right = pad - left- return String(repeating: " ", count: left) + Term.bold(s) + String(repeating: " ", count: right)+ static func pad(_ string: String, _ width: Int) -> String {+ Term.pad(string, to: width)}- static func sizeCol(_ bytes: Int64) -> String { pad(ByteCount.human(bytes), 10) }- static func pad(_ s: String, _ n: Int) -> String { s.count >= n ? s : s + String(repeating: " ", count: n - s.count) }-static func shorten(_ path: String) -> String {+ let safePath = Term.sanitize(path)let home = FileManager.default.homeDirectoryForCurrentUser.path- if path == home { return "~" }- return path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path+ if safePath == home { return "~" }+ return safePath.hasPrefix(home + "/")+ ? "~" + safePath.dropFirst(home.count)+ : safePath+ }++ private static var outputWidth: Int {+ guard isatty(STDOUT_FILENO) == 1 else { return 100 }+ var window = winsize()+ guard ioctl(STDOUT_FILENO, TIOCGWINSZ, &window) == 0 else { return 100 }+ return max(1, Int(window.ws_col))+ }++ private static func displayedPath(_ path: String, available: Int) -> String {+ return isatty(STDOUT_FILENO) == 1+ ? Term.truncate(shorten(path), to: available, middle: true)+ : Term.sanitize(path)}}diff --git a/cli/Sources/puremac/Core/Safety.swift b/cli/Sources/puremac/Core/Safety.swiftindex c99a06f..5a78765 100644--- a/cli/Sources/puremac/Core/Safety.swift+++ b/cli/Sources/puremac/Core/Safety.swift@@ -1,4 +1,5 @@import Foundation+import Darwinenum Safety {static let home = FileManager.default.homeDirectoryForCurrentUser.path@@ -33,6 +34,17 @@ enum Safety {return type == .typeSymbolicLink}+ static func hasSymlinkComponent(_ path: String) -> Bool {+ var url = URL(fileURLWithPath: (path as NSString).standardizingPath)+ while url.path != "/" {+ if isSymlink(url.path), url.path != "/tmp", url.path != "/var" { return true }+ let parent = url.deletingLastPathComponent()+ if parent.path == url.path { break }+ url = parent+ }+ return false+ }+static func isProviderOwned(_ path: String) -> Bool {let candidates = [(path as NSString).standardizingPath,@@ -45,39 +57,130 @@ enum Safety {return false}+ static func isCloudOrDataless(_ path: String) -> Bool {+ if isProviderOwned(path) { return true }+ var info = stat()+ let status = path.withCString { lstat($0, &info) }+ if status == 0, info.st_flags & 0x40000000 != 0 { return true }+ let values = try? URL(fileURLWithPath: path).resourceValues(+ forKeys: [.isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey]+ )+ guard values?.isUbiquitousItem == true else { return false }+ let downloadingStatus = values?.ubiquitousItemDownloadingStatus+ return downloadingStatus != .current && downloadingStatus != .downloaded+ }+static var deniedUserRoots: [String] {[".ssh", ".aws", ".gnupg", ".gpg", ".kube", ".docker", ".claude", ".config", ".cargo", ".rustup",".gem", ".nvm", ".pyenv", ".rbenv", ".ollama", ".lmstudio"].map { "\(home)/\($0)" }}static func isCredentialRoot(_ path: String) -> Bool {- for root in deniedUserRoots where path == root { return true }+ let allowed = [+ "\(home)/.docker/cli-plugins/.cache",+ "\(home)/.docker/buildx/cache",+ "\(home)/.cargo/registry/cache",+ "\(home)/.cargo/registry/index",+ "\(home)/.cargo/git/db",+ "\(home)/.cargo/git/checkouts",+ "\(home)/.ollama/logs",+ "\(home)/.lmstudio/server-logs",+ ]+ if allowed.contains(where: { path == $0 || path.hasPrefix($0 + "/") }) { return false }+ for root in deniedUserRoots where path == root || path.hasPrefix(root + "/") { return true }+ return false+ }++ static func ignoredPathProtectsCandidate(_ path: String, ignore: IgnoreStore) -> Bool {+ let candidates = canonicalForms(path)+ for ignored in ignore.roots where ignored.hasPrefix("/") {+ for root in canonicalForms(ignored) {+ if candidates.contains(where: {+ $0 == root || $0.hasPrefix(root + "/") || root.hasPrefix($0 + "/")+ }) {+ return true+ }+ }+ }+ return false+ }++ static func isPathIgnored(_ path: String, ignore: IgnoreStore) -> Bool {+ let candidates = canonicalForms(path)+ for ignored in ignore.roots where ignored.hasPrefix("/") {+ for root in canonicalForms(ignored) where candidates.contains(where: {+ $0 == root || $0.hasPrefix(root + "/")+ }) {+ return true+ }+ }return false}+ static func fileIdentity(at path: String) -> FileIdentity? {+ guard let attrs = try? FileManager.default.attributesOfItem(atPath: path),+ let device = (attrs[.systemNumber] as? NSNumber)?.uint64Value,+ let inode = (attrs[.systemFileNumber] as? NSNumber)?.uint64Value else { return nil }+ return FileIdentity(device: device, inode: inode)+ }+static func canRemove(_ path: String, ignore: IgnoreStore) -> (ok: Bool, reason: String?) {let std = (path as NSString).standardizingPathlet resolved = URL(fileURLWithPath: std).resolvingSymlinksInPath().path- if std.isEmpty || std == "/" || resolved == "/" { return (false, "root path") }+ if std.isEmpty || !std.hasPrefix("/") || std == "/" || resolved == "/" { return (false, "root path") }+ if hasSymlinkComponent(std) { return (false, "symlink") }if criticalRoots.contains(std) || criticalRoots.contains(resolved) { return (false, "protected root") }+ let deniedTrees = ["/System", "/Library", "/Applications", "/usr", "/bin", "/sbin", "/etc", "/private/etc", "/cores"]+ if deniedTrees.contains(where: { resolved == $0 || resolved.hasPrefix($0 + "/") }) {+ return (false, "protected system path")+ }+ if resolved.hasPrefix("/Users/"), resolved != home, !resolved.hasPrefix(home + "/") {+ return (false, "another user's files")+ }if isCredentialRoot(std) || isCredentialRoot(resolved) { return (false, "config/credentials dir") }- if isProviderOwned(std) { return (false, "cloud/provider state") }- if ignore.isIgnored(std) || ignore.isIgnored(resolved) { return (false, "ignored") }+ if isCloudOrDataless(std) { return (false, "cloud/provider state") }+ if ignoredPathProtectsCandidate(std, ignore: ignore) { return (false, "ignored") }if !FileManager.default.fileExists(atPath: std) { return (false, "missing") }return (true, nil)}- static func isValidScanRoot(_ path: String) -> (ok: Bool, reason: String?) {- let expanded = (path as NSString).expandingTildeInPath- let resolved = URL(fileURLWithPath: expanded).resolvingSymlinksInPath().path+ static func isValidScanRoot(+ _ path: String,+ currentDirectory: String = FileManager.default.currentDirectoryPath+ ) -> (ok: Bool, reason: String?) {+ let absolute = absolutePath(path, currentDirectory: currentDirectory)+ guard !hasSymlinkComponent(absolute) else {+ return (false, "scan root must not contain symbolic links")+ }+ let resolved = URL(fileURLWithPath: absolute).resolvingSymlinksInPath().pathlet std = (resolved as NSString).standardizingPathvar systemRoots: Set<String> = ["/", "/System", "/Library", "/Applications", "/Users", "/private", "/usr", "/bin", "/sbin", "/etc", "/var", "/opt", "/cores", "/Volumes", home]for dir in ["Library", "Pictures", "Music", "Movies", "Public"] { systemRoots.insert("\(home)/\(dir)") }if systemRoots.contains(std) { return (false, "'\(path)' is a system location — scan a project folder instead") }+ let deniedTrees = ["/System", "/Library", "/Applications", "/usr", "/bin", "/sbin", "/etc", "/private/etc", "/cores", "\(home)/Library", "\(home)/Pictures", "\(home)/Music", "\(home)/Movies", "\(home)/Public"]+ if deniedTrees.contains(where: { std == $0 || std.hasPrefix($0 + "/") }) {+ return (false, "'\(path)' is a protected location — scan a project folder instead")+ }+ if isCloudOrDataless(std) { return (false, "cloud/provider folders are not scanned") }var isDir: ObjCBool = falseguard FileManager.default.fileExists(atPath: std, isDirectory: &isDir), isDir.boolValue else {return (false, "not a folder: \(path)")}return (true, nil)}++ static func absolutePath(+ _ path: String,+ currentDirectory: String = FileManager.default.currentDirectoryPath+ ) -> String {+ let expanded = (path as NSString).expandingTildeInPath+ let base = URL(fileURLWithPath: currentDirectory, isDirectory: true)+ return URL(fileURLWithPath: expanded, relativeTo: base).standardizedFileURL.path+ }++ private static func canonicalForms(_ path: String) -> [String] {+ let std = (path as NSString).standardizingPath+ let resolved = URL(fileURLWithPath: std).resolvingSymlinksInPath().path+ return std == resolved ? [std] : [std, resolved]+ }}diff --git a/cli/Sources/puremac/Core/Scanner.swift b/cli/Sources/puremac/Core/Scanner.swiftindex 3f132ce..3960411 100644--- a/cli/Sources/puremac/Core/Scanner.swift+++ b/cli/Sources/puremac/Core/Scanner.swift@@ -1,12 +1,56 @@import Foundation+struct FileIdentity: Hashable, Sendable {+ let device: UInt64+ let inode: UInt64+}+struct ScanItem: Codable {let path: Stringlet sizeBytes: Int64let modified: Date?+ let identity: FileIdentity?var selected: Bool = truevar human: String { ByteCount.human(sizeBytes) }++ init(+ path: String,+ sizeBytes: Int64,+ modified: Date?,+ identity: FileIdentity? = nil,+ selected: Bool = true+ ) {+ self.path = path+ self.sizeBytes = sizeBytes+ self.modified = modified+ self.identity = identity ?? Safety.fileIdentity(at: path)+ self.selected = selected+ }++ private enum CodingKeys: String, CodingKey {+ case path+ case sizeBytes+ case modified+ case selected+ }++ init(from decoder: Decoder) throws {+ let values = try decoder.container(keyedBy: CodingKeys.self)+ path = try values.decode(String.self, forKey: .path)+ sizeBytes = try values.decode(Int64.self, forKey: .sizeBytes)+ modified = try values.decodeIfPresent(Date.self, forKey: .modified)+ selected = try values.decodeIfPresent(Bool.self, forKey: .selected) ?? true+ identity = nil+ }++ func encode(to encoder: Encoder) throws {+ var values = encoder.container(keyedBy: CodingKeys.self)+ try values.encode(path, forKey: .path)+ try values.encode(sizeBytes, forKey: .sizeBytes)+ try values.encodeIfPresent(modified, forKey: .modified)+ try values.encode(selected, forKey: .selected)+ }}struct ToolGroup: Codable {@@ -27,38 +71,89 @@ struct CategoryScan: Codable {enum DirSizer {+ enum Status: String, Codable, Sendable {+ case complete+ case partial+ case unavailable+ case cloudOrDataless+ case symlink+ }++ struct Measurement: Codable, Sendable {+ let bytes: Int64+ let status: Status+ let skippedEntries: Int+ }+static func size(of path: String) -> Int64 {+ measure(of: path).bytes+ }++ static func measure(of path: String) -> Measurement {let fm = FileManager.default+ if Safety.hasSymlinkComponent(path) {+ return Measurement(bytes: 0, status: .symlink, skippedEntries: 1)+ }+ if Safety.isCloudOrDataless(path) {+ return Measurement(bytes: 0, status: .cloudOrDataless, skippedEntries: 1)+ }var isDir: ObjCBool = false- guard fm.fileExists(atPath: path, isDirectory: &isDir) else { return 0 }- if !isDir.boolValue { return fileSize(URL(fileURLWithPath: path)) }-- let r = Shell.run("/usr/bin/du", ["-sk", path])- if r.status == 0 {- let field = r.out.prefix { $0.isNumber }- if let kb = Int64(field) {- let (bytes, overflow) = kb.multipliedReportingOverflow(by: 1024)- return overflow ? .max : bytes+ guard fm.fileExists(atPath: path, isDirectory: &isDir) else {+ return Measurement(bytes: 0, status: .unavailable, skippedEntries: 1)+ }+ if !isDir.boolValue {+ guard let bytes = fileSize(URL(fileURLWithPath: path)) else {+ return Measurement(bytes: 0, status: .unavailable, skippedEntries: 1)}+ return Measurement(bytes: bytes, status: .complete, skippedEntries: 0)}return foundationSize(URL(fileURLWithPath: path))}- private static func foundationSize(_ url: URL) -> Int64 {+ private static func foundationSize(_ url: URL) -> Measurement {var total: Int64 = 0- let keys: [URLResourceKey] = [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey]+ var skipped = 0+ let keys: [URLResourceKey] = [+ .totalFileAllocatedSizeKey,+ .fileAllocatedSizeKey,+ .fileSizeKey,+ .isDirectoryKey,+ .isRegularFileKey,+ .isSymbolicLinkKey,+ .isUbiquitousItemKey,+ .ubiquitousItemDownloadingStatusKey,+ ]guard let en = FileManager.default.enumerator(at: url, includingPropertiesForKeys: keys,- options: [], errorHandler: { _, _ in true }) else { return 0 }- for case let item as URL in en { total += fileSize(item) }- return total+ options: [], errorHandler: { _, _ in+ skipped += 1+ return true+ }) else {+ return Measurement(bytes: 0, status: .unavailable, skippedEntries: 1)+ }+ for case let item as URL in en {+ let values = try? item.resourceValues(forKeys: Set(keys))+ if values?.isSymbolicLink == true {+ en.skipDescendants()+ continue+ }+ if Safety.isCloudOrDataless(item.path) {+ if values?.isDirectory == true { en.skipDescendants() }+ skipped += 1+ continue+ }+ guard values?.isRegularFile == true, let bytes = fileSize(item, values: values) else { continue }+ let (next, overflow) = total.addingReportingOverflow(bytes)+ total = overflow ? .max : next+ }+ return Measurement(bytes: total, status: skipped == 0 ? .complete : .partial, skippedEntries: skipped)}- private static func fileSize(_ url: URL) -> Int64 {- let vals = try? url.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey, .fileSizeKey])+ private static func fileSize(_ url: URL, values: URLResourceValues? = nil) -> Int64? {+ let vals = values ?? (try? url.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey, .fileSizeKey]))if let a = vals?.totalFileAllocatedSize { return Int64(a) }if let a = vals?.fileAllocatedSize { return Int64(a) }if let a = vals?.fileSize { return Int64(a) }- return 0+ return nil}static func modified(of path: String) -> Date? {diff --git a/cli/Sources/puremac/Core/Shell.swift b/cli/Sources/puremac/Core/Shell.swiftindex 0ad60c4..b08d5cc 100644--- a/cli/Sources/puremac/Core/Shell.swift+++ b/cli/Sources/puremac/Core/Shell.swift@@ -1,32 +1,134 @@+import Darwinimport Foundationenum Shell {- struct Result { let status: Int32; let out: String; let err: String }+ struct Result {+ let status: Int32+ let out: String+ let err: String+ }++ static let outputLimit = 1_048_576@discardableResult- static func run(_ launchPath: String, _ args: [String]) -> Result {+ static func run(+ _ launchPath: String,+ _ args: [String],+ timeout: TimeInterval = 15+ ) -> Result {guard FileManager.default.isExecutableFile(atPath: launchPath) else {return Result(status: 127, out: "", err: "not found: \(launchPath)")}- let p = Process()- p.executableURL = URL(fileURLWithPath: launchPath)- p.arguments = args- let outPipe = Pipe(), errPipe = Pipe()- p.standardOutput = outPipe- p.standardError = errPipe- do { try p.run() } catch {- return Result(status: 126, out: "", err: (error as NSError).localizedDescription)++ let process = Process()+ let outputPipe = Pipe()+ let errorPipe = Pipe()+ let output = OutputBuffer(limit: outputLimit)+ let errors = OutputBuffer(limit: outputLimit)+ let readers = DispatchGroup()+ let exitSignal = DispatchSemaphore(value: 0)++ process.executableURL = URL(fileURLWithPath: launchPath)+ process.arguments = args+ process.standardInput = FileHandle.nullDevice+ process.standardOutput = outputPipe+ process.standardError = errorPipe+ process.terminationHandler = { _ in exitSignal.signal() }++ do {+ try process.run()+ } catch {+ return Result(status: 126, out: "", err: "failed to launch: \(launchPath)")+ }++ drain(outputPipe.fileHandleForReading, into: output, group: readers)+ drain(errorPipe.fileHandleForReading, into: errors, group: readers)++ let didExit = exitSignal.wait(timeout: .now() + max(timeout, 0)) == .success+ let timedOut = !didExit && process.isRunning+ if timedOut {+ stop(process, exitSignal: exitSignal)+ }++ finishReaders(+ readers,+ handles: [outputPipe.fileHandleForReading, errorPipe.fileHandleForReading]+ )++ let stdout = output.string()+ let stderr = errors.string()+ if timedOut {+ return Result(status: 124, out: stdout, err: "command timed out")+ }++ let status = process.terminationStatus+ let error = status != 0 && stderr.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ ? "command exited with status \(status)"+ : stderr+ return Result(status: status, out: stdout, err: error)+ }++ private static func stop(_ process: Process, exitSignal: DispatchSemaphore) {+ guard process.isRunning else { return }+ process.terminate()+ if exitSignal.wait(timeout: .now() + 0.25) == .success { return }+ guard process.isRunning else { return }+ Darwin.kill(process.processIdentifier, SIGKILL)+ _ = exitSignal.wait(timeout: .now() + 0.75)+ }++ private static func drain(+ _ handle: FileHandle,+ into buffer: OutputBuffer,+ group: DispatchGroup+ ) {+ group.enter()+ DispatchQueue.global(qos: .utility).async {+ defer { group.leave() }+ while true {+ do {+ guard let data = try handle.read(upToCount: 65_536), !data.isEmpty else { return }+ buffer.append(data)+ } catch {+ return+ }+ }+ }+ }++ private static func finishReaders(_ readers: DispatchGroup, handles: [FileHandle]) {+ if readers.wait(timeout: .now() + 0.25) == .success { return }+ for handle in handles {+ try? handle.close()+ }+ _ = readers.wait(timeout: .now() + 0.25)+ }+}++private final class OutputBuffer: @unchecked Sendable {+ private static let marker = "\n[output truncated]"+ private let lock = NSLock()+ private let capacity: Int+ private var data = Data()+ private var truncated = false++ init(limit: Int) {+ capacity = max(0, limit - Self.marker.utf8.count)+ }++ func append(_ chunk: Data) {+ lock.lock()+ defer { lock.unlock() }+ let remaining = max(0, capacity - data.count)+ data.append(chunk.prefix(remaining))+ if chunk.count > remaining {+ truncated = true}+ }- var outData = Data(), errData = Data()- let group = DispatchGroup()- let q = DispatchQueue(label: "puremac.shell.drain", attributes: .concurrent)- q.async(group: group) { outData = outPipe.fileHandleForReading.readDataToEndOfFile() }- q.async(group: group) { errData = errPipe.fileHandleForReading.readDataToEndOfFile() }- group.wait()- p.waitUntilExit()- return Result(status: p.terminationStatus,- out: String(decoding: outData, as: UTF8.self),- err: String(decoding: errData, as: UTF8.self))+ func string() -> String {+ lock.lock()+ defer { lock.unlock() }+ return String(decoding: data, as: UTF8.self) + (truncated ? Self.marker : "")}}diff --git a/cli/Sources/puremac/Core/Stores.swift b/cli/Sources/puremac/Core/Stores.swiftindex 73d127e..cce1ea6 100644--- a/cli/Sources/puremac/Core/Stores.swift+++ b/cli/Sources/puremac/Core/Stores.swift@@ -3,10 +3,13 @@ import Foundationenum AppPaths {static var configDir: URL {let base: URL- if let xdg = ProcessInfo.processInfo.environment["XDG_CONFIG_HOME"], !xdg.isEmpty {+ if let xdg = ProcessInfo.processInfo.environment["XDG_CONFIG_HOME"],+ !xdg.isEmpty,+ xdg.hasPrefix("/") {base = URL(fileURLWithPath: xdg, isDirectory: true)} else {- base = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config", isDirectory: true)+ base = FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent(".config", isDirectory: true)}return base.appendingPathComponent("puremac", isDirectory: true)}@@ -14,75 +17,208 @@ enum AppPaths {static var ignoreFile: URL { configDir.appendingPathComponent("ignore") }static var configFile: URL { configDir.appendingPathComponent("config.json") }- static func ensureDir() {- try? FileManager.default.createDirectory(at: configDir, withIntermediateDirectories: true)+ static func ensureDir() throws {+ try FileManager.default.createDirectory(at: configDir, withIntermediateDirectories: true)+ }+}++enum StoreError: LocalizedError {+ case invalidConfigFile(String)+ case unknownConfigKey(String)+ case invalidConfigValue(key: String, value: String)+ case invalidIgnorePath+ case invalidIgnoreFile(String)++ var errorDescription: String? {+ switch self {+ case .invalidConfigFile(let path):+ return "Configuration file is not a valid PureMac settings file: \(path)"+ case .unknownConfigKey(let key):+ return "Unknown setting '\(key)'."+ case .invalidConfigValue(let key, let value):+ return "Invalid value '\(value)' for \(key). Use a whole number from 1 to 3650."+ case .invalidIgnorePath:+ return "Protected paths cannot be empty, the filesystem root, or contain newline or NUL characters."+ case .invalidIgnoreFile(let path):+ return "Ignore file contains an invalid or relative path: \(path)"+ }}}struct IgnoreStore {private(set) var roots: [String]+ private let fileURL: URL+ private let currentDirectoryPath: Stringinit() {- if let data = try? String(contentsOf: AppPaths.ignoreFile, encoding: .utf8) {- roots = data.split(separator: "\n").map(String.init)- .map { (($0 as NSString).expandingTildeInPath as NSString).standardizingPath }- .filter { !$0.isEmpty }- } else {- roots = []- }+ fileURL = AppPaths.ignoreFile+ currentDirectoryPath = FileManager.default.currentDirectoryPath+ roots = (try? Self.load(from: fileURL)) ?? []+ }++ init(+ fileURL: URL,+ currentDirectoryPath: String = FileManager.default.currentDirectoryPath+ ) throws {+ self.fileURL = fileURL+ self.currentDirectoryPath = currentDirectoryPath+ roots = try Self.load(from: fileURL)}func isIgnored(_ path: String) -> Bool {- let std = (path as NSString).standardizingPath- for root in roots where std == root || std.hasPrefix(root + "/") { return true }+ guard let standardized = try? Self.standardized(+ path,+ relativeTo: currentDirectoryPath,+ allowRelative: true+ ) else { return false }+ for root in roots where standardized == root || standardized.hasPrefix(root + "/") {+ return true+ }return false}mutating func add(_ path: String) throws -> Bool {- let std = (((path as NSString).expandingTildeInPath) as NSString).standardizingPath- guard !roots.contains(std) else { return false }- roots.append(std)- try save()+ let standardized = try Self.standardized(+ path,+ relativeTo: currentDirectoryPath,+ allowRelative: true+ )+ guard !roots.contains(standardized) else { return false }+ let updated = roots + [standardized]+ try save(updated)+ roots = updatedreturn true}mutating func remove(_ path: String) throws -> Bool {- let std = (((path as NSString).expandingTildeInPath) as NSString).standardizingPath- guard let idx = roots.firstIndex(of: std) else { return false }- roots.remove(at: idx)- try save()+ let standardized = try Self.standardized(+ path,+ relativeTo: currentDirectoryPath,+ allowRelative: true+ )+ guard roots.contains(standardized) else { return false }+ let updated = roots.filter { $0 != standardized }+ try save(updated)+ roots = updatedreturn true}- private func save() throws {- AppPaths.ensureDir()- try (roots.sorted().joined(separator: "\n") + "\n").write(to: AppPaths.ignoreFile, atomically: true, encoding: .utf8)+ private static func standardized(+ _ path: String,+ relativeTo currentDirectoryPath: String,+ allowRelative: Bool+ ) throws -> String {+ guard !path.isEmpty,+ !path.unicodeScalars.contains(where: {+ $0.value == 0 || CharacterSet.newlines.contains($0)+ })+ else {+ throw StoreError.invalidIgnorePath+ }+ let expanded = (path as NSString).expandingTildeInPath+ let absolute: String+ if expanded.hasPrefix("/") {+ absolute = expanded+ } else {+ guard allowRelative else {+ throw StoreError.invalidIgnorePath+ }+ absolute = URL(fileURLWithPath: currentDirectoryPath, isDirectory: true)+ .appendingPathComponent(expanded)+ .path+ }+ let standardized = URL(fileURLWithPath: absolute).standardizedFileURL.path+ guard standardized.hasPrefix("/"), standardized != "/",+ !standardized.unicodeScalars.contains(where: {+ $0.value == 0 || CharacterSet.newlines.contains($0)+ })+ else {+ throw StoreError.invalidIgnorePath+ }+ return standardized+ }++ private static func load(from fileURL: URL) throws -> [String] {+ guard FileManager.default.fileExists(atPath: fileURL.path) else { return [] }+ let contents = try String(contentsOf: fileURL, encoding: .utf8)+ var seen = Set<String>()+ var roots: [String] = []+ for line in contents.split(separator: "\n").map(String.init) {+ do {+ let root = try standardized(line, relativeTo: "/", allowRelative: false)+ if seen.insert(root).inserted { roots.append(root) }+ } catch {+ throw StoreError.invalidIgnoreFile(fileURL.path)+ }+ }+ return roots+ }++ private func save(_ roots: [String]) throws {+ try FileManager.default.createDirectory(+ at: fileURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ let contents = roots.isEmpty ? "" : roots.sorted().joined(separator: "\n") + "\n"+ try contents.write(to: fileURL, atomically: true, encoding: .utf8)}}struct ConfigStore {- var values: [String: String]+ private(set) var values: [String: String]+ private let fileURL: URLstatic let knownKeys = ["purge.older_than_days"]+ static let defaultValues = ["purge.older_than_days": "7"]init() {- if let data = try? Data(contentsOf: AppPaths.configFile),- let obj = try? JSONSerialization.jsonObject(with: data) as? [String: String] {- values = obj- } else {- values = [:]- }+ fileURL = AppPaths.configFile+ values = (try? Self.load(from: fileURL)) ?? [:]}- mutating func set(_ key: String, _ value: String) {- values[key] = value- save()+ init(fileURL: URL) throws {+ self.fileURL = fileURL+ values = try Self.load(from: fileURL)}- private func save() {- AppPaths.ensureDir()- if let data = try? JSONSerialization.data(withJSONObject: values, options: [.prettyPrinted, .sortedKeys]) {- try? data.write(to: AppPaths.configFile)+ mutating func set(_ key: String, _ value: String) throws {+ let normalized = try Self.normalizedValue(value, for: key)+ var updated = values+ updated[key] = normalized+ let data = try JSONSerialization.data(+ withJSONObject: updated,+ options: [.prettyPrinted, .sortedKeys]+ )+ try FileManager.default.createDirectory(+ at: fileURL.deletingLastPathComponent(),+ withIntermediateDirectories: true+ )+ try data.write(to: fileURL, options: .atomic)+ values = updated+ }++ static func normalizedValue(_ value: String, for key: String) throws -> String {+ guard knownKeys.contains(key) else {+ throw StoreError.unknownConfigKey(key)+ }+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)+ guard let days = Int(trimmed), (1...3650).contains(days) else {+ throw StoreError.invalidConfigValue(key: key, value: value)+ }+ return String(days)+ }++ private static func load(from fileURL: URL) throws -> [String: String] {+ guard FileManager.default.fileExists(atPath: fileURL.path) else { return [:] }+ let data = try Data(contentsOf: fileURL)+ guard let object = try? JSONSerialization.jsonObject(with: data),+ let values = object as? [String: String]+ else {+ throw StoreError.invalidConfigFile(fileURL.path)+ }+ for (key, value) in values {+ _ = try normalizedValue(value, for: key)}+ return values}}diff --git a/cli/Sources/puremac/Core/SystemInfo.swift b/cli/Sources/puremac/Core/SystemInfo.swiftindex afd6e46..6487350 100644--- a/cli/Sources/puremac/Core/SystemInfo.swift+++ b/cli/Sources/puremac/Core/SystemInfo.swift@@ -1,27 +1,85 @@-import Foundationimport Darwin+import Foundation-enum SystemInfo {+struct MemoryStatus: Equatable {+ let total: Int64+ let free: Int64+ let inactive: Int64+ let active: Int64+ let wired: Int64+ let compressed: Int64+}++struct VolumeStatus: Equatable {+ let availableNow: Int64+ let availableForImportantUsage: Int64+ let total: Int64++ var systemManagedCapacity: Int64 {+ max(0, availableForImportantUsage - availableNow)+ }+}++enum SystemInfoError: LocalizedError {+ case memoryUnavailable(kern_return_t)+ case volumeUnavailable(String)- static func memory() -> (free: Int64, inactive: Int64) {+ var errorDescription: String? {+ switch self {+ case .memoryUnavailable(let status):+ return "macOS did not return memory statistics (status \(status))."+ case .volumeUnavailable(let path):+ return "macOS did not return storage capacity for \(path)."+ }+ }+}++enum SystemInfo {+ static func memoryStatus() throws -> MemoryStatus {var stats = vm_statistics64()- var count = mach_msg_type_number_t(MemoryLayout<vm_statistics64_data_t>.size / MemoryLayout<integer_t>.size)+ var count = mach_msg_type_number_t(+ MemoryLayout<vm_statistics64_data_t>.size / MemoryLayout<integer_t>.size+ )let host = mach_host_self()- let kr = withUnsafeMutablePointer(to: &stats) {+ defer { mach_port_deallocate(mach_task_self_, host) }+ let status = withUnsafeMutablePointer(to: &stats) {$0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {host_statistics64(host, HOST_VM_INFO64, $0, &count)}}- guard kr == KERN_SUCCESS else { return (0, 0) }+ guard status == KERN_SUCCESS else {+ throw SystemInfoError.memoryUnavailable(status)+ }+let page = Int64(vm_kernel_page_size)- return (Int64(stats.free_count) * page, Int64(stats.inactive_count) * page)+ return MemoryStatus(+ total: Int64(ProcessInfo.processInfo.physicalMemory),+ free: Int64(stats.free_count) * page,+ inactive: Int64(stats.inactive_count) * page,+ active: Int64(stats.active_count) * page,+ wired: Int64(stats.wire_count) * page,+ compressed: Int64(stats.compressor_page_count) * page+ )}- static func volume(_ path: String) -> (available: Int64, total: Int64) {+ static func volumeStatus(_ path: String) throws -> VolumeStatus {let url = URL(fileURLWithPath: path)- let vals = try? url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey, .volumeTotalCapacityKey, .volumeAvailableCapacityKey])- let avail = Int64(vals?.volumeAvailableCapacityForImportantUsage ?? Int64(vals?.volumeAvailableCapacity ?? 0))- let total = Int64(vals?.volumeTotalCapacity ?? 0)- return (avail, total)+ let values = try url.resourceValues(forKeys: [+ .volumeAvailableCapacityForImportantUsageKey,+ .volumeAvailableCapacityKey,+ .volumeTotalCapacityKey,+ ])+ guard let available = values.volumeAvailableCapacity,+ let total = values.volumeTotalCapacity+ else {+ throw SystemInfoError.volumeUnavailable(path)+ }+ let important = values.volumeAvailableCapacityForImportantUsage ?? Int64(available)+ return VolumeStatus(+ availableNow: max(0, Int64(available)),+ availableForImportantUsage: max(0, important),+ total: max(0, Int64(total))+ )}+}diff --git a/cli/Sources/puremac/Core/Term.swift b/cli/Sources/puremac/Core/Term.swiftindex 925ac6f..ad5ba82 100644--- a/cli/Sources/puremac/Core/Term.swift+++ b/cli/Sources/puremac/Core/Term.swift@@ -1,39 +1,139 @@+import Darwinimport Foundationenum Term {- static let colorEnabled: Bool = {- if ProcessInfo.processInfo.environment["NO_COLOR"] != nil { return false }- if ProcessInfo.processInfo.environment["TERM"] == "dumb" { return false }- return isatty(fileno(stdout)) == 1+ private static let localeConfigured: Void = {+ setlocale(LC_CTYPE, "")}()- static func style(_ s: String, _ codes: String) -> String {- colorEnabled ? "\u{1B}[\(codes)m\(s)\u{1B}[0m" : s+ static var colorEnabled: Bool {+ ProcessInfo.processInfo.environment["NO_COLOR"] == nil+ && ProcessInfo.processInfo.environment["TERM"] != "dumb"+ && isatty(fileno(stdout)) == 1}- static func bold(_ s: String) -> String { style(s, "1") }- static func dim(_ s: String) -> String { style(s, "2") }- static func red(_ s: String) -> String { style(s, "31") }- static func green(_ s: String) -> String { style(s, "32") }- static func yellow(_ s: String) -> String { style(s, "33") }- static func blue(_ s: String) -> String { style(s, "34") }- static func cyan(_ s: String) -> String { style(s, "36") }+ static func style(_ string: String, _ codes: String) -> String {+ colorEnabled ? "\u{1B}[\(codes)m\(string)\u{1B}[0m" : string+ }++ static func bold(_ string: String) -> String { style(string, "1") }+ static func dim(_ string: String) -> String { style(string, "2") }+ static func red(_ string: String) -> String { style(string, "31") }+ static func green(_ string: String) -> String { style(string, "32") }+ static func yellow(_ string: String) -> String { style(string, "33") }+ static func blue(_ string: String) -> String { style(string, "34") }+ static func cyan(_ string: String) -> String { style(string, "36") }+ static func inverse(_ string: String) -> String { style(string, "7") }- static func err(_ s: String) { FileHandle.standardError.write(Data((s + "\n").utf8)) }+ static func err(_ string: String) {+ FileHandle.standardError.write(Data((string + "\n").utf8))+ }- static func confirm(_ prompt: String, default def: Bool = false) -> Bool {- guard isatty(fileno(stdin)) == 1 else { return def }- let hint = def ? "[Y/n]" : "[y/N]"- print("\(prompt) \(hint) ", terminator: "")- guard let line = readLine() else { return def }+ static func confirm(_ prompt: String, default defaultValue: Bool = false) -> Bool {+ guard isatty(fileno(stdin)) == 1 else { return defaultValue }+ let hint = defaultValue ? "[Y/n]" : "[y/N]"+ print("\(sanitize(prompt)) \(hint) ", terminator: "")+ guard let line = readLine() else { return defaultValue }let answer = line.trimmingCharacters(in: .whitespaces).lowercased()- if answer.isEmpty { return def }+ if answer.isEmpty { return defaultValue }return answer == "y" || answer == "yes"}static func bar(fraction: Double, width: Int = 24) -> String {+ let safeWidth = max(0, width)let clamped = max(0, min(1, fraction))- let filled = Int((Double(width) * clamped).rounded())- return String(repeating: "█", count: filled) + String(repeating: "░", count: width - filled)+ let filled = Int((Double(safeWidth) * clamped).rounded())+ return String(repeating: "█", count: filled)+ + String(repeating: "░", count: safeWidth - filled)+ }++ static func sanitize(_ string: String) -> String {+ var output = ""+ output.reserveCapacity(string.count)+ for scalar in string.unicodeScalars {+ switch scalar.value {+ case 0x20...0x7E, 0xA0...0x10FFFF:+ if scalar.value >= 0x7F && scalar.value <= 0x9F {+ output.append("�")+ } else {+ output.unicodeScalars.append(scalar)+ }+ case 0x09:+ output.append(" ")+ default:+ output.append("�")+ }+ }+ return output+ }++ static func displayWidth(_ string: String) -> Int {+ _ = localeConfigured+ var width = 0+ var escapeState = 0+ for scalar in string.unicodeScalars {+ if escapeState == 1 {+ escapeState = scalar.value == 0x5B ? 2 : 0+ continue+ }+ if escapeState == 2 {+ if scalar.value >= 0x40 && scalar.value <= 0x7E {+ escapeState = 0+ }+ continue+ }+ if scalar.value == 0x1B {+ escapeState = 1+ continue+ }+ let scalarWidth = wcwidth(wchar_t(scalar.value))+ width += scalarWidth > 0 ? Int(scalarWidth) : 0+ }+ return width+ }++ static func pad(_ string: String, to width: Int) -> String {+ let missing = max(0, width - displayWidth(string))+ return string + String(repeating: " ", count: missing)+ }++ static func truncate(_ string: String, to width: Int, middle: Bool = false) -> String {+ let safe = sanitize(string)+ guard width > 0 else { return "" }+ guard displayWidth(safe) > width else { return safe }+ guard width > 1 else { return "…" }++ if middle {+ let leftWidth = (width - 1) / 2+ let rightWidth = width - 1 - leftWidth+ return prefix(safe, width: leftWidth) + "…" + suffix(safe, width: rightWidth)+ }+ return prefix(safe, width: width - 1) + "…"+ }++ private static func prefix(_ string: String, width: Int) -> String {+ var output = ""+ var used = 0+ for character in string {+ let value = String(character)+ let characterWidth = displayWidth(value)+ guard used + characterWidth <= width else { break }+ output.append(character)+ used += characterWidth+ }+ return output+ }++ private static func suffix(_ string: String, width: Int) -> String {+ var characters: [Character] = []+ var used = 0+ for character in string.reversed() {+ let value = String(character)+ let characterWidth = displayWidth(value)+ guard used + characterWidth <= width else { break }+ characters.append(character)+ used += characterWidth+ }+ return String(characters.reversed())}}diff --git a/cli/Sources/puremac/Core/TerminalMenu.swift b/cli/Sources/puremac/Core/TerminalMenu.swiftnew file mode 100644index 0000000..1eb06b2--- /dev/null+++ b/cli/Sources/puremac/Core/TerminalMenu.swift@@ -0,0 +1,135 @@+import Foundation++struct TerminalMenuModel {+ let optionCount: Int+ private(set) var selection = 0++ mutating func move(_ delta: Int) {+ guard optionCount > 0 else { return }+ selection = min(optionCount - 1, max(0, selection + delta))+ }++ mutating func moveToStart() {+ selection = 0+ }++ mutating func moveToEnd() {+ selection = max(0, optionCount - 1)+ }++ mutating func select(number: Int) -> Int? {+ let index = number - 1+ guard (1...9).contains(number), index < optionCount else { return nil }+ selection = index+ return selection+ }+}++enum TerminalMenu {+ static func choose(+ title: String,+ subtitle: String,+ options: [(title: String, detail: String)]+ ) throws -> Int? {+ guard !options.isEmpty else { return nil }+ let session = try TerminalSession()+ defer { session.close() }++ var model = TerminalMenuModel(optionCount: options.count)+ while true {+ session.draw(+ lines: render(+ title: title,+ subtitle: subtitle,+ options: options,+ selection: model.selection,+ width: session.width,+ height: session.height+ )+ )++ switch session.readKey() {+ case .up:+ model.move(-1)+ case .down:+ model.move(1)+ case .pageUp:+ model.move(-max(1, session.height / 2))+ case .pageDown:+ model.move(max(1, session.height / 2))+ case .home:+ model.moveToStart()+ case .end:+ model.moveToEnd()+ case .enter:+ return model.selection+ case .escape:+ return nil+ case .character(let character):+ if String(character).lowercased() == "q" {+ return nil+ }+ if let number = character.wholeNumberValue,+ let selection = model.select(number: number) {+ return selection+ }+ default:+ break+ }+ }+ }++ static func render(+ title: String,+ subtitle: String,+ options: [(title: String, detail: String)],+ selection: Int,+ width: Int,+ height: Int+ ) -> [String] {+ let safeWidth = max(1, width)+ let safeHeight = max(1, height)+ if safeWidth < 40 || safeHeight < 12 {+ let compact = [+ Term.bold(Term.cyan(Term.truncate("PureMac", to: safeWidth))),+ Term.truncate("Terminal too small", to: safeWidth),+ Term.dim(Term.truncate("Resize to at least 40 x 12", to: safeWidth)),+ "",+ Term.dim(Term.truncate("Esc/q cancel", to: safeWidth))+ ]+ return Array(compact.prefix(safeHeight))+ }+ let safeSelection = min(max(0, selection), max(0, options.count - 1))+ var lines = [+ Term.dim("PUREMAC / CHOOSE A TOOL"),+ Term.bold(Term.cyan(Term.truncate(title, to: safeWidth))),+ Term.dim(Term.truncate(subtitle, to: safeWidth)),+ ""+ ]++ let footerHeight = 3+ let rowHeight = 2+ let visibleCount = max(1, (safeHeight - lines.count - footerHeight) / rowHeight)+ let start = max(0, min(max(0, options.count - visibleCount), safeSelection - visibleCount / 2))+ let visible = options.enumerated().dropFirst(start).prefix(visibleCount)++ for (index, option) in visible {+ let focused = index == safeSelection+ let number = Term.pad("\(index + 1).", to: 4)+ let titleWidth = max(1, safeWidth - 6)+ let titleLine = "\(focused ? "›" : " ") \(number)\(Term.truncate(option.title, to: titleWidth))"+ let detailLine = " " + Term.truncate(option.detail, to: max(1, safeWidth - 6))+ lines.append(focused ? Term.inverse(titleLine) : titleLine)+ lines.append(focused ? Term.bold(detailLine) : Term.dim(detailLine))+ }++ while lines.count < safeHeight - footerHeight {+ lines.append("")+ }++ lines.append(Term.dim(String(repeating: "─", count: safeWidth)))+ lines.append(Term.dim("↑↓ move PgUp/PgDn page 1-9 open"))+ lines.append(Term.dim("Enter open Esc/q cancel"))+ return Array(lines.prefix(safeHeight))+ }+}diff --git a/cli/Sources/puremac/Core/TerminalSession.swift b/cli/Sources/puremac/Core/TerminalSession.swiftnew file mode 100644index 0000000..97faf4b--- /dev/null+++ b/cli/Sources/puremac/Core/TerminalSession.swift@@ -0,0 +1,262 @@+import Darwin+import Foundation++enum TerminalKey: Equatable {+ case up+ case down+ case left+ case right+ case pageUp+ case pageDown+ case home+ case end+ case enter+ case escape+ case space+ case backspace+ case delete+ case character(Character)+ case unknown+}++enum TerminalSessionError: Error {+ case unsupported+ case setupFailed+}++private var terminalSavedState = termios()+private var terminalHasSavedState = false+private var terminalSavedInputSpeed = speed_t()+private var terminalSavedOutputSpeed = speed_t()+private var terminalHasSavedSpeeds = false+private var terminalRuntimeActive = false+private var terminalPreviousSIGINT: sig_t?+private var terminalPreviousSIGTERM: sig_t?+private var terminalPreviousSIGHUP: sig_t?+private var terminalPreviousSIGQUIT: sig_t?++private func terminalWrite(_ value: String) {+ let bytes = Array(value.utf8)+ bytes.withUnsafeBytes { buffer in+ guard let base = buffer.baseAddress else { return }+ _ = Darwin.write(STDOUT_FILENO, base, buffer.count)+ }+}++private func terminalRestore() {+ if terminalHasSavedState {+ var state = terminalSavedState+ if terminalHasSavedSpeeds {+ _ = cfsetispeed(&state, terminalSavedInputSpeed)+ _ = cfsetospeed(&state, terminalSavedOutputSpeed)+ }+ _ = tcsetattr(STDIN_FILENO, TCSAFLUSH, &state)+ }+ if terminalRuntimeActive {+ let sequence: StaticString = "\u{1B}[0m\u{1B}[?25h\u{1B}[?1049l"+ _ = Darwin.write(STDOUT_FILENO, sequence.utf8Start, sequence.utf8CodeUnitCount)+ }+ terminalRuntimeActive = false+ terminalHasSavedState = false+ terminalHasSavedSpeeds = false+}++private func terminalSignalHandler(_ signalNumber: Int32) {+ terminalRestore()+ Darwin.signal(signalNumber, SIG_DFL)+ var signals = sigset_t()+ sigemptyset(&signals)+ sigaddset(&signals, signalNumber)+ pthread_sigmask(SIG_UNBLOCK, &signals, nil)+ _ = Darwin.kill(getpid(), signalNumber)+}++private func terminalExitHandler() {+ terminalRestore()+}++final class TerminalSession {+ static var isSupported: Bool {+ isatty(STDIN_FILENO) == 1+ && isatty(STDOUT_FILENO) == 1+ && ProcessInfo.processInfo.environment["TERM"] != "dumb"+ }++ private var isClosed = false++ var width: Int {+ terminalDimensions().width+ }++ var height: Int {+ terminalDimensions().height+ }++ init() throws {+ guard Self.isSupported else {+ throw TerminalSessionError.unsupported+ }+ guard !terminalRuntimeActive else {+ throw TerminalSessionError.setupFailed+ }++ var original = termios()+ guard tcgetattr(STDIN_FILENO, &original) == 0 else {+ throw TerminalSessionError.setupFailed+ }++ var raw = original+ cfmakeraw(&raw)+ raw.c_lflag |= tcflag_t(ISIG)+ let disabledControl = fpathconf(STDIN_FILENO, _PC_VDISABLE)+ withUnsafeMutablePointer(to: &raw.c_cc) { pointer in+ pointer.withMemoryRebound(to: cc_t.self, capacity: Int(NCCS)) {+ $0[Int(VSUSP)] = cc_t(disabledControl >= 0 ? disabledControl : 0xFF)+ }+ }+ guard tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == 0 else {+ throw TerminalSessionError.setupFailed+ }++ terminalSavedState = original+ terminalHasSavedState = true+ terminalSavedInputSpeed = cfgetispeed(&original)+ terminalSavedOutputSpeed = cfgetospeed(&original)+ terminalHasSavedSpeeds = true+ terminalRuntimeActive = true++ terminalPreviousSIGINT = Darwin.signal(SIGINT, terminalSignalHandler)+ terminalPreviousSIGTERM = Darwin.signal(SIGTERM, terminalSignalHandler)+ terminalPreviousSIGHUP = Darwin.signal(SIGHUP, terminalSignalHandler)+ terminalPreviousSIGQUIT = Darwin.signal(SIGQUIT, terminalSignalHandler)+ atexit(terminalExitHandler)++ terminalWrite("\u{1B}[?1049h\u{1B}[?25l\u{1B}[2J\u{1B}[H")+ }++ deinit {+ close()+ }++ func draw(lines: [String]) {+ guard !isClosed else { return }+ let visibleLines = Array(lines.prefix(max(1, height)))+ let frame = visibleLines.map { "\u{1B}[2K" + $0 }.joined(separator: "\r\n")+ terminalWrite("\u{1B}[H" + frame + "\u{1B}[J")+ }++ func readKey() -> TerminalKey {+ guard !isClosed, let first = readByte() else { return .escape }++ switch first {+ case 0x0A, 0x0D:+ return .enter+ case 0x20:+ return .space+ case 0x08, 0x7F:+ return .backspace+ case 0x1B:+ return readEscapeSequence()+ case 0x01...0x1A:+ return .unknown+ default:+ return decodeCharacter(firstByte: first)+ }+ }++ func close() {+ guard !isClosed else { return }+ isClosed = true+ terminalRestore()+ if let handler = terminalPreviousSIGINT { Darwin.signal(SIGINT, handler) }+ if let handler = terminalPreviousSIGTERM { Darwin.signal(SIGTERM, handler) }+ if let handler = terminalPreviousSIGHUP { Darwin.signal(SIGHUP, handler) }+ if let handler = terminalPreviousSIGQUIT { Darwin.signal(SIGQUIT, handler) }+ terminalPreviousSIGINT = nil+ terminalPreviousSIGTERM = nil+ terminalPreviousSIGHUP = nil+ terminalPreviousSIGQUIT = nil+ }++ private func readEscapeSequence() -> TerminalKey {+ guard inputAvailable(milliseconds: 24), let second = readByte() else {+ return .escape+ }+ guard second == 0x5B || second == 0x4F else {+ return .escape+ }+ guard inputAvailable(milliseconds: 24), let third = readByte() else {+ return .escape+ }++ switch third {+ case 0x41: return .up+ case 0x42: return .down+ case 0x43: return .right+ case 0x44: return .left+ case 0x48: return .home+ case 0x46: return .end+ case 0x31, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38:+ guard inputAvailable(milliseconds: 24), let fourth = readByte(), fourth == 0x7E else {+ return .unknown+ }+ switch third {+ case 0x31, 0x37: return .home+ case 0x33: return .delete+ case 0x34, 0x38: return .end+ case 0x35: return .pageUp+ case 0x36: return .pageDown+ default: return .unknown+ }+ default:+ return .unknown+ }+ }++ private func decodeCharacter(firstByte: UInt8) -> TerminalKey {+ let expectedCount: Int+ switch firstByte {+ case 0x00...0x7F: expectedCount = 1+ case 0xC2...0xDF: expectedCount = 2+ case 0xE0...0xEF: expectedCount = 3+ case 0xF0...0xF4: expectedCount = 4+ default: return .unknown+ }++ var bytes = [firstByte]+ while bytes.count < expectedCount {+ guard inputAvailable(milliseconds: 24), let byte = readByte() else {+ return .unknown+ }+ bytes.append(byte)+ }+ guard let string = String(bytes: bytes, encoding: .utf8), string.count == 1,+ let character = string.first else {+ return .unknown+ }+ return .character(character)+ }++ private func readByte() -> UInt8? {+ var byte: UInt8 = 0+ while true {+ let result = Darwin.read(STDIN_FILENO, &byte, 1)+ if result == 1 { return byte }+ if result == -1 && errno == EINTR { continue }+ return nil+ }+ }++ private func inputAvailable(milliseconds: Int32) -> Bool {+ var descriptor = pollfd(fd: STDIN_FILENO, events: Int16(POLLIN), revents: 0)+ return poll(&descriptor, 1, milliseconds) > 0+ }++ private func terminalDimensions() -> (width: Int, height: Int) {+ var window = winsize()+ guard ioctl(STDOUT_FILENO, TIOCGWINSZ, &window) == 0 else {+ return (80, 24)+ }+ return (max(1, Int(window.ws_col)), max(1, Int(window.ws_row)))+ }+}diff --git a/cli/Sources/puremac/PureMac.swift b/cli/Sources/puremac/PureMac.swiftindex 96e9172..83abbe3 100644--- a/cli/Sources/puremac/PureMac.swift+++ b/cli/Sources/puremac/PureMac.swift@@ -1,19 +1,70 @@import ArgumentParserimport Foundation-let puremacVersion = "1.0.0"+let puremacVersion = "1.1.0"@mainstruct PureMac: ParsableCommand {static let configuration = CommandConfiguration(commandName: "puremac",- abstract: "Clean developer caches, project artifacts, and disk clutter — from the terminal.",+ abstract: "Review caches, clean project artifacts, and explore your storage.",discussion: """- PureMac scans first and removes only what you approve. Cache/junk removal is- permanent; cloud (iCloud/Dropbox/…) state and your config dotfiles are never touched.+ Run puremac to open the interactive workspace. Select individual paths,+ review their sizes, and confirm before permanent cleanup.+ Use --help on any command for script-friendly options.""",version: puremacVersion,- subcommands: [Clean.self, Purge.self, Analyze.self, Optimize.self, Ignore.self, Config.self],- defaultSubcommand: Clean.self+ subcommands: [Clean.self, Purge.self, Analyze.self, Optimize.self, Ignore.self, Config.self])++ func run() throws {+ guard TerminalSession.isSupported else {+ print(Self.helpMessage())+ return+ }+ try HomeMenu.run()+ }+}++enum HomeMenu {+ static func run() throws {+ let options: [(title: String, detail: String)] = [+ ("Clean caches", "Choose tools and individual paths to remove"),+ ("Project cleanup", "Review dependencies and generated build artifacts"),+ ("Explore storage", "Browse folders and find what takes up space"),+ ("System status", "Inspect memory and available disk space"),+ ("Preferences", "View cleanup settings and configuration paths"),+ ("Protected paths", "View folders excluded from cleanup")+ ]+ while let choice = try TerminalMenu.choose(+ title: "PureMac",+ subtitle: "Your Mac, with room to work. / \(puremacVersion)",+ options: options+ ) {+ switch choice {+ case 0:+ guard let category = try TerminalMenu.choose(+ title: "Clean caches",+ subtitle: "Scan first. Choose what to remove afterward.",+ options: [+ ("All categories", "Developer caches, user junk, AI tools, and Trash"),+ ("Developer caches", "Package managers and build tools"),+ ("User junk", "Logs and generated Xcode files"),+ ("AI tools", "Caches and logs from local AI tools"),+ ("Trash", "Review items already in the Trash")+ ]+ ) else { continue }+ let arguments = [[], ["dev"], ["junk"], ["ai"], ["trash"]]+ try Clean.parse(arguments[category]).run()+ case 1: try Purge.parse([]).run()+ case 2: try Analyze.parse([]).run()+ case 3: try Optimize.parse([]).run()+ case 4: try Config.parse([]).run()+ case 5: try Ignore.List.parse([]).run()+ default: return+ }+ print(Term.dim("\nPress Return to return to PureMac."), terminator: " ")+ guard readLine() != nil else { return }+ }+ }}diff --git a/cli/Tests/puremacTests/AnalyzeTests.swift b/cli/Tests/puremacTests/AnalyzeTests.swiftnew file mode 100644index 0000000..349feb3--- /dev/null+++ b/cli/Tests/puremacTests/AnalyzeTests.swift@@ -0,0 +1,162 @@+import Darwin+import XCTest+@testable import puremac++final class AnalyzeTests: XCTestCase {+ private var root: URL!++ override func setUpWithError() throws {+ root = FileManager.default.temporaryDirectory+ .appendingPathComponent("puremac-analyze-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ }++ override func tearDownWithError() throws {+ if let root { try? FileManager.default.removeItem(at: root) }+ root = nil+ }++ func testDepthValidationUsesDocumentedBounds() throws {+ var analyze = Analyze()+ analyze.depth = 1+ XCTAssertNoThrow(try analyze.validate())+ analyze.depth = 8+ XCTAssertNoThrow(try analyze.validate())+ analyze.depth = 0+ XCTAssertThrowsError(try analyze.validate())+ analyze.depth = 9+ XCTAssertThrowsError(try analyze.validate())+ }++ func testDepthAndPlainModesDisableFullscreenBrowser() {+ XCTAssertTrue(Analyze.usesInteractiveBrowser(plain: false, depth: 1, terminalSupported: true))+ XCTAssertFalse(Analyze.usesInteractiveBrowser(plain: true, depth: 1, terminalSupported: true))+ XCTAssertFalse(Analyze.usesInteractiveBrowser(plain: false, depth: 2, terminalSupported: true))+ XCTAssertFalse(Analyze.usesInteractiveBrowser(plain: false, depth: 1, terminalSupported: false))+ }++ func testScanRanksAllocatedSizesAndMeasuresPackageWithoutDrilldown() throws {+ let small = root.appendingPathComponent("small.bin")+ let package = root.appendingPathComponent("Example.app", isDirectory: true)+ let contents = package.appendingPathComponent("Contents", isDirectory: true)+ try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true)+ try Data(repeating: 0x41, count: 8_192).write(to: small)+ try Data(repeating: 0x42, count: 1_000_000).write(to: contents.appendingPathComponent("payload.bin"))++ let snapshot = Analyze().scanFolder(root.path)++ XCTAssertEqual(snapshot.children.map { URL(fileURLWithPath: $0.path).lastPathComponent }, ["Example.app", "small.bin"])+ let packageChild = try XCTUnwrap(snapshot.children.first)+ XCTAssertTrue(packageChild.isDir)+ XCTAssertTrue(packageChild.isPackage)+ XCTAssertGreaterThan(packageChild.size, 0)+ }++ func testScanSkipsIgnoredAndSymbolicLinkedEntries() throws {+ let visible = root.appendingPathComponent("visible.bin")+ let ignored = root.appendingPathComponent("ignored.bin")+ let link = root.appendingPathComponent("linked.bin")+ try Data(repeating: 0x41, count: 4_096).write(to: visible)+ try Data(repeating: 0x42, count: 4_096).write(to: ignored)+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: visible)++ let ignoreFile = root.appendingPathComponent("ignore-config")+ try (ignored.path + "\n").write(to: ignoreFile, atomically: true, encoding: .utf8)+ let ignore = try IgnoreStore(fileURL: ignoreFile)+ let snapshot = Analyze().scanFolder(root.path, ignore: ignore)++ XCTAssertEqual(snapshot.children.map { URL(fileURLWithPath: $0.path).lastPathComponent }, ["ignore-config", "visible.bin"])+ XCTAssertEqual(snapshot.skippedCount, 2)+ XCTAssertTrue(snapshot.isPartial)+ }++ func testUnreadableChildIsReportedAsPartialOrInaccessible() throws {+ let locked = root.appendingPathComponent("Locked", isDirectory: true)+ try FileManager.default.createDirectory(at: locked, withIntermediateDirectories: true)+ try Data(repeating: 0x44, count: 4_096).write(to: locked.appendingPathComponent("private.bin"))+ XCTAssertEqual(chmod(locked.path, 0), 0)+ defer { _ = chmod(locked.path, S_IRWXU) }++ let snapshot = Analyze().scanFolder(root.path)++ XCTAssertTrue(snapshot.isPartial)+ XCTAssertGreaterThan(snapshot.skippedCount + snapshot.inaccessibleCount, 0)+ XCTAssertFalse(snapshot.errors.isEmpty)+ }++ func testViewportKeepsSelectionVisibleAndWithinHeight() {+ let children = (0..<20).map {+ Analyze.Child(+ path: "/tmp/item-\($0)",+ size: Int64(20 - $0) * 1_024,+ isDir: true,+ isPackage: false,+ inaccessibleCount: 0,+ skippedCount: 0+ )+ }+ let snapshot = Analyze.FolderSnapshot(+ path: "/tmp",+ children: children,+ total: children.reduce(Int64(0)) { $0 + $1.size },+ inaccessibleCount: 0,+ skippedCount: 0,+ errors: []+ )+ let visible = Analyze.visibleRowCount(snapshot: snapshot, selected: 17, width: 60, height: 14)+ let offset = Analyze.adjustedOffset(0, selected: 17, count: children.count, visibleRows: visible)+ let level = Analyze.BrowserLevel(snapshot: snapshot, selected: 17, offset: offset)+ let lines = Analyze.browserLines(level: level, width: 60, height: 14)++ XCTAssertGreaterThan(offset, 0)+ XCTAssertLessThanOrEqual(lines.count, 14)+ XCTAssertTrue(lines.joined(separator: "\n").contains("item-17"))+ }++ func testFocusedPathWrappingPreservesEveryCharacter() {+ let path = "/Users/example/a folder/with/a/very-long-name/file.bin"+ let lines = Analyze.wrap(path, width: 11)++ XCTAssertGreaterThan(lines.count, 1)+ XCTAssertEqual(lines.joined(), path)+ XCTAssertTrue(lines.allSatisfy { Term.displayWidth($0) <= 11 })+ }++ func testNarrowBrowserRenderStaysWithinViewport() {+ let path = "/Users/example/a folder/with/a/very-long-name/file.bin"+ let child = Analyze.Child(+ path: path,+ size: 8_192,+ isDir: false,+ isPackage: false,+ inaccessibleCount: 0,+ skippedCount: 0+ )+ let snapshot = Analyze.FolderSnapshot(+ path: "/Users/example/a folder",+ children: [child],+ total: child.size,+ inaccessibleCount: 0,+ skippedCount: 0,+ errors: []+ )+ let lines = Analyze.browserLines(+ level: Analyze.BrowserLevel(snapshot: snapshot),+ width: 40,+ height: 12+ )++ XCTAssertLessThanOrEqual(lines.count, 12)+ XCTAssertTrue(lines.allSatisfy { Term.displayWidth($0) <= 40 })+ XCTAssertTrue(lines.joined(separator: "\n").contains("O reveal"))+ XCTAssertTrue(lines.joined(separator: "\n").contains("q/Esc exit"))++ let tooSmall = Analyze.browserLines(+ level: Analyze.BrowserLevel(snapshot: snapshot),+ width: 39,+ height: 11+ )+ XCTAssertTrue(tooSmall.contains { $0.contains("Terminal too small") })+ XCTAssertTrue(tooSmall.allSatisfy { Term.displayWidth($0) <= 39 })+ }+}diff --git a/cli/Tests/puremacTests/CommandReviewTests.swift b/cli/Tests/puremacTests/CommandReviewTests.swiftnew file mode 100644index 0000000..627c465--- /dev/null+++ b/cli/Tests/puremacTests/CommandReviewTests.swift@@ -0,0 +1,114 @@+import XCTest+@testable import puremac++final class CommandReviewTests: XCTestCase {+ func testReadOnlyModesOverrideForceAndNeverRequireTerminal() {+ XCTAssertEqual(+ CleanupCommandPolicy.mode(+ force: true,+ dryRun: true,+ json: false,+ plain: false,+ terminalSupported: false,+ inputIsTTY: false+ ),+ .reportOnly+ )+ XCTAssertEqual(+ CleanupCommandPolicy.mode(+ force: true,+ dryRun: false,+ json: true,+ plain: false,+ terminalSupported: false,+ inputIsTTY: false+ ),+ .reportOnly+ )+ }++ func testNoninteractiveDeletionFailsClosedUnlessForced() {+ XCTAssertEqual(+ CleanupCommandPolicy.mode(+ force: false,+ dryRun: false,+ json: false,+ plain: false,+ terminalSupported: true,+ inputIsTTY: false+ ),+ .unavailable+ )+ XCTAssertEqual(+ CleanupCommandPolicy.mode(+ force: true,+ dryRun: false,+ json: false,+ plain: false,+ terminalSupported: false,+ inputIsTTY: false+ ),+ .forced+ )+ }++ func testUnsupportedFullscreenTerminalUsesPlainReview() {+ XCTAssertEqual(+ CleanupCommandPolicy.mode(+ force: false,+ dryRun: false,+ json: false,+ plain: false,+ terminalSupported: false,+ inputIsTTY: true+ ),+ .plain+ )+ XCTAssertEqual(+ CleanupCommandPolicy.mode(+ force: false,+ dryRun: false,+ json: false,+ plain: true,+ terminalSupported: true,+ inputIsTTY: true+ ),+ .plain+ )+ XCTAssertEqual(+ CleanupCommandPolicy.mode(+ force: false,+ dryRun: false,+ json: false,+ plain: false,+ terminalSupported: true,+ inputIsTTY: true+ ),+ .fullscreen+ )+ }++ func testPlainSelectionSupportsRangesAllAndNone() throws {+ XCTAssertEqual(try PlainSelectionReview.parseSelection("1, 3-5 7", itemCount: 7), [1, 3, 4, 5, 7])+ XCTAssertEqual(try PlainSelectionReview.parseSelection("all", itemCount: 3), [1, 2, 3])+ XCTAssertEqual(try PlainSelectionReview.parseSelection("none", itemCount: 3), [])+ XCTAssertEqual(try PlainSelectionReview.parseSelection("", itemCount: 0), [])+ XCTAssertThrowsError(try PlainSelectionReview.parseSelection("0,4", itemCount: 3))+ XCTAssertThrowsError(try PlainSelectionReview.parseSelection("3-1", itemCount: 3))+ }++ func testPlainReviewCanSelectRecentPurgeItemAndFreezesOnlyChosenPaths() {+ let old = ScanItem(path: "/tmp/project/old/node_modules", sizeBytes: 100, modified: nil, selected: true)+ let recent = ScanItem(path: "/tmp/project/recent/node_modules", sizeBytes: 200, modified: nil, selected: false)+ let category = CategoryScan(+ id: "purge",+ title: "Project Artifacts",+ groups: [ToolGroup(tool: "node_modules", items: [old, recent])]+ )++ let reviewed = PlainSelectionReview.applyingSelection([2], to: [category])++ XCTAssertEqual(reviewed.flatMap(\.selectedItems).map(\.path), [recent.path])+ XCTAssertEqual(category.selectedItems.map(\.path), [old.path])+ }+}diff --git a/cli/Tests/puremacTests/CoreSafetyTests.swift b/cli/Tests/puremacTests/CoreSafetyTests.swiftnew file mode 100644index 0000000..e1a59aa--- /dev/null+++ b/cli/Tests/puremacTests/CoreSafetyTests.swift@@ -0,0 +1,152 @@+import XCTest+@testable import puremac++final class CoreSafetyTests: XCTestCase {+ private var root: URL!+ private let fileManager = FileManager.default++ override func setUpWithError() throws {+ try super.setUpWithError()+ let provisionalRoot = fileManager.temporaryDirectory+ .appendingPathComponent("puremac-core-tests-\(UUID().uuidString)", isDirectory: true)+ try fileManager.createDirectory(at: provisionalRoot, withIntermediateDirectories: true)+ root = provisionalRoot.resolvingSymlinksInPath()+ }++ override func tearDownWithError() throws {+ if let root { try? fileManager.removeItem(at: root) }+ try super.tearDownWithError()+ }++ func testIgnoredDescendantProtectsParentArtifact() throws {+ let project = root.appendingPathComponent("project", isDirectory: true)+ let artifact = project.appendingPathComponent("node_modules", isDirectory: true)+ let removable = project.appendingPathComponent("target", isDirectory: true)+ let keep = artifact.appendingPathComponent("keep.bin")+ try fileManager.createDirectory(at: artifact, withIntermediateDirectories: true)+ try fileManager.createDirectory(at: removable, withIntermediateDirectories: true)+ try Data(repeating: 1, count: 4096).write(to: keep)+ try Data(repeating: 2, count: 4096).write(to: removable.appendingPathComponent("cache.bin"))+ var ignore = try makeIgnoreStore()+ _ = try ignore.add(keep.path)++ let verdict = Safety.canRemove(artifact.path, ignore: ignore)+ let scan = Purger.scan(roots: [project.path], olderThanDays: 0, ignore: ignore)++ XCTAssertFalse(verdict.ok)+ XCTAssertEqual(verdict.reason, "ignored")+ XCTAssertEqual(+ scan.groups.flatMap(\.items).map { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path },+ [removable.resolvingSymlinksInPath().path]+ )+ XCTAssertTrue(fileManager.fileExists(atPath: keep.path))+ }++ func testCleanerRefusesSymlinkAtAnyPathComponent() throws {+ let target = root.appendingPathComponent("target", isDirectory: true)+ let victim = target.appendingPathComponent("victim.bin")+ let link = root.appendingPathComponent("link", isDirectory: true)+ try fileManager.createDirectory(at: target, withIntermediateDirectories: true)+ try Data(repeating: 2, count: 4096).write(to: victim)+ try fileManager.createSymbolicLink(at: link, withDestinationURL: target)+ let linkedVictim = link.appendingPathComponent("victim.bin")+ let item = ScanItem(path: linkedVictim.path, sizeBytes: 4096, modified: nil)++ let outcome = Cleaner.remove([item], ignore: try makeIgnoreStore(), dryRun: false)++ XCTAssertEqual(outcome.removed, 0)+ XCTAssertEqual(outcome.skipped.first?.reason, "symlink")+ XCTAssertTrue(fileManager.fileExists(atPath: victim.path))+ }++ func testCleanerRefusesPathReplacedAfterScan() throws {+ let artifact = root.appendingPathComponent("node_modules", isDirectory: true)+ let replacement = root.appendingPathComponent("replacement", isDirectory: true)+ try fileManager.createDirectory(at: artifact, withIntermediateDirectories: true)+ try Data(repeating: 3, count: 4096).write(to: artifact.appendingPathComponent("old.bin"))+ let item = ScanItem(path: artifact.path, sizeBytes: 4096, modified: nil)+ try fileManager.createDirectory(at: replacement, withIntermediateDirectories: true)+ let marker = replacement.appendingPathComponent("replacement.bin")+ try Data(repeating: 4, count: 4096).write(to: marker)+ try fileManager.removeItem(at: artifact)+ try fileManager.moveItem(at: replacement, to: artifact)++ let outcome = Cleaner.remove([item], ignore: try makeIgnoreStore(), dryRun: false)++ XCTAssertEqual(outcome.removed, 0)+ XCTAssertEqual(outcome.skipped.first?.reason, "changed since scan")+ XCTAssertTrue(fileManager.fileExists(atPath: artifact.appendingPathComponent("replacement.bin").path))+ }++ func testCleanerAccountsFreshMeasuredBytes() throws {+ let file = root.appendingPathComponent("cache.bin")+ try Data(repeating: 5, count: 8192).write(to: file)+ let item = ScanItem(path: file.path, sizeBytes: 99_999_999, modified: nil)+ let measured = DirSizer.measure(of: file.path)++ let outcome = Cleaner.remove([item], ignore: try makeIgnoreStore(), dryRun: false)++ XCTAssertEqual(measured.status, .complete)+ XCTAssertEqual(outcome.removed, 1)+ XCTAssertEqual(outcome.freedBytes, measured.bytes)+ XCTAssertNotEqual(outcome.freedBytes, item.sizeBytes)+ XCTAssertFalse(fileManager.fileExists(atPath: file.path))+ }++ func testProtectedAndCloudRootsFailClosed() throws {+ let ignore = try makeIgnoreStore()++ XCTAssertFalse(Safety.canRemove("/System/Library", ignore: ignore).ok)+ XCTAssertFalse(Safety.isValidScanRoot("/System/Library").ok)+ XCTAssertTrue(Safety.isCloudOrDataless("\(Safety.home)/Library/CloudStorage/Provider/file"))+ XCTAssertFalse(Safety.isValidScanRoot("\(Safety.home)/Library/CloudStorage/Provider").ok)+ }++ func testCandidateAndRootDeduplicationPreventsDoubleCounting() throws {+ let parent = root.appendingPathComponent("project", isDirectory: true)+ let child = parent.appendingPathComponent("nested", isDirectory: true)+ try fileManager.createDirectory(at: child, withIntermediateDirectories: true)++ let candidates = CategoryScanner.uniqueCandidates([+ (target: 1, path: child.path),+ (target: 0, path: parent.path),+ (target: 2, path: parent.path),+ ])+ let roots = Purger.scanRoots([child.path, parent.path, parent.path])++ XCTAssertEqual(candidates.count, 1)+ XCTAssertEqual(candidates.first?.path, parent.path)+ XCTAssertEqual(roots.map(\.path), [parent.path])+ }++ func testTemporaryAliasesRemainUsableButCustomSymlinksDoNot() throws {+ XCTAssertFalse(Safety.hasSymlinkComponent("/tmp/puremac-fixture"))+ XCTAssertFalse(Safety.hasSymlinkComponent("/var/folders/puremac-fixture"))+ let target = root.appendingPathComponent("target", isDirectory: true)+ let link = root.appendingPathComponent("custom-link", isDirectory: true)+ try fileManager.createDirectory(at: target, withIntermediateDirectories: true)+ try fileManager.createSymbolicLink(at: link, withDestinationURL: target)+ XCTAssertTrue(Safety.hasSymlinkComponent(link.appendingPathComponent("child").path))+ }++ func testRelativeProjectRootNormalizesWithoutChangingProcessDirectory() throws {+ let project = root.appendingPathComponent("project", isDirectory: true)+ try fileManager.createDirectory(at: project, withIntermediateDirectories: true)+ let originalDirectory = fileManager.currentDirectoryPath++ let normalized = Safety.absolutePath("./project", currentDirectory: root.path)+ let verdict = Safety.isValidScanRoot("./project", currentDirectory: root.path)++ XCTAssertEqual(+ URL(fileURLWithPath: normalized).resolvingSymlinksInPath().path,+ project.resolvingSymlinksInPath().path+ )+ XCTAssertTrue(verdict.ok)+ XCTAssertEqual(fileManager.currentDirectoryPath, originalDirectory)+ XCTAssertFalse(Safety.isValidScanRoot("/private/etc").ok)+ }++ private func makeIgnoreStore() throws -> IgnoreStore {+ try IgnoreStore(fileURL: root.appendingPathComponent("config/ignore"))+ }+}diff --git a/cli/Tests/puremacTests/OptimizeConfigTests.swift b/cli/Tests/puremacTests/OptimizeConfigTests.swiftnew file mode 100644index 0000000..eae76f8--- /dev/null+++ b/cli/Tests/puremacTests/OptimizeConfigTests.swift@@ -0,0 +1,141 @@+import Foundation+import XCTest+@testable import puremac++final class OptimizeConfigTests: XCTestCase {+ func testSnapshotParserAcceptsOnlyExactTimeMachineSnapshots() {+ let output = """+ Snapshots for disk /:+ com.apple.TimeMachine.2026-09-13-235959.local+ com.apple.os.update-123456+ com.apple.TimeMachine.2026-02-30-120000.local+ com.apple.TimeMachine.2026-09-14-090102.local extra+ com.apple.TimeMachine.2026-09-14-090102.local+ com.apple.TimeMachine.2026-09-14-090102.local+ """++ XCTAssertEqual(+ Optimize.parseLocalSnapshots(output),+ [+ "com.apple.TimeMachine.2026-09-14-090102.local",+ "com.apple.TimeMachine.2026-09-13-235959.local",+ ]+ )+ }++ func testLegacyOptimizeViewsRemainRecognized() throws {+ XCTAssertEqual(try Optimize.parse(["ram"]).task, "ram")+ XCTAssertEqual(try Optimize.parse(["purgeable"]).task, "purgeable")+ XCTAssertEqual(try Optimize.parse(["snapshots"]).task, "snapshots")+ XCTAssertNil(try Optimize.parse([]).task)+ }++ func testUptimeFormatting() {+ XCTAssertEqual(Optimize.formatUptime(0), "0m")+ XCTAssertEqual(Optimize.formatUptime(3_661), "1h 1m")+ XCTAssertEqual(Optimize.formatUptime(176_461), "2d 1h 1m")+ }++ func testManagedCapacityNeverBecomesNegative() {+ XCTAssertEqual(+ VolumeStatus(availableNow: 50, availableForImportantUsage: 80, total: 100)+ .systemManagedCapacity,+ 30+ )+ XCTAssertEqual(+ VolumeStatus(availableNow: 80, availableForImportantUsage: 50, total: 100)+ .systemManagedCapacity,+ 0+ )+ }++ func testConfigStoreValidatesAndPersistsToInjectedFile() throws {+ let directory = try temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let file = directory.appendingPathComponent("settings/config.json")++ var store = try ConfigStore(fileURL: file)+ try store.set("purge.older_than_days", " 14 ")+ XCTAssertEqual(store.values["purge.older_than_days"], "14")++ let reloaded = try ConfigStore(fileURL: file)+ XCTAssertEqual(reloaded.values["purge.older_than_days"], "14")+ XCTAssertThrowsError(try store.set("purge.older_than_days", "0"))+ XCTAssertThrowsError(try store.set("purge.older_than_days", "3651"))+ XCTAssertThrowsError(try store.set("unknown", "14"))+ }++ func testMalformedConfigAndPersistenceFailuresAreReported() throws {+ let directory = try temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let malformed = directory.appendingPathComponent("malformed.json")+ try Data("[]".utf8).write(to: malformed)+ XCTAssertThrowsError(try ConfigStore(fileURL: malformed))++ let blocker = directory.appendingPathComponent("blocked")+ try Data("file".utf8).write(to: blocker)+ var store = try ConfigStore(fileURL: blocker.appendingPathComponent("config.json"))+ XCTAssertThrowsError(try store.set("purge.older_than_days", "14"))+ XCTAssertTrue(store.values.isEmpty)+ }++ func testIgnoreStoreUsesInjectedFileAndRollsBackFailedSave() throws {+ let directory = try temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let file = directory.appendingPathComponent("settings/ignore")+ let protected = directory.appendingPathComponent("protected").path++ var store = try IgnoreStore(fileURL: file)+ XCTAssertTrue(try store.add(protected))+ XCTAssertTrue(store.isIgnored(protected + "/child"))+ XCTAssertEqual(try IgnoreStore(fileURL: file).roots, [protected])++ let blocker = directory.appendingPathComponent("blocked")+ try Data("file".utf8).write(to: blocker)+ var blocked = try IgnoreStore(fileURL: blocker.appendingPathComponent("ignore"))+ XCTAssertThrowsError(try blocked.add(protected))+ XCTAssertTrue(blocked.roots.isEmpty)+ }++ func testRelativeIgnorePathBecomesAbsoluteAndProtectsCandidate() throws {+ let directory = try temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let workingDirectory = directory.appendingPathComponent("working", isDirectory: true)+ let candidate = workingDirectory.appendingPathComponent("cache", isDirectory: true)+ try FileManager.default.createDirectory(at: candidate, withIntermediateDirectories: true)++ var store = try IgnoreStore(+ fileURL: directory.appendingPathComponent("ignore"),+ currentDirectoryPath: workingDirectory.path+ )+ XCTAssertTrue(try store.add("./cache"))+ XCTAssertFalse(try store.add("nested/../cache"))+ XCTAssertEqual(store.roots, [candidate.path])+ XCTAssertFalse(Safety.canRemove(candidate.path, ignore: store).ok)+ }++ func testIgnoreStoreRejectsControlCharactersAndLegacyRelativeEntries() throws {+ let directory = try temporaryDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let file = directory.appendingPathComponent("ignore")+ var store = try IgnoreStore(fileURL: file, currentDirectoryPath: directory.path)++ for path in ["", "one\ntwo", "one\rtwo", "one\0two"] {+ XCTAssertThrowsError(try store.add(path))+ XCTAssertThrowsError(try store.remove(path))+ }+ XCTAssertTrue(store.roots.isEmpty)+ var rootStore = try IgnoreStore(fileURL: file, currentDirectoryPath: "/")+ XCTAssertThrowsError(try rootStore.add("."))++ try Data("relative/path\n".utf8).write(to: file)+ XCTAssertThrowsError(try IgnoreStore(fileURL: file))+ }++ private func temporaryDirectory() throws -> URL {+ let directory = FileManager.default.temporaryDirectory+ .appendingPathComponent("puremac-cli-tests-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ return directory+ }+}diff --git a/cli/Tests/puremacTests/ShellTests.swift b/cli/Tests/puremacTests/ShellTests.swiftnew file mode 100644index 0000000..f2827c5--- /dev/null+++ b/cli/Tests/puremacTests/ShellTests.swift@@ -0,0 +1,59 @@+import Foundation+import XCTest+@testable import puremac++final class ShellTests: XCTestCase {+ func testArgumentsArePassedWithoutShellExpansion() {+ let result = Shell.run("/usr/bin/printf", ["%s", "$(echo injected); *"])++ XCTAssertEqual(result.status, 0)+ XCTAssertEqual(result.out, "$(echo injected); *")+ XCTAssertEqual(result.err, "")+ }++ func testMissingExecutableHasDeterministicError() {+ let path = "/path/that/does/not/exist/puremac-test"+ let result = Shell.run(path, [])++ XCTAssertEqual(result.status, 127)+ XCTAssertEqual(result.out, "")+ XCTAssertEqual(result.err, "not found: \(path)")+ }++ func testNonzeroExitWithoutStderrHasDeterministicError() {+ let result = Shell.run("/bin/sh", ["-c", "exit 7"])++ XCTAssertEqual(result.status, 7)+ XCTAssertEqual(result.out, "")+ XCTAssertEqual(result.err, "command exited with status 7")+ }++ func testTimeoutTerminatesTheDirectProcess() {+ let start = Date()+ let result = Shell.run("/bin/sh", ["-c", "exec /bin/sleep 5"], timeout: 0.05)++ XCTAssertEqual(result.status, 124)+ XCTAssertEqual(result.err, "command timed out")+ XCTAssertLessThan(Date().timeIntervalSince(start), 1.5)+ }++ func testBothOutputStreamsAreDrainedAndBounded() {+ let script = "/usr/bin/yes O | /usr/bin/head -c 1200000 & /usr/bin/yes E | /usr/bin/head -c 1200000 >&2 & wait"+ let result = Shell.run("/bin/sh", ["-c", script], timeout: 10)++ XCTAssertEqual(result.status, 0)+ XCTAssertLessThanOrEqual(result.out.utf8.count, Shell.outputLimit)+ XCTAssertLessThanOrEqual(result.err.utf8.count, Shell.outputLimit)+ XCTAssertTrue(result.out.hasSuffix("[output truncated]"))+ XCTAssertTrue(result.err.hasSuffix("[output truncated]"))+ }++ func testRunnerReturnsWhenDescendantKeepsPipeOpen() {+ let start = Date()+ let result = Shell.run("/bin/sh", ["-c", "/bin/sleep 2 & /usr/bin/printf done"], timeout: 1)++ XCTAssertEqual(result.status, 0)+ XCTAssertEqual(result.out, "done")+ XCTAssertLessThan(Date().timeIntervalSince(start), 1.5)+ }+}diff --git a/cli/Tests/puremacTests/TerminalUITests.swift b/cli/Tests/puremacTests/TerminalUITests.swiftnew file mode 100644index 0000000..1e9fe6b--- /dev/null+++ b/cli/Tests/puremacTests/TerminalUITests.swift@@ -0,0 +1,201 @@+import XCTest+@testable import puremac++final class TerminalUITests: XCTestCase {+ func testANSIAndUnicodeDisplayWidth() {+ XCTAssertEqual(Term.displayWidth("\u{1B}[31mclean\u{1B}[0m"), 5)+ XCTAssertEqual(Term.displayWidth("界"), 2)+ XCTAssertEqual(Term.displayWidth("a\u{301}"), 1)+ }++ func testTerminalControlCharactersAreSanitized() {+ XCTAssertEqual(Term.sanitize("safe\u{1B}[2Jname\n"), "safe�[2Jname�")+ XCTAssertEqual(Term.sanitize("one\ttwo"), "one two")+ }++ func testMiddleTruncationRespectsVisibleWidth() {+ let value = Term.truncate("/Users/example/Library/Caches/tool", to: 18, middle: true)+ XCTAssertLessThanOrEqual(Term.displayWidth(value), 18)+ XCTAssertTrue(value.contains("…"))+ XCTAssertTrue(value.hasPrefix("/Users/e"))+ XCTAssertTrue(value.hasSuffix("ches/tool"))+ }++ func testReviewStartsWithNothingSelected() {+ let model = InteractiveReviewModel(categories: fixtureCategories())+ XCTAssertEqual(model.selectedCount, 0)+ XCTAssertEqual(model.selectedBytes, 0)+ XCTAssertEqual(model.matchingAddresses.count, 3)+ }++ func testReviewSelectionAndSearchPreserveExactItems() {+ var model = InteractiveReviewModel(categories: fixtureCategories())+ model.toggleFocused()+ model.move(1)+ model.toggleFocused()+ XCTAssertEqual(model.selectedCount, 2)+ XCTAssertEqual(model.selectedBytes, 3_000)++ model.updateQuery("second")+ XCTAssertEqual(model.matchingAddresses.count, 1)+ XCTAssertEqual(model.item(at: model.matchingAddresses[0]).path, "/tmp/second")++ model.selectNone()+ model.selectAllMatching()+ XCTAssertEqual(model.selectedCount, 1)+ XCTAssertEqual(model.selectedResult()[0].selectedItems.map(\.path), ["/tmp/second"])+ }++ func testReviewRequiresSelectionBeforeFinalReview() {+ var model = InteractiveReviewModel(categories: fixtureCategories())+ XCTAssertFalse(model.beginReview())+ XCTAssertFalse(model.isReviewing)+ XCTAssertFalse(model.status.isEmpty)++ model.toggleFocused()+ XCTAssertTrue(model.beginReview())+ XCTAssertTrue(model.isReviewing)+ }++ func testReviewRenderIsBoundedAndKeepsControlsVisible() {+ var model = InteractiveReviewModel(categories: fixtureCategories())+ model.selectAllMatching()+ for (width, height) in [(40, 12), (58, 14), (80, 24)] {+ let lines = InteractiveReview.render(+ model: model,+ title: "Review removable files",+ width: width,+ height: height+ )++ XCTAssertEqual(lines.count, height)+ XCTAssertTrue(lines.contains { $0.contains("Space toggle") })+ XCTAssertTrue(lines.contains { $0.contains("Enter review") })+ XCTAssertTrue(lines.allSatisfy { Term.displayWidth($0) <= width })+ }+ }++ func testReviewHeaderFitsFortyColumnsWithDifferentCountsAndSizes() {+ let categories = [+ CategoryScan(+ id: "cache",+ title: "Caches",+ groups: [+ ToolGroup(+ tool: "Applications",+ items: [+ ScanItem(path: "/tmp/one", sizeBytes: 138_300, modified: nil),+ ScanItem(path: "/tmp/two", sizeBytes: 1_000, modified: nil)+ ]+ )+ ]+ )+ ]+ let model = InteractiveReviewModel(categories: categories)+ let lines = InteractiveReview.render(+ model: model,+ title: "Review removable files",+ width: 40,+ height: 12+ )++ XCTAssertEqual(Term.displayWidth(lines[2]), 40)+ XCTAssertTrue(lines[2].contains("2 shown"))+ XCTAssertTrue(lines[2].contains("0 selected"))+ XCTAssertTrue(lines.allSatisfy { Term.displayWidth($0) <= 40 })+ }++ func testFinalReviewControlsFitAtMinimumSupportedWidth() {+ var model = InteractiveReviewModel(categories: fixtureCategories())+ model.selectAllMatching()+ XCTAssertTrue(model.beginReview())+ let lines = InteractiveReview.render(+ model: model,+ title: "Review removable files",+ width: 40,+ height: 12+ )+ XCTAssertEqual(lines.count, 12)+ XCTAssertTrue(lines.contains { $0.contains("Enter confirm") })+ XCTAssertTrue(lines.contains { $0.contains("q cancel") })+ XCTAssertTrue(lines.allSatisfy { Term.displayWidth($0) <= 40 })+ }++ func testCompactReviewDoesNotLieAboutTerminalDimensions() {+ let model = InteractiveReviewModel(categories: fixtureCategories())+ let lines = InteractiveReview.render(+ model: model,+ title: "Review",+ width: 18,+ height: 4+ )++ XCTAssertEqual(lines.count, 4)+ XCTAssertTrue(lines.contains { $0.contains("too small") })+ XCTAssertTrue(lines.allSatisfy { Term.displayWidth($0) <= 18 })+ }++ func testFocusedPathWindowCanRevealEntirePath() {+ let path = "/Users/example/Library/Caches/application/data"+ let first = InteractiveReview.horizontalWindow(path, offset: 0, width: 20)+ let last = InteractiveReview.horizontalWindow(path, offset: 30, width: 20)++ XCTAssertTrue(first.hasSuffix("›"))+ XCTAssertTrue(last.hasPrefix("‹"))+ XCTAssertLessThanOrEqual(Term.displayWidth(first), 20)+ XCTAssertLessThanOrEqual(Term.displayWidth(last), 20)+ }++ func testMenuSelectionClampsAndRenderPaginates() {+ var model = TerminalMenuModel(optionCount: 8)+ model.move(99)+ XCTAssertEqual(model.selection, 7)+ model.move(-99)+ XCTAssertEqual(model.selection, 0)+ XCTAssertEqual(model.select(number: 7), 6)+ XCTAssertEqual(model.selection, 6)+ XCTAssertNil(model.select(number: 9))+ XCTAssertNil(model.select(number: 0))++ let options = (1...8).map { (title: "Tool \($0)", detail: "Description \($0)") }+ for (width, height) in [(40, 12), (80, 24)] {+ let lines = TerminalMenu.render(+ title: "PureMac",+ subtitle: "Choose a task",+ options: options,+ selection: 6,+ width: width,+ height: height+ )+ XCTAssertEqual(lines.count, height)+ XCTAssertTrue(lines.contains { $0.contains("Tool 7") })+ XCTAssertTrue(lines.contains { $0.contains("Enter open") })+ XCTAssertTrue(lines.contains { $0.contains("1-9 open") })+ XCTAssertTrue(lines.allSatisfy { Term.displayWidth($0) <= width })+ }+ }++ private func fixtureCategories() -> [CategoryScan] {+ [+ CategoryScan(+ id: "dev",+ title: "Developer",+ groups: [+ ToolGroup(+ tool: "Build caches",+ items: [+ ScanItem(path: "/tmp/first", sizeBytes: 1_000, modified: nil, selected: true),+ ScanItem(path: "/tmp/second", sizeBytes: 2_000, modified: nil, selected: true)+ ]+ ),+ ToolGroup(+ tool: "Package caches",+ items: [+ ScanItem(path: "/tmp/third", sizeBytes: 3_000, modified: nil, selected: false)+ ]+ )+ ]+ )+ ]+ }+}diff --git a/cli/Tests/puremacTests/puremacTests.swift b/cli/Tests/puremacTests/puremacTests.swiftindex cd243d3..ded7b31 100644--- a/cli/Tests/puremacTests/puremacTests.swift+++ b/cli/Tests/puremacTests/puremacTests.swift@@ -75,7 +75,8 @@ final class PureMacTests: XCTestCase {try? FileManager.default.createDirectory(atPath: tmp, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(atPath: tmp) }- var ig = IgnoreStore()+ let ignoreFile = URL(fileURLWithPath: tmp).appendingPathComponent("ignore")+ var ig = try IgnoreStore(fileURL: ignoreFile)XCTAssertTrue(Safety.canRemove(tmp, ignore: ig).ok)_ = try ig.add(tmp)diff --git a/cli/screenshots/clean.png b/cli/screenshots/clean.pngindex 531e8aa..2a544c4 100644Binary files a/cli/screenshots/clean.png and b/cli/screenshots/clean.png differdiff --git a/cli/screenshots/workspace.png b/cli/screenshots/workspace.pngnew file mode 100644index 0000000..eb0f75dBinary files /dev/null and b/cli/screenshots/workspace.png differdiff --git a/scripts/release-cli-local.sh b/scripts/release-cli-local.shnew file mode 100755index 0000000..5befef8--- /dev/null+++ b/scripts/release-cli-local.sh@@ -0,0 +1,75 @@+#!/usr/bin/env bash+set -euo pipefail++VERSION="${1:?Usage: $0 <version> [notary_profile]}"+NOTARY_PROFILE="${2:-AC_NOTARY}"+SIGN_ID="Developer ID Application: Moamen Basel (H3WXHVTP97)"+cd "$(dirname "$0")/.."++SEMVER_RE='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$'+[[ "${VERSION}" =~ ${SEMVER_RE} ]] || { echo 'Invalid version' >&2; exit 1; }+[[ "$(awk -F '"' '/^let puremacVersion = / {print $2}' cli/Sources/puremac/PureMac.swift)" == "${VERSION}" ]] || {+ echo 'CLI source version does not match requested release' >&2+ exit 1+}+if ! git diff --quiet || ! git diff --cached --quiet || [[ -n "$(git ls-files --others --exclude-standard -- cli scripts/release-cli-local.sh)" ]]; then+ echo 'Commit release inputs before building' >&2+ exit 1+fi+git fetch --no-tags origin main+BUILD_SHA=$(git rev-parse 'HEAD^{commit}')+[[ "${BUILD_SHA}" == "$(git rev-parse 'origin/main^{commit}')" ]] || {+ echo 'Release commit must equal origin/main' >&2+ exit 1+}+OUTPUT="${PWD}/_work/cli-release/${VERSION}/${BUILD_SHA}"+[[ ! -e "${OUTPUT}" ]] || { echo "Output already exists: ${OUTPUT}" >&2; exit 1; }+mkdir -p "${OUTPUT}/stage"++swift test --package-path cli --scratch-path "${OUTPUT}/tests"+for ARCH in arm64 x86_64; do+ swift build --package-path cli -c release --arch "${ARCH}" --scratch-path "${OUTPUT}/build-${ARCH}"+ BIN_DIR=$(swift build --package-path cli -c release --arch "${ARCH}" --scratch-path "${OUTPUT}/build-${ARCH}" --show-bin-path)+ cp "${BIN_DIR}/puremac" "${OUTPUT}/puremac-${ARCH}"+done+lipo -create "${OUTPUT}/puremac-arm64" "${OUTPUT}/puremac-x86_64" -output "${OUTPUT}/stage/puremac"+chmod 755 "${OUTPUT}/stage/puremac"+codesign --sign "${SIGN_ID}" --timestamp --options runtime --identifier com.puremac.cli "${OUTPUT}/stage/puremac"+codesign --verify --strict --verbose=2 "${OUTPUT}/stage/puremac"+ARCHS=$(lipo -archs "${OUTPUT}/stage/puremac")+[[ " ${ARCHS} " == *' arm64 '* && " ${ARCHS} " == *' x86_64 '* ]]+[[ "$("${OUTPUT}/stage/puremac" --version)" == "${VERSION}" ]]+cp LICENSE "${OUTPUT}/stage/LICENSE"+ditto -c -k "${OUTPUT}/stage" "${OUTPUT}/notary.zip"+xcrun notarytool submit "${OUTPUT}/notary.zip" --keychain-profile "${NOTARY_PROFILE}" --wait --timeout 30m --output-format json > "${OUTPUT}/notarization.json"+jq -e '.status == "Accepted"' "${OUTPUT}/notarization.json" >/dev/null+NOTARY_ID=$(jq -r '.id' "${OUTPUT}/notarization.json")+xcrun notarytool log "${NOTARY_ID}" --keychain-profile "${NOTARY_PROFILE}" "${OUTPUT}/notarization-log.json"+codesign --verify --strict --verbose=2 "${OUTPUT}/stage/puremac"+NOTARY_SHA=$(shasum -a 256 "${OUTPUT}/notary.zip" | awk '{print $1}')+ARM_HASH=$(codesign -d --arch arm64 --verbose=4 "${OUTPUT}/stage/puremac" 2>&1 | awk -F= '$1 == "CDHash" {print $2}')+INTEL_HASH=$(codesign -d --arch x86_64 --verbose=4 "${OUTPUT}/stage/puremac" 2>&1 | awk -F= '$1 == "CDHash" {print $2}')+jq -e --arg archive "${NOTARY_SHA}" --arg arm "${ARM_HASH}" --arg intel "${INTEL_HASH}" '+ .status == "Accepted" and .sha256 == $archive+ and any(.ticketContents[]; .arch == "arm64" and .cdhash == $arm)+ and any(.ticketContents[]; .arch == "x86_64" and .cdhash == $intel)+' "${OUTPUT}/notarization-log.json" >/dev/null+COPYFILE_DISABLE=1 tar -czf "${OUTPUT}/puremac-cli-${VERSION}.tar.gz" -C "${OUTPUT}/stage" puremac LICENSE+mkdir "${OUTPUT}/verified"+tar -xzf "${OUTPUT}/puremac-cli-${VERSION}.tar.gz" -C "${OUTPUT}/verified"+cmp "${OUTPUT}/stage/puremac" "${OUTPUT}/verified/puremac"+codesign --verify --strict --verbose=2 "${OUTPUT}/verified/puremac"+[[ "$(lipo -archs "${OUTPUT}/verified/puremac")" == "${ARCHS}" ]]+[[ "$("${OUTPUT}/verified/puremac" --version)" == "${VERSION}" ]]+BINARY_SHA=$(shasum -a 256 "${OUTPUT}/verified/puremac" | awk '{print $1}')+(+ cd "${OUTPUT}"+ shasum -a 256 "puremac-cli-${VERSION}.tar.gz" > SHA256SUMS+)+jq -n --arg version "${VERSION}" --arg commit "${BUILD_SHA}" --arg binary_sha256 "${BINARY_SHA}" \+ --arg arm64_cdhash "${ARM_HASH}" --arg x86_64_cdhash "${INTEL_HASH}" --arg notarization_id "${NOTARY_ID}" \+ '{version:$version,commit:$commit,binary_sha256:$binary_sha256,arm64_cdhash:$arm64_cdhash,x86_64_cdhash:$x86_64_cdhash,notarization_id:$notarization_id}' \+ > "${OUTPUT}/release-verification.json"+printf 'Commit: %s\nArchitectures: %s\nApple notarization: %s\nArchive: %s\n' "${BUILD_SHA}" "${ARCHS}" "${NOTARY_ID}" "${OUTPUT}/puremac-cli-${VERSION}.tar.gz"+printf '%s\n' 'Signed command-line executables cannot carry a stapled ticket. Apple acceptance is recorded in notarization.json.'+printf '%s\n' 'This script prepares artifacts. It does not publish a release or update Homebrew.'