Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions core/tests/turn_checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,9 @@ fn a_checks_exit_code_and_output_tail_are_read_through_its_offset() {
"Exit code 2\nline one\nline two\nerror: it broke",
),
passes(2_000, "t2", "cargo test", None),
output_of(3_000, "t3", &numbered(1, 3000)),
// The hook's trim of that output (#1074): its last 40 lines.
output_of(4_000, "t4", &numbered(2961, 3000)),
];
let mut lines = vec![prompt()];
lines.extend(calls.concat());
Expand All @@ -208,6 +211,26 @@ fn a_checks_exit_code_and_output_tail_are_read_through_its_offset() {
assert!(failed.tail.ends_with("error: it broke"), "{}", failed.tail);
assert_eq!(passed.exit_code, Some(0));
assert_eq!(passed.tail, "ok\nall passed");
let long = check_output(ledger.row(None, "t3").unwrap(), log).unwrap();
let trimmed = check_output(ledger.row(None, "t4").unwrap(), log).unwrap();
assert_eq!(long.tail, trimmed.tail);
assert!(trimmed.tail.ends_with("line 3000"), "{}", trimmed.tail);
}

fn numbered(from: usize, to: usize) -> String {
(from..=to)
.map(|n| format!("line {n}"))
.collect::<Vec<_>>()
.join("\n")
}

/// A passing Bash call whose stdout is `stdout`.
fn output_of(ms: u64, id: &str, stdout: &str) -> Vec<String> {
let mut lines = passes(ms, id, "cargo test", None);
let mut end: Value = serde_json::from_str(&lines[1]).unwrap();
end["tool_response"]["stdout"] = stdout.into();
lines[1] = end.to_string();
lines
}

/// The suites and statuses of the checks a turn with the one command `command` shows.
Expand Down
2 changes: 1 addition & 1 deletion docs/studio/behaviour/storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ The hooks are async, so Claude Code never waits for them, and they append whethe

