@johngaynor/ocnus 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +988 -2
  3. package/agents/linear-mcp.json +1 -0
  4. package/agents/ocnus-build.md +23 -0
  5. package/agents/ocnus-write-up.md +20 -0
  6. package/cli/host-mark +36 -0
  7. package/cli/lib/agents.sh +350 -0
  8. package/cli/lib/approval.sh +94 -0
  9. package/cli/lib/archive.sh +447 -0
  10. package/cli/lib/billing.sh +166 -0
  11. package/cli/lib/close.sh +189 -0
  12. package/cli/lib/commands.sh +220 -0
  13. package/cli/lib/common.sh +215 -0
  14. package/cli/lib/finish.sh +288 -0
  15. package/cli/lib/github.sh +162 -0
  16. package/cli/lib/guard.sh +134 -0
  17. package/cli/lib/handoff.sh +551 -0
  18. package/cli/lib/host.sh +1802 -0
  19. package/cli/lib/linear.sh +1389 -0
  20. package/cli/lib/links.sh +135 -0
  21. package/cli/lib/merges.sh +853 -0
  22. package/cli/lib/recipes.sh +54 -0
  23. package/cli/lib/settings.sh +465 -0
  24. package/cli/lib/space.sh +343 -0
  25. package/cli/lib/task.sh +847 -0
  26. package/cli/lib/tests.sh +268 -0
  27. package/cli/lib/trust.sh +70 -0
  28. package/cli/ocnus +630 -0
  29. package/herdr/README.md +2238 -0
  30. package/herdr/layouts/default.json +259 -0
  31. package/herdr/mods/agent-settings/cog.svg +4 -0
  32. package/herdr/mods/agent-settings/main.js +356 -0
  33. package/herdr/mods/agent-settings/mod.json +1 -0
  34. package/herdr/mods/cards/main.js +450 -0
  35. package/herdr/mods/cards/mod.json +1 -0
  36. package/herdr/mods/cards/refresh.svg +4 -0
  37. package/herdr/mods/cpu/main.js +90 -0
  38. package/herdr/mods/cpu/mod.json +1 -0
  39. package/herdr/mods/layout-switch/main.js +48 -0
  40. package/herdr/mods/layout-switch/mod.json +1 -0
  41. package/herdr/mods/names/main.js +69 -0
  42. package/herdr/mods/names/mod.json +1 -0
  43. package/herdr/mods/ocnus-spaces/main.js +376 -0
  44. package/herdr/mods/ocnus-spaces/mod.json +1 -0
  45. package/herdr/mods/steps/main.js +354 -0
  46. package/herdr/mods/steps/mod.json +1 -0
  47. package/herdr/spaces/template/SPACE.md +19 -0
  48. package/package.json +27 -4
  49. package/prompts/task-build.md +11 -0
  50. package/prompts/task-new.md +17 -0
  51. package/skills/brief/SKILL.md +64 -0
  52. package/skills/sdlc-breakdown/SKILL.md +312 -0
  53. package/skills/sdlc-build/SKILL.md +182 -0
  54. package/skills/sdlc-define/SKILL.md +203 -0
  55. package/skills/sdlc-plan/SKILL.md +202 -0
  56. package/skills/sdlc-pr/SKILL.md +339 -0
  57. package/skills/sdlc-review/SKILL.md +227 -0
