@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,3977 @@
1
+ #!/usr/bin/env bash
2
+ # ship-loop: clear the ready column by running one engine once per issue, each in a fresh
3
+ # process so the fourth run of the night gets the same context window as the first. The
4
+ # host comes from an execution profile, or the pass script beside this one with --engine script.
5
+ # Runs from a plain terminal or from inside a session. See SKILL.md.
6
+ set -uo pipefail
7
+
8
+ # The script may be run through a link (the runbook links it onto PATH), so every link is
9
+ # followed to the real file, and the files beside it are found from there.
10
+ SELF="${BASH_SOURCE[0]}"
11
+ while [[ -L "$SELF" ]]; do
12
+ target="$(readlink "$SELF")"
13
+ case "$target" in /*) SELF="$target" ;; *) SELF="$(dirname "$SELF")/$target" ;; esac
14
+ done
15
+ HERE="$(cd "$(dirname "$SELF")" && pwd)"
16
+ SCHEMA="$HERE/outcome.schema.json"
17
+ PASS_SCRIPT="$HERE/ship-pass.sh"
18
+ # The pass script hashes the driver that started it into its record, and this is how it knows.
19
+ KRYSO_SHIFT_DRIVER_SH="$HERE/$(basename "${BASH_SOURCE[0]}")"
20
+ export KRYSO_SHIFT_DRIVER_SH
21
+
22
+ # kryso_module <file>: where the driver loads one of kryso's files from, ledger.sh or ui.sh, the
23
+ # first that exists of: the kryso directory beside this one, then .agents/skills under the
24
+ # repository and the home, then the .claude/skills compatibility path under both. ui.sh's
25
+ # header names the order, which every kryso script keeps. Status 1 when none has it.
26
+ kryso_module() {
27
+ local root candidate
28
+ root="$(git rev-parse --show-toplevel 2>/dev/null)"
29
+ for candidate in "$(dirname "$HERE")/kryso/$1" "$root/.agents/skills/kryso/$1" "$HOME/.agents/skills/kryso/$1" \
30
+ "$root/.claude/skills/kryso/$1" "$HOME/.claude/skills/kryso/$1"; do
31
+ [[ -f "$candidate" ]] && { printf '%s' "$candidate"; return 0; }
32
+ done
33
+ return 1
34
+ }
35
+
36
+ # The styled-output module, found before the arguments are read so that the help and every
37
+ # failure before the preflight, a bad flag among them, are drawn on an attended run (#142). A
38
+ # copy without it still reads its arguments, and the preflight below names the missing module.
39
+ UI_SH="$(kryso_module ui.sh)" || UI_SH=""
40
+ # shellcheck source=/dev/null
41
+ [[ -z "$UI_SH" ]] || source "$UI_SH" || UI_SH="unsourced:$UI_SH"
42
+ # Without ui.sh nothing is attended, so every line is the plain one.
43
+ declare -F ui_err_attended > /dev/null || { ui_attended() { return 1; }; ui_err_attended() { return 1; }; }
44
+ # show_usage <subcommand>: the help, drawn in sections under the brand line on an attended
45
+ # stdout, or as written.
46
+ show_usage() {
47
+ if declare -F ui_help > /dev/null; then
48
+ UI_FD=1 UI_TTY=0 ui_brand "$1" help
49
+ usage | ui_help
50
+ else
51
+ usage
52
+ fi
53
+ }
54
+
55
+ MAX=""
56
+ SWEEPS=1
57
+ SWEEPS_SET=0
58
+ BUDGET=20
59
+ BUDGET_SET=0
60
+ LABEL=ready-for-agent
61
+ MODEL=""
62
+ EFFORT=""
63
+ KEEP_API_KEY=0
64
+ DRY_RUN=0
65
+ READ_ONLY=0
66
+ CI_CHECK=1
67
+ SECOND_READER=""
68
+ MCP=""
69
+ # The deepest the workflow queue may be before the preflight stops the shift: queued runs
70
+ # repo-wide, every workflow, not counting runs in progress. --ci-max-queued sets it, over
71
+ # KRYSO_CI_MAX_QUEUED, so a box with more runner instances can take a deeper queue. Empty until
72
+ # the settings are read, below the options.
73
+ CI_MAX_QUEUED=""
74
+ # The jobs fallback, for a repo whose runner list the token may not read. How many recent
75
+ # runs it opens looking for a self-hosted job, and how old the newest one it finds may be.
76
+ # A day is deliberately loose: it answers "a runner was alive and taking work recently",
77
+ # and the queue rule below is what catches a runner that has died since.
78
+ CI_RUN_READS=10
79
+ CI_JOB_MAX_AGE=86400
80
+ # How long a rate limit that names no reset, or a reset already past, is waited out before
81
+ # --wait says otherwise. The tests shorten it through KRYSO_WAIT_SECONDS, which a real shift
82
+ # never sets, because a reset stamped a few seconds ahead can pass on a loaded machine before
83
+ # the driver reads it.
84
+ WAIT_SECONDS=""
85
+ MAX_WAITS=3
86
+ # Each pass's allowance of active execution and the grace its processes get to exit once it
87
+ # runs out. SKILL.md's "The allowance" says what counts against it and what does not.
88
+ TIMEOUT=7200
89
+ GRACE=30
90
+ # How long the driver waits, once a pass's session has exited, for the receipts it left open to
91
+ # close before it judges the pass (playbook ADR 0009). Past it the pass is interrupted, and no
92
+ # sweep continues the issue while its receipt stays open.
93
+ RECEIPT_WAIT=1800
94
+ # How long one tracker call of the driver's own may take, and the grace its processes get. A pass
95
+ # has its allowance; the driver's reads before the shift and between passes have only this.
96
+ TRACKER_SECONDS="${SHIP_LOOP_TRACKER_SECONDS:-60}"
97
+ TRACKER_GRACE=5
98
+ EXTRA_ARGS=()
99
+ ISSUES=""
100
+ EPIC=""
101
+ NOTE=""
102
+ WORKFLOW=""
103
+ BASE=""
104
+ STACK=0
105
+ ENGINE=ship-it
106
+ # The stopped shifts whose owned worktrees this one takes over, by id, one per --adopt, and
107
+ # ADOPT their ids joined by a space, empty when there are none. A bare --adopt names none: the
108
+ # driver finds the shifts itself and runs a shift per selection. See SKILL.md's "Adopting a
109
+ # stopped shift".
110
+ ADOPTS=()
111
+ ADOPT=""
112
+ ADOPT_ALL=0
113
+ PROFILE=claude
114
+
115
+ usage() {
116
+ cat <<'USAGE'
117
+ Usage: kryso shift [options]
118
+ kryso integration <epic> <slug>
119
+
120
+ Queue:
121
+ --issues "A B" a queue of issue numbers in order, one pass each, in place of
122
+ the label
123
+ --epic N a queue of the epic's open, unassigned sub-issues, in
124
+ GitHub's order
125
+ --label LABEL the label that marks an issue ready for an agent (default
126
+ ready-for-agent)
127
+ --note TEXT an instruction every pass gets (needs a queue)
128
+ --workflow NAME the workflow every pass resolves from its base and records,
129
+ over each issue's workflow:<name> label (needs a queue). A
130
+ workflow:ralph label still wins. Under the ship-it engine a
131
+ pass whose workflow is not the default runs under the
132
+ script engine
133
+ --base BRANCH the base branch for the shift's passes (default the repo's
134
+ default branch, needs a queue)
135
+ --stack base each pass on the branch the pass before it reported
136
+ (needs a queue). Under --sweeps the chain follows the
137
+ tracker's blockers: a dependent enters the sweep on its
138
+ blocker's branch once the blocker is merge-ready
139
+ --adopt SHIFT take over the worktrees of the stopped shift SHIFT: write one
140
+ handoff line in each ledger, and continue each worktree under
141
+ this shift's engine in a fresh context. Needs a queue that
142
+ holds them, and the profile, model and effort SHIFT ran with.
143
+ Repeat it to adopt several shifts that ran one selection
144
+ --adopt with no shift id and an --issues queue: find the stopped
145
+ shifts that own the queue's worktrees, and run one shift per
146
+ selection they ran, in queue order. Then run the issues with
147
+ no worktree under this command's selection. A selection flag
148
+ you give must match every group, and a group takes its own
149
+ for a flag you leave out. --max and --sweeps bound each group
150
+
151
+ Bounds:
152
+ --max N the most distinct issues the shift admits (default 4, or the
153
+ queue's length with a queue)
154
+ --sweeps N the number of sweeps over an epic, or over a workset of two
155
+ or more issues. A sweep reads the tracker afresh and runs one
156
+ pass in a fresh session per admitted issue. A later sweep
157
+ continues only the worktrees this shift owns and can prove
158
+ resumable, and the shift stops early when nothing is left
159
+ --budget USD the dollar cap per run (default 20, for a profile that has
160
+ one)
161
+ --wait SECONDS how long to wait on a rate limit that names no reset (default
162
+ 1800)
163
+ --timeout SECS each pass's allowance of active execution (default 7200). A
164
+ rate-limit wait does not count against it. The retry gets
165
+ what is left, and a pass in a later sweep gets a new
166
+ allowance
167
+ --grace SECS how long a pass's processes get to exit between SIGTERM and
168
+ SIGKILL (default 30)
169
+ --receipt-wait SECS
170
+ how long a pass whose session exited with a receipt open
171
+ waits for it to close before the pass is judged (default
172
+ 1800). Past it the pass is interrupted, and no sweep
173
+ continues it while the receipt stays open
174
+
175
+ Host:
176
+ --profile NAME the execution profile, claude or codex (default claude)
177
+ --engine NAME ship-it (default) runs the /kryso skill through the profile.
178
+ script runs ship-pass.sh for each queued issue: its model
179
+ process is the build fork, and a red check or review feedback
180
+ starts a reconciliation context
181
+ --model MODEL the exact model id, in place of the profile's default
182
+ --effort LEVEL the reasoning effort (default the profile's, high for both
183
+ built-in profiles)
184
+ --api-key keep ANTHROPIC_API_KEY set for a Claude profile
185
+ --second-reader V
186
+ the second reader every pass runs with: off, on, jev or llm.
187
+ It wins over PLAYBOOK_SECOND_READER and kryso.secondReader
188
+ in git config (default off)
189
+ --mcp SERVERS the MCP servers every pass in this shift loads: on, off, or
190
+ a comma-separated list of names as claude mcp list prints
191
+ them. It wins over KRYSO_PASS_MCP and kryso.passMcp in git
192
+ config (default on)
193
+ -- <args> arguments for the host. Claude takes them as they are, such
194
+ as --setting-sources project,local. Codex takes only the
195
+ colour, image, thread-source, strict-config and
196
+ skip-git-repo-check options, because the profile sets every
197
+ other control
198
+
199
+ Checks:
200
+ --dry-run run the preflight, then print the candidates, the bounds and
201
+ the command, and spend nothing
202
+ --read-only with --dry-run, change nothing at all: name a stale
203
+ isolation file rather than remove it, and run with the
204
+ second reader off once its setting has been checked. The
205
+ stop lines and the exit are a plain dry run's
206
+ --no-ci-check skip the CI health check: run the shift with the runner
207
+ offline or the queue deep, and let a pass park at reconcile
208
+ --ci-max-queued N
209
+ the most queued workflow runs the CI check lets a shift start
210
+ behind. It wins over KRYSO_CI_MAX_QUEUED (default 3)
211
+ -h, --help print this help
212
+
213
+ Integration branches:
214
+ kryso integration <epic> <slug> makes integration/<epic>-<slug> on origin for
215
+ a shift's --base. It cuts the branch from origin's default branch with an
216
+ empty commit of its own and pushes it. A ruleset with no bypass then blocks
217
+ deleting integration/* there. It prints the branch's name, and does nothing
218
+ when origin has the branch.
219
+
220
+ The shift exits 0 when it stops by design, 1 when it stops on failures, 2
221
+ when it stops on a rate limit and 130 when INT or TERM interrupts it.
222
+ USAGE
223
+ }
224
+
225
+ # ---- integration branches ---------------------------------------------------------------
226
+ #
227
+ # An integration branch is integration/<epic>-<slug>, and ADR 0010 is how one survives the
228
+ # cleanups that took feat/ship-loop-124: a commit of its own, so `git branch --merged` never
229
+ # lists it, a copy on origin, and a repository ruleset with no bypass that blocks deleting
230
+ # integration/* there. The subcommand makes all three. The preflight fails a --base origin
231
+ # lacks and warns when an integration base has no such ruleset.
232
+ INTEGRATION_REF="refs/heads/integration/*"
233
+
234
+ # The driver's plain note and warning lines, defined here because the subcommand runs before
235
+ # the options are parsed.
236
+ note() { echo "ship-loop: $1"; }
237
+ warn() { echo "ship-loop: warning: $1" >&2; }
238
+
239
+ # on_origin <branch>: the branch's tip on origin and status 0, or status 2 when origin lacks it,
240
+ # or git's own status with its first line when origin cannot be read. Never a credential
241
+ # prompt, because nobody is there to answer one.
242
+ on_origin() {
243
+ local out code
244
+ out="$(GIT_TERMINAL_PROMPT=0 git ls-remote --exit-code --heads origin "refs/heads/$1" 2>&1)"; code=$?
245
+ if [[ "$code" -eq 0 ]]; then cut -f1 <<< "$out" | head -1; else head -1 <<< "$out"; fi
246
+ return "$code"
247
+ }
248
+
249
+ # no_rulesets <gh output>: status 0 when gh's refusal is the plan's, as GitHub words it to a
250
+ # free private repository, rather than a permission or a network failure.
251
+ no_rulesets() { [[ "$1" == *"Upgrade to GitHub"* || "$1" == *"make this repository public"* ]]; }
252
+
253
+ # integration_ruleset: RULESET_STATE, `present` when an active branch ruleset with no bypass
254
+ # actor blocks deletion on integration/*, `missing` when none does, `unavailable` when the
255
+ # repository's plan has no rulesets, and `unreadable` when gh failed for another reason, with
256
+ # gh's first line in RULESET_WHY. A ruleset with a bypass is not one, because everything that
257
+ # touches a repository like this runs as its admin, and nor is one whose bypass list GitHub
258
+ # left out, because an absent list is unknown, not empty. A list or a ruleset that cannot be
259
+ # read is unreadable rather than missing, so the subcommand never writes a second ruleset over
260
+ # one it failed to see.
261
+ integration_ruleset() {
262
+ local list ids id detail
263
+ RULESET_STATE=missing; RULESET_WHY=""
264
+ if ! list="$(gh api --paginate 'repos/{owner}/{repo}/rulesets' 2>&1)"; then
265
+ RULESET_WHY="$(head -1 <<< "$list")"
266
+ if no_rulesets "$list"; then RULESET_STATE=unavailable; else RULESET_STATE=unreadable; fi
267
+ return 0
268
+ fi
269
+ if ! ids="$(jq -r '.[]? | select(.target == "branch" and .enforcement == "active") | .id' <<< "$list" 2>/dev/null)"; then
270
+ RULESET_STATE=unreadable; RULESET_WHY="gh api returned something other than JSON for the rulesets"
271
+ return 0
272
+ fi
273
+ for id in $ids; do
274
+ if ! detail="$(gh api "repos/{owner}/{repo}/rulesets/$id" 2>&1)"; then
275
+ RULESET_STATE=unreadable; RULESET_WHY="$(head -1 <<< "$detail")"
276
+ return 0
277
+ fi
278
+ if ! jq -e 'type == "object"' <<< "$detail" >/dev/null 2>&1; then
279
+ RULESET_STATE=unreadable; RULESET_WHY="gh api returned something other than JSON for ruleset $id"
280
+ return 0
281
+ fi
282
+ # An exclusion counts against the ruleset unless it plainly names no integration branch: a
283
+ # literal ref outside integration/, or the default branch. A pattern could cover one.
284
+ if jq -e --arg p "$INTEGRATION_REF" '
285
+ (has("bypass_actors") and (.bypass_actors | length == 0))
286
+ and any(.rules[]?; .type == "deletion")
287
+ and any(.conditions.ref_name.include[]?; . == $p or . == "~ALL")
288
+ and all(.conditions.ref_name.exclude[]?;
289
+ . == "~DEFAULT_BRANCH"
290
+ or ((test("[*?\\[]") | not) and (startswith("refs/heads/integration/") | not)))' <<< "$detail" >/dev/null 2>&1; then
291
+ RULESET_STATE=present
292
+ return 0
293
+ fi
294
+ done
295
+ }
296
+
297
+ # integration_main <epic> <slug>: the subcommand. Notes go to stderr and the branch's name alone
298
+ # to stdout, so `--base "$(ship-loop.sh integration 124 ship-loop)"` reads it. A branch already
299
+ # on origin is left as it is. A local branch origin lacks is refused rather than pushed or
300
+ # replaced, because whether it holds the epic's work is a person's call.
301
+ integration_fail() {
302
+ if ui_err_attended; then ui_error "$1"; else echo "integration: $1" >&2; fi
303
+ exit 1
304
+ }
305
+ # integration_say <message> [kind]: a note on stderr, as a mark line when stderr is attended.
306
+ integration_say() {
307
+ if ui_err_attended; then ( UI_FD=2 UI_TTY=1; "ui_${2:-ok}" "$1" )
308
+ elif [[ "${2:-}" == warn ]]; then warn "$1"
309
+ else echo "integration: $1" >&2; fi
310
+ }
311
+ integration_main() {
312
+ if [[ $# -ne 2 || "${1:-}" == -h || "${1:-}" == --help ]]; then
313
+ if [[ "${1:-}" == -h || "${1:-}" == --help ]]; then
314
+ if ui_err_attended; then echo "Usage: kryso integration <epic> <slug>" | ( exec 1>&2; UI_FD=1 UI_TTY=1 ui_brand integration help; ui_help ); else echo "Usage: kryso integration <epic> <slug>" >&2; fi
315
+ exit 0
316
+ fi
317
+ if ui_err_attended; then ui_error "integration takes an epic and a slug" "kryso integration <epic> <slug>, such as kryso integration 124 ship-loop"
318
+ else echo "Usage: kryso integration <epic> <slug>" >&2; fi
319
+ exit 1
320
+ fi
321
+ ! ui_err_attended || ( UI_FD=2 UI_TTY=1 ui_brand integration "$1-$2" )
322
+ local epic="$1" slug="$2" name tip code default start sha out
323
+ [[ "$epic" =~ ^[0-9]+$ ]] || integration_fail "the epic is an issue number, got '$epic'"
324
+ [[ "$slug" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ ]] || integration_fail "the slug is lowercase words joined by hyphens, got '$slug'"
325
+ name="integration/$epic-$slug"
326
+ command -v gh >/dev/null 2>&1 || integration_fail "gh is not installed, and the ruleset needs it"
327
+ command -v jq >/dev/null 2>&1 || integration_fail "jq is not installed"
328
+ git rev-parse --show-toplevel >/dev/null 2>&1 || integration_fail "not a git repository"
329
+ cd "$(git rev-parse --show-toplevel)" || integration_fail "cannot enter the repository's root"
330
+
331
+ tip="$(on_origin "$name")"; code=$?
332
+ if [[ "$code" -eq 0 ]]; then
333
+ integration_say "$name is already on origin at ${tip:0:12}, nothing to cut" info
334
+ else
335
+ [[ "$code" -eq 2 ]] || integration_fail "cannot read origin: $tip"
336
+ ! git show-ref --verify -q "refs/heads/$name" \
337
+ || integration_fail "$name exists locally but not on origin. Push it with git push -u origin $name if it holds the epic's work, or delete it, then run this again"
338
+ default="$(gh repo view --json defaultBranchRef --jq .defaultBranchRef.name 2>/dev/null)"
339
+ [[ -n "$default" ]] || default="$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's#^origin/##')"
340
+ [[ -n "$default" ]] || integration_fail "cannot read the repository's default branch"
341
+ out="$(GIT_TERMINAL_PROMPT=0 git fetch -q origin "+refs/heads/$default:refs/remotes/origin/$default" 2>&1)" \
342
+ || integration_fail "cannot fetch $default from origin: $(head -1 <<< "$out")"
343
+ start="$(git rev-parse "refs/remotes/origin/$default")"
344
+ sha="$(git commit-tree "$start^{tree}" -p "$start" -m "chore: open integration branch $name" 2>&1)" \
345
+ || integration_fail "cannot write the branch's own commit: $(head -1 <<< "$sha")"
346
+ out="$(GIT_TERMINAL_PROMPT=0 git push -q origin "$sha:refs/heads/$name" 2>&1)" \
347
+ || integration_fail "cannot push $name to origin: $(head -1 <<< "$out")"
348
+ git fetch -q origin "+refs/heads/$name:refs/remotes/origin/$name" >/dev/null 2>&1 \
349
+ && git branch -q --track "$name" "refs/remotes/origin/$name" >/dev/null 2>&1 \
350
+ || integration_say "$name is on origin, but git could not make the local branch that tracks it" warn
351
+ integration_say "cut $name from origin/$default at ${start:0:12}, one empty commit ${sha:0:12} of its own, pushed"
352
+ fi
353
+
354
+ integration_ruleset
355
+ case "$RULESET_STATE" in
356
+ present) integration_say "a ruleset already blocks deletion of integration/* on origin, with no bypass" info ;;
357
+ unavailable) integration_say "$name can be deleted on origin: this repository's plan has no rulesets ($RULESET_WHY)" warn ;;
358
+ unreadable) integration_fail "cannot read the repository's rulesets, so nothing stops $name being deleted on origin: $RULESET_WHY" ;;
359
+ missing)
360
+ if out="$(jq -n --arg p "$INTEGRATION_REF" \
361
+ '{name: "integration branches", target: "branch", enforcement: "active", bypass_actors: [],
362
+ conditions: {ref_name: {include: [$p], exclude: []}}, rules: [{type: "deletion"}]}' \
363
+ | gh api -X POST 'repos/{owner}/{repo}/rulesets' --input - 2>&1)"; then
364
+ integration_say "added a ruleset blocking deletion of integration/* on origin, with no bypass"
365
+ elif no_rulesets "$out"; then
366
+ integration_say "$name can be deleted on origin: this repository's plan has no rulesets ($(head -1 <<< "$out"))" warn
367
+ else
368
+ integration_fail "cannot add the ruleset that stops $name being deleted on origin: $(head -1 <<< "$out")"
369
+ fi ;;
370
+ esac
371
+ printf '%s\n' "$name"
372
+ }
373
+
374
+ if [[ "${1:-}" == integration ]]; then
375
+ shift
376
+ integration_main "$@"
377
+ exit 0
378
+ fi
379
+
380
+ # The arguments as given, which a bare --adopt hands on to the shift it runs for each group.
381
+ ARGV=("$@")
382
+ while [[ $# -gt 0 ]]; do
383
+ case "$1" in
384
+ --max) MAX="$2"; shift 2 ;;
385
+ --sweeps) SWEEPS="$2"; SWEEPS_SET=1; shift 2 ;;
386
+ --profile) PROFILE="$2"; shift 2 ;;
387
+ --budget) BUDGET="$2"; BUDGET_SET=1; shift 2 ;;
388
+ --label) LABEL="$2"; shift 2 ;;
389
+ --model) MODEL="$2"; shift 2 ;;
390
+ --effort) EFFORT="$2"; shift 2 ;;
391
+ --api-key) KEEP_API_KEY=1; shift ;;
392
+ --wait) WAIT_SECONDS="$2"; shift 2 ;;
393
+ --timeout) TIMEOUT="$2"; shift 2 ;;
394
+ --grace) GRACE="$2"; shift 2 ;;
395
+ --receipt-wait) RECEIPT_WAIT="$2"; shift 2 ;;
396
+ --issues) ISSUES="$2"; shift 2 ;;
397
+ --epic) EPIC="$2"; shift 2 ;;
398
+ --note) NOTE="$2"; shift 2 ;;
399
+ --workflow) WORKFLOW="$2"; shift 2 ;;
400
+ --base) BASE="$2"; shift 2 ;;
401
+ --stack) STACK=1; shift ;;
402
+ --engine) ENGINE="$2"; shift 2 ;;
403
+ --adopt) if [[ $# -ge 2 && "$2" != -* ]]; then ADOPTS+=("$2"); shift 2; else ADOPT_ALL=1; shift; fi ;;
404
+ --second-reader) SECOND_READER="$2"; shift 2 ;;
405
+ --mcp) MCP="$2"; shift 2 ;;
406
+ --dry-run) DRY_RUN=1; shift ;;
407
+ --read-only) READ_ONLY=1; shift ;;
408
+ --no-ci-check) CI_CHECK=0; shift ;;
409
+ --ci-max-queued) CI_MAX_QUEUED="$2"; shift 2 ;;
410
+ -h|--help) show_usage shift; exit 0 ;;
411
+ --) shift; EXTRA_ARGS=("$@"); break ;;
412
+ *) if ui_err_attended; then ui_error "unknown option $1" "kryso shift --help lists the options"
413
+ else echo "ship-loop: unknown option $1" >&2; usage >&2; fi
414
+ exit 1 ;;
415
+ esac
416
+ done
417
+
418
+ # die <message> [hint [joiner]]: the preflight's failure, on stderr in both modes, and exit 1.
419
+ # The hint is the way out, usually a `pass --flag`, and plain output joins it to the message as
420
+ # one line. The joiner is for a hint that continues the message's sentence. On an attended
421
+ # stderr the message drops its prefix and prints under an ERROR pill, the hint under a HINT
422
+ # pill, from the first argument check on, since ui.sh is found before them (#142). Only a
423
+ # failure with no ui.sh to draw it is plain on a terminal. A later sweep's snapshot is the one
424
+ # read past the preflight that dies, and it closes the shift as failed instead, because the
425
+ # passes already run have a summary to leave.
426
+ RESNAPSHOT=0
427
+ die() {
428
+ local plain="$1${2:+${3:-. }$2}"
429
+ if [[ "$RESNAPSHOT" -eq 1 ]]; then
430
+ STOP_KIND=tracker; stop_reason="sweep $((SWEPT + 1)) has no snapshot: $plain"; exit_code=1
431
+ # The passes before it ran, so the workflow's end stages still run once after the last.
432
+ [[ "${pass:-0}" -eq 0 ]] || run_shift_stages end
433
+ close_shift
434
+ exit 1
435
+ fi
436
+ if ui_err_attended; then
437
+ ui_error "$1" "${2:-}"
438
+ exit 1
439
+ fi
440
+ echo "preflight: $plain" >&2
441
+ exit 1
442
+ }
443
+
444
+ # The evidence module lives beside ship-it, whose record the ledger is. It is looked for here,
445
+ # before the settings are read, because the rule for their old names is the module's. A copy of
446
+ # ship-loop without it is a broken install, which the preflight names in its place below.
447
+ LEDGER_SH="$(kryso_module ledger.sh)" || LEDGER_SH=""
448
+ # shellcheck source=/dev/null
449
+ if [[ -n "$LEDGER_SH" ]] && source "$LEDGER_SH"; then
450
+ # The settings a person puts in the environment, by their KRYSO_ names, an old SHIP_LOOP_
451
+ # name read for one with a warning. The flags win over them.
452
+ _ledger_settings ship-loop
453
+ else LEDGER_SH=""; fi
454
+ # ledger_text <wt>: the fields of a read that the ledger file alone decides. A module older than
455
+ # this driver has no text verb, and its read prints the same fields beside the rest, at a
456
+ # read's cost, so the driver asks it for a read instead.
457
+ if declare -F _ledger_text > /dev/null; then ledger_text() { ledger text "$@"; }; else ledger_text() { ledger read "$@"; }; fi
458
+ [[ -n "$CI_MAX_QUEUED" ]] || CI_MAX_QUEUED="${KRYSO_CI_MAX_QUEUED:-3}"
459
+ [[ -n "$WAIT_SECONDS" ]] || WAIT_SECONDS="${KRYSO_WAIT_SECONDS:-1800}"
460
+ PROFILE_FILE="${KRYSO_PROFILE_FILE:-}"
461
+ # The report hook: where each pass's report goes and the bearer token it carries, read from
462
+ # the environment alone. SKILL.md says why it is never a flag or a file. Unset means nothing
463
+ # is sent and nothing is said. A failed push is retried once after this many seconds. The
464
+ # tests shorten the wait through KRYSO_REPORT_RETRY_SECONDS, which a real shift never sets.
465
+ REPORT_URL="${KRYSO_REPORT_URL:-}"
466
+ REPORT_TOKEN="${KRYSO_REPORT_TOKEN:-}"
467
+ REPORT_RETRY_SECONDS="${KRYSO_REPORT_RETRY_SECONDS:-5}"
468
+ [[ "$REPORT_RETRY_SECONDS" =~ ^[0-9]+(\.[0-9]+)?$ ]] || REPORT_RETRY_SECONDS=5
469
+
470
+ # Runner liveness for a token that may not list the runners. Listing them is the direct read
471
+ # and the only one that reports live status, but it needs admin on the repository, which a
472
+ # write collaborator on someone else's repo does not have however many runners they registered
473
+ # or host themselves. What write can read is the work a runner did: every job carries the
474
+ # runner_name that took it and the labels it was queued for. A self-hosted job that started
475
+ # recently is a runner that was alive recently, which is close enough to the question the shift
476
+ # needs answered, and the queue rule that follows is what catches a runner that has died since.
477
+ #
478
+ # Prints the health line and returns 0, or prints the reason and returns 1, with the hint on a
479
+ # second line where there is a way out to name, so the caller hands die the two apart. It never
480
+ # calls die, because the caller reads it through a command substitution, where an exit would
481
+ # end the subshell and let the shift carry on past a failed check.
482
+ ci_health_from_jobs() {
483
+ local runs ids id jobs found name age
484
+ runs="$(gh run list --limit "$CI_RUN_READS" --json databaseId 2>&1)" || {
485
+ echo "cannot read the workflow runs to judge runner health: $(head -1 <<< "$runs")"; return 1; }
486
+ ids="$(jq -r '.[].databaseId' <<< "$runs" 2>/dev/null)" || {
487
+ echo "gh run list returned something other than JSON while judging runner health"; return 1; }
488
+ [[ -n "$ids" ]] || {
489
+ echo "this repo's workflows target self-hosted, this token cannot read the runner list, and no workflow run shows a runner at work"
490
+ echo "Run one, or pass --no-ci-check to let passes park at reconcile"; return 1; }
491
+ while read -r id; do
492
+ [[ -n "$id" ]] || continue
493
+ # A run whose jobs cannot be read is passed over, but a silence is not, because the next run's
494
+ # read would only wait it out again.
495
+ jobs="$(gh api "repos/{owner}/{repo}/actions/runs/$id/jobs" 2>/dev/null)" || {
496
+ [[ "$?" -eq 124 ]] || continue
497
+ echo "cannot read a workflow run's jobs to judge runner health: gh did not answer within ${TRACKER_SECONDS}s"; return 1; }
498
+ # The freshest self-hosted job in this run that actually reached a runner. A skipped job
499
+ # carries the labels but no runner_name, so it says nothing about a runner being up.
500
+ found="$(jq -r '
501
+ [ .jobs[]?
502
+ | select(.runner_name != null)
503
+ | select([.labels[]?] | index("self-hosted"))
504
+ | { name: .runner_name, age: (now - ((.completed_at // .started_at) | fromdateiso8601)) } ]
505
+ | sort_by(.age) | .[0] // empty
506
+ | "\(.name)\t\(.age | floor)"' <<< "$jobs" 2>/dev/null)"
507
+ [[ -n "$found" ]] || continue
508
+ name="${found%%$'\t'*}"; age="${found##*$'\t'}"
509
+ [[ "$age" -ge 0 ]] 2>/dev/null || age=0
510
+ if [[ "$age" -le "$CI_JOB_MAX_AGE" ]]; then
511
+ echo "self-hosted runner '$name' took a job $(( age / 60 ))m ago (the runner list needs admin, which this token lacks)"
512
+ return 0
513
+ fi
514
+ echo "the newest self-hosted job reached runner '$name' $(( age / 3600 ))h ago, longer than the $(( CI_JOB_MAX_AGE / 3600 ))h this check allows, and the runner list needs admin, so this check cannot read the runner's live status"
515
+ echo "Check the runner, or pass --no-ci-check to let passes park at reconcile"
516
+ return 1
517
+ done <<< "$ids"
518
+ echo "none of the last $CI_RUN_READS workflow runs reached a self-hosted runner, and the runner list needs admin, so this check cannot read the runner's live status"
519
+ echo "Check the runner, or pass --no-ci-check to let passes park at reconcile"
520
+ return 1
521
+ }
522
+
523
+ # The queue is an ordered list of issue numbers, given outright or read off an epic once the
524
+ # tracker is known to be reachable. With one, the shift's length is the queue's unless --max
525
+ # caps it, and every pass is told its issue, its base and the note.
526
+ QUEUE=()
527
+ HAS_QUEUE=0
528
+ [[ -n "$ISSUES" || -n "$EPIC" ]] && HAS_QUEUE=1
529
+ [[ -z "$ISSUES" || -z "$EPIC" ]] || die "--issues and --epic are both queues, so pass one of them"
530
+ if [[ -n "$ISSUES" ]]; then
531
+ read -r -a QUEUE <<< "$ISSUES"
532
+ [[ "${#QUEUE[@]}" -gt 0 ]] || die "--issues is empty"
533
+ for n in "${QUEUE[@]}"; do
534
+ [[ "$n" =~ ^[0-9]+$ ]] || die "--issues takes issue numbers separated by spaces, got '$n'"
535
+ done
536
+ fi
537
+ [[ -z "$EPIC" || "$EPIC" =~ ^[0-9]+$ ]] || die "--epic takes an issue number, got '$EPIC'"
538
+ [[ "$HAS_QUEUE" -eq 1 || -z "$NOTE" ]] || die "--note needs a queue (--issues or --epic)"
539
+ [[ "$HAS_QUEUE" -eq 1 || -z "$WORKFLOW" ]] || die "--workflow needs a queue (--issues or --epic)"
540
+ # The engine a pass runs under is the shift's, but for a ralph issue under ship-it.
541
+ SHIFT_ENGINE="$ENGINE"
542
+ [[ "$HAS_QUEUE" -eq 1 || -z "$BASE" ]] || die "--base needs a queue (--issues or --epic)"
543
+ [[ "$HAS_QUEUE" -eq 1 || "$STACK" -eq 0 ]] || die "--stack needs a queue (--issues or --epic)"
544
+ [[ "$ENGINE" == ship-it || "$ENGINE" == script ]] || die "--engine takes ship-it or script, got '$ENGINE'"
545
+ [[ "$HAS_QUEUE" -eq 1 || "$ENGINE" == ship-it ]] || die "--engine script needs a queue (--issues or --epic), because the pass script takes one issue"
546
+ for id in ${ADOPTS[@]+"${ADOPTS[@]}"}; do
547
+ [[ "$id" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || die "--adopt takes a shift id, the name of a directory under .claude/kryso, got '$id'"
548
+ done
549
+ ADOPT="${ADOPTS[*]-}"
550
+ [[ -z "$ADOPT" && "$ADOPT_ALL" -eq 0 || "$HAS_QUEUE" -eq 1 ]] || die "--adopt needs a queue (--issues or --epic), and takes over only the worktrees in its scope"
551
+ [[ -z "$ADOPT" || "$ADOPT_ALL" -eq 0 ]] || die "--adopt takes shift ids or none, so pass a bare --adopt or name each shift"
552
+ [[ "$ADOPT_ALL" -eq 0 || -n "$ISSUES" ]] || die "a bare --adopt reads which shifts own the queue's worktrees before the tracker is read, so it needs --issues rather than --epic"
553
+
554
+ [[ -z "$MAX" || "$MAX" =~ ^[0-9]+$ ]] || die "--max must be a whole number, got '$MAX'"
555
+ # A sweep is a live eligibility check over an epic's children or a workset, so it needs one
556
+ # of those, and a workset of one issue is a pass, not a sweep. Everything here is decided
557
+ # before the preflight, so a bad value costs no gh call and no model start. --stack under
558
+ # --sweeps is the dependency-driven chain the stack section below builds, not the
559
+ # pass-after-pass chain of a plain queue.
560
+ if [[ "$SWEEPS_SET" -eq 1 ]]; then
561
+ [[ "$SWEEPS" =~ ^[0-9]+$ && "$SWEEPS" -gt 0 ]] || die "--sweeps must be a positive whole number, got '$SWEEPS'"
562
+ distinct=0
563
+ [[ "${#QUEUE[@]}" -eq 0 ]] || distinct="$(printf '%s\n' "${QUEUE[@]}" | sort -u | wc -l | tr -d ' ')"
564
+ [[ -n "$EPIC" || "$distinct" -ge 2 ]] || die "--sweeps needs an epic or a workset of at least two issues (--epic N, or --issues with two or more numbers)"
565
+ fi
566
+ # The stacked sweep: --stack with --sweeps. The two flags together mean the dependency
567
+ # chain, and the sequential chain of a plain --stack queue does not apply.
568
+ STACKED_SWEEPS=0
569
+ [[ "$STACK" -eq 1 && "$SWEEPS_SET" -eq 1 ]] && STACKED_SWEEPS=1
570
+ [[ "$CI_MAX_QUEUED" =~ ^[0-9]+$ ]] || die "--ci-max-queued must be a whole number, got '$CI_MAX_QUEUED'"
571
+ [[ "$WAIT_SECONDS" =~ ^[0-9]+$ ]] || die "--wait must be a whole number of seconds, got '$WAIT_SECONDS'"
572
+ [[ "$BUDGET" =~ ^[0-9]+(\.[0-9]+)?$ ]] || die "--budget must be a whole number or a decimal in dollars, got '$BUDGET'"
573
+ # A read-only dry run changes nothing, so kryso doctor can run it (ADR 0044). The ledger module
574
+ # reads KRYSO_READ_ONLY and keeps a stale isolation file, and second_reader_resolve turns the
575
+ # reader off once the configured value has passed its check.
576
+ [[ "$READ_ONLY" -eq 0 || "$DRY_RUN" -eq 1 ]] || die "--read-only makes a dry run read-only, so it needs --dry-run"
577
+ [[ "$READ_ONLY" -eq 0 ]] || export KRYSO_READ_ONLY=1
578
+
579
+ # ---- preflight ------------------------------------------------------------------------
580
+
581
+ # The readers for a saved result are sourced from beside this script, so a copy without
582
+ # result.sh next to it is a broken install, and the preflight says so before anything else.
583
+ # shellcheck source-path=SCRIPTDIR
584
+ # shellcheck source=result.sh
585
+ source "$HERE/result.sh" || die "cannot source $HERE/result.sh"
586
+ # The reading of a PR's review feedback, shared with the pass script.
587
+ source "$HERE/feedback.sh" || die "cannot source $HERE/feedback.sh"
588
+ # The merge-ready read, shared with the pass script, whose merge makes it under its own rule.
589
+ source "$HERE/merge-ready.sh" || die "cannot source $HERE/merge-ready.sh"
590
+ command -v jq >/dev/null 2>&1 || die "jq is not installed, and every result is JSON"
591
+ # shellcheck source-path=SCRIPTDIR
592
+ # shellcheck source=runner.sh
593
+ source "$HERE/runner.sh" || die "cannot source $HERE/runner.sh"
594
+ # shellcheck source-path=SCRIPTDIR
595
+ # shellcheck source=deadline.sh
596
+ source "$HERE/deadline.sh" || die "cannot source $HERE/deadline.sh"
597
+ # The second reader's module owns its switch: the values it takes and the order of the flag,
598
+ # the environment and git config. Sourced, it defines functions and nothing else.
599
+ # shellcheck source-path=SCRIPTDIR
600
+ # shellcheck source=reader.sh
601
+ source "$HERE/reader.sh" || die "cannot source $HERE/reader.sh"
602
+ deadline_valid "$TIMEOUT" || die "--timeout must be a positive whole number of seconds, got '$TIMEOUT'"
603
+ deadline_valid "$GRACE" || die "--grace must be a positive whole number of seconds, got '$GRACE'"
604
+ [[ "$RECEIPT_WAIT" =~ ^[0-9]+$ ]] || die "--receipt-wait must be a whole number of seconds, got '$RECEIPT_WAIT'"
605
+ deadline_valid "$TRACKER_SECONDS" || die "SHIP_LOOP_TRACKER_SECONDS must be a positive whole number of seconds, got '$TRACKER_SECONDS'"
606
+
607
+ # gh and gh_binary: every tracker call the driver makes from here on, its own and feedback.sh's, under
608
+ # TRACKER_SECONDS, because a call that never returns would hang the shift. A call that runs out is
609
+ # stopped with everything it started and is one that failed: status 124, no output, its reason on
610
+ # stderr, and a line in the shift log once there is one, since most callers drop stderr. The
611
+ # output is held back until the call has ended, so half an answer never reaches a reader and
612
+ # nothing the call left behind can hold a command substitution open. It is a function over the
613
+ # binary, so no call site can be added outside the limit, and a test for the binary is `type -P
614
+ # gh`. The pass script is a process of its own and never sees it: its calls are inside its
615
+ # allowance.
616
+ gh_binary() { local dir="$1"; shift; exec gh "$@" > "$dir/out" 2> "$dir/err"; }
617
+ gh() {
618
+ local dir code call
619
+ dir="$(mktemp -d)" || return 1
620
+ # In a subshell with its output dropped, because what bash says while it starts and stops the
621
+ # call, such as a lost setpgid race on a loaded machine, is not gh's answer, so only gh writes
622
+ # to the files a caller reads. A read holds no authority, so no --active check is given.
623
+ ( deadline_run "$TRACKER_SECONDS" "$TRACKER_GRACE" "$dir/report" gh_binary "$dir" "$@" ) > /dev/null 2>&1
624
+ code=$?
625
+ if [[ "$code" -eq 124 ]]; then
626
+ call="$(tr -s '[:space:]' ' ' <<< "gh $*" | cut -c1-120 | sed 's/ $//')"
627
+ echo "gh did not answer within ${TRACKER_SECONDS}s: $call" >&2
628
+ [[ -z "${SHIFT_LOG:-}" ]] || printf '%s pass=%s tracker=timeout after=%ss %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${pass:-0}" "$TRACKER_SECONDS" "$call" >> "$SHIFT_LOG"
629
+ else
630
+ cat "$dir/out" 2>/dev/null
631
+ cat "$dir/err" >&2 2>/dev/null
632
+ fi
633
+ rm -rf "$dir"
634
+ return "$code"
635
+ }
636
+
637
+ # die_if_silent <status> <what>: dies when the tracker call that left the status ran out of its
638
+ # time, so the reason is the silence and not what an answer would have meant. Like die, it ends
639
+ # only the shell it runs in, so it is never called from a command substitution.
640
+ die_if_silent() { [[ "$1" -ne 124 ]] || die "gh did not answer within ${TRACKER_SECONDS}s, reading $2"; }
641
+
642
+ # read_name_with_owner: the repo's owner/name, for every caller that addresses the repo by
643
+ # name: the epic and workset GraphQL queries, the PR feedback reads and the report. gh answers
644
+ # first, the answer the pass script reads too, so the driver, its pass and the rest of the
645
+ # tracker address one repo. With no gh on PATH, or a gh that cannot place the repo, it is read
646
+ # off the origin remote's configured URL, raw rather than through get-url, so a report still
647
+ # names its repo. Prints owner/name with status 0, or nothing with 124 when gh ran out of time,
648
+ # so the caller can name the silence, and 1 when neither source holds an owner and a name. It
649
+ # never dies, so a command substitution can read it.
650
+ read_name_with_owner() {
651
+ local nwo code
652
+ if type -P gh >/dev/null; then
653
+ nwo="$(gh repo view --json nameWithOwner --jq .nameWithOwner 2>/dev/null)"; code=$?
654
+ [[ "$code" -ne 124 ]] || return 124
655
+ if [[ "$code" -eq 0 && "$nwo" =~ ^[^/]+/[^/]+$ ]]; then printf '%s\n' "$nwo"; return 0; fi
656
+ fi
657
+ nwo="$(git config --get remote.origin.url 2>/dev/null | sed -E 's#\.git/?$##; s#/+$##' | awk -F'[:/]' 'NF >= 2 {print $(NF-1) "/" $NF}')"
658
+ [[ "$nwo" =~ ^[^/]+/[^/]+$ ]] || return 1
659
+ printf '%s\n' "$nwo"
660
+ }
661
+ # A person's own defaults, from ~/.kryso/config.json: each of profile, model, effort and budget
662
+ # that no flag gives is taken from the file, and a flag wins over it. MEMBER_LINE is the
663
+ # opening's sentence for what came from where. A repository's own config never sets them:
664
+ # runner_repo_config refuses one that tries.
665
+ MEMBER_LINE=""
666
+ # flag_given <flag>: the flag is on the command line, before any `--`.
667
+ flag_given() {
668
+ local a
669
+ for a in ${ARGV[@]+"${ARGV[@]}"}; do
670
+ [[ "$a" != -- ]] || return 1
671
+ [[ "$a" != "$1" && "$a" != "$1="* ]] || return 0
672
+ done
673
+ return 1
674
+ }
675
+ member_defaults() {
676
+ local name value from="" over=()
677
+ runner_member_defaults || exit 1
678
+ [[ "$RUNNER_MEMBER" != '{}' ]] || return 0
679
+ for name in profile model effort budget; do
680
+ value="$(jq -r --arg k "$name" '.[$k] // empty' <<< "$RUNNER_MEMBER")"
681
+ [[ -n "$value" ]] || continue
682
+ if flag_given "--$name"; then over+=("--$name"); continue; fi
683
+ case "$name" in
684
+ profile) PROFILE="$value" ;;
685
+ model) MODEL="$value" ;;
686
+ effort) EFFORT="$value" ;;
687
+ budget) BUDGET="$value"; BUDGET_SET=1 ;;
688
+ esac
689
+ from+="${from:+, }$name $value"
690
+ done
691
+ [[ -n "$from" || "${#over[@]}" -gt 0 ]] || return 0
692
+ local flags="" verb=wins
693
+ if [[ "${#over[@]}" -gt 0 ]]; then
694
+ flags="$(_runner_and_list "${over[@]}")"
695
+ [[ "${#over[@]}" -eq 1 ]] || verb=win
696
+ fi
697
+ if [[ -z "$from" ]]; then MEMBER_LINE="$flags $verb over $RUNNER_MEMBER_CONFIG_NAME"
698
+ else MEMBER_LINE="your defaults come from $RUNNER_MEMBER_CONFIG_NAME: $from${flags:+, and $flags $verb over the file}"; fi
699
+ }
700
+ member_defaults
701
+ runner_profile_load "$PROFILE" "$PROFILE_FILE" || exit 1
702
+ [[ -n "$EFFORT" ]] || EFFORT="$RUNNER_EFFORT"
703
+ runner_validate_options "$BUDGET_SET" "$BUDGET" "$KEEP_API_KEY" "$EFFORT" || exit 1
704
+ runner_validate_extra_args ${EXTRA_ARGS[@]+"${EXTRA_ARGS[@]}"} || exit 1
705
+ # The script engine is the pass script beside this one, so a copy without it is the same kind
706
+ # of broken install.
707
+ [[ "$ENGINE" == ship-it || -f "$PASS_SCRIPT" ]] || die "--engine script needs $PASS_SCRIPT beside this script"
708
+
709
+ git rev-parse --show-toplevel >/dev/null 2>&1 || die "not a git repository"
710
+ REPO_ROOT="$(git rev-parse --show-toplevel)"
711
+ cd "$REPO_ROOT" || die "cannot enter $REPO_ROOT"
712
+
713
+ # The second reader every pass runs with, resolved once by `reader mode`, which owns the values
714
+ # and their order: the flag over PLAYBOOK_SECOND_READER over kryso.secondReader in git config
715
+ # over off, with `on` read as jev. A value outside the set stops the shift here, before any
716
+ # pass, whichever source it came from. The flag is exported, so a /kryso session or a pass
717
+ # script started here reads the same value. Unset, nothing is exported and nothing prints: a
718
+ # child resolves the environment and the config as it always did.
719
+ SECOND_READER_VALUE=""
720
+ SECOND_READER_SOURCE=""
721
+ second_reader_resolve() {
722
+ local value where source name=kryso.secondReader
723
+ reader mode "$REPO_ROOT" "$SECOND_READER" > /dev/null 2>&1
724
+ value="$READER_MODE_VALUE"
725
+ case "$READER_MODE_SOURCE" in
726
+ unset) return 0 ;;
727
+ --second-reader) where="from --second-reader"; source="$where $value" ;;
728
+ PLAYBOOK_SECOND_READER) where="from PLAYBOOK_SECOND_READER"; source="$where=$value" ;;
729
+ kryso.secondReader|playbook.secondReader) name="$READER_MODE_SOURCE"; where="in git config"; source="from $name=$value $where" ;;
730
+ *) die "reader.sh could not read the second reader's switch in $REPO_ROOT" ;;
731
+ esac
732
+ [[ -n "$READER_MODE" ]] || die "$name is '$value' $where, not $READER_MODE_ALLOWED"
733
+ SECOND_READER_VALUE="$READER_MODE"
734
+ SECOND_READER_SOURCE="$source"
735
+ [[ -z "$SECOND_READER" ]] || export PLAYBOOK_SECOND_READER="$SECOND_READER"
736
+ # Checked as a plain dry run checks it, so the stop is the same, and then off.
737
+ [[ "$READ_ONLY" -eq 0 ]] || { SECOND_READER_VALUE=off; SECOND_READER_SOURCE="from --read-only"; export PLAYBOOK_SECOND_READER=off; }
738
+ }
739
+ second_reader_resolve
740
+
741
+ # The repository's .kryso/config.json, as the checkout holds it, for the two settings below. A
742
+ # file that sets a person's own model, effort or budget stops the shift here.
743
+ runner_repo_config "$REPO_ROOT" || exit 1
744
+ # MCP servers for every pass: --mcp over KRYSO_PASS_MCP over mcp in .kryso/config.json over
745
+ # kryso.passMcp in git config, on unless one of them says off or names the servers to keep. A
746
+ # name the host does not have stops the shift here, before any claim. The flag is exported, so
747
+ # a pass script started here and the runner's own reads take the same value.
748
+ [[ -z "$MCP" ]] || { export KRYSO_PASS_MCP="$MCP"; RUNNER_PASS_MCP_FLAG=--mcp; }
749
+ runner_pass_mcp "$REPO_ROOT" || exit 1
750
+ # The skills every Claude pass lists, from skills in .kryso/config.json, else kryso.passSkills in
751
+ # git config: the pass skills unless the repo adds some or says all. A name no skill folder or
752
+ # plugin carries stops here too.
753
+ runner_pass_skills "$REPO_ROOT" || exit 1
754
+
755
+ # A copy of ship-loop without ship-it beside it, under .agents/skills or under the
756
+ # .claude/skills compatibility path is a broken install, and the preflight says so before any pass.
757
+ [[ -n "$LEDGER_SH" ]] || die "cannot find kryso's ledger.sh beside $HERE, under .agents/skills, or under the .claude/skills compatibility path"
758
+
759
+ # A shift or a pass that `kryso --isolate docker` runs in a container holds its locks in Docker
760
+ # Desktop's VM, where this host cannot see them, so its pid file is the only sign it is running
761
+ # (ADR 0039). A host shift beside it would claim, resume or adopt its work, so the check comes before
762
+ # anything here moves.
763
+ if isolated_pid="$(ledger isolated "$REPO_ROOT")"; then
764
+ die "an isolated kryso run (docker pid $isolated_pid) is working this repository, and its locks are not visible here, so this shift would race it. Wait for it to end, or stop it"
765
+ fi
766
+
767
+ # Shift state lives under .claude/kryso/. A shift moves the .claude/ship-loop/ a driver before
768
+ # the rename left to it first, with a link back at the old name, so the shifts and archives in
769
+ # it stay where every reader looks. A dry run writes nothing, so it only reads which is there.
770
+ if [[ "$DRY_RUN" -eq 1 ]]; then _ledger_pick .claude/kryso .claude/ship-loop STATE_ROOT
771
+ else
772
+ _ledger_migrate_state "$REPO_ROOT" .claude/ship-loop .claude/kryso \
773
+ || die "cannot move .claude/ship-loop to .claude/kryso, where every shift now writes"
774
+ _ledger_pick .claude/kryso .claude/ship-loop STATE_ROOT
775
+ fi
776
+
777
+ # The styled-output module, looked for before the arguments were read. A copy without it is a
778
+ # broken install, named here like a missing ledger.sh. The driver's plain lines are on stdout,
779
+ # so that is the stream a styled line takes.
780
+ [[ -n "$UI_SH" ]] || die "cannot find kryso's ui.sh beside $HERE, under .agents/skills, or under the .claude/skills compatibility path"
781
+ [[ "$UI_SH" != unsourced:* ]] || die "cannot source ${UI_SH#unsourced:}"
782
+ ui_stream 1
783
+ # On an attended run a note is an information line under the section it falls in, with no prefix.
784
+ note() { if ui_attended; then ui_info "$1"; else echo "ship-loop: $1"; fi; }
785
+ # shift_summary: the brand line's summary, the queue the flags name and the cap a run carries.
786
+ shift_summary() {
787
+ local queue="label $LABEL" cap="no dollar cap"
788
+ if [[ -n "$ISSUES" ]]; then queue="queue $ISSUES"; elif [[ -n "$EPIC" ]]; then queue="epic #$EPIC"; fi
789
+ [[ "$RUNNER_HOST" != claude ]] || cap="\$$BUDGET per run"
790
+ printf '%s, %s' "$queue" "$cap"
791
+ }
792
+ ui_brand shift "$(shift_summary)"
793
+ ui_section primary PREFLIGHT
794
+
795
+ # runner.sh says why a host fails on a `runner:` line of its own. An attended stderr keeps that
796
+ # line off the terminal and fails through die, so it prints under an ERROR pill like any other
797
+ # preflight failure. It runs in this shell, because it sets RUNNER_VERSION.
798
+ if ui_err_attended; then
799
+ RUNNER_FAILURE="$(mktemp)"
800
+ if ! runner_preflight 2> "$RUNNER_FAILURE"; then
801
+ failure="$(cat "$RUNNER_FAILURE")"; rm -f "$RUNNER_FAILURE"
802
+ die "${failure#runner: }"
803
+ fi
804
+ rm -f "$RUNNER_FAILURE"
805
+ else
806
+ runner_preflight || exit 1
807
+ fi
808
+
809
+ # Every skill the shift's workflow pins, tdd and implement in the built-in default, is in
810
+ # kryso's store before the tracker is read, fetched where the store lacks it (ADR 0046), so a
811
+ # shift whose skills cannot be fetched stops here rather than in each pass. The pins are read
812
+ # at this checkout's HEAD, and each pass fetches its own again from its base.
813
+ command -v node >/dev/null 2>&1 || die "preflight: node is not installed, and the workflow resolver runs on it"
814
+ [[ -f "$HERE/workflow.mjs" ]] || die "preflight: cannot find kryso-shift's workflow.mjs beside $HERE"
815
+ runner_fetch_pins "$HERE/workflow.mjs" "$REPO_ROOT" HEAD "${WORKFLOW:-default}" || die "preflight: $RUNNER_PINS_FAILURE"
816
+ RUNNER_SKILLS="the ${WORKFLOW:-default} workflow's pins, $RUNNER_PINS_SAID"
817
+
818
+ # The tracker is required where the repo has one. A remote on GitHub means gh has to be
819
+ # there, logged in, holding the project scope, and the label has to exist. A repo with no
820
+ # GitHub remote still runs: /kryso reports nothing-to-take on its own, and that is a
821
+ # correct shift rather than a setup error.
822
+ TRACKER=reachable
823
+ CANDIDATES=unknown
824
+ if git config --get-regexp '^remote\..*\.url$' 2>/dev/null | grep -qiE 'github\.com[:/]'; then
825
+ type -P gh >/dev/null || die "gh is not installed, and this repo's remote is on GitHub"
826
+ auth="$(gh auth status 2>&1)" \
827
+ || { die_if_silent "$?" "its login"; die "gh is not logged in, and this repo's remote is on GitHub" "Run gh auth login"; }
828
+ grep -q "'project'" <<< "$auth" \
829
+ || die "gh has no 'project' scope, and /kryso moves cards with it" "Run gh auth refresh -s project"
830
+ gh repo view --json name >/dev/null 2>&1 \
831
+ || { die_if_silent "$?" "this repo's GitHub remote"; die "gh cannot read this repo's GitHub remote"; }
832
+ # Real jq rather than gh's --jq, which takes no --arg, so a label with a quote in it is safe.
833
+ labels="$(gh label list --search "$LABEL" --json name 2>/dev/null)" || die_if_silent "$?" "the label '$LABEL'"
834
+ if [[ -z "$(jq -r --arg l "$LABEL" '.[] | select(.name == $l) | .name' <<< "$labels")" ]]; then
835
+ die "this repo has no label '$LABEL'"
836
+ fi
837
+ # CI is the other piece of infrastructure a pass depends on, and the one a whole build
838
+ # can be lost to: a PR that gets no check parks at reconcile after the fork ran. So the
839
+ # shift asks before it claims. The runners endpoint lists self-hosted runners alone, so
840
+ # that rule applies only where a workflow targets one, read as any `self-hosted` in the
841
+ # workflow files, which over-includes a deploy-on-push job rather than parse YAML. Busy
842
+ # and labels are ignored: a busy runner plus the queue rule covers overload. Queued runs
843
+ # are the queue; a run in progress is the runner doing its job. Both reads fail closed,
844
+ # because a health the driver cannot read is not one it can vouch for.
845
+ CI="skipped (--no-ci-check)"
846
+ if [[ "$CI_CHECK" -eq 1 ]]; then
847
+ if grep -qs -- self-hosted .github/workflows/*.yml .github/workflows/*.yaml; then
848
+ # Being refused the runner list is not evidence that a runner is down. The endpoint is
849
+ # admin-only, and GitHub answers a private repo with 404 rather than 403 so as not to
850
+ # confirm it exists, so both codes mean "not allowed to look" and fall through to the
851
+ # jobs read rather than stopping the shift. Every other failure still fails closed,
852
+ # because a health the driver cannot read for any other reason is not one it can vouch for.
853
+ if runners="$(gh api 'repos/{owner}/{repo}/actions/runners' 2>&1)"; then
854
+ total="$(jq -r '.total_count // 0' <<< "$runners" 2>/dev/null)" || die "the runners endpoint returned something other than JSON"
855
+ online="$(jq -r '[.runners[]? | select(.status == "online")] | length' <<< "$runners")"
856
+ [[ "$online" -gt 0 ]] || die "no self-hosted runner is online ($online of $total), and this repo's workflows target self-hosted, so a pass's PR would get no check" \
857
+ "Bring a runner up, or pass --no-ci-check to let passes park at reconcile"
858
+ CI="$online of $total self-hosted runner(s) online"
859
+ elif [[ "$runners" == *"HTTP 403"* || "$runners" == *"HTTP 404"* ]]; then
860
+ CI="$(ci_health_from_jobs)" || die "${CI%%$'\n'*}" "$(sed -n 2p <<< "$CI")"
861
+ else
862
+ die "cannot read the self-hosted runners: $(head -1 <<< "$runners")"
863
+ fi
864
+ else
865
+ CI="github-hosted"
866
+ fi
867
+ # Read one past the limit at least, or a limit of 20 or more could never be exceeded.
868
+ queued="$(gh run list --status queued --limit "$(( CI_MAX_QUEUED < 20 ? 20 : CI_MAX_QUEUED + 1 ))" --json databaseId 2>&1)" \
869
+ || die "cannot read the workflow queue: $(head -1 <<< "$queued")"
870
+ queued="$(jq -r 'length' <<< "$queued" 2>/dev/null)" || die "gh run list returned something other than JSON"
871
+ [[ "$queued" -le "$CI_MAX_QUEUED" ]] \
872
+ || die "$queued workflow runs are queued, more than $CI_MAX_QUEUED, so a pass's checks would wait behind them" \
873
+ "Let the queue drain, or pass --no-ci-check to let passes park at reconcile"
874
+ CI+=", $queued queued"
875
+ fi
876
+ # Filtered here rather than with --search "no:assignee": a search is served from GitHub's
877
+ # search index, which lags a close by minutes, and a count that drifts between two dry
878
+ # runs reads as a bug. The issues connection is current.
879
+ CANDIDATES="$(gh issue list --state open --label "$LABEL" --limit 500 --json number,assignees 2>/dev/null \
880
+ | jq -r '[.[] | select(.assignees | length == 0)] | length' 2>/dev/null || echo unknown)"
881
+ else
882
+ TRACKER="unreachable (no GitHub remote for this repo)"
883
+ CI="not checked (no GitHub remote)"
884
+ fi
885
+
886
+ # preflight_warn <message>: the preflight's one warning path. An attended run prints it as a
887
+ # warning line on stderr, where the plain one goes. A stderr that is not attended takes warn's
888
+ # prefixed line, whatever stdout is.
889
+ preflight_warn() {
890
+ if ui_err_attended; then ( UI_FD=2 UI_TTY=1 ui_warn "$1" ); else warn "$1"; fi
891
+ }
892
+
893
+ # A --base has to be on origin before any pass claims an issue against it. A base held in a
894
+ # local ref alone is one cleanup away from gone, and no pass could open a PR against it. An
895
+ # integration base also wants the ruleset that stops origin's copy being deleted. Its absence is
896
+ # a warning, because a plan without rulesets cannot have one (ADR 0010).
897
+ if [[ -n "$BASE" ]]; then
898
+ base_tip="$(on_origin "$BASE")"; code=$?
899
+ case "$code" in
900
+ 0) ;;
901
+ 2) die "--base $BASE is not on origin, so no pass could open a PR against it" "Push it, or make an integration branch with kryso integration <epic> <slug>" ;;
902
+ *) die "cannot read origin to check that --base $BASE is there: $base_tip" ;;
903
+ esac
904
+ if [[ "$BASE" == integration/* && "$TRACKER" == reachable ]]; then
905
+ integration_ruleset
906
+ case "$RULESET_STATE" in
907
+ missing) preflight_warn "no ruleset without a bypass blocks deleting integration/* on origin, so $BASE can be deleted there. Run kryso integration <epic> <slug> to add one" ;;
908
+ unavailable) preflight_warn "$BASE can be deleted on origin: this repository's plan has no rulesets" ;;
909
+ unreadable) preflight_warn "cannot read the repository's rulesets, so this check cannot tell whether $BASE can be deleted on origin: $RULESET_WHY" ;;
910
+ esac
911
+ fi
912
+ fi
913
+
914
+ # A report URL without a token is refused here, because every push would be a 401 and the
915
+ # shift would find that out one pass at a time. The repo the reports name is the one
916
+ # read_name_with_owner answers, read only when there is a URL to report to. A repo neither
917
+ # source can name is a null repo.
918
+ REPORTING_NOTE="the shift reports nothing"
919
+ REPORT_REPO=""
920
+ if [[ -n "$REPORT_URL" ]]; then
921
+ [[ -n "$REPORT_TOKEN" ]] || die "KRYSO_REPORT_URL is set but KRYSO_REPORT_TOKEN is not, so every report would be a 401. Put the token in the secrets file the shell sources, or unset the URL"
922
+ command -v curl >/dev/null 2>&1 || die "curl is not installed, and KRYSO_REPORT_URL is set"
923
+ REPORT_REPO="$(read_name_with_owner)" || { die_if_silent "$?" "this repo's owner and name for the report"; REPORT_REPO=""; }
924
+ REPORTING_NOTE="the shift reports to $REPORT_URL"
925
+ fi
926
+
927
+ WORKTREES="$(ls -1 .claude/worktrees 2>/dev/null | tr '\n' ' ')"
928
+ [[ "$SWEEPS_SET" -eq 0 || "$TRACKER" == reachable ]] || die "--sweeps needs a GitHub remote to take the eligibility snapshot from"
929
+
930
+ # Two things a real pass showed. Under --permission-prompts none, a gh read that no allow
931
+ # rule covers is denied, and the model reads the denial as an empty column or a failure.
932
+ # And a project's own .claude/settings.json allow rules are ignored in print mode until the
933
+ # workspace has been trusted once, interactively. Both are warnings: managed settings can
934
+ # grant either in ways this script cannot see. Both apply to either engine: the pass
935
+ # script's fork runs in print mode too, and its reviewers read the tracker.
936
+ # runner.sh writes each warning with warn's prefix already on it, so the loop strips the prefix
937
+ # before preflight_warn puts it back or styles the line.
938
+ while IFS= read -r warning; do
939
+ preflight_warn "${warning#ship-loop: warning: }"
940
+ done < <(runner_preflight_warnings "$REPO_ROOT" 2>&1)
941
+
942
+ # A setting still under its name before the rename is read until 3.0.0, with one warning that
943
+ # says how to move it.
944
+ while IFS= read -r legacy; do
945
+ preflight_warn "$legacy in git config is the setting's name before the rename, read only until 3.0.0. Move it with: git config kryso.${legacy#playbook.} \"\$(git config $legacy)\" && git config --unset $legacy"
946
+ done < <(runner_config_legacy "$REPO_ROOT")
947
+ # A pass setting still in git config has moved to .kryso/config.json, and is read until 3.0.0
948
+ # where the file does not set it: one warning each, its move or that it is ignored.
949
+ while IFS= read -r moved; do
950
+ preflight_warn "$moved"
951
+ done < <(runner_config_moves "$REPO_ROOT")
952
+
953
+ # An installed copy of a skill kryso carries that differs from the one beside this driver is a
954
+ # warning: the pass script takes kryso-build, ledger.sh and ui.sh from beside the driver, but a
955
+ # session that loads a skill by its name, as /kryso and /code-review are loaded, gets the
956
+ # installed copy.
957
+ while IFS= read -r drifted; do
958
+ [[ -z "$drifted" ]] || preflight_warn "the installed $drifted skill differs from the copy beside this driver in $(dirname "$HERE"), so a session that loads it by name, as /kryso and /code-review are loaded, would use the installed copy. Run kryso skills install"
959
+ done < <(runner_skills_drifted "$REPO_ROOT" "$(dirname "$HERE")" "${RUNNER_CARRIED_SKILLS[@]}")
960
+
961
+ # ---- the shift's evidence ---------------------------------------------------------------
962
+ #
963
+ # Everything a shift leaves lands under .claude/kryso/<shift>/, and the readers below
964
+ # are the launcher's contract: summary.json is what it reports from, each sweep's manifest
965
+ # says what that sweep saw and ran, and each saved pass result carries enough to place it
966
+ # without opening it.
967
+
968
+ # open_shift: the shift directory, excluded from git through the common git directory, with
969
+ # an empty log for the passes to fill. Each sweep writes its own manifest before it runs. The
970
+ # id is the second the shift started, and a shift never shares a directory with another: one
971
+ # that started in the same second waits for the next. The shift is exported as
972
+ # KRYSO_SHIFT, so a pass reads which shift a handoff has to name. shift.json records the
973
+ # selection a later adopting shift has to keep, with model as --model gave it, and model_run as
974
+ # the model the passes run, the profile's when --model is not given. And the driver holds driver.lock on descriptor
975
+ # 5 for as long as it or any process it started runs, which is how that shift confirms this
976
+ # one stopped.
977
+ open_shift() {
978
+ # The new name, and the old one, which a driver before the rename may still write.
979
+ _ledger_exclude "$REPO_ROOT" '.claude/kryso/'
980
+ _ledger_exclude "$REPO_ROOT" '.claude/ship-loop/'
981
+ mkdir -p "$STATE_ROOT"
982
+ SHIFT_ID="$(date -u +%Y%m%dT%H%M%SZ)"
983
+ until mkdir "$STATE_ROOT/$SHIFT_ID" 2>/dev/null; do
984
+ [[ -d "$STATE_ROOT/$SHIFT_ID" ]] || die "cannot create $STATE_ROOT/$SHIFT_ID for the shift"
985
+ sleep 1; SHIFT_ID="$(date -u +%Y%m%dT%H%M%SZ)"
986
+ done
987
+ SHIFT_DIR="$STATE_ROOT/$SHIFT_ID"
988
+ export KRYSO_SHIFT="$SHIFT_ID"
989
+ SHIFT_LOG="$SHIFT_DIR/shift.log"
990
+ : > "$SHIFT_LOG"
991
+ jq -n --arg shift "$SHIFT_ID" --arg engine "$ENGINE" --arg profile "$PROFILE" --arg host "$RUNNER_HOST" \
992
+ --arg billing "$RUNNER_BILLING" --arg effort "$EFFORT" --arg model "$MODEL" --arg extra "${EXTRA_ARGS[*]-}" \
993
+ --arg model_run "${MODEL:-${RUNNER_MODEL:-}}" --arg mcp "$RUNNER_PASS_MCP" --arg mcp_kept "$RUNNER_PASS_MCP_KEPT" --argjson adopt "$(jq -nc '$ARGS.positional | if length == 0 then null elif length == 1 then .[0] else . end' --args ${ADOPTS[@]+"${ADOPTS[@]}"})" --arg started "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --argjson pid "$$" \
994
+ '{shift: $shift, engine: $engine, profile: $profile, host: $host, billing: $billing, effort: $effort,
995
+ model: (if $model == "" then null else $model end), model_run: (if $model_run == "" then null else $model_run end), extra_args: $extra, mcp: $mcp,
996
+ mcp_kept: (if $mcp_kept == "" then null else ($mcp_kept | split(", ")) end), pid: $pid, started_at: $started,
997
+ adopted: $adopt}' > "$SHIFT_DIR/shift.json"
998
+ ledger lock "$SHIFT_DIR/driver.lock" 5 || warn "cannot hold $SHIFT_DIR/driver.lock, so a later --adopt $SHIFT_ID cannot confirm this shift stopped"
999
+ shift_plugin
1000
+ }
1001
+
1002
+ # shift_plugin: the plugin of the build's pinned skills, kryso-pins, under the shift directory,
1003
+ # which every Claude start of the ship-it engine loads with --plugin-dir, as the pass script
1004
+ # loads its own per pass.
1005
+ shift_plugin() {
1006
+ RUNNER_PLUGIN_DIR=""
1007
+ [[ "$RUNNER_HOST" == claude ]] || return 0
1008
+ runner_pins_plugin "$SHIFT_DIR/plugin" build
1009
+ }
1010
+
1011
+ # close_shift: the stop state from the rows, the summary, then the close a person reads.
1012
+ # On a terminal the close is a green DONE pill on a planned stop, one of ADR 0003's
1013
+ # rows-decided ends, and a yellow STOPPED pill on every cap, stall, wait and failure, then a
1014
+ # table of the summary's pass_rows and the closing lines spec #99 fixes, the reason as an
1015
+ # information line on a planned stop and a warning otherwise, and the plain lines stay off the
1016
+ # screen. A shipped pass whose closeout is incomplete adds one warning after the paths, or a
1017
+ # plain line above the reason. In plain mode the last line stays as ADR 0006 freezes it and
1018
+ # its stop word as ADR 0003 fixes it, because a background run reads the summary path from that line.
1019
+ close_shift() {
1020
+ STOP="$(stop_state)"
1021
+ write_summary
1022
+ local closeout_note stages_note
1023
+ closeout_note="$(closeout_line)"
1024
+ stages_note="$(shift_stage_failures_line)"
1025
+ if ui_attended; then
1026
+ local planned=0
1027
+ case "$STOP" in complete|review-ready|frontier-empty) planned=1 ;; esac
1028
+ if [[ "$planned" -eq 1 ]]; then ui_section secondary DONE; else ui_section warn STOPPED; fi
1029
+ close_rows | ui_table --indent 2 --header
1030
+ ui_info "$(plural "$pass" run runs) over $(plural "$SWEPT" sweep sweeps), stop $(ui_val "$STOP")"
1031
+ if [[ "$planned" -eq 1 ]]; then ui_ok "$stop_reason"; else ui_warn "$stop_reason"; fi
1032
+ ui_info "summary at $(ui_tint dim "$SHIFT_DIR/summary.json")"
1033
+ ui_info "log at $(ui_tint dim "$SHIFT_LOG")"
1034
+ [[ "$STACKED_SWEEPS" -eq 0 ]] || ui_info "$(stack_line)"
1035
+ [[ -z "$closeout_note" ]] || ui_warn "$closeout_note"
1036
+ [[ -z "$stages_note" ]] || ui_warn "$stages_note"
1037
+ return 0
1038
+ fi
1039
+ echo
1040
+ [[ "$STACKED_SWEEPS" -eq 0 ]] || note "$(stack_line)"
1041
+ [[ -z "$closeout_note" ]] || note "$closeout_note"
1042
+ [[ -z "$stages_note" ]] || note "$stages_note"
1043
+ note "$stop_reason"
1044
+ note "$pass run(s) over $(plural "$SWEPT" sweep sweeps), stop $STOP, summary at $SHIFT_DIR/summary.json, log at $SHIFT_LOG"
1045
+ }
1046
+
1047
+ # close_rows: the close's rows for ui_table, each from ui_table_row: a header of PASS_ROW_COLUMNS, then one row
1048
+ # per entry of the summary's pass_rows, in the words a pass's line on the screen uses: the
1049
+ # issue and the PR as #N, took and the CI wait as durations, the cost to the cent, the outcome
1050
+ # in its mark's colour by ui_outcome, plain where that is information. An unknown value is a dim dash, never 0. The fields come in
1051
+ # PASS_ROW_FIELDS' order.
1052
+ close_rows() {
1053
+ local p i o pr took cost commits ci rounds column tone
1054
+ local -a header=()
1055
+ for column in "${PASS_ROW_COLUMNS[@]}"; do header+=("$(tr '[:lower:]' '[:upper:]' <<< "$column")"); done
1056
+ ui_table_row "${header[@]}"
1057
+ while IFS=$'\x1f' read -r p i o pr took cost commits ci rounds; do
1058
+ tone="$(ui_outcome "$o")"
1059
+ [[ "$tone" != info ]] || tone=""
1060
+ ui_table_row "$p" "value"$'\x1f'"#$i" "${tone:+$tone$'\x1f'}$o" "$(short_pr "$pr")" \
1061
+ "$(or_dash duration "$took")" "$(or_dash short_cost "$cost")" "$(or_dash echo "$commits")" "$(or_dash duration "$ci")" "$(or_dash echo "$rounds")"
1062
+ done < <(jq -r --argjson fields "$(pass_row_fields)" '.pass_rows[] | [.[$fields[]]]
1063
+ | map(if . == null then "" else tostring end) | join("\u001f")' "$SHIFT_DIR/summary.json")
1064
+ }
1065
+
1066
+ # or_dash <command> <value>: the command's rendering of the value, or a dim dash when it is
1067
+ # unknown.
1068
+ or_dash() { if [[ -z "$2" ]]; then printf 'dim\x1f–\n'; else "$1" "$2"; fi; }
1069
+
1070
+ # closeout_line: every shipped pass whose closeout stopped part-way, in one line for a person,
1071
+ # each with the step it stopped at and the worktree it kept. Empty when there is none.
1072
+ closeout_line() {
1073
+ jq -r '.closeout_incomplete | if length == 0 then empty else
1074
+ "closeout incomplete: " + (map("#\(.issue) at \(.step)" + (if .worktree then " (\(.worktree))" else "" end)) | join(", ")) end' \
1075
+ "$SHIFT_DIR/summary.json"
1076
+ }
1077
+
1078
+ # report_pass: one JSON body per pass to the report URL, right after the pass's shift line,
1079
+ # so a shift killed at three in the morning has still reported its first passes. The body is
1080
+ # the line's fields plus the outcome block's reason, the repo and the shift, written to
1081
+ # report-<n>.json from the same values the line was built from and sent as a POST with a
1082
+ # bearer token. The token reaches curl as a config on stdin, never on its command line. Best
1083
+ # effort: a non-2xx status or a transport error waits and retries once, and a second failure
1084
+ # is one shift-log line. Nothing here changes the pass's outcome, the shift's exit code or
1085
+ # the failure streak. What is behind the URL is the receiver's concern.
1086
+ report_pass() {
1087
+ local body="$SHIFT_DIR/report-$pass.json" err="$SHIFT_DIR/report-$pass.err" status rc why attempt
1088
+ [[ -n "$REPORT_URL" ]] || return 0
1089
+ # curl reads the config value as a quoted string, so the two characters it escapes are escaped.
1090
+ local quoted_token="${REPORT_TOKEN//\\/\\\\}"
1091
+ quoted_token="${quoted_token//\"/\\\"}"
1092
+ jq -n --arg repo "$REPORT_REPO" --arg shift "$SHIFT_ID" --argjson pass "$pass" --arg at "$ended_at" \
1093
+ --arg outcome "$outcome" --arg issue "$issue" --arg branch "$branch" --arg base "${queued:+$PASS_BASE}" \
1094
+ --arg pr "$pr" --arg reason "$reason" --arg profile "$result_profile" --arg host "$result_host" \
1095
+ --arg billing "$billing" --arg effort "$result_effort" --arg cost "$cost_usd" --argjson usage "$usage" \
1096
+ --arg session "$session" '
1097
+ def text: if . == "" or . == "none" then null else . end;
1098
+ def number: if . == "" or . == "null" then null else (tonumber? // null) end;
1099
+ { repo: ($repo | text), shift: $shift, pass: $pass, ended_at: $at, outcome: $outcome,
1100
+ issue: ($issue | text | if . == null then null else number end),
1101
+ branch: ($branch | text), base: ($base | text), pr: ($pr | text), reason: $reason,
1102
+ profile: $profile, host: $host, billing: $billing, effort: $effort,
1103
+ cost_usd: ($cost | number), usage: $usage, session: $session }' > "$body" 2>"$err" \
1104
+ || { report_failed "could not write $body: $(head -1 "$err")"; rm -f "$err"; return 0; }
1105
+ for attempt in 1 2; do
1106
+ status="$(printf 'header = "Authorization: Bearer %s"\n' "$quoted_token" \
1107
+ | curl -sS -K - -o /dev/null -w '%{http_code}' -X POST --max-time 15 \
1108
+ -H 'Content-Type: application/json' --data-binary "@$body" "$REPORT_URL" 2>"$err")"
1109
+ rc=$?
1110
+ if [[ "$rc" -eq 0 ]]; then why="status $status"; else why="$(head -1 "$err")"; fi
1111
+ rm -f "$err"
1112
+ if [[ "$rc" -eq 0 && "$status" =~ ^2[0-9][0-9]$ ]]; then return 0; fi
1113
+ [[ "$attempt" -eq 2 ]] || sleep "$REPORT_RETRY_SECONDS"
1114
+ done
1115
+ report_failed "$why"
1116
+ }
1117
+
1118
+ # report_failed <why>: the one line a report that could not be delivered leaves, so the
1119
+ # morning reader knows the post may be short.
1120
+ report_failed() {
1121
+ printf '%s pass=%s report=failed %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$pass" "${1}" | tee -a "$SHIFT_LOG"
1122
+ }
1123
+
1124
+ # repo_name_with_owner <query>: read_name_with_owner's answer into name_with_owner for a
1125
+ # GraphQL query, or a preflight stop that names the silence or the query.
1126
+ repo_name_with_owner() {
1127
+ name_with_owner="$(read_name_with_owner)" \
1128
+ || { die_if_silent "$?" "this repo's owner and name"; die "cannot read this repo's owner and name for the ${1} query"; }
1129
+ }
1130
+
1131
+ # write_manifest <order-json> <held-json> <reason>: sweep-N.json, the fixed snapshot this sweep
1132
+ # processes, what it was taken from and when, for an epic the scope (its open children at the
1133
+ # first read) and every child that read discovered, why each in-scope issue was left out, the
1134
+ # issues it holds back with the reason, the issues it continues with their recorded stage
1135
+ # and fingerprint, and the order it runs with why each issue sits where it does. Written
1136
+ # before the sweep's first pass, so the snapshot on disk is the one that ran.
1137
+ write_manifest() {
1138
+ local kind=label
1139
+ [[ -z "$EPIC" ]] || kind=epic
1140
+ [[ -z "$ISSUES" ]] || kind=workset
1141
+ jq -n --argjson sweep "$SWEEP" --arg shift "$SHIFT_ID" --arg at "$SNAPSHOT_AT" --arg kind "$kind" \
1142
+ --arg epic "$EPIC" --argjson named "$NAMED_JSON" --arg label "$LABEL" --arg eligibility "$SNAPSHOT_ELIGIBILITY" \
1143
+ --argjson discovered "$EPIC_DISCOVERED" --argjson open "${EPIC_SCOPE:-null}" \
1144
+ --arg order "$SNAPSHOT_ORDER" --argjson snapshot "$SNAPSHOT" --argjson max "$MAX" --arg base "$BASE" \
1145
+ --argjson run "$1" --argjson held "$2" --arg reason "$3" --argjson state "$ISSUE_STATE" \
1146
+ --argjson stacked "$STACKED_SWEEPS" --argjson satisfied "$STACK_SATISFIED" --argjson rejected "$STACK_REJECTED" '
1147
+ { sweep: $sweep, shift: $shift, taken_at: (if $at == "" then null else $at end),
1148
+ scope: { kind: $kind,
1149
+ epic: (if $epic == "" then null else ($epic | tonumber) end),
1150
+ named: (if $kind == "workset" then $named else null end),
1151
+ label: (if $kind == "label" then $label else null end),
1152
+ discovered: (if $kind == "epic" then $discovered else null end),
1153
+ open: (if $kind == "epic" then $open else null end) },
1154
+ base: (if $base == "" then null else $base end),
1155
+ eligibility: $eligibility, order: $order,
1156
+ candidates: $snapshot.candidates, excluded: $snapshot.excluded,
1157
+ run: $run, held: $held,
1158
+ resumable: [$run[] | select(.why != "eligible" and .why != "label") | .issue as $i
1159
+ | {issue: $i, stage: $state[$i | tostring].stage, fingerprint: $state[$i | tostring].fingerprint}],
1160
+ max: $max, admitted: [$run[] | .issue | select(. != null)],
1161
+ stack: (if $stacked == 1 then
1162
+ { satisfied: [$satisfied | to_entries[] | {issue: (.key | tonumber)} + .value],
1163
+ rejected: [$rejected | to_entries[] | {issue: (.key | tonumber), reason: .value}] }
1164
+ else null end),
1165
+ reason: (if $reason == "" then null else $reason end) }' > "$SHIFT_DIR/sweep-$SWEEP.json"
1166
+ }
1167
+
1168
+ # add_pass_meta <file> <pass> <issue> <attempt> <predecessor> <state> <stage>: a ship_loop
1169
+ # object beside the host's fields, naming the pass, the sweep, the issue the pass was for,
1170
+ # which attempt at it this is, the saved attempt before it, the typed state the supervisor
1171
+ # read off the evidence it left, the recorded stage, the fingerprint after the pass, the
1172
+ # worktree and the base the pass was told, so a stacked chain reads off the saved results
1173
+ # alone, and the allowance the pass consumed across its attempts, which a later --adopt hands on. The fingerprint, worktree and base come off ISSUE_STATE, which the caller has just
1174
+ # written for the issue, and a pass that named no issue has no entry there, so it gets none.
1175
+ # The rest stay arguments because the state does not hold them at that point. The pass and
1176
+ # the classifier's state and stage exist for a pass that named no issue. A rate-limited
1177
+ # attempt is deliberately not counted in the state. The state's artifact is already this
1178
+ # file, not the one before it. Added to the file after the host wrote it, so the readers of
1179
+ # the host's own fields see what they always saw. A file that is not JSON is left as it is,
1180
+ # because a reader that cannot parse it has a bigger problem.
1181
+ add_pass_meta() {
1182
+ local file="$1" tmp="$1.meta"
1183
+ if jq --argjson pass "$2" --argjson sweep "$SWEEP" --arg issue "$3" --argjson attempt "$4" --arg pred "$5" \
1184
+ --arg state "${6:-}" --arg stage "${7:-}" --arg fp "$(st_get "$3" fingerprint)" \
1185
+ --arg wt "$(st_get "$3" worktree)" --arg base "$(st_get "$3" base)" --argjson consumed "${PASS_CONSUMED:-0}" \
1186
+ '. + {ship_loop: {pass: $pass, sweep: $sweep, issue: $issue, attempt: $attempt,
1187
+ predecessor: (if $pred == "" then null else $pred end),
1188
+ state: (if $state == "" then null else $state end),
1189
+ stage: (if $stage == "" then null else $stage end),
1190
+ fingerprint: (if $fp == "" then null else $fp end),
1191
+ worktree: (if $wt == "" then null else $wt end),
1192
+ base: (if $base == "" then null else $base end), consumed: $consumed}}' "$file" > "$tmp" 2>/dev/null; then
1193
+ mv "$tmp" "$file"
1194
+ else
1195
+ rm -f "$tmp"
1196
+ fi
1197
+ }
1198
+
1199
+ # add_row <pass> <issue> <outcome> <pr> <branch> <artifact> <attempt> <state> <closeout-step>
1200
+ # <metrics>: one line of the shift's record per attempt, which the summary is built from at the
1201
+ # end. The step is the one a shipped pass's closeout stopped at, empty for every other attempt.
1202
+ # The metrics are row_metrics' object, merged in for the summary's pass_rows.
1203
+ ROWS=()
1204
+ add_row() {
1205
+ ROWS+=("$(jq -cn --argjson pass "$1" --arg issue "$2" --arg outcome "$3" --arg pr "$4" --arg branch "$5" \
1206
+ --arg artifact "$6" --argjson attempt "$7" --argjson sweep "$SWEEP" --arg state "${8:-}" --arg step "${9:-}" \
1207
+ --argjson metrics "${10:-"{}"}" \
1208
+ '{pass: $pass, sweep: $sweep, issue: $issue, outcome: $outcome, pr: $pr, branch: $branch, artifact: $artifact,
1209
+ attempt: $attempt, state: (if $state == "" then null else $state end),
1210
+ closeout_step: (if $step == "" then null else $step end)} + $metrics')")
1211
+ }
1212
+
1213
+ # base_commit: the commit the pass's base stands at now, origin's copy first, and origin's
1214
+ # default branch for a pass without a base. Empty when neither resolves.
1215
+ base_commit() {
1216
+ local ref=refs/remotes/origin/HEAD
1217
+ [[ -z "$PASS_BASE" ]] || ref="refs/remotes/origin/$PASS_BASE"
1218
+ git rev-parse --verify --quiet "$ref^{commit}" 2>/dev/null \
1219
+ || git rev-parse --verify --quiet "${PASS_BASE:-HEAD}^{commit}" 2>/dev/null || true
1220
+ }
1221
+
1222
+ # attempt_baseline: where the commit count of the attempt about to run starts, read just before
1223
+ # it runs, so a rate-limit retry counts only what it added: each worktree's branch and head, the
1224
+ # commit the base stands at, and the second the attempt starts, which a closeout's copy of the
1225
+ # ledger is named after.
1226
+ attempt_baseline() {
1227
+ ATTEMPT_HEADS="$(git worktree list --porcelain 2>/dev/null | awk '/^HEAD /{h = $2} /^branch /{print $2 "\t" h}')"
1228
+ ATTEMPT_BASE_SHA="$(base_commit)"
1229
+ ATTEMPT_STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
1230
+ }
1231
+
1232
+ # shipped_copy <issue>: the copy of the issue's ledger a closeout made during the attempt that
1233
+ # just ended, the newest if there are several. `ledger.sh archive` names it after the worktree,
1234
+ # which ends in the issue, and the time, under .claude/kryso/shipped/ or the old
1235
+ # .claude/ship-loop/shipped/, and the copy's run.md names the issue. Fails when there is none.
1236
+ shipped_copy() {
1237
+ local issue="$1" dir stamp found="" ld
1238
+ for dir in "$REPO_ROOT"/.claude/kryso/shipped/*-"$issue"-* "$REPO_ROOT"/.claude/ship-loop/shipped/*-"$issue"-*; do
1239
+ [[ -d "$dir" ]] || continue
1240
+ stamp="${dir##*-}"
1241
+ [[ "$stamp" =~ ^[0-9]{8}T[0-9]{6}Z$ && ! "$stamp" < "$ATTEMPT_STAMP" ]] || continue
1242
+ _ledger_d "$dir" ld
1243
+ grep -qx "issue: $issue" "$ld/run.md" 2>/dev/null || continue
1244
+ [[ -n "$found" && ! "${found##*-}" < "$stamp" ]] || found="$dir"
1245
+ done
1246
+ [[ -n "$found" ]] && printf '%s' "$found"
1247
+ }
1248
+
1249
+ # attempt_commits <issue> <branch>: the commits the attempt that just ended added to its branch,
1250
+ # or null when either end is unknown. The head is the issue's worktree's, and the start that
1251
+ # branch's head before the attempt. The ledger is read only when git leaves one of them unknown:
1252
+ # a worktree the attempt cut starts at the base commit its ledger names, and once a closeout has
1253
+ # removed the worktree, the head is the one its checkpoint last held, in the copy of the ledger
1254
+ # the closeout kept. Then the branch's head as last pushed, and the base where it stood before
1255
+ # the attempt. What the base holds is left out, as it stood before the attempt and as it stands
1256
+ # now unless the branch has been merged into it, so a continuation that merged the base counts
1257
+ # its merge and its own work and not the base's commits.
1258
+ attempt_commits() {
1259
+ local issue="$1" branch="$2" wt="" head="" from="" doc="" copy="" now
1260
+ [[ -z "$issue" || "$issue" == none ]] || wt="$(worktree_for "$issue" 2>/dev/null)" || wt=""
1261
+ if [[ -n "$wt" ]]; then
1262
+ head="$(git -C "$wt" rev-parse --verify --quiet HEAD 2>/dev/null)"
1263
+ branch="$(git -C "$wt" symbolic-ref --quiet --short HEAD 2>/dev/null)" || branch="$2"
1264
+ fi
1265
+ [[ -z "$branch" || "$branch" == none ]] || from="$(awk -F'\t' -v b="refs/heads/$branch" '$1 == b {print $2; exit}' <<< "$ATTEMPT_HEADS")"
1266
+ if [[ -z "$head" || -z "$from" ]]; then
1267
+ if [[ -n "$wt" ]]; then doc="$(ledger read "$wt" 2>/dev/null)"
1268
+ elif [[ -n "$issue" && "$issue" != none ]] && copy="$(shipped_copy "$issue")"; then doc="$(ledger read "$copy" 2>/dev/null)"; fi
1269
+ [[ -n "$head" || -z "$doc" ]] || head="$(jq -r '.checkpoint.head // "" | select(test("^[0-9a-f]{40}$"))' <<< "$doc" 2>/dev/null)"
1270
+ [[ -n "$from" || -z "$doc" ]] || from="$(jq -r '.header.base.sha // empty' <<< "$doc" 2>/dev/null)"
1271
+ fi
1272
+ if [[ -z "$head" && -n "$branch" && "$branch" != none ]]; then
1273
+ head="$(git rev-parse --verify --quiet "refs/remotes/origin/$branch^{commit}" 2>/dev/null)" \
1274
+ || head="$(git rev-parse --verify --quiet "refs/heads/$branch^{commit}" 2>/dev/null)" || head=""
1275
+ fi
1276
+ [[ -n "$head" ]] || { echo null; return 0; }
1277
+ [[ -n "$from" || -z "$ATTEMPT_BASE_SHA" ]] || from="$(git merge-base "$ATTEMPT_BASE_SHA" "$head" 2>/dev/null)"
1278
+ [[ -n "$from" ]] || { echo null; return 0; }
1279
+ local -a outside=("^$from")
1280
+ [[ -z "$ATTEMPT_BASE_SHA" ]] || outside+=("^$ATTEMPT_BASE_SHA")
1281
+ now="$(base_commit)"
1282
+ if [[ -n "$now" ]] && ! git merge-base --is-ancestor "$head" "$now" 2>/dev/null; then outside+=("^$now"); fi
1283
+ git rev-list --count "$head" "${outside[@]}" 2>/dev/null || echo null
1284
+ }
1285
+
1286
+ # volume_field <result>: ` volume=<json>` for a script-engine pass whose record says its change
1287
+ # went over the test budget, the last field of its shift.log line, or nothing.
1288
+ volume_field() {
1289
+ local record
1290
+ [[ "$ENGINE" == script ]] || return 0
1291
+ record="$(result_field "$1" .record none)"
1292
+ [[ "$record" != none && -f "$record" ]] || return 0
1293
+ jq -r 'select(.test_volume.over_threshold == true) | .test_volume
1294
+ | " volume=" + ({test_lines, source_lines, ratio, threshold, over_budget, seams, tests, tests_per_seam} | tojson)' "$record" 2>/dev/null
1295
+ }
1296
+
1297
+ # row_metrics <issue> <branch> <result> <took-seconds> <cost>: the measures a row of the
1298
+ # summary's pass_rows carries besides its identity, as one JSON object. The commits are counted
1299
+ # from git under both engines, because only that count leaves out a base the attempt merged.
1300
+ # Only the script engine writes a pass record. Its CI wait and its rounds (the record's
1301
+ # reconciliations) are the attempt's, and its changes.attempt.commits stands in when git cannot
1302
+ # find the head or the start. Without a record, or a record without the field, each is null:
1303
+ # unknown, never 0.
1304
+ row_metrics() {
1305
+ local record=none from_record='{}' commits
1306
+ [[ "$ENGINE" != script ]] || record="$(result_field "$3" .record none)"
1307
+ if [[ "$record" != none && -f "$record" ]]; then
1308
+ from_record="$(jq -c 'select(.schema // "" | test("^ship-pass-record/[1-4]$"))
1309
+ | {ci: .waits.ci_seconds, rounds: .reconciliations, commits: .changes.attempt.commits?}' "$record" 2>/dev/null)"
1310
+ [[ -n "$from_record" ]] || from_record='{}'
1311
+ fi
1312
+ commits="$(attempt_commits "$1" "$2")"
1313
+ [[ "$commits" != null ]] || commits="$(jq -r '.commits | if type == "number" then . else "null" end' <<< "$from_record")"
1314
+ jq -cn --argjson took "$4" --arg cost "$5" --arg commits "$commits" --argjson record "$from_record" '
1315
+ def number: if type == "number" then . else null end;
1316
+ {took_seconds: $took, cost_usd: ($cost | (tonumber? | . + 0) // null), commits: ($commits | tonumber? // null),
1317
+ ci_wait_seconds: ($record.ci | number), rounds: ($record.rounds | number)}'
1318
+ }
1319
+
1320
+ # The fields of a pass_rows entry, in the order the summary writes them and close_rows reads
1321
+ # them, and beside each the close's column heading. The contract is the pass_row definition in
1322
+ # packages/core/schemas/shift-summary/2.schema.json.
1323
+ PASS_ROW_FIELDS=(pass issue outcome pr took_seconds cost_usd commits ci_wait_seconds rounds)
1324
+ PASS_ROW_COLUMNS=(pass issue outcome pr took cost commits "ci wait" rounds)
1325
+ pass_row_fields() { jq -nc '$ARGS.positional' --args "${PASS_ROW_FIELDS[@]}"; }
1326
+
1327
+ # rows_json: every attempt so far as one JSON array.
1328
+ rows_json() { printf '%s\n' ${ROWS[@]+"${ROWS[@]}"} | jq -s .; }
1329
+
1330
+ # The one definition of an attempt that needs a person, shared by the stop state and the
1331
+ # summary so the two cannot drift: it failed, found its issue locked, stopped on the budget,
1332
+ # parked without a PR, or was a named issue that came back nothing-to-take. $queued says
1333
+ # whether issues were named, because without a queue nothing-to-take is the column's end.
1334
+ # An attempt a later continuation of the same issue superseded is that continuation's to
1335
+ # answer for, so it is not counted twice. A shipped attempt whose closeout stopped part-way is
1336
+ # no exception, because its merge stands, but the rest of that closeout is a person's, so the
1337
+ # stop state and the summary share its test too.
1338
+ # shellcheck disable=SC2016 # jq's $variables, not the shell's
1339
+ EXCEPTION_JQ='
1340
+ def no_pr: .pr == "none" or .pr == "";
1341
+ def closeout_incomplete: .closeout_step != null;
1342
+ def exception($queued):
1343
+ .outcome == "failed" or .outcome == "locked" or .outcome == "budget-stop" or .outcome == "interrupted"
1344
+ or (.outcome == "parked" and no_pr) or ($queued == 1 and .outcome == "nothing-to-take");
1345
+ def superseded($rows): . as $r | any($rows[]; .issue == $r.issue and .issue != "none" and .attempt > $r.attempt);'
1346
+
1347
+ # stop_state: why the shift stopped, in the words ADR 0003 fixes. The exit code names the
1348
+ # two failures. A reached --max, a budget cap and a reached sweep cap with work still
1349
+ # resumable are designed stops with work possibly left, so all three are the sweep's limit.
1350
+ # A shift whose remaining work stopped moving is stalled. Then the rows decide: nothing
1351
+ # worked is an empty frontier, every issue shipped and closed out is complete, and anything
1352
+ # else is handed to a person, with the summary saying what. A shipped pass whose closeout
1353
+ # stopped part-way left the rest of it to a person, so it is not complete.
1354
+ stop_state() {
1355
+ if [[ "$exit_code" -eq 2 ]]; then echo rate-limited
1356
+ elif [[ "$exit_code" -eq 1 ]]; then echo failed
1357
+ elif [[ "$STOP_KIND" == max || "$STOP_KIND" == budget || "$STOP_KIND" == sweeps ]]; then echo sweep-limit
1358
+ elif [[ "$STOP_KIND" == stalled ]]; then echo stalled
1359
+ else
1360
+ rows_json | jq -r --argjson queued "$HAS_QUEUE" "$EXCEPTION_JQ"'
1361
+ . as $rows
1362
+ | ([.[] | select(.outcome == "shipped" or .outcome == "parked" or .outcome == "failed" or .outcome == "interrupted")] | length) as $worked
1363
+ | (reduce .[] as $r ({}; if $r.issue == "none" then . else .[$r.issue] = $r.outcome end)) as $final
1364
+ | ([.[] | select(exception($queued) and (superseded($rows) | not))] | length) as $exceptions
1365
+ | if $worked == 0 then "frontier-empty"
1366
+ elif $exceptions == 0 and (any(.[]; closeout_incomplete) | not) and ([$final[] | select(. != "shipped")] | length) == 0 then "complete"
1367
+ else "review-ready" end'
1368
+ fi
1369
+ }
1370
+
1371
+ # write_summary: summary.json, the bounded record the launcher reports from: the stop state
1372
+ # and reason, one final row per distinct issue with its attempt count and typed state, the
1373
+ # aggregate counts, the PRs waiting for review, the shipped passes whose closeout is incomplete
1374
+ # with the step each stopped at, the issues that stalled, the attempts that need a person, and
1375
+ # the paths to the full evidence. No transcript, no result text, no log
1376
+ # tail: those stay in the files it names.
1377
+ write_summary() {
1378
+ local rows worktrees="{}" issue wt manifests briefs
1379
+ rows="$(rows_json)"
1380
+ for issue in $(jq -r '[.[] | .issue | select(. != "none")] | unique | .[]' <<< "$rows"); do
1381
+ wt="$(ls -d .claude/worktrees/*-"$issue" 2>/dev/null | head -1)"
1382
+ [[ -z "$wt" ]] || worktrees="$(jq -c --arg i "$issue" --arg w "$wt" '. + {($i): $w}' <<< "$worktrees")"
1383
+ done
1384
+ manifests="$(ls "$SHIFT_DIR"/sweep-*.json 2>/dev/null | awk -F'sweep-' '{print $NF + 0 "\t" $0}' | sort -n | cut -f2 | jq -R . | jq -sc .)"
1385
+ briefs="$(ls "$SHIFT_DIR"/continue-*.md 2>/dev/null | jq -R . | jq -sc .)"
1386
+ jq -n --arg shift "$SHIFT_ID" --arg stop "$STOP" --arg reason "$stop_reason" --argjson exit "$exit_code" \
1387
+ --argjson sweeps "$SWEEPS" --argjson swept "$SWEPT" --argjson max "$MAX" --argjson passes "$pass" \
1388
+ --argjson queued "$HAS_QUEUE" --argjson rows "$rows" --arg dir "$SHIFT_DIR" --argjson worktrees "$worktrees" \
1389
+ --argjson state "$ISSUE_STATE" --argjson manifests "$manifests" --argjson briefs "$briefs" \
1390
+ --argjson stacked "$STACKED_SWEEPS" --argjson satisfied "$STACK_SATISFIED" --argjson rejected "$STACK_REJECTED" \
1391
+ --argjson snapshot "$SNAPSHOT" --argjson adopts "$(adopts_json)" \
1392
+ --argjson taken "$ADOPT_TAKEN" --argjson refused "$ADOPT_REFUSED" --argjson fields "$(pass_row_fields)" \
1393
+ --argjson stage_failures "${SHIFT_STAGE_FAILURES:-[]}" "$EXCEPTION_JQ"'
1394
+ ($rows | reduce .[] as $r ({}; if $r.issue == "none" then . else
1395
+ .[$r.issue] = {outcome: $r.outcome, pr: $r.pr, branch: $r.branch, attempts: ((.[$r.issue].attempts // 0) + 1),
1396
+ last_pass: $r.pass, evidence: $r.artifact,
1397
+ state: ($state[$r.issue].state // null), stage: ($state[$r.issue].stage // null),
1398
+ worktree: ($state[$r.issue].worktree // null),
1399
+ base: ($state[$r.issue].base // null),
1400
+ fingerprint: {before: ($state[$r.issue].fingerprint_before // null),
1401
+ after: ($state[$r.issue].fingerprint // null)}} end)) as $issues
1402
+ | { shift: $shift, stop: $stop, stop_reason: $reason, exit: $exit,
1403
+ sweeps: {cap: $sweeps, run: $swept}, max: $max, passes: $passes,
1404
+ pass_rows: [$rows[] | . as $r | reduce $fields[] as $f ({}; .[$f] = $r[$f])],
1405
+ issues: $issues,
1406
+ counts: ($rows | reduce .[] as $r ({shipped: 0, parked: 0, failed: 0, locked: 0, "nothing-to-take": 0,
1407
+ "rate-limited": 0, "budget-stop": 0}; .[$r.outcome] += 1)),
1408
+ review_ready: ([$issues[] | select(.outcome == "parked" and (no_pr | not)) | .pr] | unique),
1409
+ closeout_incomplete: [$rows[] | select(closeout_incomplete)
1410
+ | {pass, issue, step: .closeout_step, pr, evidence: .artifact,
1411
+ worktree: ($issues[.issue].worktree | if . == "" then null else . end)}],
1412
+ interrupted: [$issues | to_entries[] | select(.value.outcome == "interrupted") | {issue: .key, state: .value.state, stage: .value.stage, reason: ($state[.key].reason // null)}],
1413
+ exhausted: [$issues | to_entries[] | select(($state[.key].disposition // "") == "retry-exhausted") | {issue: .key, stage: .value.stage, reason: ($state[.key].reason // null)}],
1414
+ merge_ready: (if $stacked == 1 then ([$satisfied[] | select(.by == "merge-ready") | .pr] | unique) else null end),
1415
+ blocked: (if $stacked == 1 then
1416
+ [$snapshot.excluded[] | select(.reason | startswith("blocked by "))
1417
+ | (.blockers | map(select($satisfied[tostring] == null))) as $unmet
1418
+ | {issue, blockers,
1419
+ reason: (if ($unmet | length) == 0 then "admissible on the next sweep: " + (.blockers | map("#\(.)") | join(" ")) + " merge-ready"
1420
+ else "blocked by " + ($unmet | map("#\(.)" + (if $rejected[tostring] != null then " (not merge-ready: \($rejected[tostring]))" else "" end)) | join(" ")) end)}]
1421
+ else null end),
1422
+ stack: (if $stacked == 1 then {satisfied: $satisfied, rejected: $rejected} else null end),
1423
+ stalled: [$issues | to_entries[] | select(.value.state == "stalled") | .key],
1424
+ shift_stages: $stage_failures,
1425
+ adopted: ($adopts | map(.shift as $s | . + {taken: [$taken[] | select(.shift == $s) | del(.shift)],
1426
+ refused: [$refused[] | select(.shift == $s) | del(.shift)]})
1427
+ | if length == 0 then null elif length == 1 then .[0] else . end),
1428
+ exceptions: [$rows[] | select(exception($queued) and (superseded($rows) | not))
1429
+ | {pass: .pass, issue: .issue, outcome: .outcome, evidence: .artifact}],
1430
+ evidence: { shift_log: "\($dir)/shift.log",
1431
+ manifests: $manifests,
1432
+ briefs: $briefs,
1433
+ passes: [$rows[] | select(.outcome != "rate-limited") | .artifact],
1434
+ rate_limited: [$rows[] | select(.outcome == "rate-limited") | .artifact],
1435
+ worktrees: $worktrees } }' > "$SHIFT_DIR/summary.json"
1436
+ }
1437
+
1438
+ # ---- the snapshot -----------------------------------------------------------------------
1439
+
1440
+ # The eligibility filter, one jq function for the epic and the workset alike: open, unassigned,
1441
+ # not locked by another run's worktree, and no open blocker, which is the frontier query
1442
+ # docs/agents/issue-tracker.md gives and the candidate rule /kryso's stage 1 applies.
1443
+ # blockedBy lists closed blockers too, so the filter reads each blocker's state rather than
1444
+ # the count. The shift's own record comes first: an issue this shift already worked to a
1445
+ # terminal state is out with that state, and one it owns and can prove resumable stays in,
1446
+ # though the tracker shows the assignment its own pass made and the worktree its own pass
1447
+ # cut, because the continuation rules in plan_sweep are what admit it. A child outside the
1448
+ # epic's scope, added after the shift started or closed when it started, is out with that
1449
+ # reason. Every node that fails the filter is kept with its reason and its open blockers,
1450
+ # so the manifest can say why each in-scope issue was left out.
1451
+ # shellcheck disable=SC2016 # jq's $variables, not the shell's
1452
+ SNAPSHOT_JQ='
1453
+ def open_blockers: [.blockedBy.nodes[]? | select(.state == "OPEN") | .number];
1454
+ def stacked: [open_blockers[] | select($satisfied[tostring] != null)];
1455
+ def unmet: [open_blockers[] | select($satisfied[tostring] == null)];
1456
+ def why_unmet: map("#\(.)" + (if $rejected[tostring] != null then " (not merge-ready: \($rejected[tostring]))" else "" end)) | join(" ");
1457
+ def recorded: $state[.number | tostring] // null;
1458
+ def reason:
1459
+ if .missing then "not found"
1460
+ elif .duplicate then "named earlier in the workset"
1461
+ elif .gone then "no longer a child of the epic"
1462
+ elif .state != "OPEN" then "closed"
1463
+ elif .outside then .outside
1464
+ elif recorded != null and recorded.state != "resumable" then "\(recorded.state) in pass \(recorded.last_pass)"
1465
+ elif recorded != null then null
1466
+ elif .assignees.totalCount > 0 then "assigned"
1467
+ elif $locks[.number | tostring] then "foreign lock \($locks[.number | tostring])"
1468
+ elif (unmet | length) > 0 then "blocked by \(unmet | why_unmet)"
1469
+ else null end;
1470
+ { candidates: [.[] | select(reason == null) | .number],
1471
+ excluded: [.[] | reason as $r | select($r != null) | {issue: .number, reason: $r, blockers: open_blockers}],
1472
+ stacked: ([.[] | select(reason == null) | {key: (.number | tostring), value: stacked}] | from_entries) }'
1473
+
1474
+ # snapshot_filter <nodes-json>: the filter over the nodes, with the shift's record and the
1475
+ # worktrees it does not own for the numbers in them.
1476
+ snapshot_filter() {
1477
+ local n wt locks='{}'
1478
+ for n in $(jq -r '.[].number' <<< "${1}"); do
1479
+ wt="$(worktree_for "$n" 2>/dev/null)" || continue
1480
+ is_owned "$wt" && continue
1481
+ [[ -z "$(st_get "$n" adopted)" ]] || continue
1482
+ locks="$(jq -c --arg i "$n" --arg w "$wt" '. + {($i): $w}' <<< "$locks")"
1483
+ done
1484
+ jq -c --argjson state "$ISSUE_STATE" --argjson locks "$locks" \
1485
+ --argjson satisfied "$STACK_SATISFIED" --argjson rejected "$STACK_REJECTED" "$SNAPSHOT_JQ" <<< "${1}"
1486
+ }
1487
+
1488
+ # The snapshot: SNAPSHOT is {candidates, excluded} as JSON, SNAPSHOT_AT the time it was
1489
+ # taken, and SNAPSHOT_ELIGIBILITY says whether the tracker was asked. Without a queue each
1490
+ # pass picks its own issue, so there is no snapshot to take and the manifest says so.
1491
+ SNAPSHOT='{"candidates":[],"excluded":[],"stacked":{}}'
1492
+ # The nodes the last live read gave the filter, so a change to the per-issue state before the
1493
+ # sweep runs can be filtered again without asking the tracker twice.
1494
+ SNAPSHOT_NODES=""
1495
+ SNAPSHOT_AT=""
1496
+ SNAPSHOT_ELIGIBILITY="per pass"
1497
+ SNAPSHOT_ORDER="label"
1498
+ NAMED_JSON="null"
1499
+ [[ -z "$ISSUES" ]] || NAMED_JSON="$(printf '%s\n' "${QUEUE[@]}" | jq -R 'tonumber' | jq -sc .)"
1500
+
1501
+ # read_epic_children: every sub-issue of the epic, into EPIC_NODES as one JSON array in GitHub's
1502
+ # order, one page of a hundred at a time through the connection's cursor until it says there
1503
+ # is no next page. Read whole because a scope cut at the first page would leave the rest of
1504
+ # the epic invisible to the shift, and --max would default from a number that is not the
1505
+ # epic's.
1506
+ read_epic_children() {
1507
+ local page nodes='[]' more=true cursor="" args
1508
+ while [[ "$more" == true ]]; do
1509
+ args=(-f owner="${name_with_owner%%/*}" -f name="${name_with_owner#*/}" -F number="$EPIC")
1510
+ [[ -z "$cursor" ]] || args+=(-f after="$cursor")
1511
+ # shellcheck disable=SC2016 # the $variables are GraphQL's, not the shell's
1512
+ page="$(gh api graphql \
1513
+ -f query='query($owner: String!, $name: String!, $number: Int!, $after: String) {
1514
+ repository(owner: $owner, name: $name) {
1515
+ issue(number: $number) {
1516
+ subIssues(first: 100, after: $after) {
1517
+ pageInfo { hasNextPage endCursor }
1518
+ nodes { number state assignees(first: 1) { totalCount } blockedBy(first: 20) { nodes { number state } } }
1519
+ }
1520
+ }
1521
+ }
1522
+ }' "${args[@]}" 2>/dev/null)" || die_if_silent "$?" "the sub-issues of #$EPIC"
1523
+ jq -e '.data.repository.issue.subIssues' <<< "$page" >/dev/null 2>&1 \
1524
+ || die "cannot read the sub-issues of #$EPIC${cursor:+ past cursor $cursor}. Is it an issue in this repo?"
1525
+ nodes="$(jq -c --argjson page "$(jq -c '.data.repository.issue.subIssues.nodes' <<< "$page")" '. + $page' <<< "$nodes")"
1526
+ more="$(jq -r '.data.repository.issue.subIssues.pageInfo.hasNextPage' <<< "$page")"
1527
+ cursor="$(jq -r '.data.repository.issue.subIssues.pageInfo.endCursor // ""' <<< "$page")"
1528
+ [[ "$more" != true || -n "$cursor" ]] || die "the sub-issues of #$EPIC say there is a next page but name no cursor to read it from"
1529
+ done
1530
+ EPIC_NODES="$nodes"
1531
+ }
1532
+
1533
+ # The epic's scope, fixed by the first read: the children open then, which are the ones this
1534
+ # shift may admit, and beside it every child that read discovered, whatever its state, so a
1535
+ # later read can tell a child reopened since from one added since. Empty until the first read.
1536
+ EPIC_DISCOVERED="[]"
1537
+ EPIC_SCOPE=""
1538
+
1539
+ # take_snapshot: one live eligibility check, into SNAPSHOT and QUEUE. Every sweep takes its
1540
+ # own, so a later sweep sees what the tracker shows now rather than what it showed at the
1541
+ # start of the shift. Read live and never cached, for the reason the tracker doc gives for
1542
+ # board ids, and filtered with real jq, so the filter is the driver's and not the tracker's
1543
+ # to get wrong.
1544
+ take_snapshot() {
1545
+ # A stacked sweep reads the merge-ready evidence of what the shift owns before the tracker,
1546
+ # because the filter treats a merge-ready blocker as satisfied.
1547
+ [[ "$STACKED_SWEEPS" -eq 0 ]] || stack_evaluate
1548
+ # An epic's queue is its sub-issues through the GraphQL connection, every page of it, in the
1549
+ # order GitHub returns them. The first read fixes the shift's scope: the children open at
1550
+ # that moment. Every later read is placed against that scope, so a child added to the epic
1551
+ # after the shift started waits for a later shift, one that was closed when it started
1552
+ # stays out, and one no longer listed is named as gone rather than quietly dropped.
1553
+ local nodes
1554
+ if [[ -n "$EPIC" ]]; then
1555
+ [[ "$TRACKER" == reachable ]] || die "--epic needs a GitHub remote to read the sub-issues from"
1556
+ repo_name_with_owner epic
1557
+ SNAPSHOT_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
1558
+ read_epic_children
1559
+ if [[ -z "$EPIC_SCOPE" ]]; then
1560
+ EPIC_DISCOVERED="$(jq -c '[.[].number]' <<< "$EPIC_NODES")"
1561
+ EPIC_SCOPE="$(jq -c '[.[] | select(.state == "OPEN") | .number]' <<< "$EPIC_NODES")"
1562
+ nodes="$EPIC_NODES"
1563
+ else
1564
+ # A child the first read found closed and the live read shows open was reopened since;
1565
+ # the reason says so, because "closed" is what the read would say of it otherwise.
1566
+ nodes="$(jq -c --argjson scope "$EPIC_SCOPE" --argjson discovered "$EPIC_DISCOVERED" '
1567
+ . as $read
1568
+ | [.[] | if (.number | IN($scope[])) then .
1569
+ elif (.number | IN($discovered[])) then . + {outside: "reopened after the shift started"}
1570
+ else . + {outside: "added after the shift started"} end]
1571
+ + [$scope[] | select(IN($read[].number) | not) | {number: ., gone: true}]' <<< "$EPIC_NODES")"
1572
+ fi
1573
+ SNAPSHOT_NODES="$nodes"
1574
+ SNAPSHOT="$(snapshot_filter "$nodes")"
1575
+ SNAPSHOT_ELIGIBILITY="live"
1576
+ SNAPSHOT_ORDER="github"
1577
+ read -r -a QUEUE <<< "$(jq -r '.candidates | map(tostring) | join(" ")' <<< "$SNAPSHOT")"
1578
+ # The blocked children are named with their open blockers, so a queue shorter than the
1579
+ # epic can be read against the tracker rather than guessed at.
1580
+ BLOCKED="$(jq -r '.excluded[] | select(.reason | startswith("blocked by ")) | "\(.issue) (\(.blockers | map("#\(.)") | join(" ")))"' <<< "$SNAPSHOT" | tr '\n' ' ' | sed 's/ $//')"
1581
+ fi
1582
+
1583
+ # A workset under --sweeps is checked live the same way, one aliased issue per named number
1584
+ # in one query, so the snapshot is the caller's issues and nothing else: no sibling is read,
1585
+ # even when they share an epic. Without --sweeps the workset runs as given, and a taken or
1586
+ # closed issue is that pass's own answer, as it always was.
1587
+ if [[ -n "$ISSUES" && "$SWEEPS_SET" -eq 0 ]]; then
1588
+ SNAPSHOT="$(jq -c --argjson named "$NAMED_JSON" '{candidates: $named, excluded: []}' <<< '{}')"
1589
+ SNAPSHOT_ELIGIBILITY="as given"
1590
+ SNAPSHOT_ORDER="caller"
1591
+ fi
1592
+ if [[ -n "$ISSUES" && "$SWEEPS_SET" -eq 1 ]]; then
1593
+ repo_name_with_owner snapshot
1594
+ local query='query($owner: String!, $name: String!' fields='' i=0 n answer
1595
+ local args=(-f owner="${name_with_owner%%/*}" -f name="${name_with_owner#*/}")
1596
+ read -r -a NAMED <<< "$(jq -r 'map(tostring) | join(" ")' <<< "$NAMED_JSON")"
1597
+ for n in "${NAMED[@]}"; do
1598
+ query+=", \$n$i: Int!"
1599
+ fields+=" i$i: issue(number: \$n$i) { number state assignees(first: 1) { totalCount } blockedBy(first: 20) { nodes { number state } } }"
1600
+ args+=(-F "n$i=$n")
1601
+ i=$((i + 1))
1602
+ done
1603
+ query+=") { repository(owner: \$owner, name: \$name) {$fields } }"
1604
+ SNAPSHOT_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
1605
+ # The answer is read even when gh exits 1, because a number that is not an issue makes the
1606
+ # whole call an error while the other aliases still come back filled.
1607
+ answer="$(gh api graphql -f query="$query" "${args[@]}" 2>/dev/null)" || die_if_silent "$?" "the workset's issues"
1608
+ jq -e '.data.repository | type == "object"' <<< "$answer" >/dev/null 2>&1 \
1609
+ || die "cannot read the workset's issues for the snapshot. Are they issues in this repo?"
1610
+ # The aliases back in caller order, a missing one standing in for an issue that is not in
1611
+ # the repo, and a repeat of an earlier number marked so it is excluded rather than run twice.
1612
+ SNAPSHOT_NODES="$(jq -c --argjson named "$NAMED_JSON" '
1613
+ .data.repository as $r
1614
+ | [range(0; $named | length) as $i
1615
+ | ($r["i\($i)"] // {number: $named[$i], missing: true})
1616
+ | if ([$named[:$i][] | select(. == $named[$i])] | length) > 0 then . + {duplicate: true} else . end]' <<< "$answer")"
1617
+ SNAPSHOT="$(snapshot_filter "$SNAPSHOT_NODES")"
1618
+ SNAPSHOT_ELIGIBILITY="live"
1619
+ SNAPSHOT_ORDER="caller"
1620
+ read -r -a QUEUE <<< "$(jq -r '.candidates | map(tostring) | join(" ")' <<< "$SNAPSHOT")"
1621
+ fi
1622
+ EXCLUDED="$(jq -r '.excluded | map("\(.issue) (\(.reason))") | join(" ")' <<< "$SNAPSHOT")"
1623
+ }
1624
+
1625
+ # ---- the per-issue state ----------------------------------------------------------------
1626
+ #
1627
+ # ISSUE_STATE is one JSON object, keyed by issue, holding what the supervisor knows about
1628
+ # each issue it has admitted: the typed state read off the evidence the last pass left, the
1629
+ # recorded stage, the worktree the shift owns for it, the fingerprint before and after the
1630
+ # last pass, the attempts so far and the last saved result. It is the whole memory a later
1631
+ # sweep has, and none of it is model text.
1632
+ ISSUE_STATE='{}'
1633
+ # The stack's record under a stacked sweep, keyed by issue: STACK_SATISFIED holds every
1634
+ # shift-owned issue whose evidence satisfies the blockers it stands in, with what was read,
1635
+ # and STACK_REJECTED every admitted issue whose evidence does not, with why. Both are
1636
+ # re-read live before every sweep and written to that sweep's manifest and the summary.
1637
+ # They live in the shift's evidence and nowhere else: the tracker is never told.
1638
+ STACK_SATISFIED='{}'
1639
+ STACK_REJECTED='{}'
1640
+ SWEEP_HELD='[]' # what the current sweep's plan held back, with the reason, for the stack line
1641
+ st_get() { jq -r --arg i "$1" --arg k "$2" '.[$i][$k] // ""' <<< "$ISSUE_STATE"; }
1642
+ st_set() { ISSUE_STATE="$(jq -c --arg i "$1" --arg k "$2" --arg v "$3" '.[$i][$k] = $v' <<< "$ISSUE_STATE")"; }
1643
+ st_issues() { jq -r 'keys_unsorted[]' <<< "$ISSUE_STATE"; }
1644
+ ADMITTED=() # distinct issues admitted to the shift, in the order they were admitted
1645
+
1646
+ # digest: a sha256 hex digest of stdin, with whichever of the two tools the machine has.
1647
+ digest() {
1648
+ if command -v shasum >/dev/null 2>&1; then shasum -a 256 | cut -c1-64
1649
+ else sha256sum | cut -c1-64; fi
1650
+ }
1651
+
1652
+ # worktree_for <issue>: the worktree under .claude/worktrees ending in -<issue> whose ledger
1653
+ # names the issue, relative to the repo root, or nothing. A directory without a ledger is
1654
+ # nobody's resume point. The read is ledger.sh's.
1655
+ worktree_for() { ledger worktree . "$1"; }
1656
+
1657
+ # is_owned <worktree>: whether this shift stamped the worktree's ledger as its own.
1658
+ is_owned() { [[ -n "${SHIFT_ID:-}" ]] && [[ "$(ledger_text "$1" | jq -r '.owner.shift // ""')" == "$SHIFT_ID" ]]; }
1659
+
1660
+ # owned_worktree <issue>: the worktree this shift stamped as its own, or nothing.
1661
+ owned_worktree() {
1662
+ local wt
1663
+ wt="$(worktree_for "$1")" || return 1
1664
+ is_owned "$wt" || return 1
1665
+ printf '%s' "$wt"
1666
+ }
1667
+
1668
+ # admitted <issue>: whether the issue is among the distinct issues admitted to the shift.
1669
+ admitted() { local i; for i in ${ADMITTED[@]+"${ADMITTED[@]}"}; do [[ "$i" != "$1" ]] || return 0; done; return 1; }
1670
+
1671
+ # fingerprint_of <worktree> <pr> <issue>: the progress fingerprint, computed by the shell
1672
+ # from durable evidence alone: the commit, the working-tree status and diff, the last ledger
1673
+ # event that is progress, the PR's head and state, its checks, the actionable review evidence
1674
+ # on it, and the issue's open blockers in the current snapshot. Two passes that leave the same
1675
+ # fingerprint made no progress a continuation could build on. The ledger event is the
1676
+ # module's `progress`, so a time, a checkpoint, a dispatch, a resume line, an attempt count, an
1677
+ # interruption or a handoff moves nothing.
1678
+ fingerprint_of() {
1679
+ local wt="$1" pr="$2" issue="$3" head status diff last pr_json checks feedback blockers n
1680
+ head="$(git -C "$wt" rev-parse HEAD 2>/dev/null)"
1681
+ status="$(git -C "$wt" status --porcelain 2>/dev/null)"
1682
+ diff="$(git -C "$wt" diff HEAD 2>/dev/null | digest)"
1683
+ last="$(ledger_text "$wt" | jq -r '.progress // ""')"
1684
+ pr_json=""; checks=""; feedback=""
1685
+ if [[ -n "$pr" && "$pr" != none ]]; then
1686
+ pr_json="$(gh pr view "$pr" --json headRefOid,state,mergeable 2>/dev/null | jq -c . 2>/dev/null)"
1687
+ checks="$(gh pr checks "$pr" --json bucket,name,state 2>/dev/null | jq -c 'sort_by(.name)' 2>/dev/null)"
1688
+ # The actionable set's evidence digest: a repeated notice, an approval or an edited
1689
+ # timestamp leaves it where it was, and an answered or a new finding moves it.
1690
+ feedback="$(pr_feedback "$pr")" && feedback="$(jq -r '.evidence' <<< "$feedback" 2>/dev/null)"
1691
+ fi
1692
+ blockers="$(jq -c --argjson i "$issue" '[.excluded[] | select(.issue == $i) | .blockers[]]' <<< "$SNAPSHOT" 2>/dev/null)"
1693
+ printf '%s\n' "$head" "$status" "$diff" "$last" "$pr_json" "$checks" "$feedback" "$blockers" | digest
1694
+ }
1695
+
1696
+ # unsafe_continuation <worktree>: why the worktree's evidence cannot be continued from, or
1697
+ # nothing: a checkpoint that does not parse, a disposition the ledger was never taught, a tree
1698
+ # on another branch than its ledger's, or a HEAD that no longer contains the checkpoint's head.
1699
+ # The same refusals the pass script's resume makes, read here so the ship-it engine gets them.
1700
+ unsafe_continuation() {
1701
+ local wt="$1" doc branch on head
1702
+ doc="$(ledger read "$wt")"
1703
+ [[ "$(jq -r '.checkpoint_error // ""' <<< "$doc")" == "" ]] || { jq -r '.checkpoint_error' <<< "$doc"; return 0; }
1704
+ [[ "$(jq -r '.disposition_known' <<< "$doc")" != false ]] || { echo "the disposition '$(jq -r .disposition <<< "$doc")' is not one the ledger knows"; return 0; }
1705
+ branch="$(jq -r '.header.branch // ""' <<< "$doc")"
1706
+ on="$(git -C "$wt" symbolic-ref -q --short HEAD 2>/dev/null)"
1707
+ [[ -z "$branch" || "$on" == "$branch" ]] || { echo "the worktree is on ${on:-a detached HEAD}, not the ledger's branch $branch"; return 0; }
1708
+ head="$(jq -r '.checkpoint.head // ""' <<< "$doc")"
1709
+ [[ -z "$head" || "$head" == none ]] || git -C "$wt" merge-base --is-ancestor "$head" HEAD 2>/dev/null \
1710
+ || { echo "HEAD does not contain the checkpoint's head ${head:0:12}"; return 0; }
1711
+ return 0
1712
+ }
1713
+
1714
+ # pr_feedback <pr>: the PR's review feedback, read whole and classified by feedback.sh, the
1715
+ # module the pass script reads it with, so the driver and the pass sort the same item the
1716
+ # same way. Prints the classified document, or `unreadable: <why>` with status 1 when any
1717
+ # read fails, so a reader that needs the answer fails closed and a fingerprint that digests
1718
+ # it still changes when the read comes back.
1719
+ pr_feedback() {
1720
+ local n="${1##*/}" nwo
1721
+ [[ "$n" =~ ^[0-9]+$ ]] || { echo "unreadable: '$1' names no pull request number"; return 1; }
1722
+ # Not repo_name_with_owner, whose die would end only the command substitution this is read in.
1723
+ nwo="$(read_name_with_owner)" || { echo "unreadable: cannot read this repo's owner and name"; return 1; }
1724
+ feedback_actionable "$nwo" "$n"
1725
+ }
1726
+
1727
+ # classify <issue> <outcome> <pr> <is_error> <worktree> <owned> <stopped> [<closeout-step>]
1728
+ # [<open-receipt>]: the typed state of an issue after a pass, from the outcome the host reported
1729
+ # and the evidence in the worktree, into CLS_STATE, CLS_STAGE and CLS_REASON. <stopped> is the
1730
+ # deadline report's word for how the allowance's stop went (confirmed, unconfirmed or exited),
1731
+ # or empty when the pass's result carries no deadline report. <open-receipt> is the log of a
1732
+ # receipt still open past --receipt-wait, which makes an interrupted pass resumable at its
1733
+ # stage once that receipt closes, never before. Only the supervisor's evidence can make an issue
1734
+ # resumable: an owned worktree whose ledger stopped at a stage a fresh pass can pick up, a
1735
+ # reconcile park on actionable CI or bot evidence, or a host that died after durable work.
1736
+ # A human gate, a foreign lock, a missing prerequisite, an open PR against the base and a
1737
+ # failure the pass itself called terminal are all terminal for this shift. A shipped pass is
1738
+ # done, unless its block named a step its closeout stopped at: its merge stands and nothing
1739
+ # continues it here, so the step is a person's to finish. The disposition is
1740
+ # ledger.sh's, the one table both engines are read through; the policy over it is this
1741
+ # driver's.
1742
+ classify() {
1743
+ local issue="$1" outcome="$2" pr="$3" is_error="$4" wt="$5" owned="$6" stopped="$7" step="${8:-}" receipt="${9:-}" doc last stage park_stage word disposition
1744
+ CLS_STATE=""; CLS_STAGE=""; CLS_REASON=""; CLS_DISPOSITION=""
1745
+ case "$outcome" in
1746
+ shipped)
1747
+ CLS_STATE="done"; CLS_REASON="shipped"
1748
+ if [[ -n "$step" ]]; then
1749
+ CLS_STATE=closeout-incomplete; CLS_STAGE=closeout; CLS_REASON="shipped, its closeout incomplete at the $step"
1750
+ fi
1751
+ return 0 ;;
1752
+ nothing-to-take|locked) CLS_STATE=not-taken; CLS_REASON="$outcome: locked or taken elsewhere"; return 0 ;;
1753
+ budget-stop|rate-limited) CLS_STATE=interrupted; CLS_REASON="$outcome"; return 0 ;;
1754
+ esac
1755
+ if [[ -n "$wt" && "$owned" -eq 0 ]]; then
1756
+ CLS_STATE=foreign-lock; CLS_REASON="$wt was not cut by this shift"; return 0
1757
+ fi
1758
+ # A pass the allowance stopped. Its process tree confirmed stopped, it continues from the
1759
+ # stage its ledger records, or from the claim when it stopped before its cut, with a new
1760
+ # allowance in a later sweep; unconfirmed, nothing continues it, because its processes may
1761
+ # still be writing.
1762
+ if [[ "$outcome" == interrupted ]]; then
1763
+ CLS_DISPOSITION=resumable
1764
+ # A session that exited on its own with a receipt still open: resumable once that receipt
1765
+ # closes. One the allowance stopped keeps the deadline's rules, so an unconfirmed stop is
1766
+ # never continued, and its reason names the receipt as well.
1767
+ if [[ -n "$receipt" && -n "$wt" && -z "$stopped" ]]; then
1768
+ CLS_STATE=resumable
1769
+ CLS_STAGE="$(ledger read "$wt" | jq -r '.stage.name // ""')"
1770
+ CLS_REASON="its session exited with $receipt still open after the ${RECEIPT_WAIT}s receipt wait, so no sweep continues it until that receipt closes"
1771
+ elif [[ "$stopped" != confirmed ]]; then
1772
+ CLS_STATE=interrupted; CLS_DISPOSITION=""
1773
+ CLS_REASON="the allowance ran out and its processes were ${stopped:-not} confirmed stopped, so nothing continues it"
1774
+ elif [[ -z "$wt" ]]; then
1775
+ CLS_STATE=resumable; CLS_STAGE=claim; CLS_REASON="interrupted before its cut; the next pass claims again"
1776
+ else
1777
+ doc="$(ledger read "$wt")"
1778
+ CLS_STATE=resumable
1779
+ CLS_STAGE="$(jq -r '.interruption.stage // .stage.name // ""' <<< "$doc")"
1780
+ CLS_REASON="interrupted at ${CLS_STAGE:-its stage} after $(jq -r '.interruption.consumed // "?"' <<< "$doc")s of a $(jq -r '.interruption.allowance // "?"' <<< "$doc")s allowance"
1781
+ fi
1782
+ [[ -z "$receipt" || -z "$stopped" ]] || CLS_REASON+=", with $receipt still open after the ${RECEIPT_WAIT}s receipt wait"
1783
+ return 0
1784
+ fi
1785
+ if [[ -z "$wt" ]]; then
1786
+ case "$outcome" in
1787
+ parked) if [[ -n "$pr" && "$pr" != none ]]; then CLS_STATE="review-ready"; CLS_REASON="PR open, no worktree to continue in"
1788
+ else CLS_STATE=no-worktree; CLS_REASON="parked without a worktree to continue in"; fi ;;
1789
+ *) CLS_STATE=failed; CLS_REASON="$outcome with no worktree left" ;;
1790
+ esac
1791
+ return 0
1792
+ fi
1793
+ # An owned worktree. The document's last event gives the recorded stage, its park the kind,
1794
+ # while the pass still stands at that park: one a later checkpoint moved past, a reconcile
1795
+ # park before a merge, is history and no longer says what kind of stop this is.
1796
+ # A receipt's start and end lines are not a stage a continuation can enter, and a session that
1797
+ # exited with a receipt open always ends on one, so the last event is read past them.
1798
+ doc="$(ledger read "$wt")"
1799
+ last="$(jq -r '[.events[] | select(.stage != "receipt")] | last | if . == null then "" else "\(.stage) \(.outcome) \(.evidence)" end' <<< "$doc")"
1800
+ stage="${last%% *}"
1801
+ park_stage="$(jq -r 'if .stage.status == "parked" then .park.stage // "" else "" end' <<< "$doc")"
1802
+ word="$(jq -r 'if .stage.status == "parked" then .park.word // "" else "" end' <<< "$doc")"
1803
+ disposition="$(jq -r '.disposition // ""' <<< "$doc")"
1804
+ CLS_DISPOSITION="$disposition"
1805
+ if [[ "$outcome" == failed ]]; then
1806
+ CLS_STATE=failed; CLS_STAGE="$stage"; CLS_REASON="the pass reported failed"; return 0
1807
+ fi
1808
+ if [[ "$outcome" == none || "$is_error" == true ]]; then
1809
+ # A host that died: no outcome block, but durable work in an owned tree. Continue from the
1810
+ # recorded stage.
1811
+ CLS_STATE=resumable; CLS_STAGE="$stage"; CLS_REASON="host interrupted after ${last:-the claim}"
1812
+ [[ -n "$park_stage" ]] || return 0
1813
+ fi
1814
+ if [[ -z "$park_stage" ]]; then
1815
+ if [[ -n "$pr" && "$pr" != none ]]; then CLS_STATE="review-ready"; CLS_STAGE="$stage"; CLS_REASON="PR open, no park line"
1816
+ else CLS_STATE=resumable; CLS_STAGE="$stage"; CLS_REASON="parked without a park line after ${last:-the claim}"; fi
1817
+ return 0
1818
+ fi
1819
+ CLS_STAGE="$park_stage"
1820
+ CLS_REASON="$park_stage parked ${word}"
1821
+ # The ledger's table types the reconcile words too: a reconciliation context's hand-back is
1822
+ # human-decision, and a failure the pass's own contexts could not change is retry-exhausted.
1823
+ # What the table cannot see is the count. Evidence that needs another reconciliation, with
1824
+ # the issue's three spent, is failed for the shift under either engine: the cap never resets,
1825
+ # so a continuation could only park on it again.
1826
+ if [[ "$park_stage" == reconcile && "$disposition" == resumable ]]; then
1827
+ case "$word" in
1828
+ ci-red|gate-red|feedback-open)
1829
+ if [[ "$(jq -r '.reconciliations.left // 1' <<< "$doc")" -eq 0 ]]; then
1830
+ CLS_STATE=failed; CLS_REASON="$park_stage parked $word with the issue's reconciliations spent ($(jq -r '.reconciliations.used' <<< "$doc")/3)"; return 0
1831
+ fi ;;
1832
+ esac
1833
+ fi
1834
+ local spent="the pass's own rerun"
1835
+ [[ "$park_stage" != reconcile ]] || spent="the pass's own reconciliation contexts"
1836
+ case "$disposition" in
1837
+ terminal) if [[ "$park_stage" == merge || "$word" == pr-open ]]; then CLS_STATE="review-ready"
1838
+ else CLS_STATE=parked-terminal; CLS_REASON="$park_stage parked ${word} is not a state this driver continues"; fi ;;
1839
+ human-decision) CLS_STATE=human-decision
1840
+ [[ "$park_stage" != reconcile ]] || CLS_REASON="$park_stage parked $word by a reconciliation context" ;;
1841
+ retry-exhausted) CLS_STATE=failed; CLS_REASON="$park_stage parked $word after $spent" ;;
1842
+ prerequisite) CLS_STATE=missing-prerequisite ;;
1843
+ resumable) CLS_STATE=resumable ;;
1844
+ # A disposition this driver was never taught is never read as resumable.
1845
+ *) CLS_STATE=parked-terminal; CLS_REASON="$park_stage parked ${word} with the unknown disposition '$disposition'" ;;
1846
+ esac
1847
+ }
1848
+
1849
+
1850
+ # ---- the stack ---------------------------------------------------------------------------
1851
+ #
1852
+ # Under --stack with --sweeps, a shift-owned child may satisfy an internal dependency before
1853
+ # a person merges its pull request, on evidence the driver reads itself. merge_ready is the
1854
+ # read, merge-ready.sh's dependent rule is the rule, and reference/sweeps.md is its prose. A
1855
+ # shipped child, merged into the branch it was based on, satisfies its dependents from that
1856
+ # branch. The tracker's own state stays authoritative for a blocker the shift did not work,
1857
+ # and nothing here closes, edits or merges anything on GitHub.
1858
+
1859
+ # merge_ready <issue>: MR_REASON when the issue's evidence does not make it merge-ready for a
1860
+ # dependent, else empty with MR_HEAD, MR_BRANCH and MR_EVIDENCE. The shift's own records come
1861
+ # first: a worktree it owns, the branch and the PR it recorded. The evidence is merge-ready.sh's
1862
+ # dependent rule, read live, and every read fails closed: a PR the driver cannot read, a head it
1863
+ # did not push and a check it cannot see all keep the dependent blocked.
1864
+ merge_ready() {
1865
+ local issue="$1" wt branch pr nwo
1866
+ MR_REASON=""; MR_HEAD=""; MR_BRANCH=""; MR_EVIDENCE=""
1867
+ wt="$(owned_worktree "$issue")" || { MR_REASON="no worktree owned by this shift"; return 1; }
1868
+ branch="$(st_get "$issue" branch)"
1869
+ [[ -n "$branch" && "$branch" != none ]] || { MR_REASON="no branch recorded"; return 1; }
1870
+ pr="$(st_get "$issue" pr)"
1871
+ [[ -n "$pr" && "$pr" != none ]] || { MR_REASON="no pull request"; return 1; }
1872
+ # Not repo_name_with_owner, whose die would end only the command substitution this is read in.
1873
+ nwo="$(read_name_with_owner)" || nwo=""
1874
+ merge_ready_read dependent "$wt" "$branch" "$pr" "$nwo" || return 1
1875
+ MR_BRANCH="$branch"
1876
+ return 0
1877
+ }
1878
+
1879
+ # stack_evaluate: STACK_SATISFIED and STACK_REJECTED from the admitted issues' evidence, read
1880
+ # now. A review-ready issue is merge-ready or not by merge_ready; a shipped one satisfies from
1881
+ # the branch it was based on, because that is where its merge put the work, whatever its
1882
+ # closeout reached; everything else
1883
+ # is not evidence of anything a dependent can build on. The sweep an issue was first read as
1884
+ # satisfied in stays on its record.
1885
+ stack_evaluate() {
1886
+ local issue state reason pr by branch head evidence first
1887
+ STACK_REJECTED='{}'
1888
+ for issue in ${ADMITTED[@]+"${ADMITTED[@]}"}; do
1889
+ state="$(st_get "$issue" state)"
1890
+ pr="$(st_get "$issue" pr)"
1891
+ by=""; branch=""; head=""; evidence=""
1892
+ if [[ "$state" == review-ready ]]; then
1893
+ if merge_ready "$issue"; then by=merge-ready; branch="$MR_BRANCH"; head="$MR_HEAD"; evidence="$MR_EVIDENCE"
1894
+ else reason="$MR_REASON"; fi
1895
+ elif [[ "$state" == closeout-incomplete || ( "$state" == "done" && "$(st_get "$issue" reason)" == shipped ) ]]; then
1896
+ by=shipped; branch="$(st_get "$issue" base)"; [[ -n "$branch" ]] || branch="$BASE"
1897
+ evidence="shipped in pass $(st_get "$issue" last_pass), merged into $branch"
1898
+ else
1899
+ reason="$state"
1900
+ [[ -n "$pr" && "$pr" != none ]] || reason+=", no pull request"
1901
+ fi
1902
+ if [[ -n "$by" ]]; then
1903
+ first="$(jq -r --arg i "$issue" '.[$i].sweep // ""' <<< "$STACK_SATISFIED")"
1904
+ [[ -n "$first" ]] || first="$SWEEP"
1905
+ STACK_SATISFIED="$(jq -c --arg i "$issue" --arg by "$by" --arg b "$branch" --arg pr "${pr:-none}" --arg h "$head" \
1906
+ --arg e "$evidence" --argjson sweep "$first" \
1907
+ '.[$i] = {by: $by, branch: $b, pr: $pr, head: (if $h == "" then null else $h end), evidence: $e, sweep: $sweep}' <<< "$STACK_SATISFIED")"
1908
+ else
1909
+ STACK_SATISFIED="$(jq -c --arg i "$issue" 'del(.[$i])' <<< "$STACK_SATISFIED")"
1910
+ STACK_REJECTED="$(jq -c --arg i "$issue" --arg r "$reason" '.[$i] = $r' <<< "$STACK_REJECTED")"
1911
+ fi
1912
+ done
1913
+ }
1914
+
1915
+ # carries <branch> <target>: whether the branch was cut, through the shift's own chain of
1916
+ # bases, from the target, so work on the target is in it.
1917
+ carries() {
1918
+ local x="$1" issue n=0
1919
+ while [[ -n "$x" && "$x" != "$BASE" && "$n" -lt 50 ]]; do
1920
+ issue="$(jq -r --arg b "$x" 'to_entries[] | select(.value.branch == $b) | .key' <<< "$ISSUE_STATE" | head -1)"
1921
+ [[ -n "$issue" ]] || return 1
1922
+ x="$(st_get "$issue" base)"
1923
+ [[ "$x" != "$2" ]] || return 0
1924
+ n=$((n + 1))
1925
+ done
1926
+ return 1
1927
+ }
1928
+
1929
+ # stack_base_for <issue>: STACK_BASE, the branch a newly eligible issue bases on: the shift
1930
+ # base when no open blocker of its is virtually satisfied, else the one branch that carries
1931
+ # every satisfied blocker's work. Two branches neither of which carries the other is
1932
+ # STACK_HOLD instead, because there is no branch to base on and a guess is what the chain
1933
+ # exists to prevent.
1934
+ stack_base_for() {
1935
+ local issue="$1" b carrier carriers=() by_issue=() keep=() named=() c d contained
1936
+ STACK_BASE="$BASE"; STACK_HOLD=""
1937
+ for b in $(jq -r --arg i "$issue" '.stacked[$i] // [] | .[]' <<< "$SNAPSHOT"); do
1938
+ carrier="$(jq -r --arg b "$b" '.[$b].branch // ""' <<< "$STACK_SATISFIED")"
1939
+ [[ -n "$carrier" && "$carrier" != "$BASE" ]] || continue
1940
+ carriers+=("$carrier"); by_issue+=("$b")
1941
+ done
1942
+ [[ "${#carriers[@]}" -gt 0 ]] || return 0
1943
+ for c in "${!carriers[@]}"; do
1944
+ contained=0
1945
+ for d in "${carriers[@]}"; do
1946
+ [[ "${carriers[$c]}" != "$d" ]] || continue
1947
+ if carries "$d" "${carriers[$c]}"; then contained=1; break; fi
1948
+ done
1949
+ [[ "$contained" -eq 1 ]] || { keep+=("${carriers[$c]}"); named+=("${carriers[$c]} (#${by_issue[$c]})"); }
1950
+ done
1951
+ if [[ "${#keep[@]}" -eq 1 ]]; then STACK_BASE="${keep[0]}"; return 0; fi
1952
+ STACK_HOLD="stacked on more than one branch: $(printf '%s, ' "${named[@]}" | sed 's/, $//')"
1953
+ return 1
1954
+ }
1955
+
1956
+ # stack_line: the stack's state in one line for a person: what is merge-ready with its branch
1957
+ # and PR, what shipped and where its work sits, what is still blocked and by what, and what
1958
+ # the plan held for want of one branch.
1959
+ stack_line() {
1960
+ local out mr shipped blocked held
1961
+ mr="$(jq -r 'to_entries | map(select(.value.by == "merge-ready")) | sort_by(.key | tonumber) | map("#\(.key) (\(.value.branch), \(.value.pr))") | join(", ")' <<< "$STACK_SATISFIED")"
1962
+ shipped="$(jq -r 'to_entries | map(select(.value.by == "shipped")) | sort_by(.key | tonumber) | map("#\(.key) (into \(.value.branch))") | join(", ")' <<< "$STACK_SATISFIED")"
1963
+ blocked="$(jq -r --argjson rejected "$STACK_REJECTED" '
1964
+ .excluded | map(select(.reason | startswith("blocked by ")))
1965
+ | map("#\(.issue) (by " + (.blockers | map("#\(.): \($rejected[tostring] // "open")") | join("; ")) + ")") | join(", ")' <<< "$SNAPSHOT")"
1966
+ held="$(jq -r '[.[] | select(.reason | startswith("stacked on "))] | map("#\(.issue) (\(.reason))") | join(", ")' <<< "${SWEEP_HELD:-[]}")"
1967
+ out="stack: merge-ready ${mr:-none}"
1968
+ [[ -z "$shipped" ]] || out+=" ◦ shipped $shipped"
1969
+ out+=" ◦ blocked ${blocked:-none}"
1970
+ [[ -z "$held" ]] || out+=" ◦ held $held"
1971
+ printf '%s' "$out"
1972
+ }
1973
+
1974
+ # stack_admissible: the issues the last snapshot left blocked whose every open blocker the
1975
+ # evidence, as last evaluated, satisfies, as a clause for the sweep-cap stop. A cap that
1976
+ # stopped the shift with one of these waiting is the cap's limit, not the frontier's.
1977
+ stack_admissible() {
1978
+ local left
1979
+ left="$(jq -r --argjson satisfied "$STACK_SATISFIED" '
1980
+ [.excluded[] | select(.reason | startswith("blocked by ")) | select(all(.blockers[]; $satisfied[tostring] != null))]
1981
+ | if length == 0 then "" else
1982
+ (map("#\(.issue)") | join(" ")) + " admissible on the next sweep: "
1983
+ + (if length == 1 then "its blocker " + (.[0].blockers | map("#\(.)") | join(" ")) + " is merge-ready"
1984
+ else "blockers " + ([.[].blockers[]] | unique | map("#\(.)") | join(" ")) + " are merge-ready" end) end' <<< "$SNAPSHOT")"
1985
+ printf '%s' "$left"
1986
+ }
1987
+
1988
+ # write_brief <issue> <pass> <worktree>: the continuation brief, a compact page of facts a
1989
+ # fresh session needs to pick the issue up at the recorded stage, into CONTINUE_BRIEF: with the
1990
+ # shift a handoff has to name, the reconciliations the issue has used, and the handoff when
1991
+ # this shift took the worktree over from another. Every
1992
+ # line is read off the ledger, the logs' exit lines, git and the tracker; no transcript,
1993
+ # child summary or log tail goes in, because those are the context the fresh session exists
1994
+ # to be without.
1995
+ write_brief() {
1996
+ local issue="$1" p="$2" wt="$3" stage reason last commits head tree log name gate pr pr_state checks review fp attempt doc ld
1997
+ CONTINUE_BRIEF="$SHIFT_DIR/continue-$issue-$p.md"
1998
+ # The brief names the ledger where the module finds it, so a worktree from before the rename is
1999
+ # moved to .kryso first, with a link back, before a fresh session is told where to read.
2000
+ _ledger_migrate_wt "$wt" || die "cannot move $wt/.ship-it to $wt/.kryso, so a continuation of #$issue cannot be told where its ledger is"
2001
+ stage="$(st_get "$issue" stage)"; reason="$(st_get "$issue" reason)"
2002
+ doc="$(ledger read "$wt")"
2003
+ _ledger_d "$wt" ld
2004
+ last="$(jq -r '.last | if . == null then "" else "\(.time) \(.stage) \(.outcome) \(.evidence)" end' <<< "$doc")"
2005
+ head="$(git -C "$wt" rev-parse --short HEAD 2>/dev/null)"
2006
+ commits="$(git -C "$wt" rev-list --count "$(git -C "$wt" merge-base "$PASS_BASE" HEAD 2>/dev/null || echo HEAD)..HEAD" 2>/dev/null || echo 0)"
2007
+ tree=clean; [[ -z "$(git -C "$wt" status --porcelain 2>/dev/null)" ]] || tree="dirty ($(git -C "$wt" status --porcelain | wc -l | tr -d ' ') paths)"
2008
+ pr="$(st_get "$issue" pr)"
2009
+ fp="$(st_get "$issue" fingerprint_before)"
2010
+ attempt="$(( $(st_get "$issue" attempts) + 1 ))"
2011
+ review="$(jq -r '.review.triaged // ""' <<< "$doc")"
2012
+ {
2013
+ echo "# Continue #$issue"
2014
+ echo
2015
+ echo "- issue: $issue"
2016
+ echo "- branch: $(st_get "$issue" branch)"
2017
+ echo "- worktree: $wt"
2018
+ echo "- base: $PASS_BASE"
2019
+ echo "- stage: ${stage:-unknown}"
2020
+ echo "- checkpoint: ${last:-none}"
2021
+ echo "- commits: $commits past $PASS_BASE, head ${head:-none}"
2022
+ echo "- tree: $tree"
2023
+ jq -r '.receipts[] | "- gate: \(.name) exit=\(.exit // "?")"' <<< "$doc"
2024
+ if [[ -n "$pr" && "$pr" != none ]]; then
2025
+ pr_state="$(gh pr view "$pr" --json state,headRefOid 2>/dev/null | jq -r '"state \(.state), head \(.headRefOid[0:7])"' 2>/dev/null)"
2026
+ checks="$(gh pr checks "$pr" --json bucket 2>/dev/null | jq -r 'group_by(.bucket) | map("\(length) \(.[0].bucket)") | join(", ")' 2>/dev/null)"
2027
+ echo "- pr: $pr${pr_state:+ ($pr_state)}${checks:+, checks: $checks}"
2028
+ else
2029
+ echo "- pr: none"
2030
+ fi
2031
+ echo "- review: ${review:-not recorded}"
2032
+ echo "- failure: ${reason:-none}"
2033
+ echo "- attempt: $attempt in this shift, fingerprint ${fp:-none}"
2034
+ echo "- shift: $SHIFT_ID"
2035
+ jq -r '"- reconciliations: \(.reconciliations.used)/3 used"' <<< "$doc"
2036
+ jq -r --arg s "$SHIFT_ID" 'select(.owner.via == "handoff" and .owner.shift == $s) | .handoff
2037
+ | "- handoff: from \(.from.engine)/\(.from.shift) to \(.to.engine)/\(.to.shift) at \(.stage), and the header keeps the engine that cut the tree"' <<< "$doc"
2038
+ # A pass cut to keep its PR open, a stacked sweep's, keeps it open under either engine.
2039
+ jq -r 'select(.header.merge == "park-at-merge") | "- merge: park-at-merge, from the ledger header: park at merge with the PR open whatever the base"' <<< "$doc"
2040
+ echo
2041
+ echo "Pick the issue up in that worktree at the stage above, in a fresh session. Fetch and fast-forward the branch first. The ledger at $ld/run.md is the record; no earlier transcript exists for you to read."
2042
+ } > "$CONTINUE_BRIEF"
2043
+ }
2044
+
2045
+ # plan_sweep: SWEEP_ORDER, SWEEP_WHY and SWEEP_BASE, the issues this sweep runs, why each
2046
+ # sits where it does and the base each is told, from the snapshot and the per-issue state.
2047
+ # First the owned resumable issue that blocks another in-scope issue, earliest first, then
2048
+ # the other owned resumable issues in admission order, then the snapshot's candidates that
2049
+ # have not been attempted, in its order, admitted while --max has room. Everything worked
2050
+ # before and now terminal is the filter's exclusion, with its state; a candidate past the
2051
+ # cap is held with the cap. A continuation keeps the base its first pass was told. A new
2052
+ # issue bases on the shift base, or under a stacked sweep on the one branch that carries its
2053
+ # satisfied blockers, and is held when no single branch does. Without a queue the sweep is
2054
+ # --max slots for the passes to fill from the label. The manifest is written from the plan.
2055
+ plan_sweep() {
2056
+ local issue state held='[]' order='[]' distinct blocked_by i reason base receipt locked=" "
2057
+ # hold <issue> <reason> [receipt]: one held entry, with the open receipt's log when that is why.
2058
+ hold() { held="$(jq -c --arg i "${1}" --arg r "${2}" --arg l "${3:-}" '. + [{issue: ($i | tonumber), reason: $r} + (if $l == "" then {} else {receipt: $l} end)]' <<< "$held")"; }
2059
+ SWEEP_ORDER=(); SWEEP_WHY=(); SWEEP_BASE=()
2060
+ if [[ "$HAS_QUEUE" -eq 0 ]]; then
2061
+ for ((i = 0; i < MAX; i++)); do SWEEP_ORDER+=(""); SWEEP_WHY+=(label); SWEEP_BASE+=("$BASE"); done
2062
+ write_manifest '[]' '[]' ''
2063
+ SWEEP_HELD='[]'
2064
+ return 0
2065
+ fi
2066
+ # The owned resumable issues, blockers first. A resumable issue the tracker now shows closed
2067
+ # was finished elsewhere, and one it no longer lists is not this sweep's.
2068
+ for issue in ${ADMITTED[@]+"${ADMITTED[@]}"}; do
2069
+ state="$(st_get "$issue" state)"
2070
+ [[ "$state" == resumable ]] || continue
2071
+ reason="$(jq -r --argjson i "$issue" '.excluded[] | select(.issue == $i) | .reason' <<< "$SNAPSHOT")"
2072
+ if [[ "$reason" == closed ]]; then
2073
+ st_set "$issue" state "done"; st_set "$issue" reason "closed on the tracker before the sweep"
2074
+ hold "$issue" "closed on the tracker"
2075
+ continue
2076
+ fi
2077
+ if [[ "$reason" == "no longer a child of the epic" ]]; then
2078
+ st_set "$issue" state "out-of-scope"; st_set "$issue" reason "$reason before the sweep"
2079
+ hold "$issue" "$reason"
2080
+ continue
2081
+ fi
2082
+ # A worktree with an open receipt is locked: a writer may still be in it, so no sweep
2083
+ # continues it until the receipt closes. It stays resumable for the sweep after.
2084
+ receipt="$(receipt_held "$issue")"
2085
+ if [[ -n "$receipt" ]]; then
2086
+ hold "$issue" "$receipt is open in its worktree" "$receipt"
2087
+ locked+="$issue "
2088
+ continue
2089
+ fi
2090
+ blocked_by="$(jq -r --argjson b "$issue" '[.excluded[] | select(.reason | startswith("blocked by ")) | select(.blockers | index($b)) | .issue] | map(tostring) | join(" ")' <<< "$SNAPSHOT")"
2091
+ if [[ -n "$blocked_by" ]]; then
2092
+ SWEEP_ORDER+=("$issue"); SWEEP_WHY+=("blocks #${blocked_by// / #}"); SWEEP_BASE+=("$(issue_base "$issue")")
2093
+ fi
2094
+ done
2095
+ for issue in ${ADMITTED[@]+"${ADMITTED[@]}"}; do
2096
+ [[ "$(st_get "$issue" state)" == resumable ]] || continue
2097
+ [[ "$locked" != *" $issue "* ]] || continue
2098
+ for i in ${SWEEP_ORDER[@]+"${SWEEP_ORDER[@]}"}; do [[ "$i" != "$issue" ]] || continue 2; done
2099
+ SWEEP_ORDER+=("$issue"); SWEEP_WHY+=("resumable $(st_get "$issue" stage)"); SWEEP_BASE+=("$(issue_base "$issue")")
2100
+ done
2101
+ # Then the newly eligible, in the snapshot's order, while the cap has room.
2102
+ distinct="${#ADMITTED[@]}"
2103
+ # An issue with a recorded state is not new: the filter excluded it with that state, or it
2104
+ # is resumable and planned above.
2105
+ for issue in ${QUEUE[@]+"${QUEUE[@]}"}; do
2106
+ [[ -z "$(st_get "$issue" state)" ]] || continue
2107
+ if [[ "$distinct" -ge "$MAX" ]]; then
2108
+ hold "$issue" "max $MAX distinct issues reached"
2109
+ continue
2110
+ fi
2111
+ base="$BASE"
2112
+ if [[ "$STACKED_SWEEPS" -eq 1 ]]; then
2113
+ if ! stack_base_for "$issue"; then
2114
+ hold "$issue" "$STACK_HOLD"
2115
+ continue
2116
+ fi
2117
+ base="$STACK_BASE"
2118
+ fi
2119
+ distinct=$((distinct + 1))
2120
+ SWEEP_ORDER+=("$issue"); SWEEP_WHY+=(eligible); SWEEP_BASE+=("$base")
2121
+ done
2122
+ for ((i = 0; i < ${#SWEEP_ORDER[@]}; i++)); do
2123
+ order="$(jq -c --arg i "${SWEEP_ORDER[$i]}" --arg w "${SWEEP_WHY[$i]}" --arg b "${SWEEP_BASE[$i]}" \
2124
+ '. + [{issue: ($i | tonumber), why: $w, base: $b}]' <<< "$order")"
2125
+ done
2126
+ HELD_BY_MAX="$(jq -r '[.[] | select(.reason | startswith("max ")) | .issue] | map(tostring) | join(" ")' <<< "$held")"
2127
+ SWEEP_HELD="$held"
2128
+ reason=""
2129
+ [[ "${#SWEEP_ORDER[@]}" -gt 0 ]] || reason="nothing resumable and nothing newly eligible"
2130
+ write_manifest "$order" "$held" "$reason"
2131
+ }
2132
+
2133
+ # issue_base <issue>: the base an admitted issue's first pass was told, or the shift base.
2134
+ issue_base() { local b; b="$(st_get "$1" base)"; printf '%s' "${b:-$BASE}"; }
2135
+
2136
+ # ---- adopting a stopped shift -------------------------------------------------------------
2137
+ #
2138
+ # --adopt names a shift that has stopped, and this one takes over the worktrees that shift
2139
+ # owns, and only those, under this shift's engine. Stopped is confirmed, never assumed: the
2140
+ # shift's driver lock is free, which it is only once its driver and every process that driver
2141
+ # started have exited, or a shift from before the lock existed wrote its summary, and no pass
2142
+ # on any of its worktrees still holds its issue's authority. The selection is the adopted
2143
+ # shift's too: an engine change keeps the host, its authentication and billing, the permission
2144
+ # policy, the model and the effort. Every refusal of the shift as a whole is a preflight stop
2145
+ # with nothing written. Then each owned worktree is typed off its ledger by the same classifier
2146
+ # a pass's outcome goes through, and only a resumable one inside this shift's scope and under
2147
+ # --max is adopted. The rest stay the adopted shift's, which this shift reads as a foreign
2148
+ # lock. The handoff is one ledger line per worktree, written once the shift has an id, and the
2149
+ # continuation is an ordinary one: a fresh context from a continuation brief, at the stage the
2150
+ # ledger records.
2151
+ # A shift that adopts more than one, as a bare --adopt's group of shifts that ran one selection
2152
+ # does, reads each in turn. ADOPT_DIR and ADOPT_STOPPED hold the shift being read, and
2153
+ # ADOPT_STOPPEDS how each one's stop was confirmed, index for index with ADOPTS. Each adopted
2154
+ # issue keeps its shift's directory in its own state.
2155
+ ADOPT_DIR=""
2156
+ ADOPT_STOPPED=""
2157
+ ADOPT_STOPPEDS=()
2158
+ ADOPT_FOUND=()
2159
+ ADOPT_ISSUES=()
2160
+ ADOPT_REFUSED='[]'
2161
+ ADOPT_TAKEN='[]'
2162
+
2163
+ # adopt_refuse <issue> <worktree> <reason> <shift>: a worktree the adoption leaves where it is.
2164
+ # The shift it stays with is kept for the summary of a shift that adopted several.
2165
+ adopt_refuse() {
2166
+ ADOPT_REFUSED="$(jq -c --argjson i "$1" --arg w "$2" --arg r "$3" --arg s "$4" '. + [{issue: $i, worktree: $w, reason: $r, shift: $s}]' <<< "$ADOPT_REFUSED")"
2167
+ }
2168
+
2169
+ # adopts_json: each adopted shift with how its stop was confirmed, as a JSON list.
2170
+ adopts_json() {
2171
+ local i out='[]'
2172
+ for i in "${!ADOPTS[@]}"; do
2173
+ out="$(jq -c --arg s "${ADOPTS[$i]}" --arg st "${ADOPT_STOPPEDS[$i]-}" '. + [{shift: $s, stopped: $st}]' <<< "$out")"
2174
+ done
2175
+ printf '%s' "$out"
2176
+ }
2177
+
2178
+ # adopt_stopped <shift>: the shift's directory in ADOPT_DIR and how its stop was confirmed in
2179
+ # ADOPT_STOPPED, or the preflight stops with nothing written.
2180
+ adopt_stopped() {
2181
+ local id="$1" got isolated_pid
2182
+ # Under the state directory, which the start moved from .claude/ship-loop, or under the old
2183
+ # name where a .claude/kryso/ already stood beside it.
2184
+ _ledger_pick "$STATE_ROOT/$id" ".claude/ship-loop/$id" ADOPT_DIR
2185
+ [[ -d "$ADOPT_DIR" ]] || die "--adopt $id: there is no shift $id under $STATE_ROOT, so nothing is adopted"
2186
+ if isolated_pid="$(ledger isolated "$REPO_ROOT")"; then
2187
+ die "--adopt $id: an isolated kryso run (docker pid $isolated_pid) is working this repository, and its driver lock is not visible here, so nothing is adopted"
2188
+ fi
2189
+ if [[ -e "$ADOPT_DIR/driver.lock" ]]; then
2190
+ got=0; ledger locked "$ADOPT_DIR/driver.lock" || got=$?
2191
+ [[ "$got" -ne 0 ]] || die "--adopt $id: its driver, or a process it started, still holds $ADOPT_DIR/driver.lock, so the shift is running and nothing is adopted"
2192
+ [[ "$got" -eq 1 ]] || die "--adopt $id: $ADOPT_DIR/driver.lock cannot be read, so the shift cannot be confirmed stopped and nothing is adopted"
2193
+ ADOPT_STOPPED="its driver lock is free"
2194
+ elif [[ -f "$ADOPT_DIR/summary.json" ]]; then
2195
+ ADOPT_STOPPED="it wrote its summary and predates the driver lock"
2196
+ else
2197
+ die "--adopt $id: the shift left no driver lock and no summary, so its driver cannot be confirmed stopped and nothing is adopted"
2198
+ fi
2199
+ }
2200
+
2201
+ # adopt_held <shift>: the issues whose worktrees the shift owns, in ADOPT_FOUND, once no pass on
2202
+ # any of them still holds its issue's authority, or the preflight stops with nothing written.
2203
+ adopt_held() {
2204
+ local id="$1" got wt issue
2205
+ ADOPT_FOUND=()
2206
+ while read -r wt issue; do
2207
+ [[ "$issue" =~ ^[0-9]+$ ]] || continue
2208
+ [[ "$(ledger_text "$wt" | jq -r '.owner.shift // ""')" == "$id" ]] || continue
2209
+ got=0; ledger active "$REPO_ROOT" "$issue" >/dev/null || got=$?
2210
+ [[ "$got" -ne 0 ]] || die "--adopt $id: the pass on #$issue still holds its issue's authority, so the shift is running and nothing is adopted"
2211
+ [[ "$got" -eq 1 ]] || die "--adopt $id: #$issue's authority cannot be read, so its pass cannot be confirmed stopped and nothing is adopted"
2212
+ ADOPT_FOUND+=("$issue")
2213
+ done < <(ledger worktrees "$REPO_ROOT")
2214
+ }
2215
+
2216
+ # shift_selection <shift> <dir>: the host, billing, profile, model, effort and passthrough
2217
+ # arguments the shift ran, in SELECTION, from its shift.json, or the first line of a shift log
2218
+ # that predates it, which records all but the model. Such a shift is taken to have run the
2219
+ # profile's default model, so a --model here cannot be confirmed to match and stops the shift.
2220
+ # It sets a variable rather than print, because a die inside a command substitution would end
2221
+ # the substitution and not the shift.
2222
+ SELECTION=""
2223
+ shift_selection() {
2224
+ local id="$1" dir="$2"
2225
+ if [[ -f "$dir/shift.json" ]]; then
2226
+ SELECTION="$(jq -c '{profile, host, billing, effort, model, extra_args}' "$dir/shift.json" 2>/dev/null)" \
2227
+ || die "--adopt $id: $dir/shift.json is not JSON, so the selection it ran cannot be kept"
2228
+ else
2229
+ [[ -z "$MODEL" ]] || die "--adopt $id: that shift predates shift.json and its log does not record the model it ran, so --model $MODEL cannot be confirmed to keep it"
2230
+ SELECTION="$(head -1 "$dir/shift.log" 2>/dev/null | grep -oE ' (profile|host|billing|effort)=[^ ]+' \
2231
+ | jq -Rnc '[inputs | capture("^ (?<k>[a-z]+)=(?<v>.*)$") | {(.k): .v}] | add // {}')"
2232
+ fi
2233
+ }
2234
+
2235
+ # selection_diff <theirs> <ours>: the first field ours holds that theirs differs on, as a
2236
+ # clause, or nothing. A field ours does not hold is not compared.
2237
+ selection_diff() {
2238
+ jq -r --argjson ours "$2" 'to_entries | map(select(.key as $k | ($ours | has($k)) and .value != $ours[$k]))
2239
+ | first // empty | "\(.key) \(.value // "the profile default") where this one would run \(.key) \($ours[.key] // "the profile default")"' <<< "$1"
2240
+ }
2241
+
2242
+ # selection_ours: this shift's selection, every field of it.
2243
+ selection_ours() {
2244
+ jq -nc --arg profile "$PROFILE" --arg host "$RUNNER_HOST" --arg billing "$RUNNER_BILLING" --arg effort "$EFFORT" \
2245
+ --arg model "$MODEL" --arg extra "${EXTRA_ARGS[*]-}" \
2246
+ '{profile: $profile, host: $host, billing: $billing, effort: $effort, model: (if $model == "" then null else $model end), extra_args: $extra}'
2247
+ }
2248
+
2249
+ # adopt_selection <shift>: the adopted shift's selection against this shift's, all of it. The
2250
+ # first field that differs stops the shift.
2251
+ adopt_selection() {
2252
+ local diff
2253
+ shift_selection "$1" "$ADOPT_DIR"
2254
+ diff="$(selection_diff "$SELECTION" "$(selection_ours)")"
2255
+ [[ -z "$diff" ]] || die "--adopt $1: that shift ran $diff. A handoff keeps the host, its authentication and billing, the permission policy, the model and the effort, so start this shift with the selection it ran"
2256
+ }
2257
+
2258
+ # adopt_read: the refusals, the selection and the typed state of every worktree each adopted
2259
+ # shift owns, before the first snapshot, so the snapshot reads an adopted worktree as this
2260
+ # shift's rather than as a lock.
2261
+ adopt_read() {
2262
+ local id wt issue doc unsafe outcome last_pass artifact
2263
+ for id in "${ADOPTS[@]}"; do
2264
+ adopt_stopped "$id"
2265
+ adopt_selection "$id"
2266
+ adopt_held "$id"
2267
+ ADOPT_STOPPEDS+=("$ADOPT_STOPPED")
2268
+ for issue in ${ADOPT_FOUND[@]+"${ADOPT_FOUND[@]}"}; do
2269
+ wt="$(worktree_for "$issue")" || continue
2270
+ doc="$(ledger read "$wt")"
2271
+ unsafe="$(unsafe_continuation "$wt")"
2272
+ if [[ -n "$unsafe" ]]; then adopt_refuse "$issue" "$wt" "unsafe: $unsafe" "$id"; continue; fi
2273
+ # The stop was confirmed above, so an interrupted pass is one whose processes have exited.
2274
+ outcome=none
2275
+ [[ "$(jq -r '.checkpoint.status // ""' <<< "$doc")" != interrupted ]] || outcome=interrupted
2276
+ classify "$issue" "$outcome" "$(jq -r '.pr // "none"' <<< "$doc")" false "$wt" 1 confirmed
2277
+ if [[ "$CLS_STATE" != resumable ]]; then adopt_refuse "$issue" "$wt" "$CLS_STATE: $CLS_REASON" "$id"; continue; fi
2278
+ # The adopted shift's last saved result for the issue is the predecessor of the continuation.
2279
+ last_pass="$(for f in "$ADOPT_DIR"/pass-*.json; do [[ -f "$f" ]] && jq -r --arg i "$issue" 'select(.ship_loop.issue == $i) | .ship_loop.pass' "$f" 2>/dev/null; done | sort -n | tail -1)"
2280
+ artifact=""; [[ -z "$last_pass" ]] || artifact="$ADOPT_DIR/pass-$last_pass.json"
2281
+ ADOPT_ISSUES+=("$issue")
2282
+ st_set "$issue" state resumable
2283
+ st_set "$issue" stage "$CLS_STAGE"
2284
+ st_set "$issue" reason "adopted from shift $id: $CLS_REASON"
2285
+ st_set "$issue" disposition "$CLS_DISPOSITION"
2286
+ st_set "$issue" worktree "$wt"
2287
+ st_set "$issue" pr "$(jq -r '.pr // "none"' <<< "$doc")"
2288
+ st_set "$issue" branch "$(jq -r '.header.branch // "none"' <<< "$doc")"
2289
+ st_set "$issue" base "$(jq -r '.header.base.name // ""' <<< "$doc")"
2290
+ st_set "$issue" attempts 0
2291
+ st_set "$issue" artifact "$artifact"
2292
+ st_set "$issue" adopted "$id"
2293
+ st_set "$issue" adopted_dir "$ADOPT_DIR"
2294
+ st_set "$issue" adopted_last_pass "$last_pass"
2295
+ done
2296
+ done
2297
+ }
2298
+
2299
+ # adopt_drop <issue> <reason>: an adoption this shift will not make after all. The worktree
2300
+ # stays the adopted shift's, so the filter reads it as a foreign lock again.
2301
+ adopt_drop() {
2302
+ local keep=() i
2303
+ adopt_refuse "$1" "$(st_get "$1" worktree)" "$2" "$(st_get "$1" adopted)"
2304
+ ISSUE_STATE="$(jq -c --arg i "$1" 'del(.[$i])' <<< "$ISSUE_STATE")"
2305
+ for i in ${ADOPT_ISSUES[@]+"${ADOPT_ISSUES[@]}"}; do [[ "$i" == "$1" ]] || keep+=("$i"); done
2306
+ ADOPT_ISSUES=(${keep[@]+"${keep[@]}"})
2307
+ }
2308
+
2309
+ # refilter: the last read filtered again, after the per-issue state changed, with no tracker call.
2310
+ refilter() {
2311
+ [[ -n "$SNAPSHOT_NODES" ]] || return 0
2312
+ SNAPSHOT="$(snapshot_filter "$SNAPSHOT_NODES")"
2313
+ read -r -a QUEUE <<< "$(jq -r '.candidates | map(tostring) | join(" ")' <<< "$SNAPSHOT")"
2314
+ EXCLUDED="$(jq -r '.excluded | map("\(.issue) (\(.reason))") | join(" ")' <<< "$SNAPSHOT")"
2315
+ [[ -z "$EPIC" ]] || BLOCKED="$(jq -r '.excluded[] | select(.reason | startswith("blocked by ")) | "\(.issue) (\(.blockers | map("#\(.)") | join(" ")))"' <<< "$SNAPSHOT" | tr '\n' ' ' | sed 's/ $//')"
2316
+ }
2317
+
2318
+ # adopt_scope: an adopted issue is one the first snapshot would run. One outside the fixed
2319
+ # scope, or excluded from it, such as closed since, is not adopted.
2320
+ adopt_scope() {
2321
+ local issue reason dropped=0
2322
+ for issue in ${ADOPT_ISSUES[@]+"${ADOPT_ISSUES[@]}"}; do
2323
+ jq -e --argjson i "$issue" '.candidates | index($i)' <<< "$SNAPSHOT" >/dev/null 2>&1 && continue
2324
+ reason="$(jq -r --argjson i "$issue" '.excluded[] | select(.issue == $i) | .reason' <<< "$SNAPSHOT")"
2325
+ adopt_drop "$issue" "${reason:-outside the scope of this shift}"
2326
+ dropped=1
2327
+ done
2328
+ [[ "$dropped" -eq 0 ]] || refilter
2329
+ }
2330
+
2331
+ # adopt_max: the adopted issues are admitted first and count toward --max like any other, in
2332
+ # the order the adopted shift's worktrees were read. One past the cap is not adopted.
2333
+ adopt_max() {
2334
+ local issue n=0 dropped=0
2335
+ for issue in ${ADOPT_ISSUES[@]+"${ADOPT_ISSUES[@]}"}; do
2336
+ n=$((n + 1))
2337
+ if [[ "$n" -gt "$MAX" ]]; then adopt_drop "$issue" "max $MAX distinct issues reached"; dropped=1; continue; fi
2338
+ admitted "$issue" || ADMITTED+=("$issue")
2339
+ done
2340
+ [[ "$dropped" -eq 0 ]] || refilter
2341
+ }
2342
+
2343
+ # adopt_consumed <issue>: the seconds of allowance the adopted shift's last pass on the issue
2344
+ # consumed, its rate-limit retries included, from that pass's saved result, else its deadline
2345
+ # report for a shift that predates the field, else the ledger's interruption, else nothing.
2346
+ adopt_consumed() {
2347
+ local last n="" dir
2348
+ last="$(st_get "$1" adopted_last_pass)"
2349
+ dir="$(st_get "$1" adopted_dir)"
2350
+ [[ -z "$last" ]] || n="$(jq -r '.ship_loop.consumed // empty' "$dir/pass-$last.json" 2>/dev/null)"
2351
+ [[ -z "$last" || "$n" =~ ^[0-9]+$ ]] || n="$(jq -r '.elapsed // empty' "$dir/deadline-$last.json" 2>/dev/null)"
2352
+ [[ "$n" =~ ^[0-9]+$ ]] || n="$(ledger_text "$(st_get "$1" worktree)" | jq -r '.interruption.consumed // empty')"
2353
+ [[ "$n" =~ ^[0-9]+$ ]] && printf '%s' "$n"
2354
+ return 0
2355
+ }
2356
+
2357
+ # adopt_limits <issue>: the limits the issue's ledger has left, as a clause.
2358
+ adopt_limits() {
2359
+ local consumed
2360
+ consumed="$(adopt_consumed "$1")"
2361
+ ledger read "$(st_get "$1" worktree)" | jq -r --arg c "${consumed:+${consumed}s}" \
2362
+ '"reconciliations \(.reconciliations.used)/3 used, forks \(.checkpoint.forks // 0) of 2, allowance consumed \(if $c == "" then "unknown" else $c end)"'
2363
+ }
2364
+
2365
+ # adopt_lines: what the adoption does, one line each, for the dry run and the shift's opening:
2366
+ # the shift and how its stop was confirmed, each worktree taken over with its stage and the
2367
+ # limits left, each one left where it is and why, and the reconciliation contexts the adopted
2368
+ # issues have left. They count toward --max, so the pass bound below holds, and a
2369
+ # reconciliation context is a model start of its own under the script engine alone, one of the
2370
+ # three per issue the start bound below already counts.
2371
+ adopt_lines() {
2372
+ local issue left=0 i n
2373
+ for i in "${!ADOPTS[@]}"; do
2374
+ n=0
2375
+ for issue in ${ADOPT_ISSUES[@]+"${ADOPT_ISSUES[@]}"}; do [[ "$(st_get "$issue" adopted)" != "${ADOPTS[$i]}" ]] || n=$((n + 1)); done
2376
+ printf 'adopt: shift %s, stopped (%s), %s under the %s engine, keeping profile %s, host %s, billing %s, effort %s%s\n' \
2377
+ "${ADOPTS[$i]}" "${ADOPT_STOPPEDS[$i]}" "$(plural "$n" "worktree taken over" "worktrees taken over")" "$ENGINE" \
2378
+ "$PROFILE" "$RUNNER_HOST" "$RUNNER_BILLING" "$EFFORT" "$(m="$(model_shown)"; printf '%s' "${m:+, model $m}")"
2379
+ done
2380
+ for issue in ${ADOPT_ISSUES[@]+"${ADOPT_ISSUES[@]}"}; do
2381
+ printf 'adopt: #%s %s on %s from stage %s: %s\n' "$issue" "$(st_get "$issue" worktree)" "$(st_get "$issue" branch)" "$(st_get "$issue" stage)" "$(adopt_limits "$issue")"
2382
+ left=$(( left + $(ledger read "$(st_get "$issue" worktree)" | jq -r '.reconciliations.left') ))
2383
+ done
2384
+ jq -r '.[] | "adopt: not #\(.issue) \(.worktree): \(.reason)"' <<< "$ADOPT_REFUSED"
2385
+ if [[ "${#ADOPT_ISSUES[@]}" -gt 0 ]]; then
2386
+ if [[ "$ENGINE" == script ]]; then
2387
+ printf 'adopt: the adopted issues count toward --max, so the pass and start bounds hold, and the start bound already counts their %s left\n' "$(plural "$left" "reconciliation context" "reconciliation contexts")"
2388
+ else
2389
+ printf 'adopt: the adopted issues count toward --max, so the pass bound holds, and their %s left run inside each continuation and start no context of their own\n' "$(plural "$left" "reconciliation attempt" "reconciliation attempts")"
2390
+ fi
2391
+ fi
2392
+ }
2393
+
2394
+ # adopt_write: one handoff line per adopted worktree, through the module, now that the shift has
2395
+ # an id: the stage the continuation is told, the limits left and the selection kept. The
2396
+ # allowance consumed is the adopted shift's last pass's on the issue. The owner is read again
2397
+ # first, so a second driver that adopted the same shift since the preflight keeps what it took.
2398
+ adopt_write() {
2399
+ local issue wt consumed owner from
2400
+ for issue in ${ADOPT_ISSUES[@]+"${ADOPT_ISSUES[@]}"}; do
2401
+ wt="$(st_get "$issue" worktree)"
2402
+ from="$(st_get "$issue" adopted)"
2403
+ consumed="$(adopt_consumed "$issue")"
2404
+ owner="$(ledger_text "$wt" | jq -r '.owner.shift // ""')"
2405
+ if [[ "$owner" != "$from" ]]; then
2406
+ adopt_refuse "$issue" "$wt" "shift ${owner:-none} took it over since the preflight" "$from"
2407
+ st_set "$issue" state foreign-lock; st_set "$issue" last_pass 0
2408
+ st_set "$issue" reason "shift ${owner:-none} took it over from shift $from since the preflight"
2409
+ warn "#$issue is not adopted: shift ${owner:-none} took it over since the preflight"
2410
+ elif ledger handoff "$wt" "$ENGINE" "$SHIFT_ID" stage="$(st_get "$issue" stage)" profile="$PROFILE" host="$RUNNER_HOST" \
2411
+ billing="$RUNNER_BILLING" effort="$EFFORT" ${MODEL:+model="$MODEL"} ${consumed:+consumed="$consumed"}; then
2412
+ ADOPT_TAKEN="$(jq -c --argjson i "$issue" --arg w "$wt" --arg s "$(st_get "$issue" stage)" --argjson h "$(ledger_text "$wt" | jq -c .handoff)" \
2413
+ --arg from "$from" '. + [{issue: $i, worktree: $w, stage: $s, handoff: $h, shift: $from}]' <<< "$ADOPT_TAKEN")"
2414
+ else
2415
+ adopt_refuse "$issue" "$wt" "the driver could not write the handoff" "$from"
2416
+ st_set "$issue" state unsafe; st_set "$issue" last_pass 0
2417
+ st_set "$issue" reason "the driver could not write the handoff from shift $from to $wt"
2418
+ warn "#$issue is not adopted: the driver could not write the handoff to $wt"
2419
+ fi
2420
+ done
2421
+ }
2422
+
2423
+ # ---- a bare --adopt: one shift per selection ----------------------------------------------
2424
+ #
2425
+ # A bare --adopt names no shift. The driver reads, for each queued issue with a worktree, the
2426
+ # shift that owns it, and every shift found goes through the checks a named one does: its
2427
+ # driver lock is free and no pass on its worktrees holds its issue's authority. A selection
2428
+ # flag given here has to match each of them, and one left out takes each shift's own. The
2429
+ # shifts are grouped by the selection they ran, since a shift has one selection, and each group
2430
+ # runs as a shift of its own through --adopt with its shift ids, in queue order of its first
2431
+ # issue, one after the other. The queued issues with no worktree a shift owns run last, in a
2432
+ # shift under this command's selection. Each group's shift takes the command's other options as
2433
+ # they are, so --max and --sweeps bound each group, and --budget is a cap per run as ever. Every refusal comes before the first group starts, so a
2434
+ # refusal writes nothing. A group that stops on a rate limit stops the groups after it, since
2435
+ # they would meet the same limit.
2436
+
2437
+ # adopt_split_argv: the arguments as given, split into GROUP_ARGS, which every group's shift is
2438
+ # handed, and SELECTION_ARGS, the selection flags given, which the last group is handed and the
2439
+ # adopted groups replace with their own. GIVEN_FIELDS holds the selection fields those flags
2440
+ # set. The queue and --dry-run are this driver's alone. Every option the parse loop above knows takes a
2441
+ # value except the ones named here.
2442
+ adopt_split_argv() {
2443
+ local a n=${#ARGV[@]} i=0
2444
+ GROUP_ARGS=(); SELECTION_ARGS=(); GIVEN_FIELDS=()
2445
+ while (( i < n )); do
2446
+ a="${ARGV[$i]}"
2447
+ case "$a" in
2448
+ --) SELECTION_ARGS+=("${ARGV[@]:i}"); GIVEN_FIELDS+=(extra_args); break ;;
2449
+ --adopt|--dry-run|--read-only) i=$((i + 1)) ;;
2450
+ --api-key) SELECTION_ARGS+=("$a"); GIVEN_FIELDS+=(billing); i=$((i + 1)) ;;
2451
+ --stack|--no-ci-check) GROUP_ARGS+=("$a"); i=$((i + 1)) ;;
2452
+ --issues) i=$((i + 2)) ;;
2453
+ --profile) SELECTION_ARGS+=("$a" "${ARGV[$((i + 1))]}"); GIVEN_FIELDS+=(profile host); i=$((i + 2)) ;;
2454
+ --effort) SELECTION_ARGS+=("$a" "${ARGV[$((i + 1))]}"); GIVEN_FIELDS+=(effort); i=$((i + 2)) ;;
2455
+ --model) SELECTION_ARGS+=("$a" "${ARGV[$((i + 1))]}"); GIVEN_FIELDS+=(model); i=$((i + 2)) ;;
2456
+ *) GROUP_ARGS+=("$a" "${ARGV[$((i + 1))]}"); i=$((i + 2)) ;;
2457
+ esac
2458
+ done
2459
+ }
2460
+
2461
+ # selection_key <selection>: the selection with every field, so two shifts that ran the same one
2462
+ # compare equal whichever record each left.
2463
+ selection_key() { jq -cS '{profile, host, billing, effort, model, extra_args: (.extra_args // "")}' <<< "$1"; }
2464
+
2465
+ # selection_flags <selection>: the flags that run a shift under it, one per line.
2466
+ selection_flags() {
2467
+ jq -r '(if .profile then "--profile", .profile else empty end), (if .effort then "--effort", .effort else empty end),
2468
+ (if .model then "--model", .model else empty end), (if .billing == "api" then "--api-key" else empty end)' <<< "$1"
2469
+ }
2470
+
2471
+ # group_line <n> <of> <who> <selection> <issues>: one group, as the dry run and the run print it.
2472
+ group_line() {
2473
+ jq -r --arg n "$1" --arg of "$2" --arg who "$3" --arg issues "$4" \
2474
+ '"group \($n) of \($of): \($who), profile \(.profile // "the default"), host \(.host // "the default"), billing \(.billing // "the default"), effort \(.effort // "the default")"
2475
+ + (if .model then ", model \(.model)" else "" end) + (if (.extra_args // "") != "" then ", arguments \(.extra_args)" else "" end)
2476
+ + ", issues \($issues | split(" ") | map("#" + .) | join(" "))"' <<< "$5"
2477
+ }
2478
+
2479
+ # adopt_groups: the groups, checked and printed, then each run in turn, and the exit the worst
2480
+ # of theirs. Under --dry-run each is printed and none runs.
2481
+ adopt_groups() {
2482
+ local issue wt owner sel key diff given seen=" " g i n of code worst=0 rest="" self a
2483
+ local ids=() shift_ids=() shift_keys=() group_keys=() group_sels=() group_shifts=() group_issues=() flags=() extra=()
2484
+ adopt_split_argv
2485
+ given="$(jq -c --args 'with_entries(select(.key as $k | $ARGS.positional | index($k)))' ${GIVEN_FIELDS[@]+"${GIVEN_FIELDS[@]}"} <<< "$(selection_ours)")"
2486
+ for issue in "${QUEUE[@]}"; do
2487
+ [[ "$seen" != *" $issue "* ]] || continue
2488
+ seen+="$issue "
2489
+ owner=""
2490
+ if wt="$(worktree_for "$issue")"; then owner="$(ledger_text "$wt" | jq -r '.owner.shift // ""')"; fi
2491
+ if [[ -z "$owner" ]]; then rest+="${rest:+ }$issue"; continue; fi
2492
+ key=""
2493
+ for i in "${!shift_ids[@]}"; do [[ "${shift_ids[$i]}" != "$owner" ]] || key="${shift_keys[$i]}"; done
2494
+ if [[ -z "$key" ]]; then
2495
+ adopt_stopped "$owner"
2496
+ shift_selection "$owner" "$ADOPT_DIR"
2497
+ sel="$SELECTION"
2498
+ diff="$(selection_diff "$sel" "$given")"
2499
+ [[ -z "$diff" ]] || die "--adopt: shift $owner, which owns #$issue's worktree, ran $diff. A selection flag given has to match every group, so leave it out to run each group under its own selection, or run that shift's issues with --adopt $owner"
2500
+ adopt_held "$owner"
2501
+ key="$(selection_key "$sel")"
2502
+ shift_ids+=("$owner"); shift_keys+=("$key")
2503
+ fi
2504
+ g=""
2505
+ for i in "${!group_keys[@]}"; do [[ "${group_keys[$i]}" != "$key" ]] || g="$i"; done
2506
+ if [[ -z "$g" ]]; then
2507
+ g="${#group_keys[@]}"; group_keys+=("$key"); group_shifts+=(""); group_issues+=("")
2508
+ fi
2509
+ [[ " ${group_shifts[$g]} " == *" $owner "* ]] || group_shifts[g]="${group_shifts[$g]:+${group_shifts[$g]} }$owner"
2510
+ group_issues[g]="${group_issues[$g]:+${group_issues[$g]} }$issue"
2511
+ done
2512
+ of="${#group_keys[@]}"
2513
+ [[ -z "$rest" ]] || of=$((of + 1))
2514
+ self="$HERE/$(basename "$SELF")"
2515
+ for i in "${!group_keys[@]}"; do
2516
+ n=$((i + 1))
2517
+ read -r -a ids <<< "${group_shifts[$i]}"
2518
+ note "$(group_line "$n" "$of" "adopt $(if [[ "${#ids[@]}" -eq 1 ]]; then echo shift; else echo shifts; fi) ${group_shifts[$i]}" "${group_issues[$i]}" "${group_keys[$i]}")"
2519
+ [[ "$DRY_RUN" -eq 0 ]] || continue
2520
+ flags=(); while IFS= read -r a; do flags+=("$a"); done < <(selection_flags "${group_keys[$i]}")
2521
+ for a in "${ids[@]}"; do flags+=(--adopt "$a"); done
2522
+ read -r -a extra <<< "$(jq -r '.extra_args' <<< "${group_keys[$i]}")"
2523
+ [[ "${#extra[@]}" -eq 0 ]] || flags+=(-- "${extra[@]}")
2524
+ code=0; bash "$self" ${GROUP_ARGS[@]+"${GROUP_ARGS[@]}"} --issues "${group_issues[$i]}" "${flags[@]}" || code=$?
2525
+ [[ "$code" -le "$worst" ]] || worst="$code"
2526
+ if [[ "$code" -eq 2 ]]; then
2527
+ note "group $n of $of stopped on a rate limit, so the groups after it did not run"
2528
+ return "$worst"
2529
+ fi
2530
+ done
2531
+ [[ -n "$rest" ]] || return "$worst"
2532
+ note "$(group_line "$of" "$of" "no stopped shift's worktree" "$rest" "$(selection_ours)")"
2533
+ [[ "$DRY_RUN" -eq 0 ]] || return 0
2534
+ code=0; bash "$self" ${GROUP_ARGS[@]+"${GROUP_ARGS[@]}"} --issues "$rest" ${SELECTION_ARGS[@]+"${SELECTION_ARGS[@]}"} || code=$?
2535
+ [[ "$code" -le "$worst" ]] || worst="$code"
2536
+ return "$worst"
2537
+ }
2538
+
2539
+ if [[ "$ADOPT_ALL" -eq 1 ]]; then
2540
+ code=0; adopt_groups || code=$?
2541
+ exit "$code"
2542
+ fi
2543
+
2544
+ # The adopted shift is read before the first snapshot, so the snapshot takes an adopted
2545
+ # worktree as this shift's.
2546
+ [[ -z "$ADOPT" ]] || adopt_read
2547
+
2548
+ # The first snapshot, taken here rather than where the filter is defined, because the filter
2549
+ # reads the per-issue state and the worktree readers above.
2550
+ take_snapshot
2551
+ [[ -z "$ADOPT" ]] || adopt_scope
2552
+
2553
+ # A queued pass is told its issue and base, so /kryso takes that issue rather than picking
2554
+ # one, and bases on that branch rather than choosing. The base defaults to the repo's default
2555
+ # branch, read live from GitHub, or from origin/HEAD where there is no tracker to ask.
2556
+ if [[ "$HAS_QUEUE" -eq 1 && -z "$BASE" ]]; then
2557
+ if [[ "$TRACKER" == reachable ]]; then
2558
+ BASE="$(gh repo view --json defaultBranchRef --jq .defaultBranchRef.name 2>/dev/null)" || die_if_silent "$?" "the repo's default branch"
2559
+ else
2560
+ BASE="$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's#^origin/##')"
2561
+ fi
2562
+ [[ -n "$BASE" ]] || die "cannot read the repo's default branch" "pass --base" ", so "
2563
+ fi
2564
+
2565
+ # The sweep this shift is on, and how many have run.
2566
+ SWEEP=1
2567
+ SWEPT=0
2568
+
2569
+ # left_open: the in-scope issues the last snapshot still shows open, each with its reason, as
2570
+ # a clause for the stop reason. A frontier that ran dry with these left is not the epic done,
2571
+ # and the line says so rather than leave it to the manifest. Closed, shipped, gone and
2572
+ # never-found issues are not open work, so they are not counted.
2573
+ left_open() {
2574
+ local left n
2575
+ left="$(jq -c '[.excluded[] | select(.reason != "closed" and .reason != "not found"
2576
+ and .reason != "named earlier in the workset" and .reason != "no longer a child of the epic"
2577
+ and (.reason | test("^done in pass ") | not))]' <<< "$SNAPSHOT")"
2578
+ n="$(jq -r 'length' <<< "$left")"
2579
+ [[ "$n" -gt 0 ]] || return 0
2580
+ printf ', with %s still open: %s' "$(plural "$n" "in-scope issue" "in-scope issues")" \
2581
+ "$(jq -r 'map("#\(.issue) (\(.reason))") | join(", ")' <<< "$left")"
2582
+ }
2583
+
2584
+ # receipt_locks: the issues the sweep's plan held because a receipt is open in their worktrees,
2585
+ # as a clause of the stop line, or nothing.
2586
+ receipt_locks() {
2587
+ jq -r '[.[] | select(.receipt != null) | "#\(.issue) held by its open receipt \(.receipt)"]
2588
+ | if length == 0 then "" else ", with " + join(", ") end' <<< "$SWEEP_HELD"
2589
+ }
2590
+
2591
+ # stop_at_max: the stop when --max held issues back, which is what a person reading the last
2592
+ # line needs to know, over a queue's end or an empty plan.
2593
+ stop_at_max() {
2594
+ STOP_KIND=max
2595
+ stop_reason="reached the max of $MAX distinct issues with $(wc -w <<< "$HELD_BY_MAX" | tr -d ' ') issue(s) still queued: $HELD_BY_MAX"
2596
+ }
2597
+
2598
+ # plural <n> <one> <many>: the count with the right form of its noun, for the bounds line.
2599
+ plural() { if [[ "$1" -eq 1 ]]; then printf '%s %s' "$1" "$2"; else printf '%s %s' "$1" "$3"; fi; }
2600
+
2601
+ # scope_line: the epic's scope as one line, the open children in GitHub's order.
2602
+ scope_line() {
2603
+ printf '%s open children of #%s in scope%s' "$(jq -r 'length' <<< "$EPIC_SCOPE")" "$EPIC" \
2604
+ "$(jq -r 'if length == 0 then "" else ": " + (map(tostring) | join(" ")) end' <<< "$EPIC_SCOPE")"
2605
+ }
2606
+ # candidates_line <count> and worktrees_line <names>: two opening lines. A line that states one
2607
+ # fact is a short sentence, and one that lists several is a label, a colon and the items.
2608
+ candidates_line() {
2609
+ if [[ "$CANDIDATES" == unknown ]]; then printf 'the count of issues that carry the label is unknown'
2610
+ elif [[ "$CANDIDATES" == 1 ]]; then printf '%s issue carries the label, before /kryso'"'"'s own filters' "$1"
2611
+ else printf '%s issues carry the label, before /kryso'"'"'s own filters' "$1"; fi
2612
+ }
2613
+ worktrees_line() { if [[ -z "$1" ]]; then printf 'no worktrees'; else printf 'worktrees: %s' "$1"; fi; }
2614
+ # model_shown: the model the passes run, for people to read: --model's, or the profile's with a
2615
+ # note that it is the default. Empty when neither names one and the host picks.
2616
+ model_shown() {
2617
+ if [[ -n "$MODEL" ]]; then printf '%s' "$MODEL"
2618
+ elif [[ -n "${RUNNER_MODEL:-}" ]]; then printf '%s (profile default)' "$RUNNER_MODEL"
2619
+ fi
2620
+ }
2621
+
2622
+ # styled_preflight: on an attended run, what the preflight found, as information lines under
2623
+ # its pill, each the plain note's words with its values green. Printed ahead of the plan whether
2624
+ # or not the queue is empty. The reporting URL is said on the same terms as the plain note.
2625
+ styled_preflight() {
2626
+ local shown
2627
+ shown="$(model_shown)"
2628
+ ui_info "working in $(ui_val "$REPO_ROOT")"
2629
+ ui_info "the $(ui_val "$PROFILE") profile runs $(ui_val "$RUNNER_HOST $RUNNER_VERSION") on $RUNNER_BILLING billing, the tracker is $TRACKER, and the label is $(ui_val "$LABEL")"
2630
+ ui_info "the effort is $(ui_val "$EFFORT")${shown:+, and the model is $(ui_val "$shown")}"
2631
+ [[ -z "$MEMBER_LINE" ]] || ui_info "$MEMBER_LINE"
2632
+ ui_info "$(candidates_line "$(ui_val "$CANDIDATES")")"
2633
+ shown="$(sed 's/ $//' <<< "$WORKTREES")"
2634
+ if [[ -z "$shown" ]]; then ui_info "$(worktrees_line "")"; else ui_info "$(worktrees_line "$(ui_val "$shown")")"; fi
2635
+ ui_info "CI: $CI"
2636
+ ui_info "skills: $RUNNER_SKILLS"
2637
+ ui_info "$(runner_pass_skills_line)"
2638
+ [[ -z "$REPORT_URL" && "$DRY_RUN" -eq 0 ]] || ui_info "$REPORTING_NOTE"
2639
+ [[ -z "$SECOND_READER_SOURCE" ]] || ui_info "the second reader is $(ui_val "$SECOND_READER_VALUE"), $SECOND_READER_SOURCE"
2640
+ if [[ "$RUNNER_HOST" == claude && "$RUNNER_PASS_MCP" == off ]]; then
2641
+ ui_info "MCP servers are off, from $RUNNER_PASS_MCP_SOURCE"
2642
+ elif [[ "$RUNNER_HOST" == claude && "$RUNNER_PASS_MCP" == keep ]]; then
2643
+ ui_info "MCP servers are limited to $(ui_val "$RUNNER_PASS_MCP_KEPT"), from $RUNNER_PASS_MCP_SOURCE"
2644
+ fi
2645
+ }
2646
+ # styled_exclusions: what the first snapshot left out, and outside a sweep the issues it holds
2647
+ # behind an open blocker.
2648
+ styled_exclusions() {
2649
+ [[ -z "$EXCLUDED" ]] || ui_info "excluded: $EXCLUDED"
2650
+ [[ "$SWEEPS_SET" -eq 1 || -z "${BLOCKED:-}" ]] || ui_info "blocked: $BLOCKED"
2651
+ }
2652
+
2653
+ # A first snapshot with nothing eligible is a shift with nothing to queue: a correct stop,
2654
+ # written down as one, with the scope and the exclusions so the empty frontier can be read
2655
+ # against the tracker.
2656
+ if [[ "$HAS_QUEUE" -eq 1 && "${#QUEUE[@]}" -eq 0 ]]; then
2657
+ if ui_attended; then
2658
+ styled_preflight
2659
+ ui_section primary PLAN
2660
+ if [[ -n "$EPIC" ]]; then
2661
+ ui_info "$(scope_line)"
2662
+ ui_warn "#$EPIC has no sub-issue that is open, unassigned, unlocked and unblocked, so the shift has nothing to queue"
2663
+ else
2664
+ ui_warn "sweep 1 found nothing eligible in the workset $ISSUES, so the shift has nothing to queue"
2665
+ fi
2666
+ styled_exclusions
2667
+ [[ "$DRY_RUN" -eq 0 ]] || { ui_section secondary DONE; ui_ok "the dry run spent nothing"; }
2668
+ else
2669
+ if [[ -n "$EPIC" ]]; then
2670
+ note "$(scope_line)"
2671
+ note "#$EPIC has no sub-issue that is open, unassigned, unlocked and unblocked, so the shift has nothing to queue"
2672
+ else
2673
+ note "sweep 1 found nothing eligible in the workset $ISSUES, so the shift has nothing to queue"
2674
+ fi
2675
+ [[ -n "$EXCLUDED" ]] && note "excluded: $EXCLUDED"
2676
+ [[ "$SWEEPS_SET" -eq 1 || -z "${BLOCKED:-}" ]] || note "blocked: $BLOCKED"
2677
+ [[ -n "$REPORT_URL" || "$DRY_RUN" -eq 1 ]] && note "$REPORTING_NOTE"
2678
+ fi
2679
+ if [[ "$DRY_RUN" -eq 0 ]]; then
2680
+ MAX="${MAX:-0}"
2681
+ open_shift
2682
+ plan_sweep
2683
+ pass=0; exit_code=0; STOP_KIND=frontier
2684
+ stop_reason="nothing eligible to queue"
2685
+ close_shift
2686
+ fi
2687
+ exit 0
2688
+ fi
2689
+
2690
+ # --max defaults to the queue's length. Under --sweeps it is the scope's size, because a
2691
+ # later sweep may admit an issue the first one excluded: for an epic the children open when
2692
+ # the shift started, for a workset every issue the caller named.
2693
+ if [[ -z "$MAX" ]]; then
2694
+ MAX=4
2695
+ [[ "$HAS_QUEUE" -eq 1 ]] && MAX="${#QUEUE[@]}"
2696
+ if [[ "$SWEEPS_SET" -eq 1 ]]; then
2697
+ if [[ -n "$EPIC" ]]; then MAX="$(jq -r 'length' <<< "$EPIC_SCOPE")"
2698
+ else MAX="$(jq -r '(.candidates | length) + (.excluded | length)' <<< "$SNAPSHOT")"; fi
2699
+ fi
2700
+ fi
2701
+ [[ -z "$ADOPT" ]] || adopt_max
2702
+
2703
+ # The worst case a shift can spend, in driver passes and model starts, from the caps alone.
2704
+ # --max caps distinct issues and --sweeps caps traversals, so the passes are their product.
2705
+ # The script engine's pass runs its fork at most twice, so its starts are two per pass, and
2706
+ # it starts up to three reconciliation contexts per issue, counted on the issue's checkpoint
2707
+ # across every pass and sweep, so those are counted once per issue and not per pass. Under
2708
+ # /kryso the reconciliation runs inside the pass's own session and starts nothing. A
2709
+ # rate-limit retry is a further start, at most MAX_WAITS of them in a shift.
2710
+ STARTS_PER_PASS=1
2711
+ RECONCILIATIONS_PER_ISSUE=0
2712
+ [[ "$ENGINE" == script ]] && { STARTS_PER_PASS=2; RECONCILIATIONS_PER_ISSUE=3; }
2713
+ WORST_PASSES=$(( MAX * SWEEPS ))
2714
+ WORST_STARTS=$(( WORST_PASSES * STARTS_PER_PASS + MAX * RECONCILIATIONS_PER_ISSUE ))
2715
+
2716
+ # starts_shown: what the start bound is made of, for the plain line's parenthesis.
2717
+ starts_shown() {
2718
+ if [[ "$RECONCILIATIONS_PER_ISSUE" -gt 0 ]]; then
2719
+ printf '%s per pass and up to %s per issue under the %s engine' "$STARTS_PER_PASS" "$(plural "$RECONCILIATIONS_PER_ISSUE" "reconciliation context" "reconciliation contexts")" "$ENGINE"
2720
+ else
2721
+ printf '%s per pass under the %s engine' "$STARTS_PER_PASS" "$ENGINE"
2722
+ fi
2723
+ }
2724
+
2725
+ # ---- the workflow each pass runs ----------------------------------------------------------
2726
+
2727
+ # A pass chooses its workflow itself, from its --workflow and the issue's labels, through the
2728
+ # resolver beside this script (ADR 0046). The driver reads the labels too, but only when it has
2729
+ # something to do with the answer: a --workflow to name in the dry run and the log, or a
2730
+ # ship-it shift, where a pass whose workflow is not the built-in default runs under the script
2731
+ # engine, because the ship-it engine runs only the default. Every other shift reads no label.
2732
+ WORKFLOW_MJS="$HERE/workflow.mjs"
2733
+ # workflow_labels_needed: the shift reads each queued issue's labels.
2734
+ workflow_labels_needed() { [[ "$HAS_QUEUE" -eq 1 ]] && [[ -n "$WORKFLOW" || "$ENGINE" == ship-it ]]; }
2735
+
2736
+ # issue_workflow <issue>: the workflow the pass on <issue> chooses, its source and, when a label
2737
+ # beat --workflow, why, into the issue's state, read once per issue. A choice the resolver
2738
+ # refuses, such as two workflow labels, is kept as the reason the pass will stop in preflight.
2739
+ issue_workflow() {
2740
+ local labels out name by why
2741
+ [[ -z "$(st_get "$1" workflow)" ]] || return 0
2742
+ labels="$(gh issue view "$1" --json labels 2>/dev/null | jq -r '[.labels[]?.name] | join(",")' 2>/dev/null)" || labels=""
2743
+ if ! out="$(node "$WORKFLOW_MJS" choose --flag "$WORKFLOW" --labels "$labels" 2>&1)"; then
2744
+ st_set "$1" workflow "?"; st_set "$1" workflow_why "$(head -1 <<< "$out" | sed 's/^kryso workflow: //')"; return 0
2745
+ fi
2746
+ IFS=$'\t' read -r name by why <<< "$out"
2747
+ st_set "$1" workflow "$name"; st_set "$1" workflow_by "$by"; st_set "$1" workflow_why "$why"
2748
+ }
2749
+
2750
+ # workflow_engine <issue>: the engine the pass on <issue> runs under: the shift's, except under
2751
+ # ship-it for a pass whose workflow is not the default, which the script engine runs. That takes
2752
+ # in a choice the resolver refused, so the pass script's preflight stops it with the reason.
2753
+ workflow_engine() {
2754
+ local name
2755
+ name="$(st_get "$1" workflow)"
2756
+ if [[ "$SHIFT_ENGINE" == ship-it && -n "$name" && "$name" != default && -f "$PASS_SCRIPT" ]]; then echo script; else echo "$SHIFT_ENGINE"; fi
2757
+ }
2758
+
2759
+ # workflow_said <issue>: the sentence that names the workflow the pass on <issue> runs and why,
2760
+ # for the dry run, and empty when the shift read no labels.
2761
+ workflow_said() {
2762
+ local name by why engine said
2763
+ name="$(st_get "$1" workflow)"; by="$(st_get "$1" workflow_by)"; why="$(st_get "$1" workflow_why)"
2764
+ [[ -n "$name" ]] || return 0
2765
+ if [[ "$name" == "?" ]]; then printf '#%s stops in the pass script'"'"'s preflight: it has %s' "$1" "$why"; return 0; fi
2766
+ case "$by" in
2767
+ flag) said="#$1 runs the $name workflow, from --workflow" ;;
2768
+ label) said="#$1 runs the $name workflow, from its label workflow:$name${why:+: $why}" ;;
2769
+ *) said="#$1 runs the default workflow" ;;
2770
+ esac
2771
+ engine="$(workflow_engine "$1")"
2772
+ [[ "$engine" == "$SHIFT_ENGINE" ]] || said+=", under the $engine engine, because the $SHIFT_ENGINE engine runs only the built-in default"
2773
+ printf '%s' "$said"
2774
+ }
2775
+
2776
+ # workflow_logged <issue>: what the shift log says of the workflow, on a pass whose label beat
2777
+ # --workflow or whose engine is not the shift's, and nothing on any other pass.
2778
+ workflow_logged() {
2779
+ [[ -n "$(st_get "$1" workflow_why)" && "$(st_get "$1" workflow)" != "?" || "$(workflow_engine "$1")" != "$SHIFT_ENGINE" ]] || return 0
2780
+ workflow_said "$1" | sed 's/^#[0-9]* runs the \([^ ]*\) workflow, from /\1 from /'
2781
+ }
2782
+
2783
+ # ---- the shift's workflow and its shift stages ----------------------------------------------
2784
+
2785
+ # The shift resolves one workflow of its own, --workflow or the repository's default, from the
2786
+ # base its passes start from, as each pass resolves its own (ADR 0046). Two things come of it.
2787
+ # Under the ship-it engine, a repository whose default workflow differs from the built-in one
2788
+ # stops in the preflight, because only the script engine keeps a workflow's stages; a pass whose
2789
+ # label or --workflow names another workflow already runs under the script engine, above. And
2790
+ # the workflow's shift stages, commands stages the driver runs in the main checkout without the
2791
+ # tracker token, after each pass and once after the last. Each command writes its own log,
2792
+ # stage-<id>-pass<n>.<k>.log or stage-<id>-end.<k>.log, in the shift's directory, and a stage line in shift.log. A
2793
+ # failing command ends its stage and is reported in the summary and the close, never retried,
2794
+ # and it changes no pass's outcome and does not stop the shift.
2795
+ SHIFT_WF_JSON=""
2796
+ SHIFT_WF_REF=""
2797
+ SHIFT_STAGE_FAILURES="[]"
2798
+
2799
+ # shift_workflow_ref: the commit the shift reads its workflow at, origin's base where it has one.
2800
+ shift_workflow_ref() {
2801
+ local ref
2802
+ for ref in ${BASE:+"origin/$BASE" "$BASE"} origin/HEAD HEAD; do
2803
+ if git -C "$REPO_ROOT" rev-parse -q --verify "$ref^{commit}" > /dev/null 2>&1; then printf '%s' "$ref"; return 0; fi
2804
+ done
2805
+ return 1
2806
+ }
2807
+
2808
+ # resolve_shift_workflow: SHIFT_WF_JSON, or a preflight stop that names why.
2809
+ resolve_shift_workflow() {
2810
+ local name="${WORKFLOW:-default}" out repo_default built_in
2811
+ [[ -f "$WORKFLOW_MJS" ]] || die "cannot find $WORKFLOW_MJS, the workflow resolver this driver runs beside"
2812
+ command -v node > /dev/null 2>&1 || die "node is not installed, and the workflow resolver runs on it"
2813
+ SHIFT_WF_REF="$(shift_workflow_ref)" || die "cannot find a commit to read the shift's workflow at"
2814
+ out="$(node "$WORKFLOW_MJS" show "$name" --repo "$REPO_ROOT" --ref "$SHIFT_WF_REF" --json 2>&1)" \
2815
+ || die "the workflow $name does not resolve at $SHIFT_WF_REF: $(head -1 <<< "$out" | sed 's/^kryso workflow: //')"
2816
+ jq -e '.hash | test("^[0-9a-f]{64}$")' <<< "$out" > /dev/null 2>&1 || die "the resolver gave no workflow for $name at $SHIFT_WF_REF"
2817
+ SHIFT_WF_JSON="$out"
2818
+ [[ "$SHIFT_ENGINE" == ship-it ]] || return 0
2819
+ repo_default="$out"
2820
+ if [[ "$name" != default ]]; then
2821
+ repo_default="$(node "$WORKFLOW_MJS" show default --repo "$REPO_ROOT" --ref "$SHIFT_WF_REF" --json 2>&1)" \
2822
+ || die "the workflow default does not resolve at $SHIFT_WF_REF: $(head -1 <<< "$repo_default" | sed 's/^kryso workflow: //')"
2823
+ fi
2824
+ built_in="$(node "$WORKFLOW_MJS" show default --built-in --repo "$REPO_ROOT" --json 2>/dev/null | jq -r .hash 2>/dev/null)"
2825
+ [[ "$built_in" =~ ^[0-9a-f]{64}$ ]] || die "the resolver cannot show kryso's built-in default workflow, so the ship-it engine cannot be checked against it"
2826
+ [[ "$(jq -r .hash <<< "$repo_default")" == "$built_in" ]] \
2827
+ || die "the repository's default workflow, $(jq -r .file <<< "$repo_default") at $SHIFT_WF_REF, differs from the built-in default, and the ship-it engine runs only the built-in default. Run the shift with --engine script"
2828
+ }
2829
+
2830
+ # shift_stages_lines: the opening's lines on the shift stages, one per point that has any.
2831
+ shift_stages_lines() {
2832
+ local at said list
2833
+ [[ -n "$SHIFT_WF_JSON" ]] || return 0
2834
+ for at in after-pass end; do
2835
+ list="$(jq -r --arg at "$at" '.shift[$at] // [] | map("\(.id) (\(.commands | join("; ")))") | join(", ")' <<< "$SHIFT_WF_JSON")"
2836
+ [[ -n "$list" ]] || continue
2837
+ if [[ "$at" == after-pass ]]; then said="after each pass"; else said="once after the last pass"; fi
2838
+ printf 'the %s workflow runs %s: %s, in %s without the tracker token\n' "$(jq -r .name <<< "$SHIFT_WF_JSON")" "$said" "$list" "$REPO_ROOT"
2839
+ done
2840
+ }
2841
+
2842
+ # run_shift_stages <after-pass|end>: the shift stages at the point, as the section above says.
2843
+ run_shift_stages() {
2844
+ local at="$1" stage id cmd n count rel code none when shown
2845
+ [[ -n "$SHIFT_WF_JSON" ]] || return 0
2846
+ if [[ "$at" == end ]]; then when=end; shown="at the end of the shift"; else when="pass$pass"; shown="after pass $pass"; fi
2847
+ while IFS= read -r -u 3 stage; do
2848
+ id="$(jq -r .id <<< "$stage")"
2849
+ count="$(jq -r '.commands | length' <<< "$stage")"
2850
+ # By index, so a command that holds a newline stays one command.
2851
+ for ((n = 1; n <= count; n++)); do
2852
+ cmd="$(jq -r --argjson i "$((n - 1))" '.commands[$i]' <<< "$stage")"
2853
+ rel="stage-$id-$when.$n.log"
2854
+ none="$(mktemp -d)"
2855
+ {
2856
+ printf '$ %s\n' "$cmd"
2857
+ ( cd "$REPO_ROOT" && unset "${RUNNER_TRACKER_TOKENS[@]}" && GH_CONFIG_DIR="$none" bash -c "$cmd" ) < /dev/null 2>&1
2858
+ code=$?
2859
+ printf 'exit=%s\n' "$code"
2860
+ } > "$SHIFT_DIR/$rel"
2861
+ rm -rf "$none"
2862
+ printf '%s stage=%s at=%s pass=%s exit=%s log=%s command=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$id" "$at" "$pass" "$code" "$rel" "${cmd//$'\n'/ }" >> "$SHIFT_LOG"
2863
+ if [[ "$code" -ne 0 ]]; then
2864
+ SHIFT_STAGE_FAILURES="$(jq -c --arg s "$id" --arg at "$at" --argjson p "$pass" --argjson e "$code" --arg l "$rel" --arg c "${cmd//$'\n'/ }" \
2865
+ '. + [{stage: $s, at: $at, pass: $p, exit: $e, log: $l, command: $c}]' <<< "$SHIFT_STAGE_FAILURES")"
2866
+ if ui_attended; then ui_warn "shift stage $id failed $shown: $cmd exit=$code ($SHIFT_DIR/$rel)"; else warn "shift stage $id failed $shown: $cmd exit=$code ($SHIFT_DIR/$rel)"; fi
2867
+ break
2868
+ fi
2869
+ done
2870
+ [[ "$code" -ne 0 ]] || note "shift stage $id ran $shown, $count command(s) exit=0"
2871
+ done 3< <(jq -c --arg at "$at" '.shift[$at] // [] | .[]' <<< "$SHIFT_WF_JSON")
2872
+ }
2873
+
2874
+ # shift_stage_failures_line: the close's line on the shift stages that failed, or nothing.
2875
+ shift_stage_failures_line() {
2876
+ jq -r 'if length == 0 then empty else "shift stages failed: " + (map("\(.stage) " + (if .at == "end" then "at the end" else "after pass \(.pass)" end) + " (\(.command) exit=\(.exit), \(.log))") | join(", ")) end' <<< "${SHIFT_STAGE_FAILURES:-[]}"
2877
+ }
2878
+
2879
+ # pass_prompt <issue> <base> [continue-brief]: the text after the skill name, when the shift
2880
+ # has a queue. A continuation names the issue, its branch, the recorded stage and the brief,
2881
+ # so /kryso resumes that worktree rather than claiming afresh. Without a queue the prompt
2882
+ # is the bare skill name, as it always was.
2883
+ pass_prompt() {
2884
+ local suffix=""
2885
+ if [[ "$HAS_QUEUE" -eq 1 ]]; then
2886
+ if [[ -n "${3:-}" ]]; then
2887
+ suffix="Continue issue #${1} on branch $(st_get "${1}" branch) from stage $(st_get "${1}" stage). Base branch: ${2}. Continuation brief: $REPO_ROOT/${3}."
2888
+ else
2889
+ suffix="Work issue #${1}. Base branch: ${2}."
2890
+ # An epic's queue is a sweep of its children, so a gate that refuses one writes nothing
2891
+ # on it. stage-1-claim.md has the rule.
2892
+ [[ -z "$EPIC" ]] || suffix+=" The issue came off a sweep of epic #$EPIC."
2893
+ fi
2894
+ [[ -n "$NOTE" ]] && suffix+=" Caller note: $NOTE"
2895
+ fi
2896
+ runner_skill_prompt kryso "$suffix"
2897
+ }
2898
+
2899
+ # pass_cmd <issue> <base> <resume> <final> [continue-brief]: fills PASS_CMD, the argv one pass
2900
+ # runs. Under the default engine it is the host with the prompt, and every pass, a
2901
+ # continuation included, is a fresh session: the one resume of a host session is a
2902
+ # rate-limit retry inside a pass, on a host that supports it. Under the script engine it is
2903
+ # the pass script with the issue, the base, the note, the budget, the model, the key and the
2904
+ # pass-through arguments, or with --resume when the pass is a retry or a continuation,
2905
+ # because the pass script reads the base and the note back off its own ledger and brief and
2906
+ # cuts no second tree. Under a stacked sweep it carries --park-at-merge either way.
2907
+ pass_cmd() {
2908
+ local issue="${1:-}" base="${2:-}" resume="${3:-0}" final="${4:-/tmp/ship-loop-final.json}" brief="${5:-}"
2909
+ if [[ "$ENGINE" == script ]]; then
2910
+ PASS_CMD=(bash "$PASS_SCRIPT" "$issue")
2911
+ if [[ "$resume" -eq 1 || -n "$brief" ]]; then
2912
+ PASS_CMD+=(--resume)
2913
+ else
2914
+ PASS_CMD+=(--base "$base")
2915
+ [[ -n "$NOTE" ]] && PASS_CMD+=(--note "$NOTE")
2916
+ [[ -z "$WORKFLOW" ]] || PASS_CMD+=(--workflow "$WORKFLOW")
2917
+ [[ -z "$EPIC" ]] || PASS_CMD+=(--swept)
2918
+ fi
2919
+ # A stacked sweep's chain stands on open merge-ready PRs, so its passes keep theirs open
2920
+ # whatever the base. Everywhere else the pass merges what the base lets it merge.
2921
+ [[ "$STACKED_SWEEPS" -eq 0 ]] || PASS_CMD+=(--park-at-merge)
2922
+ PASS_CMD+=(--profile "$PROFILE")
2923
+ PASS_CMD+=(--effort "$EFFORT")
2924
+ PASS_CMD+=(--timeout "$TIMEOUT" --grace "$GRACE")
2925
+ [[ "${PASS_CONSUMED:-0}" -eq 0 ]] || PASS_CMD+=(--consumed "$PASS_CONSUMED")
2926
+ [[ "$BUDGET_SET" -eq 0 ]] || PASS_CMD+=(--budget "$BUDGET")
2927
+ [[ -n "$MODEL" ]] && PASS_CMD+=(--model "$MODEL")
2928
+ [[ "$KEEP_API_KEY" -eq 1 ]] && PASS_CMD+=(--api-key)
2929
+ [[ -z "$SECOND_READER" ]] || PASS_CMD+=(--second-reader "$SECOND_READER")
2930
+ [[ -z "$MCP" ]] || PASS_CMD+=(--mcp "$MCP")
2931
+ [[ "${#EXTRA_ARGS[@]}" -gt 0 ]] && PASS_CMD+=(-- "${EXTRA_ARGS[@]}")
2932
+ return 0
2933
+ fi
2934
+ PASS_MODE=start
2935
+ PASS_PROMPT="$(pass_prompt "$issue" "$base" "$brief")"
2936
+ PASS_SESSION=""
2937
+ if [[ "$resume" -eq 1 ]] && runner_session_resume_supported; then
2938
+ PASS_MODE=resume
2939
+ PASS_PROMPT="Continue the same ship-it pass after the rate limit."
2940
+ PASS_SESSION="$RESUME_SESSION"
2941
+ fi
2942
+ RUNNER_EXTRA_ARGS=()
2943
+ [[ "${#EXTRA_ARGS[@]}" -eq 0 ]] || RUNNER_EXTRA_ARGS=("${EXTRA_ARGS[@]}")
2944
+ runner_prepare_command "$PASS_MODE" "$PASS_PROMPT" "$SCHEMA" "$final" "$MODEL" "$BUDGET" "$PASS_SESSION" "$EFFORT"
2945
+ PASS_CMD=("${RUNNER_CMD[@]}")
2946
+ }
2947
+
2948
+ # shell_quoted <text>: the text inside a double-quoted shell string, the four characters that
2949
+ # mean something there escaped, so a note with a quote or a dollar in it reruns as shown.
2950
+ shell_quoted() { printf '%s' "${1}" | sed -e 's/[\\"$`]/\\&/g'; }
2951
+
2952
+ # printable_cmd <issue> <base>: the same command as a line a person can read and rerun. The
2953
+ # pass script and the schema are named by their path from the repo root where they sit
2954
+ # under it, and by their absolute path from a user-level install, so the line runs from the
2955
+ # repo root either way. The key is the pass script's own flag, so the env prefix is the
2956
+ # default engine's alone. The base is quoted because a stacked dry run prints a placeholder
2957
+ # in its place.
2958
+ printable_cmd() {
2959
+ local out=""
2960
+ if [[ "$ENGINE" == script ]]; then
2961
+ out="bash ${PASS_SCRIPT#"$REPO_ROOT"/} ${1} --base \"$(shell_quoted "${2}")\""
2962
+ [[ -n "$NOTE" ]] && out+=" --note \"$(shell_quoted "$NOTE")\""
2963
+ [[ -z "$WORKFLOW" ]] || out+=" --workflow $WORKFLOW"
2964
+ [[ -z "$EPIC" ]] || out+=" --swept"
2965
+ [[ "$STACKED_SWEEPS" -eq 0 ]] || out+=" --park-at-merge"
2966
+ out+=" --profile $PROFILE"
2967
+ out+=" --effort $EFFORT"
2968
+ out+=" --timeout $TIMEOUT --grace $GRACE"
2969
+ [[ "$BUDGET_SET" -eq 0 ]] || out+=" --budget $BUDGET"
2970
+ [[ -n "$MODEL" ]] && out+=" --model $MODEL"
2971
+ [[ "$KEEP_API_KEY" -eq 1 ]] && out+=" --api-key"
2972
+ [[ -z "$SECOND_READER" ]] || out+=" --second-reader $SECOND_READER"
2973
+ [[ -z "$MCP" ]] || out+=" --mcp \"$(shell_quoted "$MCP")\""
2974
+ [[ "${#EXTRA_ARGS[@]}" -gt 0 ]] && out+=" -- ${EXTRA_ARGS[*]}"
2975
+ printf '%s' "$out"
2976
+ return 0
2977
+ fi
2978
+ runner_printable_command "$(pass_prompt "${1:-}" "${2:-}")" "$SCHEMA" "${SCHEMA#"$REPO_ROOT"/}" \
2979
+ "<last-message.json>" "$MODEL" "$BUDGET" "$EFFORT" "$KEEP_API_KEY" ${EXTRA_ARGS[@]+"${EXTRA_ARGS[@]}"}
2980
+ }
2981
+
2982
+ # shown_base <n>: the base pass n's command is shown with. A stacked queue's later pass bases
2983
+ # on the branch the pass before it reports, which a dry run cannot know yet.
2984
+ shown_base() {
2985
+ if [[ "$STACK" -eq 1 && "$STACKED_SWEEPS" -eq 0 && "$1" -gt 1 ]]; then
2986
+ printf '<the branch pass %s reports>' "$(( $1 - 1 ))"
2987
+ else
2988
+ printf '%s' "$BASE"
2989
+ fi
2990
+ }
2991
+
2992
+ # dry_cmd <issue> <base>: on a dry run, the issue's pass command under the engine its pass runs
2993
+ # under, once the loop has read its labels where the shift reads them.
2994
+ dry_cmd() {
2995
+ local cmd
2996
+ ENGINE="$(workflow_engine "$1")"
2997
+ cmd="$(printable_cmd "$1" "$2")"
2998
+ ENGINE="$SHIFT_ENGINE"
2999
+ printf '%s' "$cmd"
3000
+ }
3001
+
3002
+ # dry_workflow <issue>: on a dry run, the workflow sentence for the issue, which dry_cmd read.
3003
+ # Nothing when the shift reads no labels, or names no --workflow and the issue runs the default
3004
+ # under the shift's engine, so such a dry run reads as it did.
3005
+ dry_workflow() {
3006
+ workflow_labels_needed || return 0
3007
+ [[ -n "$WORKFLOW" || "$(st_get "$1" workflow)" != default || "$(workflow_engine "$1")" != "$SHIFT_ENGINE" ]] || return 0
3008
+ workflow_said "$1"
3009
+ }
3010
+
3011
+ # allowance_line: the plain line for the allowance, which both engines run under.
3012
+ allowance_line() {
3013
+ printf 'each pass gets %ss of active execution and %ss for its processes to exit, and a rate-limit wait does not count' "$TIMEOUT" "$GRACE"
3014
+ }
3015
+
3016
+ # styled_opening: on an attended run, the preflight facts under the preflight's pill, then the
3017
+ # plan under its own: the bounds, the queue and, on a dry run, one arrow line per planned pass
3018
+ # with its command, closed by a DONE pill. The lines are the plain notes' words with no prefix,
3019
+ # because the pills carry the context.
3020
+ styled_opening() {
3021
+ styled_preflight
3022
+ ui_section primary PLAN
3023
+ ui_info "$(runner_shift_limit_summary "$MAX" "$BUDGET")"
3024
+ ui_info "$(ui_val "$SWEEPS") $(plural "$SWEEPS" sweep sweeps | cut -d' ' -f2) $([[ "$SWEEPS" -eq 1 ]] && echo runs || echo run) at most $(plural "$WORST_PASSES" "driver pass" "driver passes") ($(plural "$MAX" issue issues) x $(plural "$SWEEPS" sweep sweeps)) and $WORST_STARTS model starts ($(starts_shown)), plus up to $MAX_WAITS rate-limit retries"
3025
+ ui_info "$(allowance_line)"
3026
+ local stages_line
3027
+ while IFS= read -r stages_line; do ui_info "$stages_line"; done < <(shift_stages_lines)
3028
+ if [[ -n "$ADOPT" ]]; then
3029
+ local line
3030
+ while IFS= read -r line; do ui_info "$line"; done < <(adopt_lines)
3031
+ fi
3032
+ if [[ "$HAS_QUEUE" -eq 1 ]]; then
3033
+ [[ -z "$EPIC" ]] || ui_info "$(scope_line)"
3034
+ if [[ "$SWEEPS_SET" -eq 1 ]]; then
3035
+ ui_info "sweep 1 snapshot: $(ui_val "${QUEUE[*]}")"
3036
+ [[ "$SWEEPS" -eq 1 ]] || ui_info "later sweeps take a fresh snapshot each, continue only what this shift owns and can prove resumable, and stop early when nothing is left to continue or admit"
3037
+ else
3038
+ ui_info "queue: $(ui_val "${QUEUE[*]}")"
3039
+ fi
3040
+ styled_exclusions
3041
+ ui_info "the base is $(ui_val "$BASE")"
3042
+ [[ -z "$NOTE" ]] || ui_info "note: $NOTE"
3043
+ [[ "$ENGINE" != script ]] || ui_info "the script engine runs one ship-pass.sh process per issue, and the build fork is its model process"
3044
+ [[ "$STACKED_SWEEPS" -eq 0 ]] || ui_info "a dependent enters a sweep on its blocker's branch once the blocker is merge-ready, and sweep 1 bases on $(ui_val "$BASE")"
3045
+ fi
3046
+ [[ "$DRY_RUN" -eq 1 ]] || return 0
3047
+ local i=0 issue cmd said
3048
+ if [[ "$HAS_QUEUE" -eq 1 ]]; then
3049
+ for issue in "${QUEUE[@]:0:$MAX}"; do
3050
+ [[ -z "$(st_get "$issue" adopted)" ]] || continue
3051
+ i=$((i + 1))
3052
+ ! workflow_labels_needed || issue_workflow "$issue"
3053
+ cmd="$(dry_cmd "$issue" "$(shown_base "$i")")"
3054
+ ui_arrow "$(ui_tint dim "pass $i") $cmd"
3055
+ said="$(dry_workflow "$issue")"
3056
+ [[ -z "$said" ]] || ui_info "$said"
3057
+ done
3058
+ else
3059
+ # Without a queue every pass runs the same bare command.
3060
+ cmd="$(printable_cmd)"
3061
+ for (( i = 1; i <= MAX; i++ )); do ui_arrow "$(ui_tint dim "pass $i") $cmd"; done
3062
+ fi
3063
+ ui_section secondary DONE
3064
+ ui_ok "the dry run spent nothing"
3065
+ }
3066
+
3067
+ # The shift's workflow, once the base is known and before the opening names its shift stages.
3068
+ resolve_shift_workflow
3069
+
3070
+ if ui_attended; then
3071
+ styled_opening
3072
+ else
3073
+ note "working in $REPO_ROOT"
3074
+ note "the $PROFILE profile runs $RUNNER_HOST $RUNNER_VERSION on $RUNNER_BILLING billing, the tracker is $TRACKER, and the label is '$LABEL'"
3075
+ shown="$(model_shown)"
3076
+ note "the effort is $EFFORT${shown:+, and the model is $shown}"
3077
+ [[ -z "$MEMBER_LINE" ]] || note "$MEMBER_LINE"
3078
+ note "$(candidates_line "$CANDIDATES")"
3079
+ note "$(worktrees_line "$(sed 's/ $//' <<< "$WORKTREES")")"
3080
+ note "CI: $CI"
3081
+ note "skills: $RUNNER_SKILLS"
3082
+ note "$(runner_pass_skills_line)"
3083
+ # Said when there is something to say, and on a dry run either way, so a misconfigured URL
3084
+ # is caught before a shift spends anything and an adopter who never set one sees no change.
3085
+ [[ -n "$REPORT_URL" || "$DRY_RUN" -eq 1 ]] && note "$REPORTING_NOTE"
3086
+ [[ -z "$SECOND_READER_SOURCE" ]] || note "the second reader is $SECOND_READER_VALUE, $SECOND_READER_SOURCE"
3087
+ if [[ "$RUNNER_HOST" == claude && "$RUNNER_PASS_MCP" == off ]]; then
3088
+ note "MCP servers are off, from $RUNNER_PASS_MCP_SOURCE"
3089
+ elif [[ "$RUNNER_HOST" == claude && "$RUNNER_PASS_MCP" == keep ]]; then
3090
+ note "MCP servers are limited to $RUNNER_PASS_MCP_KEPT, from $RUNNER_PASS_MCP_SOURCE"
3091
+ fi
3092
+ note "$(runner_shift_limit_summary "$MAX" "$BUDGET")"
3093
+ note "$(plural "$SWEEPS" sweep sweeps) $([[ "$SWEEPS" -eq 1 ]] && echo runs || echo run) at most $(plural "$WORST_PASSES" "driver pass" "driver passes") ($(plural "$MAX" issue issues) x $(plural "$SWEEPS" sweep sweeps)) and $WORST_STARTS model starts ($(starts_shown)), plus up to $MAX_WAITS rate-limit retries"
3094
+ note "$(allowance_line)"
3095
+ shift_stages_lines | sed 's/^/ship-loop: /'
3096
+ [[ -z "$ADOPT" ]] || adopt_lines | sed 's/^/ship-loop: /'
3097
+ echo
3098
+ if [[ "$HAS_QUEUE" -eq 1 ]]; then
3099
+ [[ -z "$EPIC" ]] || note "$(scope_line)"
3100
+ if [[ "$SWEEPS_SET" -eq 1 ]]; then
3101
+ note "sweep 1 snapshot: ${QUEUE[*]}"
3102
+ [[ -n "$EXCLUDED" ]] && note "excluded: $EXCLUDED"
3103
+ [[ "$SWEEPS" -eq 1 ]] || note "later sweeps take a fresh snapshot each, continue only what this shift owns and can prove resumable, and stop early when nothing is left to continue or admit"
3104
+ else
3105
+ note "queue: ${QUEUE[*]}"
3106
+ [[ -z "$EXCLUDED" ]] || note "excluded: $EXCLUDED"
3107
+ [[ -n "${BLOCKED:-}" ]] && note "blocked: $BLOCKED"
3108
+ fi
3109
+ note "the base is $BASE"
3110
+ [[ -n "$NOTE" ]] && note "note: $NOTE"
3111
+ [[ "$ENGINE" == script ]] && note "the script engine runs one ship-pass.sh process per issue, and the build fork is its model process"
3112
+ echo
3113
+ [[ "$STACKED_SWEEPS" -eq 0 ]] || note "a dependent enters a sweep on its blocker's branch once the blocker is merge-ready, and sweep 1 bases on $BASE"
3114
+ i=0
3115
+ for issue in "${QUEUE[@]:0:$MAX}"; do
3116
+ [[ -z "$(st_get "$issue" adopted)" ]] || continue
3117
+ i=$((i + 1))
3118
+ ! workflow_labels_needed || issue_workflow "$issue"
3119
+ dry_cmd "$issue" "$(shown_base "$i")"; echo
3120
+ said="$(dry_workflow "$issue")"
3121
+ [[ -z "$said" ]] || note "$said"
3122
+ done
3123
+ else
3124
+ printable_cmd; echo
3125
+ fi
3126
+ echo
3127
+ if [[ "$DRY_RUN" -eq 1 ]]; then
3128
+ note "the dry run spent nothing"
3129
+ fi
3130
+ fi
3131
+
3132
+ [[ "$DRY_RUN" -eq 0 ]] || exit 0
3133
+
3134
+ # ---- the shift ------------------------------------------------------------------------
3135
+
3136
+ open_shift
3137
+ [[ -z "$ADOPT" ]] || adopt_write
3138
+ # A ctrl+c at the driver's terminal, or a TERM, which is how kryso attach stops a shift, ends the
3139
+ # shift at the next pass boundary, with its summary written and exit 130. Inside a pass,
3140
+ # deadline_run takes the signal first and stops the pass with everything it started, recording the
3141
+ # interruption in its ledger, and the driver reads that from DEADLINE_INTERRUPT. Between passes the
3142
+ # trap only marks the stop, so a tracker call or a wait in progress ends first.
3143
+ SHIFT_INTERRUPT=""
3144
+ trap 'SHIFT_INTERRUPT=INT' INT
3145
+ trap 'SHIFT_INTERRUPT=TERM' TERM
3146
+
3147
+ if ui_attended; then
3148
+ ui_info "shift $(ui_val "$SHIFT_ID"), log at $(ui_tint dim "$SHIFT_LOG")"
3149
+ else
3150
+ note "shift $SHIFT_ID, log at $SHIFT_LOG"
3151
+ echo
3152
+ fi
3153
+
3154
+ pass=0
3155
+ streak=0
3156
+ failed_runs=0
3157
+ waits=0
3158
+ exit_code=0
3159
+ # The attempt at the current pass, and the saved attempt before it when this is a retry or
3160
+ # a continuation.
3161
+ attempt=1
3162
+ predecessor=""
3163
+
3164
+ # STOP_KIND is the break that ended the loop, for stop_state; the reason is its prose.
3165
+ STOP_KIND=max
3166
+ stop_reason="reached the max of $MAX runs, and this shift did not read whether the board holds more work"
3167
+ HELD_BY_MAX=""
3168
+
3169
+ # The base each pass is told. A stacked shift moves it to the branch the last pass reported.
3170
+ PASS_BASE="$BASE"
3171
+ # Whether the next run of the pass script is a retry of a pass that was waited out, which
3172
+ # resumes in the worktree that pass left rather than claim and cut again.
3173
+ RESUME=0
3174
+ # The pass under way: its queued issue, the allowance it runs under, and the active execution
3175
+ # the attempts before it in this pass consumed, which a rate-limit retry carries.
3176
+ PASS_ISSUE=""
3177
+ PASS_ALLOWANCE="$TIMEOUT"
3178
+ PASS_CONSUMED=0
3179
+ RESUME_SESSION=""
3180
+
3181
+ # read_pass_result <file> <exit>: what the pass left, into subtype, cost, session, outcome,
3182
+ # issue, pr, branch, closeout_step, is_error, limit and limit_result, read per engine. The
3183
+ # step is the one the pass script's closeout field names, and is empty for a closeout that
3184
+ # finished and for a ship-it block, which has no such field. The pass script
3185
+ # prints the outcome block itself, with the fork's cost and session id read off the fork's
3186
+ # saved result, and its exit code names a limit: 2 is a rate limit and 3 a budget stop, so
3187
+ # the driver's waits and stops apply as they do to claude's. A rate limit's reset is in the
3188
+ # fork's saved result, which the block names, and limit_result is the file to read it from.
3189
+ read_result_metadata() {
3190
+ local file="$1"
3191
+ result_profile="$(result_field "$file" .profile "$PROFILE")"
3192
+ result_host="$(result_field "$file" .host "$RUNNER_HOST")"
3193
+ billing="$(result_field "$file" .billing "$RUNNER_BILLING")"
3194
+ cost_usd="$(result_field "$file" .cost_usd null)"
3195
+ usage="$(result_field "$file" .usage null | jq -c . 2>/dev/null || echo null)"
3196
+ result_effort="$(result_field "$file" .effort "$EFFORT")"
3197
+ }
3198
+
3199
+ read_pass_result() {
3200
+ local file="$1" code="$2"
3201
+ closeout_step=""
3202
+ if [[ "$ENGINE" == script ]]; then
3203
+ subtype=none
3204
+ cost="$(result_field "$file" .cost_usd null)"
3205
+ session="$(result_field "$file" .session none)"
3206
+ outcome="$(result_field "$file" .outcome none)"
3207
+ issue="$(result_field "$file" .issue none)"
3208
+ pr="$(result_field "$file" .pr none)"
3209
+ branch="$(result_field "$file" .branch none)"
3210
+ reason="$(result_field "$file" .reason "")"
3211
+ closeout_step="$(result_field "$file" .closeout "")"
3212
+ case "$closeout_step" in
3213
+ "incomplete "*) closeout_step="${closeout_step#incomplete }" ;;
3214
+ *) closeout_step="" ;;
3215
+ esac
3216
+ is_error=false
3217
+ block_outcome="$outcome"
3218
+ limit=""
3219
+ case "$code" in
3220
+ 2) limit="rate-limited" ;;
3221
+ 3) limit="budget-stop" ;;
3222
+ esac
3223
+ limit_result="$(result_field "$file" .result none)"
3224
+ read_result_metadata "$file"
3225
+ return 0
3226
+ fi
3227
+ subtype="$(result_field "$file" .subtype none)"
3228
+ cost="$(result_field "$file" .cost_usd null)"
3229
+ session="$(result_field "$file" .session_id none)"
3230
+ # The outcome block comes through one reader, whether the run filled the tool or left the
3231
+ # block in its text; result.sh says why the fallback exists. Say when it was the fallback,
3232
+ # because that run is worth opening by its session id.
3233
+ outcome="$(result_outcome_field "$file" outcome)"
3234
+ issue="$(result_outcome_field "$file" issue)"
3235
+ pr="$(result_outcome_field "$file" pr)"
3236
+ branch="$(result_outcome_field "$file" branch)"
3237
+ # The reason is the block's paragraph, and a run that wrote no block has none: an empty
3238
+ # string rather than the "none" the identifiers use, because it is prose, not an id.
3239
+ reason="$(result_outcome_field "$file" reason "")"
3240
+ if [[ "$outcome" != "none" && "$(result_field "$file" .structured_output.outcome none)" == "none" ]]; then
3241
+ note "pass $pass: structured_output was empty, so the driver read the outcome from the result text"
3242
+ fi
3243
+ is_error="$(result_field "$file" .is_error true)"
3244
+ block_outcome="$outcome"
3245
+ [[ "$outcome" != "none" || "$is_error" != "true" ]] || outcome=failed
3246
+ # Read before anything is counted as a failure; result.sh says why.
3247
+ limit="$(result_limit "$file" "$code")"
3248
+ limit_result="$file"
3249
+ read_result_metadata "$file"
3250
+ }
3251
+
3252
+ # A rate limit that names its reset is waited out exactly when the reset is within the ceiling.
3253
+ # Past it, or with no reset named, the wait is --wait. reference/outputs.md says why the ceiling exists.
3254
+ MAX_EXACT_WAIT=$(( 6 * 3600 ))
3255
+
3256
+ # clock <epoch>: that second on the local clock, hours and minutes, from BSD or GNU date.
3257
+ clock() { date -r "$1" +%H:%M 2>/dev/null || date -d "@$1" +%H:%M 2>/dev/null; }
3258
+
3259
+ # nap <seconds>: a sleep that an INT or a TERM cuts short. The shift traps both, and bash runs a
3260
+ # trap only once the foreground command ends, so a plain sleep would hold a stop for hours.
3261
+ nap() {
3262
+ local s
3263
+ sleep "$1" & s=$!
3264
+ wait "$s" 2>/dev/null
3265
+ kill "$s" 2>/dev/null
3266
+ wait "$s" 2>/dev/null
3267
+ return 0
3268
+ }
3269
+
3270
+ wait_until() {
3271
+ local reset="$1" seconds="$WAIT_SECONDS"
3272
+ if [[ "$reset" =~ ^[0-9]{13,}$ ]]; then reset=$(( reset / 1000 )); fi
3273
+ if [[ "$reset" =~ ^[0-9]+$ ]]; then
3274
+ local now; now="$(date -u +%s)"
3275
+ if (( reset > now && reset - now <= MAX_EXACT_WAIT )); then seconds=$(( reset - now )); fi
3276
+ fi
3277
+ if ui_attended && ! ui_gum; then
3278
+ ui_warn "rate limited, retrying pass $pass at $(clock "$(( $(date -u +%s) + seconds ))") (wait $waits of $MAX_WAITS)"
3279
+ nap "$seconds"
3280
+ elif ui_gum; then
3281
+ local until_at=$(( $(date -u +%s) + seconds )) spun left
3282
+ ui_spin "rate limited ◦ retrying at $(clock "$until_at") ◦ wait $waits of $MAX_WAITS" sleep "$seconds"
3283
+ spun=$?
3284
+ [[ "$spun" -ne 130 ]] || interrupted
3285
+ # A spinner that failed for any other reason leaves the rest of the wait to a plain sleep.
3286
+ left=$(( until_at - $(date -u +%s) ))
3287
+ [[ "$spun" -eq 0 || "$left" -le 0 ]] || nap "$left"
3288
+ else
3289
+ note "rate limit, waiting ${seconds}s before retrying pass $pass (wait $waits of $MAX_WAITS)"
3290
+ nap "$seconds"
3291
+ fi
3292
+ }
3293
+
3294
+ # ---- the live pass ----------------------------------------------------------------------
3295
+ #
3296
+ # On an attended run a pass runs in the background behind a spinner, and each event it writes
3297
+ # to its ledger prints as a line when it lands. gum cannot change a spinner's title while it
3298
+ # runs, so the spinner's command returns when something landed and the driver restarts it
3299
+ # with the title that is true now. Unattended, the pass runs in the foreground as it always
3300
+ # has and nothing here is called.
3301
+
3302
+ # duration <seconds>: a pass's length the way a person reads it, 45s, 12m or 1h21m.
3303
+ duration() {
3304
+ local s="$1"
3305
+ if (( s < 60 )); then echo "${s}s"
3306
+ elif (( s < 3600 )); then echo "$(( s / 60 ))m"
3307
+ else echo "$(( s / 3600 ))h$(( s % 3600 / 60 ))m"; fi
3308
+ }
3309
+
3310
+ # run_engine: runs pass $pass the way the engine says, PASS_CMD under the script engine or
3311
+ # runner_execute with the mode, prompt and session pass_cmd set, writing the result to
3312
+ # $result, the final block to $final and stderr to the shift's pass-<n>.err. Its status is
3313
+ # the pass's exit.
3314
+ run_engine() {
3315
+ if [[ "$ENGINE" == script ]]; then
3316
+ # The pass's stderr is a file, and a forced colour is the driver's terminal, not the file's,
3317
+ # so the pass under a driver prints its plain lines.
3318
+ CLICOLOR_FORCE= "${PASS_CMD[@]}" > "$result" 2>"$SHIFT_DIR/pass-$pass.err" </dev/null
3319
+ else
3320
+ RUNNER_EXTRA_ARGS=()
3321
+ [[ "${#EXTRA_ARGS[@]}" -eq 0 ]] || RUNNER_EXTRA_ARGS=("${EXTRA_ARGS[@]}")
3322
+ RUNNER_SCHEMA="$SCHEMA"
3323
+ # The host's output goes to files too, so it gets no forced colour either.
3324
+ CLICOLOR_FORCE= runner_execute "$PASS_MODE" "$result" "$final" "$SHIFT_DIR/pass-$pass.err" "$PASS_PROMPT" "" "$PASS_SESSION" "$MODEL" "$BUDGET" "$KEEP_API_KEY" "$EFFORT" </dev/null
3325
+ fi
3326
+ }
3327
+
3328
+ # run_pass: run_engine under the pass's allowance, holding the queued issue's authority, so a
3329
+ # pass that hangs anywhere, in its host, a tracker call, a receipt's queue, a gate or the CI
3330
+ # wait, is stopped by this shell with every process it started and nothing else. The ship-it
3331
+ # engine is stopped at PASS_ALLOWANCE. The pass script keeps that allowance itself and records
3332
+ # its own interruption, so for it the driver's stop is a backstop past its allowance and two
3333
+ # graces. A pass the driver stopped gets its interruption written to its worktree's ledger
3334
+ # through deadline.sh, the way the pass script writes its own, and a synthesized result, since
3335
+ # the host wrote none: the outcome interrupted and the deadline's report. A pass refused
3336
+ # because a live process holds its issue gets a result that says locked. The pass's own exit
3337
+ # is returned, 124 for a stop.
3338
+ run_pass() {
3339
+ local report="$SHIFT_DIR/deadline-$pass.json" code limit="$PASS_ALLOWANCE" facts
3340
+ [[ "$ENGINE" != script ]] || limit=$(( PASS_ALLOWANCE + 2 * GRACE + 30 ))
3341
+ if [[ -n "$PASS_ISSUE" ]]; then
3342
+ deadline_run --active ledger active "$REPO_ROOT" "$PASS_ISSUE" -- "$limit" "$GRACE" "$report" ledger hold "$REPO_ROOT" "$PASS_ISSUE" run_engine
3343
+ else
3344
+ deadline_run "$limit" "$GRACE" "$report" run_engine
3345
+ fi
3346
+ code=$?
3347
+ # A pass refused because a live process holds its issue is locked, the answer a pass that
3348
+ # finds its issue taken has always given, and not a failure.
3349
+ if [[ "$code" -eq 75 && -n "$PASS_ISSUE" && ! -s "$result" ]]; then
3350
+ synthesize_result locked "A live pass holds #$PASS_ISSUE ($(ledger active "$REPO_ROOT" "$PASS_ISSUE" 2>/dev/null || echo 'which has since ended')), so this pass touched nothing." null
3351
+ return 0
3352
+ fi
3353
+ [[ "$code" -eq 124 ]] || return "$code"
3354
+ # An interrupt reaches the pass script too, which records its own interruption and prints its
3355
+ # block, so the driver writes nothing over either.
3356
+ if [[ -n "$DEADLINE_INTERRUPT" && "$ENGINE" == script ]] && jq -e '.outcome | type == "string"' "$result" > /dev/null 2>&1; then
3357
+ return "$code"
3358
+ fi
3359
+ # A ledger that refuses the interruption still gets the result, and its reason says so, the
3360
+ # same as the pass script's own. The worktree is looked up from the repository root the
3361
+ # driver runs in, so the deadline names it the way the driver always has.
3362
+ local reason deadline branch pr
3363
+ facts="$(deadline_interrupted "$report" "$PASS_CONSUMED" "$TIMEOUT" . "${PASS_ISSUE:-}" by the driver)"
3364
+ IFS=$'\x1f' read -r reason deadline branch pr \
3365
+ < <(jq -r '[.reason, (.deadline | tojson), .branch, .pr] | join("\u001f")' <<< "$facts")
3366
+ synthesize_result interrupted "$reason" "$deadline" "$branch" "$pr"
3367
+ return "$code"
3368
+ }
3369
+
3370
+ # synthesize_result <outcome> <reason> <deadline-json> [branch pr]: the result a pass that
3371
+ # wrote none leaves, in the engine's shape, so the readers of a pass's result read it the way
3372
+ # they read any other: the pass script's block, or a host result whose structured output is
3373
+ # the block. The branch and the PR are the ones given, or else come off the worktree's ledger
3374
+ # when there is one.
3375
+ synthesize_result() {
3376
+ local outcome="$1" reason="$2" deadline="$3" wt branch="${4:-none}" pr="${5:-none}" doc
3377
+ if [[ $# -lt 5 && -n "$PASS_ISSUE" ]] && wt="$(worktree_for "$PASS_ISSUE" 2>/dev/null)" && [[ -n "$wt" ]]; then
3378
+ doc="$(ledger read "$wt")"
3379
+ branch="$(jq -r '.header.branch // "none"' <<< "$doc")"
3380
+ pr="$(jq -r '.pr // "none"' <<< "$doc")"
3381
+ fi
3382
+ if [[ "$ENGINE" == script ]]; then
3383
+ result_block "$outcome" "${PASS_ISSUE:-none}" "$branch" "$pr" "$reason" "$(jq -n --arg profile "$PROFILE" \
3384
+ --arg host "$RUNNER_HOST" --arg billing "$RUNNER_BILLING" --arg effort "$EFFORT" --argjson deadline "$deadline" \
3385
+ '{profile: $profile, host: $host, billing: $billing, effort: $effort, deadline: $deadline}')" > "$result"
3386
+ else
3387
+ jq -n --arg o "$outcome" --arg i "${PASS_ISSUE:-none}" --arg b "$branch" --arg p "$pr" --arg r "$reason" \
3388
+ --arg profile "$PROFILE" --arg host "$RUNNER_HOST" --arg billing "$RUNNER_BILLING" --arg effort "$EFFORT" --argjson deadline "$deadline" \
3389
+ '{type: "result", subtype: (if $deadline == null then "refused" else "deadline" end), is_error: false,
3390
+ profile: $profile, host: $host, billing: $billing, effort: $effort, cost_usd: null, usage: null, session_id: "none",
3391
+ result: $r, structured_output: {outcome: $o, issue: $i, branch: $b, pr: $p, reason: $r}}
3392
+ + (if $deadline == null then {} else {deadline: $deadline} end)' > "$result"
3393
+ fi
3394
+ }
3395
+
3396
+ # pass_watch <done-file> <ledger.sh> <issue> <worktree> <size>: the spinner's command, run in
3397
+ # a bash of its own. It returns when the pass has ended, which its done file says, or when its
3398
+ # ledger has grown: a worktree for the issue where there was none, looked up every five
3399
+ # seconds, or a run.md longer than <size> bytes.
3400
+ # shellcheck disable=SC2329 # run by name in the spinner's bash
3401
+ pass_watch() {
3402
+ local done="$1" ledger_sh="$2" issue="$3" wt="$4" size="$5" next=0 run
3403
+ while [[ ! -e "$done" ]]; do
3404
+ if [[ -z "$wt" && -n "$issue" && "$SECONDS" -ge "$next" ]]; then
3405
+ bash "$ledger_sh" worktree . "$issue" > /dev/null 2>&1 && return 0
3406
+ next=$(( SECONDS + 5 ))
3407
+ fi
3408
+ if [[ -n "$wt" ]]; then
3409
+ # This runs in the spinner's own bash, so the module's rule for the ledger directory is sourced here.
3410
+ # shellcheck source=/dev/null
3411
+ declare -F _ledger_d > /dev/null || source "$ledger_sh"
3412
+ _ledger_d "$wt" run
3413
+ (( $(wc -c < "$run/run.md" 2>/dev/null || echo 0) <= size )) || return 0
3414
+ fi
3415
+ sleep 1
3416
+ done
3417
+ return 0
3418
+ }
3419
+
3420
+ # print_events <worktree>: the ledger's events past the EVENTS_SHOWN already on screen, one
3421
+ # line each, each one counted into EVENTS_SHOWN.
3422
+ print_events() {
3423
+ local events stage outcome evidence
3424
+ events="$(ledger_text "$1" | jq -r --argjson from "$EVENTS_SHOWN" \
3425
+ '.events[$from:][] | "\(.stage)\u001f\(.outcome)\u001f\(.evidence // "")"')" || return 0
3426
+ [[ -n "$events" ]] || return 0
3427
+ # Read on descriptor 3, so nothing in the loop meets the events on its stdin.
3428
+ while IFS=$'\x1f' read -r stage outcome evidence <&3; do
3429
+ EVENTS_SHOWN=$(( EVENTS_SHOWN + 1 ))
3430
+ ui_event "$stage" "$outcome" "$evidence"
3431
+ done 3<<< "$events"
3432
+ }
3433
+
3434
+ # watch_pass <issue>: the pass behind the spinner, or with gum missing behind none, its ledger
3435
+ # events printed under the pass's pill as they land, its exit passed back. The title names the
3436
+ # pass, the issue and the clock the pass started at, and reads starting until the issue has a
3437
+ # worktree. A pass from the column names no issue, so it has no worktree to find and its title
3438
+ # names the label. A worktree there before the pass, a continuation's, prints only what this
3439
+ # pass adds to it.
3440
+ watch_pass() {
3441
+ local issue="$1" done="$SHIFT_DIR/pass-$pass.done" wt="" size pid spun since title run
3442
+ since="$(clock "$PASS_STARTED")"
3443
+ EVENTS_SHOWN=0
3444
+ if [[ -n "$issue" ]]; then
3445
+ wt="$(worktree_for "$issue" 2>/dev/null || true)"
3446
+ [[ -z "$wt" ]] || EVENTS_SHOWN="$(ledger_text "$wt" | jq '.events | length')"
3447
+ fi
3448
+ rm -f "$done"
3449
+ ( run_pass; echo "$?" > "$done" ) &
3450
+ pid=$!
3451
+ export -f pass_watch
3452
+ while :; do
3453
+ # The pass's end is looked for before the read, so whatever it wrote last is read once,
3454
+ # after the loop.
3455
+ [[ ! -e "$done" ]] || break
3456
+ [[ -n "$wt" || -z "$issue" ]] || wt="$(worktree_for "$issue" 2>/dev/null || true)"
3457
+ size=0
3458
+ if [[ -n "$wt" ]]; then
3459
+ _ledger_d "$wt" run
3460
+ size=$(( $(wc -c < "$run/run.md") ))
3461
+ print_events "$wt"
3462
+ fi
3463
+ if [[ -z "$issue" ]]; then title="pass $pass ◦ $LABEL ◦ since $since"
3464
+ elif [[ -z "$wt" ]]; then title="pass $pass ◦ #$issue ◦ starting"
3465
+ else title="pass $pass ◦ #$issue ◦ since $since"; fi
3466
+ # Without gum the same wait runs with no spinner over it.
3467
+ if ui_gum; then
3468
+ ui_spin "$title" bash -c 'pass_watch "$@"' pass_watch "$done" "$LEDGER_SH" "$issue" "$wt" "$size"
3469
+ else
3470
+ bash -c 'pass_watch "$@"' pass_watch "$done" "$LEDGER_SH" "$issue" "$wt" "$size"
3471
+ fi
3472
+ spun=$?
3473
+ [[ "$spun" -ne 130 && -z "${SHIFT_INTERRUPT:-}" ]] || PASS_PID="$pid" interrupted
3474
+ # A spinner that failed for any other reason is not restarted: the pass is waited out
3475
+ # without one, and its row still prints when it ends.
3476
+ [[ "$spun" -eq 0 ]] || break
3477
+ done
3478
+ export -fn pass_watch
3479
+ wait "$pid"
3480
+ # The pass has ended, so its ledger is whole. Whatever landed after the loop's last read,
3481
+ # which is often the pass's last lines written just before it exits, prints now, above the row.
3482
+ [[ -n "$wt" || -z "$issue" ]] || wt="$(worktree_for "$issue" 2>/dev/null || true)"
3483
+ [[ -z "$wt" ]] || print_events "$wt"
3484
+ local code; code="$(cat "$done")"
3485
+ rm -f "$done"
3486
+ return "$code"
3487
+ }
3488
+
3489
+ # interrupted: a spinner that returned 130 was stopped at the keyboard, gum's ctrl+c, which a
3490
+ # plain run gets as SIGINT across its whole process group, or a TERM reached the driver while its
3491
+ # spinner ran. The background pass ignores SIGINT, so it is sent a TERM, which its deadline_run
3492
+ # takes as an interrupt: the pass is stopped with every process under it, because under the script
3493
+ # engine the build fork is a grandchild of the pass, and its ledger records the interruption.
3494
+ # Then the summary is written, as a plain run's stop writes it, and the driver exits 130.
3495
+ interrupted() {
3496
+ if [[ -n "${PASS_PID:-}" ]]; then
3497
+ kill -TERM "$PASS_PID" 2>/dev/null
3498
+ wait "$PASS_PID" 2>/dev/null
3499
+ fi
3500
+ SHIFT_INTERRUPT="${SHIFT_INTERRUPT:-INT}"; interrupt_requested
3501
+ STOP="$(stop_state)"
3502
+ write_summary
3503
+ ui_fail "interrupted pass $pass, log at $(ui_tint dim "$SHIFT_LOG")"
3504
+ exit 130
3505
+ }
3506
+
3507
+ # interrupt_requested: status 0, with the shift's stop set, once an INT or a TERM has asked the
3508
+ # shift to stop.
3509
+ interrupt_requested() {
3510
+ [[ -n "${SHIFT_INTERRUPT:-}" ]] || return 1
3511
+ STOP_KIND=interrupt; stop_reason="interrupted by SIG$SHIFT_INTERRUPT"; exit_code=130
3512
+ }
3513
+
3514
+ # stop_tree <pid>: SIGTERM to every process under pid, deepest first, then to pid itself.
3515
+ stop_tree() {
3516
+ local child
3517
+ for child in $(pgrep -P "$1" 2>/dev/null); do stop_tree "$child"; done
3518
+ kill -TERM "$1" 2>/dev/null
3519
+ }
3520
+
3521
+ # short_pr <url> and short_cost <usd>: a pass row's PR as #N and its cost as dollars to the
3522
+ # cent, so each column keeps its width on a terminal. Anything else prints as it came.
3523
+ short_pr() { if [[ "$1" =~ /pull/([0-9]+)$ ]]; then echo "#${BASH_REMATCH[1]}"; else echo "$1"; fi; }
3524
+ short_cost() { if [[ "$1" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then printf '$%.2f\n' "$1"; else echo "$1"; fi; }
3525
+
3526
+ # pass_line: on an attended run, the line a pass ends on in place of its logfmt line, its mark
3527
+ # from its outcome by ui_outcome, the palette's map: the outcome, the issue, the PR as #N, the
3528
+ # time taken and the cost. A pass that reported no outcome, none, fails, because the driver
3529
+ # counts it as a failure.
3530
+ pass_line() {
3531
+ "ui_$(ui_outcome "$outcome")" "$(ui_tint bold "$outcome") $(ui_val "#${queued:-$issue}"), pr $(short_pr "$pr"), took $(duration "$took_seconds"), cost $(short_cost "$cost")"
3532
+ }
3533
+ # pass_heading: on an attended run, the pill that opens a counted pass (#346), naming its place
3534
+ # in the shift and its issue. n is exact for a fixed queue without --sweeps, and then a static
3535
+ # bar of the passes follows; otherwise n is the cap, MAX x SWEEPS. With --budget given, the
3536
+ # spend so far follows, when the host reports a cost.
3537
+ pass_heading() {
3538
+ local of note="" bar=""
3539
+ if [[ "$HAS_QUEUE" -eq 1 && "$SWEEPS_SET" -eq 0 ]]; then
3540
+ of="${#SWEEP_ORDER[@]}"
3541
+ # The bar's glyphs are the palette's, Nerd Font squares that fit their cells unless the
3542
+ # pills are square.
3543
+ local done left rest
3544
+ done="$(ui_glyph bar-done)"; left="$(ui_glyph bar-left)"
3545
+ printf -v bar '%*s' "$pass" ""; bar="${bar// /$done}"
3546
+ if (( of > pass )); then printf -v rest '%*s' "$(( of - pass ))" ""; bar+="${rest// /$left}"; fi
3547
+ note="$bar"
3548
+ of="OF $of"
3549
+ else
3550
+ of="OF AT MOST $WORST_PASSES"
3551
+ fi
3552
+ if [[ "$BUDGET_SET" -eq 1 && "$RUNNER_HOST" == claude && -n "$SPENT" ]]; then
3553
+ note+="${note:+ }$(short_cost "$SPENT") spent, \$$BUDGET per run"
3554
+ fi
3555
+ ui_section primary "PASS $pass $of${queued:+ #$queued}" "$note"
3556
+ }
3557
+ # SPENT: the shift's cost so far, the sum of every pass's cost the host reported, or empty while
3558
+ # none has.
3559
+ SPENT=""
3560
+ spend() {
3561
+ [[ "$1" =~ ^[0-9]+(\.[0-9]+)?$ ]] || return 0
3562
+ SPENT="$(awk -v a="${SPENT:-0}" -v b="$1" 'BEGIN { printf "%.4f", a + b }')"
3563
+ }
3564
+
3565
+ # ---- the receipt wait ------------------------------------------------------------------
3566
+ #
3567
+ # A model host's receipt runs detached and outlives the session that started it, so a session
3568
+ # can exit while its suite still runs, and that suite's exit may change the answer (playbook
3569
+ # ADR 0009, #155). So the driver judges a pass only once the receipts in its worktree have
3570
+ # closed, bounded by --receipt-wait. An open receipt is the one `ledger.sh read` calls open.
3571
+
3572
+ # open_receipt <worktree>: the log of the first receipt open in the worktree, logs/<name>.log,
3573
+ # or nothing.
3574
+ open_receipt() { ledger read "$1" | jq -r '[.receipts[] | select(.state == "open") | .file] | first // empty'; }
3575
+
3576
+ # await_receipts <worktree> <issue>: waits for every open receipt in the worktree to close, up to
3577
+ # RECEIPT_WAIT seconds in all, through the ledger's own `wait`. On a terminal the wait is a
3578
+ # spinner naming the receipt and the clock it waits until, the way the CI wait shows. Status 0
3579
+ # once none is open, or 1 with RECEIPT_OPEN set to the log still open past the bound.
3580
+ await_receipts() {
3581
+ local wt="$1" issue="$2" log until_at left said=0 spun
3582
+ RECEIPT_OPEN=""
3583
+ until_at=$(( $(date -u +%s) + RECEIPT_WAIT ))
3584
+ while log="$(open_receipt "$wt")" && [[ -n "$log" ]]; do
3585
+ left=$(( until_at - $(date -u +%s) ))
3586
+ if (( left <= 0 )); then RECEIPT_OPEN="$log"; return 1; fi
3587
+ if [[ "$said" -eq 0 ]]; then
3588
+ said=1
3589
+ ui_attended || note "pass $pass: #$issue's session exited with $log open, so the pass is judged once it closes, waiting up to ${RECEIPT_WAIT}s"
3590
+ fi
3591
+ if ui_attended; then
3592
+ # The wait's own status is the receipt's exit, which may be 130, so the spinner's command
3593
+ # always exits 0 and a 130 is the keyboard's alone.
3594
+ ui_spin "receipt $log open ◦ #$issue ◦ waiting until $(clock "$until_at")" \
3595
+ bash -c 'bash "$1" wait "$2" "$3" --wait "$4" > /dev/null 2>&1; exit 0' receipt_wait "$LEDGER_SH" "$wt" "$log" "$left"
3596
+ spun=$?
3597
+ [[ "$spun" -ne 130 ]] || interrupted
3598
+ # A spinner that failed for any other reason leaves this wait to the plain one.
3599
+ [[ "$spun" -eq 0 ]] || ledger wait "$wt" "$log" --wait "$(( until_at - $(date -u +%s) > 0 ? until_at - $(date -u +%s) : 0 ))" > /dev/null 2>&1
3600
+ else
3601
+ ledger wait "$wt" "$log" --wait "$left" > /dev/null 2>&1
3602
+ fi
3603
+ done
3604
+ return 0
3605
+ }
3606
+
3607
+ # receipt_held <issue>: the open receipt that keeps a resumable issue's owned worktree locked, so
3608
+ # no sweep continues it while a writer may still be in it, or nothing.
3609
+ receipt_held() {
3610
+ local wt
3611
+ wt="$(st_get "$1" worktree)"
3612
+ [[ -n "$wt" && -d "$wt" ]] || return 0
3613
+ open_receipt "$wt"
3614
+ }
3615
+
3616
+ # ---- the sweeps -------------------------------------------------------------------------
3617
+ #
3618
+ # One sweep is one snapshot and one traversal of the plan it makes. A later sweep takes a
3619
+ # fresh snapshot, and runs only when the plan has something in it: an owned issue the
3620
+ # supervisor can prove resumable, or a newly eligible one with room under --max. Every pass
3621
+ # is a fresh model session; the only memory between them is on disk.
3622
+
3623
+ SWEEP=0
3624
+ while [[ "$SWEEP" -lt "$SWEEPS" ]]; do
3625
+ SWEEP=$((SWEEP + 1))
3626
+ if [[ "$SWEEP" -gt 1 ]]; then RESNAPSHOT=1; take_snapshot; RESNAPSHOT=0; fi
3627
+ plan_sweep
3628
+ if [[ "${#SWEEP_ORDER[@]}" -eq 0 ]]; then
3629
+ SWEEP=$((SWEEP - 1))
3630
+ STOP_KIND=frontier
3631
+ stop_reason="sweep $SWEEP left nothing resumable and nothing newly eligible$(receipt_locks)$(left_open)"
3632
+ [[ -z "$HELD_BY_MAX" ]] || stop_at_max
3633
+ break
3634
+ fi
3635
+ if [[ "$SWEEP" -gt 1 ]]; then
3636
+ note "sweep $SWEEP: $(jq -r '.run | map("#\(.issue) (\(.why))") | join(", ")' "$SHIFT_DIR/sweep-$SWEEP.json")"
3637
+ [[ -z "$EXCLUDED" ]] || note "sweep $SWEEP excluded: $EXCLUDED"
3638
+ echo
3639
+ fi
3640
+ # The sweep is counted once a pass of it starts, so a stop inside it still names it.
3641
+ SWEPT=$SWEEP
3642
+ slot=0
3643
+ # retry is set when the pass about to run is a rate-limit retry of the one before, so the
3644
+ # continuation baseline, the brief and the ownership read are taken once per pass.
3645
+ retry=0
3646
+ while [[ "$slot" -lt "${#SWEEP_ORDER[@]}" ]]; do
3647
+ if interrupt_requested; then break 2; fi
3648
+ queued="${SWEEP_ORDER[$slot]}"
3649
+ # Under sweeps each planned issue carries its own base; a plain queue's base is the
3650
+ # shift's, moved along by a stacked pass below.
3651
+ [[ "$SWEEPS_SET" -eq 0 ]] || PASS_BASE="${SWEEP_BASE[$slot]}"
3652
+ slot=$((slot + 1))
3653
+ pass=$((pass + 1))
3654
+ result="$SHIFT_DIR/pass-$pass.json"
3655
+ final="$SHIFT_DIR/pass-$pass.final.json"
3656
+ if [[ "$retry" -eq 0 ]]; then
3657
+ # A continuation: the issue is owned and resumable, so the brief is written from the
3658
+ # evidence and the fingerprint before the pass is taken now, because the tracker may
3659
+ # have moved since the last one.
3660
+ continue_brief=""
3661
+ # A pass's allowance is its own: a rate-limit retry below carries what the attempt before
3662
+ # it consumed, and every other pass, a later sweep's continuation included, starts anew.
3663
+ PASS_CONSUMED=0
3664
+ if [[ -n "$queued" && "$(st_get "$queued" state)" == resumable ]]; then
3665
+ owned_wt="$(owned_worktree "$queued")" || owned_wt=""
3666
+ if [[ -z "$owned_wt" && "$(st_get "$queued" stage)" == claim ]]; then
3667
+ # Interrupted before its cut: no worktree to continue in, so the pass claims again,
3668
+ # which finds the claim already made, and cuts, or finds the cut already made.
3669
+ attempt=$(( $(st_get "$queued" attempts) + 1 ))
3670
+ predecessor="$(st_get "$queued" artifact)"
3671
+ elif [[ -z "$owned_wt" ]]; then
3672
+ # The worktree went away between sweeps: nothing to continue in, so the issue is
3673
+ # not this sweep's, and the pass is not spent.
3674
+ st_set "$queued" state no-worktree; st_set "$queued" reason "the owned worktree is gone"
3675
+ pass=$((pass - 1))
3676
+ continue
3677
+ elif unsafe="$(unsafe_continuation "$owned_wt")" && [[ -n "$unsafe" ]]; then
3678
+ # The evidence the continuation would start from cannot be trusted, under either engine.
3679
+ st_set "$queued" state unsafe; st_set "$queued" reason "$unsafe"
3680
+ note "sweep $SWEEP: #$queued is not continued: $unsafe"
3681
+ pass=$((pass - 1))
3682
+ continue
3683
+ else
3684
+ st_set "$queued" fingerprint_before "$(fingerprint_of "$owned_wt" "$(st_get "$queued" pr)" "$queued")"
3685
+ write_brief "$queued" "$pass" "$owned_wt"
3686
+ continue_brief="$CONTINUE_BRIEF"
3687
+ attempt=$(( $(st_get "$queued" attempts) + 1 ))
3688
+ predecessor="$(st_get "$queued" artifact)"
3689
+ fi
3690
+ fi
3691
+ # The worktree for the issue before the pass, for the ownership check after: a tree
3692
+ # that was not there is this pass's, one that was is another pass's. Read once per
3693
+ # pass, so a rate-limit retry inside the pass still sees what the first attempt saw.
3694
+ # A label pass names no issue, and its tree is found off the outcome afterwards.
3695
+ pre_wt=""
3696
+ [[ -z "$queued" ]] || pre_wt="$(worktree_for "$queued" 2>/dev/null || true)"
3697
+ fi
3698
+ # A retry is the same pass, so its heading was drawn before the wait.
3699
+ first_attempt=$(( retry == 0 ))
3700
+ retry=0
3701
+ PASS_ISSUE="$queued"
3702
+ PASS_ALLOWANCE=$(( TIMEOUT - PASS_CONSUMED ))
3703
+ [[ "$PASS_ALLOWANCE" -ge 1 ]] || PASS_ALLOWANCE=1
3704
+ ENGINE="$SHIFT_ENGINE"
3705
+ PASS_WORKFLOW=""
3706
+ if [[ -n "$queued" ]] && workflow_labels_needed; then
3707
+ issue_workflow "$queued"
3708
+ ENGINE="$(workflow_engine "$queued")"
3709
+ PASS_WORKFLOW="$(workflow_logged "$queued")"
3710
+ [[ -z "$PASS_WORKFLOW" || "$first_attempt" -eq 0 ]] || note "pass $pass: $(workflow_said "$queued")"
3711
+ fi
3712
+ pass_cmd "$queued" "$PASS_BASE" "$RESUME" "$final" "$continue_brief"
3713
+ RESUME=0
3714
+
3715
+ attempt_baseline
3716
+ PASS_STARTED="$(date -u +%s)"
3717
+ rm -f "$SHIFT_DIR/deadline-$pass.json"
3718
+ if ui_attended; then
3719
+ [[ "$first_attempt" -eq 0 ]] || pass_heading
3720
+ watch_pass "$queued"
3721
+ else
3722
+ run_pass
3723
+ fi
3724
+ pass_exit=$?
3725
+ [[ -z "$DEADLINE_INTERRUPT" ]] || SHIFT_INTERRUPT="$DEADLINE_INTERRUPT"
3726
+ # The active execution this attempt spent, which a rate-limit retry carries.
3727
+ PASS_ELAPSED="$(jq -r '.elapsed // 0' "$SHIFT_DIR/deadline-$pass.json" 2>/dev/null)"
3728
+ [[ "$PASS_ELAPSED" =~ ^[0-9]+$ ]] || PASS_ELAPSED=0
3729
+ PASS_CONSUMED=$(( PASS_CONSUMED + PASS_ELAPSED ))
3730
+
3731
+ read_pass_result "$result" "$pass_exit"
3732
+ [[ -n "$limit" ]] && outcome="$limit" && block_outcome="$limit"
3733
+ # How the allowance's stop went, when it ran out: the pass script's block says, and so does
3734
+ # the result the driver wrote for a pass it stopped itself.
3735
+ stopped="$(jq -r '.deadline.stopped // ""' "$result" 2>/dev/null)"
3736
+ # The session has exited, but a receipt it started may still be running, and its exit may
3737
+ # change the answer. So the pass is judged once its worktree's receipts close, and past
3738
+ # --receipt-wait it is interrupted with the open receipt named. Only a tree this pass may
3739
+ # own is waited on: one that was there before and is not this shift's is another pass's.
3740
+ # A budget stop ends the shift either way, so it keeps its word.
3741
+ RECEIPT_OPEN=""
3742
+ wait_issue="${queued:-$issue}"
3743
+ if [[ -n "$wait_issue" && "$wait_issue" != none ]]; then
3744
+ wait_wt="$(worktree_for "$wait_issue" 2>/dev/null || true)"
3745
+ if [[ -n "$wait_wt" ]] && { [[ "$wait_wt" != "$pre_wt" ]] || is_owned "$wait_wt"; } \
3746
+ && ! await_receipts "$wait_wt" "$wait_issue" && [[ "$outcome" != budget-stop ]]; then
3747
+ outcome=interrupted; block_outcome=interrupted
3748
+ note "pass $pass: #$wait_issue is interrupted: $RECEIPT_OPEN is still open after the ${RECEIPT_WAIT}s receipt wait"
3749
+ else
3750
+ RECEIPT_OPEN=""
3751
+ fi
3752
+ fi
3753
+
3754
+ # A queued line also names the base, because a stacked shift reads it back to see the chain.
3755
+ base_field=""
3756
+ [[ -n "$queued" ]] && base_field=" base=$PASS_BASE"
3757
+ output_tokens="$(jq -r '.output_tokens // 0' <<< "$usage" 2>/dev/null || echo 0)"
3758
+ ended_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
3759
+ shift_line="$(printf '%s pass=%s outcome=%s issue=%s pr=%s cost=%s session=%s subtype=%s profile=%s host=%s billing=%s effort=%s cost_usd=%s usage=%s output_tokens=%s branch=%s%s sweep=%s' \
3760
+ "$ended_at" "$pass" "$outcome" "$issue" "$pr" "$cost" "$session" "$subtype" "$result_profile" "$result_host" "$billing" "$result_effort" "$cost_usd" "$usage" "$output_tokens" "$branch" "$base_field" "$SWEEP")"
3761
+ # A pass over its repository's test budget ends its line with the numbers, from its record,
3762
+ # as the PR body names them. A pass under it, or with no record, adds nothing.
3763
+ shift_line+="$(volume_field "$result")"
3764
+ # A pass whose label beat --workflow, or that ran under another engine than the shift's,
3765
+ # says so last.
3766
+ [[ -z "$PASS_WORKFLOW" ]] || shift_line+=" workflow=$PASS_WORKFLOW"
3767
+ took_seconds=$(( $(date -u +%s) - PASS_STARTED ))
3768
+ # On a terminal the line goes to shift.log alone, and one mark line with the fields a
3769
+ # person reads takes its place on the screen.
3770
+ spend "$cost"
3771
+ if ui_attended; then
3772
+ printf '%s\n' "$shift_line" >> "$SHIFT_LOG"
3773
+ pass_line
3774
+ else
3775
+ printf '%s\n' "$shift_line" | tee -a "$SHIFT_LOG"
3776
+ fi
3777
+ # The report goes out once the line is down, so the log is never behind the receiver.
3778
+ report_pass
3779
+ # A rate-limited attempt is the same pass waited out and run again, not a pass that ended.
3780
+ [[ "$outcome" == rate-limited ]] || run_shift_stages after-pass
3781
+
3782
+ # The issue this attempt was for: the queued one, or the one the pass reported picking.
3783
+ row_issue="${queued:-$issue}"
3784
+
3785
+ # Ownership, then the typed state. A worktree that appeared during the pass is this
3786
+ # shift's and is stamped in its ledger, the one line the driver ever writes there; one
3787
+ # that was there before is another pass's and is left alone.
3788
+ wt=""; owned=0
3789
+ if [[ "$row_issue" != none && "$outcome" != rate-limited ]]; then
3790
+ wt="$(worktree_for "$row_issue" 2>/dev/null || true)"
3791
+ if [[ -n "$wt" ]]; then
3792
+ if is_owned "$wt"; then owned=1
3793
+ elif [[ "$wt" != "$pre_wt" ]]; then
3794
+ ledger event "$wt" shift owned "shift=$SHIFT_ID pass=$pass"
3795
+ owned=1
3796
+ fi
3797
+ fi
3798
+ fi
3799
+ # The block's own word goes to the classifier, so a host that died without writing one
3800
+ # is told apart from a pass that called itself failed.
3801
+ classify "$row_issue" "$block_outcome" "$pr" "$is_error" "$wt" "$owned" "$stopped" "$closeout_step" "$RECEIPT_OPEN"
3802
+ fp=""
3803
+ if [[ "$CLS_STATE" == resumable ]]; then
3804
+ fp="$(fingerprint_of "$wt" "$pr" "$row_issue")"
3805
+ if [[ -n "$continue_brief" && "$fp" == "$(st_get "$row_issue" fingerprint_before)" ]]; then
3806
+ CLS_STATE=stalled
3807
+ CLS_REASON="no progress since the attempt before: fingerprint unchanged at $fp"
3808
+ note "pass $pass: #$row_issue is stalled, its fingerprint did not change, so it is not continued again this shift"
3809
+ fi
3810
+ fi
3811
+ if [[ "$row_issue" != none ]]; then
3812
+ admitted "$row_issue" || [[ "$outcome" == rate-limited ]] || ADMITTED+=("$row_issue")
3813
+ st_set "$row_issue" state "$CLS_STATE"
3814
+ st_set "$row_issue" stage "$CLS_STAGE"
3815
+ st_set "$row_issue" reason "$CLS_REASON"
3816
+ st_set "$row_issue" disposition "$CLS_DISPOSITION"
3817
+ st_set "$row_issue" worktree "$wt"
3818
+ # A host that died wrote no block, so the branch and the PR come off the ledger.
3819
+ if [[ -n "$wt" ]]; then
3820
+ [[ -n "$branch" && "$branch" != none ]] || branch="$(ledger_text "$wt" | jq -r '.header.branch // ""')"
3821
+ [[ -n "$pr" && "$pr" != none ]] || pr="$(ledger read "$wt" | jq -r '.pr // ""')"
3822
+ fi
3823
+ st_set "$row_issue" pr "${pr:-none}"
3824
+ st_set "$row_issue" branch "${branch:-none}"
3825
+ st_set "$row_issue" fingerprint "$fp"
3826
+ st_set "$row_issue" last_pass "$pass"
3827
+ st_set "$row_issue" artifact "$result"
3828
+ [[ -z "$queued" ]] || st_set "$row_issue" base "$PASS_BASE"
3829
+ [[ "$outcome" == rate-limited ]] || st_set "$row_issue" attempts "$attempt"
3830
+ fi
3831
+
3832
+ add_pass_meta "$result" "$pass" "$row_issue" "$attempt" "$predecessor" "$CLS_STATE" "$CLS_STAGE"
3833
+ artifact="$result"
3834
+ [[ "$outcome" != "rate-limited" ]] || artifact="$SHIFT_DIR/ratelimit-$pass-$((waits + 1)).json"
3835
+ add_row "$pass" "$row_issue" "$outcome" "$pr" "$branch" "$artifact" "$attempt" "$CLS_STATE" "$closeout_step" \
3836
+ "$(row_metrics "$row_issue" "$branch" "$result" "$took_seconds" "$cost")"
3837
+
3838
+ if interrupt_requested; then break 2; fi
3839
+
3840
+ if [[ "$outcome" == "rate-limited" ]]; then
3841
+ waits=$((waits + 1))
3842
+ mv "$result" "$SHIFT_DIR/ratelimit-$pass-$waits.json"
3843
+ [[ "$limit_result" == "$result" ]] && limit_result="$SHIFT_DIR/ratelimit-$pass-$waits.json"
3844
+ # The retry writes report-<n>.json again, so the waited-out attempt's body moves under its
3845
+ # wait the way its result does, and the receiver's one row per pass is unaffected.
3846
+ [[ ! -f "$SHIFT_DIR/report-$pass.json" ]] || mv "$SHIFT_DIR/report-$pass.json" "$SHIFT_DIR/report-$pass-$waits.json"
3847
+ if [[ "$waits" -gt "$MAX_WAITS" ]]; then
3848
+ STOP_KIND=rate
3849
+ stop_reason="still rate limited after $MAX_WAITS waits"
3850
+ exit_code=2
3851
+ break 2
3852
+ fi
3853
+ wait_until "$(result_reset "$limit_result")"
3854
+ if interrupt_requested; then break 2; fi
3855
+ # The retry is the same pass, not the next one, and its saved result will say which
3856
+ # attempt it is and where the waited-out one went.
3857
+ attempt=$((attempt + 1))
3858
+ predecessor="$SHIFT_DIR/ratelimit-$pass-$waits.json"
3859
+ pass=$((pass - 1))
3860
+ slot=$((slot - 1))
3861
+ retry=1
3862
+ [[ "$ENGINE" == script ]] && RESUME=1
3863
+ if [[ "$ENGINE" == ship-it ]] && runner_session_resume_supported; then RESUME=1; RESUME_SESSION="$session"; fi
3864
+ continue
3865
+ fi
3866
+
3867
+ attempt=1
3868
+ predecessor=""
3869
+
3870
+ if [[ "$outcome" == "budget-stop" ]]; then
3871
+ STOP_KIND=budget
3872
+ stop_reason="a run hit its \$$BUDGET budget cap"
3873
+ break 2
3874
+ fi
3875
+
3876
+ failed=0
3877
+ [[ "$outcome" == "failed" ]] && failed=1
3878
+ [[ "$is_error" == "true" ]] && failed=1
3879
+ [[ "$pass_exit" -ne 0 ]] && failed=1
3880
+ [[ "$outcome" == "none" ]] && failed=1
3881
+ [[ "$outcome" == "interrupted" ]] && failed=1
3882
+ if [[ "$failed" -eq 1 ]]; then
3883
+ streak=$((streak + 1))
3884
+ failed_runs=$((failed_runs + 1))
3885
+ else
3886
+ streak=0
3887
+ fi
3888
+
3889
+ if [[ "$streak" -ge 2 ]]; then
3890
+ STOP_KIND=streak
3891
+ stop_reason="two failed runs in a row"
3892
+ exit_code=1
3893
+ break 2
3894
+ fi
3895
+
3896
+ # Without a queue an empty column ends the shift. With one, the issue was named, so an
3897
+ # empty answer is that issue's alone (locked, or already taken) and the next one is tried.
3898
+ if [[ "$outcome" == "nothing-to-take" && "$HAS_QUEUE" -eq 0 ]]; then
3899
+ STOP_KIND=column
3900
+ stop_reason="the ready column is empty"
3901
+ break 2
3902
+ fi
3903
+
3904
+ # A stacked queue needs a branch to build on. A pass that parked with its PR open leaves
3905
+ # one, and the next pass bases there. A shipped pass merged its branch into the base it was
3906
+ # given and then deleted it, so the base stays where it was. An issue that could not be
3907
+ # taken, or that the pass script found locked, is a link the chain was ordered around, so
3908
+ # skipping it would build the next pass on a base that lacks it. Anything else left no
3909
+ # branch to stack on, and going on would base the next pass on a guess. A stacked sweep
3910
+ # has none of this: its chain follows the blockers, and a missing link keeps the
3911
+ # dependent blocked rather than ending the shift.
3912
+ if [[ "$STACK" -eq 1 && "$STACKED_SWEEPS" -eq 0 ]]; then
3913
+ if [[ "$outcome" == "shipped" ]]; then
3914
+ :
3915
+ elif [[ "$outcome" == "parked" && "$pr" != "none" && -n "$pr" && "$branch" != "none" && -n "$branch" ]]; then
3916
+ PASS_BASE="$branch"
3917
+ elif [[ "$outcome" == "nothing-to-take" || "$outcome" == "locked" ]]; then
3918
+ STOP_KIND=stack
3919
+ stop_reason="pass $pass on #${queued} came back $outcome, so the stack is missing a link"
3920
+ exit_code=1
3921
+ break 2
3922
+ else
3923
+ STOP_KIND=stack
3924
+ stop_reason="pass $pass on #${queued} ${outcome} without a PR, so the stack has no branch to build on"
3925
+ exit_code=1
3926
+ break 2
3927
+ fi
3928
+ fi
3929
+ done
3930
+
3931
+ # The sweep ran to its end. A queue's end is the stop unless a later sweep is allowed, in
3932
+ # which case the next snapshot decides. The wording keeps the max as the reason when the
3933
+ # cap held issues back, because that is what a person reading the last line needs to know.
3934
+ if [[ "$HAS_QUEUE" -eq 1 ]]; then
3935
+ STOP_KIND=queue
3936
+ stop_reason="the queue is done"
3937
+ [[ -z "$HELD_BY_MAX" ]] || stop_at_max
3938
+ fi
3939
+ done
3940
+ ENGINE="$SHIFT_ENGINE"
3941
+
3942
+ # After the last sweep the remaining work names the stop. Work still resumable under the
3943
+ # sweep cap is the cap's limit; work that stopped moving is stalled; a cap on distinct
3944
+ # issues is the max; otherwise the rows decide.
3945
+ if [[ "$exit_code" -eq 0 && "$HAS_QUEUE" -eq 1 && "$STOP_KIND" != budget ]]; then
3946
+ resumable_left="$(jq -r 'to_entries | map(select(.value.state == "resumable") | .key) | join(" ")' <<< "$ISSUE_STATE")"
3947
+ stalled_left="$(jq -r 'to_entries | map(select(.value.state == "stalled") | .key) | join(" ")' <<< "$ISSUE_STATE")"
3948
+ # A stacked sweep that ran out of sweeps may have left a dependent the next snapshot would
3949
+ # admit: its blockers read merge-ready now. That is the cap's limit too, and the evidence
3950
+ # is re-read once so the reason and the summary say so rather than call the frontier empty.
3951
+ admissible=""
3952
+ if [[ "$STACKED_SWEEPS" -eq 1 && "$SWEPT" -ge "$SWEEPS" ]]; then stack_evaluate; admissible="$(stack_admissible)"; fi
3953
+ # A frontier stop leaves resumable work only when an open receipt held it, and the stop line
3954
+ # already says so, so the sweep cap is not the reason.
3955
+ if [[ -n "$resumable_left" && "$SWEEPS_SET" -eq 1 && "$STOP_KIND" != frontier ]]; then
3956
+ STOP_KIND=sweeps
3957
+ stop_reason="reached the sweep cap of $SWEEPS with #${resumable_left// / #} still resumable"
3958
+ elif [[ -n "$admissible" ]]; then
3959
+ STOP_KIND=sweeps
3960
+ stop_reason="reached the sweep cap of $SWEEPS with $admissible"
3961
+ elif [[ "$STOP_KIND" == max ]]; then
3962
+ :
3963
+ elif [[ -n "$stalled_left" ]]; then
3964
+ STOP_KIND=stalled
3965
+ stop_reason="stalled: #${stalled_left// / #} made no progress on a continuation, and nothing else is left to continue or admit"
3966
+ fi
3967
+ fi
3968
+
3969
+ if [[ "$exit_code" -eq 0 && "$pass" -gt 0 && "$failed_runs" -eq "$pass" ]]; then
3970
+ STOP_KIND=failed
3971
+ stop_reason="every attempted pass failed"
3972
+ exit_code=1
3973
+ fi
3974
+
3975
+ [[ "$pass" -eq 0 ]] || run_shift_stages end
3976
+ close_shift
3977
+ exit "$exit_code"