@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
@@ -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/finish.sh CHANGED
@@ -11,7 +11,8 @@
11
11
  # - commits on the branch that are not in the remote's default branch, even
12
12
  # pushed ones, such as a fix pushed after the pull request merged;
13
13
  # - ignored files that the repo's setup does not make again (setup_makes,
14
- # in recipes.sh), which `git worktree remove` deletes without a word;
14
+ # in recipes.sh), which `git worktree remove` deletes without a word,
15
+ # other than what gpui-shell writes into a mod's folder (gpui_shells);
15
16
  # - anything in the task folder outside its worktrees.
16
17
  # scripts/after-merge makes the same checks for Claude Code's own worktrees.
17
18
  # A task that would lose work is still removed by hand.
@@ -19,6 +20,28 @@
19
20
  # Lines on stdin, indented under a heading: at most 20, then how many more.
20
21
  listed() { awk 'NR <= 20 { print " " $0 } END { if (NR > 20) print " and " NR - 20 " more" }'; }
21
22
 
23
+ # Print the lines on stdin, paths in the worktree $1, that are not what
24
+ # gpui-shell wrote. gpui-shell, which runs Herdr's mods, writes two files into
25
+ # the folder of each mod it runs, in any repo and whatever its setup says:
26
+ # gpui-kit.d.ts, which it rewrites on every run, and jsconfig.json, which it
27
+ # writes once, when there is none, and which is then the user's. So any
28
+ # gpui-kit.d.ts goes, but a jsconfig.json goes only while it is still
29
+ # gpui-shell's: it says it was written by gpui-shell, and a gpui-kit.d.ts is
30
+ # beside it. A jsconfig.json of the repo's own is still work.
31
+ gpui_shells() {
32
+ local wt=$1 f
33
+ while IFS= read -r f; do
34
+ case /$f in
35
+ */gpui-kit.d.ts) continue ;;
36
+ */jsconfig.json)
37
+ [ -f "$wt/${f%jsconfig.json}gpui-kit.d.ts" ] &&
38
+ grep -qF 'Written once by gpui-shell' "$wt/$f" 2>/dev/null && continue
39
+ ;;
40
+ esac
41
+ printf '%s\n' "$f"
42
+ done
43
+ }
44
+
22
45
  # Print the folder of a card's task, or stop when it has none on this
23
46
  # machine: tasks/<card>-<short name>, or tasks/<card> for a title with no
24
47
  # plain words, as `task build` finds it. Linear is not asked.
@@ -118,8 +141,10 @@ check_worktree() {
118
141
  fi
119
142
 
120
143
  # Ignored files, file by file: each counts as work unless it is, or is in,
121
- # something the patterns that setup_makes prints match. git quotes an odd
122
- # name the same way in both lists, so they can be compared line by line.
144
+ # something the patterns that setup_makes prints match, or is what
145
+ # gpui-shell wrote (gpui_shells). git quotes an odd name the same way in
146
+ # both lists, so they can be compared line by line; a quoted name is never
147
+ # taken for gpui-shell's, so it counts as work.
123
148
  if ! git -C "$wt" ls-files --others --ignored --exclude-standard > "$scratch/ignored" 2>/dev/null; then
124
149
  add_problem " git could not list its ignored files, so what removing it would lose is not known"
125
150
  elif [ -s "$scratch/ignored" ]; then
@@ -130,7 +155,8 @@ check_worktree() {
130
155
  else
131
156
  why=$(head -n 1 "$scratch/why"); : > "$scratch/made"
132
157
  fi
133
- out=$(awk 'FILENAME == ARGV[1] { made[$0]; next } !($0 in made)' "$scratch/made" "$scratch/ignored")
158
+ out=$(awk 'FILENAME == ARGV[1] { made[$0]; next } !($0 in made)' "$scratch/made" "$scratch/ignored" |
159
+ gpui_shells "$wt")
134
160
  if [ -n "$out" ]; then
135
161
  if [ -n "$why" ]; then add_problem " ignored files, all of them counted as work since $why:"
136
162
  else add_problem " ignored files that its setup does not make again:"