@krysoworks/kryso 0.0.0-stage → 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -2
  3. package/bin/kryso +31 -0
  4. package/bin/ship-it-status +14 -0
  5. package/bin/ship-ledger +14 -0
  6. package/bin/ship-loop +14 -0
  7. package/bin/ship-pass +14 -0
  8. package/bin/warden +14 -0
  9. package/dist/answer.d.ts +38 -0
  10. package/dist/answer.js +48 -0
  11. package/dist/bytes.d.ts +5 -0
  12. package/dist/bytes.js +35 -0
  13. package/dist/cleanup.d.ts +1 -0
  14. package/dist/cleanup.js +629 -0
  15. package/dist/commands.d.ts +48 -0
  16. package/dist/commands.js +293 -0
  17. package/dist/completions.d.ts +24 -0
  18. package/dist/completions.js +239 -0
  19. package/dist/daemon.d.ts +15 -0
  20. package/dist/daemon.js +23 -0
  21. package/dist/diagnose.d.ts +47 -0
  22. package/dist/diagnose.js +314 -0
  23. package/dist/doctor.d.ts +1 -0
  24. package/dist/doctor.js +241 -0
  25. package/dist/env.d.ts +9 -0
  26. package/dist/env.js +17 -0
  27. package/dist/evidence.d.ts +39 -0
  28. package/dist/evidence.js +327 -0
  29. package/dist/home.d.ts +3 -0
  30. package/dist/home.js +27 -0
  31. package/dist/install.d.ts +59 -0
  32. package/dist/install.js +137 -0
  33. package/dist/isolate.d.ts +28 -0
  34. package/dist/isolate.js +402 -0
  35. package/dist/leftovers.d.ts +5 -0
  36. package/dist/leftovers.js +156 -0
  37. package/dist/machine.d.ts +6 -0
  38. package/dist/machine.js +185 -0
  39. package/dist/palette.d.ts +147 -0
  40. package/dist/palette.js +167 -0
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +133 -0
  43. package/dist/proc.d.ts +23 -0
  44. package/dist/proc.js +23 -0
  45. package/dist/read.d.ts +1 -0
  46. package/dist/read.js +297 -0
  47. package/dist/readiness.d.ts +5 -0
  48. package/dist/readiness.js +64 -0
  49. package/dist/remote.d.ts +6 -0
  50. package/dist/remote.js +85 -0
  51. package/dist/self-update.d.ts +1 -0
  52. package/dist/self-update.js +224 -0
  53. package/dist/semver.d.ts +7 -0
  54. package/dist/semver.js +42 -0
  55. package/dist/style.d.ts +71 -0
  56. package/dist/style.js +187 -0
  57. package/dist/update.d.ts +47 -0
  58. package/dist/update.js +190 -0
  59. package/dist/work.d.ts +25 -0
  60. package/dist/work.js +449 -0
  61. package/dist/workflows.d.ts +4 -0
  62. package/dist/workflows.js +73 -0
  63. package/docker/entrypoint.sh +44 -0
  64. package/docker/runner.Dockerfile +39 -0
  65. package/package.json +65 -4
  66. package/scripts/install-skills.sh +607 -0
  67. package/skills/code-review/SKILL.md +231 -0
  68. package/skills/kryso/SKILL.md +107 -0
  69. package/skills/kryso/golden/help.rounded.ansi +23 -0
  70. package/skills/kryso/golden/help.square.ansi +23 -0
  71. package/skills/kryso/golden/help.txt +23 -0
  72. package/skills/kryso/golden/table-narrow.json +11 -0
  73. package/skills/kryso/golden/table-narrow.rounded.ansi +4 -0
  74. package/skills/kryso/golden/table-narrow.square.ansi +4 -0
  75. package/skills/kryso/golden/table.ansi +5 -0
  76. package/skills/kryso/golden/table.json +11 -0
  77. package/skills/kryso/ledger.sh +2146 -0
  78. package/skills/kryso/palette.json +57 -0
  79. package/skills/kryso/reference/resuming.md +30 -0
  80. package/skills/kryso/reference/routing.md +23 -0
  81. package/skills/kryso/reference/stage-1-claim.md +79 -0
  82. package/skills/kryso/reference/stage-2-build.md +133 -0
  83. package/skills/kryso/reference/stage-3-prove.md +51 -0
  84. package/skills/kryso/reference/stage-4-pr.md +76 -0
  85. package/skills/kryso/reference/stage-5-reconcile.md +81 -0
  86. package/skills/kryso/reference/stage-6-merge-or-park.md +73 -0
  87. package/skills/kryso/reference/stage-7-close-out.md +62 -0
  88. package/skills/kryso/reference/terminal.md +7 -0
  89. package/skills/kryso/ship-it-status.sh +1503 -0
  90. package/skills/kryso/ui.py +274 -0
  91. package/skills/kryso/ui.sh +609 -0
  92. package/skills/kryso-build/SKILL.md +168 -0
  93. package/skills/kryso-shift/SKILL.md +167 -0
  94. package/skills/kryso-shift/archive.py +2784 -0
  95. package/skills/kryso-shift/archive_checker.py +462 -0
  96. package/skills/kryso-shift/archive_checker_lambda.py +155 -0
  97. package/skills/kryso-shift/archive_health.py +364 -0
  98. package/skills/kryso-shift/archive_launchd.py +140 -0
  99. package/skills/kryso-shift/archive_remote.py +990 -0
  100. package/skills/kryso-shift/archiving-checker.md +140 -0
  101. package/skills/kryso-shift/archiving-keep.md +115 -0
  102. package/skills/kryso-shift/archiving-recovery.md +112 -0
  103. package/skills/kryso-shift/archiving-remote.md +166 -0
  104. package/skills/kryso-shift/archiving.md +146 -0
  105. package/skills/kryso-shift/coverage.schema.json +225 -0
  106. package/skills/kryso-shift/deadline.sh +254 -0
  107. package/skills/kryso-shift/feedback.schema.json +35 -0
  108. package/skills/kryso-shift/feedback.sh +228 -0
  109. package/skills/kryso-shift/history-manifest.schema.json +331 -0
  110. package/skills/kryso-shift/keep-after.sh +55 -0
  111. package/skills/kryso-shift/measure.sh +611 -0
  112. package/skills/kryso-shift/merge-ready.sh +207 -0
  113. package/skills/kryso-shift/outcome.schema.json +16 -0
  114. package/skills/kryso-shift/pass-rules.md +8 -0
  115. package/skills/kryso-shift/profile.schema.json +42 -0
  116. package/skills/kryso-shift/reader.sh +692 -0
  117. package/skills/kryso-shift/reads.sh +151 -0
  118. package/skills/kryso-shift/reference/allowance.md +21 -0
  119. package/skills/kryso-shift/reference/driver.md +95 -0
  120. package/skills/kryso-shift/reference/measuring.md +67 -0
  121. package/skills/kryso-shift/reference/outputs.md +21 -0
  122. package/skills/kryso-shift/reference/pass-script.md +115 -0
  123. package/skills/kryso-shift/reference/reconcile-and-merge.md +55 -0
  124. package/skills/kryso-shift/reference/second-reader.md +9 -0
  125. package/skills/kryso-shift/reference/sweeps.md +83 -0
  126. package/skills/kryso-shift/repair.schema.json +14 -0
  127. package/skills/kryso-shift/report-template.html +679 -0
  128. package/skills/kryso-shift/report.py +389 -0
  129. package/skills/kryso-shift/report_fixture.py +65 -0
  130. package/skills/kryso-shift/reporting.md +58 -0
  131. package/skills/kryso-shift/result.sh +91 -0
  132. package/skills/kryso-shift/runner.sh +1178 -0
  133. package/skills/kryso-shift/ship-loop.sh +3977 -0
  134. package/skills/kryso-shift/ship-pass.sh +4987 -0
  135. package/skills/kryso-shift/steps.jq +19 -0
  136. package/skills/kryso-shift/workflow.mjs +830 -0
  137. package/skills/kryso-shift/workflows/default.json +22 -0
  138. package/skills/kryso-shift/workflows/ralph.json +13 -0
  139. package/skills/kryso-watch/SKILL.md +100 -0
  140. package/skills/kryso-watch/answer.schema.json +23 -0
  141. package/skills/kryso-watch/base-refs.sh +44 -0
  142. package/skills/kryso-watch/board.sh +58 -0
  143. package/skills/kryso-watch/reference/config.md +23 -0
  144. package/skills/kryso-watch/reference/outputs.md +30 -0
  145. package/skills/kryso-watch/reference/report.md +29 -0
  146. package/skills/kryso-watch/reference/scheduler.md +32 -0
  147. package/skills/kryso-watch/reference/settlement.md +29 -0
  148. package/skills/kryso-watch/reference/shift.md +44 -0
  149. package/skills/kryso-watch/reference/shim-limits.md +22 -0
  150. package/skills/kryso-watch/reference/triage.md +26 -0
  151. package/skills/kryso-watch/schema.jq +40 -0
  152. package/skills/kryso-watch/settle.schema.json +36 -0
  153. package/skills/kryso-watch/stage-common.sh +187 -0
  154. package/skills/kryso-watch/stages/report.sh +525 -0
  155. package/skills/kryso-watch/stages/settle.sh +722 -0
  156. package/skills/kryso-watch/stages/shift.sh +466 -0
  157. package/skills/kryso-watch/stages/triage.sh +379 -0
  158. package/skills/kryso-watch/tracker.sh +27 -0
  159. package/skills/kryso-watch/triage.schema.json +77 -0
  160. package/skills/kryso-watch/warden.launchd.plist +50 -0
  161. package/skills/kryso-watch/warden.schema.json +98 -0
  162. package/skills/kryso-watch/warden.sh +1004 -0
