| 1 | import Foundation |
| 2 | import Darwin |
| 3 | import JavaScriptCore |
| 4 | |
| 5 | @main struct AppleCheckpointProof { |
| 6 | static func require(_ condition: @autoclosure () throws -> Bool, _ message: String) throws { |
| 7 | if try !condition() { throw PetCoreError.invalid(message) } |
| 8 | } |
| 9 | static func reject(_ action: () throws -> Void, _ message: String) throws { |
| 10 | do { try action() } catch { return } |
| 11 | throw PetCoreError.invalid(message) |
| 12 | } |
| 13 | static func same(_ a: Data, _ b: Data) throws -> Bool { |
| 14 | let left = try JSONSerialization.jsonObject(with: a) as! NSDictionary |
| 15 | return try left.isEqual(JSONSerialization.jsonObject(with: b)) |
| 16 | } |
| 17 | @MainActor static func eventually(_ message: String, _ condition: () throws -> Bool) async throws { |
| 18 | for _ in 0..<100 { |
| 19 | if try condition() { return } |
| 20 | try await Task.sleep(for: .milliseconds(50)) |
| 21 | } |
| 22 | throw PetCoreError.invalid(message) |
| 23 | } |
| 24 | @MainActor static func main() async throws { |
| 25 | let args = CommandLine.arguments |
| 26 | let pet = URL(fileURLWithPath: args[1]), out = URL(fileURLWithPath: args[2]) |
| 27 | let bundle = Bundle(url: args.count > 3 ? URL(fileURLWithPath: args[3]) : pet.appendingPathComponent("macos/CodewhalePet.app"))! |
| 28 | let script = bundle.url(forResource: "pet-native", withExtension: "js")! |
| 29 | let tape = try String(contentsOf: bundle.url(forResource: "demo", withExtension: "jsonl")!, encoding: .utf8) |
| 30 | let points = try String(contentsOf: pet.appendingPathComponent("public/whale-points.tsv"), encoding: .utf8).split(separator: "\n").map { line -> (Double, Double) in |
| 31 | let v = line.split(separator: "\t").map { Double($0)! }; return (v[0], v[1]) |
| 32 | } |
| 33 | // Exercise the actual JavaScriptCore typed-array boundary, including |
| 34 | // partial and empty ranges, against the retained JSON transport. |
| 35 | let referenceContext = JSContext()! |
| 36 | referenceContext.evaluateScript(try String(contentsOf: script, encoding: .utf8)) |
| 37 | let pointJSON = String(decoding: try JSONSerialization.data(withJSONObject: points.map { [$0.0, $0.1] }), as: UTF8.self) |
| 38 | let reference = referenceContext.objectForKeyedSubscript("PetNative")!.construct(withArguments: [pointJSON])! |
| 39 | let audioCore = try PetNativeCore(points: points, bundle: script) |
| 40 | let audioVoices = [ |
| 41 | PetVoice(id: "tone", start: 0, duration: 0.44, frequency: 196, gain: 0.04, pan: -0.6, kind: "tone"), |
| 42 | PetVoice(id: "noise", start: 12.033, duration: 0.22, frequency: 740, gain: 0.05, pan: 0.4, kind: "noise"), |
| 43 | PetVoice(id: "long-clock", start: 600_000, duration: 0.3, frequency: 49, gain: 0.03, pan: 0, kind: "tone"), |
| 44 | ] |
| 45 | var pcmCases = 0 |
| 46 | for voice in audioVoices { |
| 47 | let voiceJSON = String(decoding: try JSONEncoder().encode([voice]), as: UTF8.self) |
| 48 | for rate in [8000, 48000, 96000] { |
| 49 | for offset in [-8, 0, 31] { |
| 50 | let start = max(0, Int((voice.start * Double(rate)).rounded(.down)) + offset), count = rate / 10 |
| 51 | let transferred = try audioCore.pcm(voice: voice, startSample: start, length: count, rate: rate) |
| 52 | let json = reference.invokeMethod("pcm", withArguments: [voiceJSON, start, count, rate])!.toString()! |
| 53 | try require(referenceContext.exception == nil, "Reference PCM failed") |
| 54 | let expected = try JSONDecoder().decode([[Float]].self, from: Data(json.utf8)) |
| 55 | try require(transferred.map { $0.map(\.bitPattern) } == expected.map { $0.map(\.bitPattern) }, "Typed PCM samples differ from JSON at \(rate) Hz / \(offset)") |
| 56 | pcmCases += 1 |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | try require(audioCore.pcm(voice: audioVoices[0], startSample: 0, length: 0, rate: 48000) == [[], []], "Empty PCM range rejected") |
| 61 | try reject({ _ = try audioCore.pcm(voice: audioVoices[0], startSample: -1, length: 4, rate: 48000) }, "Invalid PCM range accepted") |
| 62 | let pcmRoot = out.appendingPathComponent("apple-pcm-fixture-" + UUID().uuidString, isDirectory: true) |
| 63 | try FileManager.default.createDirectory(at: pcmRoot, withIntermediateDirectories: true) |
| 64 | let originalScript = try String(contentsOf: script, encoding: .utf8) |
| 65 | for (index, response) in ["null", "[new Float64Array(n), new Float64Array(n)]", "[new Float32Array(n + 1), new Float32Array(n)]", "[new Float32Array(n).fill(NaN), new Float32Array(n)]"].enumerated() { |
| 66 | let invalid = pcmRoot.appendingPathComponent("invalid-\(index).js") |
| 67 | try (originalScript + "\nPetNative.prototype.pcmChannels = function(v, s, n, r) { return " + response + "; };\n").write(to: invalid, atomically: true, encoding: .utf8) |
| 68 | let badCore = try PetNativeCore(points: points, bundle: invalid) |
| 69 | try reject({ _ = try badCore.pcm(voice: audioVoices[0], startSample: 0, length: 4, rate: 48000) }, "Malformed PCM channel accepted") |
| 70 | } |
| 71 | print("PASS Apple PCM transfer: \(pcmCases) exact tone/noise/long-clock sample ranges, empty input and malformed-buffer rejection") |
| 72 | |
| 73 | for input in ["", tape] { |
| 74 | let original = try PetNativeCore(points: points, bundle: script, tape: input) |
| 75 | for i in 0..<750 { |
| 76 | if i == 615 { try original.interact(food: true) } |
| 77 | try original.tick(motion: i % 90 < 60) |
| 78 | } |
| 79 | try original.interact(food: false, x: -0.3, y: 0.2) |
| 80 | let saved = try original.recording(checkpoint: true) |
| 81 | let restored = try PetNativeCore(points: points, bundle: script, saved: saved) |
| 82 | try require(petDigest(restored.sim) == original.frame.digest, "Swift pose changed at restore") |
| 83 | try require(same(saved, restored.recording(checkpoint: true)), "World checkpoint changed at restore") |
| 84 | for i in 0..<240 { |
| 85 | let a = try original.tick(motion: i % 65 < 40), b = try restored.tick(motion: i % 65 < 40) |
| 86 | try require(a.digest == b.digest && petDigest(restored.sim) == b.digest, "Restored Swift physics diverged at \(i)") |
| 87 | try require(same(original.recording(checkpoint: true), restored.recording(checkpoint: true)), "Restored world, score or journal diverged at \(i)") |
| 88 | } |
| 89 | var bad = try JSONSerialization.jsonObject(with: saved) as! [String: Any] |
| 90 | var checkpoint = bad["checkpoint"] as! [String: Any] |
| 91 | checkpoint["random"] = -1; bad["checkpoint"] = checkpoint |
| 92 | let damaged = try JSONSerialization.data(withJSONObject: bad) |
| 93 | try reject({ _ = try PetNativeCore(points: points, bundle: script, saved: damaged) }, "Malformed checkpoint accepted") |
| 94 | print("PASS exact Apple checkpoint + 240 mixed-motion continuation frames, interactions and score: \(input.isEmpty ? "wild" : "demo pod")") |
| 95 | } |
| 96 | let human = tape.split(separator: "\n").first { line in |
| 97 | let value = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any] |
| 98 | return value?["channel"] as? String == "human" && value?["waiting"] as? Bool == true |
| 99 | }! |
| 100 | let live = try PetNativeCore(points: points, bundle: script, live: true) |
| 101 | try live.accept(packet: String(human)) |
| 102 | for _ in 0..<12 { try live.tick(motion: true) } |
| 103 | try require(live.frame.state.observed >= 0.92 && live.frame.needs != "none", "Live fixture never observed a human request") |
| 104 | let resumed = try PetNativeCore(points: points, bundle: script, live: true, saved: live.recording(checkpoint: true)) |
| 105 | try require(resumed.frame.state.observed == 0 && resumed.frame.needs == "none", "Old live request survived restoration") |
| 106 | try require(petDigest(resumed.sim) == resumed.frame.digest, "Live resume left Swift geometry behind") |
| 107 | print("PASS native live resume: preserved history, unknown interval and no stale human request") |
| 108 | |
| 109 | let root = out.appendingPathComponent("apple-checkpoint-fixture-" + UUID().uuidString, isDirectory: true) |
| 110 | try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) |
| 111 | let liveSuite = "dev.shannonlabs.pet-live-test." + UUID().uuidString |
| 112 | let liveDefaults = UserDefaults(suiteName: liveSuite)! |
| 113 | defer { liveDefaults.removePersistentDomain(forName: liveSuite) } |
| 114 | liveDefaults.set("file", forKey: "pet.source") |
| 115 | let liveFile = root.appendingPathComponent("local.jsonl") |
| 116 | func packet(_ sequence: Int) throws -> Data { |
| 117 | var value = try JSONSerialization.jsonObject(with: Data(human.utf8)) as! [String: Any] |
| 118 | value["sequence"] = sequence; value["simTimeMs"] = sequence * 400 |
| 119 | return try JSONSerialization.data(withJSONObject: value) + Data("\n".utf8) |
| 120 | } |
| 121 | func append(_ sequence: Int) throws { |
| 122 | let handle = try FileHandle(forWritingTo: liveFile); defer { try? handle.close() } |
| 123 | try handle.seekToEnd(); try handle.write(contentsOf: packet(sequence)) |
| 124 | } |
| 125 | try packet(40).write(to: liveFile) |
| 126 | let following = PetHost(points: points, bundle: bundle, defaults: liveDefaults, storageDirectory: root.appendingPathComponent("live-host")) |
| 127 | defer { following.suspend(true) } |
| 128 | following.setLiveFile(liveFile) |
| 129 | func observations() throws -> Int { |
| 130 | let recording = try JSONSerialization.jsonObject(with: following.core!.recording()) as! [String: Any] |
| 131 | return (recording["tape"] as! [[String: Any]]).filter { ($0["observed"] as? Double ?? 0) > 0 }.count |
| 132 | } |
| 133 | try require(observations() == 0, "Existing live file replayed an old request") |
| 134 | try append(41) |
| 135 | try await eventually("File append was not delivered to the actual Apple host") { try observations() == 1 } |
| 136 | for _ in 0..<12 { try following.core!.tick(motion: true) } |
| 137 | try require(following.core!.frame.state.channel == "human", "Fresh file input did not reach the visible world") |
| 138 | following.suspend(true); try append(42); following.suspend(false) |
| 139 | try require(following.core!.frame.needs == "none" && following.core!.frame.state.observed == 0, "Suspended request survived resume") |
| 140 | try require(petDigest(following.core!.sim) == following.core!.frame.digest, "Resume did not update native geometry") |
| 141 | try require(observations() == 1, "Background bytes became a fresh observation") |
| 142 | try append(43) |
| 143 | try await eventually("Resumed file did not continue") { try observations() == 2 } |
| 144 | for _ in 0..<12 { try following.core!.tick(motion: true) } |
| 145 | let truncated = try FileHandle(forWritingTo: liveFile) |
| 146 | try truncated.truncate(atOffset: 0); try truncated.write(contentsOf: packet(0)); try truncated.close() |
| 147 | try await Task.sleep(for: .milliseconds(150)) |
| 148 | try require(observations() == 2, "Producer restart replayed its baseline") |
| 149 | try packet(1).write(to: liveFile, options: .atomic) |
| 150 | try await eventually("In-place restart followed by atomic replacement was ignored") { try observations() == 3 } |
| 151 | for _ in 0..<12 { try following.core!.tick(motion: true) } |
| 152 | try FileManager.default.removeItem(at: liveFile) |
| 153 | try await eventually("Missing file was not reported") { following.message.contains("unavailable") } |
| 154 | try packet(100).write(to: liveFile) |
| 155 | try await Task.sleep(for: .milliseconds(150)) |
| 156 | try require(observations() == 3, "Recreated file did not establish a baseline") |
| 157 | try append(101) |
| 158 | try await eventually("Recreated producer did not continue") { try observations() == 4 } |
| 159 | following.suspend(true) |
| 160 | print("PASS actual Apple live file: stale attachment, append, pause/resume, in-place restart, atomic replacement and deletion/recreation") |
| 161 | |
| 162 | let files = try PetHabitatStore(directory: root, source: "wild") |
| 163 | let stale = try PetHabitatStore(directory: root, source: "wild") |
| 164 | try require(files.load() == nil && stale.load() == nil, "Fixture was not empty") |
| 165 | try files.save(Data("first".utf8)) |
| 166 | try reject({ try stale.save(Data("stale".utf8)) }, "A stale writer overwrote the habitat") |
| 167 | let path = root.appendingPathComponent("wild.json") |
| 168 | try require(String(contentsOf: path, encoding: .utf8) == "first", "Stale writer changed the file") |
| 169 | let permission = try FileManager.default.attributesOfItem(atPath: path.path)[.posixPermissions] as! NSNumber |
| 170 | try require(permission.intValue == 0o600, "Habitat is not private") |
| 171 | try Data("external".utf8).write(to: path) |
| 172 | try reject({ try files.save(Data("lost".utf8)) }, "External edit was overwritten") |
| 173 | let outside = root.appendingPathComponent("original") |
| 174 | try FileManager.default.moveItem(at: path, to: outside) |
| 175 | try FileManager.default.createSymbolicLink(at: path, withDestinationURL: outside) |
| 176 | try reject({ _ = try files.load() }, "Symbolic link accepted") |
| 177 | try FileManager.default.removeItem(at: path) |
| 178 | try FileManager.default.linkItem(at: outside, to: path) |
| 179 | try reject({ _ = try files.load() }, "Hard link accepted") |
| 180 | try FileManager.default.removeItem(at: path) |
| 181 | try Data(count: PetHabitatStore.limit + 1).write(to: path) |
| 182 | try reject({ _ = try files.load() }, "Oversize file accepted") |
| 183 | try FileManager.default.removeItem(at: root.appendingPathComponent("wild.lock")) |
| 184 | let replacement = try PetHabitatStore(directory: root, source: "wild") |
| 185 | _ = replacement |
| 186 | try reject({ try files.save(Data("split lock".utf8)) }, "Replaced writer lock accepted") |
| 187 | try require((try FileManager.default.attributesOfItem(atPath: path.path)[.size] as! NSNumber).intValue == PetHabitatStore.limit + 1, "Rejected input was modified") |
| 188 | let fifo = try PetHabitatStore(directory: root, source: "demo") |
| 189 | try FileManager.default.removeItem(at: root.appendingPathComponent("demo.lock")) |
| 190 | try require(mkfifo(root.appendingPathComponent("demo.lock").path, 0o600) == 0, "Could not create the sealed FIFO fixture") |
| 191 | try reject({ _ = try fifo.load() }, "FIFO replacement blocked or passed the lock guard") |
| 192 | print("PASS native private storage: stale and external writers, symbolic/hard links, size bound, replaced lock and nonblocking FIFO rejection") |
| 193 | |
| 194 | let hostDir = root.appendingPathComponent("host") |
| 195 | let suite = "dev.shannonlabs.pet-checkpoint-test." + UUID().uuidString |
| 196 | let defaults = UserDefaults(suiteName: suite)! |
| 197 | defaults.set("wild", forKey: "pet.source") |
| 198 | defer { defaults.removePersistentDomain(forName: suite) } |
| 199 | let host = PetHost(points: points, bundle: bundle, defaults: defaults, storageDirectory: hostDir) |
| 200 | host.suspend(true) |
| 201 | for _ in 0..<180 { try host.core!.tick(motion: true) } |
| 202 | let wildTime = host.core!.frame.timeMs, wildDigest = petDigest(host.core!.sim) |
| 203 | try require(host.selectSource(.demo), "Saved world could not switch") |
| 204 | for _ in 0..<120 { try host.core!.tick(motion: false) } |
| 205 | let demoTime = host.core!.frame.timeMs |
| 206 | try require(host.selectSource(.wild), "Saved world could not switch") |
| 207 | try require(host.core!.frame.timeMs == wildTime && petDigest(host.core!.sim) == wildDigest, "Source switch reset the wild habitat") |
| 208 | try require(host.selectSource(.demo), "Saved world could not switch") |
| 209 | try require(host.core!.frame.timeMs == demoTime, "Source switch reset the demo habitat") |
| 210 | host.suspend(true) |
| 211 | let reopened = PetHost(points: points, bundle: bundle, defaults: defaults, storageDirectory: hostDir) |
| 212 | reopened.suspend(true) |
| 213 | try require(reopened.core!.frame.timeMs == demoTime, "New host did not reopen its selected source") |
| 214 | print("PASS actual Apple host: separate wild/demo checkpoints survive source switching and a new host") |
| 215 | |
| 216 | // Force a real optimistic-revision failure while the visit has newer |
| 217 | // in-memory progress, then exercise the actual host export/recovery path. |
| 218 | for _ in 0..<30 { try reopened.core!.tick(motion: true) } |
| 219 | reopened.interact(food: true) |
| 220 | let current = reopened.core!, currentData = try current.recording(checkpoint: true) |
| 221 | let external = Data("external writer kept".utf8) |
| 222 | try external.write(to: hostDir.appendingPathComponent("demo.json")) |
| 223 | try require(!reopened.selectSource(.wild), "Failed save allowed source switching") |
| 224 | try require(reopened.source == .demo && defaults.string(forKey: "pet.source") == "demo", "Failed switch changed the source or preference") |
| 225 | try require(reopened.core === current && same(currentData, current.recording(checkpoint: true)), "Failed switch lost the current world") |
| 226 | let exported = root.appendingPathComponent("unsaved-visit.json") |
| 227 | try reopened.exportRecording(to: exported) |
| 228 | let exportedData = try Data(contentsOf: exported) |
| 229 | try require(same(exportedData, currentData), "Export lost the current pose, score or pending input") |
| 230 | let retained = try PetNativeCore(points: points, bundle: script, saved: exportedData) |
| 231 | try require(retained.frame.timeMs == current.frame.timeMs && retained.frame.digest == current.frame.digest, "Export did not restore the unsaved visit") |
| 232 | try require(Data(contentsOf: hostDir.appendingPathComponent("demo.json")) == external, "Recovery changed the other writer's file") |
| 233 | try require(reopened.selectSource(.wild, discardingUnsaved: true), "Explicit leave could not open another world") |
| 234 | print("PASS actual Apple host: save conflict blocks source/preference replacement; export restores the exact unsaved visit; explicit leave works") |
| 235 | defaults.set("demo", forKey: "pet.source") |
| 236 | |
| 237 | let corruptDir = root.appendingPathComponent("corrupt") |
| 238 | try FileManager.default.createDirectory(at: corruptDir, withIntermediateDirectories: true) |
| 239 | let corrupt = Data("{invalid habitat}".utf8) |
| 240 | try corrupt.write(to: corruptDir.appendingPathComponent("demo.json")) |
| 241 | let recovery = PetHost(points: points, bundle: bundle, defaults: defaults, storageDirectory: corruptDir) |
| 242 | recovery.suspend(true); recovery.interact(food: true) |
| 243 | try require(recovery.core != nil && !recovery.persistenceMessage.isEmpty, "Invalid file has no recovery notice") |
| 244 | try require(Data(contentsOf: corruptDir.appendingPathComponent("demo.json")) == corrupt, "Recovery overwrote the damaged habitat") |
| 245 | print("PASS actual Apple host: damaged recording is retained after suspension and interaction") |
| 246 | |
| 247 | let legacyDir = root.appendingPathComponent("legacy") |
| 248 | defaults.set("wild", forKey: "pet.source"); defaults.set(3.0, forKey: "pet.elapsed"); defaults.set("[]", forKey: "pet.interactions") |
| 249 | let legacy = PetHost(points: points, bundle: bundle, defaults: defaults, storageDirectory: legacyDir) |
| 250 | legacy.suspend(true) |
| 251 | for _ in 0..<1000 { |
| 252 | if FileManager.default.fileExists(atPath: legacyDir.appendingPathComponent("wild.json").path) { break } |
| 253 | await Task.yield() |
| 254 | } |
| 255 | try require(legacy.core?.frame.timeMs == 3000, "Legacy migration lost its elapsed time") |
| 256 | try require(FileManager.default.fileExists(atPath: legacyDir.appendingPathComponent("wild.json").path), "Legacy migration did not save a checkpoint") |
| 257 | try require(defaults.object(forKey: "pet.elapsed") == nil && defaults.object(forKey: "pet.interactions") == nil, "Legacy preferences were not retired after atomic save") |
| 258 | print("PASS actual Apple host: legacy preferences migrate once after a successful checkpoint save") |
| 259 | |
| 260 | let longDir = root.appendingPathComponent("long") |
| 261 | try FileManager.default.createDirectory(at: longDir, withIntermediateDirectories: true) |
| 262 | try FileManager.default.copyItem(at: out.appendingPathComponent("long-habitat.json"), to: longDir.appendingPathComponent("live.json")) |
| 263 | defaults.set("file", forKey: "pet.source") |
| 264 | let start = ContinuousClock.now |
| 265 | let long = PetHost(points: points, bundle: bundle, defaults: defaults, storageDirectory: longDir) |
| 266 | long.suspend(true) |
| 267 | try require(long.core!.frame.timeMs >= 7_200_000 && long.core!.frame.state.observed == 0, "Large native habitat did not resume unknown") |
| 268 | try require(long.persistenceMessage.isEmpty, "Large native habitat failed to save") |
| 269 | let activeData = try Data(contentsOf: longDir.appendingPathComponent("live.json")) |
| 270 | try require(activeData.count < 1024 * 1024 && long.archives.count == 1, "Long history was not archived before compacting the active habitat") |
| 271 | let archived = try long.archivedRecording(long.archives[0]) |
| 272 | try require(archived.count > 5 * 1024 * 1024, "Earlier telemetry was not retained") |
| 273 | let compact = try PetNativeCore(points: points, bundle: script, saved: activeData) |
| 274 | try require(compact.frame.digest == long.core!.frame.digest && compact.frame.timeMs == long.core!.frame.timeMs, "Compaction changed the current world") |
| 275 | for _ in 0..<60 { try require(compact.tick(motion: false).digest == long.core!.tick(motion: false).digest, "Compacted continuation diverged") } |
| 276 | print("PASS actual Apple host: two-hour history archived (\(archived.count) bytes), active habitat \(activeData.count) bytes, exact continuation; \(start.duration(to: .now))") |
| 277 | |
| 278 | let conflictDir = root.appendingPathComponent("archive-conflict") |
| 279 | try FileManager.default.createDirectory(at: conflictDir, withIntermediateDirectories: true) |
| 280 | try FileManager.default.copyItem(at: out.appendingPathComponent("long-habitat.json"), to: conflictDir.appendingPathComponent("live.json")) |
| 281 | let conflict = PetHost(points: points, bundle: bundle, defaults: defaults, storageDirectory: conflictDir) |
| 282 | let beforeConflict = try conflict.core!.recording(checkpoint: true) |
| 283 | try external.write(to: conflictDir.appendingPathComponent("live.json")) |
| 284 | conflict.suspend(true) |
| 285 | try require(!conflict.persistenceMessage.isEmpty && conflict.archives.isEmpty, "A conflicted archive was committed") |
| 286 | try require(same(beforeConflict, conflict.core!.recording(checkpoint: true)), "Failed archive retired live history") |
| 287 | try require(Data(contentsOf: conflictDir.appendingPathComponent("live.json")) == external, "Archiving replaced another writer") |
| 288 | print("PASS actual Apple host: archive conflict preserves all live history and the other writer's file") |
| 289 | print("PASS 11 Apple checkpoint workflows; fixtures retained at \(root.path)") |
| 290 | } |
| 291 | } |
| 292 |