Cotton code
152 lines · 6.8 KB · SwiftRaw
// The app-level half of capture: ONE service per identity, built where the// identity is known and handed to every surface that mounts the dock.//// This is the composition the `[thoughts-has-no-capture-dock]` port gap named.// `DockModel` needs a `CaptureSending`; the only real one is `CaptureService`,// which needs a `PendingLinks` keyed on `userId` + `workspaceId`; those live on// `BootModel`, which `RootView` holds. So `RootView` builds THIS once the gate// says `.ready`, puts it in the environment, and a screen takes it from there,// with the drain mounted beside the reconcilers.//// **Why the identity is read HERE and not by a screen.** `PendingLinks`' key is// a structural security property — one person's `#Meri` chip must never be// applied inside somebody else's workspace — and a screen re-reading `read.boot`// for itself is a second reader of that answer, one that could see an empty// identity and write under an empty key. `BootModel` is the one reader, and// this object exists only while it has answered.//// **The three facts the drain cannot read for itself are answered from reads// the app already makes**, which is what closes the "no production type// implements `PendingLinkSource`" hole:////   • what a capture has FILED — `read.thoughts`, whose ledger carries every//     capture with its `routedRecords` and the older `routedKind`/`routedId`//     pointer (`ThoughtStory.routedRefs` reads both shapes already);//   • the person a `person_note` names — the same read's `routedFacts`, keyed//     by the record's id, which the bubble uses for the same purpose;//   • a project's SLUG from its id — `read.home`, the one read that answers//     `id`, `name` AND `slug` together on each of its `projects` rows. The//     after-the-cutover ledger said neither list answers both; `read.projects`//     and `read.thoughts` do not, and `read.home` does.//// Each answer is a fresh read, never a cache: the drain runs seldom (on ready,// on foreground, and when a fold names the capture table), and a stale slug// would link a chip to a project the person has since renamed.import CottonKitimport Foundationimport SwiftUI/// The drain's three questions, answered from the reads this app already makes.public struct CorePendingLinkSource: PendingLinkSource {    private let core: any CottonCalling    public init(core: any CottonCalling) {        self.core = core    }    public func filed(_ inboxItemId: String) async -> FiledCapture? {        guard let ledger = try? await core.callJSON(CottonMethod.readThoughts),            let thought = ledger.list("thoughts").first(where: { $0.text("id") == inboxItemId })        else { return nil }        let listed = ThoughtStory.routedRefs(thought)        // A capture that has filed NOTHING yet answers nil, which is what keeps        // its intent waiting rather than settling it against no records.        guard !listed.isEmpty || thought.text("routedKind") != nil else { return nil }        return FiledCapture(            routedRecords: listed.map { RoutedRecord(kind: $0.kind, id: $0.id) },            routedKind: thought.text("routedKind"),            routedId: thought.text("routedId")        )    }    public func ownPerson(ofPersonNote recordId: String) async -> OwnPerson {        guard let ledger = try? await core.callJSON(CottonMethod.readThoughts),            // `routedFacts` is an OBJECT keyed by the record's id.            let personId = ledger["routedFacts"]?[recordId]?.text("personId")        else { return .unreadable }        return .known(personId)    }    public func projectSlug(_ projectId: String) async -> String? {        guard let home = try? await core.callJSON(CottonMethod.readHome) else { return nil }        return home.list("projects").first { $0.text("id") == projectId }?.text("slug")    }}/// Everything a dock host needs of the app around it, built once per identity.@MainActor@Observablepublic final class CaptureContext {    /// The UI context can compose another draft destination, but has no    /// arbitrary method caller. Services own the capabilities they perform.    private let forDatabase: @MainActor (ShownDatabase) -> CaptureContext    public let userId: String    public let workspaceId: String    public let service: CaptureService    public let links: PendingLinks    /// How a picture reaches the draft — `capture.media` over the same core,    /// so the dock never holds a core of its own.    public let media: any MediaCapturing    /// New thought's receipt verbs — Undo, Move it to — over the same core    /// (`ThoughtFiling`, CottonKit).    public let filing: any ThoughtFiling    public init(        userId: String,        workspaceId: String,        core: any CottonCalling,        store: any PendingLinkStore = DefaultsPendingLinkStore(),        report: @escaping @Sendable (PendingLinkTrouble) -> Void    ) {        self.forDatabase = { destination in            CaptureContext(                userId: userId, workspaceId: workspaceId,                core: DatabaseScopedCore(underlying: core, shown: destination),                store: store, report: report)        }        self.userId = userId        self.workspaceId = workspaceId        let links = PendingLinks(            userId: userId,            workspaceId: workspaceId,            store: store,            source: CorePendingLinkSource(core: core),            writer: CorePendingLinkWriter(core: core),            report: report        )        self.links = links        self.service = CaptureService(core: core, links: links)        // The dock's pictures ride the thought it sends, and a thought        // arrives in Personal: they are kept there, beside it.        self.media = CoreMediaCapture(core: core, forThought: true)        self.filing = CoreThoughtFiling(core: core)    }    /// The overlay owns this choice; paging another window cannot retarget    /// its draft. Changing the destination keeps the same dock and words.    func scoped(to destination: ShownDatabase) -> CaptureContext {        forDatabase(destination)    }    /// Apply every chip whose record has since landed. Safe to call often: the    /// actor collapses overlapping drains into one.    @discardableResult    public func drain() async -> Int {        await links.drain()    }}private struct CottonCaptureKey: EnvironmentKey {    /// `nil` below the gate, and on any screen a test or a preview mounts    /// alone. A host reads it as "the dock cannot be mounted here" and draws    /// the transcript without one — never a bar that writes nowhere.    static let defaultValue: CaptureContext? = nil}extension EnvironmentValues {    public var cottonCapture: CaptureContext? {        get { self[CottonCaptureKey.self] }        set { self[CottonCaptureKey.self] = newValue }    }}