`turns/` beside the log keeps the hook's record of each session's latest turn, `<session>.json`: its prompt id, the worktrees whose start tree it recorded, whether it ended, and its workers, so a hook knows what the hooks before it took. Each hook replaces the record whole, through a temporary file and a rename, so a hook killed mid-write leaves the old record or the new one, never an empty one. `<session>.lock` beside it is the record's lock (#913): the hooks of one session hold it in turn while they read and replace the record, since a rename puts a new file in the record's place and a lock on the record would be on the file it replaced. An OpenCode or agy line holds it until the line is in the log (#744). Like `events.lock`, its bytes mean nothing. The record goes at the session's `SessionEnd`, which waits for the lock first, so a hook that holds it while it replaces the record finishes before the record goes. The lock stays: a hook waiting for it would otherwise hold a deleted file while a later hook made and locked a new one, and two hooks would hold the lock at once. A hook of the session that runs after its end, such as one that was waiting for the lock, finds no record and writes a new one, as a new turn's first hook does; nothing removes that record at once, and it is pruned like any other. At a `SessionStart` a hook deletes the record and its lock of each session whose record is unchanged for 7 days and whose lock no hook holds then, judging a lock by its record's mtime, since a lock is never written, or by its own when it has no record, as an ended session's has; and any other file there, such as a killed hook's temporary file, unchanged for 7 days. The limit: while an upgrade mixes hooks, a hook from before the lock (#913) neither takes nor waits for it, so its write can bring back a record its session's end removed, or lose a turn a new hook wrote; the record left behind is pruned 7 days later.

The log holds tool inputs and results: commands and their output, errors, exit codes, the text an edit replaced and its hunks, and a written file's content. It leaves out two fields no reader takes (danielrispler/plotkeeper#132): an Edit's or Write's `originalFile`, the whole file before the change, and a Read's file `content`.
The log holds tool inputs and results: commands and their output, errors, exit codes, the text an edit replaced and its hunks, and a written file's content. It leaves out what no reader takes (danielrispler/plotkeeper#132, #1074): an Edit's or Write's `originalFile`, the whole file before the change, a Read's file `content`, the `base64` data of an image a Read opened (its path, type, dimensions and size stay), and a Bash result's `bashEditDiff`. A command's `stdout` and `stderr` each keep their last 40 lines, and those at most their last 64 KB, cut on a character boundary, so a check's output tail reads as it did unless one stream's last 40 lines run over 64 KB.

It keeps a session's events for 30 days after its last one. At each start, before the replay, the app moves the events of older sessions to `events-archive.jsonl` beside it, and drops the two fields from the lines it keeps; a prune moves lines, so it also removes `studio-state.json`, the state a replay made, which the next start saves again and later starts resume from, replaying only the log's tail. Each session in it keeps its `project`, its project folder (spec #659): the root of the first folder it got, set once and never changed by later events. It has a default, so a previous build reads the file and skips it as an unknown key; a session saved before it existed takes it from its saved folder when the file is read, a task's worktree's main checkout, so it keeps the project it showed. The app never reads the archive, and never deletes it; their turns stay in the card store.

Expand Down
48 changes: 44 additions & 4 deletions hook/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,11 @@ fn hold(log: &Path, patience: Duration) -> std::io::Result<Option<fs::File>> {
}
}

/// Leaves out of hook event `event` the two fields no reader takes, a quarter of the log's bytes on
/// 2026-11-16 (danielrispler/plotkeeper#132): a response's `originalFile`, the whole file an `Edit` or
/// `Write` changed, and a `Read`'s file `content`. The hunks, output and errors stay. Returns whether
/// it left anything out.
/// Leaves out of hook event `event` what no reader takes (danielrispler/plotkeeper#132, #1074): a
/// response's `originalFile`, the whole file an `Edit` or `Write` changed, a `Read`'s file `content`
/// and an image's `base64`, and a Bash `bashEditDiff`. A command's `stdout` and `stderr` each keep
/// their last 40 lines, and those at most their last 64 KB. The hunks, errors and the rest stay.
/// Returns whether it left anything out.
pub fn lighten(event: &mut serde_json::Value) -> bool {
use serde_json::Value;
let read = event.get("tool_name").and_then(Value::as_str) == Some("Read");
Expand All @@ -204,12 +205,51 @@ pub fn lighten(event: &mut serde_json::Value) -> bool {
return false;
};
let mut left_out = response.remove("originalFile").is_some();
left_out |= response.remove("bashEditDiff").is_some();
if read && let Some(file) = response.get_mut("file").and_then(Value::as_object_mut) {
left_out |= file.remove("content").is_some();
left_out |= file.remove("base64").is_some();
}
for stream in ["stdout", "stderr"] {
if let Some(Value::String(text)) = response.get_mut(stream) {
let start = tail_start(text);
if start > 0 {
text.drain(..start);
left_out = true;
}
}
}
left_out
}

/// Lines of a command's output the log keeps, and the most bytes of them.
const KEEP_LINES: usize = 40;
const KEEP_BYTES: usize = 64 * 1024;

/// Where in `text` its kept tail starts: its last `KEEP_LINES` lines, at most its last `KEEP_BYTES`
/// bytes, on a character boundary. 0 when all of it stays.
fn tail_start(text: &str) -> usize {
let body = text.strip_suffix('\n').unwrap_or(text);
let mut start = 0;
let mut rest = body;
for _ in 0..KEEP_LINES {
match rest.rfind('\n') {
Some(i) => rest = &rest[..i],
None => return cap(text, 0),
}
start = rest.len() + 1;
}
cap(text, start)
}

fn cap(text: &str, start: usize) -> usize {
let mut start = start.max(text.len().saturating_sub(KEEP_BYTES));
while !text.is_char_boundary(start) {
start += 1;
}
start
}

/// How long a session's events stay in the log after its last one (danielrispler/plotkeeper#132).
pub const KEEP: Duration = Duration::from_secs(30 * 24 * 60 * 60);

Expand Down
58 changes: 56 additions & 2 deletions hook/tests/prune.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,45 @@ fn read() -> Value {
})
}

/// A Bash result for the hook, with `response` as its `tool_response`.
fn bash(response: Value) -> Value {
json!({
"session_id": "s-1",
"hook_event_name": "PostToolUse",
"cwd": "/",
"tool_name": "Bash",
"tool_response": response,
})
}

fn numbered(from: usize, to: usize) -> String {
(from..=to).map(|n| format!("line {n}\n")).collect()
}

