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

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 +518 -98
  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 +340 -384
  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 +274 -76
  23. package/herdr/README.md +930 -232
  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/github.sh CHANGED
@@ -8,15 +8,29 @@
8
8
  # GitHub is asked once a minute, however many cards wait, in however many
9
9
  # spaces and repos. The call names each worktree's repo, from its origin
10
10
  # (github_repo), and its branch, and asks for that branch's newest pull
11
- # request. Its answer is read by these rules (GITHUB_READ): only the newest
12
- # pull request counts, an open one that GitHub says conflicts with its
13
- # default branch is conflict, and one whose mergeable is still UNKNOWN,
14
- # while GitHub works that out, is open. Asking
15
- # GitHub sits here alone, so that another host, such as GitLab, can sit
16
- # beside it later.
11
+ # request, with whether it can be merged and what its checks came to. Its
12
+ # answer is read by these rules (GITHUB_READ): only the newest pull request
13
+ # counts, an open one that GitHub says conflicts with its default branch is
14
+ # conflict, and one whose mergeable is still UNKNOWN, while GitHub works
15
+ # that out, is open. An open one is ready to merge, ready, when GitHub says
16
+ # that it can be merged, MERGEABLE, and that every check on its newest
17
+ # commit passed: its statusCheckRollup, which sums up its check runs and
18
+ # commit statuses, is SUCCESS, or null, as for a pull request with no
19
+ # checks. It is open while a check is pending, and once one has failed. A
20
+ # review that the repo's rules ask for is not a check, so ready does not say
21
+ # that GitHub would let it merge. Asking GitHub sits here alone, so that
22
+ # another host, such as GitLab, can sit beside it later.
17
23
  #
18
24
  # `gh search prs` asks across repos too, but it cannot say whether an open
19
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.
20
34
 
21
35
  # The most worktrees one call asks about. More are asked about in calls of
22
36
  # this many, so the common case stays one call.
@@ -47,18 +61,28 @@ github_repo() {
47
61
  }
48
62
 
49
63
  # GitHub's answer to github_ask's call, read as one line for each branch it
50
- # asked about, p0 to p<$n - 1>, in order: merged, open, closed or conflict,
51
- # then the pull request's URL; none when the branch has none; or failed and
52
- # GitHub's words when it answered that repo with an error, such as one it
53
- # cannot find. A closed pull request is closed, whatever GitHub says of its
54
- # conflicts. An answer that is empty, or holds no data, is an error, so that
55
- # the whole call counts as failed.
64
+ # asked about, p0 to p<$n - 1>, in order: merged, ready, open, closed or
65
+ # conflict, then the pull request's URL; none when the branch has none; or
66
+ # failed and GitHub's words when it answered that repo with an error, such
67
+ # as one it cannot find. A closed pull request is closed, whatever GitHub
68
+ # says of its conflicts, and an open one is ready only when it can be merged
69
+ # and its checks passed, or it has none. An error that GitHub gives for a
70
+ # pull request's checks alone, as when gh's token may not read them, fails
71
+ # nothing: the pull request is read without them, so an open one is open,
72
+ # never ready, and a merged one is still merged. An answer that is empty, or
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.
56
78
  GITHUB_READ='input
57
79
  | if (.data | type) != "object" then error("no data") else . end
58
80
  | . as $all
