@johngaynor/ocnus 0.0.0-stage → 2.0.0

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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +988 -2
  3. package/agents/linear-mcp.json +1 -0
  4. package/agents/ocnus-build.md +23 -0
  5. package/agents/ocnus-write-up.md +20 -0
  6. package/cli/host-mark +36 -0
  7. package/cli/lib/agents.sh +350 -0
  8. package/cli/lib/approval.sh +94 -0
  9. package/cli/lib/archive.sh +447 -0
  10. package/cli/lib/billing.sh +166 -0
  11. package/cli/lib/close.sh +189 -0
  12. package/cli/lib/commands.sh +220 -0
  13. package/cli/lib/common.sh +215 -0
  14. package/cli/lib/finish.sh +288 -0
  15. package/cli/lib/github.sh +162 -0
  16. package/cli/lib/guard.sh +134 -0
  17. package/cli/lib/handoff.sh +551 -0
  18. package/cli/lib/host.sh +1802 -0
  19. package/cli/lib/linear.sh +1389 -0
  20. package/cli/lib/links.sh +135 -0
  21. package/cli/lib/merges.sh +853 -0
  22. package/cli/lib/recipes.sh +54 -0
  23. package/cli/lib/settings.sh +465 -0
  24. package/cli/lib/space.sh +343 -0
  25. package/cli/lib/task.sh +847 -0
  26. package/cli/lib/tests.sh +268 -0
  27. package/cli/lib/trust.sh +70 -0
  28. package/cli/ocnus +630 -0
  29. package/herdr/README.md +2238 -0
  30. package/herdr/layouts/default.json +259 -0
  31. package/herdr/mods/agent-settings/cog.svg +4 -0
  32. package/herdr/mods/agent-settings/main.js +356 -0
  33. package/herdr/mods/agent-settings/mod.json +1 -0
  34. package/herdr/mods/cards/main.js +450 -0
  35. package/herdr/mods/cards/mod.json +1 -0
  36. package/herdr/mods/cards/refresh.svg +4 -0
  37. package/herdr/mods/cpu/main.js +90 -0
  38. package/herdr/mods/cpu/mod.json +1 -0
  39. package/herdr/mods/layout-switch/main.js +48 -0
  40. package/herdr/mods/layout-switch/mod.json +1 -0
  41. package/herdr/mods/names/main.js +69 -0
  42. package/herdr/mods/names/mod.json +1 -0
  43. package/herdr/mods/ocnus-spaces/main.js +376 -0
  44. package/herdr/mods/ocnus-spaces/mod.json +1 -0
  45. package/herdr/mods/steps/main.js +354 -0
  46. package/herdr/mods/steps/mod.json +1 -0
  47. package/herdr/spaces/template/SPACE.md +19 -0
  48. package/package.json +27 -4
  49. package/prompts/task-build.md +11 -0
  50. package/prompts/task-new.md +17 -0
  51. package/skills/brief/SKILL.md +64 -0
  52. package/skills/sdlc-breakdown/SKILL.md +312 -0
  53. package/skills/sdlc-build/SKILL.md +182 -0
  54. package/skills/sdlc-define/SKILL.md +203 -0
  55. package/skills/sdlc-plan/SKILL.md +202 -0
  56. package/skills/sdlc-pr/SKILL.md +339 -0
  57. package/skills/sdlc-review/SKILL.md +227 -0
