@johngaynor/ocnus 2.0.1-next.7 → 2.0.1-next.71

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 (43) hide show
  1. package/README.md +506 -93
  2. package/cli/lib/agents.sh +32 -16
  3. package/cli/lib/asks.sh +762 -0
  4. package/cli/lib/banner.sh +181 -0
  5. package/cli/lib/brief.sh +375 -0
  6. package/cli/lib/chain.sh +363 -0
  7. package/cli/lib/close.sh +5 -3
  8. package/cli/lib/cost.sh +500 -0
  9. package/cli/lib/finish.sh +30 -4
  10. package/cli/lib/github.sh +106 -26
  11. package/cli/lib/guard.sh +39 -10
  12. package/cli/lib/handoff.sh +196 -31
  13. package/cli/lib/host.sh +186 -345
  14. package/cli/lib/linear.sh +552 -56
  15. package/cli/lib/links.sh +6 -3
  16. package/cli/lib/merges.sh +126 -27
  17. package/cli/lib/sessions.sh +132 -0
  18. package/cli/lib/settings.sh +31 -15
  19. package/cli/lib/task.sh +169 -54
  20. package/cli/lib/tests.sh +302 -7
  21. package/cli/lib/usage.sh +204 -0
  22. package/cli/ocnus +264 -72
  23. package/herdr/README.md +867 -223
  24. package/herdr/layouts/default.json +30 -11
  25. package/herdr/layouts/showcase.json +291 -0
  26. package/herdr/layouts/vibe.json +162 -0
  27. package/herdr/layouts/vibe.svg +41 -0
  28. package/herdr/mods/agent-settings/main.js +19 -7
  29. package/herdr/mods/memory/main.js +128 -0
  30. package/herdr/mods/memory/mod.json +1 -0
  31. package/herdr/mods/memory/reading.js +88 -0
  32. package/herdr/mods/names/main.js +22 -4
  33. package/herdr/mods/step-counts/main.js +281 -0
  34. package/herdr/mods/step-counts/mod.json +1 -0
  35. package/herdr/mods/usage/main.js +149 -0
  36. package/herdr/mods/usage/mod.json +1 -0
  37. package/package.json +1 -1
  38. package/prompts/task-new.md +1 -1
  39. package/skills/brief/SKILL.md +8 -0
  40. package/skills/sdlc-breakdown/SKILL.md +66 -18
  41. package/skills/sdlc-build/SKILL.md +6 -2
  42. package/skills/sdlc-pr/SKILL.md +2 -2
  43. package/skills/sdlc-review/SKILL.md +5 -5
package/cli/lib/tests.sh CHANGED
@@ -9,6 +9,9 @@
9
9
  # "tests" in the settings file (settings.sh), "share" or "queue", and share
10
10
  # when the file leaves it out. test/run.sh reads it with jq each time a run
11
11
  # starts, so every run that starts after a change follows it.
12
+ #
13
+ # `ocnus tests ls` lists the runs going, from the pool test/run.sh keeps
14
+ # them in, and how each uses the processors (tests_ls). It only reads.
12
15
 
13
16
  #
14
17
  # `ocnus tests run <command>` is the other half: it runs a repo's test
@@ -17,8 +20,9 @@
17
20
  # run every test command through it.
18
21
 
19
22
  # What `ocnus tests` takes after it.
20
- TAKES_TESTS='share or queue, or nothing to say which is set (--json for programs), or run and a test command'
23
+ TAKES_TESTS='share or queue, or nothing to say which is set (--json for programs), or ls to list the test runs going (ls --json for programs), or run and a test command'
21
24
  TESTS_RUN_USAGE='usage: ocnus tests run <command> [<arg>...], like: ocnus tests run npm test'
25
+ TESTS_LS_USAGE='usage: ocnus tests ls [--json]: it lists the test runs going on this machine (--json for programs)'
22
26
 
23
27
  # ocnus tests [share|queue|--json]: say how test runs use the
24
28
  # processors, or set it. --json prints it as one line for programs, with the
@@ -26,12 +30,25 @@ TESTS_RUN_USAGE='usage: ocnus tests run <command> [<arg>...], like: ocnus tests
26
30
  # settings file as archive_set writes "archive": everything is checked before
27
31
  # the file is touched, and the new file is checked before it takes the old
28
32
  # one's place, so a refusal or a failure leaves the file as it was.
33
+ # ocnus tests ls [--json] lists the test runs going (tests_ls), and
29
34
  # ocnus tests run <command> runs a test command (tests_run).
