@johngaynor/ocnus 2.0.1-next.27 → 2.0.1-next.69

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.
package/cli/lib/linear.sh CHANGED
@@ -1311,7 +1311,8 @@ linear_slices() {
1311
1311
  # sdlc-breakdown records every other card a card or a slice depends on, in
1312
1312
  # another parent card too, as one that blocks it, so that the cards start in
1313
1313
  # the order the work needs: `task start` holds a card while a card that
1314
- # blocks it is not done. A blocker is a relation of the kind "blocks", from
1314
+ # blocks it is not done, and the chain starts it once they all are
1315
+ # (chain.sh). A blocker is a relation of the kind "blocks", from
1315
1316
  # the blocker to the card, as linear slices makes between slices. Nothing
1316
1317
  # here ever removes one.
1317
1318
 
@@ -1414,6 +1415,202 @@ linear_block() {
1414
1415
  done
1415
1416
  }
1416
1417
 
1418
+ # --- the cards that wait to start -------------------------------------------
1419
+ #
1420
+ # The chain (chain.sh) starts a card once every card that blocks it is done.
1421
+ # Two questions tell it which cards wait: linear_blocks, for the cards that a
1422
+ # card whose merge was just recorded blocks, and linear_waiting, for every
1423
+ # card of some teams that is in a not-started status, whatever blocks it.
1424
+ # Neither changes anything in Linear.
1425
+
1426
+ # How much of each list the two questions read. Linear caps what one question
1427
+ # may cost, and counts a list inside a list again for every card of the outer
1428
+ # one (SLICE_RELATIONS), so each is kept small: of a card that has merged, and
1429
+ # of the card it was sliced from, the relations that name the cards it blocks;
1430
+ # of a card that waits, and of the card it was sliced from, the relations that
1431
+ # name the cards that block it; a card's sub-issues; and how many cards that
1432
+ # wait are asked for at a time. A card with more than was read says so
1433
+ # (CHAIN_DEFS), and a card that was not read is found by the next question
1434
+ # that asks about every card that waits.
1435
+ CHAIN_RELATIONS=10
1436
+ CHAIN_BLOCKERS=20
1437
+ CHAIN_SUBS=20
1438
+ WAITING_PAGE=20
1439
+ # The kinds of status a card that waits to start is in: approved, and not
1440
+ # started. A card in Backlog is not approved, and is never asked for.
1441
+ WAITING_TYPES='["unstarted"]'
1442
+
1443
+ # A card's relations of every kind that name it as the related card
1444
+ # (CARD_BLOCKERS_READ).
1445
+ CHAIN_BLOCKERS_READ='inverseRelations(first: '$CHAIN_BLOCKERS') {
1446
+ nodes { type issue { identifier state { name type } } } pageInfo { hasNextPage } }'
1447
+ # A card that waits, as both questions read it: its status, its description,
1448
+ # which holds its sections, the cards that block it and those that block the
1449
+ # card it was sliced from, and its sub-issues, each with its status, its
1450
+ # description and when it was made.
1451
+ CHAIN_CARD='identifier description state { name type }
1452
+ '$CHAIN_BLOCKERS_READ'
1453
+ parent { identifier
1454
+ '$CHAIN_BLOCKERS_READ' }
1455
+ children(first: '$CHAIN_SUBS') {
1456
+ nodes { identifier createdAt description state { name type } } pageInfo { hasNextPage } }'
1457
+ # A card's relations of every kind that it is the first card of. Those of the
1458
+ # kind "blocks" name a card it blocks, as their relatedIssue.
1459
+ CHAIN_BLOCKS_READ='relations(first: '$CHAIN_RELATIONS') {
1460
+ nodes { type relatedIssue {
1461
+ '$CHAIN_CARD' } }
1462
+ pageInfo { hasNextPage } }'
1463
+ # The question for linear_blocks: a card, the card it was sliced from, and
1464
+ # the cards each of the two blocks.
1465
+ BLOCKS_QUERY='query($team: String!, $number: Float!) {
1466
+ issues(first: 1, filter: {team: {key: {eq: $team}}, number: {eq: $number}}) {
1467
+ nodes { identifier state { name type }
1468
+ '$CHAIN_BLOCKS_READ'
1469
+ parent { identifier state { name type }
1470
+ '$CHAIN_BLOCKS_READ' } }
1471
+ }
1472
+ }'
1473
+ # The question for linear_waiting: one page of the cards of some teams that
1474
+ # are in a status of the kinds given, in the order they were made, which
1475
+ # nothing changes while the pages are fetched (LIST_QUERY).
1476
+ WAITING_QUERY='query($teams: [String!], $types: [String!], $first: Int, $after: String) {
1477
+ issues(first: $first, after: $after, orderBy: createdAt,
1478
+ filter: {team: {key: {in: $teams}}, state: {type: {in: $types}}}) {
1479
+ nodes { '$CHAIN_CARD' }
1480
+ pageInfo { hasNextPage endCursor }
1481
+ }
1482
+ }'
1483
+
1484
+ # What both shapes below are made of. waiting turns a card, as CHAIN_CARD
1485
+ # reads it, into
1486
+ # {id, status, type, spec, plan, parent, blockers, cut, subs, subsCut}
1487
+ # status and type are the name and the kind of its status, made plain, as
1488
+ # every text of Linear's here is. spec and plan say whether its description
1489
+ # has a Specification and a Plan: the heading `linear section` writes for
1490
+ # each (SECTION_FORMS), which a line inside a fenced code block never is.
1491
+ # parent is the ID of the card it was sliced from, or null. blockers are the
1492
+ # cards that block it, and those that block its parent, each as CARD_SHAPE
1493
+ # has it: {id, status, type, of}, done or not. cut is true when it or its
1494
+ # parent has more relations than were read. subs are its sub-issues, in the
1495
+ # order they were made, which is the order `linear slices` makes a card's
1496
+ # slices in, each as {id, status, type, spec, plan}, and subsCut is true when
1497
+ # it has more than were read. A card, a blocker or a sub-issue whose ID is
1498
+ # not a card ID is left out: an ID is handed to `task start`.
1499
+ CHAIN_DEFS=$PLAIN_DEF'
1500
+ def has_section($name; $open): '$SECTION_FORMS'
1501
+ (split("\n") | map(rtrimstr("\r"))) as $lines
1502
+ | ($lines | in_code) as $code
1503
+ | any(range(0; $lines | length); ($code[.] | not) and ($lines[.] | is_heading));
1504
+ def is_id: type == "string" and test("^[A-Za-z][A-Za-z0-9]*-[0-9]+$");
1505
+ def status: {status: ((.state.name? | strings | plain) // ""), type: ((.state.type? | strings) // "")};
1506
+ def sections: ((.description? | strings) // "") as $text
1507
+ | {spec: ($text | has_section("Specification"; "false")), plan: ($text | has_section("Plan"; "false"))};
1508
+ def blockers: .identifier as $of
1509
+ | [.inverseRelations.nodes[]? | select(.type? == "blocks") | .issue | select(.identifier? | is_id)
1510
+ | {id: .identifier} + status + {of: $of}];
1511
+ def cut: .inverseRelations.pageInfo.hasNextPage? == true;
1512
+ def above: if (.parent | type) == "object" and (.parent.identifier? | is_id) then .parent else null end;
1513
+ def waiting: above as $above
1514
+ | {id: .identifier} + status + sections
1515
+ + {parent: (if $above == null then null else $above.identifier end),
1516
+ blockers: (blockers + (if $above == null then [] else ($above | blockers) end)),
1517
+ cut: (cut or ($above != null and ($above | cut))),
1518
+ subs: ([.children.nodes[]? | select(.identifier? | is_id)] | sort_by(.createdAt? // "")
1519
+ | map({id: .identifier} + status + sections)),
1520
+ subsCut: (.children.pageInfo.hasNextPage? == true)};
1521
+ def once: reduce .[] as $c ([]; if any(.[]; .id == $c.id) then . else . + [$c] end);'
1522
+
1523
+ # Turn Linear's answer to BLOCKS_QUERY into {card, cards, cut}, or "none"
1524
+ # when Linear has no such card. cards are the cards the card blocks, each as
1525
+ # waiting has it, in Linear's order, each once. When the card it was sliced
1526
+ # from is in a completed status, as once the merge of its last open slice has
1527
+ # closed it, the cards that card blocks come after them: the merge has freed
1528
+ # them too. While it is open, it still blocks them, so they are left out. A
1529
+ # card that is only related is never one of them. cut is true when Linear has
1530
+ # more of the relations than were read, so that a card it blocks may be
1531
+ # missing. An answer with no list of cards in it is not Linear saying it has
1532
+ # none, so it is an error (CARD_SHAPE).
1533
+ BLOCKS_SHAPE=$CHAIN_DEFS'
1534
+ def blocked: [.relations.nodes[]? | select(.type? == "blocks") | .relatedIssue
1535
+ | select((type == "object") and (.identifier? | is_id)) | waiting];
1536
+ def more: .relations.pageInfo.hasNextPage? == true;
1537
+ if (.issues.nodes | type) != "array" then error("no list of cards")
1538
+ elif (.issues.nodes | length) == 0 then "none"
1539
+ else .issues.nodes[0]
1540
+ | (if (.parent | type) == "object" and (.parent.state.type? == "completed") then .parent else null end) as $closed
1541
+ | {card: .identifier,
1542
+ cards: ((blocked + (if $closed == null then [] else ($closed | blocked) end)) | once),
1543
+ cut: (more or ($closed != null and ($closed | more)))}
1544
+ end'
1545
+
1546
+ # Turn the pages Linear answered WAITING_QUERY with, one line of JSON each,
1547
+ # into {cards}: every card that waits, as waiting has it, in the order they
1548
+ # were made, each once. A page with no list of cards in it is an error.
1549
+ WAITING_SHAPE=$CHAIN_DEFS'
1550
+ if any(.[]; (.issues.nodes | type) != "array") then error("no list of cards")
1551
+ else {cards: ([.[].issues.nodes[] | select((type == "object") and (.identifier? | is_id)) | waiting] | once)}
1552
+ end'
1553
+
1554
+ # Print the cards a card blocks, as one line of JSON (BLOCKS_SHAPE), or stop
1555
+ # and say why:
1556
+ # {"card":"ABC-122","cut":false,"cards":[{"id":"ABC-123","status":"Todo","type":"unstarted",
1557
+ # "spec":true,"plan":true,"parent":"ABC-100",
1558
+ # "blockers":[{"id":"ABC-122","status":"Done","type":"completed","of":"ABC-123"}],"cut":false,
1559
+ # "subs":[],"subsCut":false}]}
1560
+ # It asks Linear once.
1561
+ # linear_blocks <card ID, in upper case>
1562
+ linear_blocks() {
1563
+ local card=$1 key vars data found
1564
+ linear_tools
1565
+ key=$(linear_saved_key) || exit 1
1566
+ vars=$(jq -cn --arg team "${card%-*}" --arg number "${card##*-}" \
1567
+ '{team: $team, number: ($number | tonumber)}' 2>/dev/null) ||
1568
+ die "'$card' is not a card ID like ABC-122."
1569
+ data=$(linear_ask "$key" "$BLOCKS_QUERY" "$vars") || exit 1
1570
+ # Judged by what jq prints: some versions exit zero on an empty answer.
1571
+ found=$(printf '%s' "$data" | jq -c "$BLOCKS_SHAPE" 2>/dev/null) || found=
1572
+ case $found in
1573
+ '{'*) printf '%s\n' "$found" ;;
1574
+ '"none"') die "Linear has no card $card that the saved key can see." ;;
1575
+ *) die "Linear's answer was not one ocnus can read. Something between this machine and Linear may be answering for it." ;;
1576
+ esac
1577
+ }
1578
+
1579
+ # Print every card of some Linear teams that waits to start, as one line of
1580
+ # JSON (WAITING_SHAPE), or stop and say why:
1581
+ # {"cards":[{"id":"ABC-123","status":"Todo","type":"unstarted","spec":true,"plan":true,...}]}
1582
+ # It asks Linear once for every WAITING_PAGE cards that wait, so once while
1583
+ # there are no more than that.
1584
+ # linear_waiting <team key>...
1585
+ linear_waiting() {
1586
+ local key teams vars data pages='' after='' more asked=0 found
1587
+ linear_tools
1588
+ key=$(linear_saved_key) || exit 1
1589
+ teams=$(printf '%s\n' "$@" | jq -Rcn '[inputs]')
1590
+ while :; do
1591
+ asked=$((asked + 1))
1592
+ [ "$asked" -le "$LINEAR_PAGES" ] ||
1593
+ die "Linear still had more cards that wait to start after $LINEAR_PAGES pages of $WAITING_PAGE, which is more than ocnus reads."
1594
+ vars=$(jq -cn --argjson teams "$teams" --argjson types "$WAITING_TYPES" --argjson first "$WAITING_PAGE" \
1595
+ --arg after "$after" \
1596
+ '{teams: $teams, types: $types, first: $first, after: (if $after == "" then null else $after end)}')
1597
+ data=$(linear_ask "$key" "$WAITING_QUERY" "$vars") || exit 1
1598
+ pages+=$data$'\n'
1599
+ more=$(printf '%s' "$data" | jq -r '.issues.pageInfo.hasNextPage == true' 2>/dev/null) ||
1600
+ die "Linear's answer was not one ocnus can read."
1601
+ [ "$more" = true ] || break
1602
+ # Judging what came so far would pass a part of the cards for all of them.
1603
+ after=$(printf '%s' "$data" | jq -r '.issues.pageInfo.endCursor | strings' 2>/dev/null) || after=
1604
+ [ -n "$after" ] ||
1605
+ die "Linear said it had more cards that wait to start but not where the next ones start, so some would be missed."
1606
+ done
1607
+ found=$(printf '%s' "$pages" | jq -cs "$WAITING_SHAPE" 2>/dev/null) || found=
1608
+ case $found in
1609
+ '{'*) printf '%s\n' "$found" ;;
1610
+ *) die "Linear's answer was not one ocnus can read. Something between this machine and Linear may be answering for it." ;;
1611
+ esac
1612
+ }
1613
+
1417
1614
  # --- moving a card ----------------------------------------------------------