@@ -0,0 +1,611 @@
1
+ #!/usr/bin/env bash
2
+ # measure: the reproducible analysis over saved pass evidence. `freeze` turns a list of source
3
+ # files a person wrote into a manifest that pins each one by its sha256 and says whether it is
4
+ # in the sample and why. `analyze` refuses a manifest whose files have changed since, and prints
5
+ # one JSON report from the files alone: outcomes per unattended hour, interventions, active and
6
+ # waiting time, attempts, repairs, defects, eventual merges kept apart, each model context
7
+ # counted once, usage that stays unknown where the host did not report it, and an API-equivalent
8
+ # cost only when a price table is given, labelled as that. Both read files and nothing else:
9
+ # no model session, no tracker call, no clock in the report. `volume` counts the test and source
10
+ # lines a change added, from git alone, by the repository's testing policy or the default rule.
11
+ # `lasting` reports what happened to merged changes afterwards, also from git alone: reverts, and
12
+ # later `fix` commits to the same files within a window. See reference/measuring.md.
13
+ set -uo pipefail
14
+
15
+ usage() {
16
+ cat <<'USAGE'
17
+ Usage: kryso measure freeze <sources.json>
18
+ kryso measure analyze <manifest.json> [--prices <file>] [--root <dir>]
19
+ kryso measure volume <repo> <from> <to> [--policy <file>]
20
+ kryso measure volume --list <changes.jsonl>
21
+ kryso measure lasting --list <changes.jsonl> [--days <n>]
22
+
23
+ freeze print the frozen manifest for the sources the file lists. It pins
24
+ each source by its sha256, and gives its kind, cohort, time,
25
+ revisions, workload and observations, and whether the analysis
26
+ includes it and why. A relative path is relative to the sources
27
+ file.
28
+ analyze check every included source against its sha256, then print the
29
+ report as JSON. --prices adds what the run would cost at the listed
30
+ API prices. --root reads the sources from another directory, for a
31
+ manifest that moved with its archive.
32
+ volume print the lines of test and of source the change from <from> to <to>
33
+ added in the git repository <repo>, their ratio, and whether it is over
34
+ the policy's threshold. The policy is <repo>/.kryso/testing-policy.md, or
35
+ <repo>/docs/agents/testing-policy.md, its old place,
36
+ unless --policy names one. --list reads one change per line,
37
+ {"repo", "from", "to", "label"?, "seam"?, "policy"?}, and adds a summary
38
+ over them: the medians on seam passes and how many are over threshold.
39
+ lasting print, for each change in the list, where it merged on the default
40
+ branch, whether a later commit reverted any of its commits, and how
41
+ many later fix commits touched its files within --days (30) of the
42
+ merge. Then, per repository, the share of merged changes reverted
43
+ and their mean follow-up fixes, overall and in each half of the
44
+ span from the first merge to the last.
45
+
46
+ The command exits 0 when it is done, 1 when a source changed since the freeze or
47
+ an input cannot be read, and 64 on a usage error.
48
+ USAGE
49
+ }
50
+
51
+ # The styled-output module, found where ledger.sh is, so the help and a refusal are drawn on an
52
+ # attended run. A copy without it prints plain. Both verbs print JSON and nothing else, attended
53
+ # or not, so the module draws nothing on stdout but the help.
54
+ # The lookup is the order ui.sh's header names, which every kryso script keeps.
55
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
56
+ ROOT_DIR="$(git rev-parse --show-toplevel 2>/dev/null)"
57
+ for candidate in "$(dirname "$HERE")/kryso/ui.sh" "$ROOT_DIR/.agents/skills/kryso/ui.sh" "$HOME/.agents/skills/kryso/ui.sh" \
58
+ "$ROOT_DIR/.claude/skills/kryso/ui.sh" "$HOME/.claude/skills/kryso/ui.sh"; do
59
+ # shellcheck source=/dev/null
60
+ [[ -f "$candidate" ]] && { source "$candidate"; break; }
61
+ done
62
+ # Without ui.sh nothing is attended, so every line is the plain one.
63
+ declare -F ui_err_attended > /dev/null || { ui_attended() { return 1; }; ui_err_attended() { return 1; }; }
64
+ # die <message> [code]: a refusal on stderr, under an ERROR pill when attended. Exit 1 or code.
65
+ die() {
66
+ if ui_err_attended; then ui_error "$1"; else echo "measure: $1" >&2; fi
67
+ exit "${2:-1}"
68
+ }
69
+ # bad_usage: arguments neither verb takes, exit 64: an ERROR pill with the help as its hint when
70
+ # attended, else the usage.
71
+ bad_usage() {
72
+ if ui_err_attended; then ui_error "${1:-measure takes freeze or analyze and their arguments}" "kryso measure --help lists the verbs"
73
+ else usage >&2; fi
74
+ exit 64
75
+ }
76
+ command -v jq >/dev/null 2>&1 || die "jq is not installed"
77
+
78
+ # scratch: sets SCRATCH to a directory for this run's intermediate files, removed on exit.
79
+ SCRATCH=""
80
+ scratch() {
81
+ [[ -z "$SCRATCH" ]] || return 0
82
+ SCRATCH="$(mktemp -d)" || die "cannot make a scratch directory"
83
+ trap 'rm -rf "$SCRATCH"' EXIT
84
+ }
85
+
86
+ sha_of() { if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -c1-64; else sha256sum "$1" | cut -c1-64; fi; }
87
+ # mtime_of <file>: epoch seconds, GNU stat first and BSD stat after, or null.
88
+ mtime_of() {
89
+ local t
90
+ t="$(stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null)"
91
+ [[ "$t" =~ ^[0-9]+$ ]] && printf '%s' "$t" || printf 'null'
92
+ }
93
+
94
+ # ---- freeze -------------------------------------------------------------------------------
95
+
96
+ # The sources file: {period: {from, to}, cohort?, workload?, observed?, sources: [{path, cohort?,
97
+ # time?, workload?, observed?, revisions?}]}. Top-level cohort, workload and observed are the
98
+ # defaults each source overrides. Observations are what only a person knows: assisted,
99
+ # interventions, defects and the eventual state of the PR.
100
+ freeze() {
101
+ local sources="$1" root docs path abs sha bytes kind mtime
102
+ [[ -f "$sources" ]] || die "no sources file at $sources"
103
+ jq -e '.sources | type == "array"' "$sources" >/dev/null 2>&1 || die "$sources has no sources list"
104
+ jq -e '.period.from and .period.to' "$sources" >/dev/null 2>&1 || die "$sources has no period with a from and a to"
105
+ root="$(cd "$(dirname "$sources")" && pwd -P)"
106
+ # One line per source in a scratch file, read back with --slurpfile: a body passed as an
107
+ # argument would meet the kernel's cap on one argument long before a real archive ends.
108
+ scratch
109
+ docs="$SCRATCH/docs.jsonl"
110
+ while IFS= read -r path; do
111
+ case "$path" in /*) abs="$path" ;; *) abs="$root/$path" ;; esac
112
+ sha=null bytes=0 kind=missing mtime=null
113
+ if [[ -f "$abs" ]]; then
114
+ sha="\"$(sha_of "$abs")\""
115
+ bytes="$(wc -c < "$abs" | tr -d ' ')"
116
+ mtime="$(mtime_of "$abs")"
117
+ if [[ "$bytes" -eq 0 ]]; then kind=empty
118
+ elif jq -c -s --arg path "$path" --argjson sha "$sha" --argjson bytes "$bytes" --argjson mtime "$mtime" '
119
+ if length == 1 and (.[0] | type) == "object" then .[0] as $b
120
+ | {path: $path, sha256: $sha, bytes: $bytes, mtime: $mtime, body: $b,
121
+ kind: (if ($b.schema // "" | test("^ship-pass-record/[1-4]$")) then "record" elif $b.type == "result" then "result"
122
+ elif ($b.outcome | type) == "string" then "outcome" else "unknown" end)}
123
+ else error("not one object") end' "$abs" >> "$docs" 2>/dev/null; then continue
124
+ else kind=unparseable; fi
125
+ fi
126
+ jq -nc --arg path "$path" --argjson sha "$sha" --argjson bytes "$bytes" --arg kind "$kind" --argjson mtime "$mtime" \
127
+ '{path: $path, sha256: $sha, bytes: $bytes, kind: $kind, body: null, mtime: $mtime}' >> "$docs"
128
+ done < <(jq -r '.sources[].path' "$sources")
129
+ [[ -f "$docs" ]] || : > "$docs"
130
+ jq -S --slurpfile docs "$docs" --arg root "$root" "$(jq_defs)"'
131
+ . as $src
132
+ | ($src.cohort // "default") as $cohort0
133
+ | [range(0; $docs | length) as $i | ($src.sources[$i]) as $e | ($docs[$i]) as $d
134
+ | ($d.body // {}) as $b
135
+ | (if $d.kind == "record" then {time: $b.ended_at, source: "record"}
136
+ elif $e.time != null then {time: $e.time, source: "sources file"}
137
+ elif $d.mtime != null then {time: ($d.mtime | todate), source: "mtime"}
138
+ else {time: null, source: null} end) as $t
139
+ | {path: $d.path, sha256: $d.sha256, bytes: $d.bytes, kind: $d.kind,
140
+ cohort: ($e.cohort // $cohort0), time: $t.time, time_source: $t.source,
141
+ attempt: (if ($d.kind | IN("record", "outcome", "result")) then ($b | attempt_key($d.kind; $d.sha256)) else null end),
142
+ sessions: (if $d.kind == "record" then [$b.contexts[]? | select(.id != null) | "\(.host):\(.id)"]
143
+ elif $d.kind == "result" then [$b | select((.session_id // "none") != "none") | "\(.host // "claude"):\(.session_id)"]
144
+ else [] end),
145
+ issue: ((if $d.kind == "result" then ($b.ship_loop.issue // $b.structured_output.issue) else ($b.issue // $b.ship_loop.issue) end) // null | if . == null then null else tostring end),
146
+ revisions: ($e.revisions // (if $d.kind == "record" then $b.revisions else null end)),
147
+ workload: (($src.workload // {}) + (if $d.kind == "record" then {repository: $b.repository, gate: ($b.gate.names // [] | join(" "))} | with_entries(select(.value != null and .value != "")) else {} end) + ($e.workload // {})),
148
+ observed: (($src.observed // {}) + ($e.observed // {}))}]
149
+ # The reasons, in order: what the file is, then when it is, then whether an earlier included
150
+ # source is a byte-identical copy, then whether a record included anywhere in the list
151
+ # already carries it, as an outcome block or a host result of the attempt it records. The
152
+ # cover is read over the whole list, so the order the sources are listed in changes nothing.
153
+ | reduce .[] as $s ([];
154
+ . as $acc
155
+ | ([$acc[] | select(.included)]) as $in
156
+ | ($in | map(select(.sha256 == $s.sha256)) | first) as $dup
157
+ | $acc + [$s + (
158
+ if $s.kind == "missing" then {included: false, reason: "missing: no file at the path"}
159
+ elif $s.kind == "empty" then {included: false, reason: "empty file"}
160
+ elif $s.kind == "unparseable" then {included: false, reason: "not a JSON object"}
161
+ elif $s.kind == "unknown" then {included: false, reason: "not a pass record, an outcome block or a host result"}
162
+ elif $s.time == null then {included: false, reason: "no time, so the period cannot place it"}
163
+ elif $s.time < $src.period.from or $s.time >= $src.period.to then {included: false, reason: "outside the observation period"}
164
+ elif $dup != null then {included: false, reason: ("duplicate of " + $dup.path)}
165
+ else {included: true, reason: "included"} end)])
166
+ | [.[] | select(.included and .kind == "record")] as $records
167
+ | map(. as $s
168
+ | ($records | map(. as $r | select(
169
+ ($s.kind == "outcome" and $s.attempt == $r.attempt)
170
+ or ($s.kind == "result" and ($s.sessions | length) > 0 and any($s.sessions[]; . as $x | any($r.sessions[]; . == $x)))))
171
+ | first) as $cover
172
+ | if $s.included and $cover != null then $s + {included: false, reason: ("covered by the record " + $cover.path)} else $s end)
173
+ | {manifest: "ship-measure/1", root: $root, period: $src.period,
174
+ counts: {sources: length, included: (map(select(.included)) | length), excluded: (map(select(.included | not)) | length)},
175
+ sources: .}' "$sources"
176
+ }
177
+
178
+ # ---- analyze ------------------------------------------------------------------------------
179
+
180
+ # The jq both verbs share: an attempt's identity, the outcome word it counts as, and usage in
181
+ # one shape whatever host reported it.
182
+ jq_defs() {
183
+ cat <<'JQ'
184
+ def attempt_key($kind; $sha):
185
+ if ($kind == "record" or $kind == "outcome") and (.attempt_id // "") != "" then .attempt_id
186
+ elif $kind == "result" and (.session_id // "none") != "none" then "session:\(.session_id):\(.ship_loop.pass // .ship_loop.attempt // $sha)"
187
+ else "sha:\($sha)" end;
188
+ # The outcome an attempt counts as. The supervisor's typed state wins where the driver wrote one.
189
+ def outcome_class:
190
+ (.ship_loop.state // null) as $state
191
+ | (if .type == "result" then (.structured_output.outcome // null) else .outcome end) as $o
192
+ | if $state == "done" then "shipped"
193
+ elif $state == "review-ready" then "review-ready"
194
+ elif (.schema // "" | test("^ship-pass-record/[1-4]$")) and .status == "interrupted" then "interrupted"
195
+ elif $o == "shipped" then "shipped"
196
+ elif $o == "parked" and ((.stage // "") == "merge") then "review-ready"
197
+ elif $o == "parked" then "parked"
198
+ elif $o == "failed" then "failed"
199
+ elif $o == "rate-limited" or $o == "budget-stop" or $o == "interrupted" then "interrupted"
200
+ elif $o == "locked" or $o == "nothing-to-take" then "not-taken"
201
+ elif .type == "result" and (.is_error // false) then "interrupted"
202
+ else "unknown" end;
203
+ # The test volume of a set of changes, each {test_lines, source_lines, ratio, over_threshold,
204
+ # seam, tests, seams}: seam is true for a pass whose seam call was tdd, or null when unknown.
205
+ # The medians and the over-threshold count are read over the seam passes, the ones that set out
206
+ # to write tests, and the aggregate ratio over every change.
207
+ def median: sort | length as $n | if $n == 0 then null elif $n % 2 == 1 then .[($n - 1) / 2]
208
+ else ((.[$n / 2 - 1] + .[$n / 2]) / 2) end;
209
+ def round2: if . == null then null else (. * 100 | round / 100) end;
210
+ def volume_summary:
211
+ . as $all | map(select(.seam == true)) as $seam
212
+ | ($all | map(.test_lines) | add // 0) as $t | ($all | map(.source_lines) | add // 0) as $src
213
+ | {changes: ($all | length), seam_passes: ($seam | length),
214
+ test_lines: $t, source_lines: $src, ratio: (if $src > 0 then ($t / $src | round2) else null end),
215
+ seam_median_ratio: ($seam | map(.ratio | select(. != null)) | median | round2),
216
+ seam_over_threshold: ($seam | map(select(.over_threshold == true)) | length),
217
+ seam_test_only: ($seam | map(select(.ratio == null and .test_lines > 0)) | length),
218
+ tests_per_seam_median: ($all | map(select((.seams // 0) > 0 and .tests != null) | .tests / .seams) | median | round2),
219
+ tests_per_seam_known: ($all | map(select((.seams // 0) > 0 and .tests != null)) | length)};
220
+ # Usage in one shape. Codex counts cached input inside its input, and writes no cache. Claude
221
+ # splits its cache writes by lifetime where it reports the split; what it does not split stays
222
+ # in cache_write_unsplit, because pricing it at either lifetime would be a guess.
223
+ def norm_usage($host):
224
+ if type != "object" then null
225
+ elif $host == "codex" then
226
+ {input: ((.input_tokens // 0) - (.cached_input_tokens // 0)), output: (.output_tokens // 0), cache_read: (.cached_input_tokens // 0),
227
+ cache_write_5m: 0, cache_write_1h: 0, cache_write_unsplit: 0}
228
+ else
229
+ (.cache_creation_input_tokens // 0) as $cw
230
+ | (.cache_creation.ephemeral_5m_input_tokens // null) as $w5
231
+ | (.cache_creation.ephemeral_1h_input_tokens // null) as $w1
232
+ | {input: (.input_tokens // 0), output: (.output_tokens // 0), cache_read: (.cache_read_input_tokens // 0),
233
+ cache_write_5m: ($w5 // 0), cache_write_1h: ($w1 // 0),
234
+ cache_write_unsplit: ([$cw - ($w5 // 0) - ($w1 // 0), 0] | max)}
235
+ end;
236
+ JQ
237
+ }
238
+
239
+ analyze() {
240
+ local manifest="$1" prices="$2" root_override="$3" root bodies path abs want got
241
+ [[ -f "$manifest" ]] || die "no manifest at $manifest"
242
+ jq -e '.manifest == "ship-measure/1"' "$manifest" >/dev/null 2>&1 || die "$manifest is not a ship-measure/1 manifest"
243
+ if [[ -n "$prices" ]]; then
244
+ [[ -f "$prices" ]] || die "no price table at $prices"
245
+ jq -e '(.source | type) == "string" and (.date | type) == "string" and (.models | type) == "object"' "$prices" >/dev/null 2>&1 \
246
+ || die "$prices needs a source, a date and a models table"
247
+ fi
248
+ root="${root_override:-$(jq -r '.root' "$manifest")}"
249
+ # The freeze is the contract: an included file that moved or changed is refused, never read.
250
+ # Each body goes to a scratch file, one line per source, for the same reason as the freeze's.
251
+ scratch
252
+ bodies="$SCRATCH/bodies.jsonl"
253
+ : > "$bodies"
254
+ while IFS=$'\t' read -r path want; do
255
+ case "$path" in /*) abs="$path" ;; *) abs="$root/$path" ;; esac
256
+ [[ -f "$abs" ]] || die "$path is missing, and the manifest froze it at $want"
257
+ got="$(sha_of "$abs")"
258
+ [[ "$got" == "$want" ]] || die "$path changed since the freeze: sha256 $got, frozen at $want"
259
+ jq -c -s --arg p "$path" '{($p): .[0]}' "$abs" >> "$bodies" || die "jq cannot read $path as JSON"
260
+ done < <(jq -r '.sources[] | select(.included) | [.path, .sha256] | @tsv' "$manifest")
261
+ jq -S --slurpfile parts "$bodies" --argjson prices "$( [[ -n "$prices" ]] && jq -c . "$prices" || echo null)" "$(jq_defs)"'
262
+ ($parts | add // {}) as $bodies |
263
+ def sum_known(f): map(f | select(. != null)) | add // 0;
264
+ def count_known(f): map(select(f != null)) | length;
265
+ def count_unknown(f): map(select(f == null)) | length;
266
+ def per_hour($n; $s): if $s > 0 then (($n / ($s / 3600)) * 1000 | round / 1000) else null end;
267
+ . as $m
268
+ # One attempt per included source, keyed so a second copy of the same attempt is seen.
269
+ | [$m.sources[] | select(.included) | . as $s | $bodies[$s.path] as $b
270
+ | ($b.host // "claude") as $host
271
+ | {key: $s.attempt, cohort: $s.cohort, path: $s.path, kind: $s.kind, time: $s.time,
272
+ issue: $s.issue, outcome: ($b | outcome_class), observed: $s.observed, workload: $s.workload,
273
+ revisions: $s.revisions,
274
+ engine: (if $s.kind == "record" then "script" elif $s.kind == "outcome" then "script" else "ship-it" end),
275
+ host: $host, profile: ($b.profile // null), effort: ($b.effort // null),
276
+ model: (if $s.kind == "record" then ($b.model.requested // ($b.model.observed // [] | join(","))) else ($b.modelUsage // {} | [to_entries[] | .value.canonicalModel // .key] | join(",")) end | if . == "" then null else . end),
277
+ elapsed: (if $s.kind == "record" then $b.elapsed_seconds elif ($b.duration_ms | type) == "number" then ($b.duration_ms / 1000 | floor) else null end),
278
+ waiting: (if $s.kind == "record" then (($b.waits.ci_seconds // 0) + ($b.waits.receipt_queue_seconds // 0)) else null end),
279
+ repairs: (if $s.kind == "record" then $b.repairs else null end),
280
+ volume: (if $s.kind == "record" then ($b.test_volume // null) else null end),
281
+ seam_call: (if $s.kind == "record" then ($b.seam // null) else null end),
282
+ contexts: (if $s.kind == "record" then [$b.contexts[] | {id, role, host: (.host // $host), usage: (.usage | norm_usage(.host // $host)), cost: .cost_usd,
283
+ models: (.model_observed // null), peak: .peak_context, compacted: .compacted}]
284
+ elif $s.kind == "result" then [{id: ($b.session_id // null | if . == "none" then null else . end), role: "pass", host: $host,
285
+ usage: ((if $b | has("reported_usage") then $b.reported_usage else $b.usage end) | norm_usage($host)), cost: ($b.total_cost_usd // $b.cost_usd // null),
286
+ models: ($b.modelUsage // null | if . == null then null else [to_entries[] | .value.canonicalModel // .key] end),
287
+ peak: null, compacted: null}]
288
+ else [{id: ($b.session // null | if . == "none" then null else . end), role: "build", host: $host,
289
+ usage: ($b.usage | norm_usage($host)), cost: ($b.cost_usd // null), models: null, peak: null, compacted: null}] end)}]
290
+ | (group_by(.key) | map(sort_by({record: 0, outcome: 1, result: 2}[.kind]) | {kept: .[0], copies: (length - 1)})) as $grouped
291
+ | ($grouped | map(.kept)) as $attempts
292
+ # A context is keyed by its host and id; one with no id is its own and cannot be matched.
293
+ # Each attempt that names it adds its own usage, which is an invocation, not a second context.
294
+ | [$attempts[] | . as $a | .contexts | to_entries[] | .value + {
295
+ ckey: (if .value.id == null then "anon:\($a.key):\(.key)" else "\(.value.host):\(.value.id)" end),
296
+ cohort: $a.cohort, attempt: $a.key}] as $invocations
297
+ | def price($u; $models):
298
+ if $prices == null or $u == null or $models == null or ($models | length) != 1 or $u.cache_write_unsplit > 0 then null
299
+ else ($prices.models[$models[0]] // null) as $p
300
+ | if $p == null then null
301
+ else (($u.input * $p.input + $u.output * $p.output + $u.cache_read * $p.cache_read
302
+ + $u.cache_write_5m * $p.cache_write_5m + $u.cache_write_1h * $p.cache_write_1h) / 1000000 * 1000000 | round / 1000000) end end;
303
+ def cohort_report($c):
304
+ ($attempts | map(select(.cohort == $c)) | sort_by(.time)) as $as
305
+ | ($invocations | map(select(.cohort == $c))) as $inv
306
+ | ($inv | group_by(.ckey) | map({ckey: .[0].ckey, role: .[0].role, peak: (map(.peak) | map(select(. != null)) | max),
307
+ compacted: (map(.compacted) | if any(. == true) then true elif all(. == false) then false else null end)})) as $ctx
308
+ # An issue number belongs to a repository, so an issue is keyed by both. A source whose
309
+ # workload names no repository keeps the number alone, and the sample counts those issues.
310
+ # An attempt that names no issue is its own: nothing says two of them are one issue retried.
311
+ | ($as | group_by([.workload.repository, (.issue // "attempt \(.key)")]) | map({issue: .[0].issue, repository: .[0].workload.repository, attempts: length, last: .[-1],
312
+ assisted: (map(.observed.assisted) | if any(. == true) then true elif any(. == null) then null else false end),
313
+ interventions: (map(.observed.interventions) | if any(. == null) then null else add end),
314
+ defects: (map(.observed.defects) | if any(. == null) then null else add end),
315
+ eventual: (map(.observed.eventual) | map(select(. != null)) | last // "unknown"),
316
+ elapsed: (map(.elapsed) | if any(. == null) then null else add end),
317
+ waiting: (map(.waiting) | if any(. == null) then null else add end)})) as $issues
318
+ | ($issues | map(select(.assisted == false))) as $un
319
+ | ($un | map(select(.elapsed != null))) as $timed
320
+ | ($timed | map(.elapsed) | add // 0) as $secs
321
+ | {cohort: $c,
322
+ sample: {attempts: ($as | length), issues: ($issues | length), contexts: ($ctx | length),
323
+ issues_without_repository: ($issues | map(select(.issue != null and .repository == null)) | length),
324
+ duplicate_attempts: ($grouped | map(select(.kept.cohort == $c) | .copies) | add // 0)},
325
+ attempts: {total: ($as | length), retries: (($as | length) - ($issues | length)),
326
+ outcomes: ($as | group_by(.outcome) | map({key: .[0].outcome, value: length}) | from_entries)},
327
+ outcomes: ($issues | group_by(.last.outcome) | map({key: .[0].last.outcome, value: length}) | from_entries),
328
+ unknown_outcomes: ($issues | map(select(.last.outcome == "unknown")) | length),
329
+ unattended: {issues: ($un | length), timed_issues: ($timed | length), untimed_issues: (($un | length) - ($timed | length)),
330
+ hours: ($secs / 3600 * 1000 | round / 1000),
331
+ shipped: ($timed | map(select(.last.outcome == "shipped")) | length),
332
+ review_ready: ($timed | map(select(.last.outcome == "review-ready")) | length),
333
+ shipped_per_hour: per_hour($timed | map(select(.last.outcome == "shipped")) | length; $secs),
334
+ review_ready_per_hour: per_hour($timed | map(select(.last.outcome == "review-ready")) | length; $secs)},
335
+ assisted: {issues: ($issues | map(select(.assisted == true)) | length),
336
+ outcomes: ($issues | map(select(.assisted == true)) | group_by(.last.outcome) | map({key: .[0].last.outcome, value: length}) | from_entries),
337
+ unknown: ($issues | map(select(.assisted == null)) | length)},
338
+ eventual: ($issues | group_by(.eventual) | map({key: .[0].eventual, value: length}) | from_entries),
339
+ interventions: {total: ($issues | sum_known(.interventions)), known: ($issues | count_known(.interventions)), unknown: ($issues | count_unknown(.interventions))},
340
+ defects: {total: ($issues | sum_known(.defects)), known: ($issues | count_known(.defects)), unknown: ($issues | count_unknown(.defects))},
341
+ time: {elapsed_seconds: ($issues | sum_known(.elapsed)), waiting_seconds: ($issues | sum_known(.waiting)),
342
+ active_seconds: ($issues | map(select(.elapsed != null and .waiting != null) | .elapsed - .waiting) | add // 0),
343
+ waiting_known: ($issues | count_known(.waiting)), waiting_unknown: ($issues | count_unknown(.waiting)),
344
+ elapsed_unknown: ($issues | count_unknown(.elapsed))},
345
+ repairs: {total: ($as | sum_known(.repairs)), known: ($as | count_known(.repairs)), unknown: ($as | count_unknown(.repairs))},
346
+ # Per attempt whose record carries a test volume. A record from before the volume was
347
+ # recorded has none, and is left out rather than counted as no tests.
348
+ test_volume: ($as | map(select(.volume != null)
349
+ | .volume + {seam: (if (.seam_call // "") == "" then null else .seam_call == "tdd" end)}) | volume_summary),
350
+ contexts: {count: ($ctx | length), by_role: ($ctx | group_by(.role) | map({key: .[0].role, value: length}) | from_entries),
351
+ invocations: ($inv | length),
352
+ peak_context: {max: ($ctx | map(.peak) | map(select(. != null)) | max), known: ($ctx | count_known(.peak)), unknown: ($ctx | count_unknown(.peak))},
353
+ compacted: {yes: ($ctx | map(select(.compacted == true)) | length), no: ($ctx | map(select(.compacted == false)) | length),
354
+ unknown: ($ctx | map(select(.compacted == null)) | length)}},
355
+ usage: (($inv | map(.usage) | map(select(. != null))) as $u
356
+ | {input: ($u | map(.input) | add // 0), output: ($u | map(.output) | add // 0), cache_read: ($u | map(.cache_read) | add // 0),
357
+ cache_write_5m: ($u | map(.cache_write_5m) | add // 0), cache_write_1h: ($u | map(.cache_write_1h) | add // 0),
358
+ cache_write_unsplit: ($u | map(.cache_write_unsplit) | add // 0),
359
+ invocations_known: ($u | length), invocations_unknown: (($inv | length) - ($u | length)),
360
+ complete: (($u | length) == ($inv | length))}),
361
+ reported_cost_usd: {total: ($inv | sum_known(.cost) * 1000000 | round / 1000000), known: ($inv | count_known(.cost)), unknown: ($inv | count_unknown(.cost)),
362
+ label: "as each host reported it; Claude reports an API-equivalent figure, not subscription spend or an invoice"},
363
+ api_equivalent: (if $prices == null then null
364
+ else ($inv | map(price(.usage; .models))) as $p
365
+ | {total_usd: ($p | map(select(. != null)) | add // 0 | . * 1000000 | round / 1000000),
366
+ known: ($p | map(select(. != null)) | length), unknown: ($p | map(select(. == null)) | length),
367
+ label: "API-equivalent reconstruction at the listed prices; not subscription spend and not invoice savings"} end)};
368
+ ($attempts | map(.cohort) | unique) as $cohorts
369
+ | {report: "ship-measure-report/1",
370
+ period: $m.period,
371
+ sources: $m.counts,
372
+ prices: (if $prices == null then null else {source: $prices.source, date: $prices.date, currency: ($prices.currency // "USD"),
373
+ unit: "per million tokens", models: $prices.models} end),
374
+ cohorts: [$cohorts[] as $c | cohort_report($c)],
375
+ confounders: (if ($cohorts | length) < 2 then []
376
+ else [ ("engine", "host", "profile", "model", "effort") as $f
377
+ | {field: $f, values: ([$cohorts[] as $c | {key: $c, value: ($attempts | map(select(.cohort == $c) | .[$f]) | unique)}] | from_entries)}
378
+ | select([.values[]] | unique | length > 1) ]
379
+ + [ ("repository", "task", "gate") as $f
380
+ | {field: $f, values: ([$cohorts[] as $c | {key: $c, value: ($attempts | map(select(.cohort == $c) | .workload[$f] // null) | unique)}] | from_entries)}
381
+ | select([.values[]] | unique | length > 1) ]
382
+ + [ {field: "revisions", values: ([$cohorts[] as $c | {key: $c, value: ($attempts | map(select(.cohort == $c) | .revisions) | unique)}] | from_entries)}
383
+ | select([.values[]] | unique | length > 1) ] end)}' "$manifest"
384
+ }
385
+
386
+ # ---- volume --------------------------------------------------------------------------------
387
+
388
+ # The default rule, the spec's (jv-k/engineering-playbook#14): a path holding any of these is
389
+ # test code. The testing-policy template's `test-paths` row holds the same list.
390
+ DEFAULT_TEST_PATHS=(.test. .spec. tests/ __tests__/ e2e/ fixtures fake mock)
391
+
392
+ # policy_knob <file> <knob>: the Value cell of the policy table's row for the knob, trimmed, or
393
+ # nothing. The row is `| `knob` | value | what it sets |`, as templates/testing-policy.md has it.
394
+ policy_knob() {
395
+ sed -nE 's/^\|[[:space:]]*`'"$2"'`[[:space:]]*\|[[:space:]]*([^|]*[^|[:space:]])[[:space:]]*\|.*$/\1/p' "$1" 2>/dev/null | head -1
396
+ }
397
+
398
+ # default_policy <repo>: the repository's testing policy on disk, .kryso/testing-policy.md, or
399
+ # docs/agents/testing-policy.md, its old place, where that is absent.
400
+ default_policy() {
401
+ if [[ -f "$1/.kryso/testing-policy.md" ]]; then printf '%s' "$1/.kryso/testing-policy.md"
402
+ else printf '%s' "$1/docs/agents/testing-policy.md"; fi
403
+ }
404
+
405
+ # volume_json <repo> <from> <to> <policy-path or ""> [seam]: one change's volume as JSON on
406
+ # stdout, or a refusal on stderr and status 1. Lines are added lines from --numstat, renames
407
+ # followed. A path on the test paths is test code, a JSON fixture under tests/ included. Of the
408
+ # rest, JSON, Markdown, SQL and lockfiles are neither test nor source. A binary file counts as
409
+ # nothing. This is the order the spec's baseline was counted in, which the build in
410
+ # docs/qa/test-volume-baseline/ checks.
411
+ volume_json() {
412
+ local repo="$1" from="$2" to="$3" policy="$4" seam="${5:-}" stats sha="" threshold over tokens=()
413
+ git -C "$repo" rev-parse --verify -q "$from^{commit}" >/dev/null 2>&1 || { echo "measure: $from is not a commit in $repo" >&2; return 1; }
414
+ git -C "$repo" rev-parse --verify -q "$to^{commit}" >/dev/null 2>&1 || { echo "measure: $to is not a commit in $repo" >&2; return 1; }
415
+ stats="$(git -C "$repo" diff --no-ext-diff --no-textconv --find-renames --numstat "$from" "$to" -- 2>/dev/null)" \
416
+ || { echo "measure: git cannot diff $from and $to in $repo" >&2; return 1; }
417
+ if [[ -n "$policy" && -f "$policy" ]]; then
418
+ sha="$(git hash-object "$policy" 2>/dev/null)"
419
+ # shellcheck disable=SC2207,SC2016 # the tokens are backticked words with no spaces in them
420
+ tokens=($(policy_knob "$policy" test-paths | grep -oE '`[^`]+`' | tr -d '`'))
421
+ threshold="$(policy_knob "$policy" threshold)"
422
+ over="$(policy_knob "$policy" over-budget)"
423
+ fi
424
+ [[ ${#tokens[@]} -gt 0 ]] || tokens=("${DEFAULT_TEST_PATHS[@]}")
425
+ [[ "${threshold:-}" =~ ^[0-9]+(\.[0-9]+)?$ ]] || threshold=2
426
+ [[ "${over:-}" == stop ]] || over=flag
427
+ printf '%s' "$stats" | jq -Rsc --arg policy "$policy" --arg sha "$sha" --argjson threshold "$threshold" --arg over "$over" \
428
+ --arg seam "$seam" --args '
429
+ def newpath: if test("\\{.* => .*\\}") then sub("\\{(?<a>[^}]*) => (?<b>[^}]*)\\}"; "\(.b)") | gsub("//"; "/")
430
+ elif test(" => ") then split(" => ") | .[-1] else . end;
431
+ def other: test("\\.(json|md|sql|lock)$"; "i") or test("(^|/)(pnpm-lock\\.yaml|package-lock\\.json|yarn\\.lock|go\\.sum|Gemfile\\.lock|Cargo\\.lock|poetry\\.lock|uv\\.lock)$");
432
+ $ARGS.positional as $tokens
433
+ | [split("\n")[] | select(length > 0) | split("\t") | select(.[0] != "-")
434
+ | (.[2:] | join("\t") | newpath) as $path
435
+ | {path: $path, added: (.[0] | tonumber),
436
+ kind: (if any($tokens[]; . as $t | $path | contains($t)) then "test" elif ($path | other) then "other" else "source" end)}] as $rows
437
+ | def lines($k): $rows | map(select(.kind == $k) | .added) | add // 0;
438
+ lines("test") as $t | lines("source") as $s
439
+ | {rule: (if $sha == "" then "default" else "policy" end),
440
+ policy: (if $sha == "" then null else {path: $policy, sha: $sha} end),
441
+ test_paths: $tokens, threshold: $threshold, over_budget: $over,
442
+ test_lines: $t, source_lines: $s, other_lines: lines("other"),
443
+ files: {test: ($rows | map(select(.kind == "test")) | length), source: ($rows | map(select(.kind == "source")) | length),
444
+ other: ($rows | map(select(.kind == "other")) | length)},
445
+ ratio: (if $s > 0 then ($t / $s * 100 | round / 100) else null end),
446
+ over_threshold: (if $s > 0 then ($t / $s > $threshold) elif $t > 0 then true else false end)}
447
+ + (if $seam == "" then {} else {seam: ($seam == "tdd")} end)' "${tokens[@]}"
448
+ }
449
+
450
+ # volume_list <changes.jsonl>: each change's volume, in order, then the summary over them.
451
+ volume_list() {
452
+ local file="$1" line repo from to label seam policy out
453
+ [[ -f "$file" ]] || die "no changes file at $file"
454
+ scratch
455
+ out="$SCRATCH/volumes.jsonl"; : > "$out"
456
+ while IFS= read -r line; do
457
+ [[ -n "${line// /}" ]] || continue
458
+ IFS=$'\t' read -r repo from to label seam policy < <(jq -r '[.repo, .from, .to, (.label // ""), (.seam // ""), (.policy // "")] | @tsv' <<< "$line" 2>/dev/null) \
459
+ || die "a line of $file is not a change: $line"
460
+ [[ -n "$policy" ]] || policy="$(default_policy "$repo")"
461
+ volume_json "$repo" "$from" "$to" "$policy" "$seam" | jq -c --arg label "$label" '{label: $label} + .' >> "$out" || exit 1
462
+ done < "$file"
463
+ jq -s "$(jq_defs)"'{report: "ship-volume/1", changes: ., summary: volume_summary}' "$out"
464
+ }
465
+
466
+ # ---- lasting -------------------------------------------------------------------------------
467
+
468
+ # lasting_branch <repo>: the default branch: origin's HEAD, then HEAD in a bare mirror, whose HEAD
469
+ # names it, then main, then master, then HEAD.
470
+ lasting_branch() {
471
+ local b bare
472
+ bare="$(git -C "$1" rev-parse --is-bare-repository 2>/dev/null)"
473
+ for b in "$(git -C "$1" symbolic-ref -q --short refs/remotes/origin/HEAD 2>/dev/null)" \
474
+ "$([[ "$bare" == true ]] && echo HEAD)" main master; do
475
+ [[ -n "$b" ]] && git -C "$1" rev-parse --verify -q "$b^{commit}" >/dev/null 2>&1 && { printf '%s' "$b"; return; }
476
+ done
477
+ printf 'HEAD'
478
+ }
479
+
480
+ # lasting_json <repo> <from> <to> <days> <label>: what happened to one change after it merged, as
481
+ # JSON on stdout, or a refusal on stderr and status 1. The merge is the oldest commit on the
482
+ # default branch's first-parent line that holds <to>. What the change brought is what that merge
483
+ # added to the line, so commits of the branch's own base merged in on the way are not its own.
484
+ # A revert is any later commit on the branch whose message says `This reverts commit <sha>` of
485
+ # one of the change's commits, the merge included, or whose subject starts `Revert "<subject>"`
486
+ # of one of them, at any time. A follow-up fix is a later commit whose subject is a `fix`
487
+ # Conventional Commit, that touched a file the change touched, and that was committed within
488
+ # <days> of the merge.
489
+ lasting_json() {
490
+ local repo="$1" from="$2" to="$3" days="$4" label="$5" dir branch tip merge base at=null tip_at=null files=() f
491
+ git -C "$repo" rev-parse --verify -q "$from^{commit}" >/dev/null 2>&1 || { echo "measure: $from is not a commit in $repo" >&2; return 1; }
492
+ to="$(git -C "$repo" rev-parse --verify -q "$to^{commit}" 2>/dev/null)" || { echo "measure: $3 is not a commit in $repo" >&2; return 1; }
493
+ # The branch, its tip and its first-parent line, once per repository.
494
+ dir="$SCRATCH/repo-$(printf '%s' "$repo" | cksum | cut -d' ' -f1)"
495
+ if [[ ! -d "$dir" ]]; then
496
+ mkdir -p "$dir"
497
+ lasting_branch "$repo" > "$dir/branch"
498
+ git -C "$repo" rev-parse "$(<"$dir/branch")^{commit}" > "$dir/tip"
499
+ git -C "$repo" rev-list --first-parent --reverse "$(<"$dir/tip")" > "$dir/chain"
500
+ fi
501
+ branch="$(<"$dir/branch")" tip="$(<"$dir/tip")"
502
+ merge="$({ echo "$to"; git -C "$repo" rev-list --ancestry-path "$to..$tip"; } | grep -Fx -f - "$dir/chain" | head -1)"
503
+ : > "$dir/own"; : > "$dir/reverts"; : > "$dir/fixes"
504
+ if [[ -n "$merge" ]]; then
505
+ at="$(git -C "$repo" show -s --format=%ct "$merge")" tip_at="$(git -C "$repo" show -s --format=%ct "$tip")"
506
+ if [[ "$merge" == "$to" ]]; then base="$from"; else base="$merge^1"; fi
507
+ { git -C "$repo" log --format='%H%x1f%s' "$base..$to"; [[ "$merge" == "$to" ]] || git -C "$repo" log -1 --format='%H%x1f%s' "$merge"; } > "$dir/own"
508
+ git -C "$repo" log -E --grep='^This reverts commit [0-9a-f]{7,}' --grep='^Revert "' --format='%H%x1f%B%x1e' "$merge..$tip" > "$dir/reverts"
509
+ while IFS= read -r -d '' f; do files+=("$f"); done < <(git -C "$repo" diff --no-renames --name-only -z "$base" "$merge")
510
+ [[ ${#files[@]} -eq 0 ]] || git --literal-pathspecs -C "$repo" log --no-merges --full-history --format='%H%x1f%ct%x1f%s' "$merge..$tip" -- "${files[@]}" > "$dir/fixes"
511
+ fi
512
+ jq -nc --arg label "$label" --arg repo "$repo" --arg from "$from" --arg to "$to" --arg branch "$branch" --arg merge "$merge" \
513
+ --argjson at "$at" --argjson tip_at "$tip_at" --argjson days "$days" \
514
+ --rawfile own "$dir/own" --rawfile reverts "$dir/reverts" --rawfile fixes "$dir/fixes" '
515
+ def fields($s): $s | split("\n") | map(select(length > 0) | split("\u001f"));
516
+ (fields($own) | map({sha: .[0], subject: .[1]})) as $own
517
+ | ($reverts | split("\u001e") | map(sub("^\n"; "") | select(length > 0) | split("\u001f")
518
+ | {sha: .[0], subject: (.[1] | split("\n")[0]), shas: [.[1] | scan("This reverts commit ([0-9a-f]{7,40})") | .[0]]})
519
+ | map(select(. as $r | any($own[]; . as $c | ($r.shas | any(. as $p | $c.sha | startswith($p)))
520
+ or ($r.subject | startswith("Revert \"" + $c.subject + "\""))))
521
+ | .sha)) as $by
522
+ | (fields($fixes) | map(select((.[2] | test("^fix(\\([^)]*\\))?!?:"; "i"))
523
+ and (.[1] | tonumber) > $at and (.[1] | tonumber) <= $at + $days * 86400) | .[0])) as $fx
524
+ | ($merge != "") as $merged
525
+ | {label: $label, repo: $repo, from: $from, to: $to, branch: $branch, merged: $merged}
526
+ + if $merged then
527
+ {merge: $merge, merged_at: ($at | todate), reverted: ($by | length > 0), reverted_by: $by,
528
+ follow_up_fixes: ($fx | length), fix_commits: $fx, window_complete: ($tip_at >= $at + $days * 86400)}
529
+ else {merge: null, merged_at: null, reverted: null, reverted_by: null, follow_up_fixes: null, fix_commits: null, window_complete: null} end'
530
+ }
531
+
532
+ # lasting_list <changes.jsonl> <days>: each change, in order, then a summary per repository over
533
+ # its merged changes: the share reverted and the mean follow-up fixes, overall and in each half of
534
+ # the span from its first merge to its last, so a trend shows.
535
+ lasting_list() {
536
+ local file="$1" days="$2" line repo from to label out
537
+ [[ -f "$file" ]] || die "no changes file at $file"
538
+ scratch
539
+ out="$SCRATCH/lasting.jsonl"; : > "$out"
540
+ while IFS= read -r line; do
541
+ [[ -n "${line// /}" ]] || continue
542
+ IFS=$'\t' read -r repo from to label < <(jq -r '[.repo, .from, .to, (.label // "")] | @tsv' <<< "$line" 2>/dev/null) \
543
+ || die "a line of $file is not a change: $line"
544
+ [[ -n "$repo" && -n "$from" && -n "$to" ]] || die "a line of $file names no repo, from or to: $line"
545
+ lasting_json "$repo" "$from" "$to" "$days" "$label" >> "$out" || exit 1
546
+ done < "$file"
547
+ jq -s --argjson days "$days" '
548
+ def r3: . * 1000 | round / 1000;
549
+ def stats: {changes: length,
550
+ reverted_share: (if length > 0 then (map(select(.reverted)) | length) / length | r3 else null end),
551
+ mean_follow_up_fixes: (if length > 0 then (map(.follow_up_fixes) | add) / length | r3 else null end)};
552
+ {report: "ship-lasting/1", days: $days, changes: .,
553
+ repositories: (group_by(.repo) | map(
554
+ map(select(.merged)) as $m | ($m | map(.merged_at | fromdate)) as $t
555
+ | (if $t == [] then null else ($t | min + max) / 2 end) as $mid
556
+ | {repo: .[0].repo, branch: .[0].branch, changes: length, merged: ($m | length)}
557
+ + ($m | stats | del(.changes))
558
+ + {first_half: (if $mid == null then null else
559
+ {from: ($t | min | todate), to: ($mid | floor | todate)} + ($m | map(select((.merged_at | fromdate) <= $mid)) | stats) end),
560
+ second_half: (if $mid == null then null else
561
+ {from: ($mid | floor | todate), to: ($t | max | todate)} + ($m | map(select((.merged_at | fromdate) > $mid)) | stats) end)}))}' "$out"
562
+ }
563
+
564
+ # ---- arguments ----------------------------------------------------------------------------
565
+
566
+ verb="${1:-}"
567
+ [[ $# -eq 0 ]] || shift
568
+ case "$verb" in
569
+ freeze)
570
+ [[ $# -eq 1 ]] || bad_usage "freeze takes one sources file"
571
+ freeze "$1" ;;
572
+ analyze)
573
+ manifest="" prices="" root=""
574
+ while [[ $# -gt 0 ]]; do
575
+ case "$1" in
576
+ --prices|--root)
577
+ [[ $# -ge 2 ]] || bad_usage "$1 takes a path"
578
+ if [[ "$1" == --prices ]]; then prices="$2"; else root="$2"; fi
579
+ shift 2 ;;
580
+ -*) bad_usage "unknown option $1" ;;
581
+ *) [[ -z "$manifest" ]] || bad_usage "analyze takes one manifest"; manifest="$1"; shift ;;
582
+ esac
583
+ done
584
+ [[ -n "$manifest" ]] || bad_usage "analyze takes a manifest"
585
+ analyze "$manifest" "$prices" "$root" ;;
586
+ volume)
587
+ if [[ "${1:-}" == --list ]]; then
588
+ [[ $# -eq 2 ]] || bad_usage "volume --list takes one changes file"
589
+ volume_list "$2"
590
+ else
591
+ [[ $# -eq 3 || ( $# -eq 5 && "$4" == --policy ) ]] || bad_usage "volume takes a repository, two commits and an optional --policy"
592
+ volume_json "$1" "$2" "$3" "${5:-$(default_policy "$1")}" || exit 1
593
+ fi ;;
594
+ lasting)
595
+ list="" days=30
596
+ while [[ $# -gt 0 ]]; do
597
+ case "$1" in
598
+ --list|--days)
599
+ [[ $# -ge 2 ]] || bad_usage "$1 takes a value"
600
+ if [[ "$1" == --list ]]; then list="$2"; else days="$2"; fi
601
+ shift 2 ;;
602
+ *) bad_usage "lasting takes --list <changes.jsonl> and an optional --days <n>" ;;
603
+ esac
604
+ done
605
+ [[ -n "$list" ]] || bad_usage "lasting takes --list <changes.jsonl>"
606
+ [[ "$days" =~ ^[1-9][0-9]*$ ]] || bad_usage "--days takes a whole number of days"
607
+ lasting_list "$list" "$days" ;;
608
+ -h|--help|help)
609
+ if declare -F ui_help > /dev/null; then ! ui_attended || ui_brand measure help; usage | ui_help; else usage; fi ;;
610
+ *) bad_usage ;;
611
+ esac