count_shale_stops

Roc

cookbook/count_shale_stops/count_shale_stops.roc, 319 lines

## count_shale_stops, in Roc on Shale's platform (roc_platform/README.md):
## how an agent's Shale launches went, from a Claude Code transcript. Each
## Bash call's command is paired with the answer it got by the call's id. A
## launch is a heredoc (`shale <<'TAG'`) or a script (`shale path.shale`),
## and each ends one of four ways: it ran, Shale stopped it (`── stopped
## at`), the gate refused the call before Shale saw it, or the harness
## denied it. A stop by the script's own `fail` is a check's verdict,
## counted apart; Shale's other stops are grouped by kind and by message,
## quoted values blanked, so one mistake made twice counts as one line. The
## calls the heredocs make and the programs they `run` are counted too.
##
## Its launcher, cookbook/count_shale_stops.shale, is how it is run, and
## names the newest transcript when no `transcript=` is given:
##
##   shale cookbook:count_shale_stops.shale since=2026-11-14T19:50
##
## The arguments: `transcript` (a Shale path), `since` (an ISO time; only
## the lines from then on count) and `most` (how many lines each list
## shows, 20).
##
## The effects: `Shale.arg!` for the arguments, `Shale.grep_all!` for the
## transcript's lines that can hold a call or an answer (any size of file),
## `Shale.re_match!`, `Shale.re_find!`, `Shale.re_find_all!` and
## `Shale.re_replace!` for the Shale original's own patterns, and
## `Shale.print!` and `Shale.fail!` for the report. ShaleJson, beside this,
## reads a line as Shale's json_read does, its strings by JsonString;
## Transcript reads the fields; Tally counts and prints the tables.
## budget: steps=900000000 reads=50000 read_bytes=3000000000 arena_bytes=3000000000 roc_cpu_ms=60000
app [main!] { pf: platform "../../roc_platform/platform/main.roc" }

import pf.Shale
import ShaleJson
import Tally
import Transcript

## A launch's kind, and how the report names it.
Launch : [Heredoc, Script]

## A part of a message, and the transcript line it is on.
Part : { part : ShaleJson, line_number : U64 }

## What the run was asked: the transcript, from when, and how many lines
## each list shows.
Asked : {
	path : Str,
	since : Str,
	most : I64,
}

## What the run has counted so far.
Counts : {
	calls : Dict(Str, Launch),
	heredocs : U64,
	scripts : U64,
	ends : Dict(Str, U64),
	stop_kinds : Dict(Str, U64),
	stop_lines : Dict(Str, U64),
	builtins : Dict(Str, U64),
	programs : Dict(Str, U64),
}

main! : {} => {}
main! = |{}| {
	path = Shale.arg!("transcript", "")
	if path == "" {
		launcher = "the launcher names the newest under projects:"
		Shale.fail!("count_shale_stops: no transcript= given (${launcher})")
	}
	since = Shale.arg!("since", "")
	most = read_most!({})
	counts = count_transcript!(path, since)
	print_report!(counts, { path, since, most })
}

## The `most=` count: 20 unless given, and any integer.
read_most! : {} => I64
read_most! = |{}| {
	given = Shale.arg!("most", "20")
	match I64.from_str(given) {
		Ok(most) => most
		Err(_) => {
			Shale.fail!("count_shale_stops: most=${given} is not an integer")
			0
		}
	}
}

# ── The count

## Every line that can hold a Bash call or an answer, read in order. A
## line holding neither literal is never read as JSON, as the Shale
## original read none.
count_transcript! : Str, Str => Counts
count_transcript! = |path, since| {
	var $counts = {
		calls: Dict.empty(),
		heredocs: 0,
		scripts: 0,
		ends: Tally.empty,
		stop_kinds: Tally.empty,
		stop_lines: Tally.empty,
		builtins: Tally.empty,
		programs: Tally.empty,
	}
	for hit in Shale.grep_all!(path, "\"tool_") {
		line = hit.text
		is_call = line.contains("\"tool_use\"") and line.contains("\"Bash\"")
		is_answer = line.contains("\"tool_result\"")
		if is_call or is_answer {
			value = get_or_stop!(ShaleJson.read(line), hit.line)
			parts = get_or_stop!(Transcript.recent_parts(value, since), hit.line)
			for part in parts {
				$counts = count_part!($counts, { part, line_number: hit.line })
			}
		}
	}
	$counts
}

## One part of a message counted: a launch and what its heredoc calls, or
## the answer to a launch and how it ended.
count_part! : Counts, Part => Counts
count_part! = |counts, { part, line_number }|
	match get_or_stop!(Transcript.part_kind(part), line_number) {
		ShellCall(command) =>
			match find_launch_kind!(command) {
				Ok(launch) => {
					id = get_or_stop!(Transcript.call_id(part), line_number)
					counted = { ..counts, calls: counts.calls.insert(id, launch) }
					match launch {
						Heredoc => {
							with_heredoc = { ..counted, heredocs: counted.heredocs + 1 }
							count_heredoc!(with_heredoc, command)
						}
						Script => { ..counted, scripts: counted.scripts + 1 }
					}
				}
				Err(NoLaunch) => counts
			}
		Answer(id) =>
			match counts.calls.get(id) {
				Ok(launch) => count_end!(counts, { launch, part, line_number })
				Err(_) => counts
			}
		Neither => counts
	}

## A command's launch: a heredoc, a script, or no launch.
find_launch_kind! : Str => Try(Launch, [NoLaunch])
find_launch_kind! = |command|
	if !(command.contains("shale")) {
		Err(NoLaunch)
	} else if Shale.re_match!(command, "shale[^\\n]*<<'[A-Za-z]+'") {
		Ok(Heredoc)
	} else if Shale.re_match!(command, "shale[^\\n]*\\.shale") {
		Ok(Script)
	} else {
		Err(NoLaunch)
	}

