@johngaynor/ocnus 2.0.1-next.27 → 2.0.1-next.69

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.
@@ -0,0 +1,500 @@
1
+ # What each card's agents used, in tokens and in dollars, by step: the cost
2
+ # file, what writes it and what reads it. Sourced by cli/ocnus.
3
+
4
+ # Every agent `task new` and `task build` start in claude has a status line
5
+ # command, `ocnus usage record <space> <card> <phase> <account>`
6
+ # (usage.sh). Claude Code runs it as the session starts and each time the
7
+ # status line updates, and hands it a JSON that names the session, the file
8
+ # of its transcript and cost.total_cost_usd: what the session has cost so far
9
+ # at API prices, the subagents it started among it. The transcript is a file
10
+ # of JSON lines that only grows. A model turn is one message, written as a
11
+ # line for each of its parts, each with the message's id and the same usage:
12
+ # its input, output, cache read and cache write tokens. A subagent's turns
13
+ # are in a file of its own, under subagents/ in the folder named as the
14
+ # transcript is without .jsonl.
15
+ #
16
+ # cost_record adds what was written since the last reading to sums in the
17
+ # cost file, so the figures move as the agent works and are still there once
18
+ # Claude Code no longer keeps the transcript. No row is kept for a turn, only
19
+ # the sums:
20
+ # sessions each Claude Code session an agent ran in: its space, card and
21
+ # phase, its transcript, when it was first and last read, in UTC
22
+ # as a hand-off's time is, the cost last seen and how many
23
+ # readings were saved
24
+ # files each transcript file: how many bytes of it were read, and the
25
+ # last message counted
26
+ # spent the tokens, and the cost in whole millionths of a dollar, by
27
+ # session, by the hand-off the turns came after, by the day the
28
+ # reading was saved on, in this machine's time, and by the
29
+ # account the agent ran on, api or subscription
30
+ # `task log` (handoff.sh) and `usage` (usage.sh) only read it, attached
31
+ # read-only, as host_work (host.sh) attaches the hand-off store.
32
+ COST_DB=$ENT_HOME/cost.db
33
+
34
+ COST_TABLES='create table if not exists sessions (
35
+ id text primary key, space text not null, card text not null, phase text not null,
36
+ transcript text, first_at text not null, last_at text not null,
37
+ cost integer not null default 0, readings integer not null default 0);
38
+ create table if not exists files (
39
+ session text not null, path text not null, bytes integer not null default 0, last text,
40
+ primary key (session, path));
41
+ create table if not exists spent (
42
+ session text not null, handoff integer not null, day text not null, account text not null,
43
+ input integer not null default 0, output integer not null default 0,
44
+ cache_read integer not null default 0, cache_write integer not null default 0,
45
+ cost integer not null default 0,
46
+ primary key (session, handoff, day, account));'
47
+
48
+ # A message's id as a transcript gives it: letters, digits, _ and -. Nothing
49
+ # else goes into a statement, so no line of a transcript can change one.
50
+ COST_ID='^[A-Za-z0-9_-]{1,200}$'
51
+
52
+ # Is $1 a space's name: lowercase letters, digits and dashes? Each is named,
53
+ # with no range: in a UTF-8 locale, bash 3.2 takes a-z in a pattern for
54
+ # upper case letters too.
55
+ cost_space() { case ${1:-} in '' | *[!abcdefghijklmnopqrstuvwxyz0123456789-]*) return 1 ;; esac; }
56
+
57
+ # The statement that attaches the file $1 read-only under the name $2, as
58
+ # host_work attaches the hand-off store: its path as a URI, in which %, ? and
59
+ # # would be read as something else.
60
+ cost_attach() {
61
+ local uri=${1//\%/%25}
62
+ uri=${uri//\?/%3F}
63
+ uri=${uri//\#/%23}
64
+ printf 'attach %s as %s;' "$(sql_str "file:$uri?mode=ro")" "$2"
65
+ }
66
+
67
+ # How many of the $3 bytes that follow the first $2 bytes of the file $1 are
68
+ # whole lines: all of them when the last is a newline, and else those up to
69
+ # the last newline, since a line Claude Code is still writing is read once
70
+ # it is whole.
71
+ cost_whole() {
72
+ local f=$1 from=$2 n=$3 lines
73
+ [ "$n" -gt 0 ] || { printf 0; return 0; }
74
+ if [ "$(tail -c +"$((from + n))" "$f" 2>/dev/null | head -c 1 | wc -l | tr -d '[:space:]')" = 1 ]; then
75
+ printf '%s' "$n"
76
+ return 0
77
+ fi
78
+ lines=$(tail -c +"$((from + 1))" "$f" 2>/dev/null | head -c "$n" | wc -l | tr -d '[:space:]')
79
+ case $lines in '' | 0 | *[!0-9]*) printf 0; return 0 ;; esac
80
+ tail -c +"$((from + 1))" "$f" 2>/dev/null | head -c "$n" | head -n "$lines" | wc -c | tr -d '[:space:]'
81
+ }
82
+
83
+ # The id of the last model turn in the first $2 bytes of the transcript file
84
+ # $1, or nothing: the message a first reading marks as counted, so that a
85
+ # part of it written later is not taken for a new turn. Only the last
86
+ # megabyte is looked at, so a long transcript costs no more than a short one.
87
+ cost_last() {
88
+ local f=$1 whole=$2 from=0
89
+ [ "$whole" -le 1048576 ] || from=$((whole - 1048576))
90
+ tail -c +"$((from + 1))" "$f" 2>/dev/null | head -c "$((whole - from))" |
91
+ jq -rRn --arg id "$COST_ID" '[inputs | fromjson? | select(type == "object" and .type == "assistant")
92
+ | .message | select(type == "object") | .id | strings | select(test($id))] | last // ""' 2>/dev/null
93
+ }
94
+
95
+ # The jq that reads whole lines of a transcript, as raw lines on stdin, and
96
+ # prints: the id of the last model turn in them, or $last when there is none;
97
+ # then, for each message but $last, which an earlier reading counted, a
98
+ # statement that puts its time, cut to the second, and its four counts into
99
+ # the table turns; then the word read, which says that every line was read.
100
+ # A message's lines are one turn: the time is its first line's and the
101
+ # counts its last line's. A line that is not JSON, or not a model turn, is
102
+ # passed over, and a time that is not one is $now. $q is the quote around a
103
+ # value in a statement: an id and a time hold none.
104
+ # shellcheck disable=SC2016
105
+ COST_TURNS='def n: if type == "number" and . >= 0 then floor else 0 end;
106
+ [inputs | fromjson? | select(type == "object" and .type == "assistant") | . as $line | .message
107
+ | select(type == "object" and (.id | type) == "string" and (.usage | type) == "object")
108
+ | select(.id | test($id))
109
+ | {id, at: ($line.timestamp
110
+ | if type == "string" and test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}([.][0-9]+)?Z$")
111
+ then .[0:19] + "Z" else $now end),
112
+ u: (.usage | [(.input_tokens | n), (.output_tokens | n), (.cache_read_input_tokens | n),
113
+ (.cache_creation_input_tokens | n)])}]
114
+ | (if length > 0 then .[-1].id else $last end),
115
+ (reduce .[] as $m ({ids: [], by: {}};
116
+ if .by[$m.id] then .by[$m.id].u = $m.u else .ids += [$m.id] | .by[$m.id] = $m end)
117
+ | . as $all | $all.ids[] | select(. != $last) | $all.by[.]
118
+ | "insert into turns values (\($q)\(.id)\($q), \($q)\(.at)\($q), \(.u[0]), \(.u[1]), \(.u[2]), \(.u[3]));"),
119
+ "read"'
120
+
121
+ # Add to the cost file what the session in the status line JSON $1 has used
122
+ # since its last reading. The four words after it are the ones its agent was
123
+ # started with: the space, the card, the phase, write-up or build, and the
124
+ # account, api or subscription. usage_record runs it in a shell of its own,
125
+ # with no output, so nothing it does can show in the agent's status line or
126
+ # stop it.
127
+ #
128
+ # A session's first reading saves the session, marks each of its transcript
129
+ # files as read to its end and takes its cost so far as the base. Claude Code
130
+ # runs the status line as a session starts, so a new session is counted
131
+ # whole, and nothing a continued or copied session did before its first
132
+ # reading is counted.
133
+ #
134
+ # Every later reading reads the whole lines added to the transcript and to
135
+ # each .jsonl file under subagents/, a file that was not there before from
136
+ # its top, and counts each message's usage once (COST_TURNS). A turn follows
137
+ # the card's latest hand-off whose time is earlier than its own, read from
138
+ # the hand-off store, attached read-only. The row that ends its agent's phase
139
+ # is left out: a write-up agent's turn follows only a new, define, plan or
140
+ # breakdown row, and a build agent's never the merge, done with merged next.
141
+ # So what an agent says after `task start`, or after its merge is recorded,
142
+ # counts on that row. The cost added is the total less the one last seen, put
143
+ # with the newest turn read, or with the latest hand-off when none was read.
144
+ # A total below the last seen is a session whose count began again, and is
145
+ # added whole.
146
+ #
147
+ # A reading is saved in one transaction, and only when no other reading of
148
+ # the session was saved since this one began, by the count in sessions. So a
149
+ # run Claude Code cancels, or two at once, never count a turn twice, and the
150
+ # next run goes on from the bytes saved.
151
+ #
152
+ # Nothing is recorded without jq or sqlite3, with words that are not a
153
+ # space, a card ID, a phase and an account, with no session ID in the JSON,
154
+ # or when the cost file cannot be written.
155
+ # cost_record <status line JSON> <space> <card> <phase> <account>
156
+ cost_record() {
157
+ local json=$1 space=$2 card=$3 phase=$4 account=$5
158
+ command -v jq >/dev/null 2>&1 && have_sqlite || return 0
159
+ cost_space "$space" && [[ $card =~ $CARD_RE ]] || return 0
160
+ case $phase in write-up | build) ;; *) return 0 ;; esac
161
+ case $account in api | subscription) ;; *) return 0 ;; esac
162
+ card=$(printf '%s' "$card" | tr '[:lower:]' '[:upper:]')
163
+
164
+ # The session, its cost so far in millionths of a dollar, or nothing when
165
+ # the JSON has none, and its transcript.
166
+ local sep=$'\x1f' sid='' total='' transcript=''
167
+ IFS=$sep read -r sid total transcript <<< "$(jq -rn '[inputs] | last | select(type == "object")
168
+ | (.session_id | if type == "string" and test("^[A-Za-z0-9_.-]{1,128}$") then . else "" end) as $s
169
+ | (.cost | if type == "object" then .total_cost_usd else null end
170
+ | if type == "number" and . >= 0 and . < 1000000000 then . * 1000000 | round else "" end) as $c
171
+ | (.transcript_path | if type == "string" and (test("[[:cntrl:]]") | not) then . else "" end) as $t
172
+ | "\($s)\u001f\($c)\u001f\($t)"' <<< "$json" 2>/dev/null)"
173
+ [ -n "$sid" ] || return 0
174
+ case $total in *[!0-9]*) total='' ;; esac
175
+ case $transcript in /*) ;; *) transcript='' ;; esac
176
+ mkdir -p "$ENT_HOME" 2>/dev/null || return 0
177
+
178
+ # What the cost file holds of the session: how many readings were saved and
179
+ # the cost last seen, and how far each of its files was read.
180
+ local now state kind a b c readings='' seen=0
181
+ local paths=() bytes=() lasts=()
182
+ now=$(date -u +%Y-%m-%dT%H:%M:%SZ)
183
+ state=$(store -separator "$sep" "$COST_DB" "$COST_TABLES
184
+ select 's', readings, cost from sessions where id = $(sql_str "$sid");
185
+ select 'f', path, bytes, coalesce(last, '') from files where session = $(sql_str "$sid");") || return 0
186
+ while IFS=$sep read -r kind a b c; do
187
+ case $kind in
188
+ s) readings=$a seen=$b ;;
189
+ f) paths+=("$a"); bytes+=("$b"); lasts+=("$c") ;;
190
+ esac
191
+ done <<< "$state"
192
+ case $readings$seen in *[!0-9]*) return 0 ;; esac
193
+
194
+ # The session's transcript files: its own, and its subagents'.
195
+ local files=() f
196
+ if [ -n "$transcript" ]; then
197
+ files=("$transcript")
198
+ if [ "${transcript%.jsonl}" != "$transcript" ] && [ -d "${transcript%.jsonl}/subagents" ]; then
199
+ while IFS= read -r f; do
200
+ case $f in '' | *[[:cntrl:]]*) ;; *) files+=("$f") ;; esac
201
+ done <<< "$(find "${transcript%.jsonl}/subagents" -type f -name '*.jsonl' 2>/dev/null | LC_ALL=C sort)"
202
+ fi
203
+ fi
204
+
205
+ local sqlsid turns='' filed='' i size from last whole got
206
+ sqlsid=$(sql_str "$sid")
207
+ for f in ${files[@]+"${files[@]}"}; do
208
+ [ -f "$f" ] && [ -r "$f" ] || continue
209
+ size=$(wc -c < "$f" 2>/dev/null | tr -d '[:space:]')
210
+ case $size in '' | *[!0-9]*) continue ;; esac
211
+ from=0 last='' i=0
212
+ while [ "$i" -lt "${#paths[@]}" ]; do
213
+ if [ "${paths[$i]}" = "$f" ]; then
214
+ from=${bytes[$i]} last=${lasts[$i]}
215
+ break
216
+ fi
217
+ i=$((i + 1))
218
+ done
219
+ case $from in '' | *[!0-9]*) continue ;; esac
220
+ if [ -z "$readings" ] || [ "$size" -lt "$from" ]; then
221
+ # The first reading, or a file shorter than what was read of it, which
222
+ # is another file by now: it is read from its end on.
223
+ whole=$(cost_whole "$f" 0 "$size")
224
+ case $whole in '' | *[!0-9]*) continue ;; esac
225
+ last=$(cost_last "$f" "$whole")
226
+ [[ $last =~ $COST_ID ]] || last=''
227
+ from=0
228
+ else
229
+ whole=$(cost_whole "$f" "$from" "$((size - from))")
230
+ case $whole in '' | 0 | *[!0-9]*) continue ;; esac
231
+ got=$(tail -c +"$((from + 1))" "$f" 2>/dev/null | head -c "$whole" |
232
+ jq -rRn --arg id "$COST_ID" --arg last "$last" --arg now "$now" --arg q "'" "$COST_TURNS" 2>/dev/null)
233
+ # Without its last word, jq did not read every line: read them again
234
+ # next time.
235
+ [ "${got##*$'\n'}" = read ] || continue
236
+ got=${got%read}
237
+ got=${got%$'\n'}
238
+ last=${got%%$'\n'*}
239
+ [[ $last =~ $COST_ID ]] || last=''
240
+ case $got in *$'\n'*) turns="$turns${got#*$'\n'}"$'\n' ;; esac
241
+ fi
242
+ filed="$filed
243
+ insert into files (session, path, bytes, last)
244
+ select $sqlsid, $(sql_str "$f"), $((from + whole)), $(sql_str "$last") where exists (select 1 from ok)
245
+ on conflict (session, path) do update set bytes = excluded.bytes, last = excluded.last;"
246
+ done
247
+
248
+ # The cost to add, and the cost to remember.
249
+ local delta=0 cost=$seen
250
+ if [ -n "$total" ]; then
251
+ cost=$total
252
+ if [ -z "$readings" ]; then delta=0
253
+ elif [ "$total" -ge "$seen" ]; then delta=$((total - seen))
254
+ else delta=$total
255
+ fi
256
+ fi
257
+
258
+ # The hand-offs a turn of this agent can follow, and the one it follows:
259
+ # @ stands for the turn's time.
260
+ local attach='' hand allowed follows sqlnow guard session
261
+ hand='(select null as id, null as at, null as space, null as card, null as step, null as status, null as next where 0)'
262
+ if [ -f "$STORE" ]; then
263
+ attach=$(cost_attach "$STORE" h)
264
+ hand=h.handoffs
265
+ fi
266
+ if [ "$phase" = write-up ]; then allowed="x.step in ('new', 'define', 'plan', 'breakdown')"
267
+ else allowed="not (x.status = 'done' and coalesce(x.next, '') = 'merged')"
268
+ fi
269
+ follows="coalesce((select x.id from $hand x where x.space = $(sql_str "$space") and x.card = $(sql_str "$card")
270
+ and $allowed and x.at < @ order by x.at desc, x.id desc limit 1), 0)"
271
+ sqlnow=$(sql_str "$now")
272
+ if [ -z "$readings" ]; then
273
+ guard="not exists (select 1 from sessions where id = $sqlsid)"
274
+ session="insert into sessions (id, space, card, phase, transcript, first_at, last_at, cost, readings)
275
+ select $sqlsid, $(sql_str "$space"), $(sql_str "$card"), $(sql_str "$phase"), $(sql_str "$transcript"),
276
+ $sqlnow, $sqlnow, $cost, 1
277
+ where exists (select 1 from ok);"
278
+ else
279
+ guard="(select readings from sessions where id = $sqlsid) = $readings"
280
+ session="update sessions set last_at = $sqlnow, cost = $cost, readings = readings + 1,
281
+ transcript = coalesce($(sql_str "$transcript"), transcript)
282
+ where id = $sqlsid and exists (select 1 from ok);"
283
+ fi
284
+ # The statements go to sqlite3 on its stdin: a long reading's turns are too
285
+ # many for one argument. -bail stops at the first that fails, and the
286
+ # transaction it leaves open is never saved.
287
+ printf '%s\n' "$attach
288
+ begin immediate;
289
+ create temp table turns (id text, at text, input integer, output integer, cache_read integer, cache_write integer);
290
+ $turns
291
+ create temp table ok as select 1 as yes where $guard;
292
+ create temp table placed as select t.*, ${follows//@/t.at} as handoff from turns t;
293
+ insert into spent (session, handoff, day, account, input, output, cache_read, cache_write)
294
+ select $sqlsid, handoff, date('now', 'localtime'), '$account',
295
+ sum(input), sum(output), sum(cache_read), sum(cache_write)
296
+ from placed where exists (select 1 from ok) group by handoff
297
+ on conflict (session, handoff, day, account) do update set
298
+ input = input + excluded.input, output = output + excluded.output,
299
+ cache_read = cache_read + excluded.cache_read, cache_write = cache_write + excluded.cache_write;
300
+ insert into spent (session, handoff, day, account, cost)
301
+ select $sqlsid, coalesce((select handoff from placed order by at desc, rowid desc limit 1), ${follows//@/$sqlnow}),
302
+ date('now', 'localtime'), '$account', $delta
303
+ where $delta <> 0 and exists (select 1 from ok)
304
+ on conflict (session, handoff, day, account) do update set cost = cost + excluded.cost;
305
+ $filed
306
+ $session
307
+ commit;" | store -bail "$COST_DB" >/dev/null || return 0
308
+ }
309
+
310
+ # --- the figures beside the log's rows ----------------------------------------
311
+
312
+ # SQL for a count of tokens as text with room for little: 950, 42k, 1.2M,
313
+ # 3.4B. @ stands for the count.
314
+ sql_tokens() {
315
+ local t="case when @ < 1000 then cast(@ as text)
316
+ when @ < 999500 then cast(round(@ / 1000.0) as integer) || 'k'
317
+ when @ < 999950000 then printf('%.1f', @ / 1000000.0) || 'M'
318
+ else printf('%.1f', @ / 1000000000.0) || 'B' end"
319
+ printf '%s' "${t//@/$1}"
320
+ }
321
+
322
+ # SQL for millionths of a dollar as dollars and cents: $1.09. @ stands for
323
+ # the millionths.
324
+ sql_dollars() {
325
+ local t="'\$' || printf('%.2f', @ / 1000000.0)"
326
+ printf '%s' "${t//@/$1}"
327
+ }
328
+
329
+ # SQL that goes on from the log's view (log_view, in handoff.sh) of the space
330
+ # $1, after its table shown, and adds the table told: what the agents used,
331
+ # for each row of the log, for the step each card is in, and for each card.
332
+ # $2 is 1 when the cost file is attached as c, and 0 when there is none to
333
+ # read, which leaves every row not recorded.
334
+ #
335
+ # part 0 a row of the log, by its id. Its figures are those of the turns
336
+ # that follow the row before it, so they are the step's that the
337
+ # row ended.
338
+ # part 1 the step the card is in: the turns that follow its latest row,
339
+ # under that row's id. A card that has merged has none.
340
+ # part 2 the card: the rows' figures and the step's it is in, added.
341
+ # missing is how many of those are not recorded.
342
+ #
343
+ # A row's figures are recorded when a session of its phase, build for the
344
+ # build, review and pr rows and write-up for the define, plan and breakdown
345
+ # rows, had its first reading in the row's run and no later than the row. A
346
+ # new or start row goes by the row after it, so by the write-up's session and
347
+ # the build's, and the step the card is in by any session of its phase in
348
+ # the run. What is not recorded has null in tokens and cost, never 0, and
349
+ # adds nothing to its card's total.
350
+ #
351
+ # tokens and cost are JSON, as `task log --json` gives them:
352
+ # {"total", "input", "output", "cache_read", "cache_write", "cache_share",
353
+ # "short", "text"}: total is the four added, cache_share is cache read
354
+ # over all that went in, input, cache read and cache write, from 0 to 1,
355
+ # short is as 420k, and text as 378k in (88% from cache), 42k out
356
+ # {"usd", "spent", "kind", "text"}: spent is the part of usd from sessions
357
+ # on an API key, and kind says which cost it is: api-prices, what the
358
+ # work would cost at API prices, not money paid; spend, on a key; or
359
+ # both. What used nothing says what its card's sessions say.
360
+ # line is the two texts, as the plain log gives them.
361
+ cost_view() {
362
+ local space on=$2
363
+ space=$(sql_str "$1")
364
+ if [ "$on" = 1 ]; then
365
+ printf '%s' ", sess as (select id, card, phase, first_at from c.sessions where space = $space),
366
+ used as (
367
+ select s.card as card, p.handoff as handoff, sum(p.input) as input, sum(p.output) as output,
368
+ sum(p.cache_read) as cache_read, sum(p.cache_write) as cache_write, sum(p.cost) as cost,
369
+ sum(case when p.account = 'api' then p.cost else 0 end) as api,
370
+ max(p.account = 'api') as on_api, max(p.account <> 'api') as on_sub
371
+ from c.spent p join c.sessions s on s.id = p.session where s.space = $space
372
+ group by s.card, p.handoff)"
373
+ else
374
+ printf '%s' ", sess (id, card, phase, first_at) as (select null, null, null, null where 0),
375
+ used (card, handoff, input, output, cache_read, cache_write, cost, api, on_api, on_sub) as (
376
+ select null, null, null, null, null, null, null, null, null, null where 0)"
377
+ fi
378
+ printf '%s' ", accounts as (select card, max(on_api) as on_api, max(on_sub) as on_sub from used group by card),
379
+ spans as (
380
+ select id, at, card, step, status, next, after, prev,
381
+ min(at) over (partition by card, run) as run_at,
382
+ lead(at) over (partition by card order by id) as next_at
383
+ from shown),
384
+ phased as (
385
+ select *,
386
+ case when step in ('new', 'define', 'plan', 'breakdown') then 'write-up'
387
+ when step in ('start', 'build', 'review', 'pr') then 'build' end as phase,
388
+ case when step in ('new', 'start') then next_at else at end as until,
389
+ case when status = 'done' and next is not null then next else step end as stands
390
+ from spans),
391
+ units as (
392
+ select p.card as card, p.id as id, 0 as part, p.step as step,
393
+ exists (select 1 from sess s where s.card = p.card and s.phase = p.phase
394
+ and s.first_at >= p.run_at and (p.until is null or s.first_at <= p.until)) as recorded,
395
+ coalesce(u.input, 0) as input, coalesce(u.output, 0) as output,
396
+ coalesce(u.cache_read, 0) as cache_read, coalesce(u.cache_write, 0) as cache_write,
397
+ coalesce(u.cost, 0) as cost, coalesce(u.api, 0) as api,
398
+ coalesce(u.on_api, 0) as on_api, coalesce(u.on_sub, 0) as on_sub
399
+ from phased p left join used u on u.card = p.card and u.handoff = p.prev
400
+ union all
401
+ select p.card, p.id, 1, p.stands,
402
+ exists (select 1 from sess s where s.card = p.card and s.first_at >= p.run_at
403
+ and s.phase = case when p.stands in ('build', 'review', 'pr') then 'build' else 'write-up' end),
404
+ coalesce(u.input, 0), coalesce(u.output, 0), coalesce(u.cache_read, 0), coalesce(u.cache_write, 0),
405
+ coalesce(u.cost, 0), coalesce(u.api, 0), coalesce(u.on_api, 0), coalesce(u.on_sub, 0)
406
+ from phased p left join used u on u.card = p.card and u.handoff = p.id
407
+ where p.after is null and not (p.status = 'done' and coalesce(p.next, '') = 'merged')),
408
+ sums as (
409
+ select card, id, part, step, recorded, input, output, cache_read, cache_write, cost, api, on_api, on_sub,
410
+ 0 as missing
411
+ from units
412
+ union all
413
+ select card, null, 2, null, max(recorded),
414
+ sum(case when recorded then input else 0 end), sum(case when recorded then output else 0 end),
415
+ sum(case when recorded then cache_read else 0 end), sum(case when recorded then cache_write else 0 end),
416
+ sum(case when recorded then cost else 0 end), sum(case when recorded then api else 0 end),
417
+ max(case when recorded then on_api else 0 end), max(case when recorded then on_sub else 0 end),
418
+ sum(not recorded)
419
+ from units group by card),
420
+ sized as (
421
+ select s.*, s.input + s.output + s.cache_read + s.cache_write as total,
422
+ s.input + s.cache_read + s.cache_write as went_in,
423
+ case when s.on_api and s.on_sub then 'both' when s.on_api then 'spend' when s.on_sub then 'api-prices'
424
+ when a.on_api and not a.on_sub then 'spend' else 'api-prices' end as kind
425
+ from sums s left join accounts a on a.card = s.card),
426
+ worded as (
427
+ select *,
428
+ $(sql_tokens went_in) || ' in ('
429
+ || cast(round(case when went_in > 0 then cache_read * 100.0 / went_in else 0 end) as integer)
430
+ || '% from cache), ' || $(sql_tokens output) || ' out' as tokens_text,
431
+ case kind when 'spend' then $(sql_dollars cost) || ' spent on the API key'
432
+ when 'both' then '≈' || $(sql_dollars cost) || ' at API prices, ' || $(sql_dollars api)
433
+ || ' of it spent on the API key'
434
+ else '≈' || $(sql_dollars cost) || ' at API prices' end as cost_text
435
+ from sized),
436
+ told as (
437
+ select card, id, part, step, recorded, missing, total,
438
+ case when recorded then json_object('total', total, 'input', input, 'output', output,
439
+ 'cache_read', cache_read, 'cache_write', cache_write,
440
+ 'cache_share', case when went_in > 0 then round(cache_read * 1.0 / went_in, 4) else 0 end,
441
+ 'short', $(sql_tokens total), 'text', tokens_text) end as tokens,
442
+ case when recorded then json_object('usd', cost / 1000000.0, 'spent', api / 1000000.0,
443
+ 'kind', kind, 'text', cost_text) end as cost,
444
+ $(sql_tokens total) as short, cost_text,
445
+ case when recorded then tokens_text || ', ' || cost_text else 'not recorded' end as line
446
+ from worded)"
447
+ }
448
+
449
+ # What the agents ocnus started on an Anthropic API key have spent, as one
450
+ # line of JSON, for `usage` with billing on api:
451
+ # {"today": {"usd", "text", "top": {"space", "card", "usd", "text"} | null},
452
+ # "week": {"usd", "text", "from", "cards", "merged"}}
453
+ # today is from midnight and week from Monday at midnight, in this machine's
454
+ # time, by the day each reading was saved on. top is the card that has spent
455
+ # the most today, null with nothing spent today. from is Monday's date, cards
456
+ # how many cards the week's spend is for, and merged how many of those have
457
+ # merged: their latest hand-off is done with merged next. Work done on the
458
+ # subscription is in none of it. With no cost file nothing was spent. It
459
+ # fails, and prints nothing, when sqlite3 is not installed or the cost file
460
+ # cannot be read.
461
+ cost_spend() {
462
+ have_sqlite || return 1
463
+ local attach='' spent sessions hand
464
+ spent='(select null as session, null as day, null as account, null as cost where 0)'
465
+ sessions='(select null as id, null as space, null as card where 0)'
466
+ hand='(select null as id, null as space, null as card, null as status, null as next where 0)'
467
+ if [ -f "$COST_DB" ]; then
468
+ attach=$(cost_attach "$COST_DB" c)
469
+ spent=c.spent sessions=c.sessions
470
+ fi
471
+ if [ -f "$STORE" ]; then
472
+ attach="$attach $(cost_attach "$STORE" h)"
473
+ hand=h.handoffs
474
+ fi
475
+ store :memory: "$attach
476
+ with days as (select date('now', 'localtime') as today,
477
+ date('now', 'localtime', 'weekday 0', '-6 days') as monday),
478
+ api as (
479
+ select s.space as space, s.card as card, p.day as day, sum(p.cost) as cost
480
+ from $spent p join $sessions s on s.id = p.session where p.account = 'api'
481
+ group by s.space, s.card, p.day),
482
+ by_day as (
483
+ select space, card, sum(cost) as cost from api, days where day = today
484
+ group by space, card having sum(cost) > 0),
485
+ by_week as (
486
+ select space, card, sum(cost) as cost from api, days where day >= monday
487
+ group by space, card having sum(cost) > 0)
488
+ select json_object(
489
+ 'today', json_object('usd', (select coalesce(sum(cost), 0) from by_day) / 1000000.0,
490
+ 'text', $(sql_dollars '(select coalesce(sum(cost), 0) from by_day)'),
491
+ 'top', json((select json_object('space', space, 'card', card, 'usd', cost / 1000000.0,
492
+ 'text', $(sql_dollars cost))
493
+ from by_day order by cost desc, space, card limit 1))),
494
+ 'week', json_object('usd', (select coalesce(sum(cost), 0) from by_week) / 1000000.0,
495
+ 'text', $(sql_dollars '(select coalesce(sum(cost), 0) from by_week)'),
496
+ 'from', (select monday from days), 'cards', (select count(*) from by_week),
497
+ 'merged', (select count(*) from by_week w where coalesce((
498
+ select x.status = 'done' and coalesce(x.next, '') = 'merged' from $hand x
499
+ where x.space = w.space and x.card = w.card order by x.id desc limit 1), 0))));"
500
+ }
package/cli/lib/github.sh CHANGED
@@ -23,6 +23,14 @@
23
23
  #
24
24
  # `gh search prs` asks across repos too, but it cannot say whether an open
25
25
  # pull request is in conflict.
26
+ #
27
+ # `task answer` merges a card's pull requests here too, when the human
28
+ # answers its merge with merge (asks.sh). One call of the same shape asks
29
+ # what the merge of each needs (github_mergeable): whether GitHub would merge
30
+ # it as it stands, the commit at its head, and the method GitHub's merge
31
+ # button would use for the human in its repo. Then one mutation merges each
32
+ # (github_merge), by that method and only at that commit. Nothing else here
33
+ # changes anything on GitHub, and nothing turns on auto-merge.
26
34
 
27
35
  # The most worktrees one call asks about. More are asked about in calls of
28
36
  # this many, so the common case stays one call.
@@ -62,7 +70,11 @@ github_repo() {
62
70
  # pull request's checks alone, as when gh's token may not read them, fails
63
71
  # nothing: the pull request is read without them, so an open one is open,
64
72
  # never ready, and a merged one is still merged. An answer that is empty, or
65
- # holds no data, is an error, so that the whole call counts as failed.
73
+ # holds no data, is an error, so that the whole call counts as failed. With
74
+ # $merge, the answer is github_mergeable's, and an open pull request's line
75
+ # is open, then GitHub's mergeStateStatus for it, the repo's
76
+ # viewerDefaultMergeMethod, the pull request's id, the commit at its head,
77
+ # and its URL: never ready or conflict, which mergeStateStatus says better.
66
78
  GITHUB_READ='input
67
79
  | if (.data | type) != "object" then error("no data") else . end
68
80
  | . as $all
@@ -78,6 +90,8 @@ GITHUB_READ='input
78
90
  | if $pr == null then "none"
79
91
  elif $pr.state == "MERGED" then "merged \($pr.url)"
80
92
  elif $pr.state == "CLOSED" then "closed \($pr.url)"
93
+ elif $merge then
94
+ "open \($pr.mergeStateStatus // "UNKNOWN") \($repo.viewerDefaultMergeMethod // "MERGE") \($pr.id // "-") \($pr.headRefOid // "-") \($pr.url)"
81
95
  elif $pr.state == "OPEN" and $pr.mergeable == "CONFLICTING" then "conflict \($pr.url)"
82
96
  elif $pr.state == "OPEN" and $pr.mergeable == "MERGEABLE" and ($unchecked | not)
83
97
  and ($pr.statusCheckRollup == null or $pr.statusCheckRollup.state == "SUCCESS") then "ready \($pr.url)"
@@ -108,10 +122,11 @@ GITHUB_CALL_WHY=''
108
122
  # no sign-in (gh help exit-codes), and names HTTP 401 when GitHub refuses its
109
123
  # token. A repo that GitHub answers with an error fails only its own lines,
110
124
  # with GitHub's words, and a worktree whose origin is not on GitHub is not
111
- # asked about.
112
- # github_pulls <a folder for gh's answers>
125
+ # asked about. With merge, it asks what github_mergeable does instead.
126
+ # github_pulls <a folder for gh's answers> [merge]
113
127
  github_pulls() {
114
- local scratch=$1 sep=$'\x1f' key wt branch keys=() wts=() lines=() asks=() i n
128
+ local scratch=$1 merge=false sep=$'\x1f' key wt branch keys=() wts=() lines=() asks=() i n
129
+ [ "${2:-}" != merge ] || merge=true
115
130
  GITHUB_SIGN_IN=0 GITHUB_CALL_WHY=''
116
131
  while IFS=$sep read -r key wt branch; do
117
132
  [ -n "$key" ] || continue
@@ -125,7 +140,7 @@ github_pulls() {
125
140
  done
126
141
  [ "${#keys[@]}" -gt 0 ] || return 0
127
142
  for ((n = 0; n < ${#asks[@]}; n += GITHUB_BATCH)); do
128
- github_ask "$scratch" "${asks[@]:n:GITHUB_BATCH}"
143
+ github_ask "$scratch" "$merge" "${asks[@]:n:GITHUB_BATCH}"
129
144
  done
130
145
  for ((i = 0; i < ${#keys[@]}; i++)); do
131
146
  printf '%s %s\n' "${keys[i]}" "${lines[i]}"
@@ -139,17 +154,21 @@ github_pulls() {
139
154
  # variables, so that nothing in them is read as GraphQL. It sets
140
155
  # github_pulls's line for each, in its lines, reading its wts for the
141
156
  # worktree's folder, and GITHUB_SIGN_IN and GITHUB_CALL_WHY when the call
142
- # fails as a whole.
143
- # github_ask <a folder for gh's answers> <ask>...
157
+ # fails as a whole. The second argument is true for github_mergeable's call,
158
+ # which asks of each pull request what its merge needs, and of each repo the
159
+ # method GitHub's merge button would use for the human.
160
+ # github_ask <a folder for gh's answers> <true|false> <ask>...
144
161
  github_ask() {
145
- local scratch=$1 sep=$'\x1f' ask i owner name branch n=0 at=() args=() vars='' body='' code=0 why answer line
146
- shift
162
+ local scratch=$1 merge=$2 sep=$'\x1f' ask i owner name branch n=0 at=() args=() vars='' body='' code=0 why answer line
163
+ local fields='nodes { url state mergeable statusCheckRollup { state } } }'
164
+ [ "$merge" != true ] || fields='nodes { id url state mergeStateStatus headRefOid } } viewerDefaultMergeMethod'
165
+ shift 2
147
166
  for ask in "$@"; do
148
167
  IFS=$sep read -r i owner name branch <<< "$ask"
149
168
  at+=("$i")
150
169
  lines[i]="failed ${wts[i]##*/}: its answer could not be read"
