// 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 Foundation import 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.. [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..