field_ios

In-the-field app for Radroots on iOS
git clone https://radroots.dev/git/field_ios.git
Log | Files | Refs | README | LICENSE

TeraRemoteQualificationUITests.swift (68388B)


      1 import CryptoKit
      2 import XCTest
      3 
      4 final class TeraRemoteQualificationUITests: XCTestCase {
      5   private static let receiptName = "radroots-remote-qualification-bootstrap.json"
      6 
      7   @MainActor
      8   func testBootstrapIdentityWithoutInteractiveAuthentication() throws {
      9     let configuration = try QualificationConfiguration.environment()
     10     let app = launchToRoot(configuration)
     11     let publicKey = try readPublicKey(app)
     12     try exerciseSettingsIdentityOverscroll(app, expectedPublicKey: publicKey)
     13     try writeBootstrapReceipt(configuration: configuration, publicKey: publicKey)
     14 
     15     XCUIDevice.shared.press(.home)
     16     app.activate()
     17     XCTAssertTrue(app.tabBars.firstMatch.waitForExistence(timeout: 10))
     18 
     19     app.terminate()
     20     app.launch()
     21     reachRoot(app)
     22     XCTAssertTrue(app.tabBars.firstMatch.waitForExistence(timeout: 20))
     23     XCTAssertEqual(try readPublicKey(app), publicKey)
     24   }
     25 
     26   @MainActor
     27   func testStrictPublicEndpointRejectsPrivateAddress() throws {
     28     let environment = try QualificationConfiguration.environment()
     29     let configuration = QualificationConfiguration(
     30       runID: environment.runID,
     31       relayURLs: [],
     32       blossomOrigins: ["https://127.0.0.1"]
     33     )
     34     let app = XCUIApplication()
     35     app.launchEnvironment = configuration.launchEnvironment
     36     app.launch()
     37 
     38     let failureCode = app.descendants(matching: .any)["radroots.runtime.failure_code"]
     39     for _ in 0 ..< 8 where !failureCode.exists {
     40       for identifier in [
     41         "radroots.identity.create",
     42         "radroots.identity.unlock",
     43         "radroots.configuration.reconfigure",
     44         "radroots.identity.recover",
     45       ] {
     46         let action = app.descendants(matching: .any)[identifier]
     47         if action.exists, action.isHittable {
     48           action.tap()
     49           break
     50         }
     51       }
     52       _ = failureCode.waitForExistence(timeout: 4)
     53     }
     54     XCTAssertEqual(
     55       failureCode.label,
     56       "Error code runtime_failed",
     57       "A private Blossom endpoint did not expose the typed fail-closed result; "
     58         + "failure_code.label=\(failureCode.exists ? failureCode.label : "missing")"
     59     )
     60     XCTAssertFalse(app.tabBars.firstMatch.exists)
     61   }
     62 
     63   @MainActor
     64   func testLocalSocialFiveFlowScenario() throws {
     65     let configuration = try QualificationConfiguration.environment()
     66     let control = try XCTUnwrap(configuration.fixtureControl)
     67     try? FileManager.default.removeItem(atPath: control)
     68     var app = launchToRoot(configuration)
     69     let marker = "\(configuration.runID)-photo"
     70 
     71     guard preparePhotoUpdate(app, marker: marker) != nil else { return }
     72     let save = app.buttons["radroots.add.save"]
     73     scrollTo(app, element: save)
     74     guard save.waitForExistence(timeout: 10),
     75       waitUntilHittable(save, timeout: 10),
     76       isUnobscured(save, above: app.tabBars.firstMatch)
     77     else {
     78       return XCTFail("The prepared Photo update could not be saved through the visible UI")
     79     }
     80     let addRoot = app.descendants(matching: .any)["radroots.add.root"]
     81     save.tap()
     82     scrollAddFormToTop(app)
     83     let saved = app.staticTexts.matching(identifier: "radroots.add.status").firstMatch
     84     guard waitForLabel(saved, label: "Draft saved on this device.", timeout: 60) else {
     85       return XCTFail("The visible Add status did not confirm the durable draft save")
     86     }
     87     let saveSettled = NSPredicate { _, _ in
     88       addRoot.value as? String == "Ready"
     89     }
     90     let settleExpectation = XCTNSPredicateExpectation(predicate: saveSettled, object: app)
     91     guard XCTWaiter.wait(for: [settleExpectation], timeout: 60) == .completed else {
     92       return XCTFail("The visible Save draft action did not finish durable persistence")
     93     }
     94     assertSavedPhotoEditing(app)
     95     app.terminate()
     96 
     97     XCTAssertTrue(FileManager.default.createFile(atPath: control, contents: Data()))
     98     app = launchToRoot(configuration)
     99     guard openAdd(app) != nil, openDrafts(app) else {
    100       return XCTFail("The persisted media draft was unavailable after relaunch")
    101     }
    102     let reopen = app.buttons["Reopen"].firstMatch
    103     XCTAssertTrue(reopen.waitForExistence(timeout: 20))
    104     reopen.tap()
    105     guard let retrySubmit = readySubmit(app),
    106       let retryValue = submitAndWait(app, submit: retrySubmit)
    107     else { return }
    108     XCTAssertTrue(
    109       !retryValue.contains("Error code") && finishOriginalPublication(app, submit: retrySubmit),
    110       "The preserved media draft did not publish after retry; submit.value=\(retryValue)"
    111     )
    112 
    113     let markers = [
    114       "\(configuration.runID)-update",
    115       "\(configuration.runID)-ask",
    116       "\(configuration.runID)-event",
    117       "\(configuration.runID)-food",
    118     ]
    119     try publishTextFlow(app, type: "Update", marker: markers[0])
    120     try publishTextFlow(app, type: "Ask", marker: markers[1])
    121     try publishEvent(app, marker: markers[2])
    122     try publishFood(app, marker: markers[3])
    123 
    124     let expected = [marker] + markers
    125     try assertTodayContains(app, markers: expected)
    126     app.terminate()
    127     app = launchToRoot(configuration)
    128     try assertTodayContains(app, markers: expected)
    129 
    130     guard openAdd(app) != nil, openDrafts(app) else {
    131       return XCTFail("The durable outbox was unavailable after the final relaunch")
    132     }
    133     assertDraftOutboxContainsAtLeast(app, count: expected.count)
    134     app.buttons["Done"].tap()
    135   }
    136 
    137   @MainActor
    138   func testLocalSocialAccessibilitySemantics() throws {
    139     let configuration = try QualificationConfiguration.environment()
    140     _ = TeraAccessibilitySettings.setSystemReduceMotion(true, restoring: self)
    141     let app = launchToRoot(
    142       configuration,
    143       launchArguments: [
    144         "-AppleLanguages", "(en)",
    145         "-AppleLocale", "en_US",
    146       ]
    147     )
    148 
    149     XCTAssertEqual(app.tabBars.firstMatch.buttons.count, 2)
    150     XCTAssertGreaterThan(app.staticTexts["Nothing here yet"].frame.height, 36)
    151     XCTAssertGreaterThan(
    152       app.staticTexts["Pull to refresh or add the first update to this local network."].frame
    153         .height,
    154       44
    155     )
    156     app.tabBars.buttons["Today"].tap()
    157     try performLocalSocialAccessibilityAudit(app)
    158 
    159     for type in ["Update", "Photo update", "Ask", "Event", "Food availability"] {
    160       try beginDraft(app, type: type)
    161       assertProgressiveDisclosure(app, type: type)
    162       scrollTo(app, element: app.buttons["radroots.add.submit"])
    163       try performLocalSocialAccessibilityAudit(app)
    164     }
    165   }
    166 
    167   @MainActor
    168   func testLocalSocialDeterministicPersonas() throws {
    169     let environment = try QualificationConfiguration.environment()
    170     let control = try XCTUnwrap(environment.fixtureControl)
    171     let suite = try loadPersonaSuite()
    172     XCTAssertEqual(suite.locale, "en_US")
    173     XCTAssertEqual(suite.personas.map(\.alias), ["P01", "P02", "P03", "P04", "P05"])
    174 
    175     var identityDigests = Set<String>()
    176     var observations = [String: PersonaAttemptObservation]()
    177     for persona in suite.personas {
    178       try activateFixture(persona: persona.alias, at: control)
    179       let configuration = environment.forPersona(persona.alias)
    180       var networkBefore = try readFixtureNetwork(configuration)
    181       var app = launchPersona(configuration)
    182       let publicKey = try readPublicKey(app)
    183       let identityDigest = SHA256.hash(data: Data(publicKey.utf8))
    184         .map { String(format: "%02x", $0) }.joined()
    185       XCTAssertTrue(identityDigests.insert(identityDigest).inserted)
    186 
    187       for attempt in persona.attempts {
    188         let interaction: PersonaInteractionObservation
    189         switch attempt.expectedFailure {
    190         case "validation_recovery":
    191           interaction = try publishWithValidationRecovery(app, attempt: attempt)
    192         case "transport_retry_relaunch":
    193           let retry = try publishWithTransportRetry(
    194             app,
    195             configuration: configuration,
    196             attempt: attempt
    197           )
    198           app = retry.app
    199           interaction = retry.observation
    200         case "none":
    201           interaction = try publishPersonaAttempt(
    202             app,
    203             attempt: attempt,
    204             interactionProfile: persona.interactionProfile
    205           )
    206         default:
    207           throw QualificationError.invalidPersonaFixture
    208         }
    209         try assertTodayContains(app, markers: [attempt.marker])
    210         let networkAfter = try readFixtureNetwork(configuration)
    211         observations[attempt.id] = try PersonaAttemptObservation(
    212           interaction: interaction,
    213           network: networkAfter.delta(from: networkBefore),
    214           todayProjectionVerified: true,
    215           retentionVerified: false
    216         )
    217         networkBefore = networkAfter
    218       }
    219 
    220       let markers = persona.attempts.map(\.marker)
    221       app.terminate()
    222       app = launchPersona(configuration)
    223       try assertTodayContains(app, markers: markers)
    224       XCTAssertEqual(try readPublicKey(app), publicKey)
    225       for attempt in persona.attempts {
    226         let observation = try XCTUnwrap(observations[attempt.id])
    227         try writePersonaAttemptAttachment(
    228           configuration: configuration,
    229           personaAlias: persona.alias,
    230           attempt: attempt,
    231           identityDigest: identityDigest,
    232           observation: observation.confirmingRetention()
    233         )
    234       }
    235       app.terminate()
    236     }
    237     XCTAssertEqual(identityDigests.count, 5)
    238   }
    239 
    240   @MainActor
    241   func testRemoteBlossomUploadAndRecovery() throws {
    242     let configuration = try QualificationConfiguration.environment()
    243     let app = launchToRoot(configuration)
    244     let marker = "Tera remote qualification \(configuration.runID)"
    245 
    246     guard let submit = preparePhotoUpdate(app, marker: marker),
    247       let terminalSubmitValue = submitAndWait(app, submit: submit)
    248     else { return }
    249     guard !terminalSubmitValue.contains("Error code") else {
    250       return XCTFail("The Add submission failed locally; submit.value=\(terminalSubmitValue)")
    251     }
    252 
    253     guard openDrafts(app) else {
    254       return XCTFail("The Drafts sheet did not open after the upload attempt")
    255     }
    256     let mediaStatus = app.descendants(matching: .any).matching(
    257       NSPredicate(format: "identifier BEGINSWITH 'radroots.add.draft.media_status.'")
    258     ).firstMatch
    259     guard mediaStatus.waitForExistence(timeout: 20) else {
    260       app.buttons["Done"].tap()
    261       let evidence = readBlossomFailureEvidence(app)
    262       XCTFail("Draft media status was unavailable after upload; \(evidence)")
    263       return
    264     }
    265     let mediaStatusLabel = mediaStatus.label
    266     guard mediaStatusLabel.contains("1 of 1 photos verified") else {
    267       app.buttons["Done"].tap()
    268       let evidence = readBlossomFailureEvidence(app)
    269       XCTFail(
    270         "Remote Blossom upload was not verified; media=\(mediaStatusLabel); \(evidence)"
    271       )
    272       return
    273     }
    274     app.buttons["Done"].tap()
    275 
    276     XCUIDevice.shared.press(.home)
    277     app.activate()
    278     XCTAssertTrue(app.tabBars.firstMatch.waitForExistence(timeout: 10))
    279 
    280     app.terminate()
    281     app.launch()
    282     reachRoot(app)
    283     guard openAdd(app) != nil else {
    284       return XCTFail("The Add bottom tab did not recover after relaunch")
    285     }
    286     app.buttons["radroots.add.drafts"].tap()
    287     XCTAssertTrue(
    288       app.descendants(matching: .any).matching(
    289         NSPredicate(format: "label CONTAINS '1 of 1 photos verified'")
    290       ).firstMatch.waitForExistence(timeout: 20)
    291     )
    292     app.buttons["Done"].tap()
    293 
    294     if !configuration.relayURLs.isEmpty {
    295       app.tabBars.buttons["Today"].tap()
    296       let published = app.descendants(matching: .any).matching(
    297         NSPredicate(format: "label CONTAINS %@", marker)
    298       ).firstMatch
    299       XCTAssertTrue(published.waitForExistence(timeout: 30))
    300     }
    301   }
    302 
    303   @MainActor
    304   func testRemoteBlossomUnavailablePersistsDraft() throws {
    305     let configuration = try QualificationConfiguration.environment()
    306     let app = launchToRoot(configuration)
    307     let marker = "Tera unavailable qualification \(configuration.runID)"
    308 
    309     guard let submit = preparePhotoUpdate(app, marker: marker),
    310       let terminalSubmitValue = submitAndWait(app, submit: submit)
    311     else { return }
    312     XCTAssertTrue(
    313       terminalSubmitValue.contains("Error code"),
    314       "An unavailable Blossom endpoint did not produce a typed failure; "
    315         + "submit.value=\(terminalSubmitValue)"
    316     )
    317     XCTAssertTrue(assertUnverifiedDraft(app))
    318 
    319     app.terminate()
    320     app.launch()
    321     reachRoot(app)
    322     guard openAdd(app) != nil else {
    323       return XCTFail("The Add bottom tab did not recover after unavailable relaunch")
    324     }
    325     XCTAssertTrue(assertUnverifiedDraft(app))
    326   }
    327 
    328   @MainActor
    329   func testRemoteBlossomRetriesPersistedDraft() throws {
    330     let configuration = try QualificationConfiguration.environment()
    331     let app = launchToRoot(configuration)
    332     guard openAdd(app) != nil else {
    333       return XCTFail("The Add bottom tab did not present the Add surface")
    334     }
    335     guard openDrafts(app) else {
    336       return XCTFail("The Drafts sheet did not open for retry")
    337     }
    338     let unverified = app.descendants(matching: .any).matching(
    339       NSPredicate(format: "label CONTAINS '0 of 1 photos verified'")
    340     ).firstMatch
    341     XCTAssertTrue(unverified.waitForExistence(timeout: 20))
    342     let reopen = app.buttons["Reopen"].firstMatch
    343     XCTAssertTrue(reopen.waitForExistence(timeout: 10))
    344     reopen.tap()
    345 
    346     guard let submit = readySubmit(app),
    347       let terminalSubmitValue = submitAndWait(app, submit: submit)
    348     else { return }
    349     guard !terminalSubmitValue.contains("Error code") else {
    350       return XCTFail("The persisted Blossom retry failed; submit.value=\(terminalSubmitValue)")
    351     }
    352     guard openDrafts(app) else {
    353       return XCTFail("The Drafts sheet did not open after retry")
    354     }
    355     XCTAssertTrue(
    356       app.descendants(matching: .any).matching(
    357         NSPredicate(format: "label CONTAINS '1 of 1 photos verified'")
    358       ).firstMatch.waitForExistence(timeout: 20)
    359     )
    360     app.buttons["Done"].tap()
    361 
    362     app.terminate()
    363     app.launch()
    364     reachRoot(app)
    365     XCTAssertTrue(app.tabBars.firstMatch.waitForExistence(timeout: 20))
    366   }
    367 
    368   @MainActor
    369   func testLocalCancellationPersistsAfterVerifiedUpload() throws {
    370     let configuration = try QualificationConfiguration.environment()
    371     let app = launchToRoot(configuration)
    372     guard openAdd(app) != nil else {
    373       return XCTFail("The Add bottom tab did not present the Add surface")
    374     }
    375     guard openDrafts(app) else {
    376       return XCTFail("The Drafts sheet did not open for cancellation")
    377     }
    378 
    379     let cancel = app.buttons["Cancel"].firstMatch
    380     XCTAssertTrue(cancel.waitForExistence(timeout: 20))
    381     cancel.tap()
    382     let cancelled = app.staticTexts.matching(
    383       NSPredicate(format: "label == 'Cancelled'")
    384     ).firstMatch
    385     XCTAssertTrue(cancelled.waitForExistence(timeout: 20))
    386     app.buttons["Done"].tap()
    387 
    388     app.terminate()
    389     app.launch()
    390     reachRoot(app)
    391     guard openAdd(app) != nil else {
    392       return XCTFail("The Add bottom tab did not recover after cancellation")
    393     }
    394     guard openDrafts(app) else {
    395       return XCTFail("The Drafts sheet did not reopen after cancellation")
    396     }
    397     let persistedCancelled = app.staticTexts.matching(
    398       NSPredicate(format: "label == 'Cancelled'")
    399     ).firstMatch
    400     XCTAssertTrue(persistedCancelled.waitForExistence(timeout: 20))
    401     app.buttons["Done"].tap()
    402   }
    403 
    404   @MainActor
    405   func testManualDeviceLockAndProtectedDataRecovery() throws {
    406     let configuration = try QualificationConfiguration.environment()
    407     let app = launchToRoot(configuration)
    408     XCTAssertTrue(app.tabBars.firstMatch.waitForExistence(timeout: 20))
    409 
    410     XCUIDevice.shared.press(.home)
    411     Thread.sleep(forTimeInterval: 60)
    412 
    413     for _ in 0 ..< 24 {
    414       app.activate()
    415       if app.tabBars.firstMatch.waitForExistence(timeout: 5) {
    416         return
    417       }
    418     }
    419     XCTFail("Tera did not recover after the physical device was unlocked")
    420   }
    421 
    422   @MainActor
    423   private func launchToRoot(
    424     _ configuration: QualificationConfiguration,
    425     launchArguments: [String] = []
    426   ) -> XCUIApplication {
    427     let app = XCUIApplication()
    428     app.launchEnvironment = configuration.launchEnvironment
    429     app.launchArguments = launchArguments
    430     app.launch()
    431     reachRoot(app)
    432     return app
    433   }
    434 
    435   @MainActor
    436   private func launchPersona(_ configuration: QualificationConfiguration) -> XCUIApplication {
    437     launchToRoot(
    438       configuration,
    439       launchArguments: [
    440         "-AppleLanguages", "(en)",
    441         "-AppleLocale", "en_US",
    442         "-UIAccessibilityReduceMotionEnabled", "YES",
    443       ]
    444     )
    445   }
    446 
    447   @MainActor
    448   private func performLocalSocialAccessibilityAudit(
    449     _ app: XCUIApplication,
    450     includeContrast: Bool = true
    451   ) throws {
    452     let findings = try TeraAccessibilityAudit(test: self).run(app, includeContrast: includeContrast)
    453     TeraAccessibilityAudit.assertNoFindings(findings)
    454   }
    455 
    456   @MainActor
    457   private func assertProgressiveDisclosure(_ app: XCUIApplication, type: String) {
    458     scrollAddFormToTop(app)
    459     defer { scrollAddFormToTop(app) }
    460     let expected = expectedAddFields[type] ?? []
    461     for identifier in allAddFields {
    462       let element = app.descendants(matching: .any)[identifier]
    463       if expected.contains(identifier) {
    464         scrollTo(app, element: element)
    465         XCTAssertTrue(
    466           element.waitForExistence(timeout: 10),
    467           "Missing progressive-disclosure field for \(type): \(identifier)"
    468         )
    469         XCTAssertEqual(
    470           element.label,
    471           expectedAddFieldLabel(identifier, type: type),
    472           "Unexpected accessibility label: \(identifier)"
    473         )
    474       } else {
    475         XCTAssertFalse(
    476           element.exists,
    477           "Unexpected progressive-disclosure field for \(type): \(identifier)"
    478         )
    479       }
    480     }
    481     let expectsMedia = type != "Update"
    482     let mediaLibrary = app.buttons["radroots.add.media.library"]
    483     let mediaCamera = app.buttons["radroots.add.media.camera"]
    484     if expectsMedia {
    485       scrollTo(app, element: mediaLibrary)
    486       XCTAssertTrue(mediaLibrary.waitForExistence(timeout: 10))
    487       XCTAssertTrue(mediaCamera.waitForExistence(timeout: 10))
    488       XCTAssertEqual(mediaLibrary.label, "Photo Library")
    489       XCTAssertEqual(mediaCamera.label, "Camera")
    490     } else {
    491       XCTAssertFalse(mediaLibrary.exists, "Unexpected media-library disclosure for \(type)")
    492       XCTAssertFalse(mediaCamera.exists, "Unexpected camera disclosure for \(type)")
    493     }
    494   }
    495 
    496   private func expectedAddFieldLabel(_ identifier: String, type: String) -> String {
    497     switch identifier {
    498     case "radroots.add.content":
    499       switch type {
    500       case "Update":
    501         "What’s happening locally?"
    502       case "Photo update":
    503         "What should neighbors know?"
    504       case "Ask":
    505         "What do you need or want to know?"
    506       case "Event":
    507         "Event details (optional)"
    508       case "Food availability":
    509         "Details"
    510       default:
    511         preconditionFailure("Unrecognized Add type: \(type)")
    512       }
    513     case "radroots.add.title":
    514       type == "Food availability" ? "Food" : "Title"
    515     case "radroots.add.summary":
    516       "Short summary"
    517     case "radroots.add.location":
    518       type == "Food availability" ? "Public location" : "Public location (optional)"
    519     case "radroots.add.event_timing":
    520       "When, Specific time"
    521     case "radroots.add.event.start":
    522       "Starts"
    523     case "radroots.add.event.end":
    524       "Ends"
    525     case "radroots.add.price":
    526       "Price"
    527     case "radroots.add.currency":
    528       "Currency"
    529     case "radroots.add.unit":
    530       "Unit, Choose a unit"
    531     case "radroots.add.quantity":
    532       "Quantity available (optional)"
    533     default:
    534       preconditionFailure("Unrecognized Add field identifier: \(identifier)")
    535     }
    536   }
    537 
    538   private var allAddFields: [String] {
    539     [
    540       "radroots.add.content",
    541       "radroots.add.title",
    542       "radroots.add.summary",
    543       "radroots.add.location",
    544       "radroots.add.event_timing",
    545       "radroots.add.event.start",
    546       "radroots.add.event.end",
    547       "radroots.add.price",
    548       "radroots.add.currency",
    549       "radroots.add.unit",
    550       "radroots.add.quantity",
    551     ]
    552   }
    553 
    554   private var expectedAddFields: [String: Set<String>] {
    555     [
    556       "Update": ["radroots.add.content"],
    557       "Photo update": ["radroots.add.content"],
    558       "Ask": ["radroots.add.content"],
    559       "Event": [
    560         "radroots.add.content",
    561         "radroots.add.title",
    562         "radroots.add.location",
    563         "radroots.add.event_timing",
    564         "radroots.add.event.start",
    565         "radroots.add.event.end",
    566       ],
    567       "Food availability": [
    568         "radroots.add.content",
    569         "radroots.add.title",
    570         "radroots.add.summary",
    571         "radroots.add.location",
    572         "radroots.add.price",
    573         "radroots.add.currency",
    574         "radroots.add.unit",
    575         "radroots.add.quantity",
    576       ],
    577     ]
    578   }
    579 
    580   @MainActor
    581   private func readPublicKey(_ app: XCUIApplication) throws -> String {
    582     app.tabBars.buttons["Today"].tap()
    583     let account = app.descendants(matching: .any)["radroots.support.account"]
    584     XCTAssertTrue(account.waitForExistence(timeout: 10))
    585     account.tap()
    586 
    587     let meSheet = app.descendants(matching: .any)["radroots.support.me.sheet"]
    588     guard meSheet.waitForExistence(timeout: 10) else {
    589       throw QualificationError.missingProductSurface
    590     }
    591     let publicKey = app.descendants(matching: .any)[
    592       "radroots.settings.identity.public_key"
    593     ]
    594     guard openSettingsFromMe(app, meSheet: meSheet) else {
    595       XCTFail("Settings was unavailable through the visible Me sheet")
    596       throw QualificationError.missingProductSurface
    597     }
    598     guard revealSettingsPublicKey(app, publicKey: publicKey),
    599       publicKey.waitForExistence(timeout: 10)
    600     else {
    601       XCTFail("Settings did not present the native identity public key")
    602       throw QualificationError.missingProductSurface
    603     }
    604     guard let value = publicKey.value as? String,
    605       value.range(of: "^[0-9a-f]{64}$", options: .regularExpression) != nil
    606     else {
    607       throw QualificationError.invalidPublicKey
    608     }
    609     let back = app.navigationBars.buttons["Me"].firstMatch
    610     XCTAssertTrue(back.waitForExistence(timeout: 10))
    611     back.tap()
    612     let done = app.navigationBars.buttons["Done"].firstMatch
    613     XCTAssertTrue(done.waitForExistence(timeout: 10))
    614     done.tap()
    615     XCTAssertTrue(
    616       app.descendants(matching: .any)["radroots.support.me.sheet"]
    617         .waitForNonExistence(timeout: 10)
    618     )
    619     return value
    620   }
    621 
    622   @MainActor
    623   private func readBlossomFailureEvidence(_ app: XCUIApplication) -> String {
    624     app.tabBars.buttons["Today"].tap()
    625     let account = app.descendants(matching: .any)["radroots.support.account"]
    626     guard account.waitForExistence(timeout: 10) else { return "settings=unavailable" }
    627     account.tap()
    628 
    629     let meSheet = app.descendants(matching: .any)["radroots.support.me.sheet"]
    630     guard meSheet.waitForExistence(timeout: 10),
    631       openSettingsFromMe(app, meSheet: meSheet)
    632     else { return "settings=unavailable" }
    633 
    634     let httpStatus = app.descendants(matching: .any)[
    635       "radroots.settings.blossom.http_status"
    636     ]
    637     let errorCode = app.descendants(matching: .any)[
    638       "radroots.settings.blossom.error_code"
    639     ]
    640     let serverErrorCode = app.descendants(matching: .any)[
    641       "radroots.settings.blossom.server_error_code"
    642     ]
    643     for _ in 0 ..< 6 where !httpStatus.exists || !errorCode.exists || !serverErrorCode.exists {
    644       app.swipeUp()
    645     }
    646     _ = httpStatus.waitForExistence(timeout: 10)
    647     _ = errorCode.waitForExistence(timeout: 10)
    648     _ = serverErrorCode.waitForExistence(timeout: 10)
    649     return "http=\(httpStatus.exists ? httpStatus.label : "missing"), "
    650       + "error=\(errorCode.exists ? errorCode.label : "missing"), "
    651       + "server=\(serverErrorCode.exists ? serverErrorCode.label : "missing")"
    652   }
    653 
    654   @MainActor
    655   private func publishTextFlow(
    656     _ app: XCUIApplication,
    657     type: String,
    658     marker: String
    659   ) throws {
    660     try beginDraft(app, type: type)
    661     try enterText(app, identifier: "radroots.add.content", value: marker)
    662     try submitSuccessfully(app)
    663   }
    664 
    665   @MainActor
    666   private func publishEvent(_ app: XCUIApplication, marker: String) throws {
    667     try beginDraft(app, type: "Event")
    668     try enterText(app, identifier: "radroots.add.title", value: marker)
    669     try submitSuccessfully(app)
    670   }
    671 
    672   @MainActor
    673   private func publishFood(_ app: XCUIApplication, marker: String) throws {
    674     try beginDraft(app, type: "Food availability")
    675     try enterText(app, identifier: "radroots.add.title", value: marker)
    676     try enterText(app, identifier: "radroots.add.summary", value: "Fresh local food")
    677     try enterText(app, identifier: "radroots.add.content", value: "Available today")
    678     try enterText(app, identifier: "radroots.add.location", value: "Town square")
    679     try enterText(app, identifier: "radroots.add.price", value: "3")
    680     try enterText(app, identifier: "radroots.add.currency", value: "CAD")
    681     let unit = app.descendants(matching: .any)["radroots.add.unit"]
    682     scrollTo(app, element: unit)
    683     XCTAssertTrue(unit.waitForExistence(timeout: 10))
    684     unit.tap()
    685     let pounds = app.buttons["lb"]
    686     XCTAssertTrue(pounds.waitForExistence(timeout: 10))
    687     pounds.tap()
    688     try submitSuccessfully(app)
    689   }
    690 
    691   @MainActor
    692   private func publishPersonaAttempt(
    693     _ app: XCUIApplication,
    694     attempt: PersonaAttempt,
    695     interactionProfile: String
    696   ) throws -> PersonaInteractionObservation {
    697     let type = attempt.flow.uiLabel
    698     try beginDraft(app, type: type)
    699     var progressiveDisclosure = false
    700     var accessibilitySemantics = false
    701     if interactionProfile == "novice_progressive_disclosure" {
    702       assertProgressiveDisclosure(app, type: type)
    703       progressiveDisclosure = true
    704     }
    705     if interactionProfile == "novice_accessibility_keyboard" {
    706       // The dedicated accessibility test owns the exact full contrast lane.
    707       // Persona attempts retain every semantic audit plus keyboard/focus use.
    708       try performLocalSocialAccessibilityAudit(app, includeContrast: false)
    709       accessibilitySemantics = true
    710     }
    711     try completeOpenDraft(app, flow: attempt.flow, marker: attempt.marker)
    712     return PersonaInteractionObservation(
    713       validationAttempted: false,
    714       validationRejected: false,
    715       retryAttempts: 0,
    716       relaunches: 0,
    717       progressiveDisclosure: progressiveDisclosure,
    718       accessibilitySemantics: accessibilitySemantics,
    719       keyboardFocus: accessibilitySemantics,
    720       visibleActions: true
    721     )
    722   }
    723 
    724   @MainActor
    725   private func completeOpenDraft(
    726     _ app: XCUIApplication,
    727     flow: PersonaFlow,
    728     marker: String
    729   ) throws {
    730     switch flow {
    731     case .update, .ask:
    732       try enterText(app, identifier: "radroots.add.content", value: marker)
    733     case .photoUpdate:
    734       try enterText(app, identifier: "radroots.add.content", value: marker)
    735       let library = app.descendants(matching: .any)["radroots.add.media.library"]
    736       scrollTo(app, element: library)
    737       XCTAssertTrue(library.waitForExistence(timeout: 10))
    738       XCTAssertTrue(library.isEnabled)
    739       library.tap()
    740       let prepared = app.descendants(matching: .any)["radroots.add.media.prepared"]
    741       guard prepared.waitForExistence(timeout: 60) else {
    742         XCTFail("The governed prepared Photo update was unavailable through the visible UI")
    743         throw QualificationError.missingProductSurface
    744       }
    745       try enterPhotoDescription(app)
    746       guard prepared.isHittable else {
    747         XCTFail("The governed prepared Photo update was obscured")
    748         throw QualificationError.missingProductSurface
    749       }
    750     case .event:
    751       try enterText(app, identifier: "radroots.add.title", value: marker)
    752     case .foodAvailability:
    753       try enterText(app, identifier: "radroots.add.title", value: marker)
    754       try enterText(app, identifier: "radroots.add.summary", value: "Fresh local food")
    755       try enterText(app, identifier: "radroots.add.content", value: "Available today")
    756       try enterText(app, identifier: "radroots.add.location", value: "Town square")
    757       try enterText(app, identifier: "radroots.add.price", value: "3")
    758       try enterText(app, identifier: "radroots.add.currency", value: "CAD")
    759       let unit = app.descendants(matching: .any)["radroots.add.unit"]
    760       scrollTo(app, element: unit)
    761       XCTAssertTrue(unit.waitForExistence(timeout: 10))
    762       unit.tap()
    763       let pounds = app.buttons["lb"]
    764       XCTAssertTrue(pounds.waitForExistence(timeout: 10))
    765       pounds.tap()
    766     }
    767     try submitSuccessfully(app)
    768   }
    769 
    770   @MainActor
    771   private func publishWithValidationRecovery(
    772     _ app: XCUIApplication,
    773     attempt: PersonaAttempt
    774   ) throws -> PersonaInteractionObservation {
    775     guard attempt.flow == .event else {
    776       throw QualificationError.invalidPersonaFixture
    777     }
    778     try beginDraft(app, type: attempt.flow.uiLabel)
    779     try enterText(app, identifier: "radroots.add.content", value: attempt.marker)
    780     guard let submit = readySubmit(app), let value = submitAndWait(app, submit: submit) else {
    781       throw QualificationError.missingProductSurface
    782     }
    783     let content = app.descendants(matching: .any)["radroots.add.content"]
    784     try recoverRejectedEvent(app, content: content, marker: attempt.marker, failure: value)
    785     try enterText(app, identifier: "radroots.add.title", value: attempt.marker)
    786     try submitSuccessfully(app)
    787     return PersonaInteractionObservation(
    788       validationAttempted: true,
    789       validationRejected: true,
    790       retryAttempts: 0,
    791       relaunches: 0,
    792       progressiveDisclosure: false,
    793       accessibilitySemantics: false,
    794       keyboardFocus: false,
    795       visibleActions: true
    796     )
    797   }
    798 
    799   @MainActor
    800   private func publishWithTransportRetry(
    801     _ app: XCUIApplication,
    802     configuration: QualificationConfiguration,
    803     attempt: PersonaAttempt
    804   ) throws -> (app: XCUIApplication, observation: PersonaInteractionObservation) {
    805     guard attempt.flow == .ask else {
    806       throw QualificationError.invalidPersonaFixture
    807     }
    808     try beginDraft(app, type: attempt.flow.uiLabel)
    809     try enterText(app, identifier: "radroots.add.content", value: attempt.marker)
    810     guard let submit = readySubmit(app), submitAndWait(app, submit: submit) != nil else {
    811       throw QualificationError.missingProductSurface
    812     }
    813     app.terminate()
    814 
    815     let relaunched = launchPersona(configuration)
    816     guard openAdd(relaunched) != nil, openDrafts(relaunched) else {
    817       throw QualificationError.missingProductSurface
    818     }
    819     guard continueSavedPersonaSubmission(relaunched, marker: attempt.marker) else {
    820       throw QualificationError.missingProductSurface
    821     }
    822     let done = relaunched.buttons["Done"]
    823     XCTAssertTrue(done.waitForExistence(timeout: 10))
    824     done.tap()
    825     return (
    826       relaunched,
    827       PersonaInteractionObservation(
    828         validationAttempted: false,
    829         validationRejected: false,
    830         retryAttempts: 1,
    831         relaunches: 1,
    832         progressiveDisclosure: false,
    833         accessibilitySemantics: false,
    834         keyboardFocus: false,
    835         visibleActions: true
    836       )
    837     )
    838   }
    839 
    840   private func loadPersonaSuite() throws -> PersonaSuite {
    841     let bundle = Bundle(for: TeraRemoteQualificationUITests.self)
    842     let url = try XCTUnwrap(
    843       bundle.url(forResource: "local-social-personas.v1", withExtension: "json")
    844     )
    845     let data = try Data(contentsOf: url, options: [.mappedIfSafe])
    846     guard data.count <= 64 * 1024 else {
    847       throw QualificationError.invalidPersonaFixture
    848     }
    849     return try JSONDecoder().decode(PersonaSuite.self, from: data)
    850   }
    851 
    852   private func activateFixture(persona: String, at path: String) throws {
    853     guard ["P01", "P02", "P03", "P04", "P05"].contains(persona) else {
    854       throw QualificationError.invalidPersonaFixture
    855     }
    856     let data = try JSONSerialization.data(
    857       withJSONObject: [
    858         "schema": "tera.ios.local-social.persona-control.v1",
    859         "active_persona": persona,
    860         "blossom_enabled": true,
    861       ],
    862       options: [.sortedKeys]
    863     )
    864     try data.write(to: URL(fileURLWithPath: path), options: [.atomic])
    865   }
    866 
    867   private func readFixtureNetwork(
    868     _ configuration: QualificationConfiguration
    869   ) throws -> PersonaFixtureNetworkSnapshot {
    870     let path = try XCTUnwrap(configuration.fixtureEvidence)
    871     let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path))
    872     defer { try? handle.close() }
    873     let data = try handle.read(upToCount: 64 * 1024 + 1) ?? Data()
    874     guard !data.isEmpty, data.count <= 64 * 1024 else {
    875       throw QualificationError.invalidFixtureEvidence
    876     }
    877     let root = try JSONSerialization.jsonObject(with: data)
    878     guard let value = root as? [String: Any] else {
    879       throw QualificationError.invalidFixtureEvidence
    880     }
    881     return try PersonaFixtureNetworkSnapshot(value)
    882   }
    883 
    884   @MainActor
    885   func beginDraft(_ app: XCUIApplication, type: String) throws {
    886     guard openAdd(app) != nil else {
    887       XCTFail("The Add bottom tab did not present the real Add store")
    888       throw QualificationError.missingProductSurface
    889     }
    890     let newDraft = app.buttons["radroots.add.new"]
    891     guard beginNewDraft(newDraft) else {
    892       XCTFail("The New draft action was unavailable")
    893       throw QualificationError.missingProductSurface
    894     }
    895     // The explicit replacement must settle before changing the new form.
    896     scrollAddFormToTop(app)
    897     let picker = app.descendants(matching: .any)["radroots.add.type"]
    898     scrollTo(app, element: picker)
    899     guard picker.waitForExistence(timeout: 10), waitUntilHittable(picker, timeout: 10) else {
    900       XCTFail("The Add type picker was unavailable")
    901       throw QualificationError.missingProductSurface
    902     }
    903     if picker.value as? String == type {
    904       return
    905     }
    906     picker.tap()
    907     let option = app.buttons[type]
    908     guard option.waitForExistence(timeout: 10), waitUntilHittable(option, timeout: 10) else {
    909       XCTFail("The Add type picker did not present \(type)")
    910       throw QualificationError.missingProductSurface
    911     }
    912     option.tap()
    913     guard waitForValue(picker, value: type, timeout: 10) else {
    914       XCTFail("The Add type picker did not select \(type)")
    915       throw QualificationError.missingProductSurface
    916     }
    917   }
    918 
    919   @MainActor
    920   func enterText(
    921     _ app: XCUIApplication,
    922     identifier: String,
    923     value: String
    924   ) throws {
    925     let field = app.descendants(matching: .any)[identifier]
    926     scrollTo(app, element: field)
    927     guard field.waitForExistence(timeout: 10), waitUntilHittable(field, timeout: 10) else {
    928       XCTFail("The Add field \(identifier) was unavailable")
    929       throw QualificationError.missingProductSurface
    930     }
    931     guard focusForTextInput(field, timeout: 10) else {
    932       XCTFail("The Add field \(identifier) did not accept keyboard focus")
    933       throw QualificationError.missingProductSurface
    934     }
    935     enterExactText(field, value: value)
    936     let done = app.buttons["radroots.add.keyboard.done"]
    937     if done.waitForExistence(timeout: 5) {
    938       done.tap()
    939       XCTAssertFalse(app.keyboards.firstMatch.waitForExistence(timeout: 5))
    940     }
    941   }
    942 
    943   @MainActor
    944   func submitSuccessfully(_ app: XCUIApplication) throws {
    945     guard let submit = readySubmit(app),
    946       let value = submitAndWait(app, submit: submit)
    947     else {
    948       throw QualificationError.missingProductSurface
    949     }
    950     guard !value.contains("Error code"), finishOriginalPublication(app, submit: submit) else {
    951       XCTFail("The local-social flow failed: \(value)")
    952       throw QualificationError.productSubmissionFailed
    953     }
    954   }
    955 
    956   @MainActor
    957   func scrollTo(_ app: XCUIApplication, element: XCUIElement) {
    958     let root = app.descendants(matching: .any)["radroots.add.root"]
    959     let tabBar = app.tabBars.firstMatch
    960     for attempt in 0 ..< 16 where !isVisibleInAddViewport(
    961       element,
    962       root: root,
    963       above: tabBar,
    964       below: app.navigationBars["Add"]
    965     ) {
    966       if element.exists {
    967         let targetFrame = element.frame
    968         let rootFrame = root.frame
    969         if targetFrame.midY < rootFrame.midY {
    970           root.swipeDown()
    971         } else {
    972           root.swipeUp()
    973         }
    974       } else if attempt < 8 {
    975         root.swipeUp()
    976       } else {
    977         root.swipeDown()
    978       }
    979     }
    980   }
    981 
    982   @MainActor
    983   private func scrollAddFormToTop(_ app: XCUIApplication) {
    984     let root = app.descendants(matching: .any)["radroots.add.root"]
    985     for _ in 0 ..< 8 {
    986       root.swipeDown()
    987     }
    988   }
    989 
    990   @MainActor
    991   private func assertTodayContains(_ app: XCUIApplication, markers: [String]) throws {
    992     app.tabBars.buttons["Today"].tap()
    993     let refresh = app.buttons["radroots.today.refresh"]
    994     guard refresh.waitForExistence(timeout: 10), refresh.isHittable else {
    995       XCTFail("The ordinary Today refresh action was unavailable")
    996       throw QualificationError.missingProductSurface
    997     }
    998     refresh.tap()
    999     let feed = app.descendants(matching: .any)["radroots.today.feed"].firstMatch
   1000     guard feed.waitForExistence(timeout: 30) else {
   1001       XCTFail("The local relay refresh did not materialize the Today feed")
   1002       throw QualificationError.missingProductSurface
   1003     }
   1004     let maximumCards = try loadPersonaSuite().personas.reduce(0) { $0 + $1.attempts.count }
   1005     let missing = TeraTodayQualificationNavigation.unseenMarkers(
   1006       app, feed: feed, markers: markers, maximumCards: maximumCards
   1007     )
   1008     for marker in markers.reversed() where missing.contains(marker) {
   1009       let card = app.descendants(matching: .any).matching(
   1010         NSPredicate(format: "label CONTAINS %@", marker)
   1011       ).firstMatch
   1012       guard card.waitForExistence(timeout: 30) else {
   1013         XCTFail("Missing Today card \(marker)")
   1014         throw QualificationError.missingProductSurface
   1015       }
   1016     }
   1017   }
   1018 
   1019   @MainActor
   1020   func readySubmit(_ app: XCUIApplication) -> XCUIElement? {
   1021     let submit = app.descendants(matching: .any)["radroots.add.submit"]
   1022     let addRoot = app.descendants(matching: .any)["radroots.add.root"]
   1023     for _ in 0 ..< 8 {
   1024       if isUnobscured(submit, above: app.tabBars.firstMatch) {
   1025         break
   1026       }
   1027       addRoot.swipeUp()
   1028     }
   1029     guard submit.waitForExistence(timeout: 10),
   1030       submit.isEnabled,
   1031       waitUntilHittable(submit, timeout: 10),
   1032       isUnobscured(submit, above: app.tabBars.firstMatch)
   1033     else {
   1034       XCTFail(
   1035         "The Add submission control did not become unobscured; "
   1036           + submissionDiagnostics(app, submit: submit)
   1037       )
   1038       return nil
   1039     }
   1040     return submit
   1041   }
   1042 
   1043   @MainActor
   1044   func submitAndWait(_ app: XCUIApplication, submit: XCUIElement) -> String? {
   1045     let status = app.staticTexts.matching(identifier: "radroots.add.status").firstMatch
   1046     let priorStatusLabel = status.exists ? status.label : nil
   1047     let priorSubmitValue = submit.value as? String
   1048     submit.tap()
   1049     guard
   1050       waitForWorkToFinish(
   1051         app,
   1052         submit: submit,
   1053         status: status,
   1054         priorStatusLabel: priorStatusLabel,
   1055         priorSubmitValue: priorSubmitValue
   1056       )
   1057     else {
   1058       XCTFail(
   1059         "The Add submission did not reach a terminal local state; "
   1060           + submissionDiagnostics(app, submit: submit)
   1061       )
   1062       return nil
   1063     }
   1064     scrollTo(app, element: submit)
   1065     guard submit.waitForExistence(timeout: 10), terminalControlShowsSettledState(submit) else {
   1066       XCTFail("The terminal Add submission control was unavailable")
   1067       return nil
   1068     }
   1069     let terminalValue = submit.value as? String ?? "missing"
   1070     let statusChanged = status.exists
   1071       && !status.label.isEmpty
   1072       && status.label != priorStatusLabel
   1073     guard statusChanged || terminalValue != priorSubmitValue && terminalValue != "Working" else {
   1074       XCTFail(
   1075         "The Add submission did not expose changed terminal evidence; "
   1076           + submissionDiagnostics(app, submit: submit)
   1077       )
   1078       return nil
   1079     }
   1080     return terminalValue
   1081   }
   1082 
   1083   @MainActor
   1084   private func assertUnverifiedDraft(_ app: XCUIApplication) -> Bool {
   1085     guard openDrafts(app) else {
   1086       XCTFail("The Drafts sheet did not open after the unavailable attempt")
   1087       return false
   1088     }
   1089     let selectedMedia = app.descendants(matching: .any)["tera.add.submission.media_status"]
   1090     let viewSubmission = app.buttons["View submission"].firstMatch
   1091     if !selectedMedia.exists, viewSubmission.exists {
   1092       viewSubmission.tap()
   1093     }
   1094     let mediaStatus = app.descendants(matching: .any).matching(
   1095       NSPredicate(format: "label CONTAINS '0 of 1 photos verified'")
   1096     ).firstMatch
   1097     let exists = mediaStatus.waitForExistence(timeout: 20)
   1098     XCTAssertTrue(exists)
   1099     if exists {
   1100       XCTAssertTrue(
   1101         mediaStatus.label == "0 of 1 photos verified"
   1102           || mediaStatus.label == "0 of 1 photos verified; 1 possible orphan",
   1103         "An unavailable upload did not preserve a bounded retry state; "
   1104           + "media_status.label=\(mediaStatus.label)"
   1105       )
   1106     }
   1107     app.buttons["Done"].tap()
   1108     return exists
   1109   }
   1110 
   1111   @MainActor
   1112   private func isUnobscured(_ element: XCUIElement, above obstruction: XCUIElement) -> Bool {
   1113     guard element.exists, element.isEnabled, element.isHittable, obstruction.exists else {
   1114       return false
   1115     }
   1116     let frame = element.frame
   1117     return frame.height > 0
   1118       && frame.minY >= 0
   1119       && frame.maxY <= obstruction.frame.minY
   1120   }
   1121 
   1122   @MainActor
   1123   private func submissionDiagnostics(
   1124     _ app: XCUIApplication,
   1125     submit: XCUIElement
   1126   ) -> String {
   1127     let progress = app.descendants(matching: .any)["radroots.add.progress"]
   1128     let status = app.staticTexts.matching(identifier: "radroots.add.status").firstMatch
   1129     let statusLabel = status.exists ? status.label : "missing"
   1130     guard submit.exists else {
   1131       return "submit.exists=false, progress.exists=\(progress.exists), status=\(statusLabel)"
   1132     }
   1133     let tabBar = app.tabBars.firstMatch
   1134     return "submit.exists=\(submit.exists), submit.enabled=\(submit.isEnabled), "
   1135       + "submit.hittable=\(submit.isHittable), submit.value=\(String(describing: submit.value)), "
   1136       + "submit.frame=\(submit.frame), "
   1137       + "tab_bar_top=\(tabBar.exists ? tabBar.frame.minY : -1), "
   1138       + "progress.exists=\(progress.exists), status=\(statusLabel)"
   1139   }
   1140 
   1141   @MainActor
   1142   func openDrafts(_ app: XCUIApplication) -> Bool {
   1143     let drafts = app.buttons["radroots.add.drafts"]
   1144     guard drafts.waitForExistence(timeout: 10) else { return false }
   1145     let sheet = app.descendants(matching: .any)["radroots.add.drafts.sheet"]
   1146     for _ in 0 ..< 3 {
   1147       drafts.tap()
   1148       if sheet.waitForExistence(timeout: 10) {
   1149         return true
   1150       }
   1151     }
   1152     return false
   1153   }
   1154 
   1155   @MainActor
   1156   func waitUntilHittable(_ element: XCUIElement, timeout: TimeInterval) -> Bool {
   1157     let predicate = NSPredicate(format: "exists == true AND hittable == true")
   1158     let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)
   1159     return XCTWaiter.wait(for: [expectation], timeout: timeout) == .completed
   1160   }
   1161 
   1162   @MainActor
   1163   private func focusForTextInput(_ element: XCUIElement, timeout: TimeInterval) -> Bool {
   1164     let focused = NSPredicate(format: "hasKeyboardFocus == true")
   1165     for _ in 0 ..< 3 {
   1166       element.tap()
   1167       let expectation = XCTNSPredicateExpectation(predicate: focused, object: element)
   1168       if XCTWaiter.wait(for: [expectation], timeout: timeout / 3) == .completed {
   1169         return true
   1170       }
   1171     }
   1172     return false
   1173   }
   1174 
   1175   @MainActor
   1176   func waitForValue(
   1177     _ element: XCUIElement,
   1178     value: String,
   1179     timeout: TimeInterval
   1180   ) -> Bool {
   1181     let predicate = NSPredicate { object, _ in
   1182       guard let object = object as? XCUIElement else { return false }
   1183       return object.exists && object.value as? String == value
   1184     }
   1185     let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)
   1186     return XCTWaiter.wait(for: [expectation], timeout: timeout) == .completed
   1187   }
   1188 
   1189   @MainActor
   1190   private func waitForLabel(
   1191     _ element: XCUIElement,
   1192     label: String,
   1193     timeout: TimeInterval
   1194   ) -> Bool {
   1195     let predicate = NSPredicate { object, _ in
   1196       guard let object = object as? XCUIElement else { return false }
   1197       return object.exists && object.label == label
   1198     }
   1199     let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)
   1200     return XCTWaiter.wait(for: [expectation], timeout: timeout) == .completed
   1201   }
   1202 
   1203   private func writeBootstrapReceipt(
   1204     configuration: QualificationConfiguration,
   1205     publicKey: String
   1206   ) throws {
   1207     let receipt = BootstrapReceipt(
   1208       schema: "tera-ios-remote-qualification-bootstrap-v1",
   1209       schemaVersion: 1,
   1210       runID: configuration.runID,
   1211       publicKey: publicKey,
   1212       relayURLs: configuration.relayURLs,
   1213       blossomOrigins: configuration.blossomOrigins,
   1214       privateKeyPresent: false,
   1215       interactiveAuthenticationRequired: false
   1216     )
   1217     let encoder = JSONEncoder()
   1218     encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
   1219     let data = try encoder.encode(receipt)
   1220     let documents = try XCTUnwrap(
   1221       FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
   1222     )
   1223     try data.write(
   1224       to: documents.appendingPathComponent(Self.receiptName),
   1225       options: .atomic
   1226     )
   1227     let attachment = XCTAttachment(data: data, uniformTypeIdentifier: "public.json")
   1228     attachment.name = Self.receiptName
   1229     attachment.lifetime = .keepAlways
   1230     add(attachment)
   1231   }
   1232 
   1233   private func writePersonaAttemptAttachment(
   1234     configuration: QualificationConfiguration,
   1235     personaAlias: String,
   1236     attempt: PersonaAttempt,
   1237     identityDigest: String,
   1238     observation: PersonaAttemptObservation
   1239   ) throws {
   1240     let binding = try XCTUnwrap(configuration.evidenceBinding)
   1241     let evidence = PersonaAttemptEvidence(
   1242       schema: "tera.ios.local-social.persona-attempt-evidence.v1",
   1243       schemaVersion: 1,
   1244       testInvocation: .init(
   1245         target: "TeraUITests",
   1246         identifier: "TeraUITests/testLocalSocialDeterministicPersonas",
   1247         action: "test",
   1248         configuration: "Debug"
   1249       ),
   1250       source: .init(commit: binding.sourceCommit, tree: binding.sourceTree),
   1251       appBuildSHA256: binding.appBuildSHA256,
   1252       simulator: .init(
   1253         udid: binding.simulatorID,
   1254         os: Self.currentIOSVersion,
   1255         architecture: "arm64"
   1256       ),
   1257       runID: configuration.qualificationRunID,
   1258       personaRunID: configuration.runID,
   1259       personaAlias: personaAlias,
   1260       attemptID: attempt.id,
   1261       attemptOrder: attempt.order,
   1262       flow: attempt.flow.rawValue,
   1263       expectedFailure: attempt.expectedFailure,
   1264       publicIdentitySHA256: identityDigest,
   1265       endpointPolicySHA256: Self.endpointPolicyDigest(configuration),
   1266       uiObservation: observation.ui,
   1267       networkObservation: observation.network,
   1268       accessibility: .init(
   1269         locale: "en_US",
   1270         contentSize: "accessibility-extra-extra-extra-large",
   1271         reduceMotion: true,
   1272         progressiveDisclosure: observation.interaction.progressiveDisclosure,
   1273         labelsValuesTraits: observation.interaction.accessibilitySemantics,
   1274         keyboardFocus: observation.interaction.keyboardFocus,
   1275         visibleActions: observation.interaction.visibleActions,
   1276         voiceoverUserObserved: false
   1277       ),
   1278       artifactDigests: []
   1279     )
   1280     let encoder = JSONEncoder()
   1281     encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
   1282     let data = try encoder.encode(evidence)
   1283     XCTAssertLessThanOrEqual(data.count, 64 * 1024)
   1284     let attachment = XCTAttachment(data: data, uniformTypeIdentifier: "public.json")
   1285     attachment.name = "radroots-local-social-\(attempt.id).json"
   1286     attachment.lifetime = .keepAlways
   1287     add(attachment)
   1288   }
   1289 
   1290   private static var currentIOSVersion: String {
   1291     let version = ProcessInfo.processInfo.operatingSystemVersion
   1292     return "iOS \(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
   1293   }
   1294 
   1295   private static func endpointPolicyDigest(
   1296     _ configuration: QualificationConfiguration
   1297   ) -> String {
   1298     var payload = Data("radroots.ios.local-social.endpoint-policy.v1\0".utf8)
   1299     for value in (configuration.relayURLs + configuration.blossomOrigins).sorted() {
   1300       let bytes = Data(value.utf8)
   1301       var length = UInt64(bytes.count).bigEndian
   1302       withUnsafeBytes(of: &length) { payload.append(contentsOf: $0) }
   1303       payload.append(bytes)
   1304     }
   1305     return SHA256.hash(data: payload).map { String(format: "%02x", $0) }.joined()
   1306   }
   1307 }
   1308 
   1309 private struct QualificationEndpointPolicy {
   1310   private enum Role {
   1311     case relay
   1312     case blossom
   1313   }
   1314 
   1315   init(relayURLs: [String], blossomOrigins: [String], profile: String) throws {
   1316     guard !relayURLs.isEmpty,
   1317       Set(relayURLs).count == relayURLs.count,
   1318       blossomOrigins.count == 1
   1319     else {
   1320       throw QualificationError.invalidEndpointPolicy
   1321     }
   1322     if profile == "simulator" {
   1323       guard
   1324         relayURLs.allSatisfy({ Self.isEndpoint($0, role: .relay, loopbackOnly: true) }),
   1325         blossomOrigins.allSatisfy({
   1326           Self.isEndpoint($0, role: .blossom, loopbackOnly: true)
   1327         })
   1328       else {
   1329         throw QualificationError.invalidEndpointPolicy
   1330       }
   1331     } else {
   1332       guard
   1333         relayURLs.allSatisfy({ Self.isEndpoint($0, role: .relay, loopbackOnly: false) }),
   1334         blossomOrigins.allSatisfy({
   1335           Self.isEndpoint($0, role: .blossom, loopbackOnly: false)
   1336         })
   1337       else {
   1338         throw QualificationError.invalidEndpointPolicy
   1339       }
   1340     }
   1341   }
   1342 
   1343   private static func isEndpoint(
   1344     _ raw: String,
   1345     role: Role,
   1346     loopbackOnly: Bool
   1347   ) -> Bool {
   1348     guard let value = URLComponents(string: raw),
   1349       value.user == nil,
   1350       value.password == nil,
   1351       value.query == nil,
   1352       value.fragment == nil,
   1353       let scheme = value.scheme?.lowercased(),
   1354       let host = value.host?.lowercased(),
   1355       !host.isEmpty
   1356     else { return false }
   1357     let expectedScheme = switch (role, loopbackOnly) {
   1358     case (.relay, true): "ws"
   1359     case (.blossom, true): "http"
   1360     case (.relay, false): "wss"
   1361     case (.blossom, false): "https"
   1362     }
   1363     if loopbackOnly {
   1364       return scheme == expectedScheme
   1365         && host == "127.0.0.1"
   1366         && value.port.map { 1 ... 65535 ~= $0 } == true
   1367         && (value.path.isEmpty || value.path == "/")
   1368     }
   1369     return scheme == expectedScheme
   1370       && host != "127.0.0.1"
   1371       && host != "::1"
   1372       && host != "localhost"
   1373   }
   1374 }
   1375 
   1376 private struct QualificationConfiguration {
   1377   static let enabledKey = "TERA_IOS_UI_TEST_REMOTE"
   1378   static let runIDKey = "TERA_IOS_UI_TEST_RUN_ID"
   1379   static let relayURLsKey = "TERA_IOS_UI_TEST_NOSTR_RELAY_URLS"
   1380   static let blossomOriginsKey = "TERA_IOS_UI_TEST_BLOSSOM_ORIGINS"
   1381   static let fixtureControlKey = "TERA_IOS_UI_TEST_FIXTURE_CONTROL"
   1382   static let fixtureEvidenceKey = "TERA_IOS_UI_TEST_FIXTURE_EVIDENCE"
   1383   static let mediaRelativePathKey = "TERA_IOS_UI_TEST_MEDIA_RELATIVE_PATH"
   1384   static let networkProfileKey = "TERA_IOS_UI_TEST_NETWORK_PROFILE"
   1385   static let sourceCommitKey = "TERA_IOS_UI_TEST_SOURCE_COMMIT"
   1386   static let sourceTreeKey = "TERA_IOS_UI_TEST_SOURCE_TREE"
   1387   static let appBuildSHA256Key = "TERA_IOS_UI_TEST_APP_BUILD_SHA256"
   1388   static let simulatorIDKey = "TERA_IOS_UI_TEST_SIMULATOR_ID"
   1389 
   1390   let runID: String
   1391   let qualificationRunID: String
   1392   let relayURLs: [String]
   1393   let blossomOrigins: [String]
   1394   let fixtureControl: String?
   1395   let fixtureEvidence: String?
   1396   let networkProfile: String
   1397   let evidenceBinding: PersonaEvidenceBinding?
   1398 
   1399   init(
   1400     runID: String,
   1401     relayURLs: [String],
   1402     blossomOrigins: [String],
   1403     fixtureControl: String? = nil,
   1404     fixtureEvidence: String? = nil,
   1405     networkProfile: String = "public",
   1406     qualificationRunID: String? = nil,
   1407     evidenceBinding: PersonaEvidenceBinding? = nil
   1408   ) {
   1409     self.runID = runID
   1410     self.qualificationRunID = qualificationRunID ?? runID
   1411     self.relayURLs = relayURLs
   1412     self.blossomOrigins = blossomOrigins
   1413     self.fixtureControl = fixtureControl
   1414     self.fixtureEvidence = fixtureEvidence
   1415     self.networkProfile = networkProfile
   1416     self.evidenceBinding = evidenceBinding
   1417   }
   1418 
   1419   var launchEnvironment: [String: String] {
   1420     [
   1421       Self.enabledKey: "1",
   1422       Self.runIDKey: runID,
   1423       Self.relayURLsKey: relayURLs.joined(separator: ","),
   1424       Self.blossomOriginsKey: blossomOrigins.joined(separator: ","),
   1425       Self.mediaRelativePathKey: "qualification/input.png",
   1426       Self.networkProfileKey: networkProfile,
   1427       "RUST_BACKTRACE": "1",
   1428     ]
   1429   }
   1430 
   1431   func forPersona(_ alias: String) -> Self {
   1432     let digest = SHA256.hash(
   1433       data: Data("radroots.ios.local-social.persona-run.v1\0\(runID)\0\(alias)".utf8)
   1434     )
   1435     let suffix = digest.prefix(12).map { String(format: "%02x", $0) }.joined()
   1436     return Self(
   1437       runID: "persona-\(alias.lowercased())-\(suffix)",
   1438       relayURLs: relayURLs,
   1439       blossomOrigins: blossomOrigins,
   1440       fixtureControl: fixtureControl,
   1441       fixtureEvidence: fixtureEvidence,
   1442       networkProfile: networkProfile,
   1443       qualificationRunID: qualificationRunID,
   1444       evidenceBinding: evidenceBinding
   1445     )
   1446   }
   1447 
   1448   static func environment(
   1449     _ values: [String: String] = ProcessInfo.processInfo.environment
   1450   ) throws -> Self {
   1451     let bundle = Bundle(for: TeraRemoteQualificationUITests.self)
   1452     let runIDValue =
   1453       values[runIDKey]
   1454       ?? bundle.object(forInfoDictionaryKey: runIDKey) as? String
   1455     let relayValue =
   1456       values[relayURLsKey]
   1457       ?? bundle.object(forInfoDictionaryKey: relayURLsKey) as? String
   1458     let blossomValue =
   1459       values[blossomOriginsKey]
   1460       ?? bundle.object(forInfoDictionaryKey: blossomOriginsKey) as? String
   1461     let fixtureControl =
   1462       values[fixtureControlKey]
   1463       ?? bundle.object(forInfoDictionaryKey: fixtureControlKey) as? String
   1464     let fixtureEvidence =
   1465       values[fixtureEvidenceKey]
   1466       ?? bundle.object(forInfoDictionaryKey: fixtureEvidenceKey) as? String
   1467     let networkProfile =
   1468       values[networkProfileKey]
   1469       ?? bundle.object(forInfoDictionaryKey: networkProfileKey) as? String
   1470     let sourceCommit = value(sourceCommitKey, values: values, bundle: bundle)
   1471     let sourceTree = value(sourceTreeKey, values: values, bundle: bundle)
   1472     let appBuildSHA256 = value(appBuildSHA256Key, values: values, bundle: bundle)
   1473     let simulatorID = value(simulatorIDKey, values: values, bundle: bundle)
   1474     if runIDValue?.isEmpty != false, blossomValue?.isEmpty != false {
   1475       throw XCTSkip("remote qualification inputs were not selected")
   1476     }
   1477     guard let runID = runIDValue,
   1478       runID.range(of: "^[a-z0-9][a-z0-9-]{6,62}[a-z0-9]$", options: .regularExpression) != nil,
   1479       let blossom = blossomValue,
   1480       !blossom.isEmpty,
   1481       let networkProfile,
   1482       networkProfile == "public" || networkProfile == "simulator"
   1483     else {
   1484       throw QualificationError.missingEnvironment
   1485     }
   1486     _ = try QualificationEndpointPolicy(
   1487       relayURLs: separated(relayValue),
   1488       blossomOrigins: separated(blossom),
   1489       profile: networkProfile
   1490     )
   1491     if networkProfile == "simulator" {
   1492       guard
   1493         let fixtureControl,
   1494         let fixtureEvidence,
   1495         fixtureControl.utf8.count <= 1024,
   1496         fixtureEvidence.utf8.count <= 1024,
   1497         fixtureControl.hasPrefix("/"),
   1498         fixtureEvidence.hasPrefix("/")
   1499       else {
   1500         throw QualificationError.missingEnvironment
   1501       }
   1502     }
   1503     let evidenceBinding = PersonaEvidenceBinding(
   1504       sourceCommit: sourceCommit,
   1505       sourceTree: sourceTree,
   1506       appBuildSHA256: appBuildSHA256,
   1507       simulatorID: simulatorID
   1508     )
   1509     return Self(
   1510       runID: runID,
   1511       relayURLs: separated(relayValue),
   1512       blossomOrigins: separated(blossom),
   1513       fixtureControl: fixtureControl.flatMap { $0.isEmpty ? nil : $0 },
   1514       fixtureEvidence: fixtureEvidence.flatMap { $0.isEmpty ? nil : $0 },
   1515       networkProfile: networkProfile,
   1516       evidenceBinding: evidenceBinding
   1517     )
   1518   }
   1519 
   1520   private static func value(
   1521     _ key: String,
   1522     values: [String: String],
   1523     bundle: Bundle
   1524   ) -> String? {
   1525     (values[key] ?? bundle.object(forInfoDictionaryKey: key) as? String)
   1526       .flatMap { $0.isEmpty ? nil : $0 }
   1527   }
   1528 
   1529   private static func separated(_ value: String?) -> [String] {
   1530     (value ?? "").split(separator: ",").map(String.init).filter { !$0.isEmpty }
   1531   }
   1532 }
   1533 
   1534 private struct PersonaEvidenceBinding {
   1535   let sourceCommit: String
   1536   let sourceTree: String
   1537   let appBuildSHA256: String
   1538   let simulatorID: String
   1539 
   1540   init?(
   1541     sourceCommit: String?,
   1542     sourceTree: String?,
   1543     appBuildSHA256: String?,
   1544     simulatorID: String?
   1545   ) {
   1546     guard let sourceCommit,
   1547       sourceCommit.range(of: "^[0-9a-f]{40}$", options: .regularExpression) != nil,
   1548       let sourceTree,
   1549       sourceTree.range(of: "^[0-9a-f]{40}$", options: .regularExpression) != nil,
   1550       let appBuildSHA256,
   1551       appBuildSHA256.range(of: "^[0-9a-f]{64}$", options: .regularExpression) != nil,
   1552       let simulatorID,
   1553       simulatorID.uppercased().range(
   1554         of: "^[A-F0-9-]{36}$",
   1555         options: .regularExpression
   1556       ) != nil
   1557     else { return nil }
   1558     self.sourceCommit = sourceCommit
   1559     self.sourceTree = sourceTree
   1560     self.appBuildSHA256 = appBuildSHA256
   1561     self.simulatorID = simulatorID.uppercased()
   1562   }
   1563 }
   1564 
   1565 private struct PersonaAttemptTestInvocation: Encodable {
   1566   let target: String
   1567   let identifier: String
   1568   let action: String
   1569   let configuration: String
   1570 }
   1571 
   1572 private struct PersonaAttemptSource: Encodable {
   1573   let commit: String
   1574   let tree: String
   1575 }
   1576 
   1577 private struct PersonaAttemptSimulator: Encodable {
   1578   let udid: String
   1579   let os: String
   1580   let architecture: String
   1581 }
   1582 
   1583 private struct PersonaAttemptUIObservation: Encodable {
   1584   let validationAttempted: Bool
   1585   let validationRejected: Bool
   1586   let retryAttempts: Int
   1587   let relaunches: Int
   1588   let retentionVerified: Bool
   1589   let todayProjectionVerified: Bool
   1590 
   1591   enum CodingKeys: String, CodingKey {
   1592     case validationAttempted = "validation_attempted"
   1593     case validationRejected = "validation_rejected"
   1594     case retryAttempts = "retry_attempts"
   1595     case relaunches
   1596     case retentionVerified = "retention_verified"
   1597     case todayProjectionVerified = "today_projection_verified"
   1598   }
   1599 }
   1600 
   1601 private struct PersonaInteractionObservation {
   1602   let validationAttempted: Bool
   1603   let validationRejected: Bool
   1604   let retryAttempts: Int
   1605   let relaunches: Int
   1606   let progressiveDisclosure: Bool
   1607   let accessibilitySemantics: Bool
   1608   let keyboardFocus: Bool
   1609   let visibleActions: Bool
   1610 }
   1611 
   1612 private struct PersonaAttemptObservation {
   1613   let interaction: PersonaInteractionObservation
   1614   let network: PersonaAttemptNetworkObservation
   1615   let todayProjectionVerified: Bool
   1616   let retentionVerified: Bool
   1617 
   1618   var ui: PersonaAttemptUIObservation {
   1619     PersonaAttemptUIObservation(
   1620       validationAttempted: interaction.validationAttempted,
   1621       validationRejected: interaction.validationRejected,
   1622       retryAttempts: interaction.retryAttempts,
   1623       relaunches: interaction.relaunches,
   1624       retentionVerified: retentionVerified,
   1625       todayProjectionVerified: todayProjectionVerified
   1626     )
   1627   }
   1628 
   1629   func confirmingRetention() -> Self {
   1630     Self(
   1631       interaction: interaction,
   1632       network: network,
   1633       todayProjectionVerified: todayProjectionVerified,
   1634       retentionVerified: true
   1635     )
   1636   }
   1637 }
   1638 
   1639 private struct PersonaAttemptNetworkObservation: Encodable {
   1640   let state: String
   1641   let acceptedConnections: Int
   1642   let rejectedConnections: Int
   1643   let nonLoopbackAttempts: Int
   1644   let subscriptions: Int
   1645   let acceptedEvents: Int
   1646   let acceptedUploads: Int
   1647   let retrievals: Int
   1648   let unintendedPublications: Int
   1649   let eventsAcceptedDuringExpectedFailure: Int
   1650   let finalCandidateDataLoss: Int
   1651 
   1652   enum CodingKeys: String, CodingKey {
   1653     case state
   1654     case acceptedConnections = "accepted_connections"
   1655     case rejectedConnections = "rejected_connections"
   1656     case nonLoopbackAttempts = "non_loopback_attempts"
   1657     case subscriptions
   1658     case acceptedEvents = "accepted_events"
   1659     case acceptedUploads = "accepted_uploads"
   1660     case retrievals
   1661     case unintendedPublications = "unintended_publications"
   1662     case eventsAcceptedDuringExpectedFailure = "events_accepted_during_expected_failure"
   1663     case finalCandidateDataLoss = "final_candidate_data_loss"
   1664   }
   1665 }
   1666 
   1667 private struct PersonaFixtureNetworkSnapshot {
   1668   private static let keys: Set<String> = [
   1669     "schema", "schema_version", "personas", "flow_counts", "accepted_events",
   1670     "event_kind_counts", "upload_attempts", "accepted_uploads", "retrievals",
   1671     "distinct_identities", "unknown_attempts", "duplicate_attempts",
   1672     "expected_failure_rejections", "events_accepted_during_expected_failures",
   1673     "accepted_connections", "rejected_connections", "non_loopback_attempts",
   1674     "production_network_contacts", "unintended_publications", "final_candidate_data_loss",
   1675   ]
   1676 
   1677   let acceptedConnections: Int
   1678   let rejectedConnections: Int
   1679   let nonLoopbackAttempts: Int
   1680   let productionNetworkContacts: Int
   1681   let subscriptions: Int
   1682   let acceptedEvents: Int
   1683   let acceptedUploads: Int
   1684   let retrievals: Int
   1685   let unintendedPublications: Int
   1686   let eventsAcceptedDuringExpectedFailures: Int
   1687   let finalCandidateDataLoss: Int
   1688 
   1689   init(_ value: [String: Any]) throws {
   1690     guard Set(value.keys) == Self.keys,
   1691       value["schema"] as? String == "tera.ios.local-social.persona-evidence.v1",
   1692       value["schema_version"] as? Int == 1,
   1693       let acceptedConnections = value["accepted_connections"] as? Int,
   1694       let rejectedConnections = value["rejected_connections"] as? Int,
   1695       let nonLoopbackAttempts = value["non_loopback_attempts"] as? Int,
   1696       let productionNetworkContacts = value["production_network_contacts"] as? Int,
   1697       let acceptedEvents = value["accepted_events"] as? Int,
   1698       let acceptedUploads = value["accepted_uploads"] as? Int,
   1699       let retrievals = value["retrievals"] as? Int,
   1700       let unintendedPublications = value["unintended_publications"] as? Int,
   1701       let eventsAccepted = value["events_accepted_during_expected_failures"] as? Int,
   1702       let finalCandidateDataLoss = value["final_candidate_data_loss"] as? Int,
   1703       let personas = value["personas"] as? [[String: Any]],
   1704       personas.count == 5,
   1705       [
   1706         acceptedConnections, rejectedConnections, nonLoopbackAttempts,
   1707         productionNetworkContacts,
   1708         acceptedEvents, acceptedUploads, retrievals, unintendedPublications,
   1709         eventsAccepted, finalCandidateDataLoss,
   1710       ].allSatisfy({ 0 ... 61440 ~= $0 })
   1711     else {
   1712       throw QualificationError.invalidFixtureEvidence
   1713     }
   1714     let subscriptions = try personas.reduce(into: 0) { total, persona in
   1715       guard let value = persona["subscriptions"] as? Int, 0 ... 4096 ~= value else {
   1716         throw QualificationError.invalidFixtureEvidence
   1717       }
   1718       total += value
   1719     }
   1720     self.acceptedConnections = acceptedConnections
   1721     self.rejectedConnections = rejectedConnections
   1722     self.nonLoopbackAttempts = nonLoopbackAttempts
   1723     self.productionNetworkContacts = productionNetworkContacts
   1724     self.subscriptions = subscriptions
   1725     self.acceptedEvents = acceptedEvents
   1726     self.acceptedUploads = acceptedUploads
   1727     self.retrievals = retrievals
   1728     self.unintendedPublications = unintendedPublications
   1729     eventsAcceptedDuringExpectedFailures = eventsAccepted
   1730     self.finalCandidateDataLoss = finalCandidateDataLoss
   1731   }
   1732 
   1733   func delta(from prior: Self) throws -> PersonaAttemptNetworkObservation {
   1734     let current = [
   1735       acceptedConnections, rejectedConnections, nonLoopbackAttempts, subscriptions,
   1736       productionNetworkContacts,
   1737       acceptedEvents, acceptedUploads, retrievals, unintendedPublications,
   1738       eventsAcceptedDuringExpectedFailures, finalCandidateDataLoss,
   1739     ]
   1740     let previous = [
   1741       prior.acceptedConnections, prior.rejectedConnections, prior.nonLoopbackAttempts,
   1742       prior.subscriptions, prior.productionNetworkContacts, prior.acceptedEvents,
   1743       prior.acceptedUploads, prior.retrievals,
   1744       prior.unintendedPublications, prior.eventsAcceptedDuringExpectedFailures,
   1745       prior.finalCandidateDataLoss,
   1746     ]
   1747     guard zip(current, previous).allSatisfy({ pair in pair.0 >= pair.1 }) else {
   1748       throw QualificationError.invalidFixtureEvidence
   1749     }
   1750     let values = zip(current, previous).map { pair in pair.0 - pair.1 }
   1751     guard values[2] == 0, values[4] == 0 else {
   1752       throw QualificationError.invalidEndpointPolicy
   1753     }
   1754     return PersonaAttemptNetworkObservation(
   1755       state: "measured",
   1756       acceptedConnections: values[0],
   1757       rejectedConnections: values[1],
   1758       nonLoopbackAttempts: values[2],
   1759       subscriptions: values[3],
   1760       acceptedEvents: values[5],
   1761       acceptedUploads: values[6],
   1762       retrievals: values[7],
   1763       unintendedPublications: values[8],
   1764       eventsAcceptedDuringExpectedFailure: values[9],
   1765       finalCandidateDataLoss: values[10]
   1766     )
   1767   }
   1768 }
   1769 
   1770 private struct PersonaAttemptAccessibility: Encodable {
   1771   let locale: String
   1772   let contentSize: String
   1773   let reduceMotion: Bool
   1774   let progressiveDisclosure: Bool
   1775   let labelsValuesTraits: Bool
   1776   let keyboardFocus: Bool
   1777   let visibleActions: Bool
   1778   let voiceoverUserObserved: Bool
   1779 
   1780   enum CodingKeys: String, CodingKey {
   1781     case locale
   1782     case contentSize = "content_size"
   1783     case reduceMotion = "reduce_motion"
   1784     case progressiveDisclosure = "progressive_disclosure"
   1785     case labelsValuesTraits = "labels_values_traits"
   1786     case keyboardFocus = "keyboard_focus"
   1787     case visibleActions = "visible_actions"
   1788     case voiceoverUserObserved = "voiceover_user_observed"
   1789   }
   1790 }
   1791 
   1792 private struct PersonaAttemptArtifactDigest: Encodable {
   1793   let role: String
   1794   let sha256: String
   1795 }
   1796 
   1797 private struct PersonaAttemptEvidence: Encodable {
   1798   let schema: String
   1799   let schemaVersion: UInt16
   1800   let testInvocation: PersonaAttemptTestInvocation
   1801   let source: PersonaAttemptSource
   1802   let appBuildSHA256: String
   1803   let simulator: PersonaAttemptSimulator
   1804   let runID: String
   1805   let personaRunID: String
   1806   let personaAlias: String
   1807   let attemptID: String
   1808   let attemptOrder: Int
   1809   let flow: String
   1810   let expectedFailure: String
   1811   let publicIdentitySHA256: String
   1812   let endpointPolicySHA256: String
   1813   let uiObservation: PersonaAttemptUIObservation
   1814   let networkObservation: PersonaAttemptNetworkObservation
   1815   let accessibility: PersonaAttemptAccessibility
   1816   let artifactDigests: [PersonaAttemptArtifactDigest]
   1817 
   1818   enum CodingKeys: String, CodingKey {
   1819     case schema
   1820     case schemaVersion = "schema_version"
   1821     case testInvocation = "test_invocation"
   1822     case source
   1823     case appBuildSHA256 = "app_build_sha256"
   1824     case simulator
   1825     case runID = "run_id"
   1826     case personaRunID = "persona_run_id"
   1827     case personaAlias = "persona_alias"
   1828     case attemptID = "attempt_id"
   1829     case attemptOrder = "attempt_order"
   1830     case flow
   1831     case expectedFailure = "expected_failure"
   1832     case publicIdentitySHA256 = "public_identity_sha256"
   1833     case endpointPolicySHA256 = "endpoint_policy_sha256"
   1834     case uiObservation = "ui_observation"
   1835     case networkObservation = "network_observation"
   1836     case accessibility
   1837     case artifactDigests = "artifact_digests"
   1838   }
   1839 }
   1840 
   1841 private struct BootstrapReceipt: Codable {
   1842   let schema: String
   1843   let schemaVersion: UInt16
   1844   let runID: String
   1845   let publicKey: String
   1846   let relayURLs: [String]
   1847   let blossomOrigins: [String]
   1848   let privateKeyPresent: Bool
   1849   let interactiveAuthenticationRequired: Bool
   1850 }
   1851 
   1852 private struct PersonaSuite: Decodable {
   1853   let schema: String
   1854   let schemaVersion: UInt16
   1855   let locale: String
   1856   let mediaFixtureSHA256: String
   1857   let personas: [Persona]
   1858 
   1859   enum CodingKeys: String, CodingKey {
   1860     case schema
   1861     case schemaVersion = "schema_version"
   1862     case locale
   1863     case mediaFixtureSHA256 = "media_fixture_sha256"
   1864     case personas
   1865   }
   1866 }
   1867 
   1868 private struct Persona: Decodable {
   1869   let alias: String
   1870   let syntheticAgeBand: String
   1871   let interactionProfile: String
   1872   let attempts: [PersonaAttempt]
   1873 
   1874   enum CodingKeys: String, CodingKey {
   1875     case alias
   1876     case syntheticAgeBand = "synthetic_age_band"
   1877     case interactionProfile = "interaction_profile"
   1878     case attempts
   1879   }
   1880 }
   1881 
   1882 private struct PersonaAttempt: Decodable {
   1883   let id: String
   1884   let order: Int
   1885   let flow: PersonaFlow
   1886   let marker: String
   1887   let expectedFailure: String
   1888 
   1889   enum CodingKeys: String, CodingKey {
   1890     case id
   1891     case order
   1892     case flow
   1893     case marker
   1894     case expectedFailure = "expected_failure"
   1895   }
   1896 }
   1897 
   1898 private enum PersonaFlow: String, Decodable {
   1899   case update = "Update"
   1900   case photoUpdate = "PhotoUpdate"
   1901   case ask = "Ask"
   1902   case event = "Event"
   1903   case foodAvailability = "FoodAvailability"
   1904 
   1905   var uiLabel: String {
   1906     switch self {
   1907     case .update: "Update"
   1908     case .photoUpdate: "Photo update"
   1909     case .ask: "Ask"
   1910     case .event: "Event"
   1911     case .foodAvailability: "Food availability"
   1912     }
   1913   }
   1914 }
   1915 
   1916 private enum QualificationError: Error {
   1917   case missingEnvironment
   1918   case invalidEndpointPolicy
   1919   case invalidFixtureEvidence
   1920   case invalidPublicKey
   1921   case missingProductSurface
   1922   case productSubmissionFailed
   1923   case invalidPersonaFixture
   1924 }