## A heredoc's calls (`name(`) and the programs it runs (`run({"name"`).
count_heredoc! : Counts, Str => Counts
count_heredoc! = |counts, command| {
	called = Shale.re_find_all!(command, "([a-z_][a-z0-9_]*)\\(").map(first_group)
	ran = Shale.re_find_all!(command, "run\\(\\{\"([^\"]+)\"").map(first_group)
	{
		..counts,
		builtins: called.fold(counts.builtins, Tally.bump),
		programs: ran.fold(counts.programs, Tally.bump),
	}
}

## A match of one of Shale's patterns, as `Shale.re_find_all!` gives it.
Match : {
	at : U64,
	text : Str,
	groups : List(Str),
}

first_group : Match -> Str
first_group = |found|
	match found.groups.first() {
		Ok(group) => group
		Err(_) => crash "count_shale_stops: a pattern with a group matched without one"
	}

## How the launch an answer answers ended, by the answer's text.
## An answer to a launch: the launch, the answer's part, and its line.
Answered : {
	launch : Launch,
	part : ShaleJson,
	line_number : U64,
}

count_end! : Counts, Answered => Counts
count_end! = |counts, { launch, part, line_number }| {
	text = get_or_stop!(Transcript.answer_text(part), line_number)
	kind = match launch {
		Heredoc => "heredoc"
		Script => "script"
	}
	match stop_key!(text) {
		Ok(said) if said.starts_with("fail:") => {
			verdict = "stopped by its own `fail` (a check's verdict)"
			{ ..counts, ends: Tally.bump(counts.ends, "${kind}, ${verdict}") }
		}
		Ok(said) => {
			stop_kind =
				match said.split_first(":") {
					Ok({ before, .. }) => before
					Err(_) => said
				}
			{
				..counts,
				ends: Tally.bump(counts.ends, "${kind}, stopped by Shale"),
				stop_kinds: Tally.bump(counts.stop_kinds, stop_kind),
				stop_lines: Tally.bump(counts.stop_lines, said),
			}
		}
		Err(NoStop) => {
			ended =
				if text.contains("shale-gate:") {
					"refused by the gate"
				} else if get_or_stop!(Transcript.error_flag(part), line_number) {
					if text.contains("denied") {
						"denied by the harness"
					} else {
						"nonzero exit, no stop line"
					}
				} else {
					"ran"
				}
			{ ..counts, ends: Tally.bump(counts.ends, "${kind}, ${ended}") }
		}
	}
}

## A stop's line, with quoted values blanked, for grouping: what it says
## after its place, cut before its first ` (`, at most 110 bytes and `…`.
stop_key! : Str => Try(Str, [NoStop])
stop_key! = |text|
	match Shale.re_find!(text, "── stopped at [^:]+:[0-9]+:[0-9]+[^:]*: ([^\\n]*)") {
		Found(found) => {
			said = first_group(found)
			uncut =
				match said.split_first(" (") {
					Ok({ before, .. }) => before
					Err(_) => said
				}
			blanked = Shale.re_replace!(uncut, "\"[^\"]*\"", "\"…\"")
			Ok(cut_to_bytes(blanked, 110))
		}
		NoMatch => Err(NoStop)
	}

## The text cut to `most` bytes and `…` when it is longer. A cut inside a
## character goes back to the character's start: the Shale original cut
## the bytes, which a Roc `Str` cannot hold.
cut_to_bytes : Str, U64 -> Str
cut_to_bytes = |text, most| {
	bytes = text.to_utf8()
	if bytes.len() <= most {
		text
	} else {
		cut = List.from_iter(U64.until(0, 4)).find_first(
			|back| Str.from_utf8(bytes.take_first(most - back)).is_ok(),
		)
		kept =
			match cut {
				Ok(back) => Str.from_utf8_lossy(bytes.take_first(most - back))
				Err(_) => crash "count_shale_stops: no character starts within 4 bytes"
			}
		"${kept}…"
	}
}

## The value, or the run stopped naming the transcript line that gave the
## problem.
get_or_stop! : Try(a, Str), U64 => a
get_or_stop! = |got, line_number|
	match got {
		Ok(value) => value
		Err(why) => {
			Shale.fail!("count_shale_stops: line ${line_number.to_str()}: ${why}")
			crash "count_shale_stops: Shale.fail! returned"
		}
	}

# ── The report

## The transcript, the launches, how they ended, Shale's stops by kind and
## by message, and the heredocs' calls and programs, as the Shale original
## printed them.
print_report! : Counts, Asked => {}
print_report! = |counts, { path, since, most }| {
	since_note = if since == "" {
		""
	} else {
		", since ${since}"
	}
	heredocs = "${counts.heredocs.to_str()} heredocs"
	launches = "${heredocs}, ${counts.scripts.to_str()} script launches"
	Shale.print!(path)
	Shale.print!("${launches}${since_note}")
	sections = [
		("", counts.ends),
		("Shale's stops, by kind (a script's own `fail` left out):", counts.stop_kinds),
		("Shale's stops, by message:", counts.stop_lines),
		("calls in heredocs (builtins and the script's own functions):", counts.builtins),
		("programs heredocs run:", counts.programs),
	]
	for (heading, tally) in sections {
		Shale.print!("")
		if heading != "" {
			Shale.print!(heading)
		}
		Shale.print!(Tally.ranked_table(tally, most))
	}
}

cookbook/count_shale_stops/ShaleJson.roc, 315 lines

