@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,692 @@
1
+ #!/usr/bin/env bash
2
+ # reader.sh: the second reader, a model asked typed questions about evidence a context already
3
+ # wrote, whose answers are reported and decide nothing. One file with two forms, the shape ADR
4
+ # 0005 gave the ledger module. Sourced, it defines the function `reader` and its `_reader_*`
5
+ # helpers and nothing else: no output, no exit, no changed options, no variable set before a
6
+ # verb runs. Run, `bash reader.sh <verb> ...` is that same function, so a model context can use
7
+ # it one command at a time. Two backends: Jev, `typesafe-ai/jev` over the Vercel AI Gateway,
8
+ # and a bare LLM context started through ship-loop's runner on the pass's host and profile.
9
+ # Under `jev` the LLM answers when Jev cannot: no key, a failure after its retries, a 403 or a
10
+ # garbled reply. Under `llm` the LLM answers alone and curl is never called.
11
+ #
12
+ # Verbs:
13
+ # mode <repo> [<flag>] off, jev or llm and where the value came from:
14
+ # the flag, a driver's or a pass's --second-reader,
15
+ # over PLAYBOOK_SECOND_READER over
16
+ # kryso.secondReader in git config, unset as off,
17
+ # on as jev; status 1 on any other value. The one
18
+ # place the value set lives, and the order for every
19
+ # caller with this module (a pass without it reads
20
+ # only whether the switch is off). Sourced,
21
+ # it also leaves READER_MODE (empty on a refusal),
22
+ # READER_MODE_SOURCE, READER_MODE_VALUE and
23
+ # READER_MODE_ALLOWED for a caller's own line
24
+ # ask <repo> <state-file> <questions-file> <log>
25
+ # the answers, usage, cost and backend as one JSON
26
+ # document; status 0 answered, 2 skipped, 1 failed.
27
+ # An LLM answer carries its context for the pass
28
+ # record and, after a Jev skip or failure, the
29
+ # `fallback` reason; both backends failing is 1.
30
+ # The questions file is a JSON object of Jev boolean
31
+ # questions by key, each with an optional `state`,
32
+ # the text about that key alone; the state file is
33
+ # the text every request carries. Questions whose
34
+ # texts do not fit one request go out as more
35
+ # requests in series, and a state file that leaves
36
+ # no room for them is a skip
37
+ # audit <worktree> the Second reader subsection for the worktree's
38
+ # .kryso/pass/review.md, asked per deferred and rejected
39
+ # row; always status 0, a missing review a skip.
40
+ # Sourced, it also leaves READER_BACKEND, READER_ROWS,
41
+ # READER_DISPUTES, READER_COST, READER_LOG,
42
+ # READER_SKIPPED, READER_FALLBACK and READER_CONTEXT
43
+ # for the caller's ledger line and pass record
44
+ # seam <repo> <brief> <log> the seam call for a pass's cut stage: one line,
45
+ # `tdd` or `no-seam` first, then the backend and the
46
+ # probability that the brief describes behaviour a
47
+ # test can observe; status 0 answered, 2 skipped,
48
+ # 1 failed. `no-seam` only at seam_no_seam_at or
49
+ # lower; a skip or a failure is `tdd` with the
50
+ # reason, because a wrong `no-seam` ships testable
51
+ # code without tests. Sourced, it also leaves
52
+ # READER_SEAM (the line), READER_BACKEND, READER_COST,
53
+ # READER_LOG, READER_SKIPPED, READER_FALLBACK and
54
+ # READER_CONTEXT for the caller, the log and the
55
+ # context's result named relative to the log's
56
+ # parent directory, the way the audit names them
57
+ #
58
+ # Every request leaves one JSON line in the log: the backend, the request without the key, the
59
+ # status, the duration, the reply and the cost. Jev's key is AI_GATEWAY_API_KEY, or, when that
60
+ # is unset and `kryso.jevKeychain` in git config names a macOS Keychain service, the
61
+ # password of that service, read with `security find-generic-password -w` (a watch started by
62
+ # launchd sources no profile). Either way the key is held in a shell variable and reaches curl
63
+ # on stdin as a config line, never in argv, a file, a log or the ledger. The reader sets no
64
+ # base-URL variable and passes nothing to the runner, so the gateway stays
65
+ # application-code-only. The LLM context runs through `runner_classify` in runner.sh beside
66
+ # this file: no tools, no settings sources, no MCP servers, the rules and state as its system
67
+ # prompt, the questions answered through a structured-output schema, and its probability
68
+ # marked self-reported in the log. The model is `kryso.secondReaderModel` in git config,
69
+ # else `claude-haiku-4-5` on the Claude host and the profile's model elsewhere. Sourced by a
70
+ # script that has loaded a profile, that profile is used; sourced or run before one is loaded,
71
+ # READER_PROFILE names it (READER_PROFILE_FILE the profile file), default `claude`, and the
72
+ # reader loads it. A refusal is one line on stderr, nothing on stdout, status 64.
73
+ # READER_RETRY_DELAYS overrides the back-off, which the tests set to zero. Needs bash, jq,
74
+ # curl, git and, for the Keychain source, security.
75
+
76
+ # ---- constants -----------------------------------------------------------------------------
77
+
78
+ # _reader_const <name>: the module's named constants, kept out of the sourcing shell's variables.
79
+ _reader_const() {
80
+ case "$1" in
81
+ endpoint) printf 'https://ai-gateway.vercel.sh/v1/evaluate' ;;
82
+ model) printf 'typesafe-ai/jev' ;;
83
+ key_var) printf 'AI_GATEWAY_API_KEY' ;;
84
+ keychain_name) printf 'jevKeychain' ;;
85
+ timeout) printf '10' ;;
86
+ model_name) printf 'secondReaderModel' ;;
87
+ # The values the switch takes, as a refusal names them. `on` is read as jev.
88
+ modes) printf 'off, on, jev or llm' ;;
89
+ llm_model_claude) printf 'claude-haiku-4-5' ;;
90
+ # Characters, not tokens: about 21k tokens of Jev's 32k window, the budget deslopper uses.
91
+ state_budget) printf '64000' ;;
92
+ # A deferred row is disputed at this probability or higher that the brief asks for it.
93
+ dispute_deferred_at) printf '0.8' ;;
94
+ # A rejected row is disputed at this probability or lower that its evidence names a checked fact.
95
+ dispute_rejected_at) printf '0.2' ;;
96
+ # The seam call is no-seam at this probability or lower that the brief describes behaviour a
97
+ # test can observe. Anything higher, and any skip or failure, is tdd.
98
+ seam_no_seam_at) printf '0.1' ;;
99
+ # Seconds before the second, third and fourth attempt after a 429 or 503.
100
+ retry_delays) printf '%s' "${READER_RETRY_DELAYS:-2 5 10}" ;;
101
+ *) return 1 ;;
102
+ esac
103
+ }
104
+
105
+ # ---- helpers -------------------------------------------------------------------------------
106
+
107
+ _reader_refuse() { echo "reader: $1" >&2; return 64; }
108
+
109
+ # _reader_config_key <repo> <name>: the git config key that holds a kryso setting,
110
+ # kryso.<name>, else playbook.<name>, its name before the rename, read until 3.0.0. Status 1
111
+ # when neither is set. runner_config in runner.sh reads the same way; this copy lets the
112
+ # reader run without the runner.
113
+ _reader_config_key() {
114
+ local key
115
+ for key in "kryso.$2" "playbook.$2"; do
116
+ git -C "$1" config --get "$key" > /dev/null 2>&1 && { printf '%s' "$key"; return 0; }
117
+ done
118
+ return 1
119
+ }
120
+
121
+ # _reader_config <repo> <name>: the setting's value, from the key _reader_config_key names.
122
+ _reader_config() {
123
+ local key
124
+ key="$(_reader_config_key "$1" "$2")" || return 1
125
+ git -C "$1" config --get "$key" 2>/dev/null
126
+ }
127
+ _reader_now() { date -u +%FT%TZ; }
128
+ _reader_ms() {
129
+ if [[ -n "${EPOCHREALTIME:-}" ]]; then awk -v t="$EPOCHREALTIME" 'BEGIN { printf "%d", t * 1000 }'
130
+ else printf '%d' $(( $(date +%s) * 1000 )); fi
131
+ }
132
+ # _reader_dollars <n>...: the sum, printed as a dollar amount without float noise.
133
+ _reader_dollars() {
134
+ local sum
135
+ sum="$(printf '%s\n' "$@" | awk '{ s += $1 } END { printf "%.6f", s }')"
136
+ sum="$(sed -E 's/0+$//; s/\.$//' <<< "$sum")"
137
+ printf '%s' "${sum:-0}"
138
+ }
139
+ _reader_usage() {
140
+ cat <<'EOF'
141
+ Usage: bash reader.sh <verb> ...
142
+
143
+ mode <repo> [<flag>] print off, jev or llm, and
144
+ where the value came from
145
+ ask <repo> <state-file> <questions-file> <log> print the answers as one JSON
146
+ document
147
+ audit <worktree> print the review's Second
148
+ reader subsection
149
+ seam <repo> <brief> <log> print tdd or no-seam for the
150
+ brief, with the backend and
151
+ the probability
152
+ EOF
153
+ }
154
+
155
+ # ---- mode ----------------------------------------------------------------------------------
156
+
157
+ _reader_mode() {
158
+ local repo="${1:-}" flag="${2:-}" value source
159
+ # The values a sourcing caller builds its own line from, set before the first return.
160
+ # shellcheck disable=SC2034
161
+ READER_MODE=""; READER_MODE_SOURCE=""; READER_MODE_VALUE=""; READER_MODE_ALLOWED="$(_reader_const modes)"
162
+ [[ -n "$repo" && -d "$repo" ]] || { _reader_refuse "mode needs <repository>"; return 64; }
163
+ if [[ -n "$flag" ]]; then
164
+ value="$flag"; source="--second-reader"
165
+ elif [[ -n "${PLAYBOOK_SECOND_READER:-}" ]]; then
166
+ value="$PLAYBOOK_SECOND_READER"; source="PLAYBOOK_SECOND_READER"
167
+ else
168
+ source="$(_reader_config_key "$repo" secondReader)" || source=kryso.secondReader
169
+ value="$(_reader_config "$repo" secondReader)"
170
+ fi
171
+ [[ -n "$value" ]] || source=unset
172
+ # shellcheck disable=SC2034
173
+ READER_MODE_SOURCE="$source"; READER_MODE_VALUE="$value"
174
+ case "$value" in
175
+ "") READER_MODE=off; printf 'off unset\n' ;;
176
+ off|jev|llm) READER_MODE="$value"; printf '%s %s=%s\n' "$value" "$source" "$value" ;;
177
+ on) READER_MODE=jev; printf 'jev %s=%s\n' "$source" "$value" ;;
178
+ *) echo "reader: $source is '$value', not $READER_MODE_ALLOWED" >&2; return 1 ;;
179
+ esac
180
+ }
181
+
182
+ # ---- ask -----------------------------------------------------------------------------------
183
+
184
+ # _reader_batches <state-file> <questions-file> <dir>: one request body per file under <dir>,
185
+ # body-1.json onward. Questions are taken in order into batches whose per-question texts fit
186
+ # under the budget beside the shared state; a single text that cannot fit is cut to the budget.
187
+ _reader_batches() {
188
+ local state_file="$1" questions_file="$2" dir="$3" n=0 line
189
+ jq -c -n --rawfile state "$state_file" --rawfile q "$questions_file" \
190
+ --arg model "$(_reader_const model)" --argjson budget "$(_reader_const state_budget)" '
191
+ ($q | fromjson) as $questions
192
+ | ($state | length) as $base
193
+ | ([$budget - $base - 2, 0] | max) as $room
194
+ | reduce ($questions | keys_unsorted[]) as $k ({batches: [], cur: []};
195
+ (($questions[$k].state // "") | .[:$room]) as $s
196
+ | (($s | length) + 2) as $l
197
+ | (.cur | map(.len) | add // 0) as $used
198
+ | if (.cur | length) > 0 and ($used + $l) > $room
199
+ then .batches += [.cur] | .cur = [{key: $k, text: $s, len: $l}]
200
+ else .cur += [{key: $k, text: $s, len: $l}] end)
201
+ | (.batches + (if (.cur | length) > 0 then [.cur] else [] end))[]
202
+ | . as $batch
203
+ | {model: $model,
204
+ state: ($state + (if ($batch | map(select(.text != "")) | length) > 0 then "\n\n" + ($batch | map(.text) | join("\n\n")) else "" end)),
205
+ questions: ($questions | with_entries(select(.key as $k | $batch | map(.key) | index($k) != null)) | map_values(del(.state)))}' \
206
+ | while IFS= read -r line; do
207
+ n=$(( n + 1 ))
208
+ printf '%s\n' "$line" > "$dir/body-$n.json"
209
+ done
210
+ }
211
+
212
+ # _reader_jev_key <repo>: Jev's key on stdout, from the environment or the Keychain service the
213
+ # repository's config names; status 2 with the skip reason on stdout when neither gives one.
214
+ # `security` is called by name, so a shim on PATH can stand in for the Keychain.
215
+ _reader_jev_key() {
216
+ local repo="$1" key_var keychain service key err code message
217
+ key_var="$(_reader_const key_var)"
218
+ if [[ -n "${!key_var:-}" ]]; then printf '%s' "${!key_var}"; return 0; fi
219
+ keychain="$(_reader_const keychain_name)"
220
+ service="$(_reader_config "$repo" "$keychain")"
221
+ if [[ -z "$service" ]]; then
222
+ printf 'jev cannot start, no %s set and no kryso.%s in git config' "$key_var" "$keychain"; return 2
223
+ fi
224
+ err="$(mktemp)"
225
+ key="$(security find-generic-password -s "$service" -w 2>"$err")"; code=$?
226
+ message="$(head -1 "$err" 2>/dev/null)"; rm -f "$err"
227
+ if [[ "$code" -ne 0 || -z "$key" ]]; then
228
+ printf 'jev cannot start, security find-generic-password -s %s -w failed: %s' "$service" "${message:-exited $code with no password}"; return 2
229
+ fi
230
+ printf '%s' "$key"
231
+ }
232
+
233
+ # _reader_request <body-file> <log> <dir> <key>: one request with its retries. Leaves the last
234
+ # reply at <dir>/reply and prints "<status> <attempts>", where a transport failure's status is
235
+ # 000. The key is handed to curl as a config line on stdin.
236
+ _reader_request() {
237
+ local body="$1" log="$2" dir="$3" key="$4" status code attempts=0 delay started ms cost
238
+ local -a delays
239
+ read -r -a delays <<< "0 $(_reader_const retry_delays)"
240
+ for delay in "${delays[@]}"; do
241
+ [[ "$delay" == 0 ]] || sleep "$delay"
242
+ attempts=$(( attempts + 1 ))
243
+ : > "$dir/reply"
244
+ started="$(_reader_ms)"
245
+ status="$(printf 'header = "Authorization: Bearer %s"\n' "$key" \
246
+ | curl -sS --config - -X POST -H 'Content-Type: application/json' \
247
+ --max-time "$(_reader_const timeout)" --data-binary @"$body" -o "$dir/reply" -w '%{http_code}' \
248
+ "$(_reader_const endpoint)" 2>"$dir/err")"
249
+ code=$?
250
+ ms=$(( $(_reader_ms) - started ))
251
+ [[ "$status" =~ ^[0-9]{3}$ ]] || status=000
252
+ [[ "$code" -eq 0 || "$status" != 000 ]] || : > "$dir/reply"
253
+ cost="$(jq -r '.providerMetadata.gateway.marketCost // empty' "$dir/reply" 2>/dev/null)"
254
+ jq -c -n --arg backend jev --arg at "$(_reader_now)" --argjson attempt "$attempts" \
255
+ --arg url "$(_reader_const endpoint)" --rawfile body "$body" --rawfile reply "$dir/reply" \
256
+ --rawfile err "$dir/err" --arg status "$status" --argjson ms "$ms" --arg cost "$cost" '
257
+ {backend: $backend, at: $at, attempt: $attempt,
258
+ request: {method: "POST", url: $url, headers: {"Content-Type": "application/json"}, body: ($body | fromjson)},
259
+ status: (if $status == "000" then null else ($status | tonumber) end),
260
+ duration_ms: $ms,
261
+ reply: (if $status == "000" then ($err | rtrimstr("\n")) else (try ($reply | fromjson) catch $reply) end),
262
+ cost: (if $cost == "" then null else $cost end)}' >> "$log"
263
+ case "$status" in 429|503) continue ;; esac
264
+ break
265
+ done
266
+ printf '%s %s' "$status" "$attempts"
267
+ }
268
+
269
+ # _reader_failure <status> <attempts> <dir>: one line saying why a request is not an answer.
270
+ _reader_failure() {
271
+ local status="$1" attempts="$2" dir="$3" message
272
+ case "$status" in
273
+ 000) printf 'curl failed: %s' "$(head -1 "$dir/err" 2>/dev/null)"; return ;;
274
+ 429|503) printf 'gateway returned %s after %s attempts' "$status" "$attempts"; return ;;
275
+ esac
276
+ message="$(jq -r 'if type == "object" then (if (.error | type) == "object" then (.error.message // "") elif (.error | type) == "string" then .error else "" end) else "" end' "$dir/reply" 2>/dev/null)"
277
+ printf 'gateway returned %s' "$status"
278
+ [[ -z "$message" ]] || printf ': %s' "$message"
279
+ if [[ "$status" == 403 ]] && grep -qi 'free tier' <<< "$message"; then printf ' (top up gateway credits, the key is fine)'; fi
280
+ }
281
+
282
+ _reader_ask() {
283
+ local repo="${1:-}" state_file="${2:-}" questions_file="${3:-}" log="${4:-}"
284
+ local mode code out reason
285
+ [[ $# -eq 4 && -n "$repo" && -n "$state_file" && -n "$questions_file" && -n "$log" ]] \
286
+ || { _reader_refuse "ask needs <repository> <state-file> <questions-file> <log>"; return 64; }
287
+ [[ -d "$repo" ]] || { _reader_refuse "ask: no repository at $repo"; return 64; }
288
+ [[ -f "$state_file" ]] || { _reader_refuse "ask: no state file at $state_file"; return 64; }
289
+ jq -e 'type == "object" and length > 0' "$questions_file" >/dev/null 2>&1 \
290
+ || { _reader_refuse "ask: $questions_file is not a JSON object of questions"; return 64; }
291
+
292
+ mode="$(_reader_mode "$repo" 2>&1)"; code=$?
293
+ if [[ "$code" -ne 0 ]]; then
294
+ jq -c -n --arg r "${mode#reader: }" '{backend: null, skipped: $r}'; return 2
295
+ fi
296
+ case "${mode%% *}" in
297
+ off) jq -c -n '{backend: null, skipped: "the reader is off"}'; return 2 ;;
298
+ llm) _reader_llm "$repo" "$state_file" "$questions_file" "$log" ""; return $? ;;
299
+ esac
300
+ out="$(_reader_jev "$repo" "$state_file" "$questions_file" "$log")"; code=$?
301
+ if [[ "$code" -eq 0 ]]; then printf '%s\n' "$out"; return 0; fi
302
+ # Jev could not answer, so the LLM is asked the same state and questions. Both request logs
303
+ # stay in the log, and the answer names what Jev did.
304
+ case "$code" in
305
+ 2) reason="jev skipped: $(jq -r '.skipped' <<< "$out")" ;;
306
+ *) reason="jev failed: $(jq -r '.failed' <<< "$out")" ;;
307
+ esac
308
+ _reader_llm "$repo" "$state_file" "$questions_file" "$log" "$reason"
309
+ }
310
+
311
+ # _reader_jev <repo> <state-file> <questions-file> <log>: Jev's answer; status 0 answered,
312
+ # 2 skipped with the reason, 1 failed with the reason.
313
+ _reader_jev() {
314
+ local repo="$1" state_file="$2" questions_file="$3" log="$4"
315
+ local key budget size dir body status attempts failed answers usage costs=()
316
+ key="$(_reader_jev_key "$repo")" || { jq -c -n --arg r "$key" '{backend: "jev", skipped: $r}'; return 2; }
317
+ # The shared state goes into every request, so one that leaves no room for a question's own
318
+ # text would ask about rows Jev cannot see, over the budget.
319
+ budget="$(_reader_const state_budget)"
320
+ size="$(jq -r -n --rawfile s "$state_file" '$s | length')"
321
+ if (( size + 2 >= budget )); then
322
+ jq -c -n --arg r "jev cannot start, the state is $size characters before any question, over its $budget-character budget" \
323
+ '{backend: "jev", skipped: $r}'
324
+ return 2
325
+ fi
326
+
327
+ dir="$(mktemp -d)"
328
+ _reader_batches "$state_file" "$questions_file" "$dir"
329
+ mkdir -p "$(dirname "$log")"
330
+ answers='{}'; usage='{"input_tokens":0,"output_tokens":0}'; failed=""
331
+ for body in "$dir"/body-*.json; do
332
+ [[ -f "$body" ]] || continue
333
+ read -r status attempts <<< "$(_reader_request "$body" "$log" "$dir" "$key")"
334
+ if [[ "$status" != 200 ]]; then failed="$(_reader_failure "$status" "$attempts" "$dir")"; break; fi
335
+ if ! jq -e 'type == "object"' "$dir/reply" >/dev/null 2>&1; then failed="the gateway replied with something that is not JSON"; break; fi
336
+ if ! jq -e '.answers | type == "object"' "$dir/reply" >/dev/null 2>&1; then failed="the gateway's reply has no answers"; break; fi
337
+ # A probability per key, the shape every backend returns. Jev's confidence stays in the log.
338
+ answers="$(jq -c --argjson a "$answers" '$a + (.answers | map_values({probability: .probability}))' "$dir/reply")"
339
+ usage="$(jq -c --argjson u "$usage" '{input_tokens: ($u.input_tokens + (.usage.inputTokens // 0)), output_tokens: ($u.output_tokens + (.usage.outputTokens // 0))}' "$dir/reply")"
340
+ costs+=("$(jq -r '.providerMetadata.gateway.marketCost // 0' "$dir/reply")")
341
+ done
342
+ rm -rf "$dir"
343
+ if [[ -n "$failed" ]]; then
344
+ jq -c -n --arg f "$failed" '{backend: "jev", failed: $f}'
345
+ return 1
346
+ fi
347
+ jq -c -n --argjson answers "$answers" --argjson usage "$usage" --arg cost "$(_reader_dollars "${costs[@]}")" \
348
+ '{backend: "jev", answers: $answers, usage: $usage, cost: $cost}'
349
+ }
350
+
351
+ # ---- the llm backend -----------------------------------------------------------------------
352
+
353
+ # _reader_ledger: the evidence module's functions, loaded once into this shell, for its rules on
354
+ # which ledger directory to read and which name a rerun's log takes. Sourced by the pass, the
355
+ # module is already there. Run as a command, it is kryso's ledger.sh, beside this skill or under
356
+ # the home's skills. Status 1 when none.
357
+ _reader_ledger() {
358
+ local here candidate
359
+ declare -F _ledger_d >/dev/null 2>&1 && return 0
360
+ here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
361
+ for candidate in "$(dirname "$here")/kryso/ledger.sh" "$HOME/.agents/skills/kryso/ledger.sh" "$HOME/.claude/skills/kryso/ledger.sh"; do
362
+ # shellcheck source=/dev/null
363
+ [[ -f "$candidate" ]] && source "$candidate" && return 0
364
+ done
365
+ return 1
366
+ }
367
+
368
+ # _reader_runner: the runner's functions and a profile, loaded once into this shell. Sourced by
369
+ # the pass, both are already there; run as a command, runner.sh sits beside this file and
370
+ # READER_PROFILE names the profile. On failure the reason is left in READER_LLM_WHY.
371
+ _reader_runner() {
372
+ local here
373
+ READER_LLM_WHY=""
374
+ if ! declare -F runner_classify >/dev/null 2>&1; then
375
+ here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
376
+ [[ -f "$here/runner.sh" ]] || { READER_LLM_WHY="llm cannot start, no runner.sh beside $here/reader.sh"; return 1; }
377
+ # shellcheck source=runner.sh
378
+ source "$here/runner.sh" || { READER_LLM_WHY="llm cannot start, cannot source $here/runner.sh"; return 1; }
379
+ fi
380
+ if [[ -z "${RUNNER_HOST:-}" ]]; then
381
+ runner_profile_load "${READER_PROFILE:-claude}" "${READER_PROFILE_FILE:-}" 2>/dev/null \
382
+ || { READER_LLM_WHY="llm cannot start, no profile ${READER_PROFILE:-claude}"; return 1; }
383
+ fi
384
+ }
385
+
386
+ # _reader_model <repo>: the model the LLM backend asks for: the repository's key, else the
387
+ # Claude default, else nothing, which is the profile's model.
388
+ _reader_model() {
389
+ local model
390
+ model="$(_reader_config "$1" "$(_reader_const model_name)")"
391
+ [[ -n "$model" || "${RUNNER_HOST:-}" != claude ]] || model="$(_reader_const llm_model_claude)"
392
+ printf '%s' "$model"
393
+ }
394
+
395
+ # _reader_llm <repo> <state-file> <questions-file> <log> <fallback>: one bare context asked
396
+ # the same state and questions, its stated probability per key as the answer. The system
397
+ # prompt is the state with every question's own text after it; the prompt is the questions;
398
+ # the schema holds one probability per key. Status 0 answered, 1 failed. <fallback> is what
399
+ # Jev did when this is the second try, else empty.
400
+ _reader_llm() {
401
+ local repo="$1" state_file="$2" questions_file="$3" log="$4" fallback="$5"
402
+ local dir model result final err started t0 ms code failed answers keys missing usage cost ctx
403
+ if ! _reader_runner; then
404
+ jq -c -n --arg f "$READER_LLM_WHY" --arg fb "$fallback" '{backend: "llm", failed: $f} + (if $fb == "" then {} else {fallback: $fb} end)'
405
+ unset READER_LLM_WHY
406
+ return 1
407
+ fi
408
+ unset READER_LLM_WHY
409
+ model="$(_reader_model "$repo")"
410
+ dir="$(mktemp -d)"
411
+ jq -r -n --rawfile state "$state_file" --rawfile q "$questions_file" '
412
+ ($q | fromjson) as $questions
413
+ | $state + ([$questions[] | .state // "" | select(. != "")] | if length == 0 then "" else "\n\n" + join("\n\n") end)' > "$dir/system.md"
414
+ jq -r '
415
+ "Answer each question below from the system prompt alone, with the probability, from 0 to 1, that its answer is yes. Reply only through the structured output, one entry per question key.\n"
416
+ + (to_entries | map("\n## " + .key + "\n\n" + (.value.instructions // "") + "\n\n- true: " + (.value.criteria.true // "the answer is yes") + "\n- false: " + (.value.criteria.false // "the answer is no")) | join("\n"))' \
417
+ "$questions_file" > "$dir/prompt.md"
418
+ jq -c '
419
+ {type: "object", additionalProperties: false, required: ["answers"],
420
+ properties: {answers: {type: "object", additionalProperties: false, required: keys,
421
+ properties: (map_values({type: "object", additionalProperties: false, required: ["probability"],
422
+ properties: {probability: {type: "number", minimum: 0, maximum: 1,
423
+ description: "the probability, from 0 to 1, that the answer to this question is yes"}}}))}}}' \
424
+ "$questions_file" > "$dir/schema.json"
425
+ mkdir -p "$(dirname "$log")"
426
+ result="${log%.jsonl}-llm.json"; final="${log%.jsonl}-llm.final.json"; err="${log%.jsonl}-llm.err"
427
+ started="$(_reader_now)"; t0="$(_reader_ms)"
428
+ # The context has no tools, and the gateway key is kept out of it all the same, beside the
429
+ # host keys the runner strips.
430
+ ( unset "$(_reader_const key_var)"; runner_classify "$result" "$final" "$err" "$dir/system.md" "$dir/prompt.md" "$dir/schema.json" "$model" "${RUNNER_EFFORT:-high}" ) >/dev/null 2>&1
431
+ code=$?
432
+ ms=$(( $(_reader_ms) - t0 ))
433
+ [[ -s "$result" ]] || printf '{"is_error":true,"result":"the runner wrote no result"}' > "$result"
434
+ keys="$(jq -c 'keys' "$questions_file")"
435
+ failed=""
436
+ if [[ "$code" -ne 0 ]] || [[ "$(jq -r '.is_error // false' "$result")" == true ]]; then
437
+ failed="$RUNNER_HOST exited $code: $(jq -r '.result // "" | tostring | split("\n")[0]' "$result" | cut -c1-200)"
438
+ elif ! jq -e '.structured_output | type == "object" and (.answers | type == "object")' "$result" >/dev/null 2>&1; then
439
+ failed="the answer is not the structured output the schema asks for"
440
+ else
441
+ missing="$(jq -r --argjson keys "$keys" '.structured_output.answers as $a | [$keys[] | select(($a[.].probability | type) != "number")] | join(", ")' "$result")"
442
+ [[ -z "$missing" ]] || failed="the answer has no probability for $missing"
443
+ fi
444
+ cost="$(jq -r '.cost_usd // empty' "$result")"
445
+ [[ -z "$cost" ]] || cost="$(_reader_dollars "$cost")"
446
+ # One line in the same log as Jev's requests: the request without any key, the reply, and
447
+ # that the probability is the model's own word, not a measured one.
448
+ jq -c -n --arg backend llm --arg at "$started" --arg host "$RUNNER_HOST" --arg model "$model" --arg effort "${RUNNER_EFFORT:-high}" \
449
+ --rawfile system "$dir/system.md" --rawfile prompt "$dir/prompt.md" --rawfile schema "$dir/schema.json" \
450
+ --argjson exit "$code" --argjson ms "$ms" --arg cost "$cost" --arg failed "$failed" --arg result "$result" --slurpfile res "$result" '
451
+ {backend: $backend, at: $at, attempt: 1,
452
+ request: {host: $host, model: (if $model == "" then null else $model end), effort: $effort,
453
+ system_prompt: $system, prompt: $prompt, schema: ($schema | fromjson)},
454
+ exit: $exit, duration_ms: $ms,
455
+ reply: ($res[0].structured_output // ($res[0].result // null)),
456
+ probability: "self-reported",
457
+ failed: (if $failed == "" then null else $failed end),
458
+ cost: (if $cost == "" then null else $cost end),
459
+ result: $result}' >> "$log"
460
+ # The context, for the pass record: what the host reported and nothing guessed.
461
+ ctx="$(jq -c --arg host "$RUNNER_HOST" --arg model "$model" --arg result "$result" --argjson exit "$code" \
462
+ --arg started "$started" --arg ended "$(_reader_now)" --argjson seconds "$(( ms / 1000 ))" '
463
+ {id: (.session_id // null | if . == "none" then null else . end), host: $host, mode: "start",
464
+ model: (if $model == "" then null else $model end), model_observed: (.model_observed // null),
465
+ usage: (.reported_usage // null), cost_usd: (.cost_usd // null), result: $result, exit: $exit,
466
+ started_at: $started, ended_at: $ended, seconds: $seconds}' "$result")"
467
+ rm -rf "$dir"
468
+ if [[ -n "$failed" ]]; then
469
+ jq -c -n --arg f "$failed" --arg fb "$fallback" --argjson ctx "$ctx" \
470
+ '{backend: "llm", failed: $f, context: $ctx} + (if $fb == "" then {} else {fallback: $fb} end)'
471
+ return 1
472
+ fi
473
+ answers="$(jq -c --argjson keys "$keys" '.structured_output.answers | with_entries(select(.key as $k | $keys | index($k) != null)) | map_values({probability: .probability})' "$result")"
474
+ usage="$(jq -c '{input_tokens: (.reported_usage.input_tokens // 0), output_tokens: (.reported_usage.output_tokens // 0)}' "$result")"
475
+ jq -c -n --argjson answers "$answers" --argjson usage "$usage" --arg cost "$cost" --arg fb "$fallback" --argjson ctx "$ctx" \
476
+ '{backend: "llm", answers: $answers, usage: $usage, cost: (if $cost == "" then null else ($cost | tostring) end), context: $ctx}
477
+ + (if $fb == "" then {} else {fallback: $fb} end)'
478
+ }
479
+
480
+ # ---- after an ask --------------------------------------------------------------------------
481
+
482
+ # _reader_read_answer <out> <code> <log>: reads what ask printed and returned, for the audit and
483
+ # the seam call alike. It sets READER_LOG when the log exists. It sets READER_BACKEND when the
484
+ # answer names a backend: the one that answered, or the last one that tried. It sets
485
+ # READER_FALLBACK to what Jev did before the LLM, and READER_CONTEXT to the LLM's context for
486
+ # the pass record. The log and the context's result are named relative to the log's parent
487
+ # directory. Status 0 means answered. Status 2 means skipped. Status 1 means failed, and so does
488
+ # any other status from ask, which the reason names. On 1 and 2 the reason is in READER_SKIPPED.
489
+ _reader_read_answer() {
490
+ local out="$1" code="$2" log="$3" root backend
491
+ root="$(dirname "$(dirname "$log")")/"
492
+ # shellcheck disable=SC2034 # read by the caller for its ledger line
493
+ [[ ! -e "$log" ]] || READER_LOG="${log#"$root"}"
494
+ backend="$(jq -r '.backend // empty' <<< "$out" 2>/dev/null)"
495
+ [[ -z "$backend" ]] || READER_BACKEND="$backend"
496
+ READER_FALLBACK="$(jq -r '.fallback // empty' <<< "$out" 2>/dev/null)"
497
+ # shellcheck disable=SC2034 # read by the caller, ship-pass.sh records it in CONTEXTS
498
+ READER_CONTEXT="$(jq -c --arg root "$root" '.context // empty | .result |= (if type == "string" then ltrimstr($root) else . end)' <<< "$out" 2>/dev/null)"
499
+ case "$code" in
500
+ 0) return 0 ;;
501
+ 2) READER_SKIPPED="$(jq -r '.skipped' <<< "$out")"; return 2 ;;
502
+ 1) READER_SKIPPED="$READER_BACKEND failed, $(jq -r '.failed' <<< "$out")$(_reader_after ', ')"; return 1 ;;
503
+ *) READER_SKIPPED="$READER_BACKEND failed, ask returned $code$(_reader_after ', ')"; return 1 ;;
504
+ esac
505
+ }
506
+
507
+ # _reader_after <separator>: what Jev did before the LLM, as `<separator>after <what>`, or
508
+ # nothing when the LLM was not a fallback. A reason takes it after a comma, an answer after a space.
509
+ _reader_after() {
510
+ [[ -z "${READER_FALLBACK:-}" ]] || printf '%safter %s' "$1" "$READER_FALLBACK"
511
+ }
512
+
513
+ # ---- audit ---------------------------------------------------------------------------------
514
+
515
+ # _reader_rows <review>: the deferred and rejected triage rows as one JSON array of
516
+ # {row, axis, finding, outcome, evidence, question}, in table order, where the question is the
517
+ # one Jev is asked about the row and the disputes table shows. Fixed rows are left alone.
518
+ _reader_rows() {
519
+ grep -E '^\| [0-9]+ \| (Standards|Spec) \| .* \| (deferred|rejected) \| ' "$1" 2>/dev/null \
520
+ | jq -R -c -s '
521
+ split("\n") | map(select(length > 0))
522
+ | map(ltrimstr("| ") | rtrimstr(" |") | split(" | ")
523
+ | {row: .[0], axis: .[1], finding: .[2], outcome: .[3], evidence: (.[4:] | join(" | "))}
524
+ | .question = (if .outcome == "deferred" then "Does the brief ask for what row \(.row)'"'"'s finding asks for?"
525
+ else "Does row \(.row)'"'"'s evidence name a checked fact?" end))'
526
+ }
527
+
528
+ _reader_audit() {
529
+ local wt="${1:-}" review brief mode code backend rows n dir state questions log tag out cost disputes disputed after ld
530
+ [[ $# -eq 1 && -n "$wt" ]] || { _reader_refuse "audit needs <worktree>"; return 64; }
531
+ # The counts a sourcing caller reads for its ledger line, so the audit's output stays the subsection.
532
+ # shellcheck disable=SC2034
533
+ READER_BACKEND=""; READER_ROWS=0; READER_DISPUTES=0; READER_COST=0; READER_LOG=""; READER_SKIPPED=""; READER_FALLBACK=""; READER_CONTEXT=""
534
+ # The ledger directory is the module's to name: .kryso/pass, the .kryso of a pass before #618,
535
+ # or .ship-it in a worktree no writer has moved since the rename.
536
+ _reader_ledger || { _reader_skip "" "cannot find kryso's ledger.sh beside $(dirname "${BASH_SOURCE[0]}") or under the home's skills"; return 0; }
537
+ # A module older than this file has no tag rule, and an empty tag would write every audit's
538
+ # request log over the one before it.
539
+ declare -F _ledger_next_tag >/dev/null 2>&1 || { _reader_skip "" "kryso's ledger.sh is older than reader.sh, with no _ledger_next_tag"; return 0; }
540
+ _ledger_d "$wt" ld
541
+ review="$ld/review.md"; brief="$ld/brief.md"
542
+
543
+ mode="$(_reader_mode "$wt" 2>&1)"; code=$?
544
+ backend="${mode%% *}"
545
+ if [[ "$code" -ne 0 ]]; then _reader_skip "" "${mode#reader: }"; return 0; fi
546
+ READER_BACKEND="$backend"
547
+ [[ "$backend" != off ]] || { _reader_skip "" "the reader is off"; return 0; }
548
+ [[ -f "$review" ]] || { _reader_skip "" "no review at $review"; return 0; }
549
+
550
+ rows="$(_reader_rows "$review")"
551
+ n="$(jq -r 'length' <<< "$rows")"
552
+ if [[ "$n" -eq 0 ]]; then
553
+ printf '### Second reader\n\nNo deferred or rejected rows, so no reader was asked.\n'
554
+ return 0
555
+ fi
556
+
557
+ dir="$(mktemp -d)"
558
+ state="$dir/state.txt"; questions="$dir/questions.json"
559
+ {
560
+ cat <<'RULES'
561
+ # Rules
562
+
563
+ You are the second reader of a code review's triage table. A reviewer found issues in a change built from the brief below, and the builder then triaged each finding. A deferred row is a finding the builder set aside as outside the brief's scope, with the reason in its Evidence column. A rejected row is a finding the builder says is wrong, with the fact it checked in its Evidence column. Answer each question from the brief and the row alone. A deferred finding the brief asks for is a gap the pull request leaves open. A rejection whose evidence names nothing checkable is an assertion, not a check.
564
+
565
+ # Brief
566
+
567
+ RULES
568
+ if [[ -f "$brief" ]]; then cat "$brief"; else echo "(no brief in the worktree)"; fi
569
+ printf '\n# Rows\n'
570
+ } > "$state"
571
+ jq -c '
572
+ map({key: ("row-" + .row),
573
+ value: ({type: "boolean", instructions: .question,
574
+ state: ("## Row " + .row + " (" + .axis + ", " + .outcome + ")\nFinding: " + .finding + "\nEvidence: " + .evidence)}
575
+ + (if .outcome == "deferred" then
576
+ {criteria: {true: "the brief asks for it: an acceptance criterion or the work described requires what the finding names, so deferring it leaves the brief unmet",
577
+ false: "the brief does not ask for it: the finding is outside the brief'"'"'s scope, and the change meets the brief without it"}}
578
+ else
579
+ {criteria: {true: "the evidence names a concrete fact that was checked: a file and line, a command'"'"'s output, a test, a commit or a documented rule that shows the finding wrong",
580
+ false: "the evidence restates a judgement or an opinion and names nothing that was checked"}}
581
+ end))})
582
+ | from_entries' <<< "$rows" > "$questions"
583
+
584
+ mkdir -p "$ld/logs"
585
+ tag="$(_ledger_next_tag "$ld/logs" second-reader .jsonl)"
586
+ log="$ld/logs/$tag.jsonl"
587
+ out="$(_reader_ask "$wt" "$state" "$questions" "$log" 2>/dev/null)"; code=$?
588
+ rm -rf "$dir"
589
+ # shellcheck disable=SC2034
590
+ READER_ROWS="$n"
591
+ # The log sits in the ledger directory's logs/, so the answer's names are relative to the
592
+ # ledger directory, the way the ledger names logs.
593
+ _reader_read_answer "$out" "$code" "$log" || { _reader_skip "$READER_BACKEND" "$READER_SKIPPED"; return 0; }
594
+ after="$(_reader_after ', ')"
595
+
596
+ cost="$(jq -r '.cost // "unknown"' <<< "$out")"
597
+ disputes="$(jq -c --argjson answers "$(jq -c '.answers' <<< "$out")" --argjson rows "$rows" \
598
+ --argjson deferred_at "$(_reader_const dispute_deferred_at)" --argjson rejected_at "$(_reader_const dispute_rejected_at)" -n '
599
+ $rows | map(. + {probability: ($answers["row-" + .row].probability // null)})
600
+ | map(select(.probability != null and
601
+ ((.outcome == "deferred" and .probability >= $deferred_at) or
602
+ (.outcome == "rejected" and .probability <= $rejected_at))))')"
603
+ disputed="$(jq -r 'length' <<< "$disputes")"
604
+ # shellcheck disable=SC2034
605
+ { READER_COST="$cost"; READER_DISPUTES="$disputed"; }
606
+ [[ "$cost" == unknown ]] && cost="cost not reported" || cost="\$$cost"
607
+ printf '### Second reader\n\n'
608
+ if [[ "$disputed" -eq 0 ]]; then
609
+ printf '%s read %s deferred or rejected row%s and disputes none (%s)%s.\n' "$READER_BACKEND" "$n" "$([[ "$n" -eq 1 ]] || printf s)" "$cost" "$after"
610
+ return 0
611
+ fi
612
+ printf '%s read %s deferred or rejected row%s and disputes %s (%s)%s.\n\n' "$READER_BACKEND" "$n" "$([[ "$n" -eq 1 ]] || printf s)" "$disputed" "$cost" "$after"
613
+ printf '| Row | Axis | Outcome | Question | Probability |\n| --- | --- | --- | --- | --- |\n'
614
+ jq -r '.[] | "| \(.row) | \(.axis) | \(.outcome) | \(.question) | \(.probability) |"' <<< "$disputes"
615
+ }
616
+
617
+ # _reader_skip <backend> <reason>: the skip form of the subsection, and the reason for the caller.
618
+ _reader_skip() {
619
+ # shellcheck disable=SC2034
620
+ READER_SKIPPED="$2"
621
+ printf '### Second reader\n\nSkipped: %s.\n' "$2"
622
+ }
623
+
624
+ # ---- seam ----------------------------------------------------------------------------------
625
+
626
+ # _reader_seam <repo> <brief> <log>: the seam call. One question, keyed `seam`, against the
627
+ # brief, with stage 2's predicate as the criteria. Prints one line: the call, then the backend
628
+ # and the probability, or `skipped:`/`failed:` and the reason, and leaves the same line in
629
+ # READER_SEAM for a sourcing caller.
630
+ _reader_seam() {
631
+ local repo="${1:-}" brief="${2:-}" log="${3:-}" dir state questions out code p call
632
+ [[ $# -eq 3 && -n "$repo" && -n "$brief" && -n "$log" ]] || { _reader_refuse "seam needs <repository> <brief> <log>"; return 64; }
633
+ [[ -d "$repo" ]] || { _reader_refuse "seam: no repository at $repo"; return 64; }
634
+ [[ -f "$brief" ]] || { _reader_refuse "seam: no brief at $brief"; return 64; }
635
+ # shellcheck disable=SC2034
636
+ { READER_SEAM=""; READER_BACKEND=""; READER_COST=0; READER_LOG=""; READER_SKIPPED=""; READER_FALLBACK=""; READER_CONTEXT=""; }
637
+
638
+ dir="$(mktemp -d)"
639
+ state="$dir/state.txt"; questions="$dir/questions.json"
640
+ {
641
+ cat <<'RULES'
642
+ # Rules
643
+
644
+ You are the second reader of a brief that an unattended build is about to work from. Before the build starts, the driver decides whether the change has a testable seam: whether a test can observe the behaviour the brief describes. Answer the question from the brief alone. A dependency bump, a config or workflow YAML edit, a copy change and a pure rename have no behaviour a test can observe. Size is not the predicate: a two-line change with observable behaviour has a seam.
645
+
646
+ # Brief
647
+
648
+ RULES
649
+ cat "$brief"
650
+ } > "$state"
651
+ jq -c -n '{seam: {type: "boolean",
652
+ instructions: "Does the brief describe behaviour a test can observe?",
653
+ criteria: {true: "the brief asks for behaviour a test can observe: a function, a command, a script, a query or a screen whose output, exit, state or rendering a test can check, whatever the size of the change",
654
+ false: "the brief asks for nothing a test can observe: a dependency bump, a config or workflow YAML edit, a copy change, or a pure rename with no behaviour of its own"}}}' > "$questions"
655
+ mkdir -p "$(dirname "$log")"
656
+ out="$(_reader_ask "$repo" "$state" "$questions" "$log" 2>/dev/null)"; code=$?
657
+ rm -rf "$dir"
658
+
659
+ # Under a worktree's ledger logs/, the answer's names take the `logs/<name>` form the audit
660
+ # and the ledger use.
661
+ _reader_read_answer "$out" "$code" "$log" || {
662
+ code=$?
663
+ if [[ "$code" -eq 2 ]]; then READER_SEAM="tdd skipped: $READER_SKIPPED"; else READER_SEAM="tdd failed: $READER_SKIPPED"; fi
664
+ printf '%s\n' "$READER_SEAM"; return "$code"
665
+ }
666
+ p="$(jq -r '.answers.seam.probability | select(type == "number")' <<< "$out" 2>/dev/null)"
667
+ if [[ -z "$p" ]]; then
668
+ READER_SKIPPED="$READER_BACKEND answered with no probability for seam$(_reader_after ', ')"
669
+ READER_SEAM="tdd failed: $READER_SKIPPED"; printf '%s\n' "$READER_SEAM"; return 1
670
+ fi
671
+ # shellcheck disable=SC2034 # read by the caller for its ledger line
672
+ READER_COST="$(jq -r '.cost // "unknown"' <<< "$out")"
673
+ call=tdd
674
+ if jq -e -n --argjson p "$p" --argjson at "$(_reader_const seam_no_seam_at)" '$p <= $at' >/dev/null 2>&1; then call=no-seam; fi
675
+ READER_SEAM="$call reader=$READER_BACKEND probability=$p$(_reader_after ' ')"
676
+ printf '%s\n' "$READER_SEAM"
677
+ }
678
+
679
+ # ---- the one function ----------------------------------------------------------------------
680
+
681
+ reader() {
682
+ local verb="${1:-}"
683
+ [[ $# -eq 0 ]] || shift
684
+ case "$verb" in
685
+ mode|ask|audit|seam) "_reader_$verb" "$@" ;;
686
+ -h|--help|help) _reader_usage ;;
687
+ "") _reader_usage >&2; return 64 ;;
688
+ *) _reader_refuse "unknown verb '$verb'"; return 64 ;;
689
+ esac
690
+ }
691
+
692
+ if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then reader "$@"; exit $?; fi