// 4g's half of the boundary contract — the twenty-seven reads behind people's// traffic and money.//// A separate file from `BoundaryContractTests` and `BoundaryContract4dTests`// for the reason those two give about each other: several lanes are landing at// once, and a lane that appends to the middle of somebody else's file makes a// merge conflict out of what is really independent additions.//// The rule is the same one stated there — **where this app and// `crates/cotton-ffi/src/phone/reads.rs` disagree, the crate// wins** — and so is the by-path discipline AGENTS.md sets for a guard that// reads another lane's file: the read fails LOUDLY if it finds nothing, the// owning lane is named here, and the path is grepped repo-wide before it moves.//// **What this file checks that a name-only check cannot.** `READS` declares a// name AND the screens it answers, and the two are asserted together: a read// that answered the right name for the wrong screen would pass a `contains`// over the whole file and then draw the wrong page. So the table is split into// its `ScreenRead` blocks and each method is matched against the block that// bears its name, never against the file.importCottonKitimportCottonUIimport XCTestfinalclassBoundaryContract4gTests: XCTestCase {privatestaticlet lane = "Rust FFI (the phone's reads table)"privatestaticlet readsPath = "crates/cotton-ffi/src/phone/reads.rs"privatestaticlet methodsPath = "crates/cotton-ffi/src/methods.rs"/// Every read this lane calls, and a screen it must answer.////// One row per METHOD, and one method per route.privatestaticlet reads: [(method: String, screen: String)] = [// ── email ──────────────────────────────────────────────────────── (CottonMethod.readEmail, "/email"),// ── pictures and film ──────────────────────────────────────────── (CottonMethod.readPhotos, "/photos"),// ── chat ───────────────────────────────────────────────────────── (CottonMethod.readThreads, "/messages"),// ── disk ───────────────────────────────────────────────────────── (CottonMethod.readStorage, "/storage"), ]/// The routes this lane draws that are answered by a WRITTEN LINE rather/// than by a read, and the words the crate uses for each.////// Both are permanent in the sense that matters here: neither will get a/// read in this sub-step, and a screen that quietly drew nothing would be/// indistinguishable from one whose read failed. Each draws a page that/// NAMES what it waits on.privatestaticlet writtenLines: [(route: String, owes: String)] = [// EMPTY, and the test below is now the one that matters: the list is// supposed to shrink to nothing and it has.//// `/call/[id]` WAS the last line, owed nothing because live calling was// paused — and at schema 5 it stopped being paused and started being// deleted, so the route went and the debt closed by subtraction.// `/messages/import` was the one before it, until lane N landed// `import.whatsappExport`: the screen runs that job and shows its// answer, so it is on `READ_LESS`. ]privatefunc readsTable() throws -> String {let text = trySourceSweep.mustRead(BoundaryContract4gTests.readsPath, ownedBy: BoundaryContract4gTests.lane )// Anti-vacuity before any comparison: a `contains` over an empty read// is how a moved file turns a guard green. XCTAssertTrue(text.contains("pub static READS"), "reads.rs did not read as itself") XCTAssertTrue(text.contains("static DEFERRED"), "reads.rs no longer declares DEFERRED")return text }/// The table's `ScreenRead` blocks, as `name -> the screens it declares`.////// Parsed rather than grepped, so a method can be checked against ITS OWN/// block. A `contains` over the whole file would pass for a read that named/// the right screen under somebody else's name, which is precisely the/// mistake worth catching: the two halves of a `ScreenRead` are what say/// which page a method draws.////// The screens live under `audience: Audience::Screens(&[…])` since 4i,/// which also added `Audience::Extension("…")` for a read an app EXTENSION/// draws rather than a route. An extension block has no screens and is/// skipped ON PURPOSE — and a block that is NEITHER shape fails the sweep/// rather than being skipped, because the version of this parser that/// `continue`d past an unrecognised block is how the merge that renamed/// `screens:` left the guard reading almost nothing.privatefunc blocks(in table: String) throws -> [String: [String]] {// From the TABLE, not from the file: `pub struct ScreenRead {` matches// the same separator as an entry does, and a parser that failed loudly// on a malformed block failed on the struct declaration instead. Every// block after this point is a table entry, so an unrecognised one is a// real defect rather than the type it is made of.guardlet tableAt = table.range(of: "pub static READS") else {throwSweepFailure("reads.rs no longer declares READS") }let entries = String(table[tableAt.upperBound ..< table.endIndex])var found: [String: [String]] = [:]for chunk in entries.components(separatedBy: "ScreenRead {").dropFirst() {guardlet head = chunk.range(of: "source:") else {throwSweepFailure("a ScreenRead block with no `source:` — the table changed shape") }let declaration = String(chunk[chunk.startIndex ..< head.lowerBound])guardlet nameRange = declaration.range(of: "name: \""),let nameEnd = declaration.range( of: "\"", range: nameRange.upperBound ..< declaration.endIndex )else {throwSweepFailure("a ScreenRead block with no `name:` — the table changed shape") }let name = String(declaration[nameRange.upperBound ..< nameEnd.lowerBound])if declaration.contains("Audience::Extension(") { continue }guardlet screensAt = declaration.range(of: "Audience::Screens(") else {throwSweepFailure("read.\(name) declares neither Audience::Screens nor Audience::Extension — " + "either the crate renamed the field again, in which case this parser " + "follows, or the block is malformed" ) }let screens = String(declaration[screensAt.upperBound ..< declaration.endIndex]) .components(separatedBy: "\"") .enumerated()// Odd indices are what sat BETWEEN a pair of quotes. .filter { $0.offset % 2 == 1 } .map(\.element) found[name] = screens }return found }/// A by-path sweep that could not read what it came for.privatestructSweepFailure: Error, CustomStringConvertible {let description: Stringinit(_ description: String) { self.description = description } }func testEveryReadThisLaneCallsIsOneTheCrateDeclaresForThatScreen() throws {let table = try readsTable()let declared = try blocks(in: table) XCTAssertFalse(declared.isEmpty, "the table parsed as nothing")for (method, screen) inBoundaryContract4gTests.reads {let name = String(method.dropFirst("read.".count))guardlet screens = declared[name] else {return XCTFail(""" \(method) is declared in this lane's Boundary and `READS` does \ not name it. Either the crate renamed it — in which case this \ app follows, because the crate wins — or a screen is asking \ for something nobody answers, which is an unknown_method at \ runtime. """ ) } XCTAssertTrue( screens.contains(screen),""" \(method) should answer \(screen); the crate says it answers \ \(screens). A read that draws the wrong page is worse than one \ that does not answer at all, because nothing says so. """ ) } }func testTheTwoMediaMethodsAreOnesThePhoneActuallyHas() throws {// `read.mediaPath` is a READ and rides the table; `media.ensure` is a// method of its own and rides `CLIENT_METHODS`. Every picture, poster// and film in this lane goes through the pair, so a rename below the// boundary must not reach the screens as a silent absence.let table = try readsTable() XCTAssertTrue( table.contains("name: \"mediaPath\""),"\(CottonMethod.readMediaPath) is called by every media screen and READS does not name it" )let methods = trySourceSweep.mustRead(BoundaryContract4gTests.methodsPath, ownedBy: BoundaryContract4gTests.lane ) XCTAssertTrue(methods.contains("CLIENT_METHODS"), "methods.rs did not read as itself") XCTAssertTrue( methods.contains("\"\(CottonMethod.mediaEnsure)\""),"\(CottonMethod.mediaEnsure) is not a method this phone build has" ) }/// One Rust function's body, from its signature to its matching brace.////// A window bounded by the BRACES rather than by a character count, so a/// guard over it cannot be satisfied by something written after the/// function ends. Braces inside string literals would break the count and/// there are none in the three bodies this reads; a `{` that never closes/// fails rather than returning the rest of the file.privatefunc functionBody( of source: String, startingAt: String.Index ) throws -> String {guardletopen = source[startingAt...].firstIndex(of: "{") else {throwSweepFailure("no body opens after that signature") }var depth = 0var at = openwhile at < source.endIndex {if source[at] == "{" { depth += 1 }if source[at] == "}" { depth -= 1if depth == 0 { returnString(source[open ... at]) } } at = source.index(after: at) }throwSweepFailure("a body that never closes — traffic.rs did not read as Rust") }}