import XCTest import SQLite3 import CottonKit @testable import CottonUI /// Run scripts/recopy-sim-fixture.py after seeding thirteen synthetic databases. /// The simulator uses the real phone FFI, not a scripted answer. @MainActor final class HouseholdHomeReplicaTests: XCTestCase { private var fixtures: URL { URL(fileURLWithPath: #filePath) .deletingLastPathComponent().deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent() .appendingPathComponent(".local/recopy-sim/fixtures") } private func stamp(_ file: URL) throws -> Int { var db: OpaquePointer? XCTAssertEqual(sqlite3_open_v2(file.path, &db, SQLITE_OPEN_READONLY, nil), SQLITE_OK) defer { sqlite3_close(db) } var statement: OpaquePointer? XCTAssertEqual(sqlite3_prepare_v2(db, "PRAGMA user_version", -1, &statement, nil), SQLITE_OK) defer { sqlite3_finalize(statement) } XCTAssertEqual(sqlite3_step(statement), SQLITE_ROW) return Int(sqlite3_column_int(statement, 0)) } private func exercise(_ state: String) async throws { let source = fixtures.appendingPathComponent(state) guard FileManager.default.fileExists(atPath: source.path) else { throw XCTSkip("Prepare the synthetic household with scripts/recopy-sim-fixture.py") } let manifest = try JSONSerialization.jsonObject(with: Data(contentsOf: fixtures.appendingPathComponent("manifest.json"))) as! [String: Any] let personal = manifest["personal"] as! String let projects = manifest["projects"] as! [String] let container = FileManager.default.temporaryDirectory.appendingPathComponent("household-home-\(UUID().uuidString)") try FileManager.default.copyItem(at: source, to: container) defer { try? FileManager.default.removeItem(at: container) } func file(_ id: String) -> URL { container.appendingPathComponent("client/\(id)/replica.db") } XCTAssertEqual(try stamp(file(personal)), 135) for project in projects { if state == "older" { XCTAssertEqual(try stamp(file(project)), 134) } else { XCTAssertFalse(FileManager.default.fileExists(atPath: file(project).path)) } } let core = try CottonRuntime.open(CottonConfig(containerPath: container.path, appVersion: "1.0.0-test")) let databases = DatabasesModel(source: CoreDatabases(core: core)) await databases.refresh() let home = HomeModel(core: core, toasts: ToastCenter()) await home.load() let raw = try await core.callRaw(CottonMethod.shellToday, requestJSON: "{}") let debug = try await core.callRaw("diagnostics.debug", requestJSON: "{}") let evidence = "\(state): personal=135 projects=\(state == "older" ? "134" : "absent") shell.today=\(raw) diagnostics.debug=\(debug)" let attachment = XCTAttachment(string: evidence) attachment.lifetime = .keepAlways add(attachment) print("RECOPY-SIM \(evidence)") XCTAssertNil(home.answer?.failed, raw) XCTAssertTrue(home.isArranged, raw) XCTAssertFalse(home.homeTiles.tiles.isEmpty, "personal tiles must remain reachable: \(raw)") let start = Calendar.current.startOfDay(for: Date()) let end = try XCTUnwrap(Calendar.current.date(byAdding: .day, value: 1, to: start)) let formatter = ISO8601DateFormatter() let day = try await core.callJSON("read.day", DayRead( database: "all", from: formatter.string(from: start), to: formatter.string(from: end))) XCTAssertTrue(day.list("skippedDatabases").isEmpty, "\(day)") if state == "older" { // Opening the held list and Home must move all arrived copies. for project in projects { XCTAssertEqual(try stamp(file(project)), 135) let scoped = DatabaseScopedCore(underlying: core, database: project) let projectHome = HomeModel(core: scoped, toasts: ToastCenter()) await projectHome.load() XCTAssertNil(projectHome.answer?.failed, "Home must read the moved copy of \(project)") XCTAssertTrue(projectHome.isArranged) } } else { XCTAssertEqual(Set(databases.held.filter { $0.arrival != nil }.map(\.databaseId)), Set(projects)) XCTAssertNil(home.answer?.arriving, "Personal's Home speaks of Personal only") XCTAssertNil(home.notice("arriving"), "and no notice of another database's copy") XCTAssertEqual(Set(day.list("arrivingDatabases").compactMap { $0.text("databaseId") }), Set(projects)) // A cross read must never create an empty file for an arriving copy. for project in projects { XCTAssertFalse(FileManager.default.fileExists(atPath: file(project).path)) } } await core.close() } private struct DayRead: Encodable { let database: String; let from: String; let to: String } /// RULE: An arrived phone copy above the fresh-start floor moves in place before Home reads; one old project cannot hide the personal tiles or cause another whole-file fetch. func testOlderProjectCopiesMoveBeforeHomeReads() async throws { try await exercise("older") } /// RULE: Missing project copies are arriving, not unreadable; cross reads keep the personal tiles reachable without inventing empty databases. func testAbsentProjectCopiesDoNotHidePersonalHome() async throws { try await exercise("absent") } }