Cotton code
429 lines · 20.3 KB · SwiftRaw
// The plain-language sweep, in Swift.//// The Swift half of the plain-language sweep; the Rust side is// `crates/cotton-core/src/language/emit_json_tests.rs`.// The fourteen retired terms are declared ONCE, in// `crates/cotton-core/src/language/retired_terms.rs`, and reach here through the// GENERATOR (`cotton-gen` → `Generated/RetiredTerms.swift`) rather than// through a path read or a hand copy:////   • a path read cannot work — the sources are not in a test bundle running on//     a simulator, and a guard that reads the Mac's filesystem for its RULES//     (rather than for the code it is checking) would go quiet the day the file//     moves, which is the exact hazard AGENTS.md names;//   • a hand copy needs a second test to stay honest;//   • generating it makes `pnpm gen:design:check` the//     guard, which is the shape this repo already chose for the Rust half.//// WHAT IS SWEPT: the phone's own Swift sources — CODE and string literals, with// COMMENTS STRIPPED — and its string catalogue.//// Comments are stripped deliberately, and it is the one judgement call in this// guard. The script-side sweep covers the app catalog, the AGENTS.md partials,// the generator, the site and `docs/`; it does NOT sweep// every engineering comment. Engineering prose legitimately says "the mark column" (a// RecordRow's slot), "re-seats a row" and "the string front doors", and none of// those is the logo, a participant or a server. Banning them would teach the// next person to write worse comments rather than better product language.//// The STRICT list is used on the sources — a bare `room` in a Swift identifier// or string is always the retired metaphor, because this tree never talks about// disk space — and the PLAIN list on the catalogue, which holds sentences a// person reads and may legitimately say "mark read".import Foundationimport XCTest@testable import CottonUI/// The string catalogue, DECODED rather than cast.////// `JSONSerialization` hands back `[String: Any]`, and this repo bans `Any`/// for the reason it always does: every `as?` after one is a guess the compiler/// cannot check, and a shape change reads as a missing key rather than as an/// error. `Codable` structs make the shape a declaration.struct StringCatalogue: Decodable {    struct Unit: Decodable {        let state: String?        let value: String?    }    struct Variations: Decodable {        let plural: [String: Localization]?    }    struct Localization: Decodable {        let stringUnit: Unit?        let variations: Variations?    }    struct Entry: Decodable {        let extractionState: String?        let localizations: [String: Localization]?    }    let sourceLanguage: String    let strings: [String: Entry]    static func read() throws -> StringCatalogue {        let text = try SourceSweep.mustRead(            "apps/cotton/Sources/CottonUI/Resources/Localizable.xcstrings",            ownedBy: "phone (this lane)"        )        return try JSONDecoder().decode(StringCatalogue.self, from: Data(text.utf8))    }    /// Every sentence a person could read: the keys AND the values, plural    /// variations included.    func everySentence() -> [String] {        var out: [String] = []        for (key, entry) in strings {            out.append(key)            for localization in entry.localizations?.values ?? [:].values {                if let value = localization.stringUnit?.value { out.append(value) }                for plural in localization.variations?.plural?.values ?? [:].values {                    if let value = plural.stringUnit?.value { out.append(value) }                }            }        }        return out    }}final class LanguageSweepTests: XCTestCase {    /// The files that MAY say a retired word, and why. A new entry has    /// to earn a sentence — `testGivesTheExemptionAReasonWorthReading` is what    /// makes "a sentence" mean one.    private static let exempt: [String: String] = [        "Generated/RetiredTerms.swift":            "the generated vocabulary itself — it holds the fourteen patterns, so it necessarily contains every word they catch",    ]    private struct Hit {        let where_: String        let slug: String        let text: String        let instead: String    }    private func sweep(        _ terms: [RetiredTerm],        over documents: [(name: String, text: String)]    ) throws -> [Hit] {        var hits: [Hit] = []        for term in terms {            let regex = try term.regex()            for (name, text) in documents {                let range = NSRange(text.startIndex..., in: text)                for match in regex.matches(in: text, range: range) {                    guard let found = Range(match.range, in: text) else { continue }                    hits.append(                        Hit(where_: name, slug: term.slug, text: String(text[found]), instead: term.instead)                    )                }            }        }        return hits    }    private func report(_ hits: [Hit]) -> String {        hits.map { "\($0.where_): \"\($0.text)\" (\($0.slug)) — \($0.instead)" }.joined(separator: "\n")    }    // ── The vocabulary itself ─────────────────────────────────────────────    func testTheStrictListExtendsThePlainOneByIndex() {        for (at, term) in RetiredVocabulary.plain.enumerated() {            XCTAssertEqual(RetiredVocabulary.strict[at].slug, term.slug)            XCTAssertEqual(RetiredVocabulary.strict[at].pattern, term.pattern)        }        XCTAssertEqual(RetiredVocabulary.strict.last?.slug, "room-bare")    }    func testEveryTermCompilesAndSaysWhatToSayInstead() throws {        for term in RetiredVocabulary.strict {            XCTAssertNoThrow(try term.regex(), term.slug)            XCTAssertGreaterThan(term.instead.count, 5, term.slug)        }    }    /// Anti-vacuity: the patterns really do fire. A sweep whose regexes matched    /// nothing would be green over a tree full of retired words.    func testThePatternsCatchTheSentencesTheyWereWrittenFor() throws {        let sentences = [            ("door", "Open the door to your data"),            ("shelf", "Put it on the shelf"),            ("your-file", "Everything lives in your file"),            ("pack", "Read the pack this morning"),            ("seat", "Invite them to a seat"),            ("nudge", "Set a nudge for Tuesday"),            ("law", "The laws of this app"),            ("life-record", "Every life record you keep"),            ("model-on-device", "The AI runs on your Mac"),        ]        for (slug, sentence) in sentences {            let term = try XCTUnwrap(RetiredVocabulary.strict.first { $0.slug == slug })            let hits = try sweep([term], over: [("probe", sentence)])            XCTAssertFalse(hits.isEmpty, "\(slug) did not catch \"\(sentence)\"")        }    }    func testTheNarrowPatternsLeaveOrdinaryEnglishAlone() throws {        // Three of the fourteen share a word with English the product genuinely        // says. The dictionary's own phrasing is what makes the narrow form        // correct: it retires "the mark", "the box" and "the pack" as NAMES,        // not the words.        let honest = [            "Mark read", "Unpack the archive", "There isn't room to record",        ]        let hits = try sweep(            RetiredVocabulary.plain,            over: honest.map { (name: $0, text: $0) }        )        XCTAssertTrue(hits.isEmpty, "the narrow patterns fired on honest English:\n\(report(hits))")    }    // ── The sweep ─────────────────────────────────────────────────────────    func testTheExemptFileIsTheOneThatDoesSayThemAll() throws {        // Anti-vacuity: the exemption is load-bearing, not decoration. If the        // generated vocabulary stopped containing the words its own patterns        // catch, something has gone wrong with the generator.        let generated = try SourceSweep.mustRead(            "apps/cotton/Sources/CottonUI/Generated/RetiredTerms.swift",            ownedBy: "phone (generated by cotton-gen)"        )        let hits = try sweep(RetiredVocabulary.plain, over: [("RetiredTerms.swift", generated)])        XCTAssertFalse(hits.isEmpty, "the generated vocabulary no longer holds its own words")    }    func testGivesTheExemptionAReasonWorthReading() {        for (path, reason) in Self.exempt {            XCTAssertGreaterThan(reason.count, 40, "\(path): a reason worth reading")        }    }    func testTheStringCatalogueSaysNoRetiredWord() throws {        let catalogue = try StringCatalogue.read()        XCTAssertEqual(catalogue.sourceLanguage, "en", "English is the source language")        XCTAssertFalse(catalogue.strings.isEmpty, "the catalogue holds no strings")        // KEYS AND VALUES BOTH. A key is English here — that is the whole        // English-only policy — but a `stringUnit` value and a plural        // `variation` are what a person actually reads, and sweeping only the        // keys left every one of them unread.        let swept = catalogue.everySentence().map { (name: "Localizable.xcstrings", text: $0) }        XCTAssertGreaterThan(            swept.count, catalogue.strings.count,            "the sweep read no values at all — only keys"        )        let hits = try sweep(            // The PLAIN list here: these are sentences a person reads, and one            // of them may legitimately say "mark read".            RetiredVocabulary.plain,            over: swept        )        XCTAssertTrue(hits.isEmpty, "the string catalogue uses retired vocabulary:\n\(report(hits))")    }    func testEveryCatalogueEntryActuallyCarriesEnglish() throws {        // A key with no `en` unit renders its key, which is the policy working        // — but a key with an EMPTY one renders nothing at all.        let catalogue = try StringCatalogue.read()        for (key, entry) in catalogue.strings {            let english = entry.localizations?["en"]            XCTAssertNotNil(english, "\"\(key)\" has no English localization")            let value = english?.stringUnit?.value ?? english?.variations?.plural?.values.first?.stringUnit?.value            XCTAssertNotNil(value, "\"\(key)\" has an English entry with no value")            XCTAssertFalse(value?.isEmpty ?? true, "\"\(key)\" has an EMPTY English value")        }    }    func testTheProductNeverPromisesTheModelRunsOnThePhone() throws {        // Not retired metaphors — two factual claims the product must not        // make ("A database of your own data, on your Mac, that any AI        // assistant can use", never a promise about where the model runs; and        // "records", never the phrase the second rule retires, for what the        // database holds). Both are declared beside the metaphors in        // `crates/cotton-core/src/language/retired_terms.rs` and reach here through        // the generator, so this test READS them by slug rather than restating        // them: a literal here would be a second declaration to keep in step,        // and the sweep above would never know it had drifted.        //        // COMMENTS STRIPPED, for the reason the vocabulary sweep strips them:        // a file whose header writes the rule down would fail the guard that        // enforces it, which teaches the next person to delete the sentence.        let claims = try ["life-record", "model-on-device"].map { slug in            try XCTUnwrap(                RetiredVocabulary.plain.first { $0.slug == slug },                "\(slug) is missing from the generated vocabulary"            )        }        let sources = try SourceSweep.swiftSources()            .filter { file in !Self.exempt.keys.contains { file.name.hasSuffix($0) } }            .map { (name: $0.name, text: SourceSweep.withoutComments($0.text)) }        let hits = try sweep(claims, over: sources)        XCTAssertTrue(hits.isEmpty, report(hits))    }}/// **No sentence a person reads names a method the boundary answers.**////// 4l's walk opened `/messages/import` and read: *"the method that runs one —/// ingest.chatExport — isn't in this build yet."* That is a wire name from/// `crates/cotton-ffi/src/methods.rs` printed to somebody who has never seen/// the boundary and cannot act on it. The sentence was right about the fact and/// wrong about the audience: what a person needs is that importing is not in/// this build, not the identifier of the call that would do it.////// It is not a retired METAPHOR, so the vocabulary sweep above could never see/// it — the two sweeps look for different things and both are needed.////// The method names come from `CottonMethod`'s own declarations rather than a/// list here, because Swift cannot enumerate an enum of statics and a hand-kept/// copy is a copy that drifts.final class NoMethodNamesInCopyTests: XCTestCase {    func testNoUserFacingStringNamesABoundaryMethod() throws {        // Every `Boundary*.swift` and every `*Methods.swift`, not one of them:        // the names are spread over nineteen files, one per lane, and reading        // only the first would sweep a fraction of the surface while looking        // thorough. A lane whose shapes went untyped (I3) keeps its names in a        // `…Methods.swift` (`DayMethods.swift` first), which is why the second        // shape is swept too.        let declaration = try NSRegularExpression(            pattern: #"static let \w+ = "([a-z]\w*\.[A-Za-z]\w*)""#        )        var methods: [String] = []        // `AppSources.all()` names a file by its path UNDER `Sources`        // ("CottonKit/Boundary+4h.swift"), so the match is on the last        // component. A `hasPrefix` on the whole name would sweep nothing and        // pass — which is the shape of quiet guard this repo has a rule about.        for source in try AppSources.all()        where AppSources.fileName(source.name).hasPrefix("Boundary")            || AppSources.fileName(source.name).hasSuffix("Methods.swift") {            let whole = NSRange(source.text.startIndex..<source.text.endIndex, in: source.text)            methods += declaration.matches(in: source.text, range: whole).compactMap { match in                guard let range = Range(match.range(at: 1), in: source.text) else { return nil }                return String(source.text[range])            }        }        XCTAssertGreaterThan(            methods.count, 100,            "the method names were not found — have the Boundary files moved or changed shape?"        )        // **EVERY `CottonUI/` SOURCE, not the `Strings*` tables alone.** Until        // I4 the app's copy all lived in those tables, so sweeping files whose        // name starts with "Strings" swept the app's language. Copy is written        // where it is drawn now — `Text("Done")`, `ScreenBar(title: "Todos")`,        // `toasts.show("Archived")` — and the old filter would sweep the few        // hundred sentences that kept a member and miss the thousands that did        // not. `CottonKit/` stays out of the sweep because that is where the        // method names are DECLARED; a file that must say `"read.todos"` is not        // showing it to anybody.        //        // **Only a literal with a SPACE in it, and only a literal.** The old        // shape asked whether the whole file's code contained a method name,        // which on a screen reads code as copy: `CottonUI` carries route paths,        // `accessibilityIdentifier("chat-row-…")`, `systemImage: "archivebox"`        // and read keys like `"threadId"`, and a Swift expression `read.todos`        // would match a method name outright. Every one of those is a TOKEN and        // no token contains a space; a sentence a person reads almost always        // does. The obvious alternative — sweeping only literals inside `Text(`,        // `Label(`, `title:`, `toasts.show(` — is the shape this directory has        // a rule about: the app draws copy through dozens of spellings        // (`QuietState(title:message:)`, `confirmationDialog`, an enum's own        // `label`, `.accessibilityLabel`), and a new one arrives with the sweep        // green. A sweep over every sentence cannot go quiet that way.        //        // What the rule knowingly costs: a ONE-WORD sentence is not read. It        // could not name a method anyway — every method here is `noun.verb`        // with no space in it, so a bare `"read.todos"` in a source is a        // constant, not something a person is being shown.        var offenders: [String] = []        var sentenceCount = 0        for source in try AppSources.all() where source.name.hasPrefix("CottonUI/") {            // **COMMENTS STRIPPED**, for the reason the vocabulary sweep above            // strips them: the doc comment that explains WHY a method name was            // taken out of a sentence names the method, and a guard that failed            // on its own explanation teaches the next person to delete the            // explanation. `capture.media` in `Strings+4gPhotos.swift` is            // exactly that comment, and it should stay.            let code = SourceSweep.withoutComments(source.text)            for sentence in Self.sentences(in: code) {                sentenceCount += 1                for method in methods where sentence.contains(method) {                    offenders.append("\(source.name) says \(method) in \"\(sentence)\"")                }            }        }        // Anti-vacuity, as every sweep in this directory carries: a filter that        // matched nothing would pass on nothing. The app says thousands of        // sentences; the floor is well under that and still far above zero.        XCTAssertGreaterThan(            sentenceCount, 500,            "the sweep read \(sentenceCount) sentences — it would pass on nothing"        )        XCTAssertEqual(            offenders, [],            """            A sentence a person reads must not name a boundary method. Say what \            cannot be done and what still works; the identifier belongs in a \            code comment, where the next person to read the file will find it.            """        )    }    /// Every string literal in a source that reads as a SENTENCE — one with a    /// space in it. See the rule above for why a space is the line.    ///    /// A scanner rather than a regex: a pattern for a Swift literal has to know    /// about `\"` anyway, and the loop that knows it can also take a `"""`    /// block whole — a paragraph wrapped over five lines is one sentence, and a    /// regex would read its quotes as five broken ones.    static func sentences(in code: String) -> [String] {        var out: [String] = []        var i = code.startIndex        while i < code.endIndex {            guard code[i] == "\"" else {                i = code.index(after: i)                continue            }            if code[i...].hasPrefix("\"\"\"") {                let start = code.index(i, offsetBy: 3)                guard let close = code.range(of: "\"\"\"", range: start..<code.endIndex) else {                    break                }                out.append(String(code[start..<close.lowerBound]))                i = close.upperBound                continue            }            var j = code.index(after: i)            var value = ""            var closed = false            while j < code.endIndex {                let character = code[j]                if character == "\\" {                    let next = code.index(after: j)                    guard next < code.endIndex else { break }                    value.append(character)                    value.append(code[next])                    j = code.index(after: next)                    continue                }                if character == "\"" {                    closed = true                    j = code.index(after: j)                    break                }                // A newline before the closing quote: whatever that was, it was                // not a single-line literal.                if character == "\n" { break }                value.append(character)                j = code.index(after: j)            }            i = j            if closed { out.append(value) }        }        return out.filter { $0.contains(" ") }    }}