import Foundation /// What this app reports, to whom, and — mostly — when it says nothing. /// /// **The Mac's file, ported back to the phone it was written for.** The Mac /// keeps the doctrine in `CottonClient/Reporting.swift` and this is the same /// decision in the same shape, so the two apps cannot drift on when a build is /// allowed to speak. AGENTS.md states the three rules and they are all here: /// **a Debug build never sends**, **the label is build-variant truth**, and /// **nothing is uploaded to Bugsink** — no dSYM, no source map. Bugsink stores a /// dSYM without ever reading one (bugsink#20), which is why the shipping lane /// keeps the archive's dSYMs instead and `sentry-upload-target.test.ts` holds /// that the lane uploads nothing. /// /// **The sink that sends lives in the app target**, not here: /// `App/Cotton/Reporting+Sentry.swift` is the one file that imports Sentry, /// `BugsinkReporting.start()` runs at `CottonApp.init` and installs a sending /// sink when the plan says to, and the three extensions keep the dropping one — /// they run in their own processes and none of them has anything to say that /// the app would not say first. The DSN is `CottonSentryDSN` in the app's /// Info.plist, stamped by the shipping lane from `COTTON_SENTRY_DSN` /// (`project.yml`, the fastlane lane `ios_beta!`); a build nobody gave one /// to drops, exactly as the Mac's does — one silent path, not two. /// /// **Every report is DRESSED before it is scrubbed and sent.** A sentence with /// nothing around it is a report an agent cannot act on, and every one the owner /// wrote by hand arrived that way: no build, no device, no screen, no log. So /// `report` adds what the call site should not have to know — the release, the /// device model, the OS, the route the person was on, and the last two hundred /// log lines (`Log.swift`) — and `scrub` folds the home directory out of all of /// it, log included. `dressed(_:with:)` is the pure half a test can reach. /// /// **Why a seam rather than `print` at each site.** Half a dozen branches across /// `CottonUI` and `CottonKit` were written with "there is no Bugsink client in /// this app yet (4l)" beside them. A seam is what turns those into one line each /// that keeps working when the sink arrives, instead of a sweep somebody has to /// remember to do. /// Which build this is, in the words Bugsink files an event under. public enum ReportLabel: String, Sendable, Equatable { case development case production } /// The facts about the running binary that decide everything here. public struct BuildFacts: Sendable, Equatable { /// `CottonSentryDSN` from the bundle. Empty on every build today — see the /// type comment. The KEY is the Mac's, deliberately: one name for one thing. public let dsn: String /// `CottonBuildVariant` from the bundle — `$(CONFIGURATION)`, which /// `project.yml` stamps, so it reads `Release` on an archive and `Debug` on /// everything else. Build-variant truth with no script to forget. public let variant: String /// Is this one of the four bundles this app ships? An XCTest host is not, /// and neither is a preview. public let packaged: Bool /// `CFBundleShortVersionString` and `CFBundleVersion`. public let version: String public let build: String /// Which app this is, as Bugsink files it: `cotton-ios` for the phone and /// its three extensions, `cottondb-mac` for the Mac. The release name is /// `@+`, and the two names are what the server has /// been filing under since each app first reported — an identity, not a /// label to tidy. public let app: String /// `CottonBuildCommit` — the commit the bundle was built from, which the /// phone's four Info.plists carry as `$(COTTON_BUILD_COMMIT)` (`project.yml`). Empty where nothing stamped /// it: a phone build whose builder passed no commit, a test host. public let commit: String /// `CottonFlavor` — the real CottonDB or Cotton Dev (`AppFlavor.of`). /// One Bugsink project serves both, so every event carries it: without it /// a dev crash and a real one were the same event (prod item 17). public let flavor: AppFlavor public init( dsn: String, variant: String, packaged: Bool, version: String, build: String, app: String = "cotton-ios", commit: String = "", flavor: AppFlavor = .dev ) { self.dsn = dsn self.variant = variant self.packaged = packaged self.version = version self.build = build self.app = app self.commit = commit self.flavor = flavor } /// Whether this is a release build — the variant the release lane /// stamps (`COTTON_BUILD_VARIANT=release`; the phone's archive says /// `Release`). public var isRelease: Bool { variant.lowercased() == "release" } /// **A build that is not the release says which commit it is.** A Mac ran /// a local build on 29 Sep 2026 that read 0.22.0 (61) — the release's own /// version and build number, because a local build keeps them — and /// nothing on it said it was not the release. A release keeps its look: /// `nil` there, and `nil` where no commit was stamped. public var commitShown: String? { guard !isRelease, !commit.isEmpty else { return nil } return commit } /// The Build row's value: the build number, and on a build that is not /// the release the commit beside it — "61 · commit 1a2b3c4d5". public var buildShown: String { guard let commit = commitShown else { return build } return build.isEmpty ? "commit \(commit)" : "\(build) \u{00B7} commit \(commit)" } /// `@+` — `cotton-ios@…` or `cottondb-mac@…`. A /// versionless build still names a release rather than an empty string. public var release: String { "\(app)@\(version.isEmpty ? "0.0.0" : version)+\(build.isEmpty ? "0" : build)" } /// The keys `project.yml` stamps into all four Info.plists. public enum Key { public static let dsn = "CottonSentryDSN" public static let variant = "CottonBuildVariant" /// The commit, stamped by the phone's `project.yml`. public static let commit = "CottonBuildCommit" } /// The app and its three extensions — THIS build's flavor's /// (`AppFlavor.phoneAppID`). The real one is immutable (AGENTS.md's list). public static let bundlePrefix = AppFlavor.current.phoneAppID /// CottonDB for Mac — this build's flavor's. The real one is also /// immutable: it is the Sparkle feed's identity. public static let macBundleID = AppFlavor.current.macBundleID /// What the running bundle says about itself. public static func fromBundle(_ bundle: Bundle = .main) -> BuildFacts { let string = { (key: String) -> String in (bundle.object(forInfoDictionaryKey: key) as? String) ?? "" } // The bundle identifier is the honest test, as it is on the Mac: an // xctest bundle has an Info.plist of some sort and it is not this app's. // A PREFIX rather than equality, because the share sheet reports // under its own id. // EITHER flavor's ids count: whether a bundle is packaged is about the // bundle, and a Cotton Dev install is as packaged as the real one. let identifier = bundle.bundleIdentifier ?? "" let isMac = AppFlavor.allCases.contains { identifier == $0.macBundleID } let isPhone = AppFlavor.allCases.contains { identifier == $0.phoneAppID || identifier.hasPrefix("\($0.phoneAppID).") } return BuildFacts( dsn: string(Key.dsn), variant: string(Key.variant), packaged: isMac || isPhone, version: string("CFBundleShortVersionString"), build: string("CFBundleVersion"), app: isMac ? "cottondb-mac" : "cotton-ios", commit: string(Key.commit), flavor: AppFlavor.of(bundle) ) } } /// The decision, as a value: does anything go out, under what label, and why. /// /// A REASON on both arms, because "reporting is off" is a thing a person may /// have to be told, and a silence with no explanation is the failure mode this /// whole file exists to avoid. public struct ReportingPlan: Sendable, Equatable { public let sends: Bool public let dsn: String public let label: ReportLabel /// `@+` — `cotton-ios@…` or `cottondb-mac@…`. public let release: String public let reason: String /// Which app is reporting. Both apps share one Bugsink project, so this /// rides on every event as the `flavor` tag AND in `environment`. public let flavor: AppFlavor /// The Bugsink environment: the build variant for the real app, as it has /// always been, and `-dev` for Cotton Dev — so the environment /// filter alone tells a dev event from a real one. public var environment: String { flavor == .real ? label.rawValue : "\(label.rawValue)-dev" } /// The tag key the flavor is filed under. public static let flavorTag = "flavor" } /// Whether this build reports, from the facts and the compiler's own. /// /// Four "no"s, in the order they are cheap to answer: /// /// 1. **A DEBUG build never sends.** The `__DEV__` rule, one language over. /// 2. **An unpackaged run never sends** — a test host or a preview is a /// developer at a machine, and their errors are on their screen already. /// 3. **No DSN, nothing to send to.** A build nobody configured is not broken. /// The address is this Mac's own when its page names one (`pointedAt`, the /// `errorReportsTo` host setting) and the build's otherwise: where reports /// go is the person's to say, and a build is stamped with a default, not a /// destination nobody can change. /// 4. **The person said no.** `turnedOff` is the Mac's Error reports switch /// (this Mac's device page, cached in `HostSettings.sendsErrorReports`), and it is asked /// FIRST of the three that are about this run rather than about the build: /// a person who turned reporting off has not asked for a quieter version of /// it, and a plan that still carried a DSN would be one `start` could /// accidentally honour. /// /// The LABEL is decided whether or not anything is sent, so `reason` can say /// what the build is as well as what it does. public func reportingPlan( _ facts: BuildFacts, debugBuild: Bool, turnedOff: Bool = false, pointedAt: String? = nil ) -> ReportingPlan { // Build-variant truth: the CONFIGURATION the archive was built in, not the // compiler flag — the two agree today and the label should keep saying what // the build IS if they ever stop. // Case-insensitively: the phone's `project.yml` stamps `$(CONFIGURATION)` // as `Release`. let label: ReportLabel = facts.variant.lowercased() == "release" ? .production : .development let release = facts.release func off(_ reason: String) -> ReportingPlan { ReportingPlan(sends: false, dsn: "", label: label, release: release, reason: reason, flavor: facts.flavor) } if debugBuild { return off("a DEBUG build never sends") } if turnedOff { return off("you turned error reports off") } if !facts.packaged { return off("this is not one of the app's own bundles, so nothing is reported") } let pointed = pointedAt?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" let dsn = pointed.isEmpty ? facts.dsn : pointed if dsn.isEmpty { return off("this build carries no Bugsink address") } return ReportingPlan( sends: true, dsn: dsn, label: label, release: release, reason: "reporting as \(label.rawValue), \(release)", flavor: facts.flavor ) } /// One thing worth reporting. /// /// `kind` is the coarse bucket Bugsink groups on; `message` is the sentence. /// Both are ours — **nothing here carries a person's data**, and `context` is a /// small map of facts about the software, never about the owner. That is a rule /// about the call sites, not something this file can enforce: a report is /// written by hand, and a record's text never goes in one. public struct Report: Sendable, Equatable { public enum Kind: String, Sendable { /// The core answered something this app could not read — the `catch` /// that has to stringify because the error was not a `CottonCallError`. case unreadableAnswer /// A panic caught at the FFI boundary, carrying Rust's own message. case corePanic /// A refusal on a call that had no business refusing: this build asked /// the core for a method it does not answer, which is a build shipped /// against the wrong core rather than anything a person did. case unexpectedRefusal /// An exception nobody caught. case uncaught /// A page column that did not settle (`ColumnTripwire`): held for a /// second rather than freezing the phone. case layoutStorm } public let kind: Kind public let message: String public let context: [String: String] /// The log ring as it stood when the report was made — `Reporting.report` /// fills it; a call site never does. public let log: [String] public init(kind: Kind, message: String, context: [String: String] = [:], log: [String] = []) { self.kind = kind self.message = message self.context = context self.log = log } } /// What this phone is, in the two words a report needs. Not `DeviceFacts`: /// that is the push registrar's, and says who this phone is to a server. public struct Hardware: Sendable, Equatable { /// `iPhone16,2` — the hardware identifier, which is what a crash log and /// App Store Connect say too. On the simulator, the model it stands in for. public let model: String /// `iOS 18.6.1`. public let os: String public init(model: String, os: String) { self.model = model self.os = os } public static func current() -> Hardware { let version = ProcessInfo.processInfo.operatingSystemVersion let release = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" #if os(macOS) // `Mac15,12` — what a crash log and About This Mac say. `uname`'s // machine field is the architecture on a Mac, not the model. var size = 0 sysctlbyname("hw.model", nil, &size, nil, 0) var raw = [CChar](repeating: 0, count: max(size, 1)) sysctlbyname("hw.model", &raw, &size, nil, 0) let model = String(cString: raw) return Hardware(model: model.isEmpty ? "Mac" : model, os: "macOS \(release)") #else var system = utsname() uname(&system) let machine = withUnsafeBytes(of: &system.machine) { raw in String(decoding: raw.prefix(while: { $0 != 0 }), as: UTF8.self) } // The simulator's `uname` answers the Mac's own architecture; the // phone it pretends to be is in its environment. let environment = ProcessInfo.processInfo.environment let model = environment["SIMULATOR_MODEL_IDENTIFIER"].map { "\($0) (simulator)" } ?? machine return Hardware(model: model, os: "iOS \(release)") #endif } } /// Everything a report is dressed with. Gathered by `Reporting.report` from /// the live process; handed in whole by a test. public struct Surroundings: Sendable, Equatable { public let release: String public let device: Hardware public let route: String public let log: [String] public init(release: String, device: Hardware, route: String, log: [String]) { self.release = release self.device = device self.route = route self.log = log } } /// Where a report goes. One method, because a message is all Bugsink can read. public protocol ReportSink: Sendable { func send(_ report: Report) } /// The sink a build with nothing configured has: it drops, silently and on /// purpose. Every `Reporting.report` call site is written against this, so the /// call sites are the same in every build. public struct DroppingSink: ReportSink { public init() {} public func send(_ report: Report) {} } /// The process-wide seam. /// /// The app target installs a sending sink at launch if the plan says to send /// (the follow-up named at the top of this file); everything else — including /// `CottonUI`, which is where the branches worth reporting live — calls /// `Reporting.report(…)` and never learns which sink is behind it. That is also /// why the decision lives HERE, in a target the tests can reach. public enum Reporting { private static let lock = NSLock() nonisolated(unsafe) private static var sink: ReportSink = DroppingSink() public static func install(_ sink: ReportSink) { lock.lock() defer { lock.unlock() } Reporting.sink = sink } public static func current() -> ReportSink { lock.lock() defer { lock.unlock() } return sink } nonisolated(unsafe) private static var routeNow: String = "/" /// The screen the person is on, as `RootView` last said. A report made /// anywhere carries it, which is how a sentence about a share or a sync /// gets a screen beside it. public static func noteRoute(_ path: String) { lock.lock() defer { lock.unlock() } routeNow = path } public static func route() -> String { lock.lock() defer { lock.unlock() } return routeNow } /// Dress, scrub, send — in that order, so the log lines are scrubbed too. public static func report(_ report: Report) { let surroundings = Surroundings( release: BuildFacts.fromBundle().release, device: Hardware.current(), route: route(), log: Log.ring.rendered() ) current().send(scrub(dressed(report, with: surroundings))) } /// The four facts and the ring, added to a report. /// /// A call site that already named a `route` — the share seam reports the /// route IT was serving, which may not be the screen that is /// up — keeps its own; the rest are always the process's. The log is /// always the ring's: a call site has no log of its own to bring. public static func dressed(_ report: Report, with surroundings: Surroundings) -> Report { var context = report.context let facts = [ "release": surroundings.release, "device": surroundings.device.model, "os": surroundings.device.os, "route": surroundings.route, ] for (key, value) in facts where context[key] == nil { context[key] = value } return Report(kind: report.kind, message: report.message, context: context, log: surroundings.log) } /// The one rule about what leaves this phone: **no home directory path**. /// /// An iOS container path is a UUID rather than a person's name, so this /// carries less here than it does on the Mac — but the app group, the /// snapshot temp file and the media store all appear in these messages, and /// folding them to `~` costs nothing and means a sink cannot forget. /// Nothing else is redacted: a sentence that has been rewritten is a /// sentence nobody can act on. public static func scrub(_ report: Report, home: String = NSHomeDirectory()) -> Report { guard !home.isEmpty, home != "/" else { return report } let fold = { (text: String) in text.replacingOccurrences(of: home, with: "~") } return Report( kind: report.kind, message: fold(report.message), context: report.context.mapValues(fold), log: report.log.map(fold) ) } /// The FFI boundary's own reading of an error. /// /// A `CottonCallError` is a refusal the product WROTE — `no_rail`, /// `device_not_approved`, a sort column that is not in the spec — and those /// are answers, not incidents. The two exceptions are the panic code, which /// is Rust falling over inside a worker, and everything that is not a /// `CottonCallError` at all, which is the boundary itself surprising us. /// `nil` means "this one is not worth an event". public static func reportable(_ error: Error, method: String) -> Report? { if let call = error as? CottonCallError { guard call.code == "panic" else { return nil } return Report( kind: .corePanic, message: call.message, context: ["method": method, "code": call.code] ) } return Report( kind: .unreadableAnswer, message: "\(error)", context: ["method": method] ) } }