Cotton code
767 lines · 34.9 KB · SwiftRaw
// The writer's own chips, kept until there is something to put them on.//// Typing `#meri` or `@ravi` before sending, or capturing while standing on a// project or a person page, attaches links to a thought that has no record yet// (spec 2026-08-29 §D4). The links land on whatever the filing creates — and the// filing happens on the SERVER, minutes later, when the op gets there. The// record the links belong on may not exist yet, and may first appear on another// device.//// So the intent is written down and applied when the record shows up. It lives// in `UserDefaults` rather than in the file on purpose: it is this device's note// to itself about a capture it made, not a fact about the owner's life, and// syncing it would mean two devices racing to write the same links.//// ── Four places this file had to decide something the old one did not ───────//// 1. **The host hands the drain its facts.** The drain used to call three//    domain services directly. This app has no domain services: it has a//    boundary whose method list is `Boundary.swift`'s `CottonMethod`, and that//    list declares NO read for a routed capture's records and none for a person//    note's own person. Inventing `read.inboxItem` would be an `unknown_method`//    at runtime, so the drain asks a ``PendingLinkSource`` the HOST implements —//    the screen that captures already holds `read.home`'s projects, and the one//    that drains can read whatever the crate answers on the day it answers it.//    The seam is a `deps` object promoted to a protocol.//// 2. **A project link is named by SLUG below the boundary, and by ID above it.**//    Both writers resolve their `project` argument by slug and only accept an//    ACTIVE one — `project_by_slug` for `link_to_project`//    (`cotton-tools/src/mcp/handlers/projects/mod.rs:97-119`) and//    `resolve_project` for `update_thought` (`handlers/common.rs:751-768`) —//    while a `#` chip and `CaptureRequest.projectIds` both carry the project's//    ID. So the intent keeps ids (they are what the capture sent) and//    ``PendingLinkSource/projectSlug(_:)`` names one. A project this app cannot//    name is NOT a written refusal: it is a fact the app has not loaded yet, so//    the write is reported and the intent is kept for the next pass. A project//    the TOOL refuses is the opposite — see `link(projectId:ref:what:)`.//// 3. **The `applied_by` stamp, and the ONE write that still cannot say it.**//    A chip is the person's own hand and outranks the router's proposal, so//    the drain claims `applied_by: "user"`. Three writes, and only one of them//    is still short:////      • **the THOUGHT's own membership** goes through `update_thought`//        (`{id, project: <slug>}`), the thought kind's own verb, which stamps//        `applied_by: "user"` (`handlers/thoughts.rs:433`), derives the same//        `project_link_id` this file does, and SKIPS a membership that is//        already there (`:418-436`). One call per chip instead of one call with//        N records — the right hand is worth the extra round trip.//      • **a ROUTED record filed with a plan** is stamped by the SERVER's filer//        at filing time, from the plan's own `user_project_ids`//        (`cotton-server/src/routing/file_plan.rs:973-986`) — which the//        composer now sends (`DockModel.planJSON`). This drain is its backstop,//        not its writer.//      • **a ROUTED record filed with NO plan** — a dock chip the classifier//        never saw a plan for — is the one real gap. It goes through//        `link_to_project`, which takes no `applied_by` argument and writes the//        literal `"agent"` (`handlers/projects/write.rs:558`). The chip lands on//        the right row with the right derived id and claims a weaker hand than//        the person used. **The fix is NOT to widen `link_to_project`** — it is//        an assistant-facing verb and an optional "claim the owner's hand"//        argument on it is a hole — but a `capture.link` sibling of//        `capture.create` in `cotton-ffi/src/phone/`, same author and same//        precedent. **That file is the 4p lane's** (`phone/capture.rs`), so the//        gap is named here and owed there.//// 4. **Nothing below the boundary CREATES a person edge yet.** No tool in//    `cotton-tools`' catalogue creates a `cotton_links` row — 186 tools and not//    one of them. The single writer of that table is `merge_transactions`'//    `move_record_links` (`handlers/money/transactions.rs:673`), which//    RE-PARENTS edges the file already holds onto the kept transaction and//    deletes the old rows; it can make no edge that did not exist. So//    ``PendingLinkWriting/linkPerson(from:toPersonId:)`` is declared, exercised//    by the rules above it, and refused by the boundary implementation. The//    refusal keeps the intent rather than dropping it, so an `@` chip survives//    in storage until the tool exists or the expiry takes it — a chip lost//    quietly is the one outcome this whole file exists to prevent.//// ── And one the identity forced ──────────────────────────────────────────────//// The module used to be a singleton carrying `(userId, workspaceId)` on every// call, with an in-flight map keyed by both. This phone holds ONE identity at a// time, so the identity is held by the INSTANCE: two identities are two// ``PendingLinks`` over one store, writing two different keys, and neither can// see the other's intents. The security property — one person's `#Meri` chip is// never applied inside somebody else's workspace — is then structural rather// than a guard, and the in-flight collapse is one task rather than a map.//// The storage key shape is unchanged, byte for byte, so a stored list written by// an older build still reads. It is deliberately NOT a `StandingKey`: that enum// is a fixed list of two and a test holds it to exactly two, and an intent list// is neither a preference nor a refusal — it is device-local work in progress.import Foundation/// One intent list PER IDENTITY.////// A pending intent is this device's note to itself about a capture it made in/// ONE file. A single global list would let a drain running as somebody else/// apply that person's `#Meri` chip inside a workspace it was never meant for.func pendingLinksStorageKey(userId: String, workspaceId: String) -> String {    "@cotton:pendingLinks:v1:\(userId):\(workspaceId)"}/// The tag-intent key the old drain swept, and the reason THIS file does not.////// The previous app deleted `@cotton:pendingTags:v1` on every drain: it held TAG/// intents, and since chain 1 of the projects-first program nothing writes a tag/// from a capture, so reading them and doing nothing would leave a key that only/// grows.////// **That sweep was carried across once and it could never have fired.** The/// retired key lived in the previous app's own store inside the app container./// ``DefaultsPendingLinkStore`` is the APP GROUP's `UserDefaults` suite, a/// different store in a different container, which no build has ever written/// that key into. So the removal was one defaults write per fold against a key/// that cannot exist: furniture, and worse, furniture whose comment claimed a/// cleanup was happening.////// Nothing replaces it. That store went with the previous app, and there is no/// reader left that a stale tag intent could reach — so this is a comment where/// a constant used to be, and there is nothing to call./// Intents older than this are dropped: the capture was never routed. Seven/// days, in milliseconds, because `at` is an epoch-millis stamp.let pendingLinksExpiryMs: Double = 7 * 24 * 60 * 60 * 1000// MARK: - Storage/// Where the intent list is kept.////// A protocol with two members so a test touches no real defaults. The real one/// is the app group's suite, which is also what the share extension reads —/// but nothing else reads THIS key, and nothing ever should.public protocol PendingLinkStore: Sendable {    func data(_ key: String) -> Data?    func set(_ key: String, _ value: Data?)}/// The shipping store: one `UserDefaults` suite, the app group's.////// `@unchecked Sendable` because `UserDefaults` is thread-safe by contract and/// carries no annotation saying so; the struct holds nothing else.public struct DefaultsPendingLinkStore: PendingLinkStore, @unchecked Sendable {    private let defaults: UserDefaults    public init(defaults: UserDefaults = CottonDefaults.suite()) {        self.defaults = defaults    }    public func data(_ key: String) -> Data? { defaults.data(forKey: key) }    public func set(_ key: String, _ value: Data?) {        guard let value else {            defaults.removeObject(forKey: key)            return        }        defaults.set(value, forKey: key)    }}/// One capture's waiting chips.////// The records it was tried against are NOT a member and never were persisted:/// they are read back from the capture on every pass, and a stale copy would/// outlive a correction that re-filed the capture somewhere else.struct PendingLinkIntent: Codable, Equatable, Sendable {    var inboxItemId: String    var projectIds: [String]    var personIds: [String]    /// When the capture was made — the expiry clock, epoch millis.    var at: Double}// MARK: - What the host answers/// One record a capture filed, as the crate names it on the wire.////// The kind is a STRING rather than a ``RouteTargetKind`` because it arrives from/// the file, and a kind this build does not know is a fact about the data, not a/// decoding failure. The drain reports one and steps over it; see `applyOne`.public struct RoutedRecord: Codable, Equatable, Sendable {    public var kind: String    public var id: String    public init(kind: String, id: String) {        self.kind = kind        self.id = id    }}/// What a capture has filed, whichever way it was filed.////// A ROUTED capture stamps `routed_records`; one the owner filed BY HAND stamps/// `routed_kind` + `routed_id` and no list at all — so a drain reading only the/// list watched every hand-filed capture's chip wait out its week and be deleted./// The server has read both shapes since the plan era (`previouslyFiled`); so/// does this.public struct FiledCapture: Codable, Equatable, Sendable {    public var routedRecords: [RoutedRecord]    public var routedKind: String?    public var routedId: String?    public init(        routedRecords: [RoutedRecord] = [],        routedKind: String? = nil,        routedId: String? = nil    ) {        self.routedRecords = routedRecords        self.routedKind = routedKind        self.routedId = routedId    }}/// The person a `person_note` row names, or the fact that its row could not be/// read.////// NOT KNOWING is different from there being nobody, and the difference decides a/// write: ``isSelfPersonEdge(_:_:_:)`` is false for every person when the own/// person is unknown, so treating a failed read as "no own person" would let the/// SELF edge through — the one duplicate the rule exists to prevent.public enum OwnPerson: Equatable, Sendable {    case known(String)    case unreadable}/// The three facts the drain cannot read for itself.////// Implemented by the HOST, for the reason in this file's header: the boundary/// declares no method for any of them, and inventing one would be an/// `unknown_method` at runtime rather than a compile error.public protocol PendingLinkSource: Sendable {    /// What this capture has filed, or `nil` while it has filed nothing — which    /// is also the honest answer when the read itself failed.    func filed(_ inboxItemId: String) async -> FiledCapture?    /// The person a `person_note` row names.    func ownPerson(ofPersonNote recordId: String) async -> OwnPerson    /// The slug `link_to_project` needs for a project the app holds by id.    func projectSlug(_ projectId: String) async -> String?}// MARK: - What the drain writes/// The two link writes, as a seam.////// Both throw for a REFUSAL and for a dead transport alike, because `call`/// answers both the same way — and the drain treats every throw as the/// recoverable kind: report it, keep the intent, and go on writing the rest./// That is one deliberate departure from the previous app, whose single `catch`/// abandoned a record's remaining writes on the first throw; retrying is free/// here (every id is derived, so a re-run is an upsert) and abandoning a link/// that would have landed is not.public protocol PendingLinkWriting: Sendable {    /// The membership of a record a capture BECAME — `link_to_project`.    func linkProject(projectSlug: String, record: LinkRef) async throws    /// The membership of the THOUGHT itself — `update_thought`, which is the    /// thought kind's own verb and the one that stamps `applied_by: "user"`.    /// Two methods rather than one because the two writes are two different    /// tools with two different hands; see the header's third gap.    func linkThoughtProject(projectSlug: String, thoughtId: String) async throws    func linkPerson(from: LinkRef, toPersonId: String) async throws}/// The gaps this port stands on, said as errors rather than as silence.public enum PendingLinkGap: Error, Equatable, Sendable {    /// No tool in `cotton-tools`' catalogue CREATES a `cotton_links` row, so an    /// `@` chip cannot be applied yet. (`merge_transactions`'    /// `move_record_links` is the table's only writer and re-parents edges the    /// file already holds — `handlers/money/transactions.rs:673` — so it can    /// make no edge that did not exist.) Thrown rather than ignored so the    /// intent is KEPT: the chip waits in storage instead of vanishing.    case noPersonEdgeWriter}/// The shipping writer: `write { tool: "link_to_project" }` over the boundary.////// The argument names are the catalogue's own/// (`cotton-tools/src/mcp/catalogue.rs`): `project` is the SLUG and/// `records` is a list of `{kind, id}`. **No `note` key**, deliberately (ruling/// R38): omitting it keeps the note the row already carries. This drain is/// linking a record, not annotating one, and because the row id is derived it/// writes the SAME row the owner may have typed a sentence onto in the sheet —/// `null` would erase it under their eyes.public struct CorePendingLinkWriter: PendingLinkWriting {    private let core: any CottonCalling    public init(core: any CottonCalling) {        self.core = core    }    public func linkProject(projectSlug: String, record: LinkRef) async throws {        let request = WriteRequest(            tool: "link_to_project",            args: .object([                "project": .string(projectSlug),                "records": .array([                    .object(["kind": .string(record.kind.rawValue), "id": .string(record.id)])                ]),            ])        )        _ = try await core.call(CottonMethod.write, request, as: WriteAnswer.self)    }    /// `write { tool: "update_thought", args: {id, project} }`.    ///    /// The thought kind's OWN verb, and the reason it is used here rather than    /// `link_to_project`: it stamps `applied_by: "user"`    /// (`cotton-tools/src/mcp/handlers/thoughts.rs:433`) where the other writes    /// the literal `"agent"` (`handlers/projects/write.rs:558`), and a `#` chip    /// is a person's thumb. It derives the SAME `project_link_id` this file's    /// ``thoughtProjectLinkRef(_:)`` names, and it SKIPS a membership that is    /// already there (`thoughts.rs:418-436`), so a re-drain writes nothing    /// twice.    ///    /// One call per chip, where `link_to_project` would take N records in one.    /// A thought carries a handful of chips at most and the drain is not a hot    /// path; the right hand is worth the round trips.    ///    /// **No `dismissed` key**, for the reason `linkProject` sends no `note`    /// (R38): the tool refuses a call that changes nothing, and `project` alone    /// is a change, so passing the other field would be this drain deciding    /// something about the thought that nobody asked it to decide.    public func linkThoughtProject(projectSlug: String, thoughtId: String) async throws {        let request = WriteRequest(            tool: "update_thought",            args: .object([                "id": .string(thoughtId),                "project": .string(projectSlug),            ])        )        _ = try await core.call(CottonMethod.write, request, as: WriteAnswer.self)    }    public func linkPerson(from: LinkRef, toPersonId: String) async throws {        // See `PendingLinkGap.noPersonEdgeWriter`. When the tool lands this        // becomes one `write` like the one above, and nothing else in this file        // changes — which is the point of the seam being here rather than the        // rule being written at the call site.        throw PendingLinkGap.noPersonEdgeWriter    }}// MARK: - What went wrong/// Something the drain could not do, reported rather than swallowed.////// This app has no reporting seam yet, so the closure is injected and has NO/// default. A default no-op would be the silent fallback the repo bans, and/// making every caller answer the question is that ban made structural.public struct PendingLinkTrouble: Equatable, Sendable {    /// The route strings ``ShareIntakeTrouble`` reports under too, so the two    /// halves of one story are searchable together.    public var route: String    public var what: String    public init(route: String, what: String) {        self.route = route        self.what = what    }}// MARK: - The drain/// The intent list for ONE identity: remember, drain, clear.////// An `actor` because the in-flight collapse, the read and the write-back have to/// be one sequence — the host fires this on appearance AND on every fold that/// touches the inbox, so two drains really do overlap.public actor PendingLinks {    private let userId: String    private let workspaceId: String    private let store: any PendingLinkStore    private let source: any PendingLinkSource    private let writer: any PendingLinkWriting    private let now: @Sendable () -> Date    private let report: @Sendable (PendingLinkTrouble) -> Void    /// The drain already running, if any.    ///    /// One task rather than the old map: that map was keyed by identity and    /// this instance IS one identity, so a second entry could only ever be a    /// second identity's — which is a second instance here, with its own key and    /// its own task. Handing a second identity's caller this promise is not a    /// thing that can be spelt.    private var inFlight: Task<Int, Never>?    public init(        userId: String,        workspaceId: String,        store: any PendingLinkStore,        source: any PendingLinkSource,        writer: any PendingLinkWriting,        now: @escaping @Sendable () -> Date = Date.init,        report: @escaping @Sendable (PendingLinkTrouble) -> Void    ) {        self.userId = userId        self.workspaceId = workspaceId        self.store = store        self.source = source        self.writer = writer        self.now = now        self.report = report    }    private var key: String { pendingLinksStorageKey(userId: userId, workspaceId: workspaceId) }    private var nowMs: Double { now().timeIntervalSince1970 * 1000 }    // MARK: Remembering    /// Remember that this capture's records should carry these links.    public func remember(        inboxItemId: String,        projectIds: [String],        personIds: [String]    ) {        if projectIds.isEmpty && personIds.isEmpty { return }        var intents = readAll()        intents.append(            PendingLinkIntent(                inboxItemId: inboxItemId,                projectIds: projectIds,                personIds: personIds,                at: nowMs            )        )        writeAll(intents)    }    /// Forget everything this identity was holding. Leaving a workspace is the    /// caller.    public func clear() {        store.set(key, nil)    }    // MARK: Draining    /// Apply every intent whose capture has since been routed, and drop the rest    /// that have run out of time.    ///    /// Returns how many intents were SETTLED, so the caller can decide whether the    /// project and person surfaces need re-reading — and re-read only when the    /// answer is more than zero.    public func drain() async -> Int {        // Both link tables derive their ids, so a second pass is an upsert rather        // than a duplicate row; collapsing the overlap is still worth it, because        // it saves the writes and keeps one answer. The second caller awaits the        // first and reports what it settled.        if let running = inFlight { return await running.value }        let task = Task { () -> Int in            let settled = await self.runDrain()            // Cleared from INSIDE the task. Clearing after            // the first caller's `await` resumed left a window: a caller            // arriving between the task finishing and that resumption saw a            // finished task, awaited its cached count, and skipped a drain it            // should have run.            self.drainFinished()            return settled        }        inFlight = task        return await task.value    }    /// The task is done; a caller arriving now starts a new one.    private func drainFinished() {        inFlight = nil    }    private func runDrain() async -> Int {        // The old drain swept the retired tag key here. This does not, and the        // reason is written above `pendingLinksStorageKey` — the key lives in a        // store this app has no door onto.        let intents = readAll()        if intents.isEmpty { return 0 }        let cutoff = nowMs - pendingLinksExpiryMs        var remaining: [PendingLinkIntent] = []        var settling: [(intent: PendingLinkIntent, records: [RoutedRecord])] = []        // Decide first: which intents have records to link, and which are still        // waiting (or have waited too long). Nothing is written back yet — see the        // claim comment below the write loop.        for intent in intents {            let records = filedRecords(await source.filed(intent.inboxItemId))            if records.isEmpty {                // Not routed yet — keep waiting, unless it has been waiting too                // long. A capture the router never filed has no record to link,                // and an intent that lives forever is a leak.                if intent.at >= cutoff { remaining.append(intent) }                continue            }            settling.append((intent, records))        }        // Claim AFTER the write, not before.        //        // Claim-first was right while `cotton_links` ids were minted: a drain        // killed between the write and the claim would have re-run and left a        // DUPLICATE person edge nothing removes. Since chain 2 both tables' ids        // are DERIVED, so a re-run is an upsert of the row that is already there        // — and the failure claim-first traded for is real: a kill between the        // claim and the write loses the person's chip silently, forever.        //        // Settlement is tracked BY POSITION rather than by `inboxItemId`, so two        // intents that somehow name one capture cannot settle each other.        var settled: [Bool] = []        for entry in settling {            // The THOUGHT's own membership first, once per intent (schema v29): a            // thought keeps its project whatever it became, and it is written            // here rather than inside `applyOne` for two reasons — it does not            // depend on the record, and a `person_note` whose own row cannot be            // read must not take it down. Derived id, so a re-run is an upsert of            // the same row.            var ok = await applyThoughtLinks(entry.intent)            for record in entry.records {                let one = await applyOne(entry.intent, record)                ok = one && ok            }            settled.append(ok)        }        var kept = remaining        for (index, entry) in settling.enumerated() where !settled[index] {            // The SAME clock the unrouted branch runs on. A write that keeps            // refusing refuses on every fold, forever, and each retry re-states a            // link the person may have removed in between — so an intent that has            // been failing since before the cutoff is a loop, not a recovery.            if entry.intent.at >= cutoff { kept.append(entry.intent) }        }        // Only what CHANGED is written back. When nothing settled, `kept` is the        // list that came out — the records were never persisted — so a write here        // is a round trip buying nothing, on a path that runs on every fold.        if kept.count != intents.count { writeAll(kept) }        return settled.filter { $0 }.count    }    /// The chip's membership on the THOUGHT itself (spec 2026-09-04 §1).    ///    /// The third mirrored membership, and the one that survives a capture that    /// became nothing at all: ``thoughtProjectLinkRef(_:)`` is the SAME rule the    /// server's filer writes through, so the phone and the router derive one row    /// id rather than two rows for one fact.    ///    /// Written through `update_thought` and NOT `link_to_project` — the header's    /// third gap. Same derived row id, and `applied_by: "user"` rather than    /// `"agent"`, which is what a `#` chip typed with a thumb actually is.    private func applyThoughtLinks(_ intent: PendingLinkIntent) async -> Bool {        var ok = true        for projectId in intent.projectIds {            let landed = await link(projectId: projectId, what: "thought project link") { slug in                try await self.writer.linkThoughtProject(                    projectSlug: slug,                    thoughtId: intent.inboxItemId                )            }            ok = landed && ok        }        return ok    }    /// One intent's links onto ONE record it created.    ///    /// Returns false only when a WRITE did not land — the caller then keeps the    /// intent for the next pass. A written refusal (a kind with no link decision,    /// a person note whose own row cannot be read, a kind this build does not    /// know) is NOT a failure: it can only ever come out the same way, so    /// retrying it for a week would be a loop, not a recovery.    private func applyOne(_ intent: PendingLinkIntent, _ record: RoutedRecord) async -> Bool {        guard let kind = RouteTargetKind(rawValue: record.kind) else {            // A kind the schema grew and this build has not learned. Reported            // rather than retried: a build cannot learn a kind by trying again.            report(                PendingLinkTrouble(                    route: "cotton.pendingLinks",                    what: "pending links: unknown routed kind \(record.kind)"                )            )            return true        }        var ok = true        let own = await notesOwnPerson(kind: kind, recordId: record.id)        for projectId in intent.projectIds {            // Two things arrive as a nil ref, and neither is a silently dropped            // chip. Either the kind has no project-link decision — a WRITTEN            // refusal in `CaptureLinks.swift`, which its total switch keeps            // honest — or this is a person_note whose own row could not be read,            // so there is no person to hang the membership on. The second case            // drops this record's person edges too, just below, and is reported            // there.            guard let ref = projectLinkRefFor(kind, record.id, own.personId) else { continue }            let landed = await link(projectId: projectId, ref: ref, what: "project link")            ok = landed && ok        }        guard let personRef = personLinkRefFor(kind, record.id) else { return ok }        // A record whose own person could not be read writes NO person edges at        // all — `personEdgeNeedsOwnPerson` is the shared rule, and this is the        // half of it only a writer can answer. The other records this capture        // filed are unaffected.        if personEdgeNeedsOwnPerson(kind) && !own.known { return ok }        for personId in intent.personIds {            // The note's OWN person is the one edge its row already states.            if isSelfPersonEdge(kind, personId, own.personId) { continue }            do {                try await writer.linkPerson(from: personRef, toPersonId: personId)            } catch {                report(                    PendingLinkTrouble(                        route: "cotton.pendingLinks",                        what: "pending person link not applied: \(error)"                    )                )                ok = false            }        }        return ok    }    /// One project link onto a record — `link_to_project`.    private func link(projectId: String, ref: LinkRef, what: String) async -> Bool {        await link(projectId: projectId, what: what) { slug in            try await self.writer.linkProject(projectSlug: slug, record: ref)        }    }    /// One project link, whichever tool writes it: resolve the id to a slug,    /// write, and decide what a failure MEANS.    ///    /// **Two failures, two answers, and the difference is the whole point.**    ///    /// *A name this app has not loaded* is not a refusal — the project list is    /// simply not in hand yet — so the intent is KEPT and the next fold tries    /// again. That is the difference between "we decided not to" and "we could    /// not yet".    ///    /// *A refusal the CORE answered* is a decision, and it is dropped. The one    /// that actually happens: a project archived between the capture and the    /// drain. Both writers resolve their `project` argument to an ACTIVE    /// project only — `project_by_slug`    /// (`cotton-tools/src/mcp/handlers/projects/mod.rs:97-119`) for    /// `link_to_project`, `resolve_project` (`handlers/common.rs:751-768`) for    /// `update_thought` — and both throw for one that is archived. The previous    /// app had no such refusal: it wrote by project ID with no status check, so    /// the chip landed. Nothing above the boundary can restore that, and    /// RETRYING it is    /// worse than losing it: the archive is a decision only the person can undo,    /// so the write refuses identically on every fold for seven days, and each    /// retry re-states a link they may have taken off in between. So it is    /// reported once and let go, on the same rule `applyOne` already states for    /// a kind with no link decision — *a written refusal can only ever come out    /// the same way*.    ///    /// The classification is structural, not a string match: `call` throws a    /// ``CottonCallError`` ONLY when the core answered `{"ok":false,"error":…}`,    /// which is the core having deliberated. A dead transport or an unreadable    /// answer throws something else and is kept.    private func link(        projectId: String,        what: String,        write: @Sendable (String) async throws -> Void    ) async -> Bool {        guard let slug = await source.projectSlug(projectId) else {            report(                PendingLinkTrouble(                    route: "cotton.pendingLinks",                    what: "pending \(what) not applied: no name for project \(projectId)"                )            )            return false        }        do {            try await write(slug)            return true        } catch let refusal as CottonCallError {            report(                PendingLinkTrouble(                    route: "cotton.pendingLinks",                    what:                        "pending \(what) dropped, the core refused it and will refuse it again: \(refusal.message)"                )            )            return true        } catch {            report(                PendingLinkTrouble(                    route: "cotton.pendingLinks",                    what: "pending \(what) not applied: \(error)"                )            )            return false        }    }    /// The person a `person_note` row names, or nothing for any other kind.    ///    /// Read ONCE per record and used for both decisions: it is the id a project    /// membership hangs on (`cotton_project_links` has no `person_note` kind, so    /// the membership lands on the PERSON), and it is the one person edge this    /// drain must NOT write, because the note's own row already states it.    private func notesOwnPerson(        kind: RouteTargetKind,        recordId: String    ) async -> (personId: String?, known: Bool) {        guard personEdgeNeedsOwnPerson(kind) else { return (nil, true) }        switch await source.ownPerson(ofPersonNote: recordId) {        case .known(let personId):            return (personId, true)        case .unreadable:            report(                PendingLinkTrouble(                    route: "cotton.pendingLinks",                    what: "pending links: person note unreadable"                )            )            return (nil, false)        }    }    // MARK: Storage    private func readAll() -> [PendingLinkIntent] {        guard let raw = store.data(key) else { return [] }        do {            return try JSONDecoder().decode([PendingLinkIntent].self, from: raw)        } catch {            // A corrupt intent list is not worth failing a capture over; the links            // are the recoverable half (they can be attached by hand), the capture            // is not. But every chip this device was holding just went, and an            // empty list with nothing said is the silent fallback the repo bans —            // so it is REPORTED and then swallowed, which is a different thing            // from hidden.            report(                PendingLinkTrouble(route: "cotton.pendingLinks.read", what: "\(error)")            )            return []        }    }    private func writeAll(_ intents: [PendingLinkIntent]) {        guard let encoded = try? JSONEncoder().encode(intents) else {            report(                PendingLinkTrouble(                    route: "cotton.pendingLinks.write",                    what: "the intent list would not encode"                )            )            return        }        store.set(key, encoded)    }}/// The records a capture has filed, whichever way it was filed.////// The list WINS where both are present: it is what a re-filing rewrites, and the/// single columns are what the first filing left behind. Free of the actor so it/// is decidable in a unit test on its own.func filedRecords(_ filed: FiledCapture?) -> [RoutedRecord] {    guard let filed else { return [] }    if !filed.routedRecords.isEmpty { return filed.routedRecords }    guard let kind = filed.routedKind, let id = filed.routedId else { return [] }    return [RoutedRecord(kind: kind, id: id)]}