## ShaleJson is one JSON text read as Shale's json_read reads it
## (c/host/host_json.c), so a transcript line the Shale original read is
## read the same here, and a line it refused is refused here, in its words.
##
## Where Shale's values are not JSON's, it does as Shale does: a number
## with a fraction or an exponent is kept as its text; an integer past 64
## bits, a `null` in an array, a key twice in one object and a text nested
## past 64 levels are refused; a member that is `null` is left out of its
## object. `{}` and `[]` are both Shale's empty table, so `is_empty_table`
## says which values are one. A refusal is json_read's own sentence with
## its byte, line and column.
##
## Roc's builtin Json at the pin decodes into a record of known fields, and
## refuses none of what Shale refuses, so this reader is written out, held
## to what count_shale_stops reads: one value a line, decoded whole. Its
## strings are JsonString's.
import JsonString

ShaleJson := [
	Object(List((Str, ShaleJson))),
	Array(List(ShaleJson)),
	Text(Str),
	Integer(I64),
	Boolean(Bool),
	NoValue,
].{

	## The text's one value, or why json_read refuses it. `NoValue` is a
	## text that is `null`; inside a value, a `null` is left out or refused.
	read : Str -> Try(ShaleJson, Str)
	read = |text| {
		bytes = text.to_utf8()
		match value_at(bytes, { at: 0, depth_left: 64 }) {
			Ok(got) => ends_after(bytes, got).map_err(|problem| refusal(bytes, problem))
			Err(problem) => Err(refusal(bytes, problem))
		}
	}

	## Whether Shale holds the value as its empty table: `{}` or `[]`.
	is_empty_table : ShaleJson -> Bool
	is_empty_table = |value|
		match value {
			Object(members) => members.is_empty()
			Array(items) => items.is_empty()
			_ => False
		}
}

## A value read, and the byte after it.
Read : { decoded : ShaleJson, next : U64 }

## Where a value starts, and how much deeper the text may nest.
Place : { at : U64, depth_left : U64 }

## Why the text is refused, and the byte where it went wrong.
Problem : JsonString.Problem

## The value, when nothing but space comes after it.
ends_after : List(U8), Read -> Try(ShaleJson, Problem)
ends_after = |bytes, got| {
	after = skip_space(bytes, got.next)
	if after < bytes.len() {
		Err({ at: after, said: "more after the value: one text is one value" })
	} else {
		Ok(got.decoded)
	}
}

## The value at the place, after any space before it.
value_at : List(U8), Place -> Try(Read, Problem)
value_at = |bytes, place| {
	at = skip_space(bytes, place.at)
	match bytes.get(at) {
		Err(_) => Err({ at, said: "a value was expected and the text ended" })
		Ok('{') => object_at(bytes, { at, depth_left: place.depth_left })
		Ok('[') => array_at(bytes, { at, depth_left: place.depth_left })
		Ok('"') => {
			got = JsonString.read_at(bytes, at)?
			Ok({ decoded: ShaleJson.Text(got.text), next: got.next })
		}
		Ok('t') | Ok('f') | Ok('n') => literal_at(bytes, at)
		Ok(byte) =>
			if byte == '-' or is_digit(byte) {
				number_at(bytes, at)
			} else {
				unwanted = "${byte_name(byte)} (0x${JsonString.hex_pair(byte)})"
				Err({ at, said: "a value was expected, not ${unwanted}" })
			}
	}
}

## `true`, `false` or `null`, told by its first byte, spelled out whole.
literal_at : List(U8), U64 -> Try(Read, Problem)
literal_at = |bytes, at| {
	(word, meaning) =
		match bytes.get(at) {
			Ok('t') => ("true", ShaleJson.Boolean(True))
			Ok('f') => ("false", ShaleJson.Boolean(False))
			_ => ("null", ShaleJson.NoValue)
		}
	spelled = word.to_utf8()
	if bytes.sublist({ start: at, len: spelled.len() }) == spelled {
		Ok({ decoded: meaning, next: at + spelled.len() })
	} else {
		Err({ at, said: "`${word}` was expected" })
	}
}

## One level deeper, at the opening bracket, or the refusal past 64.
deeper : Place -> Try(U64, Problem)
deeper = |place|
	if place.depth_left == 0 {
		Err({ at: place.at, said: "the text nests past its depth budget" })
	} else {
		Ok(place.depth_left - 1)
	}

## The object whose `{` is at the place: its members in order, a `null`
## one left out, a key twice refused.
object_at : List(U8), Place -> Try(Read, Problem)
object_at = |bytes, place| {
	depth_left = deeper(place)?
	start = skip_space(bytes, place.at + 1)
	if bytes.get(start) == Ok('}') {
		return Ok({ decoded: ShaleJson.Object([]), next: start + 1 })
	}
	var $members = []
	var $at = start
	while True {
		key_at = skip_space(bytes, $at)
		if bytes.get(key_at) != Ok('"') {
			return Err({ at: key_at, said: "a member's name, a string, was expected" })
		}
		key = JsonString.read_at(bytes, key_at)?
		colon_at = skip_space(bytes, key.next)
		if bytes.get(colon_at) != Ok(':') {
			return Err({ at: colon_at, said: "a colon after a member's name was expected" })
		}
		member = value_at(bytes, { at: colon_at + 1, depth_left })?
		if $members.any(|(name, _)| name == key.text) {
			return Err({ at: key_at, said: "the key \"${key.text}\" is in this object twice" })
		}
		if has_value(member.decoded) {
			$members = $members.append((key.text, member.decoded))
		}
		after = skip_space(bytes, member.next)
		match bytes.get(after) {
			Err(_) => return Err({ at: after, said: "the text ended inside an object" })
			Ok(',') => {
				$at = after + 1
			}
			Ok('}') => return Ok({ decoded: ShaleJson.Object($members), next: after + 1 })
			Ok(byte) => {
				said = "a comma or `}` was expected, not ${byte_name(byte)}"
				return Err({ at: after, said })
			}
		}
	}
}

## The array whose `[` is at the place: its items in order, a `null`
## refused.
array_at : List(U8), Place -> Try(Read, Problem)
array_at = |bytes, place| {
	depth_left = deeper(place)?
	start = skip_space(bytes, place.at + 1)
	if bytes.get(start) == Ok(']') {
		return Ok({ decoded: ShaleJson.Array([]), next: start + 1 })
	}
	var $items = []
	var $at = start
	while True {
		item_at = skip_space(bytes, $at)
		item = value_at(bytes, { at: item_at, depth_left })?
		if !(has_value(item.decoded)) {
			cannot_hold = "which a Shale list cannot hold"
			said = "a null in an array, ${cannot_hold}: `{null = v}` names a value to stand for it"
			return Err({ at: item_at, said })
		}
		$items = $items.append(item.decoded)
		after = skip_space(bytes, item.next)
		match bytes.get(after) {
			Err(_) => return Err({ at: after, said: "the text ended inside an array" })
			Ok(',') => {
				$at = after + 1
			}
			Ok(']') => return Ok({ decoded: ShaleJson.Array($items), next: after + 1 })
			Ok(byte) => {
				said = "a comma or `]` was expected, not ${byte_name(byte)}"
				return Err({ at: after, said })
			}
		}
	}
}

## The number at `start`: an integer, or the text of one with a fraction
## or an exponent.
number_at : List(U8), U64 -> Try(Read, Problem)
number_at = |bytes, start| {
	digits_from = if bytes.get(start) == Ok('-') {
		start + 1
	} else {
		start
	}
	if !(digit_at(bytes, digits_from)) {
		return Err({ at: start, said: "a number needs a digit after its sign" })
	}
	if bytes.get(digits_from) == Ok('0') and digit_at(bytes, digits_from + 1) {
		return Err({ at: start, said: "a number with a leading zero" })
	}
	var $at = digits_end(bytes, digits_from)
	var $is_whole = True
	if bytes.get($at) == Ok('.') {
		$is_whole = False
		if !(digit_at(bytes, $at + 1)) {
			return Err({ at: start, said: "a number needs a digit after its point" })
		}
		$at = digits_end(bytes, $at + 1)
	}
	if bytes.get($at) == Ok('e') or bytes.get($at) == Ok('E') {
		$is_whole = False
		signed = bytes.get($at + 1) == Ok('+') or bytes.get($at + 1) == Ok('-')
		exponent_at = if signed {
			$at + 2
		} else {
			$at + 1
		}
		if !(digit_at(bytes, exponent_at)) {
			return Err({ at: start, said: "a number needs a digit in its exponent" })
		}
		$at = digits_end(bytes, exponent_at)
	}
	text = Str.from_utf8_lossy(bytes.sublist({ start, len: $at - start }))
	if !$is_whole {
		return Ok({ decoded: ShaleJson.Text(text), next: $at })
	}
	match I64.from_str(text) {
		Ok(number) => Ok({ decoded: ShaleJson.Integer(number), next: $at })
		Err(_) => Err({ at: start, said: "the integer ${text} is past 64 bits" })
	}
}

## Whether the value read is one Shale holds: a `null` is none.
has_value : ShaleJson -> Bool
has_value = |value|
	match value {
		NoValue => False
		_ => True
	}

digit_at : List(U8), U64 -> Bool
digit_at = |bytes, at|
	match bytes.get(at) {
		Ok(byte) => is_digit(byte)
		Err(_) => False
	}

## Where the run of digits from `at` ends.
digits_end : List(U8), U64 -> U64
digits_end = |bytes, from| {
	var $at = from
	while digit_at(bytes, $at) {
		$at = $at + 1
	}
	$at
}

is_digit : U8 -> Bool
is_digit = |byte| byte >= '0' and byte <= '9'

## Past the space JSON allows between tokens.
skip_space : List(U8), U64 -> U64
skip_space = |bytes, from| {
	var $at = from
	while is_space(bytes.get($at)) {
		$at = $at + 1
	}
	$at
}

is_space : Try(U8, [OutOfBounds]) -> Bool
is_space = |got|
	match got {
		Ok(' ') | Ok('\t') | Ok('\n') | Ok('\r') => True
		_ => False
	}

## How json_read names a byte it did not want.
byte_name : U8 -> Str
byte_name = |byte|
	match byte {
		'{' => "`{`"
		'}' => "`}`"
		'[' => "`[`"
		']' => "`]`"
		',' => "a comma"
		':' => "a colon"
		'"' => "a quote"
		_ => "a byte"
	}

## json_read's refusal: why, then where, by byte (from 0) and by line and
## column (each byte before it a column, a newline a line).
refusal : List(U8), Problem -> Str
refusal = |bytes, { at, said }| {
	before = bytes.take_first(at)
	line = before.count_if(|byte| byte == '\n') + 1
	column =
		match before.find_last_index(|byte| byte == '\n') {
			Ok(last_newline) => at - last_newline
			Err(_) => at + 1
		}
	location = "at byte ${at.to_str()} (line ${line.to_str()}, column ${column.to_str()})"
	"`json_read`: ${said} ${location}"
}

cookbook/count_shale_stops/Tally.roc, 90 lines