30
35
  cmd_tests() {
31
36
  if [ "${1:-}" = run ]; then
32
37
  shift
33
38
  tests_run "$@"
34
39
  fi
40
+ if [ "${1:-}" = ls ]; then
41
+ shift
42
+ case $# in
43
+ 0) tests_ls plain ;;
44
+ 1)
45
+ [ "$1" = --json ] || die "$TESTS_LS_USAGE"
46
+ tests_ls json
47
+ ;;
48
+ *) die "$TESTS_LS_USAGE" ;;
49
+ esac
50
+ return 0
51
+ fi
35
52
  case $# in
36
53
  0) tests_show plain ;;
37
54
  1)
@@ -41,22 +58,34 @@ cmd_tests() {
41
58
  *) die "'$1' is not share or queue. ocnus tests takes $TAKES_TESTS." ;;
42
59
  esac
43
60
  ;;
44
- *) die "usage: ocnus tests [share|queue|--json]: it takes $TAKES_TESTS" ;;
61
+ *) die "usage: ocnus tests [share|queue|--json] or ocnus tests ls [--json]: it takes $TAKES_TESTS" ;;
45
62
  esac
46
63
  }
47
64
 
65
+ # Set TESTS_SENTENCE to the sentence that says how the test runs use the
66
+ # processors, as the settings loaded say, for `tests` and `tests ls` alike.
67
+ TESTS_SENTENCE=''
68
+ tests_sentence() {
69
+ if [ "$SET_TESTS" = queue ]; then
70
+ TESTS_SENTENCE='Test runs go one at a time: a run that starts while another is going waits its turn, in the order the runs started, then has every processor.'
71
+ else
72
+ TESTS_SENTENCE='Test runs share the processors: runs going at the same time run one case per processor between them.'
73
+ fi
74
+ }
75
+
48
76
  # Say which is set: plain, for a person, or json, for programs, as
49
77
  # {"file":…,"tests":"share"}.
50
78
  tests_show() {
51
79
  need_jq
52
80
  settings_check
81
+ tests_sentence
53
82
  if [ "$1" = json ]; then
54
83
  printf '{"file":"%s","tests":"%s"}\n' "$(json_str "$SETTINGS")" "$SET_TESTS"
55
84
  elif [ "$SET_TESTS" = queue ]; then
56
- say "Test runs go one at a time: a run that starts while another is going waits its turn, in the order the runs started, then has every processor."
85
+ say "$TESTS_SENTENCE"
57
86
  say "Have them share the processors with: ocnus tests share"
58
87
  else
59
- say "Test runs share the processors: runs going at the same time run one case per processor between them."
88
+ say "$TESTS_SENTENCE"
60
89
  say "Have them go one at a time with: ocnus tests queue"
61
90
  fi
62
91
  }
@@ -85,6 +114,273 @@ tests_set() {
85
114
  fi
86
115
  }
87
116
 
