@krysoworks/kryso 0.0.2 → 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 (163) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +146 -6
  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 +55 -22
  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
  163. package/bin/kryso.js +0 -11
@@ -0,0 +1,722 @@
1
+ #!/usr/bin/env bash
2
+ # stages/settle.sh: the warden's settlement stage, run by warden.sh after the shift as its
3
+ # own process.
4
+ #
5
+ # settle.sh <repo> <watch-dir> read the candidates and settle them; prints one result object
6
+ # settle.sh --dry-run <repo> print the range and the candidates with what selected each; start no context
7
+ #
8
+ # The driver exports KRYSO_WATCH_CONFIG (the resolved config, base included), KRYSO_WATCH_BASE_SHA,
9
+ # KRYSO_WATCH_ID, KRYSO_SHIFT_SKILL_DIR and KRYSO_WATCH_STATE_FILE. Settlement reads only when the
10
+ # fetched base moved past the settled sha in the state file, and it never checks the base
11
+ # out: the range is read from the fetched ref. Candidates are chosen here, in shell: open
12
+ # issues cited by number in a commit message or a merged pull request in the range, or
13
+ # carrying a label whose configured paths meet the paths the range touched. When the
14
+ # repository's second reader is on, one ask per watch screens them before any context
15
+ # starts: a candidate the reader puts below the configured floor is read by no context, and
16
+ # the rest are ordered by its probability. Each one left, capped, gets one fresh context that
17
+ # reads the issue against its acceptance criteria and the range and returns a verdict. The
18
+ # context requests and this body authorises: a shipped verdict closes the issue only when
19
+ # every criterion has an evidence row and every ref resolves on the base, a superseded
20
+ # verdict parks the issue on the decision report, and an open verdict changes nothing. The
21
+ # reader's answers order and skip the reading and authorise nothing. ADR 0004 and
22
+ # reference/settlement.md say why.
23
+ set -uo pipefail
24
+
25
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
26
+ WARDEN_DIR="$(dirname "$HERE")"
27
+ OUTCOME_SCHEMA="$WARDEN_DIR/settle.schema.json"
28
+ SETTLED_MARKER='<!-- warden:settled'
29
+ # The commit list and the touched paths a context receives are bounded, so a long range
30
+ # still fits a prompt. The context reads the rest from the fetched ref.
31
+ MAX_COMMITS=300
32
+ MAX_PATHS=500
33
+
34
+ MODE=watch
35
+ if [[ "${1:-}" == --dry-run ]]; then MODE=dry; shift; fi
36
+ REPO_ROOT="${1:-}"
37
+ WATCH_DIR="${2:-}"
38
+
39
+ ISSUES_JSON='[]'
40
+ # The confirmed out-of-scope closes, kept apart so the range's record of what it read stays its own.
41
+ CONFIRMED_JSON='[]'
42
+ CANDIDATES_JSON='[]'
43
+ EXCLUDED_JSON='[]'
44
+ BACKLOG_JSON='[]'
45
+ RANGE_JSON='null'
46
+ # What the second reader did, for the result: null while the reader is off.
47
+ READER_JSON='null'
48
+ # The settled sha and the backlog for the state file, set once the stage knows them and left
49
+ # out of the result on a stop, so the state keeps what the last full run recorded.
50
+ STATE_JSON=''
51
+ # result <extra-json>: the stage's one result object, with every list it has so far.
52
+ result() {
53
+ local extra="${1:-}"
54
+ [[ -n "$extra" ]] || extra='{}'
55
+ jq -cn --argjson issues "$ISSUES_JSON" --argjson candidates "$CANDIDATES_JSON" --argjson excluded "$EXCLUDED_JSON" \
56
+ --argjson range "$RANGE_JSON" --argjson state "${STATE_JSON:-null}" --argjson reader "$READER_JSON" --argjson extra "$extra" \
57
+ --argjson confirmed "$CONFIRMED_JSON" '
58
+ def n($s): $issues | map(select(.state == $s)) | length;
59
+ def c($s): $confirmed | map(select(.state == $s)) | length;
60
+ {found: (($candidates | length) + ($confirmed | length)), open: (n("superseded") + n("unproven") + c("unproven")),
61
+ counts: ((if ($candidates | length) == 0 then {}
62
+ else {closed: n("closed"), superseded: n("superseded"), open: n("open"), unproven: n("unproven"), refused: n("refused")}
63
+ + (if $reader != null then {screened: n("screened")} else {} end) end)
64
+ + (if ($confirmed | length) == 0 then {}
65
+ else {wontfix: c("wontfix")} + (if c("unproven") > 0 then {unproven: (n("unproven") + c("unproven"))} else {} end) end)),
66
+ candidates: $candidates, excluded: $excluded, issues: ($confirmed + $issues), range: $range,
67
+ reason: (if ($candidates | length) == 0 then "nothing to settle"
68
+ else "\($candidates | length) candidate(s): \(n("closed")) closed, \(n("superseded")) superseded, \(n("open")) open, \(n("unproven")) unproven, \(n("refused")) refused\(if $reader != null then ", \(n("screened")) screened" else "" end)" end)}
69
+ + (if $reader != null then {reader: $reader} else {} end)
70
+ + (if $state != null then $state else {} end) + $extra
71
+ | if ($confirmed | length) == 0 or .stop then .
72
+ else .reason = "\(c("wontfix")) confirmed out-of-scope request(s) closed as wontfix\(if c("unproven") > 0 then ", \(c("unproven")) with no ledger file on the base" else "" end); \(.reason)" end'
73
+ exit 0
74
+ }
75
+
76
+ # stop <check> <reason>: an environment stop. In a watch it is the stage's result, carrying
77
+ # whatever was settled before it; in a dry run it is the driver's stop line and exit 3.
78
+ stop() {
79
+ if [[ "$MODE" == dry ]]; then echo "warden: stop environment ($1): $2" >&2; exit 3; fi
80
+ STATE_JSON=''
81
+ result "$(jq -cn --arg check "$1" --arg reason "$2" '{stop: "environment", check: $check, reason: $reason}')"
82
+ }
83
+
84
+ [[ -n "$REPO_ROOT" && -n "${KRYSO_WATCH_CONFIG:-}" && -n "${KRYSO_WATCH_BASE_SHA:-}" ]] \
85
+ || { echo "settle: needs <repo>, KRYSO_WATCH_CONFIG and KRYSO_WATCH_BASE_SHA from warden.sh" >&2; exit 64; }
86
+ [[ "$MODE" == dry || -n "$WATCH_DIR" ]] || { echo "settle: needs <watch-dir> outside a dry run" >&2; exit 64; }
87
+ cd "$REPO_ROOT" || stop repo "cannot enter $REPO_ROOT"
88
+
89
+ CONFIG="$KRYSO_WATCH_CONFIG"
90
+ cfg() { jq -r "$1" <<< "$CONFIG"; }
91
+ BASE="$(cfg .base)"
92
+ NOW="$KRYSO_WATCH_BASE_SHA"
93
+ BASE_REF="refs/remotes/origin/$BASE"
94
+ CAP="$(cfg .caps.settle)"
95
+ LOG_LABEL="$(cfg .labels.log)"
96
+ REPORT_LABEL="$(cfg .labels.report)"
97
+ DEFERRED_LABEL="$(cfg .labels.deferred)"
98
+ AREAS="$(jq -c '.areas // {}' <<< "$CONFIG")"
99
+ export LOG_LABEL REPORT_LABEL
100
+ # shellcheck source=../tracker.sh
101
+ source "$WARDEN_DIR/tracker.sh" || stop install "cannot source $WARDEN_DIR/tracker.sh"
102
+ # shellcheck source=../stage-common.sh
103
+ source "$WARDEN_DIR/stage-common.sh" || stop install "cannot source $WARDEN_DIR/stage-common.sh"
104
+ # shellcheck source=../board.sh
105
+ source "$WARDEN_DIR/board.sh" || stop install "cannot source $WARDEN_DIR/board.sh"
106
+ # shellcheck source=../base-refs.sh
107
+ source "$WARDEN_DIR/base-refs.sh" || stop install "cannot source $WARDEN_DIR/base-refs.sh"
108
+ ROLE_MAP="$(role_map "$REPO_ROOT")"
109
+ label_for() { jq -r --arg r "$1" '.[$r]' <<< "$ROLE_MAP"; }
110
+ SETTLE_DIR="${WATCH_DIR:+$WATCH_DIR/settle}"
111
+
112
+ # ---- the writes --------------------------------------------------------------------------
113
+ #
114
+ # Every write goes through tracker_write and is recorded. A write the tracker refuses is an
115
+ # environment stop: the issue is left part-applied, and the record says exactly how far.
116
+
117
+ WRITES='[]'
118
+ WRITE_ERR=""
119
+ write() {
120
+ WRITES="$(jq -c --arg w "gh $*" '. + [$w]' <<< "$WRITES")"
121
+ WRITE_ERR="$(tracker_write "$@" 2>&1 >/dev/null)" || { WRITE_ERR="$(head -1 <<< "$WRITE_ERR")"; return 1; }
122
+ }
123
+
124
+ save_record() { printf '%s\n' "$2" | jq . > "$SETTLE_DIR/$1.json"; }
125
+ note_state() { ISSUES_JSON="$(jq -c --argjson n "$1" --arg s "$2" '. + [{issue: $n, state: $s}]' <<< "$ISSUES_JSON")"; }
126
+
127
+ # stop_on_write <n> <record> <outcome> <what>: a refused or failed write ends the stage as an
128
+ # environment stop, with the record naming every write made before it.
129
+ stop_on_write() {
130
+ save_record "$1" "$(jq -c --argjson o "$3" --argjson w "$WRITES" --arg what "$4" \
131
+ '. + {outcome: $o, applied: {verdict: "stopped", reason: "\($what) failed", writes: $w}}' <<< "$2")"
132
+ note_state "$1" stopped
133
+ stop "tracker write" "$4 on #$1 failed${WRITE_ERR:+: $WRITE_ERR}"
134
+ }
135
+
136
+ # state_labels <n> <held-json> <role>: the label edit that moves an issue to the role, its
137
+ # label replacing any other state label the issue holds. Nothing when it holds it already.
138
+ state_labels() {
139
+ state_edit "$ROLE_MAP" "$2" "$(label_for "$3")"
140
+ [[ "${#STATE_ADD[@]}" -gt 0 || "${#STATE_REMOVE[@]}" -gt 0 ]] || return 0
141
+ write issue edit "$1" ${STATE_ADD[@]+"${STATE_ADD[@]}"} ${STATE_REMOVE[@]+"${STATE_REMOVE[@]}"}
142
+ }
143
+
144
+ # ---- the confirmed out-of-scope closes -----------------------------------------------------
145
+ #
146
+ # A person confirmed on the decision report that triage's match to the out-of-scope ledger
147
+ # stands, and the report handed the issue here with the confirmation marker. Each open issue
148
+ # whose last parking, release or confirmation comment is a confirmation is closed when the
149
+ # file it names is on the fetched base: labelled wontfix, and closed with a comment linking
150
+ # the file. A file the base does not have closes nothing: the issue is parked on the decision
151
+ # report with one item asking a person to release it or close it by hand. None of this needs
152
+ # a range, so it runs on every watch, before the settled sha is read.
153
+ # Adding the issue under the file's Prior requests is a person's step, since the warden never
154
+ # writes the working tree (ADR 0033).
155
+
156
+ POOL="$(gh issue list --state open --limit 1000 \
157
+ --json number,title,body,url,labels,createdAt,author,comments,projectItems 2>&1)" \
158
+ || stop "settle reads" "cannot list the open issues: $(head -1 <<< "$POOL")"
159
+ jq -e 'type == "array"' <<< "$POOL" >/dev/null 2>&1 || stop "settle reads" "the open-issue list is not a JSON array"
160
+ POOL="$(markers_read "$POOL")"
161
+
162
+ # The last close this stage made for a confirmation counts as a later marker, so an issue a
163
+ # person reopens after it is not closed again. The warden's own issues and Deferred ones are
164
+ # left alone, as every stage leaves them.
165
+ CONFIRMS="$(jq -c --arg m "$CONFIRM_MARKER" --arg parked "$PARK_MARKER" --arg released "$RELEASE_MARKER" \
166
+ --arg closed "$SETTLED_MARKER" --arg log "$LOG_LABEL" --arg report "$REPORT_LABEL" --arg deferred "$DEFERRED_LABEL" "$EXCLUSIONS_JQ"'
167
+ [.[] | select(own_exclusion($log; $report; $deferred) == null)
168
+ | ([(.comments // [])[] | (.body // "")
169
+ | select(contains($m) or contains($parked) or contains($released) or (contains($closed) and contains(" wontfix=")))] | last) as $last
170
+ | select($last != null and ($last | contains($m)))
171
+ | ([$last | capture("report=(?<report>[0-9]+) q=(?<q>[0-9,]+) file=(?<file>[^ ]+)")] | first) as $c
172
+ | select($c != null)
173
+ | {issue: .number, url, labels: [.labels[]?.name]} + $c] | sort_by(.issue)' <<< "$POOL" 2>&1)" \
174
+ || stop "settle reads" "cannot read the confirmations: $(head -1 <<< "$CONFIRMS")"
175
+
176
+ # on_base <file>: true when the file is a ledger file the fetched base has.
177
+ on_base() { [[ "$1" =~ ^\.out-of-scope/[^/]+\.md$ ]] && git cat-file -e "$BASE_REF:$1" 2>/dev/null; }
178
+
179
+ note_confirmed() { CONFIRMED_JSON="$(jq -c --argjson n "$1" --arg s "$2" '. + [{issue: $n, state: $s}]' <<< "$CONFIRMED_JSON")"; }
180
+
181
+ # park_on_report <n> <held-json> <lead> <items-json> <record> <outcome>: the issue parked on
182
+ # the decision report the way triage parks one: needs-info, a comment that opens with the lead
183
+ # line, lists the items and ends in the parking marker, and the items left for the report body
184
+ # to post. A refused write stops the stage with the record and the outcome.
185
+ park_on_report() {
186
+ local n="$1" f
187
+ state_labels "$n" "$2" needs-info || stop_on_write "$n" "$5" "$6" "the label edit"
188
+ f="$SETTLE_DIR/$n.comment.md"
189
+ comment_file "$f" "$(jq -r --arg lead "$3" --arg marker "$PARK_MARKER" --arg watch "${KRYSO_WATCH_ID:-}" '
190
+ "## Settlement", "", $lead, "",
191
+ "**Parked:** this issue waits on one decision the warden could not make. It goes to the decision report:", "",
192
+ (.[] | "- **\(.title)** (item \(.id)): \(.why)"), "",
193
+ "\($marker) watch=\($watch) items=\([.[].id] | join(",")) -->"' <<< "$4")"
194
+ write issue comment "$n" --body-file "$f" || stop_on_write "$n" "$5" "$6" "the parking comment"
195
+ add_report_items "$WATCH_DIR" "$4"
196
+ }
197
+
198
+ # gone_park <confirmation-json> <q-list> <record-json>: a confirmation whose file the base no
199
+ # longer has is put to a person on the report, as one item, <n>.gone. The parking marker is
200
+ # the issue's last one after this, so no later watch reads the confirmation again. The item
201
+ # carries no file, so every answer to it releases the issue with the answer on it, as ADR 0033
202
+ # has it for the other close items with no file, and no answer hands it back here. Closing it
203
+ # stays a person's step, since settlement closes a confirmed match only on a file the base has.
204
+ gone_park() {
205
+ local c="$1" record="$3" n items
206
+ n="$(jq -r .issue <<< "$c")"
207
+ items="$(jq -cn --argjson c "$c" --arg q "$2" --arg watch "${KRYSO_WATCH_ID:-}" --arg base "$BASE" --arg now "${NOW:0:12}" '[{
208
+ id: "\($c.issue).gone", issue: $c.issue, url: $c.url, watch: $watch, source: "settle",
209
+ title: "#\($c.issue)'"'"'s ledger file is gone: release it, or close it by hand?",
210
+ why: "A person confirmed on decision report #\($c.report) (\($q)) that `\($c.file)` refuses it, but `\($base)` at `\($now)` no longer has that file, so settlement has nothing to cite and closes nothing. Whoever removed the file may have lifted the refusal or moved it to another file.",
211
+ options: [{label: "release it", consequence: "it goes back to the queue with this answer on it, to be worked like any other request"},
212
+ {label: "close it by hand", consequence: "the warden closes nothing, since settlement closes a confirmed match only while its file is on `\($base)`: it goes back to the queue with this answer on it, and a person closes it"}],
213
+ recommended: 0}]')"
214
+ park_on_report "$n" "$(jq -c .labels <<< "$c")" "**Ledger file gone:** \`$(jq -r .file <<< "$c")\` is not on \`$BASE\`, so the confirmed close has no file to cite." \
215
+ "$items" "$record" null
216
+ save_record "$n" "$(jq -c --argjson w "$WRITES" --argjson items "$items" \
217
+ '.applied += {state: "parked", writes: $w, report_items: [$items[].id]}' <<< "$record")"
218
+ note_confirmed "$n" unproven
219
+ }
220
+
221
+ confirm_close() {
222
+ local c="$1" n file report q url held f record
223
+ WRITES='[]'
224
+ n="$(jq -r .issue <<< "$c")"; file="$(jq -r .file <<< "$c")"; report="$(jq -r .report <<< "$c")"
225
+ q="Q$(jq -r '.q | split(",") | join(", Q")' <<< "$c")"; url="$(jq -r .url <<< "$c")"
226
+ record="$(jq -c '{issue, candidate: "confirmed out of scope on the decision report", confirmed: {report, q, file}}' <<< "$c")"
227
+ if ! on_base "$file"; then
228
+ gone_park "$c" "$q" "$(jq -c --arg why "$file is not on $BASE, so the confirmed close has no file to cite" \
229
+ '. + {applied: {verdict: "unproven", reason: $why, writes: []}}' <<< "$record")"
230
+ return 0
231
+ fi
232
+ state_labels "$n" "$(jq -c .labels <<< "$c")" wontfix || stop_on_write "$n" "$record" null "the label edit"
233
+ f="$SETTLE_DIR/$n.comment.md"
234
+ comment_file "$f" "Closed as wontfix: a person confirmed on decision report #$report ($q) that the out-of-scope ledger refuses this request in [\`$file\`](${url%/issues/*}/blob/$NOW/$file), as \`$BASE\` has it at \`${NOW:0:12}\`.
235
+
236
+ Adding this issue under that file's Prior requests is a person's step, since the warden does not write to the repository.
237
+
238
+ $SETTLED_MARKER watch=${KRYSO_WATCH_ID:-} wontfix=$file -->"
239
+ write issue close "$n" --comment "$(cat "$f")" || stop_on_write "$n" "$record" null "the close"
240
+ save_record "$n" "$(jq -c --argjson w "$WRITES" '. + {applied: {verdict: "wontfix", writes: $w}}' <<< "$record")"
241
+ note_confirmed "$n" wontfix
242
+ }
243
+
244
+ if [[ "$MODE" == dry ]]; then
245
+ while IFS= read -r c; do
246
+ [[ -n "$c" ]] || continue
247
+ if on_base "$(jq -r .file <<< "$c")"; then
248
+ jq -r '"warden: settle would close #\(.issue) as wontfix: confirmed on report #\(.report) \(.q | split(",") | map("Q\(.)") | join(", ")), refused by \(.file)"' <<< "$c"
249
+ else
250
+ jq -r --arg base "$BASE" '"warden: settle cannot close #\(.issue) as wontfix: \(.file) is not on \($base), so it would put #\(.issue) to a person on the decision report"' <<< "$c"
251
+ fi
252
+ done < <(jq -c '.[]' <<< "$CONFIRMS")
253
+ elif [[ "$(jq length <<< "$CONFIRMS")" -gt 0 ]]; then
254
+ mkdir -p "$SETTLE_DIR" || stop state "cannot create $SETTLE_DIR"
255
+ while IFS= read -r c; do
256
+ [[ -n "$c" ]] && confirm_close "$c"
257
+ done < <(jq -c '.[]' <<< "$CONFIRMS")
258
+ # A closed issue leaves the pool the range's candidates come from.
259
+ POOL="$(jq -c --argjson closed "$CONFIRMED_JSON" '[$closed[] | select(.state == "wontfix") | .issue] as $d | map(select(.number as $n | $d | index($n) | not))' <<< "$POOL")"
260
+ fi
261
+
262
+ # ---- the settled sha ---------------------------------------------------------------------
263
+ #
264
+ # The state file holds the branch and sha the last full settlement reached, and the backlog
265
+ # a cap left unread. No sha yet, another branch, or a sha this repository no longer has, and
266
+ # this watch fixes the point at the base as it stands and reads nothing: the range before it
267
+ # has no start. The same sha, and there is nothing to read.
268
+
269
+ PREV='{}'
270
+ if [[ -n "${KRYSO_WATCH_STATE_FILE:-}" && -f "$KRYSO_WATCH_STATE_FILE" ]]; then
271
+ PREV="$(jq -c 'select(type == "object")' "$KRYSO_WATCH_STATE_FILE" 2>/dev/null)"
272
+ [[ -n "$PREV" ]] || PREV='{}'
273
+ fi
274
+ # The issues already read against the range that starts at the settled sha, so a watch that
275
+ # drains a backlog does not read them again. Cleared once the sha advances.
276
+ PREV_READ="$(jq -c '[.settled.read // [] | .[] | select(type == "number")]' <<< "$PREV")"
277
+ PREV_BACKLOG="$(jq -c '[.settle_backlog // [] | .[] | select(type == "number")]' <<< "$PREV")"
278
+
279
+ fix_point() {
280
+ STATE_JSON="$(jq -cn --arg b "$BASE" --arg s "$NOW" '{settled: {branch: $b, sha: $s, read: []}, backlog: []}')"
281
+ if [[ "$MODE" == dry ]]; then echo "warden: settle: $1, this watch fixes the settled sha at ${NOW:0:12} and reads nothing"; exit 0; fi
282
+ result "$(jq -cn --arg r "$1, fixed the settled sha at ${NOW:0:12}" '{reason: $r}')"
283
+ }
284
+
285
+ SETTLED_SHA="$(range_start "$BASE" "$NOW" "$(jq -c '.settled // {}' <<< "$PREV")")"
286
+ case $? in
287
+ 0) ;;
288
+ 2) if [[ "$MODE" == dry ]]; then echo "warden: settle: $SETTLED_SHA, nothing to read"; exit 0; fi
289
+ result "$(jq -cn --arg r "$SETTLED_SHA" '{reason: $r}')" ;;
290
+ *) fix_point "$SETTLED_SHA" ;;
291
+ esac
292
+
293
+ # ---- the range ---------------------------------------------------------------------------
294
+ #
295
+ # Everything is read from the fetched ref: the commits with their messages, the paths the
296
+ # range touched, and the merged pull requests whose merge commit is in the range.
297
+
298
+ COMMITS="$(range_commits "$SETTLED_SHA" "$NOW")" || stop "settle reads" "$COMMITS"
299
+ PATHS="$(git diff --name-only "$SETTLED_SHA" "$NOW" 2>&1)" \
300
+ || stop "settle reads" "cannot read the paths ${SETTLED_SHA:0:12}..${NOW:0:12}: $(head -1 <<< "$PATHS")"
301
+ PATHS="$(jq -Rsc 'split("\n") | map(select(length > 0))' <<< "$PATHS")"
302
+ PRS="$(range_prs "$BASE" "$COMMITS")" || stop "settle reads" "$PRS"
303
+ RANGE_JSON="$(jq -cn --arg from "$SETTLED_SHA" --arg to "$NOW" --argjson c "$COMMITS" --argjson p "$PATHS" --argjson prs "$PRS" \
304
+ '{from: $from, to: $to, commits: ($c | length), paths: ($p | length), pull_requests: ($prs | map(.number))}')"
305
+
306
+ # ---- the candidates ----------------------------------------------------------------------
307
+ #
308
+ # The pool is every open issue. An issue is reached by a citation in a commit or a merged
309
+ # pull request in the range, or by a label whose configured globs meet a touched path.
310
+ # Reached issues that are the warden's own, deferred (the label or a card in the Deferred
311
+ # column) or parked on a report item are excluded with their reason. The agent:* labels are a
312
+ # run's machine state (ADR 0031), never a triage state and never a reason to exclude, so an
313
+ # issue a pass parked on is settled like any other. The rest go oldest
314
+ # first, the backlog the last watch carried ahead of them. The second reader may then screen
315
+ # and reorder them, and the cap takes the first of what is left; the ones it leaves are
316
+ # carried to the next watch.
317
+
318
+ SELECTION="$(jq -c --argjson commits "$COMMITS" --argjson prs "$PRS" --argjson paths "$PATHS" --argjson areas "$AREAS" \
319
+ --argjson backlog "$PREV_BACKLOG" --argjson read "$PREV_READ" --arg marker "$PARK_MARKER" --arg released "$RELEASE_MARKER" \
320
+ --arg log "$LOG_LABEL" --arg report "$REPORT_LABEL" --arg deferred "$DEFERRED_LABEL" "$EXCLUSIONS_JQ"'
321
+ # A glob as a regex: ** crosses directories, * and ? stay inside one, and **/ also matches no directory.
322
+ def glob_re: gsub("(?<c>[.+^$(){}|\\[\\]\\\\])"; "\\\(.c)")
323
+ | gsub("\\*\\*/"; "\u0001") | gsub("\\*\\*"; "\u0002") | gsub("\\*"; "[^/]*") | gsub("\\?"; "[^/]")
324
+ | gsub("\u0001"; "(.*/)?") | gsub("\u0002"; ".*") | "^\(.)$";
325
+ def selected_by($n; $labels):
326
+ [$commits[] | select(.cites | index($n)) | {kind: "commit", ref: .sha}]
327
+ + [$prs[] | select(.cites | index($n)) | {kind: "pr", ref: (.number | tostring)}]
328
+ + [$labels[] | . as $l | select($areas | has($l)) | $areas[$l][] | . as $g | (glob_re) as $re
329
+ | [$paths[] | select(test($re))] | first // empty | {kind: "path", label: $l, glob: $g, path: .}];
330
+ def words: if .kind == "commit" then "cited by commit \(.ref[0:12])"
331
+ elif .kind == "pr" then "cited by pull request #\(.ref)"
332
+ else "label \(.label) matches \(.path) via \(.glob)" end;
333
+ [ .[]
334
+ | [.labels[]?.name] as $labels
335
+ | selected_by(.number; $labels) as $by
336
+ | select(($by | length) > 0)
337
+ | own_exclusion($log; $report; $deferred) as $own
338
+ | parked_reason($marker; $released) as $parked
339
+ | {issue: .number, created: .createdAt, by: $by,
340
+ why: (
341
+ if $own != null then {exclude: $own}
342
+ elif $parked != null then {exclude: $parked}
343
+ elif (.number as $n | $read | index($n)) != null then {exclude: "read against this range by an earlier watch"}
344
+ else {include: ($by[0] | words)} end)} ]
345
+ | sort_by((if (.issue as $n | $backlog | index($n)) then 0 else 1 end), .created, .issue)
346
+ | {candidates: [.[] | select(.why.include) | {issue, created, reason: .why.include, by}],
347
+ excluded: [.[] | select(.why.exclude) | {issue, created, reason: .why.exclude}]}' <<< "$POOL" 2>&1)" \
348
+ || stop "settle reads" "cannot read the open-issue list: $(head -1 <<< "$SELECTION")"
349
+ # Every candidate in the order above, before the reader and the cap.
350
+ IN_JSON="$(jq -c .candidates <<< "$SELECTION")"
351
+ EXCLUDED_JSON="$(jq -c .excluded <<< "$SELECTION")"
352
+
353
+ # ---- the second reader -------------------------------------------------------------------
354
+ #
355
+ # When the repository's second reader is on (reader.sh's mode, from PLAYBOOK_SECOND_READER
356
+ # over kryso.secondReader), it is asked once per watch, before any context starts, one
357
+ # question per candidate: whether the range's commits and merged pull requests satisfy every
358
+ # acceptance criterion of that issue. The state it reads is the range as the contexts see it,
359
+ # commit subjects, merged pull request titles and touched paths with no diff, and per issue
360
+ # its title, body and criteria. A candidate below settlement.jev_floor is screened: recorded
361
+ # with its probability and backend, read by no context, and read as far as the settled sha is
362
+ # concerned. The rest are ordered by probability, highest first, ties in the order above, and
363
+ # only then capped. A floor of 0 orders without screening. Off, or with both backends skipping
364
+ # or failing, the candidates go in the order above and the reader's outcome is recorded. The
365
+ # reader writes nothing: every close and every report item still needs a context's verdict.
366
+
367
+ SHIP_LOOP_DIR="${KRYSO_SHIFT_SKILL_DIR:-}"
368
+ FLOOR="$(cfg .settlement.jev_floor)"
369
+ PROFILE="$(cfg .profile)"
370
+
371
+ # criteria_of <body>: the acceptance criteria, one per line, from the body's section.
372
+ criteria_of() {
373
+ jq -rn --arg body "$1" '
374
+ ($body | split("\n")) as $lines
375
+ | ([$lines | to_entries[] | select(.value | test("^##[[:space:]]+Acceptance criteria[[:space:]]*$"; "i")) | .key] | first) as $at
376
+ | if $at == null then empty else
377
+ ([$lines | to_entries[] | select(.key > $at and (.value | test("^#{1,2}[[:space:]]"))) | .key] | first // ($lines | length)) as $next
378
+ | $lines[($at + 1):$next][] | capture("^[[:space:]]*[-*][[:space:]]+(\\[[ xX]\\][[:space:]]*)?(?<c>.+?)[[:space:]]*$") | .c end'
379
+ }
380
+
381
+ # range_jq [jq-args...] <program>: runs a jq program with the range bound and range_md defined.
382
+ # The reader state and a context's prompt both render the range through it, so the two cannot
383
+ # drift apart. $git is the one difference: a context can run git, and the reader has no shell.
384
+ range_jq() {
385
+ local program="${!#}"
386
+ jq -rn --argjson range "$RANGE_JSON" --argjson commits "$COMMITS" --argjson paths "$PATHS" --argjson prs "$PRS" \
387
+ --arg base "$BASE" --argjson maxc "$MAX_COMMITS" --argjson maxp "$MAX_PATHS" "${@:1:$#-1}" '
388
+ # range_md($h; $git): the range under a heading at level $h, its lists one level below.
389
+ def range_md($h; $git):
390
+ def for_git($s): if $git then $s else "" end;
391
+ def shown_sha: if $git then . else .[0:12] end;
392
+ "\($h) The range \($range.from[0:12])..\($range.to[0:12]) on \($base)",
393
+ "",
394
+ "\($h)# Commits (\($commits | length))",
395
+ "",
396
+ ($commits[:$maxc][] | "- \(.sha | shown_sha) \(.subject)"),
397
+ (if ($commits | length) > $maxc then "- and \($commits | length - $maxc) more\(for_git(": git log \($range.from)..\($range.to)"))" else empty end),
398
+ "",
399
+ "\($h)# Merged pull requests in the range",
400
+ "",
401
+ (if ($prs | length) == 0 then "(none)" else ($prs[] | "- #\(.number) \(.title)\(for_git(" (\(.sha))"))") end),
402
+ "",
403
+ "\($h)# Touched paths (\($paths | length))",
404
+ "",
405
+ ($paths[:$maxp][] | "- \(.)"),
406
+ (if ($paths | length) > $maxp then "- and \($paths | length - $maxp) more\(for_git(": git diff --name-only \($range.from) \($range.to)"))" else empty end);
407
+ '"$program"
408
+ }
409
+
410
+ # reader_state <file>: the text every request carries: the rules and the range, bounded the
411
+ # way a context's prompt is.
412
+ reader_state() {
413
+ range_jq '
414
+ "# Rules",
415
+ "",
416
+ "You are the second reader of a warden settlement. Base branch \($base) moved from \($range.from) to \($range.to), and each open issue below was reached by that range: a commit or a merged pull request in it cites the issue, or a path the issue'"'"'s area owns changed. The range is given as its commit subjects, the titles of the pull requests merged in it and the paths it touched, with no diff. For each issue, answer from the range and the issue alone whether the range'"'"'s commits and merged pull requests satisfy every one of its acceptance criteria. A criterion the range says nothing about is not satisfied. Your answers order the reading and decide nothing on their own.",
417
+ "",
418
+ range_md("#"; false),
419
+ "",
420
+ "# Issues"' > "$1"
421
+ }
422
+
423
+ # reader_questions <file>: one boolean question per candidate, keyed by issue number, with the
424
+ # issue'"'"'s title, numbered criteria and body as the text about that key alone.
425
+ reader_questions() {
426
+ local n issue criteria questions='{}'
427
+ while IFS= read -r n; do
428
+ [[ -n "$n" ]] || continue
429
+ issue="$(jq -c --argjson n "$n" '.[] | select(.number == $n)' <<< "$POOL")"
430
+ criteria="$(criteria_of "$(jq -r '.body // ""' <<< "$issue")" | jq -Rsc 'split("\n") | map(select(length > 0))')"
431
+ questions="$(jq -c --argjson n "$n" --argjson issue "$issue" --argjson criteria "$criteria" '
432
+ . + {($n | tostring): {
433
+ type: "boolean",
434
+ instructions: "Do the range'"'"'s commits and merged pull requests satisfy every acceptance criterion of issue #\($n)?",
435
+ criteria: {true: "every acceptance criterion of issue #\($n) is met by a commit or a merged pull request in the range",
436
+ false: "at least one acceptance criterion of issue #\($n) is met by nothing in the range"},
437
+ state: (["## Issue #\($n): \($issue.title)", "", "### Acceptance criteria", "",
438
+ (if ($criteria | length) == 0 then "(the issue lists none)" else ($criteria | to_entries[] | "\(.key + 1). \(.value)") end),
439
+ "", "### Body", "", ($issue.body // "")] | join("\n"))}}' <<< "$questions")"
440
+ done < <(jq -r '.[].issue' <<< "$IN_JSON")
441
+ printf '%s\n' "$questions" > "$1"
442
+ }
443
+
444
+ screen() {
445
+ local mode code dir log out backend
446
+ [[ "$(jq length <<< "$IN_JSON")" -gt 0 ]] || return 0
447
+ if [[ ! -f "$SHIP_LOOP_DIR/reader.sh" ]]; then
448
+ # An older ship-loop beside the warden: worth a line only where the switch asks for a reader.
449
+ mode="${PLAYBOOK_SECOND_READER:-$(git config --get kryso.secondReader 2>/dev/null || git config --get playbook.secondReader 2>/dev/null)}"
450
+ [[ -z "$mode" || "$mode" == off ]] || READER_JSON="$(jq -cn --arg d "$SHIP_LOOP_DIR" '{backend: null, skipped: "reader.sh is not installed in \($d)"}')"
451
+ return 0
452
+ fi
453
+ # shellcheck source=/dev/null
454
+ source "$SHIP_LOOP_DIR/reader.sh" || stop install "cannot source $SHIP_LOOP_DIR/reader.sh"
455
+ mode="$(reader mode "$REPO_ROOT" 2>&1)"; code=$?
456
+ if [[ "$code" -ne 0 ]]; then READER_JSON="$(jq -cn --arg r "${mode#reader: }" '{backend: null, skipped: $r}')"; return 0; fi
457
+ [[ "${mode%% *}" != off ]] || return 0
458
+ # The LLM backend runs on the configured profile, the one the contexts run on.
459
+ # shellcheck disable=SC2034 # both read by reader.sh
460
+ { READER_PROFILE="$PROFILE"; READER_PROFILE_FILE="${KRYSO_PROFILE_FILE:-}"; }
461
+ if [[ "$MODE" == dry ]]; then dir="$(mktemp -d)"
462
+ else dir="$SETTLE_DIR"; mkdir -p "$dir" || stop state "cannot create $dir"; fi
463
+ log="$dir/reader.jsonl"
464
+ reader_state "$dir/reader-state.md"
465
+ reader_questions "$dir/reader-questions.json"
466
+ out="$(reader ask "$REPO_ROOT" "$dir/reader-state.md" "$dir/reader-questions.json" "$log")"; code=$?
467
+ [[ "$MODE" != dry ]] || rm -rf "$dir"
468
+ backend="$(jq -r '.backend // empty' <<< "$out" 2>/dev/null)"
469
+ case "$code" in
470
+ 0) ;;
471
+ 2) READER_JSON="$(jq -c '{backend, skipped} + (if .fallback then {fallback} else {} end)' <<< "$out")"; return 0 ;;
472
+ *) READER_JSON="$(jq -c --argjson code "$code" '{backend, failed: (.failed // "ask returned \($code)")} + (if .fallback then {fallback} else {} end)' <<< "$out")"; return 0 ;;
473
+ esac
474
+ IN_JSON="$(jq -c --argjson answers "$(jq -c '.answers // {}' <<< "$out")" --arg backend "$backend" --argjson floor "$FLOOR" '
475
+ map(($answers[(.issue | tostring)].probability // null) as $p
476
+ | if $p == null then . else . + {probability: $p, backend: $backend} + (if $p < $floor then {state: "screened"} else {} end) end)
477
+ | sort_by(-(.probability // -1))' <<< "$IN_JSON")"
478
+ # A candidate the reader gave no probability is neither screened nor ordered: it goes after
479
+ # the answered ones, and the result names it, so a short answer set is visible.
480
+ READER_JSON="$(jq -c --argjson in "$IN_JSON" '
481
+ {backend, asked: ($in | length), screened: ([$in[] | select(.state == "screened")] | length), cost}
482
+ + (if .fallback then {fallback} else {} end)
483
+ + ([$in[] | select(.probability == null) | .issue] | if length > 0 then {unanswered: .} else {} end)' <<< "$out")"
484
+ }
485
+ screen
486
+
487
+ # ---- the cap -----------------------------------------------------------------------------
488
+ #
489
+ # The screened candidates stay in the list, so the manifest and the summary show them with
490
+ # their probability, and the cap takes the first of the rest; what it leaves is carried.
491
+
492
+ SELECTION="$(jq -c --argjson cap "$CAP" '
493
+ [.[] | select(.state == "screened")] as $screened
494
+ | [.[] | select(.state != "screened")] as $kept
495
+ | {candidates: (($kept[:$cap] + $screened) | map(del(.created))),
496
+ backlog: [$kept[$cap:][] | .issue],
497
+ over: [$kept[$cap:][] | {issue, created, reason: "over the cap: caps.settle is \($cap), carried to the next watch"}]}' <<< "$IN_JSON")"
498
+ CANDIDATES_JSON="$(jq -c .candidates <<< "$SELECTION")"
499
+ BACKLOG_JSON="$(jq -c .backlog <<< "$SELECTION")"
500
+ EXCLUDED_JSON="$(jq -c --argjson over "$(jq -c .over <<< "$SELECTION")" '(. + $over) | sort_by(.created, .issue) | map({issue, reason})' <<< "$EXCLUDED_JSON")"
501
+
502
+ if [[ "$MODE" == dry ]]; then
503
+ jq -rn --argjson pool "$POOL" --argjson range "$RANGE_JSON" --arg base "$BASE" --argjson reader "$READER_JSON" --argjson floor "$FLOOR" \
504
+ --argjson candidates "$CANDIDATES_JSON" --argjson excluded "$EXCLUDED_JSON" --argjson backlog "$BACKLOG_JSON" '
505
+ def title: . as $n | $pool[] | select(.number == $n) | .title;
506
+ def after: if .fallback then ", after \(.fallback)" else "" end;
507
+ [$candidates[] | select(.state == "screened")] as $screened
508
+ | "warden: settle: base \($base) moved from \($range.from[0:12]) to \($range.to[0:12]): \($range.commits) commit(s), \($range.paths) path(s), \($range.pull_requests | length) merged pull request(s)",
509
+ (if $reader == null then empty
510
+ elif $reader.skipped then "warden: settle: second reader\(if $reader.backend then " \($reader.backend)" else "" end) skipped: \($reader.skipped)\($reader | after)"
511
+ elif $reader.failed then "warden: settle: second reader \($reader.backend) failed: \($reader.failed)\($reader | after), every candidate goes to a context"
512
+ else "warden: settle: second reader \($reader.backend) screened \($reader.screened) of \($reader.asked) candidate(s) below the floor \($floor) (\(if $reader.cost == null then "cost not reported" else "$\($reader.cost)" end))\($reader | after)" end),
513
+ ([$candidates[] | select(.state != "screened")] | to_entries[] | .key as $k | .value as $c
514
+ | "warden: settle candidate \($k + 1)\(if $c.probability != null then " (probability \($c.probability))" elif $reader.asked then " (no answer)" else "" end): #\($c.issue) (\($c.reason)) \($c.issue | title)"),
515
+ ($screened[] | "warden: settle screened #\(.issue) (probability \(.probability), below the floor \($floor)): \(.issue | title)"),
516
+ ($excluded[] | "warden: settle excluded #\(.issue): \(.reason)"),
517
+ "warden: settle: \($candidates | length) candidate(s), \(if $reader != null then "\($screened | length) screened, " else "" end)\($excluded | length) excluded, \($backlog | length) carried"'
518
+ exit 0
519
+ fi
520
+
521
+ # The state this watch reaches once it stops reading: the base as it stands when no
522
+ # candidate is left, or, with a backlog, the settled sha where it was with the issues read so
523
+ # far, so the next watch reads the same range again, starting with what this one left and
524
+ # skipping what it read.
525
+ settle_state() {
526
+ local read
527
+ read="$(jq -c --argjson prev "$PREV_READ" '$prev + [.[] | select(.state != "rate-limited" and .state != "stopped") | .issue] | unique' <<< "$ISSUES_JSON")"
528
+ if [[ "$(jq length <<< "$BACKLOG_JSON")" -eq 0 ]]; then
529
+ STATE_JSON="$(jq -cn --arg b "$BASE" --arg s "$NOW" '{settled: {branch: $b, sha: $s, read: []}, backlog: []}')"
530
+ else
531
+ STATE_JSON="$(jq -cn --arg b "$BASE" --arg s "$SETTLED_SHA" --argjson read "$read" --argjson backlog "$BACKLOG_JSON" \
532
+ '{settled: {branch: $b, sha: $s, read: $read}, backlog: $backlog}')"
533
+ fi
534
+ }
535
+
536
+ if [[ "$(jq length <<< "$CANDIDATES_JSON")" -eq 0 ]]; then settle_state; result; fi
537
+
538
+ # ---- the context -------------------------------------------------------------------------
539
+
540
+ SHIP_LOOP_DIR="${KRYSO_SHIFT_SKILL_DIR:-}"
541
+ [[ -f "$SHIP_LOOP_DIR/runner.sh" && -f "$SHIP_LOOP_DIR/result.sh" ]] \
542
+ || stop install "cannot find ship-loop's runner.sh and result.sh in '${SHIP_LOOP_DIR}'"
543
+ # shellcheck source=/dev/null
544
+ source "$SHIP_LOOP_DIR/runner.sh" || stop install "cannot source $SHIP_LOOP_DIR/runner.sh"
545
+ # shellcheck source=/dev/null
546
+ source "$SHIP_LOOP_DIR/result.sh" || stop install "cannot source $SHIP_LOOP_DIR/result.sh"
547
+ BUDGET="$(cfg .caps.budget)"
548
+ RUNNER_ERR="$WATCH_DIR/settle-runner.err"
549
+ runner_profile_load "$PROFILE" "${KRYSO_PROFILE_FILE:-}" 2> "$RUNNER_ERR" \
550
+ || stop runner "cannot load profile '$PROFILE': $(head -1 "$RUNNER_ERR")"
551
+ runner_validate_options 0 "$BUDGET" 0 "$RUNNER_EFFORT" 2> "$RUNNER_ERR" || stop runner "$(head -1 "$RUNNER_ERR")"
552
+ rm -f "$RUNNER_ERR"
553
+ mkdir -p "$SETTLE_DIR" || stop state "cannot create $SETTLE_DIR"
554
+
555
+ # prompt <issue-json> <criteria-json>: what one context receives: the issue with its criteria
556
+ # and comments, the range's commits and touched paths, and the outcome's words.
557
+ prompt() {
558
+ range_jq --argjson issue "$1" --argjson criteria "$2" '
559
+ "Settle issue #\($issue.number) unattended, as one fresh context of a warden watch. Base branch \($base) moved from \($range.from) to \($range.to), and this issue was reached by that range. Read the issue below against its acceptance criteria and the range, and return a verdict: shipped when the range, or \($base) as it now stands, satisfies every acceptance criterion; superseded when \($base) took another route and the issue no longer applies as written; open when something it asks for is still missing. Nobody is here to answer, so never ask a person and never wait for direction. Read only: run git and gh reads against the fetched ref (git show, git log, git diff, gh pr view), and write nothing to the tracker, the board or the working tree, and check nothing out. The driver applies the outcome, and it closes the issue only when every criterion has an evidence row whose ref resolves to a commit or a merged pull request on \($base): name each criterion word for word as it is listed below, or by its number, and give a full commit sha or a pull request number as the ref. A criterion you cannot tie to a commit or pull request goes in unmet, and the verdict is then open, not shipped.",
560
+ "",
561
+ "## Issue #\($issue.number): \($issue.title)",
562
+ "",
563
+ "\($issue.url)",
564
+ "",
565
+ "### Acceptance criteria",
566
+ "",
567
+ (if ($criteria | length) == 0 then "(the issue lists none)" else ($criteria | to_entries[] | "\(.key + 1). \(.value)") end),
568
+ "",
569
+ "### Body",
570
+ "",
571
+ ($issue.body // ""),
572
+ "",
573
+ "### Comments",
574
+ "",
575
+ (if (($issue.comments // []) | length) == 0 then "(none)"
576
+ else ($issue.comments[] | "--- \(.author.login // "someone") at \(.createdAt // "")", (.body // "" | .[0:4000]), "") end),
577
+ "",
578
+ range_md("##"; true)'
579
+ }
580
+
581
+ # ---- the board ---------------------------------------------------------------------------
582
+
583
+ # move_to_done <issue-json>: the issue's card moved to the Done column on each board it is a
584
+ # card on, through board.sh. A repository without a board, a board without a Status field or
585
+ # one without a Done option is a no-op, recorded with its reason in BOARD_RECORD. A failed
586
+ # read or write is in BOARD_ERR with status 1.
587
+ move_to_done() {
588
+ local issue="$1" titles
589
+ titles="$(jq -r '.projectItems[]? | .title' <<< "$issue")"
590
+ if [[ -z "$titles" ]]; then BOARD_RECORD='{"moved": false, "reason": "not a card on a board"}'; return 0; fi
591
+ board_set "$(jq -r .number <<< "$issue")" "$titles" Status=Done || return 1
592
+ BOARD_RECORD="$(jq -cn --argjson m "$BOARD_WRITES" '{moved: ($m > 0), reason: (if $m > 0 then "moved to Done" else ($ARGS.positional | join("; ")) end)}' \
593
+ --args -- ${BOARD_SKIPPED[@]+"${BOARD_SKIPPED[@]}"})"
594
+ }
595
+
596
+ # ---- one candidate -----------------------------------------------------------------------
597
+
598
+ settle_one() {
599
+ local n="$1" reason="$2" host="$SETTLE_DIR/$1.host.json" issue criteria code limit outcome why base_record
600
+ local verdict checked missing unresolved f held items
601
+ WRITES='[]'
602
+ issue="$(jq -c --argjson n "$n" '.[] | select(.number == $n)' <<< "$POOL")"
603
+ criteria="$(criteria_of "$(jq -r '.body // ""' <<< "$issue")" | jq -Rsc 'split("\n") | map(select(length > 0))')"
604
+ prompt "$issue" "$criteria" > "$SETTLE_DIR/$n.prompt.md"
605
+ # shellcheck disable=SC2034 # both read by runner_execute, from ship-loop's runner.sh
606
+ RUNNER_SCHEMA="$OUTCOME_SCHEMA"
607
+ # shellcheck disable=SC2034
608
+ RUNNER_EXTRA_ARGS=()
609
+ runner_execute start "$host" "$SETTLE_DIR/$n.final.json" "$SETTLE_DIR/$n.err" "$(cat "$SETTLE_DIR/$n.prompt.md")" "" "" "" "$BUDGET" 0 "$RUNNER_EFFORT" </dev/null
610
+ code=$?
611
+ limit="$(result_limit "$host" "$code")"
612
+ base_record="$(jq -cn --argjson n "$n" --arg c "$reason" --arg h "$n.host.json" --argjson code "$code" --argjson criteria "$criteria" \
613
+ --arg sub "$(result_field "$host" .subtype none)" --arg cost "$(result_field "$host" .cost_usd null)" --argjson range "$RANGE_JSON" \
614
+ '{issue: $n, candidate: $c, range: {from: $range.from, to: $range.to}, criteria: $criteria,
615
+ host: {result: $h, exit: $code, subtype: $sub, cost_usd: ($cost | tonumber? // null)}}')"
616
+ if [[ "$limit" == rate-limited ]]; then
617
+ save_record "$n" "$(jq -c '. + {outcome: null, applied: {verdict: "rate-limited", reason: "the host hit a rate limit", writes: []}}' <<< "$base_record")"
618
+ note_state "$n" rate-limited
619
+ # The candidates not reached join the backlog, so the next watch starts with them.
620
+ BACKLOG_JSON="$(jq -c --argjson issues "$ISSUES_JSON" --argjson backlog "$BACKLOG_JSON" \
621
+ '($issues | map(select(.state != "rate-limited" and .state != "stopped") | .issue)) as $read
622
+ | [.[] | .issue | select(. as $i | $read | index($i) | not)] + $backlog' <<< "$CANDIDATES_JSON")"
623
+ settle_state
624
+ result "$(jq -cn --argjson n "$n" '{stop: "rate-limited", reason: "the settlement context for #\($n) hit a rate limit"}')"
625
+ fi
626
+ outcome="$(outcome_of "$host" verdict)"
627
+ if [[ -z "$outcome" ]]; then
628
+ why="the context returned no outcome (${limit:-subtype $(result_field "$host" .subtype none)})"
629
+ else
630
+ why="$(schema_reason "$OUTCOME_SCHEMA" "$outcome")"
631
+ fi
632
+ if [[ -n "$why" ]]; then
633
+ save_record "$n" "$(jq -c --arg why "$why" --arg o "$outcome" '. + {outcome: ($o | fromjson? // null), applied: {verdict: "refused", reason: $why, writes: []}}' <<< "$base_record")"
634
+ note_state "$n" refused
635
+ return 0
636
+ fi
637
+
638
+ verdict="$(jq -r .verdict <<< "$outcome")"
639
+ case "$verdict" in
640
+ shipped)
641
+ # Every criterion has a row, by its words or its number, and every row's ref resolves
642
+ # on the base. Anything short of that is unproven: recorded, and nothing is written.
643
+ missing="$(jq -c --argjson criteria "$criteria" '
644
+ def norm: ascii_downcase | gsub("\\s+"; " ") | sub("^ "; "") | sub(" $"; "");
645
+ [.evidence[] | .criterion | norm] as $named
646
+ | [$criteria | to_entries[] | (.value | norm) as $c | (.key + 1 | tostring) as $i
647
+ | select((($named | index($c)) != null or ($named | index($i)) != null) | not)
648
+ | "criterion \($i) (\(.value)) has no evidence row"]' <<< "$outcome" 2>/dev/null)"
649
+ # A check that cannot be made is not a pass.
650
+ [[ "$missing" == '['* ]] || missing='["the criteria could not be checked against the evidence"]'
651
+ checked='[]'; unresolved='[]'
652
+ while IFS=$'\t' read -r kind ref criterion; do
653
+ [[ -n "$kind" ]] || continue
654
+ if resolved="$(ref_on_base "$BASE_REF" "$kind" "$ref")"; then
655
+ checked="$(jq -c --arg c "$criterion" --arg r "$resolved" '. + [{criterion: $c, resolved: $r}]' <<< "$checked")"
656
+ else
657
+ unresolved="$(jq -c --arg k "$kind" --arg r "$ref" '. + ["\($k) \($r) is not on the base"]' <<< "$unresolved")"
658
+ fi
659
+ done < <(jq -r '.evidence[] | "\(.kind)\t\(.ref)\t\(.criterion)"' <<< "$outcome")
660
+ if [[ "$(jq length <<< "$criteria")" -eq 0 ]]; then
661
+ missing='["the issue lists no acceptance criteria to check the evidence against"]'
662
+ fi
663
+ if [[ "$(jq -n --argjson m "$missing" --argjson u "$unresolved" '($m | length) + ($u | length)')" -gt 0 ]]; then
664
+ save_record "$n" "$(jq -c --argjson o "$outcome" --argjson m "$missing" --argjson u "$unresolved" --argjson ok "$checked" \
665
+ '. + {outcome: $o, applied: {verdict: "unproven", reason: (($m + $u) | join("; ")), resolved_evidence: $ok, writes: []}}' <<< "$base_record")"
666
+ note_state "$n" unproven
667
+ return 0
668
+ fi
669
+ f="$SETTLE_DIR/$n.comment.md"
670
+ comment_file "$f" "$(jq -r --argjson ok "$checked" --arg base "$BASE" --arg now "$NOW" --arg from "$SETTLED_SHA" \
671
+ --arg marker "$SETTLED_MARKER" --arg watch "${KRYSO_WATCH_ID:-}" '
672
+ "Settled by the warden: `\($base)` at `\($now[0:12])` satisfies every acceptance criterion.", "",
673
+ ($ok[] | "- \(.criterion): \(.resolved)"), "",
674
+ .reason, "",
675
+ "\($marker) watch=\($watch) range=\($from[0:12])..\($now[0:12]) -->"' <<< "$outcome")"
676
+ write issue close "$n" --comment "$(cat "$f")" || stop_on_write "$n" "$base_record" "$outcome" "the close"
677
+ BOARD_ERR=""; BOARD_RECORD="null"
678
+ move_to_done "$issue" || stop_on_write "$n" "$base_record" "$outcome" "$BOARD_ERR"
679
+ save_record "$n" "$(jq -c --argjson o "$outcome" --argjson ok "$checked" --argjson w "$WRITES" --argjson board "$BOARD_RECORD" \
680
+ '. + {outcome: $o, applied: {verdict: "closed", resolved_evidence: $ok, board: $board, writes: $w}}' <<< "$base_record")"
681
+ note_state "$n" closed ;;
682
+ superseded)
683
+ # A person decides whether superseded work closes: the issue is parked on the decision
684
+ # report the way triage parks one, with one item recommending wontfix.
685
+ held="$(jq -c '[.labels[]?.name]' <<< "$issue")"
686
+ items="$(jq -cn --argjson n "$n" --arg url "$(jq -r .url <<< "$issue")" --arg watch "${KRYSO_WATCH_ID:-}" --arg base "$BASE" \
687
+ --arg why "$(jq -r .reason <<< "$outcome")" '[{
688
+ id: "\($n).1", issue: $n, url: $url, watch: $watch, source: "settle",
689
+ title: "Close #\($n) as superseded?",
690
+ why: "Settlement read it against what \($base) now has and found the work taken another route: \($why)",
691
+ options: [{label: "close it as wontfix", consequence: "it leaves every queue for good, superseded by what \($base) already has"},
692
+ {label: "keep it open", consequence: "it goes back to the queue with this answer on it"}],
693
+ recommended: 0}]')"
694
+ park_on_report "$n" "$held" "**Superseded:** $(jq -r .reason <<< "$outcome")" "$items" "$base_record" "$outcome"
695
+ save_record "$n" "$(jq -c --argjson o "$outcome" --argjson w "$WRITES" --argjson items "$items" \
696
+ '. + {outcome: $o, applied: {verdict: "superseded", state: "parked", writes: $w, report_items: [$items[].id]}}' <<< "$base_record")"
697
+ note_state "$n" superseded ;;
698
+ open)
699
+ save_record "$n" "$(jq -c --argjson o "$outcome" '. + {outcome: $o, applied: {verdict: "open", unmet: $o.unmet, writes: []}}' <<< "$base_record")"
700
+ note_state "$n" open ;;
701
+ esac
702
+ }
703
+
704
+ # A screened candidate is recorded first, and read as far as the settled sha is concerned,
705
+ # so a rate limit further down still counts it. No context starts for it and nothing is
706
+ # written: the reader's word is a probability, and only a context's verdict authorises a write.
707
+ while IFS=$'\t' read -r n p b reason; do
708
+ [[ -n "$n" ]] || continue
709
+ save_record "$n" "$(jq -cn --argjson n "$n" --arg c "$reason" --argjson p "$p" --arg b "$b" --argjson floor "$FLOOR" --argjson range "$RANGE_JSON" '
710
+ {issue: $n, candidate: $c, range: {from: $range.from, to: $range.to},
711
+ applied: {verdict: "screened", probability: $p, backend: $b, floor: $floor, writes: [],
712
+ reason: "the second reader (\($b)) put the probability that the range satisfies every criterion at \($p), below the floor \($floor), so no context read it"}}')"
713
+ note_state "$n" screened
714
+ done < <(jq -r '.[] | select(.state == "screened") | "\(.issue)\t\(.probability)\t\(.backend)\t\(.reason)"' <<< "$CANDIDATES_JSON")
715
+
716
+ while IFS=$'\t' read -r n reason; do
717
+ [[ -n "$n" ]] || continue
718
+ settle_one "$n" "$reason"
719
+ done < <(jq -r '.[] | select(.state != "screened") | "\(.issue)\t\(.reason)"' <<< "$CANDIDATES_JSON")
720
+
721
+ settle_state
722
+ result