@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,466 @@
1
+ #!/usr/bin/env bash
2
+ # stages/shift.sh: the warden's shift stage, run by warden.sh after the report and before
3
+ # settlement, as its own process.
4
+ #
5
+ # shift.sh <repo> <watch-dir> build the queue, park what the base rule holds, run one
6
+ # ship-loop shift over the rest, and print one result object
7
+ # shift.sh --dry-run <repo> print the queue in order, each exclusion, the base rule's
8
+ # parks and the exact ship-loop command, spending nothing
9
+ #
10
+ # The driver exports KRYSO_WATCH_CONFIG (the resolved config, base included), KRYSO_WATCH_BASE_SHA,
11
+ # KRYSO_WATCH_ID, KRYSO_WATCH_STATE_FILE and KRYSO_SHIFT_SKILL_DIR. The queue is built here, in
12
+ # shell: kryso's stage-1 candidate rule, then the warden's own exclusions, then the base
13
+ # rule, ordered by the board's Priority and then age, and capped at caps.shift. The shift is
14
+ # ship-loop run once over the queue as a workset. The warden reads the shift's exit code and
15
+ # its summary.json, never the saved results. ADR 0004 and reference/shift.md say why.
16
+ set -uo pipefail
17
+
18
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
19
+ WARDEN_DIR="$(dirname "$HERE")"
20
+
21
+ MODE=watch
22
+ if [[ "${1:-}" == --dry-run ]]; then MODE=dry; shift; fi
23
+ REPO_ROOT="${1:-}"
24
+ WATCH_DIR="${2:-}"
25
+
26
+ QUEUE_JSON='[]'
27
+ EXCLUDED_JSON='[]'
28
+ PARKS_JSON='[]'
29
+ ISSUES_JSON='[]'
30
+ REVIEW_JSON='[]'
31
+ RANGE_JSON='null'
32
+ COMMAND_JSON='null'
33
+ POINTER_JSON='null'
34
+ OUTCOMES_JSON='{}'
35
+ LEFT=0
36
+ # result <extra-json>: the stage's one result object, with every list it has so far. Found is
37
+ # what the stage acted on: the queue and the parks. Open is what it left for a person: the
38
+ # parks, and the pull requests waiting for review and the exceptions ship-loop's own summary
39
+ # names, so the warden never judges a pass's outcome itself.
40
+ result() {
41
+ local extra="${1:-}"
42
+ [[ -n "$extra" ]] || extra='{}'
43
+ jq -cn --argjson queue "$QUEUE_JSON" --argjson excluded "$EXCLUDED_JSON" --argjson parks "$PARKS_JSON" \
44
+ --argjson issues "$ISSUES_JSON" --argjson review "$REVIEW_JSON" --argjson range "$RANGE_JSON" --argjson left "$LEFT" \
45
+ --argjson command "$COMMAND_JSON" --argjson pointer "$POINTER_JSON" --argjson outcomes "$OUTCOMES_JSON" --argjson extra "$extra" '
46
+ ($parks | length) as $parked
47
+ | {found: (($queue | length) + $parked), open: ($parked + $left),
48
+ counts: (if ($queue | length) + $parked == 0 then {}
49
+ else {queued: ($queue | length)} + $outcomes + (if $parked > 0 then {"held by the base rule": $parked} else {} end) end),
50
+ candidates: $queue, excluded: $excluded, issues: $issues, review_ready: $review, range: $range,
51
+ command: $command, ship_loop: $pointer,
52
+ reason: "the queue is empty, so the shift was skipped"} + $extra'
53
+ exit 0
54
+ }
55
+
56
+ # stop <check> <reason>: an environment stop. In a watch it is the stage's result, carrying
57
+ # whatever was parked before it. In a dry run it is the driver's stop line and exit 3.
58
+ stop() {
59
+ if [[ "$MODE" == dry ]]; then echo "warden: stop environment ($1): $2" >&2; exit 3; fi
60
+ result "$(jq -cn --arg check "$1" --arg reason "$2" '{stop: "environment", check: $check, reason: $reason}')"
61
+ }
62
+
63
+ [[ -n "$REPO_ROOT" && -n "${KRYSO_WATCH_CONFIG:-}" && -n "${KRYSO_WATCH_BASE_SHA:-}" ]] \
64
+ || { echo "shift: needs <repo>, KRYSO_WATCH_CONFIG and KRYSO_WATCH_BASE_SHA from warden.sh" >&2; exit 64; }
65
+ [[ "$MODE" == dry || -n "$WATCH_DIR" ]] || { echo "shift: needs <watch-dir> outside a dry run" >&2; exit 64; }
66
+ cd "$REPO_ROOT" || stop repo "cannot enter $REPO_ROOT"
67
+
68
+ CONFIG="$KRYSO_WATCH_CONFIG"
69
+ cfg() { jq -r "$1" <<< "$CONFIG"; }
70
+ BASE="$(cfg .base)"
71
+ NOW="$KRYSO_WATCH_BASE_SHA"
72
+ BASE_REF="refs/remotes/origin/$BASE"
73
+ CAP="$(cfg .caps.shift)"
74
+ SWEEPS="$(cfg .caps.sweeps)"
75
+ BUDGET="$(cfg .caps.budget)"
76
+ NOTE="$(cfg .note)"
77
+ PROFILE="$(cfg .profile)"
78
+ LOG_LABEL="$(cfg .labels.log)"
79
+ REPORT_LABEL="$(cfg .labels.report)"
80
+ DEFERRED_LABEL="$(cfg .labels.deferred)"
81
+ PRIORITY_FIELD="$(cfg .board.priority_field)"
82
+ export LOG_LABEL REPORT_LABEL
83
+ # shellcheck source=../tracker.sh
84
+ source "$WARDEN_DIR/tracker.sh" || stop install "cannot source $WARDEN_DIR/tracker.sh"
85
+ # shellcheck source=../stage-common.sh
86
+ source "$WARDEN_DIR/stage-common.sh" || stop install "cannot source $WARDEN_DIR/stage-common.sh"
87
+ ROLE_MAP="$(role_map "$REPO_ROOT")"
88
+ label_for() { jq -r --arg r "$1" '.[$r]' <<< "$ROLE_MAP"; }
89
+ READY_LABEL="$(label_for ready-for-agent)"
90
+
91
+ # ---- the reads -----------------------------------------------------------------------------
92
+ #
93
+ # Every open issue, with what the candidate rule reads: assignees, blockers with their state,
94
+ # the parent and the sub-issue counts. Every pull request, for the ones in flight and the ones
95
+ # a closed blocker's work went out in. And the unsettled range, the settled sha in the state
96
+ # file to the fetched base, read the way settlement reads it, for the issues it cites.
97
+
98
+ POOL="$(gh issue list --state open --limit 1000 \
99
+ --json number,title,body,url,labels,createdAt,author,comments,projectItems,assignees,blockedBy,parent,subIssuesSummary 2>&1)" \
100
+ || stop "shift reads" "cannot list the open issues: $(head -1 <<< "$POOL")"
101
+ jq -e 'type == "array"' <<< "$POOL" >/dev/null 2>&1 || stop "shift reads" "the open-issue list is not a JSON array"
102
+ POOL="$(markers_read "$POOL")"
103
+ PRS="$(gh pr list --state all --limit 500 --json number,state,headRefName,title,body,mergeCommit 2>&1)" \
104
+ || stop "shift reads" "cannot list the pull requests: $(head -1 <<< "$PRS")"
105
+ jq -e 'type == "array"' <<< "$PRS" >/dev/null 2>&1 || stop "shift reads" "the pull request list is not a JSON array"
106
+
107
+ # The range exists only where settlement would read one: a settled sha on this base, in this
108
+ # repository, behind the fetched base. Anywhere else nothing is left to settlement.
109
+ CITES='[]'
110
+ SETTLED='{}'
111
+ if [[ -n "${KRYSO_WATCH_STATE_FILE:-}" && -f "$KRYSO_WATCH_STATE_FILE" ]]; then
112
+ SETTLED="$(jq -c '.settled // {} | select(type == "object")' "$KRYSO_WATCH_STATE_FILE" 2>/dev/null)"
113
+ [[ -n "$SETTLED" ]] || SETTLED='{}'
114
+ fi
115
+ if SETTLED_SHA="$(range_start "$BASE" "$NOW" "$SETTLED")"; then
116
+ COMMITS="$(range_commits "$SETTLED_SHA" "$NOW")" || stop "shift reads" "$COMMITS"
117
+ MERGED="$(range_prs "$BASE" "$COMMITS")" || stop "shift reads" "$MERGED"
118
+ CITES="$(jq -c --argjson prs "$MERGED" '
119
+ [.[] | .sha as $s | .cites[] | {issue: ., by: "commit \($s[0:12])"}]
120
+ + [$prs[] | .number as $p | .cites[] | {issue: ., by: "pull request #\($p)"}]' <<< "$COMMITS")"
121
+ RANGE_JSON="$(jq -cn --arg from "$SETTLED_SHA" --arg to "$NOW" --argjson c "$COMMITS" --argjson prs "$MERGED" \
122
+ '{from: $from, to: $to, commits: ($c | length), pull_requests: ($prs | map(.number))}')"
123
+ fi
124
+
125
+ # The worktrees under .claude/worktrees/, each one a run in flight for the issue its name ends in.
126
+ WORKTREES="$(for wt in "$REPO_ROOT"/.claude/worktrees/*/; do [[ -d "$wt" ]] && basename "$wt"; done | jq -Rsc 'split("\n") | map(select(length > 0))')"
127
+
128
+ # ---- gate 3 --------------------------------------------------------------------------------
129
+ #
130
+ # kryso's gate 3: an open pull request that closes the issue blocks it when a collaborator
131
+ # opened it, whatever its branch is called. The pass refuses such an issue, and because the
132
+ # shift names its queue to ship-loop with --issues, the refusal labels the issue agent:blocked
133
+ # and posts a note on it. The filter applies the gate first, so a watch does not name an issue
134
+ # the pass would refuse there, and a later watch does not post a second note on it. The open
135
+ # pull requests are read the way the pass reads them, apart from the newest 500 above: every
136
+ # open one, up to the pass's limit, since an old open pull request closes an issue as well as
137
+ # a new one does. A list past the limit stops the stage, because the pass would refuse every
138
+ # issue on it and note each one. A pull request closes the issue the way the pass reads it:
139
+ # GitHub's closingIssuesReferences, or its body naming the issue after a closing keyword. A
140
+ # check gh cannot answer keeps the issue out too, since the pass would refuse it on that and
141
+ # write the same note. LINKED maps each issue the gate holds to why.
142
+
143
+ OPEN_PR_LIMIT=1000
144
+ OPEN_PRS="$(gh pr list --state open --limit "$((OPEN_PR_LIMIT + 1))" --json number,author,headRefName,body,closingIssuesReferences 2>&1)" \
145
+ || stop "shift reads" "cannot list the open pull requests: $(head -1 <<< "$OPEN_PRS")"
146
+ jq -e 'type == "array"' <<< "$OPEN_PRS" >/dev/null 2>&1 || stop "shift reads" "the open pull request list is not a JSON array"
147
+ [[ "$(jq length <<< "$OPEN_PRS")" -le "$OPEN_PR_LIMIT" ]] \
148
+ || stop "shift reads" "more than $OPEN_PR_LIMIT pull requests are open, so gate 3 cannot read them all and every pass would refuse its issue"
149
+
150
+ # collaborator <login>: COLLABORATOR set to yes, no or `unreadable <gh's line>`, asked once per
151
+ # login. It is set rather than printed, because a subshell would drop the cache.
152
+ COLLABORATORS_SEEN=""
153
+ COLLABORATOR=""
154
+ collaborator() {
155
+ local line err
156
+ while IFS= read -r line; do
157
+ [[ -n "$line" && "${line%% *}" == "$1" ]] && { COLLABORATOR="${line#* }"; return 0; }
158
+ done <<< "$COLLABORATORS_SEEN"
159
+ err="$(mktemp)"
160
+ if gh api "repos/{owner}/{repo}/collaborators/$1" >/dev/null 2>"$err"; then COLLABORATOR=yes
161
+ elif grep -qF '(HTTP 404)' "$err"; then COLLABORATOR=no
162
+ else COLLABORATOR="unreadable $(tail -1 "$err")"; fi
163
+ rm -f "$err"
164
+ COLLABORATORS_SEEN+="$1 $COLLABORATOR"$'\n'
165
+ }
166
+
167
+ # The ready issues' numbers are the argument and the open list is the input, which can run to
168
+ # a thousand bodies, more than one argument may carry on Linux. The body match is the pass's,
169
+ # not PR_DEFS's closes below, which also reads the title and takes a colon with no space after
170
+ # it. It is the pass that refuses, so its reading is the gate.
171
+ READY_NUMBERS="$(jq -c --arg ready "$READY_LABEL" '[.[] | select(any(.labels[]?; .name == $ready)) | .number]' <<< "$POOL")"
172
+ LINKED='{}'
173
+ while IFS=$'\t' read -r n pr login; do
174
+ [[ -n "$n" ]] || continue
175
+ jq -e --arg n "$n" 'has($n)' <<< "$LINKED" >/dev/null && continue
176
+ why=""
177
+ if [[ -z "$login" ]]; then
178
+ why="open pull request #$pr closes it and names no author, so whether a collaborator opened it could not be read"
179
+ else
180
+ collaborator "$login"
181
+ case "$COLLABORATOR" in
182
+ yes) why="an open pull request a collaborator opened closes it: #$pr by $login" ;;
183
+ no) ;;
184
+ *) why="whether $login, who opened #$pr, is a collaborator could not be read (${COLLABORATOR#unreadable })" ;;
185
+ esac
186
+ fi
187
+ [[ -z "$why" ]] || LINKED="$(jq -c --arg n "$n" --arg why "$why" '.[$n] = $why' <<< "$LINKED")"
188
+ done < <(jq -r --argjson ready "$READY_NUMBERS" '
189
+ .[] as $p | $ready[] as $n | $p
190
+ | select(any(.closingIssuesReferences[]?; .number == $n)
191
+ or ((.body // "") | test("\\b(close[sd]?|fix(e[sd])?|resolve[sd]?):?\\s+#\($n)\\b"; "i")))
192
+ | "\($n)\t\(.number)\t\(.author.login // "")"' <<< "$OPEN_PRS")
193
+
194
+ # ---- the candidates ------------------------------------------------------------------------
195
+ #
196
+ # The pool is every open issue carrying the ready-for-agent label. An issue is dropped, with
197
+ # its reason, when it is the warden's own log or report, deferred (the label or a card in the
198
+ # Deferred column), parked on a report item, assigned, blocked by an open issue, a parent with
199
+ # an open sub-issue, a wayfinder child, locked by a worktree or an open pull request whose
200
+ # branch ends in its number, held by gate 3, or cited by a commit or merged pull request in
201
+ # the unsettled range, which settlement reads next. The rest meet the base rule.
202
+
203
+ # def closes($n): a title or body closes #n with one of GitHub's closing keywords.
204
+ PR_DEFS='
205
+ def closes($n): test("(?i)\\b(close[sd]?|fix(e[sd])?|resolve[sd]?)[ \\t:]+#\($n)\\b");
206
+ def prs_of($n): [$prs[] | select(((.headRefName // "") | endswith("-\($n)"))
207
+ or ([(.title // ""), (.body // "")] | join("\n") | closes($n)))];
208
+ def ready: any(.labels[]?; .name == $ready);
209
+ def blocker_prs: [.blockedBy.nodes[]? | select(.state == "CLOSED") | .number as $b
210
+ | prs_of($b)[] | select(.state != "CLOSED") | {blocker: $b, pr: .number, state, oid: (.mergeCommit.oid // null)}];'
211
+
212
+ # Which of the merged pull requests a closed blocker's work went out in are on the base.
213
+ ON_BASE='{}'
214
+ while IFS=$'\t' read -r pr oid; do
215
+ [[ -n "$pr" ]] || continue
216
+ if git merge-base --is-ancestor "$oid" "$BASE_REF" 2>/dev/null; then on=true; else on=false; fi
217
+ ON_BASE="$(jq -c --arg p "$pr" --argjson on "$on" '.[$p] = $on' <<< "$ON_BASE")"
218
+ done < <(jq -r --argjson prs "$PRS" --arg ready "$READY_LABEL" "$PR_DEFS"'
219
+ [.[] | select(ready) | blocker_prs[] | select(.state == "MERGED" and .oid != null) | "\(.pr)\t\(.oid)"] | unique[]' <<< "$POOL")
220
+
221
+ SELECTION="$(jq -c --argjson prs "$PRS" --argjson linked "$LINKED" --argjson cites "$CITES" --argjson onbase "$ON_BASE" --argjson worktrees "$WORKTREES" \
222
+ --arg ready "$READY_LABEL" --arg base "$BASE" --arg marker "$PARK_MARKER" --arg released "$RELEASE_MARKER" \
223
+ --arg log "$LOG_LABEL" --arg report "$REPORT_LABEL" --arg deferred "$DEFERRED_LABEL" "$PR_DEFS$EXCLUSIONS_JQ"'
224
+ . as $pool
225
+ # The branches a text names on a "Base branch: <name>" or "Base: <name>" line, the name in
226
+ # backticks or alone on the line.
227
+ | def named:
228
+ [split("\n")[]
229
+ | (capture("^[\\s>*_-]*base(?:[ \\t]+branch)?[*_]*[ \\t]*:[*_ \\t]*`(?<b>[^`\\s]+)`"; "i")
230
+ // capture("^[\\s>*_-]*base(?:[ \\t]+branch)?[*_]*[ \\t]*:[*_ \\t]*(?<b>[A-Za-z0-9._/-]*[A-Za-z0-9_/-])[.]?[ \\t]*$"; "i"))
231
+ | .b | sub("^(refs/heads/|origin/)"; "")] | unique;
232
+ # The brief is the latest comment with an "Agent brief" line, the way ship-it reads one.
233
+ def brief: [(.comments // [])[] | .body // "" | select(split("\n") | any(test("^[#>* \\t]*agent brief"; "i")))] | last // "";
234
+ # A base-rule item a person answered: the last answer comment for <n>.base on the issue.
235
+ def base_answer($n):
236
+ [(.comments // [])[] | .body // "" | select(contains("<!-- warden:answered ") and contains("id=\($n).base -->"))] | last
237
+ | if . == null then null
238
+ else {at: ([capture("report=(?<r>[0-9]+) q=(?<q>[0-9]+) id=")] | first | "report #\(.r) Q\(.q)"),
239
+ letter: ([capture("(^|\n)Answer: (?<l>[a-z]) \\(")] | first | .l // null)} end;
240
+ def base_rule:
241
+ (.body // "" | named | map(select(. != $base))) as $in_body
242
+ | (brief | named | map(select(. != $base))) as $in_brief
243
+ | [($in_body[] | "its body names branch `\(.)`"),
244
+ ($in_brief[] | select(. as $b | $in_body | index($b) | not) | "its brief names branch `\(.)`"),
245
+ (blocker_prs[] | select(.state == "OPEN" or ($onbase[.pr | tostring] != true))
246
+ | "its closed blocker #\(.blocker) has pull request #\(.pr), \(if .state == "OPEN" then "still open" else "merged but not into `\($base)`" end)")];
247
+ [ .[] | select(ready)
248
+ | . as $i | .number as $n | [.labels[]?.name] as $labels
249
+ | own_exclusion($log; $report; $deferred) as $own
250
+ | parked_reason($marker; $released) as $parked
251
+ | ([.blockedBy.nodes[]? | select(.state == "OPEN") | .number]) as $open_blockers
252
+ | (((.subIssuesSummary.total // 0) - (.subIssuesSummary.completed // 0))) as $open_children
253
+ | ([$worktrees[] | select(endswith("-\($n)"))] | first) as $worktree
254
+ | ([$prs[] | select(.state == "OPEN" and ((.headRefName // "") | endswith("-\($n)")))] | first) as $pr
255
+ | ([$cites[] | select(.issue == $n)] | first) as $cite
256
+ | {issue: $n, created: .createdAt, title, url, labels: $labels, cards: [.projectItems[]? | .title],
257
+ why: (
258
+ if $own != null then {exclude: $own}
259
+ elif $parked != null then {exclude: $parked}
260
+ elif ((.assignees // []) | length) > 0 then {exclude: "assigned to \([.assignees[].login] | join(", "))"}
261
+ elif ($open_blockers | length) > 0 then {exclude: "blocked by open \($open_blockers | map("#\(.)") | join(", "))"}
262
+ elif $open_children > 0 then {exclude: "a parent with \($open_children) open sub-issue(s)"}
263
+ elif any($labels[]; startswith("wayfinder:") and . != "wayfinder:map")
264
+ or ((.parent.number // null) as $p | $p != null and any($pool[]; .number == $p and any(.labels[]?; .name == "wayfinder:map")))
265
+ then {exclude: "a wayfinder child, which resolves by an answer rather than a pull request"}
266
+ elif $worktree != null then {exclude: "a worktree in flight: .claude/worktrees/\($worktree)"}
267
+ elif $pr != null then {exclude: "a pull request in flight: #\($pr.number) on \($pr.headRefName)"}
268
+ elif $linked[$n | tostring] != null then {exclude: $linked[$n | tostring]}
269
+ elif $cite != null then {exclude: "cited by \($cite.by) in the unsettled range, which settlement reads"}
270
+ else
271
+ ($i | base_rule) as $reasons
272
+ | if ($reasons | length) == 0 then {include: true}
273
+ else ($i | base_answer($n)) as $answer
274
+ | if $answer == null then {park: $reasons}
275
+ elif $answer.letter == "b" then {include: true, waived: $answer.at}
276
+ else {exclude: "held for a person: \($answer.at) answered to hold it while \($reasons | join(", and "))"} end
277
+ end
278
+ end)} ]
279
+ | sort_by(.created, .issue)
280
+ | {pending: [.[] | select(.why.include) | {issue, created, title, cards, waived: .why.waived}],
281
+ excluded: [.[] | select(.why.exclude) | {issue, created, reason: .why.exclude}],
282
+ parks: [.[] | select(.why.park) | {issue, created, title, url, labels, reasons: .why.park}]}' <<< "$POOL" 2>&1)" \
283
+ || stop "shift reads" "cannot read the open-issue list: $(head -1 <<< "$SELECTION")"
284
+ PARKS_JSON="$(jq -c .parks <<< "$SELECTION")"
285
+
286
+ # ---- the order -----------------------------------------------------------------------------
287
+ #
288
+ # The board's Priority field in the configured order, unset values last, then oldest first. A
289
+ # queue with no card on any board is ordered by age alone and reads no board at all. The field,
290
+ # the boards and the values are read live, the way triage reads them.
291
+
292
+ PRIORITIES='{}'
293
+ BOARDS="$(jq -r '[.pending[].cards[]] | unique[]' <<< "$SELECTION")"
294
+ if [[ -n "$BOARDS" ]]; then
295
+ owner="$(git remote get-url origin 2>/dev/null | sed -nE 's#.*github\.com[:/]([^/]+)/.*#\1#p')"
296
+ PROJECTS="$(gh project list --owner "$owner" --format json 2>&1)" \
297
+ || stop "shift reads" "cannot list the projects: $(head -1 <<< "$PROJECTS")"
298
+ while IFS= read -r title; do
299
+ number="$(jq -r --arg t "$title" '.projects[]? | select(.title == $t) | .number' <<< "$PROJECTS" 2>/dev/null | head -1)"
300
+ [[ -n "$number" ]] || continue
301
+ items="$(gh project item-list "$number" --owner "$owner" --format json --limit 1000 2>&1)" \
302
+ || stop "shift reads" "cannot read the items of $title: $(head -1 <<< "$items")"
303
+ PRIORITIES="$(jq -c --argjson known "$PRIORITIES" --arg f "$PRIORITY_FIELD" '
304
+ reduce (.items[]? | select(.content.number != null)) as $it ($known;
305
+ ($it[$f | ascii_downcase] // $it[$f] // null) as $v
306
+ | if $v != null and $v != "" and (has($it.content.number | tostring) | not) then .[$it.content.number | tostring] = $v else . end)' <<< "$items" 2>/dev/null)" \
307
+ || stop "shift reads" "the items of $title are not JSON"
308
+ done <<< "$BOARDS"
309
+ fi
310
+
311
+ ORDERED="$(jq -c --argjson prio "$PRIORITIES" --argjson order "$(jq -c .board.priority_order <<< "$CONFIG")" \
312
+ --argjson cap "$CAP" --argjson boarded "$([[ -n "$BOARDS" ]] && echo true || echo false)" '
313
+ (.pending | map(. + {priority: ($prio[.issue | tostring] // null)})
314
+ | map(. + {rank: ((.priority as $p | $order | index($p)) // ($order | length))})
315
+ | sort_by(.rank, .created, .issue)) as $sorted
316
+ | {queue: [$sorted[:$cap][] | {issue, title,
317
+ reason: ((if $boarded then (if .priority != null then "priority \(.priority), " else "no priority, " end) else "" end)
318
+ + "created \(.created[0:10])" + (if .waived then ", the base rule waived by \(.waived)" else "" end))}],
319
+ excluded: (.excluded + [$sorted[$cap:][] | {issue, created, reason: "over the cap: caps.shift is \($cap)"}]
320
+ + [.parks[] | {issue, created, reason: "held by the base rule and parked on the decision report: \(.reasons | join(", and "))"}]
321
+ | sort_by(.created, .issue) | map({issue, reason}))}' <<< "$SELECTION")"
322
+ QUEUE_JSON="$(jq -c '[.queue[] | {issue, reason}]' <<< "$ORDERED")"
323
+ EXCLUDED_JSON="$(jq -c .excluded <<< "$ORDERED")"
324
+ QUEUE_NUMBERS="$(jq -r '[.queue[].issue] | map(tostring) | join(" ")' <<< "$ORDERED")"
325
+
326
+ # ---- the command ---------------------------------------------------------------------------
327
+ #
328
+ # One ship-loop run over the queue: the queue as the workset, the configured base, profile,
329
+ # cap and note, a dollar cap only where the profile takes one, which runner.sh decides, and
330
+ # the sweeps where ship-loop takes them, which is a workset of two or more issues. --stack is
331
+ # never passed. Stacking stays off, so a dependant waits for the human merge of its blocker.
332
+
333
+ SHIP_LOOP_DIR="${KRYSO_SHIFT_SKILL_DIR:-}"
334
+ SHIP_LOOP="$SHIP_LOOP_DIR/ship-loop.sh"
335
+ [[ -f "$SHIP_LOOP" && -f "$SHIP_LOOP_DIR/runner.sh" ]] || stop install "cannot find ship-loop.sh and runner.sh in '$SHIP_LOOP_DIR'"
336
+ # shellcheck source=/dev/null
337
+ source "$SHIP_LOOP_DIR/runner.sh" || stop install "cannot source $SHIP_LOOP_DIR/runner.sh"
338
+ RUNNER_ERR="$(mktemp)"
339
+ runner_profile_load "$PROFILE" "${KRYSO_PROFILE_FILE:-}" 2> "$RUNNER_ERR" \
340
+ || { why="$(head -1 "$RUNNER_ERR")"; rm -f "$RUNNER_ERR"; stop runner "cannot load profile '$PROFILE': $why"; }
341
+ rm -f "$RUNNER_ERR"
342
+
343
+ COMMAND=()
344
+ if [[ -n "$QUEUE_NUMBERS" ]]; then
345
+ COMMAND=(bash "$SHIP_LOOP" --issues "$QUEUE_NUMBERS" --base "$BASE" --profile "$PROFILE" --max "$CAP")
346
+ ! runner_validate_options 1 "$BUDGET" 0 "$RUNNER_EFFORT" 2>/dev/null || COMMAND+=(--budget "$BUDGET")
347
+ [[ -z "$NOTE" ]] || COMMAND+=(--note "$NOTE")
348
+ [[ "$(wc -w <<< "$QUEUE_NUMBERS" | tr -d ' ')" -lt 2 ]] || COMMAND+=(--sweeps "$SWEEPS")
349
+ COMMAND_JSON="$(printf '%s\0' "${COMMAND[@]}" | jq -Rsc 'split("\u0000") | .[:-1]')"
350
+ fi
351
+
352
+ # render <argv...>: the command as one line a person can paste, an argument quoted only where
353
+ # the shell would split or expand it.
354
+ render() {
355
+ local a out=""
356
+ for a in "$@"; do
357
+ if [[ "$a" =~ ^[A-Za-z0-9_./:=@%+,-]+$ ]]; then out+=" $a"; else out+=" '${a//\'/\'\\\'\'}'"; fi
358
+ done
359
+ printf '%s' "${out# }"
360
+ }
361
+
362
+ if [[ "$MODE" == dry ]]; then
363
+ jq -r --argjson ordered "$ORDERED" --arg base "$BASE" --arg sha "$NOW" '
364
+ [.parks[].issue] as $parked
365
+ | [$ordered.excluded[] | select(.issue as $i | $parked | index($i) | not)] as $excluded
366
+ | ($ordered.queue | to_entries[] | "warden: shift queue \(.key + 1): #\(.value.issue) (\(.value.reason)) \(.value.title)"),
367
+ ($excluded[] | "warden: shift excluded #\(.issue): \(.reason)"),
368
+ (.parks[] | "warden: shift would park #\(.issue) on the base rule: \(.reasons | join(", and "))"),
369
+ "warden: shift: \($ordered.queue | length) queued on \($base) at \($sha[0:12]), \($excluded | length) excluded, \(.parks | length) to park on the base rule"' <<< "$SELECTION"
370
+ if [[ "${#COMMAND[@]}" -gt 0 ]]; then echo "warden: shift command: $(render "${COMMAND[@]}")"
371
+ else echo "warden: shift: the queue is empty, so the watch would skip the shift"; fi
372
+ exit 0
373
+ fi
374
+
375
+ # ---- the base rule's parks -----------------------------------------------------------------
376
+ #
377
+ # An issue the base rule holds is not queued. It is parked the way settlement parks one: its
378
+ # state label moves to needs-info, one comment names what held it and ends in the parking
379
+ # marker, and one report item, <n>.base, goes to report-items.json for the report body to post
380
+ # once settlement is done. The item recommends holding it for a person, and its other option
381
+ # lets the next shift work it on the base anyway, which the queue reads back off the answer.
382
+
383
+ WRITE_ERR=""
384
+ write() { WRITE_ERR="$(tracker_write "$@" 2>&1 >/dev/null)" || { WRITE_ERR="$(head -1 <<< "$WRITE_ERR")"; return 1; }; }
385
+ stop_on_write() { stop "tracker write" "$1 on #$2 failed${WRITE_ERR:+: $WRITE_ERR}"; }
386
+
387
+ SHIFT_DIR="$WATCH_DIR/shift"
388
+ mkdir -p "$SHIFT_DIR" || stop state "cannot create $SHIFT_DIR"
389
+
390
+ while IFS= read -r park; do
391
+ [[ -n "$park" ]] || continue
392
+ n="$(jq -r .issue <<< "$park")"
393
+ item="$(jq -c --arg base "$BASE" --arg watch "${KRYSO_WATCH_ID:-}" '
394
+ {id: "\(.issue).base", issue, url, watch: $watch, source: "shift",
395
+ title: "Work #\(.issue) on `\($base)`?",
396
+ why: "The shift works on `\($base)`, and \(.reasons | join(", and ")). A pass on `\($base)` would build without what that points at.",
397
+ options: [{label: "hold it for a person",
398
+ consequence: "it goes back to ready-for-agent with this answer on it, and the shift leaves it out while the base rule still holds, so a person takes it where it points"},
399
+ {label: "work it on `\($base)`",
400
+ consequence: "the next shift queues it on `\($base)` as the base stands, whatever the base rule found"}],
401
+ recommended: 0}' <<< "$park")"
402
+ state_edit "$ROLE_MAP" "$(jq -c .labels <<< "$park")" "$(label_for needs-info)"
403
+ if [[ "${#STATE_ADD[@]}" -gt 0 || "${#STATE_REMOVE[@]}" -gt 0 ]]; then
404
+ write issue edit "$n" ${STATE_ADD[@]+"${STATE_ADD[@]}"} ${STATE_REMOVE[@]+"${STATE_REMOVE[@]}"} || stop_on_write "the label edit" "$n"
405
+ fi
406
+ f="$SHIFT_DIR/$n.comment.md"
407
+ comment_file "$f" "$(jq -r --argjson park "$park" --arg marker "$PARK_MARKER" --arg watch "${KRYSO_WATCH_ID:-}" '
408
+ "## Shift", "",
409
+ "**Held by the base rule:** \($park.reasons | join(", and ")).", "",
410
+ "**Parked:** this issue waits on one decision the warden could not make. It goes to the decision report:", "",
411
+ "- **\(.title)** (item \(.id)): \(.why)", "",
412
+ "\($marker) watch=\($watch) items=\(.id) -->"' <<< "$item")"
413
+ write issue comment "$n" --body-file "$f" || stop_on_write "the parking comment" "$n"
414
+ add_report_items "$WATCH_DIR" "[$item]"
415
+ done < <(jq -c '.[]' <<< "$PARKS_JSON")
416
+
417
+ [[ "${#COMMAND[@]}" -gt 0 ]] || result "$(jq -cn --argjson parks "$PARKS_JSON" --argjson excluded "$EXCLUDED_JSON" '
418
+ {reason: "the queue is empty, so the shift was skipped: \($excluded | length) issue(s) excluded\(if ($parks | length) > 0 then ", \($parks | length) of them parked on the base rule" else "" end)"}')"
419
+
420
+ # ---- the shift -----------------------------------------------------------------------------
421
+ #
422
+ # The pointer goes on disk before anything is spent: the queue and the exact command. Then
423
+ # ship-loop runs once, its own output to a log beside the pointer, and its summary's path is
424
+ # read off the closing line ADR 0003 fixes for a background run to find it by. The warden
425
+ # reads the exit code and that summary.json, and nothing else the shift left: no pass result
426
+ # and no line of the log. A shift with no summary never opened: ship-loop stopped in its own
427
+ # preflight, which is an environment stop whatever its exit code.
428
+
429
+ POINTER="$WATCH_DIR/shift.json"
430
+ jq -n --argjson queue "$QUEUE_JSON" --argjson command "$COMMAND_JSON" --arg at "$(date -u +%FT%TZ)" \
431
+ '{queue: $queue, command: $command, started_at: $at}' > "$POINTER"
432
+ # Its log is a file, and the closing line read below is the plain one, so a forced colour the
433
+ # watch was started with stops here.
434
+ CLICOLOR_FORCE= "${COMMAND[@]}" > "$SHIFT_DIR/ship-loop.log" 2>&1 </dev/null
435
+ code=$?
436
+ summary_path="$(sed -n -E 's/.*summary at ([^ ,]+\/summary\.json).*/\1/p' "$SHIFT_DIR/ship-loop.log" | tail -1)"
437
+ dir=""; [[ -z "$summary_path" ]] || dir="$(dirname "$summary_path")"
438
+ POINTER_JSON="$(jq -c --argjson code "$code" --arg dir "$dir" --arg summary "$summary_path" --arg at "$(date -u +%FT%TZ)" \
439
+ '. + {exit: $code, dir: (if $dir == "" then null else $dir end), summary: (if $summary == "" then null else $summary end), ended_at: $at}' "$POINTER")"
440
+ printf '%s\n' "$POINTER_JSON" | jq . > "$POINTER"
441
+
442
+ SUMMARY='null'
443
+ if [[ -n "$summary_path" && -f "$summary_path" ]]; then
444
+ SUMMARY="$(jq -c 'select(type == "object")' "$summary_path" 2>/dev/null)"
445
+ [[ -n "$SUMMARY" ]] || SUMMARY='null'
446
+ fi
447
+ # Each queued issue with the outcome and pull request its row in the summary gives, and
448
+ # not-reached where the summary has no row for it.
449
+ ISSUES_JSON="$(jq -c --argjson queue "$QUEUE_JSON" '
450
+ (.issues // {}) as $rows
451
+ | [$queue[] | .issue as $n | $rows[$n | tostring] as $r
452
+ | {issue: $n, state: ($r.outcome // "not-reached"), pr: ($r.pr // "none")}]' <<< "$SUMMARY")"
453
+ OUTCOMES_JSON="$(jq -c 'reduce .[] as $i ({}; .[$i.state] += 1)' <<< "$ISSUES_JSON")"
454
+ if [[ "$SUMMARY" == null ]]; then
455
+ stop shift "ship-loop exited $code without opening a shift, so it stopped before its first pass. Its output is in ${SHIFT_DIR#"$REPO_ROOT"/}/ship-loop.log"
456
+ fi
457
+ REVIEW_JSON="$(jq -c '.review_ready // []' <<< "$SUMMARY")"
458
+ LEFT="$(jq '(.review_ready // [] | length) + ([.exceptions // [] | .[].issue] | unique | length)' <<< "$SUMMARY")"
459
+ said="$(jq -r '"ship-loop stopped \(.stop): \(.stop_reason)"' <<< "$SUMMARY")"
460
+
461
+ case "$code" in
462
+ 0) result "$(jq -cn --arg r "$said" '{reason: $r}')" ;;
463
+ 1) result "$(jq -cn --arg r "$said" '{stop: "failed", reason: $r}')" ;;
464
+ 2) result "$(jq -cn --arg r "$said" '{stop: "rate-limited", reason: $r}')" ;;
465
+ *) stop shift "ship-loop exited $code, which it has no meaning for, after $said" ;;
466
+ esac