1418
1615
  #
1419
1616
  # ocnus moves a card at four points: the hand-off that records the
package/cli/lib/links.sh CHANGED
@@ -17,7 +17,10 @@ is_linkable() {
17
17
  }
18
18
 
19
19
  # The mods and layouts, each (source, destination) pair one per line,
20
- # tab-separated. They go in Herdr's folder.
20
+ # tab-separated. They go in Herdr's folder. A layout's picture goes with it:
21
+ # the .svg beside it that its "preview" names, which Herdr's Settings shows
22
+ # for the layout and looks for in its own layouts folder. Nothing else in
23
+ # herdr/layouts is linked.
21
24
  herdr_wanted() {
22
25
  local m l
23
26
  for m in "$REPO"/herdr/mods/*/; do
@@ -25,7 +28,7 @@ herdr_wanted() {
25
28
  is_linkable "$m" || continue
26
29
  printf '%s\t%s\n' "$m" "$APP_HOME/mods/${m##*/}"
27
30
  done
28
- for l in "$REPO"/herdr/layouts/*.json; do
31
+ for l in "$REPO"/herdr/layouts/*.json "$REPO"/herdr/layouts/*.svg; do
29
32
  [ -f "$l" ] || continue
30
33
  printf '%s\t%s\n' "$l" "$APP_HOME/layouts/${l##*/}"