@@ -0,0 +1,853 @@
1
+ # ocnus's watch on the merges: the one watch on the pull requests of
2
+ # every card that waits on its merge. Sourced by cli/ocnus.
3
+ #
4
+ # Once a card's pull requests are open, its agent hands off pr needs-human
5
+ # and runs no watch of its own (sdlc-pr). ocnus's watch sees what happens
6
+ # to them instead, whatever the agent is doing: one terminal in herdr-core,
7
+ # named ocnus-merges, running `ocnus task merges`. Like the host
8
+ # recorder (host.sh) and `task close` (close.sh), its terminal has no labels,
9
+ # so the Herdr app does not show it and the recorder does not count it as an
10
+ # agent; no parent, so it outlives the tab that woke it; and --rm, so it is
11
+ # gone once it ends. A launchd agent brings it back after a restart (see
12
+ # merges_launchd, below), since herdr-core cannot: --keep puts a shell in
13
+ # place of a lost program and never runs the command again, and herdr-core
14
+ # runs nothing as it starts.
15
+ #
16
+ # Each pass reads the store for every card, in every space, whose latest
17
+ # hand-off is pr needs-human, however long ago: its pull requests wait on the
18
+ # human. It asks GitHub about the pull requests of all of them at once, in
19
+ # one call (github_pulls, in github.sh), however many cards wait, in however
20
+ # many spaces and repos, rather than once for each worktree of each card.
21
+ # Then it takes each card in turn, with what that call saw of its own. It
22
+ # leaves a card alone while:
23
+ # - a pull request is open, or GitHub could not be asked about one: the
24
+ # next pass looks again, and this watch records nothing and pushes
25
+ # nothing;
26
+ # - every pull request has merged, but its agent is busy, working, blocked
27
+ # or with an error, or runs a program that reports no status, so what it
28
+ # does is not known (card_seen). The next pass looks again.
29
+ # A pull request closed without merging, or in conflict with its default
30
+ # branch, wakes the card's agent (merge_wake_agent). An agent idle in the
31
+ # task's tab is told what was seen, and to bring it up to date or to ask the
32
+ # human whether to stop; one that has exited, with the tab's own shell in the
33
+ # foreground, is started again with `task build --continue` and that
34
+ # message. The agent then brings the pull request up to date, or asks the
35
+ # human about the closed one, as sdlc-pr says; this watch records and pushes
36
+ # nothing for it. A busy agent, or a closed tab, is not woken: the next pass
37
+ # looks again. It wakes the agent once for each closed or conflicting pull
38
+ # request, which it notes in the card's .woke file, and never for one the
39
+ # agent has recorded itself and is asking the human about.
40
+ # When every pull request has merged and the agent is not running, with its
41
+ # tab closed or its own shell in the foreground, or idle, its turn over, the
42
+ # watch records the merge (merge_record): the human's answer, then pr done
43
+ # with merged next, and the card moves to Done in Linear. Then it finishes
44
+ # the task (merge_finish): an idle agent is ended with /exit, as `task close`
45
+ # ends one, never killed, then `task finish` removes the task and closes its
46
+ # tab. A task that `task finish` refuses, as one that would lose work, or
47
+ # whose agent does not exit, is left as it is, with what is in the way on the
48
+ # merged row's flags, so that `task log` shows it. There is no later try: the
49
+ # card no longer waits, so the human finishes that task. No agent records the
50
+ # merge or runs `task finish` (sdlc-pr).
51
+ #
52
+ # A merge is recorded once. The watch's two rows go in one transaction, and
53
+ # only while the card's latest row is still pr needs-human, so an answer the
54
+ # agent recorded first keeps the card from being recorded until it asks
55
+ # again. Once the merge is recorded, `task handoff` refuses any block for the
56
+ # card (handoff.sh), so an agent that tries to record one after it records
57
+ # nothing.
58
+ #
59
+ # After a pass it sleeps MERGES_PAUSE, a minute, then runs itself again with
60
+ # exec, so that each pass runs the code the machine has then, even after
61
+ # `ocnus update`. It exits once no card waits. --once makes one pass.
62
+ #
63
+ # `task handoff` wakes it once it has recorded a pr needs-human, and `task
64
+ # new`, `task start` and `task build` wake it next to the host recorder, as
65
+ # `ocnus update` does, for the cards that were waiting before (merges_wake).
66
+ # The launchd agent that install and update write wakes it every minute too,
67
+ # with `task merges --wake`, so it is back within a minute of herdr-core
68
+ # starting after a restart, however herdr-core was started, and one that died
69
+ # comes back the same way. A wake never starts herdr-core, and hc lets one
70
+ # live terminal hold a name, so there is never more than one watch.
71
+ #
72
+ # What it saw is left for `task log`, which says when nothing can see a
73
+ # card's pull requests (merges_seen, read by card_agent in agents.sh), and
74
+ # for `ocnus status`, which says whether the watch runs (merges_status).
75
+ # As a pass begins it writes the time to merges/.alive, and after each card's
76
+ # turn it writes merges/<space>/<card>: on one line, the time, then what it
77
+ # saw (merges_saw). A pass whose call to GitHub failed as a whole writes
78
+ # merges/.gh: the time, sign-in when gh needs signing in or else failed, then
79
+ # gh's words. A pass whose call worked, or that asked GitHub nothing, removes
80
+ # it. All of them go once no card waits, as the watch ends then. They are
81
+ # files, not rows in the store, and `task log` and `status` read them afresh
82
+ # each time. .alive and .gh start with a dot, so that neither is ever a
83
+ # space's folder.
84
+
85
+ MERGES_TERMINAL=ocnus-merges
86
+ MERGES_USAGE='usage: ocnus task merges [--once | --wake]'
87
+ # The human's answer that the watch records once every pull request of a
88
+ # card has merged: the merge is theirs.
89
+ MERGES_ANSWER="merged on GitHub, seen by ocnus's watch"
90
+ # How long to sleep after a pass before the next, in seconds: a minute,
91
+ # however long the pull requests have been open, so that a merge is seen
92
+ # within a minute of it. The launchd agent wakes the watch as often. That is
93
+ # 60 calls to GitHub an hour, however many cards wait, far under the 5,000
94
+ # it allows.
95
+ MERGES_PAUSE=60
96
+
97
+ # Every card, in every space, whose latest hand-off is pr needs-human: its
98
+ # space, the unit separator, then the card, a line each, by space. Nothing
99
+ # when there is no store.
100
+ merges_waiting() {
101
+ [ -e "$STORE" ] || return 0
102
+ store -separator $'\x1f' "$STORE" "select space, card from (
103
+ select id, space, card, step, status,
104
+ row_number() over (partition by space, card order by id desc) as nth
105
+ from handoffs)
106
+ where nth = 1 and step = 'pr' and status = 'needs-human' order by space, id;"
107
+ }
108
+
109
+ # The worktrees of a card's task, as `task finish` finds them, each on its
110
+ # branch, as TASK_WTS and TASK_BRANCHES, in the same order, for the one call
111
+ # to GitHub. It fails with the reason in TASK_WHY, rather than exiting, so
112
+ # that a pass passes over a task it cannot watch and goes on.
113
+ # task_worktrees <the space's folder> <the task's folder> <card>
114
+ TASK_WTS=() TASK_BRANCHES=() TASK_WHY=''
115
+ task_worktrees() {
116
+ local dir=$1 tdir=$2 card=$3 f branch
117
+ TASK_WTS=() TASK_BRANCHES=() TASK_WHY=''
118
+ for f in "$tdir"/*; do
119
+ [ -f "$f/.git" ] && [ ! -L "$f" ] || continue
120
+ if ! branch=$(git -C "$f" symbolic-ref -q --short HEAD 2>/dev/null); then
121
+ TASK_WHY="the worktree ${f#"$dir"/} is not on a branch, so it has no pull request to watch."
122
+ return 1
123
+ fi
124
+ TASK_WTS+=("$f") TASK_BRANCHES+=("$branch")
125
+ done
126
+ [ "${#TASK_WTS[@]}" -gt 0 ] || {
127
+ TASK_WHY="$card's task, ${tdir#"$dir"/}, has no worktrees, so it has no pull request to watch."
128
+ return 1
129
+ }
130
+ }
131
+
132
+ # Start ocnus's watch on the merges while a card waits on its merge,
133
+ # unless it runs already. Nothing waits on it: it starts in the background,
134
+ # and a wake that fails, as a second one does since the name is taken, is
135
+ # ignored. It never starts herdr-core: with herdr-core not running, nothing is
136
+ # woken. The watch gets the PATH of what woke it, which found gh, since
137
+ # herdr-core may start it with a PATH that has none, and the same
138
+ # OCNUS_HOME, so that it reads the same store.
139
+ merges_wake() {
140
+ have_hc && have_sqlite || return 0
141
+ [ -n "$(merges_waiting 2>/dev/null)" ] || return 0
142
+ hc_cmd server status --json >/dev/null 2>&1 || return 0
143
+ local env=(PATH="$PATH")
144
+ [ -z "${OCNUS_HOME:-}" ] || env+=(OCNUS_HOME="$OCNUS_HOME")
145
+ hc_cmd run --bg --no-parent --rm --name "$MERGES_TERMINAL" --cwd "$ENT_HOME" \
146
+ -- /usr/bin/env "${env[@]}" "$REPO/cli/ocnus" task merges </dev/null >/dev/null 2>&1 || true
147
+ }
148
+
149
+ # --- the launchd agent that wakes the watch ---------------------------------
150
+ #
151
+ # After a restart nothing in Herdr starts the watch again, and herdr-core may
152
+ # be started by the Herdr app, from the phone or by an ocnus command, with
153
+ # or without the app open. So launchd, macOS's own, wakes it: install and
154
+ # update write a launchd agent into the user's LaunchAgents folder and load
155
+ # it into the user's own domain, gui/<uid>. launchd runs it once it is
156
+ # loaded, as at login, and every MERGES_PAUSE, a minute, after that. It runs
157
+ # `ocnus task merges --wake` (merges_wake), which starts the watch only
158
+ # while a card waits on its merge and herdr-core runs, so the watch is back
159
+ # within a minute of herdr-core starting. It never starts herdr-core.
160
+ MERGES_LABEL=com.johngaynor.ocnus.merges
161
+ MERGES_PLIST=$HOME/Library/LaunchAgents/$MERGES_LABEL.plist
162
+ # What launchd runs, with /bin/sh: the ocnus that wrote it is $0, the
163
+ # plist $1 and its service $2. Once that ocnus is gone, as after `npm
164
+ # uninstall`, the launchd agent removes its plist and boots itself out of
165
+ # launchd, so that no uninstall command is needed. They are arguments, never
166
+ # part of the line, so that nothing in a path is read by sh.
167
+ MERGES_SH='if [ -e "$0" ]; then exec "$0" task merges --wake; else rm -f "$1"; exec launchctl bootout "$2"; fi'
168
+
169
+ # A string as the text of a plist's <string>: &, < and > escaped. Most have
170
+ # none, and are printed as they are, with no program started.
171
+ # plist_str <string>
172
+ plist_str() {
173
+ case $1 in
174
+ *[\&\<\>]*) printf '%s' "$1" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g' ;;
175
+ *) printf '%s' "$1" ;;
176
+ esac
177
+ }
178
+
179
+ # The PATH that a plist merges_plist wrote gives the launchd agent, as it was
180
+ # before plist_str escaped it: the line after <key>PATH</key>, without its
181
+ # tags. Nothing when it has none.
182
+ # plist_path <plist>
183
+ plist_path() {
184
+ sed -n '/<key>PATH<\/key>/{n;s/^[[:space:]]*<string>\(.*\)<\/string>$/\1/p;q;}' "$1" 2>/dev/null |
185
+ sed -e 's/&lt;/</g' -e 's/&gt;/>/g' -e 's/&amp;/\&/g'
186
+ }
187
+
188
+ # The launchd agent's plist, for its service: gui/<uid>/<label>. It gives
189
+ # the launchd agent the PATH of the run that writes it, since launchd's own
190
+ # has no gh or hc, or the PATH given, and OCNUS_HOME when it is set, so
191
+ # that a wake reads the same store; merges_wake hands that PATH to the watch.
192
+ # A tag a line, indented with tabs.
193
+ # merges_plist <service> [<PATH>]
194
+ merges_plist() {
195
+ local a
196
+ printf '%s\n' '<?xml version="1.0" encoding="UTF-8"?>' \
197
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' \
198
+ '<plist version="1.0">' '<dict>'
199
+ printf '\t<key>Label</key>\n\t<string>%s</string>\n' "$MERGES_LABEL"
200
+ printf '\t<key>ProgramArguments</key>\n\t<array>\n'
201
+ for a in /bin/sh -c "$MERGES_SH" "$REPO/cli/ocnus" "$MERGES_PLIST" "$1"; do
202
+ printf '\t\t<string>%s</string>\n' "$(plist_str "$a")"
203
+ done
204
+ printf '\t</array>\n\t<key>EnvironmentVariables</key>\n\t<dict>\n'
205
+ printf '\t\t<key>PATH</key>\n\t\t<string>%s</string>\n' "$(plist_str "${2-$PATH}")"
206
+ [ -z "${OCNUS_HOME:-}" ] ||
207
+ printf '\t\t<key>OCNUS_HOME</key>\n\t\t<string>%s</string>\n' "$(plist_str "$OCNUS_HOME")"
208
+ printf '\t</dict>\n\t<key>RunAtLoad</key>\n\t<true/>\n'
209
+ printf '\t<key>StartInterval</key>\n\t<integer>%s</integer>\n' "$MERGES_PAUSE"
210
+ printf '%s\n' '</dict>' '</plist>'
211
+ }
212
+
213
+ # Write the launchd agent and load it, for install and update, saying what
214
+ # it did, as link_all says its lines. One loaded already, whose plist is as
215
+ # it would be written now, is left as it is. One whose plist has changed,
216
+ # such as with another PATH, is written again, then booted out, since launchd
217
+ # keeps what it loaded, and loaded again. One booted out by hand is loaded
218
+ # again. A machine with no launchctl has no launchd, so nothing is written,
219
+ # and the watch comes back only with the next command that wakes it. Nothing
220
+ # here stops install or update: what could not be done is said.
221
+ #
222
+ # With state, for status, it writes, loads and asks launchd nothing, and
223
+ # prints one word: written, when the plist is what install and update would
224
+ # write now; missing; stale, when it is not; or none, with no launchctl. It is
225
+ # compared with the PATH the plist has, not this run's: status may be run
226
+ # with another PATH than update was, and a PATH with no gh or hc in it shows
227
+ # as a watch that does not run.
228
+ # merges_launchd [state]
229
+ merges_launchd() {
230
+ local uid service text changed=0 loaded=0 tmp why
231
+ if [ "${1:-}" = state ]; then
232
+ command -v launchctl >/dev/null 2>&1 || { say none; return 0; }
233
+ [ -e "$MERGES_PLIST" ] || [ -L "$MERGES_PLIST" ] || { say missing; return 0; }
234
+ uid=$(id -u) && service=gui/$uid/$MERGES_LABEL
235
+ if [ "$(cat "$MERGES_PLIST" 2>/dev/null)" = "$(merges_plist "$service" "$(plist_path "$MERGES_PLIST")")" ]; then
236
+ say written
237
+ else
238
+ say stale
239
+ fi
240
+ return 0
241
+ fi
242
+ say "Loading the launchd agent that wakes ocnus's watch on the merges after a restart"
243
+ command -v launchctl >/dev/null 2>&1 || {
244
+ say " skipped launchctl is not on this machine, so ocnus's watch on the merges does not come back after a restart on its own"
245
+ return 0
246
+ }
247
+ uid=$(id -u) && service=gui/$uid/$MERGES_LABEL
248
+ text=$(merges_plist "$service")
249
+ [ "$(cat "$MERGES_PLIST" 2>/dev/null)" = "$text" ] || changed=1
250
+ ! launchctl print "$service" >/dev/null 2>&1 || loaded=1
251
+ if [ "$changed" = 0 ] && [ "$loaded" = 1 ]; then
252
+ say " already loaded $MERGES_PLIST"
253
+ return 0
254
+ fi
255
+ if [ "$changed" = 1 ]; then
256
+ # Written beside itself and moved into place whole, so that launchd
257
+ # never reads half of one.
258
+ tmp=$MERGES_PLIST.ocnus.$$
259
+ if ! { mkdir -p "${MERGES_PLIST%/*}" && printf '%s\n' "$text" > "$tmp" && mv -f "$tmp" "$MERGES_PLIST"; } 2>/dev/null; then
260
+ rm -f "$tmp" 2>/dev/null || true
261
+ say " problem could not write $MERGES_PLIST, so ocnus's watch on the merges does not come back after a restart on its own"
262
+ return 0
263
+ fi
264
+ [ "$loaded" = 0 ] || launchctl bootout "$service" >/dev/null 2>&1 || true
265
+ fi
266
+ if why=$(launchctl bootstrap "gui/$uid" "$MERGES_PLIST" 2>&1); then
267
+ if [ "$loaded" = 1 ]; then say " reloaded $MERGES_PLIST (it had changed)"
268
+ else say " loaded $MERGES_PLIST"
269
+ fi
270
+ else
271
+ why=$(printf '%s' "$why" | tr -s '\n' ' ')
272
+ why=${why% }
273
+ say " problem launchctl could not load $MERGES_PLIST${why:+ ($why)}, so ocnus's watch on the merges does not come back after a restart on its own. Run: ocnus update"
274
+ fi
275
+ }
276
+
277
+ # Finish a card's task once its merge is recorded, which no agent does. The
278
+ # tab is the one merges_check found with card_seen. An
279
+ # agent idle in it is ended first, as `task close` ends one: /exit, then up to
280
+ # CLOSE_EXIT_WAIT seconds for its shell, and never killed (end_agent, with
281
+ # nowait, so that a turn started since the pass looked is not waited on).
282
+ # Once no agent runs there, task_finish removes the task's worktrees, branch
283
+ # and folder, then closes the tab, or with the app closed ends its terminals
284
+ # in herdr-core. It runs in a subshell, since it changes folder and stops
285
+ # with exit, and with -e, as when it is run as a command; what it says is
286
+ # printed. When the task is left as it is, FINISH_LEFT says what is in the
287
+ # way, and it is empty once the task is finished.
288
+ # merge_finish <space> <card ID, in upper case>
289
+ FINISH_LEFT=''
290
+ merge_finish() {
291
+ local space=$1 card=$2 low sep=$'\x1f' name terms all='' t rc=0 out line
292
+ FINISH_LEFT=''
293
+ case $AGENT_SEEN in
294
+ idle | done)
295
+ # Every terminal of the tabs card_seen looked in.
296
+ low=$(printf '%s' "$card" | tr '[:upper:]' '[:lower:]')
297
+ while IFS=$sep read -r name terms; do
298
+ case $name in "$low" | "$low"-*) all="$all $terms" ;; esac
299
+ done <<< "$AGENT_TABS"
300
+ # Before any agent is ended: a program in the tab that reports no
301
+ # status keeps the tab open, so the task is left whole.
302
+ for t in $all; do
303
+ [ "$(terminal_doing "$t")" != unknown ] || {
304
+ FINISH_LEFT="$t, in its tab, runs a program that reports no status, so it is left running"
305
+ say " agent $FINISH_LEFT"
306
+ return 0
307
+ }
308
+ done
309
+ for t in $all; do
310
+ end_agent "$t" nowait || { FINISH_LEFT='its agent did not exit'; return 0; }
311
+ done
312
+ ;;
313
+ esac
314
+ out=$(set -e; task_finish "$space" "$card" 2>&1) || rc=$?
315
+ [ -z "$out" ] || printf '%s\n' "$out"
316
+ [ "$rc" != 0 ] || return 0
317
+ # What task_finish named, a line each, joined, without the indents or the
318
+ # name die puts before its last line.
319
+ while IFS= read -r line; do
320
+ line=${line#"${line%%[![:space:]]*}"}
321
+ line=${line#ocnus: }
322
+ [ -z "$line" ] || FINISH_LEFT=${FINISH_LEFT:+$FINISH_LEFT; }$line
323
+ done <<< "$out"
324
+ [ -n "$FINISH_LEFT" ] || FINISH_LEFT="task finish stopped (exit $rc) without saying why"
325
+ }
326
+
327
+ # Record a card's merge: the human's answer, then pr done with merged next,
328
+ # naming each pull request. Both go in one transaction,
329
+ # and only while the card's latest row is still pr needs-human. Then the
330
+ # card moves to Done in Linear, and with archiving on what is closed is
331
+ # archived (merge_linear), and what that said is printed. Last, the task is
332
+ # finished (merge_finish). No one reads this
333
+ # watch's output, so what still needs the human goes on the merged row's
334
+ # flags, which `task log` shows under it: a card that was not moved, then
335
+ # what kept the task from being finished, as `task not finished: …`. They are
336
+ # cut to fit HANDOFF_LINE_MAX, the most a line of a block may hold. It fails
337
+ # when it recorded nothing.
338
+ # merge_record <space> <card ID, in upper case> <each pull request's URL, a space between>
339
+ merge_record() {
340
+ local space=$1 card=$2 urls=$3 at s c summary id notes line kept=''
341
+ at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
342
+ s=$(sql_str "$space") c=$(sql_str "$card")
343
+ summary="Merged on GitHub: ${urls// /, }. Recorded by ocnus's watch."
344
+ # -bail: a statement that fails ends the run, so that the transaction is
345
+ # rolled back rather than going on without it.
346
+ id=$(store -bail "$STORE" "begin immediate;
347
+ insert into handoffs (at, space, card, step, status, answer)
348
+ select $(sql_str "$at"), $s, $c, 'pr', 'answered', $(sql_str "$MERGES_ANSWER")
349
+ where (select step || ' ' || status from handoffs where space = $s and card = $c
350
+ order by id desc limit 1) = 'pr needs-human';
351
+ insert into handoffs (at, space, card, step, status, next, summary)
352
+ select $(sql_str "$at"), $s, $c, 'pr', 'done', 'merged', $(sql_str "$summary")
353
+ where changes() = 1;
354
+ select case when changes() = 1 then last_insert_rowid() else '' end;
355
+ commit;") || return 1
356
+ case $id in '' | *[!0-9]*) return 1 ;; esac
357
+ say "$card in '$space': every pull request has merged, so the merge is recorded"
358
+ notes=$(merge_linear "$space" "$card" 2>&1)
359
+ [ -z "$notes" ] || printf '%s\n' "$notes"
360
+ while IFS= read -r line; do
361
+ [[ $line =~ $NOT_MOVED_RE ]] || continue
362
+ kept=${kept:+$kept; }$(plain_note "$line")
363
+ done <<< "$notes"
364
+ merge_finish "$space" "$card"
365
+ [ -z "$FINISH_LEFT" ] || {
366
+ say "$card's task is left as it is, and task log says why"
367
+ kept=${kept:+$kept; }$(plain_note "task not finished: $FINISH_LEFT")
368
+ }
369
+ [ "${#kept}" -le "$HANDOFF_LINE_MAX" ] || kept="${kept:0:$((HANDOFF_LINE_MAX - 3))}..."
370
+ [ -z "$kept" ] ||
371
+ store "$STORE" "update handoffs set flags = coalesce(flags || '; ', '') || $(sql_str "$kept") where id = $id;" ||
372
+ say "could not add to the merge what still needs the human, so task log does not show it: $kept"
373
+ }
374
+
375
+ # What ocnus's watch woke a card's agent for, a line each: closed or
376
+ # conflict, then the pull request's URL. A state already there wakes nothing.
377
+ # A line is dropped once its pull request shows another state, so that a new
378
+ # conflict after it was brought up to date wakes the agent again. The file
379
+ # goes once the card no longer waits on its merge, as when its agent has
380
+ # recorded what it was woken for: the agent has taken it up by then.
381
+ # woke_file <space> <card ID, in upper case>
382
+ woke_file() { printf '%s/merges/%s/%s.woke' "$ENT_HOME" "$1" "$2"; }
383
+
384
+ # Remove a card's .woke file, and its space's folder and the merges folder
385
+ # once they hold nothing.
386
+ # woke_forget <the card's .woke file>
387
+ woke_forget() {
388
+ [ -e "$1" ] || return 0
389
+ rm -f "$1"
390
+ rmdir "${1%/*}" "${1%/*/*}" 2>/dev/null || true
391
+ }
392
+
393
+ # Drop each line of a card's .woke file whose pull request the check saw in
394
+ # another state. One that GitHub could not be asked about is kept.
395
+ # woke_keep <the card's .woke file> <the check's lines>
396
+ woke_keep() {
397
+ local woke=$1 check=$2 state url s u now kept=''
398
+ [ -f "$woke" ] || return 0
399
+ while read -r state url; do
400
+ [ -n "$url" ] || continue
401
+ now=''
402
+ while read -r s u; do [ "$u" != "$url" ] || now=$s; done < "$check"
403
+ [ -z "$now" ] || [ "$now" = "$state" ] || continue
404
+ kept="$kept$state $url"$'\n'
405
+ done < "$woke"
406
+ if [ -n "$kept" ]; then printf '%s' "$kept" > "$woke"; else woke_forget "$woke"; fi
407
+ }
408
+
409
+ # Remove the .woke file, and the file of what the watch saw, of each card
410
+ # that no longer waits on its merge. With none waiting, the watch ends, so
411
+ # .alive and .gh go too, then each folder left with nothing in it.
412
+ # merges_tidy <the cards that wait, as merges_waiting prints them>
413
+ merges_tidy() {
414
+ local waiting=$1 f space card sep=$'\x1f'
415
+ for f in "$ENT_HOME"/merges/*/*; do
416
+ [ -f "$f" ] || continue
417
+ card=${f##*/}
418
+ case $card in
419
+ *.woke) card=${card%.woke} ;;
420
+ *.*) continue ;;
421
+ esac
422
+ space=${f%/*} space=${space##*/}
423
+ case $'\n'$waiting$'\n' in *$'\n'"$space$sep$card"$'\n'*) ;; *) rm -f "$f" ;; esac
424
+ done
425
+ [ -n "$waiting" ] || rm -f "$ENT_HOME/merges/.alive" "$ENT_HOME/merges/.gh"
426
+ rmdir "$ENT_HOME"/merges/*/ "$ENT_HOME/merges" 2>/dev/null || true
427
+ }
428
+
429
+ # What a check of a card's pull requests saw, as MERGES_SAW, for the card's
430
+ # file: closed and the URL of each closed without merging, as a closed one
431
+ # comes first; else conflict and each in conflict; else failed and why
432
+ # GitHub could not be asked about one; else open while one is open, merged
433
+ # once all have, or none when the card has none. It is none too for a card
434
+ # the pass did not check, as one whose task is not on this machine.
435
+ # merges_saw <the check's lines>
436
+ MERGES_SAW=none
437
+ merges_saw() {
438
+ local state url closed='' conflict=''
439
+ while read -r state url; do
440
+ case $state in
441
+ closed) closed=${closed:+$closed }$url ;;
442
+ conflict) conflict=${conflict:+$conflict }$url ;;
443
+ esac
444
+ done < "$1"
445
+ if [ -n "$closed" ]; then MERGES_SAW="closed $closed"
446
+ elif [ -n "$conflict" ]; then MERGES_SAW="conflict $conflict"
447
+ elif [ "$CHECK_FAILED" -gt 0 ]; then MERGES_SAW="failed $(plain_note "$CHECK_WHY")"
448
+ elif [ "$CHECK_OPEN" -gt 0 ]; then MERGES_SAW=open
449
+ elif [ "$CHECK_MERGED" -gt 0 ]; then MERGES_SAW=merged
450
+ else MERGES_SAW=none
451
+ fi
452
+ }
453
+
454
+ # Write a file for `task log` and `status` in the merges folder: the line
455
+ # given, written whole, so that neither ever reads half of it.
456
+ # merges_write <the file, under merges/> <line>
457
+ merges_write() {
458
+ local f=$ENT_HOME/merges/$1
459
+ mkdir -p "${f%/*}" && printf '%s\n' "$2" > "$f.new" && mv -f "$f.new" "$f" ||
460
+ say "could not write $f, so task log and status may not say what ocnus's watch saw"
461
+ }
462
+
463
+ # A pull request's URL as its repo and number: acme/api#7. Anything else is
464
+ # left as it is.
465
+ # pull_name <URL>
466
+ PULL_NAME=''
467
+ pull_name() {
468
+ local re='^https?://[^/]+/([^/]+)/([^/]+)/pull/([0-9]+)'
469
+ if [[ $1 =~ $re ]]; then
470
+ PULL_NAME="${BASH_REMATCH[1]}/${BASH_REMATCH[2]}#${BASH_REMATCH[3]}"
471
+ else
472
+ PULL_NAME=$1
473
+ fi
474
+ }
475
+
476
+ # What `task log` reads once a run: the time now, and whether herdr-core
477
+ # answers, each read only once some card needs it.
478
+ MERGES_NOW='' MERGES_CORE=''
479
+
480
+ # What can see the pull requests of a card whose latest hand-off is pr
481
+ # needs-human, for `task log` (card_agent), from what ocnus's watch left
482
+ # (merges_tidy) and what runs. It reads and changes nothing else. MERGES_SEEN
483
+ # is:
484
+ # '' ocnus's watch is watching them, or nothing is
485
+ # known: it ran a pass within MERGES_FRESH seconds and
486
+ # saw them open, merged or none, or has not seen the
487
+ # card in that time
488
+ # closed, conflict ocnus's watch is running and, within MERGES_FRESH
489
+ # seconds, saw one closed without merging or in
490
+ # conflict: MERGES_PULLS are their URLs, a space between
491
+ # unwatched nothing can watch them: MERGES_WHY says why. Herdr's
492
+ # hc is not installed, herdr-core is not running,
493
+ # ocnus's watch has not begun a pass within
494
+ # MERGES_FRESH seconds, or GitHub could not be asked, as
495
+ # its last pass saw
496
+ # Whether an agent runs to be woken is card_agent's to say.
497
+ # merges_seen <space> <card ID, in upper case>
498
+ MERGES_FRESH=$((3 * MERGES_PAUSE))
499
+ MERGES_SEEN='' MERGES_PULLS='' MERGES_WHY=''
500
+ merges_seen() {
501
+ local space=$1 card=$2 at what rest
502
+ MERGES_SEEN='' MERGES_PULLS='' MERGES_WHY=''
503
+ MERGES_SEEN=unwatched
504
+ have_hc || { MERGES_WHY="Herdr's hc not installed"; return 0; }
505
+ if [ -z "$MERGES_CORE" ]; then
506
+ if hc_cmd server status --json >/dev/null 2>&1; then MERGES_CORE=up; else MERGES_CORE=down; fi
507
+ fi
508
+ [ "$MERGES_CORE" = up ] || { MERGES_WHY='herdr-core not running'; return 0; }
509
+ [ -n "$MERGES_NOW" ] || MERGES_NOW=$(date +%s)
510
+ # A file that is not there leaves the time empty, which is not fresh.
511
+ at=''
512
+ { read -r at < "$ENT_HOME/merges/.alive"; } 2>/dev/null || true
513
+ merges_fresh "$at" || { MERGES_WHY="ocnus's watch not running"; return 0; }
514
+ MERGES_SEEN=''
515
+ at='' what='' rest=''
516
+ { read -r at what rest < "$ENT_HOME/merges/$space/$card"; } 2>/dev/null || true
517
+ merges_fresh "$at" || return 0
518
+ rest=${rest//[[:cntrl:]]/ }
519
+ case $what in
520
+ closed | conflict) [ -z "$rest" ] || MERGES_SEEN=$what MERGES_PULLS=$rest ;;
521
+ failed) MERGES_SEEN=unwatched MERGES_WHY=${rest:-gh failed} ;;
522
+ esac
523
+ }
524
+
525
+ # Whether a time in seconds, as the watch writes it, is less than
526
+ # MERGES_FRESH seconds before MERGES_NOW.
527
+ # merges_fresh <time>
528
+ merges_fresh() {
529
+ case $1 in '' | *[!0-9]*) return 1 ;; esac
530
+ [ $((MERGES_NOW - $1)) -lt "$MERGES_FRESH" ]
531
+ }
532
+
533
+ # What `ocnus status` says of ocnus's watch on the merges, under a
534
+ # heading of its own, as status prints its lines: one for the watch, one for
535
+ # what its last pass found of gh when that needs saying, and last one for the
536
+ # launchd agent that brings the watch back after a restart (merges_launchd
537
+ # state). It reads what the watch leaves, as merges_seen does for `task log`,
538
+ # and the store, and starts nothing: no terminal, no herdr-core, no launchd
539
+ # agent and no wake, so that a worktree's copy may run it. Its exit code is
540
+ # the number of problems it printed. The watch is:
541
+ # running it began a pass within MERGES_FRESH seconds, and herdr-core
542
+ # runs: how long ago, and how many cards wait on their merge
543
+ # not running with no card waiting on its merge, which is in order
544
+ # a problem with cards waiting, and neither: ocnus update wakes it,
545
+ # once herdr-core runs, which an update never starts
546
+ # While cards wait, a last pass within MERGES_FRESH seconds that found gh
547
+ # needing a sign-in is a problem, and one that could not ask GitHub for
548
+ # another reason is a note: it asks again each minute.
549
+ # merges_status <herdr-core, as status found it: up, down, or none when Herdr is not installed>
550
+ merges_status() {
551
+ local core=$1 waiting='' line n=0 cards at='' ago how words problems=0
552
+ say "Watch on the merges: $MERGES_TERMINAL, in herdr-core"
553
+ if have_sqlite && ! waiting=$(merges_waiting); then
554
+ printf ' %-10s %s\n' note "the hand-offs in $STORE could not be read, so which cards wait on their merge is not known"
555
+ waiting=''
556
+ fi
557
+ while IFS= read -r line; do [ -z "$line" ] || n=$((n + 1)); done <<< "$waiting"
558
+ case $n in
559
+ 0) cards='no card waits on its merge' ;;
560
+ 1) cards='1 card waits on its merge' ;;
561
+ *) cards="$n cards wait on their merge" ;;
562
+ esac
563
+ MERGES_NOW=$(date +%s)
564
+ { read -r at < "$ENT_HOME/merges/.alive"; } 2>/dev/null || at=''
565
+ if [ "$core" = up ] && merges_fresh "$at"; then
566
+ ago=$((MERGES_NOW - at))
567
+ [ "$ago" -ge 0 ] || ago=0
568
+ took_text "$ago"
569
+ printf ' %-10s %s\n' watch "running: its last pass began $TOOK ago, and $cards"
570
+ elif [ "$n" = 0 ]; then
571
+ printf ' %-10s %s\n' watch "not running; $cards, so nothing needs it"
572
+ else
573
+ problems=$((problems + 1))
574
+ case $core in
575
+ down) line="the watch is not running, and $cards. It runs in herdr-core, which is not running, and an update never starts it. Start it with: hc server start, then run: ocnus update" ;;
576
+ none) line="the watch is not running, and $cards. It runs in herdr-core, and Herdr is not installed. Install it, then run: ocnus update" ;;
577
+ *)
578
+ case $at in
579
+ '' | *[!0-9]*) line="the watch is not running, and $cards. Run: ocnus update" ;;
580
+ *)
581
+ took_text $((MERGES_NOW - at))
582
+ line="the watch has not begun a pass for $TOOK, and $cards. Run: ocnus update"
583
+ ;;
584
+ esac
585
+ ;;
586
+ esac
587
+ printf ' %-10s %s\n' problem "$line"
588
+ fi
589
+ if [ "$n" -gt 0 ]; then
590
+ at='' how='' words=''
591
+ { read -r at how words < "$ENT_HOME/merges/.gh"; } 2>/dev/null || at=''
592
+ if merges_fresh "$at"; then
593
+ words=${words//[[:cntrl:]]/ }
594
+ if [ "$how" = sign-in ]; then
595
+ problems=$((problems + 1))
596
+ printf ' %-10s %s\n' problem "gh needs signing in to GitHub, so the watch cannot see the pull requests of the cards that wait on their merge${words:+ ($words)}. Sign in with: gh auth login"
597
+ else
598
+ printf ' %-10s %s\n' note "the watch's last pass could not ask GitHub${words:+ ($words)}, and it asks again each minute"
599
+ fi
600
+ fi
601
+ fi
602
+ case $(merges_launchd state) in
603
+ written) printf ' %-10s %s\n' launchd "written: $MERGES_PLIST" ;;
604
+ none) printf ' %-10s %s\n' note "launchctl is not on this machine, so the watch does not come back after a restart on its own" ;;
605
+ missing)
606
+ problems=$((problems + 1))
607
+ printf ' %-10s %s\n' problem "the launchd agent that brings the watch back after a restart is missing: $MERGES_PLIST. Run: ocnus update"
608
+ ;;
609
+ *)
610
+ problems=$((problems + 1))
611
+ printf ' %-10s %s\n' problem "the launchd agent that brings the watch back after a restart is out of date: $MERGES_PLIST. Run: ocnus update"
612
+ ;;
613
+ esac
614
+ return "$problems"
615
+ }
616
+
617
+ # Whether the card's agent has seen the pull request so itself: since the
618
+ # card's latest hand-off of another step, it recorded the pr step's answer
619
+ # naming that state and that pull request, as sdlc-pr does when this watch
620
+ # has woken it, and as it did before when its own watch ended with 3 or 4.
621
+ # It is bringing it up to date then, or asking the human about it.
622
+ # agent_saw <space> <card ID, in upper case> <closed|conflict> <the pull request's URL>
623
+ agent_saw() {
624
+ local s c said answers answer
625
+ s=$(sql_str "$1") c=$(sql_str "$2")
626
+ case $3 in closed) said='closed on GitHub' ;; *) said='in conflict on GitHub' ;; esac
627
+ answers=$(store "$STORE" "select coalesce(answer, '') from handoffs
628
+ where space = $s and card = $c and step = 'pr' and status = 'answered'
629
+ and id > coalesce((select max(id) from handoffs where space = $s and card = $c and step <> 'pr'), 0);") ||
630
+ return 1
631
+ while IFS= read -r answer; do
632
+ case $answer in "$said, "*"$4") return 0 ;; esac
633
+ done <<< "$answers"
634
+ return 1
635
+ }
636
+
637
+ # The first terminal of the card's task tab, as card_seen found them, that
638
+ # terminal_doing says is one of the words given.
639
+ # wake_terminal <the card in lower case> <word>...
640
+ wake_terminal() {
641
+ local low=$1 sep=$'\x1f' name terms t doing
642
+ shift
643
+ while IFS=$sep read -r name terms; do
644
+ case $name in "$low" | "$low"-*) ;; *) continue ;; esac
645
+ for t in $terms; do
646
+ doing=$(terminal_doing "$t")
647
+ case " $* " in *" $doing "*) printf '%s\n' "$t"; return 0 ;; esac
648
+ done
649
+ done <<< "$AGENT_TABS"
650
+ return 1
651
+ }
652
+
653
+ # Wake a card's agent for a pull request closed without merging, or in
654
+ # conflict with its default branch: it is told what was seen, and to bring
655
+ # it up to date or to ask the human whether to stop, as sdlc-pr says. A
656
+ # closed one comes first: while one is closed, the human is asked about it
657
+ # before any conflict. It wakes the agent for the first one it has not woken
658
+ # it for already (.woke) and that the agent has not seen itself (agent_saw),
659
+ # by what card_seen finds in the task's tab:
660
+ # idle or done its turn has ended: the message is sent to it, as if typed
661
+ # none the agent has exited, and the tab's own shell is in the
662
+ # foreground: it is started again there with `task build
663
+ # --continue` and the message. The shell is in the task's
664
+ # folder, where `task build` runs.
665
+ # anything else busy, not known, or the tab closed: nothing this pass
666
+ # A wake is noted in the .woke file only once hc has taken it, so that a send
667
+ # hc refuses is made again at the next pass. It records and pushes nothing.
668
+ # merge_wake_agent <space> <card ID, in upper case> <the check's lines> <the card's .woke file>
669
+ merge_wake_agent() {
670
+ local space=$1 card=$2 check=$3 woke=$4 want=closed state url target='' low t msg text how
671
+ [ "$CHECK_CLOSED" -gt 0 ] || want=conflict
672
+ while read -r state url; do
673
+ [ "$state" = "$want" ] && [ -n "$url" ] || continue
674
+ ! grep -qxF "$state $url" "$woke" 2>/dev/null || continue
675
+ ! agent_saw "$space" "$card" "$state" "$url" || continue
676
+ target=$url
677
+ break
678
+ done < "$check"
679
+ [ -n "$target" ] && [ "$AGENTS_ON" = 1 ] || return 0
680
+ low=$(printf '%s' "$card" | tr '[:upper:]' '[:lower:]')
681
+ card_seen "$card" "$low" pr
682
+ case $AGENT_SEEN in
683
+ idle | done) t=$(wake_terminal "$low" idle done) || return 0 ;;
684
+ none) t=$(wake_terminal "$low" none) || return 0 ;;
685
+ *) return 0 ;;
686
+ esac
687
+ if [ "$want" = closed ]; then
688
+ msg="ocnus-merges: $target was closed without merging. Ask the human whether to stop, as sdlc-pr says."
689
+ else
690
+ msg="ocnus-merges: $target is in conflict with its default branch. Bring it up to date, as sdlc-pr says."
691
+ fi
692
+ text=$msg how="told in $t"
693
+ [ "$AGENT_SEEN" != none ] || {
694
+ text="ocnus task build $space $card --continue $(sh_quote "$msg")"
695
+ how="started again in $t with claude --continue"
696
+ }
697
+ if ! hc_cmd send "$t" "$text" >/dev/null 2>&1; then
698
+ say "$card in '$space': could not wake its agent in $t for $target; trying again at the next pass"
699
+ return 0
700
+ fi
701
+ mkdir -p "${woke%/*}" && printf '%s %s\n' "$want" "$target" >> "$woke" ||
702
+ say "could not note in $woke that $card's agent was woken for $target"
703
+ case $want in
704
+ closed) say "$card in '$space': $target was closed without merging, so its agent is $how" ;;
705
+ *) say "$card in '$space': $target is in conflict, so its agent is $how" ;;
706
+ esac
707
+ }
708
+
709
+ # What GitHub said of a card's pull requests, from the card's lines of
710
+ # github_pulls: a line for each pull request, merged, open, closed or
711
+ # conflict, then its URL, and the CHECK_* counts. A branch with no pull request is skipped, since the work
712
+ # did not change that repo. One that GitHub could not be asked about is
713
+ # counted in CHECK_FAILED, with the first why in CHECK_WHY, and said on
714
+ # stderr; CHECK_SIGN_IN is 1 for it when gh needs signing in.
715
+ # merges_pulls <the card's lines of github_pulls>
716
+ merges_pulls() {
717
+ local key state rest
718
+ CHECK_OPEN=0 CHECK_CLOSED=0 CHECK_MERGED=0 CHECK_CONFLICT=0 CHECK_FAILED=0
719
+ CHECK_SIGN_IN=0 CHECK_WHY=''
720
+ while read -r key state rest; do
721
+ case $state in
722
+ merged) CHECK_MERGED=$((CHECK_MERGED + 1)); say "merged $rest" ;;
723
+ closed) CHECK_CLOSED=$((CHECK_CLOSED + 1)); say "closed $rest" ;;
724
+ conflict) CHECK_CONFLICT=$((CHECK_CONFLICT + 1)); say "conflict $rest" ;;
725
+ open) CHECK_OPEN=$((CHECK_OPEN + 1)); say "open $rest" ;;
726
+ none) ;;
727
+ *)
728
+ CHECK_FAILED=$((CHECK_FAILED + 1))
729
+ [ -n "$CHECK_WHY" ] || CHECK_WHY=$rest
730
+ [ "$GITHUB_SIGN_IN" = 0 ] || CHECK_SIGN_IN=1
731
+ printf 'ocnus: could not ask GitHub for the pull request of %s. Trying again at the next pass.\n' "$rest" >&2
732
+ ;;
733
+ esac
734
+ done < "$1"
735
+ }
736
+
737
+ # One card's turn in a pass, once GitHub has been asked about every card:
738
+ # record its merge when every pull request has merged and its agent is not
739
+ # busy, wake its agent when one is closed or in conflict, or leave it for a
740
+ # later pass. A card with no lines of github_pulls is one that GitHub was not
741
+ # asked about, as one with no task on this machine. MERGES_SAW is what it
742
+ # saw, for the card's file.
743
+ # merges_check <space> <card> <the card's lines of github_pulls> <a folder for its check>
744
+ merges_check() {
745
+ local space=$1 card=$2 pulls=$3 scratch=$4 low state url urls='' woke
746
+ MERGES_SAW=none
747
+ woke=$(woke_file "$space" "$card")
748
+ [ -s "$pulls" ] || return 0
749
+ merges_pulls "$pulls" > "$scratch/check"
750
+ merges_saw "$scratch/check"
751
+ woke_keep "$woke" "$scratch/check"
752
+ if [ "$CHECK_CLOSED" -gt 0 ] || [ "$CHECK_CONFLICT" -gt 0 ]; then
753
+ merge_wake_agent "$space" "$card" "$scratch/check" "$woke"
754
+ return 0
755
+ fi
756
+ [ "$CHECK_OPEN" = 0 ] && [ "$CHECK_CLOSED" = 0 ] && [ "$CHECK_CONFLICT" = 0 ] &&
757
+ [ "$CHECK_FAILED" = 0 ] && [ "$CHECK_MERGED" -gt 0 ] || return 0
758
+ # Who is in the task's tab, read once the pull requests have merged.
759
+ [ "$AGENTS_ON" = 1 ] || return 0
760
+ low=$(printf '%s' "$card" | tr '[:upper:]' '[:lower:]')
761
+ card_seen "$card" "$low" pr
762
+ case $AGENT_SEEN in
763
+ closed | none | idle | done) ;;
764
+ *) return 0 ;;
765
+ esac
766
+ while read -r state url; do
767
+ [ "$state" != merged ] || urls=${urls:+$urls }$url
768
+ done < "$scratch/check"
769
+ merge_record "$space" "$card" "$urls"
770
+ }
771
+
772
+ # ocnus's watch on the merges: `task merges`, which merges_wake starts in
773
+ # its terminal. A pass asks GitHub about the pull requests of every card that
774
+ # waits on its merge, in one call (github_pulls), then checks each card in
775
+ # turn; then it sleeps a minute and runs itself again, until no card waits.
776
+ # With --wake it only wakes the watch, as the launchd agent has it do every
777
+ # minute (merges_wake), and says nothing.
778
+ task_merges() {
779
+ local once=0
780
+ [ "$#" -le 1 ] || die "$MERGES_USAGE"
781
+ case ${1:-} in
782
+ --once) once=1 ;;
783
+ --wake) merges_wake; return 0 ;;
784
+ '') ;;
785
+ *) die "$MERGES_USAGE" ;;
786
+ esac
787
+ have_sqlite || die "$SQLITE is not installed, so no hand-offs are recorded on this machine."
788
+ command -v gh >/dev/null 2>&1 ||
789
+ die "gh is not installed, so GitHub cannot be asked about the pull requests. Install it (https://cli.github.com), sign in with: gh auth login"
790
+ command -v jq >/dev/null 2>&1 || die "jq is not installed, so GitHub's answers cannot be read. Install it."
791
+ trap 'exit 0' HUP TERM
792
+
793
+ local waiting
794
+ waiting=$(merges_waiting) || die "could not read the hand-offs in $STORE. It may not be ocnus's store."
795
+ merges_tidy "$waiting"
796
+ [ -n "$waiting" ] || return 0
797
+ merges_write .alive "$(date +%s)"
798
+
799
+ local scratch sep=$'\x1f' space card last='' dir='' tdir i j how spaces=() cards=() dirs=()
800
+ scratch=$(mktemp -d) || die "could not make a folder for GitHub's answers."
801
+ # shellcheck disable=SC2064
802
+ trap "rm -rf $(sh_quote "$scratch")" EXIT
803
+ # The branch of each worktree of each card's task, a line each, keyed by
804
+ # the card's place in the pass, for the one call to GitHub. A card with no
805
+ # task here is passed over.
806
+ : > "$scratch/branches"
807
+ while IFS=$sep read -r space card; do
808
+ [ -n "$card" ] || continue
809
+ if [ "$space" != "$last" ]; then
810
+ last=$space dir=''
811
+ [ ! -d "$SPACES/$space" ] || dir=$(cd -P "$SPACES/$space" && pwd) || dir=''
812
+ fi
813
+ i=${#cards[@]}
814
+ spaces+=("$space") cards+=("$card") dirs+=("$dir")
815
+ [ -n "$dir" ] || continue
816
+ tdir=$(task_folder "$dir" "$card" 2>/dev/null) || continue
817
+ task_worktrees "$dir" "$tdir" "$card" || continue
818
+ for ((j = 0; j < ${#TASK_WTS[@]}; j++)); do
819
+ printf '%s\n' "$i$sep${TASK_WTS[j]}$sep${TASK_BRANCHES[j]}" >> "$scratch/branches"
820
+ done
821
+ done <<< "$waiting"
822
+ : > "$scratch/pulls"
823
+ GITHUB_SIGN_IN=0 GITHUB_CALL_WHY=''
824
+ if [ -s "$scratch/branches" ]; then
825
+ github_pulls "$scratch" < "$scratch/branches" > "$scratch/pulls"
826
+ [ "$GITHUB_SIGN_IN" = 0 ] ||
827
+ say "ocnus: gh needs signing in to GitHub: it is signed out, or GitHub refused its token, so no card's pull requests can be seen. Sign in with: gh auth login" >&2
828
+ fi
829
+ # What the call found of gh, for status: left while a call fails as a
830
+ # whole, and gone once one works or none is made.
831
+ if [ -n "$GITHUB_CALL_WHY" ]; then
832
+ how=failed
833
+ [ "$GITHUB_SIGN_IN" = 0 ] || how=sign-in
834
+ merges_write .gh "$(date +%s) $how $(plain_note "$GITHUB_CALL_WHY")"
835
+ else
836
+ rm -f "$ENT_HOME/merges/.gh"
837
+ fi
838
+ last=''
839
+ for ((i = 0; i < ${#cards[@]}; i++)); do
840
+ space=${spaces[i]} card=${cards[i]} dir=${dirs[i]}
841
+ [ -n "$dir" ] || continue
842
+ # The space's tabs, read once for its cards.
843
+ [ "$space" = "$last" ] || { last=$space; agents_read "$space" "$dir"; }
844
+ grep "^$i " "$scratch/pulls" > "$scratch/card" || true
845
+ merges_check "$space" "$card" "$scratch/card" "$scratch" || true
846
+ merges_write "$space/$card" "$(date +%s) $MERGES_SAW"
847
+ done
848
+ rm -rf "$scratch"
849
+ trap - EXIT
850
+ [ "$once" = 0 ] || return 0
851
+ sleep "$MERGES_PAUSE" || exit 0
852
+ exec "$REPO/cli/ocnus" task merges
853
+ }