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 / SwarmReference.swift

1171 lines · 58246 bytes Raw Blame History
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/// The Swarm logic as Hop shipped it in Swift, kept only as the reference the Omega core is checked against.
13enum SwarmReference {
14 // MARK: Limits
15 static let maxPosts = 400 // newest posts kept from one board
16 static let maxMembers = 96 // members of one swarm
17 static let maxNames = 192 // spellings seen on a plain-text board, before two names of one agent are joined
18 static let maxSenders = 4 // agents signing one post
19 static let maxRecipients = 16 // agents one post header may address
20 static let maxNameBytes = 64
21 static let maxNameWords = 3
22 static let maxHeaderBytes = 600 // the part of a board line before its ": "
23 static let maxLineBytes = 65536
24 static let maxTextBytes = 32768 // text kept from one post
25 static let maxSpans = 128 // highlighted parts of one post
26 static let maxSteps = 256 // newest steps looked at in a member's transcript
27 static let maxDetailItems = 8 // comma-separated items in a bracket after a name
28
29 static let stuckSeconds = 600 // working, but no movement for longer than this: stuck
30 static let failureSettleSeconds = 60 // a failed tool step counts once it stayed last this long
31 static let activeSeconds = 900 // on a board with no roster: posted within this long = working
32 static let groupSeconds = 600 // posts by one sender this close together are drawn as one group
33
34 // MARK: Codes
35 static let roleWorker = 0, roleCoordinator = 1, roleHelper = 2 // helper: narrator, monitor and other non-task roles
36 static let wakeUnknown = 0, wakeWorking = 1, wakeMentions = 2, wakeAnything = 3
37 static let turnUnknown = 0, turnRunning = 1, turnEnded = 2
38 static let stateWorking = 1, stateWaiting = 2, stateStopped = 3
39 static let attentionNone = 0, attentionStuck = 1, attentionError = 2, attentionQuota = 3
40 static let groupNeedsYou = 1, groupWorking = 2, groupWaitingOn = 3, groupParked = 4
41 static let stepOther = 0, stepPlanner = 1, stepResult = 2, stepUser = 3, stepError = 4, stepTorn = 5
42 static let statusOther = 0, statusDone = 1, statusError = 2, statusRunning = 3
43 static let spanMember = 1, spanAll = 2, spanChannel = 3, spanCite = 4
44 static let refusedMembers = 1, refusedPosts = 2, refusedShape = 3, refusedValue = 4
45
46 // MARK: Bytes
47 static func lower(_ b: UInt8) -> UInt8 { b >= 65 && b <= 90 ? b + 32 : b }
48 static func isDigit(_ b: UInt8) -> Bool { b >= 48 && b <= 57 }
49 static func isLetter(_ b: UInt8) -> Bool { (b >= 65 && b <= 90) || (b >= 97 && b <= 122) }
50 static func isSpace(_ b: UInt8) -> Bool { b == 32 || b == 9 }
51
52 /// The character that starts at byte `i`, as a code point, or -1 outside the text. A broken sequence gives its first byte.
53 static func runeAt(_ t: [UInt8], _ i: Int) -> Int {
54 if i < 0 || i >= t.count { return -1 }
55 let b0 = Int(t[i])
56 var need = 0, cp = 0
57 if b0 < 0x80 || b0 >= 0xF8 { return b0 }
58 if b0 >= 0xF0 { need = 3; cp = b0 & 0x07 } else if b0 >= 0xE0 { need = 2; cp = b0 & 0x0F } else if b0 >= 0xC0 { need = 1; cp = b0 & 0x1F } else { return b0 }
59 var k = 1
60 while k <= need {
61 if i + k >= t.count || (t[i + k] & 0xC0) != 0x80 { return b0 }
62 cp = (cp << 6) | Int(t[i + k] & 0x3F)
63 k += 1
64 }
65 return cp
66 }
67
68 /// The character that ends just before byte `end`, or -1 at the start of the text.
69 static func runeBefore(_ t: [UInt8], _ end: Int) -> Int {
70 if end <= 0 || end > t.count { return -1 }
71 var i = end - 1, back = 0
72 while i > 0 && back < 3 && (t[i] & 0xC0) == 0x80 { i -= 1; back += 1 }
73 return runeAt(t, i)
74 }
75
76 /// Can this character be part of a name? Letters, digits, "_" and "-". Outside ASCII everything counts as a
77 /// letter except the blocks that hold punctuation, symbols and emoji.
78 static func isNameRune(_ cp: Int) -> Bool {
79 if cp < 0 { return false }
80 if cp < 0x80 { return (cp >= 48 && cp <= 57) || (cp >= 65 && cp <= 90) || (cp >= 97 && cp <= 122) || cp == 95 || cp == 45 }
81 if cp < 0xC0 || cp == 0xD7 || cp == 0xF7 { return false }
82 if cp >= 0x2000 && cp <= 0x2BFF { return false }
83 if cp >= 0x3000 && cp <= 0x303F { return false }
84 if cp >= 0xFE30 && cp <= 0xFE6F { return false }
85 if (cp >= 0xFF00 && cp <= 0xFF0F) || (cp >= 0xFF1A && cp <= 0xFF20) || (cp >= 0xFF3B && cp <= 0xFF40) || (cp >= 0xFF5B && cp <= 0xFF65) { return false }
86 if cp >= 0x1F000 && cp <= 0x1FAFF { return false }
87 return true
88 }
89
90 static func equalFold(_ a: [UInt8], _ b: [UInt8]) -> Bool {
91 if a.count != b.count { return false }
92 var i = 0
93 while i < a.count { if lower(a[i]) != lower(b[i]) { return false }; i += 1 }
94 return true
95 }
96
97 /// -1, 0 or 1: order of two names, ASCII letters compared without case.
98 static func compareFold(_ a: [UInt8], _ b: [UInt8]) -> Int {
99 var i = 0
100 while i < a.count && i < b.count {
101 let x = lower(a[i]), y = lower(b[i])
102 if x != y { return x < y ? -1 : 1 }
103 i += 1
104 }
105 return a.count == b.count ? 0 : (a.count < b.count ? -1 : 1)
106 }
107
108 /// The bytes from `from` up to `to`, without spaces at either end.
109 static func trimmed(_ t: [UInt8], _ from: Int, _ to: Int) -> [UInt8] {
110 var a = from < 0 ? 0 : from, b = to > t.count ? t.count : to
111 while a < b && isSpace(t[a]) { a += 1 }
112 while b > a && isSpace(t[b - 1]) { b -= 1 }
113 return a < b ? Array(t[a..<b]) : []
114 }
115
116 static func wordCount(_ t: [UInt8]) -> Int {
117 var n = 0, i = 0, inWord = false
118 while i < t.count {
119 if isSpace(t[i]) { inWord = false } else if !inWord { inWord = true; n += 1 }
120 i += 1
121 }
122 return n
123 }
124
125 /// The form two spellings of one name share: no leading "@", ASCII lower case, each run of spaces as one "-".
126 static func nameKey(_ name: [UInt8]) -> [UInt8] {
127 let t = trimmed(name, 0, name.count)
128 var out: [UInt8] = []
129 var i = (t.count > 0 && t[0] == 64) ? 1 : 0
130 var gap = false
131 while i < t.count {
132 if isSpace(t[i]) { gap = true } else {
133 if gap && !out.isEmpty { out.append(45) }
134 gap = false
135 out.append(lower(t[i]))
136 }
137 i += 1
138 }
139 return out
140 }
141
142 // MARK: Mentions and citations
143
144 /// True when the first `length` bytes of `name` stand at byte `at` of `text` (ASCII letters compared without
145 /// case) and are followed by the end of the text or by a character that cannot be part of a name.
146 static func nameAt(_ text: [UInt8], _ at: Int, _ name: [UInt8], _ length: Int) -> Bool {
147 if length <= 0 || length > name.count || at < 0 || at + length > text.count { return false }
148 var k = 0
149 while k < length { if lower(text[at + k]) != lower(name[k]) { return false }; k += 1 }
150 return !isNameRune(runeAt(text, at + length))
151 }
152
153 /// A member called "<prefix>-<digits>" also answers to "@<prefix>". The length of that prefix, or 0.
154 static func copyPrefix(_ name: [UInt8]) -> Int {
155 var i = name.count
156 while i > 0 && isDigit(name[i - 1]) { i -= 1 }
157 if i == name.count || i < 2 || name[i - 1] != 45 { return 0 }
158 return i - 1
159 }
160
161 /// The length of a channel name at byte `at` (after "@#"): a letter, then letters, digits and "-", 24 at most.
162 static func channelLength(_ t: [UInt8], _ at: Int) -> Int {
163 if at >= t.count || !isLetter(t[at]) { return 0 }
164 var j = at
165 while j < t.count && j - at < 25 && (isLetter(t[j]) || isDigit(t[j]) || t[j] == 45) { j += 1 }
166 let len = j - at
167 if len > 24 || isNameRune(runeAt(t, j)) { return 0 }
168 return len
169 }
170
171 struct Spans {
172 var flat: [Int] = [] // [start, length, kind, value] per part, in text order
173 var clipped = false // the post has more parts than maxSpans; the rest is not marked
174 }
175
176 /// The parts of a post that address someone or cite a post: "@name", "@all", "@#channel" and "#seq".
177 /// A mention counts only at a word start: the character before "@" must not be a name character, and
178 /// the name must not run on into more name characters. `head` is the highest sequence number that may be
179 /// cited; 0 turns citations off. For a member mention `value` is the member index, for a citation the
180 /// sequence number.
181 static func spans(_ text: [UInt8], names: [[UInt8]], head: Int) -> Spans {
182 var out = Spans()
183 let n = text.count, members = names.count < maxMembers ? names.count : maxMembers
184 let all: [UInt8] = [97, 108, 108]
185 var i = 0
186 while i < n {
187 let b = text[i]
188 if (b != 64 && b != 35) || isNameRune(runeBefore(text, i)) { i += 1; continue }
189 var add: [Int] = [] // the parts that start at this byte
190 var step = 1 // bytes to move on by
191 if b == 64 && i + 1 < n && text[i + 1] == 35 {
192 let len = channelLength(text, i + 2)
193 if len > 0 { add = [i, len + 2, spanChannel, 0]; step = len + 2 }
194 } else if b == 64 {
195 var k = 0
196 while k < members {
197 if nameAt(text, i + 1, names[k], names[k].count) { add += [i, names[k].count + 1, spanMember, k] }
198 k += 1
199 }
200 if add.isEmpty && nameAt(text, i + 1, all, 3) { add = [i, 4, spanAll, 0] }
201 k = 0
202 while add.isEmpty && k < members { // "@worker" calls every "worker-<n>"
203 let p = copyPrefix(names[k])
204 if p > 0 && nameAt(text, i + 1, names[k], p) {
205 var j = k
206 while j < members {
207 if copyPrefix(names[j]) == p && nameAt(text, i + 1, names[j], p) { add += [i, p + 1, spanMember, j] }
208 j += 1
209 }
210 }
211 k += 1
212 }
213 } else if head > 0 && runeBefore(text, i) != 38 { // "&#39;" is not a citation
214 var j = i + 1, value = 0
215 while j < n && j - i <= 9 && isDigit(text[j]) { value = value * 10 + Int(text[j] - 48); j += 1 }
216 if j > i + 1 && value >= 1 && value <= head && !isNameRune(runeAt(text, j)) { add = [i, j - i, spanCite, value]; step = j - i }
217 }
218 if !add.isEmpty {
219 if out.flat.count + add.count > maxSpans * 4 { out.clipped = true; break }
220 out.flat += add
221 }
222 i += step
223 }
224 return out
225 }
226
227 /// Does a member with this role and this list of channels follow `channel`? An empty list means the role's
228 /// default: the coordinator and helpers follow every channel, a worker only the main board.
229 static func follows(role: Int, channels: [[UInt8]], channel: [UInt8]) -> Bool {
230 if channels.isEmpty { return role != roleWorker }
231 var i = 0
232 while i < channels.count && i < maxRecipients {
233 if (channels[i].count == 1 && channels[i][0] == 42) || equalFold(channels[i], channel) { return true }
234 i += 1
235 }
236 return false
237 }
238
239 struct Address {
240 var direct: [Int] = [] // member indexes called by name, in the header, or through a channel; the sender is left out
241 var all = false // addressed to everyone
242 }
243
244 /// Who a post addresses: the members its header names, the members its text calls with "@name" or reaches
245 /// through "@#channel", and whether it says "@all".
246 static func address(text: [UInt8], spans: [Int], sender: Int, headerTo: [Int], headerAll: Bool,
247 roles: [Int], channels: [[[UInt8]]]) -> Address {
248 let members = roles.count < maxMembers ? roles.count : maxMembers
249 var flag = [Int](repeating: 0, count: members)
250 var out = Address()
251 out.all = headerAll
252 var i = 0
253 while i < headerTo.count && i < maxRecipients {
254 if headerTo[i] >= 0 && headerTo[i] < members { flag[headerTo[i]] = 1 }
255 i += 1
256 }
257 let main: [UInt8] = [109, 97, 105, 110], all: [UInt8] = [97, 108, 108], here: [UInt8] = [104, 101, 114, 101]
258 var s = 0
259 while s + 3 < spans.count && s < maxSpans * 4 {
260 let start = spans[s], length = spans[s + 1], kind = spans[s + 2], value = spans[s + 3]
261 if kind == spanMember && value >= 0 && value < members { flag[value] = 1 }
262 if kind == spanAll { out.all = true }
263 if kind == spanChannel && start >= 0 && length > 2 && start + length <= text.count {
264 let channel = Array(text[(start + 2)..<(start + length)])
265 if !equalFold(channel, main) && !equalFold(channel, all) && !equalFold(channel, here) {
266 var m = 0
267 while m < members {
268 if follows(role: roles[m], channels: m < channels.count ? channels[m] : [], channel: channel) { flag[m] = 1 }
269 m += 1
270 }
271 }
272 }
273 s += 4
274 }
275 if sender >= 0 && sender < members { flag[sender] = 0 }
276 var m = 0
277 while m < members { if flag[m] == 1 { out.direct.append(m) }; m += 1 }
278 return out
279 }
280
281 // MARK: Time
282
283 struct Time {
284 var ok = false
285 var epoch = 0 // seconds since 1970; as written when the text names no zone
286 var end = 0 // first byte after the time
287 var zoned = false // the text named its zone ("Z" or an offset)
288 }
289
290 static func twoDigits(_ t: [UInt8], _ i: Int) -> Int {
291 if i < 0 || i + 1 >= t.count || !isDigit(t[i]) || !isDigit(t[i + 1]) { return -1 }
292 return Int(t[i] - 48) * 10 + Int(t[i + 1] - 48)
293 }
294
295 /// Days from 1970-01-01 to the given date in the Gregorian calendar.
296 static func daysFromCivil(_ year: Int, _ month: Int, _ day: Int) -> Int {
297 let y = month <= 2 ? year - 1 : year
298 let era = (y >= 0 ? y : y - 399) / 400
299 let yoe = y - era * 400
300 let doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1
301 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy
302 return era * 146097 + doe - 719468
303 }
304
305 /// Reads "YYYY-MM-DD", optionally followed by "T" or one space and "HH:MM" or "HH:MM:SS", optionally
306 /// followed by "Z" or an offset such as "+00:00".
307 static func parseTime(_ t: [UInt8], _ start: Int) -> Time {
308 var out = Time()
309 let s = start
310 if s < 0 || s + 10 > t.count { return out }
311 let century = twoDigits(t, s), yy = twoDigits(t, s + 2), month = twoDigits(t, s + 5), day = twoDigits(t, s + 8)
312 if century < 0 || yy < 0 || month < 1 || month > 12 || day < 1 || day > 31 || t[s + 4] != 45 || t[s + 7] != 45 { return out }
313 let year = century * 100 + yy
314 if year < 1970 { return out }
315 var p = s + 10
316 var seconds = 0
317 if p + 5 < t.count && (t[p] == 84 || t[p] == 32) {
318 let hour = twoDigits(t, p + 1), minute = twoDigits(t, p + 4)
319 if hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && p + 3 < t.count && t[p + 3] == 58 {
320 seconds = hour * 3600 + minute * 60
321 p += 6
322 if p < t.count && t[p] == 58 {
323 let sec = twoDigits(t, p + 1)
324 if sec >= 0 && sec < 61 { seconds += sec; p += 3 }
325 }
326 if p < t.count && t[p] == 46 { // fraction of a second: read and dropped
327 var q = p + 1
328 while q < t.count && q - p <= 9 && isDigit(t[q]) { q += 1 }
329 if q > p + 1 { p = q }
330 }
331 if p < t.count && (t[p] == 90 || t[p] == 122) { out.zoned = true; p += 1 }
332 else if p < t.count && (t[p] == 43 || t[p] == 45) {
333 let oh = twoDigits(t, p + 1)
334 var om = -1, used = 0
335 if p + 3 < t.count && t[p + 3] == 58 { om = twoDigits(t, p + 4); used = 6 } else { om = twoDigits(t, p + 3); used = 5 }
336 if oh >= 0 && oh < 24 && om >= 0 && om < 60 {
337 let offset = oh * 3600 + om * 60
338 seconds += t[p] == 43 ? -offset : offset
339 out.zoned = true
340 p += used
341 }
342 }
343 } else if t[p] == 84 { return out }
344 } else if p < t.count && t[p] == 84 { return out }
345 out.ok = true
346 out.epoch = daysFromCivil(year, month, day) * 86400 + seconds
347 out.end = p
348 return out
349 }
350
351 // MARK: One line of a plain-text board
352
353 struct Line {
354 var ok = false // false: not a post (no time at the start)
355 var time = 0
356 var senders: [[UInt8]] = []
357 var senderDetails: [[UInt8]] = [] // the bracket after each sender, "" when none
358 var recipients: [[UInt8]] = []
359 var recipientDetails: [[UInt8]] = []
360 var all = false // addressed to all
361 var text: [UInt8] = []
362 var clipped = false // the line, its senders, its recipients or its text went over a limit
363 }
364
365 struct NameRead {
366 var name: [UInt8] = []
367 var detail: [UInt8] = []
368 var next = 0 // first byte after the name, its bracket and the spaces that follow
369 var hadBracket = false
370 }
371
372 /// Reads one name from `from`, stopping before " + ", before "(" and, on the sender side, before " to "
373 /// and " @". A bracket right after the name is read as its detail.
374 static func readName(_ t: [UInt8], _ from: Int, _ limit: Int, senderSide: Bool) -> NameRead {
375 var out = NameRead()
376 var i = from
377 while i < limit && isSpace(t[i]) { i += 1 }
378 let start = i
379 while i < limit {
380 let c = t[i]
381 if c == 40 { break }
382 if c == 32 && i + 1 < limit {
383 let d = t[i + 1]
384 if d == 43 && (i + 2 >= limit || t[i + 2] == 32) { break }
385 if senderSide && d == 64 { break }
386 if senderSide && d == 116 && i + 2 < limit && t[i + 2] == 111 && (i + 3 >= limit || t[i + 3] == 32) { break }
387 }
388 i += 1
389 }
390 out.name = trimmed(t, start, i)
391 while i < limit && isSpace(t[i]) { i += 1 }
392 if i < limit && t[i] == 40 {
393 var depth = 0, j = i
394 while j < limit {
395 if t[j] == 40 { depth += 1 } else if t[j] == 41 { depth -= 1; if depth == 0 { break } }
396 j += 1
397 }
398 out.detail = trimmed(t, i + 1, j)
399 out.hadBracket = true
400 i = j < limit ? j + 1 : limit
401 while i < limit && isSpace(t[i]) { i += 1 }
402 }
403 out.next = i
404 return out
405 }
406
407 static func nameFits(_ name: [UInt8]) -> Bool {
408 !name.isEmpty && name.count <= maxNameBytes && wordCount(name) <= maxNameWords
409 }
410
411 /// "all", "all lanes", "everyone": the whole board, not one member.
412 static func isEveryone(_ name: [UInt8]) -> Bool {
413 let k = nameKey(name)
414 let all: [UInt8] = [97, 108, 108], everyone: [UInt8] = [101, 118, 101, 114, 121, 111, 110, 101]
415 if equalFold(k, all) || equalFold(k, everyone) { return true }
416 return k.count > 4 && k[0] == 97 && k[1] == 108 && k[2] == 108 && k[3] == 45
417 }
418
419 /// Cuts text to `limit` bytes without splitting a character.
420 static func clip(_ t: [UInt8], _ limit: Int) -> [UInt8] {
421 if t.count <= limit { return t }
422 var end = limit, back = 0
423 while end > 0 && back < 3 && (t[end] & 0xC0) == 0x80 { end -= 1; back += 1 }
424 return Array(t[0..<end])
425 }
426
427 /// Reads one board line of the form
428 /// <time> <sender> (<detail>) to <recipient> + <recipient> (<detail>): <text>
429 /// Also read: several senders joined by " + ", no "to" part, recipients written "@name" instead of
430 /// "to name", a leading "- ", and words between the sender's bracket and the colon (they stay in the text).
431 /// A line that does not start with a time is not a post (`ok` false). A header that does not fit the form
432 /// is read plainly: the first word is the sender, the rest is the text.
433 static func parseLine(_ raw: [UInt8]) -> Line {
434 var out = Line()
435 var line = raw
436 if line.count > maxLineBytes { line = clip(line, maxLineBytes); out.clipped = true }
437 var end = line.count
438 while end > 0 && (isSpace(line[end - 1]) || line[end - 1] == 13 || line[end - 1] == 10) { end -= 1 }
439 var p = 0
440 while p < end && isSpace(line[p]) { p += 1 }
441 if p + 1 < end && line[p] == 45 && line[p + 1] == 32 { p += 2 }
442 let time = parseTime(line, p)
443 if !time.ok || time.end >= end || !isSpace(line[time.end]) { return out }
444 p = time.end
445 while p < end && isSpace(line[p]) { p += 1 }
446 if p >= end { return out }
447 out.ok = true
448 out.time = time.epoch
449 let bodyStart = p
450
451 var colon = -1, depth = 0, i = p
452 while i < end && i - p < maxHeaderBytes {
453 let c = line[i]
454 if c == 40 { depth += 1 } else if c == 41 { if depth > 0 { depth -= 1 } }
455 else if c == 58 && depth == 0 && (i + 1 == end || line[i + 1] == 32) { colon = i; break }
456 i += 1
457 }
458
459 var fits = colon >= 0
460 var textStart = colon + 1
461 var q = p
462 var mode = 0 // 0 senders, 1 "to" recipients, 2 "@" recipients, 3 done
463 var round = 0
464 while fits && mode == 0 && round < 64 {
465 round += 1
466 let r = readName(line, q, colon, senderSide: true)
467 if !nameFits(r.name) { fits = false; break }
468 if out.senders.count < maxSenders { out.senders.append(r.name); out.senderDetails.append(r.detail) } else { out.clipped = true }
469 let x = r.next
470 if x >= colon { mode = 3 }
471 else if line[x] == 43 && (x + 1 >= colon || line[x + 1] == 32) { q = x + 1 }
472 else if line[x] == 116 && x + 2 < colon && line[x + 1] == 111 && line[x + 2] == 32 { mode = 1; q = x + 3 }
473 else if line[x] == 64 { mode = 2; q = x }
474 else if r.hadBracket { mode = 3; textStart = x } // words after the bracket: they belong to the text
475 else { fits = false }
476 }
477 if fits && mode == 0 { fits = false }
478 round = 0
479 while fits && mode == 1 && round < 64 {
480 round += 1
481 let r = readName(line, q, colon, senderSide: false)
482 var name = r.name
483 if !name.isEmpty && name[0] == 64 { name = Array(name[1...]) }
484 if !nameFits(name) { fits = false; break }
485 if isEveryone(name) { out.all = true }
486 else if out.recipients.count < maxRecipients { out.recipients.append(name); out.recipientDetails.append(r.detail) }
487 else { out.clipped = true }
488 let x = r.next
489 if x >= colon { mode = 3 }
490 else if line[x] == 43 && (x + 1 >= colon || line[x + 1] == 32) { q = x + 1 }
491 else { fits = false }
492 }
493 if fits && mode == 1 { fits = false }
494 round = 0
495 while fits && mode == 2 && round < 64 {
496 round += 1
497 while q < colon && (isSpace(line[q]) || line[q] == 43) { q += 1 }
498 if q >= colon { mode = 3; break }
499 if line[q] != 64 { fits = false; break }
500 var j = q + 1
501 while j < colon && !isSpace(line[j]) { j += 1 }
502 let name = trimmed(line, q + 1, j)
503 if !nameFits(name) { fits = false; break }
504 if isEveryone(name) { out.all = true }
505 else if out.recipients.count < maxRecipients { out.recipients.append(name); out.recipientDetails.append([]) }
506 else { out.clipped = true }
507 q = j
508 }
509 if fits && mode == 2 { fits = false }
510
511 if !fits { // plain reading: first word is the sender
512 out.senders = []; out.senderDetails = []; out.recipients = []; out.recipientDetails = []; out.all = false
513 var j = bodyStart
514 while j < end && !isSpace(line[j]) { j += 1 }
515 var name = trimmed(line, bodyStart, j)
516 if name.count > 1 && name[name.count - 1] == 58 { name.removeLast() }
517 if name.count > maxNameBytes { name = clip(name, maxNameBytes); out.clipped = true }
518 out.senders = [name]; out.senderDetails = [[]]
519 textStart = j
520 }
521 var text = trimmed(line, textStart, end)
522 if text.count > maxTextBytes { text = clip(text, maxTextBytes); out.clipped = true }
523 out.text = text
524 return out
525 }
526
527 /// "L1122" or "L1124/L1125": a ledger number, never another name of the agent.
528 static func isLedgerId(_ t: [UInt8]) -> Bool {
529 var i = 0, parts = 0
530 while i < t.count && parts < 8 {
531 if t[i] != 76 && t[i] != 108 { return false }
532 var j = i + 1
533 while j < t.count && j - i <= 9 && isDigit(t[j]) { j += 1 }
534 if j == i + 1 { return false }
535 parts += 1
536 if j == t.count { return true }
537 if t[j] != 47 { return false }
538 i = j + 1
539 }
540 return false
541 }
542
543 // MARK: A whole plain-text board
544
545 struct Board {
546 var names: [[UInt8]] = [] // one per member, in its newest spelling
547 var details: [[UInt8]] = [] // the newest bracket written after that member as a sender
548 var alsoCalled: [[UInt8]] = [] // other spellings joined to the same member, comma-separated
549 var postSeq: [Int] = []
550 var postTime: [Int] = []
551 var postSender: [Int] = [] // member index; -1 when the sender did not fit in the member table
552 var postSenderName: [[UInt8]] = [] // as written
553 var postWith: [[Int]] = [] // other members who signed the same post
554 var postTo: [[Int]] = [] // members the header names
555 var postAll: [Int] = []
556 var postText: [[UInt8]] = []
557 var lines = 0 // lines given
558 var olderLinesDropped = 0 // lines beyond maxPosts: the oldest ones, not read
559 var skippedLines = 0 // lines that are not posts
560 var clippedLines = 0 // posts that went over a limit and were cut
561 var membersDropped = 0 // agents named on the board beyond maxMembers: not listed as members
562 var spellingsDropped = 0 // times a name was met after the table of spellings was full
563 }
564
565 /// Joins the sets of spellings that hold `a` and `b`; the earlier table entry stays the main one.
566 static func join(_ canon: inout [Int], _ a: Int, _ b: Int) {
567 let x = root(canon, a), y = root(canon, b)
568 if x < 0 || y < 0 || x >= canon.count || y >= canon.count || x == y { return }
569 if x < y { canon[y] = x } else { canon[x] = y }
570 }
571
572 /// Is `full` the name `short` with a lane in front: "lane/short"?
573 static func isLaneForm(_ full: [UInt8], of short: [UInt8]) -> Bool {
574 let at = full.count - short.count
575 if short.isEmpty || at < 2 || full[at - 1] != 47 { return false }
576 var i = 0
577 while i < short.count { if full[at + i] != short[i] { return false }; i += 1 }
578 return true
579 }
580
581 static func findKey(_ keys: [[UInt8]], _ key: [UInt8]) -> Int {
582 var i = 0
583 while i < keys.count && i < maxNames { if keys[i] == key { return i }; i += 1 }
584 return -1
585 }
586
587 static func root(_ canon: [Int], _ start: Int) -> Int {
588 var i = start, hops = 0
589 while i >= 0 && i < canon.count && canon[i] != i && hops < maxNames { i = canon[i]; hops += 1 }
590 return i
591 }
592
593 /// Turns the lines of a plain-text board into posts and members. A post's sequence number is its line
594 /// number: `firstSeq` is the number of the first line given. Senders and recipients become members.
595 /// A name in a bracket is the same agent as the name before the bracket when that bracketed name is used
596 /// as a sender or recipient elsewhere and stands in the brackets of one agent only: so
597 /// "merge-desk (omp-queen-spark)" and "omp-queen-spark (merge desk)" are one member, while a shared word
598 /// such as a machine name joins nobody. A name written without its lane ("Worker" for "lane/Worker") is that
599 /// agent when exactly one sender on the board posts under a name that ends that way.
600 static func assemble(lines: [[UInt8]], firstSeq: Int) -> Board {
601 var board = Board()
602 board.lines = lines.count
603 let start = lines.count > maxPosts ? lines.count - maxPosts : 0
604 board.olderLinesDropped = start
605 var parsed: [Line] = []
606 var i = start
607 while i < lines.count { parsed.append(parseLine(lines[i])); i += 1 }
608 let n = parsed.count
609
610 // Spellings, newest first, senders before recipients.
611 var keys: [[UInt8]] = [], shown: [[UInt8]] = []
612 var senderKeys = 0 // the first this many spellings were used by a sender
613 var pass = 0
614 while pass < 2 {
615 var li = n - 1
616 while li >= 0 {
617 let line = parsed[li]
618 if line.ok {
619 let list = pass == 0 ? line.senders : line.recipients
620 var k = 0
621 while k < list.count && k < maxRecipients {
622 let key = nameKey(list[k])
623 if !key.isEmpty && findKey(keys, key) < 0 {
624 if keys.count < maxNames { keys.append(key); shown.append(list[k]) } else { board.spellingsDropped += 1 }
625 }
626 k += 1
627 }
628 }
629 li -= 1
630 }
631 if pass == 0 { senderKeys = keys.count }
632 pass += 1
633 }
634
635 // Which bracketed names belong to exactly one agent.
636 var owner = [Int](repeating: -1, count: keys.count)
637 var li = 0
638 while li < n {
639 let line = parsed[li]
640 if line.ok {
641 var side = 0
642 while side < 2 {
643 let list = side == 0 ? line.senders : line.recipients
644 let details = side == 0 ? line.senderDetails : line.recipientDetails
645 var k = 0
646 while k < list.count && k < details.count && k < maxRecipients {
647 let outer = findKey(keys, nameKey(list[k]))
648 let d = details[k]
649 var a = 0, items = 0
650 while outer >= 0 && a <= d.count && items < maxDetailItems {
651 var b = a
652 while b < d.count && d[b] != 44 { b += 1 }
653 let item = trimmed(d, a, b)
654 if !item.isEmpty && !isLedgerId(item) {
655 let inner = findKey(keys, nameKey(item))
656 if inner >= 0 && inner != outer {
657 if owner[inner] == -1 { owner[inner] = outer } else if owner[inner] != outer { owner[inner] = -2 }
658 }
659 }
660 items += 1
661 a = b + 1
662 }
663 k += 1
664 }
665 side += 1
666 }
667 }
668 li += 1
669 }
670 var canon = [Int](repeating: 0, count: keys.count)
671 var c = 0
672 while c < keys.count { canon[c] = c; c += 1 }
673 c = 0
674 while c < keys.count {
675 if owner[c] >= 0 { join(&canon, owner[c], c) }
676 c += 1
677 }
678 c = 0
679 while c < keys.count { // "Worker" alone, when exactly one sender posts as "lane/Worker"
680 var match = -1, matches = 0, k = 0
681 while k < senderKeys && !keys[c].contains(47) {
682 if k != c && isLaneForm(keys[k], of: keys[c]) { match = k; matches += 1 }
683 k += 1
684 }
685 if matches == 1 { join(&canon, match, c) }
686 c += 1
687 }
688
689 // Members: one per joined set of spellings, in table order.
690 var memberOf = [Int](repeating: -1, count: keys.count)
691 c = 0
692 while c < keys.count {
693 if root(canon, c) == c {
694 if board.names.count < maxMembers {
695 memberOf[c] = board.names.count
696 board.names.append(shown[c]); board.details.append([]); board.alsoCalled.append([])
697 } else { board.membersDropped += 1 }
698 }
699 c += 1
700 }
701 c = 0
702 while c < keys.count {
703 let r = root(canon, c)
704 if r != c && r >= 0 && memberOf[r] >= 0 {
705 memberOf[c] = memberOf[r]
706 if !board.alsoCalled[memberOf[r]].isEmpty { board.alsoCalled[memberOf[r]] += [44, 32] }
707 board.alsoCalled[memberOf[r]] += shown[c]
708 }
709 c += 1
710 }
711
712 // Posts, oldest first.
713 var detailSet = [Int](repeating: 0, count: board.names.count)
714 li = 0
715 while li < n {
716 let line = parsed[li]
717 if !line.ok { board.skippedLines += 1; li += 1; continue }
718 if line.clipped { board.clippedLines += 1 }
719 var sender = -1
720 var with: [Int] = []
721 var k = 0
722 while k < line.senders.count && k < maxSenders {
723 let at = findKey(keys, nameKey(line.senders[k]))
724 let m = at >= 0 ? memberOf[at] : -1
725 if k == 0 { sender = m } else if m >= 0 && m != sender && !with.contains(m) { with.append(m) }
726 k += 1
727 }
728 var to: [Int] = []
729 k = 0
730 while k < line.recipients.count && k < maxRecipients {
731 let at = findKey(keys, nameKey(line.recipients[k]))
732 let m = at >= 0 ? memberOf[at] : -1
733 if m >= 0 && m != sender && !to.contains(m) { to.append(m) }
734 k += 1
735 }
736 board.postSeq.append(firstSeq + start + li)
737 board.postTime.append(line.time)
738 board.postSender.append(sender)
739 board.postSenderName.append(line.senders.isEmpty ? [] : line.senders[0])
740 board.postWith.append(with)
741 board.postTo.append(to)
742 board.postAll.append(line.all ? 1 : 0)
743 board.postText.append(line.text)
744 li += 1
745 }
746 // The newest bracket written after each member as a sender.
747 li = n - 1
748 while li >= 0 {
749 let line = parsed[li]
750 if line.ok {
751 var k = 0
752 while k < line.senders.count && k < line.senderDetails.count && k < maxSenders {
753 let at = findKey(keys, nameKey(line.senders[k]))
754 let m = at >= 0 ? memberOf[at] : -1
755 if m >= 0 && detailSet[m] == 0 && !line.senderDetails[k].isEmpty { board.details[m] = line.senderDetails[k]; detailSet[m] = 1 }
756 k += 1
757 }
758 }
759 li -= 1
760 }
761 return board
762 }
763
764 // MARK: Roster roles
765
766 /// "narrator", "monitor", or either with "-<digits>": a helper by its name, whatever role the roster gives it.
767 static func isHelperName(_ name: [UInt8]) -> Bool {
768 let narrator: [UInt8] = [110, 97, 114, 114, 97, 116, 111, 114], monitor: [UInt8] = [109, 111, 110, 105, 116, 111, 114]
769 var base = name
770 let p = copyPrefix(name)
771 if p > 0 { base = Array(name[0..<p]) }
772 return equalFold(base, narrator) || equalFold(base, monitor)
773 }
774
775 /// The role code of a roster member. The coordinator leads; a member with any role other than "worker", or
776 /// with a helper's name, is a helper: it is left out of the member counts and of the graph.
777 static func roleCode(role: [UInt8], name: [UInt8]) -> Int {
778 let coordinator: [UInt8] = [99, 111, 111, 114, 100, 105, 110, 97, 116, 111, 114], worker: [UInt8] = [119, 111, 114, 107, 101, 114]
779 if equalFold(role, coordinator) { return roleCoordinator }
780 if role.isEmpty || equalFold(role, worker) { return isHelperName(name) ? roleHelper : roleWorker }
781 return roleHelper
782 }
783
784 // MARK: A member's own run (roster swarms)
785
786 /// Has the member's run stopped? Told from its newest steps, oldest first in the arrays: `kinds` and
787 /// `statuses` per step, and for a planner step how many tools it called (`tools`) and which of them was
788 /// the wait-for-posts call (`waits`, -1 when none). The run has stopped when the newest planner step called
789 /// no tool and nothing came after it, or when it called the wait and that call's own result is done.
790 /// Anything newer (a system message, a result still running, a torn line) means it is mid-turn.
791 static func turn(kinds: [Int], statuses: [Int], tools: [Int], waits: [Int]) -> Int {
792 let n = kinds.count
793 if n == 0 || statuses.count != n || tools.count != n || waits.count != n { return turnUnknown }
794 var i = n - 1, results = 0, looked = 0
795 while i >= 0 && looked < maxSteps && kinds[i] == stepResult { results += 1; i -= 1; looked += 1 }
796 if i < 0 || looked >= maxSteps || kinds[i] != stepPlanner { return turnRunning }
797 if tools[i] <= 0 { return results == 0 ? turnEnded : turnRunning }
798 let wait = waits[i]
799 if wait < 0 || wait >= tools[i] || results < tools[i] { return turnRunning }
800 return statuses[i + 1 + wait] == statusDone ? turnEnded : turnRunning
801 }
802
803 /// The step that says what the member is doing now: the newest planner step of the current turn that has
804 /// a label (`labelled` 1). A turn starts after user input or after a wait for posts, so an older label is
805 /// never shown as current. -1 when there is none.
806 static func activityStep(kinds: [Int], waits: [Int], labelled: [Int]) -> Int {
807 let n = kinds.count
808 if waits.count != n || labelled.count != n { return -1 }
809 var i = n - 1, looked = 0
810 while i >= 0 && looked < maxSteps {
811 if kinds[i] == stepUser { return -1 }
812 if kinds[i] == stepPlanner {
813 if waits[i] >= 0 { return -1 }
814 if labelled[i] == 1 { return i }
815 }
816 i -= 1; looked += 1
817 }
818 return -1
819 }
820
821 static func contains(_ text: [UInt8], _ word: [UInt8]) -> Bool {
822 if word.isEmpty || text.count < word.count { return false }
823 var i = 0
824 while i + word.count <= text.count && i < maxTextBytes {
825 var k = 0
826 while k < word.count && lower(text[i + k]) == word[k] { k += 1 }
827 if k == word.count { return true }
828 i += 1
829 }
830 return false
831 }
832
833 /// Does an error text say the member ran out of quota or was rate limited?
834 static func looksLikeQuota(_ text: [UInt8]) -> Bool {
835 if contains(text, Array("resource_exhausted".utf8)) || contains(text, Array("quota".utf8)) || contains(text, Array("rate limit".utf8))
836 || contains(text, Array("rate-limit".utf8)) || contains(text, Array("ratelimit".utf8)) || contains(text, Array("exhausted your capacity".utf8)) { return true }
837 var i = 0
838 while i + 3 <= text.count && i < maxTextBytes { // "429" standing alone
839 if text[i] == 52 && text[i + 1] == 50 && text[i + 2] == 57 && !isNameRune(runeBefore(text, i)) && !isNameRune(runeAt(text, i + 3)) { return true }
840 i += 1
841 }
842 return false
843 }
844
845 /// How a member's newest step failed: a model error counts at once, a failed tool step once it has stayed
846 /// the newest step for failureSettleSeconds (the member usually carries on after one).
847 static func failure(lastKind: Int, lastStatus: Int, idleSeconds: Int, quota: Bool) -> Int {
848 let failed = lastKind == stepError || (lastStatus == statusError && idleSeconds >= failureSettleSeconds)
849 if !failed { return attentionNone }
850 return quota ? attentionQuota : attentionError
851 }
852
853 // MARK: Status
854
855 /// A member's state is worked out, never taken from what it says about itself.
856 /// With a roster: stopped when it was killed; otherwise waiting when its own run has stopped and working
857 /// when it is mid-turn; with no transcript to go on, waiting when it is parked for mentions or for any post.
858 /// On a board with no roster: working when it posted within activeSeconds, waiting otherwise.
859 static func state(killed: Bool, turn: Int, wake: Int, hasRoster: Bool, lastPostAge: Int) -> Int {
860 if killed { return stateStopped }
861 if !hasRoster { return lastPostAge >= 0 && lastPostAge <= activeSeconds ? stateWorking : stateWaiting }
862 if turn == turnEnded { return stateWaiting }
863 if turn == turnRunning { return stateWorking }
864 return wake == wakeMentions || wake == wakeAnything ? stateWaiting : stateWorking
865 }
866
867 /// What needs a look: a failed newest step (error or quota), or a member that should be working and has
868 /// not moved for more than stuckSeconds. `idleSeconds` is -1 when its last movement is not known.
869 static func attention(state: Int, failure: Int, idleSeconds: Int) -> Int {
870 if state == stateStopped { return attentionNone }
871 if failure == attentionError || failure == attentionQuota { return failure }
872 if state == stateWorking && idleSeconds > stuckSeconds { return attentionStuck }
873 return attentionNone
874 }
875
876 /// Posts the member has not read: the newest sequence number minus the last one it read. -1 when not known.
877 static func unread(head: Int, lastRead: Int) -> Int {
878 if lastRead < 0 { return -1 }
879 return head > lastRead ? head - lastRead : 0
880 }
881
882 /// The Overview group of one member.
883 static func group(state: Int, attention: Int, asksYou: Bool, waitingOn: Bool) -> Int {
884 if state == stateStopped { return groupParked }
885 if attention != attentionNone || asksYou { return groupNeedsYou }
886 if state == stateWorking { return groupWorking }
887 return waitingOn ? groupWaitingOn : groupParked
888 }
889
890 /// Is this post the first row of a visual group? Posts by the same sender, next to each other and at most
891 /// groupSeconds apart, are drawn as one group.
892 static func startsGroup(previousSender: Int, previousTime: Int, sender: Int, time: Int) -> Bool {
893 if sender < 0 || sender != previousSender { return true }
894 if time <= 0 || previousTime <= 0 { return false }
895 let gap = time - previousTime
896 return gap > groupSeconds || gap < 0
897 }
898
899 // MARK: The whole picture
900
901 struct Input {
902 var hasRoster = false
903 var now = 0 // seconds since 1970
904 var citeHead = 0 // highest "#seq" that may be cited; 0 turns citations off
905 var names: [[UInt8]] = []
906 var roles: [Int] = []
907 var killed: [Int] = []
908 var wake: [Int] = []
909 var turn: [Int] = []
910 var lastRead: [Int] = [] // -1 not known
911 var lastMove: [Int] = [] // seconds since 1970 of the member's last own movement; 0 not known
912 var failure: [Int] = [] // from failure()
913 var channels: [[[UInt8]]] = []
914 var owner: [Int] = [] // 1: this member is the person using Hop
915 var postSeq: [Int] = []
916 var postTime: [Int] = [] // 0 not known
917 var postSender: [Int] = [] // member index or -1
918 var postWith: [[Int]] = []
919 var postTo: [[Int]] = []
920 var postAll: [Int] = []
921 var postText: [[UInt8]] = []
922 }
923
924 struct Derived {
925 var refused = 0 // 0 fine; otherwise why nothing was worked out
926 var head = 0 // newest sequence number
927 var postDirect: [[Int]] = [] // members each post addresses by name
928 var postAll: [Int] = []
929 var postSpans: [[Int]] = []
930 var postStartsGroup: [Int] = []
931 var postsWithClippedSpans = 0
932 var state: [Int] = []
933 var attention: [Int] = []
934 var idleSeconds: [Int] = [] // -1 not known
935 var unread: [Int] = [] // -1 not known
936 var postCount: [Int] = []
937 var lastPost: [Int] = [] // index of the member's newest post, -1 when none
938 var waitingOn: [Int] = [] // member index, -1 when none
939 var waitingSeq: [Int] = []
940 var asksYouSeq: [Int] = [] // sequence number of the unanswered post to the owner, 0 when none
941 var group: [Int] = []
942 var helper: [Int] = []
943 var overviewOrder: [Int] = [] // by group, coordinator first, then name (no roster: those who posted first)
944 var memberOrder: [Int] = [] // working, waiting, stopped; coordinator first; then name (no roster: those who posted first)
945 var working = 0, waiting = 0, stopped = 0 // task members only: helpers are not counted
946 }
947
948 /// Member indexes sorted by `key` (small first), coordinator before the others, then by name.
949 static func ordered(key: [Int], roles: [Int], names: [[UInt8]]) -> [Int] {
950 let n = key.count < maxMembers ? key.count : maxMembers
951 var order: [Int] = []
952 var i = 0
953 while i < n {
954 var at = order.count
955 while at > 0 {
956 let o = order[at - 1]
957 var after = false // does o sort after i?
958 if key[o] != key[i] { after = key[o] > key[i] }
959 else if (roles[o] == roleCoordinator) != (roles[i] == roleCoordinator) { after = roles[i] == roleCoordinator }
960 else { after = compareFold(names[o], names[i]) > 0 }
961 if !after { break }
962 at -= 1
963 }
964 order.insert(i, at: at)
965 i += 1
966 }
967 return order
968 }
969
970 /// Works out everything the four views show. Input over a limit, arrays of different lengths and indexes
971 /// that point nowhere are refused with a code; nothing is cut here.
972 static func derive(_ input: Input) -> Derived {
973 var out = Derived()
974 let n = input.names.count, p = input.postSeq.count
975 if n > maxMembers { out.refused = refusedMembers; return out }
976 if p > maxPosts { out.refused = refusedPosts; return out }
977 if input.roles.count != n || input.killed.count != n || input.wake.count != n || input.turn.count != n || input.lastRead.count != n
978 || input.lastMove.count != n || input.failure.count != n || input.channels.count != n || input.owner.count != n
979 || input.postTime.count != p || input.postSender.count != p || input.postWith.count != p || input.postTo.count != p
980 || input.postAll.count != p || input.postText.count != p { out.refused = refusedShape; return out }
981 var i = 0
982 while i < p {
983 if input.postSender[i] < -1 || input.postSender[i] >= n || input.postText[i].count > maxTextBytes { out.refused = refusedValue; return out }
984 if input.postWith[i].count > maxSenders || input.postTo[i].count > maxRecipients { out.refused = refusedValue; return out }
985 var k = 0
986 while k < input.postWith[i].count { if input.postWith[i][k] < 0 || input.postWith[i][k] >= n { out.refused = refusedValue; return out }; k += 1 }
987 k = 0
988 while k < input.postTo[i].count { if input.postTo[i][k] < 0 || input.postTo[i][k] >= n { out.refused = refusedValue; return out }; k += 1 }
989 i += 1
990 }
991
992 out.head = p > 0 ? input.postSeq[p - 1] : 0
993 out.postCount = [Int](repeating: 0, count: n)
994 out.lastPost = [Int](repeating: -1, count: n)
995 i = 0
996 while i < p {
997 let found = spans(input.postText[i], names: input.names, head: input.citeHead)
998 if found.clipped { out.postsWithClippedSpans += 1 }
999 let sender = input.postSender[i]
1000 let to = address(text: input.postText[i], spans: found.flat, sender: sender, headerTo: input.postTo[i],
1001 headerAll: input.postAll[i] == 1, roles: input.roles, channels: input.channels)
1002 out.postSpans.append(found.flat)
1003 out.postDirect.append(to.direct)
1004 out.postAll.append(to.all ? 1 : 0)
1005 out.postStartsGroup.append(i == 0 || startsGroup(previousSender: input.postSender[i - 1], previousTime: input.postTime[i - 1],
1006 sender: sender, time: input.postTime[i]) ? 1 : 0)
1007 if sender >= 0 { out.postCount[sender] += 1; out.lastPost[sender] = i }
1008 var k = 0
1009 while k < input.postWith[i].count {
1010 let w = input.postWith[i][k]
1011 if w != sender { out.postCount[w] += 1; out.lastPost[w] = i }
1012 k += 1
1013 }
1014 i += 1
1015 }
1016
1017 var m = 0
1018 while m < n {
1019 let last = out.lastPost[m]
1020 let age = last >= 0 && input.postTime[last] > 0 ? (input.now > input.postTime[last] ? input.now - input.postTime[last] : 0) : -1
1021 let st = state(killed: input.killed[m] == 1, turn: input.turn[m], wake: input.wake[m], hasRoster: input.hasRoster, lastPostAge: age)
1022 let idle = input.hasRoster && input.lastMove[m] > 0 ? (input.now > input.lastMove[m] ? input.now - input.lastMove[m] : 0) : -1
1023 out.state.append(st)
1024 out.idleSeconds.append(idle)
1025 out.attention.append(attention(state: st, failure: input.failure[m], idleSeconds: idle))
1026 out.unread.append(unread(head: out.head, lastRead: input.hasRoster ? input.lastRead[m] : -1))
1027 out.helper.append(input.roles[m] == roleHelper ? 1 : 0)
1028 m += 1
1029 }
1030
1031 // Who is each member waiting on: the people its newest post names, as long as none of them has posted since.
1032 m = 0
1033 while m < n {
1034 var on = -1, seq = 0, you = 0
1035 let last = out.lastPost[m]
1036 if last >= 0 && out.state[m] != stateStopped && !out.postDirect[last].isEmpty {
1037 let targets = out.postDirect[last]
1038 var answered = false
1039 var j = last + 1
1040 while j < p && !answered {
1041 if targets.contains(input.postSender[j]) { answered = true }
1042 var k = 0
1043 while k < input.postWith[j].count && !answered { if targets.contains(input.postWith[j][k]) { answered = true }; k += 1 }
1044 j += 1
1045 }
1046 if !answered {
1047 var k = 0
1048 while k < targets.count {
1049 let t = targets[k]
1050 if input.owner[t] == 1 { you = input.postSeq[last] }
1051 else if on < 0 && out.state[t] != stateStopped { on = t }
1052 k += 1
1053 }
1054 if on >= 0 { seq = input.postSeq[last] }
1055 }
1056 }
1057 out.waitingOn.append(on); out.waitingSeq.append(seq); out.asksYouSeq.append(you)
1058 out.group.append(group(state: out.state[m], attention: out.attention[m], asksYou: you > 0, waitingOn: on >= 0))
1059 if out.helper[m] == 0 {
1060 if out.state[m] == stateWorking { out.working += 1 } else if out.state[m] == stateWaiting { out.waiting += 1 } else { out.stopped += 1 }
1061 }
1062 m += 1
1063 }
1064 // On a board with no roster a name that was only written to, and never posted, goes after the ones that posted.
1065 var byGroup = out.group, byState = out.state
1066 m = 0
1067 while m < n && !input.hasRoster {
1068 let silent = out.postCount[m] == 0 ? 1 : 0
1069 byGroup[m] = out.group[m] * 2 + silent
1070 byState[m] = out.state[m] * 2 + silent
1071 m += 1
1072 }
1073 out.overviewOrder = ordered(key: byGroup, roles: input.roles, names: input.names)
1074 out.memberOrder = ordered(key: byState, roles: input.roles, names: input.names)
1075 return out
1076 }
1077
1078 // MARK: Graph
1079
1080 /// Who addressed whom in the first `upTo` posts, as rows [from, to, count, direct, viaAll] ordered by sender
1081 /// then receiver. `count` is how many posts went from one to the other: `direct` of them named the
1082 /// receiver, `viaAll` reached it only because the post was for everyone. Helpers are left out.
1083 static func edges(memberCount: Int, helper: [Int], postSender: [Int], postWith: [[Int]], postDirect: [[Int]],
1084 postAll: [Int], upTo: Int) -> [Int] {
1085 let n = memberCount
1086 var posts = postSender.count
1087 if upTo < posts { posts = upTo < 0 ? 0 : upTo }
1088 if n <= 0 || n > maxMembers || posts > maxPosts || helper.count != n || postWith.count < posts || postDirect.count < posts || postAll.count < posts { return [] }
1089 var direct = [Int](repeating: 0, count: n * n), all = [Int](repeating: 0, count: n * n)
1090 var i = 0
1091 while i < posts {
1092 var s = 0
1093 while s <= postWith[i].count && s <= maxSenders {
1094 let from = s == 0 ? postSender[i] : postWith[i][s - 1]
1095 if from >= 0 && from < n && helper[from] == 0 && (s == 0 || from != postSender[i]) {
1096 var named = [Int](repeating: 0, count: n)
1097 var k = 0
1098 while k < postDirect[i].count && k < n {
1099 let to = postDirect[i][k]
1100 if to >= 0 && to < n && to != from && helper[to] == 0 && named[to] == 0 { named[to] = 1; direct[from * n + to] += 1 }
1101 k += 1
1102 }
1103 if postAll[i] == 1 {
1104 var to = 0
1105 while to < n {
1106 if to != from && helper[to] == 0 && named[to] == 0 { all[from * n + to] += 1 }
1107 to += 1
1108 }
1109 }
1110 }
1111 s += 1
1112 }
1113 i += 1
1114 }
1115 var out: [Int] = []
1116 var cell = 0
1117 while cell < n * n {
1118 if direct[cell] + all[cell] > 0 { out += [cell / n, cell % n, direct[cell] + all[cell], direct[cell], all[cell]] }
1119 cell += 1
1120 }
1121 return out
1122 }
1123
1124 /// How many of the first `upTo` posts each member sent to everyone.
1125 static func broadcasts(memberCount: Int, postSender: [Int], postAll: [Int], upTo: Int) -> [Int] {
1126 var out = [Int](repeating: 0, count: memberCount > 0 && memberCount <= maxMembers ? memberCount : 0)
1127 var posts = postSender.count
1128 if upTo < posts { posts = upTo < 0 ? 0 : upTo }
1129 var i = 0
1130 while i < posts && i < maxPosts && i < postAll.count {
1131 if postAll[i] == 1 && postSender[i] >= 0 && postSender[i] < out.count { out[postSender[i]] += 1 }
1132 i += 1
1133 }
1134 return out
1135 }
1136
1137 /// Which members to draw when there are too many for one picture: the `keep` members with the most posts to
1138 /// or from others (the earlier member wins a tie). `edges` are rows from edges(); `withAll` also counts posts
1139 /// for everyone. One 0/1 flag per member; a member with no line at all is never picked.
1140 static func busiest(memberCount: Int, edges: [Int], withAll: Bool, keep: Int) -> [Int] {
1141 let n = memberCount
1142 if n <= 0 || n > maxMembers { return [] }
1143 var weight = [Int](repeating: 0, count: n)
1144 var e = 0
1145 while e + 4 < edges.count && e < maxMembers * maxMembers * 5 {
1146 let from = edges[e], to = edges[e + 1], c = withAll ? edges[e + 2] : edges[e + 3]
1147 if from >= 0 && from < n && to >= 0 && to < n { weight[from] += c; weight[to] += c }
1148 e += 5
1149 }
1150 var flag = [Int](repeating: 0, count: n)
1151 var picked = 0
1152 while picked < keep && picked < n {
1153 var best = -1, m = 0
1154 while m < n {
1155 if flag[m] == 0 && weight[m] > 0 && (best < 0 || weight[m] > weight[best]) { best = m }
1156 m += 1
1157 }
1158 if best < 0 { break }
1159 flag[best] = 1
1160 picked += 1
1161 }
1162 return flag
1163 }
1164
1165 /// Line weight for an edge, 1 (lightest) to 5, by its count against the heaviest edge shown.
1166 static func weightStep(count: Int, heaviest: Int) -> Int {
1167 if count <= 1 || heaviest <= 1 { return 1 }
1168 if count >= heaviest { return 5 }
1169 return 1 + (count - 1) * 4 / (heaviest - 1)
1170 }
1171}