31
34
  done
@@ -60,7 +63,7 @@ state_of() {
60
63
  }
61
64
 
62
65
  # A short name for a destination: mods/cpu, layouts/default.json,
63
- # skills/sdlc-plan, agents/ocnus-build.md.
66
+ # layouts/vibe.svg, skills/sdlc-plan, agents/ocnus-build.md.
64
67
  label() {
65
68
  local dst=$1
66
69
  case $dst in
package/cli/lib/merges.sh CHANGED
@@ -49,6 +49,14 @@
49
49
  # card no longer waits, so the human finishes that task. No agent records the
50
50
  # merge or runs `task finish` (sdlc-pr).
51
51
  #
52
+ # Then it runs the chain (merge_chain, in chain.sh): it starts each card the
53
+ # merged card was blocking that is ready, and adds each card started, and
54
+ # each one left with why, to the merged row's flags. A pass also runs the
55
+ # chain's catch-up, `task ready` for every space that has a Linear team, once
56
+ # the last one is READY_EVERY seconds old, half an hour, whether or not a
57
+ # card waits on its merge (ready_due, ready_pass): it starts the ready cards
58
+ # that no merge started.
59
+ #
52
60
  # A merge is recorded once. The watch's two rows go in one transaction, and
53
61
  # only while the card's latest row is still pr needs-human, so an answer the
54
62
  # agent recorded first keeps the card from being recorded until it asks
@@ -58,7 +66,8 @@
58
66
  #
59
67
  # After a pass it sleeps MERGES_PAUSE, a minute, then runs itself again with
60
68
  # 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.
69
+ # `ocnus update`. It exits once no card waits, having run a catch-up that
70
+ # was due. --once makes one pass.
62
71
  #
63
72
  # `task handoff` wakes it once it has recorded a pr needs-human, and `task
64
73
  # new`, `task start` and `task build` wake it next to the host recorder, as
@@ -66,8 +75,10 @@
66
75
  # The launchd agent that install and update write wakes it every minute too,
67
76
  # with `task merges --wake`, so it is back within a minute of herdr-core
68
77
  # 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.
78
+ # comes back the same way. With no card waiting, a wake starts it only for a
79
+ # catch-up that is due, and it ends once it has run it. A wake never starts
80
+ # herdr-core, and hc lets one live terminal hold a name, so there is never
81
+ # more than one watch.
71
82
  #
72
83
  # What it saw is left for `task log`, which says when nothing can see a
73
84
  # card's pull requests, and counts the card as ready to merge once every one
@@ -75,13 +86,18 @@
75
86
  # and for `ocnus status`, which says whether the watch runs (merges_status).
76
87
  # As a pass begins it writes the time to merges/.alive, and after each card's
77
88
  # turn it writes merges/<space>/<card>: on one line, the time, then what it
78
- # saw (merges_saw). A pass whose call to GitHub failed as a whole writes
89
+ # saw (merges_saw). A card's turn also keeps the pull requests it saw in
90
+ # merges/<space>/<card>.pulls, a line each, its state then its URL, for `task
91
+ # asks`, which lists the open ones with the card's question (asks.sh). A pass
92
+ # that could ask GitHub about none of them leaves the file as the last pass
93
+ # that could wrote it. A pass whose call to GitHub failed as a whole writes
79
94
  # merges/.gh: the time, sign-in when gh needs signing in or else failed, then
80
95
  # gh's words. A pass whose call worked, or that asked GitHub nothing, removes
81
96
  # it. All of them go once no card waits, as the watch ends then. They are
82
97
  # files, not rows in the store, and `task log` and `status` read them afresh
83
- # each time. .alive and .gh start with a dot, so that neither is ever a
84
- # space's folder.
98
+ # each time. merges/.ready holds when the last catch-up began, and stays
99
+ # whatever waits. .alive, .gh and .ready start with a dot, so that none is
100
+ # ever a space's folder.
85
101
 
86
102
  MERGES_TERMINAL=ocnus-merges
87
103
  MERGES_USAGE='usage: ocnus task merges [--once | --wake]'
@@ -130,8 +146,9 @@ task_worktrees() {
130
146
  }
131
147
  }
