// The OS is asked in ONE file, and the platform objects are built in ONE place // each — held to it by a sweep rather than by a comment. CapabilityGateSweepTests.swift // (CottonUITests), ported to vitest: it only ever read the Swift sources as // text. The describe keeps the Swift suite's name, so a source comment that // names `CapabilityGateSweepTests` still finds its guard here. // // **Three crashes, one mistake.** An `AVAudioEngine` whose `inputNode` was // touched before the audio session had a category (an Objective-C exception, so // SIGABRT, no Swift error, no Bugsink event); an `AVCaptureSession` started // inside its own configuration window; and a speech-permission completion // handed a main-actor closure (SIGTRAP). Every one was a platform object built // or touched before the OS had said yes, and every one was invisible on a // simulator. `CapabilityAuthority` is the only thing that asks, // `SystemCapabilityAuthority` is the only file that calls a permission API, // and each platform object has exactly one birthplace. // // Path ownership: every path below is the PHONE's own (`apps/cotton/Sources/**` // and `apps/cotton/App/**`), and `appSources()` walks the directory rather than // a file list. `isInitDeclaration` stays in Swift too (`InitDeclarations.swift`), // for ScaffoldSweepTests; the two are the same rule and must stay so. import { describe, expect, it } from "vitest"; import { appSources, trimSpaces, withoutComments } from "./helpers/swift-source-sweep"; /** A platform API, and the one file that may say it — with the reason written down. */ interface Exemption { api: string; file: string; reason: string; } /** The APIs that ASK the OS, or read its standing answer. */ const askingTheOS = [ "AVAudioApplication.requestRecordPermission", "AVAudioApplication.shared.recordPermission", "AVAudioSession.sharedInstance().requestRecordPermission", "SFSpeechRecognizer.requestAuthorization", "SFSpeechRecognizer.authorizationStatus", "AVCaptureDevice.requestAccess", "AVCaptureDevice.authorizationStatus", "CNContactStore.authorizationStatus", "requestAccess(for: .contacts", "PHPhotoLibrary.authorizationStatus", "PHPhotoLibrary.requestAuthorization", "requestAuthorization(options", "notificationSettings()", // The Local Network answer: iOS reports it only through a Bonjour browse, and a browse anywhere else is a prompt nobody placed. "NWBrowser(", "NWListener(", "requestAuthorization(toShare", "statusForAuthorizationRequest", ]; /** The platform objects whose CONSTRUCTION is the hazard — each has exactly one birthplace. */ const buildingThePlatform = [ "AVAudioEngine(", "SpeechAnalyzer(", "DictationTranscriber(", "SpeechTranscriber(", "SFSpeechRecognizer(", "AVCaptureSession(", "AVAudioRecorder(", ]; const authority = "CottonKit/Capabilities/SystemCapabilityAuthority.swift"; const recogniser = "CottonUI/Capture/SystemSpeechRecogniser.swift"; const alarmScheduler = "CottonUI/Alarms/AlarmScheduler.swift"; const meetingRecorder = "CottonUI/Capture/MeetingAudioRecorder.swift"; const dictation = "CottonUI/Capture/Dictation.swift"; const appleHealth = "CottonHealthKit/AppleHealthAccess.swift"; const healthKitAsks = new Set(["requestAuthorization(toShare", "statusForAuthorizationRequest"]); /** Who may say what, and why. */ const exemptions: Exemption[] = [ ...[...healthKitAsks].map((api) => ({ api, file: appleHealth, reason: "Apple Health's ask, which only HealthKit can make: it lives in the one product only Cotton Health links (an app whose binary names HealthKit is held by App Review to say why, so no other app may carry it), and it is reached only through SystemCapabilityAuthority's `.appleHealth`, which Cotton Health attaches it to. A plain struct, read-only: it asks to share nothing.", })), // ITMS-90683 (22 Nov 2026): the asks whose API only some apps may name live in the app target, compiled out of an // app whose plist does not say why (COTTON_NO_CONTACTS, _CAMERA, _PHOTOS). Still reached only through the authority. ...([ ["CNContactStore.authorizationStatus", "App/Cotton/AddressBook+Contacts.swift"], ["requestAccess(for: .contacts", "App/Cotton/AddressBook+Contacts.swift"], ["AVCaptureDevice.requestAccess", "App/Cotton/Camera+AVFoundation.swift"], ["AVCaptureDevice.authorizationStatus", "App/Cotton/Camera+AVFoundation.swift"], ["PHPhotoLibrary.authorizationStatus", "App/Cotton/CameraRoll+Photos.swift"], ["PHPhotoLibrary.requestAuthorization", "App/Cotton/CameraRoll+Photos.swift"], ] as const).map(([api, file]) => ({ api, file, reason: "An ask App Store processing holds an app to explain even unused (ITMS-90683): it lives in the app target, compiled only into an app whose Info.plist gives the purpose string, installed at launch into LiveStores, and reached only through SystemCapabilityAuthority's status and ask.", })), ...askingTheOS.filter((api) => !healthKitAsks.has(api)).map((api) => ({ api, file: authority, reason: "The ONE place this app talks to the operating system. It is a plain struct, so it inherits no actor isolation and the two completions that answer off the main queue cannot be handed a main-actor closure.", })), { api: "AVAudioEngine(", file: recogniser, reason: "The dictation engine's one birthplace, built on the first session after the gate answered and after the audio session has a category and is active — touching an input node before that is the NSException that took the app down.", }, { api: "AVAudioEngine(", file: "CottonUI/Music/SongEngine.swift", reason: "The music player's engine, which only plays: it never touches the input node, so no permission stands before it and no gate has anything to answer. It is started only after `MusicPlayback` has given the session its `.playback` category and made it active, and the tests render it offline.", }, { api: "AVAudioEngine(", file: "CottonCalls/RingbackTone.swift", reason: "The ringback heard while the other phone rings, an engine that only plays a tone it makes: it never touches the input node, so no permission stands before it and no gate has anything to answer. It is built inside `play(_:)`, when the core says `play_tone`, by which time CallKit has activated the call's audio session.", }, { api: "SpeechAnalyzer(", file: recogniser, reason: "Live dictation's analyzer, built per session inside `start(_:)` after the gate answered and the language's model was found — nothing platform exists until the gate has answered.", }, { api: "DictationTranscriber(", file: recogniser, reason: "Live dictation's model, built beside its analyzer under the same rule: after the gate, in the person's language, never in an `init`.", }, ...["SpeechAnalyzer(", "SpeechTranscriber(", "DictationTranscriber("].map((api) => ({ api, file: "CottonVoice/AppleSpeechEngine.swift", reason: "Cotton Voice's `apple.speech` engine: the analyzer and its model are built in `prepare()`, which `VoiceSession.start` reaches only after `CapabilityAuthority.gate([.microphone, .speech])` answered and the core's plan named the language — never in an `init`; the second pass builds its transcriber per sentence inside the same running session.", })), { api: "AVAudioEngine(", file: "CottonVoice/VoiceAudio.swift", reason: "Cotton Voice's microphone input: `MicrophoneInput` is made by `VoiceSession.start` only after the gate answered `.microphone` and `VoiceAudioSession.open()` gave the session `.playAndRecord` and made it active; its input node is touched in `start`, never in an `init`.", }, // `SFSpeechRecognizer(` HAS NO EXEMPTION: it went on 14 Oct 2026 with the on-device/network ladder, and dictation is `DictationTranscriber` alone. { api: "AVCaptureSession(", file: "App/Cotton/Camera+AVFoundation.swift", reason: "The Camera tool's capture session: its model opens it only after `Camera.refusal` passed the gate, configures it in one begin/commit window and starts it off the main actor after the commit.", }, { api: "AVCaptureSession(", file: "App/Cotton/Camera+AVFoundation.swift", reason: "Comms' safety-number scan: `ChatQRSession` reads QR codes only, built by its reader's `viewDidLoad`, which the screen reaches only after `CapabilityAuthority.gate([.camera])` answered ready; it configures in one begin/commit window and starts off the main actor after the commit, as `CameraSession` does. Its picture is never kept.", }, { api: "AVAudioRecorder(", file: meetingRecorder, reason: "A meeting recording's one writer, built INSIDE `open(at:)` after the gate answered `.authorized` and after the session has the `.record` category and is active. It is the same rule the dictation engine keeps and for the same reason: constructing a recorder against a session that is not yet configured is an NSException nothing can catch.", }, { api: "AVAudioRecorder(", file: "CottonUI/Chat/ChatAttach.swift", reason: "A Cotton Chat voice message's one writer, built INSIDE `ChatVoiceRecorder.start()` only after `CapabilityAuthority.gate([.microphone])` answered ready and the session has the `.playAndRecord` category and is active — the meeting recorder's rule, for the same uncatchable NSException; never in an `init`.", }, { api: "notificationSettings()", file: alarmScheduler, reason: "The alarm scheduler reads the standing permission through its INJECTED centre, which is the seam its own tests fake, and it raises no prompt. It folds to `AlarmAuthorization` — the backend question — rather than to `CapabilityAccess`.", }, ]; /** An `init` DECLARATION — never `.init(` in an expression, and never `SomeType(` that happens to end in those four letters. */ function isInitDeclaration(line: string): boolean { const trimmed = trimSpaces(line); const at = trimmed.indexOf("init("); if (at < 0) return false; const before = trimmed.slice(0, at); if (before.endsWith(".")) return false; const allowed = new Set(["public", "private", "internal", "fileprivate", "package", "required", "convenience", "override", "nonisolated", "@MainActor"]); return before .split(" ") .filter(Boolean) .every((word) => allowed.has(word)); } /** Count braces from `from` until the body that opens closes; every line inside, by zero-based number. */ function bodyFrom(lines: string[], from: number, inside: Set): number { let cursor = from; let depth = 0; let opened = false; while (cursor < lines.length) { for (const character of lines[cursor]) { if (character === "{") { depth += 1; opened = true; } else if (character === "}") depth -= 1; } if (opened) inside.add(cursor); if (opened && depth <= 0) break; cursor += 1; } return cursor; } /** * Every line of every `init` body in a file, by zero-based line number. A brace * count rather than a parser, over text with COMMENTS ALREADY STRIPPED. */ function initBodyLines(code: string): Set { const lines = code.split("\n"); const inside = new Set(); let index = 0; while (index < lines.length) { if (!isInitDeclaration(lines[index])) { index += 1; continue; } const cursor = bodyFrom(lines, index, inside); index = Math.max(cursor, index + 1); } return inside; } /** Every line of `DictationModel.live`'s body. The body opens on the signature's LAST line: a default argument written as a closure must not read as the body. */ function liveBodyLines(code: string): Set { const lines = code.split("\n"); const declared = lines.findIndex((line) => line.includes("static func live(")); if (declared < 0) return new Set(); const start = lines.findIndex((line, index) => index >= declared && line.includes("-> DictationModel {")); if (start < 0) return new Set(); const inside = new Set(); bodyFrom(lines, start, inside); return inside; } describe("CapabilityGateSweepTests", () => { // RULE: Only the authority asks the operating system, and every platform object is built in its one named birthplace — the permission sweep must read source before it can prove calls are centralised. it("only the authority asks the operating system", () => { const sources = appSources(); expect(sources.length, "the sweep read no sources").toBeGreaterThan(0); const offenders: string[] = []; for (const { name, text } of sources) { const code = withoutComments(text); for (const api of [...askingTheOS, ...buildingThePlatform]) { if (!code.includes(api)) continue; const allowed = exemptions.some((exemption) => exemption.api === api && name.endsWith(exemption.file)); if (!allowed) offenders.push(`${name} calls ${api}`); } } expect( offenders, `A permission API, or a platform object's constructor, outside the one file that owns it. Every ask goes through \`CapabilityAuthority\` (\`${authority}\`) and every platform object is built in one place, AFTER the gate answered — that is what stops the fourth uncatchable NSException. If this file really is a new owner, add an \`Exemption\` here with the reason written out.`, ).toEqual([]); }); it("every exemption says why", () => { for (const exemption of exemptions) { expect(exemption.reason.trim().length, `${exemption.file} is allowed to say ${exemption.api} with no reason written down`).toBeGreaterThan(40); } }); // RULE: `SystemSpeechRecogniser(` appears exactly once in the app, inside `DictationModel.live` in Capture/Dictation.swift; `DictationModel(recogniser:` appears nowhere but that constructor; and `DictationModel.live(` is never called inside an `init` body — because a `View.init` runs on every SwiftUI evaluation and every orphan recogniser's `deinit` gives the audio session back process-wide while the live one is using it (TakeHost, 2026), and one birthplace is what makes the accuracy harness measure what ships. it("the recogniser is built only by DictationModel.live and never in an init", () => { const recognisers: string[] = []; const models: string[] = []; const inInit: string[] = []; let liveBody = new Set(); for (const { name, text } of appSources()) { const code = withoutComments(text); const lines = code.split("\n"); const isHome = name.endsWith(dictation); const home = isHome ? liveBodyLines(code) : new Set(); if (isHome) liveBody = home; const inits = initBodyLines(code); lines.forEach((line, number) => { const site = `${name}:${number + 1}`; if (line.includes("SystemSpeechRecogniser(")) recognisers.push(home.has(number) ? "live" : site); if (line.includes("DictationModel(recogniser:") && !home.has(number)) models.push(site); if (line.includes("DictationModel.live(") && inits.has(number)) inInit.push(site); }); } expect(liveBody.size, `\`DictationModel.live\` was not found in ${dictation}`).toBeGreaterThan(0); expect(recognisers, "`SystemSpeechRecogniser(` must appear exactly once, inside `DictationModel.live`").toEqual(["live"]); expect(models, "a `DictationModel(recogniser:)` outside `DictationModel.live` — call `DictationModel.live()`").toEqual([]); expect( inInit, "`DictationModel.live()` called inside an `init` body. A `View.init` runs on every evaluation of the view value, and every orphan's `deinit` reaches the audio session the LIVE one is using. Build it in `.task`, once, into `@State` — `ShakeReportSheet`'s `makeSpeech()` is the shape.", ).toEqual([]); }); // RULE: The init scan really does find init bodies across the app — without it the guard above passes on an empty set. it("the init scan actually finds inits", () => { let found = 0; for (const { text } of appSources()) found += initBodyLines(withoutComments(text)).size; expect(found, `the init-body scan found ${found} lines across the whole app — it would pass on anything`).toBeGreaterThan(200); }); it("the init scan reads an init and not a call", () => { const code = [ "struct Host {", " public init(core: Core) {", " let made = DictationModel.live()", " self.model = made", " }", "", " func task() {", " let late = DictationModel.live()", " keep(late)", " }", "}", ].join("\n"); const inits = initBodyLines(code); const caught = code.split("\n").filter((line, offset) => line.includes("DictationModel.live(") && inits.has(offset)); expect(caught.length, "the one inside the init body, and only that one").toBe(1); expect(isInitDeclaration(" public init(core: Core) {")).toBe(true); expect(isInitDeclaration(" let x = Model.init(a: 1)")).toBe(false); expect(isInitDeclaration(" _model = State(initialValue: m)")).toBe(false); }); });