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

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,482 @@
1
+ # What a card's agents did, step by step: `ocnus task events`. Sourced by
2
+ # cli/ocnus.
3
+
4
+ # The list is read from three places, and nothing is written to any of them:
5
+ # - the card's steps, from the hand-off store through log_view
6
+ # (handoff.sh), so that they cannot disagree with `task log`. A step is
7
+ # each time the card was in it, as `host report --card` has it
8
+ # (host_card, in host.sh), so that the Trace's layers line up: hand-offs
9
+ # of one step in a row, from the hand-off before the first to the last.
10
+ # The step under way is open and runs to now. `new` and `start` have no
11
+ # entry.
12
+ # - the card's sessions, which `task new` and `task build` record as they
13
+ # start its agents (card_sessions, in sessions.sh): when each started,
14
+ # its phase and its session ID.
15
+ # - each session's transcript, <session ID>.jsonl, which Claude Code keeps
16
+ # (session_transcript), read by EVENTS_READ.
17
+ # An entry of a write-up session, a line of its transcript, goes in define,
18
+ # plan or breakdown, and one of a build session in build, review or pr, of
19
+ # the run the session started in: the first of those steps that ends at or
20
+ # after the entry's second, else the last. So the command that records a
21
+ # hand-off is in the step it ends, the write-up agent's `task start` is
22
+ # under breakdown, and nothing a session wrote lands in the other phase's
23
+ # steps. A step is recorded when a transcript has an entry in it, and so is
24
+ # the step under way once the newest session of its phase has a transcript,
25
+ # so that a step that has just started is not taken for one whose agent was
26
+ # not recorded. Any other step is not recorded: its events are null, never a
27
+ # list with nothing in it.
28
+ #
29
+ # What makes an event, in the main conversation, a subagent's left out:
30
+ # edit an Edit or Write call that worked. Calls with no other event
31
+ # between them, in one step, are one event, which names each file
32
+ # once: from the folder the session started in, or by its whole
33
+ # path outside it.
34
+ # test run a Bash call whose command, with its heredocs' bodies taken out,
35
+ # runs `ocnus tests run`. Its totals are the last line it printed
36
+ # with "<n> passed", and "<n> failed" from that line when it is
37
+ # there: the form of ocnus's own runner, jest, vitest, pytest and
38
+ # cargo. A run whose output went to a file, or that ran in the
39
+ # background, takes them from the first command after it that
40
+ # names the file and printed such a line, up to a test run that
41
+ # writes the file again. With no result, or in the background
42
+ # with neither totals nor Claude Code's notice that it ended, it
43
+ # is running; with no such line it has no totals.
44
+ # commit a Bash call that worked, runs `git commit` and printed the new
45
+ # commit: git's own "[<branch> <hash>] <subject>" line, or a
46
+ # `git log --oneline` line whose subject is the first line of the
47
+ # message the command gave, or the first such line when it gave
48
+ # none, as `git commit --no-edit` does. One that printed neither
49
+ # is a command.
50
+ # question an `ocnus task handoff` call that worked and whose block says
51
+ # status: needs-human: its question line.
52
+ # answer a prompt the human typed: not the first prompt of a transcript,
53
+ # which is ocnus's first message, not one from ocnus's watch,
54
+ # which starts ocnus-merges:, and not brief or /brief.
55
+ # command any other Bash call: what it was for, as the agent described it
56
+ # when it ran it, or the program it ran when it gave no
57
+ # description.
58
+ # Every text is one line of at most EVENTS_TEXT_MAX characters. Of what a
59
+ # command printed, only a test run's totals and a commit's hash and subject
60
+ # are given, and nothing of a file's contents or a diff is.
61
+
62
+ EVENTS_USAGE='usage: ocnus task events <space> <card> [--step <step>] [--json]'
63
+ # The most characters a text holds. A longer one is cut, and ends with ...
64
+ EVENTS_TEXT_MAX=200
65
+
66
+ # What every jq program here starts with. one makes a text one line of at
67
+ # most $max characters: control characters, newlines among them, become
68
+ # spaces, and runs of spaces one.
69
+ # shellcheck disable=SC2016
70
+ EVENTS_DEFS='
71
+ def one: gsub("[[:cntrl:]]"; " ") | gsub(" {2,}"; " ") | ltrimstr(" ") | rtrimstr(" ")
72
+ | if length > $max then .[0:$max - 3] + "..." else . end;
73
+ '
74
+
75
+ # The jq that reads one session's transcript, as raw lines on stdin, and
76
+ # prints the session as one line of JSON for EVENTS_JOIN: when it started
77
+ # and its phase, $at and $phase, read true, entries, the second of each line
78
+ # of the main conversation, and events, each with its second, the number of
79
+ # its line and of its block in the line, its kind, its text and what its
80
+ # kind has (an edit has the one file it changed, which EVENTS_JOIN joins).
81
+ # A line that is not whole JSON, such as the one Claude Code is writing, is
82
+ # passed over, and so is one with no time. Each line is made small as it is
83
+ # read, so that a long transcript is never held whole:
84
+ # nohd a command with its heredocs' bodies taken out, so that what an
85
+ # agent writes into a file or a hand-off is never taken for a
86
+ # command it ran
87
+ # words a command's words, without quotes, for finding a file it names
88
+ # targets the files a command sends its output to, as > or >> name them
89
+ # program the program a command runs: past assignments and cd
90
+ # asked a hand-off block's question, when its status is needs-human
91
+ # message the first line of the message a `git commit` gives, with -m or
92
+ # --message, in quotes or a heredoc
93
+ # result what a call's result holds: whether it failed, and for a
94
+ # command's, whether it went to the background and the file it
95
+ # writes, its totals, git's line for a commit, and the first
96
+ # `git log --oneline` lines
97
+ # said what a prompt the human typed says, or null when it is not an
98
+ # answer
99
+ # A command's result is read from what Claude Code kept of it: stdout and
100
+ # stderr, or for one that failed, its text, which starts with its exit code.
101
+ # \u0027 is a single quote.
102
+ # shellcheck disable=SC2016
103
+ EVENTS_READ='
104
+ def stamp: if type == "string" and test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}")
105
+ then (try (.[0:19] + "Z" | fromdateiso8601) catch null) else null end;
106
+ def text_of: if type == "string" then .
107
+ elif type == "array" then [.[] | objects | select(.type == "text") | .text | strings] | join("\n")
108
+ else "" end;
109
+ def plain: gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "");
110
+ def bare: gsub("[\"\u0027]"; "");
111
+ def nohd:
112
+ reduce (split("\n")[] | rtrimstr("\r")) as $l ({out: [], wait: []};
113
+ if (.wait | length) > 0 then
114
+ (if .wait[0].dash then ($l | sub("^\t+"; "")) else $l end) as $c
115
+ | if $c == .wait[0].word then .wait |= .[1:] else . end
116
+ else
117
+ .out += [$l]
118
+ | .wait = [$l | match("(?<!<)<<(?!<)(-?)[ \t]*\\\\?([\"\u0027]?)([A-Za-z0-9_.-]+)\\2"; "g")
119
+ | {dash: (.captures[0].string == "-"), word: .captures[2].string}]
120
+ end)
121
+ | .out | join("\n");
122
+ def words: [splits("[\\s;&|()<>]+") | bare | select(length > 0)];
123
+ def targets: [match("(?<![0-9<>&])(?:&|1)?>>?(?!&)[ \t]*(\"[^\"]*\"|\u0027[^\u0027]*\u0027|[^\\s;&|()<>]+)"; "g")
124
+ | .captures[0].string | bare | select(length > 0 and (startswith("/dev/") | not))];
125
+ def runs($re): test("(^|[\\s;&|(!{])([^\\s;&|(){}<>]*/)?" + $re + "(\\s|$)");
126
+ def program:
127
+ [splits("&&|\\|\\||[;|&\n]")
128
+ | [splits("[\\s()]+") | select(length > 0)]
129
+ | until(length == 0 or (.[0] | test("^([A-Za-z_][A-Za-z0-9_]*=.*|!|\\{|\\}|then|do|else|time)$") | not); .[1:])
130
+ | select(length > 0 and .[0] != "cd" and .[0] != "pushd" and (.[0] | startswith("#") | not))
131
+ | .[0] | bare | sub(".*/"; "") | select(length > 0)]
132
+ | .[0] // "";
133
+ def asked:
134
+ [split("\n")[] | rtrimstr("\r")] as $ls
135
+ | if any($ls[]; test("^[ \t]*status:[ \t]*needs-human[ \t]*$"))
136
+ then [$ls[] | capture("^[ \t]*question:[ \t]*(?<q>.*[^ \t])[ \t]*$") | .q] | .[0]
137
+ else null end;
138
+ def commit_re: "(^|[\\s;&|(!{])git(\\s+-[Cc]\\s+\\S+|\\s+--?[A-Za-z]\\S*)*\\s+commit(\\s|$)";
139
+ def message:
140
+ ([match(commit_re)] | .[0]) as $m
141
+ | if $m == null then null
142
+ else .[$m.offset + $m.length - 1:]
143
+ | ([capture("(?:^|\\s)(?:-[A-Za-z]*m|--message)(?:[ \t]+|=)?(?:\"\\$\\(cat[ \t]+<<-?[ \t]*\\\\?[\"\u0027]?[A-Za-z0-9_.-]+[\"\u0027]?[ \t]*\n(?<hb>[^\n]*)|\u0027(?<sq>[^\u0027]*)\u0027|\"(?<dq>(?:[^\"\\\\]|\\\\.)*)\"|(?<w>[^\\s;&|()<>\"\u0027]+))")] | .[0])
144
+ | if . == null then null
145
+ elif .hb != null then .hb
146
+ elif .sq != null then .sq
147
+ elif .dq != null then .dq | gsub("\\\\(?<c>[\"\\\\$`])"; .c)
148
+ else .w end
149
+ | if . == null then null else split("\n")[0] | one end
150
+ end;
151
+ def bash_call:
152
+ (.command | if type == "string" then . else "" end) as $cmd
153
+ | ($cmd | nohd) as $run
154
+ | ($run | test(commit_re)) as $commit
155
+ | {test: ($run | runs("ocnus\\s+tests\\s+run")),
156
+ question: (if $run | runs("ocnus\\s+task\\s+handoff") then $cmd | asked else null end),
157
+ commit: $commit,
158
+ message: (if $commit then $cmd | message else null end),
159
+ desc: (.description | if type == "string" then one else "" end),
160
+ targets: ($run | targets),
161
+ words: ($run | words),
162
+ program: ($run | program)};
163
+ def result($t; $b):
164
+ (.content | text_of) as $text
165
+ | (($t | type) == "string" or (($t | type) == "object" and ($t | has("stdout"))) or $t == null) as $shell
166
+ | {k: "result", b: $b, id: .tool_use_id, err: (.is_error == true)}
167
+ + (if $shell | not then {}
168
+ else
169
+ ((if ($t | type) == "object" and ($t.stdout | type) == "string"
170
+ then $t.stdout + "\n" + ($t.stderr | if type == "string" then . else "" end)
171
+ else $text end) | plain | split("\n")) as $out
172
+ | {bg: ((($t | type) == "object" and $t.backgroundTaskId != null)
173
+ or ($text | startswith("Command running in background"))),
174
+ bgfile: (if ($t | type) == "object" and ($t.backgroundOutputPath | type) == "string"
175
+ then $t.backgroundOutputPath
176
+ else [$text | capture("Output is being written to: (?<f>\\S+?)\\.?(\\s|$)") | .f] | .[0] end),
177
+ totals: ([$out[] | select(test("[0-9]+ passed"))] | last
178
+ | if . == null then null
179
+ else {passed: (capture("(?<n>[0-9]+) passed") | .n | tonumber),
180
+ failed: ([capture("(?<n>[0-9]+) failed") | .n | tonumber] | .[0])} end),
181
+ git: ([$out[] | capture("^\\[[^\\]]* (?<hash>[0-9a-f]{7,40})\\] (?<subject>.+)$")] | .[0]),
182
+ onelines: [limit(50; $out[] | capture("^(?<hash>[0-9a-f]{7,40}) (?:\\([^)]*\\) )?(?<subject>.+)$"))]}
183
+ end);
184
+ def from_assistant:
185
+ (.message | if type == "object" then .content else null end)
186
+ | if type == "array" then to_entries[] else empty end
187
+ | .key as $b | .value | objects
188
+ | select(.type == "tool_use" and (.id | type) == "string")
189
+ | (.input | if type == "object" then . else {} end) as $in
190
+ | if .name == "Bash" then {k: "call", b: $b, id, name: "Bash"} + ($in | bash_call)
191
+ elif .name == "Edit" or .name == "Write" then {k: "call", b: $b, id, name: "Edit", file: ($in.file_path | strings)}
192
+ else empty end;
193
+ def from_user:
194
+ (.message | if type == "object" then .content else null end) as $c
195
+ | [$c | if type == "array" then .[] else empty end | objects | select(.type == "tool_result")] as $rs
196
+ | if ($rs | length) > 0 then
197
+ .toolUseResult as $tur
198
+ | $rs | to_entries[] | .key as $b | .value
199
+ | result(if ($rs | length) == 1 then $tur else null end; $b)
200
+ elif .isMeta == true or .isCompactSummary == true then empty
201
+ else
202
+ ($c | text_of) as $text
203
+ | (.origin | if type == "object" then .kind else null end) as $origin
204
+ | if $origin == "task-notification" or ($text | test("^\\s*<task-notification>")) then
205
+ [$text | capture("<tool-use-id>(?<id>[^<]+)</tool-use-id>") | {k: "ended", id}] | .[0] // empty
206
+ else {k: "prompt", human: ($origin == "human"), text: $text} end
207
+ end;
208
+ def said:
209
+ (if test("<command-name>") then
210
+ ([capture("<command-name>(?<n>[^<]*)</command-name>") | .n] | .[0] // "")
211
+ + ([capture("<command-args>(?<a>[^<]*)</command-args>") | .a] | .[0] // "" | if length > 0 then " " + . else "" end)
212
+ else . end | one) as $t
213
+ | if $t == "" or ($t | ascii_downcase | . == "brief" or . == "/brief")
214
+ or ($t | startswith("ocnus-merges:")) or ($t | startswith("[Request interrupted"))
215
+ or test("^\\s*<(local-command-|bash-|system-reminder|task-notification)")
216
+ then null else $t end;
217
+ [inputs | (try fromjson catch null) | objects
218
+ | select((.type == "user" or .type == "assistant") and .isSidechain != true)
219
+ | (.timestamp | stamp) as $sec | select($sec != null)
220
+ | {sec: $sec, cwd: (.cwd | if type == "string" then . else null end),
221
+ items: [if .type == "assistant" then from_assistant else from_user end]}]
222
+ | . as $lines
223
+ | (first($lines[] | .cwd | strings) // null) as $cwd
224
+ | [range(0; $lines | length) as $i | $lines[$i] | .sec as $sec | .items[] | . + {i: $i, sec: $sec}] as $items
225
+ | [$items[] | select(.k == "call" and .name == "Bash")] as $bash
226
+ | (reduce range(0; $bash | length) as $x ({}; .[$bash[$x].id] = $x)) as $pos
227
+ | (reduce ($items[] | select(.k == "result" and (.id | type) == "string")) as $r ({};
228
+ if has($r.id) then . else .[$r.id] = $r end)) as $res
229
+ | (reduce ($items[] | select(.k == "ended")) as $e ({}; .[$e.id] = true)) as $ended
230
+ | ([$items[] | select(.k == "prompt")] | if length > 0 then .[0].i else -1 end) as $first
231
+ | def set: map({(.): true}) | add // {};
232
+ def later($j; $files):
233
+ reduce range($j + 1; $bash | length) as $x ({done: false, totals: null};
234
+ if .done then .
235
+ else $bash[$x] as $c
236
+ | if $c.test and any($c.targets[]; $files[.] == true) then .done = true
237
+ elif any($c.words[]; $files[.] == true) and $res[$c.id].totals != null
238
+ then {done: true, totals: $res[$c.id].totals}
239
+ else . end
240
+ end)
241
+ | .totals;
242
+ def where: if $cwd != null and startswith($cwd + "/") then .[($cwd | length) + 1:] else . end;
243
+ def commit_of($c; $r):
244
+ (if $r.git != null then $r.git
245
+ elif $c.message != null then first(($r.onelines // [])[] | select((.subject | one) == $c.message)) // null
246
+ else ($r.onelines // [])[0] end)
247
+ | if . == null then null else {hash, subject: (.subject | one)} end;
248
+ [$items[] | {sec, i, b} as $here
249
+ | if .k == "call" and .name == "Edit" then
250
+ select(($res[.id] // {err: true}).err | not) | $here + {kind: "edit", file: (.file | where)}
251
+ elif .k == "call" then
252
+ . as $c | $res[$c.id] as $r
253
+ | if $c.test then
254
+ (if $r == null then {totals: null, running: true}
255
+ elif $r.bg == true then
256
+ later($pos[$c.id]; $c.targets + [$r.bgfile // empty] | set) as $totals
257
+ | {totals: $totals, running: ($totals == null and $ended[$c.id] != true)}
258
+ elif $r.totals != null then {totals: $r.totals, running: false}
259
+ elif ($c.targets | length) > 0 then {totals: later($pos[$c.id]; $c.targets | set), running: false}
260
+ else {totals: null, running: false} end) as $how
261
+ | $here + {kind: "test run",
262
+ text: (if $how.totals != null
263
+ then "Ran the tests: \($how.totals.passed) passed"
264
+ + (if $how.totals.failed != null then ", \($how.totals.failed) failed" else "" end)
265
+ elif $how.running then "Running the tests"
266
+ else "Ran the tests, no totals" end),
267
+ passed: $how.totals.passed, failed: $how.totals.failed, running: $how.running}
268
+ elif $c.question != null and $r != null and ($r.err | not) then
269
+ $here + {kind: "question", text: ("Asked you: " + $c.question | one)}
270
+ elif $c.commit and $r != null and ($r.err | not) and commit_of($c; $r) != null then
271
+ commit_of($c; $r) as $m
272
+ | $here + {kind: "commit", text: ("Committed \($m.hash) \"\($m.subject)\"" | one),
273
+ hash: $m.hash, subject: $m.subject}
274
+ else
275
+ $here + {kind: "command",
276
+ text: (if $c.desc != "" then $c.desc
277
+ elif $c.program != "" then "Ran " + $c.program | one
278
+ else "Ran a command" end)}
279
+ end
280
+ elif .k == "prompt" and .human and .i != $first then
281
+ (.text | said) as $t | select($t != null) | $here + {kind: "answer", text: ("You said: " + $t | one)}
282
+ else empty end] as $events
283
+ | {at: $at, phase: $phase, read: true, entries: ([$lines[].sec] | unique), events: $events}
284
+ '
285
+
286
+ # The jq that puts each session's events under the card's steps and prints
287
+ # the list as one line of JSON: $base is the card's steps and when each of
288
+ # its runs began, from events_base, and stdin each session as EVENTS_READ
289
+ # prints it, oldest first, or as one whose transcript was not read, with
290
+ # read false. $only, when it is not empty, is the one step to list, and
291
+ # $writeup and $building the steps of each phase. Edits made one after
292
+ # another in one step are joined here, into one event that names each file
293
+ # once.
294
+ # shellcheck disable=SC2016
295
+ EVENTS_JOIN='
296
+ ($writeup | split(" ")) as $w
297
+ | ($building | split(" ")) as $bl
298
+ | def phase_of($s): if ($w | index([$s])) != null then "write-up" elif ($bl | index([$s])) != null then "build" else null end;
299
+ def run_of($t): [$base.news[] | select(. <= $t)] | length;
300
+ def join_edits:
301
+ reduce .[] as $e ([];
302
+ if $e.kind == "edit" and length > 0 and .[length - 1].kind == "edit" and .[length - 1].n == $e.n
303
+ then .[length - 1].files |= (if index([$e.file]) == null then . + [$e.file] else . end)
304
+ else . + [if $e.kind == "edit" then $e + {files: [$e.file]} else $e end] end);
305
+ def shape:
306
+ {at: (.sec | todate), clock: (.sec | strflocaltime("%H:%M")), kind,
307
+ text: (if .kind != "edit" then .text
308
+ elif (.files | length) == 1 then "Edited 1 file: " + .files[0] | one
309
+ else "Edited \(.files | length) files: " + (.files | join(", ")) | one end)}
310
+ + (if .kind == "edit" then {files, count: (.files | length)}
311
+ elif .kind == "test run" then {passed, failed, running}
312
+ elif .kind == "commit" then {hash, subject}
313
+ else {} end);
314
+ [to_entries[] | .key as $k | .value | objects
315
+ | . + {k: $k, run: run_of(.at | try fromdateiso8601 catch 0)}] as $sessions
316
+ | [$sessions[] | . as $s
317
+ | [$base.steps[] | select(.run == $s.run and phase_of(.step) == $s.phase)] as $c
318
+ | def place($t): if ($c | length) == 0 then null
319
+ else first(($c[] | select(.e >= $t) | .n), $c[-1].n) end;
320
+ {run, phase, read,
321
+ hit: [(.entries // [])[] | place(.) | select(. != null)],
322
+ events: ([(.events // [])[] | . + {n: place(.sec), k: $s.k} | select(.n != null)] | join_edits)}] as $placed
323
+ | ([$placed[].hit[] | tostring] | map({(.): true}) | add // {}) as $hit
324
+ | {space: $space, card: $card,
325
+ steps: [$base.steps[] | select($only == "" or .step == $only) | . as $st
326
+ | ($hit[$st.n | tostring] == true
327
+ or ($st.open and ([$placed[] | select(.run == $st.run and .phase == phase_of($st.step))] | last | .read) == true)) as $rec
328
+ | {run, step, start: (.s | todate), end: (.e | todate), open, recorded: $rec,
329
+ events: (if $rec then [$placed[].events[] | select(.n == $st.n)] | sort_by([.sec, .k, .i, .b]) | map(shape)
330
+ else null end)}]}
331
+ '
332
+
333
+ # The jq that prints the list in words: the card, then each step with its
334
+ # start, then a line an event with its time, its kind and its text, or not
335
+ # recorded. $rows is how many hand-offs the card has, and $only the step
336
+ # asked for.
337
+ # shellcheck disable=SC2016
338
+ EVENTS_WORDS='
339
+ if (.steps | length) == 0 then
340
+ if $rows == 0 then "No hand-offs recorded for \(.card) in \u0027\(.space)\u0027."
341
+ elif $only != "" then "\(.card) in \u0027\(.space)\u0027 has not been in \($only)."
342
+ else "\(.card) in \u0027\(.space)\u0027 has not been in a step yet." end
343
+ else
344
+ "\(.card) in \u0027\(.space)\u0027",
345
+ (.steps[]
346
+ | "\(.step + " " | .[0:10]) \(.start)\(if .open then ", under way" else "" end)",
347
+ (if .events == null then " not recorded"
348
+ elif (.events | length) == 0 then " nothing to list"
349
+ else .events[] | " \(.clock) \(.kind + " " | .[0:9]) \(.text)" end))
350
+ end
351
+ '
352
+
353
+ # ocnus task events <space> <card> [--step <step>] [--json]: list what the
354
+ # card's agents did, step by step, oldest first, in words or, with --json,
355
+ # as one line for programs. --step lists one step alone, each time the card
356
+ # was in it. It only reads.
357
+ task_events() {
358
+ local json=0 only='' asked=0 args=()
359
+ while [ "$#" -gt 0 ]; do
360
+ case $1 in
361
+ --json) json=1 ;;
362
+ --step)
363
+ [ "$asked" = 0 ] || die "--step is given once: $EVENTS_USAGE"
364
+ [ "$#" -ge 2 ] && case $2 in --*) false ;; *) true ;; esac ||
365
+ die "--step takes the step to list, one of $HOST_WRITE_UP_STEPS $HOST_BUILD_STEPS: $EVENTS_USAGE"
366
+ asked=1 only=$2
367
+ shift
368
+ ;;
369
+ -*) die "$EVENTS_USAGE" ;;
370
+ *) args+=("$1") ;;
371
+ esac
372
+ shift
373
+ done
374
+ set -- ${args[@]+"${args[@]}"}
375
+ local name=${1:-} card=${2:-}
376
+ [ -n "$name" ] || die "$EVENTS_USAGE"
377
+ space_named "$name" || die "there is no ocnus space called '$name'. See: ocnus space ls"
378
+ [ "$#" -le 2 ] || die "$EVENTS_USAGE"
379
+ card=$(handoff_card "$name" "$card" events) || exit 1
380
+ [ "$asked" = 0 ] || in_list "$only" "$HOST_WRITE_UP_STEPS $HOST_BUILD_STEPS" ||
381
+ die "'$only' is not a step an agent runs. Ask for one of: $HOST_WRITE_UP_STEPS $HOST_BUILD_STEPS"
382
+ have_sqlite || die "$SQLITE is not installed, so no hand-offs have been recorded on this machine."
383
+ command -v jq >/dev/null 2>&1 ||
384
+ die "jq is not installed, so the transcripts of the card's agents cannot be read. Install it, then run this again."
385
+
386
+ local base rows sessions out
387
+ base=$(events_base "$name" "$card") && [ -n "$base" ] ||
388
+ die "could not read the hand-offs in $STORE. It may not be ocnus's store."
389
+ rows=$(jq -r '.rows' <<< "$base") || die "could not read the hand-offs in $STORE. It may not be ocnus's store."
390
+ sessions=''
391
+ [ "$rows" = 0 ] || sessions=$(events_sessions "$name" "$card" "$only") ||
392
+ die "could not read the hand-offs in $STORE. It may not be ocnus's store."
393
+ out=$(printf '%s' "$sessions" | jq -s -c --argjson base "$base" --arg only "$only" --arg space "$name" \
394
+ --arg card "$card" --arg writeup "$HOST_WRITE_UP_STEPS" --arg building "$HOST_BUILD_STEPS" \
395
+ --argjson max "$EVENTS_TEXT_MAX" "$EVENTS_DEFS$EVENTS_JOIN") && [ -n "$out" ] ||
396
+ die "could not put what $card's agents did under its steps."
397
+ if [ "$json" = 1 ]; then
398
+ printf '%s\n' "$out"
399
+ else
400
+ jq -r --argjson rows "$rows" --arg only "$only" "$EVENTS_WORDS" <<< "$out"
401
+ fi
402
+ }
403
+
404
+ # Print the card's steps for EVENTS_JOIN, as one line of JSON: rows, how
405
+ # many hand-offs it has; news, the second of each `new` row, which begins a
406
+ # run; and steps, each with its number n, its run, the step, the seconds it
407
+ # started and ended, s and e, and whether it is open. With no store it has
408
+ # none. The steps are worked out as host_card works them out, from the same
409
+ # view, so that a step here is the step there.
410
+ # events_base <space> <card>
411
+ events_base() {
412
+ local now
413
+ if [ ! -e "$STORE" ]; then
414
+ printf '{"rows":0,"news":[],"steps":[]}\n'
415
+ return 0
416
+ fi
417
+ now=$(date +%s)
418
+ store "$STORE" "$(log_view "$1" "$2"),
419
+ flagged(id, run, step, kind, status, next, after, t, prev_t, first) as (
420
+ select id, run, step, kind, status, next, after,
421
+ cast(strftime('%s', at) as integer), cast(strftime('%s', prev_at) as integer),
422
+ case when lag(step) over (order by id) is step then 0 else 1 end
423
+ from shown),
424
+ grouped(id, run, step, kind, status, next, after, t, prev_t, g) as (
425
+ select id, run, step, kind, status, next, after, t, prev_t,
426
+ sum(first) over (order by id rows between unbounded preceding and current row)
427
+ from flagged),
428
+ spans(g, first_id, last_id) as (
429
+ select g, min(id), max(id) from grouped where kind != 'start' group by g),
430
+ latest(run, step, t, under) as (
431
+ select run, step, t, case when status in ('answered', 'needs-human') then step
432
+ when status = 'done' and coalesce(next, '') not in ('', 'start', 'setup', 'merged') then next end
433
+ from grouped where after is null),
434
+ ended(o, run, step, s, e, open) as (
435
+ select sp.g, l.run, l.step, coalesce(f.prev_t, f.t), l.t, l.after is null and l.step is u.under
436
+ from spans sp join grouped f on f.id = sp.first_id join grouped l on l.id = sp.last_id left join latest u on 1
437
+ union all
438
+ select (select max(g) from grouped) + 1, run, under, t, t, 1 from latest
439
+ where under is not null and under is not step),
440
+ steps(n, run, step, s, e, open) as (
441
+ select row_number() over (order by o), run, step, s, case when open then max($now, e) else e end, open from ended)
442
+ select json_object('rows', (select count(*) from shown),
443
+ 'news', json((select json_group_array(cast(strftime('%s', at) as integer)) from shown where step = 'new')),
444
+ 'steps', json((select json_group_array(json(entry)) from (
445
+ select json_object('n', n, 'run', run, 'step', step, 's', s, 'e', e,
446
+ 'open', json(case when open then 'true' else 'false' end)) as entry
447
+ from steps order by n))));"
448
+ }
449
+
450
+ # Print each of the card's sessions, oldest first, as a line of JSON for
451
+ # EVENTS_JOIN: what EVENTS_READ makes of its transcript, or, for one with no
452
+ # session ID, as an agent in another harness has, or whose transcript Claude
453
+ # Code no longer keeps or that could not be read, when it started and its
454
+ # phase, with read false. A session recorded twice is read once. With a step
455
+ # asked for, only the sessions of that step's phase are read. It fails only
456
+ # when the store cannot be read.
457
+ # events_sessions <space> <card> [<step>]
458
+ events_sessions() {
459
+ local rows at phase harness session file one want='' seen=' '
460
+ if [ -n "${3:-}" ]; then
461
+ want=build
462
+ ! in_list "$3" "$HOST_WRITE_UP_STEPS" || want=write-up
463
+ fi
464
+ rows=$(card_sessions "$1" "$2") || return 1
465
+ while IFS=$SESSION_SEP read -r at phase harness session; do
466
+ [ -n "$at" ] || continue
467
+ [ -z "$want" ] || [ "$phase" = "$want" ] || continue
468
+ one=''
469
+ if [ -n "$session" ] && file=$(session_transcript "$session"); then
470
+ case $seen in
471
+ *" $session "*) one="{\"at\":\"$(json_str "$at")\",\"phase\":\"$(json_str "$phase")\",\"read\":true}" ;;
472
+ *)
473
+ seen="$seen$session "
474
+ one=$(jq -R -n -c --arg at "$at" --arg phase "$phase" --argjson max "$EVENTS_TEXT_MAX" \
475
+ "$EVENTS_DEFS$EVENTS_READ" < "$file" 2>/dev/null) || one=''
476
+ ;;
477
+ esac
478
+ fi
479
+ [ -n "$one" ] || one="{\"at\":\"$(json_str "$at")\",\"phase\":\"$(json_str "$phase")\",\"read\":false}"
480
+ printf '%s\n' "$one"
481
+ done <<< "$rows"
482
+ }
package/cli/lib/guard.sh CHANGED
@@ -35,6 +35,8 @@ is_worktree_copy() {
35
35
  # GitHub, but it records the merges it sees and moves their cards in Linear,
36
36
  # so it is not a read and is not here. `task asks` reads the questions that
37
37
  # wait on the human, from the store, the files beside it and hc. `task
38
+ # events` reads a card's steps from the store and what its agents did from
39
+ # the transcripts Claude Code keeps, and writes nothing. `task
38
40
  # answer` types into an agent's terminal or merges pull requests on GitHub,
39
41
  # and `task hold`, the hook behind a permission prompt, writes its question
40
42
  # and can allow a tool, so neither is a read. Nor is `task brief`, though it
@@ -113,7 +115,7 @@ is_read() {
113
115
  ;;
114
116
  task)
115
117
  case ${2:-} in
116
- ls | list | log | asks) return 0 ;;
118
+ ls | list | log | asks | events) return 0 ;;
117
119
  *) return 1 ;;
118
120
  esac
119
121
  ;;
@@ -155,7 +157,7 @@ guard_worktree() {
155
157
  [ "${OCNUS_LIVE:-}" != 1 ] || return 0
156
158
  GUARDED=1
157
159
  ! is_read "$@" || return 0
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.
160
+ 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, task events, 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.
159
161
  - For the card's own steps, such as recording a hand-off, run plain \`ocnus\`: the copy this machine runs, not this one.
160
162
  - To try a command that changes the machine, write a test case for it, in test/.
161
163
  - To run it on this machine for real, only when that is wanted: