@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,389 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Read saved shipping evidence into a JSON file of attempts and an HTML dashboard
|
|
3
|
+
with a table of runs you can search.
|
|
4
|
+
|
|
5
|
+
It changes no model, tracker or repository, and reads no network. The transcript
|
|
6
|
+
layer is optional historical evidence: the report keeps it apart from the host's
|
|
7
|
+
totals and prices it only from a price table you give.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
from functools import lru_cache
|
|
15
|
+
from collections import defaultdict
|
|
16
|
+
from datetime import datetime, timezone
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
import sys
|
|
19
|
+
|
|
20
|
+
# archive.py sits beside this file and owns the rule for where evidence lives. Importing it must leave no
|
|
21
|
+
# __pycache__ in the installed skill directory.
|
|
22
|
+
sys.dont_write_bytecode = True
|
|
23
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
24
|
+
import archive # noqa: E402
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def read_json(path):
|
|
28
|
+
try:
|
|
29
|
+
return json.loads(path.read_text())
|
|
30
|
+
except (OSError, ValueError):
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def digest(path):
|
|
35
|
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def seconds(value):
|
|
39
|
+
return value / 1000 if isinstance(value, (float, int)) else None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def known_sum(values):
|
|
43
|
+
values = list(values)
|
|
44
|
+
return sum(values) if all(v is not None for v in values) else None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def models(result):
|
|
48
|
+
return sorted({v.get("canonicalModel", k) for k, v in (result.get("modelUsage") or {}).items()})
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def outcome(body):
|
|
52
|
+
block = body.get("structured_output")
|
|
53
|
+
if isinstance(block, dict) and "outcome" in block:
|
|
54
|
+
return block
|
|
55
|
+
text = body.get("result")
|
|
56
|
+
if isinstance(text, str):
|
|
57
|
+
for fenced in re.findall(r"^```(?:json)?\r?\n(.*?)^```\r?$", text, re.M | re.S):
|
|
58
|
+
try:
|
|
59
|
+
block = json.loads(fenced)
|
|
60
|
+
except ValueError:
|
|
61
|
+
continue
|
|
62
|
+
if isinstance(block, dict) and "outcome" in block:
|
|
63
|
+
return block
|
|
64
|
+
return body
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@lru_cache(maxsize=None)
|
|
68
|
+
def project_for(projects, sid):
|
|
69
|
+
matches = list(projects.glob(f"*/{sid}.jsonl"))
|
|
70
|
+
return matches[0].parent if len(matches) == 1 else None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def timestamp(value):
|
|
74
|
+
try:
|
|
75
|
+
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
|
|
76
|
+
except (ValueError, AttributeError):
|
|
77
|
+
return None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def pass_window(path, body, evidence):
|
|
81
|
+
"""Bound old transcripts by the shift log, never by a file's mutable mtime."""
|
|
82
|
+
log = path.parent / "shift.log"
|
|
83
|
+
if not log.is_file():
|
|
84
|
+
return None, None, None
|
|
85
|
+
evidence[str(log)] = digest(log)
|
|
86
|
+
start = None
|
|
87
|
+
try:
|
|
88
|
+
start = datetime.strptime(path.parent.name, "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc).timestamp()
|
|
89
|
+
except ValueError:
|
|
90
|
+
pass
|
|
91
|
+
number = path.stem.removeprefix("pass-")
|
|
92
|
+
for line in log.read_text().splitlines():
|
|
93
|
+
end = timestamp(line.split(" ")[0])
|
|
94
|
+
if end is None:
|
|
95
|
+
continue
|
|
96
|
+
if f" pass={number} " in line and f" session={body.get('session_id')} " in line:
|
|
97
|
+
effort = re.search(r"\beffort=(\S+)", line)
|
|
98
|
+
return start, end + 1, effort.group(1) if effort else None
|
|
99
|
+
if " outcome=" in line and " session=" in line:
|
|
100
|
+
start = end
|
|
101
|
+
return None, None, None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def transcript(path, role, prices, evidence, window=(None, None)):
|
|
105
|
+
"""Streaming chunks repeat message ids. The last usage for each id is authoritative."""
|
|
106
|
+
if not path.is_file():
|
|
107
|
+
return None
|
|
108
|
+
evidence[str(path)] = digest(path)
|
|
109
|
+
messages = {}
|
|
110
|
+
host_versions = set()
|
|
111
|
+
compacted = False
|
|
112
|
+
for line in path.read_text().splitlines():
|
|
113
|
+
try:
|
|
114
|
+
event = json.loads(line)
|
|
115
|
+
except ValueError:
|
|
116
|
+
continue
|
|
117
|
+
at = timestamp(event.get("timestamp"))
|
|
118
|
+
if window[0] is not None and (at is None or at < window[0]):
|
|
119
|
+
continue
|
|
120
|
+
if window[1] is not None and (at is None or at >= window[1]):
|
|
121
|
+
continue
|
|
122
|
+
if isinstance(event.get("version"), str) and event["version"]:
|
|
123
|
+
host_versions.add(event["version"])
|
|
124
|
+
compacted |= event.get("subtype") == "compact_boundary"
|
|
125
|
+
message = event.get("message") or {}
|
|
126
|
+
if event.get("type") == "assistant" and message.get("id") and message.get("usage"):
|
|
127
|
+
messages[message["id"]] = (message, event)
|
|
128
|
+
if not messages:
|
|
129
|
+
return None
|
|
130
|
+
costs, efforts, model_names, peaks = [], set(), set(), []
|
|
131
|
+
usage = defaultdict(int)
|
|
132
|
+
for message, event in messages.values():
|
|
133
|
+
u = message["usage"]
|
|
134
|
+
model = message.get("model")
|
|
135
|
+
if model:
|
|
136
|
+
model_names.add(model)
|
|
137
|
+
effort = event.get("effort")
|
|
138
|
+
if isinstance(effort, str):
|
|
139
|
+
efforts.add(effort)
|
|
140
|
+
for key in ("input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"):
|
|
141
|
+
usage[key] += u.get(key, 0)
|
|
142
|
+
peaks.append(sum(u.get(k, 0) for k in ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens")))
|
|
143
|
+
price = prices.get("models", {}).get(model)
|
|
144
|
+
cache = u.get("cache_creation") or {}
|
|
145
|
+
w5, w1 = cache.get("ephemeral_5m_input_tokens"), cache.get("ephemeral_1h_input_tokens")
|
|
146
|
+
if price and w5 is not None and w1 is not None and w5 + w1 == u.get("cache_creation_input_tokens", 0):
|
|
147
|
+
costs.append((u.get("input_tokens", 0) * price["input"] + u.get("output_tokens", 0) * price["output"]
|
|
148
|
+
+ u.get("cache_read_input_tokens", 0) * price["cache_read"]
|
|
149
|
+
+ w5 * price["cache_write_5m"] + w1 * price["cache_write_1h"]) / 1_000_000)
|
|
150
|
+
else:
|
|
151
|
+
costs.append(None)
|
|
152
|
+
return {"role": role, "source": str(path), "models": sorted(model_names), "efforts": sorted(efforts),
|
|
153
|
+
"host_versions": sorted(host_versions),
|
|
154
|
+
"requests": len(messages), "usage": dict(usage), "peak_input_tokens": max(peaks),
|
|
155
|
+
"compacted": compacted, "reconstructed_usd": known_sum(costs)}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# The contexts a pass starts to read a brief or a seam rather than to do its work.
|
|
159
|
+
READERS = ("second-reader", "seam-reader")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def pass_figures(roots, cost, criteria):
|
|
163
|
+
"""Turns and mean context over the contexts the pass started to do its work, and cost per criterion.
|
|
164
|
+
|
|
165
|
+
The cost review's analyse.py counted a pass's turns over its forks and repairs and left its
|
|
166
|
+
reviewers out, so these leave out the reviewers and the readers. Each is None when one of the
|
|
167
|
+
working contexts has no transcript figures, or the record has none: version 4 records them.
|
|
168
|
+
"""
|
|
169
|
+
shown = [c.get("transcript") for c in roots if c.get("role") not in READERS]
|
|
170
|
+
turns = mean = None
|
|
171
|
+
if shown and all(isinstance(t, dict) for t in shown):
|
|
172
|
+
turns = sum(t["turns"] for t in shown)
|
|
173
|
+
mean = round(sum(t["turns"] * t["context_mean"] for t in shown) / turns) if turns else None
|
|
174
|
+
per = cost / criteria if isinstance(cost, (int, float)) and isinstance(criteria, int) and criteria > 0 else None
|
|
175
|
+
return turns, mean, per
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def layers_for(result, project, prices, evidence, window=(None, None), root_role="orchestrator"):
|
|
179
|
+
sid = result.get("session_id")
|
|
180
|
+
if not sid or sid == "none" or not project:
|
|
181
|
+
return []
|
|
182
|
+
if not (project / f"{sid}.jsonl").is_file():
|
|
183
|
+
project = project_for(project.parent, sid)
|
|
184
|
+
if project is None:
|
|
185
|
+
return []
|
|
186
|
+
layers = []
|
|
187
|
+
parent = transcript(project / f"{sid}.jsonl", root_role, prices, evidence, window)
|
|
188
|
+
if parent:
|
|
189
|
+
layers.append(parent)
|
|
190
|
+
for path in sorted((project / sid / "subagents").glob("*.jsonl")):
|
|
191
|
+
meta_path = path.with_suffix(".meta.json")
|
|
192
|
+
meta = read_json(meta_path) or {}
|
|
193
|
+
if meta_path.is_file():
|
|
194
|
+
evidence[str(meta_path)] = digest(meta_path)
|
|
195
|
+
description = meta.get("description", "").lower()
|
|
196
|
+
if "standard" in description:
|
|
197
|
+
role = "standards"
|
|
198
|
+
elif "spec" in description:
|
|
199
|
+
role = "spec"
|
|
200
|
+
elif meta.get("spawnDepth") == 1 and not description:
|
|
201
|
+
role = "build"
|
|
202
|
+
else:
|
|
203
|
+
role = "other"
|
|
204
|
+
layer = transcript(path, role, prices, evidence, window)
|
|
205
|
+
if layer:
|
|
206
|
+
layers.append(layer)
|
|
207
|
+
total = known_sum(x["reconstructed_usd"] for x in layers)
|
|
208
|
+
for layer in layers:
|
|
209
|
+
layer["observed_cost_share_pct"] = 100 * layer["reconstructed_usd"] / total if total else None
|
|
210
|
+
return layers
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def attempt_row(path, body, repo, snapshot, projects, prices, evidence):
|
|
214
|
+
record = body.get("schema") in archive.RECORD_SCHEMAS
|
|
215
|
+
out = body if record else outcome(body)
|
|
216
|
+
loop = body.get("ship_loop") or {}
|
|
217
|
+
pr = out.get("pr")
|
|
218
|
+
contexts = body.get("contexts", []) if record else []
|
|
219
|
+
# A top-level host total includes its reviewers. Do not add their costs again.
|
|
220
|
+
roots = [c for c in contexts if c.get("parent") is None]
|
|
221
|
+
cost = known_sum(c.get("cost_usd") for c in roots) if record else body.get("total_cost_usd", body.get("cost_usd"))
|
|
222
|
+
project = projects / re.sub(r"[^a-zA-Z0-9-]", "-", str(repo)) if projects else None
|
|
223
|
+
start, end, logged_effort = pass_window(path, body, evidence) if not record else (None, None, None)
|
|
224
|
+
layers = layers_for(body, project, prices, evidence, (start, end)) if not record else []
|
|
225
|
+
# Host totals stay separate from exclusive transcript usage, including for script builds.
|
|
226
|
+
host_contexts = []
|
|
227
|
+
if record:
|
|
228
|
+
for ctx in roots:
|
|
229
|
+
host_contexts.append({"role": ctx.get("role"), "models": ctx.get("model_observed"), "transcript": ctx.get("transcript"),
|
|
230
|
+
"effort": ctx.get("effort"),
|
|
231
|
+
"host_total_usd_including_children": ctx.get("cost_usd"),
|
|
232
|
+
"api_seconds": ctx.get("api_seconds"), "wall_seconds": ctx.get("seconds"),
|
|
233
|
+
"observed_cost_share_pct": None})
|
|
234
|
+
result_path = path.parent.parent / ctx.get("result", "missing")
|
|
235
|
+
result = read_json(result_path)
|
|
236
|
+
if result and project:
|
|
237
|
+
evidence[str(result_path)] = digest(result_path)
|
|
238
|
+
layers.extend(layers_for(result, project, prices, evidence,
|
|
239
|
+
(timestamp(ctx.get("started_at")), (timestamp(ctx.get("ended_at")) + 1) if timestamp(ctx.get("ended_at")) is not None else None), ctx.get("role")))
|
|
240
|
+
total = known_sum(layer.get("reconstructed_usd") for layer in layers)
|
|
241
|
+
for layer in layers:
|
|
242
|
+
layer["observed_cost_share_pct"] = 100 * layer["reconstructed_usd"] / total if total else None
|
|
243
|
+
changes = body.get("changes") or {}
|
|
244
|
+
pr_info = snapshot.get("prs", {}).get(pr, {})
|
|
245
|
+
diff = changes.get("total")
|
|
246
|
+
diff_scope = "recorded committed diff" if diff else None
|
|
247
|
+
if diff is None and pr_info:
|
|
248
|
+
diff = {"additions": pr_info.get("additions"), "deletions": pr_info.get("deletions"),
|
|
249
|
+
"files": pr_info.get("changedFiles"), "from": pr_info.get("baseRefOid"),
|
|
250
|
+
"to": pr_info.get("headRefOid")}
|
|
251
|
+
diff_scope = "PR snapshot, not attempt-attributed"
|
|
252
|
+
observed_models = body.get("model", {}).get("observed") if record else models(body)
|
|
253
|
+
efforts = sorted({e for layer in layers for e in layer.get("efforts", [])})
|
|
254
|
+
usage_by_model = body.get("modelUsage") or {}
|
|
255
|
+
# modelUsage covers the whole Claude run; .usage can cover only the orchestrator.
|
|
256
|
+
tokens = sum(sum(v.get(k, 0) for k in ("inputTokens", "outputTokens", "cacheReadInputTokens", "cacheCreationInputTokens"))
|
|
257
|
+
for v in usage_by_model.values()) if usage_by_model else None
|
|
258
|
+
waits = body.get("waits") or {}
|
|
259
|
+
run_id = body.get("attempt_id") if record else f"{path.parent.name}/{path.stem}"
|
|
260
|
+
recorded_version = body.get("host_version")
|
|
261
|
+
host_versions = {v for layer in layers for v in layer["host_versions"]}
|
|
262
|
+
if isinstance(recorded_version, str) and recorded_version:
|
|
263
|
+
host_versions.add(recorded_version)
|
|
264
|
+
revisions = body.get("revisions") or {}
|
|
265
|
+
# Identify the saved component manifest, not today's installation or a guessed release.
|
|
266
|
+
shipping_fingerprint = hashlib.sha256(json.dumps(revisions, sort_keys=True, separators=(",", ":")).encode()).hexdigest() if any(revisions.values()) else None
|
|
267
|
+
begun = timestamp(body.get("started_at")) if record else start
|
|
268
|
+
turns, context_mean, per_criterion = pass_figures(roots, cost, body.get("criteria")) if record else (body.get("num_turns"), None, None)
|
|
269
|
+
row = {"run": f"{repo.name}/{run_id or path.parents[2].name}", "repository": body.get("repository") or repo.name,
|
|
270
|
+
"started_at": datetime.fromtimestamp(begun, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if begun is not None else None,
|
|
271
|
+
"source": str(path), "source_sha256": digest(path), "attempt_id": body.get("attempt_id"),
|
|
272
|
+
"session_id": body.get("session_id"), "issue": str(loop.get("issue") or out.get("issue") or "unknown"),
|
|
273
|
+
"pr": pr if pr and pr != "none" else None, "outcome": loop.get("state") or out.get("outcome") or "unknown",
|
|
274
|
+
"engine": "script" if record or isinstance(body.get("outcome"), str) else body.get("engine", "ship-it"), "host": body.get("host", "claude"),
|
|
275
|
+
"host_versions": sorted(host_versions), "recorded_host_version": recorded_version,
|
|
276
|
+
"shipping_revisions": revisions, "shipping_fingerprint": shipping_fingerprint,
|
|
277
|
+
"models": observed_models or sorted({m for layer in layers for m in layer.get("models", []) or []}),
|
|
278
|
+
"effort": body.get("effort") or logged_effort or (", ".join(efforts) if efforts else None),
|
|
279
|
+
"reported_usd": cost, "wall_seconds": body.get("elapsed_seconds") if record else seconds(body.get("duration_ms")),
|
|
280
|
+
"api_seconds": known_sum(c.get("api_seconds") for c in roots) if record else seconds(body.get("duration_api_ms")),
|
|
281
|
+
"ci_wait_seconds": waits.get("ci_seconds"), "gate_queue_seconds": waits.get("receipt_queue_seconds"),
|
|
282
|
+
"turns": turns, "context_mean": context_mean, "usd_per_criterion": per_criterion,
|
|
283
|
+
"criteria": body.get("criteria") if record else None, "rereads": body.get("rereads") if record else None,
|
|
284
|
+
"total_tokens": tokens,
|
|
285
|
+
"subagents": (body.get("subagent_stats") or {}).get("spawned"),
|
|
286
|
+
"changes": diff, "change_scope": diff_scope, "attempt_changes": changes.get("attempt"),
|
|
287
|
+
"uncommitted": changes.get("uncommitted"), "pr_snapshot_state": pr_info.get("state"),
|
|
288
|
+
"pr_snapshot_at": snapshot.get("captured_at") if pr_info else None,
|
|
289
|
+
"layers": layers, "host_contexts": host_contexts, "forks": body.get("forks"), "repairs": body.get("repairs"),
|
|
290
|
+
"reconciliations": body.get("reconciliations"),
|
|
291
|
+
"layer_basis": "observed transcript subset, reconstructed at supplied prices" if layers else "unavailable",
|
|
292
|
+
"transcript_window": {"start_epoch": start, "end_epoch_exclusive": end},
|
|
293
|
+
"warnings": []}
|
|
294
|
+
if row["wall_seconds"] is not None and row["api_seconds"] is not None and row["api_seconds"] > row["wall_seconds"]:
|
|
295
|
+
row["warnings"].append("Host API time exceeds wall time; preserved as reported, not subtracted to infer waiting.")
|
|
296
|
+
if layers:
|
|
297
|
+
row["warnings"].append("Layer shares cover surviving transcripts only; they are not shares of the reported pass cost.")
|
|
298
|
+
if not record and end is None:
|
|
299
|
+
row["warnings"].append("No shift-log time boundary: transcript metrics cover the saved session, which may include later work.")
|
|
300
|
+
return row
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def evidence_paths(repo):
|
|
304
|
+
"""The saved pass results under every shift directory, and the pass records under every ledger.
|
|
305
|
+
|
|
306
|
+
Which directories those are, under the names before and after the rename, is archive.py's rule, so the report and
|
|
307
|
+
the keep read the same passes.
|
|
308
|
+
"""
|
|
309
|
+
retained, shipped = archive.ledger_dirs(repo)
|
|
310
|
+
records = [path for ship in retained + shipped if not ship.is_symlink() for path in sorted(ship.glob("logs/record*.json"))]
|
|
311
|
+
return archive.shift_passes(repo), records
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def collect(repos, snapshot, projects, prices):
|
|
315
|
+
rows, exclusions, evidence, seen = [], [], {}, set()
|
|
316
|
+
for repo in repos:
|
|
317
|
+
passes, records = evidence_paths(repo)
|
|
318
|
+
passes = [p for p in passes if re.fullmatch(r"pass-\d+\.json", p.name)]
|
|
319
|
+
record_bodies = {p: read_json(p) for p in records}
|
|
320
|
+
covered = {d.get("attempt_id") for d in record_bodies.values() if isinstance(d, dict) and d.get("attempt_id")}
|
|
321
|
+
for path in sorted(set(passes + records)):
|
|
322
|
+
body = record_bodies.get(path) if path in record_bodies else read_json(path)
|
|
323
|
+
if not isinstance(body, dict):
|
|
324
|
+
exclusions.append({"source": str(path), "reason": "empty, unreadable or invalid JSON"})
|
|
325
|
+
continue
|
|
326
|
+
record = body.get("schema") in archive.RECORD_SCHEMAS
|
|
327
|
+
if not record and body.get("attempt_id") in covered:
|
|
328
|
+
exclusions.append({"source": str(path), "reason": "covered by pass record"})
|
|
329
|
+
continue
|
|
330
|
+
key = (str(repo), body.get("attempt_id") or digest(path))
|
|
331
|
+
if key in seen:
|
|
332
|
+
exclusions.append({"source": str(path), "reason": "duplicate attempt or bytes"})
|
|
333
|
+
continue
|
|
334
|
+
seen.add(key)
|
|
335
|
+
evidence[str(path)] = digest(path)
|
|
336
|
+
rows.append(attempt_row(path, body, repo, snapshot, projects, prices, evidence))
|
|
337
|
+
return {"schema": "ship-run-table/1", "runs": rows, "excluded": exclusions, "evidence_sha256": evidence,
|
|
338
|
+
"prices": prices or None, "notes": [
|
|
339
|
+
"Reported USD is a host API-equivalent figure, not an invoice or subscription charge.",
|
|
340
|
+
"Wall and API seconds are independent host measurements. Parallel contexts can overlap.",
|
|
341
|
+
"Added/deleted lines include tracked source, tests, docs and configuration. Binary lines are excluded from recorded diffs.",
|
|
342
|
+
"PR snapshots can include later changes or other attempts. Do not sum repeated PR diffs as delivered output.",
|
|
343
|
+
"Attempt changes compare the committed start and end of that attempt. They exclude uncommitted edits.",
|
|
344
|
+
"Layer percentages use only surviving priced transcript contexts, not the reported cost denominator.",
|
|
345
|
+
"Rows are saved pass results and script records. Separate rate-limit retry artifacts are not included.",
|
|
346
|
+
"Tool versions come from saved host records or in-window transcripts. Shipping fingerprints identify recorded component hashes, not a release number; missing components remain unknown.",
|
|
347
|
+
"Unknown values stay null. Line count is a change-size measure, not a quality or productivity score."]}
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
TEMPLATE = Path(__file__).with_name("report-template.html")
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def render(report):
|
|
354
|
+
# Embed JSON as inert text and escape script delimiters. The page builds every node with text.
|
|
355
|
+
data = json.dumps(report).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
|
|
356
|
+
return TEMPLATE.read_text().replace("__REPORT_JSON__", data, 1)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def main():
|
|
360
|
+
parser = (archive.UI.KrysoParser if archive.UI else argparse.ArgumentParser)(prog="kryso report", description=__doc__)
|
|
361
|
+
parser.add_argument("--repo", action="append", type=Path, required=True, help="a repository root (repeat it for more)")
|
|
362
|
+
parser.add_argument("--output", type=Path, required=True, help="the directory for report.json and report.html")
|
|
363
|
+
parser.add_argument("--pr-snapshot", type=Path, help="a saved file of {captured_at, prs: {URL: GitHub PR fields}}")
|
|
364
|
+
parser.add_argument("--claude-projects", type=Path, help="add the transcript layer from this Claude projects directory")
|
|
365
|
+
parser.add_argument("--prices", type=Path, help="a historical price table, in measure.sh's units")
|
|
366
|
+
args = parser.parse_args()
|
|
367
|
+
for path in (args.pr_snapshot, args.prices):
|
|
368
|
+
if path and not isinstance(read_json(path), dict):
|
|
369
|
+
parser.error(f"cannot read a JSON object from {path}")
|
|
370
|
+
report = collect([r.resolve() for r in args.repo], read_json(args.pr_snapshot) if args.pr_snapshot else {},
|
|
371
|
+
args.claude_projects, read_json(args.prices) if args.prices else {})
|
|
372
|
+
for path in (args.pr_snapshot, args.prices):
|
|
373
|
+
if path:
|
|
374
|
+
report["evidence_sha256"][str(path.resolve())] = digest(path)
|
|
375
|
+
args.output.mkdir(parents=True, exist_ok=True)
|
|
376
|
+
(args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
|
|
377
|
+
(args.output / "report.html").write_text(render(report))
|
|
378
|
+
# A person on a terminal gets the brand line with the counts and the two files as ok lines.
|
|
379
|
+
style = archive.UI.styled() if archive.UI else None
|
|
380
|
+
if style:
|
|
381
|
+
style.brand("report", f"{len(report['runs'])} runs, {len(report['excluded'])} excluded")
|
|
382
|
+
style.ok(f"dashboard at {style.val(str(args.output / 'report.html'))}")
|
|
383
|
+
style.ok(f"data at {style.val(str(args.output / 'report.json'))}")
|
|
384
|
+
else:
|
|
385
|
+
print(f"{len(report['runs'])} runs, {len(report['excluded'])} excluded: {args.output / 'report.html'}")
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
if __name__ == "__main__":
|
|
389
|
+
main()
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""The synthetic history the report CLI is tested on, shared by test-report.sh and test-archive.sh.
|
|
2
|
+
|
|
3
|
+
Imported, never run. A suite that imports it sets sys.dont_write_bytecode first, because the import
|
|
4
|
+
would otherwise leave a __pycache__ in the skill directory. Every call builds fresh objects, so a
|
|
5
|
+
suite that edits the baseline or the record it was handed changes nothing a later call returns.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
SHIFT = ".claude/ship-loop/20260929T010000Z"
|
|
12
|
+
RECORD = ".claude/worktrees/w/.ship-it/logs/record.json"
|
|
13
|
+
SHIPPED_RECORD = ".claude/ship-loop/shipped/w/.ship-it/logs/record.json"
|
|
14
|
+
PR = "https://github.com/o/r/pull/9"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def write(path, obj):
|
|
18
|
+
"""Write obj to path as JSON, making the directories above it."""
|
|
19
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
20
|
+
path.write_text(json.dumps(obj))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def baseline():
|
|
24
|
+
"""A host result for issue 7 with no pass record, its outcome in structured_output."""
|
|
25
|
+
return {"type": "result", "session_id": "s1", "duration_ms": 120000,
|
|
26
|
+
"duration_api_ms": 90000, "total_cost_usd": 4, "effort": "high",
|
|
27
|
+
"structured_output": {"issue": "7", "outcome": "parked", "pr": PR},
|
|
28
|
+
"modelUsage": {"alias": {"canonicalModel": "model-a", "inputTokens": 10, "outputTokens": 20}}}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def record():
|
|
32
|
+
"""The pass record of attempt-a on issue 8, a build context with a review context below it."""
|
|
33
|
+
return {"schema": "ship-pass-record/1", "attempt_id": "attempt-a", "issue": "8",
|
|
34
|
+
"outcome": "parked", "host": "codex", "elapsed_seconds": 30, "effort": "medium",
|
|
35
|
+
"host_version": "codex-cli 1.2.3", "revisions": {"kryso-shift/ship-pass.sh": "a" * 64, "code-review/SKILL.md": None},
|
|
36
|
+
"model": {"observed": ["model-b"]}, "changes": {"total": {"additions": 9, "deletions": 2},
|
|
37
|
+
"attempt": {"additions": 0, "deletions": 0}, "uncommitted": False},
|
|
38
|
+
"contexts": [{"id": "build", "parent": None, "role": "build", "cost_usd": 3, "api_seconds": 15},
|
|
39
|
+
{"id": "review", "parent": "build", "role": "spec", "cost_usd": 1}]}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def pr_snapshot():
|
|
43
|
+
"""The pull request snapshot that gives issue 7's pull request its size."""
|
|
44
|
+
return {"captured_at": "2026-09-29", "prs": {PR: {"additions": 20, "deletions": 12, "changedFiles": 3}}}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def write_history(repo):
|
|
48
|
+
"""Write the history under repo and return what the suites assert on.
|
|
49
|
+
|
|
50
|
+
The shift holds issue 7's result, a host sidecar that is not another pass, an empty pass file
|
|
51
|
+
and attempt-a's outcome. Attempt-a's record sits in its worktree and again in the shipped
|
|
52
|
+
copy. The return holds the shift directory and the baseline and the record as written: one
|
|
53
|
+
baseline object went to both pass-1.json and its sidecar, and editing it changes neither file.
|
|
54
|
+
"""
|
|
55
|
+
repo = Path(repo)
|
|
56
|
+
shift = repo / SHIFT
|
|
57
|
+
shift.mkdir(parents=True)
|
|
58
|
+
written = {"baseline": baseline(), "record": record(), "shift": shift}
|
|
59
|
+
write(shift / "pass-1.json", written["baseline"])
|
|
60
|
+
write(shift / "pass-1.final.json", written["baseline"])
|
|
61
|
+
(shift / "pass-2.json").write_text("")
|
|
62
|
+
write(shift / "pass-3.json", {"attempt_id": written["record"]["attempt_id"], "outcome": "parked"})
|
|
63
|
+
write(repo / RECORD, written["record"])
|
|
64
|
+
write(repo / SHIPPED_RECORD, written["record"])
|
|
65
|
+
return written
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Per-run reporting
|
|
2
|
+
|
|
3
|
+
Use `report.py` to inspect change size beside cost, elapsed and API time, model, effort and layer shares. It reads saved evidence and writes `report.html` with a `report.json` beside it. The page opens on headline figures and charts for cost by repository, layer shares, model and tool version, and cost against change size. One filter row scopes all of them and the sortable run table below. Each chart has a table view, and each run opens inline to show its layers, provenance and raw record. The page layout lives in `report-template.html`, next to the script. Python 3.10 or newer is required. It makes no model or tracker calls and changes no repository state.
|
|
4
|
+
|
|
5
|
+
From the repository whose runs you want to inspect:
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
python3 ~/.agents/skills/kryso-shift/report.py \
|
|
9
|
+
--repo "$PWD" --output "$PWD/.claude/kryso/report"
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Repeat `--repo` to compare repositories. Run the command after a shift to refresh the table. In the playbook checkout the script is `skills/kryso-shift/report.py`. The reporter is optional and does not run inside a pass. Its work consumes no model tokens.
|
|
13
|
+
|
|
14
|
+
The table includes valid `pass-N.json` files and script-engine records in retained worktrees or the shipped archive. A record replaces the outcome block for the same attempt. Duplicate records are counted once. Empty or unreadable files appear in the exclusions. Separate rate-limit retry artifacts are outside this table's scope. Use `measure.sh` and an explicit frozen source manifest for a cohort analysis that includes those artifacts.
|
|
15
|
+
|
|
16
|
+
A pass's evidence kept with [the archive command](archiving.md) can be restored into any empty directory, and this report runs over the restored repository directory the same way.
|
|
17
|
+
|
|
18
|
+
## Turns, context and cost per criterion
|
|
19
|
+
|
|
20
|
+
A version 4 pass record gives each run three more columns. Turns and mean context are over the contexts the pass started to do its work, its forks, reconciliation contexts and workflow stages. They leave out its reviewers, as the cost review did, and its second reader and seam reader, and the mean is weighted by each context's turns. Cost per criterion is the reported cost over the acceptance criteria in the pass's brief. A run's detail shows each context's turns, mean and peak context, and the five tool results the pass re-read most. A record from before version 4 shows the three columns empty, because it never measured them, and a context without a transcript leaves its pass's turns and mean context empty too.
|
|
21
|
+
|
|
22
|
+
## Change counts
|
|
23
|
+
|
|
24
|
+
New script-engine records capture two committed diffs. `changes.total` compares the pinned base's merge-base with the final HEAD. `changes.attempt` compares HEAD at the beginning of this attempt, after any resume fast-forward, with its final HEAD. A continuation that only checks CI therefore has zero attempt additions and deletions, while its total diff stays intact. Each comparison records both commit IDs, added and deleted lines, changed files, binary-file count and commit count. Renames are detected. Tests, documentation and configuration count as tracked text. Uncommitted changes are flagged and excluded from the counts.
|
|
25
|
+
|
|
26
|
+
Older runs can be joined to a saved GitHub PR snapshot with `--pr-snapshot snapshot.json`:
|
|
27
|
+
|
|
28
|
+
```json
|
|
29
|
+
{
|
|
30
|
+
"captured_at": "2026-09-29T12:00:00Z",
|
|
31
|
+
"prs": {
|
|
32
|
+
"https://github.com/owner/repo/pull/42": {
|
|
33
|
+
"additions": 120,
|
|
34
|
+
"deletions": 35,
|
|
35
|
+
"changedFiles": 4,
|
|
36
|
+
"baseRefOid": "base-commit",
|
|
37
|
+
"headRefOid": "head-commit",
|
|
38
|
+
"state": "MERGED"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
This is a snapshot of the PR when it was read, which may include later work. The table labels it as such and leaves the attempt counts unknown. Several runs may refer to the same PR. Summing their repeated PR diffs would overstate the amount of work. Line counts describe change size and do not measure quality.
|
|
45
|
+
|
|
46
|
+
## Cost and layer shares
|
|
47
|
+
|
|
48
|
+
The tool and version columns identify the host CLI, using the saved record's `host_version` and versions observed in the selected transcript window. Multiple observed versions stay visible, including in each layer's detail. Missing evidence stays unknown; the reporter never substitutes the currently installed version. Shipping fingerprints separately identify the recorded component-hash manifest, with full hashes in the JSON. They are not release numbers and only cover the components recorded by that run. Historical runs without that manifest cannot be assigned a shipping revision.
|
|
49
|
+
|
|
50
|
+
Reported dollars are the host's figure, which [measuring.md](reference/measuring.md#the-report) explains. An unavailable cost stays unknown. Top-level host totals can include reviewers, so the reporter keeps those inclusive totals separate from each agent's own transcript usage.
|
|
51
|
+
|
|
52
|
+
To inspect historical Claude layers, add `--claude-projects ~/.claude/projects`. This opt-in reads the saved session and sub-agent transcripts, de-duplicates streaming chunks by message ID, and records observed model names, effort, request count, token usage, peak input context and compaction. The shift log bounds a historical pass's transcript window. Without that boundary, the row warns that later session work may be included. Script records use their context timestamps. Missing transcripts remain missing.
|
|
53
|
+
|
|
54
|
+
Add `--prices prices.json` to reconstruct layer cost from those tokens. The price table is the one [measuring.md](reference/measuring.md#the-report) describes, keyed by each exact model ID in `models`. Keep its source and observation date with it. Unlisted models and unsplit cache writes remain unpriced. The layer percentage denominator is the sum of reconstructed costs for the observed contexts, not the host's pass total. The report retains both figures and the price assumptions. This is a partial evidence view when transcripts have gone.
|
|
55
|
+
|
|
56
|
+
Wall time and API time are separate host measurements. Concurrent contexts can overlap, and API time sometimes exceeds the reported wall time. The reporter preserves both and flags that case instead of deriving waiting time by subtraction. Script records provide CI and gate-queue waiting times separately.
|
|
57
|
+
|
|
58
|
+
The JSON contains the source paths and SHA-256 hashes, including any PR snapshot and price table supplied. Preserve that JSON with the HTML when sharing a report. The artifact contains aggregate metrics and local evidence paths, without prompts, message bodies or credentials.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# result.sh: readers for the common result envelope written by runner.sh, and the writer of
|
|
3
|
+
# the script engine's outcome block, in a file of their own so every script that reads one
|
|
4
|
+
# reads it the same way and every script that leaves a block leaves the same shape. Sourced,
|
|
5
|
+
# never run: it defines functions and nothing else, so the shell that sources it sees no
|
|
6
|
+
# output, no exit and no changed options. Each reader takes the result file first and answers
|
|
7
|
+
# on stdout, with status 0 whether or not it has an answer, so a `set -e` caller can assign
|
|
8
|
+
# it. A missing or unparseable file reads as the fallback where the function takes one, and
|
|
9
|
+
# as nothing where it does not. The public surface is result_field, result_outcome,
|
|
10
|
+
# result_outcome_field, result_reset, result_limit and result_block; a name with a leading
|
|
11
|
+
# underscore is the library's own. Needs jq on PATH.
|
|
12
|
+
|
|
13
|
+
# result_field <file> <jq path> <fallback>: one value out of the result, the fallback when
|
|
14
|
+
# the file is missing, unparseable, or has no such field. Tests for null rather than using
|
|
15
|
+
# jq's //, which would swap a real false or 0 for the fallback too.
|
|
16
|
+
result_field() {
|
|
17
|
+
jq -r --arg d "$3" "($2) as \$v | if \$v == null then \$d else \$v end" "$1" 2>/dev/null || echo "$3"
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
# result_outcome <file>: the run's outcome block as one line of JSON, or nothing. It is the
|
|
21
|
+
# structured output when the run filled it. Seen on 2.1.268: a run ends with subtype success
|
|
22
|
+
# and structured_output null, the model having written the block into its text instead of
|
|
23
|
+
# the tool, so the fallback is the first fenced JSON object in the result text that carries
|
|
24
|
+
# an outcome. Every field of the block is read from what this prints, so a field added to
|
|
25
|
+
# the schema is read in one place.
|
|
26
|
+
result_outcome() {
|
|
27
|
+
local block
|
|
28
|
+
block="$(jq -c '.structured_output | select(type == "object" and has("outcome"))' "$1" 2>/dev/null)"
|
|
29
|
+
if [[ -z "$block" ]]; then
|
|
30
|
+
block="$(jq -r '.result // ""' "$1" 2>/dev/null | tr -d '\r' \
|
|
31
|
+
| awk '/^```(json)?$/{f=!f; next} f' | jq -c 'select(type == "object" and has("outcome"))' 2>/dev/null | head -1)"
|
|
32
|
+
fi
|
|
33
|
+
printf '%s' "$block"
|
|
34
|
+
return 0
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
# result_outcome_field <file> <name> [fallback]: one field of the outcome block, the fallback
|
|
38
|
+
# ("none" by default) where the run wrote no block or the block has no such field.
|
|
39
|
+
result_outcome_field() {
|
|
40
|
+
local block fallback="${3-none}"
|
|
41
|
+
block="$(result_outcome "$1")"
|
|
42
|
+
jq -r --arg k "$2" --arg d "$fallback" '.[$k] // $d' <<< "${block:-null}" 2>/dev/null || echo "$fallback"
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
# _result_error_text <file>: the text an error arrives in, the result message and the API
|
|
46
|
+
# status together, which is what result_reset and result_limit search.
|
|
47
|
+
_result_error_text() {
|
|
48
|
+
jq -r '[.result // "", .api_error_status // ""] | join(" ")' "$1" 2>/dev/null || echo ""
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
# result_reset <file>: the reset, when the result names one: a resetsAt field anywhere in the
|
|
52
|
+
# JSON, or the |<epoch> suffix on the usage-limit message. First match wins, and the epoch
|
|
53
|
+
# comes back as written, so the caller decides what to do with milliseconds.
|
|
54
|
+
result_reset() {
|
|
55
|
+
{ jq -r '.. | objects | (.resetsAt // .resets_at // empty)' "$1" 2>/dev/null
|
|
56
|
+
grep -oE '\|[0-9]{10,13}' <<< "$(_result_error_text "$1")" | tr -d '|'; } | grep -E '^[0-9]+$' | head -1
|
|
57
|
+
return 0
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
# result_limit <file> <host exit>: the limit the run hit, when it hit one. A budget stop
|
|
61
|
+
# and a rate limit both arrive as errors, and neither is the run's fault, so a caller reads
|
|
62
|
+
# this before counting a result as a failure. Prints budget-stop, rate-limited, or nothing.
|
|
63
|
+
result_limit() {
|
|
64
|
+
local file="$1" host_exit="$2"
|
|
65
|
+
if [[ "$(result_field "$file" .subtype none)" == "error_max_budget_usd" ]]; then
|
|
66
|
+
echo budget-stop
|
|
67
|
+
elif [[ "$(result_field "$file" .is_error true)" == "true" || "$host_exit" -ne 0 ]] \
|
|
68
|
+
&& grep -qiE 'usage limit reached|rate.?limit|\b429\b' <<< "$(_result_error_text "$file")"; then
|
|
69
|
+
echo rate-limited
|
|
70
|
+
fi
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
# result_block <outcome> <issue> <branch> <pr> <reason> [fields-json]: the script engine's
|
|
74
|
+
# outcome block on stdout, the one shape ship-pass.sh's finish and the driver's result for a
|
|
75
|
+
# pass that wrote none both leave. The keys come in the block's order, each one the fields do
|
|
76
|
+
# not give left as nothing known: null for the costs and the usage, none for the names. The
|
|
77
|
+
# cost goes in both cost fields. A field the five keys and the names do not cover, such as
|
|
78
|
+
# attempt_id, deadline or closeout, follows the record, except a null deadline and an empty
|
|
79
|
+
# closeout, which are left out. Fields given but empty, as a failed jq in the caller leaves
|
|
80
|
+
# them, are an error and write no block, so a lost cost or deadline is not passed off as none.
|
|
81
|
+
result_block() {
|
|
82
|
+
local fields='{}'
|
|
83
|
+
(( $# < 6 )) || fields="$6"
|
|
84
|
+
jq -n --arg o "$1" --arg i "$2" --arg b "$3" --arg p "$4" --arg r "$5" --argjson f "$fields" '
|
|
85
|
+
{outcome: $o, issue: $i, branch: $b, pr: $p, reason: $r, cost: null, cost_usd: null, profile: "none", host: "none",
|
|
86
|
+
billing: "none", effort: "none", usage: null, session: "none", result: "none", record: "none"}
|
|
87
|
+
+ ($f | del(.cost_usd))
|
|
88
|
+
| .cost_usd = .cost
|
|
89
|
+
| if .deadline == null then del(.deadline) else . end
|
|
90
|
+
| if (.closeout // "") == "" then del(.closeout) else . end'
|
|
91
|
+
}
|