@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,2146 @@
1
+ #!/usr/bin/env bash
2
+ # ledger.sh: the evidence module for one worktree: the ledger at .kryso/pass/run.md, the checkpoint
3
+ # at .kryso/pass/checkpoint.json and the receipts under .kryso/pass/logs/. One file with two forms.
4
+ # Sourced, it defines the function `ledger` and its `_ledger_*` helpers and nothing else: no
5
+ # output, no exit, no changed options, and one stat process to pick the stat flavour, so the
6
+ # driver, the pass script and the status tool source it under their own options. Run,
7
+ # `bash ledger.sh <verb> <worktree> ...` is that same function, because the build fork is a
8
+ # model context that runs one Bash command per event. ADR 0005 says
9
+ # why it lives beside ship-it and why a model runs it by path.
10
+ #
11
+ # Verbs, each taking the worktree first:
12
+ # open <wt> key=value... the header, once; makes logs/, excludes .kryso/pass/,
13
+ # copies this file to <wt>/.kryso/pass/ledger.sh
14
+ # event <wt> <stage> <outcome> <evidence...> one line appended, the time from the clock; a
15
+ # `gate passed` line naming a receipt that did not
16
+ # end exit=0 is refused, unless a green receipt
17
+ # superseded it
18
+ # receipt <wt> <name> <command> [--wait <s>] runs the command in the worktree to logs/<name>.log,
19
+ # or <name>-2.log when one exists; returns its exit;
20
+ # waits while another worktree of the repo runs one.
21
+ # --wait runs it in a detached child and waits up to
22
+ # <s> seconds, then prints `running <log>`, status 76
23
+ # wait <wt> <log> [--wait <s>] waits on a receipt again: its exit, 76 past the
24
+ # bound, or `<log> abandoned` and 75
25
+ # ci <wt> <pr> [--wait <s>] waits on the PR's checks over HEAD, up to <s> (540)
26
+ # and the repo's ci_wait bound: green or none 0, red 1,
27
+ # pending 76, timeout 77, moved 78, one ledger line
28
+ # checkpoint <wt> <stage> <status> [detail] checkpoint.json rewritten, then its ledger line
29
+ # park <wt> <stage> <word> [evidence...] the checkpoint (parked), then the park line;
30
+ # prints the disposition; 75 and nothing written
31
+ # while one of the worktree's receipts or its CI wait
32
+ # is open
33
+ # interrupt <wt> <consumed> <allowance> <stopped> [evidence...]
34
+ # a deadline: the checkpoint (interrupted) at the
35
+ # stage the pass reached, then its ledger line
36
+ # triage <wt> <review> <diff> the review's triage table against its findings and
37
+ # its quotes against the saved diff; a void axis
38
+ # printed as `<axis> (<why>)`, a failed check refused
39
+ # with the pass script's reason
40
+ # read <wt> everything known about the worktree, one JSON document, its
41
+ # ledger directory as dir: .kryso/pass, or the old
42
+ # .kryso or .ship-it
43
+ # text <wt> what the ledger file alone says, as read says it: the
44
+ # header, engine, events, last, owner, park, handoff,
45
+ # progress and interruption, from one jq and no git,
46
+ # lock or receipt probe
47
+ # worktree <repo> <issue> the worktree under .claude/worktrees whose ledger
48
+ # names the issue; status 1 when none
49
+ # worktrees <repo> every ledgered worktree of the repo, "<path> <issue>",
50
+ # nothing when none, status 0 either way
51
+ # hold <repo> <issue> <command...> runs the command holding the issue's authority;
52
+ # 75 when a live pass already holds it
53
+ # drop <repo> <issue> removes the issue's pass lock file while it holds
54
+ # its lock; 75 when a live pass holds it, 3 when it
55
+ # cannot take the lock
56
+ # active <repo> <issue> the live holder of the issue's authority; status 1
57
+ # when nobody holds it, 3 when it cannot be read
58
+ # inherited <repo> <issue> status 0 when the caller runs under a live holder of
59
+ # the issue's authority, 1 when it does not
60
+ # handoff <wt> <engine> <shift> [key=value...]
61
+ # one `shift handoff` line: the stage it resumes at,
62
+ # from and to as engine/shift, the reconciliations
63
+ # used, the forks and the allowance consumed, then the
64
+ # caller's keys; refreshes the worktree's module copy
65
+ # authorized <wt> <engine> [shift] status 0 when that engine in that shift may continue
66
+ # the worktree, else 1 and why on one line
67
+ # attempt <wt> <evidence...> one `reconcile attempt <n>/3` line, <n> printed;
68
+ # status 1 and nothing written once three are used
69
+ # archive <wt> [repo] a copy of .kryso/pass/ that outlives the worktree, at
70
+ # .claude/kryso/shipped/<name>-<time>/ in the
71
+ # repo, the main checkout unless named; the copy's
72
+ # directory printed
73
+ # lock <path> <fd> sourced only: holds the file's kernel lock on the fd
74
+ # for this shell and everything it starts; 75 when held
75
+ # locked <path> status 0 while a live process holds the file's lock,
76
+ # 1 when none does, 3 when it cannot be read
77
+ #
78
+ # The authority is a kernel lock on <git-common-dir>/ship-it-pass-<issue>.lock, taken on a
79
+ # descriptor the command and everything it starts inherit, so it is free only when the last
80
+ # process of the pass's tree has exited. That is how a deadline confirms a stopped pass, and why
81
+ # a continuation that finds it held refuses to start: the pass before it is still running. A
82
+ # driver holds its shift the same way, through `lock`, so a later shift can confirm it stopped.
83
+ #
84
+ # Ownership is the last `shift owned` or `shift handoff` line. A handoff moves a worktree to
85
+ # another shift, under either engine, without touching the header: `authorized` is the rule both
86
+ # engines apply before continuing a ledger, and `read` returns the owner, the last handoff and
87
+ # the reconciliations used, the higher of the `reconcile attempt` lines and the script engine's
88
+ # checkpoint count, never reset. It also returns `progress`, the last event that is not
89
+ # bookkeeping, its counters and log numbers masked and a park cut to its word, URLs and
90
+ # evidence digests, which is what a driver's progress fingerprint reads.
91
+ #
92
+ # The grammar on disk is frozen: the reader takes every ledger written before this file existed,
93
+ # hyphen forms and a missing engine line included, and the writer produces the canonical form.
94
+ # The writer checks shape, never vocabulary: the reader owns the words. The one exception is a
95
+ # `gate passed` line that names a red receipt, which the writer refuses (ADR 0057). A refusal is one line on
96
+ # stderr, nothing on stdout, status 64. Readers print on stdout and return 0 whether or not they
97
+ # have an answer, so a `set -e` caller can assign. Sourced, an event given no worktree waits in
98
+ # LEDGER_PENDING and follows the next header written. Run, or named for a worktree with no
99
+ # ledger, it is a refusal. LEDGER_PR, LEDGER_FORKS, LEDGER_HEAD and LEDGER_FINGERPRINT, when set by
100
+ # a sourcing caller, fill the checkpoint fields the disk cannot know: the PR, the forks spent, and
101
+ # the pass's head and tree fingerprint when the worktree's are not them, as in an archived copy.
102
+ # LEDGER_REPAIRS and LEDGER_EVIDENCE, when LEDGER_REPAIRS is set, stamp the script engine's own
103
+ # two fields onto the checkpoint in the same write: its reconciliation count, and the
104
+ # failed-check evidence it last repaired against, null when empty.
105
+ # A count that is not JSON stamps neither, and the rest of the checkpoint is still written.
106
+ # Each receipt also appends `<receipt> queued=<s>
107
+ # ran=<s>` to its own worktree's logs/receipt-times.txt, and `read` returns those lines as
108
+ # receipt_times, so a caller can tell the time a receipt waited for the gate lock from the time
109
+ # its command ran.
110
+ #
111
+ # A receipt holds a kernel lock of its own, logs/.<name>.lock, from naming its log to its exit
112
+ # line, and writes `receipt started <log> head=<sha>` before its command runs, so `read` calls
113
+ # each receipt open, abandoned, void or closed, gives the commit it started on, and marks a
114
+ # closed one at the current HEAD reusable. Each start line gets one end line: `receipt closed
115
+ # <log> exit=<n>` once the exit is final, the void line, or, for a receipt whose process died
116
+ # first, `receipt superseded <log> exit=<n|none> by <new log>` from the next receipt of its name,
117
+ # so the ledger alone tells a failed receipt from an abandoned one (#426). Once it holds the
118
+ # gate lock it checks the worktree is on the ledger's branch, and at its exit that HEAD has not
119
+ # moved; either mismatch is a `receipt void` line and exit 78, never a pass or a fail. Only
120
+ # --wait detaches the receipt:
121
+ # without it the command stays in the caller's process tree and group, which is how the script
122
+ # engine's deadline stops it with the pass (ADR 0050). No jq call here reads the caller's stdin, so a reader
123
+ # never waits on the caller's input.
124
+ # Needs bash, jq and git.
125
+
126
+ # ---- helpers -----------------------------------------------------------------------------
127
+
128
+ _ledger_run() { [[ "${BASH_SOURCE[0]}" == "$0" ]]; }
129
+ # _ledger_refuse <message>: a refusal, status 64. Run as a command on an attended stderr, it is
130
+ # drawn under an ERROR pill with the help as its hint, through ui.sh beside this file; sourced, or
131
+ # on any other stderr, it is the one prefixed line a caller reads.
132
+ _ledger_refuse() {
133
+ if _ledger_run && declare -F ui_err_attended > /dev/null && ui_err_attended; then
134
+ ui_error "$1" "kryso ledger --help lists the verbs"
135
+ else
136
+ echo "ledger: $1" >&2
137
+ fi
138
+ return 64
139
+ }
140
+ # _ledger_clock: the UTC time an event line carries, and _ledger_epoch: epoch seconds. Bash 5
141
+ # reads the clock in the shell through printf's %(...)T, with TZ set for that one builtin, so a
142
+ # pass that writes hundreds of lines starts no date process for them. Older bash asks date, in
143
+ # the same format: 3.2 has no %(...)T, and 4 is not checked here for a TZ set on one builtin.
144
+ if [[ "${BASH_VERSINFO[0]}" -ge 5 ]]; then
145
+ _ledger_clock() { TZ=UTC0 printf '%(%Y-%m-%dT%H:%M:%SZ)T\n' -1; }
146
+ _ledger_epoch() { printf '%(%s)T\n' -1; }
147
+ else
148
+ _ledger_clock() { date -u +%FT%TZ; }
149
+ _ledger_epoch() { date -u +%s; }
150
+ fi
151
+ _ledger_now() { if [[ -n "${_LEDGER_AT:-}" ]]; then printf '%s\n' "$_LEDGER_AT"; else _ledger_clock; fi; }
152
+ # _ledger_digest: the sha256 of stdin, 64 hex characters. coreutils' sha256sum comes first
153
+ # because shasum is a Perl script whose start costs more than the hash, and a read takes two.
154
+ # ship-pass.sh calls it for its own digests too, so the choice of tool has one home.
155
+ _ledger_digest() {
156
+ local d
157
+ if command -v sha256sum >/dev/null 2>&1; then d="$(sha256sum)"; else d="$(shasum -a 256)"; fi
158
+ printf '%s\n' "${d:0:64}"
159
+ }
160
+ # _ledger_stat_pick: BSD stat (macOS) takes -f %m and GNU's -c %Y. The first call in a shell
161
+ # asks which this host has and redefines the two mtime helpers for it, so later calls in that
162
+ # shell ask nothing. A choice made inside a command substitution ends with it, so a read asks
163
+ # before its loop: once per read rather than once per log. A shell that sources the module asks
164
+ # once when it does, at the foot of this file, and its reads inherit the answer.
165
+ _ledger_stat_pick() {
166
+ if stat -f %m / >/dev/null 2>&1; then
167
+ _ledger_file_mtime() { stat -f %m "$1" 2>/dev/null; }
168
+ _ledger_files_mtime() { stat -f %m "$@" 2>/dev/null; }
169
+ _ledger_mtime() { find "$1" -type f -exec stat -f %m {} + 2>/dev/null | _ledger_newest; }
170
+ _ledger_inodes() { stat -L -f %i "$@" 2>/dev/null; }
171
+ else
172
+ _ledger_file_mtime() { stat -c %Y "$1" 2>/dev/null; }
173
+ _ledger_files_mtime() { stat -c %Y "$@" 2>/dev/null; }
174
+ _ledger_mtime() { find "$1" -type f -exec stat -c %Y {} + 2>/dev/null | _ledger_newest; }
175
+ _ledger_inodes() { stat -L -c %i "$@" 2>/dev/null; }
176
+ fi
177
+ _ledger_stat_pick() { :; }
178
+ }
179
+ # _ledger_newest: the largest of the numbers on stdin, one per line, or nothing when there are none.
180
+ _ledger_newest() { local n m=""; while IFS= read -r n; do [[ -n "$m" && "$n" -le "$m" ]] || m="$n"; done; [[ -z "$m" ]] || printf '%s\n' "$m"; }
181
+ # _ledger_mtime <dir>: the newest mtime of a file under the directory, epoch seconds, or nothing.
182
+ _ledger_mtime() { _ledger_stat_pick; _ledger_mtime "$@"; }
183
+ # _ledger_file_mtime <file>: the file's mtime, epoch seconds, from BSD or GNU stat.
184
+ _ledger_file_mtime() { _ledger_stat_pick; _ledger_file_mtime "$@"; }
185
+ # _ledger_files_mtime <file...>: one mtime per file, a line each, from one stat. A file stat
186
+ # cannot read prints no line, so a caller counts the lines before it trusts their order.
187
+ _ledger_files_mtime() { _ledger_stat_pick; _ledger_files_mtime "$@"; }
188
+ # _ledger_inodes <path...>: one inode number per path, a line each, from one stat, links followed.
189
+ _ledger_inodes() { _ledger_stat_pick; _ledger_inodes "$@"; }
190
+ # _ledger_names <fd> <path>: status 0 when the path still names the file open on the descriptor,
191
+ # 1 when it names another file or none, and 2 when the descriptor's file cannot be read, as on a
192
+ # host with no /dev/fd. The inode alone decides, because /dev/fd is a device of its own on macOS,
193
+ # and the open descriptor keeps its file's inode from being reused while the two are compared.
194
+ _ledger_names() {
195
+ local n
196
+ _ledger_stat_pick
197
+ n="$(_ledger_inodes "/dev/fd/$1")" && [[ -n "$n" ]] || return 2
198
+ [[ "$(_ledger_inodes "$2")" == "$n" ]]
199
+ }
200
+ # _ledger_last_lines <file...>: the last line of each file, as `tail -1` prints it, into the
201
+ # array _ledger_lines, which the caller declares local, one element per file and "" for an
202
+ # empty or unreadable one, from one awk. awk skips an empty file, so only non-empty ones go to
203
+ # it, and a file that went away between the check and the read leaves too few lines, which
204
+ # sends every file to tail on its own instead. The trailing dot keeps an empty last line.
205
+ _ledger_last_lines() {
206
+ local _ll_f _ll_i=0 _ll_n=0 _ll_out _ll_line
207
+ local -a _ll_read=() _ll_idx=() _ll_got=()
208
+ _ledger_lines=()
209
+ for _ll_f in "$@"; do
210
+ if [[ -s "$_ll_f" && -r "$_ll_f" ]]; then _ll_read+=("$_ll_f"); _ll_idx+=("$_ll_i"); fi
211
+ _ledger_lines[_ll_i]=""; _ll_i=$((_ll_i + 1))
212
+ done
213
+ [[ "${#_ll_read[@]}" -gt 0 ]] || return 0
214
+ if _ll_out="$(awk 'FNR == 1 && NR > 1 { print last } { last = $0 } END { if (NR > 0) print last; print "." }' "${_ll_read[@]}" 2>/dev/null)"; then
215
+ while IFS= read -r _ll_line; do _ll_got+=("$_ll_line"); done <<< "$_ll_out"
216
+ fi
217
+ _ll_n="${#_ll_got[@]}"
218
+ if [[ "$_ll_n" -eq $(( ${#_ll_read[@]} + 1 )) ]]; then
219
+ for ((_ll_i = 0; _ll_i < ${#_ll_read[@]}; _ll_i++)); do _ledger_lines[_ll_idx[_ll_i]]="${_ll_got[_ll_i]}"; done
220
+ else
221
+ for ((_ll_i = 0; _ll_i < ${#_ll_read[@]}; _ll_i++)); do _ledger_lines[_ll_idx[_ll_i]]="$(tail -1 "${_ll_read[_ll_i]}" 2>/dev/null)"; done
222
+ fi
223
+ }
224
+ # _ledger_common_dir <wt>: the repository's common git directory, absolute, or status 1.
225
+ _ledger_common_dir() {
226
+ local c
227
+ if c="$(git -C "$1" rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" && [[ -n "$c" ]]; then printf '%s' "$c"; return 0; fi
228
+ c="$(git -C "$1" rev-parse --git-common-dir 2>/dev/null)" && [[ -n "$c" ]] || return 1
229
+ case "$c" in /*) printf '%s' "$c" ;; *) (cd "$1" && cd "$c" && pwd -P) ;; esac
230
+ }
231
+ # _ledger_gate_lock <wt>: the file every worktree of the repository locks while a receipt runs,
232
+ # so one gate command runs at a time per repository however many passes are open. Status 1
233
+ # outside a repository.
234
+ _ledger_gate_lock() { local c; c="$(_ledger_common_dir "$1")" || return 1; _ledger_gate_lock_in "$c"; }
235
+ # _ledger_gate_lock_in <common-dir>: the same file, for a caller that already has the directory.
236
+ _ledger_gate_lock_in() { printf '%s/ship-it-gate.lock' "$1"; }
237
+ # _ledger_exclude <dir> <pattern>: the pattern on a line of its own in the repository's exclude
238
+ # file, once, so what the module leaves on disk is never committed and no adopting repository
239
+ # edits its .gitignore. Silent and best effort: outside a repository, or with an exclude file
240
+ # that cannot be written, the directory shows as untracked and nothing else goes wrong.
241
+ _ledger_exclude() {
242
+ local c
243
+ c="$(_ledger_common_dir "$1")" || return 0
244
+ { mkdir -p "$c/info" && { grep -qxF "$2" "$c/info/exclude" || echo "$2" >> "$c/info/exclude"; }; } 2>/dev/null || true
245
+ }
246
+ # ---- the names on disk ------------------------------------------------------------------------
247
+ #
248
+ # The rename to KrysoWorks moved three directories: a worktree's ledger from .ship-it/ to .kryso/,
249
+ # a repository's shift state from .claude/ship-loop/ to .claude/kryso/, and the warden's state from
250
+ # .claude/warden/ to .claude/kryso-watch/. A writer migrates on touch. Finding the old directory and
251
+ # not the new one, it renames old to new with one mv, atomic on one filesystem, and leaves a link at
252
+ # the old name pointing to the new, so a path that still names the old directory resolves. A reader
253
+ # takes the new name, else the old, and never renames. The old names are read until 3.0.0.
254
+
255
+ # _ledger_settled <old> <new>: status 0 when there is nothing to move: no old directory, the old
256
+ # name already a link, or the new name already taken. Tests only, so every event line can ask.
257
+ _ledger_settled() { [[ -e "$2" || -L "$2" || -L "$1" || ! -d "$1" ]]; }
258
+ # _ledger_migrate <old> <new> <lock> [pattern...]: old renamed to new, with a link back at old, when
259
+ # old is a directory and nothing is at new. Two writers can find the same old directory at once, so
260
+ # the move runs under the kernel lock on <lock>, through _ledger_lock_fd, and asks again once it
261
+ # holds it: a writer that waited finds the move made and does nothing, rather than moving the link
262
+ # the first left into the new directory. With no lock file named, or no lock tool, it moves unlocked.
263
+ # Each pattern, relative to the repository root, goes in the exclude file before the move, so git
264
+ # never sees the new directory or the link, which a directory pattern such as .ship-it/ does not
265
+ # match. Silent. Status 1 when the move failed and new is still absent.
266
+ _ledger_migrate() {
267
+ local old="$1" new="$2" lock="$3" pattern
268
+ shift 3
269
+ if _ledger_settled "$old" "$new"; then return 0; fi
270
+ for pattern in "$@"; do _ledger_exclude "${old%/*}" "$pattern"; done
271
+ (
272
+ if [[ -n "$lock" ]] && { exec 3>> "$lock"; } 2>/dev/null; then _ledger_lock_fd 3 >/dev/null 2>&1 || true; fi
273
+ if _ledger_settled "$old" "$new"; then exit 0; fi
274
+ if ! mv "$old" "$new" 2>/dev/null; then [[ -d "$new" ]]; exit; fi
275
+ ln -s "${new##*/}" "$old" 2>/dev/null || true
276
+ )
277
+ [[ -d "$new" || ! -d "$old" || -L "$old" ]]
278
+ }
279
+ # _ledger_migrate_wt <wt>: the worktree's .ship-it moved to .kryso, under a lock in the worktree's
280
+ # own git directory, with .kryso/ and the link excluded. The one call every writer of a worktree's
281
+ # ledger makes. Status 1 when the move failed.
282
+ _ledger_migrate_wt() {
283
+ local wt="$1" gd
284
+ if _ledger_settled "$wt/.ship-it" "$wt/.kryso"; then return 0; fi
285
+ gd="$(git -C "$wt" rev-parse --absolute-git-dir 2>/dev/null)" || gd=""
286
+ _ledger_migrate "$wt/.ship-it" "$wt/.kryso" "${gd:+$gd/kryso-migrate.lock}" .kryso/ .ship-it
287
+ }
288
+ # _ledger_migrate_state <repo> <old> <new>: a repository's state directory, such as .claude/ship-loop,
289
+ # moved to its new name, under a lock in the common git directory, with both excluded. Status 1 when
290
+ # the move failed.
291
+ _ledger_migrate_state() {
292
+ local repo="$1" old="$2" new="$3" c
293
+ if _ledger_settled "$repo/$old" "$repo/$new"; then return 0; fi
294
+ c="$(_ledger_common_dir "$repo")" || c=""
295
+ _ledger_migrate "$repo/$old" "$repo/$new" "${c:+$c/kryso-migrate.lock}" "$new/" "$old"
296
+ }
297
+ # _ledger_pick <new> <old> <var>: the directory a reader takes, to the named variable: the new name
298
+ # unless only the old one exists.
299
+ _ledger_pick() { if [[ -e "$1" || ! -e "$2" ]]; then printf -v "$3" '%s' "$1"; else printf -v "$3" '%s' "$2"; fi; }
300
+ # _ledger_d <wt> <var>: the worktree's ledger directory. A pass writes it at .kryso/pass, and only
301
+ # that is excluded from git, so the rest of .kryso/ can hold tracked configuration (#618, ADR 0046).
302
+ # A ledger at the old place, .kryso/run.md with no .kryso/pass beside it, is read and continued
303
+ # where it is, so a pass parked before the move resumes after it. Before the rename it was .ship-it,
304
+ # taken where it is a directory and not the link a move left. Into a variable, with no process started, because every event
305
+ # line asks.
306
+ _ledger_d() {
307
+ if [[ -d "$1/.kryso/pass" ]]; then printf -v "$2" '%s' "$1/.kryso/pass"
308
+ elif [[ -f "$1/.kryso/run.md" ]]; then printf -v "$2" '%s' "$1/.kryso"
309
+ elif [[ -e "$1/.ship-it" && ! -L "$1/.ship-it" ]]; then printf -v "$2" '%s' "$1/.ship-it"
310
+ else printf -v "$2" '%s' "$1/.kryso/pass"; fi
311
+ }
312
+ # _ledger_unexclude_old <wt>: the .kryso/ line a module before #618 put in the repository's exclude
313
+ # file taken out, once no worktree of the repository has a ledger at the old place, because it
314
+ # hides the tracked configuration beside .kryso/pass/. While one has, the line stays, so that
315
+ # ledger never shows as untracked. Silent and best effort, like _ledger_exclude.
316
+ _ledger_unexclude_old() {
317
+ local c tree
318
+ c="$(_ledger_common_dir "$1")" || return 0
319
+ grep -qxF '.kryso/' "$c/info/exclude" 2>/dev/null || return 0
320
+ while IFS= read -r tree; do
321
+ [[ -z "$tree" || -d "$tree/.kryso/pass" || ! -f "$tree/.kryso/run.md" ]] || return 0
322
+ done < <(git -C "$1" worktree list --porcelain 2>/dev/null | sed -n 's/^worktree //p')
323
+ { grep -vxF '.kryso/' "$c/info/exclude" > "$c/info/exclude.tmp"; mv "$c/info/exclude.tmp" "$c/info/exclude"; } 2>/dev/null \
324
+ || rm -f "$c/info/exclude.tmp" 2>/dev/null || true
325
+ }
326
+
327
+ # _ledger_settings <tag>: the settings a person puts in the environment, each read under its KRYSO_
328
+ # name and taken from its old name when only that one is set. One warning line on stderr names every
329
+ # old name set: read as the new one, or ignored because the new one is set too. The new names are
330
+ # exported and the old ones unset, so a driver or pass this one starts says nothing. Each driver
331
+ # calls it once, before it reads a setting.
332
+ _ledger_settings() {
333
+ local pair new old said=""
334
+ for pair in KRYSO_PROFILE_FILE:SHIP_LOOP_PROFILE_FILE KRYSO_CI_MAX_QUEUED:SHIP_LOOP_CI_MAX_QUEUED \
335
+ KRYSO_WAIT_SECONDS:SHIP_LOOP_WAIT_SECONDS KRYSO_REPORT_URL:SHIP_LOOP_REPORT_URL \
336
+ KRYSO_REPORT_TOKEN:SHIP_LOOP_REPORT_TOKEN KRYSO_REPORT_RETRY_SECONDS:SHIP_LOOP_REPORT_RETRY_SECONDS \
337
+ KRYSO_REPAIR_FLOOR:SHIP_PASS_REPAIR_FLOOR; do
338
+ new="${pair%%:*}"; old="${pair#*:}"
339
+ [[ -n "${!old:-}" ]] || continue
340
+ if [[ -n "${!new:-}" ]]; then said+="${said:+, }$old ignored because $new is set"
341
+ else export "$new=${!old}"; said+="${said:+, }$old read as $new"; fi
342
+ unset "$old"
343
+ done
344
+ [[ -z "$said" ]] || echo "${1:-ledger}: warning: old environment names work until 3.0.0: $said" >&2
345
+ }
346
+
347
+ # _ledger_pass_lock <dir> <issue>: the file whose kernel lock is the issue's pass authority.
348
+ _ledger_pass_lock() { local c; c="$(_ledger_common_dir "$1")" || return 1; _ledger_pass_lock_in "$c" "$2"; }
349
+ # _ledger_pass_lock_in <common-dir> <issue>: the same file, for a caller that already has the directory.
350
+ _ledger_pass_lock_in() { printf '%s/ship-it-pass-%s.lock' "$1" "$2"; }
351
+ # _ledger_lock_fd <fd> [try | <seconds>]: an exclusive flock(2) on the open descriptor, through
352
+ # flock where it exists and lockf where it does not (macOS). The kernel drops it when the last
353
+ # process holding the descriptor exits, so a killed pass never leaves a stale lock behind. A try
354
+ # does not wait, and a whole number of seconds waits that long at most. Status 1 means the lock
355
+ # stayed held, 2 means neither tool exists and 3 means the tool failed.
356
+ _ledger_lock_fd() {
357
+ local code wait=0
358
+ [[ ! "${2:-}" =~ ^[0-9]+$ ]] || wait="$2"
359
+ if command -v flock >/dev/null 2>&1; then
360
+ if [[ "$wait" -gt 0 ]]; then flock -w "$wait" "$1" && return 0; code=$?; [[ "$code" -eq 1 ]] && return 1; return 3
361
+ elif [[ -n "${2:-}" ]]; then flock -n "$1" && return 0; code=$?; [[ "$code" -eq 1 ]] && return 1; return 3
362
+ else flock "$1" && return 0; return 3; fi
363
+ elif command -v lockf >/dev/null 2>&1; then
364
+ if [[ -n "${2:-}" ]]; then lockf -s -t "$wait" "$1" && return 0; code=$?; [[ "$code" -eq 75 ]] && return 1; return 3
365
+ else lockf -s "$1" && return 0; return 3; fi
366
+ else return 2; fi
367
+ }
368
+ # _ledger_current_pid <var>: Bash 3.2 keeps $$ unchanged in a subshell, so ask a short-lived
369
+ # child's process record for this shell's real pid and write it to the named variable. Bash 4
370
+ # and later have it as BASHPID, which starts no process.
371
+ _ledger_current_pid() {
372
+ local var="$1" child pid
373
+ if [[ -n "${BASHPID:-}" ]]; then printf -v "$var" '%s' "$BASHPID"; return 0; fi
374
+ sleep 60 & child=$!
375
+ pid="$(ps -o ppid= -p "$child" 2>/dev/null | tr -d '[:space:]')"
376
+ kill "$child" 2>/dev/null || true
377
+ wait "$child" 2>/dev/null || true
378
+ [[ "$pid" =~ ^[0-9]+$ ]] || return 1
379
+ printf -v "$var" '%s' "$pid"
380
+ }
381
+ # _ledger_authority_held <path>: status 0 when another process holds the authority's kernel
382
+ # lock, 1 when nobody does, and 3 when it cannot be checked. Descriptor 7 is only a probe.
383
+ _ledger_authority_held() {
384
+ local got=0
385
+ { exec 7>> "$1"; } 2>/dev/null || return 3
386
+ _ledger_lock_fd 7 try || got=$?
387
+ exec 7>&-
388
+ [[ "$got" -eq 1 ]] && return 0
389
+ [[ "$got" -eq 0 ]] && return 1
390
+ return 3
391
+ }
392
+ # _ledger_nested_gate_lease <lock> <var>: register a nested receipt under the live holder and
393
+ # write its lease path to the named variable. Status 1 means the inherited marker is stale, and
394
+ # 3 means it was live but the lease could not be registered.
395
+ _ledger_nested_gate_lease() {
396
+ local lock="$1" lease_var="$2" token="${KRYSO_GATE_LOCK_TOKEN:-}" parent="${KRYSO_GATE_AUTHORITY:-}"
397
+ local file_token state rest lease_dir nested_pid pending candidate got=0
398
+ [[ "${KRYSO_GATE_LOCK:-}" == "$lock" && -n "$token" && -n "$parent" ]] || return 1
399
+ if [[ -n "${KRYSO_GATE_LEASE:-}" ]]; then
400
+ [[ "$KRYSO_GATE_LEASE" == "$parent" && "$parent" == "$lock.leases/$token/"* && -f "$parent" ]] || return 1
401
+ else
402
+ [[ "$parent" == "$lock.holders/$token" ]] || return 1
403
+ read -r file_token state rest < "$lock" 2>/dev/null || return 1
404
+ [[ "$file_token" == "$token" && "$state" == open ]] || return 1
405
+ fi
406
+ _ledger_authority_held "$parent" || { got=$?; [[ "$got" -eq 1 ]] && return 1; return 3; }
407
+ _ledger_current_pid nested_pid || return 3
408
+ lease_dir="$lock.leases/$token"
409
+ mkdir -p "$lease_dir" || return 3
410
+ pending="$lease_dir/.register-$nested_pid-$RANDOM-$RANDOM"
411
+ candidate="$lease_dir/$nested_pid-$RANDOM-$RANDOM"
412
+ (set -o noclobber; : > "$pending") 2>/dev/null || return 3
413
+ { exec 8>> "$pending"; } 2>/dev/null || { rm -f "$pending"; return 3; }
414
+ _ledger_lock_fd 8 try || got=$?
415
+ if [[ "$got" -ne 0 ]] || ! ln "$pending" "$candidate"; then
416
+ exec 8>&-; rm -f "$pending" "$candidate"; return 3
417
+ fi
418
+ rm -f "$pending"
419
+ if [[ -n "${KRYSO_GATE_LEASE:-}" ]]; then
420
+ [[ -f "$parent" ]] || { exec 8>&-; rm -f "$candidate"; return 1; }
421
+ else
422
+ read -r file_token state rest < "$lock" 2>/dev/null || { exec 8>&-; rm -f "$candidate"; return 1; }
423
+ [[ "$file_token" == "$token" && "$state" == open ]] \
424
+ || { exec 8>&-; rm -f "$candidate"; return 1; }
425
+ fi
426
+ got=0; _ledger_authority_held "$parent" || got=$?
427
+ if [[ "$got" -ne 0 ]]; then
428
+ exec 8>&-
429
+ rm -f "$candidate"
430
+ [[ "$got" -eq 1 ]] && return 1
431
+ return 3
432
+ fi
433
+ printf -v "$lease_var" '%s' "$candidate"
434
+ }
435
+ _ledger_release_gate_authority() {
436
+ local path="${1:-}"
437
+ [[ -n "$path" ]] || return 0
438
+ exec 8>&-
439
+ rm -f "$path"
440
+ rmdir "${path%/*}" 2>/dev/null || true
441
+ }
442
+ # _ledger_wait_gate_leases <lock>: wait for nested receipts whose outer holder ended, and prune
443
+ # lease files left by killed nested processes. A new main holder calls this before its command.
444
+ _ledger_wait_gate_leases() {
445
+ local root="$1.leases" lease live got
446
+ [[ -d "$root" ]] || return 0
447
+ while :; do
448
+ live=0
449
+ for lease in "$root"/*/*; do
450
+ [[ -f "$lease" ]] || continue
451
+ got=0; _ledger_authority_held "$lease" || got=$?
452
+ if [[ "$got" -eq 0 ]]; then live=1
453
+ elif [[ "$got" -eq 1 ]]; then rm -f "$lease"
454
+ else return 3; fi
455
+ done
456
+ [[ "$live" -eq 0 ]] && break
457
+ sleep 0.05
458
+ done
459
+ rmdir "$root"/* 2>/dev/null || true
460
+ rmdir "$root" 2>/dev/null || true
461
+ }
462
+ # _ledger_lock_holder <lock> <at-var> <tag-var> <owner-var>: read a live open holder, waiting
463
+ # briefly through the hand-off after the kernel lock is acquired and before its record is written.
464
+ _ledger_lock_holder() {
465
+ local lock="$1" at_var="$2" tag_var="$3" owner_var="$4" i token state found_at found_tag found_owner
466
+ for ((i = 0; i < 50; i++)); do
467
+ if read -r token state found_at found_tag found_owner < "$lock" 2>/dev/null \
468
+ && [[ "$state" =~ ^(open|closing)$ ]] && _ledger_authority_held "$lock.holders/$token"; then
469
+ printf -v "$at_var" '%s' "$found_at"
470
+ printf -v "$tag_var" '%s' "$found_tag"
471
+ printf -v "$owner_var" '%s' "$found_owner"
472
+ return 0
473
+ fi
474
+ sleep 0.02
475
+ done
476
+ return 1
477
+ }
478
+ # _ledger_next_tag <dir> <name> <ext>: prints the first of <name>, <name>-2, <name>-3 with no
479
+ # <tag><ext> in <dir> yet, so a rerun's log sits beside the run before it rather than over it.
480
+ # The receipts' naming rule, for the logs a caller writes itself: the pass script's records and
481
+ # results, and the second reader's request log. Reads only; nothing is made.
482
+ _ledger_next_tag() {
483
+ local dir="$1" name="$2" ext="$3" n=1 tag="$2"
484
+ while [[ -e "$dir/$tag$ext" ]]; do n=$((n + 1)); tag="$name-$n"; done
485
+ printf '%s' "$tag"
486
+ }
487
+ # _ledger_reserve_receipt <wt> <name> <tag-var> <log-var>: atomically claims the next receipt
488
+ # name, so even unlocked fallback mode cannot let two same-name invocations overwrite evidence.
489
+ # The names are _ledger_next_tag's, but each is claimed by creating it, so the walk is its own.
490
+ _ledger_reserve_receipt() {
491
+ local wt="$1" name="$2" tag_var="$3" log_var="$4" n=1 candidate_log
492
+ local candidate_tag="$name" ld
493
+ _ledger_d "$wt" ld
494
+ [[ -w "$ld/logs" ]] || return 1
495
+ while :; do
496
+ candidate_log="$ld/logs/$candidate_tag.log"
497
+ if (set -o noclobber; : > "$candidate_log") 2>/dev/null; then break; fi
498
+ n=$((n + 1)); candidate_tag="$name-$n"
499
+ done
500
+ printf -v "$tag_var" '%s' "$candidate_tag"
501
+ printf -v "$log_var" '%s' "$candidate_log"
502
+ }
503
+ # _ledger_receipt_lock <wt> <tag>: the file whose kernel lock a receipt's own process holds from
504
+ # the moment it names its log until it writes the exit line, so a reader tells an open receipt
505
+ # from an abandoned one without trusting a pid.
506
+ _ledger_receipt_lock() { local ld; _ledger_d "$1" ld; printf '%s/logs/.%s.lock' "$ld" "$2"; }
507
+ # _ledger_receipt_take <wt> <tag>: this shell takes the receipt's lock on descriptor 4, which
508
+ # the command runs without. Best effort: with no lock tool the receipt runs and reads as unknown.
509
+ _ledger_receipt_take() {
510
+ { exec 4>> "$(_ledger_receipt_lock "$1" "$2")"; } 2>/dev/null || return 0
511
+ _ledger_lock_fd 4 try >/dev/null 2>&1 || true
512
+ }
513
+ # _ledger_receipt_held <wt> <tag>: status 0 while a live process holds the receipt's lock, 1
514
+ # when none does, and 3 when it cannot be told: no lock file, as an older module left, or no
515
+ # lock tool. The file is never created here, so a probe leaves nothing behind.
516
+ _ledger_receipt_held() {
517
+ local f; f="$(_ledger_receipt_lock "$1" "$2")"
518
+ [[ -f "$f" ]] || return 3
519
+ _ledger_authority_held "$f"
520
+ }
521
+ # _ledger_receipt_note <wt> <outcome> <evidence>: a `receipt` ledger line, when there is a ledger.
522
+ _ledger_receipt_note() {
523
+ local ld; _ledger_d "$1" ld
524
+ [[ -f "$ld/run.md" ]] || return 0
525
+ _ledger_event "$1" receipt "$2" "$3" >/dev/null 2>&1 || true
526
+ }
527
+ # _ledger_receipt_exit <log> <var>: the exit the receipt's log ends on, its `exit=<n>` line, into
528
+ # the named variable, or empty when the last line is not one. Status 0 either way, so a caller
529
+ # under set -e can ask about a log that is gone.
530
+ _ledger_receipt_exit() {
531
+ local _re_last
532
+ _re_last="$(tail -1 "$1" 2>/dev/null)" || _re_last=""
533
+ if [[ "$_re_last" =~ ^exit=([0-9]+)$ ]]; then printf -v "$2" '%s' "${BASH_REMATCH[1]}"; else printf -v "$2" '%s' ""; fi
534
+ }
535
+ # _ledger_receipt_supersede <wt> <name> <tag>: the end line of each earlier receipt of the name
536
+ # that the receipt <tag> replaces, `receipt superseded <log> exit=<n> by logs/<tag>.log`. Earlier
537
+ # means it has a start line and no end line, closed, void or superseded, which is a receipt
538
+ # whose process died before it wrote one, and its lock reads free. A lock that cannot be read
539
+ # might hide a receipt still running, so that one is left alone. The exit is the one its log
540
+ # ends on, or `none` when it never wrote one (#426).
541
+ _ledger_receipt_supersede() {
542
+ local wt="$1" name="$2" tag="$3" ld outcome rel old got code ended=$'\n' started=""
543
+ _ledger_d "$wt" ld
544
+ [[ -f "$ld/run.md" ]] || return 0
545
+ while IFS=' ' read -r outcome rel; do
546
+ [[ "$rel" == "logs/$name.log" || ( "$rel" == "logs/$name-"*.log && "${rel#"logs/$name-"}" =~ ^[0-9]+\.log$ ) ]] || continue
547
+ if [[ "$outcome" == started ]]; then started+="$rel"$'\n'; else ended+="$rel"$'\n'; fi
548
+ done < <(sed -nE 's/^[^ ]+ receipt (started|closed|void|superseded) (logs\/[^ ]+\.log)( .*)?$/\1 \2/p' "$ld/run.md" 2>/dev/null)
549
+ while IFS= read -r rel; do
550
+ [[ -n "$rel" && "$rel" != "logs/$tag.log" && "$ended" != *$'\n'"$rel"$'\n'* ]] || continue
551
+ old="${rel#logs/}"; old="${old%.log}"
552
+ got=0; _ledger_receipt_held "$wt" "$old" || got=$?
553
+ [[ "$got" -eq 1 ]] || continue
554
+ _ledger_receipt_exit "$ld/$rel" code
555
+ _ledger_receipt_note "$wt" superseded "$rel exit=${code:-none} by logs/$tag.log"
556
+ ended+="$rel"$'\n'
557
+ done <<< "$started"
558
+ }
559
+ # _ledger_wait_args <var> <args...>: the --wait bound out of the arguments, written to the named
560
+ # variable, and the rest left in _LEDGER_ARGS in order. Status 64 when the bound is not whole seconds.
561
+ _ledger_wait_args() {
562
+ local var="$1"
563
+ shift
564
+ _LEDGER_ARGS=()
565
+ while [[ $# -gt 0 ]]; do
566
+ if [[ "$1" == --wait ]]; then
567
+ [[ "${2:-}" =~ ^[0-9]+$ ]] || { _ledger_refuse "--wait takes whole seconds, got '${2:-}'"; return 64; }
568
+ printf -v "$var" '%s' "$2"
569
+ shift 2
570
+ else
571
+ _LEDGER_ARGS+=("$1")
572
+ shift
573
+ fi
574
+ done
575
+ }
576
+ # _ledger_relay <report> <count-var>: the detached child's new stderr lines on this one's stderr,
577
+ # past the number already relayed, which the named variable holds and is moved on.
578
+ _ledger_relay() {
579
+ local report="$1" count_var="$2" done_lines total
580
+ [[ -n "$report" && -f "$report" ]] || return 0
581
+ done_lines="${!count_var}"
582
+ total="$(wc -l < "$report" | tr -d ' ')"
583
+ [[ "$total" -gt "$done_lines" ]] || return 0
584
+ sed -n "$((done_lines + 1)),${total}p" "$report" | grep '^ledger: ' | grep -v ' is void: ' >&2 || true
585
+ printf -v "$count_var" '%s' "$total"
586
+ }
587
+ # _ledger_wait_hint <wt> <logs/name.log>: the command that takes up the wait on a receipt.
588
+ _ledger_wait_hint() { local ld; _ledger_d "$1" ld; printf 'bash %s/ledger.sh wait %s %s --wait 540' "$ld" "$1" "$2"; }
589
+ # _ledger_await <wt> <logs/name.log> <bound or empty> <since> [report]: wait on a receipt until
590
+ # its exit line, its abandonment or the bound, counted from <since>. The report, when there is
591
+ # one, is the detached child's stderr, relayed as it comes. Prints `<log> exit=<n>` and returns
592
+ # n, prints `running <log>` and returns 76, or prints `<log> abandoned` and returns 75.
593
+ _ledger_await() {
594
+ local wt="$1" rel="$2" bound="$3" since="$4" report="${5:-}" path tag code="" got relayed=0 voidline ld
595
+ _ledger_d "$wt" ld
596
+ path="$ld/$rel"; tag="${rel#logs/}"; tag="${tag%.log}"
597
+ while :; do
598
+ _ledger_relay "$report" relayed
599
+ # The lock before the log: an exit line is final only once the receipt's lock is free, because
600
+ # a receipt past its exit line still waits on nested leases and may yet append exit=75.
601
+ got=0; _ledger_receipt_held "$wt" "$tag" || got=$?
602
+ _ledger_receipt_exit "$path" code
603
+ if [[ "$got" -ne 0 && -n "$code" ]]; then break; fi
604
+ if [[ "$got" -eq 1 ]]; then
605
+ echo "$rel abandoned"
606
+ echo "ledger: $rel never wrote its exit line and nothing holds it, so it proves nothing. Run the gate again" >&2
607
+ return 75
608
+ fi
609
+ if [[ -n "$bound" ]] && (( $(_ledger_epoch) - since >= bound )); then
610
+ echo "running $rel"
611
+ echo "ledger: $tag is still running. Wait for it with $(_ledger_wait_hint "$wt" "$rel")" >&2
612
+ return 76
613
+ fi
614
+ sleep 0.2
615
+ done
616
+ _ledger_relay "$report" relayed
617
+ if [[ "$code" -eq 78 ]]; then
618
+ voidline="$(grep '^ledger: void: ' "$path" 2>/dev/null | tail -1)"
619
+ [[ -z "$voidline" ]] || echo "ledger: $tag is void: ${voidline#ledger: void: }" >&2
620
+ fi
621
+ printf '%s exit=%s\n' "$rel" "$code"
622
+ ! _ledger_run || tail -20 "$path"
623
+ return "$code"
624
+ }
625
+ # _ledger_self: this file's absolute path, fixed when the file is read, because a caller that
626
+ # sourced it by a relative path may change directory before a detached receipt starts it again.
627
+ # The directory and the name are cut from the path in the shell, as dirname and basename would,
628
+ # because every run of the module reads this line and those are two processes.
629
+ eval "_ledger_self() { printf '%s' $(printf '%q' "$(s="${BASH_SOURCE[0]}"; d=.; [[ "$s" != */* ]] || d="${s%/*}"; cd "${d:-/}" && pwd -P)/${BASH_SOURCE[0]##*/}"); }"
630
+ # _ledger_receipt_detached <wt> <name> <command> <bound>: the receipt run by a child in a process
631
+ # group of its own, reparented away from the caller and deaf to a hangup, so it outlives the tool
632
+ # call and the session that asked for it. The child names its log on the report once it holds the
633
+ # receipt's lock, then this waits on it for the bound.
634
+ _ledger_receipt_detached() {
635
+ local wt="$1" name="$2" cmd="$3" bound="$4" self report rel="" started i code
636
+ self="$(_ledger_self)"
637
+ report="$(mktemp "${TMPDIR:-/tmp}/ledger-receipt.XXXXXX" 2>/dev/null)" \
638
+ || { echo "ledger: $name could not make a file to hear its detached receipt on, so it did not run" >&2; return 75; }
639
+ started="$(_ledger_epoch)"
640
+ ( set -m; trap '' HUP; _LEDGER_DETACHED="$report" bash "$self" receipt "$wt" "$name" "$cmd" < /dev/null >> "$report" 2>&1 & )
641
+ for ((i = 0; i < 600; i++)); do
642
+ rel="$(sed -n 's/^ledger-log //p' "$report" 2>/dev/null | head -1)"
643
+ [[ -n "$rel" ]] && break
644
+ sleep 0.05
645
+ done
646
+ if [[ -z "$rel" || "$rel" == none ]]; then
647
+ grep '^ledger: ' "$report" >&2 || true
648
+ [[ -n "$rel" ]] || echo "ledger: $name never named its log, so whether its command runs is unknown" >&2
649
+ rm -f "$report"
650
+ return 75
651
+ fi
652
+ _ledger_await "$wt" "$rel" "$bound" "$started" "$report"; code=$?
653
+ rm -f "$report"
654
+ return "$code"
655
+ }
656
+ _ledger_usage() {
657
+ cat <<'USAGE'
658
+ Usage: kryso ledger <verb> <worktree> ...
659
+
660
+ open <wt> key=value... write the header, once
661
+ event <wt> <stage> <outcome> <evidence...> write one event line, its time
662
+ from the clock
663
+ receipt <wt> <name> <command> [--wait <s>] run the command to logs/<name>.log
664
+ and return its exit. Past --wait
665
+ seconds, detach it, print `running
666
+ <log>` and exit 76
667
+ wait <wt> <log> [--wait <s>] wait on a receipt again, with the
668
+ same answers
669
+ checkpoint <wt> <stage> <status> [detail] write checkpoint.json again, then
670
+ its ledger line
671
+ ci <wt> <pr> [--wait <s>] wait on the PR's checks over HEAD
672
+ and print green, red or pending.
673
+ Pending exits 76: call it again.
674
+ Past ci_wait, timeout exits 77
675
+ park <wt> <stage> <word> [evidence...] write a parked checkpoint, then
676
+ the park line, and print the
677
+ disposition
678
+ interrupt <wt> <consumed> <allowance> <stopped> [evidence...]
679
+ write an interrupted checkpoint at
680
+ the stage reached, then its line
681
+ triage <wt> <review> <diff> check the review: a triage row with
682
+ an outcome for each finding, and a
683
+ quote from the diff on each axis.
684
+ Prints each void axis; a failed
685
+ check is a refusal
686
+ read <wt> print one JSON document with all
687
+ the ledger knows about the
688
+ worktree
689
+ text <wt> print the document's fields that
690
+ the ledger file alone decides
691
+ worktree <repo> <issue> print the worktree whose ledger
692
+ names the issue
693
+ worktrees <repo> print every worktree with a
694
+ ledger, "<path> <issue>" per line
695
+ hold <repo> <issue> <command...> run the command while it holds the
696
+ issue's pass authority
697
+ drop <repo> <issue> remove the issue's pass lock file
698
+ while holding its lock; exit 75
699
+ while a live pass holds it
700
+ active <repo> <issue> print the live holder of the
701
+ authority, or exit 1 when it is
702
+ free
703
+ inherited <repo> <issue> exit 0 when the caller runs under
704
+ a live holder
705
+ handoff <wt> <engine> <shift> [key=value...]
706
+ write one handoff line with the
707
+ stage and the limits left
708
+ authorized <wt> <engine> [shift] exit 0 when that engine and shift
709
+ can continue the worktree
710
+ attempt <wt> <evidence...> write one reconciliation attempt
711
+ and print its number. The fourth
712
+ exits 1
713
+ archive <wt> [repo] copy .kryso/pass/ to
714
+ .claude/kryso/shipped/ and print
715
+ where
716
+ lock <path> <fd> hold the file's lock on the
717
+ descriptor, in a shell that
718
+ sources this module
719
+ locked <path> exit 0 while a live process holds
720
+ the file's lock
721
+ isolated <repo> print the docker pid and exit 0
722
+ while an isolated kryso run holds
723
+ the repository, or kryso
724
+ cleanup's pid and exit 2 while it
725
+ holds it. A stale pid file
726
+ is removed, or named on stderr
727
+ and kept when KRYSO_READ_ONLY is 1
728
+
729
+ A refusal is one line on stderr and exits 64. The receipt verb returns the
730
+ command's exit. Receipts run one at a time per repository: while another
731
+ worktree's receipt holds the gate lock, a receipt waits and says so on stderr. A
732
+ lock-tool error records exit=75 and does not run the command. A receipt on a
733
+ branch other than the ledger's, or one whose HEAD moved while it ran, is void
734
+ and exits 78. A wait on a receipt that nothing holds and that never wrote its
735
+ exit says abandoned and exits 75. park exits 75 while one of the worktree's own
736
+ receipts or its CI wait is open, and a ci-timeout park exits 75 until a CI wait
737
+ on HEAD has run out. hold returns the command's exit, or exits 75 without
738
+ running it while a live pass holds the issue.
739
+ USAGE
740
+ }
741
+
742
+ # _ledger_heredoc [var]: a heredoc on stdin, to the named variable, or to stdout when none is
743
+ # named. It is the builtin read, so the jq programs below reach a reader without a cat process.
744
+ _ledger_heredoc() {
745
+ local _ledger_text
746
+ IFS= read -r -d '' _ledger_text || true
747
+ if [[ -n "${1:-}" ]]; then printf -v "$1" '%s' "$_ledger_text"; else printf '%s' "$_ledger_text"; fi
748
+ }
749
+
750
+ # ---- the grammar, as jq --------------------------------------------------------------------
751
+ #
752
+ # Every reader shares these definitions, so the disposition table, the header, the event line
753
+ # with its tolerances, the ownership stamp and the park are each written once.
754
+ # A base-missing park is a prerequisite at whatever stage a resume stopped on, the merge and
755
+ # reconcile included: the base is gone locally and on origin, and a person puts it back (ADR 0010).
756
+ # A tree-moved park is one too, at the prove and at reconcile: a gate's receipt is void because the
757
+ # tree moved under it, and a person puts the tree back before anything continues.
758
+ # A change over its test budget under a policy that stops the pass is a person's to judge.
759
+ # A reconciliation context's own hand-back, needs-decision or out-of-scope, is a person's, the
760
+ # way the fork's is, and so is a PR a person closed without merging, pr-closed. A reconcile park the pass's own contexts could not move, the same failure
761
+ # after a repair or the issue's three spent, is retry-exhausted, the way a spent fork rerun is:
762
+ # what a resume may then do is each driver's, and the script engine's re-reads the evidence.
763
+ # A workflow step that left its declared evidence missing, evidence-missing, and a repair stage
764
+ # that left findings unsettled, unsettled, are retry-exhausted too: the stage ran once, and only
765
+ # a tree a person moved earns the pass another run.
766
+ _ledger_jq_defs() {
767
+ _ledger_heredoc "$@" <<'JQ'
768
+ def table($stage; $word):
769
+ if $word == "base-missing" or ($word == "tree-moved" and ($stage == "prove" or $stage == "reconcile")) then "prerequisite"
770
+ elif $stage == "merge" or $word == "pr-open" then "terminal"
771
+ elif $word == "over-budget" then "human-decision"
772
+ elif ($stage == "build" and ($word == "needs-decision" or $word == "no-feedback-loop"))
773
+ or ($stage == "reconcile" and ($word == "needs-decision" or $word == "out-of-scope" or $word == "pr-closed")) then "human-decision"
774
+ elif (($stage == "build" or $stage == "check") and $word == "check-failed") or ($stage == "prove" and $word == "gate-red")
775
+ or ($stage == "reconcile" and ($word == "ci-unchanged" or $word == "repairs-exhausted" or $word == "feedback-exhausted"))
776
+ or $word == "evidence-missing" or $word == "unsettled" then "retry-exhausted"
777
+ elif ($stage == "cut" and $word == "install-failed") or ($stage == "prove" and $word == "no-gate") then "prerequisite"
778
+ elif $stage == "reconcile" then "resumable"
779
+ else "terminal" end;
780
+ def word: (split(" ") | .[0]) // "";
781
+ # The disposition of a stage at a status, the one answer the checkpoint's writer and every reader
782
+ # give: a park reads the table, and a closeout that finished is terminal, because the pass merged
783
+ # and closed out and no resume has anything left to do. Everything else is resumable.
784
+ def disposition($stage; $status; $word):
785
+ if $status == "parked" then table($stage; $word)
786
+ elif $stage == "closeout" and $status == "done" then "terminal"
787
+ else "resumable" end;
788
+ def known_disposition($d): ["resumable", "retry-exhausted", "prerequisite", "human-decision", "terminal"] | index([$d]) != null;
789
+ def lines: split("\n") | map(rtrimstr("\r"));
790
+ def header_lines: lines as $l | ($l | index("") // ($l | length)) as $n | $l[:$n];
791
+ def header:
792
+ reduce (header_lines[] | capture("^(?<k>[a-z_]+): (?<v>.*)$")) as $kv ({}; . + {($kv.k): $kv.v})
793
+ | if has("base") then .base = ((.base | capture("^(?<name>\\S+)(?: \\((?<start>\\S+) (?<sha>[0-9a-f]{40})\\))?$")) // {name: .base, start: null, sha: null}) else . end;
794
+ # The gate-log lookup in _ledger_doc matches gate lines with this capture in bash; change both.
795
+ def raw_events:
796
+ [ lines[]
797
+ | capture("^(?<time>[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z) (?<stage>\\S+) (?<outcome>\\S+)(?: (?<evidence>.*))?$")
798
+ | .evidence = (.evidence // "")
799
+ | if (.stage | test("^(build|review)-(committed|triaged)$")) then
800
+ (.stage | split("-")) as $p
801
+ | {time, stage: $p[0], outcome: $p[1], evidence: ([.outcome, .evidence] | map(select(length > 0)) | join(" "))}
802
+ else . end
803
+ | if (.outcome | test("^park:?$")) then .outcome = "parked" else . end ];
804
+ def ownership: .stage == "shift" and (.outcome == "owned" or .outcome == "handoff");
805
+ def handoff_line:
806
+ (.evidence | capture("^stage=(?<stage>\\S+) from=(?<fe>[^/ ]+)/(?<fs>\\S+) to=(?<te>[^/ ]+)/(?<ts>\\S+) reconciliations=(?<r>[0-9]+)/[0-9]+ forks=(?<f>[0-9]+) consumed=(?<c>\\S+)")) as $m
807
+ | {time, stage: $m.stage, from: {engine: $m.fe, shift: $m.fs}, to: {engine: $m.te, shift: $m.ts},
808
+ reconciliations: ($m.r | tonumber), forks: ($m.f | tonumber),
809
+ consumed: ($m.c | rtrimstr("s") | tonumber? // null), evidence};
810
+ def handoff: (raw_events | map(select(.stage == "shift" and .outcome == "handoff")) | last) | if . == null then null else (handoff_line? // null) end;
811
+ def owner:
812
+ (raw_events | map(select(ownership)) | last)
813
+ | if . == null then null
814
+ elif .outcome == "owned" then ((.evidence | capture("shift=(?<shift>\\S+) pass=(?<pass>[0-9]+)")) // null) | if . == null then null else . + {engine: null, via: "owned"} end
815
+ else (handoff_line? // null) | if . == null then null else {shift: .to.shift, pass: null, engine: .to.engine, via: "handoff"} end end;
816
+ def events: raw_events | map(select(ownership | not));
817
+ def bookkeeping: .stage == "resume" or .stage == "receipt" or (.outcome | IN("checkpoint", "dispatched", "attempt", "interrupted"));
818
+ def without_counters: gsub("repairs=[0-9]+/[0-9]+"; "repairs=") | gsub("(?<w>repair|feedback|attempt) [0-9]+"; "\(.w) n")
819
+ | gsub("-[0-9]+\\.(?<e>json|log)"; ".\(.e)") | gsub("[0-9]+s left"; "left");
820
+ # A park's prose is the session's own wording, new on every re-read of a PR nothing moved, so
821
+ # only its word, its URLs and its evidence digests are progress. The head, the checks and the
822
+ # review feedback reach the fingerprint on their own.
823
+ def park_tokens: [scan("https?://[^ ()]+|evidence=[0-9a-f]+")] | join(" ");
824
+ def progress: (events | map(select(bookkeeping | not)) | last)
825
+ | if . == null then null
826
+ elif .outcome == "parked" then ([.stage, .outcome, (.evidence | word), (.evidence | park_tokens)] | map(select(. != "")) | join(" "))
827
+ else "\(.stage) \(.outcome) \(.evidence | without_counters)" end;
828
+ def park:
829
+ (events | map(select(.outcome == "parked")) | last)
830
+ | if . == null then null else {time, stage, word: (.evidence | word), evidence} end;
831
+ def interruption:
832
+ (events | map(select(.outcome == "interrupted" and (.evidence | startswith("deadline ")))) | last)
833
+ | if . == null then null else
834
+ ((.evidence | capture("consumed=(?<c>[0-9]+)s allowance=(?<a>[0-9]+)s stopped=(?<s>[a-z]+)")) // null) as $m
835
+ | {time, stage, consumed: ($m.c // null | if . == null then null else tonumber end),
836
+ allowance: ($m.a // null | if . == null then null else tonumber end), stopped: ($m.s // null), evidence} end;
837
+ # The merge as the pass recorded it: the method its last `merge intended` line names, and the
838
+ # commit its last `merge merged` or `merge recovered` line verified on origin.
839
+ def merge_record: (events | map(select(.stage == "merge"))) as $m
840
+ | {method: ([$m[] | select(.outcome == "intended") | (.evidence | capture("(^| )method=(?<m>[a-z]+)").m)?] | last),
841
+ commit: ([$m[] | select(.outcome == "merged" or .outcome == "recovered") | (.evidence | capture(" at (?<o>[0-9a-f]{40})( |$)").o)?] | last)};
842
+ JQ
843
+ }
844
+
845
+ # The document: where the pass stands and whether anyone may continue it, from the checkpoint
846
+ # when there is one and the last park line is not newer, else from that park, else from the
847
+ # events; the pull request; the review lines; the gate verdict with the driver's own reasons; and
848
+ # what bash read off the disk (the receipts, the tree, the newest mtime).
849
+ _ledger_jq_doc() {
850
+ _ledger_heredoc "$@" <<'JQ'
851
+ header as $h
852
+ | ($h.engine // "ship-it") as $engine
853
+ | events as $ev
854
+ | ($ev | last) as $last
855
+ | park as $park
856
+ | owner as $owner
857
+ | ($checkpoint != null and $checkpoint_error == "") as $has_cp
858
+ | (if $has_cp and $park != null and ($park.time > ($checkpoint.updated_at // "")) then "park"
859
+ elif $has_cp then "checkpoint"
860
+ elif $park != null then "park"
861
+ else "events" end) as $source
862
+ | (if $source == "checkpoint" then
863
+ {name: $checkpoint.stage, status: ($checkpoint.status // "running"), detail: ($checkpoint.detail // ""),
864
+ word: (if ($checkpoint.status // "") == "parked" then (($checkpoint.detail // "") | word) else "" end)}
865
+ elif $source == "park" then {name: $park.stage, status: "parked", detail: $park.evidence, word: $park.word}
866
+ elif ($ev | map(select(.stage == "pr" and .outcome == "opened")) | length) > 0 then {name: "pr", status: "done", detail: "", word: ""}
867
+ elif ($ev | map(select(.stage == "build" and .outcome == "checked")) | length) > 0 then {name: "check", status: "done", detail: "", word: ""}
868
+ else {name: "build", status: "running", detail: "", word: ""} end
869
+ | . + {source: $source}) as $stage
870
+ # A parked stage reads the table now, not the answer stored when it parked, so a park written
871
+ # before the table learnt its word reads the word's answer today. A stored disposition the reader
872
+ # does not know is passed on, parked or not, and never read as resumable.
873
+ | (if $source == "checkpoint" and (($checkpoint.disposition // "") as $d | $d != "" and (known_disposition($d) | not)) then $checkpoint.disposition
874
+ else disposition($stage.name; $stage.status; $stage.word) end) as $disposition
875
+ | (if $has_cp and (($checkpoint.pr // "none") != "none") and (($checkpoint.pr // "") != "") then $checkpoint.pr
876
+ else (($ev | map(select(.stage == "pr" and (.outcome == "opened" or .outcome == "reused"))) | last) | if . == null then null else (.evidence | word) end) end) as $pr
877
+ | {recorded: (($ev | map(select(.stage == "review" and .outcome == "recorded")) | last) | .evidence?),
878
+ triaged: (($ev | map(select(.stage == "review" and .outcome == "triaged")) | last) | .evidence?),
879
+ missing_axes: ($ev | map(select(.stage == "build" and .outcome == "axis-missing") | .evidence | word) | unique)} as $review
880
+ | ($ev | map(select(.stage == "gate" and (.outcome == "passed" or .outcome == "failed"))) | last) as $gline
881
+ | ($ev | map(select(.stage == "prove" and (.evidence | test("^(exit=)?[0-9]+ \\(logs/"))))
882
+ | group_by(.outcome) | map(last) | map({name: .outcome, evidence, green: (.evidence | startswith("exit=0 "))})) as $proved
883
+ # The head the last proof stood on: the last `<stage> proved head=<sha> <logs>` line over a whole
884
+ # sha, whichever stage wrote it, so the merge reads it from here and not from the line's text.
885
+ | ($ev | map(select(.outcome == "proved") | . as $e | (.evidence | split(" ")) as $w
886
+ | select(($w[0] // "") | test("^head=[0-9a-f]{40}$")) | {head: ($w[0] | ltrimstr("head=")), stage: $e.stage, logs: $w[1:], time: $e.time})
887
+ | last) as $proof
888
+ # Only the `logs/...` words of a `gate passed` line are logs; any other word (#650's `lint none`)
889
+ # makes the line malformed, listed in not_logs and named in the evidence, and a reason of its own
890
+ # when the logs are green. A red log gives way to a later run of the same command on the line, a
891
+ # higher `-<n>` on the same receipt name (no suffix is run 1), when the prove stage wrote the last
892
+ # proof, over the clean worktree's head, and every prove receipt is green (#620): the prove
893
+ # receipts are the merge's authority, and the gate line is the build fork's account of its own
894
+ # runs. A missing log is never excused. The bash lookup in _ledger_doc keeps the same `logs/` words.
895
+ | ($proof != null and $proof.stage == "prove" and $proof.head == $head and ($dirty | not)
896
+ and ($proved | length) > 0 and all($proved[]; .green)) as $proved_at_head
897
+ | (if $gline == null then {last: null, logs: [], verdict: "missing", reason: "no gate passed line in the ledger", evidence: ""}
898
+ elif $gline.outcome == "failed" then {last: "failed", logs: [], verdict: "red", reason: ("the last gate line is failed: " + $gline.evidence), evidence: ""}
899
+ else
900
+ ($gline.evidence | split(" ") | map(select(length > 0))) as $words
901
+ | ($words | map(select(startswith("logs/")))) as $logs
902
+ | ($words | map(select(startswith("logs/") | not))) as $not_logs
903
+ | [$gate_logs[] | . + ((.log | capture("^(?<receipt>.*?)(-(?<n>[0-9]+))?\\.log$")
904
+ | {receipt, run: (.n // "1" | tonumber)}) // {receipt: .log, run: 1})] as $runs
905
+ | [$runs[] | . as $r | . + {superseded: (.path != null and .tail != "exit=0" and $proved_at_head
906
+ and any($runs[]; .receipt == $r.receipt and .run > $r.run))}] as $named
907
+ | ($named | map(select(.superseded | not) | select(.path == null or .tail != "exit=0")) | first) as $bad
908
+ | ($named | map(select(.superseded) | .log)) as $reran
909
+ | ($proved | map(select(.green | not)) | first) as $notgreen
910
+ | if ($logs | length) == 0 then {last: "passed", logs: [], verdict: "red", reason: ("the gate passed line names no log: " + $gline.evidence), evidence: ""}
911
+ elif $bad != null and $bad.path == null then {last: "passed", logs: $logs, verdict: "red", reason: ("gate log " + $bad.log + " is missing"), evidence: ""}
912
+ elif $bad != null then {last: "passed", logs: $logs, verdict: "red", reason: ("gate log " + $bad.log + " ends '" + ($bad.tail // "") + "', not exit=0"), evidence: ""}
913
+ elif $notgreen != null then {last: "passed", logs: $logs, verdict: "red", reason: ("gate " + $notgreen.name + " is not green in the ledger: " + $notgreen.name + " " + $notgreen.evidence), evidence: ""}
914
+ else {last: "passed", logs: $logs, verdict: "green",
915
+ reason: (if ($not_logs | length) > 0 then "the gate passed line has words that are not logs: " + ($not_logs | join(" ")) else "" end),
916
+ evidence: ("gate passed " + ($logs - $reran | join(" ")) + " exit=0"
917
+ + (if ($reran | length) > 0 then " (" + ($reran | join(" ")) + " rerun)" else "" end)
918
+ + (if ($not_logs | length) > 0 then " (not logs: " + ($not_logs | join(" ")) + ")" else "" end)
919
+ + ($proved | map(", prove " + .name + " exit=0") | join("")))} end
920
+ | . + {not_logs: $not_logs}
921
+ end
922
+ | . + {proved: ($proved | map({key: .name, value: {green, evidence}}) | from_entries)}) as $gate
923
+ # The state the reconcile stage last read the checks in, the first word of its last `ci` line,
924
+ # with a `kept <state>` read as the state it kept.
925
+ | ($ev | map(select(.stage == "reconcile" and .outcome == "ci")) | last
926
+ | if . == null then null else (.evidence | split(" ")) as $w
927
+ | {state: (if $w[0] == "kept" then ($w[1] // null) else ($w[0] // null) end), time, evidence} end) as $ci
928
+ | ($hold_started | if . == "" then null else (try fromdateiso8601 catch null) end) as $held_since
929
+ | ($ev | map(select(.stage == "receipt" and .outcome == "started"))) as $starts
930
+ | ($ev | map(select(.stage == "receipt" and .outcome == "void") | .evidence | word)) as $voids
931
+ # A log is a receipt when this module made it one: a `receipt started` or `receipt void` line
932
+ # names it, or its lock file exists, which a receipt makes as it names its log and before it
933
+ # writes a line. A ledger whose header started before 0e5bb80 (2026-10-04T09:47:45Z), or that
934
+ # has no start, came from a module that wrote neither, and every log in it is a receipt.
935
+ | ($ev | map(select(.stage == "receipt") | .evidence | word)) as $marked
936
+ | (($h.started // "") < "2026-10-04T09:47:45Z") as $older
937
+ | ($receipts | map(select(. as $r | $older or $r.lockfile or ($marked | index([$r.file])) != null) | del(.lockfile)) | map(. as $r
938
+ | (($starts | map(select((.evidence | word) == $r.file)) | last) as $s
939
+ | if $s == null then null else (($s.evidence | capture("head=(?<h>[0-9a-f]+)") | .h)? // null) end) as $start_head
940
+ | del(.mtime) + {state:
941
+ (if ($voids | index([$r.file])) != null then "void"
942
+ elif $r.exit != null and $r.lock != "held" then "closed"
943
+ elif $r.lock == "held" then "open"
944
+ elif $r.lock == "free" then "abandoned"
945
+ elif $gate_holder != null and $gate_holder.wt == $wt and $gate_holder.tag == $r.name then "open"
946
+ elif $active == true and $held_since != null and ($r.mtime // 0) > $held_since then "open"
947
+ else "abandoned" end), head: $start_head}
948
+ | . + {reusable: (.state == "closed" and .head != null and .head == $head)})) as $receipts
949
+ | ($ev | map(select(.stage == "reconcile" and .outcome == "attempt"))) as $attempts
950
+ | ([($attempts | length)] + [$attempts[] | (.evidence | capture("^(?<n>[0-9]+)/").n | tonumber)?]
951
+ + [if $has_cp then ($checkpoint.repairs // 0 | if type == "number" then . else (tonumber? // 0) end) else 0 end] | max) as $used
952
+ | {worktree: $wt, dir: $ldir, ledger: true, header: $h, engine: $engine, events: $ev, last: $last, owner: $owner, park: $park,
953
+ handoff: handoff, progress: progress, reconciliations: {used: $used, cap: 3, left: ([3 - $used, 0] | max)},
954
+ checkpoint: (if $has_cp then $checkpoint else null end),
955
+ checkpoint_error: (if $checkpoint_error == "" then null else $checkpoint_error end),
956
+ stage: $stage, disposition: $disposition, disposition_known: known_disposition($disposition),
957
+ active: $active, interruption: interruption,
958
+ pr: $pr, review: $review, gate: $gate, proof: $proof, ci: $ci, merge: merge_record, receipts: $receipts, receipt_times: $receipt_times,
959
+ tree: {head: (if $head == "" then null else $head end), dirty: $dirty, fingerprint: $fingerprint,
960
+ moved: (if $has_cp and (($checkpoint.fingerprint // "") != "") then ($checkpoint.fingerprint != $fingerprint) else null end)},
961
+ mtime: $mtime}
962
+ JQ
963
+ }
964
+
965
+ # _ledger_table <stage> <word>: the disposition the table gives a park.
966
+ _ledger_table() { jq -rn --arg s "${1:-}" --arg w "${2:-}" "$(_ledger_jq_defs) table(\$s; \$w)"; }
967
+
968
+ # ---- the verbs ---------------------------------------------------------------------------
969
+
970
+ _ledger_open() {
971
+ local wt="${1:-}"
972
+ [[ $# -eq 0 ]] || shift
973
+ [[ -n "$wt" && -d "$wt" ]] || { _ledger_refuse "open needs an existing worktree directory, got '${wt}'"; return 64; }
974
+ local ld run kv key value
975
+ _ledger_d "$wt" ld; run="$ld/run.md"
976
+ [[ ! -e "$run" ]] || { _ledger_refuse "open refuses: $run exists, and a second header would be corruption"; return 64; }
977
+ local issue="" entry="" engine="ship-it" profile="" host="" effort="" base="" start="" base_sha="" branch="" worktree="$wt" board="" seam="" config="" started="" extra=""
978
+ for kv in "$@"; do
979
+ key="${kv%%=*}"; value="${kv#*=}"
980
+ [[ "$kv" != *$'\n'* ]] || { _ledger_refuse "open: a header line is one line, and '${key//$'\n'/ }' has a newline"; return 64; }
981
+ [[ "$kv" == *=* && -n "$key" ]] || { _ledger_refuse "open takes key=value arguments, got '$kv'"; return 64; }
982
+ case "$key" in
983
+ issue|entry|engine|profile|host|effort|base|start|base_sha|branch|worktree|board|seam|config|started) printf -v "$key" '%s' "$value" ;;
984
+ *) [[ "$key" =~ ^[a-z_]+$ ]] || { _ledger_refuse "open: a header key is lowercase letters and underscores, got '$key'"; return 64; }
985
+ extra+="$key: $value"$'\n' ;;
986
+ esac
987
+ done
988
+ [[ -n "$start" && -n "$base_sha" || -z "$start" && -z "$base_sha" ]] \
989
+ || { _ledger_refuse "open: start and base_sha go together, got only ${start:+start}${base_sha:+base_sha}"; return 64; }
990
+ [[ -n "$started" ]] || started="$(_ledger_now)"
991
+ mkdir -p "$ld/logs" || { _ledger_refuse "open cannot create $ld/logs"; return 64; }
992
+ # Only .kryso/pass/ is excluded, and the name before the rename for a worktree a module before
993
+ # it opened. The .kryso/ an older module excluded goes once no ledger is left at that place.
994
+ _ledger_exclude "$wt" '.kryso/pass/'
995
+ _ledger_exclude "$wt" '.ship-it/'
996
+ _ledger_unexclude_old "$wt"
997
+ cp "${BASH_SOURCE[0]}" "$ld/ledger.sh" || { _ledger_refuse "open cannot copy ${BASH_SOURCE[0]} into $ld"; return 64; }
998
+ {
999
+ [[ -z "$issue" ]] || echo "issue: $issue"
1000
+ [[ -z "$entry" ]] || echo "entry: $entry"
1001
+ echo "engine: $engine"
1002
+ [[ -z "$profile" ]] || echo "profile: $profile"
1003
+ [[ -z "$host" ]] || echo "host: $host"
1004
+ [[ -z "$effort" ]] || echo "effort: $effort"
1005
+ if [[ -n "$base" ]]; then
1006
+ if [[ -n "$start" || -n "$base_sha" ]]; then echo "base: $base ($start $base_sha)"; else echo "base: $base"; fi
1007
+ fi
1008
+ [[ -z "$branch" ]] || echo "branch: $branch"
1009
+ echo "worktree: $worktree"
1010
+ [[ -z "$board" ]] || echo "board: $board"
1011
+ [[ -z "$seam" ]] || echo "seam: $seam"
1012
+ [[ -z "$config" ]] || echo "config: $config"
1013
+ printf '%s' "$extra"
1014
+ echo "started: $started"
1015
+ echo
1016
+ printf '%s' "${LEDGER_PENDING:-}"
1017
+ } > "$run"
1018
+ unset LEDGER_PENDING
1019
+ }
1020
+
1021
+ # _ledger_gate_green <ledger dir> <evidence>: the one vocabulary rule the writer keeps, refused in
1022
+ # the context that can still fix it (#711). Each `logs/...` word of a `gate passed` line must end
1023
+ # exit=0, or be a receipt whose `receipt superseded <log> ... by <new log>` line names a new log
1024
+ # that does. It is stricter than the reader on purpose: a red log beside a higher-numbered rerun
1025
+ # is refused here, so the fork names only green receipts. A log that does not exist is left to
1026
+ # the reader, which calls the gate red with its own reason, and so is any word that is not a log.
1027
+ _ledger_gate_green() {
1028
+ local ld="$1" word last by code words
1029
+ read -ra words <<< "$2"
1030
+ for word in "${words[@]}"; do
1031
+ [[ "$word" == logs/* && -f "$ld/$word" ]] || continue
1032
+ _ledger_receipt_exit "$ld/$word" code
1033
+ [[ "$code" != 0 ]] || continue
1034
+ by="$(sed -nE "s#^[^ ]+ receipt superseded ${word//./\\.} exit=[^ ]+ by (logs/[^ ]+\\.log)\$#\\1#p" "$ld/run.md" | tail -1)"
1035
+ if [[ -n "$by" ]]; then _ledger_receipt_exit "$ld/$by" code; [[ "$code" != 0 ]] || continue; fi
1036
+ last="$(tail -1 "$ld/$word" 2>/dev/null)"
1037
+ _ledger_refuse "event: gate passed names $word, which ends '$last', not exit=0; name only receipts that ended exit=0 or that a green receipt superseded"
1038
+ return 64
1039
+ done
1040
+ }
1041
+
1042
+ _ledger_event() {
1043
+ local wt="${1:-}" stage="${2:-}" outcome="${3:-}"
1044
+ [[ $# -ge 4 ]] || { _ledger_refuse "event needs <worktree> <stage> <outcome> <evidence...>"; return 64; }
1045
+ shift 3
1046
+ local evidence="$*"
1047
+ evidence="${evidence//$'\n'/ }"
1048
+ [[ "$stage" =~ ^[A-Za-z][A-Za-z0-9_-]*$ ]] || { _ledger_refuse "event: the stage is one word, got '$stage'"; return 64; }
1049
+ [[ "$outcome" =~ ^[A-Za-z0-9][A-Za-z0-9_.:-]*$ ]] || { _ledger_refuse "event: the outcome is one word, got '$outcome'"; return 64; }
1050
+ [[ -n "${evidence// /}" ]] || { _ledger_refuse "event: the evidence is empty"; return 64; }
1051
+ local line ld
1052
+ line="$(_ledger_now) $stage $outcome $evidence"
1053
+ if [[ -n "$wt" ]]; then
1054
+ _ledger_d "$wt" ld
1055
+ [[ -f "$ld/run.md" ]] || { _ledger_refuse "event: no ledger at $ld/run.md, open it first"; return 64; }
1056
+ [[ "$stage $outcome" != "gate passed" ]] || _ledger_gate_green "$ld" "$evidence" || return 64
1057
+ printf '%s\n' "$line" >> "$ld/run.md"
1058
+ elif _ledger_run; then
1059
+ _ledger_refuse "event: no ledger at <no worktree>/.kryso/pass/run.md, open it first"; return 64
1060
+ else
1061
+ LEDGER_PENDING="${LEDGER_PENDING:-}$line"$'\n'
1062
+ fi
1063
+ }
1064
+
1065
+ _ledger_receipt() {
1066
+ local bound="" _LEDGER_ARGS=()
1067
+ _ledger_wait_args bound "$@" || return 64
1068
+ local wt="${_LEDGER_ARGS[0]:-}" name="${_LEDGER_ARGS[1]:-}" cmd="${_LEDGER_ARGS[2]:-}" ld
1069
+ _ledger_d "$wt" ld
1070
+ [[ -n "$wt" && -d "$ld/logs" ]] || { _ledger_refuse "receipt needs an opened worktree, got '${wt}'"; return 64; }
1071
+ [[ "$name" =~ ^[A-Za-z0-9][A-Za-z0-9_.:-]*$ ]] || { _ledger_refuse "receipt: the name is one word, got '$name'"; return 64; }
1072
+ [[ -n "$cmd" ]] || { _ledger_refuse "receipt needs a command"; return 64; }
1073
+ # Only a bound detaches the receipt. Without one it stays in the caller's process tree and
1074
+ # group, so the script engine's deadline stops it with the pass (ADR 0050).
1075
+ if [[ -n "$bound" && -z "${_LEDGER_DETACHED:-}" ]]; then _ledger_receipt_detached "$wt" "$name" "$cmd" "$bound"; return $?; fi
1076
+ # The gate lock is held on descriptor 9 for as long as this subshell runs, and the command runs
1077
+ # with 9 closed, so a child it leaves behind does not keep the next receipt waiting. A receipt
1078
+ # inside one carries a lease, so the holder waits only for descendants that start receipts.
1079
+ # The receipt's own lock is on descriptor 4, from the moment its log is named to its exit line.
1080
+ (
1081
+ local got=0 locked=0 nested=0 nested_status=1 lock_error="" tag log code=0 at held owner holder_pid token started nested_lease="" holder_authority=""
1082
+ local asked_at ran_at detached="${_LEDGER_DETACHED:-}" want="" have="" start_head="" end_head="" void="" lock
1083
+ unset _LEDGER_DETACHED
1084
+ asked_at="$(_ledger_epoch)"
1085
+ # A detached receipt names its log before it queues, so the caller waiting on it has a log to
1086
+ # name past its bound, and a reader sees it open while it waits for the gate lock.
1087
+ if [[ -n "$detached" ]]; then
1088
+ _ledger_reserve_receipt "$wt" "$name" tag log || { echo "ledger: $name could not reserve a receipt" >&2; echo "ledger-log none"; exit 75; }
1089
+ _ledger_receipt_take "$wt" "$tag"
1090
+ echo "\$ $cmd" > "$log"
1091
+ echo "ledger-log logs/$tag.log"
1092
+ fi
1093
+ # Looked up after the log is named, because the lookup runs git, and a slow one must not hold
1094
+ # back the log a bounded caller waits on.
1095
+ lock="$(_ledger_gate_lock "$wt")" || lock=""
1096
+ if [[ -n "$lock" ]]; then
1097
+ if _ledger_nested_gate_lease "$lock" nested_lease; then nested_status=0
1098
+ else nested_status=$?; fi
1099
+ [[ "$nested_status" -eq 0 ]] && nested=1
1100
+ [[ "$nested_status" -eq 3 ]] && lock_error="ledger: $name could not register under the gate lock holder"
1101
+ fi
1102
+ if [[ -n "$lock" && "$nested" -eq 0 && -z "$lock_error" ]]; then
1103
+ if ! { exec 9>> "$lock"; } 2>/dev/null; then
1104
+ # The lock is in the git common dir, outside a worktree, so a host sandbox that writes
1105
+ # the worktree alone refuses it. Say where, because the status alone reads as a test.
1106
+ lock_error="ledger: $name could not open the gate lock at $lock, so it did not run; a sandbox that cannot write the git common dir refuses it"
1107
+ else
1108
+ _ledger_lock_fd 9 try || got=$?
1109
+ if [[ "$got" -eq 0 ]]; then
1110
+ locked=1
1111
+ elif [[ "$got" -eq 1 ]]; then
1112
+ _ledger_lock_holder "$lock" at held owner || true
1113
+ echo "ledger: $name waits for the gate lock, held by ${held:-a receipt} in ${owner:-another worktree} since ${at:-an unknown time}" >&2
1114
+ if _ledger_lock_fd 9; then locked=1
1115
+ else lock_error="ledger: $name could not take the gate lock"; fi
1116
+ elif [[ "$got" -eq 2 ]]; then
1117
+ echo "ledger: no flock or lockf here, so $name runs without the gate lock" >&2
1118
+ else
1119
+ lock_error="ledger: $name could not take the gate lock"
1120
+ fi
1121
+ fi
1122
+ fi
1123
+ if [[ -n "$nested_lease" ]]; then
1124
+ export KRYSO_GATE_AUTHORITY="$nested_lease"
1125
+ export KRYSO_GATE_LEASE="$nested_lease"
1126
+ trap '_ledger_release_gate_authority "$nested_lease"' EXIT
1127
+ trap '_ledger_release_gate_authority "$nested_lease"; exit 75' HUP INT TERM
1128
+ fi
1129
+ if [[ "$locked" -eq 1 ]]; then
1130
+ _ledger_current_pid holder_pid || lock_error="ledger: $name could not identify the gate lock holder"
1131
+ if [[ -z "$lock_error" ]]; then
1132
+ token="$holder_pid-$RANDOM-$RANDOM"
1133
+ started="$(_ledger_now)"
1134
+ holder_authority="$lock.holders/$token"
1135
+ mkdir -p "$lock.holders" || lock_error="ledger: $name could not create its gate authority"
1136
+ fi
1137
+ if [[ -z "$lock_error" ]]; then
1138
+ (set -o noclobber; : > "$holder_authority") 2>/dev/null \
1139
+ || lock_error="ledger: $name could not create its gate authority"
1140
+ fi
1141
+ if [[ -z "$lock_error" ]]; then
1142
+ { exec 8>> "$holder_authority"; } 2>/dev/null \
1143
+ || lock_error="ledger: $name could not open its gate authority"
1144
+ fi
1145
+ if [[ -z "$lock_error" ]]; then
1146
+ _ledger_lock_fd 8 try || lock_error="ledger: $name could not take its gate authority"
1147
+ fi
1148
+ if [[ -z "$lock_error" ]]; then
1149
+ printf '%s %s %s %s %s\n' "$token" open "$started" "$name" "$wt" >| "$lock" \
1150
+ || lock_error="ledger: $name could not record the gate lock holder"
1151
+ export KRYSO_GATE_LOCK="$lock"
1152
+ export KRYSO_GATE_LOCK_TOKEN="$token"
1153
+ export KRYSO_GATE_AUTHORITY="$holder_authority"
1154
+ unset KRYSO_GATE_LEASE
1155
+ _ledger_wait_gate_leases "$lock" \
1156
+ || lock_error="ledger: $name could not inspect inherited gate leases"
1157
+ fi
1158
+ fi
1159
+ if [[ -z "$detached" ]]; then
1160
+ _ledger_reserve_receipt "$wt" "$name" tag log || {
1161
+ _ledger_release_gate_authority "${nested_lease:-$holder_authority}"
1162
+ echo "ledger: $name could not reserve a receipt" >&2
1163
+ exit 75
1164
+ }
1165
+ _ledger_receipt_take "$wt" "$tag"
1166
+ fi
1167
+ # The holder's record names the receipt it reserved, so a reader can tell that receipt is open.
1168
+ if [[ "$locked" -eq 1 && -z "$lock_error" ]]; then
1169
+ printf '%s %s %s %s %s\n' "$token" open "$started" "$tag" "$wt" >| "$lock" 2>/dev/null || true
1170
+ fi
1171
+ if [[ -n "$lock_error" ]]; then
1172
+ echo "$lock_error" >&2
1173
+ { echo "\$ $cmd"; echo "$lock_error"; echo 'exit=75'; } > "$log"
1174
+ if [[ -z "$detached" ]]; then
1175
+ printf 'logs/%s.log exit=75\n' "$tag"
1176
+ ! _ledger_run || tail -20 "$log"
1177
+ fi
1178
+ _ledger_release_gate_authority "${nested_lease:-$holder_authority}"
1179
+ exit 75
1180
+ fi
1181
+ ran_at="$(_ledger_epoch)"
1182
+ # The tree has to be the pass's: on the ledger's branch once the gate lock is held, and at the
1183
+ # same HEAD when the command ends. Either mismatch is void, exit 78, never a pass or a fail.
1184
+ [[ ! -f "$ld/run.md" ]] || want="$(sed -nE '/^\r?$/q; s/^branch: //p' "$ld/run.md" | head -1 | tr -d '\r')"
1185
+ if [[ -n "$want" ]]; then
1186
+ have="$(git -C "$wt" symbolic-ref --short -q HEAD 2>/dev/null)" || have=""
1187
+ [[ "$have" == "$want" ]] || void="the worktree is on ${have:-a detached HEAD}, not the ledger's branch $want"
1188
+ fi
1189
+ if [[ -n "$void" ]]; then
1190
+ { echo "\$ $cmd"; echo "ledger: void: $void, so the command did not run"; echo 'exit=78'; } > "$log"
1191
+ code=78
1192
+ else
1193
+ start_head="$(git -C "$wt" rev-parse -q --verify HEAD 2>/dev/null)" || start_head=""
1194
+ _ledger_receipt_supersede "$wt" "$name" "$tag"
1195
+ _ledger_receipt_note "$wt" started "logs/$tag.log head=${start_head:-none}"
1196
+ {
1197
+ echo "\$ $cmd"
1198
+ (cd "$wt" && eval "$cmd") 4>&- 8>&- 9>&- 2>&1; code=$?
1199
+ end_head="$(git -C "$wt" rev-parse -q --verify HEAD 2>/dev/null)" || end_head=""
1200
+ if [[ "$end_head" != "$start_head" ]]; then
1201
+ void="HEAD moved from ${start_head:0:12} to ${end_head:0:12} while the command ran"
1202
+ echo "ledger: void: $void, and it exited $code"
1203
+ code=78
1204
+ fi
1205
+ echo "exit=$code"
1206
+ } > "$log" 2>&1
1207
+ fi
1208
+ if [[ -n "$void" ]]; then
1209
+ _ledger_receipt_note "$wt" void "logs/$tag.log $void"
1210
+ echo "ledger: $tag is void: $void" >&2
1211
+ fi
1212
+ printf '%s queued=%s ran=%s\n' "$tag" "$(( ran_at - asked_at ))" "$(( $(_ledger_epoch) - ran_at ))" >> "$ld/logs/receipt-times.txt" 2>/dev/null || true
1213
+ if [[ -n "$nested_lease" ]]; then
1214
+ _ledger_release_gate_authority "$nested_lease"
1215
+ nested_lease=""
1216
+ trap - EXIT HUP INT TERM
1217
+ fi
1218
+ if [[ "$locked" -eq 1 ]]; then
1219
+ printf '%s %s %s %s %s\n' "$token" closing "$started" "$tag" "$wt" >| "$lock"
1220
+ if ! _ledger_wait_gate_leases "$lock"; then
1221
+ echo "ledger: $name could not inspect inherited gate leases" >&2
1222
+ code=75
1223
+ echo 'exit=75' >> "$log"
1224
+ fi
1225
+ _ledger_release_gate_authority "$holder_authority"
1226
+ holder_authority=""
1227
+ fi
1228
+ # The start line's end, once the exit is final: a void receipt has its void line instead.
1229
+ [[ -n "$void" ]] || _ledger_receipt_note "$wt" closed "logs/$tag.log exit=$code"
1230
+ if [[ -z "$detached" ]]; then
1231
+ printf 'logs/%s.log exit=%s\n' "$tag" "$code"
1232
+ ! _ledger_run || tail -20 "$log"
1233
+ fi
1234
+ exit "$code"
1235
+ )
1236
+ }
1237
+
1238
+ # wait: the wait on a receipt taken up again, by a caller whose bound ran out, a later session or
1239
+ # a driver. The log is logs/<name>.log or its path. Same answers as a bounded receipt.
1240
+ _ledger_wait() {
1241
+ local bound="" _LEDGER_ARGS=() rel
1242
+ _ledger_wait_args bound "$@" || return 64
1243
+ local wt="${_LEDGER_ARGS[0]:-}" log="${_LEDGER_ARGS[1]:-}" ld
1244
+ _ledger_d "$wt" ld
1245
+ [[ -n "$wt" && -d "$ld/logs" ]] || { _ledger_refuse "wait needs an opened worktree, got '${wt}'"; return 64; }
1246
+ [[ -n "$log" ]] || { _ledger_refuse "wait needs a receipt's log, logs/<name>.log"; return 64; }
1247
+ case "$log" in
1248
+ "$wt/.kryso/pass/"*) rel="${log#"$wt/.kryso/pass/"}" ;;
1249
+ "$wt/.kryso/"*) rel="${log#"$wt/.kryso/"}" ;;
1250
+ "$wt/.ship-it/"*) rel="${log#"$wt/.ship-it/"}" ;;
1251
+ .kryso/pass/*) rel="${log#.kryso/pass/}" ;;
1252
+ .kryso/*) rel="${log#.kryso/}" ;;
1253
+ .ship-it/*) rel="${log#.ship-it/}" ;;
1254
+ logs/*) rel="$log" ;;
1255
+ *) rel="logs/${log##*/}" ;;
1256
+ esac
1257
+ [[ "$rel" =~ ^logs/[A-Za-z0-9][A-Za-z0-9_.:-]*\.log$ && -f "$ld/$rel" ]] \
1258
+ || { _ledger_refuse "wait: no receipt at $ld/$rel"; return 64; }
1259
+ _ledger_await "$wt" "$rel" "$bound" "$(_ledger_epoch)"
1260
+ }
1261
+
1262
+ # ---- a repository's kryso files --------------------------------------------------------------
1263
+ #
1264
+ # A repository keeps its kryso configuration under .kryso/ (ADR 0046): config.json, the gate and
1265
+ # a pass's settings, testing-policy.md and watch.json. Each had an older place, which is read
1266
+ # where the new one is absent until 3.0.0, with one warning that names the move. Where both are
1267
+ # there the new place wins, and the warning says the old one is ignored.
1268
+
1269
+ # _ledger_kryso_place <dir> <ref> <new> <old> <var>: which of <new> and <old> holds the file, in
1270
+ # the commit <ref> of the repository at <dir>, or on disk under <dir> when <ref> is empty, into
1271
+ # the named variable, empty when neither does. _ledger_kryso_note gets the warning, or nothing.
1272
+ _ledger_kryso_place() {
1273
+ local dir="$1" ref="$2" new="$3" old="$4" has_new=0 has_old=0
1274
+ _ledger_kryso_has "$dir" "$ref" "$new" && has_new=1
1275
+ _ledger_kryso_has "$dir" "$ref" "$old" && has_old=1
1276
+ _ledger_kryso_note=""
1277
+ if [[ "$has_new" -eq 1 ]]; then
1278
+ printf -v "$5" '%s' "$new"
1279
+ [[ "$has_old" -eq 0 ]] || _ledger_kryso_note="$old is ignored, since $new is there. Remove it with: git rm $old"
1280
+ elif [[ "$has_old" -eq 1 ]]; then
1281
+ printf -v "$5" '%s' "$old"
1282
+ _ledger_kryso_note="$old has moved to $new, and kryso reads the old place only until 3.0.0. Move it with: mkdir -p $(dirname "$new") && git mv $old $new"
1283
+ else
1284
+ printf -v "$5" '%s' ""
1285
+ fi
1286
+ }
1287
+ # _ledger_kryso_has <dir> <ref> <path>: the path is a file in the commit <ref>, or on disk under
1288
+ # <dir> when <ref> is empty.
1289
+ _ledger_kryso_has() {
1290
+ if [[ -n "$2" ]]; then git -C "$1" cat-file -e "$2:$3" 2>/dev/null; else [[ -f "$1/$3" ]]; fi
1291
+ }
1292
+
1293
+ # ---- the CI wait -----------------------------------------------------------------------------
1294
+ #
1295
+ # ci: the session's wait on the PR's checks over the worktree's HEAD, held in shell the way a
1296
+ # receipt's wait is, so a slow runner costs one tool call per --wait and not one per poll (#397).
1297
+ # The wait's bound is `ci_wait` in .kryso/config.json (.claude/ship-pass.json before it), the key and the 1800s default the
1298
+ # script engine reads, and read where it reads it: off the base commit the ledger's header names,
1299
+ # so a pass cannot widen its own bound with an edit. A ledger that names no base commit reads the
1300
+ # worktree's file. The wait counts from the first call on the head, whose `reconcile ci pending
1301
+ # head=<sha> started=<epoch> bound=<s>s` line every later call reads back, so the bound stated
1302
+ # when the wait began is the one it ends on, and a call after its `timeout` line times out again.
1303
+ # A new head starts a new wait.
1304
+
1305
+ # _ledger_ci_bound <wt> <var>: the bound, whole seconds, into the named variable; 64 otherwise.
1306
+ # The file is .kryso/config.json, or .claude/ship-pass.json where that is absent, by the place
1307
+ # rule below.
1308
+ _ledger_ci_bound() {
1309
+ local wt="$1" ld sha json="" where v=1800 place
1310
+ _ledger_d "$wt" ld
1311
+ sha="$(sed -nE '/^$/q; s/^base: [^ ]+ \([^ ]+ ([0-9a-f]{40})\)$/\1/p' "$ld/run.md" 2>/dev/null)"
1312
+ _ledger_kryso_place "$wt" "$sha" .kryso/config.json .claude/ship-pass.json place
1313
+ place="${place:-.kryso/config.json}"
1314
+ if [[ -n "$sha" ]]; then
1315
+ where="$place at $sha"
1316
+ json="$(git -C "$wt" show "$sha:$place" 2>/dev/null)" || json=""
1317
+ else
1318
+ where="$wt/$place"
1319
+ [[ ! -f "$where" ]] || json="$(cat "$where")"
1320
+ fi
1321
+ if [[ -n "$json" ]]; then
1322
+ v="$(jq -r '.ci_wait // 1800' <<< "$json" 2>/dev/null)" || { _ledger_refuse "ci: $where is not valid JSON"; return 64; }
1323
+ fi
1324
+ [[ "$v" =~ ^[0-9]+$ ]] || { _ledger_refuse "ci: ci_wait in $where must be whole seconds, got '$v'"; return 64; }
1325
+ printf -v "$2" '%s' "$v"
1326
+ }
1327
+ # _ledger_ci_last <wt>: the evidence of the ledger's last `reconcile ci` line, or nothing.
1328
+ _ledger_ci_last() {
1329
+ local ld; _ledger_d "$1" ld
1330
+ sed -nE 's/^[^ ]+ reconcile ci (.*)$/\1/p' "$ld/run.md" 2>/dev/null | tail -1
1331
+ }
1332
+ # _ledger_ci_wait <wt>: the wait the last `reconcile ci` line leaves, into the caller's locals
1333
+ # _ci_state, its first word, and, on a pending or timeout line, _ci_head, _ci_started, _ci_bound,
1334
+ # _ci_pr and _ci_what, what it was waiting on. A timeout line states no start, so its _ci_started
1335
+ # is the one whose bound runs out now.
1336
+ _ledger_ci_wait() {
1337
+ local last
1338
+ _ci_state=""; _ci_head=""; _ci_started=""; _ci_bound=""; _ci_pr=""; _ci_what=""
1339
+ last="$(_ledger_ci_last "$1")"
1340
+ if [[ "$last" =~ ^pending\ head=([0-9a-f]+)\ started=([0-9]+)\ bound=([0-9]+)s\ on\ ([^ ]+):\ (.*)$ ]]; then
1341
+ _ci_state=pending; _ci_head="${BASH_REMATCH[1]}"; _ci_started="${BASH_REMATCH[2]}"
1342
+ _ci_bound="${BASH_REMATCH[3]}"; _ci_pr="${BASH_REMATCH[4]}"; _ci_what="${BASH_REMATCH[5]}"
1343
+ elif [[ "$last" =~ ^timeout\ after\ ([0-9]+)s\ on\ ([^ ]+)\ head=([0-9a-f]+):\ (.*)$ ]]; then
1344
+ _ci_state=timeout; _ci_bound="${BASH_REMATCH[1]}"; _ci_pr="${BASH_REMATCH[2]}"
1345
+ _ci_head="${BASH_REMATCH[3]}"; _ci_what="${BASH_REMATCH[4]}"; _ci_started=$(( $(_ledger_epoch) - _ci_bound ))
1346
+ else
1347
+ _ci_state="${last%% *}"
1348
+ fi
1349
+ }
1350
+ # _ledger_ci_open <wt>: status 0, with the PR on stdout, while the last `reconcile ci` line is a
1351
+ # pending one whose bound has not run out. That wait may still turn green or red, so a park now
1352
+ # would answer a question nobody finished asking.
1353
+ _ledger_ci_open() {
1354
+ local _ci_state _ci_head _ci_started _ci_bound _ci_pr _ci_what
1355
+ _ledger_ci_wait "$1"
1356
+ [[ "$_ci_state" == pending ]] && (( $(_ledger_epoch) < _ci_started + _ci_bound )) || return 1
1357
+ printf '%s\n' "$_ci_pr"
1358
+ }
1359
+ # _ledger_ci_hint <wt> <pr>: the command that takes up a CI wait.
1360
+ _ledger_ci_hint() { local ld; _ledger_d "$1" ld; printf 'bash %s/ledger.sh ci %s %s --wait 540' "$ld" "$1" "$2"; }
1361
+
1362
+ # ci <wt> <pr> [--wait <s>]: reads the PR's checks on HEAD every LEDGER_CI_INTERVAL seconds (30)
1363
+ # for at most --wait seconds (540, inside a host's ten-minute command limit) and the bound, then
1364
+ # writes one `reconcile ci` line and prints it. Its first word is the answer:
1365
+ # green <n> check(s) ..., runs <ids> 0
1366
+ # none (no-ci: ...) 0 no check at all once a grace of
1367
+ # min(60s, bound) from the start passed
1368
+ # red <n> check(s) ...: <name> (run <id>), ... 1
1369
+ # pending head=<sha> started=<s> bound=<b>s on <pr>: ... 76 call again; park refuses meanwhile
1370
+ # timeout after <b>s on <pr> head=<sha>: ... 77 park with `reconcile ci-timeout`
1371
+ # moved <pr> is at <sha>, a head <wt> does not hold 78 someone else's push
1372
+ # A PR head behind HEAD is GitHub catching up on a push, so its checks count as pending. A read gh
1373
+ # refuses counts as pending too, named on the line, and is read again.
1374
+ _ledger_ci() {
1375
+ local call=540 _LEDGER_ARGS=()
1376
+ _ledger_wait_args call "$@" || return 64
1377
+ local wt="${_LEDGER_ARGS[0]:-}" pr="${_LEDGER_ARGS[1]:-}" ld bound head started="" now deadline end interval grace
1378
+ local _ci_state _ci_head _ci_started _ci_bound _ci_pr _ci_what
1379
+ _ledger_d "$wt" ld
1380
+ [[ -n "$wt" && -f "$ld/run.md" ]] || { _ledger_refuse "ci needs an opened worktree, got '$wt'"; return 64; }
1381
+ [[ -n "$pr" && "$pr" != *[[:space:]]* ]] || { _ledger_refuse "ci needs the pull request, its number or URL"; return 64; }
1382
+ _ledger_ci_bound "$wt" bound || return 64
1383
+ head="$(git -C "$wt" rev-parse -q --verify HEAD 2>/dev/null)" || { _ledger_refuse "ci: cannot read HEAD in $wt"; return 64; }
1384
+ interval="${LEDGER_CI_INTERVAL:-30}"; [[ "$interval" =~ ^[0-9]+$ ]] || interval=30
1385
+ _ledger_ci_wait "$wt"
1386
+ if [[ ( "$_ci_state" == pending || "$_ci_state" == timeout ) && "$_ci_head" == "$head" ]]; then
1387
+ started="$_ci_started"; bound="$_ci_bound"
1388
+ fi
1389
+ now="$(_ledger_epoch)"
1390
+ [[ -n "$started" ]] || started="$now"
1391
+ deadline=$(( started + bound ))
1392
+ end=$(( now + call )); (( end < deadline )) || end="$deadline"
1393
+ grace=$(( bound < 60 ? bound : 60 ))
1394
+ local err pr_head checks code state="" what="" n line rc
1395
+ err="$(mktemp "${TMPDIR:-/tmp}/ledger-ci.XXXXXX" 2>/dev/null)" || { _ledger_refuse "ci: cannot make a file for gh's errors"; return 64; }
1396
+ while :; do
1397
+ what=""
1398
+ if ! pr_head="$(cd "$wt" && gh pr view "$pr" --json headRefOid --jq .headRefOid 2>"$err")"; then
1399
+ what="the PR head could not be read: gh pr view said $(head -1 "$err")"
1400
+ elif [[ -n "$pr_head" && "$pr_head" != "$head" ]] && ! git -C "$wt" merge-base --is-ancestor "$pr_head" "$head" 2>/dev/null; then
1401
+ state=moved; break
1402
+ elif [[ "$pr_head" != "$head" ]]; then
1403
+ what="no check on this head yet, the PR is still at ${pr_head:0:12}"
1404
+ [[ -n "$pr_head" ]] || what="no check on this head yet, the PR reports no head"
1405
+ else
1406
+ # gh exits 8 while a check is pending, which must not stop a caller under set -e.
1407
+ code=0; checks="$(cd "$wt" && gh pr checks "$pr" --json bucket,name,link 2>"$err")" || code=$?
1408
+ if [[ "$code" -ne 0 && ! "$checks" =~ ^\[ ]]; then
1409
+ if grep -qi 'no checks reported' "$err"; then checks="[]"
1410
+ else what="the checks could not be read: gh pr checks exit=$code said $(head -1 "$err")"; fi
1411
+ fi
1412
+ if [[ -z "$what" ]]; then
1413
+ [[ -n "$checks" ]] || checks="[]"
1414
+ n="$(jq '[.[] | select(.bucket == "fail" or .bucket == "cancel")] | length' <<< "$checks")"
1415
+ if [[ "$n" -gt 0 ]]; then state=red; break; fi
1416
+ n="$(jq '[.[] | select(.bucket == "pending")] | length' <<< "$checks")"
1417
+ if [[ "$(jq length <<< "$checks")" -eq 0 ]]; then
1418
+ if (( $(_ledger_epoch) >= started + grace )); then state=none; break; fi
1419
+ what="no check reported yet"
1420
+ elif [[ "$n" -eq 0 ]]; then state=green; break
1421
+ else what="$n check(s) pending: $(jq -r '[.[] | select(.bucket == "pending") | .name] | join(", ")' <<< "$checks")"; fi
1422
+ fi
1423
+ fi
1424
+ now="$(_ledger_epoch)"
1425
+ if (( now >= deadline )); then state=timeout; break; fi
1426
+ if (( now >= end )); then state=pending; break; fi
1427
+ sleep "$(( end - now < interval ? end - now : interval ))"
1428
+ done
1429
+ rm -f "$err"
1430
+ case "$state" in
1431
+ green) rc=0; line="green $(jq length <<< "$checks") check(s) on $pr head=$head, runs $(jq -r '[.[] | .link // "" | capture("/runs/(?<id>[0-9]+)").id] | unique | join(",")' <<< "$checks")" ;;
1432
+ none) rc=0; line="none (no-ci: no checks reported on $pr) head=$head" ;;
1433
+ red) rc=1; line="red $n check(s) on $pr head=$head: $(jq -r '[.[] | select(.bucket == "fail" or .bucket == "cancel") | .name + ((.link // "" | capture("/runs/(?<id>[0-9]+)") | " (run \(.id))") // "")] | join(", ")' <<< "$checks")" ;;
1434
+ pending) rc=76; line="pending head=$head started=$started bound=${bound}s on $pr: $what" ;;
1435
+ timeout) rc=77; line="timeout after ${bound}s on $pr head=$head: $what" ;;
1436
+ moved) rc=78; line="moved $pr is at ${pr_head:0:12}, a head $wt does not hold" ;;
1437
+ esac
1438
+ _ledger_event "$wt" reconcile ci "$line" || return $?
1439
+ printf '%s\n' "$line"
1440
+ case "$state" in
1441
+ pending) echo "ledger: CI is still pending on $pr with $(( deadline - $(_ledger_epoch) ))s of the ${bound}s bound left. Wait again with $(_ledger_ci_hint "$wt" "$pr")" >&2 ;;
1442
+ timeout) echo "ledger: the ${bound}s CI wait on $pr ran out. Park with bash $ld/ledger.sh park $wt reconcile ci-timeout" >&2 ;;
1443
+ esac
1444
+ return "$rc"
1445
+ }
1446
+
1447
+ # read: everything known about the worktree. _ledger_doc <wt> core is the same document without
1448
+ # the parts named below, for the verbs that read none of them. A core document's receipts, gate
1449
+ # and active are not the worktree's: its gate can read green over a missing log. So only the
1450
+ # verbs here take one, and only for the header, events, checkpoint, stage, owner and tree.
1451
+ _ledger_read() { _ledger_doc "${1:-}" full; }
1452
+
1453
+ # _ledger_text <wt>: the fields of read's document that the ledger file alone decides, through
1454
+ # the same grammar, for a caller that wants nothing else, so it pays for none of the tree, the
1455
+ # locks or the receipts a read probes. No ledger is the values a read gives a worktree with none,
1456
+ # and a refusal is read's.
1457
+ _ledger_text() {
1458
+ local wt="${1:-}" ld defs
1459
+ [[ -n "$wt" && -d "$wt" ]] || { _ledger_refuse "read needs an existing worktree directory, got '${wt}'"; return 64; }
1460
+ _ledger_d "$wt" ld
1461
+ if [[ ! -f "$ld/run.md" ]]; then
1462
+ printf '%s\n' '{"header":null,"engine":null,"events":[],"last":null,"owner":null,"park":null,"handoff":null,"progress":null,"interruption":null,"merge":{"method":null,"commit":null}}'
1463
+ return 0
1464
+ fi
1465
+ _ledger_jq_defs defs
1466
+ jq -nc --rawfile text "$ld/run.md" "$defs"' $text | header as $h | events as $ev
1467
+ | {header: $h, engine: ($h.engine // "ship-it"), events: $ev, last: ($ev | last), owner: owner, park: park,
1468
+ handoff: handoff, progress: progress, interruption: interruption, merge: merge_record}'
1469
+ }
1470
+
1471
+ _ledger_doc() {
1472
+ local wt="${1:-}" part="${2:-full}"
1473
+ [[ "$part" == full || "$part" == core ]] || { _ledger_refuse "doc: the part is full or core, got '$part'"; return 64; }
1474
+ [[ -n "$wt" && -d "$wt" ]] || { _ledger_refuse "read needs an existing worktree directory, got '${wt}'"; return 64; }
1475
+ local ld; _ledger_d "$wt" ld
1476
+ local dir="$ld" run="$ld/run.md"
1477
+ if [[ ! -f "$run" ]]; then
1478
+ jq -nc --arg wt "$wt" --arg ldir "${ld#"$wt"/}" '{worktree: $wt, dir: $ldir, ledger: false, header: null, engine: null, events: [], last: null, owner: null, park: null, handoff: null, progress: null, reconciliations: null, checkpoint: null, checkpoint_error: null, stage: null, disposition: null, disposition_known: null, active: null, interruption: null, pr: null, review: null, gate: null, proof: null, ci: null, merge: {method: null, commit: null}, receipts: [], receipt_times: [], tree: null, mtime: null}'
1479
+ return 0
1480
+ fi
1481
+ local defs doc; _ledger_jq_defs defs; _ledger_jq_doc doc
1482
+ _ledger_stat_pick
1483
+ # One jq prints the document. The checkpoint, the receipts, their times and the gate's logs
1484
+ # reach it raw, and the head of its program parses each the way a jq call of its own once
1485
+ # did, so a read is one jq however many receipts the worktree holds. The checkpoint, or why
1486
+ # it cannot be trusted: the file's text, judged by the head below.
1487
+ local cp="$dir/checkpoint.json" cp_present=false
1488
+ local -a cp_arg=(--arg cp_raw "") times_arg=(--arg times_raw "")
1489
+ if [[ -f "$cp" ]]; then
1490
+ cp_present=true
1491
+ [[ ! -r "$cp" ]] || cp_arg=(--rawfile cp_raw "$cp")
1492
+ fi
1493
+ # What only a full read takes: the locks, the receipts, their times and the gate's logs, and
1494
+ # the newest mtime. A core read, for the verbs whose answer is the header, the events, the
1495
+ # checkpoint and the tree, leaves them at the values a worktree with none of them gets.
1496
+ local active=null hold_started="" holder_wt="" holder_tag="" holder=false times_present=false mtime=null
1497
+ local -a fields=() found=() _ledger_lines=()
1498
+ if [[ "$part" == full ]]; then
1499
+ # The repository's common directory, asked once for both locks below.
1500
+ local common=""; common="$(_ledger_common_dir "$wt")" || common=""
1501
+ # Whether a live pass holds the issue's authority, and since when: true, false, or null when
1502
+ # the ledger names no issue or the lock cannot be read. The issue is the first `issue: ` line.
1503
+ local issue="" line lock got hpid
1504
+ while IFS= read -r line || [[ -n "$line" ]]; do
1505
+ if [[ "$line" == "issue: "* ]]; then issue="${line#issue: }"; break; fi
1506
+ done < "$run"
1507
+ issue="${issue//$'\r'/}"
1508
+ if [[ "$issue" =~ ^[0-9]+$ && -n "$common" ]]; then
1509
+ lock="$(_ledger_pass_lock_in "$common" "$issue")"
1510
+ active=false
1511
+ if [[ -e "$lock" ]]; then
1512
+ got=0; _ledger_authority_held "$lock" || got=$?
1513
+ if [[ "$got" -eq 0 ]]; then active=true; read -r hpid hold_started _ < "$lock" 2>/dev/null || hold_started=""
1514
+ elif [[ "$got" -ne 1 ]]; then active=null; fi
1515
+ fi
1516
+ fi
1517
+ # The gate lock's live holder, when it is a receipt: the worktree and the receipt it runs.
1518
+ local glock gtoken gstate gtag gwt
1519
+ glock="$(_ledger_gate_lock_in "$common")"
1520
+ if [[ -n "$common" && -f "$glock" ]] && read -r gtoken gstate _ gtag gwt 2>/dev/null < "$glock" \
1521
+ && [[ "$gstate" =~ ^(open|closing)$ ]] && _ledger_authority_held "$glock.holders/$gtoken"; then
1522
+ holder=true; holder_wt="$gwt"; holder_tag="$gtag"
1523
+ fi
1524
+ # The receipts on disk: each log's name, exit and command, whether a live process holds its
1525
+ # lock (lock: held, free or unknown), and when it last changed, from which the document tells an open receipt from an
1526
+ # abandoned one. The last two rules are for a receipt an older module wrote with no lock.
1527
+ # Each log adds six fields to the positional arguments, read six at a time. One stat answers
1528
+ # every log's mtime, unless it could not read one, when each log asks on its own. The sixth
1529
+ # says whether the receipt's lock file exists, which the document's receipt rule reads. The
1530
+ # logs the pass script writes beside the receipts are never receipts, so they are not read.
1531
+ local f name exitv cmd rlock lockfile i
1532
+ local -a logs_found=() mtimes=()
1533
+ for f in "$dir"/logs/*.log; do
1534
+ [[ -f "$f" ]] || continue
1535
+ name="${f##*/}"; name="${name%.log}"
1536
+ [[ "$name" != ci && "$name" != park-issue && ! "$name" =~ ^ci-repair-[0-9]+$ ]] || continue
1537
+ logs_found+=("$f")
1538
+ done
1539
+ if [[ "${#logs_found[@]}" -gt 0 ]]; then
1540
+ _ledger_last_lines "${logs_found[@]}"
1541
+ local mline
1542
+ while IFS= read -r mline; do mtimes+=("$mline"); done < <(_ledger_files_mtime "${logs_found[@]}")
1543
+ if [[ "${#mtimes[@]}" -ne "${#logs_found[@]}" ]]; then
1544
+ mtimes=(); for f in "${logs_found[@]}"; do mtimes+=("$(_ledger_file_mtime "$f")"); done
1545
+ fi
1546
+ for ((i = 0; i < ${#logs_found[@]}; i++)); do
1547
+ f="${logs_found[i]}"
1548
+ name="${f##*/}"; name="${name%.log}"
1549
+ exitv=null; [[ "${_ledger_lines[i]}" =~ ^exit=([0-9]+)$ ]] && exitv="${BASH_REMATCH[1]}"
1550
+ cmd=""; IFS= read -r cmd < "$f" 2>/dev/null || true; cmd="${cmd#\$ }"
1551
+ [[ "${mtimes[i]}" =~ ^[0-9]+$ ]] || mtimes[i]=0
1552
+ rlock=unknown
1553
+ got=0; _ledger_receipt_held "$wt" "$name" || got=$?
1554
+ case "$got" in 0) rlock=held ;; 1) rlock=free ;; esac
1555
+ lockfile=false; [[ ! -f "$(_ledger_receipt_lock "$wt" "$name")" ]] || lockfile=true
1556
+ fields+=("$name" "$exitv" "$cmd" "${mtimes[i]}" "$rlock" "$lockfile")
1557
+ done
1558
+ fi
1559
+ # How long each receipt queued for the gate lock and how long its command ran.
1560
+ if [[ -f "$dir/logs/receipt-times.txt" && -r "$dir/logs/receipt-times.txt" ]]; then
1561
+ times_present=true; times_arg=(--rawfile times_raw "$dir/logs/receipt-times.txt")
1562
+ fi
1563
+ # The logs the last gate line names, looked for where the driver has always looked: the
1564
+ # evidence of the last `gate passed` or `gate failed` event, read off the ledger here with
1565
+ # the event grammar's own pattern, and nothing when that line is a failure. Each log adds
1566
+ # three fields to the positional arguments, an empty path standing for one not found. The
1567
+ # pattern is raw_events' capture with the stage and outcome written in, so a change to that
1568
+ # grammar in _ledger_jq_defs changes this line with it.
1569
+ local log path logs="" gline
1570
+ while IFS= read -r gline || [[ -n "$gline" ]]; do
1571
+ gline="${gline%$'\r'}"
1572
+ [[ "$gline" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z\ gate\ (passed|failed)(\ (.*))?$ ]] || continue
1573
+ if [[ "${BASH_REMATCH[1]}" == passed ]]; then logs="${BASH_REMATCH[3]}"; else logs=""; fi
1574
+ done < "$run"
1575
+ local -a gate_paths=()
1576
+ for log in $logs; do
1577
+ # Only a `logs/...` word is a log; the document reports any other word as a malformed line.
1578
+ [[ "$log" == logs/* ]] || continue
1579
+ path=""
1580
+ for path in "$wt/$log" "$ld/$log" "$wt/.kryso/$log" "$wt/.ship-it/$log" "$log"; do [[ -f "$path" ]] && break; path=""; done
1581
+ found+=("$log" "$path")
1582
+ [[ -z "$path" ]] || gate_paths+=("$path")
1583
+ done
1584
+ if [[ "${#found[@]}" -gt 0 ]]; then
1585
+ local -a with_tail=(); local j
1586
+ _ledger_lines=()
1587
+ [[ "${#gate_paths[@]}" -eq 0 ]] || _ledger_last_lines "${gate_paths[@]}"
1588
+ i=0
1589
+ for ((j = 0; j < ${#found[@]}; j += 2)); do
1590
+ if [[ -n "${found[j + 1]}" ]]; then with_tail+=("${found[j]}" "${found[j + 1]}" "${_ledger_lines[i]}"); i=$((i + 1))
1591
+ else with_tail+=("${found[j]}" "" ""); fi
1592
+ done
1593
+ found=("${with_tail[@]}")
1594
+ fi
1595
+ fi
1596
+ # The tree: the three reads and the digest the pass script's fingerprint has always used.
1597
+ local head status diffd fingerprint dirty=false
1598
+ head="$(git -C "$wt" rev-parse HEAD 2>/dev/null)" || head=""
1599
+ status="$(git -C "$wt" status --porcelain 2>/dev/null)"
1600
+ [[ -z "$status" ]] || dirty=true
1601
+ # A clean status leaves diff HEAD nothing to show, so a clean tree's diff digest is the empty
1602
+ # input's and costs no git and no hash process.
1603
+ if [[ -z "$status" ]]; then diffd=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
1604
+ else diffd="$(git -C "$wt" diff HEAD 2>/dev/null | _ledger_digest)"; fi
1605
+ fingerprint="$(printf '%s\n' "$head" "$status" "$diffd" | _ledger_digest)"
1606
+ if [[ "$part" == full ]]; then mtime="$(_ledger_mtime "$dir")"; [[ "$mtime" =~ ^[0-9]+$ ]] || mtime=null; fi
1607
+ # jq still reads options after --args, so the -- ends them: a gate log's last line or a
1608
+ # receipt's command that starts with a dash is a positional argument, not a flag.
1609
+ jq -nc --rawfile text "$run" --arg wt "$wt" --arg ldir "${ld#"$wt"/}" "${cp_arg[@]}" "${times_arg[@]}" --argjson cp_present "$cp_present" --arg cp_path "$cp" \
1610
+ --argjson times_present "$times_present" --argjson nreceipt "${#fields[@]}" --arg head "$head" --argjson dirty "$dirty" \
1611
+ --arg fingerprint "$fingerprint" --argjson mtime "$mtime" --argjson active "$active" --arg hold_started "$hold_started" \
1612
+ --argjson holder "$holder" --arg holder_wt "$holder_wt" --arg holder_tag "$holder_tag" "$defs"'
1613
+ (if $holder then {wt: $holder_wt, tag: $holder_tag} else null end) as $gate_holder
1614
+ | (if $cp_present then (try ($cp_raw | fromjson) catch null) else null end) as $cp_value
1615
+ | (if $cp_present and ($cp_value | type == "object" and has("stage")) then $cp_value else null end) as $checkpoint
1616
+ | (if $cp_present and $checkpoint == null then $cp_path + " is not a valid checkpoint (not a JSON object with a stage)" else "" end) as $checkpoint_error
1617
+ | ($ARGS.positional[:$nreceipt] as $a | [range(0; $a | length; 6) | $a[.:. + 6]
1618
+ | {name: .[0], file: ("logs/" + .[0] + ".log"), exit: (if .[1] == "null" then null else (.[1] | tonumber) end),
1619
+ command: .[2], mtime: (.[3] | tonumber), lock: .[4], lockfile: (.[5] == "true")}]) as $receipts
1620
+ | (if $times_present then (try ([$times_raw | split("\n")[] | capture("^(?<receipt>[A-Za-z0-9][A-Za-z0-9_.:-]*) queued=(?<queued>[0-9]+) ran=(?<ran>[0-9]+)$")
1621
+ | {receipt, queued: (.queued | tonumber), ran: (.ran | tonumber)}]) catch []) else [] end) as $receipt_times
1622
+ | ($ARGS.positional[$nreceipt:] as $a | [range(0; $a | length; 3) | $a[.:. + 3]
1623
+ | if .[1] == "" then {log: .[0], path: null, tail: null} else {log: .[0], path: .[1], tail: .[2]} end]) as $gate_logs
1624
+ | $text | '"$doc" --args -- ${fields[@]+"${fields[@]}"} ${found[@]+"${found[@]}"}
1625
+ }
1626
+
1627
+ _ledger_checkpoint() {
1628
+ local wt="${1:-}" stage="${2:-}" status="${3:-}" detail="${4:-}" ld
1629
+ _ledger_d "$wt" ld
1630
+ [[ -n "$wt" && -f "$ld/run.md" ]] || { _ledger_refuse "checkpoint needs an opened worktree, got '${wt}'"; return 64; }
1631
+ [[ "$stage" =~ ^[A-Za-z][A-Za-z0-9_-]*$ ]] || { _ledger_refuse "checkpoint: the stage is one word, got '$stage'"; return 64; }
1632
+ case "$status" in
1633
+ running|done|parked|failed|interrupted) ;;
1634
+ *) _ledger_refuse "checkpoint: the status is running, done, parked, failed or interrupted, got '$status'"; return 64 ;;
1635
+ esac
1636
+ detail="${detail//$'\n'/ }"
1637
+ local disposition doc tmp out stamp=false
1638
+ [[ -z "${LEDGER_REPAIRS+set}" ]] || stamp=true
1639
+ doc="$(_ledger_doc "$wt" core)" || return 64
1640
+ tmp="$ld/checkpoint.json.tmp"
1641
+ # The PR, the head, the forks and the fingerprint come from LEDGER_PR, LEDGER_HEAD, LEDGER_FORKS
1642
+ # and LEDGER_FINGERPRINT when a sourcing caller set them, and from the document otherwise, each
1643
+ # as `jq -r` prints it, all inside the one jq that writes the file. Forks that are not a whole
1644
+ # number are 0. The disposition is the readers' disposition() in that same jq, printed on the
1645
+ # first line ahead of the file's contents, so writer and readers share one definition and a
1646
+ # checkpoint still starts only its read and its write.
1647
+ # The shell's own error for a write that fails is dropped, so the refusal is the one line.
1648
+ if ! { out="$(jq -rn --argjson doc "$doc" --arg stage "$stage" --arg status "$status" --arg detail "$detail" \
1649
+ --arg pr_in "${LEDGER_PR:-}" --arg head_in "${LEDGER_HEAD:-}" --arg forks_in "${LEDGER_FORKS:-}" --arg fp_in "${LEDGER_FINGERPRINT:-}" --arg at "$(_ledger_now)" \
1650
+ --argjson stamp "$stamp" --arg repairs_in "${LEDGER_REPAIRS:-}" --arg evidence_in "${LEDGER_EVIDENCE:-}" "$(_ledger_jq_defs)"'
1651
+ def raw: if type == "string" then . else tojson end;
1652
+ disposition($stage; $status; ($detail | word)) as $disposition
1653
+ | (if $pr_in != "" then $pr_in else ($doc.pr // "none" | raw) end) as $pr
1654
+ | (if $head_in != "" then $head_in else ($doc.tree.head // "none" | raw) end) as $head
1655
+ | ((if $forks_in != "" then $forks_in else ($doc.checkpoint.forks // 0 | raw) end)
1656
+ | if test("^[0-9]+$") then tonumber else 0 end) as $forks
1657
+ | $disposition, ({engine: ($doc.engine // "ship-it"), issue: ($doc.header.issue // ""), branch: ($doc.header.branch // ""),
1658
+ base: ($doc.header.base.name // ""), base_sha: ($doc.header.base.sha // ""), profile: ($doc.header.profile // ""),
1659
+ stage: $stage, status: $status, detail: $detail, disposition: $disposition,
1660
+ head: $head, pr: $pr, forks: $forks, fingerprint: (if $fp_in != "" then $fp_in else ($doc.tree.fingerprint // "") end), updated_at: $at}
1661
+ + (($doc.checkpoint // {}) | with_entries(select(.key == "repairs" or .key == "evidence")))
1662
+ + ((if $stamp then (try ($repairs_in | fromjson) catch null) else null end) as $r
1663
+ | if $r != null then {repairs: $r, evidence: (if $evidence_in == "" then null else $evidence_in end)} else {} end))')" \
1664
+ && [[ "$out" == *$'\n'* ]] && disposition="${out%%$'\n'*}" && printf '%s\n' "${out#*$'\n'}" > "$tmp" \
1665
+ && mv "$tmp" "$ld/checkpoint.json"; } 2>/dev/null; then
1666
+ rm -f "$tmp" 2>/dev/null; _ledger_refuse "checkpoint: cannot write $ld/checkpoint.json"; return 64
1667
+ fi
1668
+ # The disposition handed back to a park: _ledger_park declares _ledger_want_disposition and
1669
+ # _ledger_disposition local and sets the first, so this call, which bash's dynamic scope lets
1670
+ # see both, leaves the disposition it writes in the second, and the park prints that one
1671
+ # rather than asking the table again. They are variables and not an argument because the verb
1672
+ # `ledger checkpoint` takes positional arguments only, and an output argument would change it;
1673
+ # a checkpoint called from anywhere else sees neither set and leaves them alone.
1674
+ [[ -z "${_ledger_want_disposition:-}" ]] || _ledger_disposition="$disposition"
1675
+ _ledger_event "$wt" "$stage" checkpoint "$status${detail:+ $detail} ($disposition)"
1676
+ }
1677
+
1678
+ _ledger_park() {
1679
+ local wt="${1:-}" stage="${2:-}" word="${3:-}"
1680
+ [[ $# -ge 3 && -n "$word" ]] || { _ledger_refuse "park needs <worktree> <stage> <word> [evidence...]"; return 64; }
1681
+ shift 3
1682
+ local evidence="$*" detail open ld doc
1683
+ _ledger_d "$wt" ld
1684
+ detail="$word${evidence:+ $evidence}"
1685
+ # A pass never parks while one of its own receipts is open: its exit may change the outcome.
1686
+ # Open here is read's open with a live holder of the receipt's own lock, never its guess for a
1687
+ # log no receipt locked, such as a CI log a pass script leaves beside the receipts.
1688
+ if [[ -n "$wt" && -f "$ld/run.md" ]]; then
1689
+ doc="$(_ledger_read "$wt")"
1690
+ open="$(jq -r '[.receipts[] | select(.state == "open" and .lock == "held") | .file] | first // empty' <<< "$doc")"
1691
+ if [[ -n "$open" ]]; then
1692
+ echo "ledger: park refuses: $open is still running. Wait for it with $(_ledger_wait_hint "$wt" "$open")" >&2
1693
+ return 75
1694
+ fi
1695
+ # Nor while its CI wait is open, for the same reason (#397).
1696
+ if open="$(_ledger_ci_open "$wt")"; then
1697
+ echo "ledger: park refuses: the CI wait on $open is still open. Wait for it with $(_ledger_ci_hint "$wt" "$open")" >&2
1698
+ return 75
1699
+ fi
1700
+ # A ci-timeout park stands on a wait that ran out on the head the worktree holds: its timeout
1701
+ # line, or a pending line whose bound has passed. A pass that ends its turn without one never
1702
+ # showed that the checks were still pending at the bound, so it waits first (#548). A wait on
1703
+ # an older head says nothing about this one, and a green or red read is no timeout at all.
1704
+ if [[ "$word" == ci-timeout ]]; then
1705
+ local _ci_state _ci_head _ci_started _ci_bound _ci_pr _ci_what head pr
1706
+ _ledger_ci_wait "$wt"
1707
+ head="$(git -C "$wt" rev-parse -q --verify HEAD 2>/dev/null)"
1708
+ if [[ ( "$_ci_state" != pending && "$_ci_state" != timeout ) || -z "$head" || "$_ci_head" != "$head" ]]; then
1709
+ pr="$(jq -r '.pr // "" | if type == "string" then . else tojson end' <<< "$doc")"
1710
+ [[ -n "$pr" && "$pr" != none ]] || pr="$_ci_pr"
1711
+ echo "ledger: park refuses: $stage ci-timeout needs a CI wait on ${head:0:12} that ran out, and the ledger has none. Wait with $(_ledger_ci_hint "$wt" "${pr:-<pr>}")" >&2
1712
+ return 75
1713
+ fi
1714
+ # With no evidence of its own, the park names what the wait that ran out left pending,
1715
+ # from its timeout line or, when no call came after the bound ran out, its last pending one.
1716
+ [[ -n "$evidence" ]] || evidence="after ${_ci_bound}s on $_ci_pr head=$_ci_head: $_ci_what"
1717
+ detail="$word${evidence:+ $evidence}"
1718
+ fi
1719
+ fi
1720
+ # _ledger_want_disposition asks _ledger_checkpoint to leave the disposition it writes in
1721
+ # _ledger_disposition, read below. Both are local here, so bash's dynamic scope shows them to
1722
+ # the calls this park makes and they end with it; only _ledger_checkpoint reads or writes them,
1723
+ # and its comment says why they are not an argument.
1724
+ local _LEDGER_AT _ledger_want_disposition=1 _ledger_disposition=""; _LEDGER_AT="$(_ledger_clock)"
1725
+ _ledger_checkpoint "$wt" "$stage" parked "$detail" || return $?
1726
+ _ledger_event "$wt" "$stage" parked "$detail" || return $?
1727
+ # The checkpoint's table read takes the detail's first word, which is the word unless the word
1728
+ # itself holds a space, a tab or a newline; such a word asks the table again, as it always did.
1729
+ if [[ "$word" == *[[:space:]]* ]]; then _ledger_table "$stage" "$word"; else printf '%s\n' "$_ledger_disposition"; fi
1730
+ }
1731
+
1732
+ # interrupt: a deadline ran out on the pass. The stage is where the document places the pass
1733
+ # now, the checkpoint is rewritten there as interrupted with the consumed allowance, the
1734
+ # allowance and whether its process tree was confirmed stopped, and the ledger gets the same
1735
+ # as one line, so a resume re-enters that stage and a reader knows why it stopped.
1736
+ _ledger_interrupt() {
1737
+ local wt="${1:-}" consumed="${2:-}" allowance="${3:-}" stopped="${4:-}"
1738
+ [[ $# -ge 4 ]] || { _ledger_refuse "interrupt needs <worktree> <consumed> <allowance> <stopped> [evidence...]"; return 64; }
1739
+ shift 4
1740
+ local ld; _ledger_d "$wt" ld
1741
+ [[ -n "$wt" && -f "$ld/run.md" ]] || { _ledger_refuse "interrupt needs an opened worktree, got '${wt}'"; return 64; }
1742
+ [[ "$consumed" =~ ^[0-9]+$ && "$allowance" =~ ^[0-9]+$ ]] \
1743
+ || { _ledger_refuse "interrupt: the consumed allowance and the allowance are whole seconds, got '$consumed' and '$allowance'"; return 64; }
1744
+ [[ "$stopped" =~ ^[a-z]+$ ]] \
1745
+ || { _ledger_refuse "interrupt: the stop is one lowercase word, such as confirmed or unconfirmed, got '$stopped'"; return 64; }
1746
+ local stage detail evidence="$*"
1747
+ stage="$(_ledger_doc "$wt" core | jq -r '.stage.name // "build"')"
1748
+ [[ "$stage" =~ ^[A-Za-z][A-Za-z0-9_-]*$ ]] || stage=build
1749
+ detail="deadline consumed=${consumed}s allowance=${allowance}s stopped=$stopped${evidence:+ $evidence}"
1750
+ local _LEDGER_AT; _LEDGER_AT="$(_ledger_clock)"
1751
+ _ledger_checkpoint "$wt" "$stage" interrupted "$detail" || return $?
1752
+ _ledger_event "$wt" "$stage" interrupted "$detail"
1753
+ }
1754
+
1755
+ # hold: the command runs in a subshell that holds the issue's authority on descriptor 6, which
1756
+ # the command and everything it starts inherit. Under a holder of the same issue, which the
1757
+ # environment names, the command is that holder's descendant and runs in place. Without flock
1758
+ # or lockf the command runs unheld, and says so, the way a receipt does. Once it has the lock it
1759
+ # checks that the path still names the file it locked: a drop between its open and its lock
1760
+ # removed that file, and a lock on a file no path names is no authority, so it opens again. A
1761
+ # host where the check cannot read the descriptor keeps the lock it took, as before the check.
1762
+ # drop, active and locked take the lock for a moment to read it, so a held lock may be one of
1763
+ # them: hold waits up to two seconds for it, _LEDGER_HOLD_WAIT for a suite, before it refuses.
1764
+ _ledger_hold() {
1765
+ local repo="${1:-}" issue="${2:-}" lock
1766
+ [[ $# -ge 3 && -n "$repo" && -d "$repo" ]] || { _ledger_refuse "hold needs <repo> <issue> <command...>"; return 64; }
1767
+ [[ "$issue" =~ ^[0-9]+$ ]] || { _ledger_refuse "hold: the issue is a number, got '$issue'"; return 64; }
1768
+ shift 2
1769
+ lock="$(_ledger_pass_lock "$repo" "$issue")" || { _ledger_refuse "hold: $repo is not in a git repository"; return 64; }
1770
+ if [[ "${KRYSO_PASS_HOLD:-}" == "$lock" ]] && _ledger_authority_held "$lock"; then "$@"; return $?; fi
1771
+ (
1772
+ tries=0
1773
+ while :; do
1774
+ got=0
1775
+ { exec 6>> "$lock"; } 2>/dev/null || { echo "ledger: #$issue: cannot open $lock" >&2; exit 75; }
1776
+ _ledger_lock_fd 6 "${_LEDGER_HOLD_WAIT:-2}" || got=$?
1777
+ names=0
1778
+ [[ "$got" -ne 0 ]] || _ledger_names 6 "$lock" || names=$?
1779
+ [[ "$names" -eq 1 ]] || break
1780
+ exec 6>&-
1781
+ (( ++tries < 10 )) || { echo "ledger: #$issue: $lock was removed under each of 10 locks, so this pass does not start" >&2; exit 75; }
1782
+ done
1783
+ case "$got" in
1784
+ 0) _ledger_current_pid hpid || hpid=unknown
1785
+ printf '%s %s %s\n' "$hpid" "$(_ledger_now)" "${1##*/}" >| "$lock" 2>/dev/null || true
1786
+ export KRYSO_PASS_HOLD="$lock" ;;
1787
+ 1) holder="$(head -1 "$lock" 2>/dev/null)"
1788
+ echo "ledger: a live pass holds #$issue${holder:+ ($holder)}, so this one does not start" >&2
1789
+ exit 75 ;;
1790
+ 2) echo "ledger: no flock or lockf here, so #$issue runs without its pass authority" >&2 ;;
1791
+ *) echo "ledger: #$issue: cannot take $lock" >&2; exit 75 ;;
1792
+ esac
1793
+ "$@"
1794
+ )
1795
+ }
1796
+
1797
+ # drop: remove an issue's pass lock file, which only a holder of its lock may do. It takes the
1798
+ # lock on descriptor 6, refuses with 75 while a live process holds it, and removes the file while
1799
+ # it holds the lock, and only when the path still names the file it locked. A file read as
1800
+ # unheld and then unlinked could be locked in between by a pass, and the next pass would lock a
1801
+ # new file at the same path, so two would hold one issue; holding the lock to remove it, with
1802
+ # hold's own check of the path, is what stops that. No file is status 0, and so is one another
1803
+ # drop removed first; a new file a pass made at the path since is opened and locked in its turn.
1804
+ # Without flock or lockf, or where the check cannot read the descriptor, nothing is removed: 3.
1805
+ _ledger_drop() {
1806
+ local repo="${1:-}" issue="${2:-}" lock
1807
+ [[ $# -eq 2 && -n "$repo" && -d "$repo" ]] || { _ledger_refuse "drop needs <repo> <issue>"; return 64; }
1808
+ [[ "$issue" =~ ^[0-9]+$ ]] || { _ledger_refuse "drop: the issue is a number, got '$issue'"; return 64; }
1809
+ lock="$(_ledger_pass_lock "$repo" "$issue")" || { _ledger_refuse "drop: $repo is not in a git repository"; return 64; }
1810
+ [[ -e "$lock" ]] || return 0
1811
+ (
1812
+ for _ in 1 2 3 4 5 6 7 8 9 10; do
1813
+ got=0 names=0
1814
+ { exec 6>> "$lock"; } 2>/dev/null || { echo "ledger: #$issue: cannot open $lock" >&2; exit 3; }
1815
+ _ledger_lock_fd 6 try || got=$?
1816
+ case "$got" in
1817
+ 0) ;;
1818
+ 1) echo "ledger: a live pass holds #$issue, so its lock file stays" >&2; exit 75 ;;
1819
+ 2) echo "ledger: no flock or lockf here, so #$issue's lock file stays" >&2; exit 3 ;;
1820
+ *) echo "ledger: #$issue: cannot take $lock" >&2; exit 3 ;;
1821
+ esac
1822
+ _ledger_names 6 "$lock" || names=$?
1823
+ case "$names" in
1824
+ 0) rm -f "$lock" && exit 0; echo "ledger: #$issue: cannot remove $lock" >&2; exit 3 ;;
1825
+ 2) echo "ledger: #$issue: cannot tell whether $lock is the file it locked, so it stays" >&2; exit 3 ;;
1826
+ esac
1827
+ [[ -e "$lock" ]] || exit 0
1828
+ exec 6>&-
1829
+ done
1830
+ echo "ledger: #$issue: $lock was made again under each of 10 locks, so it stays" >&2
1831
+ exit 3
1832
+ )
1833
+ }
1834
+
1835
+ _ledger_active() {
1836
+ local repo="${1:-}" issue="${2:-}" lock got=0
1837
+ [[ -n "$repo" && -d "$repo" ]] || { _ledger_refuse "active needs <repo> <issue>"; return 64; }
1838
+ [[ "$issue" =~ ^[0-9]+$ ]] || { _ledger_refuse "active: the issue is a number, got '$issue'"; return 64; }
1839
+ lock="$(_ledger_pass_lock "$repo" "$issue")" || return 3
1840
+ [[ -e "$lock" ]] || return 1
1841
+ _ledger_authority_held "$lock" || got=$?
1842
+ [[ "$got" -eq 0 ]] || return "$got"
1843
+ head -1 "$lock" 2>/dev/null
1844
+ return 0
1845
+ }
1846
+
1847
+ # inherited: the caller's environment names the issue's authority, handed down by hold, and a
1848
+ # live process still holds it, so the caller is that holder's descendant.
1849
+ _ledger_inherited() {
1850
+ local repo="${1:-}" issue="${2:-}" lock
1851
+ [[ -n "$repo" && -d "$repo" ]] || { _ledger_refuse "inherited needs <repo> <issue>"; return 64; }
1852
+ [[ "$issue" =~ ^[0-9]+$ ]] || { _ledger_refuse "inherited: the issue is a number, got '$issue'"; return 64; }
1853
+ lock="$(_ledger_pass_lock "$repo" "$issue")" || return 1
1854
+ [[ "${KRYSO_PASS_HOLD:-}" == "$lock" ]] && _ledger_authority_held "$lock"
1855
+ }
1856
+
1857
+ # handoff: a later shift takes the worktree over from the shift that owned it, under either
1858
+ # engine. The line carries what the next engine needs to keep the limits: the stage it resumes
1859
+ # at, where it came from and goes to, the reconciliations used of three, the forks and the
1860
+ # allowance consumed, read off the document unless the caller names the stage or the allowance,
1861
+ # then the caller's own keys, such as the profile the handoff keeps. The header is never rewritten, so
1862
+ # the engine that cut the tree stays on it. The worktree's copy of the module is refreshed,
1863
+ # because the next engine may be one that runs the copy for verbs an older one lacks.
1864
+ _ledger_handoff() {
1865
+ local wt="${1:-}" engine="${2:-}" to_shift="${3:-}"
1866
+ [[ $# -ge 3 ]] || { _ledger_refuse "handoff needs <worktree> <engine> <shift> [key=value...]"; return 64; }
1867
+ shift 3
1868
+ local ld; _ledger_d "$wt" ld
1869
+ [[ -n "$wt" && -f "$ld/run.md" ]] || { _ledger_refuse "handoff: no ledger at ${wt:-<no worktree>}/${ld#"$wt"/}/run.md"; return 64; }
1870
+ [[ "$engine" == ship-it || "$engine" == script ]] || { _ledger_refuse "handoff: the engine is ship-it or script, got '$engine'"; return 64; }
1871
+ [[ "$to_shift" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || { _ledger_refuse "handoff: a shift id is letters, digits, dots, dashes and underscores, got '$to_shift'"; return 64; }
1872
+ local kv key value consumed="" stage="" extra=""
1873
+ for kv in "$@"; do
1874
+ key="${kv%%=*}"; value="${kv#*=}"
1875
+ [[ "$kv" == *=* && "$key" =~ ^[a-z_]+$ && "$value" =~ ^[^[:space:]]+$ ]] \
1876
+ || { _ledger_refuse "handoff takes key=value arguments with one-word values, got '$kv'"; return 64; }
1877
+ if [[ "$key" == consumed ]]; then
1878
+ [[ "$value" =~ ^[0-9]+$ ]] || { _ledger_refuse "handoff: consumed is whole seconds, got '$value'"; return 64; }
1879
+ consumed="${value}s"
1880
+ elif [[ "$key" == stage ]]; then
1881
+ [[ "$value" =~ ^[A-Za-z][A-Za-z0-9_-]*$ ]] || { _ledger_refuse "handoff: the stage is one word, got '$value'"; return 64; }
1882
+ stage="$value"
1883
+ else extra+=" $key=$value"; fi
1884
+ done
1885
+ local doc line
1886
+ doc="$(_ledger_doc "$wt" core)" || return 64
1887
+ line="$(jq -r --arg to "$engine/$to_shift" --arg consumed "$consumed" --arg stage "$stage" '
1888
+ "stage=\(if $stage != "" then $stage else .stage.name // "claim" end) from=\(.owner.engine // .engine)/\(.owner.shift // "none") to=\($to)"
1889
+ + " reconciliations=\(.reconciliations.used)/\(.reconciliations.cap) forks=\(.checkpoint.forks // 0)"
1890
+ + " consumed=\(if $consumed != "" then $consumed elif .interruption.consumed != null then "\(.interruption.consumed)s" else "unknown" end)"' <<< "$doc")" \
1891
+ || { _ledger_refuse "handoff: cannot read $ld/run.md"; return 64; }
1892
+ _ledger_event "$wt" shift handoff "$line$extra" || return $?
1893
+ [[ "${BASH_SOURCE[0]}" -ef "$ld/ledger.sh" ]] || cp "${BASH_SOURCE[0]}" "$ld/ledger.sh" 2>/dev/null || true
1894
+ }
1895
+
1896
+ # authorized: the one rule both engines apply before continuing a ledger. A handoff names the
1897
+ # engine and the shift that may continue the worktree: no other shift, and no other engine, the
1898
+ # one that wrote the header included. A person outside any shift, who names none, may continue
1899
+ # what was handed to their engine, because the pass authority already stops a second live pass.
1900
+ # Without a handoff, the engine that wrote the header may, as it always could. Why not is one
1901
+ # line on stdout.
1902
+ _ledger_authorized() {
1903
+ local wt="${1:-}" engine="${2:-}" shift_id="${3:-}" doc why
1904
+ [[ -n "$wt" && -d "$wt" && -n "$engine" ]] || { _ledger_refuse "authorized needs <worktree> <engine> [shift]"; return 64; }
1905
+ doc="$(_ledger_doc "$wt" core)" || return 64
1906
+ why="$(jq -r --arg e "$engine" --arg s "$shift_id" '
1907
+ if .ledger != true then "no ledger at \(.dir)/run.md"
1908
+ elif .owner != null and .owner.via == "handoff" then
1909
+ (if .owner.engine == $e and (.owner.shift == $s or $s == "") then "" else "handed off to \(.owner.engine) in shift \(.owner.shift)" end)
1910
+ elif .engine == $e then ""
1911
+ else "another engine'"'"'s (engine: \(.engine)), and no handoff names \($e)" end' <<< "$doc")"
1912
+ [[ -n "$why" ]] || return 0
1913
+ printf '%s\n' "$why"
1914
+ return 1
1915
+ }
1916
+
1917
+ # attempt: one reconciliation attempt, numbered from what the document already counts, so an
1918
+ # attempt after a handoff from the other engine carries on the same count. Past three it writes
1919
+ # nothing and says so, status 1: the cap is the issue's and never resets.
1920
+ _ledger_attempt() {
1921
+ local wt="${1:-}" used n ld
1922
+ _ledger_d "$wt" ld
1923
+ [[ $# -ge 2 ]] || { _ledger_refuse "attempt needs <worktree> <evidence...>"; return 64; }
1924
+ shift
1925
+ [[ -n "${*// /}" ]] || { _ledger_refuse "attempt: the evidence is empty"; return 64; }
1926
+ [[ -n "$wt" && -f "$ld/run.md" ]] || { _ledger_refuse "attempt: no ledger at ${wt:-<no worktree>}/${ld#"$wt"/}/run.md, open it first"; return 64; }
1927
+ used="$(_ledger_doc "$wt" core | jq -r '.reconciliations.used')"
1928
+ [[ "$used" =~ ^[0-9]+$ ]] || { _ledger_refuse "attempt: cannot read the reconciliations used in $wt"; return 64; }
1929
+ n=$(( used + 1 ))
1930
+ if [[ "$n" -gt 3 ]]; then echo "ledger: the reconciliation cap is spent: $used/3 used" >&2; return 1; fi
1931
+ _ledger_event "$wt" reconcile attempt "$n/3 $*" || return $?
1932
+ printf '%s/3\n' "$n"
1933
+ }
1934
+
1935
+ # archive: the run's record once its worktree goes. The worktree's .kryso/pass/ is copied whole to
1936
+ # <repo>/.claude/kryso/shipped/<worktree name>-<time>/, the repo the main checkout unless
1937
+ # the caller names another, and .claude/kryso/ is excluded the way .kryso/pass/ is. The copy
1938
+ # keeps the worktree's layout, so every verb and reader that takes a worktree takes the copy's
1939
+ # directory, and the lines written after the worktree is removed land in it. The time is the
1940
+ # module's clock, so the caller's command holds no $(...) and keeps its allow rule. An existing
1941
+ # copy is never written over, and a copy that fails is removed rather than left half made.
1942
+ _ledger_archive() {
1943
+ local wt="${1:-}" repo="${2:-}" name stamp dir ld state rel parent
1944
+ _ledger_d "$wt" ld
1945
+ [[ -n "$wt" && -f "$ld/run.md" ]] || { _ledger_refuse "archive: no ledger at ${wt:-<no worktree>}/${ld#"$wt"/}/run.md"; return 64; }
1946
+ if [[ -z "$repo" ]]; then
1947
+ repo="$(git -C "$wt" worktree list --porcelain 2>/dev/null | sed -n '1s/^worktree //p')"
1948
+ [[ -n "$repo" ]] || { _ledger_refuse "archive: $wt is in no git repository, so name the repo"; return 64; }
1949
+ fi
1950
+ [[ -d "$repo" ]] || { _ledger_refuse "archive: the repo $repo is not a directory"; return 64; }
1951
+ name="${wt%/}"; name="${name##*/}"
1952
+ stamp="$(_ledger_now)"
1953
+ _ledger_migrate_state "$repo" .claude/ship-loop .claude/kryso \
1954
+ || { _ledger_refuse "archive: cannot move $repo/.claude/ship-loop to $repo/.claude/kryso"; return 64; }
1955
+ _ledger_pick "$repo/.claude/kryso" "$repo/.claude/ship-loop" state
1956
+ dir="$state/shipped/$name-${stamp//[-:]/}"
1957
+ [[ ! -e "$dir" ]] || { _ledger_refuse "archive refuses: $dir exists, and a copy is never written over"; return 64; }
1958
+ _ledger_exclude "$repo" '.claude/kryso/'
1959
+ _ledger_exclude "$repo" '.claude/ship-loop/'
1960
+ # The copy keeps the ledger directory's place: .kryso/pass, or the old .kryso or .ship-it, so its
1961
+ # readers pick it as they pick the worktree's, and the configuration beside .kryso/pass stays.
1962
+ rel="${ld#"$wt"/}"; parent="$dir"
1963
+ [[ "$rel" != */* ]] || parent="$dir/${rel%/*}"
1964
+ if ! { mkdir -p "$parent" && cp -R "$ld" "$parent/"; } 2>/dev/null; then
1965
+ rm -rf "$dir" 2>/dev/null
1966
+ _ledger_refuse "archive cannot copy $ld to $dir"; return 64
1967
+ fi
1968
+ printf '%s\n' "$dir"
1969
+ }
1970
+
1971
+ # lock: the kernel lock on a file, taken on a descriptor of the shell that sources this module,
1972
+ # so the shell and every process it starts hold it until the last of them exits. A driver holds
1973
+ # its shift this way, and a later driver reads it with `locked` to confirm that shift stopped.
1974
+ # Run as a command it would hold nothing past its own exit, so it is a refusal. Without flock or
1975
+ # lockf the shell runs unlocked, says so, and `locked` answers 3.
1976
+ _ledger_lock() {
1977
+ local path="${1:-}" fd="${2:-}" got=0
1978
+ ! _ledger_run || { _ledger_refuse "lock holds the file for the shell that sources this module, so run as a command it holds nothing"; return 64; }
1979
+ [[ -n "$path" && "$fd" =~ ^[3-9]$ ]] || { _ledger_refuse "lock needs <path> <descriptor 3 to 9>"; return 64; }
1980
+ { eval "exec $fd>> \"\$path\""; } 2>/dev/null || { _ledger_refuse "lock cannot open $path"; return 64; }
1981
+ _ledger_lock_fd "$fd" try || got=$?
1982
+ case "$got" in
1983
+ 0) return 0 ;;
1984
+ 1) eval "exec $fd>&-"; echo "ledger: a live process holds $path" >&2; return 75 ;;
1985
+ 2) echo "ledger: no flock or lockf here, so $path is not locked" >&2; return 0 ;;
1986
+ *) eval "exec $fd>&-"; _ledger_refuse "lock cannot take $path"; return 64 ;;
1987
+ esac
1988
+ }
1989
+
1990
+ _ledger_locked() {
1991
+ local path="${1:-}" got=0
1992
+ [[ -n "$path" ]] || { _ledger_refuse "locked needs <path>"; return 64; }
1993
+ [[ -e "$path" ]] || return 1
1994
+ _ledger_authority_held "$path" || got=$?
1995
+ return "$got"
1996
+ }
1997
+
1998
+ # _ledger_isolated <repo>: status 0, with the pid on stdout, while `kryso --isolate docker` runs a
1999
+ # shift or a pass on the repository. The kryso planner writes kryso-isolated.json in the common
2000
+ # git directory with the pid of the docker client it hands over to. flock taken inside the
2001
+ # container lives in Docker Desktop's VM, where the host cannot see it (ADR 0039), so a live
2002
+ # docker client at that pid is the host's only sign the run is going on. A file younger than ten
2003
+ # seconds counts while its pid lives, because the launcher is still about to exec docker. Status 1
2004
+ # when none runs, removing a stale file unless KRYSO_READ_ONLY is 1, and always inside the
2005
+ # container (KRYSO_ISOLATED), whose run is the one the file names. kryso cleanup holds the same
2006
+ # file for the length of its removals, with "holder": "cleanup": status 2 and its pid while that
2007
+ # process lives and runs cleanup.js, which is no isolated run, so a host driver carries on and only
2008
+ # another cleanup or an isolated run keeps off. A dead cleanup's file is stale like any other.
2009
+ _ledger_isolated() {
2010
+ local repo="${1:-}" c file pid="" args age why holder="" who=""
2011
+ [[ -n "$repo" && -d "$repo" ]] || { _ledger_refuse "isolated needs <repo>"; return 64; }
2012
+ [[ -z "${KRYSO_ISOLATED:-}" ]] || return 1
2013
+ c="$(_ledger_common_dir "$repo")" || return 1
2014
+ file="$c/kryso-isolated.json"
2015
+ [[ -f "$file" ]] || return 1
2016
+ { read -r pid; read -r holder; } < <(jq -r '(.pid // ""), (.holder // "docker")' "$file" 2>/dev/null) || true
2017
+ [[ "$holder" != cleanup ]] || who="kryso cleanup's "
2018
+ why="${who}pid $pid is not running"
2019
+ [[ -n "$pid" ]] || why="it names no pid"
2020
+ if [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
2021
+ args="$(ps -o args= -p "$pid" 2>/dev/null)"
2022
+ if [[ "$holder" == cleanup ]]; then
2023
+ # One word of the command line names cleanup.js, the script bin/kryso execs.
2024
+ if [[ " $args " == *"/cleanup.js "* || " $args " == *" cleanup.js "* ]]; then printf '%s\n' "$pid"; return 2; fi
2025
+ why="pid $pid is no kryso cleanup"
2026
+ else
2027
+ args="${args%% *}"
2028
+ age=$(( $(_ledger_epoch) - $(_ledger_file_mtime "$file" || echo 0) ))
2029
+ if [[ "${args##*/}" == docker || "$age" -lt 10 ]]; then printf '%s\n' "$pid"; return 0; fi
2030
+ why="pid $pid is no docker client"
2031
+ fi
2032
+ fi
2033
+ # A read-only caller, such as a dry run kryso doctor starts, changes nothing, so the stale
2034
+ # file is named on stderr and stays for a person to remove.
2035
+ if [[ "${KRYSO_READ_ONLY:-}" == 1 ]]; then
2036
+ echo "ledger: $file is stale: $why, and KRYSO_READ_ONLY leaves it in place" >&2
2037
+ return 1
2038
+ fi
2039
+ rm -f "$file"
2040
+ return 1
2041
+ }
2042
+
2043
+ # _ledger_axis_section <review> <axis>: the lines under the axis's heading in a review.
2044
+ _ledger_axis_section() { awk -v h="## $2" '$0 == h { f = 1; next } /^## (Standards|Spec|Summary|Triage)$/ { f = 0 } f' "$1"; }
2045
+ # _ledger_axis_quotes: every backtick-quoted string of the section on stdin, inline or fenced.
2046
+ _ledger_axis_quotes() {
2047
+ awk '
2048
+ /^```/ { fence = !fence; next }
2049
+ fence { if (length($0)) print; next }
2050
+ { s = $0; while (match(s, /`[^`]+`/)) { print substr(s, RSTART + 1, RLENGTH - 2); s = substr(s, RSTART + RLENGTH) } }
2051
+ '
2052
+ }
2053
+ # _ledger_triage_rows <review> [outcome]: the triage table's rows, or the ones with that outcome.
2054
+ # The pass script reads the table through this too, so the rows it counts are the rows it reads.
2055
+ _ledger_triage_rows() { grep -E "^\| [0-9]+ \| (Standards|Spec) \|${2:+.*\| $2 \|}" "$1"; }
2056
+ # _ledger_triage <wt> <review> <diff>: the checks a review's artefact is held to, the build's and
2057
+ # a repair's, in the context that wrote it and again by the pass script after it (ADR 0057). Each
2058
+ # axis that is not void quotes, in backticks inline or fenced, one string the saved diff holds;
2059
+ # the table has one row for each finding the summary counts, `<axis>: 1 finding` included, and
2060
+ # every row an outcome. A failed check is a refusal whose text is the reason the pass script
2061
+ # records. A void axis, or one with no spec, has nothing to quote: it is printed as
2062
+ # `<axis> (<the void line>)` once every check passed.
2063
+ _ledger_triage() {
2064
+ local wt="${1:-}" review="${2:-}" diff="${3:-}" axis section quote found n findings=0 rows untriaged missing=""
2065
+ [[ -n "$wt" && -d "$wt" && -n "$review" && -n "$diff" ]] || { _ledger_refuse "triage needs <worktree> <review> <diff>"; return 64; }
2066
+ [[ -s "$review" ]] || { _ledger_refuse "review-artefact (${review#"$wt/"} is missing or empty)"; return 64; }
2067
+ for axis in Standards Spec; do
2068
+ section="$(_ledger_axis_section "$review" "$axis")"
2069
+ if grep -qiE '^(void|no spec available)' <<< "$section" || grep -qiE "^$axis: (void|no spec)" "$review"; then
2070
+ missing+="$axis ($(grep -iE '^(void|no spec available)' <<< "$section" | head -1 | cut -c1-80))"$'\n'
2071
+ continue
2072
+ fi
2073
+ found=0
2074
+ while IFS= read -r quote; do
2075
+ [[ -n "$quote" ]] || continue
2076
+ if grep -qF -- "$quote" "$diff" 2>/dev/null; then found=1; break; fi
2077
+ done < <(_ledger_axis_quotes <<< "$section")
2078
+ [[ "$found" -eq 1 ]] || { _ledger_refuse "review-quote ($axis quotes nothing that is in the diff)"; return 64; }
2079
+ done
2080
+ for axis in Standards Spec; do
2081
+ n="$(grep -E "^$axis: [0-9]+ findings?([ ,.]|\$)" "$review" | tail -1 | grep -oE '[0-9]+' | head -1)"
2082
+ findings=$(( findings + ${n:-0} ))
2083
+ done
2084
+ rows="$(_ledger_triage_rows "$review" | grep -c .)"
2085
+ untriaged="$(_ledger_triage_rows "$review" | grep -vcE '\| (fixed|deferred|rejected) \|')"
2086
+ [[ "$rows" -eq "$findings" ]] || { _ledger_refuse "triage-rows ($rows rows for $findings findings)"; return 64; }
2087
+ [[ "$untriaged" -eq 0 ]] || { _ledger_refuse "triage-rows ($untriaged row(s) with no outcome)"; return 64; }
2088
+ printf '%s' "$missing"
2089
+ }
2090
+
2091
+ _ledger_worktree() {
2092
+ local repo="${1:-}" issue="${2:-}" dir ld
2093
+ [[ -n "$repo" && -d "$repo" && -n "$issue" ]] || { _ledger_refuse "worktree needs <repo> <issue>"; return 64; }
2094
+ for dir in "$repo"/.claude/worktrees/*-"$issue"; do
2095
+ _ledger_d "$dir" ld
2096
+ [[ -d "$dir" && -f "$ld/run.md" ]] || continue
2097
+ [[ "$(sed -nE 's/^issue: //p' "$ld/run.md" | head -1 | tr -d '\r')" == "$issue" ]] || continue
2098
+ printf '%s\n' "${dir#./}"
2099
+ return 0
2100
+ done
2101
+ return 1
2102
+ }
2103
+
2104
+ _ledger_worktrees() {
2105
+ local repo="${1:-}" wt issue ld
2106
+ [[ -n "$repo" && -d "$repo" ]] || { _ledger_refuse "worktrees needs <repo>"; return 64; }
2107
+ while IFS= read -r wt; do
2108
+ _ledger_d "$wt" ld
2109
+ [[ -n "$wt" && -f "$ld/run.md" ]] || continue
2110
+ issue="$(sed -nE 's/^issue: //p' "$ld/run.md" | head -1 | tr -d '\r')"
2111
+ printf '%s %s\n' "$wt" "$issue"
2112
+ done < <(git -C "$repo" worktree list --porcelain 2>/dev/null | sed -n 's/^worktree //p' | tail -n +2)
2113
+ return 0
2114
+ }
2115
+
2116
+ # ---- the one function ----------------------------------------------------------------------
2117
+
2118
+ ledger() {
2119
+ local verb="${1:-}"
2120
+ [[ $# -eq 0 ]] || shift
2121
+ case "$verb" in
2122
+ # The verbs that write to a worktree's ledger migrate it first. The rest only read.
2123
+ open|event|receipt|wait|ci|checkpoint|park|interrupt|handoff|attempt|archive)
2124
+ if [[ -n "${1:-}" && "$1" != --wait ]] && ! _ledger_migrate_wt "$1"; then
2125
+ _ledger_refuse "$verb: cannot move $1/.ship-it to $1/.kryso, so it wrote nothing"; return 64
2126
+ fi
2127
+ "_ledger_$verb" "$@" ;;
2128
+ read|text|triage|worktree|worktrees|hold|drop|active|inherited|authorized|lock|locked|isolated) "_ledger_$verb" "$@" ;;
2129
+ -h|--help|help)
2130
+ if _ledger_run && declare -F ui_help > /dev/null; then ! ui_attended || ui_brand ledger help; _ledger_usage | ui_help
2131
+ else _ledger_usage; fi ;;
2132
+ "")
2133
+ if _ledger_run && declare -F ui_err_attended > /dev/null && ui_err_attended; then _ledger_refuse "a verb comes first"
2134
+ else _ledger_usage >&2; return 64; fi ;;
2135
+ *) _ledger_refuse "unknown verb '$verb'"; return 64 ;;
2136
+ esac
2137
+ }
2138
+
2139
+ # Run as a command, the module draws its help and its refusals on an attended run through ui.sh
2140
+ # beside it, which a copy without one does without. Its answers, JSON and lines, stay as they are.
2141
+ if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
2142
+ # shellcheck source=/dev/null
2143
+ [[ ! -f "$(dirname "${BASH_SOURCE[0]}")/ui.sh" ]] || source "$(dirname "${BASH_SOURCE[0]}")/ui.sh"
2144
+ ledger "$@"; exit $?
2145
+ fi
2146
+ _ledger_stat_pick