@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,1389 @@
1
+ # Linear: the one place ocnus talks to Linear. Sourced by cli/ocnus.
2
+
3
+ # Cards live in Linear. An agent reaches them through its own Linear tools.
4
+ # ocnus reaches them here, with a Linear API key the human saves once, so
5
+ # that listing cards needs no agent and a Linear step goes the same way on
6
+ # every run.
7
+ #
8
+ # Linear is asked through its GraphQL API with curl, and its answers are read
9
+ # with jq. The rest of ocnus needs neither, so a command here says which
10
+ # one is missing.
11
+
12
+ LINEAR_URL=https://api.linear.app/graphql
13
+ # The key is one of ocnus's variables, LINEAR_API_KEY. It comes from the
14
+ # environment, or from ocnus's env file ($ENV_FILE), which cli/ocnus
15
+ # has read by now and `linear key` writes.
16
+ #
17
+ # What a key is made of. Linear's are lin_api_ and then letters and digits. A
18
+ # key with a quote, a backslash or a space in it is not one, and could not be
19
+ # handed to curl as a line of its config.
20
+ KEY_RE='^[A-Za-z0-9_.-]+$'
21
+ # How many seconds to wait for Linear before giving up.
22
+ LINEAR_WAIT=20
23
+ # Where the human makes a key.
24
+ KEY_PLACE='Linear, under Settings, Account, Security & access, Personal API keys'
25
+ # What is said of a LINEAR_API_KEY that does not hold a key at all.
26
+ NOT_A_KEY="LINEAR_API_KEY does not hold a Linear API key. Check your environment and $ENV_FILE, or save a new key with: ocnus linear key"
27
+ # How linear_ask exits when Linear rejects the key, so that `status` can tell
28
+ # it from Linear out of reach. It exits 1, as die does, for everything else.
29
+ KEY_REJECTED=2
30
+
31
+ # Stop unless the two programs every Linear command needs are here.
32
+ linear_tools() {
33
+ local tool
34
+ for tool in curl jq; do
35
+ command -v "$tool" >/dev/null 2>&1 ||
36
+ die "$tool is not installed, and ocnus needs it to ask Linear anything. Install it, then run this again."
37
+ done
38
+ }
39
+
40
+ # Put one question to Linear and print its answer as it came, then the HTTP
41
+ # status on a last line of its own.
42
+ # linear_post <key> <query> [<the query's variables, as JSON>]
43
+ # The key goes to curl on stdin, as a line of its config: other programs on
44
+ # the machine can read a command's arguments, and cannot read its stdin. It
45
+ # stops, as die does, only when the question cannot be put together or Linear
46
+ # cannot be reached. What Linear answered is for the caller to judge.
47
+ linear_post() {
48
+ local key=$1 query=$2 vars=${3:-} body out code=0 said
49
+ [ -n "$vars" ] || vars='{}'
50
+ body=$(jq -cn --arg q "$query" --argjson v "$vars" '{query: $q, variables: $v}') ||
51
+ die "could not put a question to Linear together."
52
+ # --disable has to be curl's first argument. It keeps a person's ~/.curlrc
53
+ # from changing how Linear's answers are read, as -init /dev/null does for
54
+ # sqlite3 in handoff.sh: a --fail or --include there would make a rejected
55
+ # key look like the network, or a good answer unreadable. The key's own
56
+ # --config - is still read.
57
+ out=$(printf 'header = "Authorization: %s"\n' "$key" |
58
+ curl --disable --silent --show-error --max-time "$LINEAR_WAIT" --config - \
59
+ --header 'Content-Type: application/json' --data-binary "$body" \
60
+ --write-out '\n%{http_code}' "$LINEAR_URL" 2>&1) || code=$?
61
+ if [ "$code" -ne 0 ]; then
62
+ said=$(printf '%s\n' "$out" | grep -m 1 '^curl: ') || said=
63
+ die "could not reach Linear${said:+ ($said)}. Check the network, then run this again."
64
+ fi
65
+ printf '%s' "$out"
66
+ }
67
+
68
+ # Ask Linear one thing and print the data it answers with, as one line of JSON.
69
+ # linear_ask <key> <query> [<the query's variables, as JSON>]
70
+ # It asks through linear_post. The ways this fails are told apart, because
71
+ # what the human does next differs: check the network, or replace the key. A
72
+ # rejected key also has an exit code of its own, KEY_REJECTED; every other
73
+ # failure exits 1.
74
+ linear_ask() {
75
+ local key=$1 out status said
76
+ # linear_post has said why on stderr when it stops.
77
+ out=$(linear_post "$@") || exit 1
78
+ # curl ends what it prints with the HTTP status, on a line of its own.
79
+ status=${out##*$'\n'}
80
+ out=${out%$'\n'*}
81
+ # A key Linear does not know: a 401, whatever comes with it.
82
+ [ "$status" != 401 ] || key_rejected
83
+ # Linear's API always answers with JSON, so an empty answer did not come
84
+ # from it. It is stopped here, before jq judges it: jq 1.6 exits zero for
85
+ # -e when it is given no JSON at all, so the tests below would pass on it.
86
+ case $out in
87
+ *[![:space:]]*) ;;
88
+ *) die "Linear's answer was empty, with HTTP status $status. Something between this machine and Linear may be answering for it: check the network, then run this again." ;;
89
+ esac
90
+ # Linear's own word for a key it does not know, at any status. A 403 counts
91
+ # only when it is Linear's own answer: a page from a proxy or a firewall
92
+ # says nothing about the key, and a new key would not get past it.
93
+ if { [ "$status" = 403 ] && printf '%s' "$out" | jq -e 'type == "object" and has("errors")' >/dev/null 2>&1; } ||
94
+ [ "$(printf '%s' "$out" | jq -r '[.errors[]?.extensions | ((.type // "") + " " + (.code // "")) | test("authentication"; "i")] | any' 2>/dev/null)" = true ]; then
95
+ key_rejected
96
+ fi
97
+ said=$(printf '%s' "$out" | jq -r '.errors[0].message // empty' 2>/dev/null) || said=
98
+ [ -z "$said" ] || die "Linear answered with an error: ${said//"$key"/<the key>}"
99
+ # An answer that is not JSON did not come from Linear's API.
100
+ [ "$status" = 200 ] || printf '%s' "$out" | jq -e . >/dev/null 2>&1 ||
101
+ die "something between this machine and Linear answered for it, with HTTP status $status. Check the network, then run this again."
102
+ [ "$status" = 200 ] || die "Linear answered with HTTP status $status and no result. Try again in a minute."
103
+ printf '%s' "$out" | jq -ce '.data // empty' 2>/dev/null ||
104
+ die "Linear's answer was not one ocnus can read. Something between this machine and Linear may be answering for it."
105
+ }
106
+
107
+ # Stop as die does, saying Linear rejected the key, with the exit code that
108
+ # says so.
109
+ key_rejected() {
110
+ printf 'ocnus: Linear rejected the key. Make a new one in %s, then save it with: ocnus linear key\n' "$KEY_PLACE" >&2
111
+ exit "$KEY_REJECTED"
112
+ }
113
+
114
+ # Print the key ocnus has been given, or stop and say how to save one.
115
+ linear_saved_key() {
116
+ local key=${LINEAR_API_KEY:-}
117
+ [ -n "$key" ] ||
118
+ die "no Linear key is saved, so ocnus cannot read Linear. Make one in $KEY_PLACE, then save it with: ocnus linear key"
119
+ [[ $key =~ $KEY_RE ]] || die "$NOT_A_KEY"
120
+ printf '%s' "$key"
121
+ }
122
+
123
+ # The question that tells whose a key is. `linear key` asks it before it saves
124
+ # a key, and `status` asks it of the saved one.
125
+ VIEWER_QUERY='query { viewer { id name } }'
126
+
127
+ # Whether the saved key works, for `status` to say. It asks Linear whose the
128
+ # key is, as `linear key` does, but it never stops: what it found is in how it
129
+ # returns, as with linear_card_known.
130
+ # linear_key_state
131
+ # It returns:
132
+ # 0 the key works; its owner's name is on stdout, with every control
133
+ # character made a space, as `task ls` does for titles
134
+ # 1 Linear rejected the key, or LINEAR_API_KEY does not hold a key; why is
135
+ # on stderr
136
+ # 2 no key is saved, so nothing was asked
137
+ # 3 the key could not be checked; why is on stderr
138
+ # Only 1 says the key is bad. 3 says nothing of it: curl or jq is missing,
139
+ # Linear is out of reach, or something else answered in its place.
140
+ linear_key_state() {
141
+ local key=${LINEAR_API_KEY:-} tool data rc=0
142
+ [ -n "$key" ] || return 2
143
+ # Not a key, whether or not curl and jq are here to ask Linear about it.
144
+ [[ $key =~ $KEY_RE ]] || { printf '%s\n' "$NOT_A_KEY" >&2; return 1; }
145
+ for tool in curl jq; do
146
+ command -v "$tool" >/dev/null 2>&1 || { printf '%s is not installed\n' "$tool" >&2; return 3; }
147
+ done
148
+ # linear_ask stops with its own message, on stderr, when it cannot ask.
149
+ data=$(linear_ask "$key" "$VIEWER_QUERY") || rc=$?
150
+ case $rc in
151
+ 0) ;;
152
+ "$KEY_REJECTED") return 1 ;;
153
+ *) return 3 ;;
154
+ esac
155
+ # As in linear_key: an answer that names nobody did not come from Linear.
156
+ [ -n "$(printf '%s' "$data" | jq -r '.viewer.id | strings' 2>/dev/null)" ] ||
157
+ { printf "Linear's answer did not say whose key it is\n" >&2; return 3; }
158
+ printf '%s' "$data" |
159
+ jq -r 'def plain: explode | map(if . < 32 or (. > 126 and . < 160) then 32 else . end) | implode;
160
+ .viewer.name | strings | plain' 2>/dev/null || true
161
+ }
162
+
163
+ # The change that tells whether a key may change cards. Linear's API has no
164
+ # field that says what a personal key may do, so it is asked to change a card
165
+ # that cannot exist, the nil UUID, with nothing in the change. A key without
166
+ # Write permission is refused for want of the write scope; a key with it is
167
+ # told there is no such card. Nothing is changed either way.
168
+ WRITE_QUERY='mutation { issueUpdate(id: "00000000-0000-0000-0000-000000000000", input: {}) { success } }'
169
+
170
+ # What is said of a key that can read cards but not change them, by `status`
171
+ # as a problem and by `linear key` once it has saved such a key.
172
+ NO_WRITE_WHY="The key can read cards but not change them, so linear type, linear section, linear slices and linear move fail with it. Make a key with Write permission in $KEY_PLACE, then save it with: ocnus linear key"
173
+
174
+ # How Linear's answer to WRITE_QUERY reads, as one word and what follows it:
175
+ # cannot a refusal: an error of type or code forbidden, or one whose
176
+ # message names the write scope
177
+ # can an error saying there is no such card
178
+ # error another error; Linear's message for the first one follows
179
+ # none no error at all
180
+ # It prints nothing for what is not JSON. It needs PLAIN_DEF before it.
181
+ WRITE_VERDICT='
182
+ def message: .message? | strings // "";
183
+ def kind: [.extensions.type?, .extensions.code?] | map(strings) | join(" ");
184
+ def said: message + " " + (.extensions.userPresentableMessage? | strings // "");
185
+ (if type == "object" then [.errors[]? | objects] else [] end) as $errors
186
+ | if any($errors[]; (kind | test("forbidden"; "i"))
187
+ or (message | test("scope"; "i") and test("write"; "i")))
188
+ then "cannot"
189
+ elif any($errors[]; said | test("not found|could not find"; "i")) then "can"
190
+ elif ($errors | length) > 0 then "error " + ($errors[0] | message | plain)
191
+ else "none" end'
192
+
193
+ # Whether a key Linear knows may change cards, for `status` and `linear key`
194
+ # to say. It asks WRITE_QUERY, and never stops: what it found is in how it
195
+ # returns, as with linear_key_state.
196
+ # linear_key_writes <key>
197
+ # It returns:
198
+ # 0 the key can change cards
199
+ # 1 it cannot
200
+ # 3 that was not checked; why is on stderr, with any key in what Linear
201
+ # said shown as <the key>
202
+ # Only Linear's own answer decides, at any HTTP status: a 403 that names the
203
+ # write scope is a refusal, not a rejected key, since the key has said whose
204
+ # it is by now.
205
+ linear_key_writes() {
206
+ local key=$1 out status verdict
207
+ # linear_post prints nothing on stdout when it stops, only why on stderr.
208
+ if ! out=$(linear_post "$key" "$WRITE_QUERY" 2>&1); then
209
+ printf '%s\n' "$(first_sentence "$out")" >&2
210
+ return 3
211
+ fi
212
+ status=${out##*$'\n'}
213
+ out=${out%$'\n'*}
214
+ # What jq prints decides, not how it exits: jq 1.6 exits zero when it is
215
+ # given no JSON at all.
216
+ verdict=$(printf '%s' "$out" | jq -r "$PLAIN_DEF$WRITE_VERDICT" 2>/dev/null) || verdict=
217
+ case $verdict in
218
+ can) return 0 ;;
219
+ cannot) return 1 ;;
220
+ none) printf "Linear's answer did not say whether the key can change cards\n" >&2 ;;
221
+ 'error '*) verdict=${verdict#error }
222
+ printf 'Linear answered with an error%s\n' "${verdict:+: ${verdict//"$key"/<the key>}}" >&2 ;;
223
+ *) printf 'something between this machine and Linear answered for it, with HTTP status %s\n' "$status" >&2 ;;
224
+ esac
225
+ return 3
226
+ }
227
+
228
+ # The kinds of status an open card is in, as Linear names them, in the order
229
+ # Linear shows them. A card that is done, cancelled or a duplicate is in one
230
+ # of the other kinds, and is never asked for.
231
+ OPEN_TYPES='["triage","backlog","unstarted","started"]'
232
+ # How many cards to ask for at a time, and how many times to ask before
233
+ # deciding that Linear will never say it has no more.
234
+ LINEAR_PAGE=100
235
+ LINEAR_PAGES=50
236
+
237
+ # The teams Linear knows of those asked for, their open statuses, and one page
238
+ # of their open cards, with when each was last changed. Linear pages through
239
+ # the cards in the order it is asked for, each page starting where the last
240
+ # ended. That order is when each card was made, which nothing changes: in the
241
+ # order they were last changed, a card edited while the pages are fetched
242
+ # would move onto a page already fetched, and never be listed.
243
+ LIST_QUERY='query($teams: [String!], $types: [String!], $first: Int, $after: String) {
244
+ teams(filter: {key: {in: $teams}}) { nodes { key } }
245
+ workflowStates(first: 250, filter: {team: {key: {in: $teams}}, type: {in: $types}}) {
246
+ nodes { name type position team { key } }
247
+ }
248
+ issues(first: $first, after: $after, orderBy: createdAt,
249
+ filter: {team: {key: {in: $teams}}, state: {type: {in: $types}}}) {
250
+ nodes { identifier title url updatedAt state { name type position } }
251
+ pageInfo { hasNextPage endCursor }
252
+ }
253
+ }'
254
+
255
+ # Turn the pages Linear answered with (one line of JSON each, on stdin) into
256
+ # the list: every open status, in Linear's order, with its cards. Teams often
257
+ # share a status name; a status of one name and kind is one group, whichever
258
+ # teams have it. $space, $teams and $types are given by the caller.
259
+ # - Under each status the card changed last comes first. Cards changed at
260
+ # the same moment keep the order Linear gave them in.
261
+ # - Should a card come on two pages, the first copy is kept.
262
+ # - The statuses are the ones the first page names, and any a card is in
263
+ # that it did not, such as one made while the pages were fetched, so that
264
+ # no card is dropped for want of a group.
265
+ # - A closed status is never listed, should Linear send one.
266
+ LIST_SHAPE='
267
+ ($types | to_entries | map({key: .value, value: .key}) | from_entries) as $rank
268
+ | .[0] as $first
269
+ | ([.[].issues.nodes[]] | to_entries | unique_by(.value.identifier)
270
+ | sort_by([.value.updatedAt, -.key]) | reverse | map(.value)) as $cards
271
+ | {
272
+ missing: ($teams - [$first.teams.nodes[].key]),
273
+ space: $space,
274
+ teams: $teams,
275
+ statuses: [
276
+ ($first.workflowStates.nodes + [$cards[].state])
277
+ | map(select($rank[.type] != null))
278
+ | group_by([.type, .name])
279
+ | map({name: .[0].name, type: .[0].type, position: ((map(.position | numbers) | min) // 1000000)})
280
+ | sort_by([$rank[.type], .position, .name])
281
+ | .[]
282
+ | . as $status
283
+ | {
284
+ name: $status.name,
285
+ type: $status.type,
286
+ cards: [
287
+ $cards[]
288
+ | select(.state.name == $status.name and .state.type == $status.type)
289
+ | {id: .identifier, title: .title, url: .url}
290
+ ]
291
+ }
292
+ ]
293
+ }'
294
+
295
+ # Print the open cards of some Linear teams as one line of JSON, grouped by
296
+ # status:
297
+ # {"space":"demo","teams":["ABC"],"statuses":[
298
+ # {"name":"Backlog","type":"backlog","cards":[{"id":"ABC-1","title":"…","url":"…"}]}]}
299
+ # Every open status of the teams is there, with no cards when it has none.
300
+ # linear_open_cards <space> <team key>...
301
+ linear_open_cards() {
302
+ local space=$1 key teams vars data pages='' after='' more asked=0 list missing
303
+ shift
304
+ linear_tools
305
+ key=$(linear_saved_key) || exit 1
306
+ teams=$(printf '%s\n' "$@" | jq -Rcn '[inputs]')
307
+ while :; do
308
+ asked=$((asked + 1))
309
+ [ "$asked" -le "$LINEAR_PAGES" ] ||
310
+ die "Linear still had more cards after $LINEAR_PAGES pages of $LINEAR_PAGE, which is more than ocnus lists."
311
+ vars=$(jq -cn --argjson teams "$teams" --argjson types "$OPEN_TYPES" --argjson first "$LINEAR_PAGE" \
312
+ --arg after "$after" \
313
+ '{teams: $teams, types: $types, first: $first, after: (if $after == "" then null else $after end)}')
314
+ data=$(linear_ask "$key" "$LIST_QUERY" "$vars") || exit 1
315
+ pages+=$data$'\n'
316
+ more=$(printf '%s' "$data" | jq -r '.issues.pageInfo.hasNextPage == true' 2>/dev/null) ||
317
+ die "Linear's answer was not one ocnus can read."
318
+ [ "$more" = true ] || break
319
+ # Listing what came so far would pass a part of the list for the whole.
320
+ after=$(printf '%s' "$data" | jq -r '.issues.pageInfo.endCursor | strings' 2>/dev/null) || after=
321
+ [ -n "$after" ] ||
322
+ die "Linear said it had more cards but not where the next ones start, so the list would be cut short."
323
+ done
324
+ # The pages go to jq on stdin, not as an argument: a long list of cards is
325
+ # more than a command's arguments may hold.
326
+ list=$(printf '%s' "$pages" |
327
+ jq -cs --arg space "$space" --argjson teams "$teams" --argjson types "$OPEN_TYPES" "$LIST_SHAPE" 2>/dev/null) ||
328
+ die "Linear's answer was not one ocnus can read."
329
+ missing=$(printf '%s' "$list" | jq -r '.missing | join(", ")')
330
+ [ -z "$missing" ] ||
331
+ die "Linear has no team with the key $missing that the saved key can see. See the space's teams with: ocnus space team $space"
332
+ printf '%s' "$list" | jq -c 'del(.missing)'
333
+ }
334
+
335
+ # Find a card by its team's key and its number, as Linear keeps them: ABC-122
336
+ # is team ABC, number 122. Its title, its labels and the card it was sliced
337
+ # from, its parent, come with it.
338
+ CARD_QUERY='query($team: String!, $number: Float!) {
339
+ issues(first: 1, filter: {team: {key: {eq: $team}}, number: {eq: $number}}) {
340
+ nodes { identifier title labels { nodes { name parent { name } } } parent { identifier } }
341
+ }
342
+ }'
343
+ # The label group a card's type is in. sdlc-define sets the type there.
344
+ TYPE_GROUP=Type
345
+ # Turn Linear's answer to CARD_QUERY into the card, {id, title, type,
346
+ # parent}, or "none" when Linear has no such card. type is null when the card
347
+ # has no label in the Type group ($group), and parent, the parent's ID, when
348
+ # it has no parent. An answer with no list of cards in it is not Linear
349
+ # saying it has none, so it is an error.
350
+ CARD_SHAPE='
351
+ if (.issues.nodes | type) != "array" then error("no list of cards")
352
+ elif (.issues.nodes | length) == 0 then "none"
353
+ else .issues.nodes[0]
354
+ | {id: .identifier, title: (.title // ""),
355
+ type: ([.labels.nodes[]? | select(.parent.name? == $group) | .name] | first),
356
+ parent: ((.parent.identifier? | strings) // null)}
357
+ end'
358
+
359
+ # Print one card as one line of JSON, or stop and say why:
360
+ # {"id":"ABC-122","title":"Export orders as CSV","type":"feat","parent":"ABC-100"}
361
+ # type is null when the card has no label in the Type group, and parent when
362
+ # it has no parent.
363
+ # linear_card <card ID, in upper case>
364
+ linear_card() {
365
+ local card=$1 key vars data found
366
+ linear_tools
367
+ key=$(linear_saved_key) || exit 1
368
+ vars=$(jq -cn --arg team "${card%-*}" --arg number "${card##*-}" \
369
+ '{team: $team, number: ($number | tonumber)}' 2>/dev/null) ||
370
+ die "'$card' is not a card ID like ABC-122."
371
+ data=$(linear_ask "$key" "$CARD_QUERY" "$vars") || exit 1
372
+ found=$(printf '%s' "$data" | jq -c --arg group "$TYPE_GROUP" "$CARD_SHAPE" 2>/dev/null) || found=
373
+ case $found in
374
+ '') die "Linear's answer was not one ocnus can read. Something between this machine and Linear may be answering for it." ;;
375
+ '"none"') die "Linear has no card $card that the saved key can see. Check the ID, then run this again." ;;
376
+ esac
377
+ printf '%s\n' "$found"
378
+ }
379
+
380
+ # Whether Linear has a card, for `task new` to check before it starts one, and
381
+ # for `task start` when it is given the card's type and title. It asks the
382
+ # same question as linear_card, but it never stops: what it found is in how
383
+ # it returns.
384
+ # linear_card_known <card ID, in upper case>
385
+ # It returns how that went:
386
+ # 0 Linear has the card, which it prints on stdout as linear_card does
387
+ # 1 Linear has no such card, that the saved key can see
388
+ # 2 no key is saved, so nothing was asked
389
+ # 3 Linear could not be asked; why is on stderr
390
+ # Only 1 is a no. The rest leave the card to start, so that a missing key,
391
+ # the network or a rejected key never keeps an agent from starting. Only 0
392
+ # prints anything on stdout.
393
+ linear_card_known() {
394
+ local card=$1 key=${LINEAR_API_KEY:-} tool vars data found
395
+ [ -n "$key" ] || return 2
396
+ for tool in curl jq; do
397
+ command -v "$tool" >/dev/null 2>&1 || { printf '%s is not installed\n' "$tool" >&2; return 3; }
398
+ done
399
+ [[ $key =~ $KEY_RE ]] || { printf 'LINEAR_API_KEY does not hold a Linear API key\n' >&2; return 3; }
400
+ vars=$(jq -cn --arg team "${card%-*}" --arg number "${card##*-}" \
401
+ '{team: $team, number: ($number | tonumber)}' 2>/dev/null) ||
402
+ { printf '%s is not a card ID\n' "$card" >&2; return 3; }
403
+ # linear_ask stops with its own message, on stderr, when it cannot ask.
404
+ data=$(linear_ask "$key" "$CARD_QUERY" "$vars") || return 3
405
+ # Judged by what jq prints: some versions exit zero on an empty answer. Only
406
+ # a real list counts (CARD_SHAPE), and a missing one must not read as
407
+ # Linear saying it has no such card.
408
+ found=$(printf '%s' "$data" | jq -c --arg group "$TYPE_GROUP" "$CARD_SHAPE" 2>/dev/null) || found=
409
+ case $found in
410
+ '"none"') return 1 ;;
411
+ '{'*) printf '%s\n' "$found" ;;
412
+ *) printf "Linear's answer was not one ocnus can read\n" >&2; return 3 ;;
413
+ esac
414
+ }
415
+
416
+ # Save the human's Linear API key as LINEAR_API_KEY in ocnus's env file,
417
+ # once Linear has said whose it is, and say when the key cannot change cards
418
+ # or that could not be checked. The key is asked for or read from stdin,
419
+ # never taken as an argument, so that it stays out of the shell's history.
420
+ linear_key() {
421
+ local key data who writes writes_rc=0
422
+ [ "$#" -eq 0 ] ||
423
+ die "usage: ocnus linear key (it asks for the key, or reads it from stdin; the key is never an argument)"
424
+ # Before the key is asked for, so nobody pastes one for nothing.
425
+ env_file_writable LINEAR_API_KEY
426
+ linear_tools
427
+ read_secret 'Linear API key (it is not shown as you type or paste it): '
428
+ key=$SECRET
429
+ [ -n "$key" ] || die "no key was given. Make one in $KEY_PLACE, then run this again."
430
+ [[ $key =~ $KEY_RE ]] ||
431
+ die "that is not a Linear API key. A key is lin_api_ and then letters and digits. Make one in $KEY_PLACE."
432
+ data=$(linear_ask "$key" "$VIEWER_QUERY") || die "the key was not saved."
433
+ # Linear always says who a good key belongs to. An answer that names nobody
434
+ # did not come from Linear, so it checked nothing. What jq prints decides,
435
+ # not how it exits: jq 1.6 exits zero for -e when it is given no JSON.
436
+ [ -n "$(printf '%s' "$data" | jq -r '.viewer.id | strings' 2>/dev/null)" ] ||
437
+ die "Linear's answer did not say whose key it is, so the key was not saved. Something between this machine and Linear may be answering for it."
438
+ who=$(printf '%s' "$data" | jq -r '.viewer.name // empty' 2>/dev/null) || who=
439
+ # Whether the key can change cards too. A key that cannot is still saved,
440
+ # since task ls and the Cards panel work with it, and it is said below.
441
+ writes=$(linear_key_writes "$key" 2>&1) || writes_rc=$?
442
+ # The key gets one line, in place of any it had (common.sh).
443
+ env_file_put LINEAR_API_KEY "$key" || die "could not write $ENV_FILE, so the key was not saved."
444
+ say "Saved the Linear key of ${who:-a user with no name} in $ENV_FILE"
445
+ case $writes_rc in
446
+ 0) ;;
447
+ 1) say " note $NO_WRITE_WHY" ;;
448
+ *) say " note could not check whether the key can change cards${writes:+: $writes}" ;;
449
+ esac
450
+ # A key exported in the shell wins over the file, so a different one there
451
+ # would go on being used.
452
+ if [ -n "$KEY_EXPORTED" ] && [ "${LINEAR_API_KEY:-}" != "$key" ]; then
453
+ say " note LINEAR_API_KEY is also set in your environment, to another key. That one is used while it is set, not the one just saved."
454
+ fi
455
+ }
456
+
457
+ # --- reading a card ---------------------------------------------------------
458
+ #
459
+ # The card skills read a card here, so that the read goes the same way on
460
+ # every run, with the card's sections, comments and sub-issues. A mod reads
461
+ # it too, with --json.
462
+
463
+ # Linear's text as a line of a list or of a card: every control character
464
+ # becomes a space, so that a newline cannot start what looks like another line
465
+ # and an escape sequence cannot reach the terminal. No regex, so any jq does
466
+ # it. `task ls` uses it too.
467
+ PLAIN_DEF='def plain: explode | map(if . < 32 or (. > 126 and . < 160) then 32 else . end) | implode;'
468
+
469
+ # How many labels, comments and sub-issues a read asks Linear for. A card
470
+ # with more than that is not printed, since what was read would pass for the
471
+ # whole of it.
472
+ READ_LABELS=100
473
+ READ_COMMENTS=100
474
+ READ_SUBS=50
475
+
476
+ # The question for linear read: the card whole.
477
+ READ_QUERY='query($team: String!, $number: Float!) {
478
+ issues(first: 1, filter: {team: {key: {eq: $team}}, number: {eq: $number}}) {
479
+ nodes {
480
+ identifier title url description
481
+ state { name type }
482
+ labels(first: '$READ_LABELS') { nodes { name parent { name } } pageInfo { hasNextPage } }
483
+ parent { identifier title }
484
+ project { name }
485
+ comments(first: '$READ_COMMENTS') { nodes { body createdAt user { name } botActor { name } } pageInfo { hasNextPage } }
486
+ children(first: '$READ_SUBS') { nodes { identifier title state { name type } } pageInfo { hasNextPage } }
487
+ }
488
+ }
489
+ }'
490
+
491
+ # From the answer to READ_QUERY, on stdin, print "none" when Linear has no
492
+ # such card, {"more": <what>} when it has more comments, sub-issues or labels
493
+ # than were asked for, or {"card": <the card>}, the card as linear read --json
494
+ # prints it. A comment's author is the app Linear credits with it, or else
495
+ # the user who wrote it. Comments come oldest first. An answer with a card in
496
+ # it that is not in this form did not come from Linear. $group is TYPE_GROUP.
497
+ READ_SHAPE='
498
+ def text: if type == "string" then . else error("unreadable") end;
499
+ def list: if (.nodes | type) == "array" then .nodes[] else error("unreadable") end;
500
+ def status: if type == "object" then {name: (.name | text), type: (.type | text)} else error("unreadable") end;
501
+ if (.issues.nodes | type) != "array" then error("no list of cards")
502
+ elif (.issues.nodes | length) == 0 then "none"
503
+ else .issues.nodes[0]
504
+ | if .comments.pageInfo.hasNextPage? == true then {more: "comments"}
505
+ elif .children.pageInfo.hasNextPage? == true then {more: "sub-issues"}
506
+ elif .labels.pageInfo.hasNextPage? == true then {more: "labels"}
507
+ else {card: {
508
+ id: (.identifier | text),
509
+ title: (.title | text),
510
+ url: (.url // "" | text),
511
+ status: (.state | status),
512
+ type: ([.labels | list | select(.parent.name? == $group) | .name] | first),
513
+ labels: [.labels | list | .name | text],
514
+ parent: (if .parent == null then null else {id: (.parent.identifier | text), title: (.parent.title | text)} end),
515
+ project: (if .project == null then null else {name: (.project.name | text)} end),
516
+ description: (.description // "" | text),
517
+ comments: ([.comments | list
518
+ | {author: (.botActor.name? // .user.name? // "unknown" | text),
519
+ createdAt: (.createdAt | text), body: (.body // "" | text)}] | sort_by(.createdAt)),
520
+ subIssues: [.children | list | {id: (.identifier | text), title: (.title | text), status: (.state | status)}]
521
+ }}
522
+ end
523
+ end'
524
+
525
+ # The card from READ_SHAPE, on stdin, laid out like the card: its head, the
526
+ # description as written, the comments, each with its body indented under who
527
+ # wrote it and when, and the sub-issues. Every field is made plain, but the
528
+ # description and the comments keep their line breaks, without the \r Linear
529
+ # may end a line with, and lose only the blank lines at either end.
530
+ READ_TEXT=$PLAIN_DEF'
531
+ def blank: explode | all(. == 32);
532
+ def trim_blank: if length > 0 and (.[0] | blank) then .[1:] | trim_blank
533
+ elif length > 0 and (.[-1] | blank) then .[:-1] | trim_blank else . end;
534
+ def lines: split("\n") | map(rtrimstr("\r") | plain) | trim_blank;
535
+ "\(.id | plain) \(.title | plain)",
536
+ "Status: \(.status.name | plain)",
537
+ "Labels: \(if .labels == [] then "none" else .labels | map(plain) | join(", ") end)",
538
+ (.parent // empty | "Parent: \(.id | plain) \(.title | plain)"),
539
+ (.project // empty | "Project: \(.name | plain)"),
540
+ "URL: \(.url | plain)",
541
+ "",
542
+ ((.description | lines) as $lines | if $lines == [] then "No description." else $lines[] end),
543
+ "",
544
+ "Comments (\(.comments | length))",
545
+ (.comments[]
546
+ | " \(.author | plain), \(.createdAt | sub("\\.[0-9]+Z$"; "Z") | plain)",
547
+ (.body | lines[] | if blank then "" else " " + . end)),
548
+ "",
549
+ "Sub-issues (\(.subIssues | length))",
550
+ (.subIssues[] | " \(.id | plain) \(.status.name | plain) \(.title | plain)")'
551
+
552
+ # Print a card whole, laid out like the card, or with --json as one line of
553
+ # JSON, for a mod:
554
+ # {"id":"ABC-122","title":"…","url":"…","status":{"name":"In Progress","type":"started"},
555
+ # "type":"feat","labels":["feat"],"parent":{"id":"ABC-100","title":"…"},"project":{"name":"…"},
556
+ # "description":"…",
557
+ # "comments":[{"author":"…","createdAt":"…","body":"…"}],
558
+ # "subIssues":[{"id":"ABC-123","title":"…","status":{"name":"Todo","type":"unstarted"}}]}
559
+ # type is the card's label in the Type group, or null; parent and project, the
560
+ # card's Linear project, are null for a card with none. When it fails it
561
+ # prints nothing on stdout.
562
+ # ocnus linear read <card> [--json]
563
+ linear_read() {
564
+ local card=${1:-} json=0 key vars data shape more=''
565
+ [ "$#" -ge 1 ] && [ "$#" -le 2 ] ||
566
+ die "usage: ocnus linear read <card> [--json], like: ocnus linear read ABC-122"
567
+ case ${2:-} in
568
+ --json) json=1 ;;
569
+ '') ;;
570
+ *) die "unknown option for linear read: $2" ;;
571
+ esac
572
+ [[ $card =~ $CARD_RE ]] || die "'$card' is not a card ID like ABC-122."
573
+ card=$(printf '%s' "$card" | tr '[:lower:]' '[:upper:]')
574
+ linear_tools
575
+ key=$(linear_saved_key) || exit 1
576
+ vars=$(jq -cn --arg team "${card%-*}" --arg number "${card##*-}" '{team: $team, number: ($number | tonumber)}') ||
577
+ die "'$card' is not a card ID like ABC-122."
578
+ data=$(linear_ask "$key" "$READ_QUERY" "$vars") || exit 1
579
+ # Judged by what jq prints: some versions exit zero on an empty answer.
580
+ shape=$(printf '%s' "$data" | jq -c --arg group "$TYPE_GROUP" "$READ_SHAPE" 2>/dev/null) || shape=
581
+ case $shape in
582
+ '{"card":'*) ;;
583
+ '"none"') die "Linear has no card $card that the saved key can see. Check the ID, then run this again." ;;
584
+ '{"more":"comments"}') more="$READ_COMMENTS comments" ;;
585
+ '{"more":"sub-issues"}') more="$READ_SUBS sub-issues" ;;
586
+ '{"more":"labels"}') more="$READ_LABELS labels" ;;
587
+ *) die "Linear's answer was not one ocnus can read. Something between this machine and Linear may be answering for it." ;;
588
+ esac
589
+ [ -z "$more" ] ||
590
+ die "$card has more than $more, more than ocnus reads, so it printed none of the card: what it read would pass for the whole. Read the card in Linear, or with an agent's Linear tools."
591
+ if [ "$json" = 1 ]; then
592
+ printf '%s' "$shape" | jq -c '.card'
593
+ else
594
+ printf '%s' "$shape" | jq -r '.card | '"$READ_TEXT"
595
+ fi
596
+ }
597
+
598
+ # --- the card skills' writes ------------------------------------------------
599
+ #
600
+ # The card skills write three things: a card's type label, a section of its
601
+ # description, and its slices, the sub-issues sdlc-breakdown makes of it. Each
602
+ # is one command here, so that it goes the same way on every run, and each
603
+ # reads back what Linear saved before it says it is done. The slices are the
604
+ # one thing created; nothing else in Linear is changed.
605
+
606
+ # The types a card can have. Each is the start of the card's branch name.
607
+ CARD_TYPES='feat fix chore'
608
+
609
+ # Change a card: its fields as Linear's IssueUpdateInput names them, in $2 as
610
+ # JSON. Linear's answer gives back what is asked for in $3.
611
+ # linear_update <key> <the card's id> <input, as JSON> <fields to read back>
612
+ linear_update() {
613
+ local key=$1 id=$2 input=$3 fields=$4 vars
614
+ vars=$(jq -cn --arg id "$id" --argjson input "$input" '{id: $id, input: $input}') ||
615
+ die "could not put the change to Linear together."
616
+ linear_ask "$key" "mutation(\$id: String!, \$input: IssueUpdateInput!) {
617
+ issueUpdate(id: \$id, input: \$input) { success issue { $fields } }
618
+ }" "$vars"
619
+ }
620
+
621
+ # The card's own question for linear type: the card, its labels, and the
622
+ # labels of the name asked for in a group of the name asked for, the card's
623
+ # team's and the workspace's only, so that other teams' never crowd them out.
624
+ TYPE_QUERY='query($team: String!, $number: Float!, $type: String!, $group: String!) {
625
+ issues(first: 1, filter: {team: {key: {eq: $team}}, number: {eq: $number}}) {
626
+ nodes { id identifier labels(first: 100) { nodes { id name parent { name } } } }
627
+ }
628
+ issueLabels(first: 50, filter: {name: {eq: $type}, parent: {name: {eq: $group}},
629
+ or: [{team: {key: {eq: $team}}}, {team: {null: true}}]}) {
630
+ nodes { id name team { key } }
631
+ }
632
+ }'
633
+
634
+ # Set a card's type: its one label in the Type group. The label is the card's
635
+ # team's, or the workspace's when the team has none. Any other label of the
636
+ # group comes off; the card's other labels are never sent, so they stay.
637
+ # ocnus linear type <card> <feat|fix|chore>
638
+ linear_type() {
639
+ local card=${1:-} type=${2:-} key vars data plan add remove was saved lost
640
+ [ "$#" -eq 2 ] || die "usage: ocnus linear type <card> <feat|fix|chore>, like: ocnus linear type ABC-122 feat"
641
+ [[ $card =~ $CARD_RE ]] || die "'$card' is not a card ID like ABC-122."
642
+ card=$(printf '%s' "$card" | tr '[:lower:]' '[:upper:]')
643
+ in_list "$type" "$CARD_TYPES" ||
644
+ die "'$type' is not a card type. A card's type is one of: $CARD_TYPES (see https://conventionalbranch.org)."
645
+ linear_tools
646
+ key=$(linear_saved_key) || exit 1
647
+ vars=$(jq -cn --arg team "${card%-*}" --arg number "${card##*-}" --arg type "$type" --arg group "$TYPE_GROUP" \
648
+ '{team: $team, number: ($number | tonumber), type: $type, group: $group}') ||
649
+ die "'$card' is not a card ID like ABC-122."
650
+ data=$(linear_ask "$key" "$TYPE_QUERY" "$vars") || exit 1
651
+ # What to add and take off, or why there is nothing to do.
652
+ plan=$(printf '%s' "$data" | jq -c --arg team "${card%-*}" --arg type "$type" --arg group "$TYPE_GROUP" '
653
+ if (.issues.nodes | type) != "array" then error("no list of cards")
654
+ elif (.issues.nodes | length) == 0 then {state: "none"}
655
+ else .issues.nodes[0] as $card
656
+ | ([.issueLabels.nodes[]? | select(.name == $type)]) as $named
657
+ | (([$named[] | select(.team.key? == $team)] + [$named[] | select(.team == null)]) | .[0]) as $label
658
+ | if $label == null then {state: "nolabel"}
659
+ else ([$card.labels.nodes[]? | select(.parent.name? == $group)]) as $types
660
+ | {state: "ok", id: $card.id,
661
+ add: (if any($types[]; .id == $label.id) then [] else [$label.id] end),
662
+ remove: [$types[] | select(.id != $label.id) | .id],
663
+ was: [$types[] | select(.id != $label.id) | .name],
664
+ keep: [$card.labels.nodes[]? | select(.parent.name? != $group) | .name]}
665
+ end
666
+ end' 2>/dev/null) || plan=
667
+ case $(printf '%s' "$plan" | jq -r '.state' 2>/dev/null) in
668
+ ok) ;;
669
+ none) die "Linear has no card $card that the saved key can see. Check the ID, then run this again." ;;
670
+ nolabel) die "team ${card%-*} has no label '$type' in a label group called $TYPE_GROUP, and nor does the workspace, so the type was not set. ocnus makes no labels: make the $TYPE_GROUP group and its labels ($CARD_TYPES) in Linear, then run this again." ;;
671
+ *) die "Linear's answer was not one ocnus can read. Something between this machine and Linear may be answering for it." ;;
672
+ esac
673
+ add=$(printf '%s' "$plan" | jq -c '.add')
674
+ remove=$(printf '%s' "$plan" | jq -c '.remove')
675
+ was=$(printf '%s' "$plan" | jq -r '.was | join(", ")')
676
+ if [ "$add" = '[]' ] && [ "$remove" = '[]' ]; then
677
+ say "$card's type is already $type"
678
+ return
679
+ fi
680
+ data=$(linear_update "$key" "$(printf '%s' "$plan" | jq -r '.id')" \
681
+ "$(jq -cn --argjson add "$add" --argjson remove "$remove" \
682
+ '{} + (if $add == [] then {} else {addedLabelIds: $add} end) + (if $remove == [] then {} else {removedLabelIds: $remove} end)')" \
683
+ 'labels(first: 100) { nodes { name parent { name } } }') || exit 1
684
+ # What Linear says the card now has: one type, the one asked for.
685
+ saved=$(printf '%s' "$data" | jq -r --arg group "$TYPE_GROUP" \
686
+ '[.issueUpdate.issue.labels.nodes[]? | select(.parent.name? == $group) | .name] | join(", ")' 2>/dev/null) || saved=
687
+ [ "$saved" = "$type" ] ||
688
+ die "Linear did not save $card's type as $type alone: its $TYPE_GROUP labels are now '${saved:-none}'. Look at the card in Linear."
689
+ # And the card's other labels are all still there.
690
+ lost=$(printf '%s' "$data" | jq -r --argjson keep "$(printf '%s' "$plan" | jq -c '.keep')" \
691
+ '$keep - [.issueUpdate.issue.labels.nodes[]?.name] | join(", ")' 2>/dev/null) || lost='its other labels'
692
+ [ -z "$lost" ] ||
693
+ die "Linear set $card's type to $type, but its answer shows the card without $lost. Look at the card in Linear."
694
+ say "Set $card's type to $type${was:+ (it was $was)}"
695
+ }
696
+
697
+ # The sections the card skills write, in the order they come on a card.
698
+ # Specification, Plan and Review are folded away; the human reads the
699
+ # Breakdown to approve the card, so it is left open. The Review, which
700
+ # sdlc-review writes, comes last: an open Breakdown ends at the next fold,
701
+ # which is the Review's heading.
702
+ CARD_SECTIONS='Specification Plan Breakdown Review'
703
+
704
+ # The question for linear section: the card and its description.
705
+ SECTION_QUERY='query($team: String!, $number: Float!) {
706
+ issues(first: 1, filter: {team: {key: {eq: $team}}, number: {eq: $number}}) {
707
+ nodes { id identifier description }
708
+ }
709
+ }'
710
+
711
+ # Place a section in a description, on stdin, and print
712
+ # {"before": <the text above it>, "new": <the description with it>}
713
+ # A folded section is "+++ ## <name>", its body, then a line "+++": the form
714
+ # Linear's API keeps it in, whatever it was written with. One written as
715
+ # ">>>", the form Linear's own tools show, is read the same. An open section
716
+ # is "## <name>" and its body, up to the next section or the end. $open,
717
+ # $replace: "true" or "false". Linear's own copy of a description can end its
718
+ # lines with \r and its sections with blank lines, so both are allowed for.
719
+ # - A line inside a fenced code block is the card's text, never a section:
720
+ # a card about ocnus itself may show these forms as examples.
721
+ # - An open section ends at the next heading of level 1 or 2, or the next
722
+ # fold. A folded one ends at its closing line, and only there: a folded
723
+ # section that meets another fold before it is closed cannot be told
724
+ # apart from the next one, so it is not replaced.
725
+ SECTION_FORMS='
726
+ def trim_end: sub("\\s+\\z"; "");
727
+ def trim_start: sub("\\A\\s+"; "");
728
+ def is_heading: if $open == "true" then . == "## " + $name
729
+ else . == "+++ ## " + $name or . == ">>> ## " + $name end;
730
+ def is_close: . == "+++" or . == ">>>";
731
+ def is_fold: test("^(\\+\\+\\+|>>>)( |$)");
732
+ def ends_open: is_fold or test("^##? ");
733
+ def is_fence: test("^ {0,3}(```|~~~)");
734
+ def in_code: . as $l
735
+ | [foreach range(0; $l | length) as $i ({in: false, out: false};
736
+ if ($l[$i] | is_fence) then {in: (.in | not), out: true} else {in: .in, out: .in} end;
737
+ .out)];'
738
+ SECTION_PLACE=$SECTION_FORMS'
739
+ def section: if $open == "true" then "## " + $name + "\n" + $body
740
+ else "+++ ## " + $name + "\n" + $body + "\n+++" end;
741
+ def join_parts: map(select(. != "")) | join("\n\n");
742
+ (. // "") as $d
743
+ | ($d | split("\n")) as $raw
744
+ | ($raw | map(rtrimstr("\r"))) as $lines
745
+ | ($lines | in_code) as $code
746
+ | [range(0; $lines | length) | select(($code[.] | not) and ($lines[.] | is_heading))] as $at
747
+ | if ($at | length) > 1 then error("twice")
748
+ elif ($at | length) == 1 and $replace != "true" then error("there")
749
+ elif ($at | length) == 0 and $replace == "true" then error("missing")
750
+ elif ($at | length) == 0 then
751
+ ($d | trim_end) as $before
752
+ | {before: $before, new: ([$before, section] | join_parts)}
753
+ else $at[0] as $start
754
+ | [range($start + 1; $lines | length) | select($code[.] | not)] as $later
755
+ | (if $open == "true"
756
+ then {at: ([$later[] | select($lines[.] | ends_open)] | .[0] // ($lines | length)), skip: 0}
757
+ else ([$later[] | select($lines[.] | is_fold)] | .[0]) as $fold
758
+ | {at: (if $fold != null and ($lines[$fold] | is_close) then $fold else null end), skip: 1}
759
+ end) as $end
760
+ | if $end.at == null then error("open") else . end
761
+ | ($raw[0:$start] | join("\n") | trim_end) as $before
762
+ | ($raw[($end.at + $end.skip):] | join("\n") | trim_start | trim_end) as $after
763
+ | {before: $before, new: ([$before, section, $after] | join_parts)}
764
+ end'
765
+
766
+ # Check a description Linear saved, on stdin: it has the section once, and
767
+ # the text above it is $before. Prints ok, or what is wrong. Line ends are
768
+ # compared without their \r, which Linear may keep or drop.
769
+ SECTION_CHECK=$SECTION_FORMS'
770
+ ((.issueUpdate.issue.description // "") | split("\n") | map(rtrimstr("\r"))) as $lines
771
+ | ($lines | in_code) as $code
772
+ | [range(0; $lines | length) | select(($code[.] | not) and ($lines[.] | is_heading))] as $at
773
+ | if ($at | length) != 1 then "count"
774
+ elif ($lines[0:$at[0]] | join("\n") | trim_end)
775
+ != ($before | split("\n") | map(rtrimstr("\r")) | join("\n") | trim_end) then "above"
776
+ else "ok" end'
777
+
778
+ # Whether a section body, on stdin, has a line that would end the section
779
+ # early or start a second one: a fold line in a folded section, and a heading
780
+ # of level 1 or 2 or a fold line in an open one. Prints true or false.
781
+ SECTION_BODY_CHECK=$SECTION_FORMS'
782
+ split("\n") | map(rtrimstr("\r")) | . as $l | ($l | in_code) as $code
783
+ | any(range(0; $l | length);
784
+ ($code[.] | not) and ($l[.] | if $open == "true" then ends_open else is_fold end))'
785
+
786
+ # Add a section to a card's description, below what is there, or with
787
+ # --replace put it in place of the one of that name. The body is on stdin;
788
+ # the heading and the folding are added here. The whole description is sent
789
+ # back, then what Linear saved is read: the text above the section must be as
790
+ # it was, and the section there once.
791
+ # ocnus linear section <card> <Specification|Plan|Breakdown|Review> [--replace]
792
+ linear_section() {
793
+ local card=${1:-} name=${2:-} replace=false open=false body key vars data id placed new before check
794
+ [ "$#" -ge 2 ] && [ "$#" -le 3 ] ||
795
+ die "usage: ocnus linear section <card> <$(printf '%s' "$CARD_SECTIONS" | tr ' ' '|')> [--replace], with the section's body on stdin"
796
+ case ${3:-} in
797
+ --replace) replace=true ;;
798
+ '') ;;
799
+ *) die "unknown option for linear section: $3" ;;
800
+ esac
801
+ [[ $card =~ $CARD_RE ]] || die "'$card' is not a card ID like ABC-122."
802
+ card=$(printf '%s' "$card" | tr '[:lower:]' '[:upper:]')
803
+ in_list "$name" "$CARD_SECTIONS" ||
804
+ die "'$name' is not a section ocnus writes. The sections are: $CARD_SECTIONS."
805
+ [ "$name" != Breakdown ] || open=true
806
+ [ ! -t 0 ] || die "give the section's body on stdin, like: ocnus linear section $card $name <<'EOF'"
807
+ # jq reads the body, so it is checked for before the body is.
808
+ linear_tools
809
+ body=$(cat)
810
+ # Blank lines at either end are dropped: the heading and the folding come
811
+ # with their own.
812
+ body=$(printf '%s' "$body" | jq -Rs 'sub("\\A\\s+"; "") | sub("\\s+\\z"; "")') ||
813
+ die "could not read the section's body."
814
+ [ "$body" != '""' ] || die "the $name has no body. Give it on stdin."
815
+ # Judged by what jq prints: some versions exit zero on an empty answer.
816
+ case $(printf '%s' "$body" | jq -r --arg open "$open" --arg name "$name" "$SECTION_BODY_CHECK" 2>/dev/null) in
817
+ false) ;;
818
+ true)
819
+ if [ "$open" = true ]; then
820
+ die "the $name's body has a line that starts a heading (# or ##) or a folded section (+++ or >>>), which would end the $name early. Make it a ### heading, or take it out. The command adds the $name's own heading."
821
+ else
822
+ die "the $name's body has a line that starts or ends a folded section (+++ or >>>), which would end the $name early. Take that line out. The command adds the $name's own heading and closing line."
823
+ fi ;;
824
+ *) die "could not read the section's body." ;;
825
+ esac
826
+ key=$(linear_saved_key) || exit 1
827
+ vars=$(jq -cn --arg team "${card%-*}" --arg number "${card##*-}" '{team: $team, number: ($number | tonumber)}') ||
828
+ die "'$card' is not a card ID like ABC-122."
829
+ data=$(linear_ask "$key" "$SECTION_QUERY" "$vars") || exit 1
830
+ case $(printf '%s' "$data" | jq -r 'if (.issues.nodes | type) != "array" then "unreadable" elif (.issues.nodes | length) == 0 then "none" else "ok" end' 2>/dev/null) in
831
+ ok) ;;
832
+ none) die "Linear has no card $card that the saved key can see. Check the ID, then run this again." ;;
833
+ *) die "Linear's answer was not one ocnus can read. Something between this machine and Linear may be answering for it." ;;
834
+ esac
835
+ id=$(printf '%s' "$data" | jq -r '.issues.nodes[0].id')
836
+ placed=$(printf '%s' "$data" | jq -c --arg name "$name" --arg open "$open" --arg replace "$replace" \
837
+ --argjson body "$body" '.issues.nodes[0].description | '"$SECTION_PLACE" 2>&1) || {
838
+ case $placed in
839
+ *there*) die "$card already has a $name. To put this one in its place, run it again with --replace." ;;
840
+ *twice*) die "$card has two sections called $name, so ocnus cannot tell which to change. Make it one in Linear, then run this again." ;;
841
+ *missing*) die "$card has no $name that ocnus can read, so there is none to replace. Look at the card in Linear: a $name written in another form needs putting right by hand." ;;
842
+ *open*) die "$card's $name is not closed before the next folded section, so ocnus cannot tell where it ends. Close it in Linear, then run this again." ;;
843
+ *) die "could not place the $name in $card's description." ;;
844
+ esac
845
+ }
846
+ new=$(printf '%s' "$placed" | jq -c '.new')
847
+ before=$(printf '%s' "$placed" | jq -r '.before')
848
+ data=$(linear_update "$key" "$id" "$(jq -cn --argjson d "$new" '{description: $d}')" 'description') || exit 1
849
+ check=$(printf '%s' "$data" | jq -r --arg name "$name" --arg open "$open" --arg before "$before" "$SECTION_CHECK" 2>/dev/null) || check=
850
+ case $check in
851
+ ok) ;;
852
+ above) die "the $name was written to $card, but the text above it changed on the way: Linear's copy is not what was there before. Look at the card in Linear." ;;
853
+ count) die "the $name was written to $card, but Linear's copy does not have it once. Look at the card in Linear." ;;
854
+ *) die "the $name was written to $card, but Linear's answer could not be read to check it. Look at the card in Linear." ;;
855
+ esac
856
+ if [ "$replace" = true ]; then say "Wrote the $name on $card"
857
+ else say "Added the $name to $card"
858
+ fi
859
+ }
860
+
861
+ # How many of a sub-issue's relations the slices' question reads. Linear caps
862
+ # what one question may cost, and each of the card's sub-issues counts them
863
+ # again. Missing one costs nothing: Linear keeps one relation of a kind
864
+ # between two cards, so a blocker added again is the same blocker.
865
+ SLICE_RELATIONS=20
866
+
867
+ # Read the slices, on stdin, raw: a line "<n>. <name>" for each, and below it
868
+ # its description, indented. Blank lines may come anywhere. Print
869
+ # {"slices": [{n, name, description}]}, the description without the
870
+ # indentation its lines share, or {"bad": <what>, ...} for the first thing
871
+ # wrong: a line in no slice, fewer than two slices, numbers that are not 1, 2,
872
+ # 3 and so on, a name given twice, or a slice with no description.
873
+ SLICES_READ='
874
+ def blank: test("^[ \t]*$");
875
+ def indent: match("^[ \t]*").length;
876
+ def drop_blank_ends: until(length == 0 or (.[0] | blank | not); .[1:])
877
+ | until(length == 0 or (.[length - 1] | blank | not); .[:length - 1]);
878
+ def body: drop_blank_ends
879
+ | if length == 0 then ""
880
+ else ([.[] | select(blank | not) | indent] | min) as $cut
881
+ | map(if blank then "" else .[$cut:] end) | join("\n") end;
882
+ (split("\n") | map(rtrimstr("\r"))) as $lines
883
+ | (reduce range(0; $lines | length) as $i ({slices: [], bad: null};
884
+ $lines[$i] as $l
885
+ | if .bad != null then .
886
+ elif ($l | test("^[0-9]+\\.[ \t]+[^ \t]")) then
887
+ ($l | capture("^(?<n>[0-9]+)\\.[ \t]+(?<name>.*)$")) as $c
888
+ | .slices += [{n: ($c.n | tonumber), name: ($c.name | sub("[ \t]+$"; "")), lines: []}]
889
+ elif ($l | blank) then
890
+ if (.slices | length) == 0 then . else .slices[(.slices | length) - 1].lines += [""] end
891
+ elif ($l | indent) > 0 and (.slices | length) > 0 then .slices[(.slices | length) - 1].lines += [$l]
892
+ else .bad = {bad: "outside", line: ($i + 1)}
893
+ end)) as $read
894
+ | ($read.slices | map({n, name, description: (.lines | body)})) as $slices
895
+ | if $read.bad != null then $read.bad
896
+ elif ($slices | length) < 2 then {bad: "fewer", count: ($slices | length)}
897
+ elif ([$slices[].n] != [range(1; ($slices | length) + 1)]) then {bad: "order", numbers: ([$slices[].n | tostring] | join(", "))}
898
+ elif ($slices | map(.name) | unique | length) != ($slices | length) then
899
+ {bad: "twice", name: ($slices | group_by(.name) | map(select(length > 1)) | .[0][0].name)}
900
+ elif any($slices[]; .description == "") then {bad: "nodesc", slice: first($slices[] | select(.description == ""))}
901
+ else {slices: $slices} end'
902
+
903
+ # The question for linear slices: the card, its team, parent and labels, and
904
+ # its sub-issues, each with the cards that block it.
905
+ SLICES_QUERY='query($team: String!, $number: Float!) {
906
+ issues(first: 1, filter: {team: {key: {eq: $team}}, number: {eq: $number}}) {
907
+ nodes {
908
+ id identifier
909
+ team { id key }
910
+ parent { identifier }
911
+ labels(first: 100) { nodes { id name parent { name } } }
912
+ children(first: '$READ_SUBS') {
913
+ nodes { id identifier title
914
+ inverseRelations(first: '$SLICE_RELATIONS') { nodes { type issue { id } } } }
915
+ pageInfo { hasNextPage }
916
+ }
917
+ }
918
+ }
919
+ }'
920
+
921
+ # From the answer to SLICES_QUERY, on stdin, and the slices ($slices, from
922
+ # SLICES_READ), what to do, as {"state": "ok", card, team, type, typeName,
923
+ # slices, others}: each slice with the id and identifier of its sub-issue when
924
+ # there is one, and the ids of the cards that block it; and the card's other
925
+ # sub-issues, which are left alone. Or {"state": <why not>, ...}: no such card,
926
+ # a card that is itself a sub-issue, one with no type or more than one, more
927
+ # sub-issues than were asked for, or two sub-issues of one slice's name. An
928
+ # answer with a card in it that is not in this form did not come from Linear.
929
+ # A sub-issue is a slice when its title is the slice's name, exactly.
930
+ SLICES_PLAN='
931
+ def text: if type == "string" then . else error("unreadable") end;
932
+ if (.issues.nodes | type) != "array" then error("no list of cards")
933
+ elif (.issues.nodes | length) == 0 then {state: "none"}
934
+ else .issues.nodes[0] as $card
935
+ | ($card.id | text) as $id | ($card.team.id | text) as $team
936
+ | (if ($card.children.nodes | type) == "array" then $card.children.nodes else error("unreadable") end
937
+ | map({id: (.id | text), identifier: (.identifier | text), title: (.title | text),
938
+ blockers: [.inverseRelations.nodes[]? | select(.type? == "blocks") | .issue.id? | strings]})) as $subs
939
+ | ([$card.labels.nodes[]? | select(.parent.name? == $group)]) as $types
940
+ | if $card.parent != null then {state: "sub", parent: ($card.parent.identifier? // "another card")}
941
+ elif $card.children.pageInfo.hasNextPage? == true then {state: "more"}
942
+ elif ($types | length) == 0 then {state: "notype"}
943
+ elif ($types | length) > 1 then {state: "types", types: ([$types[].name] | join(", "))}
944
+ else ([$slices[] | .name as $name | {slice: ., found: [$subs[] | select(.title == $name)]}]) as $each
945
+ | if any($each[]; (.found | length) > 1) then
946
+ first($each[] | select((.found | length) > 1))
947
+ | {state: "twice", name: .slice.name, ids: ([.found[].identifier] | join(" and "))}
948
+ else {state: "ok", card: $id, team: $team, type: ($types[0].id | text), typeName: ($types[0].name | text),
949
+ slices: [$each[] | .slice + {id: (.found[0].id // null), identifier: (.found[0].identifier // null),
950
+ blockers: (.found[0].blockers // [])}],
951
+ others: [$subs[] | .title as $title | select(all($slices[]; .name != $title)) | {identifier, title}]}
952
+ end
953
+ end
954
+ end'
955
+
956
+ # The changes linear slices makes: a slice, and a slice's blocker. Each
957
+ # answers with what Linear made, to be read back.
958
+ SLICE_CREATE='mutation($input: IssueCreateInput!) {
959
+ issueCreate(input: $input) { success issue { id identifier title parent { id } labels(first: 100) { nodes { id } } } }
960
+ }'
961
+ SLICE_BLOCK='mutation($input: IssueRelationCreateInput!) {
962
+ issueRelationCreate(input: $input) { success issueRelation { type issue { id } relatedIssue { id } } }
963
+ }'
964
+
965
+ # Stop linear slices partway, saying why, and that a run again picks up
966
+ # where this one stopped. The slices made so far are on stdout by now.
967
+ # slices_stopped <what could not be done> <why, as linear_ask said it>
968
+ slices_stopped() {
969
+ die "$1: $(first_sentence "$2"). Run this again with the same slices to make the rest: it finds the slices already there by their names, so none is made twice."
970
+ }
971
+
972
+ # Make a card's slices as its sub-issues, in order, from the list on stdin: a
973
+ # line "<n>. <name>" for each, and its description indented below it. Each is
974
+ # made in the card's team with the card's type, the name as its title, and is
975
+ # blocked by the slice before it; the first is blocked by nothing. A slice
976
+ # whose name a sub-issue of the card has as its title is there already, and
977
+ # only its blocker is added, when it lacks it. So a run that stopped partway
978
+ # is picked up by running it again with the same slices. Every other
979
+ # sub-issue is left alone, and named. Each slice and blocker made is read back
980
+ # before the next is made. It prints one line for each slice:
981
+ # Slice <n> of <total>: <ID> <name> (made, blocked by <ID>)
982
+ # ocnus linear slices <card>
983
+ linear_slices() {
984
+ local card=${1:-} given slices vars key data plan bad total i n slice name id ident how prev='' prev_ident='' made check
985
+ [ "$#" -eq 1 ] ||
986
+ die "usage: ocnus linear slices <card>, with the slices on stdin: a line '<n>. <name>' for each, and its description indented below it"
987
+ [[ $card =~ $CARD_RE ]] || die "'$card' is not a card ID like ABC-122."
988
+ card=$(printf '%s' "$card" | tr '[:lower:]' '[:upper:]')
989
+ [ ! -t 0 ] || die "give the slices on stdin, like: ocnus linear slices $card <<'EOF'"
990
+ # jq reads the slices, so it is checked for before they are.
991
+ linear_tools
992
+ given=$(cat | jq -Rsc "$SLICES_READ" 2>/dev/null) || given=
993
+ bad=$(printf '%s' "$given" | jq -r 'if type == "object" then .bad // "" else "unreadable" end' 2>/dev/null) || bad=
994
+ [ -n "$given" ] || bad=unreadable
995
+ case $bad in
996
+ '') ;;
997
+ outside) die "line $(printf '%s' "$given" | jq -r '.line') of the slices is neither a slice, '<n>. <name>', nor indented below one as its description. Nothing was made." ;;
998
+ fewer) die "give two slices or more: a card of one piece has no slices, and its Breakdown says so. Nothing was made." ;;
999
+ order) die "the slices are numbered $(printf '%s' "$given" | jq -r '.numbers'), not 1, 2, 3 and so on in order. Nothing was made." ;;
1000
+ twice) die "the slice name '$(printf '%s' "$given" | jq -r "$PLAIN_DEF"' .name | plain')' is given twice, so its sub-issues could not be told apart. Nothing was made." ;;
1001
+ nodesc) die "slice $(printf '%s' "$given" | jq -r "$PLAIN_DEF"' .slice | "\(.n), \(.name | plain)"'), has no description: give one or two sentences on what it delivers, indented below its name. Nothing was made." ;;
1002
+ *) die "could not read the slices. Nothing was made." ;;
1003
+ esac
1004
+ slices=$(printf '%s' "$given" | jq -c '.slices')
1005
+ total=$(printf '%s' "$slices" | jq 'length')
1006
+ key=$(linear_saved_key) || exit 1
1007
+ vars=$(jq -cn --arg team "${card%-*}" --arg number "${card##*-}" '{team: $team, number: ($number | tonumber)}') ||
1008
+ die "'$card' is not a card ID like ABC-122."
1009
+ data=$(linear_ask "$key" "$SLICES_QUERY" "$vars") || exit 1
1010
+ # Judged by what jq prints: some versions exit zero on an empty answer.
1011
+ plan=$(printf '%s' "$data" | jq -c --arg group "$TYPE_GROUP" --argjson slices "$slices" "$SLICES_PLAN" 2>/dev/null) || plan=
1012
+ case $(printf '%s' "$plan" | jq -r '.state' 2>/dev/null) in
1013
+ ok) ;;
1014
+ none) die "Linear has no card $card that the saved key can see. Check the ID, then run this again." ;;
1015
+ sub) die "$card is itself a sub-issue, of $(printf '%s' "$plan" | jq -r "$PLAIN_DEF"' .parent | plain'), and slices go one level deep. Nothing was made." ;;
1016
+ more) die "$card has more than $READ_SUBS sub-issues, more than ocnus reads, so it cannot tell which slices are there already. Nothing was made." ;;
1017
+ notype) die "$card has no type, and its slices take the card's. Set it with: ocnus linear type $card <$(printf '%s' "$CARD_TYPES" | tr ' ' '|')>, then run this again. Nothing was made." ;;
1018
+ types) die "$card has more than one type ($(printf '%s' "$plan" | jq -r "$PLAIN_DEF"' .types | plain')), and its slices take the card's. Set the one with: ocnus linear type $card <$(printf '%s' "$CARD_TYPES" | tr ' ' '|')>, then run this again. Nothing was made." ;;
1019
+ twice) die "$card has two sub-issues titled '$(printf '%s' "$plan" | jq -r "$PLAIN_DEF"' .name | plain')', $(printf '%s' "$plan" | jq -r "$PLAIN_DEF"' .ids | plain'), so ocnus cannot tell which is the slice. Make it one in Linear, then run this again. Nothing was made." ;;
1020
+ *) die "Linear's answer was not one ocnus can read. Something between this machine and Linear may be answering for it." ;;
1021
+ esac
1022
+ for ((i = 0; i < total; i++)); do
1023
+ n=$((i + 1))
1024
+ slice=$(printf '%s' "$plan" | jq -c --argjson i "$i" '.slices[$i]')
1025
+ name=$(printf '%s' "$slice" | jq -r "$PLAIN_DEF"' .name | plain')
1026
+ id=$(printf '%s' "$slice" | jq -r '.id // empty')
1027
+ if [ -n "$id" ]; then
1028
+ ident=$(printf '%s' "$slice" | jq -r "$PLAIN_DEF"' .identifier | plain')
1029
+ how='there already'
1030
+ else
1031
+ vars=$(printf '%s' "$plan" | jq -c --argjson slice "$slice" \
1032
+ '{input: {teamId: .team, parentId: .card, labelIds: [.type], title: $slice.name, description: $slice.description}}')
1033
+ made=$(linear_ask "$key" "$SLICE_CREATE" "$vars" 2>&1) ||
1034
+ slices_stopped "could not make slice $n of $total, $name" "$made"
1035
+ # What Linear made: a sub-issue of the card, of its type, with the
1036
+ # slice's name as its title.
1037
+ check=$(printf '%s' "$made" | jq -c --arg card "$(printf '%s' "$plan" | jq -r '.card')" \
1038
+ --arg type "$(printf '%s' "$plan" | jq -r '.type')" --argjson slice "$slice" "$PLAIN_DEF"'
1039
+ .issueCreate.issue as $made
1040
+ | if ($made | type) != "object" or ($made.id | type) != "string" or ($made.identifier | type) != "string"
1041
+ then {state: "unreadable"}
1042
+ else {id: $made.id, identifier: ($made.identifier | plain)}
1043
+ + if $made.parent.id? != $card then {state: "parent"}
1044
+ elif $made.title != $slice.name then {state: "title", title: ($made.title // "" | tostring | plain)}
1045
+ elif any($made.labels.nodes[]?; .id? == $type) | not then {state: "type"}
1046
+ else {state: "ok"} end
1047
+ end' 2>/dev/null) || check=
1048
+ ident=$(printf '%s' "$check" | jq -r '.identifier // empty' 2>/dev/null) || ident=
1049
+ case $(printf '%s' "$check" | jq -r '.state' 2>/dev/null) in
1050
+ ok) ;;
1051
+ parent) die "Linear made slice $n of $total, $name, as $ident, but not as a sub-issue of $card, as its answer shows. Look at it in Linear." ;;
1052
+ title) die "Linear made slice $n of $total as $ident, but its answer shows it titled '$(printf '%s' "$check" | jq -r '.title')', not '$name'. Put its title right in Linear before running this again, or the slice would be made twice." ;;
1053
+ type) die "Linear made slice $n of $total, $name, as $ident, but its answer shows it without the type $(printf '%s' "$plan" | jq -r "$PLAIN_DEF"' .typeName | plain'). Look at it in Linear." ;;
1054
+ *) die "Linear's answer did not show slice $n of $total, $name, made. Look at $card's sub-issues in Linear, then run this again with the same slices: it makes only the ones not there." ;;
1055
+ esac
1056
+ id=$(printf '%s' "$check" | jq -r '.id')
1057
+ how=made
1058
+ fi
1059
+ # Each slice but the first is blocked by the one before it.
1060
+ if [ -n "$prev" ] &&
1061
+ [ "$(printf '%s' "$slice" | jq -r --arg prev "$prev" 'any(.blockers[]; . == $prev)')" != true ]; then
1062
+ vars=$(jq -cn --arg from "$prev" --arg to "$id" '{input: {issueId: $from, relatedIssueId: $to, type: "blocks"}}')
1063
+ if ! made=$(linear_ask "$key" "$SLICE_BLOCK" "$vars" 2>&1); then
1064
+ if [ "$how" = made ]; then
1065
+ slices_stopped "made slice $n of $total, $name, as $ident, but could not mark it as blocked by $prev_ident" "$made"
1066
+ else
1067
+ slices_stopped "could not mark slice $n of $total, $ident $name, as blocked by $prev_ident" "$made"
1068
+ fi
1069
+ fi
1070
+ [ "$(printf '%s' "$made" | jq -r --arg from "$prev" --arg to "$id" '
1071
+ .issueRelationCreate.issueRelation | type == "object" and .type? == "blocks"
1072
+ and .issue.id? == $from and .relatedIssue.id? == $to' 2>/dev/null)" = true ] ||
1073
+ die "Linear did not mark $ident as blocked by $prev_ident, as its answer shows. Look at it in Linear, then run this again with the same slices to add it."
1074
+ if [ "$how" = made ]; then how="made, blocked by $prev_ident"
1075
+ else how="there already, now blocked by $prev_ident"
1076
+ fi
1077
+ fi
1078
+ say "Slice $n of $total: $ident $name ($how)"
1079
+ prev=$id
1080
+ prev_ident=$ident
1081
+ done
1082
+ printf '%s' "$plan" | jq -r --arg card "$card" "$PLAIN_DEF"'
1083
+ .others[] | "Left alone: \(.identifier | plain) \(.title | plain), a sub-issue of \($card) that is not one of its slices"'
1084
+ }
1085
+
1086
+ # --- moving a card ----------------------------------------------------------
1087
+ #
1088
+ # ocnus moves a card at four points: the hand-off that records the
1089
+ # human's approval moves it, and each of its sub-issues, to its team's first
1090
+ # not-started status; `task start` moves it to its team's first started
1091
+ # status; `sdlc-pr` runs `linear move <card> review` once every pull request
1092
+ # for it is open, which moves it to the last started status; and the hand-off
1093
+ # that records its merge moves it to the first completed one. A slice's
1094
+ # start and its merge move the card it was sliced from too: its start to the
1095
+ # first started status, and its merge to the first completed one once every
1096
+ # one of that card's sub-issues is closed. The status is picked by its kind
1097
+ # and its place in the team's order, never by its name, which each team
1098
+ # chooses. A card only moves forward, so a person who has moved it further on
1099
+ # by hand is never undone, and a card that is done, canceled or a duplicate
1100
+ # is never moved at all.
1101
+
1102
+ # The kinds of status a card moves through, in order. A card in a completed
1103
+ # status, or one of any other kind, is closed.
1104
+ MOVE_ORDER='{"triage":0,"backlog":1,"unstarted":2,"started":3,"completed":4}'
1105
+
1106
+ # A card in a move's question: its ids and its status.
1107
+ MOVE_FIELDS='id identifier state { id name type position }'
1108
+ # The question for a move: the card, its status, and its team's statuses.
1109
+ MOVE_QUERY='query($team: String!, $number: Float!) {
1110
+ issues(first: 1, filter: {team: {key: {eq: $team}}, number: {eq: $number}}) {
1111
+ nodes { '$MOVE_FIELDS'
1112
+ team { states(first: 250) { nodes { id name type position } } } }
1113
+ }
1114
+ }'
1115
+ # The question for a start's move and a merge's, which move a slice's parent
1116
+ # too: the same, and the card's parent with its status, its team's statuses
1117
+ # and its sub-issues with the kind of status each is in, so that the merge can
1118
+ # tell whether they are all closed. A card with no parent has null there.
1119
+ PARENT_QUERY='query($team: String!, $number: Float!) {
1120
+ issues(first: 1, filter: {team: {key: {eq: $team}}, number: {eq: $number}}) {
1121
+ nodes { '$MOVE_FIELDS'
1122
+ team { states(first: 250) { nodes { id name type position } } }
1123
+ parent { '$MOVE_FIELDS'
1124
+ team { states(first: 250) { nodes { id name type position } } }
1125
+ children(first: '$READ_SUBS') { nodes { identifier state { type } } pageInfo { hasNextPage } } } }
1126
+ }
1127
+ }'
1128
+ # The question for the approval's move, which moves the card's sub-issues
1129
+ # too: the same, and each sub-issue with its status and its own team's
1130
+ # statuses. Linear caps what one question may cost, and each sub-issue's
1131
+ # statuses count again, so fewer are asked for than for the card itself.
1132
+ APPROVED_QUERY='query($team: String!, $number: Float!) {
1133
+ issues(first: 1, filter: {team: {key: {eq: $team}}, number: {eq: $number}}) {
1134
+ nodes { '$MOVE_FIELDS'
1135
+ team { states(first: 250) { nodes { id name type position } } }
1136
+ children(first: 50) { nodes { '$MOVE_FIELDS'
1137
+ team { states(first: 50) { nodes { id name type position } } } } } }
1138
+ }
1139
+ }'
1140
+
1141
+ # From the answer to MOVE_QUERY, PARENT_QUERY or APPROVED_QUERY, on stdin,
1142
+ # what to do with each card: a list of {card, plan}, the card first and then,
1143
+ # for approved, each of its sub-issues, or for started and completed, its
1144
+ # parent, if it has one, marked parent: true; or "none" when Linear has no
1145
+ # such card. $card is the card's ID, $to is where to move to, approved,
1146
+ # started, review or completed, and $order is MOVE_ORDER. The target is the
1147
+ # status of that kind that comes first in the card's team's order (approved is
1148
+ # the first unstarted one); for review it is the started status that comes
1149
+ # last, which in a team with one started status is that one. A card moves only
1150
+ # when the target is further along: a later kind, or a later place within the
1151
+ # same kind. For completed, a parent that would move stays instead while any
1152
+ # of its sub-issues other than the card is open, with a plan of "open" naming
1153
+ # them and how many it has in all; and one with more sub-issues than were
1154
+ # read is "unread", since one of the rest may be open. An answer with a card
1155
+ # in it that cannot be read did not come from Linear, so none is moved.
1156
+ MOVE_PLAN='
1157
+ def place: (.position | numbers) // 1000000;
1158
+ def card_id: if (.identifier | type) != "string" or (.identifier | test("^[A-Za-z][A-Za-z0-9]*-[0-9]+$") | not)
1159
+ then error("unreadable") else .identifier | ascii_upcase end;
1160
+ (if $to == "review" then "started" elif $to == "approved" then "unstarted" else $to end) as $kind
1161
+ | def plan:
1162
+ .state as $now
1163
+ | if (.id | type) != "string" or ($now.id? | type) != "string"
1164
+ or ($now.type? | type) != "string" or (.team.states.nodes? | type) != "array"
1165
+ then error("unreadable") else . end
1166
+ | ([.team.states.nodes[] | select(.type == $kind and (.id | type) == "string")]
1167
+ | sort_by(place) | if $to == "review" then last else first end) as $target
1168
+ | if $target == null then {state: "notarget"}
1169
+ elif $now.id == $target.id then {state: "there", now: $now.name}
1170
+ elif $order[$now.type] == null or $now.type == "completed" then {state: "closed", now: $now.name}
1171
+ elif $order[$target.type] > $order[$now.type]
1172
+ or ($target.type == $now.type and ($target | place) > ($now | place))
1173
+ then {state: "move", id: .id, to: $target.id, name: $target.name, was: $now.name}
1174
+ else {state: "past", now: $now.name, name: $target.name}
1175
+ end;
1176
+ if (.issues.nodes | type) != "array" then error("no list of cards")
1177
+ elif (.issues.nodes | length) == 0 then "none"
1178
+ else .issues.nodes[0]
1179
+ | [{card: $card, plan: plan}]
1180
+ + if $to != "approved" then []
1181
+ elif (.children.nodes | type) != "array" then error("no list of sub-issues")
1182
+ else [.children.nodes[] | {card: card_id, plan: plan}]
1183
+ end
1184
+ + if ($to != "started" and $to != "completed") or .parent == null then []
1185
+ else .parent | card_id as $parent | plan as $plan
1186
+ | if $to != "completed" or $plan.state != "move" then [{card: $parent, plan: $plan, parent: true}]
1187
+ elif (.children.nodes | type) != "array" or (.children.pageInfo.hasNextPage | type) != "boolean"
1188
+ then error("no list of sub-issues")
1189
+ else [.children.nodes[]
1190
+ | if (.state.type? | type) != "string" then error("unreadable") else . end
1191
+ | {id: card_id, type: .state.type}] as $subs
1192
+ | [$subs[] | select(.id != $card and $order[.type] != null and .type != "completed") | .id] as $open
1193
+ | if .children.pageInfo.hasNextPage then [{card: $parent, plan: {state: "unread"}, parent: true}]
1194
+ elif ($open | length) > 0
1195
+ then [{card: $parent, plan: {state: "open", now: $plan.was, open: $open, total: ($subs | length)}, parent: true}]
1196
+ else [{card: $parent, plan: $plan, parent: true}]
1197
+ end
1198
+ end
1199
+ end
1200
+ end'
1201
+
1202
+ # Ask Linear what to do with a card and, for approved, its sub-issues, or for
1203
+ # started and completed, its parent, and print the list MOVE_PLAN makes, as
1204
+ # one line of JSON; or stop and say why.
1205
+ # move_plans <card ID, in upper case> <approved|started|review|completed>
1206
+ move_plans() {
1207
+ local card=$1 to=$2 query=$MOVE_QUERY key vars data plans
1208
+ case $to in
1209
+ approved) query=$APPROVED_QUERY ;;
1210
+ started | completed) query=$PARENT_QUERY ;;
1211
+ esac
1212
+ linear_tools
1213
+ key=$(linear_saved_key) || exit 1
1214
+ vars=$(jq -cn --arg team "${card%-*}" --arg number "${card##*-}" \
1215
+ '{team: $team, number: ($number | tonumber)}' 2>/dev/null) ||
1216
+ die "'$card' is not a card ID like ABC-122."
1217
+ data=$(linear_ask "$key" "$query" "$vars") || exit 1
1218
+ plans=$(printf '%s' "$data" |
1219
+ jq -c --arg card "$card" --arg to "$to" --argjson order "$MOVE_ORDER" "$MOVE_PLAN" 2>/dev/null) || plans=
1220
+ case $plans in
1221
+ '['*) printf '%s\n' "$plans" ;;
1222
+ '"none"') die "Linear has no card $card that the saved key can see." ;;
1223
+ *) die "Linear's answer was not one ocnus can read. Something between this machine and Linear may be answering for it." ;;
1224
+ esac
1225
+ }
1226
+
1227
+ # Move one card by its plan from MOVE_PLAN, and read the change back: the
1228
+ # card has to be in the status asked for. It says where the card is now, or
1229
+ # stops and says why it was not moved. A parent whose other slices are open
1230
+ # stays where it is, which is not a failure.
1231
+ # move_by_plan <card ID> <its plan, as JSON> <approved|started|review|completed>
1232
+ move_by_plan() {
1233
+ local card=$1 plan=$2 kind key data saved
1234
+ case $3 in
1235
+ approved) kind=unstarted ;;
1236
+ review) kind=started ;;
1237
+ *) kind=$3 ;;
1238
+ esac
1239
+ case $(printf '%s' "$plan" | jq -r '.state' 2>/dev/null) in
1240
+ move) ;;
1241
+ there) say "$card is in $(printf '%s' "$plan" | jq -r '.now') already"; return ;;
1242
+ past) say "$card stays in $(printf '%s' "$plan" | jq -r '.now'), which is past $(printf '%s' "$plan" | jq -r '.name'): a card only moves forward"; return ;;
1243
+ closed) say "$card stays in $(printf '%s' "$plan" | jq -r '.now'), which is closed: a card that is done or canceled is never moved"; return ;;
1244
+ open) say "$card stays in $(printf '%s' "$plan" | jq -r '
1245
+ (.open | length) as $n
1246
+ | "\(.now): \($n) of its \(.total) slices \(if $n == 1 then "is" else "are" end) still open (\(.open | join(", ")))"')"
1247
+ return ;;
1248
+ unread) die "it has more than $READ_SUBS sub-issues, more than ocnus reads" ;;
1249
+ notarget) die "team ${card%-*} has no $kind status in Linear." ;;
1250
+ *) die "Linear's answer was not one ocnus can read. Something between this machine and Linear may be answering for it." ;;
1251
+ esac
1252
+ key=$(linear_saved_key) || exit 1
1253
+ data=$(linear_update "$key" "$(printf '%s' "$plan" | jq -r '.id')" \
1254
+ "$(printf '%s' "$plan" | jq -c '{stateId: .to}')" 'state { id name }') || exit 1
1255
+ # What Linear says the card is in now: the status asked for.
1256
+ saved=$(printf '%s' "$data" | jq -r '.issueUpdate.issue.state.id // empty' 2>/dev/null) || saved=
1257
+ [ "$saved" = "$(printf '%s' "$plan" | jq -r '.to')" ] ||
1258
+ die "Linear did not save $card in $(printf '%s' "$plan" | jq -r '.name'): its answer shows it in $(printf '%s' "$data" | jq -r '.issueUpdate.issue.state.name // "no status"' 2>/dev/null || printf 'no status'). Look at the card in Linear."
1259
+ say "$card moved to $(printf '%s' "$plan" | jq -r '.name') in Linear (it was $(printf '%s' "$plan" | jq -r '.was'))"
1260
+ }
1261
+
1262
+ # What linear_move says of a card it could not move: the card's ID, then this,
1263
+ # then why. A line it says of a card that moved, or stays, never matches.
1264
+ NOT_MOVED_RE='^([A-Z][A-Z0-9]*-[0-9]+) was not moved in Linear(: (.*))?$'
1265
+
1266
+ # Move a card forward to its team's first status of a kind, or for review its
1267
+ # last started one, or leave it where it is and say why. For approved, each of
1268
+ # the card's sub-issues is moved after it the same way, by its own team's
1269
+ # statuses: each card on its own, so one that stays or cannot be moved never
1270
+ # keeps another from moving. For started and completed, the card's parent, if
1271
+ # it has one, is moved after it the same way, by its own team's statuses; for
1272
+ # completed only once the card itself is closed, so a card that was not moved
1273
+ # leaves its parent untried, and only once every other sub-issue of the
1274
+ # parent is closed too. It says one line for each card: where it is now, or
1275
+ # "<card> was not moved in Linear: <why>". It returns 1 when a card was not
1276
+ # moved; when Linear cannot be asked, that is the card itself.
1277
+ # linear_move <card ID, in upper case> <approved|started|review|completed>
1278
+ linear_move() {
1279
+ local card=$1 to=$2 plans each out id role plan failed=0 card_failed=0
1280
+ if ! plans=$(move_plans "$card" "$to" 2>&1); then
1281
+ out=${plans#ocnus: }
1282
+ say "$card was not moved in Linear${out:+: ${out//$'\n'/ }}"
1283
+ return 1
1284
+ fi
1285
+ # One line for each card: its ID, whether it is the card's parent, then its
1286
+ # plan.
1287
+ each=$(printf '%s' "$plans" |
1288
+ jq -r '.[] | .card + " " + (if .parent == true then "parent" else "card" end) + " " + (.plan | tojson)' 2>/dev/null) || each=
1289
+ if [ -z "$each" ]; then
1290
+ say "$card was not moved in Linear: Linear's answer was not one ocnus can read"
1291
+ return 1
1292
+ fi
1293
+ while read -r id role plan; do
1294
+ [ -n "$id" ] || continue
1295
+ if [ "$role" = parent ] && [ "$to" = completed ] && [ "$card_failed" = 1 ]; then
1296
+ say "$id was not moved in Linear: its slice $card was not moved"
1297
+ failed=1
1298
+ elif out=$(move_by_plan "$id" "$plan" "$to" 2>&1); then
1299
+ say "$out"
1300
+ else
1301
+ out=${out#ocnus: }
1302
+ say "$id was not moved in Linear${out:+: ${out//$'\n'/ }}"
1303
+ failed=1
1304
+ [ "$role" = parent ] || [ "$id" != "$card" ] || card_failed=1
1305
+ fi
1306
+ done <<< "$each"
1307
+ return "$failed"
1308
+ }
1309
+
1310
+ # The first sentence of a message from die, on one line, with no "ocnus: "
1311
+ # before it. The rest of such a message is often advice for a command that
1312
+ # stops, such as to run it again, which is wrong for a step that goes on.
1313
+ first_sentence() {
1314
+ local why=$1
1315
+ why=${why#ocnus: }; why=${why%%$'\n'*}; why=${why%%. *}; why=${why%.}
1316
+ printf '%s' "$why"
1317
+ }
1318
+
1319
+ # Move a card as linear_move does, for a command whose own work is done by
1320
+ # then and must not be undone by Linear: it never stops. It prints what
1321
+ # linear_move said, one line for each card, with only the first sentence of
1322
+ # why a card was not moved, and returns 1 when a card was not moved.
1323
+ # linear_move_note <card ID, in upper case> <approved|started|completed>
1324
+ linear_move_note() {
1325
+ local out line rc=0
1326
+ out=$(linear_move "$1" "$2" 2>&1) || rc=1
1327
+ while IFS= read -r line; do
1328
+ if [[ $line =~ $NOT_MOVED_RE ]] && [ -n "${BASH_REMATCH[3]}" ]; then
1329
+ say "${BASH_REMATCH[1]} was not moved in Linear: $(first_sentence "${BASH_REMATCH[3]}")"
1330
+ else
1331
+ say "$line"
1332
+ fi
1333
+ done <<< "$out"
1334
+ return "$rc"
1335
+ }
1336
+
1337
+ # The places `linear move` takes a card to, in the order a card goes through
1338
+ # them. done is the first completed status, which linear_move calls
1339
+ # completed.
1340
+ MOVE_WORDS='approved started review done'
1341
+
1342
+ # Move a card forward in Linear, by the rules of linear_move: approved is its
1343
+ # team's first not-started status (Todo in Lab, Ready for Dev in PHY), and
1344
+ # each of its sub-issues' too; started is its team's first started status,
1345
+ # review its last started one (In Review in Lab and PHY), and done its first
1346
+ # completed one. For a slice, started and done move the card it was sliced
1347
+ # from too, done only once every one of that card's sub-issues is closed.
1348
+ # Moving the card is the whole of this command, unlike in `task start` and
1349
+ # `task handoff`, so a move that cannot be made stops it, saying which card
1350
+ # was not moved, and why. A card that is there already, further on or closed
1351
+ # stays where it is, and so does a parent with slices still open, and that is
1352
+ # not a failure.
1353
+ # ocnus linear move <card> <approved|started|review|done>
1354
+ linear_move_cmd() {
1355
+ local card=${1:-} word=${2:-} to out line
1356
+ [ "$#" -eq 2 ] ||
1357
+ die "usage: ocnus linear move <card> <$(printf '%s' "$MOVE_WORDS" | tr ' ' '|')>, like: ocnus linear move ABC-122 review"
1358
+ [[ $card =~ $CARD_RE ]] || die "'$card' is not a card ID like ABC-122."
1359
+ card=$(printf '%s' "$card" | tr '[:lower:]' '[:upper:]')
1360
+ in_list "$word" "$MOVE_WORDS" ||
1361
+ die "'$word' is not a place a card moves to. A card moves to one of: $MOVE_WORDS."
1362
+ to=$word
1363
+ [ "$word" != done ] || to=completed
1364
+ if out=$(linear_move "$card" "$to" 2>&1); then
1365
+ say "$out"
1366
+ return
1367
+ fi
1368
+ # What happened to each card is said, a card that was not moved as an
1369
+ # error, and then the command stops.
1370
+ while IFS= read -r line; do
1371
+ if [[ $line =~ $NOT_MOVED_RE ]]; then printf 'ocnus: %s\n' "$line" >&2
1372
+ else say "$line"
1373
+ fi
1374
+ done <<< "$out"
1375
+ exit 1
1376
+ }
1377
+
1378
+ cmd_linear() {
1379
+ case ${1:-} in
1380
+ key) shift; linear_key "$@" ;;
1381
+ type) shift; linear_type "$@" ;;
1382
+ section) shift; linear_section "$@" ;;
1383
+ slices) shift; linear_slices "$@" ;;
1384
+ move) shift; linear_move_cmd "$@" ;;
1385
+ read) shift; linear_read "$@" ;;
1386
+ archive) shift; linear_archive_cmd "$@" ;;
1387
+ *) die "usage: ocnus linear key, or: ocnus linear read <card> [--json], or: ocnus linear type <card> <feat|fix|chore>, or: ocnus linear section <card> <Specification|Plan|Breakdown|Review> [--replace], or: ocnus linear slices <card>, or: ocnus linear move <card> <approved|started|review|done>, or: ocnus linear archive [on|off|--json] (see: ocnus help)" ;;
1388
+ esac
1389
+ }