importFoundation/// 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.publicenumReportLabel: String, Sendable, Equatable {case developmentcase production}/// The facts about the running binary that decide everything here.publicstructBuildFacts: 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.publiclet 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.publiclet variant: String/// Is this one of the four bundles this app ships? An XCTest host is not,/// and neither is a preview.publiclet packaged: Bool/// `CFBundleShortVersionString` and `CFBundleVersion`.publiclet version: Stringpubliclet 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/// `<app>@<version>+<build>`, and the two names are what the server has/// been filing under since each app first reported — an identity, not a/// label to tidy.publiclet 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.publiclet 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).publiclet flavor: AppFlavorpublicinit( dsn: String, variant: String, packaged: Bool, version: String, build: String, app: String = "cotton-ios", commit: String = "", flavor: AppFlavor = .dev ) {self.dsn = dsnself.variant = variantself.packaged = packagedself.version = versionself.build = buildself.app = appself.commit = commitself.flavor = flavor }/// Whether this is a release build — the variant the release lane/// stamps (`COTTON_BUILD_VARIANT=release`; the phone's archive says/// `Release`).publicvar 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.publicvar commitShown: String? {guard !isRelease, !commit.isEmpty else { returnnil }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".publicvar buildShown: String {guardlet commit = commitShown else { return build }return build.isEmpty ? "commit \(commit)" : "\(build) \u{00B7} commit \(commit)" }/// `<app>@<version>+<build>` — `cotton-ios@…` or `cottondb-mac@…`. A/// versionless build still names a release rather than an empty string.publicvar release: String {"\(app)@\(version.isEmpty ? "0.0.0" : version)+\(build.isEmpty ? "0" : build)" }/// The keys `project.yml` stamps into all four Info.plists.publicenumKey {publicstaticlet dsn = "CottonSentryDSN"publicstaticlet variant = "CottonBuildVariant"/// The commit, stamped by the phone's `project.yml`.publicstaticlet commit = "CottonBuildCommit" }/// The app and its three extensions — THIS build's flavor's/// (`AppFlavor.phoneAppID`). The real one is immutable (AGENTS.md's list).publicstaticlet 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.publicstaticlet macBundleID = AppFlavor.current.macBundleID/// What the running bundle says about itself.publicstaticfunc fromBundle(_ bundle: Bundle = .main) -> BuildFacts {let string = { (key: String) -> Stringin (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).") }returnBuildFacts( 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.publicstructReportingPlan: Sendable, Equatable {publiclet sends: Boolpubliclet dsn: Stringpubliclet label: ReportLabel/// `<app>@<version>+<build>` — `cotton-ios@…` or `cottondb-mac@…`.publiclet release: Stringpubliclet 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`.publiclet flavor: AppFlavor/// The Bugsink environment: the build variant for the real app, as it has/// always been, and `<variant>-dev` for Cotton Dev — so the environment/// filter alone tells a dev event from a real one.publicvar environment: String { flavor == .real ? label.rawValue : "\(label.rawValue)-dev" }/// The tag key the flavor is filed under.publicstaticlet 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.publicfunc 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 : .developmentlet release = facts.releasefunc 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 : pointedif dsn.isEmpty {return off("this build carries no Bugsink address") }returnReportingPlan( 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.publicstructReport: Sendable, Equatable {publicenumKind: 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 }publiclet kind: Kindpubliclet message: Stringpubliclet context: [String: String]/// The log ring as it stood when the report was made — `Reporting.report`/// fills it; a call site never does.publiclet log: [String]publicinit(kind: Kind, message: String, context: [String: String] = [:], log: [String] = []) {self.kind = kindself.message = messageself.context = contextself.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.publicstructHardware: 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.publiclet model: String/// `iOS 18.6.1`.publiclet os: Stringpublicinit(model: String, os: String) {self.model = modelself.os = os }publicstaticfunc current() -> Hardware {let version = ProcessInfo.processInfo.operatingSystemVersionlet 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)returnHardware(model: model.isEmpty ? "Mac" : model, os: "macOS \(release)") #elsevar system = utsname() uname(&system)let machine = withUnsafeBytes(of: &system.machine) { raw inString(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.environmentlet model = environment["SIMULATOR_MODEL_IDENTIFIER"].map { "\($0) (simulator)" } ?? machinereturnHardware(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.publicstructSurroundings: Sendable, Equatable {publiclet release: Stringpubliclet device: Hardwarepubliclet route: Stringpubliclet log: [String]publicinit(release: String, device: Hardware, route: String, log: [String]) {self.release = releaseself.device = deviceself.route = routeself.log = log }}/// Where a report goes. One method, because a message is all Bugsink can read.publicprotocolReportSink: 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.publicstructDroppingSink: ReportSink {publicinit() {}publicfunc 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.publicenumReporting {privatestaticlet lock = NSLock() nonisolated(unsafe) privatestaticvar sink: ReportSink = DroppingSink()publicstaticfunc install(_ sink: ReportSink) { lock.lock()defer { lock.unlock() }Reporting.sink = sink }publicstaticfunc current() -> ReportSink { lock.lock()defer { lock.unlock() }return sink } nonisolated(unsafe) privatestaticvar 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.publicstaticfunc noteRoute(_ path: String) { lock.lock()defer { lock.unlock() } routeNow = path }publicstaticfunc route() -> String { lock.lock()defer { lock.unlock() }return routeNow }/// Dress, scrub, send — in that order, so the log lines are scrubbed too.publicstaticfunc 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.publicstaticfunc dressed(_ report: Report, with surroundings: Surroundings) -> Report {var context = report.contextlet 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 }returnReport(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.publicstaticfunc scrub(_ report: Report, home: String = NSHomeDirectory()) -> Report {guard !home.isEmpty, home != "/"else { return report }let fold = { (text: String) in text.replacingOccurrences(of: home, with: "~") }returnReport( 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".publicstaticfunc reportable(_ error: Error, method: String) -> Report? {iflet call = error as? CottonCallError {guard call.code == "panic"else { returnnil }returnReport( kind: .corePanic, message: call.message, context: ["method": method, "code": call.code] ) }returnReport( kind: .unreadableAnswer, message: "\(error)", context: ["method": method] ) }}