#[test]
fn the_hook_leaves_out_an_edits_original_file_and_a_reads_content() {
fn the_hook_leaves_out_what_no_reader_takes_and_cuts_a_commands_output() {
let home = scratch("hook");
for event in [edit(), read()] {
let image = json!({
"session_id": "s-1",
"hook_event_name": "PostToolUse",
"cwd": "/",
"tool_name": "Read",
"tool_response": { "type": "image", "file": {
"filePath": "/w/shot.png", "base64": "iVBORw0KGgo", "type": "image/png",
"originalSize": 1234, "dimensions": { "originalWidth": 10, "originalHeight": 20 } } },
});
let long_line = "x".repeat(600_000);
let euros = "\u{20ac}".repeat(30_000);
let events = [
edit(),
read(),
image,
bash(json!({ "stdout": numbered(1, 3000), "stderr": numbered(1, 3000) })),
bash(json!({ "stdout": long_line, "stderr": "" })),
bash(json!({ "stdout": euros, "stderr": "" })),
bash(json!({ "stdout": "ok\nall passed", "stderr": "warn", "bashEditDiff": "-a\n+b" })),
];
for event in events {
let mut cmd = hook(&home);
cmd.stdout(Stdio::null());
assert!(feed(cmd, &event).wait().unwrap().success());
Expand All @@ -81,6 +116,25 @@ fn the_hook_leaves_out_an_edits_original_file_and_a_reads_content() {
assert_eq!(file.get("content"), None);
assert_eq!(file["filePath"], "/w/a.rs");
assert_eq!(file["numLines"], 1);
let image = &logged[2]["tool_response"]["file"];
assert_eq!(image.get("base64"), None);
assert_eq!(image["filePath"], "/w/shot.png");
assert_eq!(image["type"], "image/png");
assert_eq!(image["originalSize"], 1234);
assert_eq!(image["dimensions"]["originalWidth"], 10);
let many = &logged[3]["tool_response"];
assert_eq!(many["stdout"], numbered(2961, 3000));
assert_eq!(many["stderr"], numbered(2961, 3000));
let single = logged[4]["tool_response"]["stdout"].as_str().unwrap();
assert_eq!(single.len(), 64 * 1024);
assert!(single.bytes().all(|b| b == b'x'));
let multibyte = logged[5]["tool_response"]["stdout"].as_str().unwrap();
assert_eq!(multibyte.len(), 65_535);
assert!(multibyte.chars().all(|c| c == '\u{20ac}'));
let short = &logged[6]["tool_response"];
assert_eq!(short["stdout"], "ok\nall passed");
assert_eq!(short["stderr"], "warn");
assert_eq!(short.get("bashEditDiff"), None);
}

#[test]
Expand Down
21 changes: 1 addition & 20 deletions understanding/src/drift.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ impl fmt::Display for Drift {
writeln!(
f,
"Claude Code changed from {from} to {to} on {}",
date(*at)
studio_workbench::clock::utc_date(*at)
)?;
}
for (kind, count) in &self.agy {
Expand All @@ -187,22 +187,3 @@ impl fmt::Display for Drift {
const DAY: u64 = 86_400_000;
/// The window the drift counts over: 7 days.
const WEEK: u64 = 7 * DAY;

/// The UTC date of `ms`, in Unix milliseconds, as `YYYY-MM-DD` (Howard Hinnant's
/// `civil_from_days`).
pub fn date(ms: u64) -> String {
let days = ms / DAY + 719_468;
let (era, day_of_era) = (days / 146_097, days % 146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let shifted_month = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
let month = if shifted_month < 10 {
shifted_month + 3
} else {
shifted_month - 9
};
let year = era * 400 + year_of_era + u64::from(month <= 2);
format!("{year}-{month:02}-{day:02}")
}
5 changes: 2 additions & 3 deletions understanding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ pub use brief::{
Answered, DesignLine, OpenItem, OpenKind, answered, design_lines, design_sources, open_items,
write_design,
};
pub use drift::{
AGY_FIXTURE_VERSION, AgyVersions, Drift, Versions, date as utc_date, drift, dropped_events,
};
pub use drift::{AGY_FIXTURE_VERSION, AgyVersions, Drift, Versions, drift, dropped_events};
pub use fingerprint::{Fingerprints, fingerprint_changes, live_roots, worktree_root};
pub use part_lines::{
PartGroup, PartLine, PartLinesRequest, TurnHunk, TurnPaths, part_lines_input, write_part_lines,
Expand All @@ -56,6 +54,7 @@ pub use store::{
Arm, Brief, CardStore, CheckResult, Guess, Level, QuizTap, Rating, Reason, Retest, Row,
SessionCards, StoredCard, StoredSummary, Surface, Tap, millis,
};
pub use studio_workbench::clock::utc_date;
pub use summary::{
Line, LineKind, PromptFrom, ReplyPrompt, SummarySetup, TurnSummary, write_agent_summary,
write_name, write_summary,
Expand Down
40 changes: 40 additions & 0 deletions workbench/src/clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,43 @@ pub fn now_ms() -> u64 {
.elapsed()
.map_or(0, |since| since.as_millis() as u64)
}

const DAY_MS: u64 = 86_400_000;

/// The UTC date of `ms`, in Unix milliseconds, as `YYYY-MM-DD` (Howard Hinnant's
/// `civil_from_days`).
pub fn utc_date(ms: u64) -> String {
let days = ms / DAY_MS + 719_468;
let (era, day_of_era) = (days / 146_097, days % 146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let shifted_month = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
let month = if shifted_month < 10 {
shifted_month + 3
} else {
shifted_month - 9
};
let year = era * 400 + year_of_era + u64::from(month <= 2);
format!("{year}-{month:02}-{day:02}")
}

#[cfg(test)]
mod tests {
use super::utc_date;

#[test]
fn the_utc_date_of_a_millisecond() {
let cases: [(u64, &str); 5] = [
(0, "1970-01-01"),
(86_399_999, "1970-01-01"),
(86_400_000, "1970-01-02"),
(951_782_400_000, "2000-02-29"),
(1_796_169_599_999, "2026-12-01"),
];
for (ms, want) in cases {
assert_eq!(utc_date(ms), want, "{ms}");
}
}
}