Cotton code
93 lines · 4.2 KB · SwiftRaw
// A receipt can retract its capture, or move a fresh text capture by copying// it into the chosen database before retracting the source. Each write uses// that database's ordinary write door. A failed source retraction keeps the// successful copy so Retry cannot create another; Undo reverses a finished move.import Foundationpublic struct DatabaseRef: Equatable, Sendable {    public var id: String    public var name: String    public init(id: String, name: String) {        self.id = id        self.name = name    }}public enum ThoughtFilingGap: Error, Equatable, Sendable {    case missingThought    case mediaNeedsTransfer    case alreadyFiled    case moveInProgress    case sourceRetractionFailed(destination: String)}public protocol ThoughtFiling: Sendable {    func takeBack(thoughtId: String) async throws    func move(thoughtId: String, to database: DatabaseRef) async throws}public actor CoreThoughtFiling: ThoughtFiling {    private let core: any CottonCalling    private struct Copy {        let database: DatabaseRef        let id: String        var finished = false    }    private var copies: [String: Copy] = [:]    private var working: Set<String> = []    public init(core: any CottonCalling) { self.core = core }    private func dismiss(_ id: String, on core: any CottonCalling, dismissed: Bool = true) async throws {        _ = try await core.call(CottonMethod.write, WriteRequest(            tool: "update_thought", args: .object(["id": .string(id), "dismissed": .bool(dismissed)])),            as: WriteAnswer.self)    }    public func takeBack(thoughtId: String) async throws {        guard working.insert(thoughtId).inserted else { throw ThoughtFilingGap.moveInProgress }        defer { working.remove(thoughtId) }        if let copy = copies[thoughtId] {            // Restore the source before retracting a completed move's copy:            // neither a refusal nor an interrupted Undo can lose the words.            if copy.finished { try await dismiss(thoughtId, on: core, dismissed: false) }            let target = DatabaseScopedCore(underlying: core, database: copy.database.id)            try await dismiss(copy.id, on: target)            if !copy.finished { try await dismiss(thoughtId, on: core) }            copies.removeValue(forKey: thoughtId)        } else {            try await dismiss(thoughtId, on: core)        }    }    public func move(thoughtId: String, to database: DatabaseRef) async throws {        guard working.insert(thoughtId).inserted else { throw ThoughtFilingGap.moveInProgress }        defer { working.remove(thoughtId) }        if let copy = copies[thoughtId] {            guard copy.database.id == database.id else { throw ThoughtFilingGap.moveInProgress }            if copy.finished { return }        } else {            let ledger = try await core.callJSON(CottonMethod.readThoughts)            guard let thought = (ledger["thoughts"]?.array ?? []).first(where: { $0["id"]?.string == thoughtId }),                  let text = thought["rawText"]?.string, !text.isEmpty else { throw ThoughtFilingGap.missingThought }            // Never silently leave a recording or picture in the source file.            guard thought["audioUrl"]?.string == nil, (thought["attachments"]?.array ?? []).isEmpty else {                throw ThoughtFilingGap.mediaNeedsTransfer            }            // Moving already-filed records needs their own transfer, not a            // second routing of the same sentence in another database.            guard thought["routeStatus"]?.string == "pending" else { throw ThoughtFilingGap.alreadyFiled }            let target = DatabaseScopedCore(underlying: core, database: database.id)            let created = try await target.callJSON(CottonMethod.captureCreate, CaptureRequest(text: text, plan: thought["routeProposal"]))            guard let id = created["id"]?.string, !id.isEmpty else { throw ThoughtFilingGap.missingThought }            copies[thoughtId] = Copy(database: database, id: id)        }        do {            try await dismiss(thoughtId, on: core)            copies[thoughtId]?.finished = true        } catch {            throw ThoughtFilingGap.sourceRetractionFailed(destination: database.name)        }    }}