@krysoworks/kryso 0.0.0-stage → 2.0.0-rc.1

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 (162) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -2
  3. package/bin/kryso +31 -0
  4. package/bin/ship-it-status +14 -0
  5. package/bin/ship-ledger +14 -0
  6. package/bin/ship-loop +14 -0
  7. package/bin/ship-pass +14 -0
  8. package/bin/warden +14 -0
  9. package/dist/answer.d.ts +38 -0
  10. package/dist/answer.js +48 -0
  11. package/dist/bytes.d.ts +5 -0
  12. package/dist/bytes.js +35 -0
  13. package/dist/cleanup.d.ts +1 -0
  14. package/dist/cleanup.js +629 -0
  15. package/dist/commands.d.ts +48 -0
  16. package/dist/commands.js +293 -0
  17. package/dist/completions.d.ts +24 -0
  18. package/dist/completions.js +239 -0
  19. package/dist/daemon.d.ts +15 -0
  20. package/dist/daemon.js +23 -0
  21. package/dist/diagnose.d.ts +47 -0
  22. package/dist/diagnose.js +314 -0
  23. package/dist/doctor.d.ts +1 -0
  24. package/dist/doctor.js +241 -0
  25. package/dist/env.d.ts +9 -0
  26. package/dist/env.js +17 -0
  27. package/dist/evidence.d.ts +39 -0
  28. package/dist/evidence.js +327 -0
  29. package/dist/home.d.ts +3 -0
  30. package/dist/home.js +27 -0
  31. package/dist/install.d.ts +59 -0
  32. package/dist/install.js +137 -0
  33. package/dist/isolate.d.ts +28 -0
  34. package/dist/isolate.js +402 -0
  35. package/dist/leftovers.d.ts +5 -0
  36. package/dist/leftovers.js +156 -0
  37. package/dist/machine.d.ts +6 -0
  38. package/dist/machine.js +185 -0
  39. package/dist/palette.d.ts +147 -0
  40. package/dist/palette.js +167 -0
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +133 -0
  43. package/dist/proc.d.ts +23 -0
  44. package/dist/proc.js +23 -0
  45. package/dist/read.d.ts +1 -0
  46. package/dist/read.js +297 -0
  47. package/dist/readiness.d.ts +5 -0
  48. package/dist/readiness.js +64 -0
  49. package/dist/remote.d.ts +6 -0
  50. package/dist/remote.js +85 -0
  51. package/dist/self-update.d.ts +1 -0
  52. package/dist/self-update.js +224 -0
  53. package/dist/semver.d.ts +7 -0
  54. package/dist/semver.js +42 -0
  55. package/dist/style.d.ts +71 -0
  56. package/dist/style.js +187 -0
  57. package/dist/update.d.ts +47 -0
  58. package/dist/update.js +190 -0
  59. package/dist/work.d.ts +25 -0
  60. package/dist/work.js +449 -0
  61. package/dist/workflows.d.ts +4 -0
  62. package/dist/workflows.js +73 -0
  63. package/docker/entrypoint.sh +44 -0
  64. package/docker/runner.Dockerfile +39 -0
  65. package/package.json +65 -4
  66. package/scripts/install-skills.sh +607 -0
  67. package/skills/code-review/SKILL.md +231 -0
  68. package/skills/kryso/SKILL.md +107 -0
  69. package/skills/kryso/golden/help.rounded.ansi +23 -0
  70. package/skills/kryso/golden/help.square.ansi +23 -0
  71. package/skills/kryso/golden/help.txt +23 -0
  72. package/skills/kryso/golden/table-narrow.json +11 -0
  73. package/skills/kryso/golden/table-narrow.rounded.ansi +4 -0
  74. package/skills/kryso/golden/table-narrow.square.ansi +4 -0
  75. package/skills/kryso/golden/table.ansi +5 -0
  76. package/skills/kryso/golden/table.json +11 -0
  77. package/skills/kryso/ledger.sh +2146 -0
  78. package/skills/kryso/palette.json +57 -0
  79. package/skills/kryso/reference/resuming.md +30 -0
  80. package/skills/kryso/reference/routing.md +23 -0
  81. package/skills/kryso/reference/stage-1-claim.md +79 -0
  82. package/skills/kryso/reference/stage-2-build.md +133 -0
  83. package/skills/kryso/reference/stage-3-prove.md +51 -0
  84. package/skills/kryso/reference/stage-4-pr.md +76 -0
  85. package/skills/kryso/reference/stage-5-reconcile.md +81 -0
  86. package/skills/kryso/reference/stage-6-merge-or-park.md +73 -0
  87. package/skills/kryso/reference/stage-7-close-out.md +62 -0
  88. package/skills/kryso/reference/terminal.md +7 -0
  89. package/skills/kryso/ship-it-status.sh +1503 -0
  90. package/skills/kryso/ui.py +274 -0
  91. package/skills/kryso/ui.sh +609 -0
  92. package/skills/kryso-build/SKILL.md +168 -0
  93. package/skills/kryso-shift/SKILL.md +167 -0
  94. package/skills/kryso-shift/archive.py +2784 -0
  95. package/skills/kryso-shift/archive_checker.py +462 -0
  96. package/skills/kryso-shift/archive_checker_lambda.py +155 -0
  97. package/skills/kryso-shift/archive_health.py +364 -0
  98. package/skills/kryso-shift/archive_launchd.py +140 -0
  99. package/skills/kryso-shift/archive_remote.py +990 -0
  100. package/skills/kryso-shift/archiving-checker.md +140 -0
  101. package/skills/kryso-shift/archiving-keep.md +115 -0
  102. package/skills/kryso-shift/archiving-recovery.md +112 -0
  103. package/skills/kryso-shift/archiving-remote.md +166 -0
  104. package/skills/kryso-shift/archiving.md +146 -0
  105. package/skills/kryso-shift/coverage.schema.json +225 -0
  106. package/skills/kryso-shift/deadline.sh +254 -0
  107. package/skills/kryso-shift/feedback.schema.json +35 -0
  108. package/skills/kryso-shift/feedback.sh +228 -0
  109. package/skills/kryso-shift/history-manifest.schema.json +331 -0
  110. package/skills/kryso-shift/keep-after.sh +55 -0
  111. package/skills/kryso-shift/measure.sh +611 -0
  112. package/skills/kryso-shift/merge-ready.sh +207 -0
  113. package/skills/kryso-shift/outcome.schema.json +16 -0
  114. package/skills/kryso-shift/pass-rules.md +8 -0
  115. package/skills/kryso-shift/profile.schema.json +42 -0
  116. package/skills/kryso-shift/reader.sh +692 -0
  117. package/skills/kryso-shift/reads.sh +151 -0
  118. package/skills/kryso-shift/reference/allowance.md +21 -0
  119. package/skills/kryso-shift/reference/driver.md +95 -0
  120. package/skills/kryso-shift/reference/measuring.md +67 -0
  121. package/skills/kryso-shift/reference/outputs.md +21 -0
  122. package/skills/kryso-shift/reference/pass-script.md +115 -0
  123. package/skills/kryso-shift/reference/reconcile-and-merge.md +55 -0
  124. package/skills/kryso-shift/reference/second-reader.md +9 -0
  125. package/skills/kryso-shift/reference/sweeps.md +83 -0
  126. package/skills/kryso-shift/repair.schema.json +14 -0
  127. package/skills/kryso-shift/report-template.html +679 -0
  128. package/skills/kryso-shift/report.py +389 -0
  129. package/skills/kryso-shift/report_fixture.py +65 -0
  130. package/skills/kryso-shift/reporting.md +58 -0
  131. package/skills/kryso-shift/result.sh +91 -0
  132. package/skills/kryso-shift/runner.sh +1178 -0
  133. package/skills/kryso-shift/ship-loop.sh +3977 -0
  134. package/skills/kryso-shift/ship-pass.sh +4987 -0
  135. package/skills/kryso-shift/steps.jq +19 -0
  136. package/skills/kryso-shift/workflow.mjs +830 -0
  137. package/skills/kryso-shift/workflows/default.json +22 -0
  138. package/skills/kryso-shift/workflows/ralph.json +13 -0
  139. package/skills/kryso-watch/SKILL.md +100 -0
  140. package/skills/kryso-watch/answer.schema.json +23 -0
  141. package/skills/kryso-watch/base-refs.sh +44 -0
  142. package/skills/kryso-watch/board.sh +58 -0
  143. package/skills/kryso-watch/reference/config.md +23 -0
  144. package/skills/kryso-watch/reference/outputs.md +30 -0
  145. package/skills/kryso-watch/reference/report.md +29 -0
  146. package/skills/kryso-watch/reference/scheduler.md +32 -0
  147. package/skills/kryso-watch/reference/settlement.md +29 -0
  148. package/skills/kryso-watch/reference/shift.md +44 -0
  149. package/skills/kryso-watch/reference/shim-limits.md +22 -0
  150. package/skills/kryso-watch/reference/triage.md +26 -0
  151. package/skills/kryso-watch/schema.jq +40 -0
  152. package/skills/kryso-watch/settle.schema.json +36 -0
  153. package/skills/kryso-watch/stage-common.sh +187 -0
  154. package/skills/kryso-watch/stages/report.sh +525 -0
  155. package/skills/kryso-watch/stages/settle.sh +722 -0
  156. package/skills/kryso-watch/stages/shift.sh +466 -0
  157. package/skills/kryso-watch/stages/triage.sh +379 -0
  158. package/skills/kryso-watch/tracker.sh +27 -0
  159. package/skills/kryso-watch/triage.schema.json +77 -0
  160. package/skills/kryso-watch/warden.launchd.plist +50 -0
  161. package/skills/kryso-watch/warden.schema.json +98 -0
  162. package/skills/kryso-watch/warden.sh +1004 -0