## Tally counts texts, each in the order it was first counted, and prints
## the most counted as the Shale original printed them, with Shale's
## `table(rows, {"n", "what"})`: the counts right-aligned under `n`, two
## spaces, the text, and no space at a line's end.
Tally := [].{

	## Counts with none counted yet.
	empty : Dict(Str, U64)
	empty = Dict.empty()

	## The counts with one more of `what`. A new text goes after every text
	## counted before it, as a Shale map's keys do.
	bump : Dict(Str, U64), Str -> Dict(Str, U64)
	bump = |counts, what|
		counts.update(
			what,
			|was|
				match was {
					Ok(count) => Ok(count + 1)
					Err(Missing) => Ok(1)
				},
		)

	## The `most` texts counted most, highest first, ties in the order
	## they were first counted (Shale's `sort` is stable), as a table.
	## `most` under 1 shows the heading alone.
	ranked_table : Dict(Str, U64), I64 -> Str
	ranked_table = |counts, most| {
		shown = if most > 0 {
			most.to_u64_wrap()
		} else {
			0
		}
		rows =
			counts
				.to_list()
				.map_with_index(|(what, count), order| { count, order, what })
				.sort_with(compare_rows)
				.take_first(shown)
		count_cells = rows.map(|row| row.count.to_str())
		width = count_cells.fold(1, |widest, cell| U64.max(widest, cell.count_utf8_bytes()))
		# A column of integers is right-aligned, its heading too; with no
		# rows there are none, and Shale aligns the heading left.
		heading = if rows.is_empty() {
			"n"
		} else {
			right_aligned("n", width)
		}
		lines = rows.map(|row| "${right_aligned(row.count.to_str(), width)}  ${row.what}")
		Str.join_with(lines.prepend("${heading}  what").map(without_trailing_spaces), "\n")
	}
}

## A row of the ranking: its count, where it was first counted, its text.
Row : {
	count : U64,
	order : U64,
	what : Str,
}

compare_rows : Row, Row -> [Before, Same, After]
compare_rows = |left, right|
	if left.count > right.count {
		Before
	} else if left.count < right.count {
		After
	} else if left.order < right.order {
		Before
	} else if left.order > right.order {
		After
	} else {
		Same
	}

right_aligned : Str, U64 -> Str
right_aligned = |cell, width| {
	gap = width - U64.min(width, cell.count_utf8_bytes())
	"${" ".repeat(gap)}${cell}"
}

## The line with the spaces at its end taken off, as Shale's `table` does
## (spaces only: a tab stays).
without_trailing_spaces : Str -> Str
without_trailing_spaces = |line| {
	bytes = line.to_utf8()
	match bytes.find_last_index(|byte| byte != ' ') {
		Ok(last) => Str.from_utf8_lossy(bytes.take_first(last + 1))
		Err(_) => ""
	}
}

cookbook/count_shale_stops/Transcript.roc, 202 lines

## Transcript reads what count_shale_stops needs from one Claude Code
## transcript line, read by ShaleJson: its message's parts, each a call of
## the Bash tool, an answer to a call, or neither, and from an answer its
## text and whether it was an error.
##
## Each field is read where the Shale original read it and no sooner, so a
## line it stopped on stops here and a line it passed passes: a field that
## isn't there, or is not what the original's next step takes, is an `Err`
## saying which, in the words of the Shale stop it stands for.
import ShaleJson

Transcript := [].{

	## The parts of the line's `message.content`, or none when the line is
	## older than `since` or its content is not a list. `since` is `""` for
	## every line, else an ISO time the line's `timestamp` is held to as
	## text.
	recent_parts : ShaleJson, Str -> Try(List(ShaleJson), Str)
	recent_parts = |line, since| {
		is_recent =
			if since == "" {
				True
			} else {
				at_least(timestamp(line)?, since)
			}
		message = field(line, "message")?
		content = field(message, "content")?
		if is_recent and is_list(content) {
			match content {
				Array(parts) => Ok(parts)
				_ => Ok([])
			}
		} else {
			Ok([])
		}
	}

	## What a part of a message is: a call of the Bash tool (its command),
	## an answer to a call (the call's id), or neither.
	part_kind : ShaleJson -> Try([ShellCall(Str), Answer(Str), Neither], Str)
	part_kind = |part| {
		kind = field(part, "type")?
		is_shell_call =
			if is_text(kind, "tool_use") {
				is_text(field(part, "name")?, "Bash")
			} else {
				False
			}
		if is_shell_call {
			input = field(part, "input")?
			command = text_of(field(input, "command")?, "the command")?
			Ok(ShellCall(command))
		} else if is_text(kind, "tool_result") {
			Ok(Answer(text_of(field(part, "tool_use_id")?, "an answer's call id")?))
		} else {
			Ok(Neither)
		}
	}

	## A call's id, read once the call is known to be a launch.
	call_id : ShaleJson -> Try(Str, Str)
	call_id = |part| text_of(field(part, "id")?, "a call's id")

	## An answer's text: its content when that is a string, else the `text`
	## of each of its parts, a line apart.
	answer_text : ShaleJson -> Try(Str, Str)
	answer_text = |part| {
		content = field(part, "content")?
		match content {
			Text(text) => Ok(text)
			Array(items) => {
				texts = items.map_try(item_text)?
				Ok(Str.join_with(texts.keep_oks(|text| text), "\n"))
			}
			_ =>
				if ShaleJson.is_empty_table(content) {
					Ok("")
				} else {
					Err("`re_find`: its first argument must be a string, not ${type_name(content)}")
				}
		}
	}

	## The answer's `is_error` as Shale's `if` takes it: false when it has
	## none, and true when it is anything but `false`.
	error_flag : ShaleJson -> Try(Bool, Str)
	error_flag = |part|
		match optional_field(part, "is_error")? {
			Ok(Boolean(flag)) => Ok(flag)
			Ok(_) => Ok(True)
			Err(Missing) => Ok(False)
		}
}