117
+ # --- the test runs going ------------------------------------------------------
118
+
119
+ # `ocnus tests ls` lists the runs of ocnus's own tests going on this
120
+ # machine, from the pool test/run.sh keeps in test-runs in ocnus's folder
121
+ # (see the comment at the top of test/run.sh):
122
+ # runs/<number>.<pid>.<share|jobs|wait> a run going, numbered in the
123
+ # order the runs started
124
+ # slots/<number>.<worker's pid>.<run's pid> a case being run
125
+ # It only reads. An entry whose name does not parse is left out, and so is
126
+ # one whose process has gone, as after kill -9, found as `entry` in run.sh
127
+ # finds it. Either is left where it is, for a run to remove.
128
+ #
129
+ # The pool does not say which setting a run started under, and a run that
130
+ # waited its turn becomes a share entry, or a jobs one, just as a run that
131
+ # never waited is. So what a run is doing, and its mark, go by the setting
132
+ # now and the order the runs started in. A run is ahead of another when it
133
+ # has a lower number, or the same number and a lower pid, as ahead() in
134
+ # run.sh counts it, and only the runs going count:
135
+ # - with queue, a share entry with no run ahead of it has its turn, and a
136
+ # share or jobs entry with one ahead started before the switch, so it
137
+ # still runs beside the runs ahead of it;
138
+ # - with share, a wait entry started before the switch, so it still waits.
139
+ # A run that started before the switch is marked old mode.
140
+ TESTS_POOL=$ENT_HOME/test-runs
141
+ # A task's folder, tasks/<card>-<short name> or tasks/<card>, as task_folder
142
+ # (finish.sh) finds one. The card is the first group.
143
+ TESTS_TASK_RE='^([A-Za-z][A-Za-z0-9]*-[0-9]+)(-.*)?$'
144
+
145
+ # ocnus tests ls [--json]: list the test runs going, in the order they
146
+ # started, which is the order the waiting ones get their turns. Plain, for a
147
+ # person, it prints the setting's sentence as `tests` says it, then a line for
148
+ # each run: its name, what it is doing with its mark, how long ago it started
149
+ # and its processors. json, for programs, prints one line:
150
+ # {"file": <the settings file>, "tests": "share" | "queue",
151
+ # "cpus": <the processors>, "note": "No test runs going" | null,
152
+ # "runs": [{"number", "pid", "name", "card", "folder", "state", "doing",
153
+ # "mark", "tip", "age", "slots", "holds"}...]}
154
+ # A run's name is its card when it was started in a task's folder, its
155
+ # folder's name otherwise, and pid <pid> when its folder cannot be found.
156
+ # card is null outside a task, and folder is null when it cannot be found.
157
+ # state is share, wait, jobs or turn, and doing
158
+ # gives its words: sharing, waiting, OCNUS_TEST_JOBS and its turn. mark is
159
+ # "old mode" or null, and tip says what the mark means, or is null. age is how
160
+ # long ago the run started, its wait for a turn included, as took_text words
161
+ # it. slots is how many cases it has going, and holds is those out of the
162
+ # processors, as 5/10, the processors counted as run.sh counts them.
163
+ #
164
+ # With no run going, plain says so in one line with the setting's sentence.
165
+ # When jq, the settings or the pool cannot be read, it stops as `tests`
166
+ # does, saying why in one line. With no run going it runs no ps or lsof;
167
+ # otherwise it runs one ps for how long ago each started, and on a machine
168
+ # with no /proc, such as macOS, one lsof for the folder each runs in.
169
+ tests_ls() {
170
+ local mode=$1 re f name n p k w i lines='' plist='' etimes=' ' out line cur
171
+ local cpus root roots=() task card note=null sep='' wn=0 wd=0 wa=0
172
+ local nums=() pids=() kinds=() ages=() folders=() names=() cards=() slots=()
173
+ need_jq
174
+ settings_check
175
+ tests_sentence
176
+ for f in "$TESTS_POOL" "$TESTS_POOL/runs" "$TESTS_POOL/slots"; do
177
+ [ -e "$f" ] || [ -L "$f" ] || continue
178
+ [ -d "$f" ] || die "cannot read the test runs going: $f is not a folder. Move it aside, and the next test run makes it again."
179
+ [ -r "$f" ] && [ -x "$f" ] || die "cannot read the test runs going in $f: check its owner and permissions."
180
+ done
181
+ # Each run going, as "<number> <pid> <kind>".
182
+ re='^([1-9][0-9]*)\.([1-9][0-9]*)\.(share|jobs|wait)$'
183
+ for f in "$TESTS_POOL"/runs/*; do
184
+ name=${f##*/}
185
+ [[ $name =~ $re ]] || continue
186
+ n=${BASH_REMATCH[1]} p=${BASH_REMATCH[2]} k=${BASH_REMATCH[3]}
187
+ kill -0 "$p" 2>/dev/null || continue
188
+ lines="$lines$n $p $k"$'\n'
189
+ plist=$plist${plist:+,}$p
190
+ done
191
+ if [ -n "$lines" ]; then
192
+ # How long ago each started, as " <pid>=<seconds>". A run ps gives no
193
+ # line for has gone since.
194
+ out=$(ps -o pid=,etime= -p "$plist" 2>/dev/null) || true
195
+ while read -r p w; do
196
+ case $p in '' | *[!0-9]*) continue ;; esac
197
+ etime_secs "$w"
198
+ [ -z "$ETIME_SECS" ] || etimes="$etimes$p=$ETIME_SECS "
199
+ done <<< "$out"
200
+ while read -r n p k; do
201
+ case $etimes in *" $p="*) ;; *) continue ;; esac
202
+ w=${etimes#*" $p="}
203
+ took_text "${w%% *}"
204
+ nums+=("$n") pids+=("$p") kinds+=("$k") ages+=("$TOOK") folders+=('') slots+=(0)
205
+ done < <(printf '%s' "$lines" | LC_ALL=C sort -k1,1n -k2,2n)
206
+ fi
207
+ if [ "${#pids[@]}" -gt 0 ]; then
208
+ # The folder each runs in: /proc's link on Linux, or else lsof's word,
209
+ # from /usr/sbin on macOS, which a command Herdr starts may not have on
210
+ # its PATH.
211
+ if [ -L "/proc/$$/cwd" ]; then
212
+ i=0
213
+ while [ "$i" -lt "${#pids[@]}" ]; do
214
+ folders[$i]=$(readlink "/proc/${pids[$i]}/cwd" 2>/dev/null) || folders[$i]=''
215
+ i=$((i + 1))
216
+ done
217
+ else
218
+ PATH=$PATH:/usr/sbin:/sbin
219
+ out=$(lsof -a -d cwd -Fpn -p "$plist" 2>/dev/null) || true
220
+ cur=-1
221
+ while IFS= read -r line; do
222
+ case $line in
223
+ p*) if tests_ls_index "${line#p}"; then cur=$TESTS_I; else cur=-1; fi ;;
224
+ n*) [ "$cur" -lt 0 ] || folders[$cur]=${line#n} ;;
225
+ esac
226
+ done <<< "$out"
227
+ fi
228
+ # Each run's name: its card in a task's folder of one of the spaces, the
229
+ # task folders compared as their real paths, as the folder is given.
230
+ for f in "$SPACES"/*/; do
231
+ [ -d "${f}tasks" ] || continue
232
+ root=$(cd -P "${f}tasks" 2>/dev/null && pwd) || continue
233
+ roots+=("$root")
234
+ done
235
+ i=0
236
+ while [ "$i" -lt "${#pids[@]}" ]; do
237
+ f=${folders[$i]} card=''
238
+ for root in ${roots[@]+"${roots[@]}"}; do
239
+ case $f in "$root"/*) ;; *) continue ;; esac
240
+ task=${f#"$root"/}
241
+ task=${task%%/*}
242
+ if [[ $task =~ $TESTS_TASK_RE ]]; then
243
+ card=$(printf '%s' "${BASH_REMATCH[1]}" | tr '[:lower:]' '[:upper:]')
244
+ fi
245
+ break
246
+ done
247
+ cards[$i]=$card
248
+ if [ -n "$card" ]; then names[$i]=$card
249
+ elif [ -z "$f" ]; then names[$i]="pid ${pids[$i]}"
250
+ elif [ -n "${f##*/}" ]; then names[$i]=${f##*/}
251
+ else names[$i]=$f
252
+ fi
253
+ i=$((i + 1))
254
+ done
255
+ # The cases each has going: its slots whose worker answers.
256
+ re='^[0-9]+\.([1-9][0-9]*)\.([1-9][0-9]*)$'
257
+ for f in "$TESTS_POOL"/slots/*; do
258
+ name=${f##*/}
259
+ [[ $name =~ $re ]] || continue
260
+ w=${BASH_REMATCH[1]} p=${BASH_REMATCH[2]}
261
+ tests_ls_index "$p" || continue
262
+ kill -0 "$w" 2>/dev/null || continue
263
+ slots[$TESTS_I]=$((slots[TESTS_I] + 1))
264
+ done
265
+ fi
266
+ # The processors, as run.sh counts them.
267
+ cpus=$(getconf _NPROCESSORS_ONLN 2>/dev/null) || cpus=''
268
+ case $cpus in '' | *[!0-9]* | 0*) cpus=4 ;; esac
269
+
270
+ if [ "$mode" = json ]; then
271
+ [ "${#pids[@]}" -gt 0 ] || note='"No test runs going"'
272
+ tests_ls_str "$SETTINGS"
273
+ printf '{"file":"%s","tests":"%s","cpus":%s,"note":%s,"runs":[' "$TESTS_STR" "$SET_TESTS" "$cpus" "$note"
274
+ i=0
275
+ while [ "$i" -lt "${#pids[@]}" ]; do
276
+ tests_ls_doing "$i"
277
+ printf '%s{"number":%s,"pid":%s' "$sep" "${nums[$i]}" "${pids[$i]}"
278
+ tests_ls_str "${names[$i]}"
279
+ printf ',"name":"%s"' "$TESTS_STR"
280
+ tests_ls_str "${cards[$i]}"
281
+ if [ -n "${cards[$i]}" ]; then printf ',"card":"%s"' "$TESTS_STR"; else printf ',"card":null'; fi
282
+ tests_ls_str "${folders[$i]}"
283
+ if [ -n "${folders[$i]}" ]; then printf ',"folder":"%s"' "$TESTS_STR"; else printf ',"folder":null'; fi
284
+ printf ',"state":"%s","doing":"%s"' "$TESTS_STATE" "$TESTS_DOING"
285
+ if [ -n "$TESTS_MARK" ]; then printf ',"mark":"%s","tip":"%s"' "$TESTS_MARK" "$TESTS_TIP"; else printf ',"mark":null,"tip":null'; fi
286
+ printf ',"age":"%s","slots":%s,"holds":"%s/%s"}' "${ages[$i]}" "${slots[$i]}" "${slots[$i]}" "$cpus"
287
+ sep=,
288
+ i=$((i + 1))
289
+ done
290
+ printf ']}\n'
291
+ return 0
292
+ fi
293
+ if [ "${#pids[@]}" = 0 ]; then
294
+ say "No test runs going. $TESTS_SENTENCE"
295
+ return 0
296
+ fi
297
+ say "$TESTS_SENTENCE"
298
+ # A column for each part, as wide as its widest.
299
+ i=0
300
+ while [ "$i" -lt "${#pids[@]}" ]; do
301
+ tests_ls_doing "$i"
302
+ [ "${#names[$i]}" -le "$wn" ] || wn=${#names[$i]}
303
+ [ "${#TESTS_WORDS}" -le "$wd" ] || wd=${#TESTS_WORDS}
304
+ [ "$((${#ages[$i]} + 4))" -le "$wa" ] || wa=$((${#ages[$i]} + 4))
305
+ i=$((i + 1))
306
+ done
307
+ i=0
308
+ while [ "$i" -lt "${#pids[@]}" ]; do
309
+ tests_ls_doing "$i"
310
+ printf ' %-*s %-*s %-*s %s processors\n' "$wn" "${names[$i]}" "$wd" "$TESTS_WORDS" "$wa" "${ages[$i]} ago" \
311
+ "${slots[$i]}/$cpus"
312
+ i=$((i + 1))
313
+ done
314
+ }
315
+
316
+ # Set TESTS_I to the place in tests_ls's runs of the run whose pid is $1, or
317
+ # fail when it is not one of them.
318
+ TESTS_I=0
319
+ tests_ls_index() {
320
+ TESTS_I=0
321
+ while [ "$TESTS_I" -lt "${#pids[@]}" ]; do
322
+ [ "${pids[$TESTS_I]}" != "$1" ] || return 0
323
+ TESTS_I=$((TESTS_I + 1))
324
+ done
325
+ return 1
326
+ }
327
+
328
+ # Set TESTS_STATE, TESTS_DOING, TESTS_MARK and TESTS_TIP to what tests_ls's
329
+ # run $1 is doing, and TESTS_WORDS to its words with its mark, for a person.
330
+ # Only the runs going count, so a run with any before it in the list has one
331
+ # ahead.
332
+ TESTS_STATE='' TESTS_DOING='' TESTS_MARK='' TESTS_TIP='' TESTS_WORDS=''
333
+ tests_ls_doing() {
334
+ local i=$1
335
+ TESTS_STATE=${kinds[$i]} TESTS_MARK='' TESTS_TIP=''
336
+ case $SET_TESTS:$TESTS_STATE in
337
+ queue:share)
338
+ if [ "$i" = 0 ]; then
339
+ TESTS_STATE=turn
340
+ else
341
+ TESTS_MARK='old mode' TESTS_TIP='Started before the switch to queue, so it still shares the processors'
342
+ fi
343
+ ;;
344
+ queue:jobs)
345
+ [ "$i" = 0 ] ||
346
+ TESTS_MARK='old mode' TESTS_TIP='Started before the switch to queue, so it still runs beside the runs ahead of it'
347
+ ;;
348
+ share:wait) TESTS_MARK='old mode' TESTS_TIP='Started before the switch to share, so it still waits its turn' ;;
349
+ esac
350
+ case $TESTS_STATE in
351
+ share) TESTS_DOING=sharing ;;
352
+ wait) TESTS_DOING=waiting ;;
353
+ jobs) TESTS_DOING=OCNUS_TEST_JOBS ;;
354
+ turn) TESTS_DOING='its turn' ;;
355
+ esac
356
+ TESTS_WORDS=$TESTS_DOING${TESTS_MARK:+ ($TESTS_MARK)}
357
+ }
358
+
359
+ # Set TESTS_STR to $1 as the inside of a JSON string. Only a string with
360
+ # something to escape starts a program, through json_str.
361
+ TESTS_STR=''
362
+ tests_ls_str() {
363
+ case $1 in
364
+ *[\\\"[:cntrl:]]*) TESTS_STR=$(json_str "$1") ;;
365
+ *) TESTS_STR=$1 ;;
366
+ esac
367
+ }
368
+
369
+ # Set ETIME_SECS to a time as ps's etime gives it, [[dd-]hh:]mm:ss, in
370
+ # seconds, or to nothing when it is not one.
371
+ ETIME_SECS=''
372
+ etime_secs() {
373
+ local t=$1 d=0 h=0 m s x
374
+ ETIME_SECS=''
375
+ case $t in *-*) d=${t%%-*} t=${t#*-} ;; esac
376
+ case $t in *:*:*) h=${t%%:*} t=${t#*:} ;; esac
377
+ case $t in *:*) m=${t%%:*} s=${t#*:} ;; *) return 0 ;; esac
378
+ for x in "$d" "$h" "$m" "$s"; do
379
+ case $x in '' | *[!0-9]*) return 0 ;; esac
380
+ done
381
+ ETIME_SECS=$((10#$d * 86400 + 10#$h * 3600 + 10#$m * 60 + 10#$s))
382
+ }
383
+
88
384
  # --- a test run ---------------------------------------------------------------
89
385
 
90
386
  # ocnus tests run <command> [<arg>...]: run a test command as it is, and
@@ -107,9 +403,8 @@ tests_set() {
107
403
  # readings is there too. The job's row goes in test_runs as it starts, with
108
404
  # its card, repo, start and the job's pid, and the fingerprint of its
109
405
  # command, cmd: the first 15 hex digits of the SHA-256 of its arguments, each
110
- # ended by a NUL, as a number. It is the same for the same command, so that
111
- # `host report` can set runs of the same command in the same repo against
112
- # each other, and the command's text cannot be read back from it. It is all
406
+ # ended by a NUL, as a number. It is the same for the same command,
407
+ # and the command's text cannot be read back from it. It is all
113
408
  # that is kept of the command line. While the job runs, the sampler adds up
114
409
  # the memory of its processes every second, and writes the most it saw to
115
410
  # the row. When the job ends, the row gets its end and the figures, and what
@@ -0,0 +1,204 @@
1
+ # How much of the Claude subscription's usage limits is used: the five-hour
2
+ # limit and the weekly one, and when each resets. With billing on api, also
3
+ # what the agents have spent on the API key. Sourced by cli/ocnus.
4
+
5
+ # Claude Code hands a status line command a JSON on stdin each time it
6
+ # updates the status line, and while it runs on a Claude subscription,
7
+ # once the first answer has come, that JSON has rate_limits.five_hour and
8
+ # rate_limits.seven_day, each with used_percentage (0 to 100) and resets_at
9
+ # (seconds since 1970). A window is left out once its resets_at has passed,
10
+ # until the next answer, and both are left out on an API key.
11
+ #
12
+ # Every agent `task new` and `task build` start in claude, on the
13
+ # subscription or on an API key, gets a statusLine that runs `ocnus usage
14
+ # record <space> <card> <phase> <account>` (profile_args, in task.sh). It
15
+ # saves the two windows, and when they were read, to usage.json in ocnus's
16
+ # folder, and adds what the agent's session has used to the cost file
17
+ # (cost_record, in cost.sh). `ocnus usage` reads the file back, and the
18
+ # Usage section in Herdr's sidebar runs `ocnus usage --json` every 30
19
+ # seconds. So the reading is as fresh as the last update of an ocnus
20
+ # agent's status line: it ages while no agent works, says how old it is, and
21
+ # a window whose reset has passed since is shown as reset, not as a number.
22
+ # An agent on an API key hands over no windows, so it leaves the reading as
23
+ # it was. Claude Code sessions the human starts are not read: their settings
24
+ # are their own.
25
+
26
+ # The last reading: {"read_at": <seconds>, "five_hour": {"used": <0 to 100>,
27
+ # "resets_at": <seconds>} | null, "seven_day": the same | null}.
28
+ USAGE_FILE=$ENT_HOME/usage.json
29
+ USAGE_TAKES='usage: ocnus usage [--json]: it takes nothing, to say how much of your Claude usage limits is used, or --json for programs'
30
+ # A reading older than this, in seconds, says how old it is.
31
+ USAGE_STALE=600
32
+
33
+ # ocnus usage [--json | record [<space> <card> <phase> <account>]]: say
34
+ # how much of the usage limits is used, as a person reads it or, with --json,
35
+ # as one line for programs, or, with record, save the reading in the status
36
+ # line JSON on stdin. Only the agents' statusLine runs record, with the four
37
+ # words its agent was started with, so that what the session used is recorded
38
+ # as that card's too. record alone saves the limits only.
39
+ cmd_usage() {
40
+ case $# in
41
+ 0) usage_show plain ;;
42
+ 1)
43
+ case $1 in
44
+ --json) usage_show json ;;
45
+ record) usage_record ;;
46
+ *) die "$USAGE_TAKES" ;;
47
+ esac
48
+ ;;
49
+ 5)
50
+ [ "$1" = record ] || die "$USAGE_TAKES"
51
+ shift
52
+ usage_record "$@"
53
+ ;;
54
+ *) die "$USAGE_TAKES" ;;
55
+ esac
56
+ }
57
+
58
+ # Save the two windows of the status line JSON on stdin, with the time now,
59
+ # in the usage file, through a file of its own that takes the old one's place
60
+ # at once, so that the section never reads half a file and two agents
61
+ # writing at once leave one whole reading. It is a status line command, so it
62
+ # prints nothing, and it never fails: a JSON with neither window in it, as
63
+ # before an agent's first answer or on an API key, leaves the last reading as
64
+ # it was, and so does anything that goes wrong. stdin is read once, to its
65
+ # end, either way.
66
+ #
67
+ # Given the four words an agent's statusLine has, the space, the card, the
68
+ # phase and the account, it then adds what the session in that JSON has used
69
+ # to the cost file (cost_record, in cost.sh), in a shell of its own with no
70
+ # output: an agent whose figures cannot be recorded works as before.
71
+ # usage_record [<space> <card> <phase> <account>]
72
+ usage_record() {
73
+ local now tmp json
74
+ if ! command -v jq >/dev/null 2>&1 || ! mkdir -p "$ENT_HOME" 2>/dev/null; then
75
+ cat >/dev/null 2>&1 || true
76
+ return 0
77
+ fi
78
+ # A null byte is no part of a JSON, and bash would warn of one.
79
+ json=$(tr -d '\000' 2>/dev/null) || true
80
+ now=$(date +%s)
81
+ tmp=$USAGE_FILE.ocnus.$$
82
+ if jq -cn --argjson now "$now" '
83
+ def win: if type == "object" and (.used_percentage | type) == "number" and (.resets_at | type) == "number"
84
+ then {used: .used_percentage, resets_at: (.resets_at | floor)} else null end;
85
+ [inputs] | last
86
+ | (if type == "object" and (.rate_limits | type) == "object" then .rate_limits else {} end) as $r
87
+ | {read_at: $now, five_hour: ($r.five_hour | win), seven_day: ($r.seven_day | win)}
88
+ | select(.five_hour != null or .seven_day != null)' <<< "$json" > "$tmp" 2>/dev/null && [ -s "$tmp" ]; then
89
+ mv -f "$tmp" "$USAGE_FILE" 2>/dev/null || true
90
+ fi
91
+ rm -f "$tmp" 2>/dev/null || true
92
+ [ "$#" -ne 4 ] || (set +e +o pipefail; cost_record "$json" "$@") >/dev/null 2>&1 || true
93
+ return 0
94
+ }
95
+
96
+ # Say what the last reading holds: plain, for a person, or json, for
97
+ # programs, as one line:
98
+ # {"file": …, "read_at": <seconds> | null, "age": "3m" | null,
99
+ # "stale": <older than ten minutes>,
100
+ # "five_hour": <window> | null, "seven_day": <window> | null,
101
+ # "note": <the one line to show instead of numbers> | null,
102
+ # "spend": <what the agents spent on the API key> | null}
103
+ # where a window is {"used": <0 to 100> | null, "resets_at": <seconds>,
104
+ # "reset": <its reset has passed>, "resets": "3:40pm"}: used is null once
105
+ # reset is true, since the window the reading was of is over. resets is when,
106
+ # in the machine's own time: the clock alone on the same day, the weekday
107
+ # too within six days, and the date further away. A window the reading has
108
+ # none of is null. note says why there are no numbers when there are none:
109
+ # no reading yet, a file that cannot be read, or both limits reset since.
110
+ #
111
+ # spend is null with billing on the subscription. With billing on api it is
112
+ # what the agents ocnus started on an API key have spent today and this
113
+ # week, from the cost file (cost_spend, in cost.sh), and null only when that
114
+ # cannot be read. The words give it on two lines.
115
+ usage_show() {
116
+ local mode=$1 now got=missing reading=null view billing=subscription spend=null
117
+ command -v jq >/dev/null 2>&1 ||
118
+ die "jq is not installed, and ocnus reads the usage reading with it. Install it, then run this again."
119
+ ! settings_load 2>/dev/null || billing=$SET_BILLING
120
+ if [ "$billing" = api ]; then
121
+ spend=$(cost_spend) && [ -n "$spend" ] && jq -e 'type == "object"' <<< "$spend" >/dev/null 2>&1 || spend=null
122
+ fi
123
+ now=$(date +%s)
124
+ if [ -e "$USAGE_FILE" ] || [ -L "$USAGE_FILE" ]; then
125
+ if reading=$(jq -cs 'if length == 1 and (.[0] | type) == "object" then .[0] else null end' "$USAGE_FILE" 2>/dev/null) &&
126
+ [ -n "$reading" ] && [ "$reading" != null ]; then
127
+ got=ok
128
+ else
129
+ got=bad reading=null
130
+ fi
131
+ fi
132
+ view=$(jq -cn --argjson r "$reading" --arg got "$got" --argjson now "$now" --argjson stale "$USAGE_STALE" \
133
+ --arg file "$USAGE_FILE" --argjson spend "$spend" '
134
+ def num: type == "number";
135
+ def clock: (strflocaltime("%H") | tonumber) as $h | strflocaltime("%M") as $m
136
+ | "\(if $h % 12 == 0 then 12 else $h % 12 end)\(if $m == "00" then "" else ":" + $m end)\(if $h < 12 then "am" else "pm" end)";
137
+ def when: (if . > $now then . - $now else $now - . end) as $far
138
+ | if strflocaltime("%Y-%m-%d") == ($now | strflocaltime("%Y-%m-%d")) then clock
139
+ elif $far < 6 * 86400 then "\(["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][strflocaltime("%w") | tonumber]) \(clock)"
140
+ else "\(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][(strflocaltime("%m") | tonumber) - 1]) \(strflocaltime("%d") | tonumber) \(clock)"
141
+ end;
142
+ def ago: floor
143
+ | if . < 60 then "\(.)s" elif . < 3600 then "\(. / 60 | floor)m"
144
+ elif . < 86400 then "\(. / 3600 | floor)h \(. % 3600 / 60 | floor)m"
145
+ else "\(. / 86400 | floor)d \(. % 86400 / 3600 | floor)h" end;
146
+ def window: if type == "object" and (.used | num) and (.resets_at | num) then
147
+ (.resets_at <= $now) as $reset
148
+ | {used: (if $reset then null else .used end), resets_at, reset: $reset, resets: (.resets_at | when)}
149
+ else null end;
150
+ (if ($r | type) == "object" and ($r.read_at | num) then $r else null end) as $r
151
+ | ($r.five_hour | window) as $five | ($r.seven_day | window) as $week
152
+ | (if $r then [$now - $r.read_at, 0] | max else null end) as $age
153
+ | ([$five, $week] | map(select(. != null))) as $windows
154
+ | {file: $file, read_at: $r.read_at, age: (if $age then $age | ago else null end),
155
+ stale: ($age != null and $age > $stale), five_hour: $five, seven_day: $week,
156
+ note: (if $got == "bad" or ($got == "ok" and $r == null) then "The last reading could not be read"
157
+ elif $r == null or ($windows | length) == 0 then "No reading yet"
158
+ elif ($windows | all(.reset)) then "Both limits have reset since the last reading"
159
+ else null end),
160
+ spend: $spend}')
161
+ if [ "$mode" = json ]; then
162
+ printf '%s\n' "$view"
163
+ return
164
+ fi
165
+ jq -r '
166
+ def row($name): " \($name) " + (if . == null then "no reading"
167
+ elif .reset then "reset at \(.resets), no reading since"
168
+ else "\(.used + 0.5 | floor)% used, resets \(.resets)" end);
169
+ if .read_at == null then
170
+ if .note == "No reading yet" then "No reading of your Claude usage limits yet."
171
+ else "The last reading of your Claude usage limits, in \(.file), could not be read." end
172
+ else
173
+ "Claude usage limits, read \(.age) ago:",
174
+ (.five_hour | row("five-hour")),
175
+ (.seven_day | row("weekly "))
176
+ end' <<< "$view"
177
+ say "An agent task new or task build starts on your Claude subscription reads them as it works, and saves the reading in $USAGE_FILE."
178
+ [ "$billing" = api ] || return 0
179
+ say "Billing is on the API, so the agents ocnus starts read no usage limits: switch back with: ocnus billing subscription"
180
+ if [ "$spend" = null ]; then
181
+ say "What they have spent on the API key could not be read from $COST_DB."
182
+ return 0
183
+ fi
184
+ jq -r '
185
+ "Spent on the API key today: \(.today.text)"
186
+ + (if .today.top then ", most of it on \(.today.top.card) in \(.today.top.space) (\(.today.top.text))" else "" end),
187
+ "Spent on the API key this week, from Monday \(.week.from): \(.week.text)"
188
+ + (if .week.cards == 0 then ""
189
+ else ", on \(.week.cards) \(if .week.cards == 1 then "card" else "cards" end), \(.week.merged) of them merged" end)' <<< "$spend"
190
+ }
191
+
192
+ # The statusLine claude is given, on either account (profile_args, in
193
+ # task.sh), as one line of JSON: a command that runs this copy of ocnus,
194
+ # told where ocnus's folder is, as billing_helper is, to save the reading
195
+ # it is handed and record what its session used as its card's. After `usage
196
+ # record` come the agent's space, card and phase and the account it runs on,
197
+ # which billing is on now. Each word is quoted for the shell claude runs it
198
+ # in, and none needs jq. There is no refreshInterval: a timer would save an
199
+ # idle agent's old limits as a new reading.
200
+ # usage_status_line <space> <card> <phase>
201
+ usage_status_line() {
202
+ printf '{"type":"command","command":"%s"}' \
203
+ "$(json_str "OCNUS_HOME=$(sh_quote "$ENT_HOME") $(sh_quote "$REPO/cli/ocnus") usage record $(sh_quote "$1") $(sh_quote "$2") $(sh_quote "$3") $(sh_quote "$SET_BILLING")")"
204
+ }