59
81
  | ($all.errors // []) as $errors
60
82
  | range(0; $n) | "p\(.)" as $alias
61
- | ([$errors[] | select((.path // [])[0] == $alias) | .message] | first) as $own
83
+ | [$errors[] | select((.path // [])[0] == $alias)] as $mine
84
+ | ([$mine[] | select(any(.path[]; . == "statusCheckRollup") | not) | .message] | first) as $own
85
+ | any($mine[]; any(.path[]; . == "statusCheckRollup")) as $unchecked
62
86
  | $all.data[$alias] as $repo
63
87
  | if $own != null then "failed \($own)"
64
88
  elif $repo == null then "failed \(([$errors[] | .message] | first) // "GitHub gave no answer for it")"
@@ -66,7 +90,11 @@ GITHUB_READ='input
66
90
  | if $pr == null then "none"
67
91
  elif $pr.state == "MERGED" then "merged \($pr.url)"
68
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)"
69
95
  elif $pr.state == "OPEN" and $pr.mergeable == "CONFLICTING" then "conflict \($pr.url)"
96
+ elif $pr.state == "OPEN" and $pr.mergeable == "MERGEABLE" and ($unchecked | not)
97
+ and ($pr.statusCheckRollup == null or $pr.statusCheckRollup.state == "SUCCESS") then "ready \($pr.url)"
70
98
  else "open \($pr.url)" end
71
99
  end
72
100
  | split("\r") | join(" ") | split("\n") | join(" ")'
@@ -83,19 +111,22 @@ GITHUB_CALL_WHY=''
83
111
  # or in calls of GITHUB_BATCH when more are given. Each line on stdin is a
84
112
  # key, which holds no space, the worktree, and its branch, with the unit
85
113
  # separator between them. It prints a line for each, in the same order:
86
- # <key> merged|open|closed|conflict <the pull request's URL>
114
+ # <key> merged|ready|open|closed|conflict <the pull request's URL>
87
115
  # <key> none the branch has no pull request
88
116
  # <key> failed <the worktree's folder>: <why>
89
- # A call that fails as a whole, such as with GitHub out of reach, fails
90
- # every line it asked about, with gh's words, which GITHUB_CALL_WHY keeps.
117
+ # ready is an open pull request that can be merged and whose checks passed
118
+ # (GITHUB_READ). A call that fails as a whole, such as with GitHub out of
119
+ # reach, fails every line it asked about, with gh's words, which
120
+ # GITHUB_CALL_WHY keeps.
91
121
  # GITHUB_SIGN_IN is 1 then when gh needs signing in: it exits 4 when it has
92
122
  # no sign-in (gh help exit-codes), and names HTTP 401 when GitHub refuses its
93
123
  # token. A repo that GitHub answers with an error fails only its own lines,
94
124
  # with GitHub's words, and a worktree whose origin is not on GitHub is not
95
- # asked about.
96
- # 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]
97
127
  github_pulls() {
98
- 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
99
130
  GITHUB_SIGN_IN=0 GITHUB_CALL_WHY=''
100
131
  while IFS=$sep read -r key wt branch; do
101
132
  [ -n "$key" ] || continue
@@ -109,7 +140,7 @@ github_pulls() {
109
140
  done
110
141
  [ "${#keys[@]}" -gt 0 ] || return 0
111
142
  for ((n = 0; n < ${#asks[@]}; n += GITHUB_BATCH)); do
112
- github_ask "$scratch" "${asks[@]:n:GITHUB_BATCH}"
143
+ github_ask "$scratch" "$merge" "${asks[@]:n:GITHUB_BATCH}"
113
144
  done
114
145
  for ((i = 0; i < ${#keys[@]}; i++)); do
115
146
  printf '%s %s\n' "${keys[i]}" "${lines[i]}"
@@ -123,17 +154,21 @@ github_pulls() {
123
154
  # variables, so that nothing in them is read as GraphQL. It sets
124
155
  # github_pulls's line for each, in its lines, reading its wts for the
125
156
  # worktree's folder, and GITHUB_SIGN_IN and GITHUB_CALL_WHY when the call
126
- # fails as a whole.
127
- # 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>...
128
161
  github_ask() {
129
- local scratch=$1 sep=$'\x1f' ask i owner name branch n=0 at=() args=() vars='' body='' code=0 why answer line
130
- 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
131
166
  for ask in "$@"; do
132
167
  IFS=$sep read -r i owner name branch <<< "$ask"
133
168
  at+=("$i")
134
169
  lines[i]="failed ${wts[i]##*/}: its answer could not be read"
135
170
  vars="$vars, \$o$n: String!, \$n$n: String!, \$b$n: String!"
136
- 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 } } }"
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 }"
137
172
  args+=(-f "o$n=$owner" -f "n$n=$name" -f "b$n=$branch")
138
173
  n=$((n + 1))
139
174
  done
@@ -141,7 +176,7 @@ github_ask() {
141
176
  # then exits 1, so the answer is read whatever gh exits with.
142
177
  gh api graphql -f "query=query(${vars#, }) {$body }" "${args[@]}" > "$scratch/answer" 2> "$scratch/err" ||
143
178
  code=$?
144
- 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
145
180
  n=0
146
181
  while IFS= read -r line; do
147
182
  [ "$n" -lt "${#at[@]}" ] || break
@@ -160,3 +195,48 @@ github_ask() {
160
195
  [ -n "$GITHUB_CALL_WHY" ] || GITHUB_CALL_WHY=${why:-gh failed}
161
196
  for i in "${at[@]}"; do lines[i]="failed ${wts[i]##*/}: ${why:-gh failed}"; done
162
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
+ }
package/cli/lib/guard.sh CHANGED
@@ -33,24 +33,45 @@ is_worktree_copy() {
33
33
  # read. Each of these leaves the machine as it was, the hand-off store
34
34
  # included; `task ls` asks Linear, and only reads. `task merges` asks
35
35
  # GitHub, but it records the merges it sees and moves their cards in Linear,
36
- # so it is not a read and is not here.
36
+ # so it is not a read and is not here. `task asks` reads the questions that
37
+ # wait on the human, from the store, the files beside it and hc. `task
38
+ # answer` types into an agent's terminal or merges pull requests on GitHub,
39
+ # and `task hold`, the hook behind a permission prompt, writes its question
40
+ # and can allow a tool, so neither is a read. Nor is `task brief`, though it
41
+ # leaves the agent and its card alone: a new brief is a model call, paid for
42
+ # on the human's account, and it writes the brief it keeps into the store.
37
43
  # `profile ls` reads the settings file; `profile set` changes it,
38
44
  # and the review subagents in Claude Code's agents folder. `linear archive`
39
45
  # alone, or with --json, reads whether archiving is on; with on or off it
40
46
  # changes the settings file. `tests` alone, or with --json, reads how the
41
47
  # test runs use the processors; with share or queue it changes the settings
42
- # file too.
48
+ # file too. `tests ls`, alone or with --json, reads the test runs going from
49
+ # the pool test/run.sh keeps, and removes nothing from it, not even an entry
50
+ # whose process has gone.
43
51
  # `approval` alone, or with --json, reads whether the breakdown approval is
44
52
  # on; with --breakdown on or off it changes the settings file. `billing`
45
53
  # alone, or with --json, reads which account the agents run on, and whether
46
54
  # an Anthropic key is saved; with api or subscription it changes the
47
55
  # settings file, and with key the env file. `billing key --print` changes
48
56
  # nothing, but it prints the saved key, so it is not a read either: it is for
49
- # an agent's apiKeyHelper, which runs the copy that started the agent. `host`
57
+ # an agent's apiKeyHelper, which runs the copy that started the agent. `chain`
58
+ # alone, or with --json, reads whether the chain is on; with on or off it
59
+ # changes the settings file. `task ready` starts cards, as `task start`
60
+ # does, so it is not a read.
61
+ # `usage` alone, or with --json, reads the last reading of the Claude usage
62
+ # limits, and with billing on api what the agents spent, from the cost file;
63
+ # `usage record` writes the reading, and with an agent's space, card, phase
64
+ # and account after it the cost file too, so it is refused with the words or
65
+ # without, and is for an agent's statusLine. `task log` reads the cost file
66
+ # beside the store, both read-only. `host`
50
67
  # alone says whether the host is recorded, and `host report` reads its
51
- # readings; `host on` and `host off` make and delete them, and `host record`
52
- # writes them.
68
+ # readings: alone, with a period, or as `host report --card <space> <card>
69
+ # --json`, a card's readings, which is six words with --card and --json
70
+ # among them. Any other number of words is refused, as `host report 7d 1h`
71
+ # is. `host on` and `host off` make and delete the readings, and `host
72
+ # record` writes them.
53
73
  is_read() {
74
+ local word card=0 json=0
54
75
  case ${1:-help} in
55
76
  help | -h | --help | status) return 0 ;;
56
77
  space)
@@ -78,11 +99,12 @@ is_read() {
78
99
  tests)
79
100
  case $# in
80
101
  1) return 0 ;;
81
- 2) [ "$2" = --json ] ;;
102
+ 2) [ "$2" = --json ] || [ "$2" = ls ] ;;
103
+ 3) [ "$2" = ls ] && [ "$3" = --json ] ;;
82
104
  *) return 1 ;;
83
105
  esac
84
106
  ;;
85
- approval | billing)
107
+ approval | billing | chain | usage)
86
108
  case $# in
87
109
  1) return 0 ;;
88
110
  2) [ "$2" = --json ] ;;
@@ -91,14 +113,21 @@ is_read() {
91
113
  ;;
92
114
  task)
93
115
  case ${2:-} in
94
- ls | list | log) return 0 ;;
116
+ ls | list | log | asks) return 0 ;;
95
117
  *) return 1 ;;
96
118
  esac
97
119
  ;;
98
120
  host)
99
121
  case ${2:-} in
100
122
  '') [ "$#" -le 1 ] ;;
