From f9f4e437e47253b4d9ea3a3f5a1d624fb63199a0 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 28 Oct 2026 15:45:22 -0700 Subject: [PATCH] feat(annotate): mark the timeline from a script while recording `komorebi-recorder mark "text"` appends a point note (author script) to the session being recorded, found by --session, KOMOREBI_RECORDER_SESSION or the newest running recording. Notes now show as ticks on the viewer's bug lane. --- README.md | 3 + docs/usage/investigating-a-recording.md | 1 + docs/usage/recording-a-bug-repro.md | 17 + komorebi-recorder/src/analysis/schemas.rs | 5 + komorebi-recorder/src/cli/mark.rs | 393 ++++++++++++++++++++++ komorebi-recorder/src/cli/mod.rs | 7 +- komorebi-recorder/src/guide.md | 3 + komorebi-recorder/src/viewer/lanes.rs | 43 ++- komorebi-recorder/src/viewer/loaded.rs | 8 + komorebi-recorder/tests/mark.rs | 118 +++++++ 10 files changed, 596 insertions(+), 2 deletions(-) create mode 100644 komorebi-recorder/src/cli/mark.rs create mode 100644 komorebi-recorder/tests/mark.rs diff --git a/README.md b/README.md index 9386a5ee..564725d9 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,9 @@ komorebi-recorder overview ./repro # the whole recording at a glance komorebi-recorder trace ./repro event:7 # one event, from the handler that ran to what changed and who changed it ``` +A script that drives the repro can name its steps on the timeline while recording, with +`komorebi-recorder mark "step 3: move window right"`; they show up as notes. + For example, a four second recording of a Mac with komorebi running: ```text diff --git a/docs/usage/investigating-a-recording.md b/docs/usage/investigating-a-recording.md index 3c48fb46..1d10e4dc 100644 --- a/docs/usage/investigating-a-recording.md +++ b/docs/usage/investigating-a-recording.md @@ -128,6 +128,7 @@ and `event:12.end` when it finished. | `blank --region x,y,w,h` | When a region was blank (one colour, named: `white`, `black`, a hex code) or frozen (identical to the frame before): "the window went white for 200 ms" | | `compare A B` | Two recordings side by side: duration, frames, effective fps, worst frame gap, motion, findings by kind, annotations, and the difference | | `annotate`, `annotations` | Add, change and list bug regions, notes and findings | +| `mark TEXT` | While recording: drop a named point note (author `script`) onto the timeline from a script; it then appears in `annotations`, `brief` and the viewer like any note | ### Who changed it diff --git a/docs/usage/recording-a-bug-repro.md b/docs/usage/recording-a-bug-repro.md index a1cb3816..14aea578 100644 --- a/docs/usage/recording-a-bug-repro.md +++ b/docs/usage/recording-a-bug-repro.md @@ -127,6 +127,23 @@ This is what makes the recording useful to whoever investigates it, person or ag truth of _what_ went wrong, and everything else in the session is evidence of _why_. See [Investigating a recording](investigating-a-recording.md#marking-the-bug). +### Marking steps from a script + +A script that performs the repro can drop named markers onto the timeline while the recording is going: + +``` +komorebi-recorder mark "step 3: move window right" +``` + +A marker is a note by the author `script`, written at the moment the command runs, so it appears in `annotations`, +`brief`, `search`, `overview` and as a tick on the viewer's bug lane. `mark` prints the video time (`marked 00:03.28 (a-3f9c1e02): ...`) once the first frame has been captured and +the wall time (`marked 12:00:08.12Z (...)`) before that. + +It marks the session named by `--session DIR`, else by the environment variable `KOMOREBI_RECORDER_SESSION` (which +`record --until-exit` sets for the command it runs), else the newest recording in komorebi's data directory that is +still running. A recording that has finished is refused: it has no "now" to mark; use `annotate add` with a +time instead. `--json` prints the `mark/1` envelope. + ### Without video `komorebi-recorder record --no-video` records everything but the screen: komorebi's events and log, the OS trace and diff --git a/komorebi-recorder/src/analysis/schemas.rs b/komorebi-recorder/src/analysis/schemas.rs index 0d1db284..c82631f8 100644 --- a/komorebi-recorder/src/analysis/schemas.rs +++ b/komorebi-recorder/src/analysis/schemas.rs @@ -149,6 +149,11 @@ pub const ALL: &[Entry] = &[ about: "`annotate delete`: the id removed", schema: of::, }, + Entry { + name: "mark/1", + about: "`mark`: the marker dropped on a recording that is still going", + schema: of::, + }, Entry { name: "doctor/1", about: "`doctor`: what this machine can do for a recording", diff --git a/komorebi-recorder/src/cli/mark.rs b/komorebi-recorder/src/cli/mark.rs new file mode 100644 index 00000000..43e789c0 --- /dev/null +++ b/komorebi-recorder/src/cli/mark.rs @@ -0,0 +1,393 @@ +//! `mark`: dropping a named marker onto a recording's timeline while it is being recorded. +//! +//! A script that drives komorebi (or anything else on the machine) can say where it is: +//! `komorebi-recorder mark "step 3: move window right"`. The marker is a note, written to the +//! session's `annotations.jsonl` at the instant the command runs, so it shows up in `annotations`, +//! `brief`, `search`, `overview` and the viewer like any other note, with the author `script`. +//! +//! The note is a point in time: its start and end are the same nanosecond of the master clock +//! ([`crate::clock::mono_now_ns`], which every process on the machine agrees on). It does not go +//! through `cli::load`, which refuses a session that is still recording, and it does not take +//! the recorder's lock: [`crate::annotations::add`] only appends one line, which is safe beside the +//! recorder and beside other marks. +//! +//! # Which session +//! +//! In this order ([`resolve_session`]): +//! +//! 1. `--session DIR`; +//! 2. the environment variable [`SESSION_ENV`] (`record --until-exit` sets it for the command it +//! runs); +//! 3. the newest session under komorebi's `recordings/` directory whose recorder is running. +//! +//! A session no recorder is working on is refused: a finished recording has no "now" to mark, and +//! `annotate add` is how to put a note at a time in it. Covered by `tests/mark.rs`. + +use super::print_json; +use crate::analysis::envelope; +use crate::analysis::envelope::Envelope; +use crate::annotations; +use crate::annotations::Kind; +use crate::annotations::New; +use crate::clock; +use crate::lock; +use crate::lock::Recorder; +use crate::session::Session; +use crate::timecode; +use crate::timeline; +use clap::Args; +use color_eyre::eyre; +use schemars::JsonSchema; +use serde::Serialize; +use std::path::Path; +use std::path::PathBuf; + +/// The environment variable that names the session to mark: `KOMOREBI_RECORDER_SESSION`, which +/// `record --until-exit` sets for its command. +pub use super::until_exit::SESSION_ENV; + +/// The author a marker is written under. +pub const AUTHOR_SCRIPT: &str = "script"; + +/// The `schema` of the output of `mark` with `--json` ([`MarkData`]). +pub const SCHEMA_MARK: &str = "mark/1"; + +/// The arguments of `mark`. +#[derive(Args, Debug)] +pub struct MarkArgs { + /// What to call this moment, e.g. "step 3: move window right" + pub text: String, + /// The session being recorded [default: `$KOMOREBI_RECORDER_SESSION`, else the newest recording + /// in komorebi's data directory that is still running] + #[arg(long, value_name = "DIR")] + pub session: Option, + /// The kind of annotation to drop: `note`, or `bug` for a point where the bug is seen + #[arg(long, value_enum, default_value = "note")] + pub kind: MarkKind, + /// Machine-readable JSON output + #[arg(long)] + pub json: bool, +} + +/// The kinds of annotation `mark` writes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum MarkKind { + /// A remark about a moment + Note, + /// A point where the bug is seen + Bug, +} + +/// What `mark` answers with `--json`. +#[derive(Debug, Serialize, JsonSchema)] +pub struct MarkData { + /// The id of the annotation written, such as `a-3f9c1e02`. + pub id: String, + /// The kind of annotation: `note` unless `--kind` said otherwise. + pub kind: String, + /// The text of the marker. + pub text: String, + /// The session directory it was written to. + pub session: String, + /// The moment of the marker on the master clock, in nanoseconds. + pub at_mach_ns: u64, + /// The moment as a UTC time in RFC 3339 form with microseconds. + pub at_wall_utc: Option, + /// The moment in seconds of video time. `None` until the recording has captured its first + /// frame, where video time starts. + pub video_s: Option, +} + +/// Decides which session a mark goes to. +/// +/// `explicit` is `--session`, `env` the value of [`SESSION_ENV`] (empty counts as unset) and +/// `recordings` the directory to search for the newest running recording, which is the +/// name-ordered last directory in it whose recorder holds its lock (recordings are named for the +/// UTC time they began). +/// +/// # Errors +/// +/// - a not-found error if a named directory does not exist, or if nothing was named and no recording +/// in `recordings` is running; the message gives the three ways to name a session; +/// - a usage error if the session named is not being recorded: a finished recording has no "now" to +/// mark. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::cli::mark::resolve_session; +/// use komorebi_recorder::lock::RecorderLock; +/// +/// let root = std::env::temp_dir().join(format!("komorebi-recorder-doc-resolve-{}", std::process::id())); +/// let (old, new) = (root.join("20260101T000000Z"), root.join("20260102T000000Z")); +/// std::fs::create_dir_all(&old)?; +/// std::fs::create_dir_all(&new)?; +/// let _old = RecorderLock::acquire(&old)?; +/// let _new = RecorderLock::acquire(&new)?; +/// +/// // nothing named: the newest recording that is running +/// assert_eq!(resolve_session(None, None, &root)?, new); +/// // the environment beats the search, and --session beats the environment +/// assert_eq!(resolve_session(None, Some(old.clone().into()), &root)?, old); +/// assert_eq!(resolve_session(Some(&new), Some(old.clone().into()), &root)?, new); +/// # std::fs::remove_dir_all(&root)?; +/// # Ok::<(), Box>(()) +/// ``` +pub fn resolve_session( + explicit: Option<&Path>, + env: Option, + recordings: &Path, +) -> eyre::Result { + let named = explicit + .map(Path::to_path_buf) + .or_else(|| env.filter(|value| !value.is_empty()).map(PathBuf::from)); + + if let Some(dir) = named { + if !dir.is_dir() { + return Err(envelope::not_found(format!( + "{} is not a session directory", + dir.display() + ))); + } + return match lock::recorder(&dir) { + Recorder::Running(_) => Ok(dir), + Recorder::NotRunning | Recorder::Unknown => Err(envelope::with_hint( + envelope::usage(format!( + "{} is not being recorded, and a finished recording has no \"now\" to mark", + dir.display() + )), + format!( + "put a note at a time in it with `komorebi-recorder annotate {} add --kind note \ + --start --text `", + dir.display() + ), + )), + }; + } + + let mut candidates: Vec = std::fs::read_dir(recordings) + .into_iter() + .flatten() + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.is_dir()) + .collect(); + candidates.sort(); + candidates + .into_iter() + .rev() + .find(|dir| matches!(lock::recorder(dir), Recorder::Running(_))) + .ok_or_else(|| { + envelope::not_found(format!( + "no recording to mark: name the session with --session , or with the \ + environment variable {SESSION_ENV} (`record --until-exit` sets it for its command), \ + or start a recording; none under {} is running", + recordings.display() + )) + }) +} + +/// Writes the marker and returns what was written. +/// +/// # Errors +/// +/// Returns a usage error if the text is blank, and whatever [`annotations::add`] fails with. +pub fn write_mark(dir: &Path, text: &str, kind: MarkKind) -> eyre::Result { + if text.trim().is_empty() { + return Err(envelope::usage("a marker needs some text")); + } + + let at = clock::mono_now_ns(); + let at_wall_us = clock::wall_now_us(); + let kind = match kind { + MarkKind::Note => Kind::Note, + MarkKind::Bug => Kind::Bug, + }; + let id = annotations::add( + dir, + New { + kind: Some(kind), + // a point in time: an annotation with no end would run to the end of the recording + start_mach_ns: at, + end_mach_ns: Some(at), + text: text.to_string(), + author: Some(AUTHOR_SCRIPT.to_string()), + ..New::default() + }, + )?; + + // video time starts at the first frame, which the manifest records once there is one; before + // that the wall time is all there is + let video_s = Session::open(dir) + .and_then(|session| session.manifest()) + .ok() + .filter(|manifest| manifest.video_t0_mach_ns.is_some()) + .map(|manifest| manifest.video_seconds(at)); + + Ok(MarkData { + id, + kind: kind.to_string(), + text: text.to_string(), + session: dir.display().to_string(), + at_mach_ns: at, + at_wall_utc: timeline::format_wall_us(at_wall_us), + video_s, + }) +} + +pub(super) fn mark(args: &MarkArgs) -> eyre::Result<()> { + let dir = resolve_session( + args.session.as_deref(), + std::env::var_os(SESSION_ENV), + &crate::session::default_recordings_dir(), + )?; + let marked = write_mark(&dir, &args.text, args.kind)?; + + if args.json { + return print_json(&Envelope::ok(SCHEMA_MARK, marked)); + } + + let when = match (marked.video_s, &marked.at_wall_utc) { + (Some(video_s), _) => timecode::format(video_s), + // 2026-10-26T12:00:08.123456Z -> 12:00:08.12Z + (None, Some(wall)) => format!("{}Z", wall.get(11..22).unwrap_or(wall)), + (None, None) => "now".to_string(), + }; + println!("marked {when} ({}): {}", marked.id, marked.text); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::lock::RecorderLock; + + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "komorebi-recorder-mark-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create"); + dir + } + + fn running(root: &Path, name: &str) -> (PathBuf, RecorderLock) { + let dir = root.join(name); + std::fs::create_dir_all(&dir).expect("create"); + let lock = RecorderLock::acquire(&dir).expect("lock"); + (dir, lock) + } + + #[test] + fn the_newest_running_recording_is_the_default() { + let root = scratch("newest"); + let (_old, _a) = running(&root, "20260101T000000Z"); + let (new, _b) = running(&root, "20260102T000000Z"); + // newer still, but its recorder is gone + let finished = root.join("20260103T000000Z"); + std::fs::create_dir_all(&finished).expect("create"); + drop(RecorderLock::acquire(&finished).expect("lock")); + + assert_eq!(resolve_session(None, None, &root).expect("found"), new); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn the_environment_beats_the_search_and_the_flag_beats_the_environment() { + let root = scratch("order"); + let (old, _a) = running(&root, "20260101T000000Z"); + let (new, _b) = running(&root, "20260102T000000Z"); + + assert_eq!( + resolve_session(None, Some(old.clone().into()), &root).expect("env"), + old + ); + assert_eq!( + resolve_session(Some(&new), Some(old.into()), &root).expect("flag"), + new + ); + // an empty variable is not set + assert_eq!( + resolve_session(None, Some(String::new().into()), &root).expect("empty"), + new + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn nothing_running_says_how_to_name_a_session() { + let root = scratch("none"); + let error = resolve_session(None, None, &root).unwrap_err(); + assert_eq!( + envelope::exit_kind(&error), + envelope::ExitKind::NotFound, + "{error:?}" + ); + let message = format!("{error}"); + assert!(message.contains("--session") && message.contains(SESSION_ENV)); + + // not even a recordings directory + let error = resolve_session(None, None, &root.join("missing")).unwrap_err(); + assert_eq!(envelope::exit_kind(&error), envelope::ExitKind::NotFound); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn a_finished_session_is_refused_with_a_pointer_to_annotate() { + let root = scratch("finished"); + let finished = root.join("done"); + std::fs::create_dir_all(&finished).expect("create"); + drop(RecorderLock::acquire(&finished).expect("lock")); + + let error = resolve_session(Some(&finished), None, &root).unwrap_err(); + assert_eq!(envelope::exit_kind(&error), envelope::ExitKind::Usage); + assert!(format!("{error:?}").contains("annotate"), "{error:?}"); + + // no lock file at all is no recorder either + let bare = root.join("bare"); + std::fs::create_dir_all(&bare).expect("create"); + assert!(resolve_session(Some(&bare), None, &root).is_err()); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn a_marker_is_one_point_note_by_the_script() { + let root = scratch("line"); + let (dir, _lock) = running(&root, "now"); + + let marked = write_mark(&dir, "step 3: move window right", MarkKind::Note).expect("mark"); + let text = std::fs::read_to_string(dir.join(annotations::ANNOTATIONS_FILE)).expect("read"); + assert_eq!(text.lines().count(), 1); + assert!(text.ends_with('\n')); + + let line: serde_json::Value = serde_json::from_str(text.trim()).expect("json"); + assert_eq!(line["v"], 1); + assert_eq!(line["id"], marked.id.as_str()); + assert_eq!(line["op"], "add"); + assert_eq!(line["kind"], "note"); + assert_eq!(line["author"], "script"); + assert_eq!(line["title"], ""); + assert_eq!(line["text"], "step 3: move window right"); + assert_eq!(line["start_mach_ns"], line["end_mach_ns"]); + assert_eq!(line["start_mach_ns"].as_u64(), Some(marked.at_mach_ns)); + + let loaded = annotations::load(&dir).expect("load"); + let note = loaded.get(&marked.id).expect("read back"); + assert!(!note.open_ended()); + // no manifest here, so only the wall time is known + assert_eq!(marked.video_s, None); + assert!(marked.at_wall_utc.is_some()); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn blank_text_is_refused_and_writes_nothing() { + let root = scratch("blank"); + let (dir, _lock) = running(&root, "now"); + let error = write_mark(&dir, " ", MarkKind::Note).unwrap_err(); + assert_eq!(envelope::exit_kind(&error), envelope::ExitKind::Usage); + assert!(!dir.join(annotations::ANNOTATIONS_FILE).exists()); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/komorebi-recorder/src/cli/mod.rs b/komorebi-recorder/src/cli/mod.rs index 79c9c2c7..6073ba09 100644 --- a/komorebi-recorder/src/cli/mod.rs +++ b/komorebi-recorder/src/cli/mod.rs @@ -10,8 +10,9 @@ mod annotate; mod doctor; mod findings; mod investigate; -pub mod outputs; mod logq; +pub mod mark; +pub mod outputs; mod query; mod record; pub mod refspec; @@ -147,6 +148,8 @@ pub enum Command { Annotate(AnnotateArgs), /// List a session's bug regions, notes and findings Annotations(AnnotationsArgs), + /// Drop a named marker onto the timeline of a recording that is still going + Mark(mark::MarkArgs), /// Rebuild a session's timeline from its raw files, recovering it first if the recorder died Reindex(ReindexArgs), /// Check the video-to-clock alignment against a rendered on-screen clock @@ -222,6 +225,7 @@ impl Command { Self::Compare(args) => args.json, Self::Annotate(args) => args.json(), Self::Annotations(args) => args.json, + Self::Mark(args) => args.json, Self::Doctor(args) => args.json, Self::Record(args) => args.json, Self::Displays(args) => args.json, @@ -294,6 +298,7 @@ pub fn run(command: Command) -> eyre::Result<()> { Command::Findings(args) => findings::findings(&args), Command::Annotate(args) => annotate::annotate(&args), Command::Annotations(args) => annotate::list(&args), + Command::Mark(args) => mark::mark(&args), Command::Reindex(args) => reindex(&args), Command::Selftest(args) => crate::selftest::run(&args), Command::SelftestClock => crate::selftest::run_clock(), diff --git a/komorebi-recorder/src/guide.md b/komorebi-recorder/src/guide.md index 0a8c96b7..893c6b03 100644 --- a/komorebi-recorder/src/guide.md +++ b/komorebi-recorder/src/guide.md @@ -32,6 +32,9 @@ not listed), what looked wrong and for how long, the state as the bug began and what differs, what happened to the machine nearby (a display unplugged, a sleep), and the events most worth tracing first with the reason each was chosen. +Notes by the author `script` are markers a script dropped while recording (`komorebi-recorder mark`), +naming the steps of the repro; read them as the timeline of what was being done. + Check `skew` before trusting any source location: it says whether komorebi's source is the commit that was recorded. If not, check out the recorded commit and rebuild the recorder, or treat source locations as hints. diff --git a/komorebi-recorder/src/viewer/lanes.rs b/komorebi-recorder/src/viewer/lanes.rs index 277f53af..2dd59fff 100644 --- a/komorebi-recorder/src/viewer/lanes.rs +++ b/komorebi-recorder/src/viewer/lanes.rs @@ -458,6 +458,27 @@ impl Open { } } + // notes, and the markers a script dropped with `mark`: a tick, in the bugs lane + for note in self.loaded.notes() { + let x = view.x(note.start_video_s, left, width); + if x < left || x > area.right() { + continue; + } + let selected = self.selected_bug.as_deref() == Some(note.id.as_str()); + let colour = if selected { + Color32::WHITE + } else { + Color32::from_rgb(120, 190, 235) + }; + painter.line_segment( + [ + Pos2::new(x, bugs_strip.top() + 1.0), + Pos2::new(x, bugs_strip.bottom() - 1.0), + ], + Stroke::new(2.0_f32, colour), + ); + } + // the range being picked if let Some((from, to)) = self.selection { let (x0, x1) = (view.x(from, left, width), view.x(to, left, width)); @@ -821,7 +842,13 @@ impl Open { .find(|bug| { time >= bug.start_video_s - reach && time <= bug.end_video_s + reach }) - .map(|bug| (bug.id.clone(), bug.start_video_s)); + .map(|bug| (bug.id.clone(), bug.start_video_s)) + .or_else(|| { + self.loaded + .notes() + .find(|note| (note.start_video_s - time).abs() <= reach) + .map(|note| (note.id.clone(), note.start_video_s)) + }); match hit { Some((id, start)) => { self.selected_bug = Some(id); @@ -918,6 +945,20 @@ impl Open { timecode::format(bug.end_video_s), bug.text ) + }) + .or_else(|| { + self.loaded + .notes() + .find(|note| (note.start_video_s - time).abs() <= reach) + .map(|note| { + format!( + "{} ยท note by {} +{}", + timecode::format(note.start_video_s), + note.author, + note.text + ) + }) }), Some(Lane::Screen) => self.changes.as_ref().and_then(|changes| { changes diff --git a/komorebi-recorder/src/viewer/loaded.rs b/komorebi-recorder/src/viewer/loaded.rs index fae069c0..75b6b8d3 100644 --- a/komorebi-recorder/src/viewer/loaded.rs +++ b/komorebi-recorder/src/viewer/loaded.rs @@ -235,6 +235,14 @@ impl Loaded { .filter(|annotation| annotation.kind == annotations::Kind::Bug) } + /// Returns the notes (the annotations of kind [`Kind::Note`](annotations::Kind::Note)), in + /// time order. A marker dropped by `mark` is one, with the same start and end. + pub fn notes(&self) -> impl Iterator { + self.annotations + .iter() + .filter(|annotation| annotation.kind == annotations::Kind::Note) + } + /// Returns the event with sequence number `seq`, if there is one. /// /// The search is linear in the number of events. diff --git a/komorebi-recorder/tests/mark.rs b/komorebi-recorder/tests/mark.rs new file mode 100644 index 00000000..c6d2a4d5 --- /dev/null +++ b/komorebi-recorder/tests/mark.rs @@ -0,0 +1,118 @@ +//! `mark` through the real binary, against a synthetic session whose recorder lock is held by the +//! test, the way a recorder holds it. + +use komorebi_recorder::lock::RecorderLock; +use komorebi_recorder::testkit::SessionBuilder; +use serde_json::Value; +use std::process::Command; +use std::process::Output; + +fn recorder(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_komorebi-recorder")) + .args(args) + // never pick up the environment of whoever runs the tests + .env_remove("KOMOREBI_RECORDER_SESSION") + .output() + .expect("run komorebi-recorder") +} + +fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +fn json(output: &Output) -> Value { + serde_json::from_slice(&output.stdout) + .unwrap_or_else(|error| panic!("not JSON ({error}): {}", stdout(output))) +} + +#[test] +fn a_marker_lands_on_a_session_being_recorded_and_is_listed_like_a_note() { + let (session, _) = SessionBuilder::new("mark-running").build(); + let dir = session.dir.display().to_string(); + let _lock = RecorderLock::acquire(&session.dir).expect("hold the recorder lock"); + + // `annotations` and `brief` refuse nothing here, but `view`-style loading would: marking must + // not depend on it + let first = recorder(&["mark", "step 1: open it", "--session", &dir]); + assert!( + first.status.success(), + "{}", + String::from_utf8_lossy(&first.stderr) + ); + let text = stdout(&first); + assert!(text.starts_with("marked "), "{text}"); + assert!( + text.contains("(a-") && text.trim_end().ends_with("step 1: open it"), + "{text}" + ); + + let second = recorder(&["mark", "step 2", "--session", &dir, "--json"]); + assert!(second.status.success()); + let envelope = json(&second); + assert_eq!(envelope["schema"], "mark/1"); + assert_eq!(envelope["ok"], true); + assert_eq!(envelope["data"]["kind"], "note"); + assert_eq!(envelope["data"]["text"], "step 2"); + assert!(envelope["data"]["at_mach_ns"].as_u64().is_some()); + + let listed = recorder(&["annotations", &dir, "--json", "--kind", "note"]); + let annotations = json(&listed)["data"]["annotations"].clone(); + let annotations = annotations.as_array().expect("array"); + assert_eq!(annotations.len(), 2); + for note in annotations { + assert_eq!(note["author"], "script"); + assert_eq!(note["open_ended"], false); + assert_eq!(note["start_mach_ns"], note["end_mach_ns"]); + } + + let brief = json(&recorder(&["brief", &dir, "--json"])); + assert_eq!( + brief["data"]["notes"].as_array().map(Vec::len), + Some(2), + "{brief}" + ); +} + +#[test] +fn the_environment_names_the_session() { + let (session, _) = SessionBuilder::new("mark-env").build(); + let _lock = RecorderLock::acquire(&session.dir).expect("hold the recorder lock"); + + let output = Command::new(env!("CARGO_BIN_EXE_komorebi-recorder")) + .args(["mark", "from the environment"]) + .env("KOMOREBI_RECORDER_SESSION", &session.dir) + .output() + .expect("run"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let file = std::fs::read_to_string(session.dir.join("annotations.jsonl")).expect("written"); + assert!(file.contains("from the environment")); +} + +#[test] +fn a_finished_session_is_refused_and_pointed_at_annotate() { + let (session, _) = SessionBuilder::new("mark-finished").build(); + let dir = session.dir.display().to_string(); + + let output = recorder(&["mark", "too late", "--session", &dir, "--json"]); + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("annotate")); + assert_eq!(json(&output)["ok"], false); + assert!(!session.dir.join("annotations.jsonl").exists()); +} + +#[test] +fn no_session_to_mark_is_not_found() { + let missing = std::env::temp_dir().join("komorebi-recorder-no-such-session"); + let output = recorder(&[ + "mark", + "nobody is listening", + "--session", + &missing.display().to_string(), + ]); + assert_eq!(output.status.code(), Some(3)); + assert!(String::from_utf8_lossy(&output.stderr).contains("not a session directory")); +}