## A part of a list content's `text`, `Err(Missing)` for a part without one.
## Shale's `join` writes an integer as its digits.
item_text : ShaleJson -> Try(Try(Str, [Missing]), Str)
item_text = |item|
	match optional_field(item, "text")? {
		Ok(Text(text)) => Ok(Ok(text))
		Ok(Integer(number)) => Ok(Ok(number.to_str()))
		Ok(other) => {
			taken = "`join` takes strings and integers"
			Err("${taken}, and a part's `text` is ${type_name(other)}")
		}
		Err(Missing) => Ok(Err(Missing))
	}

## Whether the value is the string `text`.
is_text : ShaleJson, Str -> Bool
is_text = |value, text|
	match value {
		Text(got) => got == text
		_ => False
	}

## The line's `timestamp`, `""` when it has none (Shale's `get`).
timestamp : ShaleJson -> Try(Str, Str)
timestamp = |line|
	match line {
		Array(items) if !(items.is_empty()) =>
			Err("`get`: a list's keys are integers: this one is a list, given a string")
		Object(_) | Array(_) =>
			match optional_field(line, "timestamp")? {
				Ok(Text(text)) => Ok(text)
				Ok(other) => {
					compared = "`>=` compares a string with a string"
					Err("${compared}, and a line's `timestamp` is ${type_name(other)}")
				}
				Err(Missing) => Ok("")
			}
		_ => Err("`get` takes a map or a list, not ${type_name(line)}")
	}

## A map's member, as Shale's `v.name` reads it: a stop when it is missing.
field : ShaleJson, Str -> Try(ShaleJson, Str)
field = |value, name|
	match optional_field(value, name)? {
		Ok(member) => Ok(member)
		Err(Missing) => Err("no key \"${name}\" in the map (`has_key` asks first)")
	}

## A map's member, or `Missing`; a value that is no map stops.
optional_field : ShaleJson, Str -> Try(Try(ShaleJson, [Missing]), Str)
optional_field = |value, name|
	match value {
		Object(members) =>
			match members.find_first(|(key, _)| key == name) {
				Ok((_, member)) => Ok(Ok(member))
				Err(_) => Ok(Err(Missing))
			}
		Array(items) if items.is_empty() => Ok(Err(Missing))
		_ => Err("`.${name}` reads a map's member, and this is ${type_name(value)}")
	}

## A string where the next step takes one.
text_of : ShaleJson, Str -> Try(Str, Str)
text_of = |value, what|
	match value {
		Text(text) => Ok(text)
		_ => Err("${what} is ${type_name(value)}, not a string")
	}

## Whether Shale's `is_list` holds: JSON written back starts with `[`, so a
## list or the empty table.
is_list : ShaleJson -> Bool
is_list = |value|
	match value {
		Array(_) => True
		_ => ShaleJson.is_empty_table(value)
	}

## Whether `text` sorts at or after `since`, byte by byte, as Shale's `>=`
## compares strings.
at_least : Str, Str -> Bool
at_least = |text, since| {
	text_bytes = text.to_utf8()
	since_bytes = since.to_utf8()
	$at : U64
	var $at = 0
	while $at < text_bytes.len() and text_bytes.get($at) == since_bytes.get($at) {
		$at = $at + 1
	}
	match (text_bytes.get($at), since_bytes.get($at)) {
		(Ok(text_byte), Ok(since_byte)) => text_byte > since_byte
		(_, Err(_)) => True
		(Err(_), Ok(_)) => False
	}
}

## How a value is named in a stop.
type_name : ShaleJson -> Str
type_name = |value|
	match value {
		Object(members) if !(members.is_empty()) => "a map"
		Array(items) if !(items.is_empty()) => "a list"
		Object(_) | Array(_) => "an empty table"
		Text(_) => "a string"
		Integer(_) => "an integer"
		Boolean(_) => "a boolean"
		NoValue => "nil"
	}

cookbook/count_shale_stops/JsonString.roc, 197 lines

## JsonString reads one JSON string as Shale's json_read reads it
## (c/host/host_json.c): its escapes decoded to UTF-8, a `\u` high
## surrogate taking the low one after it, and the four hex digits of a `\u`
## read as Zig's parseInt reads them. A refusal says why and at which byte,
## for ShaleJson to put as json_read's sentence.
JsonString := [].{

	## Why a text is refused, and the byte where it went wrong.
	Problem : { at : U64, said : Str }

	## The string whose opening quote is at `open`, its escapes decoded, and
	## the byte after its closing quote. A string with no escape is its own
	## bytes; one with escapes is built a stretch at a time.
	read_at : List(U8), U64 -> Try({ text : Str, next : U64 }, JsonString.Problem)
	read_at = |bytes, open| {
		var $at = open + 1
		var $copied_to = $at
		var $decoded = []
		var $has_escape = False
		while True {
			match bytes.get($at) {
				Err(_) => return Err({ at: open, said: "a string that never closes" })
				Ok('"') => {
					stretch = { start: $copied_to, len: $at - $copied_to }
					content =
						if $has_escape {
							$decoded.append_sublist(bytes, stretch)
						} else {
							bytes.sublist(stretch)
						}
					return match Str.from_utf8(content) {
						Ok(text) => Ok({ text, next: $at + 1 })
						Err(_) => Err({ at: open, said: "a string that is not UTF-8" })
					}
				}
				Ok('\\') => {
					escape = escape_at(bytes, $at)?
					stretch = { start: $copied_to, len: $at - $copied_to }
					$decoded = $decoded.append_sublist(bytes, stretch).concat(escape.decoded)
					$has_escape = True
					$at = escape.next
					$copied_to = $at
				}
				Ok(byte) =>
					if byte < 0x20 {
						written = "which JSON writes as an escape"
						code = JsonString.hex_pair(byte)
						said = "a control byte (0x${code}) inside a string, ${written}"
						return Err({ at: $at, said })
					} else {
						$at = $at + 1
					}
			}
		}
	}

	## A byte as two lowercase hex digits.
	hex_pair : U8 -> Str
	hex_pair = |byte| Str.from_utf8_lossy([hex_digit_byte(byte // 16), hex_digit_byte(byte % 16)])
}

## A string's bytes decoded from an escape, and the byte after it.
Escape : { decoded : List(U8), next : U64 }

## The escape whose backslash is at `at`. A `\u` high surrogate takes the
## low one after it.
escape_at : List(U8), U64 -> Try(Escape, JsonString.Problem)
escape_at = |bytes, at| {
	plain = |byte| Ok({ decoded: [byte], next: at + 2 })
	match bytes.get(at + 1) {
		Err(_) => Err({ at, said: "a string that ends in a backslash" })
		Ok('"') => plain('"')
		Ok('\\') => plain('\\')
		Ok('/') => plain('/')
		Ok('b') => plain(8)
		Ok('f') => plain(12)
		Ok('n') => plain('\n')
		Ok('r') => plain('\r')
		Ok('t') => plain('\t')
		Ok('u') => unicode_escape_at(bytes, at)
		Ok(byte) => {
			escaped = Str.from_utf8_lossy([byte])
			Err({ at, said: "the escape `\\${escaped}`, which JSON has not" })
		}
	}
}

## A `\u` escape at `at`, with the low surrogate's own escape after a high
## one, as UTF-8.
unicode_escape_at : List(U8), U64 -> Try(Escape, JsonString.Problem)
unicode_escape_at = |bytes, at| {
	high = hex_four(bytes, at)?
	after = at + 6
	if high >= 0xD800 and high <= 0xDBFF {
		if bytes.sublist({ start: after, len: 2 }) != ['\\', 'u'] {
			return Err({ at, said: "a high surrogate with no low one after it" })
		}
		low = hex_four(bytes, after)?
		if low < 0xDC00 or low > 0xDFFF {
			return Err({ at: after, said: "a high surrogate followed by no low one" })
		}
		code_point = 0x10000 + (high - 0xD800) * 0x400 + (low - 0xDC00)
		Ok({ decoded: utf8_of(code_point), next: after + 6 })
	} else if high >= 0xDC00 and high <= 0xDFFF {
		Err({ at, said: "a low surrogate with no high one before it" })
	} else {
		Ok({ decoded: utf8_of(high), next: after })
	}
}

## The four bytes after the `\u` at `at`, read as Zig's
## `std.fmt.parseInt(u16, s, 16)` reads them, as Shale's reader does: a
## `+` or `-` may lead (a `-` only before zero), and `_` may stand between
## digits.
hex_four : List(U8), U64 -> Try(U32, JsonString.Problem)
hex_four = |bytes, at| {
	refused = Err({ at, said: "`\\u` needs four hex digits" })
	four = bytes.sublist({ start: at + 2, len: 4 })
	if four.len() < 4 {
		return refused
	}
	is_negative = four.first() == Ok('-')
	digits =
		if is_negative or four.first() == Ok('+') {
			four.drop_first(1)
		} else {
			four
		}
	if digits.is_empty() or digits.first() == Ok('_') or digits.last() == Ok('_') {
		return refused
	}
	$code_point : U32
	var $code_point = 0
	for byte in digits {
		if byte != '_' {
			match hex_digit(byte) {
				Ok(digit) => {
					$code_point = $code_point * 16 + digit
				}
				Err(_) => return refused
			}
		}
	}
	if is_negative and $code_point != 0 {
		return refused
	}
	Ok($code_point)
}

hex_digit : U8 -> Try(U32, [NotHex])
hex_digit = |byte|
	if byte >= '0' and byte <= '9' {
		Ok((byte - '0').to_u32())
	} else if byte >= 'a' and byte <= 'f' {
		Ok((byte - 'a' + 10).to_u32())
	} else if byte >= 'A' and byte <= 'F' {
		Ok((byte - 'A' + 10).to_u32())
	} else {
		Err(NotHex)
	}

## The lowercase hex digit for a value under 16.
hex_digit_byte : U8 -> U8
hex_digit_byte = |value|
	if value < 10 {
		'0' + value
	} else {
		'a' + value - 10
	}

## A code point's UTF-8 bytes: its bits six at a time, after a lead byte
## that says how many follow.
utf8_of : U32 -> List(U8)
utf8_of = |code_point| {
	if code_point < 0x80 {
		[code_point.to_u8_wrap()]
	} else if code_point < 0x800 {
		[(0xC0 + code_point // 0x40).to_u8_wrap(), low_six(code_point)]
	} else if code_point < 0x10000 {
		[
			(0xE0 + code_point // 0x1000).to_u8_wrap(),
			low_six(code_point // 0x40),
			low_six(code_point),
		]
	} else {
		[
			(0xF0 + code_point // 0x40000).to_u8_wrap(),
			low_six(code_point // 0x1000),
			low_six(code_point // 0x40),
			low_six(code_point),
		]
	}
}

## A continuation byte: the low six bits of the code point shifted down.
low_six : U32 -> U8
low_six = |shifted| (0x80 + shifted % 0x40).to_u8_wrap()

Shale original

cookbook/count_shale_stops.shale, 164 lines, at 18e1b3c6

-- This recipe counts how an agent's Shale launches went, from a Claude Code
-- transcript: each Bash call's command and the answer it got, paired by the
-- call's id. A launch is a heredoc (`shale <<'TAG'`) or a script (`shale
-- path.shale`). Each ends one of four ways: it ran, Shale stopped it (`──
-- stopped at`), the gate refused the call before Shale saw it, or the
-- harness denied it. A stop by the script's own `fail` is a check's verdict,
-- counted apart; Shale's other stops are grouped by kind and by message,
-- with quoted values blanked so that one mistake made twice counts as one
-- line. The calls the heredocs make and the programs they `run` are counted
-- too: where the agent works, and where it trips.
--
-- With no `transcript=`, it reads the newest transcript under the
-- `projects:` mount. `since=` is an ISO time; only the calls from then on
-- count. `most=N` sets how many lines each list shows (20).
--
--   shale cookbook:count_shale_stops.shale
--   shale cookbook:count_shale_stops.shale since=2026-11-14T19:50
--
-- budget: steps=2000000000 reads=100000 read_bytes=4000000000 arena_bytes=4000000000

const TRANSCRIPT = arg("transcript", "")
const SINCE = arg("since", "")
const MOST = arg("most", 20)
const PART = 8 * 1024 * 1024

function newest_transcript()
  local best = nil
  local best_at = -1
  for p in glob("projects:*/*.jsonl") do
    local s = stat(p)
    if s.modified > best_at then
      best = p
      best_at = s.modified
    end
  end
  if best == nil then fail("count_shale_stops: no transcript under projects:") end
  return best
end

-- Whether a JSON value read back is a list: Shale has no `type`, so by the
-- first byte of its JSON.
function is_list(v)
  return starts_with(json_write(v), "[")
end

-- A tool result's text: a string, or a list of parts with `text`.
function result_text(content)
  if not is_list(content) then return content end
  local parts = {}
  for c in content do
    if has_key(c, "text") then push(parts, c.text) end
  end
  return join(parts, "\n")
end

function launch_kind(command)
  if find(command, "shale") == nil then return "" end
  if re_find(command, "shale[^\\n]*<<'[A-Za-z]+'") ~= nil then return "heredoc" end
  if re_find(command, "shale[^\\n]*\\.shale") ~= nil then return "script" end
  return ""
end

-- One stop's line, with quoted values blanked, for grouping.
function stop_key(text)
  local m = re_find(text, "── stopped at [^:]+:[0-9]+:[0-9]+[^:]*: ([^\\n]*)")
  if m == nil then return nil end
  local said = m.groups[1]
  local cut = find(said, " (")
  if cut ~= nil then said = sub(said, 1, cut - 1) end
  said = re_replace(said, "\"[^\"]*\"", "\"…\"")
  if #said > 110 then said = sub(said, 1, 110) .. "…" end
  return said
end

function bump(counts, key)
  counts[key] = get(counts, key, 0) + 1
end

function ranked(counts)
  local rows = {}
  for k in keys(counts) do push(rows, {n = counts[k], what = k}) end
  sort(rows, "n", "desc")
  local top = {}
  for r in rows do if #top < MOST then push(top, r) end end
  return top
end

local path = TRANSCRIPT
if path == "" then path = newest_transcript() end

local calls = {}
local tally = {heredoc = 0, script = 0}
local ends = {}
local stop_kinds = {}
local stop_lines = {}
local builtins = {}
local programs = {}
local at = 0
local done = false
while not done do
  local part = read_lines(path, at, PART)
  for l in part.lines do
    local is_call = find(l, "\"tool_use\"") ~= nil and find(l, "\"Bash\"") ~= nil
    local is_answer = find(l, "\"tool_result\"") ~= nil
    if is_call or is_answer then
      local v = json_read(l)
      local recent = SINCE == "" or get(v, "timestamp", "") >= SINCE
      local content = v.message.content
      if recent and is_list(content) then
        for c in content do
          if c.type == "tool_use" and c.name == "Bash" then
            local kind = launch_kind(c.input.command)
            if kind ~= "" then
              calls[c.id] = kind
              tally[kind] = tally[kind] + 1
              if kind == "heredoc" then
                for b in re_find_all(c.input.command, "([a-z_][a-z0-9_]*)\\(") do bump(builtins, b.groups[1]) end
                for p in re_find_all(c.input.command, "run\\(\\{\"([^\"]+)\"") do bump(programs, p.groups[1]) end
              end
            end
          elseif c.type == "tool_result" and has_key(calls, c.tool_use_id) then
            local text = result_text(c.content)
            local kind = calls[c.tool_use_id]
            local key = stop_key(text)
            if key ~= nil and starts_with(key, "fail:") then
              bump(ends, kind .. ", stopped by its own `fail` (a check's verdict)")
            elseif key ~= nil then
              bump(ends, kind .. ", stopped by Shale")
              bump(stop_kinds, split(key, ":")[1])
              bump(stop_lines, key)
            elseif find(text, "shale-gate:") ~= nil then
              bump(ends, kind .. ", refused by the gate")
            elseif find(text, "denied") ~= nil and get(c, "is_error", false) then
              bump(ends, kind .. ", denied by the harness")
            elseif get(c, "is_error", false) then
              bump(ends, kind .. ", nonzero exit, no stop line")
            else
              bump(ends, kind .. ", ran")
            end
          end
        end
      end
    end
  end
  at = part.next
  done = part.done
end

print(path)
print(tally.heredoc .. " heredocs, " .. tally.script .. " script launches" .. (SINCE == "" and "" or ", since " .. SINCE))
print("")
print(table(ranked(ends), {"n", "what"}))
print("")
print("Shale's stops, by kind (a script's own `fail` left out):")
print(table(ranked(stop_kinds), {"n", "what"}))
print("")
print("Shale's stops, by message:")
print(table(ranked(stop_lines), {"n", "what"}))
print("")
print("calls in heredocs (builtins and the script's own functions):")
print(table(ranked(builtins), {"n", "what"}))
print("")
print("programs heredocs run:")
print(table(ranked(programs), {"n", "what"}))