// 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".importFoundationimport XCTest@testable importCottonUI/// 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.structStringCatalogue: Decodable {structUnit: Decodable {let state: String?let value: String? }structVariations: Decodable {let plural: [String: Localization]? }structLocalization: Decodable {let stringUnit: Unit?let variations: Variations? }structEntry: Decodable {let extractionState: String?let localizations: [String: Localization]? }let sourceLanguage: Stringlet strings: [String: Entry]staticfunc read() throws -> StringCatalogue {let text = trySourceSweep.mustRead("apps/cotton/Sources/CottonUI/Resources/Localizable.xcstrings", ownedBy: "phone (this lane)" )returntry 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 {iflet value = localization.stringUnit?.value { out.append(value) }for plural in localization.variations?.plural?.values ?? [:].values {iflet value = plural.stringUnit?.value { out.append(value) } } } }return out }}finalclassLanguageSweepTests: 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.privatestaticlet exempt: [String: String] = ["Generated/RetiredTerms.swift":"the generated vocabulary itself — it holds the fourteen patterns, so it necessarily contains every word they catch", ]privatestructHit {let where_: Stringlet slug: Stringlet text: Stringlet instead: String }privatefunc 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) {guardlet 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 }privatefunc 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) inRetiredVocabulary.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 inRetiredVocabulary.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 = trySourceSweep.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) inSelf.exempt { XCTAssertGreaterThan(reason.count, 40, "\(path): a reason worth reading") } }func testTheStringCatalogueSaysNoRetiredWord() throws {let catalogue = tryStringCatalogue.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 = tryStringCatalogue.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 intry XCTUnwrap(RetiredVocabulary.plain.first { $0.slug == slug },"\(slug) is missing from the generated vocabulary" ) }let sources = trySourceSweep.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.finalclassNoMethodNamesInCopyTests: 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 intryAppSources.all()whereAppSources.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 inguardlet range = Range(match.range(at: 1), in: source.text) else { returnnil }returnString(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 = 0for source intryAppSources.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 inSelf.sentences(in: code) { sentenceCount += 1for 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.staticfunc sentences(in code: String) -> [String] {var out: [String] = []var i = code.startIndexwhile i < code.endIndex {guard code[i] == "\""else { i = code.index(after: i)continue }if code[i...].hasPrefix("\"\"\"") {let start = code.index(i, offsetBy: 3)guardlet close = code.range(of: "\"\"\"", range: start..<code.endIndex) else {break } out.append(String(code[start..<close.lowerBound])) i = close.upperBoundcontinue }var j = code.index(after: i)var value = ""var closed = falsewhile 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 = jif closed { out.append(value) } }return out.filter { $0.contains(" ") } }}