Cotton code
330 lines · 12.2 KB · SwiftRaw
// What became of a capture — the whole routing story, as a table.//// The capture story, case for case — what the list's caption and the thought's// own page both read (`ThoughtStory`).//// The four distinctions `ThoughtStory` exists to keep are the four this file// exists to hold: filed vs corrected, filing vs a proposal, routed-into-nothing// vs still waiting, and the sweep's own sentence vs the filed caption. Each of// them was erased once by a shorter reading, and each has its own case below.//// EVERY FIXTURE IS THE READ'S OWN JSON. A capture is whatever `read.thoughts`// answered, held as a `JSONValue` and asked for its keys — so a fixture is// written the way the wire writes it and nothing here can drift from the crate// by agreeing with a Swift shape instead. THE CLOCK AND THE ZONE ARE FIXED: a// Kolkata calendar and an explicit `now`, never `Calendar.current`.import CottonKitimport Foundationimport XCTest@testable import CottonUIprivate enum ThoughtFixtures {    static var calendar: Calendar {        var out = Calendar(identifier: .gregorian)        if let zone = TimeZone(identifier: "Asia/Kolkata") { out.timeZone = zone }        out.locale = Locale(identifier: "en_US_POSIX")        return out    }    private static func quoted(_ value: String?) -> String {        guard let value else { return "null" }        return "\"\(value)\""    }    /// One capture, every column spelled out — the ledger's own shape.    /// `routedRecords` and `routeProposal` are passed as RAW JSON, because that    /// is what the read parses them into.    static func thought(        id: String = "t1",        rawText: String? = "Buy milk",        audioUrl: String? = nil,        capturedAt: String = "2026-08-17T09:00:00+05:30",        routeStatus: String = "pending",        routeReason: String? = nil,        routeConfidence: Double? = nil,        routedKind: String? = nil,        routedId: String? = nil,        routedRecords: String = "null",        routeProposal: String = "null",        sweepNote: String? = nil    ) throws -> JSONValue {        let json = """            {              "id": \(quoted(id)),              "rawText": \(quoted(rawText)),              "audioUrl": \(quoted(audioUrl)),              "capturedAt": \(quoted(capturedAt)),              "routeStatus": \(quoted(routeStatus)),              "routeReason": \(quoted(routeReason)),              "routeConfidence": \(routeConfidence.map { "\($0)" } ?? "null"),              "routedKind": \(quoted(routedKind)),              "routedId": \(quoted(routedId)),              "routedRecords": \(routedRecords),              "routeProposal": \(routeProposal),              "sweepNote": \(quoted(sweepNote)),              "sweptAt": null            }            """        return try value(json)    }    static func value(_ json: String) throws -> JSONValue {        try JSONDecoder().decode(JSONValue.self, from: Data(json.utf8))    }}final class ThoughtFilingHandTests: XCTestCase {    func testTheRouterIsTheHandUntilSomebodyCorrectsIt() throws {        XCTAssertEqual(            ThoughtStory.filingHand(try ThoughtFixtures.thought(routeStatus: "routed")), .router)        XCTAssertEqual(            ThoughtStory.filingHand(try ThoughtFixtures.thought(routeStatus: "pending")), .router)    }    func testACorrectionOverAConfidentFilingIsAMOVE() throws {        // The router only ever writes the confidence column at or above its own        // line, so a confident number under `corrected` means it filed this and        // the person moved it.        XCTAssertEqual(            ThoughtStory.filingHand(                try ThoughtFixtures.thought(routeStatus: "corrected", routeConfidence: 0.91)),            .userMoved        )    }    func testTheThresholdItselfCountsAsConfident() throws {        XCTAssertEqual(            ThoughtStory.filingHand(                try ThoughtFixtures.thought(                    routeStatus: "corrected", routeConfidence: confidenceThreshold)),            .userMoved        )    }    func testAHandFilingAfterAnAbstentionIsNotACorrectionOfAnything() throws {        XCTAssertEqual(            ThoughtStory.filingHand(                try ThoughtFixtures.thought(routeStatus: "corrected", routeConfidence: 0.2)),            .userFiled        )        XCTAssertEqual(            ThoughtStory.filingHand(                try ThoughtFixtures.thought(routeStatus: "corrected", routeConfidence: nil)),            .userFiled        )    }}final class ThoughtRoutedRefsTests: XCTestCase {    func testEveryListedRecordIsARef() throws {        let thought = try ThoughtFixtures.thought(            routeStatus: "routed",            routedRecords: """                [{"kind":"todo","id":"td1"},{"kind":"event","id":"e1"}]                """        )        XCTAssertEqual(            ThoughtStory.routedRefs(thought),            [RoutedRef(kind: "todo", id: "td1"), RoutedRef(kind: "event", id: "e1")]        )    }    func testTheOlderSinglePointerIsTheFallback() throws {        let thought = try ThoughtFixtures.thought(            routeStatus: "routed", routedKind: "todo", routedId: "td1")        XCTAssertEqual(ThoughtStory.routedRefs(thought), [RoutedRef(kind: "todo", id: "td1")])    }    func testTheListWinsOverThePointer() throws {        let thought = try ThoughtFixtures.thought(            routeStatus: "routed",            routedKind: "todo",            routedId: "old",            routedRecords: """                [{"kind":"note","id":"n1"}]                """        )        XCTAssertEqual(ThoughtStory.routedRefs(thought), [RoutedRef(kind: "note", id: "n1")])    }    func testAnEntryMissingItsKindOrIdIsSkippedRatherThanDrawnHalfBuilt() throws {        let thought = try ThoughtFixtures.thought(            routeStatus: "routed",            routedRecords: """                [{"kind":"todo"},{"id":"e1"},{"kind":"note","id":"n1"}]                """        )        XCTAssertEqual(ThoughtStory.routedRefs(thought), [RoutedRef(kind: "note", id: "n1")])    }    func testNothingRoutedIsNoRefsAtAll() throws {        XCTAssertTrue(            ThoughtStory.routedRefs(try ThoughtFixtures.thought(routeStatus: "routed")).isEmpty)    }    func testARefKnowsItsBadgeAndAnUnknownKindDoesNot() {        XCTAssertEqual(RoutedRef(kind: "person_note", id: "p1").badge, .personNote)        XCTAssertNil(RoutedRef(kind: "spaceship", id: "x").badge)    }}final class ThoughtProposalTests: XCTestCase {    // ── what a chip is ────────────────────────────────────────────────────    func testAKindThisAppCannotDrawSaysNothing() throws {        XCTAssertNil(            ThoughtStory.targetKind(                try ThoughtFixtures.value("""                    {"kind":"spaceship","title":"nope"}                    """)))    }}final class ThoughtCaptionTests: XCTestCase {    private let cal = ThoughtFixtures.calendar    // ── the resolved date ─────────────────────────────────────────────────    // ── the one line under a filed capture ────────────────────────────────    func testAPersonNoteIsWordedWithTheNameItLandedOn() {        XCTAssertEqual(            ThoughtStory.filedSummary(kind: .personNote, destinationName: "Asha", calendar: cal),            CottonStrings.noteOnPerson("Asha")        )    }    func testAPersonNoteWithNoNameFallsBackToItsKind() {        XCTAssertEqual(            ThoughtStory.filedSummary(kind: .personNote, destinationName: "  ", calendar: cal),            BadgeKind.personNote.label        )    }    func testTheSpokenMarkLeadsAndTheCorrectionCloses() {        let plain = ThoughtStory.filedSummary(kind: .todo, calendar: cal)        let line = ThoughtStory.filedSummary(            kind: .todo, corrected: true, spoken: true, calendar: cal)        XCTAssertTrue(line.contains(plain))        XCTAssertFalse(line.hasPrefix(plain), "the spoken mark leads")        XCTAssertFalse(line.hasSuffix(plain), "the correction closes")    }    func testADismissedCaptureSaysOnlyThatAndKeepsTheSpokenMark() {        let dismissed = ThoughtStory.filedSummary(kind: .todo, dismissed: true, calendar: cal)        XCTAssertFalse(dismissed.isEmpty)        XCTAssertFalse(dismissed.contains(BadgeKind.todo.label), "says only that it was dismissed")        let spoken = ThoughtStory.filedSummary(kind: .todo, dismissed: true, spoken: true, calendar: cal)        XCTAssertTrue(spoken.hasSuffix(dismissed))        XCTAssertNotEqual(spoken, dismissed)    }    func testNoFactsIsAnEmptyLineRatherThanAnEmptySentence() {        XCTAssertEqual(ThoughtStory.filedSummary(kind: nil, calendar: cal), "")    }}final class ThoughtWhyItStoppedTests: XCTestCase {}final class ThoughtOutcomeTests: XCTestCase {    func testAnUnconfirmedRowIsStillSending() throws {        XCTAssertEqual(ThoughtStory.outcome(try ThoughtFixtures.thought(id: "temp-1")), .sending)    }    func testPendingWithNoReasonIsStillBeingRead() throws {        XCTAssertEqual(            ThoughtStory.outcome(try ThoughtFixtures.thought(routeStatus: "pending")), .filing)    }    func testPendingWithAReasonIsAProposalWaitingForAnAnswer() throws {        XCTAssertEqual(            ThoughtStory.outcome(                try ThoughtFixtures.thought(routeStatus: "pending", routeReason: "low_confidence")),            .proposal        )    }    func testADismissedCaptureWasKept() throws {        XCTAssertEqual(            ThoughtStory.outcome(try ThoughtFixtures.thought(routeStatus: "dismissed")), .kept)    }    func testRoutedIntoNothingSTAYEDAThought() throws {        // Not `filed` with an empty list, which would draw an attachment block        // that says nothing — and not "still waiting to be filed", which was a        // lie about a capture nothing more was going to happen to.        XCTAssertEqual(            ThoughtStory.outcome(try ThoughtFixtures.thought(routeStatus: "routed")), .thought)    }    func testAConfidentFilingCarriesItsRecordsAndAnEmptyCaption() throws {        let thought = try ThoughtFixtures.thought(            routeStatus: "routed",            routeConfidence: 0.9,            routedRecords: """                [{"kind":"todo","id":"td1"}]                """        )        XCTAssertEqual(            ThoughtStory.outcome(thought),            .filed(records: [RoutedRef(kind: "todo", id: "td1")], caption: "")        )    }    func testACaptureTheOwnerMOVEDSaysItWasCorrected() throws {        let thought = try ThoughtFixtures.thought(            routeStatus: "corrected",            routeConfidence: 0.9,            routedRecords: """                [{"kind":"note","id":"n1"}]                """        )        XCTAssertEqual(            ThoughtStory.outcome(thought),            .filed(records: [RoutedRef(kind: "note", id: "n1")], caption: "corrected")        )    }    func testAHandFilingAfterAnAbstentionSaysNothingAboutCorrection() throws {        let thought = try ThoughtFixtures.thought(            routeStatus: "corrected",            routeConfidence: 0.2,            routedRecords: """                [{"kind":"note","id":"n1"}]                """        )        XCTAssertEqual(            ThoughtStory.outcome(thought),            .filed(records: [RoutedRef(kind: "note", id: "n1")], caption: "")        )    }    func testTheSweepsOwnSentenceREPLACESTheCaption() throws {        // The chips above already show the new outcome, so the sweep's note        // stands alone rather than sitting beside a correction clause.        let thought = try ThoughtFixtures.thought(            routeStatus: "corrected",            routeConfidence: 0.9,            routedRecords: """                [{"kind":"todo","id":"td1"}]                """,            sweepNote: "Refiled as a todo when the plumber replied."        )        XCTAssertEqual(            ThoughtStory.outcome(thought),            .filed(                records: [RoutedRef(kind: "todo", id: "td1")],                caption: "Refiled as a todo when the plumber replied."            )        )    }}