132
148
 
133
- # Start ocnus's watch on the merges while a card waits on its merge,
134
- # unless it runs already. Nothing waits on it: it starts in the background,
149
+ # Start ocnus's watch on the merges while a card waits on its merge, or
150
+ # once its catch-up is due (ready_due), unless it runs already. Nothing waits
151
+ # on it: it starts in the background,
135
152
  # and a wake that fails, as a second one does since the name is taken, is
136
153
  # ignored. It never starts herdr-core: with herdr-core not running, nothing is
137
154
  # woken. The watch gets the PATH of what woke it, which found gh, since
@@ -139,7 +156,7 @@ task_worktrees() {
139
156
  # OCNUS_HOME, so that it reads the same store.
140
157
  merges_wake() {
141
158
  have_hc && have_sqlite || return 0
142
- [ -n "$(merges_waiting 2>/dev/null)" ] || return 0
159
+ [ -n "$(merges_waiting 2>/dev/null)" ] || ready_due || return 0
143
160
  hc_cmd server status --json >/dev/null 2>&1 || return 0
144
161
  local env=(PATH="$PATH")
145
162
  [ -z "${OCNUS_HOME:-}" ] || env+=(OCNUS_HOME="$OCNUS_HOME")
@@ -156,8 +173,9 @@ merges_wake() {
156
173
  # it into the user's own domain, gui/<uid>. launchd runs it once it is
157
174
  # loaded, as at login, and every MERGES_PAUSE, a minute, after that. It runs
158
175
  # `ocnus task merges --wake` (merges_wake), which starts the watch only
159
- # while a card waits on its merge and herdr-core runs, so the watch is back
160
- # within a minute of herdr-core starting. It never starts herdr-core.
176
+ # while a card waits on its merge, or once its catch-up is due, and
177
+ # herdr-core runs, so the watch is back within a minute of herdr-core
178
+ # starting. It never starts herdr-core.
161
179
  MERGES_LABEL=com.johngaynor.ocnus.merges
162
180
  MERGES_PLIST=$HOME/Library/LaunchAgents/$MERGES_LABEL.plist
163
181
  # What launchd runs, with /bin/sh: the ocnus that wrote it is $0, the
@@ -338,7 +356,7 @@ merge_finish() {
338
356
  # when it recorded nothing.
339
357
  # merge_record <space> <card ID, in upper case> <each pull request's URL, a space between>
340
358
  merge_record() {
341
- local space=$1 card=$2 urls=$3 at s c summary id notes line kept=''
359
+ local space=$1 card=$2 urls=$3 at s c summary id notes line kept='' chain
342
360
  at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
343
361
  s=$(sql_str "$space") c=$(sql_str "$card")
344
362
  summary="Merged on GitHub: ${urls// /, }. Recorded by ocnus's watch."
@@ -367,6 +385,13 @@ merge_record() {
367
385
  say "$card's task is left as it is, and task log says why"
368
386
  kept=${kept:+$kept; }$(plain_note "task not finished: $FINISH_LEFT")
369
387
  }
388
+ # The task is finished first, so that each card the merge frees starts
389
+ # from what is merged, with the merged card's own worktree out of the way.
390
+ chain=$(merge_chain "$space" "$card") || true
391
+ [ -z "$chain" ] || printf '%s\n' "$chain"
392
+ while IFS= read -r line; do
393
+ [ -z "$line" ] || kept=${kept:+$kept; }$(plain_note "$line")
394
+ done <<< "$chain"
370
395
  [ "${#kept}" -le "$HANDOFF_LINE_MAX" ] || kept="${kept:0:$((HANDOFF_LINE_MAX - 3))}..."
371
396
  [ -z "$kept" ] ||
372
397
  store "$STORE" "update handoffs set flags = coalesce(flags || '; ', '') || $(sql_str "$kept") where id = $id;" ||
@@ -407,9 +432,11 @@ woke_keep() {
407
432
  if [ -n "$kept" ]; then printf '%s' "$kept" > "$woke"; else woke_forget "$woke"; fi
408
433
  }
409
434
 
410
- # Remove the .woke file, and the file of what the watch saw, of each card
411
- # that no longer waits on its merge. With none waiting, the watch ends, so
412
- # .alive and .gh go too, then each folder left with nothing in it.
435
+ # Remove the .woke file, the .pulls file, and the file of what the watch
436
+ # saw, of each card that no longer waits on its merge. With none waiting,
437
+ # the watch ends, so .alive and .gh go too, then each folder left with
438
+ # nothing in it. .ready stays, since it says when the last catch-up ran,
439
+ # whatever waits.
413
440
  # merges_tidy <the cards that wait, as merges_waiting prints them>
414
441
  merges_tidy() {
415
442
  local waiting=$1 f space card sep=$'\x1f'
@@ -418,6 +445,7 @@ merges_tidy() {
418
445
  card=${f##*/}
419
446
  case $card in
420
447
  *.woke) card=${card%.woke} ;;
448
+ *.pulls) card=${card%.pulls} ;;
421
449
  *.*) continue ;;
422
450
  esac
423
451
  space=${f%/*} space=${space##*/}
@@ -427,6 +455,61 @@ merges_tidy() {
427
455
  rmdir "$ENT_HOME"/merges/*/ "$ENT_HOME/merges" 2>/dev/null || true
428
456
  }
429
457
 
458
+ # --- the catch-up -----------------------------------------------------------
459
+
460
+ # How old the watch's last catch-up is, in seconds, when it runs the next.
461
+ READY_EVERY=1800
462
+
463
+ # Whether the watch's catch-up is due: its last one began READY_EVERY seconds
464
+ # ago or more, or none has, as merges/.ready says, and there is something for
465
+ # it to do. There is nothing to do with the chain off, with no Linear key
466
+ # saved, or with no space that has a Linear team. Nor without gh or jq: the
467
+ # watch stops before its catch-up without either, so a wake would start it
468
+ # every minute for nothing. A note that cannot be read, or that is from the
469
+ # future, as after the clock was set back, is no note.
470
+ ready_due() {
471
+ local at='' now d
472
+ { read -r at < "$ENT_HOME/merges/.ready"; } 2>/dev/null || at=''
473
+ case $at in
474
+ '' | *[!0-9]* | 0?* | ????????????*) ;;
475
+ *)
476
+ now=$(date +%s)
477
+ [ "$at" -gt "$now" ] || [ $((now - at)) -ge "$READY_EVERY" ] || return 1
478
+ ;;
479
+ esac
480
+ [ -n "${LINEAR_API_KEY:-}" ] || return 1
481
+ command -v gh >/dev/null 2>&1 && command -v jq >/dev/null 2>&1 || return 1
482
+ settings_load 2>/dev/null && [ "$SET_CHAIN" = true ] || return 1
483
+ for d in "$SPACES"/*/; do
484
+ [ -d "$d" ] || continue
485
+ [ -z "$(space_teams "${d%/}" 2>/dev/null)" ] || return 0
486
+ done
487
+ return 1
488
+ }
489
+
490
+ # The watch's catch-up: for every space that has a Linear team, start each
491
+ # card that waits and is ready, as `task ready <space>` does (ready_cards in
492
+ # chain.sh), but for a card whose team more than one space lists. It notes
493
+ # when it began in merges/.ready first, so that a catch-up Linear cannot
494
+ # answer is tried again in READY_EVERY seconds and not at every pass. What
495
+ # each space's cards came to is said, a line each, and nothing is recorded:
496
+ # a card that starts records its own start.
497
+ ready_pass() {
498
+ local d name dir
499
+ merges_write .ready "$(date +%s)"
500
+ for d in "$SPACES"/*/; do
501
+ [ -d "$d" ] || continue
502
+ d=${d%/}
503
+ name=${d##*/}
504
+ [ -n "$(space_teams "$d" 2>/dev/null)" ] || continue
505
+ dir=$(space_dir "$name" 2>/dev/null) || continue
506
+ say "Looking for the cards of '$name' that are ready to start"
507
+ # In a shell of its own: it stops, as die does, when Linear cannot be asked.
508
+ (ready_cards "$name" "$dir" watch) || true
509
+ done
510
+ return 0
511
+ }
512
+
430
513
  # What a check of a card's pull requests saw, as MERGES_SAW, for the card's
431
514
  # file: closed and the URL of each closed without merging, as a closed one
432
515
  # comes first; else conflict and each in conflict; else failed and why
@@ -759,6 +842,8 @@ merges_check() {
759
842
  [ -s "$pulls" ] || return 0
760
843
  merges_pulls "$pulls" > "$scratch/check"
761
844
  merges_saw "$scratch/check"
845
+ # The pull requests seen, for `task asks`.
846
+ [ ! -s "$scratch/check" ] || merges_write "$space/$card.pulls" "$(cat "$scratch/check")"
762
847
  woke_keep "$woke" "$scratch/check"
763
848
  if [ "$CHECK_CLOSED" -gt 0 ] || [ "$CHECK_CONFLICT" -gt 0 ]; then
764
849
  merge_wake_agent "$space" "$card" "$scratch/check" "$woke"
@@ -784,6 +869,7 @@ merges_check() {
784
869
  # its terminal. A pass asks GitHub about the pull requests of every card that
785
870
  # waits on its merge, in one call (github_pulls), then checks each card in
786
871
  # turn; then it sleeps a minute and runs itself again, until no card waits.
872
+ # Before that, a pass runs the chain's catch-up when one is due (ready_pass).
787
873
  # With --wake it only wakes the watch, as the launchd agent has it do every
788
874
  # minute (merges_wake), and says nothing.
789
875
  task_merges() {
@@ -804,6 +890,8 @@ task_merges() {
804
890
  local waiting
805
891
  waiting=$(merges_waiting) || die "could not read the hand-offs in $STORE. It may not be ocnus's store."
806
892
  merges_tidy "$waiting"
893
+ # The catch-up, when one is due, whether or not a card waits on its merge.
894
+ ! ready_due || ready_pass
807
895
  [ -n "$waiting" ] || return 0
808
896
  merges_write .alive "$(date +%s)"
809
897
 
@@ -0,0 +1,132 @@
1
+ # The Claude Code sessions of the agents ocnus starts. Sourced by cli/ocnus.
2
+
3
+ # `task new` and `task build` choose the session ID of the claude they start
4
+ # and give it to claude with --session-id=, so ocnus knows which conversation
5
+ # is a card's agent's without asking Claude Code. `task build --continue`
6
+ # continues the card's newest build session by that ID, and `task brief`
7
+ # (brief.sh) makes a copy of the card's newest session to brief the human
8
+ # from. Each start is a row of the sessions table, in the hand-off store
9
+ # (handoff.sh): when, the space, the card, the phase (write-up or build), the
10
+ # harness, and the session ID, which is null for a harness other than claude,
11
+ # whose sessions ocnus cannot name. A session ocnus did not start has no row.
12
+
13
+ # Where Claude Code keeps its transcripts: a folder for each folder a session
14
+ # was started in, holding <session ID>.jsonl for each session there.
15
+ TRANSCRIPTS=${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects
16
+ # What card_sessions puts between a row's values: the unit separator, which no
17
+ # value can hold, and which lets `read` keep an empty value, as a tab does not.
18
+ SESSION_SEP=$'\x1f'
19
+
20
+ # Print a new session ID: a version 4 UUID in lower case, which is what
21
+ # `claude --session-id` takes. It is read from /dev/urandom, as new_herdr_id
22
+ # reads its ids. The 13th digit is the version, 4, and the 17th the variant,
23
+ # one of 8, 9, a and b.
24
+ session_id() {
25
+ local hex
26
+ hex=$(LC_ALL=C od -A n -t x1 -N 16 /dev/urandom | LC_ALL=C tr -d ' \n')
27
+ [ "${#hex}" = 32 ] || die "could not read /dev/urandom to make a session ID for Claude Code"
28
+ printf '%s-%s-4%s-%x%s-%s\n' "${hex:0:8}" "${hex:8:4}" "${hex:13:3}" \
29
+ "$(( (0x${hex:16:1} & 3) | 8 ))" "${hex:17:3}" "${hex:20:12}"
30
+ }
31
+
32
+ # Choose the session of a claude that is about to start: its ID in SESSION,
33
+ # and the flag that gives it to claude in SESSION_ARGS, which goes after the
34
+ # profile's flags, last before the first message. --session-id= is Claude
35
+ # Code's, so another harness (HARNESS, in task.sh) is given none, and both
36
+ # are left empty. Call it in the shell that starts the agent, not in a
37
+ # subshell: it sets them, and stops when no ID could be made.
38
+ SESSION='' SESSION_ARGS=()
39
+ session_new() {
40
+ SESSION='' SESSION_ARGS=()
41
+ [ "${HARNESS##*/}" = claude ] || return 0
42
+ SESSION=$(session_id) || exit 1
43
+ SESSION_ARGS=("--session-id=$SESSION")
44
+ }
45
+
46
+ # Make the sessions table on its first use, in a store that has the
47
+ # hand-offs' table too (store_ready), which `task log` reads in any store.
48
+ sessions_ready() {
49
+ store_ready &&
50
+ store "$STORE" 'create table if not exists sessions (
51
+ id integer primary key, at text not null, space text not null,
52
+ card text not null, phase text not null, harness text not null,
53
+ session text);'
54
+ }
55
+
56
+ # Note the session of an agent that is about to start, or has just started,
57
+ # timed now in UTC as a hand-off is. An empty session ID is recorded as null.
58
+ # Like record_start, it never fails the command that starts the agent: it
59
+ # only says when it could not record.
60
+ # session_record <space> <card> <phase> <harness> <session ID, or empty>
61
+ session_record() {
62
+ local at values='' v
63
+ if ! have_sqlite; then
64
+ say " note $SQLITE is not installed, so the agent's session is not recorded"
65
+ return 0
66
+ fi
67
+ at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
68
+ for v in "$at" "$@"; do values="$values${values:+, }$(sql_str "$v")"; done
69
+ { sessions_ready &&
70
+ store "$STORE" "insert into sessions (at, space, card, phase, harness, session) values ($values);"; } ||
71
+ say " note could not record the agent's session in $STORE"
72
+ }
73
+
74
+ # Whether the store has the sessions table. A store made before sessions were
75
+ # recorded has none until an agent is started, and reading never makes it. It
76
+ # fails with 2 when the store cannot be read at all.
77
+ store_has_sessions() {
78
+ local n
79
+ [ -e "$STORE" ] || return 1
80
+ n=$(store "$STORE" "select count(*) from sqlite_master where type = 'table' and name = 'sessions';") || return 2
81
+ [ "$n" = 1 ]
82
+ }
83
+
84
+ # Print a card's sessions, oldest first, a line each: when it was started,
85
+ # its phase, its harness and its session ID, which is empty for a harness
86
+ # other than claude, with SESSION_SEP between them. It prints nothing for a
87
+ # card with none, with no store, and for a store with no sessions table, and
88
+ # it makes neither. It fails only when the store cannot be read.
89
+ # card_sessions <space> <card>
90
+ card_sessions() {
91
+ local rc=0
92
+ have_sqlite || return 0
93
+ store_has_sessions || rc=$?
94
+ case $rc in
95
+ 0) ;;
96
+ 1) return 0 ;;
97
+ *) return 1 ;;
98
+ esac
99
+ store -separator "$SESSION_SEP" "$STORE" "select at, phase, harness, coalesce(session, '') from sessions
100
+ where space = $(sql_str "$1") and card = $(sql_str "$2") order by id;"
101
+ }
102
+
103
+ # Print the newest of a card's sessions, as card_sessions prints it, or the
104
+ # newest of one phase when $3 names it: the build agent started last, or the
105
+ # write-up agent. Nothing for a card with none, and it fails as card_sessions
106
+ # does.
107
+ # newest_session <space> <card> [<phase>]
108
+ newest_session() {
109
+ local rows at phase harness session found=''
110
+ rows=$(card_sessions "$1" "$2") || return 1
111
+ while IFS=$SESSION_SEP read -r at phase harness session; do
112
+ [ -n "$at" ] || continue
113
+ [ -z "${3:-}" ] || [ "$phase" = "$3" ] || continue
114
+ found=$at$SESSION_SEP$phase$SESSION_SEP$harness$SESSION_SEP$session
115
+ done <<< "$rows"
116
+ [ -z "$found" ] || printf '%s\n' "$found"
117
+ }
118
+
119
+ # Print the path of a session's transcript, <session ID>.jsonl in one of the
120
+ # folders under TRANSCRIPTS, or fail when Claude Code keeps none. Those
121
+ # folders' names start with a -, so each is looked in by its whole path.
122
+ # session_transcript <session ID>
123
+ session_transcript() {
124
+ local f
125
+ [ -n "${1:-}" ] || return 1
126
+ for f in "$TRANSCRIPTS"/*/"$1.jsonl"; do
127
+ [ -f "$f" ] || continue
128
+ printf '%s\n' "$f"
129
+ return 0
130
+ done
131
+ return 1
132
+ }