Cotton code
404 lines · 22.9 KB · SwiftRaw
// swift-tools-version: 6.0//// Cotton — ONE Swift package for the iPhone app (Cotton note "The phone and// Mac app — how a screen is built"). The Mac's Cotton.app (`Mac/`) imports no// module of it.//// The CODE is a Swift package so every layer is testable without launching an// app. The iPhone APP is a generated Xcode project (`project.yml` + `xcodegen`),// because a code-signed extension, an app group, entitlements and two// Info.plists cannot be expressed in SwiftPM at all.////   bash ../../scripts/gen-ios-project.sh      Cotton.xcodeproj (gitignored)//   xcodebuild test -scheme tinmen-cotton …    the phone's library tests//   swift test                                 every test target, on macOS//// iOS 26 is the floor for the app and its share extension (P8); macOS is// declared so the package's tests run on a Mac.//// THE MODULES, AND WHICH DESTINATION EACH IS FOR////   CottonMailbox    the app AND its share extension — the share hand-off//                    with no core under it (mailbox, classification, knock,//                    Route, AppFlavor, Log). CottonKit re-exports it.//   CottonKit        every build — the Swift face of the Rust core (the actor,//                    the event stream, the six C functions), the DTO boundary.//   CottonUI         the phone — every screen, over `CottonPaper`, which it//                    re-exports so a screen reads the look as its own. It//                    still compiles for macOS (the package's tests run//                    there); what is genuinely iOS-only (haptics, the system//                    keyboard) sits under `#if os(iOS)`.//// The plain values (`CottonValues`), the look (`CottonPaper`) and the faces// (`CottonFaces`) are not here: they are Loom's (`../loom/Package.swift`), a// package with no Rust in it, so they build where this one cannot resolve.//// "macOS only" and "iOS only" are statements about who LINKS a module, not a// per-platform exclusion SwiftPM could express: `swift build` on a Mac// compiles every target, so an iOS-only module still has to compile for macOS// (its UIKit uses are under `#if canImport(UIKit)`), and the iOS app's// generated project links only the products it names.import Foundationimport PackageDescription// The Rust core arrives as ONE XCFramework `scripts/build-xcframework.sh`// builds: two iOS slices (the client build, `--no-default-features`). It is a// BUILD PRODUCT — gitignored, ~35–60 MiB per slice// — so it is absent on a fresh clone and on any lane that has not built it.//// THE BINARY TARGET IS DECLARED UNCONDITIONALLY, AND THE PATH IS ALWAYS THERE.// SwiftPM refuses to even RESOLVE a package whose `binaryTarget` path does not// exist, so `scripts/ffi-stub.sh` guarantees the path: when the real archive is// absent it writes a STUB XCFramework — a valid `Info.plist` listing an EMPTY// archive with no headers for each destination — at `.ffi/CottonFFI.xcframework`. It is run by// the new-worktree script, by `scripts/gen-ios-project.sh` and by the Mac// job before `swift package resolve`; `scripts/build-xcframework.sh` deletes// whatever is there before writing the real slices, so a stub never survives// beside one.//// WHY, AND IT IS NOT A STYLE CHOICE. This file used to ask the filesystem// whether the archive was there and declare the target only when it was. A// MANIFEST IS COMPILED ONCE AND CACHED MACHINE-WIDE — SwiftPM keys// `~/Library/Caches/org.swift.swiftpm` by package identity, manifest BYTES,// tools version, environment and swiftpm version, and NOT by the package's// path — so the FIRST worktree on a Mac to evaluate this file before its// `.ffi` existed answered "no FFI" for every OTHER worktree of the same// commit. They built with the archive sitting right there and the app said// "The Rust core is not in this build". `swift package reset` inside a// worktree does not fix it (the cache is machine-wide, not per package), and// `touch Package.swift` does not either (the key is the bytes, not the mtime).// Measured on 2026-09-15: with the archive present the cached answer was still// "no FFI", and only `COTTON_FFI_STAMP=1 swift package describe` — a changed// ENVIRONMENT, which is part of the key — found the target. With three or four// worktrees per Mac that is a daily trap, not the twice-in-a-lifetime one the// old comment here claimed. Cotton note "Repo landmines — why the build's rules exist".//// NOTHING ABOUT THIS FILE IS FILESYSTEM-DEPENDENT ANY MORE, so the cached// MANIFEST is always right. The cached BUILD PLAN is a second cache and it is// not: under Swift Build (`.build/.buildSystem_debug` == `swiftbuild`) the// XCFramework's `Info.plist` is read while PLANNING, and the plan — cached at// `.build/manifest.pif` and `.build/out/Intermediates.noindex/XCBuildData`,// keyed by the PIF and the build REQUEST rather than by the bytes at this// path — decides whether a `CottonFFI` module exists at all. So dropping the// real archive over a stub does NOT take effect on the next build by itself,// and `swift build` and `swift test` cache two separate plans, which is why// clearing `manifest.pif` fixed one and not the other.// `scripts/build-xcframework.sh` drops both on every write path, so an ordinary// build-then-test needs nothing by hand. Cotton note "Repo landmines — why the build's rules exist".//// A STUB IS NOT A SILENT FALLBACK. Its libraries are empty and carry no// headers (an empty list is refused by Swift Build in Xcode 27.0), so// the `CottonFFI` module genuinely is not there, `canImport(CottonFFI)` is// false, `CottonRuntime.linksFFI` (CottonKit/CottonCore.swift) answers false// and `FFISmokeTests` FAILS rather than skipping — exactly what an absent// archive did before, minus the cached lie. `CottonRuntime` is still the one// door that answers "is the core in this build", so no caller above it writes// `#if canImport(CottonFFI)`.let package = Package(    name: "Cotton",    defaultLocalization: "en",    // iOS 26 / macOS 26: the floor of the on-device dictation engine    // (DictationTranscriber over SpeechAnalyzer), which every microphone in    // the app uses — `DictationFloorGuardTests` keeps every floor at or above it.    platforms: [.iOS("26.0"), .macOS("26.0")],    products: [        .library(name: "CottonMailbox", targets: ["CottonMailbox"]),        .library(name: "CottonKit", targets: ["CottonKit"]),        .library(name: "CottonUI", targets: ["CottonUI"]),        // The writing surface (notes-new-ios, 19 Nov 2026): the editor, its        // bar and formatting panel, the list row and the theme reader, with        // no knowledge of notes, so Notes, Journal, Story and any later app        // drop it in. UIKit and the bundled Nunito Sans only.        .library(name: "CottonWriting", targets: ["CottonWriting"]),        // Cotton Calling's engine: the core's `calls.*` effects performed on        // CallKit, PushKit, the audio session, the camera and WebRTC. Only the        // Calling targets link it (`project.yml`'s calling flavour), so no        // other app carries the WebRTC framework.        .library(name: "CottonCalls", targets: ["CottonCalls"]),        .library(name: "CottonChat", targets: ["CottonChat"]),        // Cotton Health's HealthKit reader and its one ask. Only the Health        // targets link it (`project.yml`'s health flavour), so no other app's        // binary names HealthKit.        .library(name: "CottonHealthKit", targets: ["CottonHealthKit"]),        // Voice (the voice plan, 17 Nov 2026): the engines, the shared model        // store and the session over the core's `voice.*`. CottonUI links it,        // so every Cotton app has the same microphone.        .library(name: "CottonVoice", targets: ["CottonVoice"]),        // The shared composer (19 Nov 2026): the one input bar every app that        // takes typed or spoken words mounts. SwiftUI only; it knows no app.        .library(name: "CottonComposer", targets: ["CottonComposer"]),        // Cotton Meetings on the lock screen, the Dynamic Island, the Action        // Button and in Shortcuts: the Live Activity's shape and the intents.        // Only the Meetings targets and their widget extension link it, so no        // other app offers "record a meeting" to the system.        .library(name: "CottonMeetingsLive", targets: ["CottonMeetingsLive"]),    ],    dependencies: [        // The faces, the look and the values they draw from (Loom, 27 Oct        // 2026). By path: one tree builds both.        .package(path: "../loom"),        // The crash reporter the iPhone APP links (`project.yml`, `App/Cotton/        // Reporting+Sentry.swift`). No target here links it: it is declared so        // the one committed pin set (`Package.resolved`, which        // `scripts/gen-ios-project.sh` seeds the phone's workspace from for an        // offline `-onlyUsePackageVersionsFromResolvedFile` cut) carries it.        // `SourceGuardTests` holds both pins equal and no target linking it.        .package(url: "https://github.com/getsentry/sentry-cocoa", exact: "9.9.0"),        // The terminal emulator the Code tool's Terminal tab renders        // (Cotton note "The Code tool — why a Mac holds the sessions"). MIT, one package, no transitive        // dependencies, carrying a `UIKit` and an `AppKit` `TerminalView`;        // `CottonUI/Terminal/` draws the session's terminal over it.        //        // Pinned EXACTLY: a terminal emulator's patch        // release is somebody else's decision about how bytes on a screen are        // interpreted.        //        // AND PINNED BELOW 1.12, DELIBERATELY. SwiftTerm 1.12 added a Metal        // renderer, and its `Apple/Metal/Shaders.metal` is compiled by every        // build of the package — which needs Xcode's Metal Toolchain, a        // component Xcode 26 and later do NOT install by default        // (`xcodebuild -downloadComponent MetalToolchain`). A stock Mac fails        // the build with `cannot execute tool 'metal'`, and this repo's Mac        // builds run on three machines. 1.11.2 is the        // last release before that backend; its `TerminalView`,        // `TerminalViewDelegate`, `feed(byteArray:)` and `resize(cols:rows:)`        // are the same API 1.20 has, which is the whole of what        // `Sources/CottonUI/Terminal/` uses. Moving up is a one-line change        // here once the toolchain is on every Mac that builds this.        .package(url: "https://github.com/migueldeicaza/SwiftTerm", exact: "1.11.2"),        // The book reader (`CottonUI/Reader/`): Readium's Swift toolkit renders        // an EPUB (one web view per spread, paginated by Readium CSS) and a        // PDF (PDFKit, paged), and both say where the reader is as one        // Locator JSON — the shape Readium's Kotlin toolkit writes too, so the        // object's `book.position` reads the same on an Android phone. BSD-3.        // Only Shared, Streamer and Navigator are linked; LCP, OPDS and the        // GCDWebServer/SQLite adapters never are.        //        // Pinned EXACTLY, and on 3.x: 4.0 is alpha (Swift 6 strict        // concurrency, renamed locator calls).        .package(url: "https://github.com/readium/swift-toolkit", exact: "3.11.1"),        // Readium's ZIP reader, pinned EXACTLY at 3.0.2 although no target        // names it: 3.0.1 (what the toolkit's `from: "3.0.1"` would also        // accept) traps every DEBUG build with "load from misaligned raw        // pointer" the moment an EPUB is opened (readium/swift-toolkit#927,        // fixed by readium/ZIPFoundation#17 in 3.0.2). Declaring it here is        // the one pin set (`Package.resolved`) refusing the trapping release.        .package(url: "https://github.com/readium/ZIPFoundation", exact: "3.0.2"),        // The song files' tags (Cotton Music, `CottonTagReader`): TagLib, the        // one library that reads ID3, MP4 atoms and FLAC/Vorbis comments        // alike — AVFoundation reads no FLAC fields. sbooth's CXXTagLib is        // TagLib 2.x packaged for SwiftPM from source (no prebuilt binary, no        // CMake), kept by SFBAudioEngine's author for his own players; LGPL        // 2.1 / MPL 1.1, linked statically as TagLib permits under MPL.        // Pinned EXACTLY: a tag reader's patch release changes what a file        // is said to say.        .package(url: "https://github.com/sbooth/CXXTagLib", exact: "2.3.2"),        // WebRTC for Cotton Calling (`CottonCalls`): Google's WebRTC framework        // as stasel's prebuilt binary (BSD), milestone 157, the newest tag when        // it was pinned (13 Nov 2026). Pinned EXACTLY: the media path is        // somebody else's code, and a milestone changes it. No app code of        // ours sits in the media path; only `CottonCalls` links it.        .package(url: "https://github.com/stasel/WebRTC", exact: "157.0.0"),    ],    targets: [        // What the app and its share extension say to each other, with no core        // under it: the mailbox in the App Group, the rules that classify a        // shared file, the knock's route and URL scheme, which app this is,        // and the log. The share extension links this and nothing of the Rust        // core, so it does not carry its own copy of it (about 90 MB).        // `CottonKit` re-exports it, so the app reads it as its own.        .target(            name: "CottonMailbox",            path: "Sources/CottonMailbox"        ),        // The Swift face of the Rust core, and the model layer over it.        .target(            name: "CottonKit",            dependencies: [.product(name: "CottonValues", package: "loom"), "CottonMailbox", "CottonTagReader", "CottonFFIBinary"],            path: "Sources/CottonKit"        ),        // What a song file says about itself: TagLib (C++) behind one C        // function, so CottonKit reads tags with no C++ interop. Only the        // fields Cotton Music reads are asked for (`CottonTagReader.h`).        .target(            name: "CottonTagReader",            dependencies: [.product(name: "taglib", package: "CXXTagLib")],            path: "Sources/CottonTagReader"        ),        // Every screen — a library target, so a screen is testable without        // launching (P17) — over `CottonPaper`'s look.        .target(            name: "CottonUI",            dependencies: [                .product(name: "CottonValues", package: "loom"),                "CottonKit",                .product(name: "CottonPaper", package: "loom"),                .product(name: "CottonFaces", package: "loom"),                "CottonSpeech",                "CottonVoice",                "CottonWriting",                "CottonComposer",                // The session's terminal (`Terminal/`): the one screen that                // draws a pseudo-terminal, and the only module that names it.                .product(name: "SwiftTerm", package: "SwiftTerm"),                // The book reader (`Reader/`). Readium is an iOS package (it                // links UIKit), so it is linked on iOS only and the reader's                // views sit under `#if os(iOS)`; the package's macOS tests                // compile everything else.                .product(name: "ReadiumShared", package: "swift-toolkit", condition: .when(platforms: [.iOS])),                .product(name: "ReadiumStreamer", package: "swift-toolkit", condition: .when(platforms: [.iOS])),                .product(name: "ReadiumNavigator", package: "swift-toolkit", condition: .when(platforms: [.iOS])),            ],            path: "Sources/CottonUI",            resources: [                .process("Resources/Localizable.xcstrings"),                // The core's catalogue of a fresh database, for a process with                // no core of its own: the share sheet, the tests                // (`DefinitionCatalogue`). The core's guard keeps it byte for                // byte what the core answers.                .copy("Resources/Shipped"),                // The synthetic household previews and the package's tests                // draw (`Definitions/FixtureDefinitions.swift`): its catalogue,                // as the core answers it, and its records. No table definition                // ships: tables come from the object.                .copy("Resources/Fixtures"),                // The places found by name that are no table's tool —                // Projects, About, the Tools screen (`HomeData.places`).                .copy("Resources/Places"),                .copy("Resources/Licenses"),                // The ink's letter model, Core ML and the same weights as                // TFLite for Android (`Ink/InkModel.swift`); the reading rules                // and their knobs are the core's (`cotton_core::ink`).                .copy("Resources/Ink"),            ]        ),        .target(            name: "CottonWriting",            path: "Sources/CottonWriting",            // Nunito Sans, upright and italic, and its SIL Open Font Licence.            resources: [.copy("Resources/Fonts")]        ),        // The shared composer (owner's direction, 19 Nov 2026): a text area        // that grows to about seven lines, a pick chip, a microphone that turns        // the row into a live dictation, cancel, stop and send. SwiftUI and        // UIKit only: every word, option, colour and the voice path behind        // the mic are handed in by the app (`ComposerDictation`), so Story,        // Chat and the rest mount the same bar.        .target(            name: "CottonComposer",            path: "Sources/CottonComposer"        ),        // The operating system's speech model, chosen and fetched in one place        // for live dictation (CottonUI). Speech and Foundation only.        .target(            name: "CottonSpeech",            path: "Sources/CottonSpeech"        ),        // Voice: audio in, timed words out. The core decides (`voice.plan`,        // `voice.heard`); this runs the engines the plan names —        // `apple.speech` (SpeechAnalyzer over SpeechTranscriber) and        // `sherpa:<model>` through sherpa-onnx — keeps their models in the one        // App Group store every Cotton app shares, and hands what was heard        // back. sherpa-onnx is iOS-only (its archive has no macOS slice), so        // on macOS the target compiles without it and a sherpa engine answers        // that it is not in this build.        .target(            name: "CottonVoice",            dependencies: [                "CottonKit",                "CottonSpeech",                .product(name: "CottonValues", package: "loom"),                .target(name: "SherpaOnnxC", condition: .when(platforms: [.iOS])),            ],            path: "Sources/CottonVoice"        ),        // Cotton Calling's engine (the product above): the effect performer        // over ports, and the live ports (CallKit, PushKit, the audio        // session, URLSession's socket, WebRTC's peer and camera).        .target(            name: "CottonCalls",            dependencies: ["CottonKit", "CottonUI", .product(name: "CottonFaces", package: "loom"), .product(name: "WebRTC", package: "WebRTC")],            path: "Sources/CottonCalls"        ),        .target(            name: "CottonChat",            dependencies: ["CottonKit", "CottonMailbox", "CottonUI"],            path: "Sources/CottonChat"        ),        // Cotton Health's reader (the product above): HealthKit's ask,        // anchored reads landed through the core, observers once answered.        // Cotton Meetings' intents and Live Activity (the product above):        // ActivityKit and App Intents only, no core and no shell, so the        // widget extension can link it.        .target(            name: "CottonMeetingsLive",            path: "Sources/CottonMeetingsLive"        ),        .target(            name: "CottonHealthKit",            dependencies: ["CottonKit", "CottonUI"],            path: "Sources/CottonHealthKit"        ),        .testTarget(name: "CottonCallsTests", dependencies: ["CottonCalls"], path: "Tests/CottonCallsTests"),        .testTarget(name: "CottonChatTests", dependencies: ["CottonChat"], path: "Tests/CottonChatTests"),        .testTarget(name: "CottonWritingTests", dependencies: ["CottonWriting"], path: "Tests/CottonWritingTests"),        .testTarget(name: "CottonComposerTests", dependencies: ["CottonComposer"], path: "Tests/CottonComposerTests"),        .testTarget(name: "CottonKitTests", dependencies: ["CottonKit"], path: "Tests/CottonKitTests", resources: [.copy("Fixtures")]),        .testTarget(name: "CottonHealthKitTests", dependencies: ["CottonHealthKit"], path: "Tests/CottonHealthKitTests", resources: [.copy("Fixtures")]),        .testTarget(            name: "CottonUITests",            dependencies: [.product(name: "CottonValues", package: "loom"), "CottonUI", "CottonVoice"],            path: "Tests/CottonUITests",            // The book reader's two small public-domain books (`Fixtures/Books`).            resources: [.copy("Fixtures")]        ),    ],    swiftLanguageModes: [.v6],    cxxLanguageStandard: .cxx17)package.targets.append(.binaryTarget(name: "CottonFFIBinary", path: ".ffi/CottonFFI.xcframework"))// sherpa-onnx, the one runtime for open speech models (voice plan, 17 Nov// 2026): k2-fsa's own SwiftPM archive — sherpa-onnx as one dynamic framework// with ONNX Runtime linked statically inside (Apache-2.0 and MIT), iOS device// and simulator slices, module `SherpaOnnxC`. Pinned by URL and checksum, so// it is fetched like any package and nothing is built or stubbed here.// v2.0.1, published 26 Oct 2026.package.targets.append(.binaryTarget(    name: "SherpaOnnxC",    url: "https://github.com/k2-fsa/sherpa-onnx/releases/download/xcframework/sherpa-onnx-v2.0.1-ios-shared-onnxruntime-static.xcframework.zip",    checksum: "fc4c665e694322ced5393aafafaae6bb3e0a7449d98d5db60bc220ac7ac4cbc9"))// DEVELOPER TOOLS ARE COMPILED INTO COTTON DEV ONLY (owner, DEV MODE,// 2026-10-03: "developer tools stay off" is the REAL app's rule now). Every// developer tool — Settings › Developer, the timings overlay, the build// corner, the read counter — sits inside `#if COTTON_DEV`, and this is the one// place the condition is set: for every Swift target unless the build says// `COTTON_FLAVOR=real`, which only a release of the real app does. Undeclared// is dev, the same rule as `AppFlavor`/`flavor.rs`: a build that forgot to say// which it is gets the tools, never the real household. The ENVIRONMENT is// part of SwiftPM's manifest cache key (above), so a real build never reuses a// dev answer. Xcode compiles this package's targets with THIS manifest's// settings, not the app target's, so the iPhone's release lane must export// `COTTON_FLAVOR=real` into the environment, not only pass it as a build// setting. Guard: the dev-tools real-flavor test.if ProcessInfo.processInfo.environment["COTTON_FLAVOR"] != "real" {    for target in package.targets where target.type != .binary {        target.swiftSettings = (target.swiftSettings ?? []) + [.define("COTTON_DEV")]    }}