// Reading the repo's own files from a test, safely.//// Three guards in this target sweep source: the colour guard, the language// sweep and the metrics check. All three read files BY PATH, which AGENTS.md// warns about by name — "a guard that reads another package's file BY PATH is a// guard that goes quiet, not red, when that file moves". The three rules it// gives are implemented HERE, once, so no individual guard can forget one://// (a) A read that finds nothing FAILS LOUDLY, with the path in the message,// before any regex runs. `mustRead` is the only way to read a file.// (b) Every reader names the lane that owns the path it reads — see each// guard's own comment.// (c) Before any file move lands, grep the moved path repo-wide, `__tests__`// included, in every open worktree. These readers are exactly the ones// `tsc` and the Swift import graph cannot see.//// The paths are resolved from `#filePath`, which is a COMPILE-time constant// baked into the test binary — the simulator then reads the Mac's own// filesystem through it. That works, and is proved by// `SourceSweepTests.testTheRepoIsReachableAtAll` rather than assumed.importFoundationimport XCTestenumSourceSweep {/// Names the checkout these tests were copied from, when they run from a/// copy: `scripts/ui-tests-stub.sh` builds them in a package outside the/// tree, where `#filePath` names the copy and walking up from it finds no/// repository. Unset everywhere else — `swift test` in the package and the/// simulator read the path the compiler baked in.staticlet rootVariable = "COTTON_UI_TESTS_REPO_ROOT"/// The repo root every test that reads the tree asks for.staticvar repoRoot: URL { root(named: ProcessInfo.processInfo.environment[rootVariable], file: #filePath) }/// The root `named`, else walked up from this file:/// Tests/CottonUITests/SourceSweep.swift → cotton → apps → root.staticfunc root(named: String?, file: String) -> URL {iflet named, !named.isEmpty { return URL(fileURLWithPath: named) }return URL(fileURLWithPath: file) .deletingLastPathComponent() // CottonUITests .deletingLastPathComponent() // Tests .deletingLastPathComponent() // cotton .deletingLastPathComponent() // apps .deletingLastPathComponent() // <repo> }staticvar iosSources: URL { repoRoot.appendingPathComponent("apps/cotton/Sources") }/// Loom's sources (`apps/loom/Sources`): the values, the look and the/// faces the app draws with, a package of their own since 28 Oct 2026.staticvar loomSources: URL { repoRoot.appendingPathComponent("apps/loom/Sources") }/// The modules that live in Loom, not in `apps/cotton`.staticlet loomModules: Set<String> = ["CottonValues", "CottonPaper", "CottonFaces"]/// A source by its module-relative path (`CottonPaper/Theme/Theme.swift`,/// `CottonUI/Deck/DeckFace.swift`), in whichever package holds its module.staticfunc source(_ relativePath: String) -> URL {let module = String(relativePath.prefix { $0 != "/" })return (loomModules.contains(module) ? loomSources : iosSources).appendingPathComponent(relativePath) }/// The kits (`crates/cotton-core/kits`): each table's one definition,/// read by path — the app bundles none, tables come from the object.staticvar kits: URL { repoRoot.appendingPathComponent("crates/cotton-core/kits") }/// The one definition of `table`: the shell's, else the personal kit's.staticfunc kitTable(_ table: String) -> URL {let shell = kits.appendingPathComponent("shell/tables/\(table).json")returnFileManager.default.fileExists(atPath: shell.path) ? shell : kits.appendingPathComponent("personal/tables/\(table).json") }/// Every table the object serves a personal database: the personal/// kit's listed tables (its kit.json) and the shell's, by id.staticfunc kitTables() throws -> [URL] {let listed = try JSONSerialization.jsonObject(with: Data(contentsOf: kits.appendingPathComponent("personal/kit.json"))) as? [String: Any]let personal = (listed?["tables"] as? [String] ?? []).map { kits.appendingPathComponent("personal/tables/\($0).json") }let shellDirectory = kits.appendingPathComponent("shell/tables")let shell = tryFileManager.default.contentsOfDirectory(atPath: shellDirectory.path).filter { $0.hasSuffix(".json") }.map { shellDirectory.appendingPathComponent($0) }let ids = Set(shell.map(\.lastPathComponent))return (personal.filter { !ids.contains($0.lastPathComponent) } + shell).sorted { $0.lastPathComponent < $1.lastPathComponent } }/// Rule (a): a read that finds nothing fails LOUDLY, naming the path and/// the lane, before anything is compared. A regex over an empty string/// passes, which is how a moved file turns a guard green.staticfunc mustRead(_ relativePath: String, ownedBy lane: String, file: StaticString = #filePath, line: UInt = #line) throws -> String {let url = repoRoot.appendingPathComponent(relativePath)let text = try? String(contentsOf: url, encoding: .utf8) XCTAssertNotNil( text,""" could not read \(url.path) — did the file move? \ That path is the \(lane) lane's; grep it repo-wide (\\_\\_tests\\_\\_ and \ every open worktree included) before changing this guard. """, file: file, line: line )let found = try XCTUnwrap(text, file: file, line: line) XCTAssertGreaterThan(found.count, 0, "\(url.path) is empty", file: file, line: line)return found }/// Every `.swift` file under the app's `Sources` and Loom's, as/// (module-relative path, text) — `CottonPaper/…` reads the same wherever/// its package is. A DIRECTORY walk, never a file list: a two-file list is/// green on the day a third file starts writing colours.staticfunc swiftSources() throws -> [(name: String, text: String)] {var found: [(String, String)] = []for root in [iosSources, loomSources] {let walker = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)whilelet url = walker?.nextObject() as? URL {guard url.pathExtension == "swift"else { continue }let text = tryString(contentsOf: url, encoding: .utf8) found.append((url.path.replacingOccurrences(of: root.path + "/", with: ""), text)) } }return found.sorted { $0.0 < $1.0 } }/// Comments stripped, so a guard reads the CODE. A rule written down in/// prose beside a rule being kept must not fail the rule.staticfunc withoutComments(_ text: String) -> String {var out = ""var iterator = text.startIndexvar inLine = falsevar inBlock = falsevar inString = falsewhile iterator < text.endIndex {let ch = text[iterator]let next = text.index(after: iterator)let peek = next < text.endIndex ? text[next] : nilif inLine {if ch == "\n" { inLine = false; out.append(ch) } } elseif inBlock {if ch == "*", peek == "/" { inBlock = false; iterator = next } } elseif inString {if ch == "\\" { iterator = next } elseif ch == "\"" { inString = false; out.append(ch) } else { out.append(ch) } } elseif ch == "/", peek == "/" { inLine = true iterator = next } elseif ch == "/", peek == "*" { inBlock = true iterator = next } else {if ch == "\"" { inString = true } out.append(ch) } iterator = text.index(after: iterator) }return out }/// Every `public struct <Name>…: … View` declared in a source.////// The gallery's `switch` proves every LISTED primitive is drawn; nothing/// proved every drawable thing is listed, so a new public view could ship/// with nobody ever having looked at it. This is the other direction.staticfunc publicViewNames(in text: String) -> [String] {let pattern = #"public\s+struct\s+(\w+)\s*(?:<[^>]*>)?\s*:[^{]*\bView\b"#guardlet regex = try? NSRegularExpression(pattern: pattern) else { return [] }let range = NSRange(text.startIndex..., in: text)return regex.matches(in: text, range: range).compactMap { match inRange(match.range(at: 1), in: text).map { String(text[$0]) } } }/// A file split at its TOP-LEVEL declarations — `(name, text)` per/// `struct` / `enum` / `class` / `extension` written at column 0, the text/// running to the next one.////// A line split rather than brace matching, and deliberately: every Swift/// file in this package writes its types at column 0 (swift-format keeps/// them there), and a brace counter has to understand string literals,/// interpolation and `#if` to be right. What this is used for — "is the/// rule kept somewhere in the type that breaks it" — does not need the/// exact span.staticfunc topLevelDeclarations(in text: String) -> [(name: String, text: String)] {let head = try? NSRegularExpression( pattern: #"^(?:@\w+\s+)*(?:public |package |internal |fileprivate |private |final |nonisolated |indirect )*(?:struct|enum|class|extension|actor|protocol) (\w+)"# )guardlet head else { return [] }var found: [(String, String)] = []var name: String?var body: [String] = []for line in text.components(separatedBy: "\n") {let range = NSRange(line.startIndex..., in: line)iflet match = head.firstMatch(in: line, range: range),let nameRange = Range(match.range(at: 1), in: line) {ifletopen = name { found.append((open, body.joined(separator: "\n"))) } name = String(line[nameRange]) body = [line] } elseif name != nil { body.append(line) } }ifletopen = name { found.append((open, body.joined(separator: "\n"))) }return found }staticfunc matches(_ pattern: String, in text: String, options: NSRegularExpression.Options = []) throws -> [String] {let regex = try NSRegularExpression(pattern: pattern, options: options)let range = NSRange(text.startIndex..., in: text)return regex.matches(in: text, range: range).compactMap { match inRange(match.range, in: text).map { String(text[$0]) } } }}finalclassSourceSweepTests: XCTestCase {/// RULE: A test reads the repository from SourceSweep.repoRoot: the checkout COTTON_UI_TESTS_REPO_ROOT names when the tests run from a copy (scripts/ui-tests-stub.sh), else the tree their own file sits in — never a path walked up from a copy.func testTheRootIsTheNamedCheckoutElseTheTreeThisFileSitsIn() {let copy = "/tmp/example-stub/Tests/Check/SourceSweep.swift" XCTAssertEqual(SourceSweep.root(named: "/example/checkout", file: copy).path, "/example/checkout")let inTree = "/example/checkout/apps/cotton/Tests/CottonUITests/SourceSweep.swift" XCTAssertEqual(SourceSweep.root(named: nil, file: inTree).path, "/example/checkout") XCTAssertEqual(SourceSweep.root(named: "", file: inTree).path, "/example/checkout") }func testCommentStrippingLeavesTheCode() {let stripped = SourceSweep.withoutComments(""" // #FFFFFF in a comment let kept = 1 /* #000000 */ let text = "a // b" """ ) XCTAssertFalse(stripped.contains("#FFFFFF")) XCTAssertFalse(stripped.contains("#000000")) XCTAssertTrue(stripped.contains("let kept = 1")) XCTAssertTrue(stripped.contains("a // b"), "a slash inside a string literal is not a comment") }}