//! What people and agents say about a recording: where a bug starts and ends, notes, findings. //! //! The most important annotation is the **bug region**: the stretch of the recording during which //! the user saw something wrong, with a description of what it looked like. It is the ground truth //! of *what* went wrong that every investigation starts from; the rest of the session is evidence //! of *why*. An agent's conclusion is written back as a `finding` that points at its evidence. //! //! They live in `annotations.jsonl`, one JSON object per line, **append-only**: the viewer and an //! agent may both add to it, even while the recording is still running, and a crash //! mid-write can only damage the last line. Changing or removing an annotation appends an `edit` or //! `delete` line for its id; reading folds the lines in order. Times are on the master clock //! (`*_mach_ns`), not in video seconds, so they stay right if `reindex` moves video t=0. //! //! A region whose end was never set is *open-ended*: the bug was still happening when the recording //! stopped. Readers treat it as ending when the recording did and say so. //! //! # The three kinds //! //! | [`Kind`] | What it is | Written by | //! |---|---|---| //! | [`Kind::Bug`] | a region of the recording where the bug was visible, in the user's words | the viewer, `komorebi-recorder annotate` (author [`AUTHOR_USER`]) | //! | [`Kind::Note`] | a remark about a moment or region | `komorebi-recorder annotate` | //! | [`Kind::Finding`] | an agent's conclusion about the cause of a bug, with [`Ref`]s to its evidence | `komorebi-recorder annotate` (author `agent` unless told otherwise) | //! //! The kind is a lowercase word in the file, and prints the same way: //! //! ```rust //! use komorebi_recorder::annotations::Kind; //! //! assert_eq!(Kind::Finding.to_string(), "finding"); //! assert_eq!(serde_json::to_string(&Kind::Bug)?, r#""bug""#); //! assert_eq!(serde_json::from_str::(r#""note""#)?, Kind::Note); //! # Ok::<(), Box>(()) //! ``` //! //! # Writing and reading //! //! | To | Use | Lines appended | //! |---|---|---| //! | add an annotation | [`add`] with a [`New`] | one `add` | //! | change one | [`edit`] with a [`Patch`] | one `edit` carrying only the changed fields | //! | remove one | [`delete`] | one `delete`, a tombstone: the earlier lines stay | //! | read them | [`load`], or [`fold`] over text already read | none | //! | check evidence | [`validate_refs`] | none | //! //! Every write goes through [`append`], which serializes writers on `annotations.lock` and //! closes off a line a crashed writer left unterminated. [`fold`] never fails: a line it cannot //! understand is skipped and reported in [`Loaded::warnings`], and the rest of the file is still //! read. //! //! # What is enforced here, and what is not //! //! This module checks that an end is not before its start ([`add`], [`edit`]) and, on request, that //! evidence exists ([`validate_refs`]). It does not require a bug to have a description, a finding //! to have evidence, or a finding to name the bug it is about. //! [`Annotation::needs_description`] flags a bug that is still without a description. `komorebi-recorder annotate add` is stricter (it requires a //! description, and evidence for a finding), and a hand-written line is held to neither: [`fold`] //! accepts it. //! //! # Example //! //! A user marks a region that is still open, adds the description afterwards, and an agent records //! its conclusion. All of it is lines in one file, folded on read: //! //! ```rust //! use komorebi_recorder::annotations::{Kind, Ref, fold}; //! //! let text = [ //! r#"{"v":1,"id":"a-00000001","op":"add","kind":"bug","start_mach_ns":2000000000}"#, //! r#"{"v":1,"id":"a-00000001","op":"edit","end_mach_ns":5000000000,"text":"tiles overlap"}"#, //! r#"{"v":1,"id":"a-00000002","op":"add","kind":"finding","start_mach_ns":2000000000,"about":"a-00000001","refs":[{"kind":"event","seq":12}]}"#, //! ] //! .join("\n"); //! //! let loaded = fold(&text); //! assert!(loaded.warnings.is_empty()); //! //! let bug = loaded.get("a-00000001").expect("the bug"); //! assert_eq!(bug.kind, Kind::Bug); //! assert_eq!(bug.end_mach_ns, Some(5_000_000_000)); //! assert_eq!(bug.text, "tiles overlap"); //! //! let finding = loaded.get("a-00000002").expect("the finding"); //! assert_eq!(finding.about.as_deref(), Some("a-00000001")); //! assert_eq!(finding.refs, [Ref::Event { seq: 12 }]); //! ``` //! //! Writing goes through the file system; [`add`], [`edit`], [`delete`] and [`load`] have examples //! that use a temporary session directory. use crate::analysis::envelope; use crate::analysis::flavor::Flavor; use crate::analysis::guard::SessionPath; use crate::analysis::guard::is_plain_relative; use crate::analysis::ids; use crate::clock; use crate::clock::ClockMap; use crate::session::Manifest; use crate::session::Session; use crate::timeline; use color_eyre::eyre; use color_eyre::eyre::WrapErr; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; use std::collections::BTreeMap; use std::fmt; use std::fs::OpenOptions; use std::io::Read; use std::io::Seek; use std::io::SeekFrom; use std::io::Write; use std::path::Path; use std::path::PathBuf; use std::str::FromStr; /// The name, inside a session directory, of the file the annotations are appended to. pub const ANNOTATIONS_FILE: &str = "annotations.jsonl"; /// The name, inside a session directory, of the file writers lock so that their lines do not /// interleave. /// /// It is created empty and nothing is ever written to it. It is a separate file because Windows /// locks are mandatory: locking [`ANNOTATIONS_FILE`] itself would make it unreadable for everyone /// else while a line is added. pub const ANNOTATIONS_LOCK_FILE: &str = "annotations.lock"; /// The version written to every line. /// /// [`fold`] skips a line whose version is greater than this one, and reports it in /// [`Loaded::warnings`]. A line with a lower version is read as written. pub const LINE_VERSION: u32 = 1; /// The author recorded when none is given: [`add`] uses it for a [`New`] without an author, and /// [`fold`] for an `add` line without one. pub const AUTHOR_USER: &str = "user"; /// The kind of an annotation: `bug`, `note` or `finding`. /// /// The kind is fixed when the annotation is added: an edit cannot change it. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "lowercase")] pub enum Kind { /// A region where the bug was visible, described by the user. Bug, /// A remark about a moment or a region. Note, /// An agent's conclusion about what caused a bug, pointing at its evidence. Finding, } impl fmt::Display for Kind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::Bug => "bug", Self::Note => "note", Self::Finding => "finding", }) } } /// The operation a [`Line`] performs on the annotation it names. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Op { /// Creates the annotation. A line with no `op` is an `add`. Add, /// Changes the fields the line carries and leaves the rest as they were. Edit, /// Removes the annotation. The id cannot be added again. Delete, } /// Evidence a finding points at. /// /// Each kind names something in the session, or in komorebi's source, that a reader can open; the /// annotate command checks that it exists. On the command line a reference is written `event:12`, /// `log:345`, `log:oslog/komorebi.ndjson:77`, `code:komorebi/src/window.rs:210` or `frame:12.5`. /// In `annotations.jsonl` and in `--json` output it is an object tagged with `kind`, such as /// `{"kind":"event","seq":12}`. /// /// The text form is read by [`str::parse`] and printed by [`Display`](fmt::Display); the example is /// on the [`FromStr`] implementation, and [`validate_refs`] does the checking. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Ref { /// A komorebi subscriber event. Event { /// The event's sequence number, as in `events.jsonl` and the `#` of the `events` /// command. seq: u64, }, /// A line of a recorded text file (the komorebi log slice by default). Log { /// The file, as a path relative to the session directory. file: String, /// The line, counted from 1. line: u64, }, /// A line of komorebi's source, relative to the repository root. Code { /// The file, as a path relative to the root of komorebi's repository. path: String, /// The line, counted from 1. line: u64, }, /// A moment in the video. Frame { /// Seconds of video time: from the first frame of any display. video_s: f64, }, } /// The file `log:` refers to when it names no file: komorebi's plaintext log in the session /// directory. pub const DEFAULT_LOG_FILE: &str = "komorebi.log"; impl fmt::Display for Ref { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Event { seq } => write!(f, "event:{seq}"), Self::Log { file, line } => write!(f, "log:{file}:{line}"), Self::Code { path, line } => write!(f, "code:{path}:{line}"), Self::Frame { video_s } => write!(f, "frame:{}", crate::timecode::format(*video_s)), } } } impl FromStr for Ref { type Err = eyre::Report; /// Reads a reference: `event:12`, `log:345`, `log:oslog/komorebi.ndjson:77`, /// `code:komorebi/src/window.rs:210` or `frame:12.5`. /// /// For `log:` and `code:` the line is what follows the last colon. A `log:` whose rest is a /// whole number is a line of [`DEFAULT_LOG_FILE`]. The time of a `frame:` is any form /// [`crate::timecode::parse`] reads. [`Display`](fmt::Display) prints the same forms, with the /// file of a `log:` always spelled out. /// /// # Errors /// /// Returns a usage error (`komorebi-recorder` exits with code 2 on it) when the text has no /// colon, the kind is not `event`, `log`, `code` or `frame`, the sequence number is not a whole /// number, or a `log:` or `code:` does not end in a colon and a whole number. A `frame:` whose /// time cannot be parsed returns the error of [`crate::timecode::parse`], which is an ordinary /// error (exit code 1). /// /// This only checks the spelling; whether the thing exists is [`validate_refs`]'s question. /// /// # Example /// /// ```rust /// use komorebi_recorder::annotations::Ref; /// /// let evidence: Ref = "code:komorebi/src/window.rs:210".parse()?; /// assert_eq!( /// evidence, /// Ref::Code { path: "komorebi/src/window.rs".to_string(), line: 210 }, /// ); /// assert_eq!( /// serde_json::to_string(&evidence)?, /// r#"{"kind":"code","path":"komorebi/src/window.rs","line":210}"#, /// ); /// /// // `log:` means the komorebi log; printing spells the file out /// let line: Ref = "log:345".parse()?; /// assert_eq!(line.to_string(), "log:komorebi.log:345"); /// assert_eq!(line.to_string().parse::()?, line); /// /// // a video time is printed as a timecode /// let frame: Ref = "frame:12.5".parse()?; /// assert_eq!(frame.to_string(), "frame:00:12.500"); /// /// // a malformed reference is refused, and says what was expected /// let error = "cat:1".parse::().unwrap_err(); /// assert_eq!(error.to_string(), "'cat:1': unknown kind of reference"); /// # Ok::<(), Box>(()) /// ``` fn from_str(input: &str) -> Result { let bad = |why: &str| envelope::usage(format!("'{input}': {why}")); let (kind, rest) = input.split_once(':').ok_or_else(|| { bad("expected event:, log:, code:: or frame: