hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
hop / Sources / SwarmCore.swift
| 1 | // Swarm board core. |
| 2 | // |
| 3 | // Every decision the Swarm section makes is in this one file: how a board line is read, who a post is |
| 4 | // addressed to, what state a member is in, which Overview group it belongs to, and how heavy each line of |
| 5 | // the graph is. The functions are pure: plain integers and byte arrays in, plain integers and byte arrays |
| 6 | // out. There are no imports, no closures kept in data and no generics. Every loop is bounded by a named |
| 7 | // limit, and input over a limit is reported in the result (a count, a flag or a refusal code), never cut |
| 8 | // without saying so. Text is UTF-8 bytes; letter case is folded for ASCII only. |
| 9 | // |
| 10 | // SwarmStore.swift is the adapter (files, ssh, JSON, the clock). SwarmView.swift draws the result. |
| 11 | |
| 12 | enum SwarmCore { |
| 13 | // MARK: Limits |
| 14 | static let maxPosts = 400 // newest posts kept from one board |
| 15 | static let maxMembers = 96 // members of one swarm |
| 16 | static let maxNames = 192 // spellings seen on a plain-text board, before two names of one agent are joined |
| 17 | static let maxSenders = 4 // agents signing one post |
| 18 | static let maxRecipients = 16 // agents one post header may address |
| 19 | static let maxNameBytes = 64 |
| 20 | static let maxNameWords = 3 |
| 21 | static let maxHeaderBytes = 600 // the part of a board line before its ": " |
| 22 | static let maxLineBytes = 65536 |
| 23 | static let maxTextBytes = 32768 // text kept from one post |
| 24 | static let maxSpans = 128 // highlighted parts of one post |
| 25 | static let maxSteps = 256 // newest steps looked at in a member's transcript |
| 26 | static let maxDetailItems = 8 // comma-separated items in a bracket after a name |
| 27 | |
| 28 | static let stuckSeconds = 600 // working, but no movement for longer than this: stuck |
| 29 | static let failureSettleSeconds = 60 // a failed tool step counts once it stayed last this long |
| 30 | static let activeSeconds = 900 // on a board with no roster: posted within this long = working |
| 31 | static let groupSeconds = 600 // posts by one sender this close together are drawn as one group |
| 32 | |
| 33 | // MARK: Codes |
| 34 | static let roleWorker = 0, roleCoordinator = 1, roleHelper = 2 // helper: narrator, monitor and other non-task roles |
| 35 | static let wakeUnknown = 0, wakeWorking = 1, wakeMentions = 2, wakeAnything = 3 |
| 36 | static let turnUnknown = 0, turnRunning = 1, turnEnded = 2 |
| 37 | static let stateWorking = 1, stateWaiting = 2, stateStopped = 3 |
| 38 | static let attentionNone = 0, attentionStuck = 1, attentionError = 2, attentionQuota = 3 |
| 39 | static let groupNeedsYou = 1, groupWorking = 2, groupWaitingOn = 3, groupParked = 4 |
| 40 | static let stepOther = 0, stepPlanner = 1, stepResult = 2, stepUser = 3, stepError = 4, stepTorn = 5 |
| 41 | static let statusOther = 0, statusDone = 1, statusError = 2, statusRunning = 3 |
| 42 | static let spanMember = 1, spanAll = 2, spanChannel = 3, spanCite = 4 |
| 43 | static let refusedMembers = 1, refusedPosts = 2, refusedShape = 3, refusedValue = 4 |
| 44 | |
| 45 | // MARK: Bytes |
| 46 | static func lower(_ b: UInt8) -> UInt8 { b >= 65 && b <= 90 ? b + 32 : b } |
| 47 | static func equalFold(_ a: [UInt8], _ b: [UInt8]) -> Bool { |
| 48 | if a.count != b.count { return false } |
| 49 | var i = 0 |
| 50 | while i < a.count { if lower(a[i]) != lower(b[i]) { return false }; i += 1 } |
| 51 | return true |
| 52 | } |
| 53 | |
| 54 | /// -1, 0 or 1: order of two names, ASCII letters compared without case. |
| 55 | static func compareFold(_ a: [UInt8], _ b: [UInt8]) -> Int { |
| 56 | var i = 0 |
| 57 | while i < a.count && i < b.count { |
| 58 | let x = lower(a[i]), y = lower(b[i]) |
| 59 | if x != y { return x < y ? -1 : 1 } |
| 60 | i += 1 |
| 61 | } |
| 62 | return a.count == b.count ? 0 : (a.count < b.count ? -1 : 1) |
| 63 | } |
| 64 | |
| 65 | /// Does `text` hold `word` (given in lower case), ASCII letters compared without case? Used by the views' filter. |
| 66 | static func contains(_ text: [UInt8], _ word: [UInt8]) -> Bool { |
| 67 | if word.isEmpty || text.count < word.count { return false } |
| 68 | var i = 0 |
| 69 | while i + word.count <= text.count && i < maxTextBytes { |
| 70 | var k = 0 |
| 71 | while k < word.count && lower(text[i + k]) == word[k] { k += 1 } |
| 72 | if k == word.count { return true } |
| 73 | i += 1 |
| 74 | } |
| 75 | return false |
| 76 | } |
| 77 | |
| 78 | // MARK: Mentions and citations |
| 79 | |
| 80 | struct Spans { |
| 81 | var flat: [Int] = [] // [start, length, kind, value] per part, in text order |
| 82 | var clipped = false // the post has more parts than maxSpans; the rest is not marked |
| 83 | } |
| 84 | |
| 85 | /// The parts of a post that address someone or cite a post: "@name", "@all", "@#channel" and "#seq". |
| 86 | /// A mention counts only at a word start: the character before "@" must not be a name character, and |
| 87 | /// the name must not run on into more name characters. `head` is the highest sequence number that may be |
| 88 | /// cited; 0 turns citations off. For a member mention `value` is the member index, for a citation the |
| 89 | /// sequence number. Found by Omega code (`Omega/hopcore.om`, fn spans); nothing is marked in a post the |
| 90 | /// core cannot take (a name over 65535 bytes, 900000 bytes in all). |
| 91 | static func spans(_ text: [UInt8], names: [[UInt8]], head: Int) -> Spans { |
| 92 | var out = Spans() |
| 93 | let members = names.count < maxMembers ? names.count : maxMembers |
| 94 | let cite = UInt32(head < 0 ? 0 : (head > 4_000_000_000 ? 4_000_000_000 : head)) |
| 95 | var body: [UInt8] = [3, 0, 0, 0, UInt8(cite & 255), UInt8((cite >> 8) & 255), UInt8((cite >> 16) & 255), UInt8(cite >> 24), |
| 96 | UInt8(members & 255), UInt8(members >> 8)] |
| 97 | for k in 0..<members { |
| 98 | if names[k].count > 65535 { return out } |
| 99 | body += [UInt8(names[k].count & 255), UInt8(names[k].count >> 8)] + names[k] |
| 100 | } |
| 101 | if text.count > 900_000 || body.count + text.count > 1_000_000 { return out } |
| 102 | body += text |
| 103 | guard let r = OmegaCore.shared.request(kind: 5, body: body), r.count >= 8 else { return out } |
| 104 | let n = coreNumber(r, 0, 2) |
| 105 | if r.count != 8 + 16 * n { return out } |
| 106 | out.clipped = r[2] == 1 |
| 107 | out.flat.reserveCapacity(4 * n) |
| 108 | for k in 0..<(4 * n) { out.flat.append(coreNumber(r, 8 + 4 * k, 4)) } |
| 109 | return out |
| 110 | } |
| 111 | |
| 112 | struct Address { |
| 113 | var direct: [Int] = [] // member indexes called by name, in the header, or through a channel; the sender is left out |
| 114 | var all = false // addressed to everyone |
| 115 | } |
| 116 | |
| 117 | /// Who a post addresses: the members its header names, the members its text calls with "@name" or reaches |
| 118 | /// through "@#channel", and whether it says "@all". A member with no channel list follows its role's default: |
| 119 | /// the coordinator and helpers follow every channel, a worker only the main board. |
| 120 | /// Worked out by Omega code (`Omega/hopcore.om`, fn addr); a post the core cannot take addresses only what |
| 121 | /// its header says to all. |
| 122 | static func address(text: [UInt8], spans: [Int], sender: Int, headerTo: [Int], headerAll: Bool, |
| 123 | roles: [Int], channels: [[[UInt8]]]) -> Address { |
| 124 | var out = Address() |
| 125 | out.all = headerAll |
| 126 | let members = roles.count < maxMembers ? roles.count : maxMembers |
| 127 | let parts = spans.count / 4 < maxSpans ? spans.count / 4 : maxSpans |
| 128 | let headers = headerTo.count < maxRecipients ? headerTo.count : maxRecipients |
| 129 | func u32(_ v: Int) -> [UInt8] { |
| 130 | let x = UInt32(v < 0 || v > 4_000_000_000 ? 0xFFFF_FFFF : UInt32(v)) |
| 131 | return [UInt8(x & 255), UInt8((x >> 8) & 255), UInt8((x >> 16) & 255), UInt8(x >> 24)] |
| 132 | } |
| 133 | var body: [UInt8] = [4, 0, 0, 0, 0, 0, 0, 0, UInt8(members), 0, UInt8(parts), 0, UInt8(headers), 0, headerAll ? 1 : 0, 0] + u32(sender) |
| 134 | for m in 0..<members { body.append(roles[m] == roleWorker ? 0 : 1) } |
| 135 | for i in 0..<headers { body += u32(headerTo[i]) } |
| 136 | for k in 0..<(4 * parts) { body += u32(spans[k]) } |
| 137 | for m in 0..<members { |
| 138 | let list = m < channels.count ? channels[m] : [] |
| 139 | let n = list.count < maxRecipients ? list.count : maxRecipients |
| 140 | body.append(UInt8(n)) |
| 141 | for c in 0..<n { |
| 142 | if list[c].count > 65535 { return out } |
| 143 | body += [UInt8(list[c].count & 255), UInt8(list[c].count >> 8)] + list[c] |
| 144 | } |
| 145 | } |
| 146 | if body.count + text.count > 1_000_000 { return out } |
| 147 | body += text |
| 148 | guard let r = OmegaCore.shared.request(kind: 5, body: body), r.count >= 2, r.count == 2 + Int(r[1]) else { return out } |
| 149 | out.all = r[0] == 1 |
| 150 | out.direct = r[2...].map(Int.init) |
| 151 | return out |
| 152 | } |
| 153 | |
| 154 | // MARK: Time |
| 155 | |
| 156 | struct Time { |
| 157 | var ok = false |
| 158 | var epoch = 0 // seconds since 1970; as written when the text names no zone |
| 159 | var end = 0 // first byte after the time |
| 160 | var zoned = false // the text named its zone ("Z" or an offset) |
| 161 | } |
| 162 | |
| 163 | /// Reads "YYYY-MM-DD", optionally followed by "T" or one space and "HH:MM" or "HH:MM:SS", optionally |
| 164 | /// followed by "Z" or an offset such as "+00:00". Read by Omega code (`Omega/hopcore.om`, fn ltime). |
| 165 | static func parseTime(_ t: [UInt8], _ start: Int) -> Time { |
| 166 | var out = Time() |
| 167 | if start < 0 || start >= t.count { return out } |
| 168 | let part = t[start..<min(t.count, start + 64)] // a time is well under 64 bytes |
| 169 | guard let r = OmegaCore.shared.request(kind: 5, body: [2, 0, 0, 0, 0, 0, 0, 0] + part), r.count == 16, r[0] == 1 else { return out } |
| 170 | out.ok = true |
| 171 | out.zoned = r[1] == 1 |
| 172 | out.end = start + coreNumber(r, 4, 4) |
| 173 | out.epoch = coreNumber(r, 8, 8) - 100_000 |
| 174 | return out |
| 175 | } |
| 176 | |
| 177 | /// A little-endian number of `n` bytes at byte `o` of an answer from the Omega core. |
| 178 | static func coreNumber(_ r: [UInt8], _ o: Int, _ n: Int) -> Int { |
| 179 | var v = 0 |
| 180 | for k in 0..<n { v |= Int(r[o + k]) << (8 * k) } |
| 181 | return v |
| 182 | } |
| 183 | |
| 184 | // MARK: One line of a plain-text board |
| 185 | |
| 186 | struct Line { |
| 187 | var ok = false // false: not a post (no time at the start) |
| 188 | var time = 0 |
| 189 | var senders: [[UInt8]] = [] |
| 190 | var senderDetails: [[UInt8]] = [] // the bracket after each sender, "" when none |
| 191 | var recipients: [[UInt8]] = [] |
| 192 | var recipientDetails: [[UInt8]] = [] |
| 193 | var all = false // addressed to all |
| 194 | var text: [UInt8] = [] |
| 195 | var clipped = false // the line, its senders, its recipients or its text went over a limit |
| 196 | } |
| 197 | |
| 198 | /// Cuts text to `limit` bytes without splitting a character. |
| 199 | static func clip(_ t: [UInt8], _ limit: Int) -> [UInt8] { |
| 200 | if t.count <= limit { return t } |
| 201 | var end = limit, back = 0 |
| 202 | while end > 0 && back < 3 && (t[end] & 0xC0) == 0x80 { end -= 1; back += 1 } |
| 203 | return Array(t[0..<end]) |
| 204 | } |
| 205 | |
| 206 | /// Reads one board line of the form |
| 207 | /// <time> <sender> (<detail>) to <recipient> + <recipient> (<detail>): <text> |
| 208 | /// Also read: several senders joined by " + ", no "to" part, recipients written "@name" instead of |
| 209 | /// "to name", a leading "- ", and words between the sender's bracket and the colon (they stay in the text). |
| 210 | /// A line that does not start with a time is not a post (`ok` false). A header that does not fit the form |
| 211 | /// is read plainly: the first word is the sender, the rest is the text. |
| 212 | /// Read by Omega code (`Omega/hopcore.om`, fn lline), which answers where each part sits in the line. |
| 213 | static func parseLine(_ raw: [UInt8]) -> Line { |
| 214 | var out = Line() |
| 215 | // One byte past the limit lets the core see that the line is too long and cut it at a whole character. |
| 216 | let part = raw.count > maxLineBytes + 1 ? raw[0...maxLineBytes] : raw[...] |
| 217 | guard let r = OmegaCore.shared.request(kind: 5, body: [1, 0, 0, 0, 0, 0, 0, 0] + part), r.count == 344 else { return out } |
| 218 | out.clipped = r[2] == 1 |
| 219 | if r[0] != 1 { return out } |
| 220 | out.ok = true |
| 221 | out.all = r[1] == 1 |
| 222 | out.time = coreNumber(r, 8, 8) - 100_000 |
| 223 | func piece(_ o: Int) -> [UInt8] { |
| 224 | let s = coreNumber(r, o, 4), l = coreNumber(r, o + 4, 4) |
| 225 | return l > 0 && s + l <= raw.count ? Array(raw[s..<(s + l)]) : [] |
| 226 | } |
| 227 | for k in 0..<min(Int(r[3]), maxSenders) { out.senders.append(piece(24 + 16 * k)); out.senderDetails.append(piece(32 + 16 * k)) } |
| 228 | for k in 0..<min(Int(r[4]), maxRecipients) { out.recipients.append(piece(88 + 16 * k)); out.recipientDetails.append(piece(96 + 16 * k)) } |
| 229 | out.text = piece(16) |
| 230 | return out |
| 231 | } |
| 232 | |
| 233 | // MARK: A whole plain-text board |
| 234 | |
| 235 | struct Board { |
| 236 | var names: [[UInt8]] = [] // one per member, in its newest spelling |
| 237 | var details: [[UInt8]] = [] // the newest bracket written after that member as a sender |
| 238 | var alsoCalled: [[UInt8]] = [] // other spellings joined to the same member, comma-separated |
| 239 | var postSeq: [Int] = [] |
| 240 | var postTime: [Int] = [] |
| 241 | var postSender: [Int] = [] // member index; -1 when the sender did not fit in the member table |
| 242 | var postSenderName: [[UInt8]] = [] // as written |
| 243 | var postWith: [[Int]] = [] // other members who signed the same post |
| 244 | var postTo: [[Int]] = [] // members the header names |
| 245 | var postAll: [Int] = [] |
| 246 | var postText: [[UInt8]] = [] |
| 247 | var lines = 0 // lines given |
| 248 | var olderLinesDropped = 0 // lines beyond maxPosts: the oldest ones, not read |
| 249 | var skippedLines = 0 // lines that are not posts |
| 250 | var clippedLines = 0 // posts that went over a limit and were cut |
| 251 | var membersDropped = 0 // agents named on the board beyond maxMembers: not listed as members |
| 252 | var spellingsDropped = 0 // times a name was met after the table of spellings was full |
| 253 | } |
| 254 | |
| 255 | /// Turns the lines of a plain-text board into posts and members. A post's sequence number is its line |
| 256 | /// number: `firstSeq` is the number of the first line given. Senders and recipients become members. |
| 257 | /// A name in a bracket is the same agent as the name before the bracket when that bracketed name is used |
| 258 | /// as a sender or recipient elsewhere and stands in the brackets of one agent only: so |
| 259 | /// "merge-desk (omp-queen-spark)" and "omp-queen-spark (merge desk)" are one member, while a shared word |
| 260 | /// such as a machine name joins nobody. A name written without its lane ("Worker" for "lane/Worker") is that |
| 261 | /// agent when exactly one sender on the board posts under a name that ends that way. |
| 262 | /// Worked out by Omega code (`Omega/hopcore.om`, fn asm) from what each line names; this function reads |
| 263 | /// the lines (fn lline), sends their names and brackets, and fills the board from the answer. |
| 264 | static func assemble(lines: [[UInt8]], firstSeq: Int) -> Board { |
| 265 | var board = Board() |
| 266 | board.lines = lines.count |
| 267 | let start = lines.count > maxPosts ? lines.count - maxPosts : 0 |
| 268 | board.olderLinesDropped = start |
| 269 | var parsed: [Line] = [] |
| 270 | var i = start |
| 271 | while i < lines.count { parsed.append(parseLine(lines[i])); i += 1 } |
| 272 | func counted(_ t: [UInt8]) -> [UInt8] { [UInt8(t.count & 255), UInt8((t.count >> 8) & 255)] + t } |
| 273 | var body: [UInt8] = [UInt8(parsed.count & 255), UInt8(parsed.count >> 8), 0, 0] |
| 274 | for line in parsed { |
| 275 | let ns = line.ok ? (line.senders.count < maxSenders ? line.senders.count : maxSenders) : 0 |
| 276 | let nr = line.ok ? (line.recipients.count < maxRecipients ? line.recipients.count : maxRecipients) : 0 |
| 277 | body += [line.ok ? 1 : 0, line.clipped ? 1 : 0, UInt8(ns), UInt8(nr)] |
| 278 | for k in 0..<ns { body += counted(line.senders[k]) + counted(k < line.senderDetails.count ? line.senderDetails[k] : []) } |
| 279 | for k in 0..<nr { body += counted(line.recipients[k]) + counted(k < line.recipientDetails.count ? line.recipientDetails[k] : []) } |
| 280 | } |
| 281 | guard body.count <= 1_000_000, let r = OmegaCore.shared.request(kind: 6, body: body), r.count >= 24 else { return board } |
| 282 | let members = coreNumber(r, 0, 2), joined = coreNumber(r, 2, 2), posts = coreNumber(r, 4, 2) |
| 283 | board.skippedLines = coreNumber(r, 8, 4); board.clippedLines = coreNumber(r, 12, 4) |
| 284 | board.membersDropped = coreNumber(r, 16, 4); board.spellingsDropped = coreNumber(r, 20, 4) |
| 285 | func spelling(_ o: Int) -> [UInt8] { |
| 286 | let li = coreNumber(r, o, 2), side = Int(r[o + 2]), k = Int(r[o + 3]) |
| 287 | guard li < parsed.count else { return [] } |
| 288 | let list = side == 0 ? parsed[li].senders : parsed[li].recipients |
| 289 | return k < list.count ? list[k] : [] |
| 290 | } |
| 291 | var o = 24 |
| 292 | guard r.count >= o + 8 * members + 6 * joined else { return board } |
| 293 | for _ in 0..<members { |
| 294 | board.names.append(spelling(o)) |
| 295 | let li = coreNumber(r, o + 4, 2), k = Int(r[o + 6]) |
| 296 | board.details.append(li < parsed.count && k < parsed[li].senderDetails.count ? parsed[li].senderDetails[k] : []) |
| 297 | board.alsoCalled.append([]) |
| 298 | o += 8 |
| 299 | } |
| 300 | for _ in 0..<joined { |
| 301 | let m = Int(r[o]) |
| 302 | if m < members { |
| 303 | if !board.alsoCalled[m].isEmpty { board.alsoCalled[m] += [44, 32] } |
| 304 | board.alsoCalled[m] += spelling(o + 2) |
| 305 | } |
| 306 | o += 6 |
| 307 | } |
| 308 | var li = 0, done = 0 |
| 309 | while li < parsed.count && done < posts { |
| 310 | let line = parsed[li] |
| 311 | if !line.ok { li += 1; continue } |
| 312 | guard o + 3 <= r.count else { break } |
| 313 | let nw = Int(r[o + 1]), nt = Int(r[o + 2]) |
| 314 | guard o + 3 + nw + nt <= r.count else { break } |
| 315 | board.postSeq.append(firstSeq + start + li) |
| 316 | board.postTime.append(line.time) |
| 317 | board.postSender.append(r[o] == 255 ? -1 : Int(r[o])) |
| 318 | board.postSenderName.append(line.senders.isEmpty ? [] : line.senders[0]) |
| 319 | board.postWith.append(r[(o + 3)..<(o + 3 + nw)].map(Int.init)) |
| 320 | board.postTo.append(r[(o + 3 + nw)..<(o + 3 + nw + nt)].map(Int.init)) |
| 321 | board.postAll.append(line.all ? 1 : 0) |
| 322 | board.postText.append(line.text) |
| 323 | o += 3 + nw + nt |
| 324 | done += 1 |
| 325 | li += 1 |
| 326 | } |
| 327 | return board |
| 328 | } |
| 329 | |
| 330 | // MARK: Asking the Omega core about members and the graph (kind 7) |
| 331 | // Every number travels as the value plus 2^40, so that -1 ("not known", "none") is an unsigned number. |
| 332 | |
| 333 | static let coreBias = 1_099_511_627_776 |
| 334 | |
| 335 | /// One request of kind 7: an op, numbers, and bytes when the op reads a text. nil when the core cannot take it. |
| 336 | static func status(_ op: Int, _ numbers: [Int], bytes: [UInt8] = []) -> [UInt8]? { |
| 337 | if 8 + 8 * numbers.count + bytes.count > 1_000_000 { return nil } |
| 338 | var body: [UInt8] = [UInt8(op), 0, 0, 0] |
| 339 | body.reserveCapacity(8 + 8 * numbers.count + bytes.count) |
| 340 | var c = UInt32(numbers.count) |
| 341 | for _ in 0..<4 { body.append(UInt8(c & 255)); c >>= 8 } |
| 342 | for v in numbers { |
| 343 | var x = UInt64((v < -coreBias / 2 ? -coreBias / 2 : (v > coreBias / 2 ? coreBias / 2 : v)) + coreBias) |
| 344 | for _ in 0..<8 { body.append(UInt8(x & 255)); x >>= 8 } |
| 345 | } |
| 346 | return OmegaCore.shared.request(kind: 7, body: body + bytes) |
| 347 | } |
| 348 | |
| 349 | /// The numbers of an answer. |
| 350 | static func statusNumbers(_ op: Int, _ numbers: [Int], bytes: [UInt8] = []) -> [Int]? { |
| 351 | guard let r = status(op, numbers, bytes: bytes), r.count % 8 == 0 else { return nil } |
| 352 | return (0..<(r.count / 8)).map { coreNumber(r, 8 * $0, 8) - coreBias } |
| 353 | } |
| 354 | |
| 355 | static func statusNumber(_ op: Int, _ numbers: [Int], bytes: [UInt8] = [], else fallback: Int) -> Int { |
| 356 | guard let v = statusNumbers(op, numbers, bytes: bytes), v.count == 1 else { return fallback } |
| 357 | return v[0] |
| 358 | } |
| 359 | |
| 360 | // MARK: Roster roles |
| 361 | |
| 362 | /// The role code of a roster member. The coordinator leads; a member with any role other than "worker", or |
| 363 | /// with a helper's name ("narrator", "monitor", or either with "-<digits>"), is a helper: it is left out of |
| 364 | /// the member counts and of the graph. (fn swrole) |
| 365 | static func roleCode(role: [UInt8], name: [UInt8]) -> Int { |
| 366 | statusNumber(11, [role.count, name.count], bytes: role + name, else: roleWorker) |
| 367 | } |
| 368 | |
| 369 | // MARK: A member's own run (roster swarms) |
| 370 | |
| 371 | /// Has the member's run stopped? Told from its newest steps, oldest first in the arrays: `kinds` and |
| 372 | /// `statuses` per step, and for a planner step how many tools it called (`tools`) and which of them was |
| 373 | /// the wait-for-posts call (`waits`, -1 when none). The run has stopped when the newest planner step called |
| 374 | /// no tool and nothing came after it, or when it called the wait and that call's own result is done. |
| 375 | /// Anything newer (a system message, a result still running, a torn line) means it is mid-turn. (fn swturn) |
| 376 | static func turn(kinds: [Int], statuses: [Int], tools: [Int], waits: [Int]) -> Int { |
| 377 | let n = kinds.count |
| 378 | if statuses.count != n || tools.count != n || waits.count != n { |
| 379 | return statusNumber(8, [kinds.count, statuses.count, tools.count, waits.count], else: turnUnknown) |
| 380 | } |
| 381 | let k = n < 2048 ? n : 2048 // only the newest steps are looked at |
| 382 | return statusNumber(8, [k, k, k, k] + kinds.suffix(k) + statuses.suffix(k) + tools.suffix(k) + waits.suffix(k), else: turnUnknown) |
| 383 | } |
| 384 | |
| 385 | /// The step that says what the member is doing now: the newest planner step of the current turn that has |
| 386 | /// a label (`labelled` 1). A turn starts after user input or after a wait for posts, so an older label is |
| 387 | /// never shown as current. -1 when there is none. (fn swact) |
| 388 | static func activityStep(kinds: [Int], waits: [Int], labelled: [Int]) -> Int { |
| 389 | let n = kinds.count |
| 390 | if waits.count != n || labelled.count != n { return statusNumber(9, [kinds.count, waits.count, labelled.count], else: -1) } |
| 391 | let k = n < 2048 ? n : 2048 |
| 392 | let at = statusNumber(9, [k, k, k] + kinds.suffix(k) + waits.suffix(k) + labelled.suffix(k), else: -1) |
| 393 | return at < 0 ? -1 : at + (n - k) |
| 394 | } |
| 395 | |
| 396 | /// Does an error text say the member ran out of quota or was rate limited? (fn swquota) |
| 397 | static func looksLikeQuota(_ text: [UInt8]) -> Bool { |
| 398 | statusNumber(10, [], bytes: Array(text.prefix(maxTextBytes + 64)), else: 0) == 1 |
| 399 | } |
| 400 | |
| 401 | /// How a member's newest step failed: a model error counts at once, a failed tool step once it has stayed |
| 402 | /// the newest step for failureSettleSeconds (the member usually carries on after one). |
| 403 | static func failure(lastKind: Int, lastStatus: Int, idleSeconds: Int, quota: Bool) -> Int { |
| 404 | statusNumber(6, [lastKind, lastStatus, idleSeconds, quota ? 1 : 0], else: attentionNone) |
| 405 | } |
| 406 | |
| 407 | // MARK: Status |
| 408 | |
| 409 | /// A member's state is worked out, never taken from what it says about itself. |
| 410 | /// With a roster: stopped when it was killed; otherwise waiting when its own run has stopped and working |
| 411 | /// when it is mid-turn; with no transcript to go on, waiting when it is parked for mentions or for any post. |
| 412 | /// On a board with no roster: working when it posted within activeSeconds, waiting otherwise. (fn swstate) |
| 413 | static func state(killed: Bool, turn: Int, wake: Int, hasRoster: Bool, lastPostAge: Int) -> Int { |
| 414 | statusNumber(1, [killed ? 1 : 0, turn, wake, hasRoster ? 1 : 0, lastPostAge], else: stateWaiting) |
| 415 | } |
| 416 | |
| 417 | /// What needs a look: a failed newest step (error or quota), or a member that should be working and has |
| 418 | /// not moved for more than stuckSeconds. `idleSeconds` is -1 when its last movement is not known. (fn swatt) |
| 419 | static func attention(state: Int, failure: Int, idleSeconds: Int) -> Int { |
| 420 | statusNumber(2, [state, failure, idleSeconds], else: attentionNone) |
| 421 | } |
| 422 | |
| 423 | /// Posts the member has not read: the newest sequence number minus the last one it read. -1 when not known. |
| 424 | static func unread(head: Int, lastRead: Int) -> Int { |
| 425 | statusNumber(3, [head, lastRead], else: -1) |
| 426 | } |
| 427 | |
| 428 | /// The Overview group of one member. (fn swgroup) |
| 429 | static func group(state: Int, attention: Int, asksYou: Bool, waitingOn: Bool) -> Int { |
| 430 | statusNumber(4, [state, attention, asksYou ? 1 : 0, waitingOn ? 1 : 0], else: groupParked) |
| 431 | } |
| 432 | |
| 433 | /// Is this post the first row of a visual group? Posts by the same sender, next to each other and at most |
| 434 | /// groupSeconds apart, are drawn as one group. (fn swstarts) |
| 435 | static func startsGroup(previousSender: Int, previousTime: Int, sender: Int, time: Int) -> Bool { |
| 436 | statusNumber(5, [previousSender, previousTime, sender, time], else: 1) == 1 |
| 437 | } |
| 438 | |
| 439 | // MARK: The whole picture |
| 440 | |
| 441 | struct Input { |
| 442 | var hasRoster = false |
| 443 | var now = 0 // seconds since 1970 |
| 444 | var citeHead = 0 // highest "#seq" that may be cited; 0 turns citations off |
| 445 | var names: [[UInt8]] = [] |
| 446 | var roles: [Int] = [] |
| 447 | var killed: [Int] = [] |
| 448 | var wake: [Int] = [] |
| 449 | var turn: [Int] = [] |
| 450 | var lastRead: [Int] = [] // -1 not known |
| 451 | var lastMove: [Int] = [] // seconds since 1970 of the member's last own movement; 0 not known |
| 452 | var failure: [Int] = [] // from failure() |
| 453 | var channels: [[[UInt8]]] = [] |
| 454 | var owner: [Int] = [] // 1: this member is the person using Hop |
| 455 | var postSeq: [Int] = [] |
| 456 | var postTime: [Int] = [] // 0 not known |
| 457 | var postSender: [Int] = [] // member index or -1 |
| 458 | var postWith: [[Int]] = [] |
| 459 | var postTo: [[Int]] = [] |
| 460 | var postAll: [Int] = [] |
| 461 | var postText: [[UInt8]] = [] |
| 462 | } |
| 463 | |
| 464 | struct Derived { |
| 465 | var refused = 0 // 0 fine; otherwise why nothing was worked out |
| 466 | var head = 0 // newest sequence number |
| 467 | var postDirect: [[Int]] = [] // members each post addresses by name |
| 468 | var postAll: [Int] = [] |
| 469 | var postSpans: [[Int]] = [] |
| 470 | var postStartsGroup: [Int] = [] |
| 471 | var postsWithClippedSpans = 0 |
| 472 | var state: [Int] = [] |
| 473 | var attention: [Int] = [] |
| 474 | var idleSeconds: [Int] = [] // -1 not known |
| 475 | var unread: [Int] = [] // -1 not known |
| 476 | var postCount: [Int] = [] |
| 477 | var lastPost: [Int] = [] // index of the member's newest post, -1 when none |
| 478 | var waitingOn: [Int] = [] // member index, -1 when none |
| 479 | var waitingSeq: [Int] = [] |
| 480 | var asksYouSeq: [Int] = [] // sequence number of the unanswered post to the owner, 0 when none |
| 481 | var group: [Int] = [] |
| 482 | var helper: [Int] = [] |
| 483 | var overviewOrder: [Int] = [] // by group, coordinator first, then name (no roster: those who posted first) |
| 484 | var memberOrder: [Int] = [] // working, waiting, stopped; coordinator first; then name (no roster: those who posted first) |
| 485 | var working = 0, waiting = 0, stopped = 0 // task members only: helpers are not counted |
| 486 | } |
| 487 | |
| 488 | /// Works out everything the four views show. Input over a limit, arrays of different lengths and indexes |
| 489 | /// that point nowhere are refused with a code; nothing is cut here. Who each post calls and addresses comes |
| 490 | /// from fn spans and fn addr, everything about the members from fn swderive (`Omega/hopcore.om`). |
| 491 | static func derive(_ input: Input) -> Derived { |
| 492 | var out = Derived() |
| 493 | let n = input.names.count, p = input.postSeq.count |
| 494 | if n > maxMembers { out.refused = refusedMembers; return out } |
| 495 | if p > maxPosts { out.refused = refusedPosts; return out } |
| 496 | if input.roles.count != n || input.killed.count != n || input.wake.count != n || input.turn.count != n || input.lastRead.count != n |
| 497 | || input.lastMove.count != n || input.failure.count != n || input.channels.count != n || input.owner.count != n |
| 498 | || input.postTime.count != p || input.postSender.count != p || input.postWith.count != p || input.postTo.count != p |
| 499 | || input.postAll.count != p || input.postText.count != p { out.refused = refusedShape; return out } |
| 500 | var i = 0 |
| 501 | while i < p { |
| 502 | if input.postSender[i] < -1 || input.postSender[i] >= n || input.postText[i].count > maxTextBytes { out.refused = refusedValue; return out } |
| 503 | if input.postWith[i].count > maxSenders || input.postTo[i].count > maxRecipients { out.refused = refusedValue; return out } |
| 504 | var k = 0 |
| 505 | while k < input.postWith[i].count { if input.postWith[i][k] < 0 || input.postWith[i][k] >= n { out.refused = refusedValue; return out }; k += 1 } |
| 506 | k = 0 |
| 507 | while k < input.postTo[i].count { if input.postTo[i][k] < 0 || input.postTo[i][k] >= n { out.refused = refusedValue; return out }; k += 1 } |
| 508 | i += 1 |
| 509 | } |
| 510 | i = 0 |
| 511 | while i < p { |
| 512 | let found = spans(input.postText[i], names: input.names, head: input.citeHead) |
| 513 | if found.clipped { out.postsWithClippedSpans += 1 } |
| 514 | let to = address(text: input.postText[i], spans: found.flat, sender: input.postSender[i], headerTo: input.postTo[i], |
| 515 | headerAll: input.postAll[i] == 1, roles: input.roles, channels: input.channels) |
| 516 | out.postSpans.append(found.flat) |
| 517 | out.postDirect.append(to.direct) |
| 518 | out.postAll.append(to.all ? 1 : 0) |
| 519 | i += 1 |
| 520 | } |
| 521 | var numbers = [input.hasRoster ? 1 : 0, input.now, n, p] |
| 522 | var names: [UInt8] = [] |
| 523 | for m in 0..<n { |
| 524 | numbers += [input.roles[m], input.killed[m], input.wake[m], input.turn[m], input.lastRead[m], input.lastMove[m], input.failure[m], |
| 525 | input.owner[m], input.names[m].count] |
| 526 | names += input.names[m] |
| 527 | } |
| 528 | for k in 0..<p { |
| 529 | numbers += [input.postSeq[k], input.postTime[k], input.postSender[k], input.postWith[k].count] + input.postWith[k] |
| 530 | numbers += [out.postDirect[k].count] + out.postDirect[k] |
| 531 | } |
| 532 | guard let v = statusNumbers(16, numbers, bytes: names), v.count == 4 + p + 13 * n else { |
| 533 | var refused = Derived(); refused.refused = refusedValue; return refused |
| 534 | } |
| 535 | out.head = v[0]; out.working = v[1]; out.waiting = v[2]; out.stopped = v[3] |
| 536 | out.postStartsGroup = Array(v[4..<(4 + p)]) |
| 537 | func list(_ k: Int) -> [Int] { Array(v[(4 + p + k * n)..<(4 + p + (k + 1) * n)]) } |
| 538 | out.postCount = list(0); out.lastPost = list(1); out.state = list(2); out.attention = list(3); out.idleSeconds = list(4) |
| 539 | out.unread = list(5); out.helper = list(6); out.waitingOn = list(7); out.waitingSeq = list(8); out.asksYouSeq = list(9) |
| 540 | out.group = list(10); out.overviewOrder = list(11); out.memberOrder = list(12) |
| 541 | return out |
| 542 | } |
| 543 | |
| 544 | // MARK: Graph |
| 545 | |
| 546 | /// Who addressed whom in the first `upTo` posts, as rows [from, to, count, direct, viaAll] ordered by sender |
| 547 | /// then receiver. `count` is how many posts went from one to the other: `direct` of them named the |
| 548 | /// receiver, `viaAll` reached it only because the post was for everyone. Helpers are left out. (fn swedges) |
| 549 | static func edges(memberCount: Int, helper: [Int], postSender: [Int], postWith: [[Int]], postDirect: [[Int]], |
| 550 | postAll: [Int], upTo: Int) -> [Int] { |
| 551 | var numbers = [memberCount, upTo, postSender.count, helper.count, postWith.count, postDirect.count, postAll.count] |
| 552 | numbers += helper.prefix(maxMembers) |
| 553 | var posts = postSender.count |
| 554 | for c in [postWith.count, postDirect.count, postAll.count, maxPosts] where c < posts { posts = c } |
| 555 | for i in 0..<posts { |
| 556 | let w = postWith[i].prefix(maxSenders), d = postDirect[i].prefix(maxMembers) |
| 557 | numbers += [postSender[i], w.count] + w + [d.count] + d + [postAll[i]] |
| 558 | } |
| 559 | guard let r = status(12, numbers) else { return [] } |
| 560 | var out: [Int] = [] |
| 561 | var o = 0 |
| 562 | while o + 6 <= r.count { |
| 563 | let direct = Int(r[o + 2]) | Int(r[o + 3]) << 8, all = Int(r[o + 4]) | Int(r[o + 5]) << 8 |
| 564 | out += [Int(r[o]), Int(r[o + 1]), direct + all, direct, all] |
| 565 | o += 6 |
| 566 | } |
| 567 | return out |
| 568 | } |
| 569 | |
| 570 | /// How many of the first `upTo` posts each member sent to everyone. (fn swbroad) |
| 571 | static func broadcasts(memberCount: Int, postSender: [Int], postAll: [Int], upTo: Int) -> [Int] { |
| 572 | var numbers = [memberCount, upTo, postSender.count, postAll.count] |
| 573 | var posts = postSender.count |
| 574 | for c in [postAll.count, maxPosts] where c < posts { posts = c } |
| 575 | for i in 0..<posts { numbers += [postSender[i], postAll[i]] } |
| 576 | return statusNumbers(13, numbers) ?? [Int](repeating: 0, count: memberCount > 0 && memberCount <= maxMembers ? memberCount : 0) |
| 577 | } |
| 578 | |
| 579 | /// Which members to draw when there are too many for one picture: the `keep` members with the most posts to |
| 580 | /// or from others (the earlier member wins a tie). `edges` are rows from edges(); `withAll` also counts posts |
| 581 | /// for everyone. One 0/1 flag per member; a member with no line at all is never picked. (fn swbusy) |
| 582 | static func busiest(memberCount: Int, edges: [Int], withAll: Bool, keep: Int) -> [Int] { |
| 583 | let rows = edges.prefix(maxMembers * maxMembers * 5 + 5) |
| 584 | guard let r = status(14, [memberCount, withAll ? 1 : 0, keep, rows.count] + rows) else { return [] } |
| 585 | return r.map(Int.init) |
| 586 | } |
| 587 | |
| 588 | /// Line weight for an edge, 1 (lightest) to 5, by its count against the heaviest edge shown. |
| 589 | static func weightStep(count: Int, heaviest: Int) -> Int { |
| 590 | statusNumber(7, [count, heaviest], else: 1) |
| 591 | } |
| 592 | } |