151
170
  vars="$vars, \$o$n: String!, \$n$n: String!, \$b$n: String!"
152
- body="$body p$n: repository(owner: \$o$n, name: \$n$n) { pullRequests(headRefName: \$b$n, states: [OPEN, CLOSED, MERGED], first: 1, orderBy: {field: CREATED_AT, direction: DESC}) { nodes { url state mergeable statusCheckRollup { state } } } }"
171
+ body="$body p$n: repository(owner: \$o$n, name: \$n$n) { pullRequests(headRefName: \$b$n, states: [OPEN, CLOSED, MERGED], first: 1, orderBy: {field: CREATED_AT, direction: DESC}) { $fields }"
153
172
  args+=(-f "o$n=$owner" -f "n$n=$name" -f "b$n=$branch")
154
173
  n=$((n + 1))
155
174
  done
@@ -157,7 +176,7 @@ github_ask() {
157
176
  # then exits 1, so the answer is read whatever gh exits with.
158
177
  gh api graphql -f "query=query(${vars#, }) {$body }" "${args[@]}" > "$scratch/answer" 2> "$scratch/err" ||
159
178
  code=$?
160
- if answer=$(jq -rn --argjson n "$n" "$GITHUB_READ" "$scratch/answer" 2>/dev/null); then
179
+ if answer=$(jq -rn --argjson n "$n" --argjson merge "$merge" "$GITHUB_READ" "$scratch/answer" 2>/dev/null); then
161
180
  n=0
162
181
  while IFS= read -r line; do
163
182
  [ "$n" -lt "${#at[@]}" ] || break
@@ -176,3 +195,48 @@ github_ask() {
176
195
  [ -n "$GITHUB_CALL_WHY" ] || GITHUB_CALL_WHY=${why:-gh failed}
177
196
  for i in "${at[@]}"; do lines[i]="failed ${wts[i]##*/}: ${why:-gh failed}"; done
178
197
  }
198
+
199
+ # Ask GitHub what the merge of each branch's newest pull request needs, in
200
+ # one call, as github_pulls asks for each one's state: the same lines on
201
+ # stdin, and the same lines printed, but for an open pull request, whose line
202
+ # is:
203
+ # <key> open <mergeStateStatus> <method> <id> <head commit> <URL>
204
+ # mergeStateStatus is GitHub's word for whether it would merge it as it
205
+ # stands: CLEAN, or HAS_HOOKS or UNSTABLE, which it merges too, or why not,
206
+ # as DIRTY for a conflict, BLOCKED for a required check or review, BEHIND,
207
+ # DRAFT, or UNKNOWN while it works that out. The method is the repo's
208
+ # viewerDefaultMergeMethod, the one GitHub's merge button would use for the
209
+ # human: MERGE, SQUASH or REBASE.
210
+ # github_mergeable <a folder for gh's answers>
211
+ github_mergeable() { github_pulls "$1" merge; }
212
+
213
+ # Merge one pull request, as GitHub's merge button does: by the method given,
214
+ # and only while the commit at its head is still the one given, so that a
215
+ # push since github_mergeable asked is not merged unseen. The id, the method
216
+ # and the commit are passed as variables, so that nothing in them is read as
217
+ # GraphQL. It succeeds only when GitHub answers that the pull request has
218
+ # merged. Else it fails, with why in GITHUB_MERGE_WHY: GitHub's own words
219
+ # when it refuses, as for a required check that has not passed, or gh's when
220
+ # the call fails. GitHub is asked for the merge as it stands and no more:
221
+ # nothing is forced past what protects the branch, and no auto-merge is
222
+ # turned on.
223
+ # github_merge <a folder for gh's answers> <the pull request's id> <MERGE|SQUASH|REBASE> <head commit>
224
+ GITHUB_MERGE_WHY=''
225
+ github_merge() {
226
+ local scratch=$1 state why
227
+ GITHUB_MERGE_WHY=''
228
+ # gh prints GitHub's answer even when it refuses, and then exits 1, so the
229
+ # answer is read whatever gh exits with.
230
+ gh api graphql \
231
+ -f 'query=mutation($id: ID!, $method: PullRequestMergeMethod!, $oid: GitObjectID!) { mergePullRequest(input: {pullRequestId: $id, mergeMethod: $method, expectedHeadOid: $oid}) { pullRequest { url state } } }' \
232
+ -f "id=$2" -f "method=$3" -f "oid=$4" > "$scratch/merged" 2> "$scratch/err" || true
233
+ state=$(jq -r '.data.mergePullRequest.pullRequest.state // empty' "$scratch/merged" 2>/dev/null) || state=''
234
+ [ "$state" != MERGED ] || return 0
235
+ why=$(jq -r '[.errors[]?.message | strings] | first // empty' "$scratch/merged" 2>/dev/null) || why=''
236
+ [ -n "$why" ] || why=$(sed -n '/[^[:space:]]/{p;q;}' "$scratch/err" 2>/dev/null) || why=''
237
+ [ -z "$state" ] ||
238
+ why="GitHub took the merge, but the pull request is still $state, as in a repo that merges through a queue"
239
+ why=${why//[[:cntrl:]]/ }
240
+ GITHUB_MERGE_WHY=${why:-gh failed}
241
+ return 1
242
+ }