Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/hop/blob/main/Sources/SwarmChecks.swift # hop Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key. Brought by drakestapleton Sign in to star 1 stars 1 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `hop / Sources / SwarmChecks.swift` 419 lines · 38372 bytes Raw Blame History 1 import Foundation 2 3 /// The Swarm section's part of `Hop --selftest` (also run alone by `hop swarm check`). The rules in SwarmCore 4 /// are checked on made-up boards, and each rule has a control that must come out the other way. The last 5 /// checks read a throwaway swarm folder and a throwaway board text through the same code the app uses. 6 /// Nothing here touches a real swarm or the network. 7 enum SwarmChecks { 8 static func b(_ s: String) -> [UInt8] { Array(s.utf8) } 9 static func s(_ b: [UInt8]) -> String { String(decoding: b, as: UTF8.self) } 10 11 static func run(_ report: (String, Bool, String) -> Void) { 12 mentions(report) 13 lines(report) 14 boards(report) 15 status(report) 16 picture(report) 17 limits(report) 18 reading(report) 19 } 20 21 // MARK: Who a post addresses 22 23 static func mentions(_ report: (String, Bool, String) -> Void) { 24 let names = ["monitor", "ctmp-m2", "worker-1", "worker-2", "recon"].map(b) 25 let roles = [Int](repeating: SwarmCore.roleWorker, count: names.count) 26 let none = [[[UInt8]]](repeating: [], count: names.count) 27 func who(_ text: String, sender: Int = -1) -> String { 28 let t = b(text) 29 let a = SwarmCore.address(text: t, spans: SwarmCore.spans(t, names: names, head: 0).flat, sender: sender, headerTo: [], headerAll: false, roles: roles, channels: none) 30 return (a.direct.map { s(names[$0]) } + (a.all ? ["+all"] : [])).joined(separator: " ") 31 } 32 let called: [(String, String)] = [ 33 ("@monitor please look", "monitor"), ("ping @Monitor.", "monitor"), ("(@ctmp-m2) and @recon,", "ctmp-m2 recon"), 34 ("@all heads up", "+all"), ("@ALL: stop", "+all"), ("@worker go", "worker-1 worker-2"), ("@worker-2 only", "worker-2"), 35 ("“@monitor” in curly quotes", "monitor"), ("line one\n@recon line two", "recon"), 36 ] 37 // Controls: none of these calls anyone. 38 let silent = ["mail me at bob@monitor.example", "@monitors are plural", "@recon-spark is someone else", "@ monitor", "no mention of monitor", 39 "é@monitor after a letter", "x_@recon", "@allow is a word", "@worker-3 is not on the roster"] 40 let wrongCalled = called.filter { who($0.0) != $0.1 }.map { "“\($0.0)” gave “\(who($0.0))”" } 41 let wrongSilent = silent.filter { !who($0).isEmpty }.map { "“\($0)” called “\(who($0))”" } 42 let notSelf = who("@monitor @recon", sender: 0) 43 report("Swarm: @name counts only at a word start, whole, in any letter case; @all is everyone", 44 wrongCalled.isEmpty && wrongSilent.isEmpty && notSelf == "recon", 45 wrongCalled.isEmpty && wrongSilent.isEmpty ? "\(called.count) mentions found, the sender never calls itself; controls: \(silent.count) look-alikes call nobody (an address like bob@monitor.example, a longer name, a name not on the roster)" 46 : (wrongCalled + wrongSilent).joined(separator: "; ")) 47 48 let cited = SwarmCore.spans(b("see #12 and #99, PR#7, #0, ' (#3) #4x"), names: names, head: 20).flat 49 var cites: [Int] = [], i = 0 50 while i + 3 < cited.count { if cited[i + 2] == SwarmCore.spanCite { cites.append(cited[i + 3]) }; i += 4 } 51 let off = SwarmCore.spans(b("see #12"), names: names, head: 0).flat 52 report("Swarm: #seq cites an earlier post, only when that post exists", cites == [12, 3] && off.isEmpty, 53 "in “see #12 and #99, PR#7, #0, ' (#3) #4x” on a board of 20 posts: \(cites); control: citations off gives \(off.count / 4)") 54 55 // "@#parser" reaches the members who follow that channel; the coordinator and helpers follow every channel. 56 let chNames = ["lead", "writer", "parser-dev", "star", "narrator", "plain"].map(b) 57 let chRoles = [SwarmCore.roleCoordinator, SwarmCore.roleWorker, SwarmCore.roleWorker, SwarmCore.roleWorker, SwarmCore.roleHelper, SwarmCore.roleWorker] 58 let chSets: [[[UInt8]]] = [[], [], [b("parser")], [b("*")], [], [b("docs")]] 59 func via(_ text: String) -> String { 60 let t = b(text) 61 return SwarmCore.address(text: t, spans: SwarmCore.spans(t, names: chNames, head: 0).flat, sender: 1, headerTo: [], headerAll: false, roles: chRoles, channels: chSets) 62 .direct.map { s(chNames[$0]) }.joined(separator: " ") 63 } 64 report("Swarm: @#channel reaches the members who follow that channel", via("@#parser ready") == "lead parser-dev star narrator" && via("@#main hello").isEmpty && via("@#Docs v2") == "lead star narrator plain", 65 "@#parser: \(via("@#parser ready")); @#Docs: \(via("@#Docs v2")); control, @#main calls nobody: “\(via("@#main hello"))”") 66 } 67 68 // MARK: Reading one board line 69 70 static func lines(_ report: (String, Bool, String) -> Void) { 71 func show(_ text: String) -> String { 72 let l = SwarmCore.parseLine(b(text)) 73 if !l.ok { return "not a post" } 74 func named(_ names: [[UInt8]], _ details: [[UInt8]]) -> [String] { 75 var out: [String] = [] 76 for i in names.indices { out.append(s(names[i]) + (details[i].isEmpty ? "" : "(" + s(details[i]) + ")")) } 77 return out 78 } 79 var to: [String] = named(l.recipients, l.recipientDetails) 80 if l.all { to.append("ALL") } 81 let from: String = named(l.senders, l.senderDetails).joined(separator: "+") 82 return from + " > " + to.joined(separator: ",") + " | " + s(l.text) 83 } 84 let cases: [(String, String)] = [ 85 ("2026-11-11T03:04:47Z factory-flawless (claude, MacBook, L1122) to bays + merge-desk (omp-queen-spark) + fixer (L1128): the hand-off: done", 86 "factory-flawless(claude, MacBook, L1122) > bays,merge-desk(omp-queen-spark),fixer(L1128) | the hand-off: done"), 87 ("2026-11-11T03:19:24Z omp-queen-spark (merge desk): LANDED x", "omp-queen-spark(merge desk) > | LANDED x"), 88 ("2026-11-11T03:38:36Z omp-queen-spark (merge desk) correction to my MERGE HOLD post: a signing path exists", 89 "omp-queen-spark(merge desk) > | correction to my MERGE HOLD post: a signing path exists"), 90 ("2026-11-07T04:27Z reviewer-`90c77212` to all: DONE", "reviewer-`90c77212` > ALL | DONE"), 91 ("2026-11-11T03:14:29Z research-hub + salvage-on-one (Claude Code, MacBook, L1124/L1125) to merge-desk (omp-queen-spark) + Manager(Aien): bay 1", 92 "research-hub+salvage-on-one(Claude Code, MacBook, L1124/L1125) > merge-desk(omp-queen-spark),Manager(Aien) | bay 1"), 93 ("2026-11-10T22:01:00Z omp-queen-spark (merge desk) @mac-ham/NgBack: ack", "omp-queen-spark(merge desk) > mac-ham/NgBack | ack"), 94 ("- 2026-11-10T20:50:19Z factory-bay-3: CUDApp review at 12:30", "factory-bay-3 > | CUDApp review at 12:30"), 95 ("2026-11-02T21:36Z omp-ollm DONE WINDOW gg-r8t4 closed (open rc 0, leg rc 0)", "omp-ollm > | DONE WINDOW gg-r8t4 closed (open rc 0, leg rc 0)"), 96 ("2026-11-06 reviewer-538 to all lanes + bays: DONE probe", "reviewer-538 > bays,ALL | DONE probe"), 97 ("2026-11-11T03:20Z mac-ham/NgFront(omp, MacBook) to merge-desk + bays: READY", "mac-ham/NgFront(omp, MacBook) > merge-desk,bays | READY"), 98 ] 99 // Controls: lines that are not posts. 100 let notPosts = ["# Format: : ", "RECOVERY NOTICE 2026-11-03T10:07Z: this is a partial recovery", "", 101 "DRAKE-WANTED: 2026-11-10T20:31:45+00:00 a reply came", "2026-11-11T03:04:47Z", "2026-13-40T03:04:47Z nobody: bad date"] 102 let wrong = cases.filter { show($0.0) != $0.1 }.map { "got “\(show($0.0))” for “\($0.0.prefix(60))”" } 103 let taken = notPosts.filter { SwarmCore.parseLine(b($0)).ok } 104 report("Swarm: a board line gives its time, sender, recipients and text", wrong.isEmpty && taken.isEmpty, 105 wrong.isEmpty && taken.isEmpty ? "\(cases.count) shapes read (brackets, several senders, no “to” part, “@name” recipients, words after the bracket, to all); controls: \(notPosts.count) lines that are not posts are refused" 106 : (wrong + taken.map { "taken as a post: “\($0)”" }).joined(separator: "; ")) 107 108 func at(_ text: String) -> String { let t = SwarmCore.parseTime(b(text), 0); return t.ok ? "\(t.epoch)\(t.zoned ? "Z" : "")" : "no" } 109 let times: [(String, String)] = [("2026-11-11T03:04:47Z", "1794366287Z"), ("2026-11-01T19:06:24+00:00", "1793559984Z"), ("2026-11-11T03:20Z", "1794367200Z"), 110 ("2026-11-06", "`1793923200`"), ("2026-11-10 18:23:56", "`1794335036`"), ("2026-11-10T22:05:50-06:00", "1794369950Z"), 111 ("2024-02-29T23:59:59Z", "1709251199Z"), ("1970-01-01T00:00:00Z", "0Z"), 112 ("2026-13-01T00:00:00Z", "no"), ("2026-11-32", "no"), ("11/10/2026", "no"), ("2026-11-10T25:00Z", "no")] 113 let badTimes = times.filter { at($0.0) != $0.1 }.map { "\($0.0) gave \(at($0.0))" } 114 report("Swarm: times are read to the second, with or without a zone", badTimes.isEmpty, 115 badTimes.isEmpty ? "\(times.count) cases, among them a leap day, an offset, a date alone; 4 of them are not times and are refused" : badTimes.joined(separator: "; ")) 116 117 let many = "2026-11-11T03:00:00Z a to " + (1...20).map { "r\($0)" }.joined(separator: " + ") + ": hi" 118 let crowd = SwarmCore.parseLine(b(many)), few = SwarmCore.parseLine(b("2026-11-11T03:00:00Z a to r1 + r2: hi")) 119 let long = SwarmCore.parseLine(b("2026-11-11T03:00:00Z a: " + String(repeating: "é", count: 20_000))) 120 report("Swarm: a line over a limit is cut and says so", crowd.recipients.count == SwarmCore.maxRecipients && crowd.clipped && !few.clipped 121 && long.clipped && long.text.count == SwarmCore.maxTextBytes && String(bytes: long.text, encoding: .utf8) != nil, 122 "20 recipients: \(crowd.recipients.count) kept, flagged=\(crowd.clipped); 40,000 bytes of text: \(long.text.count) kept at a whole character, flagged=\(long.clipped); control, 2 recipients: flagged=\(few.clipped)") 123 } 124 125 // MARK: A whole plain-text board 126 127 static let sampleBoard = [ 128 "# Format: to : ", 129 "2026-11-11T03:00:00Z alpha (claude, MacBook, L1) to merge-desk (queen) + bays: READY one", 130 "2026-11-11T03:01:00Z queen (merge desk) to alpha: ack one", 131 "2026-11-11T03:02:00Z beta (claude, MacBook, L2) to merge-desk + alpha: READY two", 132 "not a post", 133 "2026-11-11T03:03:00Z gamma (helper) to helper: can you look?", 134 "2026-11-11T03:04:00Z delta (helper): on my own", 135 "2026-11-11T03:05:00Z merge-desk (queen, L9) to all: HOLD", 136 ] 137 138 static func boards(_ report: (String, Bool, String) -> Void) { 139 let board = SwarmCore.assemble(lines: sampleBoard.map(b), firstSeq: 101) 140 let names = board.names.map(s) 141 func member(_ n: String) -> Int { names.firstIndex(of: n) ?? -9 } 142 let desk = member("merge-desk") 143 let posts = board.postSeq.indices.map { i in 144 "\(board.postSeq[i]) \(board.postSender[i] >= 0 ? names[board.postSender[i]] : "?") > " + (board.postTo[i].map { names[$0] } + (board.postAll[i] == 1 ? ["ALL"] : [])).joined(separator: ",") 145 } 146 let expected = ["102 alpha > merge-desk,bays", "103 merge-desk > alpha", "104 beta > merge-desk,alpha", "106 gamma > helper", "107 delta > ", "108 merge-desk > ALL"] 147 report("Swarm: board lines become posts and members; a post's number is its line number", posts == expected && board.skippedLines == 2 && board.lines == 8, 148 posts == expected ? "\(posts.count) posts numbered 102 to 108 from 8 lines starting at line 101; 2 lines that are not posts are counted, not shown" : "got \(posts)") 149 // "queen" and "merge-desk" name each other in brackets: one member. "helper" stands in two agents' brackets: it joins nobody. 150 report("Swarm: two names of one agent are joined; a bracket word shared by several agents joins nobody", 151 desk >= 0 && !names.contains("queen") && s(board.alsoCalled[desk]) == "queen" && s(board.details[desk]) == "queen, L9" 152 && names.contains("gamma") && names.contains("delta") && names.contains("helper") && names.count == 7 && !names.contains("claude") && !names.contains("MacBook"), 153 "members: \(names.joined(separator: ", ")); merge-desk is also \(desk >= 0 ? s(board.alsoCalled[desk]) : "?"); control: gamma, delta and helper stay three members, and claude and MacBook are nobody") 154 155 // A name written without its lane is that agent only when one name ends that way. 156 let lanes = SwarmCore.assemble(lines: ["2026-11-11T03:00:00Z ham/Perf (omp) to desk: READY", "2026-11-11T03:01:00Z desk to Perf + Dup + Solo + ham/Solo: ack", 157 "2026-11-11T03:02:00Z ham/Dup to desk: one", "2026-11-11T03:03:00Z site/Dup to desk: two"].map(b), firstSeq: 1) 158 let laneNames = lanes.names.map(s).sorted() 159 let perf = lanes.names.map(s).firstIndex(of: "ham/Perf") ?? -9 160 report("Swarm: a name written without its lane is that agent when only one sender's name ends that way", 161 laneNames == ["Dup", "Solo", "desk", "ham/Dup", "ham/Perf", "ham/Solo", "site/Dup"] && perf >= 0 && lanes.postTo[1].contains(perf) && s(lanes.alsoCalled[perf]) == "Perf", 162 "members: \(laneNames.joined(separator: ", ")); “Perf” is ham/Perf; controls: “Dup” could be ham/Dup or site/Dup, and nobody posts as ham/Solo, so “Dup” and “Solo” stay their own names") 163 164 var big: [[UInt8]] = [] 165 let agents = SwarmCore.maxMembers + 6 // with "desk" that is 7 names too many 166 for i in 0..<450 { big.append(b("2026-11-11T03:00:00Z agent-\(i % agents) to desk: post \(i)")) } 167 let cut = SwarmCore.assemble(lines: big, firstSeq: 1) 168 let unnamed = cut.postSender.filter { $0 < 0 }.count 169 let small = SwarmCore.assemble(lines: Array(big.prefix(40)), firstSeq: 1) 170 report("Swarm: a board over the limits says what it left out", 171 cut.postSeq.count == SwarmCore.maxPosts && cut.olderLinesDropped == 50 && cut.postSeq.first == 51 && cut.postSeq.last == 450 172 && cut.names.count == SwarmCore.maxMembers && cut.membersDropped == 7 && cut.spellingsDropped == 0 && unnamed > 0 && s(cut.postSenderName[cut.postSender.firstIndex(of: -1) ?? 0]).hasPrefix("agent-") 173 && small.olderLinesDropped == 0 && small.membersDropped == 0 && !small.postSender.contains(-1), 174 "450 lines: newest \(cut.postSeq.count) kept, \(cut.olderLinesDropped) older counted; \(agents + 1) names: \(cut.names.count) members, \(cut.membersDropped) counted as left out, their \(unnamed) posts keep the written name; control, 40 lines: nothing left out") 175 } 176 177 // MARK: Status is worked out, not reported 178 179 static func status(_ report: (String, Bool, String) -> Void) { 180 let P = SwarmCore.stepPlanner, R = SwarmCore.stepResult, O = SwarmCore.stepOther, T = SwarmCore.stepTorn 181 let D = SwarmCore.statusDone, G = SwarmCore.statusRunning 182 func turn(_ steps: [(Int, Int, Int, Int)]) -> Int { SwarmCore.turn(kinds: steps.map(\.0), statuses: steps.map(\.1), tools: steps.map(\.2), waits: steps.map(\.3)) } 183 let turns: [([(Int, Int, Int, Int)], Int)] = [ 184 ([(P, D, 1, 0), (R, D, 0, -1)], SwarmCore.turnEnded), // waited for posts, the wait is done 185 ([(P, D, 0, -1)], SwarmCore.turnEnded), // a final reply with no tool 186 ([(P, D, 2, 1), (R, G, 0, -1), (R, D, 0, -1)], SwarmCore.turnEnded), // the wait is done; the other tool runs in the background 187 ([(P, D, 1, 0), (R, G, 0, -1)], SwarmCore.turnRunning), // the wait itself still runs 188 ([(P, D, 2, 1), (R, D, 0, -1)], SwarmCore.turnRunning), // not every result is in 189 ([(P, D, 1, -1), (R, D, 0, -1)], SwarmCore.turnRunning), // a tool that is not the wait 190 ([(P, D, 1, 0), (R, D, 0, -1), (O, D, 0, -1)], SwarmCore.turnRunning), // woken by a system message 191 ([(P, D, 0, -1), (T, 0, 0, -1)], SwarmCore.turnRunning), // a half-written last line 192 ([], SwarmCore.turnUnknown), 193 ] 194 let badTurns = turns.indices.filter { turn(turns[$0].0) != turns[$0].1 } 195 func state(_ killed: Bool, _ turn: Int, _ wake: Int, roster: Bool = true, age: Int = -1) -> Int { 196 SwarmCore.state(killed: killed, turn: turn, wake: wake, hasRoster: roster, lastPostAge: age) 197 } 198 let W = SwarmCore.stateWorking, Q = SwarmCore.stateWaiting, X = SwarmCore.stateStopped 199 let states = [state(true, SwarmCore.turnRunning, SwarmCore.wakeWorking) == X, 200 state(false, SwarmCore.turnEnded, SwarmCore.wakeWorking) == Q, // its own word says "working": the run has stopped, so waiting 201 state(false, SwarmCore.turnRunning, SwarmCore.wakeMentions) == W, // its own word says "parked": it is mid-turn, so working 202 state(false, SwarmCore.turnUnknown, SwarmCore.wakeMentions) == Q, 203 state(false, SwarmCore.turnUnknown, SwarmCore.wakeAnything) == Q, 204 state(false, SwarmCore.turnUnknown, SwarmCore.wakeWorking) == W, 205 state(false, SwarmCore.turnUnknown, SwarmCore.wakeUnknown, roster: false, age: SwarmCore.activeSeconds) == W, 206 state(false, SwarmCore.turnUnknown, SwarmCore.wakeUnknown, roster: false, age: SwarmCore.activeSeconds + 1) == Q, 207 state(false, SwarmCore.turnUnknown, SwarmCore.wakeUnknown, roster: false, age: -1) == Q] 208 report("Swarm: stopped, waiting or working comes from what a member did, not from what it says", 209 badTurns.isEmpty && !states.contains(false), 210 badTurns.isEmpty && !states.contains(false) ? "\(turns.count) transcript endings and \(states.count) state cases; a member marked working whose run ended is waiting, and one marked parked that is mid-turn is working" 211 : "wrong turn cases \(badTurns), state cases \(states)") 212 213 func look(_ st: Int, _ fail: Int, _ idle: Int) -> Int { SwarmCore.attention(state: st, failure: fail, idleSeconds: idle) } 214 let N = SwarmCore.attentionNone 215 let stuck = look(W, N, 601) == SwarmCore.attentionStuck && look(W, N, 3600) == SwarmCore.attentionStuck 216 let notStuck = look(W, N, 600) == N && look(W, N, 30) == N && look(W, N, -1) == N && look(Q, N, 5000) == N && look(X, N, 5000) == N 217 report("Swarm: a working member with no movement for more than 10 minutes is stuck", stuck && notStuck && SwarmCore.stuckSeconds == 600, 218 "601 s and an hour: stuck=\(stuck); controls: exactly 600 s, 30 s, unknown, and a waiting or stopped member however long: stuck=\(!notStuck)") 219 220 let E = SwarmCore.stepError, bad = SwarmCore.statusError 221 let fails = [SwarmCore.failure(lastKind: E, lastStatus: D, idleSeconds: 0, quota: false) == SwarmCore.attentionError, 222 SwarmCore.failure(lastKind: R, lastStatus: bad, idleSeconds: 60, quota: false) == SwarmCore.attentionError, 223 SwarmCore.failure(lastKind: R, lastStatus: bad, idleSeconds: 59, quota: false) == N, // it usually carries on after one failed tool 224 SwarmCore.failure(lastKind: E, lastStatus: D, idleSeconds: 0, quota: true) == SwarmCore.attentionQuota, 225 SwarmCore.failure(lastKind: R, lastStatus: D, idleSeconds: 9999, quota: true) == N, 226 look(W, SwarmCore.attentionQuota, 5) == SwarmCore.attentionQuota, look(X, SwarmCore.attentionError, 5) == N] 227 let quota = ["RESOURCE_EXHAUSTED: try later", "You exceeded your Quota", "HTTP 429 Too Many Requests", "rate limit reached", "Rate-limited for 60 s"].filter { !SwarmCore.looksLikeQuota(b($0)) } 228 let notQuota = ["file not found", "error 14290", "exit 4291", "timeout after 60 s"].filter { SwarmCore.looksLikeQuota(b($0)) } 229 report("Swarm: a failed last step is an error, or quota when the message says so", !fails.contains(false) && quota.isEmpty && notQuota.isEmpty, 230 "7 failure cases \(fails.contains(false) ? "WRONG \(fails)" : "right"); quota wording missed: \(quota); control, taken for quota: \(notQuota)") 231 232 let unread = [SwarmCore.unread(head: 36, lastRead: 33), SwarmCore.unread(head: 36, lastRead: 36), SwarmCore.unread(head: 36, lastRead: 40), SwarmCore.unread(head: 36, lastRead: -1)] 233 let act = [SwarmCore.activityStep(kinds: [P, R, P], waits: [-1, -1, -1], labelled: [1, 0, 1]), // the newest labelled step 234 SwarmCore.activityStep(kinds: [P, R, P], waits: [-1, -1, -1], labelled: [1, 0, 0]), // an older one in the same turn 235 SwarmCore.activityStep(kinds: [P, P, R], waits: [-1, 0, -1], labelled: [1, 1, 0]), // nothing since it last waited 236 SwarmCore.activityStep(kinds: [P, SwarmCore.stepUser], waits: [-1, -1], labelled: [1, 0])] // nothing since the user wrote 237 report("Swarm: unread is the newest post number minus the last one read; activity is from the current turn only", 238 unread == [3, 0, 0, -1] && act == [2, 0, -1, -1], "unread \(unread) (-1 = not known); activity step \(act) (-1 = none to show)") 239 } 240 241 // MARK: Overview groups and the graph 242 243 /// A roster swarm of nine. `answered` adds dave's answer to carol. 244 static func scenario(answered: Bool) -> SwarmCore.Input { 245 var x = SwarmCore.Input() 246 x.hasRoster = true 247 x.now = 1_794_366_000 248 let names = ["coordinator", "alice", "bob", "carol", "dave", "erin", "monitor", "frank", "user"] 249 x.names = names.map(b) 250 x.roles = names.map { SwarmCore.roleCode(role: b($0 == "coordinator" ? "coordinator" : "worker"), name: b($0)) } 251 x.killed = [0, 0, 0, 0, 0, 1, 0, 0, 0] 252 x.wake = [Int](repeating: SwarmCore.wakeMentions, count: 9) 253 let run = SwarmCore.turnRunning, end = SwarmCore.turnEnded 254 x.turn = [end, run, run, end, end, run, end, end, SwarmCore.turnUnknown] 255 x.lastRead = [5, 5, 2, 3, 5, 1, 5, 4, -1] 256 x.lastMove = [x.now - 5, x.now - 30, x.now - 700, x.now - 5000, x.now - 5000, x.now - 9000, x.now - 20, x.now - 100, 0] 257 x.failure = [Int](repeating: SwarmCore.attentionNone, count: 9) 258 x.channels = [[[UInt8]]](repeating: [], count: 9) 259 x.owner = [0, 0, 0, 0, 0, 0, 0, 0, 1] 260 var posts: [(Int, String)] = [(0, "@alice @bob @carol @dave start"), (4, "@carol done with part one"), (3, "@dave can you check #2?"), 261 (7, "@user which one do you want?"), (1, "working on it")] 262 if answered { posts.append((4, "@carol looks fine")) } 263 for (i, p) in posts.enumerated() { 264 x.postSeq.append(i + 1); x.postTime.append(x.now - 600 + i * 30); x.postSender.append(p.0); x.postWith.append([]); x.postTo.append([]) 265 x.postAll.append(0); x.postText.append(b(p.1)) 266 } 267 x.citeHead = posts.count 268 return x 269 } 270 271 static func picture(_ report: (String, Bool, String) -> Void) { 272 let x = scenario(answered: false), d = SwarmCore.derive(x) 273 let names = x.names.map(s) 274 func groups(_ d: SwarmCore.Derived) -> String { 275 var out: [String] = [], g = 0 276 for i in d.overviewOrder { 277 if d.group[i] != g { g = d.group[i]; out.append("[\(g)]") } 278 out.append(names[i]) 279 } 280 return out.joined(separator: " ") 281 } 282 let want = "[1] bob frank [2] alice [3] carol [4] coordinator dave erin monitor user" 283 let carol = d.refused == 0 && d.waitingOn[3] == 4 && d.waitingSeq[3] == 3 && d.asksYouSeq[7] == 4 && d.attention[2] == SwarmCore.attentionStuck 284 let later = SwarmCore.derive(scenario(answered: true)) 285 let wantLater = "[1] bob frank [2] alice [3] dave [4] coordinator carol erin monitor user" 286 report("Swarm: Overview groups are needs you, working, waiting on someone, parked", 287 d.refused == 0 && groups(d) == want && carol && groups(later) == wantLater && later.waitingOn[3] == -1, 288 groups(d) == want ? "\(want): bob is stuck, frank wrote to you, carol waits on dave since #3; control: once dave answers her, carol is parked and dave is the one waiting (\(groups(later) == wantLater))" : "got \(groups(d))") 289 report("Swarm: members are counted and ordered without the helpers", 290 d.working == 2 && d.waiting == 5 && d.stopped == 1 && d.helper == [0, 0, 0, 0, 0, 0, 1, 0, 0] && d.unread == [0, 0, 3, 2, 0, 4, 0, 1, -1] 291 && d.memberOrder.map { names[$0] } == ["alice", "bob", "coordinator", "carol", "dave", "frank", "monitor", "user", "erin"] 292 && d.postStartsGroup == [1, 1, 1, 1, 1] && d.head == 5, 293 "\(d.working) working, \(d.waiting) waiting, \(d.stopped) stopped (monitor is a helper and not counted); unread \(d.unread); order \(d.memberOrder.map { names[$0] }.joined(separator: " "))") 294 295 // The graph: who wrote to whom by name, weighted by how often; a post for everyone reaches each task member once. 296 var g = scenario(answered: true) 297 for (who, text) in [(1, "@all status please"), (4, "@carol one more thing"), (6, "@alice I am the monitor")] { 298 g.postSeq.append(g.postSeq.count + 1); g.postTime.append(g.now); g.postSender.append(who); g.postWith.append([]); g.postTo.append([]); g.postAll.append(0); g.postText.append(b(text)) 299 } 300 let gd = SwarmCore.derive(g) 301 func links(_ upTo: Int) -> [String] { 302 let e = SwarmCore.edges(memberCount: 9, helper: gd.helper, postSender: g.postSender, postWith: g.postWith, postDirect: gd.postDirect, postAll: gd.postAll, upTo: upTo) 303 var out: [String] = [], i = 0 304 while i + 4 < e.count { out.append("\(names[e[i]])>\(names[e[i + 1]]) \(e[i + 2])=\(e[i + 3])+\(e[i + 4])"); i += 5 } 305 return out 306 } 307 let all = links(g.postSeq.count), first = links(1) 308 let wantAll = ["coordinator>alice 1=1+0", "coordinator>bob 1=1+0", "coordinator>carol 1=1+0", "coordinator>dave 1=1+0", 309 "alice>coordinator 1=0+1", "alice>bob 1=0+1", "alice>carol 1=0+1", "alice>dave 1=0+1", "alice>erin 1=0+1", "alice>frank 1=0+1", "alice>user 1=0+1", 310 "carol>dave 1=1+0", "dave>carol 3=3+0", "frank>user 1=1+0"] 311 let everyone = SwarmCore.broadcasts(memberCount: 9, postSender: g.postSender, postAll: gd.postAll, upTo: g.postSeq.count) 312 let steps = [SwarmCore.weightStep(count: 1, heaviest: 1), SwarmCore.weightStep(count: 1, heaviest: 9), SwarmCore.weightStep(count: 5, heaviest: 9), SwarmCore.weightStep(count: 9, heaviest: 9)] 313 let rows = SwarmCore.edges(memberCount: 9, helper: gd.helper, postSender: g.postSender, postWith: g.postWith, postDirect: gd.postDirect, postAll: gd.postAll, upTo: g.postSeq.count) 314 // By name: dave 4 (3 out, 1 in), carol 5... the three busiest are carol, dave and the coordinator; counting "@all" too, alice comes in. 315 let top3 = SwarmCore.busiest(memberCount: 9, edges: rows, withAll: false, keep: 3), top3All = SwarmCore.busiest(memberCount: 9, edges: rows, withAll: true, keep: 3) 316 let everybody = SwarmCore.busiest(memberCount: 9, edges: rows, withAll: false, keep: 50) 317 report("Swarm: graph lines are weighted by how many posts went from one member to another", 318 gd.refused == 0 && all == wantAll && first == Array(wantAll.prefix(4)) && everyone == [0, 1, 0, 0, 0, 0, 0, 0, 0] && steps == [1, 1, 3, 5] 319 && top3 == [1, 0, 0, 1, 1, 0, 0, 0, 0] && top3All == [0, 1, 0, 1, 1, 0, 0, 0, 0] && everybody == [1, 1, 1, 1, 1, 0, 0, 1, 1], 320 all == wantAll ? "dave wrote to carol 3 times: weight 3; alice's post for everyone reaches the 7 other task members once each; the monitor's post draws no line; control: replay at post 1 shows only the coordinator's 4 lines; line weights \(steps)" 321 : "got \(all)") 322 } 323 324 // MARK: Limits 325 326 static func limits(_ report: (String, Bool, String) -> Void) { 327 func blank(members: Int, posts: Int) -> SwarmCore.Input { 328 var x = SwarmCore.Input() 329 x.now = 1_794_366_000 330 x.names = (0.. Void) { 357 let fm = FileManager.default 358 let scratch = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("hop-swarmcheck-\(ProcessInfo.processInfo.processIdentifier)-\(Int(Date().timeIntervalSince1970))", isDirectory: true) 359 defer { try? fm.removeItem(at: scratch) } 360 func write(_ path: String, _ text: String) { 361 let u = scratch.appendingPathComponent(path) 362 try? fm.createDirectory(at: u.deletingLastPathComponent(), withIntermediateDirectories: true) 363 try? Data(text.utf8).write(to: u) 364 } 365 func member(_ conv: String, role: String = "worker", wake: String, read: Int, killed: Bool = false) -> String { 366 "{\"conversation_id\":\"\(conv)\",\"role\":\"\(role)\",\"wake_mode\":\"\(wake)\",\"last_read_seq\":\(read),\"killed\":\(killed),\"model\":\"test-model\"}" 367 } 368 write("brain/lead/.system_generated/swarm/members.json", 369 "{\"title\":\"Check swarm\",\"members\":{\"coordinator\":\(member("lead", role: "coordinator", wake: "anything", read: 3))," 370 + "\"builder\":\(member("conv-b", wake: "working", read: 1)),\"runner\":\(member("conv-r", wake: "mentions", read: 3))," 371 + "\"gone\":\(member("conv-g", wake: "working", read: 0, killed: true)),\"bad/../id\":\(member("../../x", wake: "working", read: 0))}}") 372 write("brain/lead/.system_generated/swarm/board.jsonl", 373 "{\"seq\":1,\"agent\":\"coordinator\",\"text\":\"@builder @runner build it, then run it\",\"time\":\"2026-11-10 18:23:56\"}\n" 374 + "{\"seq\":2,\"agent\":\"builder\",\"text\":\"@runner built, see #1\",\"time\":\"2026-11-10 18:30:00\"}\n" 375 + "{\"seq\":3,\"agent\":\"stranger\",\"text\":\"hello\",\"time\":\"2026-11-10 18:31:00\"}\n" 376 + "{\"seq\":4,\"agent\":\"runner\",\"text\":\"half writ") 377 // builder says "working" but its run ended on a finished wait: waiting. runner says "parked" but is mid-turn with a tool running: working. 378 write("brain/conv-b/.system_generated/logs/transcript.jsonl", 379 "{\"step_index\":7,\"type\":\"PLANNER_RESPONSE\",\"status\":\"DONE\",\"tool_calls\":[{\"name\":\"swarm_wait\",\"args\":{}}]}\n" 380 + "{\"step_index\":8,\"type\":\"GENERIC\",\"status\":\"DONE\"}\n") 381 write("brain/conv-r/.system_generated/logs/transcript.jsonl", 382 "{\"step_index\":40,\"type\":\"PLANNER_RESPONSE\",\"status\":\"DONE\",\"tool_calls\":[{\"name\":\"run_command\",\"args\":{\"toolSummary\":\"\\\"Running the tests\\\"\"}}]}\n" 383 + "{\"step_index\":41,\"type\":\"GENERIC\",\"status\":\"RUNNING\"}\n") 384 let root = scratch.appendingPathComponent("brain").path 385 let found = SwarmReader.scan(roots: [root, scratch.appendingPathComponent("no-such-folder").path]) 386 let dir = root + "/lead/.system_generated/swarm" 387 let read = SwarmReader.folder(dir, owners: ["user"], now: Date(), cache: SwarmTranscriptCache()) 388 let empty = SwarmReader.folder(root + "/conv-b/.system_generated/swarm", owners: [], now: Date(), cache: SwarmTranscriptCache()) 389 if let f = read.snapshot { 390 func m(_ n: String) -> SwarmMember? { f.members.first { $0.name == n } } 391 let states = ["coordinator", "builder", "runner", "gone"].map { n in m(n).map(SwarmReader.stateWord) ?? "?" } 392 report("Swarm: a folder with board.jsonl and members.json is read as a swarm", 393 found.sources.count == 1 && found.sources.first?.title == "Check swarm" && f.title == "Check swarm" && f.hasRoster && f.members.count == 5 && f.posts.map(\.id) == [1, 2, 3] 394 && states == ["waiting", "waiting", "working", "stopped"] && m("runner")?.activity == "Running the tests" && m("runner")?.activityIsLive == true 395 && m("builder")?.unread == 2 && f.posts[0].to.map { f.members[$0].name } == ["builder", "runner"] && f.posts[1].spans.count == 8 396 && f.posts[2].sender == "stranger" && f.posts[2].senderIndex == -1 && f.notices.contains { $0.contains("1 board line") } 397 && m("coordinator")?.group == SwarmCore.groupParked && m("builder")?.waitingOn == "runner" && empty.snapshot == nil && !empty.problem.isEmpty, 398 "found \(found.sources.count) swarm “\(f.title)”: \(f.members.count) members, posts \(f.posts.map(\.id)); states \(states); runner is “\(m("runner")?.activity ?? "?")”; builder has \(m("builder")?.unread ?? -9) unread and waits on \(m("builder")?.waitingOn ?? "?"); a post by someone not on the roster is kept; the half-written last line is counted, not shown; control: a folder with no members.json is “\(empty.problem)”") 399 } else { report("Swarm: a folder with board.jsonl and members.json is read as a swarm", false, read.problem) } 400 401 let now = Date(timeIntervalSince1970: 1_794_366_400) // 2026-11-11T03:06:40Z: 100 s after the newest sample post 402 let text = sampleBoard.joined(separator: "\n") + "\n" 403 let board = SwarmReader.board(text: text, totalLines: 108, title: "Factory board on Test", owners: ["drake"], now: now) 404 let command = SwarmReader.fetchCommand(path: "~/handoffs/BOARD.md", known: `2047938`) 405 // A day later everybody is quiet: those who posted are listed by name first, then the names that were only written to. 406 let quiet = SwarmReader.board(text: text, totalLines: 108, title: "t", owners: [], now: now.addingTimeInterval(86_400)).snapshot 407 let quietOrder = quiet.map { q in q.memberOrder.map { q.members[$0].name } } ?? [] 408 if let f = board.snapshot { 409 let desk = f.members.first { $0.name == "merge-desk" }, alpha = f.members.first { $0.name == "alpha" }, gamma = f.members.first { $0.name == "gamma" } 410 report("Swarm: the factory's board text is read the same way, tail only", 411 !f.hasRoster && f.posts.map(\.id) == [102, 103, 104, 106, 107, 108] && f.members.count == 7 && f.head == 108 412 && desk?.state == SwarmCore.stateWorking && desk?.posts == 2 && desk?.alsoCalled == "queen" && alpha?.group == SwarmCore.groupWorking 413 && gamma?.waitingOn == "helper" && f.posts.last?.all == true && f.notices.contains { $0.contains("2 lines that are not posts") } 414 && quietOrder == ["alpha", "beta", "delta", "gamma", "merge-desk", "bays", "helper"] && quiet?.working == 0 415 && command.contains("tail -n \(SwarmCore.maxPosts)") && command.contains("\"$HOME\"/'handoffs/BOARD.md'") && command.contains("\"`2047938`\"") && !command.contains("cat "), 416 "\(f.posts.count) posts numbered by line (\(f.posts.first?.id ?? 0) to \(f.head)), \(f.members.count) members, merge-desk also called \(desk?.alsoCalled ?? "?"); gamma waits on \(gamma?.waitingOn ?? "?"); the fetch asks for the last \(SwarmCore.maxPosts) lines and for nothing when the size is unchanged") 417 } else { report("Swarm: the factory's board text is read the same way, tail only", false, board.problem) } 418 } 419 }