@@ -0,0 +1,1802 @@
1
+ # Recording the host: how hard the machine ocnus runs on works while its
2
+ # agents are open. Sourced by cli/ocnus.
3
+ #
4
+ # Recording is off until the human turns it on with `host on`, and it is on
5
+ # while the host folder is there. `host off` stops the recorder and deletes
6
+ # the folder, every reading with it. While it is on, the recorder is one
7
+ # terminal in herdr-core, named ocnus-host, running `ocnus host
8
+ # record`. `task new`, `task start` and `task build` wake it (host_wake), so
9
+ # it starts with the first agent. It takes a reading every 10 seconds while
10
+ # an agent is open, and exits once none is. Nothing starts it with the
11
+ # machine: no launchd agent, no login item, and no --keep on its terminal, so
12
+ # after a restart it starts again only with the next agent.
13
+ #
14
+ # A reading is numbers only: CPU, memory, disk, network, and power and heat,
15
+ # from macOS's own tools, run as the human, with no admin rights, and nothing
16
+ # sent off the machine. It holds no app's name, command line, window title,
17
+ # file or prompt, and no address, host or site reached, or the network's
18
+ # name. It keeps the CPU and memory of ocnus's agents, every process
19
+ # under a terminal labelled with a space, apart from everything else on the
20
+ # host, which is one number each, and the recorder's own CPU apart from both.
21
+ # A process outside those terminals is never written down, not even its pid.
22
+ #
23
+ # With each reading go the shares of those terminals, one each: the CPU and
24
+ # memory of every process under it, the commands its agent started included,
25
+ # so that no process counts toward two, and the shares add up to the agents'
26
+ # totals. A share names its terminal's work by the card its labels give, the
27
+ # phase its tab gives, and the step that card is in, from the hand-off store,
28
+ # which the recorder only ever reads. `host report` ranks the steps and
29
+ # phases by them.
30
+ #
31
+ # Each reading also counts the agents open as working or waiting, and each
32
+ # share says which its agent was. An agent is working while it takes its
33
+ # turn, as herdr-core's status for its terminal says, and waiting while it is
34
+ # open but its turn has ended, it waits on the human in its tab, it hit an
35
+ # error, or it reports no status. A tab that holds its shell alone is not
36
+ # open, so it is neither. `host report` shows, for each number of agents
37
+ # working, how much of the time the host was at its limit, and from which
38
+ # number the host was the limit.
39
+ #
40
+ # Beside the readings go the test runs: each run of a repo's tests that an
41
+ # agent starts through `ocnus tests run` (tests.sh), with its card and
42
+ # repo, when it started, how long it took, the CPU it used and the most
43
+ # memory it held at once. A test run is named by its card and repo alone.
44
+ # Its command is kept only as a fingerprint, a number the same for the same
45
+ # command and from which its text cannot be read back, and nothing else of
46
+ # its command line is kept. `host report` ranks the test runs too, and sets
47
+ # runs of the same command in the same repo against each other to say how
48
+ # much slower they were with more agents working.
49
+ #
50
+ # With each reading go the shares of the test runs going then, too, each
51
+ # worked out as a terminal's is, from the processes under the run's job,
52
+ # which are in their terminal's share as well. A run that ended since the
53
+ # reading before gets the rest of its CPU in the next one. `host report`
54
+ # names the cards' steps and the test runs going in the longest stretches
55
+ # when the CPU or memory was at its limit.
56
+ #
57
+ # While recording is on, `task new` and `task build` start claude with hooks
58
+ # that mark its agent's time (host_hooks): cli/host-mark appends a word and
59
+ # the time, to the millisecond, to a file for the agent's card and phase, as
60
+ # the session starts and stops, a prompt is given, a tool starts and ends,
61
+ # and a tool asks for permission. It never reads what the hook is given, so
62
+ # a marks file holds no prompt, reply, command, file or tool output. With
63
+ # each reading goes the split of each open agent's seconds, worked out from
64
+ # those marks (host_splits): on the host, while its tools run, and waiting
65
+ # on the model. The rest of the time its agent was open is neither, such as
66
+ # waiting on the human. `host report` says where the steps' time went by
67
+ # them, and ends with its verdict on the host, which weighs each reading by
68
+ # the agents' time on the host in it: what to upgrade first, if anything.
69
+ #
70
+ # From the same marks, each wait on the model is kept too, as its start and
71
+ # end alone, by the reading it ended in. A wait is slow at over twice the
72
+ # median of every wait kept. When slow waits came while the CPU, memory and
73
+ # disk were all below their limit, `host report` says the network may be the
74
+ # cause, and when they were at least a tenth of the period's waits, and no
75
+ # resource was the one to upgrade, its verdict is that the network was the
76
+ # limit.
77
+ #
78
+ # A share's card, phase and step, a split's, a wait's, and a test run's card
79
+ # and repo, are the only text the readings hold, and only the values
80
+ # ocnus gives them: a card ID, a phase, a step of it, and the name of
81
+ # one of the space's repos.
82
+ #
83
+ # Readings go in a SQLite file of their own, not the hand-off store, so that
84
+ # `host off` can delete every one of them and never a hand-off.
85
+
86
+ HOST_DIR=$ENT_HOME/host
87
+ HOST_DB=$HOST_DIR/readings.db
88
+ # The marks of the agents' time: a folder for each space, holding a file for
89
+ # each card's phase, as ABC-1.build.
90
+ HOST_MARKS=$HOST_DIR/marks
91
+ # The recorder's terminal in herdr-core. hc lets one live terminal hold a
92
+ # name, so a second wake fails, and there is never more than one recorder.
93
+ HOST_TERMINAL=ocnus-host
94
+ # Seconds between readings, and the longest gap a reading may cover: after a
95
+ # longer one, such as the machine sleeping, the recorder starts again from
96
+ # the new sample, with no reading for the gap.
97
+ HOST_EVERY=10
98
+ HOST_GAP=30
99
+ # Readings older than this many days are deleted, when a run starts and
100
+ # every HOST_PRUNE_EVERY readings.
101
+ HOST_KEEP_DAYS=90
102
+ HOST_PRUNE_EVERY=360
103
+
104
+ # One row a reading, each covering the secs before its at (seconds since
105
+ # 1970). Every column is a number, so no reading can hold a name.
106
+ #
107
+ # And one row a terminal labelled with a space, for each reading, by its at:
108
+ # the share of all cores' time its processes used, cpu, and the memory they
109
+ # held, mem_mb, which add up to the reading's cpu_agents and mem_agents_mb;
110
+ # whether its agent was open, as 1 or 0; whether it was working, as 1 or 0,
111
+ # in a column HOST_ADDED gives it; and its work. That is the card its
112
+ # ocnus.card label names, when it is a card ID; its phase, write-up when
113
+ # its tab is named after that card, as `task new` names it, and build
114
+ # otherwise; and the step that card is in, when it is one of that phase's.
115
+ # Each is empty when it is not known, and they are the only columns that are
116
+ # not numbers.
117
+ #
118
+ # And one row a test run (tests.sh): its card and its repo, the folder name
119
+ # the space's repos file gives, the only columns that are not numbers; when
120
+ # it started and ended, in seconds since 1970; how long it took, secs, to
121
+ # 0.01 s; the CPU its command and everything that command waited for used,
122
+ # cpu_secs; the most memory its processes held at once, mem_mb; the CPU that
123
+ # watching it used, watch_secs, which counts as recording's own; the pid of
124
+ # its job while it runs; cut, 1 when the recorder ended it, as its process
125
+ # had gone with no end written, after kill -9, and 0 otherwise; and the
126
+ # fingerprint of its command, cmd, in a column HOST_ADDED gives it. A value
127
+ # not known is empty. A cut run's CPU is what the recorder counted of it,
128
+ # and empty when it counted none.
129
+ #
130
+ # And one row a test run going, for each reading, by its at: run, the id of
131
+ # its row in test_runs; the share of all cores' time its processes used,
132
+ # cpu, and the memory they held, mem_mb, as for a terminal's share, which
133
+ # holds them too. The reading after a run ended has the rest of its CPU, and
134
+ # the most memory it held at once, its row's mem_mb.
135
+ #
136
+ # And one row an open agent with marks of its time, for each reading, by its
137
+ # at: its work, card, phase and step, as its share names it, and the seconds
138
+ # of the reading it was on the host, host_secs, and waiting on the model,
139
+ # model_secs, to the millisecond. The rest of the reading's secs is neither.
140
+ #
141
+ # And one row a wait on the model, written by the reading it ended in: the
142
+ # work of the agent that waited, card, phase and step, as its split names
143
+ # it, and when the wait started and ended, in seconds since 1970, to the
144
+ # millisecond. A wait that started before the reading keeps its real start.
145
+ HOST_TABLE='create table if not exists readings (
146
+ at integer not null, secs integer not null, agents integer not null,
147
+ cpu_busy real, cpu_system real, cpu_p real, cpu_e real, cpu_self real,
148
+ cpu_agents real, cpu_rest real,
149
+ mem_pressure integer, mem_used_mb integer, mem_agents_mb integer, mem_rest_mb integer,
150
+ swap_used_mb integer, swap_ins integer, swap_outs integer, compressed_mb integer,
151
+ disk_read_kb integer, disk_write_kb integer, disk_free_pct real);
152
+ create index if not exists readings_at on readings (at);
153
+ create table if not exists shares (
154
+ at integer not null, card text, phase text, step text,
155
+ open integer not null, cpu real, mem_mb integer);
156
+ create index if not exists shares_at on shares (at);
157
+ create table if not exists test_runs (
158
+ id integer primary key, card text not null, repo text not null,
159
+ started integer not null, ended integer, secs real, cpu_secs real,
160
+ mem_mb integer, watch_secs real, pid integer, cut integer not null default 0);
161
+ create index if not exists test_runs_started on test_runs (started);
162
+ create table if not exists run_shares (
163
+ at integer not null, run integer not null, cpu real, mem_mb integer);
164
+ create index if not exists run_shares_at on run_shares (at);
165
+ create table if not exists splits (
166
+ at integer not null, card text, phase text, step text, host_secs real, model_secs real);
167
+ create index if not exists splits_at on splits (at);
168
+ create table if not exists model_waits (
169
+ card text, phase text, step text, started real not null, ended real not null);
170
+ create index if not exists model_waits_ended on model_waits (ended);'
171
+ # The steps of each phase, as a share names them.
172
+ HOST_WRITE_UP_STEPS='define plan breakdown'
173
+ HOST_BUILD_STEPS='build review pr'
174
+ # The columns added since, each as its table and its name, with its type, one
175
+ # a line. host_table gives them to a store made before them, as to a new one.
176
+ HOST_ADDED='readings.net_in_kb integer
177
+ readings.net_out_kb integer
178
+ readings.net_wifi integer
179
+ readings.net_resent_pct real
180
+ readings.wifi_rssi integer
181
+ readings.wifi_noise integer
182
+ readings.on_battery integer
183
+ readings.low_power integer
184
+ readings.thermal integer
185
+ readings.cores integer
186
+ readings.working integer
187
+ readings.waiting integer
188
+ shares.working integer
189
+ test_runs.cmd integer'
190
+ # cores is how many cores the reading counted, so that a share of all cores'
191
+ # time can be made CPU time again: share * secs * cores / 100 seconds.
192
+ # working and waiting are how many of the agents open were working and how
193
+ # many were waiting (host_agents), and a share's working is 1 when its agent
194
+ # was working and 0 otherwise. A reading or share made before them has none.
195
+ # A test run's cmd is the fingerprint of its command (tests_run), and one
196
+ # made before it has none.
197
+ HOST_COLUMNS='at, secs, agents, cpu_busy, cpu_system, cpu_p, cpu_e, cpu_self,
198
+ cpu_agents, cpu_rest, mem_pressure, mem_used_mb, mem_agents_mb, mem_rest_mb,
199
+ swap_used_mb, swap_ins, swap_outs, compressed_mb,
200
+ disk_read_kb, disk_write_kb, disk_free_pct,
201
+ net_in_kb, net_out_kb, net_wifi, net_resent_pct, wifi_rssi, wifi_noise,
202
+ on_battery, low_power, thermal, cores, working, waiting'
203
+
204
+ # Make the tables, and add the HOST_ADDED columns they do not have, all of
205
+ # them in one go.
206
+ host_table() {
207
+ local have name type sql=
208
+ store "$HOST_DB" "$HOST_TABLE" || return 1
209
+ have=$(store "$HOST_DB" "select ' ' || (select group_concat('readings.' || name, ' ') from pragma_table_info('readings'))
210
+ || ' ' || (select group_concat('shares.' || name, ' ') from pragma_table_info('shares'))
211
+ || ' ' || (select group_concat('test_runs.' || name, ' ') from pragma_table_info('test_runs')) || ' ';") || return 1
212
+ while read -r name type; do
213
+ case $have in *" $name "*) ;; *) sql="${sql}alter table ${name%%.*} add column ${name#*.} $type; " ;; esac
214
+ done <<< "$HOST_ADDED"
215
+ [ -z "$sql" ] || store "$HOST_DB" "begin; ${sql}commit;"
216
+ }
217
+
218
+ HOST_USAGE='usage: ocnus host [on|off|report [<period>]] (see: ocnus help)'
219
+ HOST_PERIODS='a period is <n>d or <n>h back from now, like 7d or 12h; a day, like 2026-11-29; or two days and every day between, like 2026-11-01..2026-11-29'
220
+
221
+ # --- on and off -------------------------------------------------------------
222
+
223
+ # Say whether recording is on, and what it has.
224
+ host_show() {
225
+ local row count first last state
226
+ if [ ! -d "$HOST_DIR" ]; then
227
+ say "Recording is off: ocnus keeps no readings of this machine. Turn it on with: ocnus host on"
228
+ return 0
229
+ fi
230
+ say "Recording is on: a reading of CPU, memory, disk, network, and power and heat every $HOST_EVERY seconds while an ocnus agent is open."
231
+ if have_sqlite && [ -f "$HOST_DB" ] &&
232
+ row=$(store "$HOST_DB" "select count(*), coalesce(strftime('%Y-%m-%d %H:%M', min(at), 'unixepoch', 'localtime'), ''),
233
+ coalesce(strftime('%Y-%m-%d %H:%M', max(at), 'unixepoch', 'localtime'), '') from readings;"); then
234
+ IFS='|' read -r count first last <<< "$row"
235
+ if [ "${count:-0}" -gt 0 ] 2>/dev/null; then say " readings $count, from $first to $last"
236
+ else say " readings none yet"
237
+ fi
238
+ fi
239
+ state=$(hc_cmd get "$HOST_TERMINAL" --json 2>/dev/null) || state=
240
+ case $state in
241
+ *'"state":"live"'* | *'"state": "live"'*) say " recorder running, as the terminal $HOST_TERMINAL in herdr-core" ;;
242
+ *) say " recorder not running: it starts with the next agent" ;;
243
+ esac
244
+ say " report ocnus host report [<period>]"
245
+ say " off ocnus host off, which deletes every reading"
246
+ }
247
+
248
+ host_on() {
249
+ local os
250
+ [ "$#" -eq 0 ] || die "$HOST_USAGE"
251
+ os=$(uname -s 2>/dev/null) || os=
252
+ [ "$os" = Darwin ] ||
253
+ die "recording reads macOS's own tools, so it works on macOS only, and this machine is ${os:-not one uname can name}. Nothing was turned on."
254
+ if [ -d "$HOST_DIR" ]; then
255
+ say "Recording is already on. See it with: ocnus host report"
256
+ host_wake
257
+ return 0
258
+ fi
259
+ have_sqlite ||
260
+ die "$SQLITE is not installed, and the readings are kept with it. Install it, then run this again."
261
+ command -v jq >/dev/null 2>&1 ||
262
+ die "jq is not installed, and the recorder reads herdr-core's terminals with it. Install it, then run this again."
263
+ have_hc ||
264
+ die "Herdr's hc is not installed, and the recorder runs in herdr-core. Install Herdr, then run this again:
265
+ $HERDR_INSTALL"
266
+ mkdir -p "$HOST_DIR" && chmod 700 "$HOST_DIR" || die "could not make $HOST_DIR, so recording is still off."
267
+ host_table || {
268
+ rm -rf "$HOST_DIR"
269
+ die "could not make $HOST_DB, so recording is still off."
270
+ }
271
+ say "Recording is on: a reading of CPU, memory, disk, network, and power and heat every $HOST_EVERY seconds while an ocnus agent is open."
272
+ say " readings $HOST_DB, kept for $HOST_KEEP_DAYS days"
273
+ say " report ocnus host report [<period>]"
274
+ say " off ocnus host off, which deletes every reading"
275
+ host_wake
276
+ }
277
+
278
+ host_off() {
279
+ local tries=0
280
+ [ "$#" -eq 0 ] || die "$HOST_USAGE"
281
+ if [ ! -d "$HOST_DIR" ]; then
282
+ say "Recording is already off: ocnus keeps no readings of this machine."
283
+ return 0
284
+ fi
285
+ # Stop the recorder before its folder goes, so that it writes nothing more.
286
+ # hc kill hangs it up; --rm removes its terminal once it has exited.
287
+ if have_hc; then
288
+ hc_cmd kill "$HOST_TERMINAL" >/dev/null 2>&1 || true
289
+ while host_recording; do
290
+ tries=$((tries + 1))
291
+ [ "$tries" -le 50 ] ||
292
+ die "the recorder, the terminal $HOST_TERMINAL in herdr-core, did not stop, so recording is still on. Stop it with: hc kill $HOST_TERMINAL, then run this again."
293
+ sleep 0.2
294
+ done
295
+ fi
296
+ rm -rf "$HOST_DIR" 2>/dev/null || rm -rf "$HOST_DIR" 2>/dev/null || true
297
+ [ ! -e "$HOST_DIR" ] || die "could not delete $HOST_DIR, so its readings are still there. Delete it, then run this again."
298
+ say "Recording is off, and every reading is deleted."
299
+ }
300
+
301
+ # Whether the recorder's terminal is live in herdr-core.
302
+ host_recording() {
303
+ local state
304
+ state=$(hc_cmd get "$HOST_TERMINAL" --json 2>/dev/null) || return 1
305
+ case $state in *'"state":"live"'* | *'"state": "live"'*) return 0 ;; *) return 1 ;; esac
306
+ }
307
+
308
+ # Start the recorder while recording is on, unless it is running already. An
309
+ # agent never waits on it: it starts in the background, and a wake that
310
+ # fails, as a second one does since the name is taken, is ignored. Its
311
+ # terminal has no herdr.space label, so the Herdr app never shows it; no
312
+ # parent, so it goes on when the tab that woke it closes; and no --keep, so
313
+ # nothing brings it back after a restart.
314
+ host_wake() {
315
+ [ -d "$HOST_DIR" ] || return 0
316
+ have_hc || return 0
317
+ hc_cmd run --bg --no-parent --rm --name "$HOST_TERMINAL" --cwd "$HOST_DIR" \
318
+ -- "$REPO/cli/ocnus" host record </dev/null >/dev/null 2>&1 || true
319
+ }
320
+
321
+ # Print the settings, as one line of JSON for claude's --settings=, whose
322
+ # Claude Code hooks mark the time of the agent of the space $1 on the card $2
323
+ # in the phase $3, while recording is on, or fail when it is off or they
324
+ # cannot be given. Each hook runs cli/host-mark with its mark and the card's
325
+ # marks file for that phase, each path quoted for the shell that runs it, and
326
+ # the space's folder of marks is made here, as host-mark makes none. A
327
+ # SessionStart marks a start only as the session starts or is continued: one
328
+ # after /clear or a compaction is no new start.
329
+ host_hooks() {
330
+ local space=$1 card=$2 phase=$3 dir
331
+ [ -d "$HOST_DIR" ] || return 1
332
+ valid_name "$space" && [[ $card =~ $CARD_RE ]] || return 1
333
+ case $phase in write-up | build) ;; *) return 1 ;; esac
334
+ command -v jq >/dev/null 2>&1 && command -v perl >/dev/null 2>&1 || return 1
335
+ dir=$HOST_MARKS/$space
336
+ mkdir -p "$dir" 2>/dev/null || return 1
337
+ jq -cn --arg mark "$REPO/cli/host-mark" --arg file "$dir/$card.$phase" '
338
+ def run($m): [{type: "command", command: "\($mark | @sh) \($m) \($file | @sh)"}];
339
+ def on($m): [{hooks: run($m)}];
340
+ def tools($m): [{matcher: "*", hooks: run($m)}];
341
+ {hooks: {
342
+ SessionStart: [{matcher: "startup|resume", hooks: run("start")}],
343
+ UserPromptSubmit: on("prompt"),
344
+ PreToolUse: tools("pre"), PostToolUse: tools("post"), PostToolUseFailure: tools("post"),
345
+ PermissionRequest: tools("ask"),
346
+ Stop: on("stop"), StopFailure: on("stop"), SessionEnd: on("stop")}}'
347
+ }
348
+
349
+ # --- the recorder -----------------------------------------------------------
350
+
351
+ # Each core's user, system, idle and nice ticks since the machine started,
352
+ # one core a line, from the Mach call top and Activity Monitor read. Then a
353
+ # line @time, and a line for each pid it is given, one of the agents'
354
+ # processes: the pid and its CPU time in seconds. That is its own user and
355
+ # system time and those of its children that have exited and been waited
356
+ # for, grandchildren included, from proc_pid_rusage: ri_user_time,
357
+ # ri_system_time, ri_child_user_time and ri_child_system_time, the 64-bit
358
+ # words 2, 3, 12 and 13 of a rusage_info_v2. They are in Mach ticks, so many
359
+ # nanoseconds each as mach_timebase_info says, and each is 64 bits, which JXA
360
+ # joins as text unless made a Number. It reads only the human's own
361
+ # processes, so it needs no admin rights, and a pid it cannot read, such as
362
+ # one that has exited, gets no line. JXA binds every call, so no compiler or
363
+ # helper is needed.
364
+ #
365
+ # Then a line @wifi, and after it the Wi-Fi interface's name with its signal
366
+ # and noise in dBm, from CoreWLAN, when the Mac has one: "en0 -61 -92". It
367
+ # asks the interface for those three alone, and never for the network it has
368
+ # joined. Last a line @power, and after it the thermal state, 0 nominal to 3
369
+ # critical, and 1 when Low Power Mode is on, from NSProcessInfo: "0 0". Each
370
+ # is left out when it cannot be read, and the rest is not.
371
+ HOST_JXA='function run(argv) {
372
+ ObjC.bindFunction("mach_host_self", ["unsigned int", []]);
373
+ ObjC.bindFunction("host_processor_info", ["int", ["unsigned int", "int", "unsigned int *", "int **", "unsigned int *"]]);
374
+ var count = Ref(), info = Ref(), size = Ref(), out = [];
375
+ if ($.host_processor_info($.mach_host_self(), 2, count, info, size) == 0)
376
+ for (var i = 0; i < count[0]; i++)
377
+ out.push([0, 1, 2, 3].map(function (s) { return info[0][i * 4 + s] >>> 0; }).join(" "));
378
+ ObjC.bindFunction("mach_timebase_info", ["int", ["unsigned int *"]]);
379
+ ObjC.bindFunction("calloc", ["unsigned int *", ["unsigned long", "unsigned long"]]);
380
+ ObjC.bindFunction("malloc", ["unsigned long long *", ["unsigned long"]]);
381
+ ObjC.bindFunction("proc_pid_rusage", ["int", ["int", "int", "unsigned long long *"]]);
382
+ var tb = $.calloc(2, 4), ru = $.malloc(512);
383
+ if ($.mach_timebase_info(tb) == 0 && tb[1] > 0) {
384
+ out.push("@time");
385
+ argv.forEach(function (p) {
386
+ if (/^[0-9]+$/.test(p) && $.proc_pid_rusage(Number(p), 2, ru) == 0)
387
+ out.push(p + " " + ([2, 3, 12, 13].reduce(function (t, k) { return t + Number(ru[k]); }, 0) * tb[0] / tb[1] / 1e9).toFixed(3));
388
+ });
389
+ }
390
+ try {
391
+ ObjC.import("CoreWLAN");
392
+ var w = $.CWWiFiClient.sharedWiFiClient.interface, wifi = ["@wifi"];
393
+ if (w && !w.isNil()) wifi.push(ObjC.unwrap(w.interfaceName) + " " + w.rssiValue + " " + w.noiseMeasurement);
394
+ out = out.concat(wifi);
395
+ } catch (e) {}
396
+ try {
397
+ var pi = $.NSProcessInfo.processInfo;
398
+ out.push("@power", pi.thermalState + " " + (pi.isLowPowerModeEnabled ? 1 : 0));
399
+ } catch (e) {}
400
+ return out.join("\n");
401
+ }'
402
+
403
+ # Each core's type, E or P, in the order of its logical id, from the device
404
+ # tree: "E E E E P P P P" on an M1. Nothing on a Mac whose cores have no type.
405
+ host_core_types() {
406
+ ioreg -l -p IODeviceTree 2>/dev/null | LC_ALL=C awk '
407
+ function flush() { if (incpu && id != "" && (type == "E" || type == "P")) t[id] = type; id = ""; type = "" }
408
+ /\+-o / { flush(); incpu = ($0 ~ /\+-o cpu[0-9]+@/); next }
409
+ incpu && /"logical-cpu-id" = / { id = $NF; if (id !~ /^[0-9]+$/) id = "" }
410
+ incpu && /"cluster-type" = / { type = $0; sub(/.*<"/, "", type); sub(/">.*/, "", type) }
411
+ END { flush(); for (i = 0; i in t; i++) printf "%s%s", (i ? " " : ""), t[i]; print "" }'
412
+ }
413
+
414
+ # The terminals seen so far in this run, by the terminal's address, as
415
+ # "t7=1234,demo,ABC-1,write-up ": its process, its space, and the card and
416
+ # phase its labels give, either empty when they give none. A terminal's
417
+ # process and labels do not change while it lives, so hc is asked once.
418
+ HOST_TERMS=' '
419
+ # How many agents are open, the pids of ocnus's agents' processes, and
420
+ # each of them with the process of the terminal it is under, as
421
+ # "500:77 600:77": host_agents sets them. And each terminal's work, by its
422
+ # process, as " 77=ABC-1,write-up,plan ": host_work sets it.
423
+ HOST_AGENTS=0
424
+ HOST_PROCS=
425
+ HOST_ROOTS=
426
+ HOST_WORK=' '
427
+ # nettop's counts in the sample before, as the recorder's awk printed them,
428
+ # kept here and never in a file.
429
+ HOST_NET=
430
+
431
+ # What hc says of the terminal $1, of the space $2, as host_agents keeps it:
432
+ # "1234,demo,ABC-1,write-up". The card is its ocnus.card label, in its
433
+ # usual upper-case form, when that is a card ID, and empty otherwise. Its
434
+ # phase is write-up when its ocnus.tab label is the card, as `task new`
435
+ # names the write-up tab, and build otherwise: `task start` names the tab
436
+ # after the task. With no card, it has no phase. jq turns every character a
437
+ # card ID cannot hold into ?, so that no label can split the line it prints.
438
+ # Fails when hc gives no pid.
439
+ host_term() {
440
+ local line pid card tab phase='' space=$2
441
+ line=$(hc_cmd get "$1" --json 2>/dev/null | jq -r '[(.pid // ""), (.labels["ocnus.card"] // ""), (.labels["ocnus.tab"] // "")]
442
+ | map(tostring | gsub("[^A-Za-z0-9-]"; "?") | if . == "" then "-" else . end) | join(" ")' 2>/dev/null) || return 1
443
+ read -r pid card tab <<< "$line"
444
+ case $pid in '' | *[!0-9]*) return 1 ;; esac
445
+ if [[ $card =~ $CARD_RE ]]; then
446
+ read -r card tab <<< "$(printf '%s %s\n' "$card" "$tab" | tr '[:lower:]' '[:upper:]')"
447
+ if [ "$tab" = "$card" ]; then phase=write-up; else phase=build; fi
448
+ else
449
+ card=
450
+ fi
451
+ valid_name "$space" || space=
452
+ printf '%s,%s,%s,%s\n' "$pid" "$space" "$card" "$phase"
453
+ }
454
+
455
+ # An awk function for a program that reads ps's lines, each process's pid,
456
+ # ppid and RSS, into there[pid] and kids[ppid], a list of its children's pids
457
+ # each after a space: walk(n, p) finds every process under the n roots p[1]
458
+ # to p[n] that are there, the roots included, from each root down. It puts
459
+ # them in procs[0] onward, and returns how many there are. Each is under one
460
+ # root alone, the first that reaches it, which mine[pid] names.
461
+ HOST_WALK='
462
+ function walk(n, p, i, h, m, j, k) {
463
+ q = 0
464
+ for (i = 1; i <= n; i++) if ((p[i] in there) && !(p[i] in mine)) { mine[p[i]] = p[i]; procs[q++] = p[i] }
465
+ for (h = 0; h < q; h++) {
466
+ m = split(kids[procs[h]], k, " ")
467
+ for (j = 1; j <= m; j++) if (!(k[j] in mine)) { mine[k[j]] = mine[procs[h]]; procs[q++] = k[j] }
468
+ }
469
+ return q
470
+ }'
471
+
472
+ # Count the open agents: the terminals labelled with a space, in every space,
473
+ # whose process has a child in ps's list, $1, of each process's pid, ppid and
474
+ # RSS. While an agent runs, its terminal's shell is its parent; once it has
475
+ # exited, the tab holds only a login shell, with no child. Every process
476
+ # under those terminals, their shells included, whether an agent is running
477
+ # in them or not, is ocnus's: HOST_PROCS. Each is under one terminal
478
+ # alone, the first that reaches it, whose process it is tagged with in
479
+ # HOST_ROOTS. A ps line that does not start with three numbers is skipped.
480
+ # HOST_TERMS_NOW is what host_term gave for each terminal listed.
481
+ #
482
+ # The same list from hc gives each terminal's status, which changes from one
483
+ # sample to the next, so it is read every time: HOST_WORKING holds the
484
+ # process of each terminal whose status is working, as " 77 88 ". An open
485
+ # agent is working while it takes its turn, and waiting otherwise: its turn
486
+ # has ended (idle or done), it waits on the human in its tab (blocked), it
487
+ # hit an error, or it has reported no status. hc's list gives the status as
488
+ # a word, and hc get as an object holding it, so either is read. A terminal
489
+ # that is not open, its shell alone, is neither, whatever its status.
490
+ #
491
+ # Before the walk, host_work reads each terminal's work and the test runs,
492
+ # as of $2, the time of this sample. Each process under the job of a test
493
+ # run going, among those under the terminals, is tagged with that run too,
494
+ # the first run that reaches it, so HOST_ROOTS holds each process as
495
+ # "pid:terminal's process", or "pid:terminal's process:run".
496
+ HOST_TERMS_NOW=
497
+ HOST_WORKING=' '
498
+ host_agents() {
499
+ local d t status info out pids=' ' working=' '
500
+ HOST_TERMS_NOW=
501
+ for d in "$SPACES"/*/; do
502
+ [ -d "$d" ] || continue
503
+ d=${d%/}
504
+ # Each terminal as "address:status", the status with every character
505
+ # but a-z taken out, so that neither can split the list.
506
+ for t in $(hc_cmd ls --json --label "ocnus.space=${d##*/}" 2>/dev/null |
507
+ jq -r '.terminals[]? | select(.address) | "\(.address):\((.status | if type == "object" then .state else . end) // ""
508
+ | tostring | gsub("[^a-z]"; ""))"' 2>/dev/null); do
509
+ status=${t##*:} t=${t%:*}
510
+ case $t in '' | *[!A-Za-z0-9_/-]*) continue ;; esac
511
+ case $HOST_TERMS in
512
+ *" $t="*) info=${HOST_TERMS#*" $t="}; info=${info%% *} ;;
513
+ *)
514
+ info=$(host_term "$t" "${d##*/}") || continue
515
+ HOST_TERMS="$HOST_TERMS$t=$info "
516
+ ;;
517
+ esac
518
+ pids="$pids${info%%,*} "
519
+ [ "$status" != working ] || working="$working${info%%,*} "
520
+ HOST_TERMS_NOW="$HOST_TERMS_NOW$info "
521
+ done
522
+ done
523
+ HOST_WORKING=$working
524
+ if [ -n "$HOST_TERMS_NOW" ]; then
525
+ # shellcheck disable=SC2086
526
+ host_work "$2" $HOST_TERMS_NOW
527
+ else
528
+ HOST_WORK=' ' HOST_OPEN_RUNS='' HOST_ENDED_RUNS=''
529
+ fi
530
+ # It prints the count, then the processes, from each terminal down, and on
531
+ # a second line each process with its terminal's, and its run's.
532
+ out=$(printf '%s\n' "$1" | LC_ALL=C awk -v pids="$pids" -v runs="$HOST_OPEN_RUNS" "$HOST_WALK"'
533
+ BEGIN { n = split(pids, p, " "); for (i = 1; i <= n; i++) want[p[i]] = 1 }
534
+ !($1 ~ /^[0-9]+$/ && $2 ~ /^[0-9]+$/ && $3 ~ /^[0-9]+$/) { next }
535
+ { there[$1] = 1; kids[$2] = kids[$2] " " $1 }
536
+ ($2 in want) && !($2 in seen) { seen[$2] = 1; open++ }
537
+ END {
538
+ q = walk(n, p)
539
+ nr = split(runs, rr, " ")
540
+ for (i = 1; i <= nr; i++) {
541
+ if (split(rr[i], g, ":") != 2 || !(g[2] in mine) || (g[2] in runof)) continue
542
+ runof[g[2]] = g[1]; t = 0; todo[t++] = g[2]
543
+ for (h = 0; h < t; h++) {
544
+ m = split(kids[todo[h]], k, " ")
545
+ for (j = 1; j <= m; j++) if ((k[j] in mine) && !(k[j] in runof)) { runof[k[j]] = g[1]; todo[t++] = k[j] }
546
+ }
547
+ }
548
+ printf "%d", open + 0
549
+ for (h = 0; h < q; h++) printf " %s", procs[h]
550
+ print ""
551
+ for (h = 0; h < q; h++) printf "%s%s:%s%s", (h ? " " : ""), procs[h], mine[procs[h]], ((procs[h] in runof) ? ":" runof[procs[h]] : "")
552
+ print ""
553
+ }') || out=0
554
+ HOST_ROOTS=
555
+ case $out in *$'\n'*) HOST_ROOTS=${out#*$'\n'}; out=${out%%$'\n'*} ;; esac
556
+ HOST_AGENTS=${out%% *}
557
+ case $out in *' '*) HOST_PROCS=${out#* } ;; *) HOST_PROCS= ;; esac
558
+ }
559
+
560
+ # Set HOST_WORK to the work of each terminal host_agents listed, $2 onward as
561
+ # HOST_TERMS_NOW holds them, by its process: its card and phase, and the step
562
+ # that card is in. That is what its latest hand-off in its space says: the
563
+ # step it names as next when it is done, as a `new` row names define and a
564
+ # `start` row build, and its own step otherwise. A step that is not one
565
+ # of the terminal's phase's is left empty, as for a write-up tab still open
566
+ # once `task start` has started the build phase. One sqlite3 reads every
567
+ # card's step, on the readings, with the hand-off store attached read-only,
568
+ # so that it is never changed, nor made when there is none. When it cannot be
569
+ # read, every step is empty, and the cards and phases are kept.
570
+ #
571
+ # The same sqlite3 lists the test runs first, so that they are listed when
572
+ # the hand-off store cannot be read: those with no end, as "id:pid" in
573
+ # HOST_OPEN_RUNS, and those not cut short that ended in the HOST_GAP +
574
+ # HOST_EVERY seconds before $1, the time of this sample, as
575
+ # "id:cpu:mem:started" in HOST_ENDED_RUNS, with the CPU their row says they
576
+ # used and the most memory they held, each - when it is not known, and when
577
+ # they started. That reaches back past the sample before, so that a run
578
+ # whose end was written as that one was taken is not missed. The recorder's
579
+ # awk gives each the rest of its CPU once.
580
+ HOST_OPEN_RUNS='' HOST_ENDED_RUNS=''
581
+ host_work() {
582
+ local at=$1 info pid space card phase want='' sql out line mark id run cpu mem steps='' found step uri
583
+ shift
584
+ HOST_WORK=' ' HOST_OPEN_RUNS='' HOST_ENDED_RUNS=''
585
+ for info in "$@"; do
586
+ IFS=, read -r pid space card phase <<< "$info"
587
+ [ -n "$space" ] && [ -n "$card" ] || continue
588
+ want="$want${want:+, }($(sql_str "$space"), $(sql_str "$card"))"
589
+ done
590
+ sql="select '@run ' || id || ' ' || pid from test_runs where ended is null and pid is not null;"
591
+ case $at in
592
+ '' | *[!0-9]*) ;;
593
+ *)
594
+ sql="$sql select '@ran ' || id || ' ' || case when cpu_secs is null then '-' else printf('%.2f', cpu_secs) end
595
+ || ' ' || case when mem_mb is null then '-' else printf('%d', mem_mb) end || ' ' || started
596
+ from test_runs where ended >= $at - $((HOST_GAP + HOST_EVERY)) and cut = 0;"
597
+ ;;
598
+ esac
599
+ if [ -n "$want" ] && [ -f "$STORE" ]; then
600
+ # In a URI, % starts an escape, ? the options and # the end.
601
+ uri=${STORE//\%/%25}; uri=${uri//\?/%3F}; uri=${uri//\#/%23}
602
+ sql="$sql attach $(sql_str "file:$uri?mode=ro") as h;
603
+ with want(space, card) as (values $want)
604
+ select w.space || ',' || w.card || ',' || case when x.status = 'done' then coalesce(x.next, '') else x.step end
605
+ from want w join h.handoffs x on x.id = (select max(id) from h.handoffs where space = w.space and card = w.card);"
606
+ fi
607
+ out=$(store "$HOST_DB" "$sql") || true
608
+ while IFS= read -r line; do
609
+ case $line in
610
+ '@run '*)
611
+ read -r mark id run <<< "$line"
612
+ case $id in '' | *[!0-9]*) continue ;; esac
613
+ case $run in '' | *[!0-9]*) continue ;; esac
614
+ HOST_OPEN_RUNS="$HOST_OPEN_RUNS${HOST_OPEN_RUNS:+ }$id:$run"
615
+ ;;
616
+ '@ran '*)
617
+ read -r mark id cpu mem run <<< "$line"
618
+ case $id in '' | *[!0-9]*) continue ;; esac
619
+ case $cpu in '' | *[!0-9.-]*) continue ;; esac
620
+ case $mem in '' | *[!0-9-]*) continue ;; esac
621
+ case $run in '' | *[!0-9]*) continue ;; esac
622
+ HOST_ENDED_RUNS="$HOST_ENDED_RUNS${HOST_ENDED_RUNS:+ }$id:$cpu:$mem:$run"
623
+ ;;
624
+ ?*) steps="$steps$line"$'\n' ;;
625
+ esac
626
+ done <<< "$out"
627
+ for info in "$@"; do
628
+ IFS=, read -r pid space card phase <<< "$info"
629
+ step=
630
+ found=$'\n'$steps$'\n'
631
+ case $found in
632
+ *$'\n'"$space,$card,"*) [ -z "$card" ] || { step=${found#*$'\n'"$space,$card,"}; step=${step%%$'\n'*}; } ;;
633
+ esac
634
+ case $phase in
635
+ write-up) in_list "$step" "$HOST_WRITE_UP_STEPS" || step= ;;
636
+ build) in_list "$step" "$HOST_BUILD_STEPS" || step= ;;
637
+ *) step= ;;
638
+ esac
639
+ HOST_WORK="$HOST_WORK$pid=$card,$phase,$step "
640
+ done
641
+ }
642
+
643
+ # What one reading is worked out from, each tool's output after a line
644
+ # naming it, and last the ps that host_agents read, $1. osascript is given
645
+ # the agents' processes, HOST_PROCS, which are numbers alone, so they are
646
+ # split on spaces unquoted. A tool that fails leaves its values out of the
647
+ # reading, and never the rest: with pipefail on, the last tool's failure
648
+ # would fail the whole pipeline into awk.
649
+ #
650
+ # The interface the host's traffic goes by is the first on scutil's
651
+ # "Network interfaces:" line. Its name alone goes on, for netstat's count of
652
+ # its bytes: the addresses scutil prints beside it go nowhere. With none,
653
+ # the host is offline, and netstat and nettop are not run. nettop gives each
654
+ # process's TCP bytes out and bytes sent again, since it started, by its
655
+ # name and pid. Its name is never kept, and its pid and counts are kept in
656
+ # the recorder's memory, HOST_NET, until the next sample: never in a file.
657
+ host_sample() {
658
+ local nwi iface='' re='Network interfaces: ([A-Za-z0-9]+)'
659
+ # shellcheck disable=SC2086
660
+ echo @cpu; osascript -l JavaScript -e "$HOST_JXA" $HOST_PROCS 2>/dev/null
661
+ echo @vm; vm_stat 2>/dev/null
662
+ echo @sysctl; sysctl -n kern.memorystatus_vm_pressure_level vm.swapusage 2>/dev/null
663
+ echo @io; ioreg -r -c IOBlockStorageDriver -k Statistics -d 1 2>/dev/null
664
+ echo @df; df -k "$HOME" 2>/dev/null
665
+ nwi=$(scutil --nwi 2>/dev/null) || nwi=
666
+ if [[ $nwi =~ $re ]]; then iface=${BASH_REMATCH[1]}; fi
667
+ echo @nwi; [ -z "$iface" ] || printf '%s\n' "$iface"
668
+ if [ -n "$iface" ]; then
669
+ echo @netstat; netstat -ibn -I "$iface" 2>/dev/null
670
+ echo @nettop; nettop -m tcp -P -L 1 -n -x -J bytes_out,re-tx 2>/dev/null
671
+ fi
672
+ echo @netwas; printf '%s\n' "$HOST_NET"
673
+ echo @pmset; pmset -g batt 2>/dev/null
674
+ echo @ps; printf '%s\n' "$1"
675
+ return 0
676
+ }
677
+
678
+ # The reading, worked out by one awk from this sample and the one before.
679
+ # It reads the sample on stdin, the sample before from the file prev, and the
680
+ # recorder's own time from the file self, which bash's `times` wrote: its
681
+ # own CPU, then that of every program it has run and waited for. It writes
682
+ # this sample to the file out, and prints the reading's values for SQL, or
683
+ # nothing when there is no reading: the first sample of a run, or one after
684
+ # a gap of over HOST_GAP seconds. A value it cannot work out is NULL. It
685
+ # keeps numbers alone: whatever else a tool prints is never kept.
686
+ #
687
+ # The agents' processes are procs, which host_agents found. Their CPU is
688
+ # what their times, from osascript, grew by since the sample before, which
689
+ # keeps a proc line for each of them, with its ppid and its time then. A
690
+ # process not there then counts all of its time, as does one whose time went
691
+ # down, which means its pid was used again. A process seen then that has
692
+ # exited since had its time taken into the nearest of its ancestors then
693
+ # that is still there, when that ancestor waited for it, so when that one is
694
+ # among the agents' processes, its time then is taken away again, and counts
695
+ # once. One still in ps but no longer under the terminals, such as one
696
+ # launchd took over when its parent exited, counts in the rest from then on.
697
+ # Without the times in this sample or the one before, such as when osascript
698
+ # failed, the agents' CPU is NULL: each process would otherwise count all the
699
+ # time it has ever used. The rest is what was busy or used less the agents
700
+ # and, for the CPU, the recorder. None of the four is ever below 0. A process
701
+ # outside procs counts only in the rest, and is never written down.
702
+ #
703
+ # roots tags each of procs with the process of the terminal it is under, as
704
+ # host_agents found it, and each terminal's share is worked out by the same
705
+ # rules from the processes under it: their CPU, with an exited process's time
706
+ # taken away again from the terminal whose process waited for it, which is
707
+ # the one it was under, and their RSS. Each share is rounded, then never
708
+ # below 0, and the agents' CPU and memory are what the shares add up to.
709
+ # After the reading it prints a line for each terminal: its process, 1 when
710
+ # its agent is open and 0 when its shell is alone, its CPU, its memory, and
711
+ # 1 when its agent is working and 0 otherwise. working names the processes
712
+ # of the terminals whose status is working, and an agent works when its
713
+ # terminal is one of them and it is open. The reading counts the agents
714
+ # working, and the agents open less those as waiting.
715
+ #
716
+ # roots also tags some of procs with the test run whose job they are under,
717
+ # and each run going, of openruns, gets a share by the same rules, from the
718
+ # processes tagged with it. An exited process's time is taken away again
719
+ # from a run only when the process that waited for it is in the run it was
720
+ # in, which its proc line in the sample says. Those processes are under a
721
+ # terminal too, so a run's share is in its terminal's.
722
+ #
723
+ # The sample keeps, for each run going, the CPU counted of it so far: what
724
+ # the readings gave it, on top of what its processes had used by the first
725
+ # sample that saw them, when that gave no reading, as the first of a run of
726
+ # the recorder does, and one after a gap. Otherwise the run's time before
727
+ # would all count in the reading after its end. A run that ended since the
728
+ # sample before, of endruns, gets the rest of its CPU in this reading: what
729
+ # its row says it used less what was counted, never below 0, with the most
730
+ # memory it held as its memory. The sample notes each one, so that it gets
731
+ # the rest once, though endruns names it again in the samples after. One
732
+ # with nothing counted gets it only when it started after the sample before,
733
+ # a run between two samples: one going then, uncounted, was under no
734
+ # terminal, and has no share.
735
+ #
736
+ # After the terminals' lines it prints a line for each run's share: "run",
737
+ # the run, its CPU and its memory. Then, for each run going that was
738
+ # counted, "counted", the run and the CPU counted of it so far, in seconds,
739
+ # which a run the recorder cuts short gets as its CPU.
740
+ #
741
+ # Its first line, before the reading, is nettop's counts for HOST_NET:
742
+ # "nettop" and a pid,out,again for each process, or nothing when nettop did
743
+ # not answer. The share sent again is what every process's bytes sent again
744
+ # grew by over what its bytes out grew by, since the sample before; a
745
+ # process not there then, or whose counts went down, as when its
746
+ # connections closed, counts all it has now. The network's bytes are its
747
+ # interface's, and only while it is the same one as in the sample before,
748
+ # by its link's number. The signal is the Wi-Fi's only while that is the
749
+ # interface in use. Offline, every network value is NULL.
750
+ HOST_AWK='
751
+ function isnum(v) { return v ~ /^[0-9]+(\.[0-9]+)?$/ }
752
+ function sint(v) { return v ~ /^-?[0-9]+$/ }
753
+ function still(x) { return (x in tnow) && (x in was) && tnow[x] + 0 >= was[x] + 0 }
754
+ function gone(x) { return !(x in there) || ((x in mine) && !still(x)) }
755
+ function took(t, m, s) { m = t; sub(/m.*/, "", m); s = t; sub(/^[0-9]*m/, "", s); sub(/s$/, "", s); return m * 60 + s }
756
+ function mb(v, u) { u = substr(v, length(v)); v = substr(v, 1, length(v) - 1)
757
+ if (!isnum(v)) return ""
758
+ return u == "G" ? v * 1024 : u == "K" ? v / 1024 : u == "M" ? v : "" }
759
+ function int0(v) { return v == "" ? "NULL" : sprintf("%.0f", v) }
760
+ function dec(v) { return v == "" ? "NULL" : sprintf("%.2f", v) }
761
+ function share(a, b) { return b > 0 ? 100 * a / b : "" }
762
+ function grew(k) { return (k in now_) && (k in prev) && now_[k] + 0 >= prev[k] + 0 ? now_[k] - prev[k] : "" }
763
+ # Write each run going that has been counted, with the CPU counted of it so
764
+ # far, into the sample, and each run that ended. known is 1 when this
765
+ # reading worked out the CPU of each run, rspent.
766
+ function runlines(known, r, x, c) {
767
+ for (r in going) {
768
+ if (known && ((r in isrun) || (r in counted))) c = ((r in counted) ? counted[r] : 0) + (rspent[r] > 0 ? rspent[r] : 0)
769
+ else if (gottime && (r in isrun)) { c = 0; for (x in tnow) if ((x in runof) && runof[x] == r) c += tnow[x] }
770
+ else if (r in counted) c = counted[r]
771
+ else continue
772
+ sofar[r] = c
773
+ print "run", r, sprintf("%.3f", c) > outfile
774
+ }
775
+ for (r in ended_) print "ran", r > outfile
776
+ }
777
+ BEGIN {
778
+ cores = pcores = 0
779
+ while ((getline line < prevfile) > 0) {
780
+ n = split(line, f, " ")
781
+ if (f[1] == "core" && n == 5) { pb[f[2]] = f[3]; psy[f[2]] = f[4]; pt[f[2]] = f[5]; pcores++ }
782
+ else if (f[1] == "proc" && (n == 4 || n == 5) && isnum(f[4])) { wasof[f[2]] = f[3]; was[f[2]] = f[4]; if (n == 5) wasrun[f[2]] = f[5] }
783
+ else if (f[1] == "run" && n == 3 && isnum(f[3])) counted[f[2]] = f[3]
784
+ else if (f[1] == "ran" && n == 2) given[f[2]] = 1
785
+ else if (n == 2 && isnum(f[2])) prev[f[1]] = f[2]
786
+ }
787
+ close(prevfile)
788
+ n = split(procs, f, " ")
789
+ for (i = 1; i <= n; i++) mine[f[i]] = 1
790
+ n = split(roots, f, " ")
791
+ for (i = 1; i <= n; i++) {
792
+ m = split(f[i], g, ":")
793
+ if ((m == 2 || m == 3) && (g[1] in mine)) {
794
+ rootof[g[1]] = g[2]; isroot[g[2]] = 1
795
+ if (m == 3) { runof[g[1]] = g[3]; isrun[g[3]] = 1 }
796
+ }
797
+ }
798
+ n = split(working, f, " ")
799
+ for (i = 1; i <= n; i++) isworking[f[i]] = 1
800
+ n = split(openruns, f, " ")
801
+ for (i = 1; i <= n; i++) if (split(f[i], g, ":") == 2) going[g[1]] = 1
802
+ n = split(endruns, f, " ")
803
+ for (i = 1; i <= n; i++) if (split(f[i], g, ":") == 4 && !(g[1] in going)) { ended_[g[1]] = 1; endcpu[g[1]] = g[2]; endmem[g[1]] = g[3]; endstart[g[1]] = g[4] }
804
+ got = 0; self = 0
805
+ while ((getline line < selffile) > 0) {
806
+ n = split(line, f, " ")
807
+ for (i = 1; i <= n; i++) if (f[i] ~ /^[0-9]+m[0-9.]+s$/) { self += took(f[i]); got = 1 }
808
+ }
809
+ close(selffile)
810
+ if (got) now_["self"] = self
811
+ ntypes = split(types, type, " ")
812
+ }
813
+ /^@/ { sect = substr($0, 2); if (sect == "time") gottime = 1; if (sect == "wifi") gotwifi = 1; next }
814
+ sect == "wifi" && wifiname == "" && NF == 3 && $1 ~ /^[A-Za-z0-9]+$/ && sint($2) && sint($3) { wifiname = $1; rssi_ = $2; noise_ = $3 }
815
+ sect == "power" && thermal == "" && NF == 2 && $1 ~ /^[0-3]$/ && $2 ~ /^[01]$/ { thermal = $1; lowpower = $2 }
816
+ sect == "nwi" && iface == "" && NF == 1 && $1 ~ /^[A-Za-z0-9]+$/ { iface = $1 }
817
+ # Bytes in and out are counted from the end, as the address before them can
818
+ # be empty.
819
+ sect == "netstat" && !("netlink" in now_) && $1 == iface && $3 ~ /^<Link#[0-9]+>$/ && NF >= 10 && isnum($(NF - 4)) && isnum($(NF - 1)) {
820
+ v = $3; gsub(/[^0-9]/, "", v); now_["netlink"] = v; now_["netin"] = $(NF - 4); now_["netout"] = $(NF - 1) }
821
+ sect == "nettop" && /^,bytes_out,re-tx,?$/ { gotnettop = 1 }
822
+ sect == "nettop" && match($0, /\.[0-9]+,[0-9]+,[0-9]+,?$/) {
823
+ v = substr($0, RSTART + 1); sub(/,$/, "", v); split(v, g, ","); sent[g[1]] = g[2]; again[g[1]] = g[3] }
824
+ sect == "netwas" && $1 == "nettop" {
825
+ gotnetwas = 1
826
+ for (i = 2; i <= NF; i++) if (split($i, g, ",") == 3 && isnum(g[1]) && isnum(g[2]) && isnum(g[3])) { wassent[g[1]] = g[2]; wasagain[g[1]] = g[3] }
827
+ }
828
+ sect == "pmset" && !pmset { pmset = 1; if (/Battery Power/) batt = 1; else if (/^Now drawing from /) batt = 0 }
829
+ sect == "cpu" && NF == 4 && isnum($1) && isnum($2) && isnum($3) && isnum($4) {
830
+ b[cores] = $1 + $2 + $4; sy[cores] = $2; t[cores] = $1 + $2 + $3 + $4; cores++ }
831
+ sect == "time" && NF == 2 && ($1 in mine) && isnum($2) { tnow[$1] = $2 }
832
+ sect == "ps" && $1 ~ /^[0-9]+$/ && $2 ~ /^[0-9]+$/ && $3 ~ /^[0-9]+$/ {
833
+ there[$1] = 1; gotps = 1
834
+ if ($2 in isroot) opened[$2] = 1
835
+ if ($1 in mine) { par[$1] = $2; trss[rootof[$1]] += $3; if ($1 in runof) rrss[runof[$1]] += $3 } }
836
+ sect == "vm" && /page size of/ { for (i = 1; i < NF; i++) if ($i == "of" && isnum($(i + 1))) page = $(i + 1) }
837
+ sect == "vm" && /:/ { k = $0; sub(/:.*/, "", k); v = $NF; sub(/\.$/, "", v); if (isnum(v)) vm[k] = v }
838
+ sect == "sysctl" && /^[0-9]+$/ { pressure = $0 }
839
+ sect == "sysctl" && /used = / { v = $0; sub(/.*used = /, "", v); sub(/ .*/, "", v); swap = mb(v) }
840
+ sect == "io" {
841
+ line = $0
842
+ while (match(line, /"Bytes \((Read|Write)\)"=[0-9]+/)) {
843
+ m = substr(line, RSTART, RLENGTH); line = substr(line, RSTART + RLENGTH)
844
+ v = m; sub(/.*=/, "", v)
845
+ if (m ~ /Read/) { rd += v; gotrd = 1 } else { wr += v; gotwr = 1 }
846
+ }
847
+ }
848
+ # The first percentage is the capacity; one after it is of inodes.
849
+ sect == "df" && size == "" { for (i = 4; i <= NF; i++) if ($i ~ /^[0-9]+%$/ && isnum($(i - 3)) && isnum($(i - 1))) { size = $(i - 3); avail = $(i - 1); break } }
850
+ END {
851
+ line = gotnettop ? "nettop" : ""
852
+ if (gotnettop) for (x in sent) line = line " " x "," sent[x] "," again[x]
853
+ print line
854
+ if (("Swapins" in vm)) now_["swin"] = vm["Swapins"]
855
+ if (("Swapouts" in vm)) now_["swout"] = vm["Swapouts"]
856
+ if (gotrd) now_["rd"] = rd
857
+ if (gotwr) now_["wr"] = wr
858
+ print "pid", pid > outfile
859
+ print "at", at > outfile
860
+ for (k in now_) print k, sprintf("%.3f", now_[k]) > outfile
861
+ for (c = 0; c < cores; c++) print "core", c, b[c], sy[c], t[c] > outfile
862
+ if (gottime) print "times", 1 > outfile
863
+ for (x in tnow) { pp = par[x]; r = (x in runof) ? " " runof[x] : ""; print "proc", x, pp, sprintf("%.3f", tnow[x]) r > outfile }
864
+
865
+ reading = 1
866
+ if (prev["pid"] != pid || !("at" in prev)) reading = 0
867
+ else { secs = at - prev["at"]; if (secs <= 0 || secs > gap) reading = 0 }
868
+ if (!reading) { runlines(0); close(outfile); exit }
869
+
870
+ busy = sysp = cpu_p = cpu_e = ""
871
+ if (cores > 0 && cores == pcores) {
872
+ ok = 1
873
+ for (c = 0; c < cores; c++) {
874
+ db = b[c] - pb[c]; ds = sy[c] - psy[c]; dt = t[c] - pt[c]
875
+ if (db < 0 || ds < 0 || dt < 0) { ok = 0; break }
876
+ tb += db; ts += ds; tt += dt
877
+ if (ntypes == cores && type[c + 1] == "P") { Pb += db; Pt += dt; typed = 1 }
878
+ if (ntypes == cores && type[c + 1] == "E") { Eb += db; Et += dt; typed = 1 }
879
+ }
880
+ if (ok) {
881
+ busy = share(tb, tt); sysp = share(ts, tt)
882
+ if (typed) { cpu_p = share(Pb, Pt); cpu_e = share(Eb, Et) }
883
+ }
884
+ }
885
+ selfd = grew("self")
886
+ cpu_self = (selfd != "" && cores > 0) ? 100 * selfd / (secs * cores) : ""
887
+ cpu_agents = cpu_rest = ""
888
+ cpuknown = 0
889
+ if (gottime && ("times" in prev) && cores > 0) {
890
+ for (x in tnow) {
891
+ dx = ((x in was) && tnow[x] + 0 >= was[x] + 0) ? tnow[x] - was[x] : tnow[x]
892
+ spent[rootof[x]] += dx
893
+ if (x in runof) rspent[runof[x]] += dx
894
+ }
895
+ for (x in was) {
896
+ if (!gone(x)) continue
897
+ a = wasof[x]; hops = 0
898
+ while ((a in was) && gone(a) && hops++ < 100000) a = wasof[a]
899
+ if (still(a)) {
900
+ spent[rootof[a]] -= was[x]
901
+ if ((x in wasrun) && (a in runof) && runof[a] == wasrun[x]) rspent[runof[a]] -= was[x]
902
+ }
903
+ }
904
+ cpu_agents = 0
905
+ for (r in isroot) if (r in there) {
906
+ tcpu[r] = spent[r] > 0 ? sprintf("%.2f", 100 * spent[r] / (secs * cores)) + 0 : 0
907
+ cpu_agents += tcpu[r]
908
+ }
909
+ for (r in isrun) rcpu[r] = rspent[r] > 0 ? sprintf("%.2f", 100 * rspent[r] / (secs * cores)) + 0 : 0
910
+ cpuknown = 1
911
+ if (busy != "" && cpu_self != "") { cpu_rest = busy - cpu_agents - cpu_self; if (cpu_rest < 0) cpu_rest = 0 }
912
+ }
913
+ for (r in ended_) if (!(r in given)) {
914
+ if (!(r in counted) && endstart[r] + 0 < prev["at"] - 2) { given[r] = 1; continue }
915
+ restcpu[r] = ""
916
+ if (isnum(endcpu[r]) && cores > 0) {
917
+ rest = endcpu[r] - ((r in counted) ? counted[r] : 0)
918
+ restcpu[r] = rest > 0 ? sprintf("%.2f", 100 * rest / (secs * cores)) + 0 : 0
919
+ }
920
+ restmem[r] = isnum(endmem[r]) ? endmem[r] : ""
921
+ }
922
+ runlines(cpuknown)
923
+ close(outfile)
924
+
925
+ used = compressed = ""
926
+ if (isnum(page) && ("Anonymous pages" in vm) && ("Pages wired down" in vm) && ("Pages occupied by compressor" in vm)) {
927
+ used = (vm["Anonymous pages"] - vm["Pages purgeable"] + vm["Pages wired down"] + vm["Pages occupied by compressor"]) * page / 1048576
928
+ compressed = vm["Pages occupied by compressor"] * page / 1048576
929
+ }
930
+ mem_agents = ""
931
+ if (gotps) {
932
+ mem_agents = 0
933
+ for (r in isroot) if (r in there) { tmem[r] = sprintf("%.0f", trss[r] / 1024) + 0; mem_agents += tmem[r] }
934
+ for (r in isrun) rmem[r] = sprintf("%.0f", rrss[r] / 1024) + 0
935
+ }
936
+ mem_rest = ""
937
+ if (used != "" && mem_agents != "") { mem_rest = used - mem_agents; if (mem_rest < 0) mem_rest = 0 }
938
+ rdk = grew("rd"); wrk = grew("wr")
939
+ free = size > 0 ? 100 * avail / size : ""
940
+
941
+ nin = nout = wifi = resent = rssi = noise = ""
942
+ if (iface != "") {
943
+ if (("netlink" in now_) && ("netlink" in prev) && now_["netlink"] + 0 == prev["netlink"] + 0) { nin = grew("netin"); nout = grew("netout") }
944
+ if (gotwifi) wifi = iface == wifiname ? 1 : 0
945
+ if (wifi == 1 && rssi_ + 0 < 0) rssi = rssi_
946
+ if (wifi == 1 && noise_ + 0 < 0) noise = noise_
947
+ if (gotnettop && gotnetwas) {
948
+ out = re = 0
949
+ for (x in sent) {
950
+ if ((x in wassent) && sent[x] + 0 >= wassent[x] + 0 && again[x] + 0 >= wasagain[x] + 0) { out += sent[x] - wassent[x]; re += again[x] - wasagain[x] }
951
+ else { out += sent[x]; re += again[x] }
952
+ }
953
+ resent = share(re, out)
954
+ if (resent != "" && resent > 100) resent = 100
955
+ }
956
+ }
957
+
958
+ nworking = 0
959
+ for (r in isroot) if ((r in there) && (r in opened) && (r in isworking)) { works[r] = 1; nworking++ }
960
+ nwaiting = agents - nworking
961
+ if (nwaiting < 0) nwaiting = 0
962
+
963
+ printf "%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\n",
964
+ int0(at), int0(secs), int0(agents), dec(busy), dec(sysp), dec(cpu_p), dec(cpu_e), dec(cpu_self),
965
+ dec(cpu_agents), dec(cpu_rest), int0(pressure), int0(used), int0(mem_agents), int0(mem_rest),
966
+ int0(swap), int0(grew("swin")), int0(grew("swout")), int0(compressed),
967
+ int0(rdk == "" ? "" : rdk / 1024), int0(wrk == "" ? "" : wrk / 1024), dec(free),
968
+ int0(nin == "" ? "" : nin / 1024), int0(nout == "" ? "" : nout / 1024), int0(wifi), dec(resent),
969
+ int0(rssi), int0(noise), int0(batt), int0(lowpower), int0(thermal), int0(cores > 0 ? cores : ""),
970
+ int0(nworking), int0(nwaiting)
971
+ for (r in isroot) if (r in there)
972
+ print r, (r in opened) ? 1 : 0, dec(cpu_agents == "" ? "" : tcpu[r]), int0(mem_agents == "" ? "" : tmem[r]), (r in works) ? 1 : 0
973
+ for (r in isrun) print "run", r, dec(cpuknown ? rcpu[r] : ""), int0(mem_agents == "" ? "" : rmem[r])
974
+ for (r in ended_) if (!(r in given)) print "run", r, dec(restcpu[r]), int0(restmem[r])
975
+ for (r in sofar) print "counted", r, sprintf("%.3f", sofar[r])
976
+ }'
977
+
978
+ # Delete the readings older than HOST_KEEP_DAYS, as of $1, their shares,
979
+ # their splits and their test runs' shares, the waits on the model that
980
+ # ended before then, and the test runs that started before then. And the
981
+ # marks files untouched for HOST_KEEP_DAYS days, by the clock, as their
982
+ # times are: an agent appends to its file as it works.
983
+ host_prune() {
984
+ case $1 in '' | *[!0-9]*) return 0 ;; esac
985
+ store "$HOST_DB" "delete from readings where at < $1 - $((HOST_KEEP_DAYS * 86400));
986
+ delete from shares where at < $1 - $((HOST_KEEP_DAYS * 86400));
987
+ delete from splits where at < $1 - $((HOST_KEEP_DAYS * 86400));
988
+ delete from model_waits where ended < $1 - $((HOST_KEEP_DAYS * 86400));
989
+ delete from run_shares where at < $1 - $((HOST_KEEP_DAYS * 86400));
990
+ delete from test_runs where started < $1 - $((HOST_KEEP_DAYS * 86400));" || true
991
+ [ ! -d "$HOST_MARKS" ] || find "$HOST_MARKS" -type f -mtime +"$HOST_KEEP_DAYS" -exec rm -f {} + 2>/dev/null || true
992
+ }
993
+
994
+ # The ids of the test runs in $2 onward, each as host_work lists one,
995
+ # "id:pid", whose pid is not in ps's list, $1, joined by commas.
996
+ host_gone() {
997
+ local ps=$1
998
+ shift
999
+ [ "$#" -gt 0 ] || return 0
1000
+ printf '%s\n' "$ps" | LC_ALL=C awk -v runs="$*" '
1001
+ $1 ~ /^[0-9]+$/ { there[$1] = 1 }
1002
+ END {
1003
+ n = split(runs, r, " ")
1004
+ for (i = 1; i <= n; i++) if (split(r[i], f, ":") == 2 && !(f[2] in there)) printf "%s%s", (c++ ? "," : ""), f[1]
1005
+ }'
1006
+ }
1007
+
1008
+ # The SQL of the lines the recorder's awk printed after the reading, $2, for
1009
+ # the reading at $1. HOST_SHARE_VALUES are the values of the terminals'
1010
+ # shares, each of whose process gives its work, from HOST_WORK, and
1011
+ # HOST_RUN_VALUES those of the test runs' shares. HOST_CUT_CPU gives each
1012
+ # run going the CPU counted of it, by its id, or NULL when none was, for a
1013
+ # run the recorder cuts short. Every value but a share's card, phase and
1014
+ # step is a number the awk printed. It sets them in this shell, not in a
1015
+ # subshell.
1016
+ HOST_SHARE_VALUES='' HOST_RUN_VALUES='' HOST_CUT_CPU=NULL
1017
+ host_shares() {
1018
+ local at=$1 a b c d e work card phase step cut=''
1019
+ HOST_SHARE_VALUES='' HOST_RUN_VALUES='' HOST_CUT_CPU=NULL
1020
+ while read -r a b c d e; do
1021
+ case $a in
1022
+ run)
1023
+ # The run, its CPU and its memory.
1024
+ case $b in '' | *[!0-9]*) continue ;; esac
1025
+ HOST_RUN_VALUES="$HOST_RUN_VALUES${HOST_RUN_VALUES:+, }($at, $b, $c, $d)"
1026
+ ;;
1027
+ counted)
1028
+ # The run, and the CPU counted of it so far.
1029
+ case $b in '' | *[!0-9]*) continue ;; esac
1030
+ cut="$cut when $b then $c"
1031
+ ;;
1032
+ '' | *[!0-9]*) ;;
1033
+ *)
1034
+ # A terminal's process, whether its agent is open, its CPU, its
1035
+ # memory, and whether its agent is working.
1036
+ work=
1037
+ case $HOST_WORK in *" $a="*) work=${HOST_WORK#*" $a="}; work=${work%% *} ;; esac
1038
+ IFS=, read -r card phase step <<< "$work"
1039
+ HOST_SHARE_VALUES="$HOST_SHARE_VALUES${HOST_SHARE_VALUES:+, }($at, $(sql_str "$card"), $(sql_str "$phase"), $(sql_str "$step"), $b, $c, $d, $e)"
1040
+ ;;
1041
+ esac
1042
+ done <<< "$2"
1043
+ [ -z "$cut" ] || HOST_CUT_CPU="case id$cut end"
1044
+ }
1045
+
1046
+ # One agent's split of a reading, from its marks file on stdin, a mark and
1047
+ # its time a line: of the seconds the reading covers, between the awk
1048
+ # variables from and to, those it was on the host and those it waited on the
1049
+ # model, to the millisecond, as "<host> <model>". It replays the file from
1050
+ # its start, so nothing is kept between readings:
1051
+ # pre raises the count of tools running: on the host while it is above 0
1052
+ # post lowers it, never below 0, and ends an ask: at 0, on the model
1053
+ # prompt on the model, with the count at 0
1054
+ # ask the rest, until the next post: the human is asked for permission
1055
+ # start, stop
1056
+ # the rest, with the count at 0
1057
+ # Before the first mark is the rest too. A time that goes back, as two hooks
1058
+ # writing at once can leave, counts as the time before it. A line that is
1059
+ # not a known mark and a time is skipped.
1060
+ #
1061
+ # After it, a line "<start> <end>" for each wait on the model that ended in
1062
+ # the reading's seconds, after from and by to, to the millisecond. A wait
1063
+ # starts as the agent comes to wait on the model, with a prompt or a post
1064
+ # that leaves no tool running, and ends as it stops, with a pre, an ask, a
1065
+ # start or a stop. Replayed from the file's start, a wait that began before
1066
+ # the reading keeps its real start, and one that spans readings is written
1067
+ # once, by the reading it ends in.
1068
+ HOST_MARKS_AWK='
1069
+ function part(a, b, lo, hi) {
1070
+ lo = a > from ? a : from; hi = b < to ? b : to
1071
+ if (hi <= lo || asking) return
1072
+ if (count > 0) host += hi - lo
1073
+ else if (onmodel) model += hi - lo
1074
+ }
1075
+ NF != 2 || $2 !~ /^[0-9]+(\.[0-9]+)?$/ { next }
1076
+ $1 == "start" || $1 == "prompt" || $1 == "pre" || $1 == "post" || $1 == "ask" || $1 == "stop" {
1077
+ t = $2 + 0
1078
+ if (seen && t < last) t = last
1079
+ if (seen) part(last, t)
1080
+ last = t; seen = 1
1081
+ if ($1 == "pre") count++
1082
+ else if ($1 == "post") { if (count > 0) count--; asking = 0; if (count == 0) onmodel = 1 }
1083
+ else if ($1 == "ask") asking = 1
1084
+ else { count = 0; asking = 0; onmodel = ($1 == "prompt") }
1085
+ if (count == 0 && onmodel && !asking) { if (!waiting) { waiting = 1; began = t } }
1086
+ else if (waiting) {
1087
+ waiting = 0
1088
+ if (t > from && t <= to) waits = waits sprintf("%.3f %.3f\n", began, t)
1089
+ }
1090
+ }
1091
+ END { if (seen) part(last, to); printf "%.3f %.3f\n%s", host + 0, model + 0, waits }'
1092
+
1093
+ # Set HOST_SPLIT_VALUES to the SQL values of the splits of the reading at
1094
+ # $1, which covers the $2 seconds before it: one for each terminal, of the
1095
+ # lines the recorder's awk printed after the reading, $3, whose agent is
1096
+ # open and has a card and a phase, from HOST_TERMS_NOW, and a marks file for
1097
+ # them. Its step is its share's, from HOST_WORK. Two terminals of one
1098
+ # card's phase share its marks, so the split is given once. And
1099
+ # HOST_WAIT_VALUES to those of the waits on the model that ended in the
1100
+ # reading, each with the work its agent's split names. It sets them in this
1101
+ # shell, not in a subshell.
1102
+ HOST_SPLIT_VALUES='' HOST_WAIT_VALUES=''
1103
+ host_splits() {
1104
+ local at=$1 secs=$2 terms=" $HOST_TERMS_NOW" a b rest info space card phase step work file out host model seen=' '
1105
+ local waits began ended
1106
+ HOST_SPLIT_VALUES='' HOST_WAIT_VALUES=''
1107
+ case $at in '' | *[!0-9]*) return 0 ;; esac
1108
+ case $secs in '' | 0 | *[!0-9]*) return 0 ;; esac
1109
+ while read -r a b rest; do
1110
+ case $a in '' | *[!0-9]*) continue ;; esac
1111
+ [ "$b" = 1 ] || continue
1112
+ case $terms in *" $a,"*) info=${terms#*" $a,"}; info=${info%% *} ;; *) continue ;; esac
1113
+ IFS=, read -r space card phase <<< "$info"
1114
+ valid_name "$space" && [[ $card =~ $CARD_RE ]] || continue
1115
+ case $phase in write-up | build) ;; *) continue ;; esac
1116
+ file=$HOST_MARKS/$space/$card.$phase
1117
+ [ -f "$file" ] || continue
1118
+ case $seen in *" $file "*) continue ;; esac
1119
+ seen="$seen$file "
1120
+ out=$(LC_ALL=C awk -v from=$((at - secs)) -v to="$at" "$HOST_MARKS_AWK" < "$file" 2>/dev/null) || continue
1121
+ read -r host model <<< "$out"
1122
+ case $host in '' | *[!0-9.]*) continue ;; esac
1123
+ case $model in '' | *[!0-9.]*) continue ;; esac
1124
+ work=
1125
+ case $HOST_WORK in *" $a="*) work=${HOST_WORK#*" $a="}; work=${work%% *} ;; esac
1126
+ step=${work##*,}
1127
+ HOST_SPLIT_VALUES="$HOST_SPLIT_VALUES${HOST_SPLIT_VALUES:+, }($at, $(sql_str "$card"), $(sql_str "$phase"), $(sql_str "$step"), $host, $model)"
1128
+ # The awk's lines after the split, a wait each.
1129
+ case $out in *$'\n'*) waits=${out#*$'\n'} ;; *) continue ;; esac
1130
+ while read -r began ended; do
1131
+ case $began in '' | *[!0-9.]*) continue ;; esac
1132
+ case $ended in '' | *[!0-9.]*) continue ;; esac
1133
+ HOST_WAIT_VALUES="$HOST_WAIT_VALUES${HOST_WAIT_VALUES:+, }($(sql_str "$card"), $(sql_str "$phase"), $(sql_str "$step"), $began, $ended)"
1134
+ done <<< "$waits"
1135
+ done <<< "$3"
1136
+ }
1137
+
1138
+ # The recorder: `host record`, which host_wake starts in its terminal. It
1139
+ # takes a reading every HOST_EVERY seconds while an agent is open, and exits
1140
+ # once none is, once the host folder has gone, or when hc kill hangs it up.
1141
+ host_record() {
1142
+ local ps at out row shares secs gone types readings=0
1143
+ [ "$#" -eq 0 ] || die "$HOST_USAGE"
1144
+ [ -d "$HOST_DIR" ] || return 0
1145
+ # hc may start it without the folders macOS keeps sysctl and ioreg in.
1146
+ PATH=$PATH:/usr/sbin:/sbin
1147
+ trap 'exit 0' HUP TERM
1148
+ have_sqlite && host_table || return 0
1149
+ host_prune "$(date +%s)"
1150
+ types=$(host_core_types) || types=
1151
+ while :; do
1152
+ [ -d "$HOST_DIR" ] || return 0
1153
+ # exec: ps is the recorder's own child, as every tool it runs is. RSS is
1154
+ # in KB.
1155
+ ps=$(exec ps -A -o pid=,ppid=,rss=) || return 0
1156
+ at=$(date +%s) || return 0
1157
+ case $at in '' | *[!0-9]*) return 0 ;; esac
1158
+ host_agents "$ps" "$at"
1159
+ [ "$HOST_AGENTS" -gt 0 ] || return 0
1160
+ # The shell's own CPU, and that of every program it has run: a builtin,
1161
+ # so it is run here and not in a subshell, which would count only its own.
1162
+ times > "$HOST_DIR/self" 2>/dev/null || return 0
1163
+ out=$(host_sample "$ps" | LC_ALL=C awk -v pid="$$" -v at="$at" -v agents="$HOST_AGENTS" -v types="$types" \
1164
+ -v procs="$HOST_PROCS" -v roots="$HOST_ROOTS" -v working="$HOST_WORKING" \
1165
+ -v openruns="$HOST_OPEN_RUNS" -v endruns="$HOST_ENDED_RUNS" \
1166
+ -v gap="$HOST_GAP" -v prevfile="$HOST_DIR/sample" \
1167
+ -v selffile="$HOST_DIR/self" -v outfile="$HOST_DIR/sample.next" "$HOST_AWK" 2>/dev/null) || out=
1168
+ mv -f "$HOST_DIR/sample.next" "$HOST_DIR/sample" 2>/dev/null || true
1169
+ # nettop's counts first, then the reading, if there is one, then a line
1170
+ # for each terminal's share of it, and each test run's. Each open agent
1171
+ # with marks of its time gets its split of the reading too, and its
1172
+ # waits on the model that ended in it.
1173
+ HOST_NET=${out%%$'\n'*}
1174
+ case $out in *$'\n'*) row=${out#*$'\n'} ;; *) row= ;; esac
1175
+ shares=
1176
+ case $row in *$'\n'*) shares=${row#*$'\n'}; row=${row%%$'\n'*} ;; esac
1177
+ if [ -n "$row" ]; then
1178
+ host_shares "$at" "$shares"
1179
+ # The reading's secs, its second value, is the window of its splits.
1180
+ secs=${row#*, }
1181
+ host_splits "$at" "${secs%%,*}" "$shares"
1182
+ # A test run with no end whose process was not in this sample's ps has
1183
+ # gone without finishing its row, as after kill -9: it ended by now,
1184
+ # was cut short, and its CPU is what was counted of it. One that
1185
+ # started in the last seconds may have started after ps was read, so
1186
+ # it waits for the next reading.
1187
+ # shellcheck disable=SC2086
1188
+ gone=$(host_gone "$ps" $HOST_OPEN_RUNS) || gone=
1189
+ if store "$HOST_DB" "begin; insert into readings ($HOST_COLUMNS) values ($row);
1190
+ ${HOST_SHARE_VALUES:+insert into shares (at, card, phase, step, open, cpu, mem_mb, working) values $HOST_SHARE_VALUES;}
1191
+ ${HOST_RUN_VALUES:+insert into run_shares (at, run, cpu, mem_mb) values $HOST_RUN_VALUES;}
1192
+ ${HOST_SPLIT_VALUES:+insert into splits (at, card, phase, step, host_secs, model_secs) values $HOST_SPLIT_VALUES;}
1193
+ ${HOST_WAIT_VALUES:+insert into model_waits (card, phase, step, started, ended) values $HOST_WAIT_VALUES;}
1194
+ ${gone:+update test_runs set ended = $at, secs = $at - started, cut = 1, cpu_secs = $HOST_CUT_CPU
1195
+ where id in ($gone) and ended is null and started < $at - 2;} commit;"; then
1196
+ readings=$((readings + 1))
1197
+ [ $((readings % HOST_PRUNE_EVERY)) != 0 ] || host_prune "$at"
1198
+ fi
1199
+ fi
1200
+ sleep "$HOST_EVERY"
1201
+ done
1202
+ }
1203
+
1204
+ # --- the report -------------------------------------------------------------
1205
+
1206
+ # Set DAY_START and DAY_END to the first second of the local day $1, a date
1207
+ # like 2026-11-29, and the first of the day after, or fail when $1 is not a
1208
+ # date. SQLite rolls a date like 2026-02-30 over into March, so a date that
1209
+ # does not come back as itself is not one.
1210
+ DAY_START='' DAY_END=''
1211
+ host_day() {
1212
+ local row ok
1213
+ [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || return 1
1214
+ row=$(store ':memory:' "select date('$1') = '$1', strftime('%s', '$1', 'utc'), strftime('%s', '$1', '+1 day', 'utc');") || return 1
1215
+ IFS='|' read -r ok DAY_START DAY_END <<< "$row"
1216
+ [ "$ok" = 1 ] && [ -n "$DAY_START" ] && [ -n "$DAY_END" ]
1217
+ }
1218
+
1219
+ # How the CPU, memory and disk were, over a period: how much of the time it
1220
+ # was recorded, and how much of that each was at its limit. Time with no
1221
+ # reading is shown as missing, never as idle. It ends with whether the
1222
+ # network may be the cause of slow waits on the model, and the verdict on
1223
+ # the host: what to upgrade first, if anything (host_verdict_sql).
1224
+ host_report() {
1225
+ local period=${1:-7d} now start end n first last row works runs working shared splits power slower waits
1226
+ [ "$#" -le 1 ] || die "$HOST_USAGE"
1227
+ now=$(date +%s)
1228
+ case $period in
1229
+ *d | *h)
1230
+ n=${period%?}
1231
+ case $n in '' | 0* | *[!0-9]*) die "'$period' is not a period: $HOST_PERIODS." ;; esac
1232
+ [ "${#n}" -le 6 ] || die "'$period' is not a period: $HOST_PERIODS."
1233
+ if [ "${period#"$n"}" = d ]; then start=$((now - n * 86400)); else start=$((now - n * 3600)); fi
1234
+ end=$now
1235
+ ;;
1236
+ *..*)
1237
+ first=${period%%..*} last=${period#*..}
1238
+ host_day "$first" || die "'$first' is not a date like 2026-11-29: $HOST_PERIODS."
1239
+ start=$DAY_START
1240
+ host_day "$last" || die "'$last' is not a date like 2026-11-29: $HOST_PERIODS."
1241
+ end=$DAY_END
1242
+ [ "$start" -lt "$end" ] || die "'$period' ends before it starts: give the earlier day first."
1243
+ ;;
1244
+ *)
1245
+ host_day "$period" || die "'$period' is not a period: $HOST_PERIODS."
1246
+ start=$DAY_START end=$DAY_END
1247
+ ;;
1248
+ esac
1249
+ [ "$start" -lt "$now" ] || die "'$period' has not started yet, so it has no readings."
1250
+ [ "$end" -le "$now" ] || end=$now
1251
+ if [ ! -d "$HOST_DIR" ]; then
1252
+ say "Recording is off, so there are no readings of this machine. Turn it on with: ocnus host on"
1253
+ return 0
1254
+ fi
1255
+ have_sqlite || die "$SQLITE is not installed, and the readings are kept with it."
1256
+ [ -f "$HOST_DB" ] && row=$(store "$HOST_DB" "select count(*) from readings where at > $start and at < $end + $HOST_GAP and at - secs < $end;") ||
1257
+ row=0
1258
+ if [ "${row:-0}" = 0 ]; then
1259
+ store ':memory:' "select 'No readings of this machine from ' || strftime('%Y-%m-%d %H:%M', $start, 'unixepoch', 'localtime')
1260
+ || ' to ' || strftime('%Y-%m-%d %H:%M', $end, 'unixepoch', 'localtime') || ' ($period): all ' || $(sql_took "($end - $start)")
1261
+ || ' of it is missing.';"
1262
+ say "Recording is on, and takes a reading every $HOST_EVERY seconds while an ocnus agent is open."
1263
+ return 0
1264
+ fi
1265
+ # A store the recorder has not opened since the shares, the cores, the
1266
+ # test runs and their shares, the agents working, the splits, the power
1267
+ # state, the fingerprints of the test runs' commands, and the waits on the
1268
+ # model came has none of them: one digit each, 1 for what it has, and for
1269
+ # the power state how many of its 3 columns it has. The report only reads
1270
+ # the store, so it never adds them, and leaves out what is missing.
1271
+ row=$(store "$HOST_DB" "select (select count(*) from pragma_table_info('readings') where name = 'cores')
1272
+ || (select count(*) from sqlite_master where type = 'table' and name = 'shares')
1273
+ || (select count(*) from sqlite_master where type = 'table' and name = 'test_runs')
1274
+ || (select count(*) from sqlite_master where type = 'table' and name = 'run_shares')
1275
+ || (select count(*) from pragma_table_info('readings') where name = 'working')
1276
+ || (select count(*) from pragma_table_info('shares') where name = 'working')
1277
+ || (select count(*) from sqlite_master where type = 'table' and name = 'splits')
1278
+ || (select count(*) from pragma_table_info('readings') where name in ('on_battery', 'low_power', 'thermal'))
1279
+ || (select count(*) from pragma_table_info('test_runs') where name = 'cmd')
1280
+ || (select count(*) from sqlite_master where type = 'table' and name = 'model_waits');") || row=
1281
+ works=0 runs=0 working=0 shared=0 splits=0 power=0 slower=0 waits=0
1282
+ case $row in ?1????????) works=1 ;; esac
1283
+ case $row in ??11??????) runs=1 ;; esac
1284
+ case $row in ????1?????) working=1 ;; esac
1285
+ case $row in ?1???1????) shared=1 ;; esac
1286
+ case $row in ?1????1???) splits=1 ;; esac
1287
+ case $row in ???????3??) power=1 ;; esac
1288
+ case $row in ????1???1?) slower=1 ;; esac
1289
+ case $row in ?????????1) waits=1 ;; esac
1290
+ case $row in 111???????) row=1 ;; *) row=0 ;; esac
1291
+ store "$HOST_DB" "$(host_report_sql "$start" "$end" "$period" "$row")" ||
1292
+ die "could not read $HOST_DB"
1293
+ store "$HOST_DB" "$(host_working_sql "$start" "$end" "$working" "$slower")" ||
1294
+ die "could not read $HOST_DB"
1295
+ store "$HOST_DB" "$(host_peaks_sql "$start" "$end" "$works" "$runs" "$shared")" ||
1296
+ die "could not read $HOST_DB"
1297
+ if [ "$row" = 1 ]; then
1298
+ store "$HOST_DB" "$(host_ranks_sql "$start" "$end")" || die "could not read $HOST_DB"
1299
+ else
1300
+ say ''
1301
+ say 'No step, phase or test run was recorded in this period.'
1302
+ fi
1303
+ store "$HOST_DB" "$(host_split_sql "$start" "$end" "$works" "$splits")" || die "could not read $HOST_DB"
1304
+ store "$HOST_DB" "$(host_verdict_sql "$start" "$end" "$splits" "$power" "$waits")" || die "could not read $HOST_DB"
1305
+ }
1306
+
1307
+ # The report's query, for the period from $1 to $2, named $3. A reading
1308
+ # covers the secs before its at, so each one counts for the part of that
1309
+ # which falls in the period, and in each day. With $4 as 1, the store has
1310
+ # test runs and the readings their cores, and what watching the test runs
1311
+ # that started in the period used counts as recording's own CPU, as a share
1312
+ # of the cores the readings counted over the recorded time.
1313
+ host_report_sql() {
1314
+ local s=$1 e=$2 name=$3 watch=0
1315
+ [ "${4:-0}" != 1 ] ||
1316
+ watch="coalesce(100.0 * (select sum(watch_secs) from test_runs where started >= $s and started < $e)
1317
+ / (select nullif(max(cores), 0) from readings where at > $s and at < $e + $HOST_GAP and at - secs < $e), 0)"
1318
+ cat <<EOF
1319
+ with recursive
1320
+ days(day, ds, de) as (
1321
+ select date($s, 'unixepoch', 'localtime'),
1322
+ max($s, cast(strftime('%s', date($s, 'unixepoch', 'localtime'), 'utc') as integer)),
1323
+ min($e, cast(strftime('%s', date($s, 'unixepoch', 'localtime'), '+1 day', 'utc') as integer))
1324
+ union all
1325
+ select date(day, '+1 day'),
1326
+ cast(strftime('%s', date(day, '+1 day'), 'utc') as integer),
1327
+ min($e, cast(strftime('%s', date(day, '+2 days'), 'utc') as integer))
1328
+ from days where de < $e),
1329
+ parts(day, len, d, cpu_busy, mem_pressure, disk_free_pct, cpu_self) as (
1330
+ select days.day, days.de - days.ds,
1331
+ max(0, min(at, days.de) - max(at - secs, days.ds)), cpu_busy, mem_pressure, disk_free_pct, cpu_self
1332
+ from days left join readings on at > days.ds and at < days.de + $HOST_GAP and at - secs < days.de),
1333
+ byday(day, len, rec, cpu, mem, disk, self_time, self_d) as (
1334
+ select day, len, cast(coalesce(sum(d), 0) as integer),
1335
+ cast(coalesce(sum(case when cpu_busy >= 90 then d end), 0) as integer),
1336
+ cast(coalesce(sum(case when mem_pressure >= 2 then d end), 0) as integer),
1337
+ cast(coalesce(sum(case when disk_free_pct < 10 then d end), 0) as integer),
1338
+ coalesce(sum(cpu_self * d), 0), coalesce(sum(case when cpu_self is not null then d end), 0)
1339
+ from parts group by day),
1340
+ total(len, rec, cpu, mem, disk, self) as (
1341
+ select $e - $s, sum(rec), sum(cpu), sum(mem), sum(disk),
1342
+ case when sum(self_d) > 0 then (sum(self_time) + $watch) / sum(self_d) end
1343
+ from byday),
1344
+ shown(len, rec, missing, cpu, mem, disk, self) as (
1345
+ select len, rec, max(0, len - rec), cpu, mem, disk, self from total),
1346
+ lines(n, k, line) as (
1347
+ select 1, '', 'The host from ' || strftime('%Y-%m-%d %H:%M', $s, 'unixepoch', 'localtime') || ' to '
1348
+ || strftime('%Y-%m-%d %H:%M', $e, 'unixepoch', 'localtime') || ' ($name)' from shown
1349
+ union all select 2, '', ' recorded ' || $(sql_took rec) || ' of ' || $(sql_took len) from shown
1350
+ union all select 3, '', ' missing ' || $(sql_took missing) || ', shown as missing, not idle: no reading was taken then' from shown
1351
+ union all select 4, '', ' CPU at its limit ' || $(sql_took cpu) || ', ' || printf('%.1f%%', 100.0 * cpu / rec)
1352
+ || ' of the recorded time (at least 90% busy across all cores)' from shown
1353
+ union all select 5, '', ' memory at its limit ' || $(sql_took mem) || ', ' || printf('%.1f%%', 100.0 * mem / rec)
1354
+ || ' of the recorded time (memory pressure at warning or critical)' from shown
1355
+ union all select 6, '', ' disk at its limit ' || $(sql_took disk) || ', ' || printf('%.1f%%', 100.0 * disk / rec)
1356
+ || ' of the recorded time (under 10% free on the disk holding the home folder)' from shown
1357
+ union all select 7, '', ' recording ' || case when self is null then 'its own use of the CPU was not read'
1358
+ else 'used ' || printf('%.2f%%', self) || ' of the CPU, all cores together, on average' end from shown
1359
+ union all select 8, '', '' union all select 9, '', 'By day:'
1360
+ union all select 10, day, ' ' || day || ' recorded ' || $(sql_took rec) || ', missing ' || $(sql_took "max(0, len - rec)")
1361
+ || case when rec > 0 then '; at its limit: CPU ' || printf('%.1f%%', 100.0 * cpu / rec)
1362
+ || ', memory ' || printf('%.1f%%', 100.0 * mem / rec) || ', disk ' || printf('%.1f%%', 100.0 * disk / rec)
1363
+ else '' end
1364
+ from byday)
1365
+ select line from lines order by n, k;
1366
+ EOF
1367
+ }
1368
+
1369
+ # The agents working at once, from $1 to $2: for each number of agents
1370
+ # working that the readings counted, from none up, how long that many were
1371
+ # working, and how much of that time the CPU or the memory was at its limit,
1372
+ # as the report counts it. Each reading counts for the part of it in the
1373
+ # period. A reading from before the agents working were counted has no
1374
+ # count, and nor has any when $3 is not 1, as the store has no column for
1375
+ # them yet: it is left out, never counted as none working, and its time is
1376
+ # on a line of its own. Last, the fewest working at which the CPU or memory
1377
+ # was at its limit for at least a quarter of the time is named as the number
1378
+ # from which the host was the limit; or it says there is no such number, or
1379
+ # that no reading counted the agents working.
1380
+ #
1381
+ # Under each number from 2 up, with $4 as 1, which says the store has the
1382
+ # fingerprints of the test runs' commands, comes how much slower test runs
1383
+ # were than with one working. A test run that started in the period counts
1384
+ # at the number working that covers most of its time, over the readings
1385
+ # that counted them, and at the larger number on a tie. A run that was cut
1386
+ # short, is still going, has no fingerprint, as one from before they were
1387
+ # kept, or overlaps no reading with a count, is left out. A command is a
1388
+ # repo and a fingerprint, so only runs of the same command in the same repo
1389
+ # are set against each other, and a command counts at a number when it ran
1390
+ # at least 3 times with that many working and 3 times with one. Its ratio is
1391
+ # its runs' median time with that many working over their median time with
1392
+ # one, and the figure is the median of the commands' ratios, so one odd run,
1393
+ # such as one that failed early, does not move it. With no such command, it
1394
+ # says it cannot tell yet.
1395
+ host_working_sql() {
1396
+ local s=$1 e=$2 working=working slower=0 runs='select null, null, null, null, null where 0' counted=null
1397
+ [ "${3:-0}" = 1 ] || working=null
1398
+ if [ "$working" = working ] && [ "${4:-0}" = 1 ]; then
1399
+ slower=1 counted=g.working
1400
+ runs="select id, repo, cmd, started, secs from test_runs
1401
+ where started >= $s and started < $e and ended is not null and cut = 0 and cmd is not null and secs is not null"
1402
+ fi
1403
+ cat <<EOF
1404
+ with
1405
+ parts(n, d, lim) as (
1406
+ select $working, max(0, min(at, $e) - max(at - secs, $s)), coalesce(cpu_busy >= 90 or mem_pressure >= 2, 0)
1407
+ from readings where at > $s and at < $e + $HOST_GAP and at - secs < $e),
1408
+ counts(n, len, lim) as (
1409
+ select n, sum(d), sum(case when lim then d else 0 end) from parts where n is not null group by n),
1410
+ uncounted(len) as (select coalesce(sum(d), 0) from parts where n is null),
1411
+ fewest(n) as (select min(n) from counts where len > 0 and 4 * lim >= len),
1412
+ runs(id, repo, cmd, started, secs) as ($runs),
1413
+ -- A cross join keeps the runs outside, so that each one looks up only its
1414
+ -- own readings by their at, never every reading for each run.
1415
+ over(id, n, d) as (
1416
+ select r.id, $counted, sum(max(0, min(g.at, r.started + r.secs) - max(g.at - g.secs, r.started)))
1417
+ from runs r cross join readings g
1418
+ on g.at > r.started and g.at < r.started + r.secs + $HOST_GAP and g.at - g.secs < r.started + r.secs
1419
+ where $counted is not null group by r.id, $counted),
1420
+ at_n(id, n) as (
1421
+ select id, n from (select id, n, row_number() over (partition by id order by d desc, n desc) k from over) where k = 1),
1422
+ timed(repo, cmd, n, secs, i, c) as (
1423
+ select r.repo, r.cmd, a.n, r.secs, row_number() over (partition by r.repo, r.cmd, a.n order by r.secs),
1424
+ count(*) over (partition by r.repo, r.cmd, a.n)
1425
+ from runs r join at_n a on a.id = r.id),
1426
+ medians(repo, cmd, n, runs, secs) as (
1427
+ select repo, cmd, n, max(c), avg(secs) from timed where i in ((c + 1) / 2, (c + 2) / 2) group by repo, cmd, n),
1428
+ ratios(n, ratio, runs, base, i, c) as (
1429
+ select m.n, m.secs / b.secs, m.runs, b.runs, row_number() over (partition by m.n order by m.secs / b.secs),
1430
+ count(*) over (partition by m.n)
1431
+ from medians m join medians b on b.repo = m.repo and b.cmd = m.cmd and b.n = 1
1432
+ where m.n >= 2 and m.runs >= 3 and b.runs >= 3 and b.secs > 0),
1433
+ slower(n, ratio) as (select n, avg(ratio) from ratios where i in ((c + 1) / 2, (c + 2) / 2) group by n),
1434
+ rested(n, cmds, runs, base) as (select n, count(*), sum(runs), sum(base) from ratios group by n),
1435
+ lines(part, n, o, line) as (
1436
+ select 0, 0, 0, ''
1437
+ union all select 0, 1, 0, 'Agents working at once:'
1438
+ union all
1439
+ select 1, n, 0, ' ' || printf('%-11s', n || ' working') || ' ' || $(sql_took len) || ', CPU or memory at its limit '
1440
+ || $(sql_took lim) || ', ' || printf('%.1f%%', 100.0 * lim / nullif(len, 0)) || ' of it'
1441
+ from counts
1442
+ union all
1443
+ select 1, c.n, 1, ' test runs' || case when s.ratio is null
1444
+ then ': cannot tell yet, as no command ran at least 3 times with ' || c.n || ' working and 3 times with 1'
1445
+ else ' ' || case when s.ratio >= 1 then printf('%.0f%% slower', 100.0 * (s.ratio - 1))
1446
+ else printf('%.0f%% faster', 100.0 * (1 - s.ratio)) end
1447
+ || ' than with 1 working, from ' || r.runs || ' runs of ' || r.cmds || case when r.cmds = 1 then ' command' else ' commands' end
1448
+ || ' against ' || r.base || ' with 1 working' end
1449
+ from counts c left join slower s on s.n = c.n left join rested r on r.n = c.n
1450
+ where c.n >= 2 and $slower
1451
+ union all
1452
+ select 2, 0, 0, ' not counted ' || $(sql_took len) || ', by readings from before the agents working were counted'
1453
+ from uncounted where len > 0
1454
+ union all
1455
+ select 3, 0, 0, case
1456
+ when not exists (select 1 from counts) then ' No reading in this period counted the agents working.'
1457
+ when n is null then ' The host was not the limit at any number of working agents in this period: at each, the CPU or memory was at its limit for under a quarter of the time.'
1458
+ else ' The host was the limit from ' || n || ' working ' || case when n = 1 then 'agent' else 'agents' end
1459
+ || ': the fewest at which the CPU or memory was at its limit for at least a quarter of the time.' end
1460
+ from fewest)
1461
+ select line from lines order by part, n, o;
1462
+ EOF
1463
+ }
1464
+
1465
+ # The longest stretches from $1 to $2 when the CPU or the memory was at its
1466
+ # limit, as the report counts it, five at most, longest first. A stretch is
1467
+ # readings in a row at the limit, each starting where the one before ended,
1468
+ # and each counts for the part of it in the period, as the report counts a
1469
+ # reading. Each says when it started, how long it lasted and which of the
1470
+ # two was at its limit, then the work going in it: each card's step, or its
1471
+ # phase when its card is in none, from the shares when $3 is 1, then each
1472
+ # test run, from their shares when $4 is 1. Each has its share of all cores
1473
+ # over the stretch, its share in each reading counted for that reading's
1474
+ # part, and the most memory it held in one reading. Each card also has how
1475
+ # much of the stretch its agent was working: the parts of the readings in
1476
+ # which a share of its was working, over the stretch's length. With $5 not 1,
1477
+ # the shares have no column for it, and with no share that says, as from
1478
+ # before the agents working were told apart, it says it was not read. A
1479
+ # share that names no card is left out. With no stretch, it says the host was
1480
+ # never at its limit.
1481
+ host_peaks_sql() {
1482
+ local s=$1 e=$2 shares runs
1483
+ shares='select at, card, phase, step, cpu, mem_mb, working from shares'
1484
+ [ "${5:-0}" = 1 ] || shares='select at, card, phase, step, cpu, mem_mb, null from shares'
1485
+ [ "${3:-0}" = 1 ] || shares='select null, null, null, null, null, null, null where 0'
1486
+ runs='select r.at, r.run, t.card, t.repo, t.started, r.cpu, r.mem_mb from run_shares r join test_runs t on t.id = r.run'
1487
+ [ "${4:-0}" = 1 ] || runs='select null, null, null, null, null, null, null where 0'
1488
+ cat <<EOF
1489
+ with
1490
+ lim(at, start, d, cpu, mem, new) as (
1491
+ select at, max(at - secs, $s), max(0, min(at, $e) - max(at - secs, $s)),
1492
+ coalesce(cpu_busy >= 90, 0), coalesce(mem_pressure >= 2, 0),
1493
+ case when lag(at) over (order by at) = at - secs then 0 else 1 end
1494
+ from readings
1495
+ where at > $s and at < $e + $HOST_GAP and at - secs < $e and (cpu_busy >= 90 or mem_pressure >= 2)),
1496
+ grouped(at, start, d, cpu, mem, n) as (
1497
+ select at, start, d, cpu, mem, sum(new) over (order by at rows between unbounded preceding and current row) from lim),
1498
+ stretches(n, start, len, cpu, mem) as (
1499
+ select n, min(start), sum(d), max(cpu), max(mem) from grouped group by n),
1500
+ ranked(k, n, start, len, cpu, mem) as (
1501
+ select row_number() over (order by len desc, start), n, start, len, cpu, mem from stretches),
1502
+ top(k, n, start, len, cpu, mem) as (select k, n, start, len, cpu, mem from ranked where k <= 5),
1503
+ parts(k, len, at, d) as (select t.k, t.len, g.at, g.d from top t join grouped g on g.n = t.n),
1504
+ sh(at, card, phase, step, cpu, mem, working) as ($shares),
1505
+ rs(at, run, card, repo, started, cpu, mem) as ($runs),
1506
+ cards(k, len, at, d, name, cpu, mem, working) as (
1507
+ select p.k, p.len, p.at, p.d, sh.card || ' ' || coalesce(sh.step || ' step', sh.phase || ' phase'), sum(sh.cpu), sum(sh.mem),
1508
+ max(sh.working)
1509
+ from parts p join sh on sh.at = p.at
1510
+ where sh.card is not null and coalesce(sh.step, sh.phase) is not null
1511
+ group by p.k, p.at, sh.card, sh.step, sh.phase),
1512
+ work(k, part, name, cpu, mem, working) as (
1513
+ select k, 1, name, sum(1.0 * cpu * d) / len, max(mem),
1514
+ case when count(working) > 0 then 100.0 * sum(case when working = 1 then d else 0 end) / len end
1515
+ from cards group by k, name
1516
+ union all
1517
+ select p.k, 2, rs.card || ' ' || rs.repo || ' test run ' || strftime('%Y-%m-%d %H:%M', rs.started, 'unixepoch', 'localtime'),
1518
+ sum(1.0 * rs.cpu * p.d) / p.len, max(rs.mem), null
1519
+ from parts p join rs on rs.at = p.at group by p.k, rs.run),
1520
+ lines(k, part, o, line) as (
1521
+ select -1, 0, 0, ''
1522
+ union all select 0, 0, 0, 'Longest stretches with CPU or memory at its limit:' where exists (select 1 from top)
1523
+ union all select 0, 0, 0, 'The host was never at its limit for CPU or memory in this period.' where not exists (select 1 from top)
1524
+ union all
1525
+ select k, 0, 0, ' ' || strftime('%Y-%m-%d %H:%M:%S', start, 'unixepoch', 'localtime') || ' for ' || $(sql_took len) || ', '
1526
+ || case when cpu and mem then 'CPU and memory at their limit' when cpu then 'CPU at its limit' else 'memory at its limit' end
1527
+ from top
1528
+ union all
1529
+ select k, part, row_number() over (partition by k, part order by cpu desc, name),
1530
+ ' ' || printf('%-44s', name) || ' ' || case when cpu is null then 'CPU not read' else 'CPU ' || printf('%.1f%%', cpu) end
1531
+ || ', ' || case when mem is null then 'memory not read' else 'memory ' || mem || ' MB' end
1532
+ || case when part = 2 then '' when working is null then ', working not read'
1533
+ else ', working ' || printf('%.0f%%', working) || ' of it' end
1534
+ from work
1535
+ union all
1536
+ select k, 3, 0, ' no card or test run was going' from top t where not exists (select 1 from work w where w.k = t.k))
1537
+ select line from lines order by k, part, o;
1538
+ EOF
1539
+ }
1540
+
1541
+ # The steps and the phases that used the most CPU time, and that held the
1542
+ # most memory at once, from $1 to $2: ten of each, each one card's own. Each
1543
+ # counts what its shares say for the part of their reading in the period,
1544
+ # as the report counts a reading: its CPU time is its share of all cores
1545
+ # times that part times the cores, its memory the most its shares held in one
1546
+ # reading, and its time those parts together.
1547
+ #
1548
+ # Then the ten test runs that started in the period and used the most CPU
1549
+ # time, and the ten that held the most memory at once, each named by its
1550
+ # card, its repo and when it started, with how long it ran. A run the
1551
+ # recorder cut short says so, and has as its CPU what the recorder counted
1552
+ # of it: with none counted, it is only ranked by its memory. One still going
1553
+ # says that in place of its time. With no step, phase or test run in the
1554
+ # period, it says so in place of the lists.
1555
+ host_ranks_sql() {
1556
+ local s=$1 e=$2 name ran
1557
+ name="' ' || printf('%-32s', card || ' ' || repo || ' ' || strftime('%Y-%m-%d %H:%M', started, 'unixepoch', 'localtime'))"
1558
+ ran="case when ended is null then ', still going'
1559
+ else ', ran ' || $(sql_took "cast(round(secs) as integer)") || case when cut = 1 then ', cut short' else '' end end"
1560
+ cat <<EOF
1561
+ with
1562
+ runs(card, repo, started, ended, secs, cpu, mem, cut) as (
1563
+ select card, repo, started, ended, secs, cpu_secs, mem_mb, cut from test_runs where started >= $s and started < $e),
1564
+ parts(at, d, cores) as (
1565
+ select at, max(0, min(at, $e) - max(at - secs, $s)), cores from readings
1566
+ where at > $s and at < $e + $HOST_GAP and at - secs < $e),
1567
+ owned(kind, card, what, at, d, cpu, mem) as (
1568
+ select 'step', s.card, s.step, p.at, p.d, s.cpu * p.d * p.cores / 100.0, s.mem_mb
1569
+ from parts p join shares s on s.at = p.at where s.card is not null and s.step is not null
1570
+ union all
1571
+ select 'phase', s.card, s.phase, p.at, p.d, s.cpu * p.d * p.cores / 100.0, s.mem_mb
1572
+ from parts p join shares s on s.at = p.at where s.card is not null and s.phase is not null),
1573
+ once(kind, card, what, d, cpu, mem) as (
1574
+ select kind, card, what, max(d), sum(cpu), sum(mem) from owned group by kind, card, what, at),
1575
+ totals(kind, card, what, ran, cpu, mem) as (
1576
+ select kind, card, what, sum(d), cast(round(sum(cpu)) as integer), max(mem) from once group by kind, card, what),
1577
+ ranked(n, k, line) as (
1578
+ select case kind when 'step' then 1 else 3 end, row_number() over (partition by kind order by cpu desc, card, what),
1579
+ ' ' || printf('%-24s', card || ' ' || what || ' ' || kind) || ' CPU time ' || $(sql_took cpu) || ', ran ' || $(sql_took ran)
1580
+ from totals where cpu is not null
1581
+ union all
1582
+ select case kind when 'step' then 2 else 4 end, row_number() over (partition by kind order by mem desc, card, what),
1583
+ ' ' || printf('%-24s', card || ' ' || what || ' ' || kind) || ' memory ' || mem || ' MB, ran ' || $(sql_took ran)
1584
+ from totals where mem is not null
1585
+ union all
1586
+ select 5, row_number() over (order by cpu desc, started, card, repo),
1587
+ $name || ' CPU time ' || $(sql_took "cast(round(cpu) as integer)") || $ran
1588
+ from runs where cpu is not null
1589
+ union all
1590
+ select 6, row_number() over (order by mem desc, started, card, repo),
1591
+ $name || ' memory ' || mem || ' MB' || $ran
1592
+ from runs where mem is not null),
1593
+ heads(n, head) as (values (1, 'Steps that used the most CPU time:'), (2, 'Steps that held the most memory at once:'),
1594
+ (3, 'Phases that used the most CPU time:'), (4, 'Phases that held the most memory at once:'),
1595
+ (5, 'Test runs that used the most CPU time:'), (6, 'Test runs that held the most memory at once:')),
1596
+ found(yes) as (select exists (select 1 from totals) or exists (select 1 from runs)),
1597
+ lines(n, k, line) as (
1598
+ select 0, 0, ''
1599
+ union all select 0, 1, 'No step, phase or test run was recorded in this period.' from found where not yes
1600
+ union all select n, 0, head from heads, found where yes
1601
+ union all select n, 1, ' none recorded' from heads h, found
1602
+ where yes and not exists (select 1 from ranked r where r.n = h.n)
1603
+ union all select n, k, line from ranked where k <= 10)
1604
+ select line from lines order by n, k;
1605
+ EOF
1606
+ }
1607
+
1608
+ # Where the steps' time went from $1 to $2, from the shares when $3 is 1 and
1609
+ # the splits when $4 is 1: first the agents' time in all on the host,
1610
+ # waiting on the model and the rest, over the splits, then the same for the
1611
+ # 10 steps open longest with a split, each one card's own, longest first.
1612
+ # Each split counts for the part of its reading in the period, as the report
1613
+ # counts a reading: its seconds on the host and on the model in that
1614
+ # proportion, and the rest is that part less the two. Each line says how
1615
+ # long it was open, and its three parts, to the second, which add up to
1616
+ # that. Then how many steps were open in the period with no split. With no
1617
+ # split, it says no step was split, and why.
1618
+ HOST_NO_SPLIT="an agent's time is split only when it starts in Claude Code while recording is on"
1619
+ host_split_sql() {
1620
+ local s=$1 e=$2 shares splits line why
1621
+ why=$(sql_str "$HOST_NO_SPLIT")
1622
+ shares='select at, card, step, open from shares'
1623
+ [ "${3:-0}" = 1 ] || shares='select null, null, null, null where 0'
1624
+ splits='select at, card, step, host_secs, model_secs from splits'
1625
+ [ "${4:-0}" = 1 ] || splits='select null, null, null, null, null where 0'
1626
+ line="' ' || printf('%-24s', name) || ' open ' || $(sql_took d) || ': on the host ' || $(sql_took h)
1627
+ || ', waiting on the model ' || $(sql_took m) || ', the rest ' || $(sql_took r)"
1628
+ cat <<EOF
1629
+ with
1630
+ parts(at, secs, d) as (
1631
+ select at, secs, max(0, min(at, $e) - max(at - secs, $s)) from readings
1632
+ where at > $s and at < $e + $HOST_GAP and at - secs < $e and secs > 0),
1633
+ sh(at, card, step, open) as ($shares),
1634
+ x(at, card, step, host, model) as ($splits),
1635
+ sp(card, step, d, host, model) as (
1636
+ select x.card, x.step, p.d, 1.0 * x.host * p.d / p.secs, 1.0 * x.model * p.d / p.secs
1637
+ from parts p join x on x.at = p.at),
1638
+ steps(card, step, d, host, model) as (
1639
+ select card, step, sum(d), sum(host), sum(model) from sp
1640
+ where card is not null and step is not null group by card, step),
1641
+ shown(k, name, d, host, model) as (
1642
+ select 0, 'all agents', d, host, model from (select count(*) n, sum(d) d, sum(host) host, sum(model) model from sp) where n > 0
1643
+ union all
1644
+ select row_number() over (order by d desc, card, step), card || ' ' || step || ' step', d, host, model from steps),
1645
+ timed(k, name, d, h, m, r) as (
1646
+ select k, name, d, cast(round(host) as integer),
1647
+ cast(round(host + model) as integer) - cast(round(host) as integer),
1648
+ max(0, d - cast(round(host + model) as integer))
1649
+ from shown where k <= 10),
1650
+ unsplit(n) as (
1651
+ select count(*) from (
1652
+ select distinct sh.card, sh.step from parts p join sh on sh.at = p.at
1653
+ where sh.open = 1 and sh.card is not null and sh.step is not null
1654
+ except select card, step from steps)),
1655
+ lines(k, line) as (
1656
+ select -2, '' union all select -1, 'Where the steps'' time went:'
1657
+ union all select k, $line from timed
1658
+ union all select 11, ' ' || n || case when n = 1 then ' step' else ' steps' end
1659
+ || ' had no split, as ' || $why from unsplit
1660
+ where n > 0 and exists (select 1 from sp)
1661
+ union all select 0, ' no step was split, as ' || $why where not exists (select 1 from sp))
1662
+ select line from lines order by k;
1663
+ EOF
1664
+ }
1665
+
1666
+ # The verdict on the host from $1 to $2, from the splits when $3 is 1, and
1667
+ # the power state of the readings when $4 is 1, and the waits on the model
1668
+ # when $5 is 1: the report's last line, after the network line when there
1669
+ # is one.
1670
+ #
1671
+ # A wait on the model is slow when it took over twice the median of every
1672
+ # wait in model_waits, so 90 days at most: the wait halfway in order of
1673
+ # length, the later of the two for an even count. A slow wait counts for the
1674
+ # network when there is a reading over it, and every reading over it, in
1675
+ # whole or in part, had the CPU, memory and disk below their limit, as the
1676
+ # report counts it. The period's waits are those that ended in it. With any
1677
+ # that count, the network line, between blank lines, says the network may
1678
+ # be the cause: how many of the period's waits were slow while the host was
1679
+ # below its limit, and the median. A store with no waits on the model has
1680
+ # none.
1681
+ #
1682
+ # The agents' time on the host is their splits' seconds on the host, an
1683
+ # agent's second each, each split counted for the part of its reading in the
1684
+ # period, as the report counts a reading. The verdict is the first of these
1685
+ # that holds:
1686
+ # - too little data yet, with under HOST_VERDICT_STEPS steps with a split
1687
+ # in the period, each one card's own, or under HOST_VERDICT_SECS of the
1688
+ # agents' time on the host. It says how many and how long, against them.
1689
+ # - of the CPU, memory and disk, the one at its limit, as the report counts
1690
+ # it, for the most of the agents' time on the host, and for at least
1691
+ # HOST_VERDICT_PCT% of it, the CPU before memory before the disk when two
1692
+ # were as long: the power state was the limit, when over half of that
1693
+ # one's time at its limit was on battery, in Low Power Mode or with the
1694
+ # thermal state at serious or critical, and otherwise it is the one to
1695
+ # upgrade first.
1696
+ # - the network was the limit, when the waits that count for it are at
1697
+ # least HOST_VERDICT_PCT% of the period's waits on the model. It gives
1698
+ # that share and the median.
1699
+ # - no upgrade is needed.
1700
+ # All but the first say how much of the agents' time on the host each was at
1701
+ # its limit. A store with no splits has too little data, and one whose
1702
+ # readings have no power state counts them as on power, as a reading with
1703
+ # none of it does.
1704
+ HOST_VERDICT_STEPS=10
1705
+ HOST_VERDICT_SECS=3600
1706
+ HOST_VERDICT_PCT=10
1707
+ host_verdict_sql() {
1708
+ local s=$1 e=$2 splits power waits took median
1709
+ splits='select at, card, step, host_secs from splits'
1710
+ [ "${3:-0}" = 1 ] || splits='select null, null, null, null where 0'
1711
+ power='coalesce(on_battery = 1 or low_power = 1 or thermal >= 2, 0)'
1712
+ [ "${4:-0}" = 1 ] || power=0
1713
+ waits='select ended - started, started, ended from model_waits'
1714
+ [ "${5:-0}" = 1 ] || waits='select null, null, null where 0'
1715
+ took=$(sql_took 'cast(round(t.host) as integer)')
1716
+ # A median under a minute is given to a tenth of a second.
1717
+ median="case when m < 59.95 then printf('%.1fs', m) else $(sql_took 'cast(round(m) as integer)') end"
1718
+ cat <<EOF
1719
+ with
1720
+ parts(at, secs, d, cpu, mem, disk, power) as (
1721
+ select at, secs, max(0, min(at, $e) - max(at - secs, $s)),
1722
+ coalesce(cpu_busy >= 90, 0), coalesce(mem_pressure >= 2, 0), coalesce(disk_free_pct < 10, 0), $power
1723
+ from readings where at > $s and at < $e + $HOST_GAP and at - secs < $e and secs > 0),
1724
+ x(at, card, step, host) as ($splits),
1725
+ sp(card, step, host, cpu, mem, disk, power) as (
1726
+ select x.card, x.step, 1.0 * coalesce(x.host, 0) * p.d / p.secs, p.cpu, p.mem, p.disk, p.power
1727
+ from parts p join x on x.at = p.at),
1728
+ total(steps, host) as (
1729
+ select (select count(*) from (select distinct card, step from sp where card is not null and step is not null)),
1730
+ coalesce(sum(host), 0) from sp),
1731
+ res(o, name, lim, pow) as (
1732
+ select 1, 'the CPU', coalesce(sum(case when cpu then host end), 0), coalesce(sum(case when cpu and power then host end), 0) from sp
1733
+ union all
1734
+ select 2, 'memory', coalesce(sum(case when mem then host end), 0), coalesce(sum(case when mem and power then host end), 0) from sp
1735
+ union all
1736
+ select 3, 'the disk', coalesce(sum(case when disk then host end), 0), coalesce(sum(case when disk and power then host end), 0) from sp),
1737
+ pcts(cpu, mem, disk) as (
1738
+ select max(case when o = 1 then pct end), max(case when o = 2 then pct end), max(case when o = 3 then pct end)
1739
+ from (select o, printf('%.1f%%', 100.0 * lim / nullif(t.host, 0)) pct from res, total t)),
1740
+ named(o, name, lim, pow) as (
1741
+ select o, name, lim, pow from res, total t
1742
+ where lim > 0 and 100.0 * lim >= $HOST_VERDICT_PCT * t.host order by lim desc, o limit 1),
1743
+ w(d, started, ended) as ($waits),
1744
+ med(m) as (select d from w order by d limit 1 offset (select count(*) / 2 from w)),
1745
+ inp(d, started, ended) as (select d, started, ended from w where ended >= $s and ended < $e),
1746
+ slow(started, ended) as (select i.started, i.ended from inp i, med where i.d > 2 * med.m),
1747
+ span(secs) as (select coalesce(max(secs), 0) from readings),
1748
+ below(n) as (
1749
+ select count(*) from slow, span
1750
+ where exists (select 1 from readings r
1751
+ where r.at > slow.started and r.at < slow.ended + span.secs and r.at - r.secs < slow.ended)
1752
+ and not exists (select 1 from readings r
1753
+ where r.at > slow.started and r.at < slow.ended + span.secs and r.at - r.secs < slow.ended
1754
+ and (coalesce(r.cpu_busy >= 90, 0) or coalesce(r.mem_pressure >= 2, 0) or coalesce(r.disk_free_pct < 10, 0)))),
1755
+ net(n, total, median) as (select b.n, (select count(*) from inp), $median from below b, med),
1756
+ lines(k, line) as (
1757
+ select 0, ''
1758
+ union all
1759
+ select 1, 'The network may be the cause: ' || n || ' of ' || total || case when total = 1 then ' wait' else ' waits' end
1760
+ || ' on the model ' || case when n = 1 then 'was' else 'were' end || ' slow (over twice the median of ' || median
1761
+ || ') while CPU, memory and disk were below their limit.'
1762
+ from net where n > 0
1763
+ union all
1764
+ select 2, '' from net where n > 0
1765
+ union all
1766
+ select 3, 'Verdict: ' || case
1767
+ when t.steps < $HOST_VERDICT_STEPS or t.host < $HOST_VERDICT_SECS then
1768
+ 'too little data yet: ' || t.steps || case when t.steps = 1 then ' step had its' else ' steps had their' end
1769
+ || ' time split, with ' || $took || ' of the agents'' time on the host, and a verdict takes at least '
1770
+ || '$HOST_VERDICT_STEPS steps and ' || $(sql_took $HOST_VERDICT_SECS) || '.'
1771
+ when f.o is not null then
1772
+ case when 2 * f.pow > f.lim then 'the power state was the limit, not ' || f.name else 'upgrade ' || f.name || ' first' end
1773
+ || ': it was at its limit for ' || printf('%.1f%%', 100.0 * f.lim / t.host) || ' of the agents'' ' || $took || ' on the host'
1774
+ || case when 2 * f.pow > f.lim then ', ' || printf('%.1f%%', 100.0 * f.pow / f.lim)
1775
+ || ' of that on battery, in Low Power Mode or with the thermal state at serious or critical' else '' end
1776
+ || ' (' || case f.o when 1 then 'memory ' || p.mem || ', disk ' || p.disk
1777
+ when 2 then 'CPU ' || p.cpu || ', disk ' || p.disk else 'CPU ' || p.cpu || ', memory ' || p.mem end || ').'
1778
+ when nt.n > 0 and 100 * nt.n >= $HOST_VERDICT_PCT * nt.total then
1779
+ 'the network was the limit: ' || printf('%.1f%%', 100.0 * nt.n / nt.total) || ' of the ' || nt.total
1780
+ || case when nt.total = 1 then ' wait on the model was' else ' waits on the model were' end
1781
+ || ' slow (over twice the median of ' || nt.median || ') while CPU, memory and disk were below their limit,'
1782
+ || ' and each was at its limit for under $HOST_VERDICT_PCT% of the agents'' ' || $took
1783
+ || ' on the host (CPU ' || p.cpu || ', memory ' || p.mem || ', disk ' || p.disk || ').'
1784
+ else
1785
+ 'no upgrade is needed: CPU, memory and disk were each at their limit for under $HOST_VERDICT_PCT% of the agents'' '
1786
+ || $took || ' on the host (CPU ' || p.cpu || ', memory ' || p.mem || ', disk ' || p.disk || ').'
1787
+ end
1788
+ from total t left join named f on 1 left join pcts p on 1 left join net nt on 1)
1789
+ select line from lines order by k;
1790
+ EOF
1791
+ }
1792
+
1793
+ cmd_host() {
1794
+ case ${1:-} in
1795
+ '') [ "$#" -le 1 ] || die "$HOST_USAGE"; host_show ;;
1796
+ on) shift; host_on "$@" ;;
1797
+ off) shift; host_off "$@" ;;
1798
+ report) shift; host_report "$@" ;;
1799
+ record) shift; host_record "$@" ;;
1800
+ *) die "$HOST_USAGE" ;;
1801
+ esac
1802
+ }