@@ -0,0 +1,1503 @@
1
+ #!/usr/bin/env bash
2
+ # kryso status shows the passes in progress, and the session that owns each.
3
+ #
4
+ # Usage: kryso status [repo-path]
5
+ # kryso status --all
6
+ # kryso status --repos
7
+ # kryso status --inspect [issue...] [repo-path]
8
+ # kryso status --inspect --all [issue...]
9
+ # kryso status --inspect <issue> --follow [repo-path]
10
+ # kryso attach [shift-id | issue] [--log <path>] [repo-path]
11
+ #
12
+ # It shows the passes in one repo, the repo of the current directory by default,
13
+ # or with --all in each repo a session has used. --repos prints those repos, one path a line,
14
+ # which is how kryso doctor --all finds them by the same rule. --inspect shows the work in each
15
+ # named pass, or in every pass of the repo when you name none: a card with where
16
+ # the pass stands, then a table row per ledger event with its time, the gap since
17
+ # the event before, its stage, its outcome and its evidence. A named issue that no
18
+ # ledger carries exits 1.
19
+ #
20
+ # Above a repo's passes it shows each running shift: its id, start, engine, profile, model and
21
+ # base, the pass it is on, and what the passes that ended spent, then a line per ticket of its
22
+ # queue, shipped, parked, live or queued. A shift runs while a live process holds its
23
+ # driver.lock, between two passes too. The newest shift, when it stopped without a summary.json,
24
+ # shows once as stopped with its last pass, and a running watch shows with its stage. A LIVE
25
+ # pass a shift is working names the shift. On a terminal a shift is a block: its state and
26
+ # settings, its pass with a bar and its spend, its queue on one line, then a table of its own
27
+ # tickets. The passes no shift owns follow in a table under "no shift".
28
+ #
29
+ # --follow takes one issue and then prints each new ledger event as a row of the same table
30
+ # when the ledger gets it, every KRYSO_STATUS_INTERVAL seconds (default 2). On a terminal, the
31
+ # card's state, stage, PR and head lines are redrawn in place as they change, and a line under
32
+ # the table keeps them too. A terminal cannot reach a card line that has scrolled above its
33
+ # window, so that line stays as first drawn and the line under the table carries the change. Off
34
+ # a terminal the output is append-only, and the state changes only when LIVE ends. It stops
35
+ # with status 0 on a final state line once the pass is no longer LIVE: shipped, parked,
36
+ # exhausted, interrupted, review-ready or stale. It follows the ledger's copy once the
37
+ # closeout removes the worktree. Ctrl-C stops it and leaves the pass alone, and it only reads.
38
+ # It reads this machine's ledgers, so with kryso remote set it is refused as --inspect is.
39
+ #
40
+ # Attach:
41
+ # kryso attach the one shift that runs here, or a list of what runs
42
+ # kryso attach <shift-id> that shift, from pass to pass until it ends
43
+ # kryso attach <issue> that pass, until it is no longer LIVE
44
+ # --log <path> the log to write, in place of the one beside the run
45
+ #
46
+ # It shows a shift or a pass that runs detached the way its owner would see it
47
+ # in the foreground. First comes the output so far: the shift's shift.log and
48
+ # the ledger rows of its live pass. Then each new driver line, each ledger
49
+ # event as the ledger gets it, and each line the host's streams gain: its
50
+ # stderr in the shift's pass-<n>.err and the pass's logs/*.err, and its stdout
51
+ # in the files beside them that end .raw. It writes the same lines to a log,
52
+ # attach-<time>-<pid>.txt in the shift's folder or in the pass's logs/,
53
+ # and its first line names that log. A shift id or an issue with nothing
54
+ # running exits 1 at once, and so does no argument when no shift or several
55
+ # run, after a list of the shifts and passes running.
56
+ #
57
+ # Ctrl-C on a terminal asks "detach, or stop the run". Detach exits 0 and
58
+ # leaves the run alone. Stop sends the run's driver a TERM, which it takes as
59
+ # a ctrl+c in its own foreground: the pass in progress is stopped and its
60
+ # ledger records the interruption, so kryso pass <issue> --resume continues
61
+ # it, and a shift writes its summary. A pass that a shift runs has the shift's
62
+ # driver, so stop ends that shift too. Attach then follows the run until it
63
+ # ends. A second Ctrl-C at the prompt detaches, and without a terminal an
64
+ # interrupt detaches with no prompt.
65
+ #
66
+ # It reads the run's files and holds no lock, so it works for a run that tmux,
67
+ # another session, the warden or a resume started, and any number of terminals
68
+ # can attach to one run. Until stop is chosen it writes only its own log. It
69
+ # reads this machine's runs only: with kryso remote set it still reads the
70
+ # files here, never the daemon.
71
+ #
72
+ # Context:
73
+ # A pass writes its state to .kryso/pass/ in its worktree (.kryso/ before #618
74
+ # and .ship-it/ before the rename, which kryso still reads where they are). The build fork
75
+ # writes there too, and the parent transcript does not change while the fork
76
+ # works. An interrupt in the parent session does not stop the fork, so a pass
77
+ # can look stopped in one transcript and go on in another. Run this before you
78
+ # resume a worktree or start a second fork on it.
79
+ #
80
+ # Signals:
81
+ # It reads three signals, the most trusted first.
82
+ # 1. The ledger, the checkpoint and the receipts in each worktree, read through
83
+ # ledger.sh beside this script. A pass is LIVE while a process holds its
84
+ # issue's pass authority or one of its receipts is open. A pass is
85
+ # "interrupted" when its allowance ran out and nothing has parked it since. A
86
+ # park that is the latest event, or that a refused resume restated, makes it
87
+ # "review-ready" at the merge gate, "exhausted" when its pass spent its own
88
+ # rerun, and "parked" otherwise. Any other pass is LIVE when one of these
89
+ # files changed in the last 15 minutes, and "stale" when none did. When only
90
+ # receipts follow a park and one is open, the last line names the park and
91
+ # the log. The branch is the ledger's. A ⚠ marks a worktree on another branch
92
+ # or on a detached HEAD, with what is checked out.
93
+ # 2. The transcripts in ~/.claude/projects/<repo>/ and ~/.codex/sessions/. The
94
+ # build fork starts in the worktree, and each transcript records its start
95
+ # directory on its first lines. The owner is the session that has that
96
+ # transcript, or that fork. Before the fork starts, the owner is the newest
97
+ # transcript that names the worktree path, and the output marks it with a
98
+ # "?".
99
+ # 3. The open PR on the ledger's branch.
100
+ #
101
+ # --all finds repos through both hosts' session stores. A transcript records the
102
+ # directory it started in, and the git common directory of that directory is the
103
+ # repo. The script does not decode the project directory names, because a "-" in a
104
+ # path and a "-" that stands for "/" look the same. It leaves out repos in a
105
+ # Claude scratchpad (/private/tmp/claude-*).
106
+ #
107
+ # ------------------------------------------------------------------------------
108
+
109
+ set -u
110
+
111
+ # The evidence module beside this script, which every read of a worktree's ledger goes through.
112
+ # The script may be run through a symlink (the runbook links it onto PATH), so every link is
113
+ # followed to find the file's real directory.
114
+ self="$0"
115
+ while [ -L "$self" ]; do
116
+ target="$(readlink "$self")"
117
+ case "$target" in /*) self="$target" ;; *) self="$(dirname "$self")/$target" ;; esac
118
+ done
119
+ # shellcheck source=ledger.sh
120
+ . "$(cd "$(dirname "$self")" && pwd)/ledger.sh" || { echo "cannot source ledger.sh beside $self" >&2; exit 1; }
121
+
122
+ # The styled-output module, searched for where ship-loop.sh searches for ledger.sh. This script
123
+ # already sits in ship-it, so its own directory is the first place. Its stream is stdout.
124
+ here="$(cd "$(dirname "$self")" && pwd)"
125
+ repo_root="$(git rev-parse --show-toplevel 2>/dev/null)"
126
+ ui_sh=""
127
+ for candidate in "$here/ui.sh" "$repo_root/.agents/skills/kryso/ui.sh" "$HOME/.agents/skills/kryso/ui.sh" "$repo_root/.claude/skills/kryso/ui.sh" "$HOME/.claude/skills/kryso/ui.sh"; do
128
+ [ -f "$candidate" ] && { ui_sh="$candidate"; break; }
129
+ done
130
+ [ -n "$ui_sh" ] || { echo "cannot find kryso's ui.sh beside $here, under .agents/skills, or under the .claude/skills compatibility path" >&2; exit 1; }
131
+ # shellcheck source=/dev/null
132
+ . "$ui_sh" || { echo "cannot source $ui_sh" >&2; exit 1; }
133
+ ui_stream 1
134
+
135
+ now=$(date +%s)
136
+ live_secs=$((15 * 60))
137
+ projects="${CLAUDE_PROJECTS:-$HOME/.claude/projects}" # the tests point this at a fixture
138
+ codex_sessions="${CODEX_SESSIONS:-$HOME/.codex/sessions}"
139
+ tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT
140
+ # BSD stat on macOS, GNU stat on Linux.
141
+ if stat -f %m / >/dev/null 2>&1; then STAT="stat -f %m"; else STAT="stat -c %Y"; fi
142
+
143
+ # ── Width ─────────────────────────────────────────────────────────────────────
144
+ # The width is COLUMNS, then tput cols. The plain layout fits its rows to it. Styling is ui.sh's,
145
+ # and only an attended run gets it: there a terminal wraps a long last event itself.
146
+ cols="${COLUMNS:-}"
147
+ [ -n "$cols" ] || cols="$(tput cols 2>/dev/null)" || cols=""
148
+ [ -n "$cols" ] || cols=100
149
+
150
+ age() { # seconds since an epoch, as "3m" / "2h" / "1d"
151
+ local s=$(( now - ${1:-$now} ))
152
+ if [ "$s" -lt 3600 ]; then echo "$((s / 60))m"
153
+ elif [ "$s" -lt 86400 ]; then echo "$((s / 3600))h"
154
+ else echo "$((s / 86400))d"; fi
155
+ }
156
+ mtime() { $STAT "$1" 2>/dev/null || echo "$now"; }
157
+ newest_mtime() { # newest mtime under the given paths, epoch
158
+ find "$@" -type f -print0 2>/dev/null | xargs -0 $STAT 2>/dev/null | sort -n | tail -1
159
+ }
160
+ codex_session_id() { # the UUID in a Codex rollout's session_meta record
161
+ awk 'FNR<=20 && /"type":"session_meta"/ && match($0,/"id":"[^"]*"/) {
162
+ print substr($0,RSTART+6,RLENGTH-7); exit
163
+ }
164
+ FNR>20 {exit}' "$1"
165
+ }
166
+ pad() { # <plain-length> <width>: the spaces that take a string of that length to the width
167
+ local n=$(( $2 - $1 )); [ "$n" -gt 0 ] && printf '%*s' "$n" ''; return 0
168
+ }
169
+ header() { # <repo> <run count>: the repo's name, its run count and its path, home as ~
170
+ printf '%s (%s) %s' "$(basename "$1")" "$2" "${1/#$HOME/\~}"
171
+ }
172
+ glyph() { # <state>
173
+ case "$1" in LIVE) echo "●" ;; parked|review-ready|exhausted) echo "‖" ;; interrupted) echo "◌" ;; *) echo "○" ;; esac
174
+ }
175
+ # The tones the attended tables draw a value in, from ui.sh's palette.
176
+ state_tone() { # <state>: green for LIVE or shipped, yellow for a park, red for a stop, dim otherwise
177
+ case "$1" in
178
+ LIVE|shipped) echo ok ;;
179
+ parked|review-ready) echo warn ;;
180
+ interrupted|exhausted) echo fail ;;
181
+ *) echo dim ;;
182
+ esac
183
+ }
184
+ outcome_tone() { # <outcome> <evidence>: red for a failure, green for work landed, plain otherwise
185
+ case "$1" in failed|check-failed|blocked|interrupted) echo fail; return ;; parked) echo warn; return ;; esac
186
+ # A receipt's exit, as `exit=<n> (logs/...)` or the older bare `<n> (logs/...)` the module reads.
187
+ case "$2" in
188
+ exit=0\ *|exit=0|0\ \(logs/*) echo ok; return ;;
189
+ exit=*|[0-9]*\ \(logs/*) echo fail; return ;;
190
+ esac
191
+ case "$1" in claimed|committed|checked|passed|opened|merged|shipped|done) echo ok ;; *) echo "" ;; esac
192
+ }
193
+ # cell <tone> <text>: one cell for ui_table, its tone ahead of the unit separator when it has one.
194
+ cell() { if [ -n "$1" ]; then printf '%s\x1f%s' "$1" "$2"; else printf '%s' "$2"; fi; }
195
+ # BRANDED: the brand line is drawn once, ahead of the first repo.
196
+ BRANDED=0
197
+ brand_once() { # <summary>
198
+ [ "$BRANDED" -eq 0 ] || return 0
199
+ BRANDED=1
200
+ ui_brand status "$1"
201
+ }
202
+
203
+ # ── Shifts ────────────────────────────────────────────────────────────────────
204
+ # A shift keeps its state in .claude/kryso/<shift id>/ in the main checkout (.claude/ship-loop/
205
+ # before the rename), where ship-loop.sh writes shift.json, a sweep-<n>.json per sweep and a
206
+ # pass-<n>.json per pass: empty while the pass runs, and carrying the driver's ship_loop block
207
+ # once it ended. A watch keeps its own in .claude/kryso-watch/ (.claude/warden/ before the rename).
208
+
209
+ # shift_running <dir>: status 0 while the shift's driver, or a process it started, still runs.
210
+ # A live driver at shift.json's pid answers without touching its lock, its summary written or not,
211
+ # because it still runs until its close. Otherwise the shift runs while a live process holds
212
+ # driver.lock, which the module's `locked` probes and lets go at once, as `read` probes a pass's
213
+ # authority. A dead driver's summary is written at its close, after its last pass returned, so a
214
+ # shift with one is not probed.
215
+ # The probe is a momentary try-lock because the module has no other: flock and lockf answer only
216
+ # by taking the lock, macOS has no /proc/locks, and its lsof leaves the lock column blank. A
217
+ # driver takes driver.lock with a try that does not wait, so a probe at that moment would cost it
218
+ # the lock. Status never probes at that moment: a driver writes its live pid to shift.json before
219
+ # it opens driver.lock, and while that pid runs ship-loop.sh the file is never opened here.
220
+ shift_running() {
221
+ local dir="$1" pid got=0
222
+ pid="$(jq -r '.pid // empty' "$dir/shift.json" 2>/dev/null)"
223
+ if [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
224
+ case "$(ps -o args= -p "$pid" 2>/dev/null)" in *ship-loop*) return 0 ;; esac
225
+ fi
226
+ [ ! -f "$dir/summary.json" ] && [ -e "$dir/driver.lock" ] || return 1
227
+ ledger locked "$dir/driver.lock" || got=$?
228
+ [ "$got" -eq 0 ]
229
+ }
230
+
231
+ # stamp_jq: a jq def, stamp, that draws an ISO time as its date and minute in UTC, as a shift's and
232
+ # a watch's start read.
233
+ stamp_jq() {
234
+ echo 'def stamp: if length >= 16 then .[0:10] + " " + .[11:16] + "Z" else "unknown" end;'
235
+ }
236
+
237
+ # The shift's lines from its files, the record "S" first and then a "T" record per ticket, the
238
+ # fields split on the unit separator. The queue is every issue its sweeps planned, in order, then
239
+ # any other a pass ended on, which is how a label shift's queue reads: it plans no issue ahead. A
240
+ # ticket's state is live for the pass in progress, queued where the latest sweep planned it and
241
+ # has not run it yet, and otherwise the outcome of the last pass that ended on it. The pass in
242
+ # progress is the highest pass-<n>.json with no ship_loop block yet, and its count gives "pass N
243
+ # of M". Its issue is the first the latest sweep planned and no pass of that sweep ended on whose
244
+ # authority the shift holds now, in $held, because a slot the driver skipped runs no pass and the
245
+ # count would name it. Where the holds cannot be seen, $seen false, it is the first of those issues:
246
+ # a stopped shift holds nothing, and an isolated one holds its locks in the container. The spend
247
+ # sums cost_usd over the passes that ended.
248
+ shift_jq() {
249
+ stamp_jq
250
+ cat <<'JQ'
251
+ def iss: if . == null then "?" else tostring end;
252
+ ($shift[0] // {}) as $s
253
+ | ($passes | sort_by(.pass)) as $p
254
+ | ($sweeps | sort_by(.sweep)) as $sw
255
+ | ($sw | last // {sweep: null, base: null, run: []}) as $latest
256
+ | ($latest.run | map(iss)) as $plan
257
+ | ($p | map(select(.sweep == $latest.sweep) | .issue)) as $ended
258
+ | [$plan[] | select(. as $i | any($ended[]; . == $i) | not)] as $left
259
+ | ([($p | map(select(.sweep != $latest.sweep)) | length) + ($plan | length), $top] | max) as $total
260
+ | (if $top > 0 and ($p | last | .pass) != $top then $top else null end) as $inflight
261
+ | (if $inflight == null then null
262
+ else first($left[] | select(. as $i | any($held[]; . == $i))) // (if $seen then "?" else $left[0] // "?" end) end) as $cur
263
+ | (reduce (($sw[].run[] | iss), ($p[].issue | select(. != "?"))) as $i ([]; if any(.[]; . == $i) then . else . + [$i] end)) as $queue
264
+ | ($p | map(.cost | numbers)) as $costs
265
+ | ["S", $id, (if $running then "running" else "stopped" end),
266
+ ($s.started_at // "" | stamp),
267
+ ($s.engine // "unknown"), ($s.profile // "unknown"), ($s.model_run // $s.model // "default"),
268
+ ($latest.base // "default"),
269
+ (if $inflight != null then
270
+ (if $running then "pass \($inflight) of \($total), #\($cur)" else "last pass \($inflight) of \($total), #\($cur) unfinished" end)
271
+ elif $p != [] then ($p | last) as $l | (if $running then "after" else "last" end) + " pass \($l.pass) of \($total), #\($l.issue) \($l.outcome)"
272
+ else "no pass yet" end),
273
+ (if $p == [] then "0" elif $costs == [] then "" else ($costs | add | tostring) end),
274
+ (if $running then ($cur // "") else "" end)],
275
+ ($queue[] as $i | ($p | map(select(.issue == $i))) as $mine
276
+ | ["T", $i,
277
+ (if $running and $i == $cur then "live"
278
+ elif any($plan[]; . == $i) and ($mine | map(select(.sweep == $latest.sweep))) == [] then "queued"
279
+ elif $mine != [] then ($mine | last | .outcome)
280
+ else "queued" end)])
281
+ | join("\u001f")
282
+ JQ
283
+ }
284
+
285
+ # shift_records <dir> <running 0|1> <repo> <seen 0|1>: the shift's records by shift_jq. Each engine opens a pass's
286
+ # pass-<n>.err when the pass starts, and the script engine its pass-<n>.json too, so the highest of
287
+ # either is the latest pass. A pass-<n>.json with no ship_loop block has not ended. An outcome the
288
+ # result does not carry at its top level or in its structured output is the driver's, from its
289
+ # shift.log line for the pass. With seen 1, the latest sweep's issues whose authority the module's
290
+ # `active` finds held, by a process under the driver while shift.json's pid lives, are $held. A
291
+ # pass's hold waits for such a probe, so it costs no pass its start.
292
+ shift_records() {
293
+ local dir="$1" f n top=0 said i holder driver
294
+ : > "$tmp/passes"; : > "$tmp/sweeps"; : > "$tmp/held"
295
+ for f in "$dir"/pass-*.err; do
296
+ n="${f##*/pass-}"; n="${n%.err}"
297
+ [[ "$n" =~ ^[0-9]+$ ]] && [ "$n" -gt "$top" ] && top="$n"
298
+ done
299
+ for f in "$dir"/pass-*.json; do
300
+ n="${f##*/pass-}"; n="${n%.json}"
301
+ [[ "$n" =~ ^[0-9]+$ ]] || continue
302
+ [ "$n" -le "$top" ] || top="$n"
303
+ said="$(sed -nE "s/^[^ ]+ pass=$n outcome=([^ ]+) .*/\1/p" "$dir/shift.log" 2>/dev/null | tail -1)"
304
+ jq -c --argjson n "$n" --arg said "$said" 'select(type == "object" and .ship_loop != null)
305
+ | {pass: $n, sweep: .ship_loop.sweep, issue: (.ship_loop.issue // .issue | if . == null then "?" else tostring end),
306
+ outcome: (.outcome // .structured_output.outcome // (if $said == "" then null else $said end) // "ended"), cost: .cost_usd}' \
307
+ "$f" 2>/dev/null >> "$tmp/passes"
308
+ done
309
+ for f in "$dir"/sweep-*.json; do
310
+ [ -f "$f" ] && jq -c '{sweep, base, run: [.run[]? | .issue]}' "$f" 2>/dev/null >> "$tmp/sweeps"
311
+ done
312
+ if [ "$4" -eq 1 ]; then
313
+ driver="$(jq -r '.pid // empty' "$dir/shift.json" 2>/dev/null)"
314
+ [[ "$driver" =~ ^[0-9]+$ ]] && kill -0 "$driver" 2>/dev/null || driver=""
315
+ for i in $(jq -rs 'max_by(.sweep) | .run[]? | tostring | select(test("^[0-9]+$"))' "$tmp/sweeps"); do
316
+ holder="$(ledger active "$3" "$i" 2>/dev/null)" || continue
317
+ [ -z "$driver" ] || descends "${holder%% *}" "$driver" || continue
318
+ printf '"%s"\n' "$i" >> "$tmp/held"
319
+ done
320
+ fi
321
+ jq -c . "$dir/shift.json" > "$tmp/shift" 2>/dev/null || : > "$tmp/shift"
322
+ jq -nr --slurpfile shift "$tmp/shift" --slurpfile passes "$tmp/passes" --slurpfile sweeps "$tmp/sweeps" --slurpfile held "$tmp/held" \
323
+ --argjson top "$top" --argjson running "$([ "$2" -eq 1 ] && echo true || echo false)" \
324
+ --argjson seen "$([ "$4" -eq 1 ] && echo true || echo false)" --arg id "${dir##*/}" "$(shift_jq)"
325
+ }
326
+
327
+ # collect_shifts <repo>: the repo's shift and watch records in $tmp/shifts, by shift_records, and a
328
+ # "W" record for a running watch: every running shift, then the newest shift when it is not
329
+ # running and wrote no summary, which is a driver that died, then the watch. "<issue><TAB><shift>"
330
+ # for each running shift's pass in progress goes to $tmp/shift-live. It writes nothing under
331
+ # .claude/. While `kryso --isolate docker` runs on the repo, the driver's pid and lock are in the
332
+ # container, out of sight (ADR 0039), so the newest shift without a summary counts as running.
333
+ collect_shifts() {
334
+ local repo="$1" root wroot dir newest="" running=0 id pid stage s
335
+ : > "$tmp/shifts"; : > "$tmp/shift-live"
336
+ _ledger_pick "$repo/.claude/kryso" "$repo/.claude/ship-loop" root
337
+ for dir in "$root"/*/; do
338
+ dir="${dir%/}"; id="${dir##*/}"
339
+ [[ "$id" =~ ^[0-9]{8}T[0-9]{6}Z$ ]] || continue
340
+ newest="$dir"; running=0
341
+ shift_running "$dir" || continue
342
+ running=1
343
+ shift_records "$dir" 1 "$repo" 1 >> "$tmp/shifts"
344
+ done
345
+ if [ -n "$newest" ] && [ "$running" -eq 0 ] && [ ! -f "$newest/summary.json" ]; then
346
+ # Read-only, the module names a stale isolation file rather than remove it.
347
+ if KRYSO_READ_ONLY=1 ledger isolated "$repo" > /dev/null 2>&1; then running=1; fi
348
+ shift_records "$newest" "$running" "$repo" 0 >> "$tmp/shifts"
349
+ fi
350
+ awk -F$'\x1f' '$1 == "S" && $3 == "running" && $11 != "" {print $11 "\t" $2}' "$tmp/shifts" > "$tmp/shift-live"
351
+ # The watch runs while the pid its lock names is alive, the watch's own rule. Its stage is the
352
+ # last whose log it opened, preflight before the first.
353
+ _ledger_pick "$repo/.claude/kryso-watch" "$repo/.claude/warden" wroot
354
+ pid="$(cut -d' ' -f1 "$wroot/lock" 2>/dev/null)"
355
+ [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null || return 0
356
+ dir=""
357
+ for s in "$wroot"/*/; do
358
+ [[ "$(basename "$s")" =~ ^[0-9]{8}T[0-9]{6}Z(-[0-9]+)?$ ]] && dir="${s%/}"
359
+ done
360
+ [ -n "$dir" ] || return 0
361
+ stage=preflight
362
+ for s in triage report shift settle; do [ -e "$dir/stage-$s.log" ] && stage="$s"; done
363
+ jq -nr --arg id "${dir##*/}" --arg stage "$stage" --slurpfile m <(jq -c . "$dir/manifest.json" 2>/dev/null) "$(stamp_jq)"'
364
+ ($m[0] // {}) as $m
365
+ | ["W", $id, "running", ($m.started_at // "" | stamp),
366
+ ($m.base.branch // "" | if . == "" then "unknown" else . end), $stage] | join("\u001f")' >> "$tmp/shifts"
367
+ }
368
+
369
+ # shift_lines: the records in $tmp/shifts as the plain output's lines, one a shift or a watch and
370
+ # one a ticket under a running shift. The attended view draws the same records by shift_block.
371
+ shift_lines() {
372
+ local indent="" kind id state started engine profile model base where spent _cur tone shown="" wbase wstage
373
+ while IFS=$'\x1f' read -r kind id state started engine profile model base where spent _cur; do
374
+ case "$kind" in
375
+ S)
376
+ shown="$state"
377
+ if [ -z "$spent" ]; then spent=unknown; else spent="$(LC_ALL=C printf '$%.2f' "$spent")"; fi
378
+ if [ "$state" = running ]; then tone=ok; id="$(glyph LIVE) shift $id $state"; else tone=fail; id="$(glyph interrupted) shift $id $state"; fi
379
+ printf '%s%s ◦ started %s ◦ engine %s ◦ profile %s ◦ model %s ◦ base %s ◦ %s ◦ spent %s\n' "$indent" \
380
+ "$(ui_tint "$tone" "$id")" "$started" "$engine" "$profile" "$model" "$base" "$where" "$spent" ;;
381
+ T)
382
+ # A ticket is its issue and its state, listed under a running shift only.
383
+ [ "$shown" = running ] || continue
384
+ case "$state" in live) tone=ok ;; queued) tone=dim ;; *) tone="$(ui_outcome "$state")" ;; esac
385
+ [ "$tone" != info ] || tone=""
386
+ printf '%s #%s %s\n' "$indent" "$id" "$(if [ -n "$tone" ]; then ui_tint "$tone" "$state"; else printf '%s' "$state"; fi)" ;;
387
+ W)
388
+ # A watch's record is its id, its state, its start, its base and its stage.
389
+ shown=""; wbase="$engine"; wstage="$profile"
390
+ printf '%s%s ◦ started %s ◦ base %s ◦ stage %s\n' "$indent" "$(ui_tint ok "$(glyph LIVE) watch $id $state")" "$started" "$wbase" "$wstage" ;;
391
+ esac
392
+ done < "$tmp/shifts"
393
+ }
394
+
395
+ # mark <state>: the mark the attended view draws ahead of a pass's or a ticket's state. A shipped
396
+ # pass takes a tick and a failed one a cross, a ticket that is live the LIVE dot and one still
397
+ # queued a ring. Any other outcome word takes the mark of its tone, and a ledger state its glyph.
398
+ mark() {
399
+ case "$1" in
400
+ shipped) echo "✔" ;; failed) echo "✖" ;; live) glyph LIVE ;; queued) echo "○" ;;
401
+ LIVE|parked|review-ready|exhausted|interrupted) glyph "$1" ;;
402
+ *) case "$(ui_outcome "$1")" in ok) echo "✔" ;; warn) echo "‖" ;; fail) echo "✖" ;; *) echo "○" ;; esac ;;
403
+ esac
404
+ }
405
+ # ticket_tone <state>: the tone of a ticket's state in a shift's queue, live as ok, queued dim, an
406
+ # outcome as ui_outcome draws it, and none for a word the palette does not name.
407
+ ticket_tone() {
408
+ local tone
409
+ case "$1" in live) tone=ok ;; queued) tone=dim ;; *) tone="$(ui_outcome "$1")" ;; esac
410
+ [ "$tone" != info ] || tone=""
411
+ printf '%s' "$tone"
412
+ }
413
+ # pass_row <shift id> <row>: one of $tmp/rows as a row of the attended passes table. The owner
414
+ # names the shift a LIVE pass works for when the table is not that shift's own.
415
+ pass_row() {
416
+ local sid="$1" state issue branch pr owner lage last _wt
417
+ IFS=$'\x1f' read -r state issue branch pr owner lage last _wt <<< "$2"
418
+ ui_table_row "$(cell "$(state_tone "$state")" "$(mark "$state") $state")" \
419
+ "$(cell value "#$issue")" "$(cell "$(case "$branch" in *⚠*) echo fail ;; *) echo value ;; esac)" "$branch")" \
420
+ "$(if [ -n "$pr" ]; then cell value "#$pr"; else cell dim "no PR"; fi)" "$(cell dim "${owner:-unknown}${sid:+ ◦ shift $sid}")" \
421
+ "$(cell dim "$lage ago")" "$last"
422
+ }
423
+
424
+ # shift_block <cols>: the records in $tmp/shifts as the attended view draws them, a block a shift
425
+ # under the repo's pill, a blank line ahead of each. Its heading is the shift and its state in
426
+ # their tone, then its model, engine, profile and base, dim. The start is left out, as the shift's
427
+ # id is that time. The pass line is the pass it is on, a bar a cell a pass, the passes that ended
428
+ # filled and the one in progress green, what a stopped shift's last pass came to, and the spend.
429
+ # The queue line is every ticket behind its mark, and it breaks between tickets at the terminal's
430
+ # width. Then the shift's own table: a row a ticket in the queue's order, the pass's row from
431
+ # $tmp/rows where the ticket has a worktree and its state alone where it has none. A LIVE row is
432
+ # a shift's only when $tmp/shift-live names it, so a pass started by hand on a planned issue stays
433
+ # out. A watch is one line. ROWS holds $tmp/rows and TAKEN the rows a shift's table drew, for the
434
+ # caller to draw the rest, and DREW is 1 once a shift or a watch is drawn.
435
+ shift_block() {
436
+ local cols="$1" rec tone spent state="" sid="" where n m k tail bar text line width piece plain i last tid tstate r table found
437
+ local -a f row
438
+ ROWS=(); TAKEN=(); DREW=0
439
+ while IFS= read -r rec; do ROWS+=("$rec"); done < "$tmp/rows"
440
+ while IFS= read -r rec; do
441
+ IFS=$'\x1f' read -r -a f <<< "$rec"
442
+ case "${f[0]}" in
443
+ S)
444
+ DREW=1; sid="${f[1]}"; state="${f[2]}"; where="${f[8]}"; spent="${f[9]:-}"
445
+ if [ -z "$spent" ]; then spent="spend unknown"; else spent="$(LC_ALL=C printf '$%.2f spent' "$spent")"; fi
446
+ if [ "$state" = running ]; then tone=ok; piece="$(glyph LIVE)"; else tone=fail; piece="$(glyph interrupted)"; fi
447
+ printf '\n %s %s\n' "$(ui_tint "$tone" "$piece shift $sid $state")" "$(ui_tint dim "${f[6]} ◦ ${f[4]} ◦ ${f[5]} ◦ base ${f[7]}")"
448
+ text="$where"
449
+ if [[ "$where" =~ pass\ ([0-9]+)\ of\ ([0-9]+)(,\ (.*))?$ ]]; then
450
+ n="${BASH_REMATCH[1]}"; m="${BASH_REMATCH[2]}"; tail="${BASH_REMATCH[4]:-}"
451
+ # The pass named is in progress, or was when a stopped shift's driver died, unless
452
+ # "after" or an outcome says it ended.
453
+ k="$n"; case "$where" in pass\ *|*\ unfinished) k=$(( n - 1 )) ;; esac
454
+ bar=""
455
+ for (( i = 1; i <= m; i++ )); do
456
+ if [ "$i" -le "$k" ]; then bar+="$(ui_glyph bar-done)"
457
+ elif [ "$i" -eq "$n" ] && [ "$state" = running ]; then bar+="$(ui_tint ok "$(ui_glyph bar-done)")"
458
+ else bar+="$(ui_tint dim "$(ui_glyph bar-left)")"; fi
459
+ done
460
+ text="$n of $m $bar"
461
+ [ "$state" = running ] || [ -z "$tail" ] || text+=" $tail"
462
+ fi
463
+ printf ' %s %s %s\n' "$(ui_tint dim "pass ")" "$text" "$(ui_tint dim "$spent")" ;;
464
+ Q)
465
+ line=" $(ui_tint dim "queue ")"; width=12; table=""; last=$(( ${#f[@]} - 2 ))
466
+ for (( i = 1; i <= last; i += 2 )); do
467
+ tid="${f[i]}"; tstate="${f[i+1]}"; tone="$(ticket_tone "$tstate")"
468
+ plain="$(mark "$tstate") #$tid"
469
+ if [ -n "$tone" ]; then piece="$(ui_tint "$tone" "$(mark "$tstate")") #$tid"; else piece="$plain"; fi
470
+ if [ "$width" -gt 12 ] && [ $(( width + 2 + ${#plain} )) -gt "$cols" ]; then
471
+ printf '%s\n' "$line"; line=" "; width=12
472
+ fi
473
+ line+=" $piece"; width=$(( width + 2 + ${#plain} ))
474
+ found=""
475
+ for r in "${!ROWS[@]}"; do
476
+ [ -z "${TAKEN[r]:-}" ] || continue
477
+ IFS=$'\x1f' read -r -a row <<< "${ROWS[r]}"
478
+ [ "${row[1]}" = "$tid" ] || continue
479
+ [ "${row[0]}" != LIVE ] || [ "$(row_shift LIVE "$tid")" = "$sid" ] || continue
480
+ TAKEN[r]=1; found=1; table+="$(pass_row "" "${ROWS[r]}")"$'\n'
481
+ break
482
+ done
483
+ [ -n "$found" ] || table+="$(ui_table_row "$(cell "$tone" "$(mark "$tstate") $tstate")" "$(cell dim "#$tid")")"$'\n'
484
+ done
485
+ printf '%s\n\n' "$line"
486
+ { ui_table_row STATE ISSUE BRANCH PR OWNER LEDGER "LAST EVENT"; printf '%s' "$table"; } | ui_table --indent 4 --header --width "$cols" ;;
487
+ W)
488
+ DREW=1
489
+ printf '\n %s stage %s %s\n' "$(ui_tint ok "$(glyph LIVE) watch ${f[1]} ${f[2]}")" "${f[5]}" "$(ui_tint dim "base ${f[4]}")" ;;
490
+ esac
491
+ done < <(awk -F$'\x1f' 'BEGIN { OFS = FS }
492
+ $1 == "T" { q = q FS $2 FS $3; next }
493
+ { if (q != "") { print "Q" q; q = "" } print }
494
+ END { if (q != "") print "Q" q }' "$tmp/shifts")
495
+ }
496
+
497
+ # A row's state and its trailer, one record, from a `ledger read` document. A park holds only
498
+ # while it is the latest event, so a pass that went on after one is classified like any other. A
499
+ # refused resume spends nothing and restates the park, so it leaves the park holding. An open
500
+ # receipt is a live writer whatever the ledger says, and when nothing but receipts follows the
501
+ # park, the trailer names the park and what is still writing. Under a held authority `read` also
502
+ # calls a fresh log with no lock open, as a guess. The row is LIVE there without it, so the guess
503
+ # is never named as a writer, as the `park` verb never refuses for one.
504
+ row_state_jq() {
505
+ cat <<'JQ'
506
+ .events as $ev
507
+ | ($ev | map(.outcome == "parked") | rindex(true)) as $at
508
+ | (if $at == null then null else $ev[$at + 1:] end) as $since
509
+ | ($since != null and all($since[]; .stage == "resume") and ($since == [] or $since[-1].outcome == "refused")) as $parked
510
+ | (.active == true) as $held
511
+ | [.receipts[] | select(.state == "open" and (.lock == "held" or ($held | not))) | .file] as $open
512
+ | [(if $held or $open != [] then "LIVE"
513
+ elif .stage.status == "interrupted" and .interruption != null and .interruption.time >= (.park.time // "") then "interrupted"
514
+ elif $parked then
515
+ # A park at the merge gate is review-ready work, one whose pass spent its own rerun is
516
+ # exhausted, and any other park is parked.
517
+ if .disposition == "retry-exhausted" then "exhausted"
518
+ elif .stage.name == "merge" or .park.word == "pr-open" then "review-ready" else "parked" end
519
+ elif $now - (.mtime // $now) < $live then "LIVE"
520
+ else "stale" end),
521
+ (if $open != [] and $since != null and all($since[]; .stage == "receipt") then
522
+ "parked \(.park.time[11:16]) ◦ still writing \($open | join(", "))"
523
+ elif .last == null then "" else .last | "\(.stage) \(.outcome) \(.evidence)" end)]
524
+ | join("\u001f")
525
+ JQ
526
+ }
527
+
528
+ # collect_rows <repo>: one record per ledgered worktree in $tmp/rows, its fields split on the
529
+ # unit separator: state, issue, branch as shown, PR, owner, ledger age, last event and worktree. Sets
530
+ # wi to the widest issue and wb to the widest branch without its flag, so that in the plain
531
+ # layout a flag makes its own row wider and not the column. Returns 1 when the repo has no ledger at all.
532
+ collect_rows() {
533
+ local repo="$1" proj_dir prs wt
534
+ proj_dir="$projects/$(printf '%s' "$repo" | tr '/' '-')"
535
+
536
+ # The worktrees that carry a ledger, "<path> <issue>" per line from the module, path kept.
537
+ ledger worktrees "$repo" 2>/dev/null | sed 's/ [^ ]*$//' > "$tmp/wts"
538
+ [ -s "$tmp/wts" ] || return 1
539
+
540
+ # Open PRs, one "branch<TAB>number" per line, fetched once and past gh's default of 30.
541
+ prs="$(cd "$repo" && gh pr list --state open --limit 1000 --json number,headRefName \
542
+ --jq '.[] | "\(.headRefName)\t\(.number)"' 2>/dev/null)"
543
+
544
+ # Where each transcript started: "cwd<TAB>file", from its first lines only.
545
+ : > "$tmp/cwds"
546
+ [ -d "$proj_dir" ] && find "$proj_dir" -maxdepth 3 -name '*.jsonl' -print0 2>/dev/null \
547
+ | xargs -0 awk 'FNR<=5 && match($0,/"cwd":"[^"]*"/) {print substr($0,RSTART+7,RLENGTH-8) "\t" FILENAME; nextfile}
548
+ FNR>5 {nextfile}' > "$tmp/cwds"
549
+ : > "$tmp/codex-cwds"
550
+ [ -d "$codex_sessions" ] && find "$codex_sessions" -name '*.jsonl' -print0 2>/dev/null \
551
+ | xargs -0 awk 'FNR<=20 && match($0,/"cwd":"[^"]*"/) {print substr($0,RSTART+7,RLENGTH-8) "\t" FILENAME; nextfile}
552
+ FNR>20 {nextfile}' > "$tmp/codex-cwds"
553
+
554
+ # Pass 1: one row per run, fields split on the unit separator so an empty one
555
+ # (no PR, no owner) keeps its place, which a tab would not.
556
+ : > "$tmp/rows"
557
+ local doc ledger branch on_branch shown issue last state pr owner sid best best_at at
558
+ wb=0; wi=0
559
+ while IFS= read -r wt; do
560
+ doc="$(ledger read "$wt")"
561
+ # .kryso/pass, the .kryso of a pass before #618, or .ship-it in a worktree no writer has
562
+ # touched since the rename, by the module's rule. Never moved here.
563
+ _ledger_d "$wt" ledger; ledger="$ledger/run.md"
564
+ # The pass's branch is the ledger's, and the checked-out one only where an older ledger names
565
+ # none.
566
+ on_branch="$(git -C "$wt" symbolic-ref --short -q HEAD 2>/dev/null)" || on_branch=""
567
+ branch="$(printf '%s' "$doc" | jq -r '.header.branch // ""')"
568
+ branch="${branch:-$on_branch}"
569
+ shown="$branch"
570
+ if [ -z "$on_branch" ]; then
571
+ shown="${branch:+$branch }⚠ on $(printf '%s' "$doc" | jq -r '"detached HEAD" + (if .tree.head == null then "" else " " + .tree.head[0:7] end)')"
572
+ elif [ "$on_branch" != "$branch" ]; then
573
+ shown="$branch ⚠ on $on_branch"
574
+ fi
575
+ issue="$(printf '%s' "$doc" | jq -r '.header.issue // ""')"
576
+ IFS=$'\x1f' read -r state last < <(printf '%s' "$doc" | jq -r --argjson now "$now" --argjson live "$live_secs" "$(row_state_jq)")
577
+
578
+ pr="$(printf '%s\n' "$prs" | awk -F'\t' -v b="$branch" '$1==b {print $2}')"
579
+
580
+ # Owner: the session with a transcript (its own or a fork's) that started
581
+ # in this worktree; with more than one, the most recently active.
582
+ owner=""; best=""; best_at=0
583
+ while IFS= read -r sid; do
584
+ [ -n "$sid" ] || continue
585
+ at=$(newest_mtime "$proj_dir/$sid.jsonl" "$proj_dir/$sid")
586
+ [ "${at:-0}" -gt "$best_at" ] && { best="$sid"; best_at="$at"; }
587
+ done < <(awk -F'\t' -v w="$wt" '$1==w {print $2}' "$tmp/cwds" \
588
+ | sed -E "s|^$proj_dir/||; s|/subagents/.*||; s|\.jsonl$||" | sort -u)
589
+ if [ -n "$best" ]; then
590
+ owner="${best:0:8} $(age "$best_at")"
591
+ elif [ -d "$proj_dir" ]; then
592
+ best="$(ls -t "$proj_dir"/*.jsonl 2>/dev/null | head -5 | xargs grep -l -F "$wt" 2>/dev/null | head -1)"
593
+ [ -n "$best" ] && owner="$(basename "$best" .jsonl | cut -c1-8)? $(age "$(mtime "$best")")"
594
+ fi
595
+ if [ -z "$owner" ]; then
596
+ best=""; best_at=0
597
+ while IFS= read -r sid; do
598
+ [ -n "$sid" ] || continue
599
+ at="$(mtime "$sid")"
600
+ [ "${at:-0}" -gt "$best_at" ] && { best="$sid"; best_at="$at"; }
601
+ done < <(awk -F'\t' -v w="$wt" '$1==w {print $2}' "$tmp/codex-cwds")
602
+ if [ -n "$best" ]; then
603
+ sid="$(codex_session_id "$best")"
604
+ [ -n "$sid" ] || sid="$(basename "$best" .jsonl)"
605
+ owner="codex:${sid:0:8} $(age "$best_at")"
606
+ fi
607
+ fi
608
+
609
+ [ "${#branch}" -gt "$wb" ] && wb=${#branch}
610
+ [ "${#issue}" -gt "$wi" ] && wi=${#issue}
611
+ printf "%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\n" "$state" "$issue" "$shown" "$pr" "$owner" "$(age "$(mtime "$ledger")")" "$last" "$wt" >> "$tmp/rows"
612
+ done < "$tmp/wts"
613
+ }
614
+
615
+ # Print the shifts and the passes under one repo. Returns 1 when it has no ledger, no shift to show
616
+ # and no watch running.
617
+ report_repo() {
618
+ local repo="$1" state issue branch pr owner lage last _wt sid
619
+ collect_shifts "$repo"
620
+ if ! collect_rows "$repo"; then
621
+ [ -s "$tmp/shifts" ] || return 1
622
+ : > "$tmp/rows"; wi=0; wb=0
623
+ fi
624
+
625
+ # Attended, the brand line counts the runs and the running shifts, the repo opens under a pill
626
+ # with its run count and its path, and each shift follows with a table of its own tickets. The
627
+ # runs no shift owns are one table, LIVE rows first, with the ledger's age and last line in
628
+ # columns of their own.
629
+ local title
630
+ title="$(header "$repo" "$(wc -l < "$tmp/rows" | tr -d ' ')")"
631
+ if ui_attended; then
632
+ local n live shifts
633
+ n="$(wc -l < "$tmp/rows" | tr -d ' ')"
634
+ live="$(awk -F$'\x1f' '$1 == "LIVE"' "$tmp/rows" | wc -l | tr -d ' ')"
635
+ shifts="$(awk -F$'\x1f' '$1 == "S" && $3 == "running"' "$tmp/shifts" | wc -l | tr -d ' ')"
636
+ brand_once "$n $( [ "$n" -eq 1 ] && echo pass || echo passes ), $live live$( [ "$shifts" -eq 0 ] || echo ", $shifts $( [ "$shifts" -eq 1 ] && echo shift || echo shifts ) running")"
637
+ ui_section primary "$(basename "$repo")" "($n) ${repo/#$HOME/\~}"
638
+ shift_block "$cols"
639
+ # The passes no shift's table drew, LIVE first. Under a shift they take a heading of their
640
+ # own and the shift tables' indent.
641
+ local r rest="" pad=2 any=0
642
+ for r in "${!ROWS[@]}"; do [ -n "${TAKEN[r]:-}" ] || { [ "${ROWS[r]%%$'\x1f'*}" != LIVE ] || rest+="$(pass_row "$(row_shift LIVE "$(cut -d$'\x1f' -f2 <<< "${ROWS[r]}")")" "${ROWS[r]}")"$'\n'; }; done
643
+ for r in "${!ROWS[@]}"; do [ -n "${TAKEN[r]:-}" ] || { [ "${ROWS[r]%%$'\x1f'*}" = LIVE ] || rest+="$(pass_row "" "${ROWS[r]}")"$'\n'; }; done
644
+ [ -n "$rest" ] || return 0
645
+ any="$(awk -F$'\x1f' '$1 == "S"' "$tmp/shifts" | wc -l | tr -d ' ')"
646
+ if [ "$any" -gt 0 ]; then pad=4; printf '\n %s\n' "$(ui_tint bold "no shift")"
647
+ elif [ "$DREW" -eq 1 ]; then echo; fi
648
+ { ui_table_row STATE ISSUE BRANCH PR OWNER LEDGER "LAST EVENT"; printf '%s' "$rest"; } | ui_table --indent "$pad" --header --width "$cols"
649
+ return 0
650
+ fi
651
+
652
+ # Pass 2: render without styling. The shifts come first, a line each and a line per ticket of a
653
+ # running one's queue. The left block is
654
+ # "<glyph> <state> #<issue> <branch>", padded to the widest branch; the meta
655
+ # block follows on the same line when it fits the terminal, else on its own line. The ledger's last line trails under ↳,
656
+ # whole, and the terminal wraps it.
657
+ printf '\n %s\n' "$title"
658
+ shift_lines
659
+ local left meta pr_txt own_txt lw width
660
+ lw=$(( 2 + 6 + 1 + 1 + wi + 1 + wb ))
661
+ while IFS=$'\x1f' read -r state issue branch pr owner lage last _wt; do
662
+ sid="$(row_shift "$state" "$issue")"
663
+ left="$(glyph "$state") $(printf '%-6s' "$state") #$(printf '%-*s' "$wi" "$issue") $branch"
664
+ if [ -n "$pr" ]; then pr_txt="PR #$pr"; else pr_txt="no PR"; fi
665
+ if [ -n "$owner" ]; then own_txt="owner $owner"; else own_txt="owner ?"; fi
666
+ meta="$pr_txt ◦ $own_txt${sid:+ ◦ shift $sid} ◦ ledger $lage"
667
+ width="$lw"; [ "${#left}" -le "$width" ] || width=${#left}
668
+ if [ $(( width + 2 + ${#meta} )) -le "$cols" ]; then
669
+ printf '%s%s %s\n' "$left" "$(pad "${#left}" "$lw")" "$meta"
670
+ else
671
+ printf '%s\n %s\n' "$left" "$meta"
672
+ fi
673
+ printf ' ↳ %s\n' "$last"
674
+ done < "$tmp/rows"
675
+ }
676
+
677
+ # row_shift <state> <issue>: the running shift whose pass in progress is this LIVE row's issue.
678
+ row_shift() {
679
+ [ "$1" = LIVE ] || return 0
680
+ awk -F'\t' -v i="$2" '$1 == i {print $2; exit}' "$tmp/shift-live"
681
+ }
682
+
683
+ # ── Inspect ───────────────────────────────────────────────────────────────────
684
+ # One record per event of a `ledger read` document, the ownership stamps already left out by the
685
+ # module: the time, with the date on the first event and whenever the day changes; the gap since
686
+ # the event before, or since the header's start for the first; the stage, outcome and evidence.
687
+ inspect_events_jq() {
688
+ cat <<'JQ'
689
+ def two: tostring | if length < 2 then "0" + . else . end;
690
+ def gap($s): if $s == null or $s < 0 then ""
691
+ elif $s < 60 then "+\($s)s"
692
+ elif $s < 3600 then "+\($s / 60 | floor)m"
693
+ elif $s < 86400 then "+\($s / 3600 | floor)h\(($s % 3600) / 60 | floor | two)m"
694
+ else "+\($s / 86400 | floor)d\(($s % 86400) / 3600 | floor | two)h" end;
695
+ def epoch: try fromdateiso8601 catch null;
696
+ reduce .events[] as $e ({prev: (.header.started // "" | epoch), day: "", rows: []};
697
+ ($e.time | epoch) as $t
698
+ | ($e.time[0:10]) as $d
699
+ | .rows += [[(if $d != .day then "\($d) \($e.time[11:19])" else $e.time[11:19] end),
700
+ (if .prev != null and $t != null then gap($t - .prev) else "" end),
701
+ $e.stage, $e.outcome, $e.evidence]]
702
+ | .prev = ($t // .prev) | .day = $d)
703
+ | .rows[] | join("\u001f")
704
+ JQ
705
+ }
706
+ # The card's derived fields, one record: the stage, the gate, the reconciliations and the tree.
707
+ inspect_card_jq() {
708
+ cat <<'JQ'
709
+ ["\(.stage.name) \(.stage.status)" + (if .stage.status == "parked" then " \(.stage.word) (\(.disposition))" else "" end),
710
+ .gate.verdict + (if (.gate.reason // "") != "" then ": \(.gate.reason)" else "" end),
711
+ "\(.reconciliations.used)/\(.reconciliations.cap) used",
712
+ (if .tree.head == null then "none" else .tree.head[0:7] + (if .tree.dirty == true then " dirty" else " clean" end) end)]
713
+ | join("\u001f")
714
+ JQ
715
+ }
716
+
717
+ # inspect_repo <repo> [issue...]: a card and an event table for each named pass in the repo, or
718
+ # for every ledgered pass when none is named, LIVE first. Each issue shown is added to
719
+ # $tmp/found. Returns 1 when no pass is shown.
720
+ inspect_repo() {
721
+ local repo="$1"; shift
722
+ collect_rows "$repo" || return 1
723
+ { awk -F$'\x1f' '$1 == "LIVE"' "$tmp/rows"; awk -F$'\x1f' '$1 != "LIVE"' "$tmp/rows"; } \
724
+ | awk -F$'\x1f' -v want=" $* " 'want == " " || index(want, " " $2 " ")' > "$tmp/picked"
725
+ [ -s "$tmp/picked" ] || return 1
726
+ # --follow follows one pass, so it shows only the first, LIVE first.
727
+ if [ "$following" -eq 1 ]; then head -1 "$tmp/picked" > "$tmp/one"; mv "$tmp/one" "$tmp/picked"; fi
728
+ cut -d$'\x1f' -f2 "$tmp/picked" >> "$tmp/found"
729
+ local title state issue branch pr owner lage last wt doc name stage gate recon head
730
+ title="$(header "$repo" "$(wc -l < "$tmp/picked" | tr -d ' ')")"
731
+ if ui_attended; then
732
+ brand_once "inspect"
733
+ ui_section primary "$(basename "$repo")" "($(wc -l < "$tmp/picked" | tr -d ' ')) ${repo/#$HOME/\~}"
734
+ else
735
+ printf '\n %s\n' "$title"
736
+ fi
737
+ # The loop reads its records on fd 3, so nothing it runs can drain them through stdin.
738
+ while IFS=$'\x1f' read -r -u 3 state issue branch pr owner lage last wt; do
739
+ doc="$(ledger read "$wt")"
740
+ name=""
741
+ [ -z "$issue" ] || name="$(cd "$repo" && gh issue view "$issue" --json title --jq .title < /dev/null 2>/dev/null)"
742
+ printf '%s' "$doc" | jq -r "$(inspect_events_jq)" > "$tmp/events"
743
+ IFS=$'\x1f' read -r stage gate recon head < <(printf '%s' "$doc" | jq -r "$(inspect_card_jq)")
744
+ if ui_attended; then inspect_styled; else inspect_plain; fi
745
+ follow_wt="$wt"; follow_pr="$pr"; follow_card=("$issue" "$branch" "$owner" "$lage")
746
+ done 3< "$tmp/picked"
747
+ }
748
+
749
+ # event_widths: the columns' widths over $tmp/events, at least the headers', so a row --follow
750
+ # adds lines up under the table.
751
+ event_widths() {
752
+ local t g s o e
753
+ w_time=4; w_gap=3; w_stage=5; w_outcome=7
754
+ while IFS=$'\x1f' read -r t g s o e; do
755
+ [ "${#t}" -gt "$w_time" ] && w_time=${#t}
756
+ [ "${#g}" -gt "$w_gap" ] && w_gap=${#g}
757
+ [ "${#s}" -gt "$w_stage" ] && w_stage=${#s}
758
+ [ "${#o}" -gt "$w_outcome" ] && w_outcome=${#o}
759
+ done < "$tmp/events"
760
+ }
761
+ # event_row <time> <gap> <stage> <outcome> <evidence>: one event in the plain columns, the
762
+ # evidence trailing whole.
763
+ event_row() {
764
+ printf ' %19s %-7s %-*s %-*s %s\n' "$1" "$2" "$w_stage" "$3" "$w_outcome" "$4" "$5"
765
+ }
766
+
767
+ # inspect_plain: the card as label and value lines, then a line per event in fixed columns with
768
+ # the evidence trailing whole, as the status lines leave the terminal to wrap it. The card and the
769
+ # table are kept in $tmp/card and $tmp/table as drawn, which is where --follow finds the card.
770
+ inspect_plain() {
771
+ local t g s o e
772
+ printf '\n #%s%s\n' "$issue" "${name:+ $name}"
773
+ card_plain > "$tmp/card"; cat "$tmp/card"
774
+ event_widths
775
+ { echo; while IFS=$'\x1f' read -r t g s o e; do event_row "$t" "$g" "$s" "$o" "$e"; done < "$tmp/events"; } > "$tmp/table"
776
+ cat "$tmp/table"
777
+ }
778
+ # card_plain: the card's label and value lines, from the pass's fields in the caller's scope.
779
+ card_plain() {
780
+ printf ' %-10s %s\n' state "$(glyph "$state") $state" branch "$branch" pr "${pr:+#}${pr:-none}" \
781
+ owner "${owner:-unknown}" stage "$stage" gate "$gate" reconcile "$recon" head "$head" ledger "$lage ago"
782
+ }
783
+
784
+ # inspect_styled: the pass under a pill naming its issue and title, its card as label and value
785
+ # lines in aligned columns, then a table of its events, each outcome and its evidence in the
786
+ # tone of what happened. A terminal wraps a long evidence itself. The card and the table are kept
787
+ # in $tmp/card and $tmp/table as drawn, as inspect_plain keeps them.
788
+ inspect_styled() {
789
+ local t g s o e tone
790
+ ui_section secondary "#$issue" "$name"
791
+ card_styled > "$tmp/card"; cat "$tmp/card"
792
+ {
793
+ ui_attended && echo
794
+ {
795
+ ui_table_row TIME GAP STAGE OUTCOME EVIDENCE
796
+ while IFS=$'\x1f' read -r t g s o e; do
797
+ tone="$(outcome_tone "$o" "$e")"
798
+ ui_table_row "$(cell dim "$t")" "$(cell dim "$g")" "$s" "$(cell "$tone" "$o")" "$(cell "$tone" "$e")"
799
+ done < "$tmp/events"
800
+ } | ui_table --indent 2 --header --width "$cols"
801
+ } > "$tmp/table"
802
+ cat "$tmp/table"
803
+ }
804
+ # card_styled: the card as a two-column table of labels and values, from the same fields.
805
+ card_styled() {
806
+ {
807
+ ui_table_row "$(cell dim state)" "$(cell "$(state_tone "$state")" "$(glyph "$state") $state")"
808
+ ui_table_row "$(cell dim branch)" "$(cell "$(case "$branch" in *⚠*) echo fail ;; *) echo value ;; esac)" "$branch")"
809
+ ui_table_row "$(cell dim pr)" "$(if [ -n "$pr" ]; then cell value "#$pr"; else cell dim none; fi)"
810
+ ui_table_row "$(cell dim owner)" "${owner:-unknown}"
811
+ ui_table_row "$(cell dim stage)" "$stage"
812
+ ui_table_row "$(cell dim gate)" "$gate"
813
+ ui_table_row "$(cell dim reconcile)" "$recon"
814
+ ui_table_row "$(cell dim head)" "$head"
815
+ ui_table_row "$(cell dim ledger)" "$lage ago"
816
+ } | ui_table --indent 2 --width "$cols"
817
+ }
818
+
819
+ # ── Follow ────────────────────────────────────────────────────────────────────
820
+ # The state line's PR, whether the pass shipped, and the head of a copy the closeout archived,
821
+ # one record from a `ledger read` document. The PR is the ledger's, as a number where it is a
822
+ # URL. A pass shipped once its closeout is done and nothing holds or writes it any more. The copy's
823
+ # git reads the main checkout, so its head is the checkpoint's.
824
+ follow_extra_jq() {
825
+ cat <<'JQ'
826
+ [(.pr // "" | tostring | if test("/pull/[0-9]+$") then capture("/pull/(?<n>[0-9]+)$").n else . end),
827
+ (if .active != true and ([.receipts[] | select(.state == "open")] == [])
828
+ and .stage.name == "closeout" and .stage.status == "done" then "shipped" else "" end),
829
+ (.checkpoint.head // "" | if . == "none" then "" else .[0:7] end)]
830
+ | join("\u001f")
831
+ JQ
832
+ }
833
+
834
+ # follow_read <dir> <archived> [released]: reads the ledger at the dir, a worktree or the closeout's
835
+ # copy of its ledger, into $tmp/events and fstate, fstage, fgate, frecon, fpr and fhead. Status 1
836
+ # when it carries no ledger any more. With released 1 the caller has read the pass's authority as
837
+ # free, so the document's .active is set to false: `ledger read` takes the lock for a moment to
838
+ # test it, and a second reader testing it at that moment would read as a live holder.
839
+ follow_read() {
840
+ local doc _last ledger_pr shipped chead
841
+ now=$(date +%s)
842
+ # A worktree the closeout removed is refused on stderr, which is the copy's cue and no error.
843
+ doc="$(ledger read "$1" 2>/dev/null)"
844
+ [ "$(printf '%s' "$doc" | jq -r '.ledger')" = true ] || return 1
845
+ [ "${3:-0}" -eq 0 ] || doc="$(printf '%s' "$doc" | jq -c '.active = false')"
846
+ printf '%s' "$doc" | jq -r "$(inspect_events_jq)" > "$tmp/events"
847
+ IFS=$'\x1f' read -r fstate _last < <(printf '%s' "$doc" | jq -r --argjson now "$now" --argjson live "$live_secs" "$(row_state_jq)")
848
+ IFS=$'\x1f' read -r fstage fgate frecon fhead < <(printf '%s' "$doc" | jq -r "$(inspect_card_jq)")
849
+ IFS=$'\x1f' read -r ledger_pr shipped chead < <(printf '%s' "$doc" | jq -r "$(follow_extra_jq)")
850
+ [ -n "$ledger_pr" ] && fpr="$ledger_pr"
851
+ [ "$fstate" = LIVE ] && [ "$shipped" = shipped ] && fstate=shipped
852
+ [ "$2" -eq 0 ] || fhead="${chead:-none}"
853
+ return 0
854
+ }
855
+
856
+ # state_line <width>: the pass's state, stage, PR and head on one line, cut to the width with the
857
+ # palette's ellipsis when one is given, the state in its tone on an attended run.
858
+ state_line() {
859
+ local lead rest w
860
+ lead="$(glyph "$fstate") $fstate"
861
+ rest="◦ stage $fstage ◦ pr ${fpr:+#}${fpr:-none} ◦ head $fhead"
862
+ if [ -n "${1:-}" ]; then
863
+ _ui_width w "$lead $rest"
864
+ if [ "$w" -gt "$1" ]; then _ui_cut rest "$rest" $(( $1 - ${#lead} - 2 )); rest+="$(ui_glyph ellipsis)"; fi
865
+ fi
866
+ printf '%s %s' "$(ui_tint "$(state_tone "$fstate")" "$lead")" "$rest"
867
+ }
868
+
869
+ # term_size: the terminal's rows and columns into term_rows and term_cols: LINES and COLUMNS where
870
+ # they are numbers, else the size the terminal reports, else 0. A script inherits neither variable,
871
+ # and tput in a command substitution answers its terminfo default rather than the window, so a
872
+ # guess here would climb to the wrong row. A 0 draws no card line again.
873
+ term_size() {
874
+ local size=""
875
+ term_rows="${LINES:-}"; term_cols="${COLUMNS:-}"
876
+ [[ "$term_rows" =~ ^[1-9][0-9]*$ && "$term_cols" =~ ^[1-9][0-9]*$ ]] \
877
+ || size="$(stty size < /dev/tty 2>/dev/null)" || size=""
878
+ [[ "$term_rows" =~ ^[1-9][0-9]*$ ]] || term_rows="${size% *}"
879
+ [[ "$term_cols" =~ ^[1-9][0-9]*$ ]] || term_cols="${size#* }"
880
+ [[ "$term_rows" =~ ^[1-9][0-9]*$ ]] || term_rows=0
881
+ [[ "$term_cols" =~ ^[1-9][0-9]*$ ]] || term_cols=0
882
+ }
883
+ # line_rows <file>: the terminal rows each of the file's lines takes at $term_cols columns, one
884
+ # count a line: at least one, and more where a long line wraps. Its colours take no room. A wide
885
+ # character counts as one column, as _ui_width counts it.
886
+ line_rows() {
887
+ local line w c="${term_cols:-0}"
888
+ [ "$c" -gt 0 ] || c="$cols"
889
+ while IFS= read -r line || [ -n "$line" ]; do
890
+ _ui_width w "$line"
891
+ echo $(( w > c ? (w + c - 1) / c : 1 ))
892
+ done < <(sed $'s/\033\\[[0-9;]*m//g' "$1")
893
+ }
894
+ # rows_of <file>: the terminal rows the whole file takes, by line_rows.
895
+ rows_of() { line_rows "$1" | awk '{ n += $1 } END { print n + 0 }'; }
896
+
897
+ # refresh_card: draws again each line of the card that the pass has changed, in its own place above
898
+ # the table. The cursor is at the start of the row under the table, $below rows under the card's
899
+ # first. A line is drawn again only when it took one row, its new text fits in one, and the
900
+ # terminal can still reach it. A terminal cannot move its cursor above the window's top row, so a
901
+ # line scrolled up out of the window stays as first drawn, and the state line under the table
902
+ # carries what changed. It reads and updates follow_pass's below, card_drawn (each line as it
903
+ # stands on the terminal) and card_rows (the rows each took), and term_size's term_rows. A resize
904
+ # while it follows makes the counts wrong, so the size is read once, at the start.
905
+ refresh_card() {
906
+ local issue="${follow_card[0]}" branch="${follow_card[1]}" owner="${follow_card[2]}" lage="${follow_card[3]}"
907
+ local state="$fstate" pr="$fpr" stage="$fstage" gate="$fgate" recon="$frecon" head="$fhead"
908
+ local i=0 d line high=() off=0
909
+ [ "$term_rows" -gt 0 ] && [ "$term_cols" -gt 0 ] || return 0
910
+ if ui_attended; then card_styled; else card_plain; fi > "$tmp/card.new"
911
+ while IFS= read -r line; do high+=("$line"); done < <(line_rows "$tmp/card.new")
912
+ while IFS= read -r line && [ "$i" -lt "${#card_drawn[@]}" ]; do
913
+ d=$(( below - off ))
914
+ if [ "$line" != "${card_drawn[i]}" ] && [ "${card_rows[i]}" -eq 1 ] && [ "${high[i]:-2}" -eq 1 ] && [ "$d" -lt "$term_rows" ]; then
915
+ printf '\033[%dA\r\033[K%s\r\033[%dB' "$d" "$line" "$d"
916
+ card_drawn[i]="$line"
917
+ fi
918
+ off=$(( off + card_rows[i] )); i=$(( i + 1 ))
919
+ done < "$tmp/card.new"
920
+ }
921
+
922
+ # follow_row <time> <gap> <stage> <outcome> <evidence>: one new event, in the plain columns or as a
923
+ # row of the styled table, its cells padded to the table's widths.
924
+ follow_row() {
925
+ if ! ui_attended; then event_row "$@"; return; fi
926
+ local tone; tone="$(outcome_tone "$4" "$5")"
927
+ ui_table_row "$(cell dim "$(printf '%-*s' "$w_time" "$1")")" "$(cell dim "$(printf '%-*s' "$w_gap" "$2")")" \
928
+ "$(printf '%-*s' "$w_stage" "$3")" "$(cell "$tone" "$(printf '%-*s' "$w_outcome" "$4")")" "$(cell "$tone" "$5")" \
929
+ | ui_table --indent 2 --width "$cols"
930
+ }
931
+
932
+ # archived_copy <repo> <worktree>: the newest copy of the worktree's ledger that the closeout
933
+ # archived under the worktree's name, or nothing. The copies are named <worktree>-<UTC time>, so
934
+ # the glob's order is their age.
935
+ archived_copy() {
936
+ local copies
937
+ copies=("$1/.claude/kryso/shipped/$(basename "$2")"-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9][0-9][0-9]Z)
938
+ [ -d "${copies[${#copies[@]}-1]}" ] && printf '%s' "${copies[${#copies[@]}-1]}"
939
+ return 0
940
+ }
941
+
942
+ # follow_pass <repo>: after the inspection of the pass in follow_wt, prints each event its ledger
943
+ # gets until the pass is no longer LIVE, then the final state line, and returns 0. On a terminal the
944
+ # card's lines are drawn again in place while the terminal can reach them (refresh_card), and the
945
+ # state line stays under the table, redrawn in place, for when the card has scrolled away above a
946
+ # table that grows. Off one the output is append-only, and the only state that changes while it follows
947
+ # is LIVE's end, so the final line is its one state line. It reads the ledger and nothing else: no
948
+ # authority, no receipt, no write. When the closeout has removed the worktree it reads the newest
949
+ # copy of the ledger the closeout archived under the worktree's name, and only one that starts with
950
+ # the rows already printed, so an earlier pass's copy is never taken for this one.
951
+ follow_pass() {
952
+ local repo="$1" src="$follow_wt" archived=0 shown tty=0 printed="" line copy t g s o e
953
+ local interval="${KRYSO_STATUS_INTERVAL:-2}" below=0 key="" now_key card_drawn=() card_rows=() term_rows=0 term_cols=0
954
+ [[ "$interval" =~ ^[0-9]+(\.[0-9]+)?$ ]] || interval=2
955
+ [ -t 1 ] && tty=1
956
+ fpr="$follow_pr"
957
+ shown="$(wc -l < "$tmp/events" | tr -d ' ')"
958
+ cp "$tmp/events" "$tmp/seen"
959
+ event_widths
960
+ if [ "$tty" -eq 1 ]; then
961
+ term_size
962
+ while IFS= read -r line; do card_drawn+=("$line"); done < "$tmp/card"
963
+ while IFS= read -r line; do card_rows+=("$line"); done < <(line_rows "$tmp/card")
964
+ below=$(( $(rows_of "$tmp/card") + $(rows_of "$tmp/table") ))
965
+ fi
966
+ # Ctrl-C clears the state line under the table and stops. The pass is not this script's.
967
+ # shellcheck disable=SC2064 # the terminal check is fixed now, as tty is gone once this returns
968
+ trap "[ $tty -eq 0 ] || printf '\r\033[K'; exit 130" INT TERM
969
+ unfoot() { [ "$tty" -eq 0 ] || printf '\r\033[K'; }
970
+ while :; do
971
+ if follow_read "$src" "$archived" && head -n "$shown" "$tmp/events" | cmp -s - "$tmp/seen"; then :
972
+ else
973
+ copy="$(archived_copy "$repo" "$follow_wt")"
974
+ if [ "$archived" -eq 0 ] && [ -n "$copy" ]; then src="$copy"; archived=1; continue; fi
975
+ unfoot
976
+ printf '%s %s\n' "$(ui_tint dim "○ gone")" "◦ $follow_wt and any copy of its ledger are gone"
977
+ return 0
978
+ fi
979
+ if [ "$(wc -l < "$tmp/events" | tr -d ' ')" -gt "$shown" ]; then
980
+ unfoot
981
+ while IFS=$'\x1f' read -r t g s o e; do follow_row "$t" "$g" "$s" "$o" "$e"; done \
982
+ < <(tail -n +"$((shown + 1))" "$tmp/events") > "$tmp/rows"
983
+ cat "$tmp/rows"
984
+ [ "$tty" -eq 0 ] || below=$(( below + $(rows_of "$tmp/rows") ))
985
+ cp "$tmp/events" "$tmp/seen"
986
+ shown="$(wc -l < "$tmp/seen" | tr -d ' ')"
987
+ printed=""
988
+ fi
989
+ now_key="$fstate|$fstage|$fgate|$frecon|$fpr|$fhead"
990
+ if [ "$tty" -eq 1 ] && [ "$now_key" != "$key" ]; then refresh_card; key="$now_key"; fi
991
+ if [ "$fstate" != LIVE ]; then
992
+ unfoot
993
+ printf '%s\n' "$(state_line)"
994
+ return 0
995
+ fi
996
+ if [ "$tty" -eq 1 ]; then
997
+ line="$(state_line $(( cols - 1 )))"
998
+ [ "$line" = "$printed" ] || { printf '\r\033[K%s' "$line"; printed="$line"; }
999
+ fi
1000
+ sleep "$interval"
1001
+ done
1002
+ }
1003
+
1004
+ # ── Attach ────────────────────────────────────────────────────────────────────
1005
+ # kryso attach is this script's --attach. It reads what follow_pass reads, a pass's ledger through
1006
+ # follow_read, plus a shift's folder and the streams the passes write, and prints them the plain way,
1007
+ # append-only, so its log holds what the terminal showed.
1008
+
1009
+ # attach_say <line>: one line to the terminal, and to the log without its colours.
1010
+ attach_say() {
1011
+ printf '%s\n' "$1"
1012
+ printf '%s\n' "$1" | sed $'s/\033\\[[0-9;]*m//g' >> "$attach_log"
1013
+ }
1014
+
1015
+ # driver_alive <pid> <script>: status 0 while the pid is a live process running the script.
1016
+ driver_alive() {
1017
+ [[ "$1" =~ ^[0-9]+$ ]] && kill -0 "$1" 2>/dev/null && ps -o args= -p "$1" 2>/dev/null | grep -q "$2"
1018
+ }
1019
+
1020
+ # attach_shifts <repo>: "<folder> <id> <pid>" for each running shift of the repo: a folder under
1021
+ # .claude/kryso, or .claude/ship-loop before the rename, whose shift.json names a pid that is alive
1022
+ # and runs ship-loop.sh. It reads the pid and never the driver's lock, which it would take for a
1023
+ # moment to read. Each folder is named by its real path and listed once, because the rename left
1024
+ # .claude/ship-loop as a link to .claude/kryso in some checkouts, and both names reach it (#665).
1025
+ attach_shifts() {
1026
+ local d real pid seen=$'\n'
1027
+ for d in "$1"/.claude/kryso/*/ "$1"/.claude/ship-loop/*/; do
1028
+ [ -f "$d/shift.json" ] || continue
1029
+ real="$(cd -P "$d" 2>/dev/null && pwd)" || continue
1030
+ case "$seen" in *$'\n'"$real"$'\n'*) continue ;; esac
1031
+ seen+="$real"$'\n'
1032
+ pid="$(jq -r '.pid // empty' "$real/shift.json" 2>/dev/null)"
1033
+ driver_alive "$pid" ship-loop.sh || continue
1034
+ printf '%s %s %s\n' "$real" "${real##*/}" "$pid"
1035
+ done
1036
+ }
1037
+
1038
+ # parent_of <pid>: the pid's parent, or status 1 at the top of the tree or for a pid that is gone.
1039
+ parent_of() {
1040
+ local p
1041
+ p="$(ps -o ppid= -p "$1" 2>/dev/null | tr -d ' ')"
1042
+ [[ "$p" =~ ^[0-9]+$ && "$p" -gt 1 ]] && printf '%s\n' "$p"
1043
+ }
1044
+
1045
+ # descends <pid> <ancestor>: status 0 when the ancestor is the pid or one of its parents.
1046
+ descends() {
1047
+ local p="$1" i
1048
+ for (( i = 0; i < 30; i++ )); do
1049
+ [ "$p" = "$2" ] && return 0
1050
+ p="$(parent_of "$p")" || return 1
1051
+ done
1052
+ return 1
1053
+ }
1054
+
1055
+ # attach_live <repo> [driver-pid]: "<worktree> <issue>" for each LIVE pass of the repo, or with a
1056
+ # driver pid only the pass whose authority a process under that driver holds.
1057
+ attach_live() {
1058
+ local repo="$1" driver="${2:-}" wt issue holder state _last doc
1059
+ # The loop reads its records on fd 3, so nothing it runs can drain them through stdin.
1060
+ while read -r -u 3 wt issue; do
1061
+ [[ "$issue" =~ ^[0-9]+$ ]] || continue
1062
+ if [ -n "$driver" ]; then
1063
+ holder="$(ledger active "$repo" "$issue" 2>/dev/null)" || continue
1064
+ descends "${holder%% *}" "$driver" && printf '%s %s\n' "$wt" "$issue"
1065
+ continue
1066
+ fi
1067
+ doc="$(ledger read "$wt" 2>/dev/null)" || continue
1068
+ IFS=$'\x1f' read -r state _last < <(printf '%s' "$doc" | jq -r --argjson now "$(date +%s)" --argjson live "$live_secs" "$(row_state_jq)")
1069
+ [ "$state" = LIVE ] && printf '%s %s\n' "$wt" "$issue"
1070
+ done 3< <(ledger worktrees "$repo")
1071
+ }
1072
+
1073
+ # driver_of <repo> <issue>: "<pid> <script>" of the driver that runs the pass, or nothing. The
1074
+ # authority's holder is a fork of a driver, which carries the driver's command line, so the driver
1075
+ # is the topmost of the unbroken run of parents, from the holder's nearest driver parent up, whose
1076
+ # command line names ship-pass.sh or ship-loop.sh. A pass a shift runs gives the shift's driver.
1077
+ driver_of() {
1078
+ local p holder args i top=""
1079
+ holder="$(ledger active "$1" "$2" 2>/dev/null)" || return 1
1080
+ p="${holder%% *}"
1081
+ for (( i = 0; i < 30; i++ )); do
1082
+ [[ "$p" =~ ^[0-9]+$ ]] || break
1083
+ args="$(ps -o args= -p "$p" 2>/dev/null)"
1084
+ case "$args" in
1085
+ *ship-loop.sh*) top="$p ship-loop.sh" ;;
1086
+ *ship-pass.sh*) top="$p ship-pass.sh" ;;
1087
+ *) [ -z "$top" ] || break ;;
1088
+ esac
1089
+ p="$(parent_of "$p")" || break
1090
+ done
1091
+ [ -n "$top" ] && printf '%s\n' "$top"
1092
+ }
1093
+
1094
+ # attach_stream <file>...: the whole lines each file has gained since the last read, each after its
1095
+ # file's name. A file seen for the first time is read from its start. The bytes read so far are in
1096
+ # $tmp/offsets, a "<bytes> <path>" line each.
1097
+ attach_stream() {
1098
+ local f size had chunk whole line
1099
+ for f in "$@"; do
1100
+ [ -f "$f" ] || continue
1101
+ size="$(wc -c < "$f" | tr -d ' ')"
1102
+ had="$(awk -v f="$f" '$2 == f { n = $1 } END { print n + 0 }' "$tmp/offsets")"
1103
+ [ "$size" -gt "$had" ] || continue
1104
+ chunk="$(tail -c +"$(( had + 1 ))" "$f" | head -c "$(( size - had ))"; echo x)"
1105
+ chunk="${chunk%x}"
1106
+ case "$chunk" in *$'\n'*) ;; *) continue ;; esac
1107
+ whole="${chunk%$'\n'*}"
1108
+ printf '%s %s\n' "$(( had + $(printf '%s\n' "$whole" | wc -c) ))" "$f" >> "$tmp/offsets"
1109
+ while IFS= read -r line; do attach_say "$(basename "$f") │ $line"; done <<< "$whole"
1110
+ done
1111
+ }
1112
+ # attach_skip <file>...: marks what each file holds now as read, so a stream already written before
1113
+ # the attach is not replayed.
1114
+ attach_skip() {
1115
+ local f
1116
+ for f in "$@"; do [ -f "$f" ] && printf '%s %s\n' "$(wc -c < "$f" | tr -d ' ')" "$f" >> "$tmp/offsets"; done
1117
+ return 0
1118
+ }
1119
+
1120
+ # attach_open <worktree> <issue>: makes the pass the one followed, and prints its heading and the
1121
+ # ledger rows it has so far. Status 1 when it carries no ledger.
1122
+ attach_open() {
1123
+ local t g s o e
1124
+ a_wt="$1"; a_issue="$2"; a_src="$1"; a_archived=0; fpr=""
1125
+ _ledger_d "$1" a_ld
1126
+ follow_read "$a_src" 0 || return 1
1127
+ attach_say ""
1128
+ attach_say "#$a_issue ◦ $a_wt"
1129
+ event_widths
1130
+ while IFS=$'\x1f' read -r t g s o e; do attach_say "$(event_row "$t" "$g" "$s" "$o" "$e")"; done < "$tmp/events"
1131
+ cp "$tmp/events" "$tmp/aseen"
1132
+ a_shown="$(wc -l < "$tmp/aseen" | tr -d ' ')"
1133
+ return 0
1134
+ }
1135
+
1136
+ # attach_pass_tick: the new ledger rows and stream lines of the pass followed. Status 1, after its
1137
+ # final state line, once it is over: no longer LIVE, or in a shift, no longer held by the shift's
1138
+ # driver, which waits on nothing of the pass's but its open receipts. The hold is read before the
1139
+ # ledger, so a pass seen released has every line it wrote before its release printed, and its state
1140
+ # is read with that hold, so another terminal's test of the lock is not taken for the driver.
1141
+ attach_pass_tick() {
1142
+ local t g s o e copy over=0
1143
+ [ -z "$a_driver" ] || ledger active "$repo" "$a_issue" > /dev/null 2>&1 || over=1
1144
+ if ! follow_read "$a_src" "$a_archived" "$over" || ! head -n "$a_shown" "$tmp/events" | cmp -s - "$tmp/aseen"; then
1145
+ copy="$(archived_copy "$repo" "$a_wt")"
1146
+ if [ "$a_archived" -eq 0 ] && [ -n "$copy" ]; then
1147
+ a_src="$copy"; a_archived=1; _ledger_d "$copy" a_ld
1148
+ follow_read "$a_src" 1 "$over" && head -n "$a_shown" "$tmp/events" | cmp -s - "$tmp/aseen"
1149
+ else
1150
+ false
1151
+ fi || { attach_say "$(ui_tint dim "○ gone") ◦ $a_wt and any copy of its ledger are gone"; a_wt=""; return 1; }
1152
+ fi
1153
+ if [ "$(wc -l < "$tmp/events" | tr -d ' ')" -gt "$a_shown" ]; then
1154
+ while IFS=$'\x1f' read -r t g s o e; do attach_say "$(event_row "$t" "$g" "$s" "$o" "$e")"; done \
1155
+ < <(tail -n +"$((a_shown + 1))" "$tmp/events")
1156
+ cp "$tmp/events" "$tmp/aseen"
1157
+ a_shown="$(wc -l < "$tmp/aseen" | tr -d ' ')"
1158
+ fi
1159
+ attach_stream "$a_ld"/logs/*.err "$a_ld"/logs/*.raw
1160
+ [ "$fstate" = LIVE ] || over=1
1161
+ [ "$over" -eq 1 ] || return 0
1162
+ attach_say "$(state_line)"
1163
+ a_wt=""
1164
+ return 1
1165
+ }
1166
+
1167
+ # attach_stop: sends the run's driver a TERM, which it takes as a ctrl+c in its own foreground, and
1168
+ # says so. A pass a shift runs has the shift's driver, so the shift stops with it.
1169
+ attach_stop() {
1170
+ local pid script
1171
+ if [ "$a_mode" = shift ]; then pid="$a_pid"; script=ship-loop.sh
1172
+ else read -r pid script < <(driver_of "$repo" "$a_issue"); fi
1173
+ if [ -z "${pid:-}" ]; then attach_say "stop: no driver holds #$a_issue any more, so nothing was sent"; return 0; fi
1174
+ kill -TERM "$pid" 2>/dev/null || { attach_say "stop: $script pid $pid has already exited"; return 0; }
1175
+ attach_say "stop: sent TERM to $script pid $pid, which stops the run as a ctrl+c in its foreground does; following until it ends"
1176
+ a_stopped=1
1177
+ }
1178
+
1179
+ # attach_ask: the prompt a ctrl+c on a terminal gets. Detach exits 0 and leaves the run alone. Stop
1180
+ # sends the TERM and goes on following. A second ctrl+c or a TERM while it asks detaches.
1181
+ attach_ask() {
1182
+ local ans=""
1183
+ attach_int=0
1184
+ printf '\n%s' "detach, or stop the run? [d]etach, [s]top: " > /dev/tty
1185
+ # A read takes no ctrl+c: the trap runs and the read goes on. So it waits a second at a time.
1186
+ while [ "$attach_int" -eq 0 ] && [ "$attach_term" -eq 0 ]; do read -r -t 1 ans < /dev/tty && break; done
1187
+ [ "$attach_int" -eq 0 ] && [ "$attach_term" -eq 0 ] || { printf '\n' > /dev/tty; ans=d; }
1188
+ attach_int=0
1189
+ case "$ans" in s|S|stop) attach_stop ;; *) attach_detach ;; esac
1190
+ }
1191
+ # attach_detach: stops the follower, leaves the run alone, and exits 0. The follower ends once its
1192
+ # tick is done, and the detach line waits for it, so the detach line is the last line. A signal cuts
1193
+ # a wait short, so it waits until the follower is gone.
1194
+ attach_detach() {
1195
+ if [ -n "${a_follow:-}" ]; then
1196
+ kill -TERM "$a_follow" 2>/dev/null; kill -CONT "$a_follow" 2>/dev/null
1197
+ while kill -0 "$a_follow" 2>/dev/null; do wait "$a_follow" 2>/dev/null; done
1198
+ fi
1199
+ attach_say "detached; the run goes on"
1200
+ exit 0
1201
+ }
1202
+
1203
+ # attach_main [shift-id | issue] [--log <path>] [repo-path]: finds the run, then follows it.
1204
+ attach_main() {
1205
+ local target="" log="" interval="${KRYSO_STATUS_INTERVAL:-2}" list stamp code again
1206
+ [[ "$interval" =~ ^[0-9]+(\.[0-9]+)?$ ]] || interval=2
1207
+ repo=""
1208
+ while [ $# -gt 0 ]; do
1209
+ case "$1" in
1210
+ -h|--help)
1211
+ printf 'Usage: kryso attach [shift-id | issue] [--log <path>] [repo-path]\n\n'
1212
+ awk '/^# Attach:$/ { f = 1; next } f && (/^# [A-Z][a-z]*:$/ || /^# -{20,}$/) { exit } f { sub(/^# ?/, ""); sub(/^ /, ""); print }' "$self"
1213
+ exit 0 ;;
1214
+ --log) [ $# -ge 2 ] || { echo "--log needs a path" >&2; exit 64; }; log="$2"; shift ;;
1215
+ *)
1216
+ if [[ "$1" =~ ^#?[0-9]+$ || "$1" =~ ^[0-9]{8}T[0-9]{6}Z$ ]] && [ -z "$target" ]; then target="${1#\#}"
1217
+ else repo="$1"; fi ;;
1218
+ esac
1219
+ shift
1220
+ done
1221
+ repo="${repo:-.}"
1222
+ [ -d "$repo" ] || not_a_repo "$repo"
1223
+ repo="$(git -C "$repo" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" || not_a_repo "$repo"
1224
+ repo="$(cd "$(dirname "$repo")" && pwd -P)"
1225
+ a_mode=""; a_pid=""; a_dir=""; a_wt=""; a_issue=""; a_driver=""; a_stopped=0; a_follow=""; sid=""
1226
+ if [[ "$target" =~ T ]]; then
1227
+ read -r a_dir sid a_pid < <(attach_shifts "$repo" | awk -v id="$target" '$2 == id')
1228
+ [ -n "$a_dir" ] || { echo "no running shift $target under $repo/.claude/kryso" >&2; exit 1; }
1229
+ a_mode=shift
1230
+ elif [ -n "$target" ]; then
1231
+ read -r a_wt a_issue < <(attach_live "$repo" | awk -v n="$target" '$2 == n')
1232
+ [ -n "$a_wt" ] || { echo "no running pass for #$target under $repo" >&2; exit 1; }
1233
+ a_mode=pass
1234
+ else
1235
+ attach_shifts "$repo" > "$tmp/shifts"
1236
+ if [ "$(wc -l < "$tmp/shifts" | tr -d ' ')" -eq 1 ]; then
1237
+ read -r a_dir sid a_pid < "$tmp/shifts"; a_mode=shift
1238
+ else
1239
+ list="$(awk '{ print "shift " $2 " ◦ pid " $3 }' "$tmp/shifts"; attach_live "$repo" | awk '{ print "pass #" $2 " ◦ " $1 }')"
1240
+ if [ -z "$list" ]; then echo "no shift or pass is running under $repo" >&2; exit 1; fi
1241
+ printf '%s\n' "$list"
1242
+ echo "more than one shift, or no shift, runs under $repo, so name one: kryso attach <shift-id> or kryso attach <issue>" >&2
1243
+ exit 1
1244
+ fi
1245
+ fi
1246
+
1247
+ stamp="$(date -u +%Y%m%dT%H%M%SZ)-$$"
1248
+ if [ -z "$log" ]; then
1249
+ if [ "$a_mode" = shift ]; then log="$a_dir/attach-$stamp.txt"
1250
+ else _ledger_d "$a_wt" a_ld; mkdir -p "$a_ld/logs"; log="$a_ld/logs/attach-$stamp.txt"; fi
1251
+ fi
1252
+ attach_log="$log"
1253
+ : > "$attach_log" 2>/dev/null || { echo "cannot write the log $attach_log" >&2; exit 1; }
1254
+
1255
+ # Once the run is found, this shell takes ctrl+c and TERM, and the follower prints the output so
1256
+ # far and then follows. The follower runs in the background and ignores ctrl+c, as everything it
1257
+ # runs does, so a key pressed in the middle of a read never cuts the read short, not even while
1258
+ # the output so far prints. On a terminal a ctrl+c holds the follower still and asks, and without
1259
+ # one it detaches. A TERM detaches. A follower that has ended gives its status: from the wait
1260
+ # that saw it end, or from a second wait when a signal cut the first short.
1261
+ attach_int=0; attach_term=0
1262
+ trap 'attach_int=1' INT
1263
+ trap 'attach_term=1' TERM
1264
+ attach_follow "$interval" &
1265
+ a_follow=$!
1266
+ while :; do
1267
+ code=0
1268
+ if [ "$attach_int" -eq 0 ] && [ "$attach_term" -eq 0 ]; then wait "$a_follow"; code=$?; fi
1269
+ if ! kill -0 "$a_follow" 2>/dev/null; then
1270
+ wait "$a_follow" 2>/dev/null; again=$?
1271
+ [ "$again" -eq 127 ] || code="$again"
1272
+ exit "$code"
1273
+ fi
1274
+ [ "$attach_term" -eq 0 ] || attach_detach
1275
+ [ "$attach_int" -eq 1 ] || continue
1276
+ attach_int=0
1277
+ if [ "$a_stopped" -eq 1 ] || [ ! -t 0 ]; then attach_detach; fi
1278
+ kill -STOP "$a_follow" 2>/dev/null
1279
+ attach_ask
1280
+ kill -CONT "$a_follow" 2>/dev/null
1281
+ done
1282
+ }
1283
+
1284
+ # attach_start: the log's line and the output so far: the shift's heading and its shift.log, and
1285
+ # the ledger rows of the pass it is on, or of the pass named. What the streams hold already is
1286
+ # marked read before anything of the run prints, so a line written once the output so far is on
1287
+ # the screen is never taken for one written before.
1288
+ attach_start() {
1289
+ : > "$tmp/offsets"
1290
+ if [ "$a_mode" = shift ]; then
1291
+ attach_skip "$a_dir"/pass-*.err "$a_dir"/pass-*.raw
1292
+ read -r a_wt a_issue < <(attach_live "$repo" "$a_pid" | head -1)
1293
+ fi
1294
+ if [ -n "$a_wt" ]; then _ledger_d "$a_wt" a_ld; attach_skip "$a_ld"/logs/*.err "$a_ld"/logs/*.raw; fi
1295
+ attach_say "kryso attach: log at $attach_log"
1296
+ if [ "$a_mode" = shift ]; then
1297
+ a_driver="$a_pid"
1298
+ attach_say "shift $sid ◦ driver pid $a_pid ◦ $(jq -r '"started \(.started_at // "?") ◦ engine \(.engine // "?") ◦ profile \(.profile // "?")"' "$a_dir/shift.json" 2>/dev/null)"
1299
+ a_lines=0
1300
+ attach_shift_log
1301
+ fi
1302
+ [ -z "$a_wt" ] || attach_open "$a_wt" "$a_issue" || a_wt=""
1303
+ }
1304
+
1305
+ # attach_follow <interval>: attach_start, then the follow itself, a tick every interval until the
1306
+ # run ends, status 0. A TERM, a detach, ends it once the tick in hand is done, so every reader the
1307
+ # tick started has written all it will, and none is left to write, or to fail to, after the detach
1308
+ # line. The pause between ticks is a wait, which a TERM cuts short.
1309
+ attach_follow() {
1310
+ local nap
1311
+ trap '' INT
1312
+ a_quit=0
1313
+ trap 'a_quit=1' TERM
1314
+ attach_start
1315
+ while [ "$a_quit" -eq 0 ]; do
1316
+ if [ "$a_mode" = shift ]; then
1317
+ # The driver writes its line for a pass once the pass has ended, so while a pass is followed
1318
+ # its lines wait, and come after the pass's state line.
1319
+ [ -z "$a_wt" ] || attach_pass_tick || true
1320
+ [ -n "$a_wt" ] || attach_shift_log
1321
+ attach_stream "$a_dir"/pass-*.err "$a_dir"/pass-*.raw
1322
+ if ! driver_alive "$a_pid" ship-loop.sh; then
1323
+ [ -z "$a_wt" ] || attach_pass_tick || true
1324
+ attach_shift_log
1325
+ attach_stream "$a_dir"/pass-*.err "$a_dir"/pass-*.raw
1326
+ if [ -f "$a_dir/summary.json" ]; then
1327
+ attach_say "$(jq -r '"shift \(.shift) ended ◦ stop \(.stop) ◦ \(.stop_reason)"' "$a_dir/summary.json") ◦ summary at $a_dir/summary.json"
1328
+ else
1329
+ attach_say "shift $sid ended: its driver exited and wrote no summary.json"
1330
+ fi
1331
+ return 0
1332
+ fi
1333
+ # The driver writes its line for a pass before it starts the next, so the lines it has once
1334
+ # a new pass is seen come before that pass's heading.
1335
+ if [ -z "$a_wt" ]; then
1336
+ read -r a_wt a_issue < <(attach_live "$repo" "$a_pid" | head -1)
1337
+ [ -z "$a_wt" ] || { attach_shift_log; attach_open "$a_wt" "$a_issue" || a_wt=""; }
1338
+ fi
1339
+ else
1340
+ attach_pass_tick || return 0
1341
+ fi
1342
+ [ "$a_quit" -eq 0 ] || break
1343
+ sleep "$1" & nap=$!
1344
+ wait "$nap" || kill "$nap" 2>/dev/null
1345
+ done
1346
+ return 0
1347
+ }
1348
+ # attach_shift_log: the lines shift.log has gained, a_lines counting those already printed.
1349
+ attach_shift_log() {
1350
+ local n line
1351
+ [ -f "$a_dir/shift.log" ] || return 0
1352
+ n="$(wc -l < "$a_dir/shift.log" | tr -d ' ')"
1353
+ [ "$n" -gt "$a_lines" ] || return 0
1354
+ while IFS= read -r line; do attach_say "$line"; done < <(sed -n "$((a_lines + 1)),${n}p" "$a_dir/shift.log")
1355
+ a_lines="$n"
1356
+ }
1357
+
1358
+ # Every main checkout a Claude or Codex session has run in, deduplicated, scratch skipped.
1359
+ all_repos() {
1360
+ local d f cwd common
1361
+ for d in "$projects"/*/; do
1362
+ f="$(ls -t "$d"*.jsonl 2>/dev/null | head -1)"
1363
+ [ -n "$f" ] || continue
1364
+ cwd="$(LC_ALL=C grep -m1 -o '"cwd":"[^"]*"' "$f" 2>/dev/null | head -1 | cut -d'"' -f4)"
1365
+ [ -d "$cwd" ] || continue
1366
+ case "$cwd" in /private/tmp/claude-*|/tmp/claude-*) continue ;; esac
1367
+ common="$(git -C "$cwd" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" || continue
1368
+ dirname "$common"
1369
+ done
1370
+ if [ -d "$codex_sessions" ]; then
1371
+ find "$codex_sessions" -name '*.jsonl' -print0 2>/dev/null \
1372
+ | xargs -0 awk 'FNR<=20 && match($0,/"cwd":"[^"]*"/) {print substr($0,RSTART+7,RLENGTH-8); nextfile}
1373
+ FNR>20 {nextfile}' \
1374
+ | while IFS= read -r cwd; do
1375
+ [ -d "$cwd" ] || continue
1376
+ case "$cwd" in /private/tmp/codex-*|/tmp/codex-*) continue ;; esac
1377
+ common="$(git -C "$cwd" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" || continue
1378
+ dirname "$common"
1379
+ done
1380
+ fi
1381
+ }
1382
+
1383
+ # say_empty <message>: the empty result, under the brand line as an information line when
1384
+ # attended, and a plain line otherwise.
1385
+ say_empty() {
1386
+ if ui_attended; then brand_once "nothing to show"; ui_info "$1"; else printf '○ %s\n' "$1"; fi
1387
+ }
1388
+
1389
+ # ── Spinner ───────────────────────────────────────────────────────────────────
1390
+ # The ledgers, the transcripts, the open PRs and Glow's cells take seconds, and nothing prints
1391
+ # until all of them are in. An attended run on a terminal thus runs itself again behind a
1392
+ # spinner, forced to the styled path at the terminal's width, and prints that run's output and
1393
+ # errors once it ends. A forced run off a terminal has nobody to watch a spinner, and gum would
1394
+ # draw its frames into the pipe.
1395
+ spun() { # <arg>...: this script with the args behind a spinner, its streams and status replayed
1396
+ local status
1397
+ # shellcheck disable=SC2016 # the inner shell expands its own arguments
1398
+ ui_spin "Reading the ledgers" bash -c '"${@:2}" > "$1/out" 2> "$1/err"' _ "$tmp" \
1399
+ env CLICOLOR_FORCE=1 COLUMNS="$cols" KRYSO_STATUS_SPUN=1 KRYSO_STATUS_ERR="$(ui_err_attended && echo drawn || echo plain)" bash "$self" "$@"
1400
+ status=$?
1401
+ # An inspection taller than the terminal opens in gum's pager, and anything shorter prints.
1402
+ if [ "$inspecting" -eq 1 ] && [ "$(wc -l < "$tmp/out" 2>/dev/null || echo 0)" -gt "${LINES:-$(tput lines 2>/dev/null || echo 24)}" ]; then
1403
+ ui_pager < "$tmp/out"
1404
+ else
1405
+ cat "$tmp/out" 2>/dev/null
1406
+ fi
1407
+ cat "$tmp/err" >&2 2>/dev/null
1408
+ return "$status"
1409
+ }
1410
+ # err_drawn: status 0 when a refusal is drawn. Behind the spinner the run is forced, so the
1411
+ # spinner says whether the stderr its errors replay to is attended.
1412
+ err_drawn() {
1413
+ if [ -n "${KRYSO_STATUS_ERR:-}" ]; then [ "$KRYSO_STATUS_ERR" = drawn ]; else ui_err_attended; fi
1414
+ }
1415
+ # not_a_repo <path>: the refusal for a path that is no repository, under an ERROR pill when
1416
+ # stderr is attended. Exit 1.
1417
+ not_a_repo() {
1418
+ if err_drawn; then ui_error "$1 is not in a git repo" "Run it inside a repository, or name one with kryso status <repo-path>"
1419
+ else echo "$1 is not in a git repo" >&2; fi
1420
+ exit 1
1421
+ }
1422
+ inspecting=0; following=0
1423
+ case " $* " in *" --inspect "*) inspecting=1 ;; esac
1424
+ case " $* " in *" --follow "*) following=1 ;; esac
1425
+ # --attach follows a run, so it never waits behind the spinner either.
1426
+ [ "${1:-}" != --attach ] || following=1
1427
+ # --follow prints as the ledger moves, so it never waits behind the spinner.
1428
+ case "${1:-}" in -h|--help) ;; *)
1429
+ if [ -z "${KRYSO_STATUS_SPUN:-}" ] && [ "$following" -eq 0 ] && [ -t 1 ] && ui_gum; then spun "$@"; exit; fi ;;
1430
+ esac
1431
+ follow_wt=""; follow_pr=""; follow_card=()
1432
+
1433
+ case "${1:-}" in
1434
+ --attach)
1435
+ shift
1436
+ attach_main "$@"
1437
+ ;;
1438
+ --repos)
1439
+ all_repos | awk '!seen[$0]++'
1440
+ ;;
1441
+ -a|--all)
1442
+ # report_repo prints nothing for a repo it skips, so it writes straight to stdout: in a
1443
+ # command substitution stdout is a pipe, and a terminal run would lose its styling.
1444
+ any=0
1445
+ ! ui_attended || brand_once "every repo a session has used"
1446
+ while IFS= read -r repo; do
1447
+ report_repo "$repo" && any=1
1448
+ done < <(all_repos | awk '!seen[$0]++')
1449
+ [ "$any" -eq 1 ] || say_empty "no repo under $projects carries a .kryso/ ledger, no shift running"
1450
+ ;;
1451
+ --inspect)
1452
+ shift
1453
+ all=0; repo=""; issues=(); n_issues=0
1454
+ for arg in "$@"; do
1455
+ case "$arg" in
1456
+ -a|--all) all=1 ;;
1457
+ --follow) ;;
1458
+ *)
1459
+ # An issue is the whole argument in digits, a leading # allowed; anything else, a
1460
+ # relative path that starts with a digit included, is the repo.
1461
+ if [[ "$arg" =~ ^#?[0-9]+$ ]]; then issues+=("${arg#\#}"); n_issues=$((n_issues + 1))
1462
+ else repo="$arg"; fi ;;
1463
+ esac
1464
+ done
1465
+ if [ "$following" -eq 1 ] && { [ "$n_issues" -ne 1 ] || [ "$all" -eq 1 ]; }; then
1466
+ why="--follow follows one pass, so it takes one issue and no --all"
1467
+ if err_drawn; then ui_error "$why" "kryso status --inspect <issue> --follow [repo-path]"; else echo "$why" >&2; fi
1468
+ exit 1
1469
+ fi
1470
+ : > "$tmp/found"
1471
+ any=0
1472
+ if [ "$all" -eq 1 ]; then
1473
+ while IFS= read -r each; do
1474
+ inspect_repo "$each" ${issues[@]+"${issues[@]}"} && any=1
1475
+ done < <(all_repos | awk '!seen[$0]++')
1476
+ where="any repo under $projects"
1477
+ else
1478
+ repo="${repo:-$(git rev-parse --show-toplevel 2>/dev/null)}"
1479
+ [ -d "$repo" ] || not_a_repo "${repo:-$PWD}"
1480
+ repo="$(cd "$repo" && pwd -P)"
1481
+ inspect_repo "$repo" ${issues[@]+"${issues[@]}"} && any=1
1482
+ where="$repo"
1483
+ fi
1484
+ missing=0
1485
+ for issue in ${issues[@]+"${issues[@]}"}; do
1486
+ grep -qxF "$issue" "$tmp/found" || { if err_drawn; then ui_error "no ledger names issue #$issue under $where" "kryso status --inspect $where lists the passes it holds"; else echo "no ledger names issue #$issue under $where" >&2; fi; missing=1; }
1487
+ done
1488
+ [ "$n_issues" -gt 0 ] || [ "$any" -eq 1 ] || say_empty "no worktree under $where carries a .kryso/ ledger"
1489
+ [ "$following" -eq 0 ] || [ "$missing" -ne 0 ] || follow_pass "$repo"
1490
+ exit "$missing"
1491
+ ;;
1492
+ -h|--help)
1493
+ # The help is the header's usage block, drawn in sections on an attended stdout.
1494
+ { ui_attended && ui_brand status help; } || true
1495
+ awk 'NR > 1 && /^# -{20,}$/ {exit} NR > 1 {sub(/^# ?/, ""); print}' "$0" | ui_help
1496
+ ;;
1497
+ *)
1498
+ repo="${1:-$(git rev-parse --show-toplevel 2>/dev/null)}"
1499
+ [ -d "$repo" ] || not_a_repo "${1:-$PWD}"
1500
+ repo="$(cd "$repo" && pwd -P)"
1501
+ report_repo "$repo" || say_empty "no worktree under $repo carries a .kryso/ ledger, no shift running"
1502
+ ;;
1503
+ esac