101
- report) [ "$#" -le 3 ] ;;
123
+ report)
124
+ [ "$#" -gt 3 ] || return 0
125
+ [ "$#" -eq 6 ] || return 1
126
+ for word in "${@:3}"; do
127
+ case $word in --card) card=1 ;; --json) json=1 ;; esac
128
+ done
129
+ [ "$card$json" = 11 ]
130
+ ;;
102
131
  *) return 1 ;;
103
132
  esac
104
133
  ;;
@@ -126,7 +155,7 @@ guard_worktree() {
126
155
  [ "${OCNUS_LIVE:-}" != 1 ] || return 0
127
156
  GUARDED=1
128
157
  ! is_read "$@" || return 0
129
- die "this is the copy of ocnus in the worktree $REPO. It runs only the commands that read (help, status, space ls, space team <name>, profile ls, linear archive, tests, approval, billing, task ls, task log, host and host report), so \`$(shell_words "$@")\` was not run: it could change this machine's Herdr, spaces and tasks, hand-offs, host readings, Linear key or cards, or Claude Code's skills, agents and trust file.
158
+ die "this is the copy of ocnus in the worktree $REPO. It runs only the commands that read (help, status, space ls, space team <name>, profile ls, linear archive, tests, tests ls, approval, billing, chain, usage, task ls, task log, task asks, host and host report), so \`$(shell_words "$@")\` was not run: it could change this machine's Herdr, spaces and tasks, hand-offs, host readings, Linear key or cards, or Claude Code's skills, agents and trust file.
130
159
  - For the card's own steps, such as recording a hand-off, run plain \`ocnus\`: the copy this machine runs, not this one.
131
160
  - To try a command that changes the machine, write a test case for it, in test/.
132
161
  - To run it on this machine for real, only when that is wanted:
@@ -23,7 +23,7 @@ HANDOFF_KEYS='step status next summary flags approved question options answer re
23
23
  # start (record_start). Breakdown hands on to it once the human approves the
24
24
  # card, or the setting does, but it is only ever what comes next in a block, since it is a command
25
25
  # that records its own row, not a skill: the write-up agent runs it, or the
26
- # human does again once it has held a card for a card that blocks it. A review that finds the work done hands on to pr, the step that pushes
26
+ # chain does once it has held a card for a card that blocks it (chain.sh). A review that finds the work done hands on to pr, the step that pushes
27
27
  # the task's branch, opens its pull requests and waits for the human to merge
28
28
  # them. merged is where a card ends: pr hands on to it once every pull request
29
29
  # has merged. It too is only ever what comes next, since nothing runs after it.
@@ -343,7 +343,15 @@ merge_linear() {
343
343
  # the merges folder beside the store, merges/.alive, the time its latest pass
344
344
  # began, and merges/<space>/<card>, the time and what that pass saw of the
345
345
  # card's pull requests. They are never rows in the store, and nothing in the
346
- # log reads them but the agent.
346
+ # log reads them but the agent, and the counts in the list's JSON, which mark
347
+ # each card from the same table (counts_sql).
348
+ #
349
+ # What each step's agents used, in tokens and in dollars, is not in the store
350
+ # either: it is in the cost file, which the agents' status lines add to
351
+ # (cost.sh). The log attaches it read-only for each run, when there is one,
352
+ # and reads each row's figures beside the row (cost_view): those of the turns
353
+ # that follow the row before it. With no cost file, or one that cannot be
354
+ # read, every row is not recorded, and the rest of the log is as it was.
347
355
 
348
356
  # SQL for a number of seconds as text: 50s, 1m 44s, 1h 02m, 3d 04h. @ stands
349
357
  # for the column that holds the seconds.
@@ -357,6 +365,8 @@ sql_took() {
357
365
 
358
366
  # SQL that starts a query on one card's view, or on every card's in the
359
367
  # space, as the table `shown`. Each card's rows are worked out on their own.
368
+ # prev is the id of the row before each row, which the row's figures are
369
+ # read by (cost_view, in cost.sh), and after the id of the row after it.
360
370
  # A store made before the approved line has no column for it until a
361
371
  # hand-off is recorded in it, and the log never adds one, since it reads a
362
372
  # store it cannot write too: its rows are read with approved null.
@@ -369,6 +379,7 @@ log_view() {
369
379
  select id, at, card, step, status, next, summary, flags, question, options,
370
380
  answer, reason, %s,
371
381
  lag(at) over w as prev_at, lag(status) over w as before, lead(id) over w as after,
382
+ lag(id) over w as prev,
372
383
  sum(case when step = 'new' then 1 else 0 end) over w as run
373
384
  from handoffs where space = %s %s
374
385
  window w as (partition by card order by id)),
@@ -413,10 +424,107 @@ log_view() {
413
424
 
414
425
  LOG_USAGE='usage: ocnus task log <space> [<card>] [--json]'
415
426
 
427
+ # Run one select on the log's view with what the agents used beside it, as
428
+ # the table told (cost_view, in cost.sh), and print its answer. The cost file
429
+ # is attached read-only when there is one. When it cannot be read, the select
430
+ # is run again without it, as with no cost file, so that a cost file that is
431
+ # not one never hides the hand-offs. It fails only when the store cannot be
432
+ # read.
433
+ # log_read <space> <the view's SQL> <the select> [<sqlite3 flag>...]
434
+ log_read() {
435
+ local space=$1 view=$2 select=$3 out
436
+ shift 3
437
+ if [ -f "$COST_DB" ] &&
438
+ out=$(store ${@+"$@"} "$STORE" "$(cost_attach "$COST_DB" c) $view$(cost_view "$space" 1) $select"); then
439
+ printf '%s\n' "$out"
440
+ return 0
441
+ fi
442
+ store ${@+"$@"} "$STORE" "$view$(cost_view "$space" 0) $select"
443
+ }
444
+
445
+ # The steps a card can stand on, in the order a card goes through them: the
446
+ # seven that the Step counts section in Herdr lists. merged is not one of
447
+ # them: a card whose pull requests have merged stands on no step.
448
+ COUNT_STEPS='define plan breakdown start build review pr'
449
+
450
+ # How many of the space's cards stand on each of COUNT_STEPS, and how each
451
+ # card's agent is doing, for the list's JSON: its counts, which the Step
452
+ # counts section in Herdr draws, holding no rules of its own. It prints the
453
+ # SQL for the table counted (step, nth, count, marks), a row for each step,
454
+ # with nth its place among them. It reads the tables latest, each card's
455
+ # latest row, and agents, what Herdr and ocnus's watch say of each card
456
+ # (agents.sh), so it follows them in the query.
457
+ #
458
+ # A card stands on the step that comes next when its latest hand-off is
459
+ # done, with setup, start's old name, counted as start, and on that
460
+ # hand-off's own step otherwise: the step that asked, was answered or
461
+ # failed. So a card whose next step is merged stands on no step.
462
+ #
463
+ # count is how many cards stand on the step, and marks is a JSON list with a
464
+ # mark for each of them. A card's mark is the first of these that holds:
465
+ # - none, at start: the card is held, approved with its work not started,
466
+ # whatever the agent of its write-up phase is doing
467
+ # - needs-human its agent is blocked on a prompt in its tab
468
+ # - stuck its agent has any other state, as the log says it: it hit
469
+ # an error, stopped without handing off or is not running,
470
+ # or a pull request of the card's is closed, in conflict or
471
+ # unwatched; or its step failed
472
+ # - ready it waits on the human at pr, and ocnus's watch says its
473
+ # pull requests are ready to merge (the agents table's ready)
474
+ # - needs-human it waits on the human
475
+ # - working anything else: its step is under way
476
+ # A step's marks come most urgent first: stuck, needs-human, ready, working.
477
+ counts_sql() {
478
+ local s n=0 steps=''
479
+ for s in $COUNT_STEPS; do
480
+ n=$((n + 1))
481
+ steps="$steps${steps:+, }('$s', $n)"
482
+ done
483
+ printf "steps (step, nth) as (values %s),
484
+ placed as (
485
+ select status, json_extract(agent, '\$.state') as doing, coalesce(ready, 0) as ready,
486
+ case when status = 'done' then case when next = 'setup' then 'start' else next end
487
+ else step end as stand
488
+ from latest left join agents using (card)),
489
+ marked as (
490
+ select stand,
491
+ case when stand = 'start' then null
492
+ when doing = 'blocked' then 'needs-human'
493
+ when doing is not null or status = 'failed' then 'stuck'
494
+ when status = 'needs-human' and stand = 'pr' and ready = 1 then 'ready'
495
+ when status = 'needs-human' then 'needs-human'
496
+ else 'working' end as mark
497
+ from placed),
498
+ counted as (
499
+ select steps.step, nth, (select count(*) from marked where stand = steps.step) as count,
500
+ (select json_group_array(mark) from (
501
+ select mark from marked where stand = steps.step and mark is not null
502
+ order by case mark when 'stuck' then 1 when 'needs-human' then 2 when 'ready' then 3 else 4 end)) as marks
503
+ from steps)" "$steps"
504
+ }
505
+
506
+ # The counts of a space with no card on any step, as the list's JSON gives
507
+ # them, for a machine with no store yet: every step with 0 and no marks. A
508
+ # step's text is its count, and start's how many cards are held.
509
+ counts_none() {
510
+ local s text out=''
511
+ for s in $COUNT_STEPS; do
512
+ text=0
513
+ [ "$s" != start ] || text='0 held'
514
+ out="$out${out:+,}{\"step\":\"$s\",\"count\":0,\"marks\":[],\"text\":\"$text\"}"
515
+ done
516
+ printf '[%s]' "$out"
517
+ }
518
+
416
519
  # The space's cards that have hand-offs, newest first by their latest row:
417
520
  # where each stands and how long it has stood there, or what its agent is
418
- # doing when Herdr says it is stuck or has stopped. With --json, the same as
419
- # one line of JSON, with the agent beside where the card stands.
521
+ # doing when Herdr says it is stuck or has stopped, then what the card's
522
+ # agents have used in all, or that it is not recorded. With --json, the same
523
+ # as one line of JSON, with the agent beside where the card stands, and the
524
+ # card's total as tokens and cost, each null when nothing is recorded, and
525
+ # partial, true when a step of the card is not recorded; and then counts:
526
+ # the seven steps in order, each with how many cards stand on it, a mark for
527
+ # each card and its text (counts_sql).
420
528
  # log_cards <space> <json: 1 or 0> <view>
421
529
  log_cards() {
422
530
  local name=$1 json=$2 list
@@ -426,41 +534,59 @@ log_cards() {
426
534
  from shown where after is null), $AGENTS_SQL"
427
535
  if [ "$json" = 1 ]; then
428
536
  if [ ! -e "$STORE" ]; then
429
- printf '{"space":"%s","cards":[]}\n' "$(json_str "$name")"
537
+ printf '{"space":"%s","cards":[],"counts":%s}\n' "$(json_str "$name")" "$(counts_none)"
430
538
  return
431
539
  fi
432
- store "$STORE" "$list
540
+ log_read "$name" "$list, $(counts_sql)" "
433
541
  select json_object('space', $(sql_str "$name"),
434
542
  'cards', (select json_group_array(json(c)) from (
435
- select json_object('card', card, 'at', at, 'state', state,
543
+ select json_object('card', latest.card, 'at', at, 'state', state,
436
544
  'waiting', nullif(waiting, ''), 'for', $(sql_took since), 'seconds', since,
437
- 'run', run, 'step', step, 'status', status, 'next', next,
438
- 'agent', json(agent)) as c
439
- from latest left join agents using (card) order by at desc, id desc)));" ||
545
+ 'run', run, 'step', latest.step, 'status', status, 'next', next,
546
+ 'agent', json(agent), 'tokens', json(t.tokens), 'cost', json(t.cost),
547
+ 'partial', json(case when t.missing > 0 then 'true' else 'false' end)) as c
548
+ from latest left join agents using (card) join told t on t.part = 2 and t.card = latest.card
549
+ order by at desc, latest.id desc)),
550
+ 'counts', (select json_group_array(json(c)) from (
551
+ select json_object('step', step, 'count', count, 'marks', json(marks),
552
+ 'text', case when step = 'start' then count || ' held' else '' || count end) as c
553
+ from counted order by nth)));" ||
440
554
  die "could not read the hand-offs in $STORE. It may not be ocnus's store."
441
555
  return
442
556
  fi
443
557
 
444
- local sep=$'\x1f' found='' count=0 card state for
558
+ local sep=$'\x1f' found='' count=0 card state for total
445
559
  if [ -e "$STORE" ]; then
446
- found=$(store -separator "$sep" "$STORE" "$list
447
- select card, coalesce(json_extract(agent, '\$.label'), state),
448
- coalesce(json_extract(agent, '\$.for'), $(sql_took since))
449
- from latest left join agents using (card) order by at desc, id desc;") ||
560
+ found=$(log_read "$name" "$list" "
561
+ select latest.card, coalesce(json_extract(agent, '\$.label'), state),
562
+ coalesce(json_extract(agent, '\$.for'), $(sql_took since)),
563
+ case when t.recorded then t.short || ' tokens, ' || t.cost_text
564
+ || case when t.missing > 0 then ', not the whole card' else '' end
565
+ else 'tokens not recorded' end
566
+ from latest left join agents using (card) join told t on t.part = 2 and t.card = latest.card
567
+ order by at desc, latest.id desc;" -separator "$sep") ||
450
568
  die "could not read the hand-offs in $STORE. It may not be ocnus's store."
451
569
  fi
452
- while IFS=$sep read -r card state for; do
570
+ while IFS=$sep read -r card state for total; do
453
571
  [ -n "$card" ] || continue
454
572
  [ "$count" -gt 0 ] || say "Cards in '$name' with hand-offs, newest first"
455
573
  count=$((count + 1))
456
- printf '%-10s %-28s for %s\n' "$card" "$state" "$for"
574
+ printf '%-10s %-28s for %s, %s\n' "$card" "$state" "$for" "$total"
457
575
  done <<< "$found"
458
576
  [ "$count" -gt 0 ] || say "No hand-offs recorded in '$name'."
459
577
  }
460
578
 
461
- # List a card's hand-offs, oldest first, with how long each step took. With
462
- # no card, list the space's cards instead. With --json, the same view as
463
- # one line of JSON.
579
+ # List a card's hand-offs, oldest first, with how long each step took and
580
+ # what its agents used: a tokens line under each row, then what the step the
581
+ # card is in has used so far, and the card in all, which says when it is not
582
+ # the whole card's. A card with nothing recorded says so once. With no card,
583
+ # list the space's cards instead. With --json, the same view as one line of
584
+ # JSON: each of steps has tokens and cost, each null when not recorded;
585
+ # current is the step the card is in and what it has used since the latest
586
+ # row, null once the card has merged; spent is the rows' figures and
587
+ # current's added, null when none is recorded, with partial true when a row
588
+ # or current is not recorded; and sessions lists its agents' Claude Code
589
+ # sessions.
464
590
  task_log() {
465
591
  local json=0 a
466
592
  local args=()
@@ -490,13 +616,25 @@ task_log() {
490
616
 
491
617
  if [ "$json" = 1 ]; then
492
618
  if [ ! -e "$STORE" ]; then
493
- printf '{"space":"%s","card":"%s","state":null,"waiting":null,"run":null,"agent":null,"steps":[]}\n' \
619
+ printf '{"space":"%s","card":"%s","state":null,"waiting":null,"run":null,"agent":null,"steps":[],"current":null,"spent":null,"sessions":[]}\n' \
494
620
  "$(json_str "$name")" "$(json_str "$card")"
495
621
  return
496
622
  fi
623
+ # The Claude Code sessions of the agents ocnus started on the card
624
+ # (sessions.sh), oldest first: the ones that have a session ID, each with
625
+ # its phase and when it started. A store made before sessions were
626
+ # recorded has no table for them, and the log never makes one, since it
627
+ # reads a store it cannot write too: the card has none then. The table is
628
+ # named with its schema, main, since the cost file log_read attaches has a
629
+ # sessions table of its own.
630
+ local sessions='json_array()'
631
+ ! store_has_sessions || sessions="(select json_group_array(json(entry)) from (
632
+ select json_object('session', session, 'phase', phase, 'at', at) as entry
633
+ from main.sessions where space = $(sql_str "$name") and card = $(sql_str "$card") and session is not null
634
+ order by id))"
497
635
  # SQLite builds the JSON, so no value is escaped by hand. A store that
498
636
  # cannot be read is an error, not an empty history.
499
- store "$STORE" "$view, $AGENTS_SQL
637
+ log_read "$name" "$view, $AGENTS_SQL" "
500
638
  select json_object('space', $(sql_str "$name"), 'card', $(sql_str "$card"),
501
639
  'state', (select state from shown order by id desc limit 1),
502
640
  'waiting', (select nullif(waiting, '') from shown order by id desc limit 1),
@@ -504,12 +642,19 @@ task_log() {
504
642
  'agent', json((select agent from agents limit 1)),
505
643
  'steps', (select json_group_array(json(entry)) from (
506
644
  select json_object('run', run, 'at', at, 'clock', strftime('%H:%M', at, 'localtime'),
507
- 'step', step, 'status', status, 'next', next, 'kind', kind, 'label', label,
508
- 'took', took, 'short', short, 'seconds', seconds, 'waiting', nullif(waiting, ''),
645
+ 'step', shown.step, 'status', status, 'next', next, 'kind', kind, 'label', label,
646
+ 'took', took, 'short', shown.short, 'seconds', seconds, 'waiting', nullif(waiting, ''),
509
647
  'summary', summary, 'flags', flags, 'approved', approved,
510
648
  'question', question, 'options', options,
511
- 'answer', answer, 'reason', reason) as entry
512
- from shown order by id)));" ||
649
+ 'answer', answer, 'reason', reason,
650
+ 'tokens', json(t.tokens), 'cost', json(t.cost)) as entry
651
+ from shown join told t on t.part = 0 and t.id = shown.id order by shown.id)),
652
+ 'current', json((select json_object('step', step, 'tokens', json(tokens), 'cost', json(cost))
653
+ from told where part = 1)),
654
+ 'spent', json((select case when recorded then json_object('tokens', json(tokens), 'cost', json(cost),
655
+ 'partial', json(case when missing > 0 then 'true' else 'false' end)) end
656
+ from told where part = 2)),
657
+ 'sessions', $sessions);" ||
513
658
  die "could not read the hand-offs in $STORE. It may not be ocnus's store."
