interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / Omega / tests / core-parity / main.swift

537 lines · 44615 bytes Raw Blame History
1import Foundation
2import CryptoKit
3// Parity of the Omega core (hopcore) against the Swift code Hop shipped up to 0.4.0, through the same host code
4// Hop uses (Sources/OmegaCore.swift and Sources/OmegaText.swift; the core to run is named by HOP_CORE).
5// names: fn hopfuzz against FuzzyReference, on this Mac's app names and queries derived from them
6// paths: fn fscore against FileScoreReference, on real paths under the home folder and terms derived from them
7// text: fn qlike, keyw, weba and alike against TextReference, on generated sentences, addresses and spellings
8// words: fn wdiff and pick against TextReference.corrections, on generated dictations and edited fields
9// board: fn lline, ltime and spans against the Swift Swarm code (SwarmReference), on generated and damaged board
10// lines, times, and posts with mentions and citations
11// status: the members' state, the whole picture and the graph (kind 7) against the same Swift Swarm code
12// Lines: CORE-PARITY names|paths|text|words|board|status same N different D, then the last line
13// CORE-PARITY same N different D. Exit 0 only when D is 0 and both parts matched enough cases to mean something.
14var seed: UInt64 = 0x9E3779B97F4A7C15
15extension Array { func shuffledBy(_ r: (Int) -> Int) -> [Element] { var a = self; var i = a.count - 1; while i > 0 { a.swapAt(i, r(i + 1)); i -= 1 }; return a } }
16func rnd(_ n: Int) -> Int { seed = seed &* 6364136223846793005 &+ 1442695040888963407; return Int((seed >> 33) % UInt64(max(1, n))) }
17
18// ---- names
19var names: [String] = []
20for root in ["/Applications", "/System/Applications", "/System/Applications/Utilities", NSHomeDirectory() + "/Applications", "/System/Library/CoreServices/Applications"] {
21 for f in (try? FileManager.default.contentsOfDirectory(atPath: root)) ?? [] where f.hasSuffix(".app") { names.append(String(f.dropLast(4))) }
22}
23names += ["Visual Studio Code", "Disk Safety", "Screen Sharing Remote Desktop Viewer", "Café Münster 2", "日本語 入力", "a", "ab", "A-B_C.d", " spaced out ", "naïve résumé", "Ünïcödé App", "x1 y2 z3", "éa", "Final Cut Pro", "1Password 7"]
24names = Array(Set(names)).sorted()
25var queries = Set<String>()
26for nm in names {
27 let c = Array(nm)
28 for k in 1...min(6, c.count) { queries.insert(String(c.prefix(k))) }
29 let ws = nm.split(whereSeparator: { !($0.isLetter || $0.isNumber) }).map(String.init)
30 for w in ws { for k in 1...min(5, w.count) { queries.insert(String(w.prefix(k))) } }
31 queries.insert(String(ws.compactMap(\.first)))
32 if ws.count > 1 { queries.insert(ws[0].prefix(3) + " " + ws[1].prefix(2)); queries.insert(ws[1].prefix(2) + " " + ws[0].prefix(2)); queries.insert(ws.joined(separator: " ")) }
33 if c.count >= 4 {
34 for _ in 0..<6 {
35 var t = Array(c.prefix(4 + rnd(4)))
36 let p = rnd(t.count - 1)
37 switch rnd(4) { case 0: t.swapAt(p, p + 1); case 1: t.remove(at: p); case 2: t.insert("q", at: p); default: t[p] = "z" }
38 queries.insert(String(t))
39 }
40 for _ in 0..<4 { var t: [Character] = []; var i = rnd(2); while i < c.count && t.count < 6 { t.append(c[i]); i += 1 + rnd(3) }; queries.insert(String(t)) }
41 let a = rnd(c.count - 2); queries.insert(String(c[a..<min(c.count, a + 2 + rnd(4))]))
42 }
43 queries.insert(" " + nm.prefix(3) + " "); queries.insert(nm.uppercased()); queries.insert(nm)
44}
45for q in ["", " ", "\t", "xyz", "zzzz", "a b c", " ", "é", "saf", "vsc", "code", "sri", "q", "ab cd", "1p", "日本", "入力"] { queries.insert(q) }
46let qs = queries.sorted()
47var cases: [(String, String)] = []
48for q in qs { for _ in 0..<14 { cases.append((q, names[rnd(names.count)])) } }
49for nm in names { for q in qs where rnd(40) == 0 || nm.lowercased().hasPrefix(q.lowercased().prefix(2)) && rnd(3) == 0 { cases.append((q, nm)) } }
50let got = OmegaCore.shared.scores(cases.map { OmegaCore.encode(query: $0.0, name: $0.1) })
51var nSame = 0, nDiff = 0, nMatched = 0
52for (i, (q, n)) in cases.enumerated() {
53 let sw = FuzzyReference.score(q, in: n)
54 if got[i] == sw { nSame += 1; if sw != nil { nMatched += 1 } }
55 else { nDiff += 1; if nDiff <= 12 { print("DIFF name q=[\(q)] n=[\(n)] swift=\(sw.map(String.init) ?? "nil") omega=\(got[i].map(String.init) ?? "nil")") } }
56}
57print("names \(names.count) queries \(qs.count) cases \(cases.count) matched \(nMatched)")
58print("CORE-PARITY names same \(nSame) different \(nDiff)")
59
60// ---- paths
61var paths: [String] = []
62let home = NSHomeDirectory()
63for root in [home + "/workspace", home + "/Documents", home + "/Desktop", "/Applications", "/usr/share"] {
64 guard let e = FileManager.default.enumerator(atPath: root) else { continue }
65 var k = 0
66 while let f = e.nextObject() as? String, k < 6000 {
67 if e.level > 4 { e.skipDescendants(); continue }
68 if f.hasPrefix(".") || f.contains("/.") { continue }
69 paths.append(root + "/" + f); k += 1
70 }
71}
72paths += ["/", "", "/a", "a", "/a/b/", "/A/B/C.TXT", "/tmp/Café Münster/résumé FINAL.pdf", "/x/日本語/入力 メモ.txt", "relative/dir/file name.md", "/a//b", "/only-folder/"]
73var pcases: [(String, [String])] = []
74for p in paths {
75 let low = p.lowercased(), name = (low as NSString).lastPathComponent, nc = Array(name)
76 let parts = low.split(separator: "/").map(String.init)
77 var sets: [[String]] = []
78 if nc.count >= 1 { sets.append([String(nc.prefix(1 + rnd(min(6, nc.count))))]) }
79 if nc.count >= 3 { let a = rnd(nc.count - 2); sets.append([String(nc[a..<min(nc.count, a + 2 + rnd(5))])]) }
80 sets.append([name])
81 if parts.count >= 2 { sets.append([String(parts[rnd(parts.count - 1)].prefix(4)), String(name.prefix(2))]) }
82 if parts.count >= 3 { sets.append([String(parts[0].prefix(3)), String(parts[1].prefix(3)), String(name.suffix(3))]) }
83 sets.append(["zqxj"]); sets.append([String(name.prefix(2)), "zqxj"])
84 let words = name.split(whereSeparator: { !($0.isLetter || $0.isNumber) }).map(String.init)
85 if words.count >= 2 { sets.append(words); sets.append([words[0], words[1]]) }
86 if rnd(50) == 0 { sets.append([]) }
87 if rnd(40) == 0 { sets.append([""]); sets.append([String(name.prefix(2)), ""]) }
88 for s in sets { pcases.append((p, s)) }
89}
90var pSame = 0, pDiff = 0, pMatched = 0, over = 0
91var byTerms: [[String]: [Int]] = [:]
92for (i, c) in pcases.enumerated() { byTerms[c.1, default: []].append(i) }
93var pgot = [Int?](repeating: nil, count: pcases.count)
94for (terms, idx) in byTerms { for (k, s) in zip(idx, OmegaCore.shared.fileScores(paths: idx.map { pcases[$0].0 }, terms: terms)) { pgot[k] = s } }
95for (i, (p, terms)) in pcases.enumerated() {
96 if p.utf8.count > 65535 { over += 1; continue }
97 let sw = FileScoreReference.score(path: p, terms: terms)
98 if pgot[i] == sw { pSame += 1; if sw != nil { pMatched += 1 } }
99 else { pDiff += 1; if pDiff <= 12 { print("DIFF path p=[\(p)] terms=\(terms) swift=\(sw.map(String.init) ?? "nil") omega=\(pgot[i].map(String.init) ?? "nil")") } }
100}
101print("paths \(paths.count) cases \(pcases.count) matched \(pMatched) over-limit \(over)")
102print("CORE-PARITY paths same \(pSame) different \(pDiff)")
103// ---- text decisions
104var texts = Set<String>(qs)
105for nm in names { texts.insert(nm); texts.insert(nm + "?"); texts.insert("what is " + nm); texts.insert("how " + nm) }
106let lead = ["what", "what's", "whats", "why", "how", "how's", "who", "who's", "whom", "whose", "when", "where", "which", "explain", "define", "translate", "summarize", "summarise", "describe", "the", "and", "open", "Why", "HOW", "whatever", "ho"]
107let filler = ["the", "and", "for", "with", "that", "this", "does", "can", "you", "have", "from", "about", "please", "make", "need", "just", "our", "my", "its", "not", "omega", "compiler", "radicle", "seed", "hop", "a", "is", "in", "self-test", "file_name", "v1.2.3", "naïve", "日本語", "Café", "x", "to", "do", "long-running", "re.do", "OMEGA", "Compiler"]
108let seps = [" ", " ", "\t", "\n", " \n ", "\u{00A0}", "\u{2003}", ", ", "/", "; "]
109for _ in 0..<12000 {
110 var t = rnd(3) == 0 ? "" : lead[rnd(lead.count)]
111 for _ in 0..<rnd(9) { t += (t.isEmpty ? "" : seps[rnd(seps.count)]) + filler[rnd(filler.count)] }
112 switch rnd(8) { case 0: t += "?"; case 1: t = " " + t + " \n"; case 2: t += " ?"; case 3: t = "?"; default: break }
113 texts.insert(t)
114}
115let ends = ["com", "org", "net", "io", "dev", "ai", "co", "edu", "gov", "xyz", "me", "us", "uk", "ca", "de", "tv", "gg", "app", "txt", "md", "COM", "c0m", ""]
116let hosts = ["example", "a", "my-site", "sub.example", "ex_ample", "EXAMPLE", "exämple", "-", "a..b", "", "localhost", "192.168.1.1", "notes", "x y"]
117let tails = ["", "/", "/docs", "/a/b?c=d#e", "//x", "/ space", ":8080/x", "?q=1"]
118let heads = ["", "https://", "http://", "HTTPS://", "https:/", "httpss://", "ftp://", "/", "//", " ", "http//", "https://https://"]
119for h in heads { for ho in hosts { for e in ends { for tl in tails { if rnd(3) == 0 { texts.insert(h + ho + (e.isEmpty ? "" : "." + e) + tl) } } } } }
120texts.insert(String(repeating: "a", count: 1990) + ".com"); texts.insert(String(repeating: "a", count: 2000) + ".com"); texts.insert("")
121var tSame = 0, tDiff = 0, tYes = 0
122for t in texts.sorted() {
123 let q1 = TextReference.questionLike(t), q2 = OmegaText.questionLike(t)
124 let k1 = TextReference.keywords(t), k2 = OmegaText.keywords(t)
125 let w1 = TextReference.webAddress(t), w2 = OmegaText.webAddress(t)
126 for (ok, what) in [(q1 == q2, "question \(q1) \(q2)"), (k1 == k2, "keywords \(k1) \(k2)"), (w1 == w2, "address \(w1 ?? "nil") \(w2 ?? "nil")")] {
127 if ok { tSame += 1 } else { tDiff += 1; if tDiff <= 12 { print("DIFF text [\(t.prefix(80))] swift then omega: \(what)") } }
128 }
129 if q1 { tYes += 1 }; if !k1.isEmpty { tYes += 1 }; if w1 != nil { tYes += 1 }
130}
131// How alike two spellings are (op 4): pairs of names, queries and near misses.
132var pairs: [(String, String)] = [("", ""), ("", "a"), ("a", ""), ("ORCID", "ocid"), ("Gandi", "gandhi"), (" -- ", "!!"), ("naïve", "naive"), ("日本語", "日本"), ("A-B", "ab")]
133for _ in 0..<9000 { pairs.append((qs[rnd(qs.count)], rnd(3) == 0 ? qs[rnd(qs.count)] : names[rnd(names.count)])) }
134var likes = 0
135for (x, y) in pairs {
136 let l1 = TextReference.likeness(x, y), l2 = OmegaText.likeness(x, y)
137 if l1 == l2 { tSame += 1 } else { tDiff += 1; if tDiff <= 12 { print("DIFF alike [\(x)] [\(y)] swift \(l1) omega \(l2)") } }
138 if l1 >= 0.5 { likes += 1 }
139}
140tYes += likes
141print("texts \(texts.count) decisions \(texts.count * 3) pairs \(pairs.count) alike \(likes) positive \(tYes)")
142print("CORE-PARITY text same \(tSame) different \(tDiff)")
143// ---- which words were corrected (kind 4 fn wdiff, and op 5 fn pick for which typed words are the fix)
144var vocab: [String] = ["ORCID", "ocid", "Gandi", "gandhi", "GrokBot", "grok", "bot", "Radicle", "radical", "Hello,", "hello", "(seed)", "seed.", "Ben.", "Ben", "file", "files", "send", "Send", "naive", "—", "...", "Σίσυφος", "ΟΔΟΣ", "e\u{301}cole", "école", "\u{301}abc", "it's", "its", "42", "4.2", "#tag", "tag"]
145vocab += filler
146vocab += lead
147for nm in names.prefix(80) { vocab += nm.split(separator: " ").map(String.init) }
148func word() -> String { vocab[rnd(vocab.count)] }
149func nearby(_ w: String) -> String {
150 var c = Array(w)
151 guard !c.isEmpty else { return "x" }
152 let at = rnd(c.count)
153 switch rnd(6) {
154 case 0: c[at] = "z"
155 case 1: c.remove(at: at)
156 case 2: c.insert("e", at: at)
157 case 3: return w.uppercased()
158 case 4: return w.capitalized + (rnd(2) == 0 ? "," : "")
159 default: c.swapAt(at, max(0, at - 1))
160 }
161 return c.isEmpty ? "x" : String(c)
162}
163let gaps = [" ", " ", "\n", "\t", " \n"]
164func joined(_ w: [String]) -> String { w.enumerated().map { ($0.offset == 0 ? "" : gaps[rnd(8) == 0 ? rnd(gaps.count) : 0]) + $0.element }.joined() }
165var wcases: [(String, String, String)] = [("", "", ""), ("a", "", ""), ("", "a b", "a c"), ("Send the file to Ben.", "Send the file to Ben.", "Send the file to Ben."),
166 ("my ocid is here", "Notes: my ocid is here ", "Notes: my ORCID Then I kept typing is here "), ("a b", "a b", "c d"), ("one", "one", "won"), ("x", "x x x", "x y x")]
167for round in 0..<16000 {
168 let nd = 1 + rnd(rnd(4) == 0 ? 30 : 9)
169 let d = (0..<nd).map { _ in word() }
170 let big = round % 400 == 0 // a long field: the line-up table is large, or over its limit
171 let pre = (0..<(big ? 200 + rnd(300) : rnd(8))).map { _ in word() }, post = (0..<(big ? 200 + rnd(300) : rnd(8))).map { _ in word() }
172 var field = pre + d + post
173 if rnd(12) == 0 { field += d } // the dictation stands twice: the last one counts
174 if rnd(25) == 0 { field = pre + post } // or it is not there
175 var after = field
176 let first = field.count >= pre.count + nd && rnd(12) != 0 ? max(0, field.count - nd - (field.count == pre.count + nd + post.count ? post.count : 0)) : 0
177 var edits = 1 + rnd(3)
178 if big { edits += 2 }
179 for e in 0..<edits {
180 guard !after.isEmpty else { break }
181 var at = rnd(4) == 0 || (big && e >= 1 && rnd(2) == 0) ? rnd(after.count) : min(after.count - 1, first + rnd(nd))
182 at = max(0, min(at, after.count - 1))
183 switch rnd(9) {
184 case 0, 1, 2: after[at] = nearby(after[at])
185 case 3:
186 let k = min(1 + rnd(3), after.count - at)
187 after.replaceSubrange(at..<(at + k), with: [nearby(after[at..<(at + k)].joined())])
188 case 4:
189 after.replaceSubrange(at..<(at + 1), with: [nearby(after[at]), word(), word()] + (rnd(2) == 0 ? [word(), word()] : []))
190 case 5: after.remove(at: at)
191 case 6: after.insert(word(), at: at)
192 case 7: after[at] = word()
193 default:
194 let k = min(1 + rnd(4), after.count - at)
195 after.replaceSubrange(at..<(at + k), with: (at..<(at + k)).map { nearby(after[$0]) })
196 }
197 }
198 wcases.append((joined(d), joined(field), joined(after)))
199}
200var wSame = 0, wDiff = 0, wYes = 0, fixes = 0
201for (d, b, a) in wcases {
202 let r1 = TextReference.corrections(dictated: d, before: b, after: a).map { $0.heard + "\u{1}" + $0.write }
203 let r2 = OmegaText.corrections(dictated: d, before: b, after: a).map { $0.heard + "\u{1}" + $0.write }
204 if r1 == r2 { wSame += 1 } else { wDiff += 1; if wDiff <= 12 { print("DIFF words d=[\(d.prefix(60))] b=[\(b.prefix(80))] a=[\(a.prefix(80))] swift=\(r1) omega=\(r2)") } }
205 if !r1.isEmpty { wYes += 1; fixes += r1.count }
206}
207print("fields \(wcases.count) with a fix \(wYes) fixes \(fixes)")
208print("CORE-PARITY words same \(wSame) different \(wDiff)")
209// ---- board lines and times (kind 5: fn lline and ltime) against the Swift Swarm code
210func bytes(_ s: String) -> [UInt8] { Array(s.utf8) }
211let times = ["2026-11-11T05:58:53Z", "2026-11-11 05:58", "2026-11-11", "2026-11-11T05:58:53.123456+05:30", "2026-11-11T05:58-0800", "1970-01-01T00:00+05:00", "1970-01-01",
212 "1969-12-31T00:00Z", "2026-13-01T00:00Z", "2026-11-11T25:00Z", "2026-11-11T05:58:61Z", "2026-02-29T12:00:00z", "2024-02-29 23:59:60", "2026-11-11T", "2026-11-11T0558",
213 "9999-12-31T23:59:59Z", "2026-1-1", "20261111", "", "2026-11-11T05:58:53.1234567890Z", "2026-11-11T05:58:53+2", "2026-11-11T05:58+24:00", "2026/11/11 05:58", "2026-11-11T05:5"]
214let who = ["hop-omega-core", "merge desk", "Manager(Aien)", "ng-vec-a64", "a", "all", "ALL lanes", "everyone", "Everyone", "@star", "José", "名前", "three word name", "four word name here",
215 String(repeating: "n", count: 64), String(repeating: "n", count: 65), "x+y", "to", "tom", "L1138", "all-hands", "alls", "allx", "every one", "@all"]
216let notes = ["", "", "", " (Claude Code, MacBook, L1138)", " (a (nested) one)", " (unclosed", " ()", " (x) extra words"]
217let bodies = ["LANDED on receipts", "", "see #12 and @star: done", "naïve café 日本語 text", "a: b: c", " spaced ", "to all + everyone", "x"]
218func aLine() -> String {
219 var l = ["", "", "", "- ", " ", "\t- "][rnd(6)] + times[rnd(4) == 0 ? rnd(times.count) : rnd(5)] + [" ", " ", " ", " ", "\t", ""][rnd(6)]
220 let ns = rnd(8) == 0 ? 2 + rnd(5) : 1
221 l += (0..<ns).map { _ in who[rnd(who.count)] + notes[rnd(notes.count)] }.joined(separator: rnd(6) == 0 ? "+" : " + ")
222 switch rnd(6) {
223 case 0, 1, 2:
224 let nr = rnd(10) == 0 ? 15 + rnd(5) : 1 + rnd(3)
225 l += " to " + (0..<nr).map { _ in who[rnd(who.count)] + notes[rnd(notes.count)] }.joined(separator: rnd(8) == 0 ? " +" : " + ")
226 case 3:
227 l += (0..<(1 + rnd(4))).map { _ in " @" + who[rnd(who.count)].replacingOccurrences(of: " ", with: "-") }.joined()
228 default: break
229 }
230 l += [": ", ": ", ": ", ":", " : ", " ", ""][rnd(7)] + bodies[rnd(bodies.count)] + ["", "", " ", "\r\n", "\n"][rnd(5)]
231 return l
232}
233var lines: [[UInt8]] = ["", "x", "2026-11-11T05:58:53Z", "2026-11-11T05:58:53Z ", "2026-11-11T05:58:53Z a", "2026-11-11T05:58:53Z a: b", "2026-11-11T05:58:53Za: b"].map(bytes)
234for _ in 0..<30000 {
235 var b = bytes(aLine())
236 if rnd(5) == 0, !b.isEmpty { // a damaged line
237 let at = rnd(b.count)
238 switch rnd(3) { case 0: b.remove(at: at); case 1: b.insert([32, 40, 41, 58, 43, 64, 116, 0xC3][rnd(8)], at: at); default: b[at] = [32, 58, 40, 0xA9][rnd(4)] }
239 }
240 lines.append(b)
241}
242for extra in [65500, 65534, 65535, 65536, 65537, 65538, 70000, 200000] { // lines at and over the limits, cut inside a character or not
243 for filler in ["é", "日", "x", "🙂"] {
244 var b = bytes("2026-11-11T05:58:53Z merge desk to all: ")
245 while b.count < extra { b += bytes(filler) }
246 lines.append(b); lines.append(Array(b.dropLast(1))); lines.append([120] + b)
247 }
248}
249for size in [32760, 32768, 32769, 40000] { for filler in ["é", "日", "x"] { var b = bytes("2026-11-11T05:58:53Z a: "); while b.count < size + 24 { b += bytes(filler) }; lines.append(b) } }
250lines.append(bytes("2026-11-11T05:58:53Z " + String(repeating: "h", count: 700) + ": text after a long header"))
251lines.append(bytes("2026-11-11T05:58:53Z " + String(repeating: "é", count: 40) + ": plain reading of a long first word"))
252func sameLine(_ a: SwarmReference.Line, _ b: SwarmCore.Line) -> Bool {
253 a.ok == b.ok && a.time == b.time && a.senders == b.senders && a.senderDetails == b.senderDetails && a.recipients == b.recipients
254 && a.recipientDetails == b.recipientDetails && a.all == b.all && a.text == b.text && a.clipped == b.clipped
255}
256var bSame = 0, bDiff = 0, bPosts = 0
257for l in lines {
258 let r1 = SwarmReference.parseLine(l), r2 = SwarmCore.parseLine(l)
259 if sameLine(r1, r2) { bSame += 1 } else {
260 bDiff += 1
261 if bDiff <= 10 { print("DIFF board [\(String(decoding: l.prefix(110), as: UTF8.self))] bytes \(l.count)\n swift \(r1.ok) \(r1.time) s=\(r1.senders.map { String(decoding: $0, as: UTF8.self) }) r=\(r1.recipients.count) all=\(r1.all) clip=\(r1.clipped) text=\(r1.text.count)\n omega \(r2.ok) \(r2.time) s=\(r2.senders.map { String(decoding: $0, as: UTF8.self) }) r=\(r2.recipients.count) all=\(r2.all) clip=\(r2.clipped) text=\(r2.text.count)") }
262 }
263 if r1.ok { bPosts += 1 }
264}
265var tCases = 0
266for tm in times {
267 for pre in ["", "x ", "- ", "at 2026-11-11 "] {
268 for post in ["", " ", "Z", " and more text that runs on for a while, past sixty-four bytes of everything", ":30", "+01"] {
269 let t = bytes(pre + tm + post)
270 for start in [0, pre.utf8.count, pre.utf8.count + 1, t.count, t.count + 5, -1] {
271 let a = SwarmReference.parseTime(t, start), b = SwarmCore.parseTime(t, start)
272 tCases += 1
273 if a.ok == b.ok && a.epoch == b.epoch && a.end == b.end && a.zoned == b.zoned { bSame += 1 } else {
274 bDiff += 1
275 if bDiff <= 10 { print("DIFF time [\(pre + tm + post)] at \(start): swift \(a.ok) \(a.epoch) \(a.end) \(a.zoned) omega \(b.ok) \(b.epoch) \(b.end) \(b.zoned)") }
276 }
277 }
278 }
279 }
280}
281// who a post calls and what it cites (kind 5 op 3: fn spans)
282let crew = ["lead", "parser-dev", "star", "worker-1", "worker-2", "worker-10", "José", "m0", "a", "narrator", "x-1", "all", "Lead-2", "名前", "bot_3", "worker"].map(bytes)
283let bits = ["@lead", "@Lead", "@lead,", "@leader", "x@lead", "é@lead", "@star.", "@worker", "@worker-1", "@worker-10", "@worker-1x", "@x", "@all", "@ALL!", "@allx", "@#parser", "@#Docs",
284 "@#main", "@#x-1", "@#" + String(repeating: "c", count: 24), "@#" + String(repeating: "c", count: 25), "@#9x", "@#", "@", "#12", "#99", "PR#7", "#0", "&#39;", "(#3)", "#4x", "#1234567890",
285 "#000000012", "@José", "@名前", "@m0", "@a", "@bot_3", "@Lead-2", "@lead-2", "mail bob@m0.example", "see", "the", "—", "日本語", "@@lead", "#", "@#parser-dev", "@narrator's", "@star@lead"]
286var sSame = 0, sDiff = 0, sMarked = 0, sCalled = 0
287var posts: [([UInt8], [[UInt8]], Int)] = [([], crew, 20), (bytes("@lead"), [], 20), (bytes(String(repeating: "@m0 ", count: 200)), [bytes("m0")], 0), (bytes(String(repeating: "@m0 ", count: 128)), [bytes("m0")], 0),
288 (bytes(String(repeating: "@m0 ", count: 127) + "@worker and more"), crew, 0), (bytes(String(repeating: "#1 ", count: 126) + "@worker @lead"), crew, 5)]
289for _ in 0..<20000 {
290 let text = (0..<(1 + rnd(12))).map { _ in bits[rnd(bits.count)] }.joined(separator: [" ", " ", ", ", "", "\n", "("][rnd(6)])
291 var names = crew
292 if rnd(6) == 0 { names = Array(crew.shuffledBy(rnd).prefix(1 + rnd(crew.count))) }
293 posts.append((bytes(text), names, [0, 20, 20, 1_000_000_000, -3][rnd(5)]))
294}
295posts.append((bytes("@n5 @n99 @n100 @n"), (0..<120).map { bytes("n\($0)") }, 0)) // more names than a swarm has members
296for (text, names, head) in posts {
297 let a = SwarmReference.spans(text, names: names, head: head), b = SwarmCore.spans(text, names: names, head: head)
298 if a.flat == b.flat && a.clipped == b.clipped { sSame += 1 } else {
299 sDiff += 1
300 if sDiff <= 10 { print("DIFF spans [\(String(decoding: text.prefix(100), as: UTF8.self))] names \(names.count) head \(head)\n swift \(a.flat.prefix(24)) \(a.clipped)\n omega \(b.flat.prefix(24)) \(b.clipped)") }
301 }
302 if !a.flat.isEmpty { sMarked += 1 }
303 // who the post addresses (kind 5 op 4: fn addr), from the same parts
304 let chans = ["parser", "docs", "*", "main", "Docs", "x-1", "here", "c"].map(bytes)
305 let mcount = rnd(4) == 0 ? rnd(names.count + 3) : names.count
306 let roles = (0..<mcount).map { _ in rnd(3) }
307 let lists: [[[UInt8]]] = (0..<(rnd(3) == 0 ? rnd(mcount + 1) : mcount)).map { _ in rnd(2) == 0 ? [] : (0..<(1 + rnd(3))).map { _ in chans[rnd(chans.count)] } }
308 var flat = a.flat
309 if rnd(12) == 0 { flat += [rnd(50), rnd(9) - 2, rnd(6), rnd(140) - 5]; if rnd(2) == 0 { flat.append(7) } }
310 let to = (0..<rnd(4)).map { _ in rnd(mcount + 4) - 2 }
311 let sender = rnd(mcount + 3) - 1, toAll = rnd(5) == 0
312 let x = SwarmReference.address(text: text, spans: flat, sender: sender, headerTo: to, headerAll: toAll, roles: roles, channels: lists)
313 let y = SwarmCore.address(text: text, spans: flat, sender: sender, headerTo: to, headerAll: toAll, roles: roles, channels: lists)
314 if x.direct == y.direct && x.all == y.all { sSame += 1 } else {
315 sDiff += 1
316 if sDiff <= 10 { print("DIFF address [\(String(decoding: text.prefix(80), as: UTF8.self))] members \(mcount) sender \(sender) to \(to): swift \(x.direct) \(x.all) omega \(y.direct) \(y.all)") }
317 }
318 if !x.direct.isEmpty { sCalled += 1 }
319}
320bSame += sSame; bDiff += sDiff
321// whole boards (kind 6: fn asm): members, joined spellings, who each post is from and to
322let agents = ["merge-desk", "omp-queen-spark", "merge desk", "Manager(Aien)", "hop/Worker", "Worker", "ng/Worker", "lane/star", "star", "Star", "@star", "narrator", "ng-vec-a64",
323 "hop-omega-core", "spark", "MacBook", "L1138", "José", "a b c", "x/y/z", "z", "ALL", "everyone", "lead"]
324func boardLine(_ pool: [String]) -> String {
325 func one() -> String {
326 var s = pool[rnd(pool.count)]
327 switch rnd(7) {
328 case 0: s += " (" + pool[rnd(pool.count)] + ")"
329 case 1: s += " (" + pool[rnd(pool.count)] + ", " + pool[rnd(pool.count)] + ", L1138)"
330 case 2: s += " (Claude Code, MacBook, L11/L12)"
331 case 3: s += " (" + (0..<10).map { _ in pool[rnd(pool.count)] }.joined(separator: ",") + ")"
332 default: break
333 }
334 return s
335 }
336 if rnd(14) == 0 { return ["", "not a post", "## heading", "2026-11-11 no colon here"][rnd(4)] }
337 var l = "2026-11-\(10 + rnd(20))T0\(rnd(10)):1\(rnd(10)):00Z " + (0..<(rnd(7) == 0 ? 2 + rnd(4) : 1)).map { _ in one() }.joined(separator: " + ")
338 if rnd(3) != 0 { l += " to " + (0..<(rnd(9) == 0 ? 17 + rnd(3) : 1 + rnd(3))).map { _ in one() }.joined(separator: " + ") }
339 return l + ": post text @star #3"
340}
341func sameBoard(_ a: SwarmReference.Board, _ b: SwarmCore.Board) -> Bool {
342 a.names == b.names && a.details == b.details && a.alsoCalled == b.alsoCalled && a.postSeq == b.postSeq && a.postTime == b.postTime && a.postSender == b.postSender
343 && a.postSenderName == b.postSenderName && a.postWith == b.postWith && a.postTo == b.postTo && a.postAll == b.postAll && a.postText == b.postText && a.lines == b.lines
344 && a.olderLinesDropped == b.olderLinesDropped && a.skippedLines == b.skippedLines && a.clippedLines == b.clippedLines && a.membersDropped == b.membersDropped
345 && a.spellingsDropped == b.spellingsDropped
346}
347var boards: [[[UInt8]]] = [[], [bytes("x")], [bytes("2026-11-11T05:58:53Z merge-desk (omp-queen-spark) to all: a"), bytes("2026-11-11T05:59:53Z omp-queen-spark (merge desk) to Worker: b"), bytes("2026-11-11T06:00:00Z hop/Worker to merge desk: c")]]
348for _ in 0..<1200 {
349 let pool = rnd(3) == 0 ? agents : Array(agents.shuffledBy(rnd).prefix(3 + rnd(8)))
350 boards.append((0..<(1 + rnd(40))).map { _ in bytes(rnd(10) == 0 ? aLine() : boardLine(pool)) })
351}
352let crowd = (0..<260).map { "agent-\($0)" }
353boards.append((0..<450).map { bytes("2026-11-11T05:58:53Z \(crowd[$0 % 260]) to \(crowd[($0 * 7) % 260]) + \(crowd[($0 * 3) % 130]): n\($0)") }) // over 400 lines, 192 spellings, 96 members
354boards.append((0..<120).map { bytes("2026-11-11T05:58:53Z \(crowd[$0]) (\(crowd[$0 + 120])): n") } + (0..<120).map { bytes("2026-11-11T06:00:00Z \(crowd[$0 + 120]) to all: m") })
355var aSame = 0, aDiff = 0, aMembers = 0, aJoined = 0
356for (bi, lns) in boards.enumerated() {
357 let x = SwarmReference.assemble(lines: lns, firstSeq: 1 + bi % 5), y = SwarmCore.assemble(lines: lns, firstSeq: 1 + bi % 5)
358 if sameBoard(x, y) { aSame += 1 } else {
359 aDiff += 1
360 if aDiff <= 6 {
361 print("DIFF board \(bi) lines \(lns.count): swift members \(x.names.map { String(decoding: $0, as: UTF8.self) }) also \(x.alsoCalled.map { String(decoding: $0, as: UTF8.self) }) posts \(x.postSender.count) sender \(x.postSender.prefix(12)) dropped \(x.membersDropped) \(x.spellingsDropped) skipped \(x.skippedLines)")
362 print(" omega members \(y.names.map { String(decoding: $0, as: UTF8.self) }) also \(y.alsoCalled.map { String(decoding: $0, as: UTF8.self) }) posts \(y.postSender.count) sender \(y.postSender.prefix(12)) dropped \(y.membersDropped) \(y.spellingsDropped) skipped \(y.skippedLines)")
363 for l in lns.prefix(6) { print(" | " + String(decoding: l.prefix(150), as: UTF8.self)) }
364 }
365 }
366 aMembers += x.names.count; aJoined += x.alsoCalled.filter { !$0.isEmpty }.count
367}
368bSame += aSame; bDiff += aDiff
369print("boards \(boards.count) members \(aMembers) of them with a second spelling \(aJoined)")
370print("board lines \(lines.count) posts \(bPosts) times \(tCases) texts \(posts.count) with marks \(sMarked) addressing someone \(sCalled)")
371print("CORE-PARITY board same \(bSame) different \(bDiff)")
372// ---- the members' state and the graph (kind 7) against the Swift Swarm code
373var uSame = 0, uDiff = 0, uCases = 0
374func tally(_ ok: Bool, _ what: @autoclosure () -> String) { uCases += 1; if ok { uSame += 1 } else { uDiff += 1; if uDiff <= 12 { print("DIFF status " + what()) } } }
375let nums = [-2, -1, 0, 1, 2, 3, 4, 5, 59, 60, 61, 599, 600, 601, 899, 900, 901, 1_762_840_000, 1_762_840_600, 1_762_840_601]
376func num() -> Int { nums[rnd(nums.count)] }
377for _ in 0..<4000 {
378 let a = num(), b = num(), c = num(), d = num(), k = rnd(2) == 0, h = rnd(2) == 0
379 let tu = rnd(4) - 1, wk = rnd(5) - 1
380 tally(SwarmReference.state(killed: k, turn: tu, wake: wk, hasRoster: h, lastPostAge: a) == SwarmCore.state(killed: k, turn: tu, wake: wk, hasRoster: h, lastPostAge: a), "state \(k) \(tu) \(wk) \(h) \(a)")
381 let stt = rnd(5), fl = rnd(5)
382 tally(SwarmReference.attention(state: stt, failure: fl, idleSeconds: b) == SwarmCore.attention(state: stt, failure: fl, idleSeconds: b), "attention \(stt) \(fl) \(b)")
383 tally(SwarmReference.unread(head: a, lastRead: b) == SwarmCore.unread(head: a, lastRead: b), "unread \(a) \(b)")
384 tally(SwarmReference.group(state: stt, attention: fl, asksYou: k, waitingOn: h) == SwarmCore.group(state: stt, attention: fl, asksYou: k, waitingOn: h), "group \(stt) \(fl) \(k) \(h)")
385 let s1 = rnd(4) - 1, s2 = rnd(4) - 1
386 tally(SwarmReference.startsGroup(previousSender: s1, previousTime: c, sender: s2, time: d) == SwarmCore.startsGroup(previousSender: s1, previousTime: c, sender: s2, time: d), "startsGroup \(s1) \(c) \(s2) \(d)")
387 let lk = rnd(6), ls = rnd(4)
388 tally(SwarmReference.failure(lastKind: lk, lastStatus: ls, idleSeconds: a, quota: k) == SwarmCore.failure(lastKind: lk, lastStatus: ls, idleSeconds: a, quota: k), "failure \(lk) \(ls) \(a) \(k)")
389 let cn = rnd(40) - 2, hv = rnd(40) - 2
390 tally(SwarmReference.weightStep(count: cn, heaviest: hv) == SwarmCore.weightStep(count: cn, heaviest: hv), "weightStep \(cn) \(hv)")
391}
392for round in 0..<6000 {
393 var n = rnd(14)
394 if round % 1500 == 7 { n = 3000 }
395 var kinds = (0..<n).map { _ in [1, 2, 2, 2, 3, 0, 4, 5][rnd(8)] }
396 if round % 1500 == 7 { for i in (n - 300)..<n { kinds[i] = 2 } }
397 let statuses = (0..<(rnd(15) == 0 ? n + 1 : n)).map { _ in rnd(4) }
398 let tools = (0..<n).map { _ in rnd(5) - 1 }, waits = (0..<n).map { _ in rnd(5) - 1 }, labelled = (0..<(rnd(15) == 0 ? max(0, n - 1) : n)).map { _ in rnd(2) }
399 tally(SwarmReference.turn(kinds: kinds, statuses: statuses, tools: tools, waits: waits) == SwarmCore.turn(kinds: kinds, statuses: statuses, tools: tools, waits: waits), "turn \(kinds) \(statuses) \(tools) \(waits)")
400 tally(SwarmReference.activityStep(kinds: kinds, waits: waits, labelled: labelled) == SwarmCore.activityStep(kinds: kinds, waits: waits, labelled: labelled), "activityStep \(kinds) \(waits) \(labelled)")
401}
402let qbits = ["RESOURCE_EXHAUSTED", "quota", "Quota exceeded", "rate limit", "rate-limit", "RateLimit", "exhausted your capacity", "429", "x429", "4290", "(429)", "é429", "error", "rate limit", "quo ta", "capacity", "", "日本", "HTTP 429 Too Many"]
403var qtexts: [[UInt8]] = [[], bytes("429"), bytes("4"), bytes("42")]
404for _ in 0..<3000 { qtexts.append(bytes((0..<(1 + rnd(5))).map { _ in qbits[rnd(qbits.count)] }.joined(separator: [" ", "", ": ", "\n"][rnd(4)]))) }
405for at in [32740, 32760, 32765, 32766, 32767, 32768, 32769, 32790] { for w in ["quota", "429", "exhausted your capacity"] { qtexts.append([UInt8](repeating: 120, count: at) + bytes(w)); qtexts.append([UInt8](repeating: 32, count: at) + bytes(w) + bytes(" tail")) } }
406for t in qtexts { tally(SwarmReference.looksLikeQuota(t) == SwarmCore.looksLikeQuota(t), "looksLikeQuota bytes \(t.count) [\(String(decoding: t.prefix(60), as: UTF8.self))]") }
407let rolesW = ["", "worker", "Worker", "coordinator", "COORDINATOR", "narrator", "helper", "x", "workers", "coordinato"], namesW = ["narrator", "Narrator-2", "monitor-10", "monitor-", "worker-1", "narrator-x", "", "mon", "MONITOR", "narrator-", "a-1", "-1", "monitor-1-2"]
408for r in rolesW { for nm in namesW { tally(SwarmReference.roleCode(role: bytes(r), name: bytes(nm)) == SwarmCore.roleCode(role: bytes(r), name: bytes(nm)), "roleCode [\(r)] [\(nm)]") } }
409// the whole picture, from the boards above, and the graph from it
410func sameDerived(_ a: SwarmReference.Derived, _ b: SwarmCore.Derived) -> Bool {
411 a.refused == b.refused && a.head == b.head && a.postDirect == b.postDirect && a.postAll == b.postAll && a.postSpans == b.postSpans && a.postStartsGroup == b.postStartsGroup
412 && a.postsWithClippedSpans == b.postsWithClippedSpans && a.state == b.state && a.attention == b.attention && a.idleSeconds == b.idleSeconds && a.unread == b.unread
413 && a.postCount == b.postCount && a.lastPost == b.lastPost && a.waitingOn == b.waitingOn && a.waitingSeq == b.waitingSeq && a.asksYouSeq == b.asksYouSeq && a.group == b.group
414 && a.helper == b.helper && a.overviewOrder == b.overviewOrder && a.memberOrder == b.memberOrder && a.working == b.working && a.waiting == b.waiting && a.stopped == b.stopped
415}
416var pictures = 0, refusedPictures = 0, graphRows = 0
417for (bi, lns) in boards.enumerated() where bi % 2 == 0 || lns.count > 100 {
418 let bd = SwarmReference.assemble(lines: lns, firstSeq: 1)
419 let n = bd.names.count, p = bd.postSeq.count
420 let now = 1_762_840_000 + rnd(5000)
421 var x = SwarmReference.Input(), y = SwarmCore.Input()
422 let roster = rnd(2) == 0
423 let roles = (0..<n).map { _ in [0, 0, 0, 1, 2][rnd(5)] }, killed = (0..<n).map { _ in rnd(6) == 0 ? 1 : 0 }, wake = (0..<n).map { _ in rnd(4) }, turn = (0..<n).map { _ in rnd(3) }
424 let lastRead = (0..<n).map { _ in rnd(p + 3) - 1 }, lastMove = (0..<n).map { _ in rnd(4) == 0 ? 0 : now - rnd(1500) }, failure = (0..<n).map { _ in rnd(4) }
425 let owner = (0..<n).map { _ in rnd(7) == 0 ? 1 : 0 }
426 let channels: [[[UInt8]]] = (0..<n).map { _ in rnd(3) == 0 ? [bytes("parser")] : [] }
427 var times = bd.postTime
428 if rnd(3) == 0 { times = times.map { _ in now - rnd(2000) } }
429 var texts = bd.postText
430 for i in 0..<p where rnd(3) == 0 && n > 0 { texts[i] += bytes(" @" + String(decoding: bd.names[rnd(n)], as: UTF8.self).replacingOccurrences(of: " ", with: "-") + " #\(1 + rnd(max(1, p)))") }
431 var toFix = bd.postTo
432 if rnd(40) == 0, p > 0 { toFix[rnd(p)].append(n + 2) } // an index that points nowhere: refused
433 var killedFix = killed
434 if rnd(40) == 0 { killedFix.append(0) } // lists of different lengths: refused
435 x.hasRoster = roster; x.now = now; x.citeHead = p; x.names = bd.names; x.roles = roles; x.killed = killedFix; x.wake = wake; x.turn = turn; x.lastRead = lastRead
436 x.lastMove = lastMove; x.failure = failure; x.channels = channels; x.owner = owner; x.postSeq = bd.postSeq; x.postTime = times; x.postSender = bd.postSender
437 x.postWith = bd.postWith; x.postTo = toFix; x.postAll = bd.postAll; x.postText = texts
438 y.hasRoster = roster; y.now = now; y.citeHead = p; y.names = bd.names; y.roles = roles; y.killed = killedFix; y.wake = wake; y.turn = turn; y.lastRead = lastRead
439 y.lastMove = lastMove; y.failure = failure; y.channels = channels; y.owner = owner; y.postSeq = bd.postSeq; y.postTime = times; y.postSender = bd.postSender
440 y.postWith = bd.postWith; y.postTo = toFix; y.postAll = bd.postAll; y.postText = texts
441 let dx = SwarmReference.derive(x), dy = SwarmCore.derive(y)
442 tally(sameDerived(dx, dy), "derive board \(bi) members \(n) posts \(p) roster \(roster): refused \(dx.refused)/\(dy.refused) state \(dx.state.prefix(8))/\(dy.state.prefix(8)) order \(dx.overviewOrder.prefix(8))/\(dy.overviewOrder.prefix(8)) on \(dx.waitingOn.prefix(8))/\(dy.waitingOn.prefix(8)) starts \(dx.postStartsGroup.prefix(8))/\(dy.postStartsGroup.prefix(8))")
443 pictures += 1
444 if dx.refused != 0 { refusedPictures += 1; continue }
445 for upTo in [p, rnd(p + 2) - 1, p + 5] {
446 let e1 = SwarmReference.edges(memberCount: n, helper: dx.helper, postSender: bd.postSender, postWith: bd.postWith, postDirect: dx.postDirect, postAll: dx.postAll, upTo: upTo)
447 let e2 = SwarmCore.edges(memberCount: n, helper: dx.helper, postSender: bd.postSender, postWith: bd.postWith, postDirect: dx.postDirect, postAll: dx.postAll, upTo: upTo)
448 tally(e1 == e2, "edges board \(bi) members \(n) upTo \(upTo): \(e1.prefix(15)) / \(e2.prefix(15))")
449 graphRows += e1.count / 5
450 tally(SwarmReference.broadcasts(memberCount: n, postSender: bd.postSender, postAll: dx.postAll, upTo: upTo) == SwarmCore.broadcasts(memberCount: n, postSender: bd.postSender, postAll: dx.postAll, upTo: upTo), "broadcasts board \(bi) upTo \(upTo)")
451 let keep = rnd(n + 2) - 1, all = rnd(2) == 0
452 tally(SwarmReference.busiest(memberCount: n, edges: e1, withAll: all, keep: keep) == SwarmCore.busiest(memberCount: n, edges: e1, withAll: all, keep: keep), "busiest board \(bi) keep \(keep) all \(all)")
453 }
454}
455tally(SwarmReference.edges(memberCount: 0, helper: [], postSender: [], postWith: [], postDirect: [], postAll: [], upTo: 3) == SwarmCore.edges(memberCount: 0, helper: [], postSender: [], postWith: [], postDirect: [], postAll: [], upTo: 3), "edges of nobody")
456tally(SwarmReference.edges(memberCount: 2, helper: [0], postSender: [0], postWith: [[]], postDirect: [[1]], postAll: [0], upTo: 3) == SwarmCore.edges(memberCount: 2, helper: [0], postSender: [0], postWith: [[]], postDirect: [[1]], postAll: [0], upTo: 3), "edges with a short helper list")
457tally(SwarmReference.broadcasts(memberCount: 200, postSender: [0], postAll: [1], upTo: 3) == SwarmCore.broadcasts(memberCount: 200, postSender: [0], postAll: [1], upTo: 3), "broadcasts over the member limit")
458// the rows of the one box (kind 7 op 17: fn swrank) against the Swift rules it replaced
459let boxWords: [[String]] = [["clipboard", "copied", "clipboard history"], ["find", "files", "find files"], ["ask", "chat"], ["agent"], ["factory", "stations", "queues", "droids"], ["accounts", "keys", "api keys", "passwords", "logins"], ["voice", "dictation", "microphone"]]
460let boxCommands: [[String]] = [["settings", "preferences", "config", "hop settings"], ["rebuild file index", "reindex", "index files"], ["new chat", "clear chat"], ["quit hop"]]
461let typed = ["s", "se", "set", "settings", "clip", "clipboard", "ask", "a", "ag", "agent", "quit hop", "qu", "qui", "fi", "find files", "index", "re", "rei", "new chat", "sé", "se\u{301}", "keys", "ke", "xyzzy", "voice", "日本", "c", "co", "con", "config", ""]
462var rankRows = 0
463for round in 0..<6000 {
464 var x = SmartRank.Input()
465 let t = typed[rnd(typed.count)]
466 x.low = bytes(t); x.lowCount = t.count
467 x.apps = (0..<(round % 500 == 3 ? 600 : rnd(14))).map { _ in SmartRank.App(score: rnd(6) == 0 ? 100 : rnd(240), boost: rnd(3) == 0 ? rnd(60) : 0, lift: rnd(4) == 0 ? rnd(81) - 10 : 0, previous: rnd(9) == 0) }
468 x.address = rnd(5) == 0 ? 1 + rnd(2) : 0; x.searched = rnd(3) != 0; x.exactFile = rnd(3) == 0
469 x.files = (0..<rnd(20)).map { _ in SmartRank.File(score: rnd(120), boost: rnd(3) == 0 ? rnd(40) : 0, isApp: rnd(5) == 0) }
470 let on = (0..<boxWords.count).filter { _ in rnd(4) != 0 }
471 x.screens = on.map { boxWords[$0].map(bytes) }
472 x.commands = boxCommands.map { $0.map(bytes) }
473 x.accounts = (0..<rnd(6)).map { _ in let c = rnd(2) == 0; return SmartRank.Account(contains: c, prefix: c && rnd(2) == 0) }
474 x.clips = (0..<rnd(12)).map { _ in rnd(4) == 0 }
475 x.question = rnd(6) == 0; x.agentWanted = rnd(2) == 0
476 if rnd(8) == 0 { x.apps = []; x.files = []; x.clips = []; x.accounts = []; x.address = 0 }
477 let r1 = SmartRankReference.rank(x), r2 = SmartRank.rank(x)
478 tally(r1 == r2, "rank [\(t)] apps \(x.apps.count) files \(x.files.count): swift \(r1.prefix(6).map { "\($0.kind):\($0.index):\($0.score)" }) omega \(r2.prefix(6).map { "\($0.kind):\($0.index):\($0.score)" })")
479 rankRows += r1.count
480}
481// what the one box offers before anything is typed (kind 7 op 18: fn swsuggest) and the lift from habit (op 19: fn swlifts)
482var offered = 0, lifted = 0
483for round in 0..<5000 {
484 var x = SmartSuggest.Input()
485 x.hasLatest = rnd(3) != 0
486 x.age = [-5, 0, 1, 59, 60, 61, 599, 600, 601, 5000][rnd(10)]
487 x.latestIsAddress = rnd(3) == 0; x.frontIsBrowser = rnd(2) == 0
488 x.rest = [0, 1, 2, 5, 19, 20, 21, 40][rnd(8)]; x.paused = rnd(5) == 0
489 x.apps = (0..<(round % 700 == 5 ? 300 : rnd(16))).map { _ in
490 SmartSuggest.App(liftFrom: rnd(3) == 0 ? rnd(61) : 0, liftHour: rnd(3) == 0 ? rnd(26) : 0, used: rnd(2) == 0 ? rnd(81) : 0,
491 running: rnd(3) == 0, previous: rnd(8) == 0, lately: rnd(3) == 0 ? [10, 8, 6, 4, 2, 0][rnd(6)] : 0)
492 }
493 let r1 = SuggestReference.rows(x), r2 = SmartSuggest.rows(x)
494 tally(r1 == r2, "suggest latest \(x.hasLatest) age \(x.age) apps \(x.apps.count) rest \(x.rest): swift \(r1.prefix(6).map { "\($0.kind):\($0.index):\($0.score):\($0.why)" }) omega \(r2.prefix(6).map { "\($0.kind):\($0.index):\($0.score):\($0.why)" })")
495 offered += r1.count
496}
497for round in 0..<3000 {
498 let apps = round % 600 == 9 ? 150 : rnd(8), hour = rnd(24), front = rnd(4) != 0
499 let ls = (0..<(round % 600 == 9 ? 400 : rnd(40))).map { _ in (here: rnd(2) == 0, hour: rnd(30) == 0 ? [-3, 24, 25, 47][rnd(4)] : rnd(24), app: rnd(apps + 3) - 1) }
500 let l1 = SuggestReference.lifts(hour: hour, hasFront: front, apps: apps, launches: ls), l2 = SmartSuggest.lifts(hour: hour, hasFront: front, apps: apps, launches: ls)
501 tally(l1.count == l2.count && zip(l1, l2).allSatisfy { $0.from == $1.from && $0.hour == $1.hour }, "lifts apps \(apps) hour \(hour) front \(front) launches \(ls.count): swift \(l1.prefix(6)) omega \(l2.prefix(6))")
502 lifted += l1.reduce(0) { $0 + ($1.from > 0 ? 1 : 0) + ($1.hour > 0 ? 1 : 0) }
503}
504// AES-256-GCM (kind 7 op 20: fn swgcm) against CryptoKit, which is what seals Hop's clipboard history: sealing
505// gives the same bytes and tag, unsealing gives the data back, and a changed byte anywhere is refused by both
506var sealedBytes = 0, refusedSeals = 0
507func coreGCM(seal: Bool, key: [UInt8], nonce: [UInt8], data: [UInt8], tag: [UInt8] = []) -> [Int]? {
508 SwarmCore.statusNumbers(20, [seal ? 1 : 0, data.count], bytes: key + nonce + data + tag)
509}
510for round in 0..<1500 {
511 let key = (0..<32).map { _ in UInt8(rnd(256)) }, nonce = (0..<12).map { _ in UInt8(rnd(256)) }
512 let n = round < 40 ? round : (round % 300 == 7 ? 4096 : [1, 15, 16, 17, 31, 32, 33, 64, 255, 256, 257, 1000][rnd(12)] + rnd(3))
513 let plain = (0..<n).map { _ in UInt8(rnd(256)) }
514 let box = try! AES.GCM.seal(Data(plain), using: SymmetricKey(data: Data(key)), nonce: try! AES.GCM.Nonce(data: Data(nonce)))
515 let ct = [UInt8](box.ciphertext), tag = [UInt8](box.tag)
516 let s = coreGCM(seal: true, key: key, nonce: nonce, data: plain)
517 tally(s.map { $0 == [1] + ct.map(Int.init) + tag.map(Int.init) } ?? false, "gcm seal \(n) bytes: omega \(s?.prefix(6).map(String.init).joined(separator: ",") ?? "nothing")")
518 let u = coreGCM(seal: false, key: key, nonce: nonce, data: ct, tag: tag)
519 tally(u.map { $0 == [1] + plain.map(Int.init) } ?? false, "gcm unseal \(n) bytes: omega \(u?.prefix(6).map(String.init).joined(separator: ",") ?? "nothing")")
520 sealedBytes += n
521 // one changed bit: in the data, the tag, the nonce or the key
522 var k2 = key, n2 = nonce, c2 = ct, t2 = tag
523 switch rnd(n == 0 ? 3 : 4) {
524 case 0: t2[rnd(16)] ^= UInt8(1 << rnd(8))
525 case 1: n2[rnd(12)] ^= UInt8(1 << rnd(8))
526 case 2: k2[rnd(32)] ^= UInt8(1 << rnd(8))
527 default: c2[rnd(n)] ^= UInt8(1 << rnd(8))
528 }
529 let swiftRefuses = (try? AES.GCM.open(try AES.GCM.SealedBox(nonce: AES.GCM.Nonce(data: Data(n2)), ciphertext: Data(c2), tag: Data(t2)), using: SymmetricKey(data: Data(k2)))) == nil
530 let bad = coreGCM(seal: false, key: k2, nonce: n2, data: c2, tag: t2)
531 tally(swiftRefuses && bad == [0], "gcm changed bit, \(n) bytes: swift refuses \(swiftRefuses) omega \(bad?.prefix(3).map(String.init).joined(separator: ",") ?? "nothing")")
532 if bad == [0] { refusedSeals += 1 }
533}
534print("status cases \(uCases) sealed bytes \(sealedBytes) refused seals \(refusedSeals) offered rows \(offered) lifts \(lifted) rank rows \(rankRows) pictures \(pictures) refused \(refusedPictures) graph rows \(graphRows)")
535print("CORE-PARITY status same \(uSame) different \(uDiff)")
536print("CORE-PARITY same \(nSame + pSame + tSame + wSame + bSame + uSame) different \(nDiff + pDiff + tDiff + wDiff + bDiff + uDiff)")
537exit(nDiff + pDiff + tDiff + wDiff + bDiff + uDiff == 0 && pictures >= 300 && graphRows >= 1000 && offered >= 10000 && lifted >= 500 && sealedBytes >= 100000 && refusedSeals == 1500 && nMatched >= 1000 && pMatched >= 1000 && tYes >= 1000 && wYes >= 1000 && bPosts >= 1000 && sMarked >= 1000 && sCalled >= 1000 && aJoined >= 300 ? 0 : 1)