diff --git a/core/src/ledger.rs b/core/src/ledger.rs index 4708a5be6..a034060df 100644 --- a/core/src/ledger.rs +++ b/core/src/ledger.rs @@ -1,8 +1,8 @@ //! The step ledger (danielrispler/plotkeeper#110): one row for every tool call of an agent session, //! its workers' calls included. A row keeps what the rail needs to rank and count a turn's work, and -//! where in the event log its two events are (`Bytes`). It keeps no output and no hunk text: those -//! are read on demand, by one seek and one read of the event's length (`Row::details`), so a read -//! costs the same on a large log as on a small one. +//! where in the event log its two events are (`Bytes`): a day file and the offset in it. It keeps no output and no hunk +//! text: those are read on demand, by one seek and one read of the event's length (`Row::details`), so a read costs the +//! same on a large log as on a small one. use crate::event::{Event, Tool, ToolKind}; use serde::{Deserialize, Serialize}; @@ -14,14 +14,23 @@ use std::{ path::Path, }; -/// Where one event's line is in the event log: its byte offset from the file's start, and its byte -/// length without the line's newline. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +/// Where one event's line is in the event log: its day file, by name in the log's folder, its byte offset from the +/// file's start, and its byte length without the line's newline. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Bytes { + pub file: String, pub offset: u64, pub len: u64, } +/// A place in the event log: a day file, by name in the log's folder, and a byte offset in it (spec #1072, +/// "Positions"). A day file never changes once the next day's exists, so a position stays good until its day is deleted. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Position { + pub file: String, + pub offset: u64, +} + /// How a call ended. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -111,20 +120,25 @@ impl Row { } } - /// Reads the two events of this call from the event log at `log`: one seek and one read of each - /// line's length. The log must be the file the offsets were taken from. + /// Reads the two events of this call from the event log's folder `log`: one seek and one read of each line's length + /// in its day file. An event whose day was deleted, or that names no file, reads as none. pub fn details(&self, log: &Path) -> io::Result
{ - let mut file = File::open(log)?; - let mut read = |at: Option| -> io::Result> { - let Some(at) = at else { return Ok(None) }; + let read = |at: &Option| -> io::Result> { + let Some(at) = at.as_ref().filter(|at| !at.file.is_empty()) else { + return Ok(None); + }; + let mut file = match File::open(log.join(&at.file)) { + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + file => file?, + }; file.seek(SeekFrom::Start(at.offset))?; let mut line = Vec::new(); - (&mut file).take(at.len).read_to_end(&mut line)?; + file.take(at.len).read_to_end(&mut line)?; Ok(serde_json::from_slice(&line).ok()) }; Ok(Details { - start: read(self.start)?, - end: read(self.end)?, + start: read(&self.start)?, + end: read(&self.end)?, }) } @@ -269,7 +283,7 @@ impl Ledger { let row = self.of(event, tool, turn); row.started_at = Some(at); row.take_roots(roots); - row.start = Some(event.line); + row.start = Some(event.line.clone()); row.settle(); row.turn } @@ -324,7 +338,7 @@ impl Ledger { row.ran = ran; row.background = task.is_some(); row.task = task; - row.end = Some(event.line); + row.end = Some(event.line.clone()); row.settle(); row.turn } diff --git a/core/src/lib.rs b/core/src/lib.rs index 4103509bb..14883a037 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -37,7 +37,7 @@ pub use codex::CAPABILITIES as CODEX_CAPABILITIES; pub use copilot::CAPABILITIES as COPILOT_CAPABILITIES; pub use cursor::CAPABILITIES as CURSOR_CAPABILITIES; pub use event::{Capabilities, TranscriptFormat}; -pub use ledger::{Bytes, Details, Ledger, Outcome, Row}; +pub use ledger::{Bytes, Details, Ledger, Outcome, Position, Row}; pub use notifications::{Due, Notification, Notifications, Sound}; pub use opencode::CAPABILITIES as OPENCODE_CAPABILITIES; pub use output::{ diff --git a/core/src/saved.rs b/core/src/saved.rs index 5c5b22d46..b046b28a6 100644 --- a/core/src/saved.rs +++ b/core/src/saved.rs @@ -4,15 +4,16 @@ //! except while `Studio::save` runs. The shell's own fields (its root lookup, its clock, its //! settings) are not saved. -use crate::Studio; +use crate::{Position, Studio}; use std::{cell::Cell, collections::BTreeMap, fmt}; /// The saved state's format. Bump it when a saved field changes meaning, the replay makes a saved /// field differently (11: a pasted prompt's turn line, #824; 12: `ended_stale`, #854; 13: planning, -/// the command's issue and Herdr's tags out of a turn's line, spec #967; 14: a round's block, #974), or a field the pane's JSON +/// the command's issue and Herdr's tags out of a turn's line, spec #967; 14: a round's block, #974; 15: positions in day +/// files, spec #1072), or a field the pane's JSON /// leaves out is added, so an older file is not read as the new shape and the first launch replays /// the whole log: a field the old file lacks makes it unreadable anyway, unless it has a default. -const FORMAT: u32 = 14; +const FORMAT: u32 = 15; thread_local! { static SAVING: Cell = const { Cell::new(false) }; @@ -36,19 +37,25 @@ impl Studio { saved } - /// Takes the state `save` made, for a launch about to replay the event log of `log_len` bytes: - /// returns the byte offset the replay goes on from. Saved state of another format, one that does - /// not read, or one beside a log shorter than it read, is ignored, and the replay starts from - /// 0. Call it on a new studio, before any replay; the shell's root lookup and its setting stay. - pub fn resume(&mut self, saved: &[u8], log_len: u64) -> u64 { - let Some(at) = saved.iter().position(|b| *b == b'\n') else { - return 0; - }; + /// Takes the state `save` made, for a launch about to replay the event log, whose day file of each name is + /// `file_len` bytes long, `None` when there is none: returns the position the replay goes on from. Saved state of + /// another format, one that does not read, or one whose day file is gone or shorter than its position, is ignored, + /// and `None` says the replay reads the whole log. Call it on a new studio, before any replay; the shell's root + /// lookup and its setting stay. + pub fn resume( + &mut self, + saved: &[u8], + file_len: impl Fn(&str) -> Option, + ) -> Option { + let at = saved.iter().position(|b| *b == b'\n')?; if saved[..at] != *format!("studio-state {FORMAT}").as_bytes() { - return 0; + return None; } + let fits = |end: &Position| { + !end.file.is_empty() && file_len(&end.file).is_some_and(|len| end.offset <= len) + }; match serde_json::from_slice::(&saved[at + 1..]) { - Ok(mut state) if state.log_end <= log_len => { + Ok(mut state) if fits(&state.log_end) => { state.roots = std::mem::take(&mut self.roots); state.summaries_on_open = self.summaries_on_open; state.check_lists = std::mem::take(&mut self.check_lists); @@ -59,9 +66,9 @@ impl Studio { } } *self = state; - self.log_end + Some(self.log_end.clone()) } - _ => 0, + _ => None, } } } diff --git a/core/src/studio.rs b/core/src/studio.rs index f1e94f75a..4318d58bc 100644 --- a/core/src/studio.rs +++ b/core/src/studio.rs @@ -13,9 +13,9 @@ pub use tasks::{BranchQuery, TaskFacts, TaskQuery}; use crate::{ AGY_CAPABILITIES, AgyDrift, AgyDriftKind, Bytes, CardRequest, Change, CheckLists, FactFile, - Facts, Fingerprint, Kind, LiveFacts, MIN_HISTORY, Outcome, Output, Purpose, RootDiff, Row, - Session, State, Status, Subagent, SubagentLog, SubagentLogFile, TranscriptFormat, TurnDiff, - TurnFiles, TurnFilesSnapshot, TurnTrees, Work, agy, checks, claude, cline, codex, + Facts, Fingerprint, Kind, LiveFacts, MIN_HISTORY, Outcome, Output, Position, Purpose, RootDiff, + Row, Session, State, Status, Subagent, SubagentLog, SubagentLogFile, TranscriptFormat, + TurnDiff, TurnFiles, TurnFilesSnapshot, TurnTrees, Work, agy, checks, claude, cline, codex, compute_turn_files, copilot, cursor, event::{Event, Happened, Start, ToolKind}, opencode, qwen, range, @@ -86,9 +86,9 @@ pub struct Studio { /// The commands that are checks, per project (danielrispler/plotkeeper#112), from the settings. #[serde(skip)] pub(crate) check_lists: CheckLists, - /// Where the next log line starts in the event log, in bytes: every line given to `replay`, - /// `apply` or `apply_with_changes` moves it, as the shell reads the log from its start. - pub(crate) log_end: u64, + /// Where the next log line starts in the event log: `next_file` sets its day file, and every line given to `replay`, + /// `apply` or `apply_with_changes` moves its offset, as the shell reads each day file from its start. + pub(crate) log_end: Position, /// How long each command of checks ran when it did not fail (danielrispler/Falinks#461, decision 13). pub(crate) durations: checks::Durations, /// The row of each session that continues another after a `/clear`, by its own id (danielrispler/Falinks#461, diff --git a/core/src/studio/replay.rs b/core/src/studio/replay.rs index 4eddcc51c..a2822163b 100644 --- a/core/src/studio/replay.rs +++ b/core/src/studio/replay.rs @@ -32,13 +32,14 @@ impl Studio { // A line's newline is not part of it; one the caller left off is counted all the same. let len = line.strip_suffix('\n').unwrap_or(line).len() as u64; let at = Bytes { - offset: self.log_end, + file: self.log_end.file.clone(), + offset: self.log_end.offset, len, }; - self.log_end += len + 1; + self.log_end.offset += len + 1; let mut outputs = Vec::new(); for mut event in events { - event.line = at; + event.line = at.clone(); outputs.extend(self.take_event(event, &mut changes, replay)); } outputs @@ -112,6 +113,14 @@ impl Studio { studio } + /// The lines given next are the event log's day file `file`'s, by its name, from its start. + pub fn next_file(&mut self, file: &str) { + self.log_end = Position { + file: file.into(), + offset: 0, + }; + } + /// Takes one event log line replayed at app start. It updates state exactly like `apply` and /// requests nothing, so turns that ended while the app was down get no summaries and no notices /// here. diff --git a/core/tests/ask_facts.rs b/core/tests/ask_facts.rs index a166b18c8..d36ba26bb 100644 --- a/core/tests/ask_facts.rs +++ b/core/tests/ask_facts.rs @@ -85,8 +85,8 @@ fn session() -> (Studio, std::path::PathBuf, tempfile::TempDir) { "npm run check", "Exit code 2\nline one\nerror: it broke", )); - let (log, dir) = logged(&lines); - (Studio::replayed(&lines), log, dir) + let (dir, studio) = crate::common::day_files(&[(DAY, &lines)]); + (studio, dir.path().to_owned(), dir) } fn labels(facts: &studio_core::AskFacts) -> Vec<&str> { @@ -221,14 +221,8 @@ fn a_files_facts_leave_out_another_worktrees_file_of_the_same_relative_path() { ); } -/// `lines` as the log file holds them, and a log file holding them. -fn logged(lines: &[String]) -> (std::path::PathBuf, tempfile::TempDir) { - let dir = tempfile::tempdir().unwrap(); - let log = dir.path().join("events.jsonl"); - let text: String = lines.iter().map(|l| format!("{l}\n")).collect(); - std::fs::write(&log, text).unwrap(); - (log, dir) -} +/// The day file the tests' lines are read as. +const DAY: &str = "2026-12-02.jsonl"; /// A Copilot CLI session in `/w/hello` whose one turn creates `hello.txt`. fn copilot_create() -> Vec { @@ -318,16 +312,14 @@ fn a_files_facts_list_every_agents_edit_as_a_step_that_edited_it() { ), ]; for (case, lines, session, (root, path), step) in cases { - let (log, _dir) = logged(&lines); + let (dir, studio) = crate::common::day_files(&[(DAY, &lines)]); let anchor = Anchor::File { turn: 0, root: root.into(), path: path.into(), from: None, }; - let facts = Studio::replayed(&lines) - .ask_facts(session, &anchor, &log) - .unwrap(); + let facts = studio.ask_facts(session, &anchor, dir.path()).unwrap(); let edited = facts .sections .iter() diff --git a/core/tests/common.rs b/core/tests/common.rs index b1789e19c..a123bc69e 100644 --- a/core/tests/common.rs +++ b/core/tests/common.rs @@ -94,6 +94,20 @@ pub(crate) fn apply_looking( /// A `.jsonl` file holding `contents`, deleted when the guard is dropped: keep it for as long as the test /// reads it. +/// An event log folder of the day files `files`, each a name and its lines, and a core that read them in order as the +/// read loop does. +pub(crate) fn day_files(files: &[(&str, &[String])]) -> (tempfile::TempDir, Studio) { + let dir = tempfile::tempdir().unwrap(); + let mut studio = Studio::default(); + for (name, lines) in files { + let text: String = lines.iter().map(|l| format!("{l}\n")).collect(); + std::fs::write(dir.path().join(name), text).unwrap(); + studio.next_file(name); + lines.iter().for_each(|l| studio.replay(l)); + } + (dir, studio) +} + pub(crate) fn temp_file(contents: &str) -> tempfile::NamedTempFile { let mut file = tempfile::Builder::new() .suffix(".jsonl") diff --git a/core/tests/ledger.rs b/core/tests/ledger.rs index a0798a522..619021391 100644 --- a/core/tests/ledger.rs +++ b/core/tests/ledger.rs @@ -48,7 +48,7 @@ fn log(lines: &[String]) -> Vec { .collect() } -fn bytes_of(file: &[u8], at: Bytes) -> &[u8] { +fn bytes_of<'a>(file: &'a [u8], at: &Bytes) -> &'a [u8] { &file[at.offset as usize..(at.offset + at.len) as usize] } @@ -161,7 +161,10 @@ fn a_rows_offsets_give_back_the_log_lines_it_came_from_after_a_replay() { assert!(!session.ledger.rows().is_empty()); for row in session.ledger.rows() { - let (start, end) = (row.start.expect("a start"), row.end.expect("an end")); + let (start, end) = ( + row.start.as_ref().expect("a start"), + row.end.as_ref().expect("an end"), + ); let text = |at| String::from_utf8(bytes_of(&file, at).to_vec()).unwrap(); let (start, end) = (text(start), text(end)); assert!( @@ -195,9 +198,18 @@ fn a_rows_offsets_hold_for_calls_followed_after_the_replay() { let second = &rows[1]; assert_eq!(second.call, "t2"); - assert_eq!(bytes_of(&file, second.start.unwrap()), lines[3].as_bytes()); - assert_eq!(bytes_of(&file, second.end.unwrap()), lines[4].as_bytes()); - assert_eq!(bytes_of(&file, rows[0].end.unwrap()), lines[2].as_bytes()); + assert_eq!( + bytes_of(&file, second.start.as_ref().unwrap()), + lines[3].as_bytes() + ); + assert_eq!( + bytes_of(&file, second.end.as_ref().unwrap()), + lines[4].as_bytes() + ); + assert_eq!( + bytes_of(&file, rows[0].end.as_ref().unwrap()), + lines[2].as_bytes() + ); } #[test] @@ -223,7 +235,9 @@ fn details_come_from_one_seek_and_one_read_of_the_rows_lines() { ), line("Stop", 3_000, json!({ "last_assistant_message": "done" })), ]; - let studio = Studio::replayed(&lines); + let mut studio = Studio::default(); + studio.next_file("2026-12-02.jsonl"); + lines.iter().for_each(|l| studio.replay(l)); let rows = rows(&studio); // Every other line is overwritten with filler of the same length. let mut file = log(&lines); @@ -234,8 +248,8 @@ fn details_come_from_one_seek_and_one_read_of_the_rows_lines() { } offset += l.len() + 1; } - let mut log = tempfile::NamedTempFile::new().unwrap(); - std::io::Write::write_all(&mut log, &file).unwrap(); + let log = tempfile::tempdir().unwrap(); + std::fs::write(log.path().join("2026-12-02.jsonl"), &file).unwrap(); let details = rows[1].details(log.path()).unwrap(); @@ -280,8 +294,14 @@ fn a_result_that_lands_before_its_start_is_one_row_with_both() { assert_eq!(rows.len(), 1); let file = log(&lines); - assert_eq!(bytes_of(&file, rows[0].end.unwrap()), lines[1].as_bytes()); - assert_eq!(bytes_of(&file, rows[0].start.unwrap()), lines[2].as_bytes()); + assert_eq!( + bytes_of(&file, rows[0].end.as_ref().unwrap()), + lines[1].as_bytes() + ); + assert_eq!( + bytes_of(&file, rows[0].start.as_ref().unwrap()), + lines[2].as_bytes() + ); assert_eq!(rows[0].started_at, Some(1_793_265_001_000)); assert_eq!(rows[0].outcome, Some(Outcome::Succeeded)); } @@ -301,7 +321,7 @@ fn an_agy_session_gets_rows_from_its_tool_events() { assert!(!rows.is_empty()); assert!(rows.iter().all(|r| r.turn.is_some() && !r.tool.is_empty())); for row in rows { - let at = row.end.or(row.start).expect("a line"); + let at = row.end.as_ref().or(row.start.as_ref()).expect("a line"); let text = std::str::from_utf8(bytes_of(&file, at)).unwrap(); assert!(serde_json::from_str::(text).is_ok(), "{text}"); } diff --git a/core/tests/record-subagent-run.sh b/core/tests/record-subagent-run.sh index 3870d6d3e..a971beed6 100755 --- a/core/tests/record-subagent-run.sh +++ b/core/tests/record-subagent-run.sh @@ -10,7 +10,7 @@ set -eu studio=$(cd "$(dirname "$0")/../.." && pwd) -log="$HOME/Library/Application Support/plotkeeper/events.jsonl" +log="$HOME/Library/Application Support/plotkeeper/events" session=$(uuidgen | tr '[:upper:]' '[:lower:]') repo=$(mktemp -d) trap 'rm -rf "$repo"' EXIT @@ -38,5 +38,5 @@ PROMPT # The hooks are async, so the last events may land just after `claude` exits. sleep 2 cd "$studio" -cargo run -q -p studio-core --bin scrub -- "$session" <"$log" >core/tests/fixtures/subagent-run.jsonl +cargo run -q -p studio-hook --example day_lines -- "$log" | cargo run -q -p studio-core --bin scrub -- "$session" >core/tests/fixtures/subagent-run.jsonl echo "Recorded session $session with Claude Code $(claude --version)" diff --git a/core/tests/run-unisolated-worker.sh b/core/tests/run-unisolated-worker.sh index f0ee0a1da..f762ee485 100755 --- a/core/tests/run-unisolated-worker.sh +++ b/core/tests/run-unisolated-worker.sh @@ -105,7 +105,7 @@ PROMPT echo "Session $session with Claude Code $(claude --version)" cd "$studio" -python3 - "$data/events.jsonl" "$session" "$repo" "$worktree" <<'PY' +python3 - "$data/events" "$session" "$repo" "$worktree" <<'PY' import json, subprocess, sys, time log, session, repo, worktree = sys.argv[1:] @@ -123,16 +123,18 @@ def shown(event): def read_events(): events = [] try: - with open(log) as f: - for line in f: - if session not in line: - continue - try: - event = json.loads(line) - except ValueError: - continue - if event.get("session_id") == session: - events.append(event) + # The day files in read order, from the one function that lists them; the script runs from the checkout. + lines = subprocess.run(["cargo", "run", "-q", "-p", "studio-hook", "--example", "day_lines", "--", log], + capture_output=True, text=True, errors="replace").stdout.splitlines() + for line in lines: + if session not in line: + continue + try: + event = json.loads(line) + except ValueError: + continue + if event.get("session_id") == session: + events.append(event) except OSError: pass return events diff --git a/core/tests/saved.rs b/core/tests/saved.rs index 4804d7ec1..d4d370ea8 100644 --- a/core/tests/saved.rs +++ b/core/tests/saved.rs @@ -2,7 +2,15 @@ //! replays only the log's tail, gives what a full replay of the log gives. use std::{fs, path::PathBuf}; -use studio_core::Studio; +use studio_core::{Position, Studio}; + +/// The day file the tests' logs are read as. +const DAY: &str = "2026-12-02.jsonl"; + +/// The length of `log` when `file` is the day file it is read as. +fn len_of(log: &str) -> impl Fn(&str) -> Option + '_ { + move |file| (file == DAY).then_some(log.len() as u64) +} /// Every recorded log of the tests: Claude Code's, agy's, Codex's, Qwen Code's, Cursor's, Copilot's, OpenCode's and Cline's, as the log file holds them, each line /// ending in a newline. @@ -38,6 +46,7 @@ fn file(lines: &[String]) -> String { fn replayed(file: &str) -> Studio { let mut studio = Studio::default(); + studio.next_file(DAY); file.split_inclusive('\n').for_each(|l| studio.replay(l)); studio } @@ -47,13 +56,17 @@ fn resumed(lines: &[String], at: usize) -> Studio { let saved = replayed(&file(&lines[..at])).save(); let log = file(lines); let mut studio = Studio::default(); - let from = studio.resume(&saved, log.len() as u64); + let from = studio.resume(&saved, len_of(&log)).expect("it reads"); + let offset = file(&lines[..at]).len(); assert_eq!( - from as usize, - file(&lines[..at]).len(), + from, + Position { + file: DAY.into(), + offset: offset as u64 + }, "it goes on from where the state stopped" ); - log[from as usize..] + log[offset..] .split_inclusive('\n') .for_each(|l| studio.replay(l)); studio @@ -130,18 +143,24 @@ fn a_launch_with_saved_state_gives_what_a_full_replay_gives() { } } +/// A state of another format, one that does not read, or one whose day file is gone or shorter than its position, is +/// ignored, and the replay reads the whole log. #[test] -fn saved_state_of_another_format_or_beside_a_shorter_log_is_ignored() { +fn saved_state_of_another_format_or_beside_a_shorter_or_missing_day_file_is_ignored() { let (_, lines) = fixtures() .into_iter() .find(|(n, _)| n.ends_with("subagent-run.jsonl")) .unwrap(); let log = file(&lines); let saved = replayed(&log).save(); - let again = |saved: &[u8], len: u64| { + let again = |saved: &[u8], len: Option| { let mut studio = Studio::default(); - assert_eq!(studio.resume(saved, len), 0); + assert_eq!( + studio.resume(saved, |file| len.filter(|_| file == DAY)), + None + ); // Nothing of it was taken, so a full replay from the start is the whole state. + studio.next_file(DAY); log.split_inclusive('\n').for_each(|l| studio.replay(l)); assert_eq!(format!("{studio:#?}"), format!("{:#?}", replayed(&log))); }; @@ -149,21 +168,25 @@ fn saved_state_of_another_format_or_beside_a_shorter_log_is_ignored() { let newline = saved.iter().position(|b| *b == b'\n').unwrap(); // Format 10 is the build's before #824, whose turns kept a pasted prompt's tag as their line; 12 the build's // before spec #967, with no planning state and Herdr's tags in its turns' lines; 13 the build's before #974, whose - // replay opened no block for a round's line. + // replay opened no block for a round's line; 14 the build's before the day files (spec #1072), whose positions were + // offsets in the one log file. + let len = Some(log.len() as u64); for format in [ "studio-state 0", "studio-state 10", "studio-state 12", "studio-state 13", + "studio-state 14", ] { let mut other_format = format.as_bytes().to_vec(); other_format.extend(&saved[newline..]); - again(&other_format, log.len() as u64); + again(&other_format, len); } - again(&with_terminals(&saved), log.len() as u64); - again(&saved, log.len() as u64 - 1); - again(&saved[..saved.len() / 2], log.len() as u64); - again(b"", log.len() as u64); + again(&with_terminals(&saved), len); + again(&saved, Some(log.len() as u64 - 1)); + again(&saved, None); + again(&saved[..saved.len() / 2], len); + again(b"", len); } /// The saved state `saved` as the build before #725 wrote it, format 8: the studio and its @@ -230,8 +253,8 @@ fn saved_state_before_the_project_folder_gives_each_session_the_project_of_its_s let old = without_projects(&replayed(log).save()); let mut studio = Studio::default(); assert_eq!( - studio.resume(&old, log.len() as u64), - log.len() as u64, + studio.resume(&old, len_of(log)).map(|at| at.offset), + Some(log.len() as u64), "it reads" ); diff --git a/core/tests/terminal.rs b/core/tests/terminal.rs index 520716e61..1f629b452 100644 --- a/core/tests/terminal.rs +++ b/core/tests/terminal.rs @@ -160,13 +160,15 @@ fn a_saved_state_keeps_the_terminal_and_one_from_before_reads_with_none() { ); let file: String = log.iter().map(|l| format!("{l}\n")).collect(); let mut replayed = Studio::default(); + replayed.next_file("2026-12-02.jsonl"); file.split_inclusive('\n').for_each(|l| replayed.replay(l)); let saved = replayed.save(); let resumed = |saved: &[u8]| { let mut studio = Studio::default(); + let len = |_: &str| Some(file.len() as u64); assert_eq!( - studio.resume(saved, file.len() as u64), - file.len() as u64, + studio.resume(saved, len).map(|at| at.offset), + Some(file.len() as u64), "it reads" ); terminal(&studio, common::FIRST) diff --git a/core/tests/turn_checks.rs b/core/tests/turn_checks.rs index a0a6d51d8..5bc475329 100644 --- a/core/tests/turn_checks.rs +++ b/core/tests/turn_checks.rs @@ -182,9 +182,12 @@ fn a_workers_check_counts_in_the_turn_that_spawned_it() { assert_eq!(turns[1].checks, []); } +/// A check's exit code and output tail are read through its row's position: its day file and the offset in it. A row in +/// a day the prune deleted reads no tail and no error. #[test] -fn a_checks_exit_code_and_output_tail_are_read_through_its_offset() { - let calls = [ +fn a_checks_exit_code_and_output_tail_are_read_through_its_position() { + let deleted = [vec![prompt()], passes(500, "t0", "cargo test", None)].concat(); + let kept = [ fails( 1_000, "t1", @@ -192,13 +195,21 @@ 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), - ]; - let mut lines = vec![prompt()]; - lines.extend(calls.concat()); - let text: String = lines.iter().map(|l| format!("{l}\n")).collect(); - let log = common::temp_file(&text); + ] + .concat(); + let today = [ + 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)), + ] + .concat(); + let (log, studio) = common::day_files(&[ + ("2026-11-01.jsonl", &deleted), + ("2026-12-01.jsonl", &kept), + ("2026-12-02.jsonl", &today), + ]); + std::fs::remove_file(log.path().join("2026-11-01.jsonl")).unwrap(); let log = log.path(); - let studio = Studio::replayed(&lines); let ledger = &studio.session(SESSION).unwrap().ledger; let failed = check_output(ledger.row(None, "t1").unwrap(), log).unwrap(); @@ -208,6 +219,29 @@ 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); + let gone = check_output(ledger.row(None, "t0").unwrap(), log).unwrap(); + assert_eq!(gone.tail, "", "a deleted day's row reads no tail"); + assert_eq!(gone.exit_code, Some(0)); +} + +fn numbered(from: usize, to: usize) -> String { + (from..=to) + .map(|n| format!("line {n}")) + .collect::>() + .join("\n") +} + +/// A passing Bash call whose stdout is `stdout`. +fn output_of(ms: u64, id: &str, stdout: &str) -> Vec { + 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. diff --git a/docs/agents/domain.md b/docs/agents/domain.md index 94524b96e..e63ad6aed 100644 --- a/docs/agents/domain.md +++ b/docs/agents/domain.md @@ -8,7 +8,7 @@ The studio, a control room for understanding agent work, keeps its vocabulary in Read `docs/studio/CONTEXT.md` and any ADRs relevant to the area you are exploring. If they do not exist, proceed silently. The domain-modeling skill creates them when terms or decisions are resolved. -To measure the real event log, use `~/Library/Application Support/plotkeeper/events.jsonl` on macOS, and on Linux `$XDG_DATA_HOME/plotkeeper/events.jsonl`, else `~/.local/share/plotkeeper/events.jsonl`. plotkeeper writes what it reports itself (errors, warnings, panics, and the page's log lines) to the stderr of the terminal it was started in; it keeps no log file. +To measure the real event log, use its day files, `events/YYYY-MM-DD.jsonl` (and a day's `YYYY-MM-DD.migrated.jsonl`, read before it), in `~/Library/Application Support/plotkeeper/` on macOS, and on Linux in `$XDG_DATA_HOME/plotkeeper/`, else `~/.local/share/plotkeeper/`. A day's files are deleted once it is more than 30 days old. plotkeeper writes what it reports itself (errors, warnings, panics, and the page's log lines) to the stderr of the terminal it was started in; it keeps no log file. ## Behaviour docs diff --git a/docs/studio/behaviour/storage.md b/docs/studio/behaviour/storage.md index 820b22582..a47a9cffd 100644 --- a/docs/studio/behaviour/storage.md +++ b/docs/studio/behaviour/storage.md @@ -6,9 +6,9 @@ plotkeeper keeps its data in one folder, the data folder: `~/Library/Application ## The event log -`~/Library/Application Support/plotkeeper/events.jsonl` (on Linux, `events.jsonl` in the data folder above), one hook payload per line, with added fields: +`~/Library/Application Support/plotkeeper/events/` (on Linux, `events/` in the data folder above), one file per UTC day, `YYYY-MM-DD.jsonl`, one hook payload per line (spec #1072). A day may also have a migrated part, `YYYY-MM-DD.migrated.jsonl`, which is read before its live file. The log is read day after day, each day's migrated part, then its live file. Each line has added fields: -- `studio_agent`: the agent its hook entry named (`--agent claude`, `--agent agy`, `--agent codex`, `--agent qwen`, `--agent cursor`, `--agent copilot`, `--agent opencode`, `--agent cline`), by which the core picks the line's parser and a prune finds its session (#355). A name plotkeeper has no parser for is counted as drift, not read as Claude's; a line with no name, written before entries named one or by the app, is read by its shape; +- `studio_agent`: the agent its hook entry named (`--agent claude`, `--agent agy`, `--agent codex`, `--agent qwen`, `--agent cursor`, `--agent copilot`, `--agent opencode`, `--agent cline`), by which the core picks the line's parser (#355). A name plotkeeper has no parser for is counted as drift, not read as Claude's; a line with no name, written before entries named one or by the app, is read by its shape; - `studio_event`: the event its hook entry named (`--event preToolUse`), for a payload that names none: Copilot's camelCase payloads (#361); - `studio_received_ms`: when the hook received the event, in Unix milliseconds. @@ -20,13 +20,13 @@ The data folder was `~/Library/Application Support/dev.falinks.studio/` before p The hooks are async, so Claude Code never waits for them, and they append whether the app runs or not. Two events that fire within a few milliseconds can land in either order. -`events.lock` beside the log is the log's lock (#811). Every writer of `events.jsonl` holds `events.lock` while it writes: the hook, the answer hook, and the app's own lines (`StudioRename`, `StudioDelete`, `StudioPromptName`, `StudioRound`, a `SessionEnd` with reason `process_gone` or `stale`). It takes the lock before it opens the log, and writes its lines in one write, so two writers never interleave their lines. A prune swaps the new log in only while holding it, so a writer always opens the log the last prune left. Readers take no lock, and nothing locks `events.jsonl` itself. A hook waits up to 5 seconds for the lock (a Codex or Cursor line 1 second) and otherwise drops its event to `drops.txt` beside the log; the app and a prune wait up to 60 seconds. The lock file is made on first use, so a data folder from before it needs no step, and its bytes mean nothing: it is never written, read, truncated, replaced or deleted. +`events.lock` beside the `events/` folder is the lock of all its day files (#811). Every writer of the log holds `events.lock` while it writes: the hook, the answer hook, and the app's own lines (`StudioRename`, `StudioDelete`, `StudioPromptName`, `StudioRound`, a `SessionEnd` with reason `process_gone` or `stale`). Once it holds the lock it picks the day from its own clock, in UTC, opens that day's file and writes its lines in one write, so two writers never interleave their lines, and the order the lock grants is the order of the files. A writer whose clock reads an earlier day than the newest day file writes to that newest file, so no line goes into a day once the next day's file exists. A prune deletes days only while holding it. Readers take no lock, and nothing locks a day file itself. A hook waits up to 5 seconds for the lock (a Codex or Cursor line 1 second) and otherwise drops its event to `drops.txt` beside the log; the app and a prune wait up to 60 seconds. The lock file is made on first use, so a data folder from before it needs no step, and its bytes mean nothing: it is never written, read, truncated, replaced or deleted. `turns/` beside the log keeps the hook's record of each session's latest turn, `.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. `.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. +It keeps a day's events until the day is more than 30 days before today (UTC): the prune then deletes the day's files, its live file and its migrated part. It runs at each start, before the saved state is taken, and again when the UTC day changes while the app runs. It moves no line and scans none, and it never deletes `studio-state.json`, the state the start's read made. The app saves it once a start, after reading the log, and the next start takes it and reads on from where it stopped, a day file and the offset in it, so a start reads only the lines since the previous one. A state whose day file is gone or shorter than its position, or one of another format, is refused, and that start reads the whole log. A ledger row whose day was deleted shows no output tail: details are read from a kept day only. A session still running after 30 days keeps its state; only its oldest lines' details are gone. Each session in the state 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. `events-archive.jsonl`, the archive of the per-session prune before the day files, is no longer written or read. The app also keeps `roots.json` beside the log: the git worktree root of each folder it has looked up, so a start runs `git` only for new folders. diff --git a/docs/studio/development.md b/docs/studio/development.md index 9cc2794f9..91b85f4c2 100644 --- a/docs/studio/development.md +++ b/docs/studio/development.md @@ -7,9 +7,9 @@ - `plugin-cursor/`: plotkeeper's entries for Cursor's user-level hook file (#362). `hooks.json` runs `plotkeeper-hook --agent cursor` on seven of Cursor's events that wait on no answer; `plotkeeper install` renders it with the data folder's `bin/` and adds its entries to `~/.cursor/hooks.json` beside the user's own ([install](plugin.md)). `core/src/cursor.rs` reads the lines. - `plugin-copilot/`: plotkeeper's plugin for Copilot, CLI and VS Code's agent (#361). `hooks.json` runs `plotkeeper-hook --agent copilot --event ` on seven of Copilot's camelCase events, whose payloads name no event; `plotkeeper install` renders it with the data folder's `bin/` and installs it with `copilot plugin install` ([install](plugin.md)). `core/src/copilot.rs` reads the lines, in either casing. - `plugin/`: the Claude Code plugin, which `plotkeeper install` renders with the data folder's `bin/` and installs with `claude plugin install` ([install](plugin.md)). On thirteen hook events, `SubagentStart` and `SubagentStop` among them, it runs `plotkeeper-hook`. On every `PermissionRequest`, it also runs `plotkeeper-answer`, synchronously, with a `timeout` of 1800 seconds. -- `hook/`: `plotkeeper-hook`, which appends each hook payload as one line to the event log, and the log's path; it also records each turn's and worker's trees and the worktree roots a call touched (`studio_touched_roots`), from the folders and paths the call names, the roots `git worktree list` gives and the roots it already knows; and `plotkeeper-answer`, the answer hook (danielrispler/Falinks#477, danielrispler/Falinks#478, #892): at a `PermissionRequest`, while Claude Code's dialog stays open, it leaves an ask per call in `asks//.json` and waits for an answer from the card and returns it: a question's `answers`, a plan's approval or rejection, a permission's allow or deny. A plan or a question waits while plotkeeper's server runs (the pid in `plotkeeper.running.json`), up to 29 minutes 50 seconds, and logs a `StudioWaitEnded` line when it gives up; another tool's permission waits only while the studio watches the asking session, up to 120 seconds. It logs a card's answer as a `StudioAnswer` line, which clears "needs you" for a plan or a permission at once. Otherwise it returns with no decision and the terminal's dialog decides. A Bash `PermissionDenied` it never waits on: the agent's own UI handles it (#572). +- `hook/`: `plotkeeper-hook`, which appends each hook payload as one line to the event log, into the file of the UTC day it picks under the log's lock, and the log's path, its day files in read order (`day_files`) and the day prune; it also records each turn's and worker's trees and the worktree roots a call touched (`studio_touched_roots`), from the folders and paths the call names, the roots `git worktree list` gives and the roots it already knows; and `plotkeeper-answer`, the answer hook (danielrispler/Falinks#477, danielrispler/Falinks#478, #892): at a `PermissionRequest`, while Claude Code's dialog stays open, it leaves an ask per call in `asks//.json` and waits for an answer from the card and returns it: a question's `answers`, a plan's approval or rejection, a permission's allow or deny. A plan or a question waits while plotkeeper's server runs (the pid in `plotkeeper.running.json`), up to 29 minutes 50 seconds, and logs a `StudioWaitEnded` line when it gives up; another tool's permission waits only while the studio watches the asking session, up to 120 seconds. It logs a card's answer as a `StudioAnswer` line, which clears "needs you" for a plan or a permission at once. Otherwise it returns with no decision and the terminal's dialog decides. A Bash `PermissionDenied` it never waits on: the agent's own UI handles it (#572). - Its files and trust boundary are in `hook/src/answer.rs`. -- `core/`: the studio core, plain Rust whose only I/O is reading the sessions' transcripts (`src/transcript.rs`, `.jsonl` files only), and `scrub`, which turns event log lines into test fixtures. At start the app takes the state its last start saved, `studio-state.json` beside the log, and replays only the log from where that state stopped, then feeds it each new line live; a pruned log, a state of another format or one that does not read means a replay from the start. It keeps the step ledger (`ledger`), the checks (`checks`: the statement parser, a run's worktree and exit code, running checks and checks sent to the background, the feed's checks, and the typical durations with the 2-minute rule: their recording, median and lookup, which `lib.rs` calls), each turn's files (`turn_files`) and the facts Ask shows (`ask`). The `Studio` type is in `src/studio.rs`, its methods by responsibility in `src/studio/`: `take` (one hook event), `roots` (worktree roots and fingerprints), `replay` (a log line applied or replayed), `turn_files` (the turns the shell diffs), `tasks` (what the shell found about each task and its PR) and `selection` (the session list, the selection and the subagent logs). +- `core/`: the studio core, plain Rust whose only I/O is reading the sessions' transcripts (`src/transcript.rs`, `.jsonl` files only), and `scrub`, which turns event log lines into test fixtures. At start the app takes the state its last start saved, `studio-state.json` beside the log, and replays only the log from where that state stopped, a day file and the offset in it, then feeds it each new line live; a state whose day file is gone or shorter than its position, a state of another format or one that does not read means a replay from the start. It keeps the step ledger (`ledger`), the checks (`checks`: the statement parser, a run's worktree and exit code, running checks and checks sent to the background, the feed's checks, and the typical durations with the 2-minute rule: their recording, median and lookup, which `lib.rs` calls), each turn's files (`turn_files`) and the facts Ask shows (`ask`). The `Studio` type is in `src/studio.rs`, its methods by responsibility in `src/studio/`: `take` (one hook event), `roots` (worktree roots and fingerprints), `replay` (a log line applied or replayed), `turn_files` (the turns the shell diffs), `tasks` (what the shell found about each task and its PR) and `selection` (the session list, the selection and the subagent logs). - Only live lines request cards and notifications. - `understanding/`: the understanding layer's I/O: the writer interface (turn summaries, goals, "Design so far", Ask, names and risk notes), the `claude -p` writer and the other CLI writers (agy, Codex, Copilot, Cursor) in `writer.rs`, the API-key writers' HTTP calls (`http_writer.rs`: Anthropic's API and an OpenAI-compatible one) and a fake, the worktree fingerprint, the card store with the briefs, the turn summaries, Turn writing (`turn_writing.rs`: what a turn's end and a worker's return write, on a queue for each session), which files are logic and which are tests (`logic_file.rs`), Claude Code's version kept beside the event log, and `weekly`, the command that prints the drift: unrecognised wake-ups and version changes. - `workbench/`: workbench git (danielrispler/Falinks#328, module 7): a folder's main checkout, `fetch` and what removing a task's worktree would lose; the `gh` to run; and agy's plugin. Its `run` module (`src/run.rs`, #548) is the one process runner: `git(dir)` and `gh(dir)` build every `git` and `gh` the workspace starts, with `--no-optional-locks`, `GIT_TERMINAL_PROMPT=0`, `GH_PROMPT_DISABLED=1` and no input, and a caller adds its own arguments; `run_until(command, deadline)` runs a command in a process group of its own (on Windows a Job Object) and kills the group at the deadline, leaving alone what it left running after a clean exit, and its `RunError` tells apart a command that did not start, one that timed out and one that exited non-zero; `run_logged(command, deadline, given_up)` does the same for a command whose output goes to a file, gives its exit status, and also kills what it left in its group when it exits (#568). On Windows `run_logged` starts nothing and returns `RunError::Start`, as its callers are refused there. A new `git` or `gh` call uses both, with its deadline a named constant beside it: 30 s for a lookup or a read, 120 s for a fetch. Every wait on a child with a deadline goes through the runner: the launcher's check, setup and harness and the micro-world checks too (#568). A command streamed into another program (the hook's untracked-file listing, `git archive` into `tar`) is built by the runner and waited on by its caller. What only its own tests used is in `archive/workbench/` (#415). @@ -22,7 +22,7 @@ `cargo test` runs: - `core/tests/`: hook events replayed through the core: what the pane shows and the two recorded logs (`replay`), the session list, its states and the selection on the recorded day (`sessions`), needs you (`needs_you`), the subagent tree, workers and helpers, their status, end and fading, and the waits they raise on their session (`subagents`), agents' questions, who asks them and their answers (`questions`), notifications: their triggers, text and combining (`notices`), the change requests at `Stop`, the prompt each belongs to, the `Stop` a row tells about, where the shell fingerprints, and the recorded worker's requests at its commit and its end, a session's touch of a running worker's home, and a worktree root a hook lists (`cards`), and wake-ups, the needs you a wake-up leaves in place and the ask for Claude Code's version (`wake_ups`); the step ledger's rows, offsets and details, workers' included, and the roots a call's start and end touched (`ledger`); a turn's files from its two trees, and the checks of the project's list: what runs one, each statement of a command a run of its own, its worktree, when its exit code counts in a chain, last run, retries, `ran`, a running or background check and its notification, and the same checks on a log that arrives live (`turn_checks`), the checks the feed lists with their typical durations (`check_feed`), the files another session's command names by path boundaries, the homes of a turn's workers, a worker spawned in an earlier turn included, and a Codex `apply_patch` and a Cursor `Delete` keeping their file from another session's edit (`turn_files`); the recorded facts Ask shows for each anchor (`ask_facts`); and the saved state, a restored studio compared with a full replay field by field, a state of another format replayed from the start, and an older log's terminal fields ignored (`saved`); every fixture file's row in `fixtures/PROVENANCE.md`, a source that says real, hand-built or unknown, and no row for a missing file (`fixtures_provenance`); -- `understanding/tests/`: the `claude -p` commands for a Goal, built but never run, the `claude` lookup with a stand-in shell, the writer's replies, summaries with their Headline, typed lines and grounding, its retry, and a name request saying "here" is the session's folder, not the writer's (`writer`); the fingerprint against real `git` in temporary repositories, a worktree's creation counted from a turn's or worker's own start, the root cache's prune and a removed worktree's path (`fingerprint`); the core, the fingerprint, `git diff --stat`, a fake writer and the card store joined through Turn writing, its jobs run in order on the test's thread: a turn's end writing its summary and its Goal and no card, a code-only turn with a short reply getting no summary and its row showing the reply's first line, a summary kept for opening, written once and returned before Design so far, a failed write parked again, a session deleted while its job waited, workers and prompts read when the job runs, every entry point returning against a core with no such turn, and one thread for a session's queue that ends with its last job; and a Goal written only when your prompt count changes, each case of a row's line, a worker's brief in its own worktree, a killed worker's Goal at its wake-up, a wake-up's turn, and a helper made a worker by its command, and not by others' changes before it (`turn_writing`); the card store, the briefs, the decision history, the live facts, its move aside and the summaries (`store`); the seven files the card store opens at start, each frozen in a full and a minimal-fields sample that today's code must load, with the loaded values asserted, a check's runs among them, and the risk notes' file in its own `full-2` and `minimal-2` samples, which also freeze its key's hash (`stored_fixtures`; never edit a sample, see `understanding/tests/fixtures/stored/README.md`); the risk note's judge: its command built and never run, the command fenced as data with the folder and never the agent's words, its own 15-second limit with the writer's others kept, a canned reply read into each of the six levels, and an unreadable reply or a timeout a failure (`writer`); the risk notes' store: kept across a reopen, one note for a card whose call id changed and for two cards of one command and folder, a failure not kept, asked once per run and never for an ended session or a card with no button, a corrupt file opening empty, and the judge run with the store unlocked (`store`); the version read from a transcript, its notice and `weekly`'s drift lines (`drift`); the Brief's slots and "Design so far" with its citations (`brief`); the model's answers grounded on Ask's facts (`ask`); a turn's trees and hunks, also after `git gc`, and the reads of a turn's files with the core unlocked (`diff_turn`, `found_files`, `turn_facts`, in `understanding/src/turn_trees.rs`, which the shell's turn-files pass and Turn writing both call), with the oversized-turn warning and its settling (`turn_trees`); and the saved state with the card store (`saved_state`); +- `understanding/tests/`: the `claude -p` commands for a Goal, built but never run, the `claude` lookup with a stand-in shell, the writer's replies, summaries with their Headline, typed lines and grounding, its retry, and a name request saying "here" is the session's folder, not the writer's (`writer`); the fingerprint against real `git` in temporary repositories, a worktree's creation counted from a turn's or worker's own start, the root cache's prune and a removed worktree's path (`fingerprint`); the core, the fingerprint, `git diff --stat`, a fake writer and the card store joined through Turn writing, its jobs run in order on the test's thread: a turn's end writing its summary and its Goal and no card, a code-only turn with a short reply getting no summary and its row showing the reply's first line, a summary kept for opening, written once and returned before Design so far, a failed write parked again, a session deleted while its job waited, workers and prompts read when the job runs, every entry point returning against a core with no such turn, and one thread for a session's queue that ends with its last job; and a Goal written only when your prompt count changes, each case of a row's line, a worker's brief in its own worktree, a killed worker's Goal at its wake-up, a wake-up's turn, and a helper made a worker by its command, and not by others' changes before it (`turn_writing`); the card store, the briefs, the decision history, the live facts, its move aside and the summaries (`store`); the seven files the card store opens at start, each frozen in a full and a minimal-fields sample that today's code must load, with the loaded values asserted, a check's runs among them, and the risk notes' file in its own `full-2` and `minimal-2` samples, which also freeze its key's hash (`stored_fixtures`; never edit a sample, see `understanding/tests/fixtures/stored/README.md`); the risk note's judge: its command built and never run, the command fenced as data with the folder and never the agent's words, its own 15-second limit with the writer's others kept, a canned reply read into each of the six levels, and an unreadable reply or a timeout a failure (`writer`); the risk notes' store: kept across a reopen, one note for a card whose call id changed and for two cards of one command and folder, a failure not kept, asked once per run and never for an ended session or a card with no button, a corrupt file opening empty, and the judge run with the store unlocked (`store`); the version read from a transcript, its notice and `weekly`'s drift lines (`drift`); the Brief's slots and "Design so far" with its citations (`brief`); the model's answers grounded on Ask's facts (`ask`); a turn's trees and hunks, also after `git gc`, and the reads of a turn's files with the core unlocked (`diff_turn`, `found_files`, `turn_facts`, in `understanding/src/turn_trees.rs`, which the shell's turn-files pass and Turn writing both call), with the oversized-turn warning and its settling (`turn_trees`); and the saved state kept by a prune of whole days, each row of a kept day reading its details and a row of a deleted day none (`saved_state`); - `workbench/tests/`: against real `git` in temporary repositories, `fetch` (`fetch.rs`) and what removing a task's worktree would lose, with no code path passing git's force option (`tasks.rs`); agy's plugin (`agy_plugin.rs`); and the runner (`run.rs`): a fake `git` and `gh` that print how they were started, a deadline that kills a command and the helper it started, `RunError`'s three kinds, and a search of the workspace's sources that fails when a `git` or `gh` is built outside the runner (`archive/`, `tests/` folders, `test-support/` and a file's own test module aside); - `system-map/tests/`: the library's two entry points and the binary, on temporary git repositories the tests build (also the lenient parser that the Map view reads with, and the law tags' resolver that tells which test follows each `@law` tag): each failure of the check with a repository that causes it and one that does not, ownership (the last match winning, `ignored` winning, the three pattern forms) through `touched`, which still answers a map over a cap, law tags, each extractor on a small tree, a link's kind and reason and the pass line's counts of proven and unproven import links (`edges.rs`), a part's purpose and held items, their caps and messages, and a version 1 map's conversion (`parts.rs`), the imports' counts, hubs and the `imports` command (`imports.rs`), and the binary's exit status, output and `--json`; and the free scan over small fixture repositories (`scan.rs`: the step into the folder holding most of the code, manifests and Go `main` packages, loose files and tests, the reference-copy candidates and which are ticked, the cap of 15); - the unit tests of `system-map/src/extract/`: the contract cases each registered extractor runs through its fixture kit (the anchor case, a file that is not UTF-8, a missing and a malformed config, each skipped case printing its reason), and the core's rules on fake extractors (untracked and self pairs dropped, duplicates kept once with their lowest line, ignored files, declaration pairs, problem order); @@ -33,7 +33,7 @@ - `core/tests/blocked_commands.rs`: blocked commands replayed through the core: the command's fields, block order, a subagent's block, needs you until the session moves on (the agent's next call, Daniel's next prompt, a subagent's end, not the turn's end), which blocks count as waiting, and an older log's Allow, Decline, decision and retry. - `hook/tests/named_roots.rs`: the hook binary in a scratch `HOME` and a temporary repository with a second worktree: the roots a Bash call names and touches, the deepest root on a path boundary, a worktree an earlier command made, a removed worktree's folder (by path or as the event's folder) touching nothing, a new folder in a listed one touching it, a known root not listed again, and a worktree made mid-turn starting from its creation commit; - `hook/tests/harness_trees.rs`: the hook binary in a scratch `HOME` and a temporary repository fed wave 1's trial lines of a Codex and a Cursor turn and a real OpenCode turn, each recording its worktree's start and end trees, which differ by the file it changed; OpenCode turns whose hooks run at once and out of order, their appends waiting on the log's lock together, each listing their own edit once the core replays the log; a Cursor turn writing in its second workspace root listing the file, a Cursor prompt starting every workspace root but touching only its folder's, a Cursor `Shell` call touching the folder its input names, a Cursor line logged in time while `git` hangs, and a Cursor prompt's trees given up past the budget leaving the worktree's start to the turn's next touch; -- `hook/tests/agents.rs`: the agent a hook entry names stored on the line, and another harness's payload dropped by the Claude entry and recorded once by its own; `hook/tests/names.rs`: every name a user sees says plotkeeper; `hook/tests/prune.rs`: the two heavy fields left out and the ended sessions' archive, each session's lines kept together by its agent's own id, and the log's lock, `events.lock` (a line waiting through a swap landing in the new log, a held lock leaving the log readable and an append waiting or giving up, whole lines from threads at once, the lock file made on first use, a prune's tail copy, and no file but the log code naming the log and opening a file to write); +- `hook/tests/agents.rs`: the agent a hook entry names stored on the line, and another harness's payload dropped by the Claude entry and recorded once by its own; `hook/tests/names.rs`: every name a user sees says plotkeeper; `hook/tests/prune.rs`: what the hook leaves out of a line and a command's output cut to its tail, appends on either side of a UTC midnight landing in their days' files in lock order, the prune deleting the days more than 30 days old and nothing else, and the log's lock, `events.lock` (a line waiting for the lock picking its day once it holds it, a held lock leaving the log readable and an append waiting or giving up, whole lines from threads at once, the lock file made on first use, a prune deleting days only while it holds the lock, and no file but the log code naming the log, its `events/` folder or a day file and opening a file to write); - `server/tests/runner.rs`: the background runner with a fake harness that is a real child process, a shell script run through the real launcher: a run's result, cost, exit and record, denials in a 0 exit, a failed run's prompt, a refused run (no harness, no `checks`), `checks` and `setup` read for each run, one run at a time per project, a run picked up after a restart, a dead run failed live and at a start, Cancel killing the group and removing the folder and refusing a process whose start time differs, Cancel of a run that ends at that moment, the pause on a login or limit failure and Resume, the time limit, the cores, an orphaned folder, a running run a start cannot read left alone, a queued run never started beside a running one, a refusal that removes nothing but a new run's folder, a finished run's stray children stopped, standard input closed and the command's removed variables, a pause told to every project, the page's two commands, and the `claude` command, sandbox block and allow list as built, never run; - `server/tests/back_a_law.rs`: Back a law end to end against a temporary repository with a bare `origin`, a fake agent run by the real launcher, a fake `srt` that runs its command as it is and a recorded `gh`: the clone of the default branch with no remote, a well-formed run proven and kept with Daniel's repository untouched byte for byte, each rejection (no test patch, a test patch outside its scope, a plant that edits the test or breaks the build, a red run that does not name the new test, a test that fails alone, a law left on trust), Discard, the prompt's text, a missing `srt` copying the prompt, a proof with no home folder or with a settings file that cannot be written rejected before `srt` starts, Dismiss refused while the proof runs, a proof plotkeeper stopped in rejected at the next start, Open draft PR from a temporary worktree (its branch, body and ratify record), a retry after `gh` failed past the push, Daniel's other worktrees left alone, an out-of-date patch, and the new-law variant (the writer's draft, the confirmed sentence alone in the prompt, its proof and PR); - `server/tests/micro_worlds.rs`: micro-worlds with the real launcher, a fake harness that writes the page and the fake dsh-visual (`tests/fake-dsh-visual/`): a flow's topic, a checked page stored and served with its policy first, a failing page never served, rewritten once and then falling back to the prompt to copy, no run without `microWorlds.dshVisual`, out of date and Rebuild, Dismiss refused while the host check runs, a check plotkeeper stopped in failing with why at the next start, and a folder of its own for each project; diff --git a/hook/examples/day_lines.rs b/hook/examples/day_lines.rs new file mode 100644 index 000000000..872f48884 --- /dev/null +++ b/hook/examples/day_lines.rs @@ -0,0 +1,12 @@ +//! Prints the lines of an event log's day files in read order, for the shell scripts that read the log +//! (spec #1072): `cargo run -q -p studio-hook --example day_lines -- `. + +use std::io::Write; + +fn main() { + let log = std::env::args_os().nth(1).expect("the events folder"); + let mut out = std::io::stdout().lock(); + for line in studio_hook::day_lines(log.as_ref()).expect("read the event log") { + writeln!(out, "{line}").expect("write the line"); + } +} diff --git a/hook/src/lib.rs b/hook/src/lib.rs index 134628ef9..c05358be7 100644 --- a/hook/src/lib.rs +++ b/hook/src/lib.rs @@ -1,4 +1,5 @@ -//! The event log (danielrispler/Falinks#328, module 2): one append-only JSON Lines file, the only source of session state. +//! The event log (danielrispler/Falinks#328, module 2): append-only JSON Lines, one file per UTC day (spec #1072), the only +//! source of session state. pub mod answer; pub mod rollout; @@ -96,18 +97,67 @@ pub const HOOK_BINARIES: [&str; 2] = if cfg!(windows) { ["plotkeeper-hook", "plotkeeper-answer"] }; -/// The log in the studio's data directory. The hook writes it; the app reads it. +/// The event log in the studio's data directory: the folder of its day files. The hook writes it; the app reads it. pub fn event_log(home: &Path) -> PathBuf { event_log_in(&data_dir(home)) } -/// The log in the data folder `data`. +/// The event log in the data folder `data`. pub fn event_log_in(data: &Path) -> PathBuf { data.join(EVENT_LOG) } -/// The event log's name in the data folder. -pub const EVENT_LOG: &str = "events.jsonl"; +/// The event log's folder in the data folder: one file of lines per UTC day, `YYYY-MM-DD.jsonl`, and for a day before +/// the day files a migrated part, `YYYY-MM-DD.migrated.jsonl`, read before it (spec #1072, "Day files"). +pub const EVENT_LOG: &str = "events"; + +/// The ends of a day's live file's name and of its migrated part's. +const LIVE: &str = ".jsonl"; +const MIGRATED: &str = ".migrated.jsonl"; + +/// A day file's place in the read order, by its name: its UTC day, then its migrated part before its live file. `None` +/// for a name that is no day file's. +fn day_of(name: &str) -> Option<(&str, bool)> { + let (day, live) = match name.strip_suffix(MIGRATED) { + Some(day) => (day, false), + None => (name.strip_suffix(LIVE)?, true), + }; + let dated = day.len() == 10 + && day.bytes().enumerate().all(|(i, b)| match i { + 4 | 7 => b == b'-', + _ => b.is_ascii_digit(), + }); + dated.then_some((day, live)) +} + +/// The day files of the event log `log`, in read order: day after day, each day's migrated part before its live file. +/// No folder gives none; a file of another name is left out. +pub fn day_files(log: &Path) -> io::Result> { + let entries = match fs::read_dir(log) { + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + entries => entries?, + }; + let mut files = Vec::new(); + for entry in entries { + let name = entry?.file_name(); + if let Some((day, live)) = name.to_str().and_then(day_of) { + files.push(((day.to_owned(), live), log.join(&name))); + } + } + files.sort(); + Ok(files.into_iter().map(|(_, file)| file).collect()) +} + +/// The lines of the event log `log`'s day files, in `day_files`' order, for a tool that reads the whole log by path. A +/// file that cannot be read gives no lines; a line that is not UTF-8 is read lossily. +pub fn day_lines(log: &Path) -> io::Result> { + let mut lines = Vec::new(); + for file in day_files(log)? { + let Ok(bytes) = fs::read(&file) else { continue }; + lines.extend(String::from_utf8_lossy(&bytes).lines().map(str::to_owned)); + } + Ok(lines) +} /// How long the hook waits for the log's lock before it drops the event (#43, decision 11). pub const PATIENCE: Duration = Duration::from_secs(5); @@ -118,9 +168,9 @@ pub fn drops_file(log: &Path) -> PathBuf { log.with_file_name("drops.txt") } -/// The event log's lock beside the log `log`, `events.lock`, which every writer of the log holds while it writes and a -/// prune holds while it puts a new log in the old one's place. Its bytes mean nothing: it is never written, read, -/// truncated, replaced or deleted, and no reader takes it, so the log itself is never locked. +/// The event log's lock beside the log `log`, `events.lock`, the one lock of all its day files: every writer of the log +/// holds it while it picks its day and writes, and a prune while it deletes days. Its bytes mean nothing: it is never +/// written, read, truncated, replaced or deleted, and no reader takes it, so the log itself is never locked. pub fn lock_file(log: &Path) -> PathBuf { log.with_file_name("events.lock") } @@ -129,10 +179,20 @@ pub fn lock_file(log: &Path) -> PathBuf { /// that fire together never interleave their lines. Waits up to `patience` for the lock; returns /// `false`, having written nothing, when it never came. pub fn append(log: &Path, event: &serde_json::Value, patience: Duration) -> std::io::Result { + append_at(log, event, patience, &studio_workbench::clock::now_ms) +} + +/// [`append`] with the clock that picks the day, in Unix milliseconds, for a test. +pub fn append_at( + log: &Path, + event: &serde_json::Value, + patience: Duration, + clock: &dyn Fn() -> u64, +) -> std::io::Result { use std::io::Write; let mut line = serde_json::to_vec(event)?; line.push(b'\n'); - let Some(mut log) = locked(log, patience)? else { + let Some(mut log) = locked_at(log, patience, clock)? else { return Ok(false); }; log.write_all(&line)?; @@ -155,15 +215,34 @@ impl std::io::Write for Locked { } } -/// The log at `log`, open to append under the log's lock, which it waits up to `patience` for; -/// `None` when the lock never came. A prune puts a new file in the log's place only while it holds -/// the lock (danielrispler/plotkeeper#132), and the log is opened after the lock is taken, so it is -/// always the one the last prune left. +/// The day file of the log `log` to append to, open under the log's lock, which it waits up to `patience` for; `None` +/// when the lock never came. The day is picked once the lock is held, so the order the lock grants is the order of the +/// files: today's by the clock, in UTC, or a later day's whose file is already there, so no line goes into a day once +/// the next day's file exists. pub fn locked(log: &Path, patience: Duration) -> std::io::Result> { + locked_at(log, patience, &studio_workbench::clock::now_ms) +} + +/// [`locked`] with the clock that picks the day, in Unix milliseconds. +fn locked_at( + log: &Path, + patience: Duration, + clock: &dyn Fn() -> u64, +) -> std::io::Result> { let Some(lock) = hold(log, patience)? else { return Ok(None); }; - let log = fs::OpenOptions::new().create(true).append(true).open(log)?; + fs::create_dir_all(log)?; + let today = studio_workbench::clock::utc_date(clock()); + let newest = day_files(log)? + .last() + .and_then(|file| Some(day_of(file.file_name()?.to_str()?)?.0.to_owned())); + let day = newest.filter(|newest| *newest > today).unwrap_or(today); + let file = log.join(format!("{day}{LIVE}")); + let log = fs::OpenOptions::new() + .create(true) + .append(true) + .open(file)?; Ok(Some(Locked { log, _lock: lock })) } @@ -190,10 +269,11 @@ fn hold(log: &Path, patience: Duration) -> std::io::Result> { } } -/// 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"); @@ -204,186 +284,79 @@ 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 } -/// 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); +/// 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) +} -/// The archive beside the log `log`, which a prune appends to and a launch never replays. -pub fn archive_file(log: &Path) -> PathBuf { - log.with_file_name("events-archive.jsonl") +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 } -/// The state a replay of the log made, beside the log `log` (danielrispler/plotkeeper#134), which a -/// prune removes: it moves lines, so the byte offsets the state holds point elsewhere. +/// How long a day's events stay in the log: a day's files go once the day is more than this before today. +pub const KEEP: Duration = Duration::from_secs(30 * 24 * 60 * 60); + +/// The state a replay of the log made, beside the log `log` (danielrispler/plotkeeper#134). pub fn state_file(log: &Path) -> PathBuf { log.with_file_name("studio-state.json") } -/// What a prune did: the lines it moved to the archive, and the kept lines it lightened. -#[derive(Debug, Default, PartialEq)] -pub struct Pruned { - pub archived: usize, - pub lightened: usize, -} - -/// What a prune reads of a line: its session, by `session_id` (Claude Code's, Codex's and Qwen Code's), agy's -/// `conversationId`, Cursor's `conversation_id` or Copilot's camelCase `sessionId`, the agent its hook entry -/// named, and when it was received. -#[derive(Default, serde::Deserialize)] -struct Stamp { - session_id: Option, - #[serde(rename = "conversationId")] - conversation_id: Option, - /// Cursor's session (#362). - #[serde(rename = "conversation_id")] - cursor_conversation: Option, - /// Copilot's session, in its camelCase payloads (#361). - #[serde(rename = "sessionId")] - copilot_session: Option, - studio_agent: Option, - studio_received_ms: Option, -} - -impl Stamp { - fn of(line: &[u8]) -> Self { - serde_json::from_slice(line).unwrap_or_default() - } - - /// The session id the line's agent uses (#355); a line that names no agent, written before - /// entries named one or by the server, goes by whichever id it has. - fn session(&self) -> Option<&str> { - let (claude, agy) = (self.session_id.as_deref(), self.conversation_id.as_deref()); - match self.studio_agent.as_deref() { - Some("agy") => agy, - Some("claude" | "codex" | "qwen") => claude, - Some("cursor") => self.cursor_conversation.as_deref(), - Some("copilot") => claude.or(self.copilot_session.as_deref()), - _ => claude.or(agy), - } - } -} - -/// Moves to the archive the lines of each session whose last event was received more than `KEEP` -/// before `now`, in Unix milliseconds, and lightens the lines it keeps (danielrispler/plotkeeper#132). -/// A line of no session goes by its own time; a line with no time stays. A log whose first line is -/// recent is left as it is, so most launches read one line. The new log takes the old one's place -/// under the log's lock, with the lines hooks appended meanwhile. -pub fn prune(log: &Path, now: u64) -> std::io::Result { - use std::{ - collections::HashMap, - io::{self, BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write}, - }; - let cutoff = now.saturating_sub(KEEP.as_millis() as u64); - let file = match fs::File::open(log) { - Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Pruned::default()), - file => file?, - }; - let mut first = Vec::new(); - BufReader::new(&file).read_until(b'\n', &mut first)?; - if Stamp::of(&first) - .studio_received_ms - .is_some_and(|at| at >= cutoff) - { - return Ok(Pruned::default()); - } - // Calls `each` with each whole line up to `end`, and returns the bytes they hold: a line a hook - // is still writing waits for the tail. - let lines = |end: u64, each: &mut dyn FnMut(&[u8]) -> io::Result<()>| -> io::Result { - let mut reader = BufReader::new(fs::File::open(log)?.take(end)); - let (mut line, mut read) = (Vec::new(), 0); - while reader.read_until(b'\n', &mut line)? > 0 && line.ends_with(b"\n") { - read += line.len() as u64; - each(&line)?; - line.clear(); - } - Ok(read) - }; - let mut last = HashMap::::new(); - let end = lines(u64::MAX, &mut |line| { - let stamp = Stamp::of(line); - if let (Some(session), Some(at)) = (stamp.session(), stamp.studio_received_ms) { - let last = last.entry(session.into()).or_default(); - *last = (*last).max(at); - } - Ok(()) - })?; - let name = log.file_name().unwrap_or_default().to_string_lossy(); - let next = log.with_file_name(format!("{name}.next")); - let mut kept = BufWriter::new(fs::File::create(&next)?); - let mut archived = Vec::new(); - let mut pruned = Pruned::default(); - lines(end, &mut |line| { - let stamp = Stamp::of(line); - let session = stamp.session().and_then(|s| last.get(s)); - if session - .copied() - .or(stamp.studio_received_ms) - .is_some_and(|at| at < cutoff) - { - archived.extend_from_slice(line); - pruned.archived += 1; - } else if let Some(light) = lightened(line) { - kept.write_all(&light)?; - pruned.lightened += 1; - } else { - kept.write_all(line)?; +/// Deletes the files of each day of the log `log`, its live file and its migrated part, once the day is more than +/// [`KEEP`] before `now`'s UTC day, `now` in Unix milliseconds, under the log's lock (spec #1072, "The prune"). It moves +/// no line, so the saved state's positions in the days it keeps stay good, and it never deletes the state. Returns the +/// files it deleted. +pub fn prune(log: &Path, now: u64) -> io::Result> { + let cutoff = studio_workbench::clock::utc_date(now.saturating_sub(KEEP.as_millis() as u64)); + let _held = hold(log, Duration::from_secs(60))?.ok_or(io::ErrorKind::TimedOut)?; + let mut deleted = Vec::new(); + for file in day_files(log)? { + let day = file + .file_name() + .and_then(|n| Some(day_of(n.to_str()?)?.0.to_owned())); + if day.is_some_and(|day| day < cutoff) { + match fs::remove_file(&file) { + Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e), + _ => deleted.push(file), + } } - Ok(()) - })?; - if pruned == Pruned::default() { - fs::remove_file(&next)?; - return Ok(pruned); - } - // The archive first: a failure after it leaves a line in both files, never in neither. - if !archived.is_empty() { - let mut archive = fs::OpenOptions::new() - .create(true) - .append(true) - .open(archive_file(log))?; - archive.write_all(&archived)?; - archive.sync_all()?; - } - let held = hold(log, Duration::from_secs(60))?.ok_or(io::ErrorKind::TimedOut)?; - // Writers only append, so a log shorter than the bytes read was replaced, which only another prune - // could do. - if fs::metadata(log)?.len() < end { - fs::remove_file(&next)?; - return Err(io::Error::other("the log was replaced during the prune")); - } - let mut tail = fs::File::open(log)?; - tail.seek(SeekFrom::Start(end))?; - io::copy(&mut tail, &mut kept)?; - let kept = kept.into_inner().map_err(io::IntoInnerError::into_error)?; - kept.sync_all()?; - // Before the new log takes the old one's place: a failure between the two leaves no state, never - // a state beside a log it does not fit. - match fs::remove_file(state_file(log)) { - Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e), - _ => {} - } - fs::rename(&next, log)?; - drop(held); - Ok(pruned) -} - -/// Line `line` lightened, `None` when it has nothing to leave out. -fn lightened(line: &[u8]) -> Option> { - let has = |text: &[u8]| line.windows(text.len()).any(|w| w == text); - if !has(b"\"originalFile\"") && !has(b"\"content\"") { - return None; - } - let mut event = serde_json::from_slice(line).ok()?; - if !lighten(&mut event) { - return None; } - let mut light = serde_json::to_vec(&event).ok()?; - light.push(b'\n'); - Some(light) + Ok(deleted) } /// Notes in the drops file beside `log` that the hook dropped `event` at `at`, in Unix milliseconds, diff --git a/hook/tests/agents.rs b/hook/tests/agents.rs index 9775d7a42..89d3a5d93 100644 --- a/hook/tests/agents.rs +++ b/hook/tests/agents.rs @@ -10,7 +10,7 @@ fn logged(args: &[&str], payload: Value, name: &str) -> Value { let mut cmd = hook(&home); cmd.args(args).stdout(Stdio::null()); assert!(feed(cmd, &payload).wait().unwrap().success()); - let text = fs::read_to_string(studio_hook::event_log(&home)).unwrap(); + let text = crate::common::logged_text(&studio_hook::event_log(&home)); serde_json::from_str(text.lines().next().unwrap()).unwrap() } @@ -98,7 +98,7 @@ fn a_cursor_payload_is_dropped_by_the_claude_entry_and_recorded_once_by_cursors( assert!(out.status.success()); stderrs.push(String::from_utf8(out.stderr).unwrap()); } - let text = fs::read_to_string(studio_hook::event_log(&home)).unwrap(); + let text = crate::common::logged_text(&studio_hook::event_log(&home)); let lines: Vec = text .lines() .map(|l| serde_json::from_str(l).unwrap()) @@ -134,7 +134,7 @@ fn a_copilot_payload_is_dropped_by_the_claude_entry_and_recorded_once_by_copilot assert!(out.status.success()); stderrs.push(String::from_utf8(out.stderr).unwrap()); } - let text = fs::read_to_string(studio_hook::event_log(&home)).unwrap(); + let text = crate::common::logged_text(&studio_hook::event_log(&home)); let lines: Vec = text .lines() .map(|l| serde_json::from_str(l).unwrap()) diff --git a/hook/tests/agy.rs b/hook/tests/agy.rs index 25385f930..98da79d8e 100644 --- a/hook/tests/agy.rs +++ b/hook/tests/agy.rs @@ -1,7 +1,7 @@ // `plotkeeper-hook` records an agy event from any terminal (#323, which reverses #43's decision 9), and // no event from a process with `PLOTKEEPER_INTERNAL=1`, plotkeeper's own model runs. use crate::common::{feed, hook, scratch}; -use std::{fs, process::Stdio}; +use std::process::Stdio; fn run(payload: serde_json::Value, name: &str) -> (bool, String) { let home = scratch(&format!("agy-{name}")); @@ -11,7 +11,7 @@ fn run(payload: serde_json::Value, name: &str) -> (bool, String) { assert!(out.status.success()); assert!(out.stdout.is_empty()); let log = studio_hook::event_log(&home); - (log.exists(), fs::read_to_string(log).unwrap_or_default()) + (log.exists(), crate::common::logged_text(&log)) } fn agy() -> serde_json::Value { diff --git a/hook/tests/answer.rs b/hook/tests/answer.rs index 149afc8a2..616367367 100644 --- a/hook/tests/answer.rs +++ b/hook/tests/answer.rs @@ -213,7 +213,7 @@ fn reply(home: &Path, answer: Value) { /// The event log's lines. #[cfg(unix)] fn logged(home: &Path) -> Vec { - let text = fs::read_to_string(studio_hook::event_log(home)).unwrap_or_default(); + let text = crate::common::logged_text(&studio_hook::event_log(home)); text.lines() .map(|l| serde_json::from_str(l).unwrap()) .collect() diff --git a/hook/tests/common.rs b/hook/tests/common.rs index a1b5a197f..d7c42607b 100644 --- a/hook/tests/common.rs +++ b/hook/tests/common.rs @@ -63,3 +63,20 @@ pub(crate) fn hold(log: &Path) -> studio_hook::Locked { .unwrap() .expect("the log's lock is free") } + +/// The lines of the event log `log`, its day files read in order, parsed. +pub(crate) fn logged(log: &Path) -> Vec { + logged_text(log) + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .collect() +} + +/// The text of the event log `log`: its day files in read order, one after the other; empty when it has none. +pub(crate) fn logged_text(log: &Path) -> String { + let files = studio_hook::day_files(log).unwrap(); + files + .iter() + .map(|f| fs::read_to_string(f).unwrap()) + .collect() +} diff --git a/hook/tests/data_folder.rs b/hook/tests/data_folder.rs index 80598f842..cb07922d3 100644 --- a/hook/tests/data_folder.rs +++ b/hook/tests/data_folder.rs @@ -30,7 +30,7 @@ fn on_windows_the_event_log_lands_in_appdata_local() { let home = scratch("appdata-local"); assert_eq!( log_the_hook_writes(&home, None), - home.join(r"AppData\Local\plotkeeper\events.jsonl") + home.join(r"AppData\Local\plotkeeper\events") ); } @@ -43,7 +43,7 @@ fn the_data_folder_is_plotkeeper() { ); assert_eq!( studio_hook::event_log(Path::new("/h")), - Path::new("/h/Library/Application Support/plotkeeper/events.jsonl") + Path::new("/h/Library/Application Support/plotkeeper/events") ); } @@ -70,7 +70,8 @@ fn set_env(var: &str, value: Option<&str>) { } } -/// The event log `plotkeeper-hook` writes on a Stop, with `home` as its `HOME` and `XDG_DATA_HOME` as given. +/// The event log `plotkeeper-hook` writes on a Stop, with `home` as its `HOME` and `XDG_DATA_HOME` as given: the folder +/// of the one day file it writes. #[cfg(any(target_os = "linux", windows))] fn log_the_hook_writes(home: &Path, xdg_data_home: Option<&Path>) -> std::path::PathBuf { let mut cmd = hook(home); @@ -80,12 +81,21 @@ fn log_the_hook_writes(home: &Path, xdg_data_home: Option<&Path>) -> std::path:: }; let payload = serde_json::json!({ "hook_event_name": "Stop", "session_id": "s" }); assert!(feed(cmd, &payload).wait().unwrap().success()); - let logs: Vec<_> = walk(home) - .into_iter() - .filter(|p| p.ends_with("events.jsonl")) - .collect(); + let logs = day_files(home); assert_eq!(logs.len(), 1, "{logs:?}"); - logs[0].clone() + logs[0].parent().unwrap().to_owned() +} + +/// The day files under `dir`: each `.jsonl` file in a folder named `events`. +#[cfg(any(target_os = "linux", windows))] +fn day_files(dir: &Path) -> Vec { + let day_file = |p: &Path| { + p.extension().is_some_and(|e| e == "jsonl") + && p.parent() + .and_then(Path::file_name) + .is_some_and(|n| n == "events") + }; + walk(dir).into_iter().filter(|p| day_file(p)).collect() } #[cfg(any(target_os = "linux", windows))] @@ -109,7 +119,7 @@ fn on_linux_the_event_log_lands_in_the_xdg_data_folder() { let home = scratch("xdg-data"); assert_eq!( log_the_hook_writes(&home, Some(&home.join("data"))), - home.join("data/plotkeeper/events.jsonl") + home.join("data/plotkeeper/events") ); } @@ -119,12 +129,12 @@ fn on_linux_without_xdg_data_home_the_event_log_lands_in_local_share() { let home = scratch("xdg-data-unset"); assert_eq!( log_the_hook_writes(&home, None), - home.join(".local/share/plotkeeper/events.jsonl") + home.join(".local/share/plotkeeper/events") ); let empty = scratch("xdg-data-empty"); assert_eq!( log_the_hook_writes(&empty, Some(Path::new(""))), - empty.join(".local/share/plotkeeper/events.jsonl") + empty.join(".local/share/plotkeeper/events") ); } @@ -144,7 +154,7 @@ fn on_linux_the_data_folder_follows_xdg_data_home() { set_env("XDG_DATA_HOME", None); assert_eq!( studio_hook::event_log(Path::new("/h")), - Path::new("/h/.local/share/plotkeeper/events.jsonl") + Path::new("/h/.local/share/plotkeeper/events") ); } @@ -189,10 +199,8 @@ fn on_linux_a_hook_copy_writes_to_the_data_folder_it_sits_in() { let payload = serde_json::json!({ "hook_event_name": "Stop", "session_id": "s" }); assert!(feed(cmd, &payload).wait().unwrap().success()); } - let logs: Vec<_> = walk(&home) - .into_iter() - .filter(|p| p.ends_with("events.jsonl")) - .collect(); - assert_eq!(logs, [data.join("events.jsonl")]); + let logs = day_files(&home); + assert_eq!(logs.len(), 1, "{logs:?}"); + assert_eq!(logs[0].parent().unwrap(), data.join("events")); assert_eq!(fs::read_to_string(&logs[0]).unwrap().lines().count(), 2); } diff --git a/hook/tests/deadline.rs b/hook/tests/deadline.rs index d6ae6414e..6818de43d 100644 --- a/hook/tests/deadline.rs +++ b/hook/tests/deadline.rs @@ -42,7 +42,7 @@ fn a_held_lock_gives_a_drops_line_and_no_log_line_once_its_patience_runs_out() { assert!(took >= Duration::from_millis(200), "took {took:?}"); assert!(took < Duration::from_secs(3), "took {took:?}"); - assert_eq!(fs::read_to_string(&log).unwrap_or_default(), ""); + assert_eq!(crate::common::logged_text(&log), ""); let drops = fs::read_to_string(studio_hook::drops_file(&log)).unwrap(); let fields: Vec<&str> = drops.trim_end().split(' ').collect(); assert_eq!(drops.lines().count(), 1); @@ -59,7 +59,7 @@ fn a_free_lock_writes_the_log_and_leaves_the_drops_file_alone() { hook(&home, 200, event()); - assert_eq!(fs::read_to_string(&log).unwrap().lines().count(), 1); + assert_eq!(crate::common::logged_text(&log).lines().count(), 1); assert!(!studio_hook::drops_file(&log).exists()); // Cleanup: a leftover temp file fails no test. fs::remove_dir_all(&home).ok(); diff --git a/hook/tests/harness_trees.rs b/hook/tests/harness_trees.rs index ff837f995..e18cc85ac 100644 --- a/hook/tests/harness_trees.rs +++ b/hook/tests/harness_trees.rs @@ -76,7 +76,7 @@ fn replay( } assert!(feed(cmd, &payload).wait().unwrap().success()); } - let log = fs::read_to_string(studio_hook::event_log(&home)).unwrap(); + let log = crate::common::logged_text(&studio_hook::event_log(&home)); let logged = log .lines() .map(|l| serde_json::from_str(l).unwrap()) @@ -242,7 +242,7 @@ fn cursor(home: &Path, payload: Value) -> Value { let mut cmd = untimed(hook(home)); cmd.args(["--agent", "cursor"]); assert!(feed(cmd, &payload).wait().unwrap().success()); - let log = fs::read_to_string(studio_hook::event_log(home)).unwrap(); + let log = crate::common::logged_text(&studio_hook::event_log(home)); serde_json::from_str(log.lines().last().unwrap()).unwrap() } @@ -398,7 +398,7 @@ fn a_hook_agents_line_is_logged_in_time_when_git_hangs() { let began = std::time::Instant::now(); assert!(feed(cmd, &payload).wait().unwrap().success()); let took = began.elapsed(); - let log = fs::read_to_string(studio_hook::event_log(&home)).unwrap_or_default(); + let log = crate::common::logged_text(&studio_hook::event_log(&home)); // Cleanup: a leftover temp file fails no test. fs::remove_dir_all(&base).ok(); @@ -592,7 +592,7 @@ fn turns_whose_hooks_run_at_once_out_of_order_each_list_their_own_edit() { run(group); } - let log = fs::read_to_string(log).unwrap(); + let log = crate::common::logged_text(&log); let listed = core_listed(&log, &root); // Cleanup: a leftover temp file fails no test. fs::remove_dir_all(&base).ok(); @@ -672,7 +672,7 @@ fn an_opencode_or_agy_lines_session_record_stays_locked_until_the_line_is_in_the drop(log_lock); assert!(child.wait().unwrap().success()); let free_once_logged = free(&file); - let logged = fs::read_to_string(&log).unwrap(); + let logged = crate::common::logged_text(&log); // Cleanup: a leftover temp file fails no test. fs::remove_dir_all(&base).ok(); assert_eq!(free_while_waiting, !held, "{agent}"); diff --git a/hook/tests/named_roots.rs b/hook/tests/named_roots.rs index 0652b2ef4..4dd1f7dd0 100644 --- a/hook/tests/named_roots.rs +++ b/hook/tests/named_roots.rs @@ -75,7 +75,7 @@ impl Scene { cmd.args(["--agent", agent]); cmd.env("PATH", self.path()); assert!(feed(cmd, &event).wait().unwrap().success()); - let log = fs::read_to_string(studio_hook::event_log(&self.home)).unwrap(); + let log = crate::common::logged_text(&studio_hook::event_log(&self.home)); serde_json::from_str(log.lines().last().unwrap()).unwrap() } diff --git a/hook/tests/pid.rs b/hook/tests/pid.rs index 012b949ca..352cab86b 100644 --- a/hook/tests/pid.rs +++ b/hook/tests/pid.rs @@ -1,7 +1,7 @@ // The pid the hook records as `studio_pid` (#330): the agent's process, so the server can end a // session whose agent is gone. A fake process table stands in for `ps`; no process is signalled. use crate::common::{feed, hook, scratch}; -use std::{fs, process::Stdio}; +use std::process::Stdio; use studio_hook::agent_pid; /// A table of `(pid, command, parent)`. @@ -87,7 +87,7 @@ fn recorded(wrapper: Option<&str>, name: &str) -> serde_json::Value { .status .success() ); - let log = fs::read_to_string(studio_hook::event_log(&home)).unwrap(); + let log = crate::common::logged_text(&studio_hook::event_log(&home)); serde_json::from_str(log.lines().next().unwrap()).unwrap() } @@ -223,7 +223,7 @@ fn the_real_lookup_finds_a_childs_executable_and_its_parent() { let found = studio_hook::inspect(child.id()); drop(child.stdin.take()); child.wait().unwrap(); - let exe = fs::canonicalize("/bin/sh").unwrap(); + let exe = std::fs::canonicalize("/bin/sh").unwrap(); assert_eq!( found, Some((exe.to_string_lossy().into_owned(), std::process::id())) @@ -237,7 +237,7 @@ fn the_real_lookup_finds_a_childs_executable_and_its_parent() { #[test] fn the_real_lookup_skips_a_busybox_shell() { let dir = scratch("busybox"); - fs::copy("/bin/sh", dir.join("busybox")).unwrap(); + std::fs::copy("/bin/sh", dir.join("busybox")).unwrap(); std::os::unix::fs::symlink("busybox", dir.join("sh")).unwrap(); let mut child = std::process::Command::new(dir.join("sh")) .args(["-c", "read line"]) diff --git a/hook/tests/prune.rs b/hook/tests/prune.rs index f9f6e9341..822328624 100644 --- a/hook/tests/prune.rs +++ b/hook/tests/prune.rs @@ -1,8 +1,8 @@ -// The event log's growth (danielrispler/plotkeeper#132): the hook leaves out the two heavy fields, -// and a prune moves the sessions that ended more than 30 days ago to the archive. And the log's lock -// (#805): appends and a prune against a held `events.lock`, and the law's scan that every writer of -// the log goes through the hook crate's log code. -use crate::common::{feed, hold, hook, scratch as scratch_home}; +// The event log's growth (danielrispler/plotkeeper#132, spec #1072): the hook leaves out what no reader +// takes, each line goes into its UTC day's file, and a prune deletes the days more than 30 days old. And +// the log's lock (#805): appends and a prune against a held `events.lock`, and the law's scan that every +// writer of the log goes through the hook crate's log code. +use crate::common::{feed, hold, hook, logged, scratch as scratch_home}; use serde_json::{Value, json}; use std::{ fs, @@ -11,7 +11,7 @@ use std::{ thread, time::Duration, }; -use studio_hook::{Pruned, archive_file, prune}; +use studio_hook::prune; const DAY: u64 = 24 * 60 * 60 * 1000; const NOW: u64 = 100 * DAY; @@ -29,6 +29,13 @@ fn lines(path: &Path) -> Vec { .collect() } +/// The live day file the real clock picks today in the log `log`, made with its folder. +fn today(log: &Path) -> PathBuf { + fs::create_dir_all(log).unwrap(); + let day = studio_workbench::clock::utc_date(studio_workbench::clock::now_ms()); + log.join(format!("{day}.jsonl")) +} + fn write(path: &Path, events: &[Value]) { let text: String = events.iter().map(|e| format!("{e}\n")).collect(); fs::write(path, text).unwrap(); @@ -62,16 +69,51 @@ 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()); } - let logged = lines(&studio_hook::event_log(&home)); + let logged = logged(&studio_hook::event_log(&home)); let edit = &logged[0]["tool_response"]; assert_eq!(edit.get("originalFile"), None); @@ -81,203 +123,140 @@ 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); } +/// Each append picks its day file from its own clock once it holds the lock, so lines on either side of a UTC midnight +/// land in two files, in the order the lock gave; a clock that reads an earlier day than a file already there writes to +/// that newer file, so no line goes into a day once the next day's file exists. #[test] -fn a_prune_archives_the_sessions_whose_last_event_is_older_than_30_days() { - let home = scratch("archive"); - let log = studio_hook::event_log(&home); - let old = at("old", NOW - 40 * DAY); - let long = at("long", NOW - 40 * DAY); - let rename = - json!({ "session_id": "old", "hook_event_name": "StudioRename", "studio_name": "x" }); - let recent = at("recent", NOW - DAY); - let long_again = at("long", NOW - 2 * DAY); - write( - &log, - &[ - old.clone(), - long.clone(), - rename.clone(), - recent.clone(), - long_again.clone(), - ], - ); - - let pruned = prune(&log, NOW).unwrap(); - - assert_eq!( - pruned, - Pruned { - archived: 2, - lightened: 0 - } - ); - assert_eq!(lines(&log), [long, recent, long_again]); - assert_eq!(lines(&archive_file(&log)), [old, rename]); -} - -#[test] -fn a_prune_appends_to_the_archive_and_strips_the_heavy_fields_from_the_lines_it_keeps() { - let home = scratch("strip"); - let log = studio_hook::event_log(&home); - let earlier = at("earlier", NOW - 90 * DAY); - write(&archive_file(&log), std::slice::from_ref(&earlier)); - let old = at("old", NOW - 31 * DAY); - let mut kept = edit(); - kept["studio_received_ms"] = json!(NOW); - write(&log, &[old.clone(), kept.clone(), read()]); - - let pruned = prune(&log, NOW).unwrap(); - - assert_eq!( - pruned, - Pruned { - archived: 1, - lightened: 2 +fn appends_on_either_side_of_a_utc_midnight_land_in_their_days_files_in_lock_order() { + const MIDNIGHT: u64 = 1_796_169_600_000; // 2026-12-02T00:00:00Z + type Files<'a> = &'a [(&'a str, &'a [&'a str])]; + let cases: [(&str, [u64; 2], Files); 3] = [ + ( + "across midnight", + [MIDNIGHT - 1, MIDNIGHT], + &[ + ("2026-12-01.jsonl", &["s-0"]), + ("2026-12-02.jsonl", &["s-1"]), + ], + ), + ( + "same day", + [MIDNIGHT, MIDNIGHT + DAY - 1], + &[("2026-12-02.jsonl", &["s-0", "s-1"])], + ), + ( + "a clock behind the newest file", + [MIDNIGHT, MIDNIGHT - 1], + &[("2026-12-02.jsonl", &["s-0", "s-1"])], + ), + ]; + for (name, clocks, expected) in cases { + let home = scratch(&format!("midnight-{}", name.replace(' ', "-"))); + let log = studio_hook::event_log(&home); + for (n, clock) in clocks.into_iter().enumerate() { + let event = at(&format!("s-{n}"), clock); + let appended = studio_hook::append_at(&log, &event, Duration::from_secs(1), &|| clock); + assert!(appended.unwrap(), "{name}"); } - ); - assert_eq!(lines(&archive_file(&log)), [earlier, old]); - let logged = lines(&log); - assert_eq!(logged.len(), 2); - assert_eq!(logged[0]["tool_response"].get("originalFile"), None); - assert_eq!( - logged[0]["tool_response"]["structuredPatch"], - kept["tool_response"]["structuredPatch"] - ); - assert_eq!(logged[1]["tool_response"]["file"].get("content"), None); -} - -#[test] -fn a_log_whose_first_line_is_recent_is_left_as_it_is() { - let home = scratch("recent"); - let log = studio_hook::event_log(&home); - let mut first = edit(); - first["studio_received_ms"] = json!(NOW - DAY); - write(&log, &[first, at("s-2", NOW)]); - let before = fs::read(&log).unwrap(); - - assert_eq!(prune(&log, NOW).unwrap(), Pruned::default()); - assert_eq!(fs::read(&log).unwrap(), before); - assert!(!archive_file(&log).exists()); -} - -#[test] -fn no_log_prunes_nothing() { - let home = scratch("none"); - let log = studio_hook::event_log(&home); - assert_eq!(prune(&log, NOW).unwrap(), Pruned::default()); - assert!(!log.exists()); + assert_eq!(day_sessions(&log), expected_files(expected), "{name}"); + } } -/// A prune replaces the log's file while it holds the lock. A hook that waits for the lock must write -/// to the new one, or its line is lost. -// @law: log-writers-hold-the-log-lock +/// A prune deletes a day's files, its live file and its migrated part, once the day is more than 30 days before today in +/// UTC, and nothing else: not a newer day, not a file of another name in the log's folder, not the saved state beside it. #[test] -fn a_line_waiting_for_the_lock_lands_in_the_log_that_replaced_it() { - let home = scratch("replaced"); - let log = studio_hook::event_log(&home); - fs::write(&log, "").unwrap(); - let held = hold(&log); - let waiting = { - let log = log.clone(); - thread::spawn(move || studio_hook::append(&log, &at("s-1", NOW), Duration::from_secs(5))) - }; - thread::sleep(Duration::from_millis(200)); - let next = log.with_file_name("next.jsonl"); - write(&next, &[at("s-0", NOW)]); - fs::rename(&next, &log).unwrap(); - drop(held); +fn a_prune_deletes_the_days_more_than_30_days_before_today() { + const TODAY: u64 = 1_796_169_600_000 + 12 * 60 * 60 * 1000; // 2026-12-02T12:00:00Z + type Case<'a> = (&'a str, &'a [&'a str], &'a [&'a str]); + let cases: [Case; 3] = [ + ( + "old days", + &[ + "2026-10-01.migrated.jsonl", + "2026-11-01.migrated.jsonl", + "2026-11-01.jsonl", + "2026-11-02.jsonl", + "2026-12-02.jsonl", + ], + &["2026-11-02.jsonl", "2026-12-02.jsonl"], + ), + ("no old day", &["2026-11-02.jsonl"], &["2026-11-02.jsonl"]), + ("no folder", &[], &[]), + ]; + for (name, files, kept) in cases { + let home = scratch(&format!("days-{}", name.replace(' ', "-"))); + let log = studio_hook::event_log(&home); + for file in files { + fs::create_dir_all(&log).unwrap(); + write(&log.join(file), &[at("s-0", TODAY)]); + } + let state = studio_hook::state_file(&log); + fs::write(&state, "studio-state").unwrap(); + if !files.is_empty() { + fs::write(log.join("legacy.jsonl"), "{}\n").unwrap(); + } - assert!(waiting.join().unwrap().unwrap()); - assert_eq!(lines(&log), [at("s-0", NOW), at("s-1", NOW)]); -} + prune(&log, TODAY).unwrap(); -/// A line's session is read by the agent its hook entry named (#355): an agy line goes by its -/// conversation, whatever other id its payload holds. -#[test] -fn a_prune_keeps_a_sessions_lines_together_by_the_id_its_agent_uses() { - let home = scratch("agent"); - let log = studio_hook::event_log(&home); - let agy = |ms: u64, extra: Value| { - let mut line = json!({ - "conversationId": "c-1", - "hookEventName": "PreToolUse", - "studio_agent": "agy", - "studio_received_ms": ms, - }); - line.as_object_mut() + let left: Vec = studio_hook::day_files(&log) .unwrap() - .extend(extra.as_object().unwrap().clone()); - line - }; - let old = agy(NOW - 40 * DAY, json!({ "session_id": "a-tools-id" })); - let recent = agy(NOW - DAY, json!({})); - let claude_old = json!({ - "session_id": "s-1", - "conversationId": "c-1", - "hook_event_name": "Stop", - "studio_agent": "claude", - "studio_received_ms": NOW - 40 * DAY, - }); - write(&log, &[old.clone(), claude_old.clone(), recent.clone()]); - - prune(&log, NOW).unwrap(); - - assert_eq!(lines(&log), [old, recent]); - assert_eq!(lines(&archive_file(&log)), [claude_old]); -} - -/// A Cursor line goes by its `conversation_id` (#362): its `sessionStart` also carries a -/// `session_id`, and its other events carry none. -#[test] -fn a_prune_keeps_a_cursor_sessions_lines_together_by_its_conversation_id() { - let home = scratch("cursor"); - let log = studio_hook::event_log(&home); - let start = json!({ - "conversation_id": "c-1", - "session_id": "c-1-start", - "hook_event_name": "sessionStart", - "studio_agent": "cursor", - "studio_received_ms": NOW - 40 * DAY, - }); - let recent = json!({ - "conversation_id": "c-1", - "hook_event_name": "stop", - "studio_agent": "cursor", - "studio_received_ms": NOW - DAY, - }); - write(&log, &[start.clone(), recent.clone()]); - - prune(&log, NOW).unwrap(); - - assert_eq!(lines(&log), [start, recent]); + .iter() + .map(|f| f.file_name().unwrap().to_string_lossy().into_owned()) + .collect(); + assert_eq!(left, kept, "{name}"); + assert!(state.exists(), "{name}: the saved state stays"); + assert_eq!( + log.join("legacy.jsonl").exists(), + !files.is_empty(), + "{name}" + ); + } } -/// A camelCase Copilot line has its session in `sessionId` (#361): its old and recent lines stay -/// together. -#[test] -fn a_prune_keeps_a_copilot_sessions_camel_case_lines_together() { - let home = scratch("copilot"); - let log = studio_hook::event_log(&home); - let copilot = |ms: u64| { - json!({ - "sessionId": "cs-1", - "studio_event": "preToolUse", - "studio_agent": "copilot", - "studio_received_ms": ms, +/// Each day file of the log `log`, in read order, by name, with the sessions of its lines. +fn day_sessions(log: &Path) -> Vec<(String, Vec)> { + let files = studio_hook::day_files(log).unwrap(); + files + .iter() + .map(|file| { + let name = file.file_name().unwrap().to_string_lossy().into_owned(); + let lines = lines(file); + let sessions = lines + .iter() + .map(|l| l["session_id"].as_str().unwrap().to_owned()); + (name, sessions.collect()) }) - }; - let (old, recent) = (copilot(NOW - 40 * DAY), copilot(NOW - DAY)); - write( - &log, - &[old.clone(), at("s-0", NOW - 40 * DAY), recent.clone()], - ); - - prune(&log, NOW).unwrap(); + .collect() +} - assert_eq!(lines(&log), [old, recent]); +fn expected_files(files: &[(&str, &[&str])]) -> Vec<(String, Vec)> { + let owned = |sessions: &[&str]| sessions.iter().map(ToString::to_string).collect(); + files + .iter() + .map(|(file, sessions)| (file.to_string(), owned(sessions))) + .collect() } /// No reader meets the log's lock: while another writer holds it, the log opens and reads whole, and an append waits for @@ -293,7 +272,7 @@ fn an_append_against_a_held_lock_lands_once_it_is_let_go_or_writes_nothing_when_ ] { let home = scratch(&format!("held-{name}")); let log = studio_hook::event_log(&home); - write(&log, &[at("s-0", NOW)]); + write(&today(&log), &[at("s-0", NOW)]); let held = hold(&log); let waiting = { let log = log.clone(); @@ -301,7 +280,7 @@ fn an_append_against_a_held_lock_lands_once_it_is_let_go_or_writes_nothing_when_ }; thread::sleep(Duration::from_millis(200)); - assert_eq!(lines(&log), [at("s-0", NOW)], "{name}"); + assert_eq!(logged(&log), [at("s-0", NOW)], "{name}"); let appended = if lands { assert!(!waiting.is_finished(), "{name}"); drop(held); @@ -317,7 +296,7 @@ fn an_append_against_a_held_lock_lands_once_it_is_let_go_or_writes_nothing_when_ } else { &[at("s-0", NOW)] }; - assert_eq!(lines(&log), expected, "{name}"); + assert_eq!(logged(&log), expected, "{name}"); } } @@ -328,14 +307,14 @@ fn an_append_against_a_held_lock_lands_once_it_is_let_go_or_writes_nothing_when_ fn a_data_folder_with_no_lock_file_gets_one_on_the_first_append_and_keeps_its_lines() { let home = scratch("no-lock"); let log = studio_hook::event_log(&home); - write(&log, &[at("s-0", NOW)]); + write(&today(&log), &[at("s-0", NOW)]); let lock = studio_hook::lock_file(&log); assert!(!lock.exists()); assert!(studio_hook::append(&log, &at("s-1", NOW), Duration::from_secs(1)).unwrap()); assert!(lock.is_file()); - assert_eq!(lines(&log), [at("s-0", NOW), at("s-1", NOW)]); + assert_eq!(logged(&log), [at("s-0", NOW), at("s-1", NOW)]); } /// Many appends at once, from threads, give whole lines, none interleaved, in a log that ends with a newline. @@ -360,9 +339,9 @@ fn appends_from_many_threads_at_once_give_whole_lines() { thread.join().unwrap(); } - let text = fs::read_to_string(&log).unwrap(); + let text = fs::read_to_string(today(&log)).unwrap(); assert!(text.ends_with('\n')); - let mut logged = lines(&log); + let mut logged = logged(&log); logged.sort_by_key(|l| l["session_id"].as_str().unwrap().to_owned()); let mut expected: Vec<_> = (0..8) .flat_map(|t| (0..20).map(move |n| line(t, n))) @@ -371,42 +350,85 @@ fn appends_from_many_threads_at_once_give_whole_lines() { assert_eq!(logged, expected); } -/// A prune reads the log, then waits for the lock to swap the new log in; lines appended between its read and its swap -/// are copied to the new log's tail. +/// A line that waits for the lock picks its day once it holds it, by the clock then: a hook that started before +/// midnight and got the lock after it writes to the new day's file, behind the line that holds the lock, so the order +/// the lock grants is the order of the files. // @law: log-writers-hold-the-log-lock #[test] -fn a_prunes_tail_copy_keeps_the_lines_appended_between_its_read_and_its_swap() { - let home = scratch("tail"); +fn a_line_waiting_for_the_lock_picks_its_day_once_it_holds_it() { + use std::sync::{ + Arc, + atomic::{AtomicU64, Ordering}, + }; + const MIDNIGHT: u64 = 1_796_169_600_000; // 2026-12-02T00:00:00Z + let home = scratch("waiting-day"); let log = studio_hook::event_log(&home); - let (old, recent, late) = ( - at("old", NOW - 40 * DAY), - at("recent", NOW - DAY), - at("late", NOW), + fs::create_dir_all(&log).unwrap(); + let clock = Arc::new(AtomicU64::new(MIDNIGHT - 1)); + // The lock alone: `hold` would open a day file by the real clock. + let held = fs::File::options() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(studio_hook::lock_file(&log)) + .unwrap(); + held.lock().unwrap(); + let waiting = { + let (log, clock) = (log.clone(), clock.clone()); + thread::spawn(move || { + let now = || clock.load(Ordering::Acquire); + studio_hook::append_at(&log, &at("s-1", NOW), Duration::from_secs(5), &now) + }) + }; + thread::sleep(Duration::from_millis(200)); + clock.store(MIDNIGHT, Ordering::Release); + let first = log.join("2026-12-02.jsonl"); + write(&first, &[at("s-0", NOW)]); + drop(held); + + assert!(waiting.join().unwrap().unwrap()); + assert_eq!( + day_sessions(&log), + expected_files(&[("2026-12-02.jsonl", &["s-0", "s-1"])]) ); - write(&log, &[old.clone(), recent.clone()]); +} + +/// A prune deletes the old days only while it holds the lock: it waits for a writer that holds it, and the line that +/// writer appends meanwhile stays in today's file. +// @law: log-writers-hold-the-log-lock +#[test] +fn a_prune_deletes_old_days_only_while_it_holds_the_lock() { + let home = scratch("prune-held"); + let log = studio_hook::event_log(&home); + let now = studio_workbench::clock::now_ms(); + let old = log.join(format!( + "{}.jsonl", + studio_workbench::clock::utc_date(now - 40 * DAY) + )); + write(&today(&log), &[at("recent", now)]); + write(&old, &[at("old", now - 40 * DAY)]); let mut held = hold(&log); let pruning = { let log = log.clone(); - thread::spawn(move || prune(&log, NOW)) + thread::spawn(move || prune(&log, now)) }; thread::sleep(Duration::from_millis(300)); - assert!( - !pruning.is_finished(), - "the prune swapped the log without its lock" - ); + assert!(!pruning.is_finished(), "the prune ran without the lock"); + assert!(old.exists(), "the prune deleted a day without the lock"); // A hook that got the lock before the prune writes its line. - std::io::Write::write_all(&mut held, format!("{late}\n").as_bytes()).unwrap(); + std::io::Write::write_all(&mut held, format!("{}\n", at("late", now)).as_bytes()).unwrap(); drop(held); - let pruned = pruning.join().unwrap().unwrap(); + pruning.join().unwrap().unwrap(); - assert_eq!(pruned.archived, 1); - assert_eq!(lines(&log), [recent, late]); - assert_eq!(lines(&archive_file(&log)), [old]); + assert!(!old.exists()); + assert_eq!(logged(&log), [at("recent", now), at("late", now)]); } /// Every writer of the log goes through the hook crate's log code, which takes the lock: outside it, `archive/` and the -/// tests' own helpers, no source file names the event log and opens a file to write. +/// tests' own helpers, no source file names the event log, its `events/` folder or a day file, and opens a file to +/// write. // @law: log-writers-hold-the-log-lock #[test] fn no_file_but_the_log_code_names_the_log_and_opens_a_file_to_write() { @@ -424,7 +446,14 @@ fn no_file_but_the_log_code_names_the_log_and_opens_a_file_to_write() { || file.ends_with("tests.rs"); !file.is_empty() && !helper && !file.starts_with("archive/") && *file != "hook/src/lib.rs" }); - let names = ["events.jsonl", "EVENT_LOG", "event_log(", "event_log_in("]; + let names = [ + "events.jsonl", + "events/", + "EVENT_LOG", + "event_log(", + "event_log_in(", + "day_files(", + ]; let opens = ["OpenOptions", "File::create", "fs::write"]; let mut found = Vec::new(); for file in ours { diff --git a/hook/tests/rollout.rs b/hook/tests/rollout.rs index 07e455124..25545533f 100644 --- a/hook/tests/rollout.rs +++ b/hook/tests/rollout.rs @@ -24,7 +24,7 @@ fn logged(home: &Path, event: &Value) -> Vec { let mut cmd = hook(home); cmd.args(["--agent", "codex"]); assert!(feed(cmd, event).wait().unwrap().success()); - let log = fs::read_to_string(studio_hook::event_log(home)).unwrap(); + let log = crate::common::logged_text(&studio_hook::event_log(home)); log.lines() .map(|l| serde_json::from_str(l).unwrap()) .collect() @@ -99,8 +99,7 @@ fn a_null_transcript_path_or_an_event_but_a_stop_adds_no_context_size() { assert!(line.get("context_tokens").is_none(), "{event}"); } assert_eq!( - fs::read_to_string(studio_hook::event_log(&home)) - .unwrap() + crate::common::logged_text(&studio_hook::event_log(&home)) .lines() .count(), 2 diff --git a/hook/tests/terminal.rs b/hook/tests/terminal.rs index 71aa23ecd..49b7ee7cb 100644 --- a/hook/tests/terminal.rs +++ b/hook/tests/terminal.rs @@ -2,7 +2,7 @@ //! `TERM_PROGRAM` and Herdr's terminal id, from the agent's environment, so the page can bring Daniel to the session. use crate::common::{feed, hook, scratch}; use serde_json::{Value, json}; -use std::{collections::HashMap, fs, process::Stdio}; +use std::{collections::HashMap, process::Stdio}; use studio_hook::{agent_pid, terminal}; /// The line `plotkeeper-hook` with `args` and the variables `vars` logs for `payload`. @@ -13,7 +13,7 @@ fn logged(args: &[&str], vars: &[(&str, &str)], payload: &Value, name: &str) -> .envs(vars.iter().copied()) .stdout(Stdio::null()); assert!(feed(cmd, payload).wait().unwrap().success(), "{name}"); - let text = fs::read_to_string(studio_hook::event_log(&home)).unwrap(); + let text = crate::common::logged_text(&studio_hook::event_log(&home)); serde_json::from_str(text.lines().next().unwrap()).unwrap() } diff --git a/scripts/npm/smoke.sh b/scripts/npm/smoke.sh index 75cb6623a..7599fc86b 100755 --- a/scripts/npm/smoke.sh +++ b/scripts/npm/smoke.sh @@ -169,5 +169,5 @@ npm rm -g --prefix "$prefix" plotkeeper "$platform" [ ! -e "$package" ] && [ ! -e "$bin" ] || fail "the packages are still installed" command=$(node -p "require('$hooks').hooks.SessionStart[0].hooks[0].command") echo '{"hook_event_name":"SessionStart","session_id":"smoke-368"}' | sh -c "$command" -grep -q "smoke-368" "$data/events.jsonl" || fail "the hook recorded nothing after the package was removed" +grep -q "smoke-368" "$data"/events/*.jsonl || fail "the hook recorded nothing after the package was removed" echo "smoke: ok" diff --git a/server/src/lib.rs b/server/src/lib.rs index 4ef227ed5..7efcf7916 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -599,14 +599,13 @@ pub fn saved_roots(log: &Path) -> HashMap { live } -/// Takes the state a launch before saved, when it fits the log, and returns the offset to replay the -/// log from: 0 when there is none (danielrispler/plotkeeper#134). -pub fn resume(studio: &Mutex, log: &Path) -> u64 { - let Ok(saved) = std::fs::read(studio_hook::state_file(log)) else { - return 0; - }; - let len = std::fs::metadata(log).map_or(0, |m| m.len()); - studio.lock().unwrap().resume(&saved, len) +/// Takes the state a launch before saved, when its day file of the log `log` is there to its position, and returns +/// the position to read the log on from: `None` when there is no such state, and the log is read in full +/// (danielrispler/plotkeeper#134, spec #1072). +pub fn resume(studio: &Mutex, log: &Path) -> Option { + let saved = std::fs::read(studio_hook::state_file(log)).ok()?; + let file_len = |file: &str| std::fs::metadata(log.join(file)).ok().map(|m| m.len()); + studio.lock().unwrap().resume(&saved, file_len) } /// Keeps the replayed state beside the log, through a new file that takes the old one's place. @@ -633,7 +632,7 @@ pub fn append(lines: &[serde_json::Value]) -> Result<(), String> { append_to(&studio_hook::event_log(&home), lines) } -/// Appends `lines` to the event log `log`, under the log's lock, `events.lock`. +/// Appends `lines` to the event log `log`, its day file the lock's holder picks, under the log's lock, `events.lock`. pub fn append_to(log: &Path, lines: &[serde_json::Value]) -> Result<(), String> { let locked = studio_hook::locked(log, Duration::from_secs(60)); let mut log = locked diff --git a/server/src/read_loop.rs b/server/src/read_loop.rs index b4af345ff..cac45e288 100644 --- a/server/src/read_loop.rs +++ b/server/src/read_loop.rs @@ -1,7 +1,8 @@ -//! The read loop (danielrispler/plotkeeper#324, spec #319 "The server"): it reads the event log from its start, then from where -//! it stopped, and sends what changed to the [`Sink`](crate::Sink) the shell set: the session list, the selection, the cards, the -//! notices (a `notification` event). It holds no window: whether Daniel is looking comes from the sink's `focused`. It never marks a -//! session seen: the page does, on Daniel's act (`see_session`, #1019). +//! The read loop (danielrispler/plotkeeper#324, spec #319 "The server"): it reads the event log's day files from where the +//! saved state stopped, or from the first, each to its end and then the next (spec #1072), and sends what changed to the +//! [`Sink`](crate::Sink) the shell set: the session list, the selection, the cards, the notices (a `notification` event). It +//! holds no window: whether Daniel is looking comes from the sink's `focused`. It never marks a session seen: the page +//! does, on Daniel's act (`see_session`, #1019). use crate::{ App, CardsKey, PROCESS_CHECK, append_to, cards, current_cards_key, process_ends, @@ -10,7 +11,7 @@ use crate::{ use std::{ collections::HashMap, fs::File, - io::{BufRead, BufReader, Seek, SeekFrom}, + io::{BufRead, BufReader, ErrorKind, Seek, SeekFrom}, path::{Path, PathBuf}, process::Command, sync::{Arc, LazyLock, Mutex, OnceLock, Weak, atomic::Ordering}, @@ -210,14 +211,19 @@ pub fn follow(app: &Arc, log: &Path) { } } -/// The read loop's state between passes. The lines there at start are replayed, so steps that ran while the app was down get no -/// cards and no notifications, but for the turns of the last 24 hours with no card, which get one on the hook's trees -/// (danielrispler/Falinks#486). Live lines get the worktree fingerprint the core asks for; replayed ones get none. Each pass -/// ends with a tick, the first right after the replay. +/// The read loop's state between passes. It reads the day files in order, each to its end, and goes on to the next once +/// one exists; a day file deleted under it is passed over. The lines there at start are replayed, so steps that ran while +/// the app was down get no cards and no notifications, but for the turns of the last 24 hours with no card, which get one +/// on the hook's trees (danielrispler/Falinks#486). Live lines get the worktree fingerprint the core asks for; replayed +/// ones get none. Each pass ends with a tick, the first right after the replay. pub struct Follower { app: Arc, log: PathBuf, - read_to: u64, + /// Where the next read starts: a day file, by name, and the offset in it; `None` before the first file. + read_to: Option, + /// The UTC day of the last prune, and the clock that tells when the day changes, in Unix milliseconds. + pruned: String, + clock: Box u64 + Send>, roots_saved: usize, live: bool, /// Each session's and each subagent's own, so another's prompt or step in the same worktree moves no base. @@ -231,28 +237,26 @@ pub struct Follower { impl Follower { /// Prunes the log, then takes the saved state, when there is one that fits it, which starts the replay from where it - /// stopped (danielrispler/plotkeeper#134). + /// stopped (danielrispler/plotkeeper#134). The log is pruned again each time the UTC day changes. pub fn start(app: &Arc, log: &Path) -> Self { - Self::start_at(app, log, millis()) + Self::with_clock(app, log, Box::new(millis)) } - /// [`Follower::start`] with the prune's clock, `now` in Unix milliseconds, for a test whose log is - /// dated: by the real clock, a recorded log ages out of the log 30 days after its last line. + /// [`Follower::start`] with the prune's clock standing at `now`, in Unix milliseconds, for a test whose log is + /// dated: by the real clock, a recorded log's day is deleted 30 days after it. pub fn start_at(app: &Arc, log: &Path, now: u64) -> Self { - // Before the replay, so it reads none of what the prune moves (danielrispler/plotkeeper#132). - match studio_hook::prune(log, now) { - Ok(pruned) if pruned != studio_hook::Pruned::default() => log::info!( - "pruned the event log: {} lines archived, {} lightened", - pruned.archived, - pruned.lightened - ), - Ok(_) => {} - Err(e) => log::warn!("prune the event log: {e}"), - } + Self::with_clock(app, log, Box::new(move || now)) + } + + fn with_clock(app: &Arc, log: &Path, clock: Box u64 + Send>) -> Self { + // Before the state is taken, which is refused when the prune deleted the day it stops in. + let pruned = prune(log, clock()); Follower { app: app.clone(), log: log.to_path_buf(), read_to: resume(&app.core, log), + pruned, + clock, roots_saved: 0, live: false, fingerprints: HashMap::new(), @@ -267,6 +271,10 @@ impl Follower { pub fn pass(&mut self) { let shared = self.app.clone(); let app: &App = &shared; + let now = (self.clock)(); + if studio_workbench::clock::utc_date(now) != self.pruned { + self.pruned = prune(&self.log, now); + } let read = self.read_log(); // A session whose agent is gone ends within about 30 s (#330); the lines are read on the next pass. if self.live && self.checked.is_none_or(|at| at.elapsed() >= PROCESS_CHECK) { @@ -306,32 +314,28 @@ impl Follower { fn read_log(&mut self) -> bool { let shared = self.app.clone(); let app: &App = &shared; - let Ok(mut file) = File::open(&self.log) else { - return false; + // Listed before any is read: a writer appends only to the newest day file there is, so each file before the + // last one listed is whole by now. + let files = studio_hook::day_files(&self.log).unwrap_or_default(); + let names: Vec = (files.iter()) + .filter_map(|f| Some(f.file_name()?.to_str()?.to_owned())) + .collect(); + // A file the loop stopped in that is gone was pruned, and every file left comes after it. + let first = match &self.read_to { + Some(at) => names.iter().position(|n| *n == at.file).unwrap_or(0), + None => 0, }; - if file.seek(SeekFrom::Start(self.read_to)).is_err() { - return false; - } - let mut reader = BufReader::new(file); - let mut line = Vec::new(); let mut outputs = Vec::new(); - let read_from = self.read_to; - // The core is locked per line, and not while the fingerprint runs `git`, so the pane's - // commands do not wait on it. - while reader.read_until(b'\n', &mut line).unwrap_or(0) > 0 && line.ends_with(b"\n") { - self.read_to += line.len() as u64; - let text = String::from_utf8_lossy(&line); - if self.live { - // shortcut: fingerprints when the line is read, up to one poll after the prompt, - // so an edit in between counts as Daniel's; take the fingerprint in the hook if a - // card ever misses one. - let looks = app.core().fingerprint_folders(&text); - let changes = fingerprint_changes(looks, &mut self.fingerprints); - outputs.extend(app.core().apply_with_changes(&text, changes)); - } else { - app.core().replay(&text); + let mut read = false; + for name in names.iter().skip(first) { + if self.read_to.as_ref().is_none_or(|at| at.file != *name) { + self.read_to = Some(studio_core::Position { + file: name.clone(), + offset: 0, + }); + app.core().next_file(name); } - line.clear(); + read |= self.read_file(&mut outputs); } if !self.live { self.replayed(); @@ -339,7 +343,6 @@ impl Follower { for output in outputs { self.act(output); } - let read = self.read_to > read_from; if read { let roots = app.core().known_roots(); if roots.len() != self.roots_saved { @@ -357,6 +360,49 @@ impl Follower { read } + /// Reads the whole lines of the day file the loop is in from where it stopped, replayed or applied live, the live + /// lines' outputs added to `outputs`. A line a writer is still writing waits for the next pass. A file gone under it + /// reads nothing. Returns whether a line was read. + fn read_file(&mut self, outputs: &mut Vec) -> bool { + let shared = self.app.clone(); + let app: &App = &shared; + let Some(at) = self.read_to.as_mut() else { + return false; + }; + let mut file = match File::open(self.log.join(&at.file)) { + Err(e) if e.kind() == ErrorKind::NotFound => return false, + Err(e) => { + log::warn!("read the event log's {}: {e}", at.file); + return false; + } + Ok(file) => file, + }; + if file.seek(SeekFrom::Start(at.offset)).is_err() { + return false; + } + let mut reader = BufReader::new(file); + let mut line = Vec::new(); + let read_from = at.offset; + // The core is locked per line, and not while the fingerprint runs `git`, so the pane's + // commands do not wait on it. + while reader.read_until(b'\n', &mut line).unwrap_or(0) > 0 && line.ends_with(b"\n") { + at.offset += line.len() as u64; + let text = String::from_utf8_lossy(&line); + if self.live { + // shortcut: fingerprints when the line is read, up to one poll after the prompt, + // so an edit in between counts as Daniel's; take the fingerprint in the hook if a + // card ever misses one. + let looks = app.core().fingerprint_folders(&text); + let changes = fingerprint_changes(looks, &mut self.fingerprints); + outputs.extend(app.core().apply_with_changes(&text, changes)); + } else { + app.core().replay(&text); + } + line.clear(); + } + at.offset > read_from + } + /// The replay is done. A worktree's first fingerprint only records it, so the turns still open /// after the replay get their base now, and their `Stop` has something to compare with. The /// list goes first, so Daniel sees it while `git` runs. @@ -469,6 +515,19 @@ impl Follower { } } +/// Prunes the log `log` by the clock's `now`, in Unix milliseconds, and returns the UTC day it pruned on. A failed +/// prune is said and tried again when the day changes. +fn prune(log: &Path, now: u64) -> String { + match studio_hook::prune(log, now) { + Ok(deleted) if !deleted.is_empty() => { + log::info!("pruned the event log: {} day files deleted", deleted.len()); + } + Ok(_) => {} + Err(e) => log::warn!("prune the event log: {e}"), + } + studio_workbench::clock::utc_date(now) +} + /// Removes the asks whose block the core saw open and then close, which ends their hooks' waits (#892). fn end_answered_waits(app: &App) { if let Ok(data) = crate::answer::data() { diff --git a/server/src/session_view/tests.rs b/server/src/session_view/tests.rs index 11b680f28..b0036a7ad 100644 --- a/server/src/session_view/tests.rs +++ b/server/src/session_view/tests.rs @@ -45,13 +45,11 @@ fn a_refused_rename_appends_nothing_to_the_event_log() { std::env::remove_var("XDG_CACHE_HOME"); } let log = studio_hook::event_log(home.path()); - std::fs::create_dir_all(log.parent().unwrap()).unwrap(); - std::fs::write(&log, "").unwrap(); + std::fs::create_dir_all(&log).unwrap(); let refused = rename("s1".into(), mixed(NAME_LIMIT + 1)).unwrap_err(); assert!(refused.contains("200"), "{refused}"); - assert_eq!( - std::fs::read_to_string(&log).unwrap(), - "", + assert!( + studio_hook::day_files(&log).unwrap().is_empty(), "the refused rename appended a line" ); } diff --git a/server/src/tests.rs b/server/src/tests.rs index 9fb0718d1..bc0abd1c6 100644 --- a/server/src/tests.rs +++ b/server/src/tests.rs @@ -138,7 +138,7 @@ fn a_session_whose_agent_process_is_gone_gets_a_synthetic_end_and_ends() { #[test] fn the_servers_lines_wait_for_the_logs_lock_then_land_whole() { let dir = tempfile::tempdir().unwrap(); - let log = dir.path().join("events.jsonl"); + let log = dir.path().join("events"); let held = studio_hook::locked(&log, std::time::Duration::from_secs(1)) .unwrap() .unwrap(); @@ -155,7 +155,9 @@ fn the_servers_lines_wait_for_the_logs_lock_then_land_whole() { assert!(!appending.is_finished(), "wrote without the log's lock"); drop(held); appending.join().unwrap().unwrap(); - let text = std::fs::read_to_string(&log).unwrap(); + let files = studio_hook::day_files(&log).unwrap(); + assert_eq!(files.len(), 1, "{files:?}"); + let text = std::fs::read_to_string(&files[0]).unwrap(); assert_eq!(text, format!("{}\n{}\n", lines[0], lines[1])); } diff --git a/server/tests/read_loop.rs b/server/tests/read_loop.rs index 07a7fce8c..1dc20f557 100644 --- a/server/tests/read_loop.rs +++ b/server/tests/read_loop.rs @@ -1,10 +1,11 @@ //! The read loop over a recorded log into a fake sink (danielrispler/plotkeeper#324): what it sends, when it sends it again, -//! and where its focus input comes from. +//! and where its focus input comes from; where a start resumes the day files from, and how the loop reads them live +//! (spec #1072). mod isolated_home; use std::{ io::Write, - path::Path, + path::{Path, PathBuf}, sync::{ Arc, Mutex, atomic::{AtomicBool, Ordering}, @@ -14,6 +15,8 @@ use studio_server::{App, Follower, Notice, Sink, tell}; use studio_understanding::{CardStore, Effects, FakeWriter, RiskNotes}; const LOG: &str = include_str!("../../core/tests/fixtures/two-sessions.jsonl"); +/// The fixture's day file. +const FIXTURE_DAY: &str = "2026-10-28.jsonl"; /// A day after the fixture's last line, the prune's clock: by the real one, the fixture's sessions /// left the log on 2026-11-28, 30 days after it. const NOW: u64 = 1_793_261_013_520 + 24 * 60 * 60 * 1000; @@ -70,6 +73,15 @@ fn app(log: &Path) -> (Arc, Arc) { (Arc::new(app), sink) } +/// An event log in `dir` whose one day file holds the fixture; the log and that file. +fn fixture_log(dir: &Path) -> (PathBuf, PathBuf) { + let log = dir.join("events"); + std::fs::create_dir_all(&log).unwrap(); + let day = log.join(FIXTURE_DAY); + std::fs::write(&day, LOG).unwrap(); + (log, day) +} + fn ids(list: &serde_json::Value) -> Vec<&str> { let mut ids: Vec<_> = (list.as_array().unwrap().iter()) .map(|row| row["id"].as_str().unwrap()) @@ -81,8 +93,7 @@ fn ids(list: &serde_json::Value) -> Vec<&str> { #[test] fn the_replay_sends_the_list_once_and_a_live_line_sends_it_again() { let dir = tempfile::tempdir().unwrap(); - let log = dir.path().join("events.jsonl"); - std::fs::write(&log, LOG).unwrap(); + let (log, day) = fixture_log(dir.path()); let (app, sink) = app(&log); let mut follower = Follower::start_at(&app, &log, NOW); @@ -99,7 +110,7 @@ fn the_replay_sends_the_list_once_and_a_live_line_sends_it_again() { "an unchanged list is not sent again" ); - let mut file = std::fs::OpenOptions::new().append(true).open(&log).unwrap(); + let mut file = std::fs::OpenOptions::new().append(true).open(&day).unwrap(); writeln!( file, r#"{{"session_id":"third","prompt_id":"p","cwd":"/nowhere","hook_event_name":"UserPromptSubmit","prompt":"Hello","studio_received_ms":1793261100000}}"# @@ -114,13 +125,12 @@ fn the_replay_sends_the_list_once_and_a_live_line_sends_it_again() { #[test] fn a_finished_turn_is_seen_only_when_the_page_sees_its_session() { let dir = tempfile::tempdir().unwrap(); - let log = dir.path().join("events.jsonl"); - std::fs::write(&log, LOG).unwrap(); + let (log, day) = fixture_log(dir.path()); let (app, sink) = app(&log); let mut follower = Follower::start_at(&app, &log, NOW); follower.pass(); studio_server::select(&app, Some(FIRST.into())); - let mut file = std::fs::OpenOptions::new().append(true).open(&log).unwrap(); + let mut file = std::fs::OpenOptions::new().append(true).open(&day).unwrap(); writeln!( file, r#"{{"session_id":"{FIRST}","prompt_id":"e2a7c9d1-3f5b-4a8e-9c6d-0b1a2f3e4d5c","cwd":"/nowhere","hook_event_name":"Stop","last_assistant_message":"Done.","studio_received_ms":1793261100000}}"# @@ -152,8 +162,7 @@ fn a_finished_turn_is_seen_only_when_the_page_sees_its_session() { #[test] fn a_due_notice_goes_to_the_page_as_an_event_only_while_it_is_unfocused() { let dir = tempfile::tempdir().unwrap(); - let log = dir.path().join("events.jsonl"); - std::fs::write(&log, LOG).unwrap(); + let (log, _) = fixture_log(dir.path()); let (app, sink) = app(&log); let mut follower = Follower::start_at(&app, &log, NOW); follower.pass(); @@ -177,3 +186,213 @@ fn a_due_notice_goes_to_the_page_as_an_event_only_while_it_is_unfocused() { "a focused tab looks at the page itself" ); } + +const MIDNIGHT: u64 = 1_796_169_600_000; // 2026-12-02T00:00:00Z +const DAY_MS: u64 = 24 * 60 * 60 * 1000; + +/// A prompt line of session `session`, its prompt `prompt`, at `ms`. +fn prompt(session: &str, prompt: &str, ms: u64) -> String { + let line = serde_json::json!({ + "session_id": session, "prompt_id": prompt, "cwd": "/nowhere", "hook_event_name": "UserPromptSubmit", + "prompt": prompt, "studio_received_ms": ms, + }); + format!("{line}\n") +} + +fn append(file: &Path, text: &str) { + let mut file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(file) + .unwrap(); + file.write_all(text.as_bytes()).unwrap(); +} + +/// The ids of the sessions the core holds, sorted. +fn sessions(app: &App) -> Vec { + let mut ids: Vec = (app.core().sessions().iter()) + .map(|s| s.agent.id.clone()) + .collect(); + ids.sort(); + ids +} + +/// How the log changes between two starts. +enum Change { + /// Its first day file is emptied, so a read from its start finds no `old`, and `new` is appended to its second. + EmptyFirst, + /// `new` is appended to its second day file. + AppendNew, + /// Its second day file, where the state stops, holds only `new`: shorter than the state's position. + ShortenSecond, + /// Its second day file is deleted and a third holds `new`. + DeleteSecond, + /// Its first day file is emptied, `new` is appended to its second, and the state is of the format before day files. + OldFormat, +} + +/// A start takes the state the start before it saved when its day file is there to its position, and reads on from +/// there, never from byte 0; a prune that deleted an older day changes nothing of that (the slow restarts, spec #1072). +/// A state whose day file is gone or shorter, or of the old format, is refused and the log is read in full. +#[test] +fn a_start_resumes_from_the_saved_state_when_its_day_file_holds_its_position() { + let first_start = MIDNIGHT - 12 * DAY_MS + DAY_MS / 2; // 2026-11-20T12:00Z + let after_prune = MIDNIGHT + 3 * DAY_MS + DAY_MS / 2; // 2026-12-05T12:00Z + let cases = [ + ( + "a plain start resumes", + Change::EmptyFirst, + first_start, + &["kept", "new", "old"][..], + ), + ( + "a start after a prune resumes", + Change::AppendNew, + after_prune, + &["kept", "new", "old"], + ), + ( + "a shorter day file is refused", + Change::ShortenSecond, + first_start, + &["new", "old"], + ), + ( + "a deleted day file is refused", + Change::DeleteSecond, + first_start, + &["new", "old"], + ), + ( + "the old format is ignored", + Change::OldFormat, + first_start, + &["kept", "new"], + ), + ]; + for (name, change, second_start, expected) in cases { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("events"); + std::fs::create_dir_all(&log).unwrap(); + let (first, second) = (log.join("2026-11-01.jsonl"), log.join("2026-11-20.jsonl")); + append(&first, &prompt("old", "p1", MIDNIGHT - 31 * DAY_MS)); + append(&second, &prompt("kept", "p1", MIDNIGHT - 12 * DAY_MS)); + let state = studio_hook::state_file(&log); + { + let (app, _sink) = app(&log); + Follower::start_at(&app, &log, first_start).pass(); + let began = std::time::Instant::now(); + while !state.exists() { + assert!( + began.elapsed() < std::time::Duration::from_secs(10), + "{name}: no state saved" + ); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + // Its write is atomic, so the file is whole once it is there. + } + let new = prompt("new", "p1", MIDNIGHT - 11 * DAY_MS); + match change { + Change::EmptyFirst => { + std::fs::write(&first, "").unwrap(); + append(&second, &new); + } + Change::AppendNew => append(&second, &new), + // Its line is one byte shorter than `kept`'s. + Change::ShortenSecond => std::fs::write(&second, &new).unwrap(), + Change::DeleteSecond => { + std::fs::remove_file(&second).unwrap(); + append(&log.join("2026-11-21.jsonl"), &new); + } + Change::OldFormat => { + std::fs::write(&first, "").unwrap(); + append(&second, &new); + let saved = std::fs::read(&state).unwrap(); + let body = &saved[saved.iter().position(|b| *b == b'\n').unwrap()..]; + std::fs::write(&state, [b"studio-state 14".as_slice(), body].concat()).unwrap(); + } + } + + let (app, _sink) = app(&log); + Follower::start_at(&app, &log, second_start).pass(); + + assert_eq!(sessions(&app), expected, "{name}"); + if second_start == after_prune { + assert!(!first.exists(), "{name}: the prune deleted the old day"); + } + } +} + +/// One file's change before a pass: lines appended, or the file deleted. +enum Step { + Append(&'static str, &'static [&'static str]), + Delete(&'static str), +} + +/// The read loop reads each day file to its end and then the next, so lines appended across a day change are read once +/// and in order; a day's migrated part is read before its live file; and a day file deleted under it is passed over. +#[test] +fn the_read_loop_reads_the_day_files_in_order_each_line_once() { + use Step::{Append, Delete}; + type Passes = &'static [&'static [Step]]; + let cases: [(&str, Passes, &[&str]); 3] = [ + ( + "lines across a day change", + &[ + &[Append("2026-12-01.jsonl", &["p1"])], + &[ + Append("2026-12-01.jsonl", &["p2"]), + Append("2026-12-02.jsonl", &["p3"]), + ], + &[Append("2026-12-02.jsonl", &["p4"])], + ], + &["p1", "p2", "p3", "p4"], + ), + ( + "a migrated part before its live file", + &[&[ + Append("2026-12-01.jsonl", &["p3"]), + Append("2026-12-01.migrated.jsonl", &["p1", "p2"]), + ]], + &["p1", "p2", "p3"], + ), + ( + "a day file deleted under it", + &[ + &[Append("2026-11-01.jsonl", &["p1"])], + &[ + Delete("2026-11-01.jsonl"), + Append("2026-12-02.jsonl", &["p2"]), + ], + ], + &["p1", "p2"], + ), + ]; + for (name, passes, expected) in cases { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("events"); + std::fs::create_dir_all(&log).unwrap(); + let (app, _sink) = app(&log); + let mut follower = Follower::start_at(&app, &log, MIDNIGHT); + let mut ms = MIDNIGHT; + for steps in passes { + for step in *steps { + match step { + Append(file, prompts) => { + for p in *prompts { + ms += 1000; + append(&log.join(file), &prompt("s", p, ms)); + } + } + Delete(file) => std::fs::remove_file(log.join(file)).unwrap(), + } + } + follower.pass(); + } + + let prompts: Vec = (app.core().session("s").unwrap().turns.iter()) + .map(|t| t.prompt.clone()) + .collect(); + assert_eq!(prompts, expected, "{name}"); + } +} diff --git a/server/tests/web.rs b/server/tests/web.rs index 2f4bf6294..ff634e780 100644 --- a/server/tests/web.rs +++ b/server/tests/web.rs @@ -55,8 +55,10 @@ fn fixture() -> Fixture { fn fixture_of(events: impl FnOnce(&std::path::Path) -> String) -> Fixture { isolated_home::set(); let dir = tempfile::tempdir().unwrap(); - let log = dir.path().join("events.jsonl"); - std::fs::write(&log, events(dir.path())).unwrap(); + let log = dir.path().join("events"); + std::fs::create_dir_all(&log).unwrap(); + let day = studio_workbench::clock::utc_date(NOW); + std::fs::write(log.join(format!("{day}.jsonl")), events(dir.path())).unwrap(); let cards = Arc::new(Mutex::new(CardStore::open_beside(&log).unwrap())); let notes = Arc::new(Mutex::new(RiskNotes::open_beside(&log).unwrap())); let app = App::open_with( diff --git a/server/tests/writer.rs b/server/tests/writer.rs index ae2096194..25c0e0765 100644 --- a/server/tests/writer.rs +++ b/server/tests/writer.rs @@ -82,8 +82,10 @@ fn log_with_turn(dir: &Path, ended: u64) -> std::path::PathBuf { ), line("Stop", ended, json!({"studio_turn_end": {&root: end}})), ]; - let log = dir.join("events.jsonl"); - fs::write(&log, text.join("\n") + "\n").unwrap(); + let log = dir.join("events"); + fs::create_dir_all(&log).unwrap(); + let day = studio_workbench::clock::utc_date(ended); + fs::write(log.join(format!("{day}.jsonl")), text.join("\n") + "\n").unwrap(); log } diff --git a/system-map.json b/system-map.json index c53691a19..f3d4eb2d3 100644 --- a/system-map.json +++ b/system-map.json @@ -20,7 +20,7 @@ "id": "hook", "name": "Hook", "caption": "Records every agent event", "purpose": "Runs on each agent event and appends it to the event log. It also holds a question, a plan or a permission open until you answer.", "holds": [ - { "name": "The event log", "text": "One append-only JSON Lines file, the only source of session state.", "paths": ["hook/src/lib.rs"] }, + { "name": "The event log", "text": "Append-only JSON Lines, one file per UTC day in `events/`, the only source of session state; a prune deletes the days more than 30 days old.", "paths": ["hook/src/lib.rs"] }, { "name": "The recorder", "text": "Appends each event with its agent, terminal and a Codex turn end's context size; drops another harness's event, which that harness records.", "paths": ["hook/src/main.rs", "hook/src/rollout.rs"] }, { "name": "IDE sessions", "text": "Records no process for an agent inside an IDE app such as VS Code, so its session goes idle, then ends after 24 hours with no events." }, { "name": "The answer hook", "text": "Waits for your answer on the page, the terminal's dialog open: plans and questions while plotkeeper runs, other permissions while shown.", "paths": ["hook/src/answer.rs", "hook/src/bin/plotkeeper-answer.rs"] }, @@ -234,7 +234,7 @@ { "id": "hook-never-makes-agent-wait", "on": "hook", "backing": "trust", "text": "The hook never makes the agent wait, except for your answer." }, { "id": "log-writers-hold-the-log-lock", "on": "hook", "backing": "check", - "text": "Every line written to the event log is written whole, under `events.lock`; a prune replaces the log only while holding it, and no reader takes it." }, + "text": "Every line written to the event log's day files in `events/` is written whole, under `events.lock`, into the day its writer picks while holding it; a prune deletes days only while holding it, and no reader takes it." }, { "id": "switchboard-runs-fixed-programs", "on": "server", "backing": "check", "text": "The switchboard starts only `open` (`xdg-open` on Linux), Herdr, herdr-core's `hc`, the chosen editor's tool and `ps`, with arguments it builds and never through a shell; its `git` is built by the runner." }, { "id": "projects-leave-only-by-remove", "on": "server", "backing": "check", diff --git a/understanding/examples/ask_trial.rs b/understanding/examples/ask_trial.rs index ac0f761f0..3ab4fa77d 100644 --- a/understanding/examples/ask_trial.rs +++ b/understanding/examples/ask_trial.rs @@ -7,7 +7,7 @@ //! //! `cargo run -q -p studio-understanding --example ask_trial -- --anchors 30` -use std::{io::BufRead, time::Instant}; +use std::time::Instant; use studio_core::{Anchor, Studio}; use studio_understanding::{ClaudeWriter, ask_about, ask_item, turn_hunk}; @@ -35,9 +35,7 @@ fn main() { .unwrap_or(30); let home = std::env::home_dir().expect("a home directory"); let log = studio_hook::event_log(&home); - let lines = std::io::BufReader::new(std::fs::File::open(&log).expect("the event log")) - .lines() - .map_while(Result::ok); + let lines = studio_hook::day_lines(&log).expect("the event log"); let studio = Studio::replayed(lines); let writer = ClaudeWriter::beside(&log).expect("create the card writer's folder"); diff --git a/understanding/examples/replay_time.rs b/understanding/examples/replay_time.rs index b4d58d899..cf0291f9e 100644 --- a/understanding/examples/replay_time.rs +++ b/understanding/examples/replay_time.rs @@ -4,7 +4,6 @@ //! `cargo run --release -p studio-understanding --example replay_time`. use std::{ - io::{BufRead, BufReader}, sync::atomic::{AtomicUsize, Ordering}, time::Instant, }; @@ -16,8 +15,7 @@ static LOOKUPS: AtomicUsize = AtomicUsize::new(0); fn main() { let log = studio_hook::event_log(&std::env::home_dir().expect("a home directory")); let start = Instant::now(); - let file = std::fs::File::open(&log).expect("open the event log"); - let lines: Vec = BufReader::new(file).lines().map_while(Result::ok).collect(); + let lines: Vec = studio_hook::day_lines(&log).expect("read the event log"); let read = start.elapsed(); let start = Instant::now(); @@ -48,7 +46,9 @@ fn main() { // A launch with saved state (danielrispler/plotkeeper#134): the state the replay above made, taken // back with the last 1% of the log left to replay as a tail. let tail = lines.len() / 100; + // Its lines are read as one day file's. let mut head = Studio::default(); + head.next_file("day.jsonl"); lines[..lines.len() - tail] .iter() .for_each(|line| head.replay(line)); @@ -58,7 +58,9 @@ fn main() { let len: u64 = lines.iter().map(|l| l.len() as u64 + 1).sum(); let start = Instant::now(); let mut resumed = Studio::default(); - let from = resumed.resume(&state, len); + let from = resumed + .resume(&state, |_| Some(len)) + .map_or(0, |at| at.offset); let resume = start.elapsed(); let start = Instant::now(); let mut at = 0; diff --git a/understanding/examples/risk_trial.rs b/understanding/examples/risk_trial.rs index 9477d7daf..718d48986 100644 --- a/understanding/examples/risk_trial.rs +++ b/understanding/examples/risk_trial.rs @@ -8,7 +8,7 @@ //! //! `cargo run -q -p studio-understanding --example risk_trial > local-evidence/2026-11-22-blocked-card-explain-risk/reports/risk-trial.md` -use std::{io::BufRead, time::Instant}; +use std::time::Instant; use studio_understanding::{ClaudeWriter, RISK_TIMEOUT, RiskLevel}; /// The folder the hand-made commands are asked to run in. @@ -97,15 +97,16 @@ fn judge(writer: &ClaudeWriter, heading: &str, command: &str, folder: &str) -> J fn main() { let home = std::env::home_dir().expect("a home directory"); let log = studio_hook::event_log(&home); - let lines = std::io::BufReader::new(std::fs::File::open(&log).expect("the event log")) - .lines() - .map_while(Result::ok); + let lines = studio_hook::day_lines(&log).expect("the event log"); let writer = ClaudeWriter::beside(&log).expect("create the card writer's folder"); // Each distinct command and folder once, in the order they were first blocked. Read from the log's `PermissionDenied` // lines and not the session list, which leaves out deleted sessions and their cards. let mut distinct: Vec<(String, String)> = Vec::new(); - for line in lines.filter(|l| l.contains("\"PermissionDenied\"")) { + for line in lines + .into_iter() + .filter(|l| l.contains("\"PermissionDenied\"")) + { let Ok(event) = serde_json::from_str::(&line) else { continue; }; diff --git a/understanding/src/bin/weekly.rs b/understanding/src/bin/weekly.rs index 42997d300..ab9f872d9 100644 --- a/understanding/src/bin/weekly.rs +++ b/understanding/src/bin/weekly.rs @@ -3,15 +3,15 @@ //! surprise rates and the ratings it printed before cards were retired (danielrispler/plotkeeper#348) are gone. Words after the //! command are Daniel's one-line verdict, which it appends with the rest to `weekly.txt` beside the event log. -use std::{fs, fs::OpenOptions, io::Write}; +use std::{fs::OpenOptions, io::Write}; use studio_core::Studio; use studio_understanding::{Versions, drift, dropped_events, millis}; fn main() -> std::io::Result<()> { let log = studio_hook::event_log(&std::env::home_dir().expect("a home directory")); let now = millis(); - let lines = String::from_utf8_lossy(&fs::read(&log).unwrap_or_default()).into_owned(); - let studio = Studio::replayed(lines.lines()); + let lines = studio_hook::day_lines(&log).unwrap_or_default(); + let studio = Studio::replayed(&lines); let drift = drift(&studio, &Versions::beside(&log), now); let drops = format!("dropped events: {}\n", dropped_events(&log, now)); print!("{drift}{drops}"); diff --git a/understanding/src/drift.rs b/understanding/src/drift.rs index 16424ee53..0dde53e59 100644 --- a/understanding/src/drift.rs +++ b/understanding/src/drift.rs @@ -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 { @@ -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}") -} diff --git a/understanding/src/lib.rs b/understanding/src/lib.rs index ac8c51e3c..927cff967 100644 --- a/understanding/src/lib.rs +++ b/understanding/src/lib.rs @@ -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, @@ -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, diff --git a/understanding/tests/drift.rs b/understanding/tests/drift.rs index 8f7067a37..506ad3258 100644 --- a/understanding/tests/drift.rs +++ b/understanding/tests/drift.rs @@ -203,3 +203,53 @@ fn an_agy_version_equal_to_the_fixtures_gives_no_notice_and_a_different_one_give let kept = fs::read_to_string(data.path().join("agy-versions.txt")).unwrap(); assert_eq!(kept, format!("{} 1.5.9\n{NOW} 1.6.0\n", NOW - DAY)); } + +#[test] +fn weekly_reads_a_data_folder_of_day_files_in_order_like_one_file() { + let home = tempfile::tempdir().unwrap(); + let log = studio_hook::event_log(home.path()); + fs::create_dir_all(&log).unwrap(); + let now = studio_understanding::millis(); + let at = |days: u64| { + let tasks = json!([ + { "id": "bx7k2", "status": "running", "type": "shell" }, + { "id": "by8m3", "status": "running", "type": "shell" }, + ]); + let prompt = |id: &str| format!("{id}"); + let base = json!({ + "session_id": "5b9e3d71-0c2a-4f8e-b6d4-8a1c3e5f7092", + "cwd": "/Users/danielrispler/work/Falinks", + "studio_received_ms": now - days * DAY, + }); + let with = |fields: serde_json::Value| { + let mut event = base.clone(); + event + .as_object_mut() + .unwrap() + .extend(fields.as_object().unwrap().clone()); + event.to_string() + "\n" + }; + ( + with(json!({ "hook_event_name": "Stop", "background_tasks": tasks })), + with(json!({ "hook_event_name": "UserPromptSubmit", "prompt": prompt("bx7k2") })), + with(json!({ "hook_event_name": "UserPromptSubmit", "prompt": prompt("by8m3") })), + ) + }; + // The task starts in a day's migrated part, and its wake-ups come in that day's live file and the next day's. + fs::write(log.join("2025-01-01.migrated.jsonl"), at(3).0).unwrap(); + fs::write(log.join("2025-01-01.jsonl"), at(2).1).unwrap(); + fs::write(log.join("2025-01-02.jsonl"), at(1).2).unwrap(); + + let out = std::process::Command::new(env!("CARGO_BIN_EXE_weekly")) + .env("HOME", home.path()) + .env("USERPROFILE", home.path()) + .env_remove("XDG_DATA_HOME") + .output() + .unwrap(); + + assert!(out.status.success()); + assert_eq!( + String::from_utf8_lossy(&out.stdout), + "unrecognised wake-ups: 2\ndropped events: 0\n" + ); +} diff --git a/understanding/tests/saved_state.rs b/understanding/tests/saved_state.rs index 1dff6c740..e8c20d95b 100644 --- a/understanding/tests/saved_state.rs +++ b/understanding/tests/saved_state.rs @@ -1,6 +1,5 @@ -//! Saved state beside a pruned event log (danielrispler/plotkeeper#134): a prune moves lines, so it -//! removes the saved state, and the replay that follows takes its offsets from the new log, which -//! every row of the ledger reads its details by. +//! Saved state beside a pruned event log (danielrispler/plotkeeper#134, spec #1072): a prune deletes whole day files and +//! moves no line, so it keeps the saved state, whose rows read their details by their positions in the days kept. use serde_json::{Value, json}; use std::fs; @@ -8,7 +7,8 @@ use studio_core::Studio; use studio_hook::{prune, state_file}; const DAY: u64 = 24 * 60 * 60 * 1000; -const NOW: u64 = 100 * DAY; +/// 2026-12-02T12:00:00Z. +const NOW: u64 = 1_796_169_600_000 + DAY / 2; const OLD: &str = "0a1b2c3d-0000-4000-8000-000000000001"; const NEW: &str = "0a1b2c3d-0000-4000-8000-000000000002"; @@ -33,10 +33,11 @@ fn call(session: &str, id: &str, tool: &str, input: Value, response: Value, ms: line(session, "PreToolUse", ms, both) + &line(session, "PostToolUse", ms + 500, end) } -fn log() -> String { - let old = DAY; +/// The log's two days: the old one, 40 days before `NOW`, and yesterday's. +fn days() -> [(&'static str, String); 2] { + let old = NOW - 40 * DAY; let now = NOW - DAY; - [ + let old_day = [ line(OLD, "UserPromptSubmit", old, json!({ "prompt": "old" })), call( OLD, @@ -46,6 +47,16 @@ fn log() -> String { json!({ "file": { "content": "x" } }), old + 1_000, ), + call( + NEW, + "n0", + "Bash", + json!({ "command": "cargo test" }), + json!({ "stdout": "an old day's output", "stderr": "" }), + old + 2_000, + ), + ]; + let new_day = [ line(NEW, "UserPromptSubmit", now, json!({ "prompt": "new" })), call( NEW, @@ -75,31 +86,51 @@ fn log() -> String { json!({ "answers": { "Which one?": "A" } }), now + 5_000, ), + ]; + [ + ("2026-10-23.jsonl", old_day.concat()), + ("2026-12-01.jsonl", new_day.concat()), ] - .concat() } -fn replayed(text: &str) -> Studio { +/// A studio that read the day files `days` in order, as the read loop does. +fn replayed(days: &[(&str, String)]) -> Studio { let mut studio = Studio::default(); - text.split_inclusive('\n').for_each(|l| studio.replay(l)); + for (file, text) in days { + studio.next_file(file); + text.split_inclusive('\n').for_each(|l| studio.replay(l)); + } studio } +/// After a prune, the saved state stays and every row of a kept day reads its details by its position; a row of the +/// deleted day reads none, and no error. #[test] -fn after_a_prune_every_row_reads_its_details_by_its_offset() { +fn after_a_prune_the_saved_state_stays_and_each_row_of_a_kept_day_reads_its_details() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("events.jsonl"); - fs::write(&path, log()).unwrap(); - fs::write(state_file(&path), replayed(&log()).save()).unwrap(); + let path = dir.path().join("events"); + fs::create_dir_all(&path).unwrap(); + for (file, text) in days() { + fs::write(path.join(file), text).unwrap(); + } + let studio = replayed(&days()); + fs::write(state_file(&path), studio.save()).unwrap(); - let pruned = prune(&path, NOW).unwrap(); + let deleted = prune(&path, NOW).unwrap(); - assert_eq!((pruned.archived, pruned.lightened), (3, 1)); - assert!(!state_file(&path).exists(), "the saved state is gone"); - let studio = replayed(&fs::read_to_string(&path).unwrap()); - assert!(studio.session(OLD).is_none()); + assert_eq!(deleted, [path.join("2026-10-23.jsonl")]); + assert!(state_file(&path).exists(), "the saved state stays"); + assert!( + studio.session(OLD).is_some(), + "the state keeps the old day's session" + ); let ledger = &studio.session(NEW).expect("the session").ledger; - assert_eq!(ledger.rows().len(), 3); + assert_eq!(ledger.rows().len(), 4); + assert_eq!( + ledger.row(None, "n0").unwrap().details(&path).unwrap(), + studio_core::Details::default(), + "a row of the deleted day reads nothing" + ); let details = |call: &str| ledger.row(None, call).unwrap().details(&path).unwrap(); let edit = details("e1").end.unwrap(); @@ -107,7 +138,6 @@ fn after_a_prune_every_row_reads_its_details_by_its_offset() { edit["tool_response"]["structuredPatch"][0]["lines"], json!(["-a", "+b"]) ); - assert_eq!(edit["tool_response"].get("originalFile"), None); let check = details("c1").end.unwrap(); assert_eq!( check["tool_response"]["stdout"], diff --git a/workbench/src/clock.rs b/workbench/src/clock.rs index 3326363f2..2c47d86fa 100644 --- a/workbench/src/clock.rs +++ b/workbench/src/clock.rs @@ -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}"); + } + } +}