514
659
  return
515
660
  fi
@@ -518,16 +663,26 @@ task_log() {
518
663
  # `read` run two empty fields together.
519
664
  local sep=$'\x1f' count=0 key
520
665
  local at step what took summary flags approved question options answer reason waiting
666
+ # What the agents used: tokens is each row's line, sofar that of the step
667
+ # the card is in, with the step, and inall the card's. sofar is empty once
668
+ # the card has merged, and inall when nothing is recorded for the card.
669
+ local tokens sofar inall so_far='' in_all=''
521
670
  if [ -e "$STORE" ]; then
522
- found=$(store -separator "$sep" "$STORE" "$view
523
- select at, step, what, took, coalesce(summary, ''), coalesce(flags, ''),
671
+ found=$(log_read "$name" "$view" "
672
+ select shown.at, shown.step, what, took, coalesce(summary, ''), coalesce(flags, ''),
524
673
  coalesce(approved, ''), coalesce(question, ''), coalesce(options, ''),
525
- coalesce(answer, ''), coalesce(reason, ''), waiting
526
- from shown order by id;") ||
674
+ coalesce(answer, ''), coalesce(reason, ''), waiting, t.line,
675
+ coalesce((select 'so far in ' || step || ': ' || line from told where part = 1), ''),
676
+ coalesce((select case when recorded then line || case when missing = 0 then ''
677
+ else ', not the whole card: ' || missing || case when missing = 1 then ' step' else ' steps' end
678
+ || ' not recorded' end end
679
+ from told where part = 2), '')
680
+ from shown join told t on t.part = 0 and t.id = shown.id order by shown.id;" -separator "$sep") ||
527
681
  die "could not read the hand-offs in $STORE. It may not be ocnus's store."
528
682
  fi
529
- while IFS=$sep read -r at step what took summary flags approved question options answer reason waiting; do
683
+ while IFS=$sep read -r at step what took summary flags approved question options answer reason waiting tokens sofar inall; do
530
684
  [ -n "$at" ] || continue
685
+ so_far=$sofar in_all=$inall
531
686
  [ "$count" -gt 0 ] || say "$card in '$name'"
532
687
  count=$((count + 1))
533
688
  if [ -n "$took" ]; then printf '%s %-10s %-22s %s\n' "$at" "$step" "$what" "$took"
@@ -539,9 +694,19 @@ task_log() {
539
694
  for key in summary flags approved question options answer reason; do
540
695
  [ -z "${!key}" ] || printf ' %s: %s\n' "$key" "${!key}"
541
696
  done
697
+ # With nothing recorded for the card, that is said once, below.
698
+ [ -z "$inall" ] || printf ' tokens: %s\n' "$tokens"
542
699
  [ -z "$waiting" ] || printf ' %s\n' "$waiting"
543
700
  done <<< "$found"
544
701
  [ "$count" -gt 0 ] || say "No hand-offs recorded for $card in '$name'."
702
+ if [ "$count" -gt 0 ]; then
703
+ if [ -z "$in_all" ]; then
704
+ printf ' tokens: not recorded for this card\n'
705
+ else
706
+ [ -z "$so_far" ] || printf ' %s\n' "$so_far"
707
+ printf ' in all: %s\n' "$in_all"
708
+ fi
709
+ fi
545
710
  # Last, what the card's agent is doing, when Herdr says it is stuck or has
546
711
  # stopped, or what can see its pull requests, as the list says it
547
712
  # (agents_table). An agent is only ever worked out with jq to hand.