diff --git a/Cargo.lock b/Cargo.lock index 24134d38..4de535bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -136,6 +136,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + [[package]] name = "android-activity" version = "0.6.1" @@ -1920,6 +1929,7 @@ dependencies = [ "parking_lot", "png", "proc-macro2", + "regex", "schemars", "serde", "serde_json_lenient", @@ -2933,6 +2943,35 @@ dependencies = [ "syn", ] +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + [[package]] name = "renderdoc-sys" version = "1.1.0" diff --git a/README.md b/README.md index 540cf7b9..b6f385ba 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,31 @@ with `--log-level trace` first: the recorder never changes komorebi's log level, `--no-video` has everything but the screen. [Recording a bug repro](docs/usage/recording-a-bug-repro.md) has the rest: what is captured on each OS, docking, sleep and lock, and recovering a recording after a crash. +## Investigate it + +```sh +komorebi-recorder brief ./repro # what the user marked as the bug, and what the recording shows around it +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 +``` + +For example, a four second recording of a Mac with komorebi running: + +```text +$ komorebi-recorder overview ./repro +session /private/tmp/kr-sample: 4 s of video, 2 events, 2 log lines, 1 incidents + +findings, most worth looking at first (1 of 1): + info 00:00.631 incident:recorder recorder: recording started without video; komorebi pid 2732 + +when things happened (events | errors | incidents): + 00:00.500 ############################## 1 0 1 + 00:04.500 ############################## 1 0 0 +``` + +Every command takes `--json`, and `komorebi-recorder guide` prints a playbook for an agent. +[Investigating a recording](docs/usage/investigating-a-recording.md) walks through both ways of working. + ## How it fits together Two things vary independently: the _host_ the recorder runs on (macOS or Windows) and the _flavor_ of komorebi it diff --git a/dependencies.json b/dependencies.json index 35d60ad1..e59e4cc5 100644 --- a/dependencies.json +++ b/dependencies.json @@ -128,6 +128,9 @@ "raw-window-handle 0.6.2 registry+https://github.com/rust-lang/crates.io-index", "ref-cast 1.0.25 registry+https://github.com/rust-lang/crates.io-index", "ref-cast-impl 1.0.25 registry+https://github.com/rust-lang/crates.io-index", + "regex 1.12.3 registry+https://github.com/rust-lang/crates.io-index", + "regex-automata 0.4.14 registry+https://github.com/rust-lang/crates.io-index", + "regex-syntax 0.8.10 registry+https://github.com/rust-lang/crates.io-index", "rustc-demangle 0.1.27 registry+https://github.com/rust-lang/crates.io-index", "rustix 1.1.4 registry+https://github.com/rust-lang/crates.io-index", "ryu 1.0.23 registry+https://github.com/rust-lang/crates.io-index", @@ -248,6 +251,7 @@ "addr2line 0.25.1 registry+https://github.com/rust-lang/crates.io-index", "adler2 2.0.1 registry+https://github.com/rust-lang/crates.io-index", "ahash 0.8.12 registry+https://github.com/rust-lang/crates.io-index", + "aho-corasick 1.1.4 registry+https://github.com/rust-lang/crates.io-index", "anstream 1.0.0 registry+https://github.com/rust-lang/crates.io-index", "anstyle 1.0.14 registry+https://github.com/rust-lang/crates.io-index", "anstyle-parse 1.0.0 registry+https://github.com/rust-lang/crates.io-index", @@ -366,6 +370,9 @@ "raw-window-handle 0.6.2 registry+https://github.com/rust-lang/crates.io-index", "ref-cast 1.0.25 registry+https://github.com/rust-lang/crates.io-index", "ref-cast-impl 1.0.25 registry+https://github.com/rust-lang/crates.io-index", + "regex 1.12.3 registry+https://github.com/rust-lang/crates.io-index", + "regex-automata 0.4.14 registry+https://github.com/rust-lang/crates.io-index", + "regex-syntax 0.8.10 registry+https://github.com/rust-lang/crates.io-index", "rustc-demangle 0.1.27 registry+https://github.com/rust-lang/crates.io-index", "rustix 1.1.4 registry+https://github.com/rust-lang/crates.io-index", "schemars 1.2.1 registry+https://github.com/rust-lang/crates.io-index", @@ -494,6 +501,7 @@ [ "Unlicense", [ + "aho-corasick 1.1.4 registry+https://github.com/rust-lang/crates.io-index", "byteorder-lite 0.1.0 registry+https://github.com/rust-lang/crates.io-index", "memchr 2.8.0 registry+https://github.com/rust-lang/crates.io-index" ] diff --git a/docs/usage/investigating-a-recording.md b/docs/usage/investigating-a-recording.md new file mode 100644 index 00000000..43337218 --- /dev/null +++ b/docs/usage/investigating-a-recording.md @@ -0,0 +1,90 @@ +# Investigating a Recording + +A [recording](recording-a-bug-repro.md) answers "what was komorebi doing when this went wrong?" if you can read it. +`komorebi-recorder` has commands that do the reading, built so that a person or an agent can go from "the user says +this is broken" to "this is the line of komorebi that causes it" using what was recorded rather than guessing. + +``` +komorebi-recorder brief # start here +komorebi-recorder guide # the playbook, for an agent +``` + +Every command takes `--json`, which prints an envelope `{ok, schema, data, warnings, truncated, next_cursor, error}`; +`komorebi-recorder schema` lists the schemas and `komorebi-recorder schema brief/1` prints one. Exit codes: 0 ok, 1 +error, 2 usage, 3 not found, 4 the session cannot answer (still recording, or the recorder died: `reindex` it), 5 over +budget. + +Everything a recording holds is available from the command line, so an agent can investigate headlessly: + +## What the user said + +The first thing in a [brief](#brief) is the **bug region**: the stretch of the recording the user marked, with their +description of what is wrong and what they expected. +Add one with `annotate`: + +``` +komorebi-recorder annotate add --kind bug --start 12.5 --end 18 \ + --text "the new window opens on the wrong monitor" --expected "it should open on the focused one" +komorebi-recorder annotations +``` + +Times can be a video timecode (`12.5`, `1:02.5`), `wall:`, `event:`, `log:`, `incident:` or +`bug:` (`.start` or `.end`), each with an offset such as `+3s`. `event:12` is when komorebi began handling event 12 +and `event:12.end` when it finished. + +## Commands + +| Command | What it tells you | +| --- | --- | +| `brief` | The bug region(s) in the user's words, then what the recording shows around them: the events, what looked wrong, the state as it began and ended, what happened to the machine, and the events most worth tracing first, with why | +| `overview` | The whole recording at a glance: what stands out, ranked (states that are wrong and for how long, windows that flap, event storms, slow handlers, errors, a display unplugged), anything near a bug region first | +| `state --at T` | What komorebi believed at a moment, and anything inconsistent in it: a window parked off screen on a workspace that is showing, a window in two places, a layout that was not applied | +| `diff A B` | What changed between two moments in terms a person would use: a window appeared, moved, was really somewhere else; focus moved; a monitor came or went | +| `events` | komorebi's events, classified (command, focus, lifecycle, drag, monitor, lock, and `echo`: the OS reporting back a move komorebi made itself), with the handler that ran and whether the state changed | +| `trace event:N` | One event end to end: what its handler logged, with the source statement for each line, what other threads logged meanwhile, and every change with who made it (see below). `--os` adds the OS trace around it: komorebi's own calls into the OS, the system and each application, split into while the handler ran and after | +| `window ID\|TEXT` | One window's life: when it appeared, moved, was parked off screen, was really somewhere else, and which event did each | +| `code event:N`, `code log:N` | The line of komorebi's source that wrote a log line, with the code around it | +| `search TEXT` | Where a word appears: komorebi's log, events, incidents, annotations (and `--oslog` for the macOS trace) | +| `annotate`, `annotations` | Add, change and list bug regions, notes and findings | + +### Who changed it + +komorebi sends the state _after_ each event, so what an event changed is the difference from the previous one. That +includes whatever background threads did since: the reaper (removes windows that no longer exist) and the workspace +reconciliator (moves windows between workspaces after a space change) change state **without sending a notification**. +`trace` therefore gives each change an _attribution_ with its evidence and how sure it is: `handler`, `reaper` (when its +log line names the window), `workspace-reconciliator`, or `unexplained`, which means state changed and nothing in the log +accounts for it. That is a finding in itself. + +### From a log line to the source + +komorebi's log says what happened but not where in its code. The recorder is built with an index of every `tracing` +statement in komorebi's source; `code` matches a recorded line to the statement that wrote it, says when several +statements read alike (`ambiguous`) or only print a value (`generic`), and flags the reaper and workspace reconciliator. + +A mapping is only as good as the source it was made against, so every answer says whether the source the recorder was +built from is the komorebi that was recorded, by comparing the commit the recorded binary reports with the indexed +source and naming the files that differ. Lines in files that did not change are exactly as good as if the commits were +the same. + +### What the data cannot tell you + +- The event timestamp is when komorebi finished the handler. Time spent waiting for its lock or in accessibility calls + before the handler's first log line is invisible, so `handler_ms` is a lower bound. +- At the default `info` level there is no log line for the end of an event handler, and few for the decisions inside it. + Start komorebi with `--log-level trace` before recording a bug you intend to investigate. +- The `rect` of a window in the state is read live from the accessibility API when the state is serialized: it is where + the window really was, which is what makes comparing it with where komorebi's layout put it meaningful. +- An `AXError` in komorebi's log comes from the application or the OS, not from komorebi. + +## Recording what you conclude + +``` +komorebi-recorder annotate add --kind finding --about \ + --text "the Show handler tiles the window onto the display that is going away" \ + --ref event:12 --ref log:340 --ref code:komorebi/src/process_event.rs:512 +``` + +A finding with no evidence is refused, and every reference is checked to exist: the event, the log line, the video time, +the line of komorebi's source. Findings are stored in `annotations.jsonl` beside the bug region, so the person who +recorded the bug can see what was concluded and why. diff --git a/docs/usage/recording-a-bug-repro.md b/docs/usage/recording-a-bug-repro.md index c5559f4c..7387ec30 100644 --- a/docs/usage/recording-a-bug-repro.md +++ b/docs/usage/recording-a-bug-repro.md @@ -198,6 +198,7 @@ komorebi.log exact slice of komorebi's own log events.jsonl, states/ subscriber notifications; full State stored only when it changed state-start.json, state-end.json recorder.jsonl what happened to the recording environment (displays, sleep/wake, lock, restarts) +annotations.jsonl bug regions, notes and findings (appended, never rewritten) oslog/komorebi.ndjson unified log, komorebi's process (oslog/komorebi-.ndjson after a restart) oslog/system.ndjson unified log, accessibility / SkyLight / workspace subsystems oslog/apps/-.ndjson unified log, one managed application diff --git a/komorebi-recorder/Cargo.toml b/komorebi-recorder/Cargo.toml index aea44013..c6d9d594 100644 --- a/komorebi-recorder/Cargo.toml +++ b/komorebi-recorder/Cargo.toml @@ -16,6 +16,7 @@ dunce = { workspace = true } eframe = { workspace = true } parking_lot = { workspace = true } png = "0.18" +regex = "1" schemars = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/komorebi-recorder/src/analysis/brief.rs b/komorebi-recorder/src/analysis/brief.rs new file mode 100644 index 00000000..c18deb74 --- /dev/null +++ b/komorebi-recorder/src/analysis/brief.rs @@ -0,0 +1,574 @@ +//! The first thing an investigator reads: what the user says is wrong, and what the recording shows +//! around it. +//! +//! The user's bug region and description are the ground truth of *what* went wrong and come first, +//! verbatim. Everything after them is evidence of *why*, drawn from the recording: the events in the +//! region (with komorebi's own echoes counted but not listed), what looked wrong and for how long, +//! the state as the bug began and as it ended and the difference, what happened to the machine +//! nearby, and the few events most worth tracing first, each with the reason it was chosen. +//! +//! [`Analysis::brief`] makes a [`BriefData`]: one [`BugBrief`] for each bug region the user marked, +//! each holding a [`RegionBrief`] of what the recording shows around it. A recording with no bug +//! marked gets the same digest over the whole recording instead ([`BriefData::whole_session`]). +//! +//! # What a region covers +//! +//! | Part | What it holds | Cut off at | +//! |---|---|---| +//! | the region | the bug region, widened to start half of [`PRE_ROLL_NS`] (five seconds) before it so that causes just before it are inside; the end is the bug's end, or the end of the recording for an open-ended region | | +//! | [`RegionEvents`] | the events received in the region, counted by class; komorebi's own echoes are counted and not listed | 40 events listed | +//! | [`RegionBrief::findings`] | what looked wrong or unusual in or just before the region, ranked as in `overview` | 10 findings | +//! | [`RegionBrief::suspects`] | the events most worth tracing first | 5 suspects | +//! | [`RegionBrief::state_at_start`], [`RegionBrief::state_at_end`] | komorebi's state as the bug began and as the region ended, with anything wrong in it | | +//! | [`RegionBrief::changes`] | what differs between those two states | 40 changes, with the total in [`RegionBrief::changes_total`] | +//! | [`RegionBrief::incidents`] | what happened to the machine (a display unplugged, a sleep) within [`PRE_ROLL_NS`] of the region | | +//! +//! # How suspects are chosen +//! +//! Each event received in the region is scored, and the five with the highest scores are +//! returned, highest first and earliest first among equals. Echoes and komorebi's own synthetic +//! events ([`Class::Echo`], [`Class::Manual`]) are never suspects. An event with none of the +//! reasons below is not a suspect, whatever its class: +//! +//! | Reason | Score | +//! |---|---| +//! | it left the state wrong: a violation is present after it that was not before | +100 | +//! | its handler logged an error (or, failing that, a warning) | +50 (+25) | +//! | its handler was slow: at least 250 ms from its header to the event being received | +30 | +//! | it was received within a second of the start of the bug | +20 | +//! | it changed the state in a way a person would notice | +15 | +//! +//! Each event also starts from a base that depends on its class: 40 for a command, a monitor change +//! or a lock; 20 for a lifecycle event; 10 for a focus change; 5 for anything else. The scores are +//! a ranking aid, not a measure: they say which event to trace first, not how likely it is to be +//! the cause. +//! +//! Warnings about annotation lines that could not be read are not part of a brief; the +//! `annotations` command shows them. + +use super::Analysis; +use super::answers::ChangeView; +use super::answers::EventQuery; +use super::catalog::Skew; +use super::classify::Class; +use super::diff; +use super::invariants; +use super::invariants::Violation; +use super::overview::Finding; +use super::overview::IncidentView; +use super::overview::PRE_ROLL_NS; +use super::overview::SessionInfo; +use super::state::Focus; +use super::views::EventView; +use super::views::Moment; +use super::views::StateOrigin; +use crate::annotations::Annotation; +use crate::annotations::AnnotationView; +use crate::annotations::Kind; +use color_eyre::eyre; +use schemars::JsonSchema; +use serde::Serialize; +use std::collections::BTreeMap; + +/// The `schema` of the `brief` command's output: the name that [`BriefData`] has in an envelope. +pub const SCHEMA_BRIEF: &str = "brief/1"; + +/// How many non-echo events a brief lists for a region. +const LISTED_EVENTS: usize = 40; +const LISTED_CHANGES: usize = 40; +const LISTED_FINDINGS: usize = 10; +const LISTED_SUSPECTS: usize = 5; + +/// komorebi's state at one moment of a region, in a line and with anything wrong in it. +#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)] +pub struct StateBrief { + /// The moment the state is of. + pub at: Moment, + /// Which notification the state is from, and how old it was at `at`. + pub origin: Option, + /// How big the state is, in words: the number of monitors and windows. + pub summary: String, + /// What had the keyboard focus. + pub focus: Option, + /// What looks wrong in the state. + pub violations: Vec, +} + +/// An event worth tracing first, with why. +#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)] +pub struct Suspect { + /// The event. + pub event: EventView, + /// A ranking score: higher is more worth tracing. It means something only compared with the + /// other suspects of the same region. + pub score: i64, + /// Why this event is worth tracing. + pub reasons: Vec, + /// The command that traces it: `komorebi-recorder trace event:`. + pub next: String, +} + +/// The events received in a region, counted and the first of them listed. +#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)] +pub struct RegionEvents { + /// How many events there were, echoes included. + pub total: usize, + /// How many events there were of each class, keyed by the class name in lowercase. + pub by_class: BTreeMap, + /// Echoes of komorebi's own moves: counted above, not listed. + pub echoes_hidden: usize, + /// The events that are not echoes, in the order received, up to a limit of 40. + pub listed: Vec, + /// Whether there were more events that are not echoes than were listed. The `events` command, + /// with `--from` and `--to`, pages through the rest. + pub truncated: bool, +} + +/// What the recording shows around one stretch of time: the events, what looked wrong, the events +/// to trace first, the state at either end and what changed between them. +#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)] +pub struct RegionBrief { + /// The start of the region. For a bug region this is a few seconds before it starts, so causes + /// just before it are included; for the whole recording, the start of the video. + pub from: Moment, + /// The end of the region. + pub to: Moment, + /// The events received between `from` and `to`. + pub events: RegionEvents, + /// What looked wrong or unusual in or just before the region, most relevant first, up to a + /// limit of 10. + pub findings: Vec, + /// The events most worth tracing first, best first, up to a limit of 5. + pub suspects: Vec, + /// komorebi's state as the region began; `None` if no state had been recorded by then. + pub state_at_start: Option, + /// komorebi's state as the region ended; `None` if no state had been recorded by then. + pub state_at_end: Option, + /// What differs between the state at the start and at the end, up to a limit of 40. + pub changes: Vec, + /// How many differences there are in all, including any not listed in `changes`. + pub changes_total: usize, + /// What happened to the machine (a display unplugged, a sleep) in or near the region. + pub incidents: Vec, +} + +/// One bug region the user marked, and what the recording shows around it. +#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)] +pub struct BugBrief { + /// What the user said: the region, the description and what they expected. + pub bug: AnnotationView, + /// What the recording shows around the region. + pub region: RegionBrief, + /// Commands that dig further. + pub commands: Vec, +} + +/// The first thing an investigator reads, made by [`Analysis::brief`]. +#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)] +pub struct BriefData { + /// The facts about the recording an investigator wants first. + pub session: SessionInfo, + /// Whether komorebi's source is the version that was recorded. + pub skew: Skew, + /// One brief for each bug region the user marked, in the order of their start. Empty if none + /// was marked. + pub bugs: Vec, + /// With no bug marked: the same digest over the whole recording. + pub whole_session: Option, + /// Conclusions an earlier investigation recorded. + pub findings_recorded: Vec, + /// The notes people or agents wrote. + pub notes: Vec, + /// What to do next, as commands to run and questions to ask. + pub next: Vec, +} + +impl Analysis { + fn state_brief(&self, mach_ns: u64) -> Option { + let found = self.state_at(mach_ns).ok()?; + let data = self + .state_answer(mach_ns, &super::answers::StateQuery::default()) + .ok()?; + Some(StateBrief { + at: data.at, + origin: Some(data.origin), + summary: super::views::headline(&found.snapshot), + focus: data.focus, + violations: data.violations, + }) + } + + /// Score each event in `from..=to` by how likely it is to be where things went wrong. + fn suspects(&self, from_ns: u64, to_ns: u64, bug_start_ns: u64) -> Vec { + let events = self.events(); + let pairing = self.pairing(); + let mut ranked = Vec::new(); + + for (index, event) in events.iter().enumerate() { + if event.recv_mach_ns < from_ns || event.recv_mach_ns > to_ns { + continue; + } + + let class = pairing.classes[index].class; + if matches!(class, Class::Echo | Class::Manual) { + continue; + } + + let mut score = 0_i64; + let mut reasons = Vec::new(); + + score += match class { + Class::Command | Class::Monitor | Class::Lock => 40, + Class::Lifecycle => 20, + Class::Focus => 10, + _ => 5, + }; + + // did it leave the state wrong? + if let (Some(this), Some(before)) = ( + event.state_id, + index + .checked_sub(1) + .and_then(|before| events[before].state_id), + ) && this != before + && let (Ok(after), Ok(previous)) = (self.snapshot(this), self.snapshot(before)) + { + let (now, was) = (invariants::check(&after), invariants::check(&previous)); + let appeared: Vec<&Violation> = now.iter().filter(|v| !was.contains(v)).collect(); + if !appeared.is_empty() { + score += 100; + reasons.push(format!( + "left the state wrong: {}", + appeared + .iter() + .map(|violation| violation.kind.as_str()) + .collect::>() + .join(", ") + )); + } + if diff::diff(&previous, &after).is_empty() { + // the state was rewritten but nothing a person would notice changed + } else { + score += 15; + reasons.push("changed the state".to_string()); + } + } + + if let Some(handler) = &pairing + .pairs + .get(index) + .and_then(|pair| pair.block) + .and_then(|id| self.log().blocks.get(id)) + { + if handler.errors > 0 { + score += 50; + reasons.push(format!("its handler logged {} error(s)", handler.errors)); + } else if handler.warnings > 0 { + score += 25; + reasons.push(format!( + "its handler logged {} warning(s)", + handler.warnings + )); + } + } + if pairing.pairs[index] + .handler_ms + .is_some_and(|ms| ms >= 250.0) + { + score += 30; + reasons.push("its handler was slow".to_string()); + } + + // what happens as the bug begins matters most + let near_start = event.recv_mach_ns.abs_diff(bug_start_ns) <= 1_000_000_000; + if near_start { + score += 20; + reasons.push("right at the start of the region".to_string()); + } + + if reasons.is_empty() { + continue; + } + + if let Some(view) = self.event_view(index) { + ranked.push(Suspect { + next: format!( + "komorebi-recorder trace {} event:{}", + self.session.dir.display(), + event.seq + ), + event: view, + score, + reasons, + }); + } + } + + ranked.sort_by(|a, b| b.score.cmp(&a.score).then(a.event.seq.cmp(&b.event.seq))); + ranked.truncate(LISTED_SUSPECTS); + ranked + } + + fn region_brief( + &self, + from_ns: u64, + to_ns: u64, + bug_start_ns: u64, + findings: &[Finding], + ) -> eyre::Result { + let answer = self.events_answer(&EventQuery { + from_mach_ns: Some(from_ns), + to_mach_ns: Some(to_ns), + ..EventQuery::default() + }); + let mut by_class: BTreeMap = BTreeMap::new(); + for view in &answer.data.events { + *by_class + .entry(format!("{:?}", view.class).to_lowercase()) + .or_default() += 1; + } + let echoes = answer + .data + .events + .iter() + .filter(|view| view.class == Class::Echo) + .count(); + let real: Vec = answer + .data + .events + .into_iter() + .filter(|view| view.class != Class::Echo) + .collect(); + let truncated = real.len() > LISTED_EVENTS; + + let start = self.state_brief(from_ns.max(bug_start_ns.min(to_ns))); + let end = self.state_brief(to_ns); + let changes = match (self.state_at(bug_start_ns.min(to_ns)), self.state_at(to_ns)) { + (Ok(before), Ok(after)) => diff::diff(&before.snapshot, &after.snapshot), + _ => Vec::new(), + }; + let changes_total = changes.len(); + + let incidents: Vec = self + .incidents() + .into_iter() + .filter(|incident| { + let at = self.manifest.mach_at_video_seconds(incident.video_s); + at + PRE_ROLL_NS >= from_ns && at <= to_ns + PRE_ROLL_NS + }) + .collect(); + + Ok(RegionBrief { + from: self.moment(from_ns), + to: self.moment(to_ns), + events: RegionEvents { + total: real.len() + echoes, + by_class, + echoes_hidden: echoes, + listed: real.into_iter().take(LISTED_EVENTS).collect(), + truncated, + }, + findings: findings + .iter() + .filter(|finding| finding.end_mach_ns >= from_ns && finding.start_mach_ns <= to_ns) + .take(LISTED_FINDINGS) + .cloned() + .collect(), + suspects: self.suspects(from_ns, to_ns, bug_start_ns), + state_at_start: start, + state_at_end: end, + changes: changes + .into_iter() + .take(LISTED_CHANGES) + .map(|change| ChangeView { + text: change.describe(), + change, + }) + .collect(), + changes_total, + incidents, + }) + } + + /// Returns the brief of the session: one entry per bug region the user marked, or, if none, a + /// digest of the whole recording. + /// + /// See the [module docs](self) for what a region covers and how suspects are chosen. A bug's + /// region, description and expectation are returned as written, and the rest is evidence drawn + /// from the recording. A part of the brief that cannot be made (the state at a moment before any + /// state was recorded) is `None` or empty, and does not fail the brief. + /// + /// # Errors + /// + /// Returns an error if `annotations.jsonl` exists but cannot be read, or if one of the states + /// the recording refers to is missing or is not valid JSON (the search for what looked wrong + /// reads them all). + /// + /// # Example + /// + /// A user marked a region after a display went away. A focus change at 5.2 s left a window + /// parked off screen, and that is the first thing to trace: + /// + /// ```rust + /// use komorebi_recorder::analysis::Analysis; + /// use komorebi_recorder::annotations::{Kind, New, add}; + /// use komorebi_recorder::testkit::{ + /// SessionBuilder, container, mach_ns, monitor, state, window, workspace, + /// }; + /// use serde_json::json; + /// + /// let layout = [[0, 0, 500, 800], [500, 0, 500, 800]]; + /// // two tiled windows; the second is where the layout says, or parked off screen + /// let screen = |second: [i64; 4]| { + /// state( + /// vec![monitor( + /// 1, + /// [0, 0, 1000, 800], + /// vec![workspace( + /// "one", + /// vec![ + /// container("a", vec![window(1, "Ghostty", Some(layout[0]))]), + /// container("b", vec![window(2, "Brave", Some(second))]), + /// ], + /// 1, + /// &layout, + /// )], + /// 0, + /// )], + /// 0, + /// ) + /// }; + /// let focus = |what: &str| { + /// json!({"type": "FocusChange", "content": [{"type": "Accessibility", "content": what}, 11, 2]}) + /// }; + /// + /// let (session, _) = SessionBuilder::new("doc-brief") + /// .event(2.0, json!({"type": "Retile"}), Some(screen(layout[1]))) + /// .event(5.2, focus("AXApplicationActivated"), Some(screen([-499, 790, 500, 800]))) + /// .incident(4.9, "display-disconnected", "display 3 went away") + /// .build(); + /// add(&session.dir, New { + /// kind: Some(Kind::Bug), + /// start_mach_ns: mach_ns(4.5), + /// end_mach_ns: Some(mach_ns(7.0)), + /// text: "my Brave window is gone from the screen".to_string(), + /// ..New::default() + /// })?; + /// + /// let brief = Analysis::open(&session.dir)?.brief()?; + /// + /// // the user's words come first, verbatim + /// assert_eq!(brief.bugs[0].bug.text, "my Brave window is gone from the screen"); + /// + /// // the focus change left the state wrong, so it is the first suspect, and says why + /// let suspect = &brief.bugs[0].region.suspects[0]; + /// assert_eq!(suspect.event.seq, 2); + /// assert!(suspect.reasons[0].starts_with("left the state wrong")); + /// + /// // as the bug began the state was fine; as it ended it was not + /// let region = &brief.bugs[0].region; + /// assert!(region.state_at_start.as_ref().is_some_and(|s| s.violations.is_empty())); + /// assert!(region.state_at_end.as_ref().is_some_and(|s| !s.violations.is_empty())); + /// assert_eq!(region.incidents[0].kind, "display-disconnected"); + /// # Ok::<(), Box>(()) + /// ``` + /// + /// Covered, through the command, by the tests in `tests/brief.rs`, such as + /// `the_brief_leads_with_the_users_words_and_points_at_the_event_that_broke_it`. + pub fn brief(&self) -> eyre::Result { + let loaded = crate::annotations::load(&self.session.dir)?; + let bugs: Vec<&Annotation> = loaded.bugs().collect(); + let all = self.findings()?; + let dir = self.session.dir.display().to_string(); + + let mut briefs = Vec::new(); + for bug in &bugs { + let end = bug.end_or_session_end(&self.manifest); + let from = bug.start_mach_ns.saturating_sub(PRE_ROLL_NS / 2); + let ranked = self.rank(all.clone(), &[bug]); + let region = self.region_brief(from, end, bug.start_mach_ns, &ranked)?; + + let mut commands = vec![ + format!( + "komorebi-recorder events {dir} --from bug:{id} --to bug:{id}.end --hide-echo", + id = bug.id + ), + format!( + "komorebi-recorder diff {dir} bug:{id} bug:{id}.end", + id = bug.id + ), + ]; + if let Some(suspect) = region.suspects.first() { + commands.insert(0, suspect.next.clone()); + commands.push(format!( + "komorebi-recorder code {dir} event:{}", + suspect.event.seq + )); + } + if !self.manifest.displays.is_empty() { + commands.push(format!("komorebi-recorder sheet {dir} --bug {}", bug.id)); + commands.push(format!("komorebi-recorder changes {dir} --bug {}", bug.id)); + } + for window in region + .findings + .iter() + .flat_map(|finding| finding.window_ids.iter()) + .take(1) + { + commands.push(format!("komorebi-recorder window {dir} {window}")); + } + commands.push(format!( + "komorebi-recorder annotate {dir} add --kind finding --about {} --text '' --ref event: --ref code::", + bug.id + )); + + briefs.push(BugBrief { + bug: bug.view(&self.manifest), + region, + commands, + }); + } + + let whole_session = if bugs.is_empty() { + let end = crate::analysis::timespec::session_end_ns(&self.manifest); + let start = self.manifest.video_t0(); + let ranked = self.rank(all, &[]); + Some(self.region_brief(start, end, start, &ranked)?) + } else { + None + }; + + let mut next = Vec::new(); + if bugs.is_empty() { + next.push(format!( + "no bug region was marked: ask the user when it happened and what it looked like, \ + then `komorebi-recorder annotate {dir} add --kind bug --start --end --text ''`" + )); + } + next.push(format!("komorebi-recorder overview {dir}")); + next.push("komorebi-recorder guide".to_string()); + + let recorded: Vec = loaded + .annotations + .iter() + .filter(|annotation| annotation.kind == Kind::Finding) + .map(|annotation| annotation.view(&self.manifest)) + .collect(); + let notes: Vec = loaded + .annotations + .iter() + .filter(|annotation| annotation.kind == Kind::Note) + .map(|annotation| annotation.view(&self.manifest)) + .collect(); + + Ok(BriefData { + session: self.session_info(), + skew: self.skew(), + bugs: briefs, + whole_session, + findings_recorded: recorded, + notes, + next, + }) + } +} diff --git a/komorebi-recorder/src/analysis/budget.rs b/komorebi-recorder/src/analysis/budget.rs new file mode 100644 index 00000000..8a2125d4 --- /dev/null +++ b/komorebi-recorder/src/analysis/budget.rs @@ -0,0 +1,230 @@ +//! A limit on how much work one answer may do. +//! +//! A session can hold gigabytes of OS trace, and an agent's context window is small. Scans take a +//! [`Budget`] and stop when it runs out; a command then either returns what it has marked +//! `truncated` with a cursor, or fails with the "over budget" exit code if a partial answer would +//! mislead. +//! +//! A [`Budget`] has three limits: a deadline, a number of bytes read, and a flag that something else +//! (another thread, a signal handler) can set to cancel the work. A scan calls +//! [`Budget::charge`] with the size of each record it reads, or [`Budget::check`] where it reads +//! none, and the first [`Exceeded`] it gets is its cue to stop. A budget is a value, not a thread: +//! nothing interrupts a scan that does not ask, and the limits are enforced at the granularity the +//! scan checks. + +use std::fmt; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; +use std::time::Duration; +use std::time::Instant; + +/// Which limit of a [`Budget`] was hit. +/// +/// Its [`Display`](fmt::Display) completes a sentence about the work: `the search ran out of time`. +/// A command turns it into an "over budget" failure (the `Budget` exit kind of the `envelope` +/// module) with that sentence and a hint on how to narrow the request. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::budget::Exceeded; +/// +/// assert_eq!(Exceeded::Time.to_string(), "ran out of time"); +/// assert_eq!(Exceeded::Bytes.to_string(), "read more data than the budget allows"); +/// assert_eq!(Exceeded::Cancelled.to_string(), "was cancelled"); +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Exceeded { + /// The deadline passed. + Time, + /// More bytes were charged than the budget reads at most. + Bytes, + /// The budget's cancel flag was set. + Cancelled, +} + +impl fmt::Display for Exceeded { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Time => "ran out of time", + Self::Bytes => "read more data than the budget allows", + Self::Cancelled => "was cancelled", + }) + } +} + +impl std::error::Error for Exceeded {} + +/// How much time and data a scan may use, and a way to cancel it. +/// +/// The default is [`Budget::unlimited`]. Limits are added with [`Budget::within`] and +/// [`Budget::reading_at_most`]. Each returns the budget, so they chain. +/// +/// A clone is another handle on the same budget as far as bytes and cancellation go: the count of +/// bytes charged and the cancel flag are shared between a budget and every clone of it, so a limit +/// applies across the threads a scan is split over. The deadline and the byte limit are copied. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::budget::{Budget, Exceeded}; +/// +/// // a scan may read 100 bytes; 60 and then 60 more is too much +/// let budget = Budget::unlimited().reading_at_most(100); +/// assert_eq!(budget.charge(60), Ok(())); +/// assert_eq!(budget.charge(60), Err(Exceeded::Bytes)); +/// assert_eq!(budget.spent_bytes(), 120); +/// +/// // clones share the count and the cancel flag +/// let budget = Budget::unlimited(); +/// let worker = budget.clone(); +/// budget +/// .cancel_handle() +/// .store(true, std::sync::atomic::Ordering::Relaxed); +/// assert_eq!(worker.check(), Err(Exceeded::Cancelled)); +/// ``` +#[derive(Debug, Clone)] +pub struct Budget { + deadline: Option, + max_bytes: Option, + spent_bytes: Arc, + cancelled: Arc, +} + +impl Default for Budget { + fn default() -> Self { + Self::unlimited() + } +} + +impl Budget { + /// Returns a budget with no deadline and no byte limit. Only [`Budget::cancel_handle`] can + /// make it run out. + #[must_use] + pub fn unlimited() -> Self { + Self { + deadline: None, + max_bytes: None, + spent_bytes: Arc::new(AtomicU64::new(0)), + cancelled: Arc::new(AtomicBool::new(false)), + } + } + + /// Returns the budget with a deadline `time` from now. + /// + /// The clock starts when this is called, not when the scan starts, so build the budget just + /// before the scan. A second call replaces the deadline. + #[must_use] + pub fn within(mut self, time: Duration) -> Self { + self.deadline = Some(Instant::now() + time); + self + } + + /// Returns the budget with a limit of `bytes` that may be charged in total, across every clone + /// of it. A second call replaces the limit. + /// + /// The limit is exceeded when the total is more than `bytes`; charging exactly `bytes` is + /// within the budget. + #[must_use] + pub fn reading_at_most(mut self, bytes: u64) -> Self { + self.max_bytes = Some(bytes); + self + } + + /// Returns a handle that cancels this budget (and every clone of it) when set. + /// + /// Store `true` in it, from any thread, and the next [`Budget::check`] or [`Budget::charge`] on + /// the budget or a clone fails with [`Exceeded::Cancelled`]. + #[must_use] + pub fn cancel_handle(&self) -> Arc { + self.cancelled.clone() + } + + /// Returns an error if the work was cancelled or the deadline passed, and `Ok` if the work may + /// go on. Cheap enough to call per record. + /// + /// # Errors + /// + /// - [`Exceeded::Cancelled`] if the cancel flag was set. This is checked first. + /// - [`Exceeded::Time`] if the deadline has passed. An unlimited budget has none. + /// + /// The byte limit is not looked at; [`Budget::charge`] does that. + pub fn check(&self) -> Result<(), Exceeded> { + if self.cancelled.load(Ordering::Relaxed) { + return Err(Exceeded::Cancelled); + } + + if self + .deadline + .is_some_and(|deadline| Instant::now() >= deadline) + { + return Err(Exceeded::Time); + } + + Ok(()) + } + + /// Accounts for `bytes` read, then does what [`Budget::check`] does. + /// + /// The bytes are counted even when the answer is an error, so [`Budget::spent_bytes`] includes + /// the charge that went over the limit. + /// + /// # Errors + /// + /// - [`Exceeded::Bytes`] if the total charged, with these `bytes`, is more than the limit of + /// [`Budget::reading_at_most`]. This is checked before the cancel flag and the deadline, + /// so a budget that is over its limit and also cancelled says `Bytes`. + /// - [`Exceeded::Cancelled`] or [`Exceeded::Time`], as for [`Budget::check`]. + pub fn charge(&self, bytes: u64) -> Result<(), Exceeded> { + let spent = self.spent_bytes.fetch_add(bytes, Ordering::Relaxed) + bytes; + if self.max_bytes.is_some_and(|max| spent > max) { + return Err(Exceeded::Bytes); + } + + self.check() + } + + /// Returns the total number of bytes charged so far, across this budget and every clone of it. + #[must_use] + pub fn spent_bytes(&self) -> u64 { + self.spent_bytes.load(Ordering::Relaxed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_unlimited_budget_never_runs_out() { + let budget = Budget::unlimited(); + for _ in 0..1000 { + assert_eq!(budget.charge(1 << 30), Ok(())); + } + } + + #[test] + fn bytes_are_counted_across_clones() { + let budget = Budget::unlimited().reading_at_most(100); + let clone = budget.clone(); + assert_eq!(budget.charge(60), Ok(())); + assert_eq!(clone.charge(60), Err(Exceeded::Bytes)); + assert_eq!(budget.spent_bytes(), 120); + } + + #[test] + fn time_runs_out() { + let budget = Budget::unlimited().within(Duration::ZERO); + assert_eq!(budget.check(), Err(Exceeded::Time)); + } + + #[test] + fn cancelling_a_handle_stops_every_clone() { + let budget = Budget::unlimited(); + let clone = budget.clone(); + budget.cancel_handle().store(true, Ordering::Relaxed); + assert_eq!(clone.check(), Err(Exceeded::Cancelled)); + } +} diff --git a/komorebi-recorder/src/analysis/mod.rs b/komorebi-recorder/src/analysis/mod.rs index cff2aa93..b51360ff 100644 --- a/komorebi-recorder/src/analysis/mod.rs +++ b/komorebi-recorder/src/analysis/mod.rs @@ -3,11 +3,14 @@ //! Everything here reads a session directory and produces plain serializable values, so the same //! answers serve the command line and anything else that wants them. //! This module holds the parts every command shares: the JSON envelope and exit codes -//! ([`envelope`]), how a point in time is named ([`timespec`], [`ids`]) and the guard that keeps -//! file access inside the session ([`guard`]). +//! ([`envelope`]), how a point in time is named ([`timespec`], [`ids`]), the guard that keeps file +//! access inside the session ([`guard`]) and the budget that keeps an answer from growing without +//! bound ([`budget`]). pub mod answers; pub mod blocks; +pub mod brief; +pub mod budget; pub mod catalog; pub mod classify; pub mod code; @@ -23,6 +26,8 @@ pub mod invariants; pub mod logparse; pub mod lookup; pub mod overview; +pub mod schemas; +pub mod search; pub mod state; pub mod timespec; pub mod trace; diff --git a/komorebi-recorder/src/analysis/schemas.rs b/komorebi-recorder/src/analysis/schemas.rs new file mode 100644 index 00000000..a132b06e --- /dev/null +++ b/komorebi-recorder/src/analysis/schemas.rs @@ -0,0 +1,146 @@ +//! The JSON Schema of every command's output, so a caller can know what to expect. +//! +//! An [`Envelope`] names the command whose `data` it carries in its `schema` field (`brief/1`). +//! [`ALL`] lists those names with a sentence about each and a function that produces the JSON +//! Schema of the `data` (generated from the Rust type with `schemars`, so the schema and the output +//! cannot drift apart). [`find`] looks one up by name. `komorebi-recorder schema` prints the list, +//! and `komorebi-recorder schema ` prints one schema. +//! +//! The list is written by hand, one entry per name. `guide --json` names its `data` `guide/1`, +//! which is not listed. + +use super::answers::AnnotationData; +use super::answers::AnnotationsData; +use super::answers::DeletedData; +use super::answers::DiffData; +use super::answers::EventsData; +use super::answers::StateData; +use super::brief::BriefData; +use super::code::CodeData; +use super::envelope::Envelope; +use super::history::HistoryData; +use super::overview::OverviewData; +use super::search::SearchData; +use super::trace::TraceData; +use schemars::schema_for; +use serde_json::Value; + +/// A command output's schema: its name, a sentence about it, and the JSON Schema of its `data`. +/// +/// The schema is produced on demand by calling [`Entry::schema`]: it is not stored. +pub struct Entry { + /// The name that appears in an envelope's `schema`: the command and a version, `brief/1`. + pub name: &'static str, + /// A sentence naming the command that prints this and describing its `data`. + pub about: &'static str, + /// Returns the JSON Schema of the output's `data`. For `error/1` it is the schema of the whole + /// failed [`Envelope`], because a failed command has no `data`. It returns `null` if the + /// schema could not be turned into JSON. + pub schema: fn() -> Value, +} + +fn of() -> Value { + serde_json::to_value(schema_for!(T)).unwrap_or(Value::Null) +} + +/// Every schema, by the name that appears in an envelope's `schema`. +/// +/// The order is the order `komorebi-recorder schema` lists them in. +pub const ALL: &[Entry] = &[ + Entry { + name: "brief/1", + about: "`brief`: the user's bug regions and what the recording shows around each", + schema: of::, + }, + Entry { + name: "overview/1", + about: "`overview`: ranked findings, a histogram of the recording and its incidents", + schema: of::, + }, + Entry { + name: "state/1", + about: "`state`: komorebi's state at a moment, with anything wrong in it", + schema: of::, + }, + Entry { + name: "diff/1", + about: "`diff`: what changed between two moments", + schema: of::, + }, + Entry { + name: "events/1", + about: "`events`: komorebi's events, classified, with the handler that ran", + schema: of::, + }, + Entry { + name: "trace/1", + about: "`trace`: one event end to end with attributed changes", + schema: of::, + }, + Entry { + name: "window/1", + about: "`window`: one window's life through the recording", + schema: of::, + }, + Entry { + name: "code/1", + about: "`code`: log lines mapped to komorebi's source", + schema: of::, + }, + Entry { + name: "search/1", + about: "`search`: where a word appears in the recording", + schema: of::, + }, + Entry { + name: "annotation/1", + about: "`annotate add|edit`: the annotation as it now reads", + schema: of::, + }, + Entry { + name: "annotations/1", + about: "`annotations`: bug regions, notes and findings", + schema: of::, + }, + Entry { + name: "annotation-deleted/1", + about: "`annotate delete`: the id removed", + schema: of::, + }, + Entry { + name: "doctor/1", + about: "`doctor`: what this machine can do for a recording", + schema: of::, + }, + Entry { + name: "probe/1", + about: "`doctor --probe`: what one measurement found", + schema: of::, + }, + Entry { + name: "error/1", + about: "any failed command: the envelope with `ok: false` and an `error`", + schema: of::>, + }, +]; + +/// Returns the schema named `name`, or `None` if there is none. +/// +/// The name is matched exactly, version included: `brief/1`, not `brief`. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::schemas; +/// +/// let entry = schemas::find("brief/1").expect("the brief schema is listed"); +/// assert_eq!(entry.name, "brief/1"); +/// assert!((entry.schema)().is_object()); +/// +/// assert!(schemas::find("brief").is_none()); +/// assert!(schemas::ALL.iter().any(|entry| entry.name == "error/1")); +/// ``` +#[must_use] +pub fn find(name: &str) -> Option<&'static Entry> { + ALL.iter().find(|entry| entry.name == name) +} diff --git a/komorebi-recorder/src/analysis/search.rs b/komorebi-recorder/src/analysis/search.rs new file mode 100644 index 00000000..f24f33c2 --- /dev/null +++ b/komorebi-recorder/src/analysis/search.rs @@ -0,0 +1,379 @@ +//! Finding a word across everything the session recorded. +//! +//! A user says "it happened when Slack woke up" or an error names a window; this looks for the text +//! in komorebi's log, the events, what happened to the machine, the annotations and, on request, +//! the OS trace, and returns where each hit is so it can be fed straight to `trace`, `code` or +//! `at`. +//! +//! [`Analysis::search`] is what the `search` command prints. A [`SearchQuery`] describes what to +//! look for and where in time; the answer is a [`SearchData`] of [`Hit`]s ordered by time, each +//! with a `reference` (`log:345`, `event:12`, ...) in the same notation the time arguments of the +//! other commands take. +//! +//! # Where it looks +//! +//! | `source` of a hit | looked at | `reference` | searched when | +//! |---|---|---|---| +//! | `komorebi-log` | each line's message, and its spans and module with the message | `log:` | always | +//! | `events` | the event's one-line summary | `event:` | always | +//! | `recorder` | an incident's kind and detail, `kind: detail` | `incident:` | always | +//! | `annotations` | an annotation's title, text and expected behavior | the annotation's id | always | +//! | `oslog:...` | the text of each OS trace record | `oslog::` | [`SearchQuery::oslog`] | +//! +//! The OS trace is large, which is why it is opt-in and the only source a `Budget` limits. OS +//! trace records from either host are searched the same way. + +use super::Analysis; +use super::budget::Budget; +use super::envelope; +use crate::annotations; +use crate::timeline; +use crate::timeline::Filter; +use color_eyre::eyre; +use regex::Regex; +use regex::RegexBuilder; +use schemars::JsonSchema; +use serde::Serialize; + +/// The schema name that identifies a [`SearchData`] in an envelope (`search/1`); listed by the +/// `schema` command. +pub const SCHEMA_SEARCH: &str = "search/1"; + +/// Where a piece of text was found in the session. +#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)] +pub struct Hit { + /// `komorebi-log`, `events`, `recorder`, `annotations` or `oslog:...`. For an OS trace record + /// it is the source of the record itself, such as `oslog:system` or `oslog:app:Ghostty`. + pub source: String, + /// When it happened, in seconds of video time. + pub video_s: f64, + /// When it happened, in nanoseconds on the host's master monotonic clock. + pub mach_ns: u64, + /// Something to give another command: `log:345`, `event:12`, `incident:2`, an annotation id + /// or `oslog::`. + pub reference: String, + /// The text that matched. For a log line it is the line's message; for an event, its summary; + /// for an annotation, its title, text and expected behavior joined by spaces; for an OS trace + /// record, the rendered record. + pub text: String, +} + +/// The hits for a [`SearchQuery`], ordered by time: the `data` of the `search` command. +#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)] +pub struct SearchData { + /// The pattern that was searched for, as given. + pub query: String, + /// The hits of this page, ordered by time and then by reference. + pub hits: Vec, + /// How many hits there were after the cursor, including any not returned. + pub matching: usize, + /// Where it looked: always `komorebi-log`, `events`, `recorder` and `annotations`, and + /// `oslog` if the OS trace was searched. + pub searched: Vec, +} + +/// A search: what to look for, where in time, and how much to return. +/// +/// The default is an empty pattern, which [`Analysis::search`] refuses, so a query is built with +/// at least a `pattern`. The other defaults are: a literal, case-insensitive match, the whole +/// recording, no OS trace, from the first hit, with no limit. +#[derive(Debug, Clone, Default)] +pub struct SearchQuery { + /// The text to look for. A literal substring, or a regular expression if `regex` is set. + pub pattern: String, + /// Whether `pattern` is a regular expression (the syntax of the `regex` crate). A regular + /// expression may match anywhere in the text, and for a log line it is tried against the + /// message alone first, so an anchor such as `^processing` applies to the start of the message. + pub regex: bool, + /// Whether upper and lower case must match. Off by default. + pub case_sensitive: bool, + /// Ignore anything earlier than this, in nanoseconds on the host's master monotonic clock. + pub from_mach_ns: Option, + /// Ignore anything later than this, in nanoseconds on the host's master monotonic clock. + pub to_mach_ns: Option, + /// Also search the OS trace (large). Off by default. + pub oslog: bool, + /// Hits already returned: this many of the earliest hits are skipped, so a caller pages by + /// passing how many it has seen. + pub skip: usize, + /// The most hits to return; `None` for all of them. + pub limit: Option, +} + +enum Matcher { + Literal { + needle: String, + case_sensitive: bool, + }, + Pattern(Regex), +} + +impl Matcher { + fn new(query: &SearchQuery) -> eyre::Result { + if query.pattern.is_empty() { + return Err(envelope::usage("nothing to search for")); + } + + if query.regex { + return RegexBuilder::new(&query.pattern) + .case_insensitive(!query.case_sensitive) + .build() + .map(Self::Pattern) + .map_err(|error| envelope::usage(format!("not a valid pattern: {error}"))); + } + + Ok(Self::Literal { + needle: if query.case_sensitive { + query.pattern.clone() + } else { + query.pattern.to_lowercase() + }, + case_sensitive: query.case_sensitive, + }) + } + + fn matches(&self, text: &str) -> bool { + match self { + Self::Literal { + needle, + case_sensitive, + } => { + if *case_sensitive { + text.contains(needle.as_str()) + } else { + text.to_lowercase().contains(needle.as_str()) + } + } + Self::Pattern(pattern) => pattern.is_match(text), + } + } +} + +impl Analysis { + /// Searches the session for `query`, within the limits of `budget`. + /// + /// Hits from every source are put together, ordered by time (earliest first, ties by + /// reference) and then paged with [`SearchQuery::skip`] and [`SearchQuery::limit`], so + /// [`SearchData::matching`] counts what is left after the skip, whatever the limit. + /// + /// A log line is a hit if the pattern matches its message alone (so `^processing` means what + /// it says) or its message together with its spans and module. A log line with no time, or + /// one that cannot be placed on the master clock, is never a hit, because it cannot be placed + /// in a range. The time range applies to every source. + /// + /// `budget` limits only the OS trace, the one source that can be gigabytes: every record read + /// is charged against it. The rest of the search does not consult it. + /// + /// # Errors + /// + /// Returns an error if: + /// + /// - the pattern is empty (the usage exit kind); + /// - `query.regex` is set and the pattern is not a valid regular expression (the usage exit + /// kind); + /// - the annotations file exists and cannot be read; + /// - `query.oslog` is set and the timeline index (`timeline.jsonl`) is missing, in which case + /// `komorebi-recorder reindex` rebuilds it, or an OS trace file cannot be read; + /// - `query.oslog` is set and `budget` runs out (time, bytes or cancellation) while records are + /// read (the budget exit kind). No partial result is returned: narrow the range with + /// [`SearchQuery::from_mach_ns`] and [`SearchQuery::to_mach_ns`] and search again. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::analysis::Analysis; + /// use komorebi_recorder::analysis::budget::Budget; + /// use komorebi_recorder::analysis::search::SearchQuery; + /// use komorebi_recorder::testkit::SessionBuilder; + /// use serde_json::json; + /// + /// let (session, _) = SessionBuilder::new("doc-search") + /// .log(2.0, "INFO", "komorebi::reaper: reaping window: 4711") + /// .event(3.0, json!({"type": "FocusWorkspaceNumber", "content": 1}), None) + /// .incident(4.0, "display-disconnected", "display 2 was unplugged") + /// .build(); + /// let analysis = Analysis::open(&session.dir)?; + /// + /// let found = analysis.search( + /// &SearchQuery { pattern: "WINDOW".to_string(), ..SearchQuery::default() }, + /// &Budget::unlimited(), + /// )?; + /// assert_eq!(found.matching, 1); + /// assert_eq!(found.hits[0].source, "komorebi-log"); + /// assert_eq!(found.hits[0].reference, "log:1"); + /// + /// // case matters when asked to, and nothing in the recording contains `WINDOW` + /// let found = analysis.search( + /// &SearchQuery { + /// pattern: "WINDOW".to_string(), + /// case_sensitive: true, + /// ..SearchQuery::default() + /// }, + /// &Budget::unlimited(), + /// )?; + /// assert!(found.hits.is_empty()); + /// + /// // hits from different sources come back in time order, each with a reference to follow + /// let found = analysis.search( + /// &SearchQuery { + /// pattern: r"workspace|unplugged|reaping".to_string(), + /// regex: true, + /// ..SearchQuery::default() + /// }, + /// &Budget::unlimited(), + /// )?; + /// let references: Vec<_> = found.hits.iter().map(|hit| hit.reference.as_str()).collect(); + /// assert_eq!(references, ["log:1", "event:1", "incident:1"]); + /// + /// // an empty pattern is a usage error + /// assert!(analysis.search(&SearchQuery::default(), &Budget::unlimited()).is_err()); + /// # Ok::<(), Box>(()) + /// ``` + /// + /// Searching with `oslog` set needs OS trace files and a timeline index. It is covered, with + /// paging by cursor, by + /// `tests/brief.rs::search_finds_words_across_sources_and_gives_references` and + /// `tests/brief.rs::search_pages_with_a_cursor`. + pub fn search(&self, query: &SearchQuery, budget: &Budget) -> eyre::Result { + let matcher = Matcher::new(query)?; + let in_range = |mach_ns: u64| { + query.from_mach_ns.is_none_or(|from| mach_ns >= from) + && query.to_mach_ns.is_none_or(|to| mach_ns <= to) + }; + let mut hits: Vec = Vec::new(); + let mut searched = vec!["komorebi-log", "events", "recorder", "annotations"]; + + for line in &self.log().lines { + let Some(mach_ns) = line + .wall_us + .and_then(|wall_us| self.clock().wall_to_mach(wall_us)) + else { + continue; + }; + let spans: Vec<&str> = line.spans.iter().map(|span| span.name.as_str()).collect(); + let haystack = format!( + "{} {}: {}", + spans.join(":"), + line.target.as_deref().unwrap_or(""), + line.message + ); + // the message alone, so `^processing` anchors mean what they say, or with its spans and module + if in_range(mach_ns) && (matcher.matches(&line.message) || matcher.matches(&haystack)) { + hits.push(Hit { + source: "komorebi-log".to_string(), + video_s: self.video_s(mach_ns), + mach_ns, + reference: format!("log:{}", line.number), + text: line.message.clone(), + }); + } + } + + for event in self.events() { + let haystack = format!( + "{} {}", + event.info.summary(), + event.info.argument.as_deref().unwrap_or("") + ); + if in_range(event.recv_mach_ns) && matcher.matches(&haystack) { + hits.push(Hit { + source: "events".to_string(), + video_s: self.video_s(event.recv_mach_ns), + mach_ns: event.recv_mach_ns, + reference: format!("event:{}", event.seq), + text: event.info.summary(), + }); + } + } + + for incident in self.incidents() { + let mach_ns = self.manifest.mach_at_video_seconds(incident.video_s); + let text = format!("{}: {}", incident.kind, incident.detail); + if in_range(mach_ns) && matcher.matches(&text) { + hits.push(Hit { + source: "recorder".to_string(), + video_s: incident.video_s, + mach_ns, + reference: format!("incident:{}", incident.number), + text, + }); + } + } + + for annotation in annotations::load(&self.session.dir)?.annotations { + let text = format!( + "{} {} {}", + annotation.title, + annotation.text, + annotation.expected.clone().unwrap_or_default() + ); + if in_range(annotation.start_mach_ns) && matcher.matches(&text) { + hits.push(Hit { + source: "annotations".to_string(), + video_s: self.video_s(annotation.start_mach_ns), + mach_ns: annotation.start_mach_ns, + reference: annotation.id.clone(), + text: text.trim().to_string(), + }); + } + } + + if query.oslog { + searched.push("oslog"); + let from_s = query + .from_mach_ns + .map_or(f64::MIN / 2.0, |ns| self.video_s(ns)); + let to_s = query + .to_mach_ns + .map_or(f64::MAX / 2.0, |ns| self.video_s(ns)); + // the timeline index reads each record's raw text; stop when the budget says to + let records = timeline::query( + &self.session, + &self.manifest, + from_s.max(-1e6), + to_s.min(1e9), + &Filter { + app: None, + sources: vec!["oslog".to_string()], + }, + )?; + for record in records { + budget + .charge(record.text.len() as u64) + .map_err(|exceeded| { + envelope::over_budget(format!( + "the search {exceeded}; narrow it with --from/--to" + )) + })?; + if matcher.matches(&record.text) { + hits.push(Hit { + source: record.entry.source.clone(), + video_s: record.entry.video_s, + mach_ns: record.entry.mach_ns, + reference: format!("oslog:{}:{}", record.entry.file, record.entry.line), + text: record.text, + }); + } + } + } + + hits.sort_by(|a, b| { + a.mach_ns + .cmp(&b.mach_ns) + .then(a.reference.cmp(&b.reference)) + }); + let matching = hits.len().saturating_sub(query.skip); + let page: Vec = hits + .into_iter() + .skip(query.skip) + .take(query.limit.unwrap_or(usize::MAX)) + .collect(); + + Ok(SearchData { + query: query.pattern.clone(), + hits: page, + matching, + searched: searched.into_iter().map(str::to_string).collect(), + }) + } +} diff --git a/komorebi-recorder/src/cli/agent.rs b/komorebi-recorder/src/cli/agent.rs new file mode 100644 index 00000000..b2498175 --- /dev/null +++ b/komorebi-recorder/src/cli/agent.rs @@ -0,0 +1,217 @@ +//! The commands an agent starts with: `brief`, `overview`, `search`, `guide` and `schema`. +//! +//! | Command | Asks | Answer, with `--json` | +//! |---|---|---| +//! | `brief` | [`Analysis::brief`] | `brief/1` | +//! | `overview` | [`Analysis::overview`] | `overview/1` | +//! | `search` | [`Analysis::search`] | `search/1` | +//! | `guide` | nothing: prints [`GUIDE`] | `guide/1` | +//! | `schema` | nothing: prints the JSON Schema of an output | the schema itself | +//! +//! With `--json` an answer is wrapped in the envelope every investigation command uses +//! (`{ok, schema, data, warnings, truncated, next_cursor, error}`), and a failure is reported in the +//! same envelope with an exit code that says what kind of failure it was (0 ok, 1 error, 2 usage, 3 +//! not found, 4 unusable session, 5 over budget). A list that was cut short sets `truncated` and +//! gives a `next_cursor`, which `search` takes back as `--cursor`. +//! +//! Covered by `tests/brief.rs`, which runs these commands through the real binary. + +use super::print_json; +use crate::analysis::Analysis; +use crate::analysis::brief::SCHEMA_BRIEF; +use crate::analysis::budget::Budget; +use crate::analysis::envelope; +use crate::analysis::envelope::Envelope; +use crate::analysis::overview::SCHEMA_OVERVIEW; +use crate::analysis::schemas; +use crate::analysis::search::SCHEMA_SEARCH; +use crate::analysis::search::SearchQuery; +use crate::report; +use clap::Args; +use color_eyre::eyre; +use serde::Serialize; +use std::path::PathBuf; +use std::time::Duration; + +/// The agent playbook, also printed by `guide`: the text of `guide.md`, which is part of the binary. +pub const GUIDE: &str = include_str!("../guide.md"); + +/// The arguments of `brief`. +#[derive(Args, Debug)] +pub struct BriefArgs { + /// Session directory + pub session: PathBuf, + /// Machine-readable JSON output + #[arg(long)] + pub json: bool, +} + +/// The arguments of `overview`. +#[derive(Args, Debug)] +pub struct OverviewArgs { + /// Session directory + pub session: PathBuf, + /// Most findings to list (0 for all) + #[arg(long, default_value_t = 20)] + pub limit: usize, + /// Machine-readable JSON output + #[arg(long)] + pub json: bool, +} + +/// The arguments of `search`. +#[derive(Args, Debug)] +pub struct SearchArgs { + /// Session directory + pub session: PathBuf, + /// The text to look for + pub text: String, + /// Treat the text as a regular expression + #[arg(long)] + pub regex: bool, + /// Match case + #[arg(long)] + pub case_sensitive: bool, + /// Only after this moment + #[arg(long, value_name = "TIME")] + pub from: Option, + /// Only before this moment + #[arg(long, value_name = "TIME")] + pub to: Option, + /// Also search the macOS trace (large; narrow it with --from/--to) + #[arg(long)] + pub oslog: bool, + /// Most hits to print (0 for all) + #[arg(long, default_value_t = 50)] + pub limit: usize, + /// Continue after this many hits (from a truncated answer's `next_cursor`) + #[arg(long, value_name = "N")] + pub cursor: Option, + /// Give up after this many milliseconds + #[arg(long, value_name = "MS")] + pub budget_ms: Option, + /// Machine-readable JSON output + #[arg(long)] + pub json: bool, +} + +/// The arguments of `guide`. +#[derive(Args, Debug)] +pub struct GuideArgs { + /// Machine-readable JSON output + #[arg(long)] + pub json: bool, +} + +/// The arguments of `schema`. +#[derive(Args, Debug)] +pub struct SchemaArgs { + /// Which output's schema, e.g. `brief/1`; omit to list them + pub name: Option, +} + +pub(super) fn brief(args: &BriefArgs) -> eyre::Result<()> { + let analysis = Analysis::open(&args.session)?; + let data = analysis.brief()?; + + if args.json { + let mut warnings = analysis.warnings(); + warnings.extend(data.skew.warning.clone()); + return print_json(&Envelope::ok(SCHEMA_BRIEF, data).warnings(warnings)); + } + + print!("{}", report::brief_text(&data)); + Ok(()) +} + +pub(super) fn overview(args: &OverviewArgs) -> eyre::Result<()> { + let analysis = Analysis::open(&args.session)?; + let data = analysis.overview((args.limit != 0).then_some(args.limit))?; + + if args.json { + return print_json(&Envelope::ok(SCHEMA_OVERVIEW, data).warnings(analysis.warnings())); + } + + print!("{}", report::overview_text(&data)); + Ok(()) +} + +pub(super) fn search(args: &SearchArgs) -> eyre::Result<()> { + let analysis = Analysis::open(&args.session)?; + let moment = |text: &Option| -> eyre::Result> { + text.as_deref() + .map(|text| analysis.resolve(text).map(|resolved| resolved.mach_ns)) + .transpose() + }; + + let mut budget = Budget::unlimited().reading_at_most(512 * 1024 * 1024); + if let Some(ms) = args.budget_ms { + budget = budget.within(Duration::from_millis(ms)); + } + + let limit = (args.limit != 0).then_some(args.limit); + let skip = args.cursor.unwrap_or(0); + let data = analysis.search( + &SearchQuery { + pattern: args.text.clone(), + regex: args.regex, + case_sensitive: args.case_sensitive, + from_mach_ns: moment(&args.from)?, + to_mach_ns: moment(&args.to)?, + oslog: args.oslog, + skip, + limit, + }, + &budget, + )?; + + let truncated = limit.is_some_and(|limit| data.matching > limit); + let next_cursor = truncated.then(|| (skip + data.hits.len()).to_string()); + + if args.json { + let mut envelope = Envelope::ok(SCHEMA_SEARCH, data).warnings(analysis.warnings()); + if truncated { + envelope = envelope.truncated(next_cursor); + } + return print_json(&envelope); + } + + print!("{}", report::search_text(&data)); + if let Some(cursor) = next_cursor { + println!("... more; continue with --cursor {cursor}"); + } + Ok(()) +} + +#[derive(Serialize)] +struct GuideData { + guide: &'static str, +} + +pub(super) fn guide(args: &GuideArgs) -> eyre::Result<()> { + if args.json { + return print_json(&Envelope::ok("guide/1", GuideData { guide: GUIDE })); + } + + print!("{GUIDE}"); + Ok(()) +} + +pub(super) fn schema(args: &SchemaArgs) -> eyre::Result<()> { + let Some(name) = &args.name else { + for entry in schemas::ALL { + println!("{:<22} {}", entry.name, entry.about); + } + println!( + "\nevery command's --json output is {{ok, schema, data, warnings, truncated, next_cursor, error}}; `schema` names which of these `data` is" + ); + return Ok(()); + }; + + let entry = schemas::find(name).ok_or_else(|| { + envelope::not_found(format!( + "there is no schema '{name}'; run `komorebi-recorder schema` to list them" + )) + })?; + print_json(&(entry.schema)()) +} diff --git a/komorebi-recorder/src/cli/annotate.rs b/komorebi-recorder/src/cli/annotate.rs new file mode 100644 index 00000000..79432fd2 --- /dev/null +++ b/komorebi-recorder/src/cli/annotate.rs @@ -0,0 +1,450 @@ +//! `annotate` and `annotations`: marking where a bug starts and ends, notes, and agent findings. +//! +//! `annotate add|edit|delete` writes to the session's `annotations.jsonl` (see +//! [`crate::annotations`], which does the writing and holds the format) and `annotations ` +//! lists what is there. Both work on a session that is still being recorded, so a bug can be marked +//! while it is happening. +//! +//! This file is where the rules about what an annotation must say are enforced, since +//! [`crate::annotations::add`] itself only refuses an end before a start: +//! +//! | Kind | Must have | +//! |---|---| +//! | bug | `--text`, and `--end` or `--open-ended` | +//! | note | `--text` | +//! | finding | `--text` and at least one `--ref` | +//! +//! The start is `--start`; failing that, the start of the annotation named by `--about`; for a +//! finding, failing that, the earliest of its evidence that has a time (an `event:` or a `frame:` +//! reference); otherwise `--start` is required. A finding with no `--end` takes the end of the bug +//! it is `--about`. The author is `user`, or `agent` for a finding, unless `--author` says +//! otherwise. +//! +//! Every `--ref` is checked to exist before anything is written +//! ([`crate::annotations::validate_refs`]), and a reference that cannot be checked (komorebi's +//! source was not found) is a warning, not a refusal. Times take any form `state --at` takes (see +//! `analysis::timespec`). An annotation is printed back as it reads after the change +//! ([`crate::report::annotation_text`], or the `annotation/1` envelope with `--json`). +//! +//! Covered by `tests/annotate.rs`, which runs the commands through the real binary. + +use super::print_json; +use crate::analysis::answers::AnnotationData; +use crate::analysis::answers::AnnotationsData; +use crate::analysis::answers::DeletedData; +use crate::analysis::envelope; +use crate::analysis::envelope::Envelope; +use crate::analysis::lookup::SessionLookup; +use crate::analysis::timespec::TimeSpec; +use crate::annotations; +use crate::annotations::AnnotationView; +use crate::annotations::Kind; +use crate::annotations::New; +use crate::annotations::Patch; +use crate::annotations::Ref; +use crate::report; +use crate::session::Manifest; +use crate::session::Session; +use clap::Args; +use clap::Subcommand; +use clap::ValueEnum; +use color_eyre::eyre; +use std::path::PathBuf; + +/// The kind of annotation, as the `--kind` option spells it. +#[derive(Debug, Clone, Copy, ValueEnum)] +pub enum KindArg { + /// A region of the recording where the bug is visible, with what the user saw + Bug, + /// A remark about a moment or region + Note, + /// A conclusion about the cause of a bug, with the evidence for it + Finding, +} + +impl From for Kind { + fn from(kind: KindArg) -> Self { + match kind { + KindArg::Bug => Self::Bug, + KindArg::Note => Self::Note, + KindArg::Finding => Self::Finding, + } + } +} + +/// The arguments of `annotate`: the session and what to do to its annotations. +#[derive(Args, Debug)] +pub struct AnnotateArgs { + /// Session directory (it may still be recording) + pub session: PathBuf, + /// What to do: `add`, `edit` or `delete` + #[command(subcommand)] + pub action: Action, +} + +/// The operations of `annotate` on the session's annotations. +#[derive(Subcommand, Debug)] +pub enum Action { + /// Add a bug region, a note or a finding + Add(AddArgs), + /// Change an annotation + Edit(EditArgs), + /// Remove an annotation + Delete(DeleteArgs), +} + +/// The arguments of `annotate add`. +#[derive(Args, Debug)] +pub struct AddArgs { + /// What kind of annotation this is + #[arg(long, value_enum)] + pub kind: KindArg, + /// Where it starts: 12.5, 1:02.5, wall:, event:, bug:.end, optionally +3s. + /// A finding defaults to the start of the bug it is --about + #[arg(long, value_name = "TIME")] + pub start: Option, + /// Where it ends (same forms). A bug needs this or --open-ended + #[arg(long, value_name = "TIME")] + pub end: Option, + /// The bug was still happening when the recording stopped + #[arg(long, conflicts_with = "end")] + pub open_ended: bool, + /// What it looks like (a bug), the remark (a note) or the conclusion (a finding) + #[arg(long)] + pub text: Option, + /// A short title + #[arg(long)] + pub title: Option, + /// What should have happened instead + #[arg(long)] + pub expected: Option, + /// Only on this display (repeatable) + #[arg(long = "display", value_name = "ID")] + pub displays: Vec, + /// Who is saying this [default: user, or agent for a finding] + #[arg(long)] + pub author: Option, + /// For a finding: the bug annotation it explains + #[arg(long, value_name = "ID")] + pub about: Option, + /// Evidence (repeatable; a finding needs at least one): event:, log:, + /// log::, code::, frame: