@krysoworks/kryso 0.0.0-stage → 2.0.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +152 -2
- package/bin/kryso +31 -0
- package/bin/ship-it-status +14 -0
- package/bin/ship-ledger +14 -0
- package/bin/ship-loop +14 -0
- package/bin/ship-pass +14 -0
- package/bin/warden +14 -0
- package/dist/answer.d.ts +38 -0
- package/dist/answer.js +48 -0
- package/dist/bytes.d.ts +5 -0
- package/dist/bytes.js +35 -0
- package/dist/cleanup.d.ts +1 -0
- package/dist/cleanup.js +629 -0
- package/dist/commands.d.ts +48 -0
- package/dist/commands.js +293 -0
- package/dist/completions.d.ts +24 -0
- package/dist/completions.js +239 -0
- package/dist/daemon.d.ts +15 -0
- package/dist/daemon.js +23 -0
- package/dist/diagnose.d.ts +47 -0
- package/dist/diagnose.js +314 -0
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +241 -0
- package/dist/env.d.ts +9 -0
- package/dist/env.js +17 -0
- package/dist/evidence.d.ts +39 -0
- package/dist/evidence.js +327 -0
- package/dist/home.d.ts +3 -0
- package/dist/home.js +27 -0
- package/dist/install.d.ts +59 -0
- package/dist/install.js +137 -0
- package/dist/isolate.d.ts +28 -0
- package/dist/isolate.js +402 -0
- package/dist/leftovers.d.ts +5 -0
- package/dist/leftovers.js +156 -0
- package/dist/machine.d.ts +6 -0
- package/dist/machine.js +185 -0
- package/dist/palette.d.ts +147 -0
- package/dist/palette.js +167 -0
- package/dist/plan.d.ts +1 -0
- package/dist/plan.js +133 -0
- package/dist/proc.d.ts +23 -0
- package/dist/proc.js +23 -0
- package/dist/read.d.ts +1 -0
- package/dist/read.js +297 -0
- package/dist/readiness.d.ts +5 -0
- package/dist/readiness.js +64 -0
- package/dist/remote.d.ts +6 -0
- package/dist/remote.js +85 -0
- package/dist/self-update.d.ts +1 -0
- package/dist/self-update.js +224 -0
- package/dist/semver.d.ts +7 -0
- package/dist/semver.js +42 -0
- package/dist/style.d.ts +71 -0
- package/dist/style.js +187 -0
- package/dist/update.d.ts +47 -0
- package/dist/update.js +190 -0
- package/dist/work.d.ts +25 -0
- package/dist/work.js +449 -0
- package/dist/workflows.d.ts +4 -0
- package/dist/workflows.js +73 -0
- package/docker/entrypoint.sh +44 -0
- package/docker/runner.Dockerfile +39 -0
- package/package.json +65 -4
- package/scripts/install-skills.sh +607 -0
- package/skills/code-review/SKILL.md +231 -0
- package/skills/kryso/SKILL.md +107 -0
- package/skills/kryso/golden/help.rounded.ansi +23 -0
- package/skills/kryso/golden/help.square.ansi +23 -0
- package/skills/kryso/golden/help.txt +23 -0
- package/skills/kryso/golden/table-narrow.json +11 -0
- package/skills/kryso/golden/table-narrow.rounded.ansi +4 -0
- package/skills/kryso/golden/table-narrow.square.ansi +4 -0
- package/skills/kryso/golden/table.ansi +5 -0
- package/skills/kryso/golden/table.json +11 -0
- package/skills/kryso/ledger.sh +2146 -0
- package/skills/kryso/palette.json +57 -0
- package/skills/kryso/reference/resuming.md +30 -0
- package/skills/kryso/reference/routing.md +23 -0
- package/skills/kryso/reference/stage-1-claim.md +79 -0
- package/skills/kryso/reference/stage-2-build.md +133 -0
- package/skills/kryso/reference/stage-3-prove.md +51 -0
- package/skills/kryso/reference/stage-4-pr.md +76 -0
- package/skills/kryso/reference/stage-5-reconcile.md +81 -0
- package/skills/kryso/reference/stage-6-merge-or-park.md +73 -0
- package/skills/kryso/reference/stage-7-close-out.md +62 -0
- package/skills/kryso/reference/terminal.md +7 -0
- package/skills/kryso/ship-it-status.sh +1503 -0
- package/skills/kryso/ui.py +274 -0
- package/skills/kryso/ui.sh +609 -0
- package/skills/kryso-build/SKILL.md +168 -0
- package/skills/kryso-shift/SKILL.md +167 -0
- package/skills/kryso-shift/archive.py +2784 -0
- package/skills/kryso-shift/archive_checker.py +462 -0
- package/skills/kryso-shift/archive_checker_lambda.py +155 -0
- package/skills/kryso-shift/archive_health.py +364 -0
- package/skills/kryso-shift/archive_launchd.py +140 -0
- package/skills/kryso-shift/archive_remote.py +990 -0
- package/skills/kryso-shift/archiving-checker.md +140 -0
- package/skills/kryso-shift/archiving-keep.md +115 -0
- package/skills/kryso-shift/archiving-recovery.md +112 -0
- package/skills/kryso-shift/archiving-remote.md +166 -0
- package/skills/kryso-shift/archiving.md +146 -0
- package/skills/kryso-shift/coverage.schema.json +225 -0
- package/skills/kryso-shift/deadline.sh +254 -0
- package/skills/kryso-shift/feedback.schema.json +35 -0
- package/skills/kryso-shift/feedback.sh +228 -0
- package/skills/kryso-shift/history-manifest.schema.json +331 -0
- package/skills/kryso-shift/keep-after.sh +55 -0
- package/skills/kryso-shift/measure.sh +611 -0
- package/skills/kryso-shift/merge-ready.sh +207 -0
- package/skills/kryso-shift/outcome.schema.json +16 -0
- package/skills/kryso-shift/pass-rules.md +8 -0
- package/skills/kryso-shift/profile.schema.json +42 -0
- package/skills/kryso-shift/reader.sh +692 -0
- package/skills/kryso-shift/reads.sh +151 -0
- package/skills/kryso-shift/reference/allowance.md +21 -0
- package/skills/kryso-shift/reference/driver.md +95 -0
- package/skills/kryso-shift/reference/measuring.md +67 -0
- package/skills/kryso-shift/reference/outputs.md +21 -0
- package/skills/kryso-shift/reference/pass-script.md +115 -0
- package/skills/kryso-shift/reference/reconcile-and-merge.md +55 -0
- package/skills/kryso-shift/reference/second-reader.md +9 -0
- package/skills/kryso-shift/reference/sweeps.md +83 -0
- package/skills/kryso-shift/repair.schema.json +14 -0
- package/skills/kryso-shift/report-template.html +679 -0
- package/skills/kryso-shift/report.py +389 -0
- package/skills/kryso-shift/report_fixture.py +65 -0
- package/skills/kryso-shift/reporting.md +58 -0
- package/skills/kryso-shift/result.sh +91 -0
- package/skills/kryso-shift/runner.sh +1178 -0
- package/skills/kryso-shift/ship-loop.sh +3977 -0
- package/skills/kryso-shift/ship-pass.sh +4987 -0
- package/skills/kryso-shift/steps.jq +19 -0
- package/skills/kryso-shift/workflow.mjs +830 -0
- package/skills/kryso-shift/workflows/default.json +22 -0
- package/skills/kryso-shift/workflows/ralph.json +13 -0
- package/skills/kryso-watch/SKILL.md +100 -0
- package/skills/kryso-watch/answer.schema.json +23 -0
- package/skills/kryso-watch/base-refs.sh +44 -0
- package/skills/kryso-watch/board.sh +58 -0
- package/skills/kryso-watch/reference/config.md +23 -0
- package/skills/kryso-watch/reference/outputs.md +30 -0
- package/skills/kryso-watch/reference/report.md +29 -0
- package/skills/kryso-watch/reference/scheduler.md +32 -0
- package/skills/kryso-watch/reference/settlement.md +29 -0
- package/skills/kryso-watch/reference/shift.md +44 -0
- package/skills/kryso-watch/reference/shim-limits.md +22 -0
- package/skills/kryso-watch/reference/triage.md +26 -0
- package/skills/kryso-watch/schema.jq +40 -0
- package/skills/kryso-watch/settle.schema.json +36 -0
- package/skills/kryso-watch/stage-common.sh +187 -0
- package/skills/kryso-watch/stages/report.sh +525 -0
- package/skills/kryso-watch/stages/settle.sh +722 -0
- package/skills/kryso-watch/stages/shift.sh +466 -0
- package/skills/kryso-watch/stages/triage.sh +379 -0
- package/skills/kryso-watch/tracker.sh +27 -0
- package/skills/kryso-watch/triage.schema.json +77 -0
- package/skills/kryso-watch/warden.launchd.plist +50 -0
- package/skills/kryso-watch/warden.schema.json +98 -0
- package/skills/kryso-watch/warden.sh +1004 -0
|
@@ -0,0 +1,1004 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# warden: one watch over a repository's tracker. Validates the tracked config, runs the
|
|
3
|
+
# preflight, takes the per-repo lock, writes the manifest before anything is spent, runs the
|
|
4
|
+
# four stages behind their switches, leaves one bounded entry on the warden log and one
|
|
5
|
+
# bounded summary on disk, and exits with a stop state. A driver, never a context: ADR 0004
|
|
6
|
+
# says why. Runs from a plain terminal or from inside a session. See SKILL.md.
|
|
7
|
+
set -uo pipefail
|
|
8
|
+
|
|
9
|
+
# The script may be run through a link (the runbook links it onto PATH), so every link is
|
|
10
|
+
# followed to the real file, and the files beside it are found from there.
|
|
11
|
+
SELF="${BASH_SOURCE[0]}"
|
|
12
|
+
while [[ -L "$SELF" ]]; do
|
|
13
|
+
target="$(readlink "$SELF")"
|
|
14
|
+
case "$target" in /*) SELF="$target" ;; *) SELF="$(dirname "$SELF")/$target" ;; esac
|
|
15
|
+
done
|
|
16
|
+
HERE="$(cd "$(dirname "$SELF")" && pwd)"
|
|
17
|
+
SCHEMA="$HERE/warden.schema.json"
|
|
18
|
+
|
|
19
|
+
# kryso_module <file>: where the watch loads one of kryso's files from, ledger.sh or ui.sh, the
|
|
20
|
+
# first that exists of: the kryso directory beside this one, then .agents/skills under the
|
|
21
|
+
# repository and the home, then the .claude/skills compatibility path under both. ui.sh's
|
|
22
|
+
# header names the order, which every kryso script keeps. Status 1 when none has it.
|
|
23
|
+
kryso_module() {
|
|
24
|
+
local root candidate
|
|
25
|
+
root="$(git rev-parse --show-toplevel 2>/dev/null)"
|
|
26
|
+
for candidate in "$(dirname "$HERE")/kryso/$1" "$root/.agents/skills/kryso/$1" "$HOME/.agents/skills/kryso/$1" \
|
|
27
|
+
"$root/.claude/skills/kryso/$1" "$HOME/.claude/skills/kryso/$1"; do
|
|
28
|
+
[[ -f "$candidate" ]] && { printf '%s' "$candidate"; return 0; }
|
|
29
|
+
done
|
|
30
|
+
return 1
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
# The styled-output module, found before the arguments are read, so the help and a bad option
|
|
34
|
+
# are drawn on an attended run. A copy without it prints its plain lines, which are what the
|
|
35
|
+
# schedule and the scheduler read. stdout is the stream its lines take.
|
|
36
|
+
UI_SH="$(kryso_module ui.sh)" || UI_SH=""
|
|
37
|
+
# shellcheck source=/dev/null
|
|
38
|
+
if [[ -n "$UI_SH" ]] && source "$UI_SH"; then ui_stream 1; fi
|
|
39
|
+
# Without ui.sh nothing is attended, so every line is the plain one.
|
|
40
|
+
declare -F ui_err_attended > /dev/null || { ui_attended() { return 1; }; ui_err_attended() { return 1; }; }
|
|
41
|
+
# styled: status 0 when stdout is attended.
|
|
42
|
+
styled() { ui_attended; }
|
|
43
|
+
CONFIG_REL=.kryso/watch.json
|
|
44
|
+
# The config's old places, docs/agents/kryso.json and, before the rename, docs/agents/warden.json,
|
|
45
|
+
# read in that order when the new one is absent, until 3.0.0, by ledger.sh's place rule. A
|
|
46
|
+
# tracked file is never moved here: that is a commit, and a person's to make.
|
|
47
|
+
CONFIG_OLD=(docs/agents/kryso.json docs/agents/warden.json)
|
|
48
|
+
STATE_SCHEMA=1
|
|
49
|
+
# The stages in the order a watch runs them. The report batches the calls triage could not
|
|
50
|
+
# make, so it follows the triage switch.
|
|
51
|
+
STAGES=(triage report shift settle)
|
|
52
|
+
# ship-loop waits out at most this many rate limits a shift, each a further model start.
|
|
53
|
+
SHIFT_RATE_LIMIT_RETRIES=3
|
|
54
|
+
|
|
55
|
+
DRY_RUN=0
|
|
56
|
+
READ_ONLY=0
|
|
57
|
+
REPO_DIR=""
|
|
58
|
+
SCHEDULE=0
|
|
59
|
+
SECOND_READER=""
|
|
60
|
+
# How the schedule or watch started. BY_SCHEDULER is 1 only when the launchd agent's own
|
|
61
|
+
# arguments say so.
|
|
62
|
+
# SCHEDULE_ID is the schedule a watch belongs to, handed over by the schedule that starts it.
|
|
63
|
+
BY_SCHEDULER=0
|
|
64
|
+
SCHEDULE_ID=""
|
|
65
|
+
# A schedule's id: its UTC start time, as unique_id makes it, with a numeric suffix for a
|
|
66
|
+
# second already taken.
|
|
67
|
+
SCHEDULE_ID_RE='^[0-9]{8}T[0-9]{6}Z(-[0-9]+)?$'
|
|
68
|
+
|
|
69
|
+
usage() {
|
|
70
|
+
cat <<'USAGE'
|
|
71
|
+
Usage: kryso watch [options]
|
|
72
|
+
|
|
73
|
+
--dry-run check the config and run the preflight, then print the resolved
|
|
74
|
+
config, the base and its sha, the stages that would run, the
|
|
75
|
+
caps and the most model contexts the watch can start. It writes
|
|
76
|
+
nothing to the tracker or the state file
|
|
77
|
+
--read-only with --dry-run, change nothing at all: read the base on origin
|
|
78
|
+
without fetching it, name a stale isolation file rather than
|
|
79
|
+
remove it, and run the stages with the second reader off, so
|
|
80
|
+
nothing is spent. The stages read refs/remotes/origin/<base>
|
|
81
|
+
as it is here, and a warning says when origin's tip differs
|
|
82
|
+
from it. A base never fetched here has no copy to read, so
|
|
83
|
+
the stages are skipped and a warning says so. The stop lines
|
|
84
|
+
and the exit are a plain dry run's
|
|
85
|
+
--repo DIR watch the repository at DIR (default the current one)
|
|
86
|
+
--schedule run one watch in each repository that
|
|
87
|
+
${XDG_CONFIG_HOME:-~/.config}/kryso/repos lists, one after
|
|
88
|
+
another under one lock. With --dry-run, list them and run each
|
|
89
|
+
one's dry run
|
|
90
|
+
--by-scheduler with --schedule: the scheduler started this schedule. Only the
|
|
91
|
+
launchd agent passes it, so a schedule a person runs from a
|
|
92
|
+
terminal records a person as its starter
|
|
93
|
+
--schedule-id ID
|
|
94
|
+
the schedule this watch belongs to. The schedule passes it to
|
|
95
|
+
each watch it starts, with --by-scheduler when the scheduler
|
|
96
|
+
started the schedule
|
|
97
|
+
--second-reader off|on|jev|llm
|
|
98
|
+
the second reader for this run. It wins over the repository's
|
|
99
|
+
kryso.secondReader, and the warden exports it as
|
|
100
|
+
PLAYBOOK_SECOND_READER to every stage and to ship-loop, so
|
|
101
|
+
settlement screens its candidates with it and a shift's passes
|
|
102
|
+
read with it
|
|
103
|
+
-h, --help print this help
|
|
104
|
+
|
|
105
|
+
The config is the tracked .kryso/watch.json, and warden.schema.json beside
|
|
106
|
+
this script checks it. Without it the watch reads docs/agents/kryso.json, then
|
|
107
|
+
docs/agents/warden.json, its old places, with a warning. With none of them, the
|
|
108
|
+
watch takes the schema's defaults.
|
|
109
|
+
|
|
110
|
+
The watch exits 0 when it stops by design (complete, review-ready or
|
|
111
|
+
frontier-empty), 1 on a failed shift, 2 on a rate limit and 3 on an environment
|
|
112
|
+
stop. A bad option exits 64 before any watch starts. A schedule exits with the
|
|
113
|
+
highest exit code of its repositories.
|
|
114
|
+
USAGE
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
# bad_option <message> [usage]: an option this cannot take, before any watch starts, exit 64:
|
|
118
|
+
# an ERROR pill with the help as its hint on an attended stderr, else the prefixed line and,
|
|
119
|
+
# when asked, the usage.
|
|
120
|
+
bad_option() {
|
|
121
|
+
if ui_err_attended; then ui_error "$1" "kryso watch --help lists the options"
|
|
122
|
+
else
|
|
123
|
+
echo "warden: $1" >&2
|
|
124
|
+
[[ "${2:-}" != usage ]] || usage >&2
|
|
125
|
+
fi
|
|
126
|
+
exit 64
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
while [[ $# -gt 0 ]]; do
|
|
130
|
+
case "$1" in
|
|
131
|
+
--dry-run) DRY_RUN=1; shift ;;
|
|
132
|
+
--read-only) READ_ONLY=1; shift ;;
|
|
133
|
+
--repo) [[ $# -ge 2 ]] || bad_option "--repo needs a directory"
|
|
134
|
+
REPO_DIR="$2"; shift 2 ;;
|
|
135
|
+
--schedule) SCHEDULE=1; shift ;;
|
|
136
|
+
--by-scheduler) BY_SCHEDULER=1; shift ;;
|
|
137
|
+
--schedule-id)
|
|
138
|
+
[[ $# -ge 2 ]] || bad_option "--schedule-id needs a schedule id"
|
|
139
|
+
# A schedule's id is its directory's name, written into the log entry, so nothing else
|
|
140
|
+
# is taken.
|
|
141
|
+
[[ "$2" =~ $SCHEDULE_ID_RE ]] \
|
|
142
|
+
|| bad_option "--schedule-id is '$2', not a schedule id such as 20261004T020000Z"
|
|
143
|
+
SCHEDULE_ID="$2"; shift 2 ;;
|
|
144
|
+
--second-reader)
|
|
145
|
+
[[ $# -ge 2 ]] || bad_option "--second-reader needs off, on, jev or llm"
|
|
146
|
+
# The reader's own words, refused here so a bad value never reaches a watch.
|
|
147
|
+
case "$2" in
|
|
148
|
+
off|on|jev|llm) SECOND_READER="$2" ;;
|
|
149
|
+
*) bad_option "--second-reader is '$2', not off, on, jev or llm" ;;
|
|
150
|
+
esac
|
|
151
|
+
shift 2 ;;
|
|
152
|
+
-h|--help)
|
|
153
|
+
if styled; then ui_brand watch help; usage | ui_help; else usage; fi
|
|
154
|
+
exit 0 ;;
|
|
155
|
+
*) bad_option "unknown option $1" usage ;;
|
|
156
|
+
esac
|
|
157
|
+
done
|
|
158
|
+
[[ "$SCHEDULE" -eq 0 || -z "$REPO_DIR" ]] || bad_option "--schedule reads its repositories from the list, so it takes no --repo"
|
|
159
|
+
[[ "$SCHEDULE" -eq 0 || -z "$SCHEDULE_ID" ]] || bad_option "--schedule takes its own id, so it takes no --schedule-id"
|
|
160
|
+
[[ "$BY_SCHEDULER" -eq 0 || "$SCHEDULE" -eq 1 || -n "$SCHEDULE_ID" ]] \
|
|
161
|
+
|| bad_option "--by-scheduler marks a schedule, so it needs --schedule, or --schedule-id on a watch a schedule starts"
|
|
162
|
+
# Who started the schedule: its record word, the words its lines and each watch's start line
|
|
163
|
+
# use, the argument it hands each watch, and the clause the watch's log entry uses.
|
|
164
|
+
# reference/scheduler.md says what the mark can and cannot prove.
|
|
165
|
+
if [[ "$BY_SCHEDULER" -eq 1 ]]; then
|
|
166
|
+
STARTED_BY=scheduler; STARTED_BY_WORDS="the scheduler"; STARTED_BY_ARGS=(--by-scheduler)
|
|
167
|
+
STARTED_BY_ENTRY="which the scheduler started"
|
|
168
|
+
else
|
|
169
|
+
STARTED_BY=person; STARTED_BY_WORDS="a person"; STARTED_BY_ARGS=()
|
|
170
|
+
STARTED_BY_ENTRY="which a person ran by hand"
|
|
171
|
+
fi
|
|
172
|
+
[[ "$READ_ONLY" -eq 0 || "$DRY_RUN" -eq 1 ]] || bad_option "--read-only makes a dry run read-only, so it needs --dry-run"
|
|
173
|
+
# A read-only dry run changes nothing, so kryso doctor can run it (ADR 0044): the ledger module
|
|
174
|
+
# reads KRYSO_READ_ONLY and keeps a stale isolation file. ship-loop checks the reader's setting
|
|
175
|
+
# in the preflight as a plain dry run does, and stage_env turns it off for the stages, so
|
|
176
|
+
# settlement's dry run asks nothing.
|
|
177
|
+
READ_ONLY_ARGS=()
|
|
178
|
+
[[ "$READ_ONLY" -eq 0 ]] || { export KRYSO_READ_ONLY=1; READ_ONLY_ARGS=(--read-only); }
|
|
179
|
+
# The per-run switch is the environment variable ship-loop's reader already reads, exported
|
|
180
|
+
# once so every stage body, every ship-loop call and every watch of a schedule sees it.
|
|
181
|
+
[[ -z "$SECOND_READER" ]] || export PLAYBOOK_SECOND_READER="$SECOND_READER"
|
|
182
|
+
|
|
183
|
+
# say and warn: the watch's plain lines, or on an attended run an information line and a
|
|
184
|
+
# warning line with no prefix, under the section they fall in.
|
|
185
|
+
say() { if styled; then ui_info "$1"; else echo "warden: $1"; fi; }
|
|
186
|
+
warn() { if ui_err_attended; then ( UI_FD=2 UI_TTY=1 ui_warn "$1" ); else echo "warden: warning: $1" >&2; fi; }
|
|
187
|
+
# relay: a stage body's dry-run lines, which it prints plain, as say and warn would draw them.
|
|
188
|
+
relay() {
|
|
189
|
+
if ! styled; then cat; return 0; fi
|
|
190
|
+
local line
|
|
191
|
+
while IFS= read -r line; do
|
|
192
|
+
case "$line" in
|
|
193
|
+
"warden: warning: "*) ui_warn "${line#warden: warning: }" ;;
|
|
194
|
+
"warden: "*) ui_info "${line#warden: }" ;;
|
|
195
|
+
*) printf '%s\n' "$line" ;;
|
|
196
|
+
esac
|
|
197
|
+
done
|
|
198
|
+
}
|
|
199
|
+
# stop_line <check> <reason>: an environment stop on stderr, under an ERROR pill when attended.
|
|
200
|
+
stop_line() {
|
|
201
|
+
if ui_err_attended; then ui_error "stop environment ($1): $2"; else echo "warden: stop environment ($1): $2" >&2; fi
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
# An environment stop that leaves no watch record: before the lock is taken, where another
|
|
205
|
+
# watch may hold the state, or where the state directory, the state file or the watch
|
|
206
|
+
# directory cannot be written or read. Nothing goes to the tracker either.
|
|
207
|
+
early_stop() {
|
|
208
|
+
stop_line "$1" "$2"
|
|
209
|
+
exit 3
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
# ---- the locks ----------------------------------------------------------------------------
|
|
213
|
+
#
|
|
214
|
+
# take_lock <file> <holder> <check>: a lock is a file created exclusively, holding the pid
|
|
215
|
+
# that took it. A lock whose pid is no longer running still holds: clearing it here would
|
|
216
|
+
# race a second run clearing it too, so the stop says so and a person removes the file. A
|
|
217
|
+
# watch takes its repository's lock and a schedule takes its own, and one process holds at
|
|
218
|
+
# most one of them.
|
|
219
|
+
LOCK_HELD=""
|
|
220
|
+
take_lock() {
|
|
221
|
+
local file="$1" noun="$2" check="$3" holder
|
|
222
|
+
if (set -C; printf '%s %s\n' "$$" "$(date -u +%FT%TZ)" > "$file") 2>/dev/null; then LOCK_HELD="$file"; return 0; fi
|
|
223
|
+
holder="$(cut -d' ' -f1 "$file" 2>/dev/null)"
|
|
224
|
+
if [[ "$holder" =~ ^[0-9]+$ ]] && kill -0 "$holder" 2>/dev/null; then
|
|
225
|
+
early_stop "$check" "another $noun holds $file (pid $holder)"
|
|
226
|
+
fi
|
|
227
|
+
early_stop "$check" "pid ${holder:-unknown} holds $file and is no longer running. Remove the file once no $noun is running"
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
release_lock() {
|
|
231
|
+
[[ -n "$LOCK_HELD" ]] || return 0
|
|
232
|
+
[[ "$(cut -d' ' -f1 "$LOCK_HELD" 2>/dev/null)" == "$$" ]] && rm -f "$LOCK_HELD"
|
|
233
|
+
LOCK_HELD=""
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
# unique_id <dir>: a name for a new directory under <dir>, the UTC start time, suffixed when
|
|
237
|
+
# a directory of that name already exists. Watches and schedules are named this way.
|
|
238
|
+
unique_id() {
|
|
239
|
+
local id n=1
|
|
240
|
+
id="$(date -u +%Y%m%dT%H%M%SZ)"
|
|
241
|
+
while [[ -e "$1/$id" ]]; do n=$(( n + 1 )); id="$(date -u +%Y%m%dT%H%M%SZ)-$n"; done
|
|
242
|
+
printf '%s' "$id"
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
command -v jq >/dev/null 2>&1 || early_stop tools "jq is not installed, and the config, the manifest and every result are JSON"
|
|
246
|
+
command -v git >/dev/null 2>&1 || early_stop tools "git is not installed"
|
|
247
|
+
[[ -f "$SCHEMA" ]] || early_stop install "cannot find $SCHEMA beside the driver"
|
|
248
|
+
# The validator every warden schema goes through, and the one guard every tracker write does.
|
|
249
|
+
VALIDATOR="$HERE/schema.jq"
|
|
250
|
+
[[ -f "$VALIDATOR" ]] || early_stop install "cannot find $VALIDATOR beside the driver"
|
|
251
|
+
[[ -f "$HERE/tracker.sh" ]] || early_stop install "cannot find $HERE/tracker.sh beside the driver"
|
|
252
|
+
# shellcheck source=tracker.sh
|
|
253
|
+
source "$HERE/tracker.sh" || early_stop install "cannot source $HERE/tracker.sh"
|
|
254
|
+
# The evidence module, for its rule on the old names: the settings a person puts in the
|
|
255
|
+
# environment, which the stages and ship-loop read, and the directories renamed with the product.
|
|
256
|
+
LEDGER_SH="$(kryso_module ledger.sh)" || LEDGER_SH=""
|
|
257
|
+
[[ -n "$LEDGER_SH" ]] || early_stop install "cannot find kryso's ledger.sh beside $HERE or under .agents/skills"
|
|
258
|
+
# shellcheck source=/dev/null
|
|
259
|
+
source "$LEDGER_SH" || early_stop install "cannot source $LEDGER_SH"
|
|
260
|
+
_ledger_settings warden
|
|
261
|
+
|
|
262
|
+
# ---- the schedule -------------------------------------------------------------------------
|
|
263
|
+
#
|
|
264
|
+
# One process runs the repositories the user's list names, one watch at a time in the list's
|
|
265
|
+
# order, under one lock. ADR 0004 says why they run in series. Each watch is this script run
|
|
266
|
+
# again with --repo, so its config, preflight, per-repo lock and log entry apply unchanged. A
|
|
267
|
+
# watch that stops early never stops the schedule, which exits with the highest exit code
|
|
268
|
+
# among its watches. Outside the repositories it reads the list under the user's config directory and
|
|
269
|
+
# changes only the user's state directory: it writes its lock and one log per watch there, and
|
|
270
|
+
# removes or empties what earlier schedules left.
|
|
271
|
+
|
|
272
|
+
SCHEDULE_LIST="${XDG_CONFIG_HOME:-$HOME/.config}/kryso/repos"
|
|
273
|
+
SCHEDULE_STATE="${XDG_STATE_HOME:-$HOME/.local/state}/kryso"
|
|
274
|
+
# Their names before the rename. The list is read where only the old one exists, with a
|
|
275
|
+
# warning, and the state directory is moved to the new name when a schedule starts.
|
|
276
|
+
SCHEDULE_LIST_OLD="${XDG_CONFIG_HOME:-$HOME/.config}/warden/repos"
|
|
277
|
+
SCHEDULE_STATE_OLD="${XDG_STATE_HOME:-$HOME/.local/state}/warden"
|
|
278
|
+
|
|
279
|
+
# read_schedule: the list, one repository path per line. Blank lines and lines starting with
|
|
280
|
+
# # are skipped, and a leading ~/ is the home directory. Any other path that is not absolute
|
|
281
|
+
# stops the schedule before a watch starts, since launchd's working directory is not the one
|
|
282
|
+
# the list was written in.
|
|
283
|
+
read_schedule() {
|
|
284
|
+
local line n=0
|
|
285
|
+
REPOS=()
|
|
286
|
+
if [[ ! -f "$SCHEDULE_LIST" && -f "$SCHEDULE_LIST_OLD" ]]; then
|
|
287
|
+
warn "reading the repository list at $SCHEDULE_LIST_OLD, its name before the rename. Move it to $SCHEDULE_LIST, because the warden reads the old name only until 3.0.0"
|
|
288
|
+
SCHEDULE_LIST="$SCHEDULE_LIST_OLD"
|
|
289
|
+
fi
|
|
290
|
+
[[ -f "$SCHEDULE_LIST" ]] || early_stop schedule "no repository list at $SCHEDULE_LIST, one repository path per line"
|
|
291
|
+
while IFS= read -r line || [[ -n "$line" ]]; do
|
|
292
|
+
n=$(( n + 1 ))
|
|
293
|
+
line="${line#"${line%%[![:space:]]*}"}"
|
|
294
|
+
line="${line%"${line##*[![:space:]]}"}"
|
|
295
|
+
[[ -z "$line" || "$line" == \#* ]] && continue
|
|
296
|
+
# shellcheck disable=SC2088 # the list's literal ~/, which no shell expanded
|
|
297
|
+
[[ "$line" == "~/"* ]] && line="$HOME/${line#"~/"}"
|
|
298
|
+
[[ "$line" == /* ]] || early_stop schedule "$SCHEDULE_LIST line $n: '$line' is not an absolute path"
|
|
299
|
+
REPOS+=("$line")
|
|
300
|
+
done < "$SCHEDULE_LIST"
|
|
301
|
+
[[ ${#REPOS[@]} -gt 0 ]] || early_stop schedule "$SCHEDULE_LIST names no repositories"
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
# What the state directory keeps, tidied at the start of each schedule that takes the lock:
|
|
305
|
+
# the last SCHEDULE_KEEP schedules' directories, this one's among them, and launchd.log until
|
|
306
|
+
# it reaches SCHEDULE_LOG_MAX bytes.
|
|
307
|
+
SCHEDULE_KEEP=30
|
|
308
|
+
SCHEDULE_LOG_MAX=1048576
|
|
309
|
+
|
|
310
|
+
# prune_schedules <dir> <current>: removes the oldest schedules' directories under <dir> so
|
|
311
|
+
# that SCHEDULE_KEEP are left, never <current>. Sorting the ids by time and then by suffix
|
|
312
|
+
# puts them in start order. A name of any other
|
|
313
|
+
# shape is no schedule's and is left alone. A directory that cannot be removed is a warning,
|
|
314
|
+
# not a stop: tonight's watches matter more than last month's logs.
|
|
315
|
+
prune_schedules() {
|
|
316
|
+
local dir="$1" current="$2" path name removed=0
|
|
317
|
+
local -a ids=()
|
|
318
|
+
for path in "$dir"/*; do
|
|
319
|
+
name="${path##*/}"
|
|
320
|
+
[[ -d "$path" && "$name" != "$current" && "$name" =~ $SCHEDULE_ID_RE ]] && ids+=("$name")
|
|
321
|
+
done
|
|
322
|
+
(( ${#ids[@]} >= SCHEDULE_KEEP )) || return 0
|
|
323
|
+
while IFS= read -r name; do
|
|
324
|
+
if rm -rf "${dir:?}/$name" 2>/dev/null; then removed=$(( removed + 1 ))
|
|
325
|
+
else warn "cannot remove $dir/$name, an old schedule's directory"; fi
|
|
326
|
+
done < <(printf '%s\n' "${ids[@]}" | sort -t- -k1,1 -k2,2n | head -n $(( ${#ids[@]} - SCHEDULE_KEEP + 1 )))
|
|
327
|
+
(( removed == 0 )) || say "schedule: removed $removed schedule directories older than the last $SCHEDULE_KEEP in $dir"
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
# rotate_log <file>: once <file> reaches SCHEDULE_LOG_MAX bytes, copies it to <file>.1, over
|
|
331
|
+
# the rotation before, and empties it in place. launchd holds the file open for appending, so
|
|
332
|
+
# after a move it would go on writing this schedule's lines into the moved file. After the
|
|
333
|
+
# emptying it writes them from the start of <file>. The lines this schedule wrote before the
|
|
334
|
+
# copy are in <file>.1.
|
|
335
|
+
rotate_log() {
|
|
336
|
+
local file="$1" size
|
|
337
|
+
[[ -f "$file" ]] || return 0
|
|
338
|
+
size="$(wc -c < "$file" | tr -d ' ')"
|
|
339
|
+
(( size >= SCHEDULE_LOG_MAX )) || return 0
|
|
340
|
+
if ! cp "$file" "$file.1" 2>/dev/null; then
|
|
341
|
+
warn "cannot copy $file to ${file##*/}.1 at $size bytes, so it is not rotated"
|
|
342
|
+
elif ! : > "$file" 2>/dev/null; then
|
|
343
|
+
warn "copied $file to ${file##*/}.1 at $size bytes, over the rotation before, but cannot empty it"
|
|
344
|
+
else
|
|
345
|
+
say "schedule: rotated $file to ${file##*/}.1 at $size bytes"
|
|
346
|
+
fi
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
run_schedule() {
|
|
350
|
+
local self repo i code highest=0 stop dir run_id run_dir log watch_args
|
|
351
|
+
self="$HERE/$(basename "$SELF")"
|
|
352
|
+
read_schedule
|
|
353
|
+
# The state directory under its new name. A dry run writes nothing, so it only reads which
|
|
354
|
+
# one is there, and a schedule moves the old one across first, leaving a link back.
|
|
355
|
+
if [[ "$DRY_RUN" -eq 1 ]]; then _ledger_pick "$SCHEDULE_STATE" "$SCHEDULE_STATE_OLD" SCHEDULE_STATE
|
|
356
|
+
else
|
|
357
|
+
# Outside any repository, so there is no git directory to hold a lock in. Only launchd or a
|
|
358
|
+
# person starts a schedule, and the schedule's own lock is inside the directory being moved.
|
|
359
|
+
_ledger_migrate "$SCHEDULE_STATE_OLD" "$SCHEDULE_STATE" "" \
|
|
360
|
+
|| early_stop state "cannot move $SCHEDULE_STATE_OLD to $SCHEDULE_STATE"
|
|
361
|
+
_ledger_pick "$SCHEDULE_STATE" "$SCHEDULE_STATE_OLD" SCHEDULE_STATE
|
|
362
|
+
fi
|
|
363
|
+
! styled || { ui_brand watch "schedule, $(plural_repos "${#REPOS[@]}")"; ui_section primary SCHEDULE; }
|
|
364
|
+
say "schedule: ${#REPOS[@]} repositories from $SCHEDULE_LIST"
|
|
365
|
+
i=0; for repo in "${REPOS[@]}"; do i=$(( i + 1 )); say "schedule: $i. $repo"; done
|
|
366
|
+
# Each watch is told which schedule started it, and whether the scheduler started that.
|
|
367
|
+
run_id="$(unique_id "$SCHEDULE_STATE/runs")"
|
|
368
|
+
watch_args=(--schedule-id "$run_id" ${STARTED_BY_ARGS[@]+"${STARTED_BY_ARGS[@]}"})
|
|
369
|
+
|
|
370
|
+
# The dry run takes no lock and writes nothing, the way a watch's dry run does. Each
|
|
371
|
+
# repository's dry run prints to the terminal as it would run alone, with the id a schedule
|
|
372
|
+
# started now would take, so it shows what each watch would record.
|
|
373
|
+
if [[ "$DRY_RUN" -eq 1 ]]; then
|
|
374
|
+
for repo in "${REPOS[@]}"; do
|
|
375
|
+
bash "$self" --dry-run ${READ_ONLY_ARGS[@]+"${READ_ONLY_ARGS[@]}"} --repo "$repo" "${watch_args[@]}"; code=$?
|
|
376
|
+
say "schedule: $repo: dry run, exit $code, started by $STARTED_BY_WORDS"
|
|
377
|
+
(( code > highest )) && highest=$code
|
|
378
|
+
done
|
|
379
|
+
say "schedule: dry run exit $highest, spent nothing and wrote nothing, started by $STARTED_BY_WORDS"
|
|
380
|
+
exit "$highest"
|
|
381
|
+
fi
|
|
382
|
+
|
|
383
|
+
mkdir -p "$SCHEDULE_STATE" 2>/dev/null || early_stop state "cannot create $SCHEDULE_STATE"
|
|
384
|
+
take_lock "$SCHEDULE_STATE/lock" schedule schedule-lock
|
|
385
|
+
trap release_lock EXIT
|
|
386
|
+
run_dir="$SCHEDULE_STATE/runs/$run_id"
|
|
387
|
+
mkdir -p "$run_dir" 2>/dev/null || early_stop state "cannot create $run_dir"
|
|
388
|
+
say "schedule: logs in $run_dir"
|
|
389
|
+
prune_schedules "$SCHEDULE_STATE/runs" "$run_id"
|
|
390
|
+
rotate_log "$SCHEDULE_STATE/launchd.log"
|
|
391
|
+
|
|
392
|
+
# A watch's own lines go to its log. The watch directory is read off the watch's opening
|
|
393
|
+
# line, which names the repository root, so a listed subdirectory still resolves.
|
|
394
|
+
i=0
|
|
395
|
+
for repo in "${REPOS[@]}"; do
|
|
396
|
+
i=$(( i + 1 ))
|
|
397
|
+
log="$run_dir/$i-$(basename "$repo").log"
|
|
398
|
+
# The log is a file, so the watch prints its plain lines there, which the two reads below take.
|
|
399
|
+
CLICOLOR_FORCE= bash "$self" --repo "$repo" "${watch_args[@]}" > "$log" 2>&1; code=$?
|
|
400
|
+
stop="$(sed -n -E 's/^warden: stop ([a-z-]+) .*/\1/p' "$log" | tail -1)"
|
|
401
|
+
dir="$(sed -n -E 's/^warden: watch ([^ ]+) in (.+), config: .*/\2\/.claude\/kryso-watch\/\1/p' "$log" | head -1)"
|
|
402
|
+
say "schedule: $repo: stop ${stop:-unknown}, exit $code, watch ${dir:-none}, started by $STARTED_BY_WORDS"
|
|
403
|
+
(( code > highest )) && highest=$code
|
|
404
|
+
done
|
|
405
|
+
say "schedule: exit $highest, the highest of ${#REPOS[@]} repositories, started by $STARTED_BY_WORDS"
|
|
406
|
+
exit "$highest"
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
plural_repos() { if [[ "$1" -eq 1 ]]; then echo "1 repository"; else echo "$1 repositories"; fi; }
|
|
410
|
+
[[ "$SCHEDULE" -eq 0 ]] || run_schedule
|
|
411
|
+
|
|
412
|
+
# ---- how the watch started ----------------------------------------------------------------
|
|
413
|
+
#
|
|
414
|
+
# A schedule names itself and who started it. A watch started directly records that no
|
|
415
|
+
# schedule did. The record changes no stage, cap or stop: a watch does the same work whoever
|
|
416
|
+
# starts it.
|
|
417
|
+
|
|
418
|
+
if [[ -n "$SCHEDULE_ID" ]]; then
|
|
419
|
+
START_JSON="$(jq -cn --arg id "$SCHEDULE_ID" --arg by "$STARTED_BY" '{id: $id, started_by: $by}')"
|
|
420
|
+
START_LINE="schedule $SCHEDULE_ID, started by $STARTED_BY_WORDS"
|
|
421
|
+
START_ENTRY="Started by schedule \`$SCHEDULE_ID\`, $STARTED_BY_ENTRY. Its log is under \`runs/$SCHEDULE_ID/\` in the warden state directory."
|
|
422
|
+
else
|
|
423
|
+
START_JSON=null
|
|
424
|
+
START_LINE="no schedule, started directly"
|
|
425
|
+
START_ENTRY="Started directly, by no schedule."
|
|
426
|
+
fi
|
|
427
|
+
|
|
428
|
+
# ---- the repository and the config ---------------------------------------------------
|
|
429
|
+
|
|
430
|
+
if [[ -n "$REPO_DIR" ]]; then cd "$REPO_DIR" 2>/dev/null || early_stop repo "cannot enter $REPO_DIR"; fi
|
|
431
|
+
REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null)" || early_stop repo "not a git repository"
|
|
432
|
+
cd "$REPO_ROOT" || early_stop repo "cannot enter $REPO_ROOT"
|
|
433
|
+
# The new place wins, with a warning for each old one beside it. Without it, the first old place
|
|
434
|
+
# there is read, with the warning that names its move.
|
|
435
|
+
CONFIG_PLACE=""
|
|
436
|
+
for old in "${CONFIG_OLD[@]}"; do
|
|
437
|
+
_ledger_kryso_place "$REPO_ROOT" "" "$CONFIG_REL" "$old" place
|
|
438
|
+
[[ -n "$place" ]] || continue
|
|
439
|
+
[[ -z "$_ledger_kryso_note" ]] || warn "$_ledger_kryso_note"
|
|
440
|
+
CONFIG_PLACE="$place"
|
|
441
|
+
[[ "$place" == "$CONFIG_REL" ]] || break
|
|
442
|
+
done
|
|
443
|
+
CONFIG_REL="${CONFIG_PLACE:-$CONFIG_REL}"
|
|
444
|
+
|
|
445
|
+
# The defaults, written into the document from the schema's own default keywords, so an
|
|
446
|
+
# absent key and an absent file resolve the same way.
|
|
447
|
+
FILL_JQ='
|
|
448
|
+
def fill($s):
|
|
449
|
+
if ($s.type // "") == "object" and ($s | has("properties")) then
|
|
450
|
+
(. // {}) as $v
|
|
451
|
+
| reduce ($s.properties | to_entries[]) as $e ($v;
|
|
452
|
+
if has($e.key) then .[$e.key] |= fill($e.value)
|
|
453
|
+
elif ($e.value | has("default")) then .[$e.key] = (null | fill($e.value) // $e.value.default)
|
|
454
|
+
else . end)
|
|
455
|
+
elif . == null and ($s | has("default")) then $s.default
|
|
456
|
+
else . end;
|
|
457
|
+
fill($schema[0])
|
|
458
|
+
'
|
|
459
|
+
|
|
460
|
+
if [[ -f "$CONFIG_REL" ]]; then
|
|
461
|
+
CONFIG_SOURCE="$CONFIG_REL"
|
|
462
|
+
jq empty "$CONFIG_REL" >/dev/null 2>&1 || early_stop config "$CONFIG_REL is not valid JSON"
|
|
463
|
+
[[ "$(jq -s length "$CONFIG_REL")" == 1 ]] || early_stop config "$CONFIG_REL does not hold one JSON object"
|
|
464
|
+
invalid="$(jq -r --slurpfile schema "$SCHEMA" -f "$VALIDATOR" "$CONFIG_REL" 2>&1)" \
|
|
465
|
+
|| early_stop config "cannot validate $CONFIG_REL against $SCHEMA: $invalid"
|
|
466
|
+
[[ -z "$invalid" ]] || early_stop config "$CONFIG_REL: $invalid"
|
|
467
|
+
RAW_CONFIG="$(jq -c . "$CONFIG_REL")"
|
|
468
|
+
else
|
|
469
|
+
CONFIG_SOURCE="defaults (no $CONFIG_REL)"
|
|
470
|
+
RAW_CONFIG='{}'
|
|
471
|
+
fi
|
|
472
|
+
CONFIG="$(jq -c --slurpfile schema "$SCHEMA" "$FILL_JQ" <<< "$RAW_CONFIG")" \
|
|
473
|
+
|| early_stop config "cannot resolve the defaults from $SCHEMA"
|
|
474
|
+
cfg() { jq -r "$1" <<< "$CONFIG"; }
|
|
475
|
+
|
|
476
|
+
PROFILE="$(cfg .profile)"
|
|
477
|
+
SHIFT_CAP="$(cfg .caps.shift)"
|
|
478
|
+
BUDGET="$(cfg .caps.budget)"
|
|
479
|
+
LOG_LABEL="$(cfg .labels.log)"
|
|
480
|
+
# shellcheck disable=SC2034 # read by tracker_write, from tracker.sh
|
|
481
|
+
REPORT_LABEL="$(cfg .labels.report)"
|
|
482
|
+
|
|
483
|
+
# stage_on <stage>: whether the stage's switch is on. The report rides on triage's.
|
|
484
|
+
stage_on() {
|
|
485
|
+
case "$1" in
|
|
486
|
+
report) [[ "$(cfg .stages.triage)" == true ]] ;;
|
|
487
|
+
*) [[ "$(cfg ".stages.$1")" == true ]] ;;
|
|
488
|
+
esac
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
# ---- the state directory and the lock ---------------------------------------------------
|
|
492
|
+
#
|
|
493
|
+
# Everything durable lives under .claude/kryso-watch/, excluded through the common git directory
|
|
494
|
+
# the way ship-loop's shift directories are: state.json, the lock, and one directory per
|
|
495
|
+
# watch. Nothing the tracker already holds goes in the state file. A watch moves the
|
|
496
|
+
# .claude/warden/ a warden before the rename left to the new name first, with a link back, and
|
|
497
|
+
# a dry run, which writes nothing, reads whichever is there.
|
|
498
|
+
|
|
499
|
+
STATE_NEW="$REPO_ROOT/.claude/kryso-watch"
|
|
500
|
+
STATE_OLD="$REPO_ROOT/.claude/warden"
|
|
501
|
+
_ledger_pick "$STATE_NEW" "$STATE_OLD" STATE_DIR
|
|
502
|
+
STATE_FILE="$STATE_DIR/state.json"
|
|
503
|
+
LOCK="$STATE_DIR/lock"
|
|
504
|
+
|
|
505
|
+
open_state_dir() {
|
|
506
|
+
_ledger_migrate_state "$REPO_ROOT" .claude/warden .claude/kryso-watch \
|
|
507
|
+
|| early_stop state "cannot move $STATE_OLD to $STATE_NEW"
|
|
508
|
+
_ledger_pick "$STATE_NEW" "$STATE_OLD" STATE_DIR
|
|
509
|
+
STATE_FILE="$STATE_DIR/state.json"
|
|
510
|
+
LOCK="$STATE_DIR/lock"
|
|
511
|
+
mkdir -p "$STATE_DIR" || early_stop state "cannot create $STATE_DIR"
|
|
512
|
+
_ledger_exclude "$REPO_ROOT" '.claude/kryso-watch/'
|
|
513
|
+
_ledger_exclude "$REPO_ROOT" '.claude/warden/'
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
# ---- the tracker -----------------------------------------------------------------------
|
|
517
|
+
#
|
|
518
|
+
# Every tracker write the driver and its stage bodies make goes through tracker_write, from
|
|
519
|
+
# tracker.sh beside this script, which refuses anything outside what ADR 0004 lets the warden
|
|
520
|
+
# do. It reads the report and log labels from these two names.
|
|
521
|
+
|
|
522
|
+
# ---- the preflight -----------------------------------------------------------------------
|
|
523
|
+
|
|
524
|
+
# find_ship_loop: ship-loop beside this skill, under .agents/skills, or under the
|
|
525
|
+
# .claude/skills compatibility path, the same places ship-loop looks for ship-it.
|
|
526
|
+
find_ship_loop() {
|
|
527
|
+
local candidate
|
|
528
|
+
for candidate in "$(dirname "$HERE")/kryso-shift/ship-loop.sh" "$REPO_ROOT/.agents/skills/kryso-shift/ship-loop.sh" \
|
|
529
|
+
"$HOME/.agents/skills/kryso-shift/ship-loop.sh" "$REPO_ROOT/.claude/skills/kryso-shift/ship-loop.sh" \
|
|
530
|
+
"$HOME/.claude/skills/kryso-shift/ship-loop.sh"; do
|
|
531
|
+
[[ -f "$candidate" ]] && { printf '%s' "$candidate"; return 0; }
|
|
532
|
+
done
|
|
533
|
+
return 1
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
# preflight <stop-fn> <log>: ship-loop's own checks, run unchanged through its dry run, then
|
|
537
|
+
# the warden's: a GitHub tracker, and the three labels the config names. The stop function
|
|
538
|
+
# is early_stop on a dry run and env_stop in a watch.
|
|
539
|
+
preflight() {
|
|
540
|
+
local stop="$1" log="$2" ship_loop out code failed args labels key name ledger_sh isolated
|
|
541
|
+
ship_loop="$(find_ship_loop)" \
|
|
542
|
+
|| "$stop" install "cannot find ship-loop.sh beside $HERE, under .agents/skills, or under the .claude/skills compatibility path"
|
|
543
|
+
# A shift `kryso --isolate docker` runs in a container holds its locks in Docker Desktop's VM,
|
|
544
|
+
# out of this host's sight, so a watch beside it would triage, shift and settle its issues
|
|
545
|
+
# (ADR 0039). The ledger module beside ship-loop reads its pid file.
|
|
546
|
+
ledger_sh="$(dirname "$(dirname "$ship_loop")")/kryso/ledger.sh"
|
|
547
|
+
if [[ -f "$ledger_sh" ]] && isolated="$(bash "$ledger_sh" isolated "$REPO_ROOT")"; then
|
|
548
|
+
"$stop" isolated "an isolated kryso run (docker pid $isolated) is working this repository, and its locks are not visible here"
|
|
549
|
+
fi
|
|
550
|
+
args=(--dry-run ${READ_ONLY_ARGS[@]+"${READ_ONLY_ARGS[@]}"} --profile "$PROFILE" --max "$SHIFT_CAP")
|
|
551
|
+
# A budget the config names is passed on, so a profile that has no dollar cap refuses it
|
|
552
|
+
# in ship-loop's own words. The default is ship-loop's default already.
|
|
553
|
+
[[ "$(jq -r '.caps.budget // empty' <<< "$RAW_CONFIG")" == "" ]] || args+=(--budget "$BUDGET")
|
|
554
|
+
out="$(bash "$ship_loop" "${args[@]}" 2>&1)"; code=$?
|
|
555
|
+
# The receipt shows the reader switch ship-loop was handed, since it travels as environment.
|
|
556
|
+
[[ -z "$log" ]] || printf '$ %sbash %s %s\n%s\nexit=%s\n' "${PLAYBOOK_SECOND_READER:+PLAYBOOK_SECOND_READER=$PLAYBOOK_SECOND_READER }" "$ship_loop" "${args[*]}" "$out" "$code" > "$log"
|
|
557
|
+
grep -E '^ship-loop: warning: ' <<< "$out" | sed 's/^ship-loop: /warden: preflight /' >&2
|
|
558
|
+
if [[ "$code" -ne 0 ]]; then
|
|
559
|
+
failed="$(grep -E '^(preflight|runner): ' <<< "$out" | tail -1)"
|
|
560
|
+
"$stop" preflight "ship-loop ${failed:-exited $code: $(tail -1 <<< "$out")}"
|
|
561
|
+
fi
|
|
562
|
+
git config --get-regexp '^remote\..*\.url$' 2>/dev/null | grep -qiE 'github\.com[:/]' \
|
|
563
|
+
|| "$stop" tracker "no GitHub remote, and the warden log lives on the tracker"
|
|
564
|
+
labels="$(gh label list --limit 1000 --json name 2>&1)" || "$stop" labels "cannot list the labels: $(head -1 <<< "$labels")"
|
|
565
|
+
for key in deferred report log; do
|
|
566
|
+
name="$(cfg ".labels.$key")"
|
|
567
|
+
jq -e --arg l "$name" 'any(.[]; .name == $l)' <<< "$labels" >/dev/null 2>&1 \
|
|
568
|
+
|| "$stop" labels "this repo has no label '$name' (labels.$key)"
|
|
569
|
+
done
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
# resolve_base <stop-fn>: the configured base, else the repository's default branch, fetched
|
|
573
|
+
# from origin, so the sha is the remote's and the main working tree is never touched.
|
|
574
|
+
resolve_base() {
|
|
575
|
+
local stop="$1" err
|
|
576
|
+
BASE="$(cfg '.base // empty')"
|
|
577
|
+
if [[ -z "$BASE" ]]; then
|
|
578
|
+
BASE="$(gh repo view --json defaultBranchRef --jq .defaultBranchRef.name 2>/dev/null)"
|
|
579
|
+
[[ -n "$BASE" ]] || BASE="$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's#^origin/##')"
|
|
580
|
+
[[ -n "$BASE" ]] || "$stop" base "cannot read the repository's default branch, and the config names no base"
|
|
581
|
+
fi
|
|
582
|
+
if [[ "$READ_ONLY" -eq 1 ]]; then read_base "$stop"
|
|
583
|
+
else
|
|
584
|
+
err="$(git fetch --quiet origin "+refs/heads/$BASE:refs/remotes/origin/$BASE" 2>&1)" \
|
|
585
|
+
|| "$stop" base "cannot fetch '$BASE' from origin: $(head -1 <<< "$err")"
|
|
586
|
+
BASE_SHA="$(git rev-parse --verify --quiet "refs/remotes/origin/$BASE")" \
|
|
587
|
+
|| "$stop" base "origin has no '$BASE' after the fetch"
|
|
588
|
+
fi
|
|
589
|
+
CONFIG="$(jq -c --arg b "$BASE" '.base = $b' <<< "$CONFIG")"
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
# read_base <stop-fn>: resolve_base's sha under --read-only. Origin's tip is read with ls-remote,
|
|
593
|
+
# which writes no ref, and a failure stops in the words a failed fetch would, git's own for a
|
|
594
|
+
# missing branch, so the stop line is a plain dry run's. The stages read
|
|
595
|
+
# refs/remotes/origin/<base>, so that is the sha the dry run takes, with a warning when origin's
|
|
596
|
+
# tip differs from it. A base never fetched here has no copy for shift and settle to read, so the
|
|
597
|
+
# dry run takes origin's tip, sets BASE_UNREAD and skips those two. Triage and report read the
|
|
598
|
+
# tracker alone, so they still run, and a read they cannot make stops as a plain dry run stops.
|
|
599
|
+
BASE_UNREAD=""
|
|
600
|
+
read_base() {
|
|
601
|
+
local stop="$1" out code tip
|
|
602
|
+
out="$(GIT_TERMINAL_PROMPT=0 git ls-remote --exit-code --heads origin "refs/heads/$BASE" 2>&1)"; code=$?
|
|
603
|
+
[[ "$code" -ne 2 ]] || "$stop" base "cannot fetch '$BASE' from origin: fatal: couldn't find remote ref refs/heads/$BASE"
|
|
604
|
+
[[ "$code" -eq 0 ]] || "$stop" base "cannot fetch '$BASE' from origin: $(head -1 <<< "$out")"
|
|
605
|
+
tip="${out%%[[:space:]]*}"
|
|
606
|
+
if ! BASE_SHA="$(git rev-parse --verify --quiet "refs/remotes/origin/$BASE")"; then
|
|
607
|
+
warn "this repository has never fetched $BASE, and --read-only fetches nothing, so the dry run skips the shift and settle stages, which read its history"
|
|
608
|
+
BASE_SHA="$tip"; BASE_UNREAD=1
|
|
609
|
+
elif [[ "$tip" != "$BASE_SHA" ]]; then
|
|
610
|
+
warn "origin has $BASE at ${tip:0:12} and refs/remotes/origin/$BASE here is at ${BASE_SHA:0:12}. --read-only fetches nothing, so the dry run reads the copy here"
|
|
611
|
+
BASE_WHERE="in refs/remotes/origin/$BASE here"
|
|
612
|
+
fi
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
# The worst case in fresh model contexts the driver starts, from the caps alone: one per
|
|
616
|
+
# issue triaged, one per answered issue the report puts back in the queue (triage's cap),
|
|
617
|
+
# one per shift pass per sweep plus ship-loop's rate-limit retries, one per issue settled.
|
|
618
|
+
# A shift pass spawns its own fork and reviewers inside, which ship-loop's bounds and each
|
|
619
|
+
# pass's budget cover.
|
|
620
|
+
worst_case() {
|
|
621
|
+
local total=0 parts=() t s w unit
|
|
622
|
+
if stage_on triage; then t="$(cfg .caps.triage)"; total=$(( total + t )); parts+=("triage $t"); fi
|
|
623
|
+
if stage_on report; then t="$(cfg .caps.triage)"; total=$(( total + t )); parts+=("report $t"); fi
|
|
624
|
+
if stage_on shift; then
|
|
625
|
+
s="$SHIFT_CAP"; w="$(cfg .caps.sweeps)"
|
|
626
|
+
total=$(( total + s * w + SHIFT_RATE_LIMIT_RETRIES ))
|
|
627
|
+
[[ "$w" -eq 1 ]] && unit=sweep || unit=sweeps
|
|
628
|
+
parts+=("shift $s x $w $unit" "$SHIFT_RATE_LIMIT_RETRIES rate-limit retries")
|
|
629
|
+
fi
|
|
630
|
+
if stage_on settle; then t="$(cfg .caps.settle)"; total=$(( total + t )); parts+=("settle $t"); fi
|
|
631
|
+
local joined="" p
|
|
632
|
+
for p in ${parts[@]+"${parts[@]}"}; do joined+="${joined:+ + }$p"; done
|
|
633
|
+
printf '%s fresh model contexts%s' "$total" "${joined:+ ($joined)}"
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
stages_line() {
|
|
637
|
+
local out="" s
|
|
638
|
+
for s in "${STAGES[@]}"; do
|
|
639
|
+
if stage_on "$s"; then out+="${out:+, }$s runs"; else out+="${out:+, }$s skipped"; fi
|
|
640
|
+
done
|
|
641
|
+
printf '%s' "$out"
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
caps_line() {
|
|
645
|
+
cfg '"triage \(.caps.triage), shift \(.caps.shift), settle \(.caps.settle), budget \(.caps.budget) per shift pass, sweeps \(.caps.sweeps)"'
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
# stage_env: what a stage body reads besides its two arguments: the resolved config with the
|
|
649
|
+
# base in it, the base sha, the watch id, the state file settlement reads its settled sha
|
|
650
|
+
# from, and the ship-loop install whose runner starts a context. Exported, so the body is
|
|
651
|
+
# its own process and still sees what the driver resolved.
|
|
652
|
+
stage_env() {
|
|
653
|
+
export KRYSO_WATCH_CONFIG="$CONFIG" KRYSO_WATCH_BASE_SHA="$BASE_SHA" KRYSO_WATCH_ID="${WATCH_ID:-dry-run}"
|
|
654
|
+
export KRYSO_WATCH_STATE_FILE="$STATE_FILE" KRYSO_SHIFT_SKILL_DIR
|
|
655
|
+
KRYSO_SHIFT_SKILL_DIR="$(dirname "$(find_ship_loop)")"
|
|
656
|
+
[[ "$READ_ONLY" -eq 0 ]] || export PLAYBOOK_SECOND_READER=off
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
# ---- the dry run ---------------------------------------------------------------------------
|
|
660
|
+
|
|
661
|
+
if [[ "$DRY_RUN" -eq 1 ]]; then
|
|
662
|
+
! styled || { ui_brand watch "$(basename "$REPO_ROOT"), dry run"; ui_section primary PREFLIGHT; }
|
|
663
|
+
say "working in $REPO_ROOT"
|
|
664
|
+
say "the config comes from $CONFIG_SOURCE"
|
|
665
|
+
say "start: $START_LINE"
|
|
666
|
+
preflight early_stop ""
|
|
667
|
+
resolve_base early_stop
|
|
668
|
+
# On an attended run the resolved config, one long JSON line, is dim under the plan's pill.
|
|
669
|
+
if styled; then ui_section primary PLAN; ui_info "resolved config: $(ui_tint dim "$CONFIG")"
|
|
670
|
+
else say "resolved config: $CONFIG"; fi
|
|
671
|
+
say "the base is $BASE at $BASE_SHA ${BASE_WHERE:-on origin}"
|
|
672
|
+
say "stages: $(stages_line)"
|
|
673
|
+
say "caps: $(caps_line)"
|
|
674
|
+
say "the watch starts at most $(worst_case)"
|
|
675
|
+
# The triage candidates in order, and each exclusion with its reason, read live. The body
|
|
676
|
+
# prints them and starts nothing. A read it cannot make is an environment stop.
|
|
677
|
+
if stage_on triage && [[ -f "$HERE/stages/triage.sh" ]]; then
|
|
678
|
+
stage_env
|
|
679
|
+
bash "$HERE/stages/triage.sh" --dry-run "$REPO_ROOT" | relay; [[ "${PIPESTATUS[0]}" -eq 0 ]] || exit 3
|
|
680
|
+
fi
|
|
681
|
+
# The report items pending on the open report and the answers a watch would apply.
|
|
682
|
+
if stage_on report && [[ -f "$HERE/stages/report.sh" ]]; then
|
|
683
|
+
stage_env
|
|
684
|
+
bash "$HERE/stages/report.sh" --dry-run "$REPO_ROOT" | relay; [[ "${PIPESTATUS[0]}" -eq 0 ]] || exit 3
|
|
685
|
+
fi
|
|
686
|
+
# The shift's queue in order, each exclusion, the base rule's parks and the exact command.
|
|
687
|
+
if stage_on shift && [[ -z "$BASE_UNREAD" && -f "$HERE/stages/shift.sh" ]]; then
|
|
688
|
+
stage_env
|
|
689
|
+
bash "$HERE/stages/shift.sh" --dry-run "$REPO_ROOT" | relay; [[ "${PIPESTATUS[0]}" -eq 0 ]] || exit 3
|
|
690
|
+
fi
|
|
691
|
+
# The range settlement would read and its candidates with what selected each.
|
|
692
|
+
if stage_on settle && [[ -z "$BASE_UNREAD" && -f "$HERE/stages/settle.sh" ]]; then
|
|
693
|
+
stage_env
|
|
694
|
+
bash "$HERE/stages/settle.sh" --dry-run "$REPO_ROOT" | relay; [[ "${PIPESTATUS[0]}" -eq 0 ]] || exit 3
|
|
695
|
+
fi
|
|
696
|
+
! styled || ui_section secondary DONE
|
|
697
|
+
if styled; then ui_ok "the dry run spent nothing and wrote nothing"; else say "the dry run spent nothing and wrote nothing"; fi
|
|
698
|
+
exit 0
|
|
699
|
+
fi
|
|
700
|
+
|
|
701
|
+
# ---- the watch -----------------------------------------------------------------------------
|
|
702
|
+
|
|
703
|
+
open_state_dir
|
|
704
|
+
take_lock "$LOCK" watch lock
|
|
705
|
+
trap release_lock EXIT
|
|
706
|
+
|
|
707
|
+
if [[ -f "$STATE_FILE" ]]; then
|
|
708
|
+
PREV_STATE="$(jq -c 'select(type == "object")' "$STATE_FILE" 2>/dev/null)"
|
|
709
|
+
[[ -n "$PREV_STATE" ]] || early_stop state "$STATE_FILE is not a JSON object"
|
|
710
|
+
else
|
|
711
|
+
PREV_STATE='{}'
|
|
712
|
+
fi
|
|
713
|
+
|
|
714
|
+
WATCH_ID="$(unique_id "$STATE_DIR")"
|
|
715
|
+
WATCH_DIR="$STATE_DIR/$WATCH_ID"
|
|
716
|
+
WATCH_REL="${STATE_DIR#"$REPO_ROOT"/}/$WATCH_ID"
|
|
717
|
+
mkdir -p "$WATCH_DIR" || early_stop state "cannot create $WATCH_DIR"
|
|
718
|
+
STARTED_AT="$(date -u +%FT%TZ)"
|
|
719
|
+
BASE=""
|
|
720
|
+
BASE_SHA=""
|
|
721
|
+
STOP_CHECK=""
|
|
722
|
+
LOG_ISSUE=""
|
|
723
|
+
LOG_COMMENT=""
|
|
724
|
+
# One result per stage, keyed by name, the shape the stage slices fill.
|
|
725
|
+
RESULTS='{}'
|
|
726
|
+
for s in "${STAGES[@]}"; do RESULTS="$(jq -c --arg s "$s" '.[$s] = {status: "not-reached"}' <<< "$RESULTS")"; done
|
|
727
|
+
|
|
728
|
+
! styled || { ui_brand watch "$(basename "$REPO_ROOT")"; ui_section primary PREFLIGHT; }
|
|
729
|
+
say "watch $WATCH_ID in $REPO_ROOT, config: $CONFIG_SOURCE"
|
|
730
|
+
say "start: $START_LINE"
|
|
731
|
+
|
|
732
|
+
# write_json <file> <json>: written whole, then moved into place, so a reader never sees half.
|
|
733
|
+
write_json() { printf '%s\n' "$2" | jq . > "$1.tmp" && mv "$1.tmp" "$1"; }
|
|
734
|
+
|
|
735
|
+
write_manifest() {
|
|
736
|
+
write_json "$WATCH_DIR/manifest.json" "$(jq -n \
|
|
737
|
+
--arg watch "$WATCH_ID" --arg repo "$REPO_ROOT" --arg started "$STARTED_AT" \
|
|
738
|
+
--arg source "$CONFIG_SOURCE" --argjson config "$CONFIG" \
|
|
739
|
+
--arg base "$BASE" --arg sha "$BASE_SHA" --arg worst "$(worst_case)" \
|
|
740
|
+
--argjson results "$RESULTS" --argjson run "$1" --argjson schedule "$START_JSON" '
|
|
741
|
+
{watch: $watch, repo: $repo, started_at: $started, schedule: $schedule, config_source: $source, config: $config,
|
|
742
|
+
base: {branch: $base, remote: "origin", sha: $sha}, worst_case: $worst,
|
|
743
|
+
stages: ($results | with_entries(.value = ({run: $run[.key]} + .value)))}')"
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
# finish <stop> <exit> <reason>: the summary, the state file, the closing line, and the exit.
|
|
747
|
+
# The summary is bounded: the stop, the counts per stage and the paths to every artefact,
|
|
748
|
+
# never a transcript, a result text or a log tail.
|
|
749
|
+
finish() {
|
|
750
|
+
local stop="$1" code="$2" reason="$3" paths settled backlog
|
|
751
|
+
paths="$(cd "$REPO_ROOT" && jq -n --arg dir "$WATCH_REL" --arg state "${STATE_FILE#"$REPO_ROOT"/}" '
|
|
752
|
+
{watch_dir: $dir, summary: "\($dir)/summary.json", state: $state}')"
|
|
753
|
+
[[ -f "$WATCH_DIR/manifest.json" ]] && paths="$(jq -c --arg p "$WATCH_REL/manifest.json" '.manifest = $p' <<< "$paths")"
|
|
754
|
+
[[ -f "$WATCH_DIR/preflight.log" ]] && paths="$(jq -c --arg p "$WATCH_REL/preflight.log" '.preflight = $p' <<< "$paths")"
|
|
755
|
+
[[ -f "$WATCH_DIR/log-entry.md" ]] && paths="$(jq -c --arg p "$WATCH_REL/log-entry.md" '.log_entry = $p' <<< "$paths")"
|
|
756
|
+
# The pointer to the shift's own directory under ship-loop, and that shift's summary.
|
|
757
|
+
if [[ -f "$WATCH_DIR/shift.json" ]]; then
|
|
758
|
+
paths="$(jq -c --arg p "$WATCH_REL/shift.json" '.shift = $p' <<< "$paths")"
|
|
759
|
+
local shift_summary
|
|
760
|
+
shift_summary="$(jq -r '.summary // empty' "$WATCH_DIR/shift.json" 2>/dev/null)"
|
|
761
|
+
[[ -z "$shift_summary" || ! -f "$REPO_ROOT/$shift_summary" ]] \
|
|
762
|
+
|| paths="$(jq -c --arg p "$shift_summary" '.shift_summary = $p' <<< "$paths")"
|
|
763
|
+
fi
|
|
764
|
+
local s
|
|
765
|
+
for s in "${STAGES[@]}"; do
|
|
766
|
+
[[ -f "$WATCH_DIR/stage-$s.log" ]] && paths="$(jq -c --arg s "$s" --arg p "$WATCH_REL/stage-$s.log" '.stage_logs[$s] = $p' <<< "$paths")"
|
|
767
|
+
done
|
|
768
|
+
write_json "$WATCH_DIR/summary.json" "$(jq -n \
|
|
769
|
+
--arg watch "$WATCH_ID" --arg stop "$stop" --argjson exit "$code" --arg reason "$reason" \
|
|
770
|
+
--arg check "$STOP_CHECK" --arg started "$STARTED_AT" --arg ended "$(date -u +%FT%TZ)" \
|
|
771
|
+
--arg base "$BASE" --arg sha "$BASE_SHA" --argjson results "$RESULTS" \
|
|
772
|
+
--arg issue "$LOG_ISSUE" --arg comment "$LOG_COMMENT" --argjson paths "$paths" \
|
|
773
|
+
--argjson schedule "$START_JSON" '
|
|
774
|
+
def nn: if . == "" then null else . end;
|
|
775
|
+
{watch: $watch, stop: $stop, reason: $reason, exit: $exit, check: ($check | nn),
|
|
776
|
+
started_at: $started, ended_at: $ended, schedule: $schedule,
|
|
777
|
+
base: {branch: ($base | nn), sha: ($sha | nn)},
|
|
778
|
+
stages: ($results | with_entries(.value |= {status, found: (.found // 0), open: (.open // 0), counts: (.counts // {})}
|
|
779
|
+
+ (if has("issues") then {issues: [.issues[] | {issue, state} + (if has("pr") then {pr} else {} end)]} else {} end)
|
|
780
|
+
+ (if has("ship_loop") then {review_ready: (.review_ready // []), reason: (.reason // null),
|
|
781
|
+
ship_loop: (if .ship_loop == null then null else .ship_loop | {dir, summary, exit} end)} else {} end)
|
|
782
|
+
+ (if has("report") then {report, added: [.added[]? | {n, issue}], applied: [.applied[]? | {n, issue, answer}],
|
|
783
|
+
unparsed: (.unparsed // [])} else {} end)
|
|
784
|
+
+ (if has("backlog") then {backlog, range: (.range // null)} else {} end)
|
|
785
|
+
+ (if has("reader") then {reader} else {} end))),
|
|
786
|
+
counts: {found: ([$results[] | .found // 0] | add), open: ([$results[] | .open // 0] | add)},
|
|
787
|
+
log: {issue: ($issue | nn), comment: ($comment | nn)},
|
|
788
|
+
paths: $paths}')"
|
|
789
|
+
# The settled branch and sha and the settle backlog move only when settlement reports them.
|
|
790
|
+
settled="$(jq -c --argjson prev "$PREV_STATE" '.settle.settled // $prev.settled // {branch: null, sha: null}' <<< "$RESULTS")"
|
|
791
|
+
backlog="$(jq -c --argjson prev "$PREV_STATE" '.settle.backlog // $prev.settle_backlog // []' <<< "$RESULTS")"
|
|
792
|
+
write_json "$STATE_FILE" "$(jq -n --argjson v "$STATE_SCHEMA" --arg id "$WATCH_ID" --arg stop "$stop" \
|
|
793
|
+
--argjson exit "$code" --argjson settled "$settled" --argjson backlog "$backlog" '
|
|
794
|
+
{schema: $v, last_watch: {id: $id, stop: $stop, exit: $exit}, settled: $settled, settle_backlog: $backlog}')"
|
|
795
|
+
if styled; then
|
|
796
|
+
# The close: a green DONE on a planned stop, a yellow STOPPED on any other, the same words.
|
|
797
|
+
if [[ "$code" -eq 0 ]]; then ui_section secondary DONE; ui_ok "stop $stop (exit $code): $reason"
|
|
798
|
+
else ui_section warn STOPPED; ui_warn "stop $stop (exit $code): $reason"; fi
|
|
799
|
+
ui_info "summary at $(ui_tint dim "$WATCH_REL/summary.json")"
|
|
800
|
+
else
|
|
801
|
+
say "stop $stop (exit $code): $reason"
|
|
802
|
+
say "summary at $WATCH_REL/summary.json"
|
|
803
|
+
fi
|
|
804
|
+
exit "$code"
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
# env_stop <check> <reason>: an environment stop once the watch holds the lock. The summary
|
|
808
|
+
# and the state record it, and nothing goes to the tracker.
|
|
809
|
+
env_stop() {
|
|
810
|
+
STOP_CHECK="$1"
|
|
811
|
+
stop_line "$1" "$2"
|
|
812
|
+
finish environment 3 "$1: $2"
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
preflight env_stop "$WATCH_DIR/preflight.log"
|
|
816
|
+
resolve_base env_stop
|
|
817
|
+
|
|
818
|
+
# The manifest, before anything is spent: the resolved config, the base sha at the start,
|
|
819
|
+
# which stages run and which are skipped, and one section per stage for its slice to fill.
|
|
820
|
+
RUN_MAP="$(for s in "${STAGES[@]}"; do if stage_on "$s"; then echo "{\"$s\":true}"; else echo "{\"$s\":false}"; fi; done | jq -sc add)"
|
|
821
|
+
write_manifest "$RUN_MAP"
|
|
822
|
+
say "the base is $BASE at $BASE_SHA"
|
|
823
|
+
say "stages: $(stages_line)"
|
|
824
|
+
|
|
825
|
+
# ---- the stages ----------------------------------------------------------------------------
|
|
826
|
+
#
|
|
827
|
+
# A stage switched off is skipped. A stage switched on runs its body, stages/<stage>.sh beside
|
|
828
|
+
# this script, with the repository root and the watch directory, and the body prints one JSON
|
|
829
|
+
# object: found (what it found to act on), open (what it left for a person), counts, and
|
|
830
|
+
# optionally stop, check and reason. Settlement may add settled and backlog for the state
|
|
831
|
+
# file, range, the commits it read, and reader, what the second reader did with its
|
|
832
|
+
# candidates. A body may add candidates and excluded, which go into the manifest, and issues,
|
|
833
|
+
# one {issue, state} per issue it touched, with a pr where it has one, which the summary and
|
|
834
|
+
# the log entry name. Triage adds blocked, the open issues holding agent:blocked, which the
|
|
835
|
+
# log entry names. The report adds report, added (the items it posted), applied (the
|
|
836
|
+
# answers it wrote onto their issues) and unparsed (what it could not read as an answer),
|
|
837
|
+
# which all three name. The shift adds review_ready, the pull requests waiting for review,
|
|
838
|
+
# which all three name, and command and ship_loop, the ship-loop argv and the pointer to its
|
|
839
|
+
# shift directory. A stage with no body yet found nothing. An environment failure ends the
|
|
840
|
+
# watch there, and so does a rate limit anywhere but the shift. Only the shift can fail, and a
|
|
841
|
+
# failed or rate-limited shift does not end the watch, because settlement still runs after
|
|
842
|
+
# it. A body that prints anything else is a broken install, an environment stop naming that
|
|
843
|
+
# body.
|
|
844
|
+
|
|
845
|
+
set_result() { RESULTS="$(jq -c --arg s "$1" --argjson r "$2" '.[$s] = $r' <<< "$RESULTS")"; }
|
|
846
|
+
# quiet_result <status> <reason>: the result of a stage that ran no body.
|
|
847
|
+
quiet_result() { jq -cn --arg status "$1" --arg reason "$2" '{status: $status, found: 0, open: 0, counts: {}, reason: $reason}'; }
|
|
848
|
+
# broken_result <stage> <reason>: the environment stop for a body whose output is not a result.
|
|
849
|
+
broken_result() {
|
|
850
|
+
jq -cn --arg s "$1" --arg reason "$2" \
|
|
851
|
+
'{status: "environment", stop: "environment", check: "\($s) body", found: 0, open: 0, counts: {}, reason: $reason}'
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
run_stage() {
|
|
855
|
+
local stage="$1" body="$HERE/stages/$1.sh" out result
|
|
856
|
+
if ! stage_on "$stage"; then set_result "$stage" "$(quiet_result skipped "switched off in the config")"; return; fi
|
|
857
|
+
if [[ ! -f "$body" ]]; then set_result "$stage" "$(quiet_result found-nothing "no stage body yet")"; return; fi
|
|
858
|
+
stage_env
|
|
859
|
+
out="$(bash "$body" "$REPO_ROOT" "$WATCH_DIR" 2> "$WATCH_DIR/stage-$stage.log")"
|
|
860
|
+
result="$(jq -cs --arg stage "$stage" '
|
|
861
|
+
if length != 1 or (.[0] | type) != "object" or (.[0].found | type) != "number" then "the stage body printed no result object"
|
|
862
|
+
else .[0]
|
|
863
|
+
| if (.stop // null) as $st | $st == null or $st == "rate-limited" or $st == "environment" or ($st == "failed" and $stage == "shift") then
|
|
864
|
+
{found, open: (.open // 0), counts: (.counts // {})}
|
|
865
|
+
+ (if .stop then {stop, check, reason} else {reason} end)
|
|
866
|
+
+ (if has("settled") then {settled} else {} end) + (if has("backlog") then {backlog} else {} end)
|
|
867
|
+
+ (with_entries(select(.key as $k | ["candidates", "excluded", "issues", "blocked", "report", "added", "applied", "unparsed", "range", "reader", "review_ready", "command", "ship_loop"] | index($k))))
|
|
868
|
+
| .status = (if .stop then .stop elif .found > 0 then "ran" else "found-nothing" end)
|
|
869
|
+
else "the stage body reported stop \(.stop | tojson), which this stage cannot make" end
|
|
870
|
+
end' <<< "$out" 2>/dev/null)"
|
|
871
|
+
case "$result" in
|
|
872
|
+
'{'*) ;;
|
|
873
|
+
'"'*) result="$(broken_result "$stage" "$(jq -r . <<< "$result")")" ;;
|
|
874
|
+
*) result="$(broken_result "$stage" "the stage body printed no result object")" ;;
|
|
875
|
+
esac
|
|
876
|
+
set_result "$stage" "$result"
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
for s in "${STAGES[@]}"; do
|
|
880
|
+
! styled || ui_section primary "$(tr '[:lower:]' '[:upper:]' <<< "$s")"
|
|
881
|
+
run_stage "$s"
|
|
882
|
+
write_manifest "$RUN_MAP"
|
|
883
|
+
say "$s: $(jq -r --arg s "$s" '.[$s] | "\(.status), found \(.found)"' <<< "$RESULTS")"
|
|
884
|
+
case "$s:$(jq -r --arg s "$s" '.[$s].stop // ""' <<< "$RESULTS")" in
|
|
885
|
+
*:environment) break ;;
|
|
886
|
+
shift:rate-limited) ;;
|
|
887
|
+
*:rate-limited) break ;;
|
|
888
|
+
esac
|
|
889
|
+
done
|
|
890
|
+
|
|
891
|
+
# The shift parks what the base rule holds and settlement parks superseded issues on the
|
|
892
|
+
# decision report too, and both run after the report stage, so the report body runs once
|
|
893
|
+
# more in its post mode, which posts the items they left in report-items.json and nothing
|
|
894
|
+
# else. Their items and the report join the report stage's result, whichever switches were
|
|
895
|
+
# on, since the report is the one place for the calls a watch cannot make.
|
|
896
|
+
post_late_items() {
|
|
897
|
+
local out post
|
|
898
|
+
[[ -f "$HERE/stages/report.sh" && -f "$WATCH_DIR/report-items.json" ]] || return 0
|
|
899
|
+
jq -e 'type == "array" and any(.[]; .source == "shift" or .source == "settle")' "$WATCH_DIR/report-items.json" >/dev/null 2>&1 || return 0
|
|
900
|
+
stage_env
|
|
901
|
+
out="$(bash "$HERE/stages/report.sh" --post "$REPO_ROOT" "$WATCH_DIR" 2>> "$WATCH_DIR/stage-report.log")"
|
|
902
|
+
post="$(jq -cs 'if length == 1 and (.[0] | type) == "object" and (.[0].found | type) == "number" then .[0] else empty end' <<< "$out" 2>/dev/null)"
|
|
903
|
+
if [[ -z "$post" ]]; then
|
|
904
|
+
set_result report "$(broken_result report "the report body printed no result object when posting the shift's and settlement's items")"
|
|
905
|
+
return
|
|
906
|
+
fi
|
|
907
|
+
RESULTS="$(jq -c --argjson p "$post" '
|
|
908
|
+
.report as $r | ($p.added // []) as $added
|
|
909
|
+
| .report = ($r + {found: (($r.found // 0) + ($added | length)), counts: (($r.counts // {}) + {added: (($r.counts.added // 0) + ($added | length))}),
|
|
910
|
+
report: ($p.report // $r.report), added: (($r.added // []) + $added), unparsed: (($r.unparsed // []) + ($p.unparsed // []))}
|
|
911
|
+
+ (if $p.stop then {stop: $p.stop, check: ($p.check // "report body"), reason: $p.reason} else {} end))
|
|
912
|
+
| .report.status = (if .report.stop then .report.stop elif .report.found > 0 then "ran" else .report.status end)' <<< "$RESULTS")"
|
|
913
|
+
write_manifest "$RUN_MAP"
|
|
914
|
+
say "report: posted $(jq -r '.added | length' <<< "$post") item(s) from the shift and settlement"
|
|
915
|
+
}
|
|
916
|
+
post_late_items
|
|
917
|
+
|
|
918
|
+
# ---- the stop -------------------------------------------------------------------------------
|
|
919
|
+
#
|
|
920
|
+
# One reading of the stage results: the stop, its exit code, the reason and, for an
|
|
921
|
+
# environment stop, the check. A stop a stage made wins, environment over a rate limit over a
|
|
922
|
+
# failed shift. Otherwise nothing found is an empty frontier, anything left for a person is
|
|
923
|
+
# review-ready, and the rest is complete.
|
|
924
|
+
|
|
925
|
+
STOP_JSON="$(jq -c '
|
|
926
|
+
([.[] | .found // 0] | add) as $found
|
|
927
|
+
| ([.[] | .open // 0] | add) as $open
|
|
928
|
+
| {environment: 3, "rate-limited": 2, failed: 1} as $codes
|
|
929
|
+
| ([("environment", "rate-limited", "failed") as $k | to_entries[] | select(.value.stop == $k)] | first) as $s
|
|
930
|
+
| if $s then
|
|
931
|
+
{stop: $s.value.stop, exit: $codes[$s.value.stop], reason: "\($s.key): \($s.value.reason // "no reason given")",
|
|
932
|
+
check: (if $s.value.stop == "environment" then ($s.value.check // $s.key) else "" end)}
|
|
933
|
+
elif $found == 0 then {stop: "frontier-empty", exit: 0, reason: "no stage found anything to act on", check: ""}
|
|
934
|
+
elif $open > 0 then {stop: "review-ready", exit: 0, reason: "\($open) item(s) left for a person", check: ""}
|
|
935
|
+
else {stop: "complete", exit: 0, reason: "every stage finished what it found", check: ""} end' <<< "$RESULTS")"
|
|
936
|
+
STOP="$(jq -r .stop <<< "$STOP_JSON")"
|
|
937
|
+
EXIT_CODE="$(jq -r .exit <<< "$STOP_JSON")"
|
|
938
|
+
REASON="$(jq -r .reason <<< "$STOP_JSON")"
|
|
939
|
+
STOP_CHECK="$(jq -r .check <<< "$STOP_JSON")"
|
|
940
|
+
|
|
941
|
+
# ---- the warden log ---------------------------------------------------------------------------
|
|
942
|
+
#
|
|
943
|
+
# One open issue per repository carries the log label, found live by the label and created on
|
|
944
|
+
# first use. Each watch that got past the preflight leaves exactly one comment on it, an
|
|
945
|
+
# environment stop inside a stage included: the counts per stage, the stop and its reason,
|
|
946
|
+
# and the watch directory, which holds the evidence the entry points at.
|
|
947
|
+
|
|
948
|
+
jq -r --arg id "$WATCH_ID" --arg stop "$STOP" --arg code "$EXIT_CODE" --arg reason "$REASON" \
|
|
949
|
+
--arg dir "$WATCH_REL" --arg base "$BASE" --arg sha "$BASE_SHA" --arg start "$START_ENTRY" '
|
|
950
|
+
"Watch `\($id)` stopped `\($stop)` (exit \($code)): \($reason)",
|
|
951
|
+
"",
|
|
952
|
+
"Base `\($base)` at `\($sha[0:12])`.",
|
|
953
|
+
"",
|
|
954
|
+
$start,
|
|
955
|
+
"",
|
|
956
|
+
"| Stage | Status | Found | Left for a person | Counts |",
|
|
957
|
+
"| --- | --- | --- | --- | --- |",
|
|
958
|
+
(to_entries[] | "| \(.key) | \(.value.status) | \(.value.found // 0) | \(.value.open // 0) | \(.value.counts // {} | to_entries | map("\(.key) \(.value)") | join(", ") | if . == "" then "-" else . end) |"),
|
|
959
|
+
(to_entries[] | select((.value.issues // []) | length > 0)
|
|
960
|
+
| "", "\(.key | .[0:1] | ascii_upcase)\(.key[1:]): \([.value.issues[]
|
|
961
|
+
| "#\(.issue) \(.state)\(if (.decisions // 0) > 0 then " (\(.decisions) decision\(if .decisions == 1 then "" else "s" end))" else "" end)\(if (.pr // "none") != "none" then " (\(.pr))" else "" end)"] | join(", "))"),
|
|
962
|
+
(to_entries[] | select((.value.review_ready // []) | length > 0)
|
|
963
|
+
| "", "Pull requests waiting for review: \(.value.review_ready | join(", "))."),
|
|
964
|
+
(to_entries[] | select((.value.blocked // []) | length > 0)
|
|
965
|
+
| "", "Issues a pass parked on, carrying `agent:blocked`: \(.value.blocked | map("#\(.)") | join(", "))."),
|
|
966
|
+
(to_entries[] | .value | select(.report != null and ((.added // []) + (.applied // []) + (.unparsed // []) | length) > 0)
|
|
967
|
+
| "", "Decision report \(.report): \([
|
|
968
|
+
(if (.added // []) | length > 0 then "added \([.added[] | "Q\(.n) (#\(.issue))"] | join(", "))" else empty end),
|
|
969
|
+
(if (.applied // []) | length > 0 then "applied \([.applied[] | "Q\(.n) \(.answer) to #\(.issue)"] | join(", "))" else empty end),
|
|
970
|
+
(if (.unparsed // []) | length > 0 then "not understood: \(.unparsed[:5] | join("; "))\(if (.unparsed | length) > 5 then "; and \(.unparsed | length - 5) more" else "" end)" else empty end)
|
|
971
|
+
] | join("; "))."),
|
|
972
|
+
(.settle | select((.range // null) != null)
|
|
973
|
+
| "", "Settlement read `\(.range.from[0:12])..\(.range.to[0:12])` (\(.range.commits) commit(s)) and carried \(if (.backlog // []) | length > 0 then (.backlog | map("#\(.)") | join(", ")) else "no backlog" end)."),
|
|
974
|
+
(.settle | select((.reader // null) != null) | .reader
|
|
975
|
+
| (if .fallback then ", after \(.fallback)" else "" end) as $after
|
|
976
|
+
| "", (if .skipped then "Settlement'"'"'s second reader\(if .backend then " (\(.backend))" else "" end) skipped: \(.skipped)\($after), so every candidate went to a context."
|
|
977
|
+
elif .failed then "Settlement'"'"'s second reader (\(.backend)) failed: \(.failed)\($after), so every candidate went to a context."
|
|
978
|
+
else "Settlement screened \(.screened) of \(.asked) candidate(s) with \(.backend) (\(if .cost == null then "cost not reported" else "$\(.cost)" end))\($after)." end)),
|
|
979
|
+
"",
|
|
980
|
+
"Watch directory: `\($dir)`"' <<< "$RESULTS" > "$WATCH_DIR/log-entry.md"
|
|
981
|
+
|
|
982
|
+
log_err=""
|
|
983
|
+
issues="$(gh issue list --state open --label "$LOG_LABEL" --json number,url --limit 100 2>&1)" || log_err="cannot read the log issue: $(head -1 <<< "$issues")"
|
|
984
|
+
if [[ -z "$log_err" ]]; then
|
|
985
|
+
LOG_ISSUE="$(jq -r 'min_by(.number) | .url // empty' <<< "$issues" 2>/dev/null)"
|
|
986
|
+
if [[ -z "$LOG_ISSUE" ]]; then
|
|
987
|
+
LOG_ISSUE="$(tracker_write issue create --title "Watch log" --label "$LOG_LABEL" \
|
|
988
|
+
--body "One entry per watch, left by the warden. Each entry names the watch directory that holds its evidence." 2>&1)" \
|
|
989
|
+
|| { log_err="cannot create the log issue: $(head -1 <<< "$LOG_ISSUE")"; LOG_ISSUE=""; }
|
|
990
|
+
LOG_ISSUE="$(grep -oE 'https://[^ ]+/issues/[0-9]+' <<< "$LOG_ISSUE" | tail -1)"
|
|
991
|
+
[[ -n "$LOG_ISSUE" || -n "$log_err" ]] || log_err="gh issue create printed no issue URL"
|
|
992
|
+
fi
|
|
993
|
+
fi
|
|
994
|
+
if [[ -z "$log_err" ]]; then
|
|
995
|
+
LOG_COMMENT="$(tracker_write issue comment "${LOG_ISSUE##*/}" --body-file "$WATCH_DIR/log-entry.md" 2>&1)" \
|
|
996
|
+
|| { log_err="cannot comment on $LOG_ISSUE: $(head -1 <<< "$LOG_COMMENT")"; LOG_COMMENT=""; }
|
|
997
|
+
LOG_COMMENT="$(grep -oE 'https://[^ ]+' <<< "$LOG_COMMENT" | tail -1)"
|
|
998
|
+
fi
|
|
999
|
+
# A log entry that did not land is an environment stop: the tracker is the thing that failed,
|
|
1000
|
+
# and the scheduler reading the exit code has to hear it. The stages' own stop is in the reason.
|
|
1001
|
+
[[ -z "$log_err" ]] || env_stop warden-log "$log_err (the stages stopped $STOP: $REASON)"
|
|
1002
|
+
say "log entry on $LOG_ISSUE"
|
|
1003
|
+
|
|
1004
|
+
finish "$STOP" "$EXIT_CODE" "$REASON"
|