feat(analysis): investigate from what you marked

The brief starts from what the user marked as the bug, in their words, and ranks
the events most worth tracing first; findings an agent concludes are saved with
the evidence they cite, which must exist. The commands arrive: `state`, `diff`,
`events`, `window`, `trace`, `code`, `brief`, `overview`, `search`, `annotate`,
`annotations`, `guide` and `schema`, all with `--json`, and a search is bounded
by a budget.
This commit is contained in:
LGUG2Z committed 2026-10-27 22:22:56 -07:00
1 parent 079f1ac6d0
commit 26963391a3
23 files changed
+4741 -2

No files matched your search

Generated
+39
View File
@@ -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"
+25
View File
@@ -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
+8
View File
@@ -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"
]
+90
View File
@@ -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 <session> # 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 <session> 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 <session>
```
Times can be a video timecode (`12.5`, `1:02.5`), `wall:<RFC 3339>`, `event:<seq>`, `log:<line>`, `incident:<n>` or
`bug:<id>` (`.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 <session> add --kind finding --about <bug id> \
--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.
+1
View File
@@ -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-<pid>.ndjson after a restart)
oslog/system.ndjson unified log, accessibility / SkyLight / workspace subsystems
oslog/apps/<exe>-<pid>.ndjson unified log, one managed application
+1
View File
@@ -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 }
+574
View File
@@ -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<StateOrigin>,
/// How big the state is, in words: the number of monitors and windows.
pub summary: String,
/// What had the keyboard focus.
pub focus: Option<Focus>,
/// What looks wrong in the state.
pub violations: Vec<Violation>,
}
/// 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<String>,
/// The command that traces it: `komorebi-recorder trace <session> event:<seq>`.
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<String, usize>,
/// 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<EventView>,
/// 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<Finding>,
/// The events most worth tracing first, best first, up to a limit of 5.
pub suspects: Vec<Suspect>,
/// komorebi's state as the region began; `None` if no state had been recorded by then.
pub state_at_start: Option<StateBrief>,
/// komorebi's state as the region ended; `None` if no state had been recorded by then.
pub state_at_end: Option<StateBrief>,
/// What differs between the state at the start and at the end, up to a limit of 40.
pub changes: Vec<ChangeView>,
/// 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<IncidentView>,
}
/// 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<String>,
}
/// 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<BugBrief>,
/// With no bug marked: the same digest over the whole recording.
pub whole_session: Option<RegionBrief>,
/// Conclusions an earlier investigation recorded.
pub findings_recorded: Vec<AnnotationView>,
/// The notes people or agents wrote.
pub notes: Vec<AnnotationView>,
/// What to do next, as commands to run and questions to ask.
pub next: Vec<String>,
}
impl Analysis {
fn state_brief(&self, mach_ns: u64) -> Option<StateBrief> {
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<Suspect> {
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::<Vec<_>>()
.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<RegionBrief> {
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<String, usize> = 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<EventView> = 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<IncidentView> = 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<dyn std::error::Error>>(())
/// ```
///
/// 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<BriefData> {
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 '<cause>' --ref event:<n> --ref code:<path>:<line>",
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 <t> --end <t> --text '<what is wrong>'`"
));
}
next.push(format!("komorebi-recorder overview {dir}"));
next.push("komorebi-recorder guide".to_string());
let recorded: Vec<AnnotationView> = loaded
.annotations
.iter()
.filter(|annotation| annotation.kind == Kind::Finding)
.map(|annotation| annotation.view(&self.manifest))
.collect();
let notes: Vec<AnnotationView> = 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,
})
}
}
+230
View File
@@ -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<Instant>,
max_bytes: Option<u64>,
spent_bytes: Arc<AtomicU64>,
cancelled: Arc<AtomicBool>,
}
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<AtomicBool> {
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));
}
}
+7 -2
View File
@@ -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;
+146
View File
@@ -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 <name>` 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<T: schemars::JsonSchema>() -> 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::<BriefData>,
},
Entry {
name: "overview/1",
about: "`overview`: ranked findings, a histogram of the recording and its incidents",
schema: of::<OverviewData>,
},
Entry {
name: "state/1",
about: "`state`: komorebi's state at a moment, with anything wrong in it",
schema: of::<StateData>,
},
Entry {
name: "diff/1",
about: "`diff`: what changed between two moments",
schema: of::<DiffData>,
},
Entry {
name: "events/1",
about: "`events`: komorebi's events, classified, with the handler that ran",
schema: of::<EventsData>,
},
Entry {
name: "trace/1",
about: "`trace`: one event end to end with attributed changes",
schema: of::<TraceData>,
},
Entry {
name: "window/1",
about: "`window`: one window's life through the recording",
schema: of::<HistoryData>,
},
Entry {
name: "code/1",
about: "`code`: log lines mapped to komorebi's source",
schema: of::<CodeData>,
},
Entry {
name: "search/1",
about: "`search`: where a word appears in the recording",
schema: of::<SearchData>,
},
Entry {
name: "annotation/1",
about: "`annotate add|edit`: the annotation as it now reads",
schema: of::<AnnotationData>,
},
Entry {
name: "annotations/1",
about: "`annotations`: bug regions, notes and findings",
schema: of::<AnnotationsData>,
},
Entry {
name: "annotation-deleted/1",
about: "`annotate delete`: the id removed",
schema: of::<DeletedData>,
},
Entry {
name: "doctor/1",
about: "`doctor`: what this machine can do for a recording",
schema: of::<crate::doctor::Report>,
},
Entry {
name: "probe/1",
about: "`doctor --probe`: what one measurement found",
schema: of::<crate::doctor::ProbeReport>,
},
Entry {
name: "error/1",
about: "any failed command: the envelope with `ok: false` and an `error`",
schema: of::<Envelope<()>>,
},
];
/// 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)
}
+379
View File
@@ -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:<line>` | always |
//! | `events` | the event's one-line summary | `event:<seq>` | always |
//! | `recorder` | an incident's kind and detail, `kind: detail` | `incident:<number>` | always |
//! | `annotations` | an annotation's title, text and expected behavior | the annotation's id | always |
//! | `oslog:...` | the text of each OS trace record | `oslog:<file>:<line>` | [`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:<file>:<line>`.
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<Hit>,
/// 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<String>,
}
/// 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<u64>,
/// Ignore anything later than this, in nanoseconds on the host's master monotonic clock.
pub to_mach_ns: Option<u64>,
/// 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<usize>,
}
enum Matcher {
Literal {
needle: String,
case_sensitive: bool,
},
Pattern(Regex),
}
impl Matcher {
fn new(query: &SearchQuery) -> eyre::Result<Self> {
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<dyn std::error::Error>>(())
/// ```
///
/// 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<SearchData> {
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<Hit> = 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<Hit> = 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(),
})
}
}
+217
View File
@@ -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<String>,
/// Only before this moment
#[arg(long, value_name = "TIME")]
pub to: Option<String>,
/// 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<usize>,
/// Give up after this many milliseconds
#[arg(long, value_name = "MS")]
pub budget_ms: Option<u64>,
/// 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<String>,
}
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<String>| -> eyre::Result<Option<u64>> {
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)())
}
+450
View File
@@ -0,0 +1,450 @@
//! `annotate` and `annotations`: marking where a bug starts and ends, notes, and agent findings.
//!
//! `annotate <session> add|edit|delete` writes to the session's `annotations.jsonl` (see
//! [`crate::annotations`], which does the writing and holds the format) and `annotations <session>`
//! 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<KindArg> 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:<RFC 3339>, event:<seq>, bug:<id>.end, optionally +3s.
/// A finding defaults to the start of the bug it is --about
#[arg(long, value_name = "TIME")]
pub start: Option<String>,
/// Where it ends (same forms). A bug needs this or --open-ended
#[arg(long, value_name = "TIME")]
pub end: Option<String>,
/// 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<String>,
/// A short title
#[arg(long)]
pub title: Option<String>,
/// What should have happened instead
#[arg(long)]
pub expected: Option<String>,
/// Only on this display (repeatable)
#[arg(long = "display", value_name = "ID")]
pub displays: Vec<u32>,
/// Who is saying this [default: user, or agent for a finding]
#[arg(long)]
pub author: Option<String>,
/// For a finding: the bug annotation it explains
#[arg(long, value_name = "ID")]
pub about: Option<String>,
/// Evidence (repeatable; a finding needs at least one): event:<seq>, log:<line>,
/// log:<file>:<line>, code:<path>:<line>, frame:<time>
#[arg(long = "ref", value_name = "REF")]
pub refs: Vec<String>,
/// A checkout of the recorded komorebi, to check code: references [default: `$KOMOREBI_MAC_SRC`
/// or `$KOMOREBI_WINDOWS_SRC` for the session's komorebi, `$KOMOREBI_SOURCE`, or this build's]
#[arg(long = "komorebi-src", alias = "code-root", value_name = "DIR")]
pub code_root: Option<PathBuf>,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
/// The arguments of `annotate edit`: the id, and the fields to change.
#[derive(Args, Debug)]
pub struct EditArgs {
/// The annotation id, e.g. a-3f9c1e02
pub id: String,
/// Move the start (same forms as `add --start`)
#[arg(long, value_name = "TIME")]
pub start: Option<String>,
/// An end can be moved but not removed
#[arg(long, value_name = "TIME")]
pub end: Option<String>,
/// Replace the description
#[arg(long)]
pub text: Option<String>,
/// Replace the title
#[arg(long)]
pub title: Option<String>,
/// Replace what should have happened instead (an empty text clears it)
#[arg(long)]
pub expected: Option<String>,
/// Replace the displays (repeatable)
#[arg(long = "display", value_name = "ID")]
pub displays: Vec<u32>,
/// Replace the evidence (repeatable)
#[arg(long = "ref", value_name = "REF")]
pub refs: Vec<String>,
/// A checkout of the recorded komorebi, to check code: references [default: `$KOMOREBI_MAC_SRC`
/// or `$KOMOREBI_WINDOWS_SRC` for the session's komorebi, `$KOMOREBI_SOURCE`, or this build's]
#[arg(long = "komorebi-src", alias = "code-root", value_name = "DIR")]
pub code_root: Option<PathBuf>,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
/// The arguments of `annotate delete`.
#[derive(Args, Debug)]
pub struct DeleteArgs {
/// The annotation id, e.g. a-3f9c1e02
pub id: String,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
/// The arguments of `annotations`.
#[derive(Args, Debug)]
pub struct AnnotationsArgs {
/// Session directory
pub session: PathBuf,
/// Only this kind
#[arg(long, value_enum)]
pub kind: Option<KindArg>,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
impl AnnotateArgs {
/// Returns `true` if and only if the action was asked for `--json`, which also decides how a
/// failure is reported.
#[must_use]
pub fn json(&self) -> bool {
match &self.action {
Action::Add(args) => args.json,
Action::Edit(args) => args.json,
Action::Delete(args) => args.json,
}
}
}
/// The `schema` of the output of `annotate add` and `annotate edit` with `--json`: the annotation as
/// it reads after the change ([`AnnotationData`]).
pub const SCHEMA_ANNOTATION: &str = "annotation/1";
/// The `schema` of the output of `annotations` with `--json` ([`AnnotationsData`]).
pub const SCHEMA_ANNOTATIONS: &str = "annotations/1";
/// The `schema` of the output of `annotate delete` with `--json`: the id removed ([`DeletedData`]).
pub const SCHEMA_DELETED: &str = "annotation-deleted/1";
fn parse_refs(refs: &[String]) -> eyre::Result<Vec<Ref>> {
refs.iter().map(|text| text.parse()).collect()
}
fn resolve_ns(session: &Session, manifest: &Manifest, text: &str) -> eyre::Result<u64> {
let spec: TimeSpec = text.parse()?;
Ok(spec
.resolve(manifest, &SessionLookup::new(session, manifest))?
.mach_ns)
}
fn emit(
json: bool,
schema: &str,
annotation: &annotations::Annotation,
manifest: &Manifest,
warnings: Vec<String>,
) -> eyre::Result<()> {
let view = annotation.view(manifest);
if json {
return print_json(
&Envelope::ok(schema, AnnotationData { annotation: view }).warnings(warnings),
);
}
print!("{}", report::annotation_text(&view));
for warning in warnings {
eprintln!("note: {warning}");
}
Ok(())
}
pub(super) fn annotate(args: &AnnotateArgs) -> eyre::Result<()> {
// not `load`: marking has to work on a session that is still being recorded
let session = Session::open(&args.session)?;
let manifest = session.manifest()?;
match &args.action {
Action::Add(add) => add_annotation(&session, &manifest, add),
Action::Edit(edit) => edit_annotation(&session, &manifest, edit),
Action::Delete(delete) => {
annotations::delete(&session.dir, &delete.id)?;
if delete.json {
return print_json(&Envelope::ok(
SCHEMA_DELETED,
DeletedData {
deleted: delete.id.clone(),
},
));
}
println!("deleted {}", delete.id);
Ok(())
}
}
}
fn add_annotation(session: &Session, manifest: &Manifest, args: &AddArgs) -> eyre::Result<()> {
let kind = Kind::from(args.kind);
let loaded = annotations::load(&session.dir)?;
let refs = parse_refs(&args.refs)?;
let about = match &args.about {
Some(id) => Some(
loaded
.get(id)
.ok_or_else(|| envelope::not_found(format!("there is no annotation {id}")))?,
),
None => None,
};
let text = args.text.clone().unwrap_or_default();
if text.trim().is_empty() {
return Err(envelope::usage(match kind {
Kind::Bug => "a bug needs --text: what does it look like?",
Kind::Note => "a note needs --text",
Kind::Finding => "a finding needs --text: what is the cause?",
}));
}
if kind == Kind::Finding && refs.is_empty() {
return Err(envelope::usage(
"a finding needs evidence: pass at least one --ref (event:<seq>, log:<line>, \
code:<path>:<line> or frame:<time>)",
));
}
if kind == Kind::Bug && args.end.is_none() && !args.open_ended {
return Err(envelope::usage(
"a bug region needs --end (or --open-ended if it was still happening when the \
recording stopped)",
));
}
// a finding without a time of its own takes the bug it explains, else its earliest evidence
let start = if let Some(start) = &args.start {
resolve_ns(session, manifest, start)?
} else if let Some(about) = about {
about.start_mach_ns
} else if kind == Kind::Finding {
let lookup = SessionLookup::new(session, manifest);
let earliest = refs
.iter()
.filter_map(|reference| match reference {
Ref::Event { seq } => format!("event:{seq}").parse::<TimeSpec>().ok(),
Ref::Frame { video_s } => format!("{video_s}").parse::<TimeSpec>().ok(),
_ => None,
})
.filter_map(|spec| spec.resolve(manifest, &lookup).ok())
.map(|resolved| resolved.mach_ns)
.min();
earliest.ok_or_else(|| {
envelope::usage("say when with --start or --about <bug id>: no evidence has a time")
})?
} else {
return Err(envelope::usage("--start is required"));
};
let end = match (&args.end, about, kind) {
(Some(end), _, _) => Some(resolve_ns(session, manifest, end)?),
(None, Some(about), Kind::Finding) => about.end_mach_ns,
_ => None,
};
let code_root = args
.code_root
.clone()
.or_else(|| annotations::default_code_root(manifest.komorebi.flavor));
let warnings = annotations::validate_refs(session, manifest, &refs, code_root.as_deref())?;
let author = args.author.clone().unwrap_or_else(|| {
if kind == Kind::Finding {
"agent".to_string()
} else {
annotations::AUTHOR_USER.to_string()
}
});
let id = annotations::add(
&session.dir,
New {
kind: Some(kind),
start_mach_ns: start,
end_mach_ns: end,
title: args.title.clone().unwrap_or_default(),
text,
expected: args.expected.clone(),
displays: args.displays.clone(),
author: Some(author),
about: args.about.clone(),
refs,
},
)?;
let added = annotations::load(&session.dir)?;
let annotation = added.get(&id).ok_or_else(|| {
eyre::Report::msg("the annotation was written but could not be read back")
})?;
emit(args.json, SCHEMA_ANNOTATION, annotation, manifest, warnings)
}
fn edit_annotation(session: &Session, manifest: &Manifest, args: &EditArgs) -> eyre::Result<()> {
let refs = (!args.refs.is_empty())
.then(|| parse_refs(&args.refs))
.transpose()?;
let mut warnings = Vec::new();
if let Some(refs) = &refs {
let code_root = args
.code_root
.clone()
.or_else(|| annotations::default_code_root(manifest.komorebi.flavor));
warnings = annotations::validate_refs(session, manifest, refs, code_root.as_deref())?;
}
let patch = Patch {
start_mach_ns: args
.start
.as_deref()
.map(|text| resolve_ns(session, manifest, text))
.transpose()?,
end_mach_ns: args
.end
.as_deref()
.map(|text| resolve_ns(session, manifest, text))
.transpose()?,
title: args.title.clone(),
text: args.text.clone(),
expected: args.expected.clone(),
displays: (!args.displays.is_empty()).then(|| args.displays.clone()),
refs,
};
annotations::edit(&session.dir, &args.id, patch)?;
let loaded = annotations::load(&session.dir)?;
let annotation = loaded.get(&args.id).ok_or_else(|| {
eyre::Report::msg("the annotation was written but could not be read back")
})?;
emit(args.json, SCHEMA_ANNOTATION, annotation, manifest, warnings)
}
pub(super) fn list(args: &AnnotationsArgs) -> eyre::Result<()> {
let session = Session::open(&args.session)?;
let manifest = session.manifest()?;
let loaded = annotations::load(&session.dir)?;
let wanted = args.kind.map(Kind::from);
let views: Vec<AnnotationView> = loaded
.annotations
.iter()
.filter(|annotation| wanted.is_none_or(|kind| annotation.kind == kind))
.map(|annotation| annotation.view(&manifest))
.collect();
if args.json {
return print_json(
&Envelope::ok(SCHEMA_ANNOTATIONS, AnnotationsData { annotations: views })
.warnings(loaded.warnings),
);
}
if views.is_empty() {
println!("no annotations; add one with `komorebi-recorder annotate <session> add ...`");
}
for view in &views {
print!("{}", report::annotation_text(view));
}
for warning in &loaded.warnings {
eprintln!("warning: {warning}");
}
Ok(())
}
+390
View File
@@ -0,0 +1,390 @@
//! `state`, `diff` and `events`: what komorebi believed, what changed, and what happened. Also
//! `code`, `trace` and `window`, which explain one log line, one event and one window.
//!
//! Each command opens the session as an [`Analysis`] ([`Analysis::open`]), asks it one question,
//! and prints the answer as text ([`crate::report`]) or, with `--json`, in the envelope its schema
//! names. A time argument is any form [`Analysis::resolve`] reads: `12.5`, `1:02.5`,
//! `wall:<RFC 3339>`, `event:<seq>`, `bug:<id>.end`, optionally followed by an offset such as `+3s`.
//!
//! | Command | Asks | Answer, with `--json` |
//! |---|---|---|
//! | `state` | [`Analysis::state_answer`] | `state/1` |
//! | `diff` | [`Analysis::diff_answer`] | `diff/1` |
//! | `events` | [`Analysis::events_answer`] | `events/1` |
//! | `code` | [`Analysis::code_for_lines`], [`Analysis::code_for_event`] or [`Analysis::code_search`] | `code/1` |
//! | `trace` | [`Analysis::trace`], and `Analysis::os_trace` with `--os` | `trace/1` |
//! | `window` | [`Analysis::window_history`] | `window/1` |
//!
//! `events` and `window` page with `--limit` and `--cursor`: when an answer is cut short it prints
//! (or, with `--json`, sets `next_cursor` to) the sequence number to continue after. A limit of 0
//! means no limit.
//!
//! Covered by `tests/investigate.rs`, `tests/trace.rs` and `tests/code.rs`, which run the commands
//! through the real binary.
use super::print_json;
use crate::analysis::Analysis;
use crate::analysis::answers::EventQuery;
use crate::analysis::answers::SCHEMA_DIFF;
use crate::analysis::answers::SCHEMA_EVENTS;
use crate::analysis::answers::SCHEMA_STATE;
use crate::analysis::answers::StateQuery;
use crate::analysis::classify::Class;
use crate::analysis::code::SCHEMA_CODE;
use crate::analysis::envelope;
use crate::analysis::envelope::Envelope;
use crate::report;
use clap::Args;
use clap::ValueEnum;
use color_eyre::eyre;
use std::path::PathBuf;
/// The arguments of `state`.
#[derive(Args, Debug)]
pub struct StateArgs {
/// Session directory
pub session: PathBuf,
/// The moment: 12.5, 1:02.5, `wall:<RFC 3339>`, `event:<seq>`, `bug:<id>.end`, optionally +3s.
/// `event:<seq>` is the state before that event ran, `event:<seq>.end` after it
#[arg(long, value_name = "TIME")]
pub at: String,
/// Only windows with this id, or whose application or title contains this text
#[arg(long, value_name = "ID|TEXT")]
pub window: Option<String>,
/// Only this monitor (display id)
#[arg(long, value_name = "ID")]
pub monitor: Option<u64>,
/// Show workspaces that are not showing too
#[arg(long)]
pub all: bool,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
/// The arguments of `diff`.
#[derive(Args, Debug)]
pub struct DiffArgs {
/// Session directory
pub session: PathBuf,
/// The earlier moment (see `state --at`)
pub from: String,
/// The later moment
pub to: String,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
/// A class of event, as the `--class` option of `events` spells it: one variant for each [`Class`],
/// which says what each means.
///
/// The variants have no doc comments: clap would show each as a line of the option's help, and
/// that switches `events --help` to its long layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ClassArg {
Command,
Drag,
Focus,
Lifecycle,
Echo,
Manual,
Monitor,
Lock,
Other,
}
impl From<ClassArg> for Class {
fn from(class: ClassArg) -> Self {
match class {
ClassArg::Command => Self::Command,
ClassArg::Drag => Self::Drag,
ClassArg::Focus => Self::Focus,
ClassArg::Lifecycle => Self::Lifecycle,
ClassArg::Echo => Self::Echo,
ClassArg::Manual => Self::Manual,
ClassArg::Monitor => Self::Monitor,
ClassArg::Lock => Self::Lock,
ClassArg::Other => Self::Other,
}
}
}
/// The arguments of `events`.
#[derive(Args, Debug)]
pub struct EventsArgs {
/// Session directory
pub session: PathBuf,
/// Only events received at or after this moment
#[arg(long, value_name = "TIME")]
pub from: Option<String>,
/// Only events received at or before this moment
#[arg(long, value_name = "TIME")]
pub to: Option<String>,
/// Only these classes (repeatable)
#[arg(long = "class", value_enum)]
pub classes: Vec<ClassArg>,
/// Leave out echoes of komorebi's own moves
#[arg(long)]
pub hide_echo: bool,
/// Only events whose name contains this text, e.g. `MoveEnd` or `FocusWorkspace`
#[arg(long)]
pub name: Option<String>,
/// Only events about this process id
#[arg(long)]
pub pid: Option<i32>,
/// Only events about this window id
#[arg(long)]
pub window: Option<u32>,
/// Most events to print (0 for all)
#[arg(long, default_value_t = 50)]
pub limit: usize,
/// Continue after this event sequence number (from a truncated answer's `next_cursor`)
#[arg(long, value_name = "SEQ")]
pub cursor: Option<u64>,
/// Say why each event was classified as it was
#[arg(long)]
pub verbose: bool,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
pub(super) fn state(args: &StateArgs) -> eyre::Result<()> {
let analysis = Analysis::open(&args.session)?;
let at = analysis.resolve(&args.at)?;
let data = analysis.state_answer(
at.mach_ns,
&StateQuery {
window: args.window.clone(),
monitor: args.monitor,
all: args.all,
},
)?;
if args.json {
return print_json(&Envelope::ok(SCHEMA_STATE, data).warnings(analysis.warnings()));
}
print!("{}", report::state_text(&data));
Ok(())
}
pub(super) fn diff_command(args: &DiffArgs) -> eyre::Result<()> {
let analysis = Analysis::open(&args.session)?;
let from = analysis.resolve(&args.from)?;
let to = analysis.resolve(&args.to)?;
if to.mach_ns < from.mach_ns {
return Err(envelope::usage(format!(
"{} is before {}: give the earlier moment first",
args.to, args.from
)));
}
let data = analysis.diff_answer(from.mach_ns, to.mach_ns)?;
if args.json {
return print_json(&Envelope::ok(SCHEMA_DIFF, data).warnings(analysis.warnings()));
}
print!("{}", report::diff_text(&data));
Ok(())
}
pub(super) fn events(args: &EventsArgs) -> eyre::Result<()> {
let analysis = Analysis::open(&args.session)?;
let moment = |text: &Option<String>| -> eyre::Result<Option<u64>> {
text.as_deref()
.map(|text| analysis.resolve(text).map(|resolved| resolved.mach_ns))
.transpose()
};
let answer = analysis.events_answer(&EventQuery {
from_mach_ns: moment(&args.from)?,
to_mach_ns: moment(&args.to)?,
classes: args.classes.iter().copied().map(Class::from).collect(),
hide_echo: args.hide_echo,
name: args.name.clone(),
pid: args.pid,
window: args.window,
limit: (args.limit != 0).then_some(args.limit),
after_seq: args.cursor,
});
if args.json {
let mut envelope = Envelope::ok(SCHEMA_EVENTS, answer.data).warnings(analysis.warnings());
if answer.next_cursor.is_some() {
envelope = envelope.truncated(answer.next_cursor);
}
return print_json(&envelope);
}
print!("{}", report::events_text(&answer.data, args.verbose));
if let Some(cursor) = &answer.next_cursor {
println!("... more; continue with --cursor {cursor}");
}
Ok(())
}
/// The arguments of `code`.
#[derive(Args, Debug)]
pub struct CodeArgs {
/// Session directory
pub session: PathBuf,
/// What to explain: `log:<line>` (a line of komorebi's log) or `event:<seq>` (everything the
/// handler of that event logged)
pub refs: Vec<String>,
/// Instead, find statements in komorebi's source whose message contains this text
#[arg(long, value_name = "TEXT")]
pub grep: Option<String>,
/// Lines of source to show either side of each statement
#[arg(long, default_value_t = 3)]
pub context: usize,
/// A checkout of the recorded komorebi, to show source from [default: `$KOMOREBI_MAC_SRC` or
/// `$KOMOREBI_WINDOWS_SRC` for the session's komorebi, `$KOMOREBI_SOURCE`, or the one this
/// recorder was built from]
#[arg(long = "komorebi-src", alias = "code-root", value_name = "DIR")]
pub code_root: Option<PathBuf>,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
pub(super) fn code(args: &CodeArgs) -> eyre::Result<()> {
let analysis = Analysis::open(&args.session)?;
let root = args
.code_root
.clone()
.or_else(|| crate::annotations::default_code_root(analysis.flavor()));
let data = if let Some(text) = &args.grep {
analysis.code_search(text)
} else {
if args.refs.is_empty() {
return Err(envelope::usage(
"say what to explain: log:<line>, event:<seq>, or --grep <text>",
));
}
let mut combined: Option<crate::analysis::code::CodeData> = None;
for text in &args.refs {
let item: crate::analysis::ids::ItemRef = text.parse()?;
let part = match item {
crate::analysis::ids::ItemRef::Log(line) => {
analysis.code_for_lines(text, &[line], args.context, root.as_deref())?
}
crate::analysis::ids::ItemRef::Event(seq) => {
analysis.code_for_event(seq, args.context, root.as_deref())?
}
_ => {
return Err(envelope::usage(format!(
"'{text}': only log:<line> and event:<seq> have source code"
)));
}
};
match &mut combined {
Some(all) => {
all.about = format!("{} {text}", all.about);
all.lines.extend(part.lines);
}
None => combined = Some(part),
}
}
combined.ok_or_else(|| envelope::usage("nothing to explain"))?
};
if args.json {
let mut warnings = analysis.warnings();
warnings.extend(data.skew.warning.clone());
return print_json(&Envelope::ok(SCHEMA_CODE, data).warnings(warnings));
}
print!("{}", report::code_text(&data));
Ok(())
}
/// The arguments of `trace`.
#[derive(Args, Debug)]
pub struct TraceArgs {
/// Session directory
pub session: PathBuf,
/// The event: `event:<seq>` or just the number
pub event: String,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
pub(super) fn trace(args: &TraceArgs) -> eyre::Result<()> {
let analysis = Analysis::open(&args.session)?;
let item: crate::analysis::ids::ItemRef = if args.event.chars().all(|c| c.is_ascii_digit()) {
format!("event:{}", args.event).parse()?
} else {
args.event.parse()?
};
let crate::analysis::ids::ItemRef::Event(seq) = item else {
return Err(envelope::usage(format!(
"'{}': trace explains an event, e.g. event:12",
args.event
)));
};
let data = analysis.trace(seq)?;
if args.json {
let mut warnings = analysis.warnings();
let skew = analysis.skew();
warnings.extend(skew.warning);
return print_json(
&Envelope::ok(crate::analysis::trace::SCHEMA_TRACE, data).warnings(warnings),
);
}
let skew = analysis.skew();
if let Some(warning) = skew.warning {
eprintln!("WARNING: {warning}");
}
print!("{}", report::trace_text(&data));
Ok(())
}
/// The arguments of `window`.
#[derive(Args, Debug)]
pub struct WindowArgs {
/// Session directory
pub session: PathBuf,
/// A window id, or text in the application name or title
pub query: String,
/// Most entries to print (0 for all)
#[arg(long, default_value_t = 100)]
pub limit: usize,
/// Continue after this event sequence number
#[arg(long, value_name = "SEQ")]
pub cursor: Option<u64>,
/// Machine-readable JSON output
#[arg(long)]
pub json: bool,
}
pub(super) fn window(args: &WindowArgs) -> eyre::Result<()> {
let analysis = Analysis::open(&args.session)?;
let limit = (args.limit != 0).then_some(args.limit);
let data = analysis.window_history(&args.query, args.cursor, limit)?;
let truncated = data.matching > data.entries.len();
let next_cursor = truncated
.then(|| data.entries.last().map(|entry| entry.seq.to_string()))
.flatten();
if args.json {
let mut envelope = Envelope::ok(crate::analysis::history::SCHEMA_WINDOW, data)
.warnings(analysis.warnings());
if next_cursor.is_some() {
envelope = envelope.truncated(next_cursor);
}
return print_json(&envelope);
}
print!("{}", report::history_text(&data));
if let Some(cursor) = next_cursor {
println!("continue with --cursor {cursor}");
}
Ok(())
}
+68
View File
@@ -5,7 +5,10 @@
//! command is run through [`execute`], which turns its outcome into the process's exit status.
//! `--json` on a command also decides how a failure is reported (see [`Command::wants_json`]).
mod agent;
mod annotate;
mod doctor;
mod investigate;
mod query;
mod record;
@@ -19,7 +22,20 @@ use color_eyre::eyre;
use serde::Serialize;
use std::path::PathBuf;
pub use agent::BriefArgs;
pub use agent::GuideArgs;
pub use agent::OverviewArgs;
pub use agent::SchemaArgs;
pub use agent::SearchArgs;
pub use annotate::AnnotateArgs;
pub use annotate::AnnotationsArgs;
pub use doctor::DoctorArgs;
pub use investigate::CodeArgs;
pub use investigate::DiffArgs;
pub use investigate::EventsArgs;
pub use investigate::StateArgs;
pub use investigate::TraceArgs;
pub use investigate::WindowArgs;
pub use query::AtArgs;
pub use query::FilterArgs;
pub use query::FramesArgs;
@@ -68,6 +84,33 @@ pub enum Command {
Locate(LocateArgs),
/// Extract PNG frames at video timecodes (needs ffmpeg)
Frames(FramesArgs),
/// Start here when investigating: what the user marked as the bug, and what the recording shows
/// around it
Brief(BriefArgs),
/// The whole recording at a glance: what stands out, ranked, and when things happened
Overview(OverviewArgs),
/// Where a word appears: komorebi's log, events, incidents, annotations, optionally the OS trace
Search(SearchArgs),
/// How to investigate a recording, for an agent
Guide(GuideArgs),
/// The JSON Schema of a command's `--json` output
Schema(SchemaArgs),
/// The state komorebi was in at a moment: monitors, workspaces, windows, focus, and anything wrong
State(StateArgs),
/// What changed between two moments, in terms a person would use
Diff(DiffArgs),
/// komorebi's events, classified, with the handler that ran for each
Events(EventsArgs),
/// One window's life through the recording: where it was, when it moved or was hidden
Window(WindowArgs),
/// One event end to end: what its handler logged, what changed, and who changed it
Trace(TraceArgs),
/// Which line of komorebi's source wrote a line of its log, with the code around it
Code(CodeArgs),
/// Add, edit or delete a session's bug regions, notes and an agent's findings
Annotate(AnnotateArgs),
/// List a session's bug regions, notes and findings
Annotations(AnnotationsArgs),
/// 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
@@ -118,6 +161,18 @@ impl Command {
Self::Summary(args) => args.json,
Self::Locate(args) => args.json,
Self::Frames(args) => args.json,
Self::Brief(args) => args.json,
Self::Overview(args) => args.json,
Self::Search(args) => args.json,
Self::Guide(args) => args.json,
Self::State(args) => args.json,
Self::Diff(args) => args.json,
Self::Events(args) => args.json,
Self::Code(args) => args.json,
Self::Trace(args) => args.json,
Self::Window(args) => args.json,
Self::Annotate(args) => args.json(),
Self::Annotations(args) => args.json,
Self::Doctor(args) => args.json,
_ => false,
}
@@ -163,6 +218,19 @@ pub fn run(command: Command) -> eyre::Result<()> {
Command::Summary(args) => query::summary(&args),
Command::Locate(args) => query::locate(&args),
Command::Frames(args) => query::frames_command(&args),
Command::Brief(args) => agent::brief(&args),
Command::Overview(args) => agent::overview(&args),
Command::Search(args) => agent::search(&args),
Command::Guide(args) => agent::guide(&args),
Command::Schema(args) => agent::schema(&args),
Command::State(args) => investigate::state(&args),
Command::Diff(args) => investigate::diff_command(&args),
Command::Events(args) => investigate::events(&args),
Command::Code(args) => investigate::code(&args),
Command::Trace(args) => investigate::trace(&args),
Command::Window(args) => investigate::window(&args),
Command::Annotate(args) => annotate::annotate(&args),
Command::Annotations(args) => annotate::list(&args),
Command::Reindex(args) => reindex(&args),
Command::Selftest(args) => crate::selftest::run(&args),
Command::SelftestClock => crate::selftest::run_clock(),
+99
View File
@@ -0,0 +1,99 @@
# Investigating a komorebi recording
You have a recording of komorebi misbehaving: the screen, komorebi's log, every event it sent with
its full state, and (on a Mac) what macOS did to the machine meanwhile, all on one clock. It is
komorebi for Mac or komorebi for Windows: `overview` says which, and what a handler, a window id
and a hidden window look like differ between them (a window is a window id and a process on a Mac,
a handle and a program on Windows; a hidden window is parked in a corner on a Mac and cloaked in
place on Windows, so its position says nothing there). Your job is to find
what *produces* the bug the user described, from the recording, and then propose a fix that rests on
what it shows. Every command takes `--json`; its output is an envelope
`{ok, schema, data, warnings, truncated, next_cursor, error}` whose `data` is described by
`komorebi-recorder schema <schema>`. Exit codes: 0 ok, 1 error, 2 usage, 3 not found, 4 unusable
session, 5 over budget.
## 1. Start with the brief
komorebi-recorder brief <session>
The user marked a **region** of the video where the bug was visible and described it. That
description is the ground truth of *what* went wrong. Do not reinterpret it; explain it. If no region
was marked the brief says so: ask the user when it happened and what they saw, then record it with
komorebi-recorder annotate <session> add --kind bug --start <t> --end <t> --text "<what is wrong>"
The brief then gives, for each region: the events in it (echoes of komorebi's own moves are counted,
not listed), what looked wrong and for how long, the state as the bug began and as it ended 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.
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.
## 2. Work from effect to cause
1. **What was wrong.** `state --at bug:<id>` and `state --at bug:<id>.end` show what komorebi
believed, with `violations` for anything inconsistent (a window parked off screen on a workspace
that is showing, a window in two places, the layout not applied). A window's `rect` is where it
really was, read live from the accessibility API; `layout_rect` is where komorebi meant it to be.
2. **What changed.** `diff bug:<id> bug:<id>.end`, or `diff event:N event:N.end` for one event.
3. **What happened.** `events --from bug:<id> --to bug:<id>.end --hide-echo`. Classes: `command`,
`focus`, `lifecycle`, `drag`, `monitor`, `lock`; `echo` is the OS reporting back a move komorebi
made itself, never user input.
4. **Who did it.** `trace event:N` shows what the handler logged (each line with the source
statement that wrote it), what other threads logged meanwhile, and every change with an
**attribution**: `handler`, `reaper`, `workspace-reconciliator`, or `unexplained`. The reaper and
the workspace reconciliator change state *without a notification*, so their changes surface in
the next event. `unexplained` means state changed and nothing in the log accounts for it: that is
a finding in itself (komorebi changed state silently, or its log level hides the cause).
`trace event:N --os` adds what the **OS trace** recorded around it: komorebi's own calls into the
OS while the handler ran, then the system and each application reacting, in time order. Records
in that window are not proof the event caused them (other events' handlers may overlap it, and
the output lists them), but it is where to look for "what did the system do when komorebi did
this".
5. **One window.** `window <id|text>` follows a window through every recorded state.
6. **The code.** `code event:N` or `code log:N` maps log lines to the statement that wrote them,
with the code around it. `ambiguous` and `generic` matches say so: do not pin a cause on one.
7. **Anything else.** `search <text>` across the log, events, incidents and annotations
(`--oslog` adds the OS trace, where the recording has one); `at`, `range` and `summary` read the raw timeline.
## 3. Facts about the data that change what it means
- An event's receive time is when komorebi **finished** handling it: the notification is sent after
the handler body. `event:N` as a time is the moment the handler began; `event:N.end` the moment
it was received.
- komorebi logs no handler *end* line for events at INFO, and cannot show time spent waiting for the
lock or in accessibility calls before the handler's header. `handler_ms` is a lower bound.
- The state in a notification is the state *after* the event, plus anything background threads did
since the last one. States can be stale: `age_ms` in `origin` says how long.
- An `AXError` in komorebi's log comes from the application or the OS, not from komorebi.
- komorebi for Windows hides a window by **cloaking it where it is**, so its `State` cannot say
whether a window is really hidden, and the position-based hidden-window checks do not apply. A
recording made with `--probe-windows` stores, with each window event, what Windows said about that
window just after it (`exists`, `visible`, `cloaked`, `minimized`, `rect`, and now and then
komorebi's own `DebugWindow` verdict with the rules that matched); `overview` then reports
`visible-window-hidden` (komorebi has it in front, Windows has it cloaked or minimized),
`hidden-window-visible` (komorebi has it put away, Windows has it on screen) and
`unmanaged-window` (on screen and not managed: usually right, and komorebi's explanation is
quoted), and `trace event:N` shows the facts. Without the probe none of that is knowable, and
`overview` says nothing about it.
- Video time `00:00.000` is the first frame of any display. A display that was unplugged, asleep
or whose capture failed has a gap, and `incident` records say why.
## 4. Record what you conclude, with evidence
komorebi-recorder annotate <session> add --kind finding --about <bug id> \
--text "<the cause, in one or two sentences>" \
--ref event:<n> --ref log:<n> --ref code:<path>:<line>
A finding with no evidence is refused, and every reference is checked to exist. Cite evidence by
event number, log line, video time and state difference. Never claim a cause without a reference,
and say what you could not verify.
## 5. Propose the fix
Name the file and function from `code`. Explain the chain from what the user saw to the state to the
event to the statement. Propose the smallest change that breaks the chain, say what would confirm it
(which command shows the difference once the fix is in; re-record the same scenario), and say what
the recording cannot show.
+313
View File
@@ -29,16 +29,20 @@
use crate::analysis::answers::DiffData;
use crate::analysis::answers::EventsData;
use crate::analysis::answers::StateData;
use crate::analysis::brief::BriefData;
use crate::analysis::brief::RegionBrief;
use crate::analysis::code::CodeData;
use crate::analysis::history::HistoryData;
use crate::analysis::invariants::Severity;
use crate::analysis::invariants::Violation;
use crate::analysis::overview::Finding;
use crate::analysis::overview::OverviewData;
use crate::analysis::search::SearchData;
use crate::analysis::state::Container;
use crate::analysis::state::Window;
use crate::analysis::trace::TraceData;
use crate::analysis::trace::TraceLine;
use crate::analysis::views::EventView;
use crate::annotations::AnnotationView;
use crate::annotations::Kind;
use crate::timecode;
@@ -1141,6 +1145,31 @@ pub fn history_text(data: &HistoryData) -> String {
out
}
fn event_line(event: &EventView) -> String {
let handler = event.handler.as_ref().map_or_else(String::new, |handler| {
let ms = handler
.handler_ms
.map_or_else(String::new, |ms| format!(" {ms:.0} ms"));
let problems = if handler.errors + handler.warnings > 0 {
format!(" {}E/{}W", handler.errors, handler.warnings)
} else {
String::new()
};
format!(" handler{ms}{problems}")
});
let state = match event.state_changed {
Some(true) => " state changed",
_ => "",
};
format!(
"#{:<5} {} {:<9} {}{handler}{state}",
event.seq,
timecode::format(event.video_s),
format!("{:?}", event.class).to_lowercase(),
event.summary
)
}
fn finding_line(finding: &Finding) -> String {
let severity = match finding.severity {
Severity::Error => "error",
@@ -1160,6 +1189,238 @@ fn finding_line(finding: &Finding) -> String {
)
}
fn region_text(out: &mut String, region: &RegionBrief) {
let _ = writeln!(
out,
"\nlooking at {} to {} (the region, from a few seconds before it)",
region.from.timecode, region.to.timecode
);
let classes: Vec<String> = region
.events
.by_class
.iter()
.map(|(class, count)| format!("{count} {class}"))
.collect();
let _ = writeln!(
out,
"events: {} ({}{})",
region.events.total,
classes.join(", "),
if region.events.echoes_hidden > 0 {
format!(
"; {} echoes of komorebi's own moves not listed",
region.events.echoes_hidden
)
} else {
String::new()
}
);
for event in &region.events.listed {
let _ = writeln!(out, " {}", event_line(event));
}
if region.events.truncated {
let _ = writeln!(out, " ... more: use `events` with --from/--to to page");
}
if !region.suspects.is_empty() {
let _ = writeln!(out, "\nmost worth tracing first:");
for (index, suspect) in region.suspects.iter().enumerate() {
let _ = writeln!(
out,
" {}. event #{} {} (score {}): {}\n {}",
index + 1,
suspect.event.seq,
suspect.event.summary,
suspect.score,
suspect.reasons.join("; "),
suspect.next
);
}
}
if !region.findings.is_empty() {
let _ = writeln!(out, "\nwhat looked wrong or unusual:");
for finding in &region.findings {
let _ = writeln!(out, " {}", finding_line(finding));
}
}
for (label, state) in [
("as it began", &region.state_at_start),
("as it ended", &region.state_at_end),
] {
match state {
Some(state) => {
let _ = writeln!(
out,
"\nkomorebi's state {label} ({}): {}",
state.at.timecode, state.summary
);
if state.violations.is_empty() {
let _ = writeln!(out, " nothing looks wrong");
} else {
violation_lines(out, &state.violations);
}
}
None => {
let _ = writeln!(out, "\nkomorebi's state {label}: not recorded");
}
}
}
if !region.changes.is_empty() {
let _ = writeln!(
out,
"\nwhat changed between them ({} total):",
region.changes_total
);
for change in &region.changes {
let _ = writeln!(out, " {}", change.text);
}
}
if !region.incidents.is_empty() {
let _ = writeln!(out, "\nwhat happened to the machine nearby:");
for incident in &region.incidents {
let _ = writeln!(
out,
" {} {}{}: {}",
timecode::format(incident.video_s),
incident.kind,
incident
.display
.map_or_else(String::new, |display| format!(" (display {display})")),
incident.detail
);
}
}
}
/// Renders the answer to `brief`: what the user says is wrong comes first, word for word.
///
/// The text has, in order: each bug region as the user reported it (or, if none was marked, a
/// line saying so); the facts of the session and any warnings, including that komorebi's source
/// is not the version that was recorded; for each region, what the recording shows around it and
/// the commands to run next (or, with no region, the same over the whole recording); conclusions
/// already recorded and notes; and what to do next.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::analysis::Analysis;
/// use komorebi_recorder::annotations::{Kind, New, add};
/// use komorebi_recorder::report::brief_text;
/// use komorebi_recorder::testkit::{SessionBuilder, mach_ns};
/// use serde_json::json;
///
/// let (session, _) = SessionBuilder::new("doc-brief-text")
/// .event(2.0, json!({"type": "Retile"}), None)
/// .build();
/// add(&session.dir, New {
/// kind: Some(Kind::Bug),
/// start_mach_ns: mach_ns(1.0),
/// end_mach_ns: Some(mach_ns(3.0)),
/// text: "the window jumps".to_string(),
/// ..New::default()
/// })?;
///
/// let text = brief_text(&Analysis::open(&session.dir)?.brief()?);
/// // the user's words come first
/// assert!(text.starts_with("BUG, as the user reported it:\nbug "));
/// assert!(text.contains("\n the window jumps\n"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[must_use]
pub fn brief_text(data: &BriefData) -> String {
let mut out = String::new();
if data.bugs.is_empty() {
let _ = writeln!(out, "NO BUG REGION WAS MARKED in this recording.\n");
}
for bug in &data.bugs {
let _ = writeln!(out, "BUG, as the user reported it:");
out.push_str(&annotation_text(&bug.bug));
}
let session = &data.session;
let displays: Vec<String> = session
.displays
.iter()
.map(|display| {
format!(
"{} ({}x{}, {} segment(s))",
display.id, display.width_px, display.height_px, display.segments
)
})
.collect();
let _ = writeln!(
out,
"\nsession {}\n {} s of video, displays: {}\n komorebi: {}{}\n {} events, {} log lines, {} incidents; video sync: {}",
session.dir,
session.duration_s as i64,
if displays.is_empty() {
"none".to_string()
} else {
displays.join(", ")
},
if session.komorebi.is_empty() {
"version unknown".to_string()
} else {
session.komorebi.join("; ")
},
session
.komorebi_log_level
.as_ref()
.map_or_else(String::new, |level| format!(", logging at {level}")),
session.events,
session.log_lines,
session.incidents,
session.sync_quality
);
for warning in &session.warnings {
let _ = writeln!(out, " warning: {warning}");
}
if let Some(warning) = &data.skew.warning {
let _ = writeln!(out, "\nWARNING: {warning}");
}
for bug in &data.bugs {
let _ = writeln!(out, "\n=== {} ===", bug.bug.id);
region_text(&mut out, &bug.region);
let _ = writeln!(out, "\nnext:");
for command in &bug.commands {
let _ = writeln!(out, " {command}");
}
}
if let Some(region) = &data.whole_session {
let _ = writeln!(out, "\n=== the whole recording ===");
region_text(&mut out, region);
}
if !data.findings_recorded.is_empty() {
let _ = writeln!(out, "\nconclusions already recorded:");
for finding in &data.findings_recorded {
out.push_str(&annotation_text(finding));
}
}
if !data.notes.is_empty() {
let _ = writeln!(out, "\nnotes:");
for note in &data.notes {
out.push_str(&annotation_text(note));
}
}
if !data.next.is_empty() {
let _ = writeln!(out, "\n");
for line in &data.next {
let _ = writeln!(out, "{line}");
}
}
out
}
/// Renders the answer to `overview`: the session's size, the bug regions the user marked, the
/// findings most worth looking at first, and a histogram of when things happened.
///
@@ -1241,6 +1502,58 @@ pub fn overview_text(data: &OverviewData) -> String {
out
}
/// Renders the answer to `search`: how many hits there were and where it looked, then a line for
/// each hit.
///
/// A line has the hit's time, its source, the reference to give another command (`log:345`,
/// `event:12`) and the first line of its text.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::analysis::Analysis;
/// use komorebi_recorder::analysis::budget::Budget;
/// use komorebi_recorder::analysis::search::SearchQuery;
/// use komorebi_recorder::report::search_text;
/// use komorebi_recorder::testkit::SessionBuilder;
///
/// let (session, _) = SessionBuilder::new("doc-search-text")
/// .log(2.0, "INFO", "komorebi::process_command: retiling the workspace")
/// .build();
/// let analysis = Analysis::open(&session.dir)?;
///
/// let found = analysis.search(
/// &SearchQuery { pattern: "retiling".to_string(), ..SearchQuery::default() },
/// &Budget::unlimited(),
/// )?;
/// let text = search_text(&found);
/// assert!(text.starts_with("1 hit(s) for 'retiling' in "));
/// assert!(text.contains("log:1"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[must_use]
pub fn search_text(data: &SearchData) -> String {
let mut out = String::new();
let _ = writeln!(
out,
"{} hit(s) for '{}' in {}",
data.matching,
data.query,
data.searched.join(", ")
);
for hit in &data.hits {
let _ = writeln!(
out,
"{} {:<14} {:<22} {}",
timecode::format(hit.video_s),
hit.source,
hit.reference,
hit.text.lines().next().unwrap_or("")
);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
+306
View File
@@ -0,0 +1,306 @@
//! `annotate` and `annotations` through the real binary, against a synthetic session.
use komorebi_recorder::testkit::SessionBuilder;
use komorebi_recorder::testkit::state_with_windows;
use serde_json::Value;
use serde_json::json;
use std::process::Command;
use std::process::Output;
fn recorder(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_komorebi-recorder"))
.args(args)
.output()
.expect("run komorebi-recorder")
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).into_owned()
}
fn envelope(output: &Output) -> Value {
serde_json::from_slice(&output.stdout)
.unwrap_or_else(|error| panic!("not JSON ({error}): {}", stdout(output)))
}
fn session(name: &str) -> String {
let (session, _) = SessionBuilder::new(name)
.event(
2.0,
json!({"type": "Show", "content": []}),
Some(state_with_windows(&[(1, "one")])),
)
.event(
4.0,
json!({"type": "FocusChange", "content": []}),
Some(state_with_windows(&[(1, "one"), (2, "two")])),
)
.log(3.0, "INFO", "komorebi::process_event: processing event")
.build();
session.dir.display().to_string()
}
#[test]
fn a_bug_region_is_added_listed_and_read_back_verbatim() {
let dir = session("annotate-bug");
let added = recorder(&[
"annotate",
&dir,
"add",
"--kind",
"bug",
"--start",
"2.5",
"--end",
"6",
"--text",
"the new window opens on the wrong monitor",
"--expected",
"it should open on the focused monitor",
"--json",
]);
assert!(
added.status.success(),
"{}",
String::from_utf8_lossy(&added.stderr)
);
let added = envelope(&added);
assert_eq!(added["ok"], true);
assert_eq!(added["schema"], "annotation/1");
let id = added["data"]["annotation"]["id"]
.as_str()
.expect("id")
.to_string();
assert!(
(added["data"]["annotation"]["start_video_s"]
.as_f64()
.expect("start")
- 2.5)
.abs()
< 1e-6
);
assert!(
(added["data"]["annotation"]["end_video_s"]
.as_f64()
.expect("end")
- 6.0)
.abs()
< 1e-6
);
let listed = envelope(&recorder(&["annotations", &dir, "--kind", "bug", "--json"]));
let annotations = listed["data"]["annotations"].as_array().expect("array");
assert_eq!(annotations.len(), 1);
assert_eq!(annotations[0]["id"], id.as_str());
assert_eq!(
annotations[0]["text"],
"the new window opens on the wrong monitor"
);
assert_eq!(annotations[0]["open_ended"], false);
// the text rendering leads with what the user said is wrong
let text = stdout(&recorder(&["annotations", &dir]));
assert!(text.contains("what goes wrong"), "{text}");
assert!(
text.contains("the new window opens on the wrong monitor"),
"{text}"
);
assert!(text.contains("00:02.500 -> 00:06.000"), "{text}");
}
#[test]
fn a_bug_can_be_marked_relative_to_an_event_and_edited_and_deleted() {
let dir = session("annotate-edit");
let added = envelope(&recorder(&[
"annotate",
&dir,
"add",
"--kind",
"bug",
"--start",
"event:2-1s",
"--open-ended",
"--text",
"tiles overlap",
"--json",
]));
let id = added["data"]["annotation"]["id"]
.as_str()
.expect("id")
.to_string();
// event 2 is at 4s
assert!(
(added["data"]["annotation"]["start_video_s"]
.as_f64()
.expect("start")
- 3.0)
.abs()
< 1e-6
);
assert_eq!(added["data"]["annotation"]["open_ended"], true);
let edited = envelope(&recorder(&[
"annotate",
&dir,
"edit",
&id,
"--end",
"event:2.end+2s",
"--json",
]));
assert_eq!(edited["data"]["annotation"]["open_ended"], false);
assert!(
(edited["data"]["annotation"]["end_video_s"]
.as_f64()
.expect("end")
- 6.0)
.abs()
< 1e-6
);
let deleted = recorder(&["annotate", &dir, "delete", &id, "--json"]);
assert!(deleted.status.success());
let listed = envelope(&recorder(&["annotations", &dir, "--json"]));
assert_eq!(
listed["data"]["annotations"]
.as_array()
.expect("array")
.len(),
0
);
}
#[test]
fn a_bug_without_an_end_or_a_description_is_refused_with_the_usage_exit_code() {
let dir = session("annotate-refuse");
let no_end = recorder(&[
"annotate", &dir, "add", "--kind", "bug", "--start", "2", "--text", "x",
]);
assert_eq!(no_end.status.code(), Some(2));
assert!(String::from_utf8_lossy(&no_end.stderr).contains("--end"));
let no_text = recorder(&[
"annotate", &dir, "add", "--kind", "bug", "--start", "2", "--end", "3",
]);
assert_eq!(no_text.status.code(), Some(2));
}
#[test]
fn a_finding_must_cite_evidence_that_exists() {
let dir = session("annotate-finding");
let bug = envelope(&recorder(&[
"annotate", &dir, "add", "--kind", "bug", "--start", "2", "--end", "5", "--text", "wrong",
"--json",
]));
let bug_id = bug["data"]["annotation"]["id"]
.as_str()
.expect("id")
.to_string();
// no evidence at all
let bare = recorder(&[
"annotate", &dir, "add", "--kind", "finding", "--about", &bug_id, "--text", "cause",
]);
assert_eq!(bare.status.code(), Some(2));
// evidence that is not there is not found
let missing = recorder(&[
"annotate", &dir, "add", "--kind", "finding", "--about", &bug_id, "--text", "cause",
"--ref", "event:99",
]);
assert_eq!(
missing.status.code(),
Some(3),
"{}",
String::from_utf8_lossy(&missing.stderr)
);
// real evidence is accepted and the finding inherits the bug's region
let found = envelope(&recorder(&[
"annotate",
&dir,
"add",
"--kind",
"finding",
"--about",
&bug_id,
"--text",
"the show handler tiled it twice",
"--ref",
"event:1",
"--ref",
"log:1",
"--json",
]));
assert_eq!(found["ok"], true);
assert_eq!(found["data"]["annotation"]["kind"], "finding");
assert_eq!(found["data"]["annotation"]["about"], bug_id.as_str());
assert!(
(found["data"]["annotation"]["start_video_s"]
.as_f64()
.expect("start")
- 2.0)
.abs()
< 1e-6
);
assert_eq!(
found["data"]["annotation"]["refs"]
.as_array()
.expect("refs")
.len(),
2
);
}
#[test]
fn failures_in_json_mode_are_an_error_envelope_with_the_exit_code() {
let dir = session("annotate-json-error");
let output = recorder(&[
"annotate",
&dir,
"edit",
"a-00000000",
"--text",
"x",
"--json",
]);
assert_eq!(output.status.code(), Some(3));
let body = envelope(&output);
assert_eq!(body["ok"], false);
assert_eq!(body["error"]["kind"], "not-found");
assert_eq!(body["error"]["code"], 3);
}
#[test]
fn annotating_works_on_a_session_that_is_still_recording() {
let (session, mut manifest) = SessionBuilder::new("annotate-live").build();
manifest.status = "recording".to_string();
session.write_manifest(&manifest).expect("manifest");
let dir = session.dir.display().to_string();
let output = recorder(&[
"annotate",
&dir,
"add",
"--kind",
"bug",
"--start",
"1",
"--open-ended",
"--text",
"x",
"--json",
]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
// but reading the timeline of a live session says so, with the unusable exit code
let at = recorder(&["at", &dir, "1"]);
assert_eq!(at.status.code(), Some(4));
}
+426
View File
@@ -0,0 +1,426 @@
//! The agent's entry points through the real binary: `brief`, `overview`, `search`, `guide` and
//! `schema`, on a session shaped like a docking bug with the user's bug region marked.
use komorebi_recorder::testkit::SessionBuilder;
use komorebi_recorder::testkit::container;
use komorebi_recorder::testkit::monitor;
use komorebi_recorder::testkit::state;
use komorebi_recorder::testkit::window;
use komorebi_recorder::testkit::workspace;
use serde_json::Value;
use serde_json::json;
use std::process::Command;
use std::process::Output;
fn recorder(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_komorebi-recorder"))
.args(args)
.output()
.expect("run komorebi-recorder")
}
fn json(args: &[&str]) -> Value {
let output = recorder(args);
assert!(
output.status.success(),
"{args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("JSON")
}
fn text(args: &[&str]) -> String {
let output = recorder(args);
assert!(
output.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8_lossy(&output.stdout).into_owned()
}
const LAYOUT: [[i64; 4]; 2] = [[0, 0, 500, 800], [500, 0, 500, 800]];
fn screen(second: [i64; 4]) -> Value {
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,
)
}
/// A retile, its echo, then at 5 s a display goes away and the next focus change leaves window 2
/// parked off screen on the workspace that is showing.
fn session(name: &str, mark_bug: bool) -> String {
let notification = |kind: &str, what: &str| json!({"type": kind, "content": [{"type": "Accessibility", "content": what}, 11, 2]});
let (session, _) = SessionBuilder::new(name)
.event(2.1, json!({"type": "Retile"}), Some(screen(LAYOUT[1])))
.event(3.05, notification("MoveEnd", "AXWindowMoved"), Some(screen(LAYOUT[1])))
.event(5.2, notification("FocusChange", "AXApplicationActivated"), Some(screen([-499, 790, 500, 800])))
.log(2.0, "INFO", "process_command: komorebi::process_command: processing command: Retile")
.log(2.2, "INFO", "process_command: komorebi::process_command: processed command: Retile")
.log(3.0, "INFO", "process_event: komorebi::process_event: processing event: MoveEnd for process 11 with notification AXWindowMoved")
.log(5.0, "INFO", "process_event: komorebi::process_event: processing event: FocusChange for process 11 with notification AXApplicationActivated")
.log(5.1, "ERROR", "process_event:window_rect: komorebi::macos_api: failed to get window position: AXError::InvalidUIElement")
.incident(4.9, "display-disconnected", "display 3 went away")
.komorebi_commit("0000000000000000000000000000000000000000")
.build();
let dir = session.dir.display().to_string();
if mark_bug {
let output = recorder(&[
"annotate",
&dir,
"add",
"--kind",
"bug",
"--start",
"4.5",
"--end",
"7",
"--text",
"After unplugging the monitor my Brave window is gone from the screen",
"--expected",
"it should move to the laptop display",
]);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
dir
}
#[test]
fn the_brief_leads_with_the_users_words_and_points_at_the_event_that_broke_it() {
let dir = session("brief-bug", true);
let answer = json(&["brief", &dir, "--json"]);
assert_eq!(answer["schema"], "brief/1");
let data = &answer["data"];
// the user's description, verbatim, with the region
let bug = &data["bugs"][0]["bug"];
assert_eq!(
bug["text"],
"After unplugging the monitor my Brave window is gone from the screen"
);
assert_eq!(bug["expected"], "it should move to the laptop display");
assert!((bug["start_video_s"].as_f64().expect("start") - 4.5).abs() < 1e-6);
assert!((bug["end_video_s"].as_f64().expect("end") - 7.0).abs() < 1e-6);
let region = &data["bugs"][0]["region"];
// the first suspect is the focus change that left the window parked, and says why
let suspect = &region["suspects"][0];
assert_eq!(suspect["event"]["seq"], 3);
let reasons: Vec<&str> = suspect["reasons"]
.as_array()
.expect("reasons")
.iter()
.map(|reason| reason.as_str().expect("reason"))
.collect();
assert!(
reasons
.iter()
.any(|reason| reason.contains("visible-window-hidden")),
"{reasons:?}"
);
assert!(
reasons
.iter()
.any(|reason| reason.contains("logged 1 error")),
"{reasons:?}"
);
// the state as the bug began was fine and as it ended was wrong
assert_eq!(
region["state_at_start"]["violations"]
.as_array()
.expect("v")
.len(),
0
);
assert_eq!(
region["state_at_end"]["violations"][0]["kind"],
"visible-window-hidden"
);
// the display that went away is there, and so is what changed
assert_eq!(region["incidents"][0]["kind"], "display-disconnected");
let changes: Vec<&str> = region["changes"]
.as_array()
.expect("changes")
.iter()
.map(|change| change["kind"].as_str().expect("kind"))
.collect();
assert!(changes.contains(&"window-rect"), "{changes:?}");
// the echo of the retile is counted but not listed
assert_eq!(region["events"]["echoes_hidden"], 1);
let listed: Vec<&str> = region["events"]["listed"]
.as_array()
.expect("listed")
.iter()
.map(|event| event["class"].as_str().expect("class"))
.collect();
assert!(!listed.contains(&"echo"), "{listed:?}");
// a commit the repository does not have cannot be compared, which is said, not assumed
assert_eq!(data["skew"]["verdict"], "unknown");
assert!(
answer["warnings"]
.as_array()
.expect("warnings")
.iter()
.any(|w| w.as_str().is_some_and(|text| text.contains("0000000000")))
);
}
#[test]
fn the_text_brief_starts_with_the_bug_as_reported() {
let dir = session("brief-text", true);
let brief = text(&["brief", &dir]);
assert!(
brief.starts_with("BUG, as the user reported it:"),
"{brief}"
);
let words = brief
.find("After unplugging the monitor my Brave window is gone")
.expect("words");
let evidence = brief.find("most worth tracing first").expect("suspects");
assert!(
words < evidence,
"the user's words come before the evidence"
);
assert!(brief.contains("komorebi-recorder trace"), "{brief}");
assert!(brief.contains("--kind finding --about"), "{brief}");
}
#[test]
fn without_a_bug_region_the_brief_says_so_and_digests_the_whole_recording() {
let dir = session("brief-no-bug", false);
let answer = json(&["brief", &dir, "--json"]);
assert_eq!(answer["data"]["bugs"].as_array().expect("bugs").len(), 0);
assert!(
answer["data"]["whole_session"]["events"]["total"]
.as_u64()
.expect("total")
>= 3
);
let next = answer["data"]["next"][0].as_str().expect("next");
assert!(next.contains("no bug region was marked"), "{next}");
assert!(text(&["brief", &dir]).starts_with("NO BUG REGION WAS MARKED"));
}
#[test]
fn findings_in_the_bug_region_rank_above_the_rest() {
let dir = session("overview-rank", true);
let answer = json(&["overview", &dir, "--json"]);
let findings = answer["data"]["findings"].as_array().expect("findings");
assert!(findings.len() >= 3, "{findings:#?}");
// the stuck window overlaps the bug region and is an error, so it leads
assert_eq!(findings[0]["kind"], "invariant:visible-window-hidden");
assert_eq!(findings[0]["persisted_to_end"], true);
assert_eq!(findings[0]["bugs"].as_array().expect("bugs").len(), 1);
// and an ERROR line in the log and the unplugged display are found too
let kinds: Vec<&str> = findings
.iter()
.map(|f| f["kind"].as_str().expect("kind"))
.collect();
assert!(kinds.contains(&"log-error"), "{kinds:?}");
assert!(
kinds.contains(&"incident:display-disconnected"),
"{kinds:?}"
);
// scores are descending
let scores: Vec<i64> = findings
.iter()
.map(|f| f["score"].as_i64().expect("score"))
.collect();
assert!(
scores.windows(2).all(|pair| pair[0] >= pair[1]),
"{scores:?}"
);
assert!(
answer["data"]["histogram"]
.as_array()
.expect("histogram")
.len()
> 5
);
assert!(text(&["overview", &dir]).contains("findings, most worth looking at first"));
}
#[test]
fn search_finds_words_across_sources_and_gives_references() {
let dir = session("search", true);
let answer = json(&["search", &dir, "InvalidUIElement", "--json"]);
let hits = answer["data"]["hits"].as_array().expect("hits");
assert_eq!(hits.len(), 1);
assert_eq!(hits[0]["source"], "komorebi-log");
assert_eq!(hits[0]["reference"], "log:5");
// events, incidents and annotations are searched too, case-insensitively
let many = json(&["search", &dir, "brave", "--json"]);
let sources: Vec<&str> = many["data"]["hits"]
.as_array()
.expect("hits")
.iter()
.map(|hit| hit["source"].as_str().expect("source"))
.collect();
assert!(sources.contains(&"annotations"), "{sources:?}");
let incident = json(&["search", &dir, "display 3", "--json"]);
assert_eq!(incident["data"]["hits"][0]["reference"], "incident:1");
let regex = json(&[
"search",
&dir,
"^processing (event|command)",
"--regex",
"--json",
]);
// two event headers and one command header; `processed command` does not match
assert_eq!(regex["data"]["matching"], 3);
// a reference from a hit goes straight into another command
let traced = json(&["code", &dir, "log:5", "--json"]);
assert_eq!(traced["data"]["lines"][0]["message"], hits[0]["text"]);
assert_eq!(
recorder(&["search", &dir, "(", "--regex"]).status.code(),
Some(2)
);
assert_eq!(recorder(&["search", &dir, ""]).status.code(), Some(2));
}
#[test]
fn search_pages_with_a_cursor() {
let dir = session("search-page", true);
let first = json(&["search", &dir, "process", "--limit", "2", "--json"]);
assert_eq!(first["truncated"], true);
let cursor = first["next_cursor"].as_str().expect("cursor").to_string();
let next = json(&[
"search", &dir, "process", "--limit", "2", "--cursor", &cursor, "--json",
]);
let first_refs: Vec<&str> = first["data"]["hits"]
.as_array()
.expect("hits")
.iter()
.map(|hit| hit["reference"].as_str().expect("ref"))
.collect();
for hit in next["data"]["hits"].as_array().expect("hits") {
assert!(!first_refs.contains(&hit["reference"].as_str().expect("ref")));
}
}
#[test]
fn the_guide_and_the_schemas_describe_the_outputs() {
let guide = text(&["guide"]);
assert!(guide.contains("## 1. Start with the brief"));
assert!(guide.contains("annotate <session> add --kind finding"));
let wrapped = json(&["guide", "--json"]);
assert!(
wrapped["data"]["guide"]
.as_str()
.expect("guide")
.contains("Investigating a komorebi recording")
);
let listed = text(&["schema"]);
for name in [
"brief/1",
"overview/1",
"state/1",
"trace/1",
"code/1",
"error/1",
] {
assert!(listed.contains(name), "{name} missing from:\n{listed}");
}
let schema = json_stdout(&["schema", "brief/1"]);
assert_eq!(schema["title"], "BriefData");
assert!(schema["properties"]["bugs"].is_object());
assert_eq!(recorder(&["schema", "nothing/9"]).status.code(), Some(3));
}
/// Every `schema` an envelope names can be asked for.
#[test]
fn every_command_names_a_schema_that_exists() {
let dir = session("schema-names", true);
let ids = json(&["annotations", &dir, "--json"]);
let bug = ids["data"]["annotations"][0]["id"]
.as_str()
.expect("id")
.to_string();
let commands: Vec<Vec<String>> = vec![
vec!["brief".into(), dir.clone()],
vec!["overview".into(), dir.clone()],
vec![
"state".into(),
dir.clone(),
"--at".into(),
"event:3.end".into(),
],
vec![
"diff".into(),
dir.clone(),
"event:3".into(),
"event:3.end".into(),
],
vec!["events".into(), dir.clone()],
vec!["trace".into(), dir.clone(), "event:3".into()],
vec!["window".into(), dir.clone(), "brave".into()],
vec!["code".into(), dir.clone(), "log:5".into()],
vec!["search".into(), dir.clone(), "event".into()],
vec!["annotations".into(), dir.clone()],
vec![
"annotate".into(),
dir.clone(),
"edit".into(),
bug,
"--title".into(),
"t".into(),
],
];
for command in commands {
let mut args: Vec<&str> = command.iter().map(String::as_str).collect();
args.push("--json");
let answer = json(&args);
let name = answer["schema"].as_str().expect("schema");
assert!(
recorder(&["schema", name]).status.success(),
"{args:?} names the schema '{name}', which `schema` does not know"
);
}
}
fn json_stdout(args: &[&str]) -> Value {
json(args)
}
+237
View File
@@ -0,0 +1,237 @@
//! `code`: from a recorded log line to the line of komorebi's source that wrote it.
use komorebi_recorder::analysis::catalog;
use komorebi_recorder::analysis::flavor::Flavor;
use komorebi_recorder::testkit::SessionBuilder;
use serde_json::Value;
use serde_json::json;
use std::process::Command;
use std::process::Output;
fn recorder(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_komorebi-recorder"))
.args(args)
.output()
.expect("run komorebi-recorder")
}
fn json(args: &[&str]) -> Value {
let output = recorder(args);
assert!(
output.status.success(),
"{args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("JSON")
}
/// A session whose log was written by real komorebi statements, recorded by the komorebi this
/// recorder was built against (so there is no version skew) or by another one.
fn session(name: &str, commit: Option<&str>) -> String {
let mut builder = SessionBuilder::new(name)
.event(
2.3,
json!({"type": "FocusChange", "content": [{"type": "Accessibility", "content": "AXApplicationActivated"}, 7, 3]}),
None,
)
.log(2.0, "INFO", "process_event: komorebi::process_event: processing event: FocusChange for process 7 with notification AXApplicationActivated")
.log(2.1, "INFO", "process_event:focus_window{idx=0}: komorebi::container: focusing window")
.log(2.2, "INFO", "komorebi::reaper: reaping window: 4711")
.log(2.25, "INFO", "komorebi::border_manager: invalidating border observer");
if let Some(commit) = commit {
builder = builder.komorebi_commit(commit);
}
builder.build().0.dir.display().to_string()
}
#[test]
fn a_log_line_is_traced_to_the_statement_that_wrote_it() {
let recorded = catalog::of(Flavor::Macos).commit().unwrap_or("unknown");
let dir = session("code-line", Some(recorded));
let answer = json(&["code", &dir, "log:3", "--context", "1", "--json"]);
assert_eq!(answer["schema"], "code/1");
let line = &answer["data"]["lines"][0];
assert_eq!(line["target"], "komorebi::reaper");
assert_eq!(line["message"], "reaping window: 4711");
let source = &line["source"]["statement"];
assert_eq!(source["file"], "komorebi/src/reaper.rs");
assert!(
source["template"]
.as_str()
.expect("template")
.starts_with("reaping window")
);
// the reaper logs this from three places, and the answer says so rather than picking one
assert_eq!(line["source"]["confidence"], "ambiguous");
assert_eq!(
line["source"]["alternatives"]
.as_array()
.expect("alternatives")
.len(),
2
);
// the reaper changes state without telling subscribers, which is the point of saying so
assert_eq!(line["changes_state_silently"], true);
assert!(
line["role"]
.as_str()
.expect("role")
.contains("no longer exist")
);
// and the code around the statement is there, with the statement in the middle
let snippet = line["snippet"]["lines"].as_array().expect("snippet");
assert_eq!(snippet.len(), 3);
let middle = snippet[1][1].as_str().expect("text");
assert!(middle.contains("reaping window"), "{middle}");
}
#[test]
fn an_event_is_explained_by_everything_its_handler_logged() {
let recorded = catalog::of(Flavor::Macos).commit().unwrap_or("unknown");
let dir = session("code-event", Some(recorded));
let answer = json(&["code", &dir, "event:1", "--json"]);
let lines = answer["data"]["lines"].as_array().expect("lines");
// the header and the focus line are the handler's; the reaper and border manager are not
assert_eq!(lines.len(), 2, "{lines:#?}");
assert_eq!(lines[0]["source"]["statement"]["function"], "process_event");
assert_eq!(lines[1]["source"]["statement"]["owner"], "Container");
assert_eq!(lines[1]["source"]["statement"]["function"], "focus_window");
}
#[test]
fn a_commit_that_cannot_be_compared_is_a_warning_on_every_answer() {
let dir = session(
"code-skew",
Some("0000000000000000000000000000000000000000"),
);
let answer = json(&["code", &dir, "log:3", "--json"]);
assert_eq!(answer["data"]["skew"]["verdict"], "unknown");
// nothing is vouched for when it cannot be told
assert_eq!(answer["data"]["lines"][0]["file_changed"], true);
let warnings = answer["warnings"].as_array().expect("warnings");
assert!(
warnings.iter().any(|warning| warning
.as_str()
.is_some_and(|text| text.contains("0000000000"))),
"{warnings:?}"
);
let text = String::from_utf8_lossy(&recorder(&["code", &dir, "log:3"]).stdout).into_owned();
assert!(text.starts_with("WARNING:"), "{text}");
}
fn git(args: &[&str]) -> Option<String> {
let root = komorebi_recorder::testkit::komorebi_mac_src();
let output = Command::new("git")
.arg("-C")
.arg(root)
.args(args)
.output()
.ok()?;
output
.status
.success()
.then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
}
/// An older komorebi: only the files that really differ from it are doubted, the rest are as good
/// as if the commits were the same.
#[test]
fn only_the_files_that_changed_since_the_recorded_commit_are_doubted() {
let Some(history) = git(&["log", "-2", "--format=%H", "--", "komorebi/src"]) else {
return;
};
let Some(older) = history.lines().nth(1) else {
return;
};
let Some(indexed) = catalog::of(Flavor::Macos).commit() else {
return;
};
let Some(changed) = git(&[
"diff",
"--name-only",
older,
indexed,
"--",
"komorebi/src",
"komorebi-client/src",
]) else {
return;
};
let changed: Vec<&str> = changed.lines().collect();
let dir = session("code-older", Some(older));
let answer = json(&["code", &dir, "log:1", "log:2", "log:3", "--json"]);
let lines = answer["data"]["lines"].as_array().expect("lines");
assert_eq!(lines.len(), 3);
for line in lines {
let file = line["source"]["statement"]["file"].as_str().expect("file");
assert_eq!(
line["file_changed"],
changed.contains(&file),
"{file} (changed files: {changed:?})"
);
}
let verdict = answer["data"]["skew"]["verdict"].as_str().expect("verdict");
assert_eq!(
verdict,
if changed.is_empty() {
"same"
} else {
"different"
}
);
}
#[test]
fn a_session_that_did_not_record_the_version_says_it_is_unknown() {
let dir = session("code-unknown", None);
let answer = json(&["code", &dir, "log:3", "--json"]);
assert_eq!(answer["data"]["skew"]["verdict"], "unknown");
}
#[test]
fn a_line_no_statement_writes_is_said_so_and_a_bad_reference_is_not_found() {
let dir = session("code-missing", None);
let none = json(&["code", &dir, "log:4", "--json"]);
// the border manager line is a real statement; a made-up one is not
assert!(none["data"]["lines"][0]["source"].is_object());
let (made_up, _) = SessionBuilder::new("code-made-up")
.log(1.0, "INFO", "komorebi::reaper: a message nothing writes")
.build();
let dir_made_up = made_up.dir.display().to_string();
let unknown = json(&["code", &dir_made_up, "log:1", "--json"]);
assert!(unknown["data"]["lines"][0]["source"].is_null());
let beyond = recorder(&["code", &dir, "log:99"]);
assert_eq!(beyond.status.code(), Some(3));
let no_event = recorder(&["code", &dir, "event:99"]);
assert_eq!(no_event.status.code(), Some(3));
let nothing = recorder(&["code", &dir]);
assert_eq!(nothing.status.code(), Some(2));
let wrong_kind = recorder(&["code", &dir, "incident:1"]);
assert_eq!(wrong_kind.status.code(), Some(2));
}
#[test]
fn statements_can_be_searched_by_their_text() {
let dir = session("code-grep", None);
let answer = json(&["code", &dir, "--grep", "reaping window", "--json"]);
let statements = answer["data"]["statements"].as_array().expect("statements");
let in_reaper = statements
.iter()
.filter(|statement| statement["file"] == "komorebi/src/reaper.rs")
.count();
assert_eq!(in_reaper, 3, "{statements:#?}");
}
+298
View File
@@ -0,0 +1,298 @@
//! `state`, `diff` and `events` through the real binary, on a session shaped like a real bug: a
//! command retiles, the OS echoes it back, then a focus change leaves a window parked off screen.
use komorebi_recorder::testkit::SessionBuilder;
use komorebi_recorder::testkit::container;
use komorebi_recorder::testkit::monitor;
use komorebi_recorder::testkit::state;
use komorebi_recorder::testkit::window;
use komorebi_recorder::testkit::workspace;
use serde_json::Value;
use serde_json::json;
use std::process::Command;
use std::process::Output;
fn recorder(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_komorebi-recorder"))
.args(args)
.output()
.expect("run komorebi-recorder")
}
fn json(args: &[&str]) -> Value {
let output = recorder(args);
assert!(
output.status.success(),
"{args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).unwrap_or_else(|error| {
panic!(
"{args:?} printed no JSON ({error}): {}",
String::from_utf8_lossy(&output.stdout)
)
})
}
fn text(args: &[&str]) -> String {
let output = recorder(args);
assert!(
output.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8_lossy(&output.stdout).into_owned()
}
const LAYOUT: [[i64; 4]; 2] = [[0, 0, 500, 800], [500, 0, 500, 800]];
fn tidy() -> Value {
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(LAYOUT[1]))]),
],
0,
&LAYOUT,
)],
0,
)],
0,
)
}
/// Window 2 parked at the bottom-left sliver although its workspace is showing.
fn stuck() -> Value {
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([-499, 790, 500, 800]))]),
],
1,
&LAYOUT,
)],
0,
)],
0,
)
}
fn session(name: &str) -> String {
let move_end = json!({"type": "MoveEnd", "content": [{"type": "Accessibility", "content": "AXWindowMoved"}, 10, 7]});
let focus = json!({"type": "FocusChange", "content": [{"type": "Accessibility", "content": "AXApplicationActivated"}, 11, 2]});
let (session, _) = SessionBuilder::new(name)
.event(2.1, json!({"type": "Retile"}), Some(tidy()))
.event(3.05, move_end, Some(tidy()))
.event(5.2, focus, Some(stuck()))
.log(2.0, "INFO", "process_command: komorebi::process_command: processing command: Retile")
.log(2.2, "INFO", "process_command: komorebi::process_command: processed command: Retile")
.log(3.0, "INFO", "process_event: komorebi::process_event: processing event: MoveEnd for process 10 with notification AXWindowMoved")
.log(5.0, "INFO", "process_event: komorebi::process_event: processing event: FocusChange for process 11 with notification AXApplicationActivated")
.log(5.1, "ERROR", "process_event:window_rect: komorebi::macos_api: failed to get window position: AXError::InvalidUIElement")
.build();
session.dir.display().to_string()
}
#[test]
fn events_are_classified_and_paired_with_the_handler_that_ran() {
let dir = session("investigate-events");
let answer = json(&["events", &dir, "--json"]);
assert_eq!(answer["schema"], "events/1");
let events = answer["data"]["events"].as_array().expect("events");
assert_eq!(events.len(), 3);
assert_eq!(events[0]["name"], "Retile");
assert_eq!(events[0]["class"], "command");
assert_eq!(events[0]["handler"]["quality"], "header");
// the move changed nothing right after a command: an echo, and it says of what
assert_eq!(events[1]["class"], "echo");
assert_eq!(events[1]["state_changed"], false);
assert!(
events[1]["reason"]
.as_str()
.expect("reason")
.contains("Retile")
);
// the focus change took 200 ms to handle and logged an error
assert_eq!(events[2]["class"], "focus");
assert_eq!(events[2]["state_changed"], true);
assert_eq!(events[2]["handler"]["errors"], 1);
let ms = events[2]["handler"]["handler_ms"].as_f64().expect("ms");
assert!((ms - 200.0).abs() < 5.0, "handler took {ms} ms");
}
#[test]
fn events_filter_by_class_and_page_with_a_cursor() {
let dir = session("investigate-filter");
let quiet = json(&["events", &dir, "--hide-echo", "--json"]);
let names: Vec<&str> = quiet["data"]["events"]
.as_array()
.expect("events")
.iter()
.map(|event| event["name"].as_str().expect("name"))
.collect();
assert_eq!(names, ["Retile", "FocusChange"]);
let only_focus = json(&["events", &dir, "--class", "focus", "--json"]);
assert_eq!(only_focus["data"]["matching"], 1);
let first = json(&["events", &dir, "--limit", "2", "--json"]);
assert_eq!(first["truncated"], true);
let cursor = first["next_cursor"].as_str().expect("cursor").to_string();
let rest = json(&["events", &dir, "--cursor", &cursor, "--json"]);
assert_eq!(rest["data"]["events"].as_array().expect("events").len(), 1);
assert_eq!(rest["data"]["events"][0]["seq"], 3);
assert_eq!(rest["truncated"], false);
}
#[test]
fn the_state_before_an_event_is_what_the_previous_event_left() {
let dir = session("investigate-state");
// event 3 is the one that left window 2 parked: before it, nothing is wrong
let before = json(&["state", &dir, "--at", "event:3", "--json"]);
assert_eq!(
before["data"]["violations"]
.as_array()
.expect("violations")
.len(),
0
);
assert_eq!(before["data"]["origin"]["seq"], 2);
let after = json(&["state", &dir, "--at", "event:3.end", "--json"]);
let violations = after["data"]["violations"].as_array().expect("violations");
assert_eq!(violations.len(), 1);
assert_eq!(violations[0]["kind"], "visible-window-hidden");
assert_eq!(violations[0]["window_ids"][0], 2);
assert_eq!(after["data"]["origin"]["seq"], 3);
assert_eq!(after["data"]["focus"]["window_id"], 2);
}
#[test]
fn diff_names_what_an_event_did() {
let dir = session("investigate-diff");
let answer = json(&["diff", &dir, "event:3", "event:3.end", "--json"]);
let changes = answer["data"]["changes"].as_array().expect("changes");
let kinds: Vec<&str> = changes
.iter()
.map(|change| change["kind"].as_str().expect("kind"))
.collect();
assert!(kinds.contains(&"window-rect"), "{kinds:?}");
assert!(kinds.contains(&"focus"), "{kinds:?}");
let rect = changes
.iter()
.find(|change| change["kind"] == "window-rect")
.expect("rect");
assert_eq!(rect["hidden_before"], false);
assert_eq!(rect["hidden_after"], true);
assert!(rect["text"].as_str().expect("text").contains("now hidden"));
let appeared = answer["data"]["violations_appeared"]
.as_array()
.expect("appeared");
assert_eq!(appeared[0]["kind"], "visible-window-hidden");
// the command before it changed nothing visible: an echo-sized event diffs empty
let quiet = json(&["diff", &dir, "event:2", "event:2.end", "--json"]);
assert_eq!(
quiet["data"]["changes"].as_array().expect("changes").len(),
0
);
}
#[test]
fn state_can_be_asked_about_one_window() {
let dir = session("investigate-window");
let answer = json(&[
"state",
&dir,
"--at",
"event:3.end",
"--window",
"brave",
"--json",
]);
let found = &answer["data"]["matches"][0];
assert_eq!(found["window"]["id"], 2);
assert_eq!(found["hidden_position"], true);
assert_eq!(found["layout_rect"]["left"], 500);
assert_eq!(found["window"]["rect"]["left"], -499);
let missing = recorder(&[
"state",
&dir,
"--at",
"event:3.end",
"--window",
"nothing-like-this",
]);
assert_eq!(missing.status.code(), Some(3));
}
#[test]
fn the_text_forms_lead_with_what_matters() {
let dir = session("investigate-text");
let state = text(&["state", &dir, "--at", "event:3.end"]);
assert!(state.contains("as of event #3"), "{state}");
assert!(state.contains("visible-window-hidden"), "{state}");
assert!(state.contains("[showing]"), "{state}");
let diff = text(&["diff", &dir, "event:3", "event:3.end"]);
assert!(diff.contains("now hidden"), "{diff}");
assert!(diff.contains("wrong now, and not before"), "{diff}");
let events = text(&["events", &dir, "--verbose"]);
assert!(events.contains("echo"), "{events}");
assert!(events.contains("the OS reporting back"), "{events}");
}
#[test]
fn a_time_before_any_state_was_recorded_is_not_found_not_a_guess() {
let (session, _) = SessionBuilder::new("investigate-no-state").build();
let dir = session.dir.display().to_string();
let output = recorder(&["state", &dir, "--at", "1", "--json"]);
assert_eq!(output.status.code(), Some(3));
let body: Value = serde_json::from_slice(&output.stdout).expect("envelope");
assert_eq!(body["ok"], false);
assert_eq!(body["error"]["kind"], "not-found");
}
#[test]
fn a_session_that_is_still_recording_is_unusable_with_a_hint() {
let (session, mut manifest) = SessionBuilder::new("investigate-live").build();
manifest.status = "recording".to_string();
session.write_manifest(&manifest).expect("manifest");
let dir = session.dir.display().to_string();
let output = recorder(&["events", &dir, "--json"]);
assert_eq!(output.status.code(), Some(4));
let body: Value = serde_json::from_slice(&output.stdout).expect("envelope");
assert_eq!(body["error"]["kind"], "unusable");
assert!(
body["error"]["hint"]
.as_str()
.expect("hint")
.contains("reindex")
);
}
+264
View File
@@ -0,0 +1,264 @@
//! `trace` and `window`: one event end to end, and one window through the whole recording.
use komorebi_recorder::testkit::SessionBuilder;
use komorebi_recorder::testkit::container;
use komorebi_recorder::testkit::monitor;
use komorebi_recorder::testkit::state;
use komorebi_recorder::testkit::window;
use komorebi_recorder::testkit::workspace;
use serde_json::Value;
use serde_json::json;
use std::process::Command;
use std::process::Output;
fn recorder(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_komorebi-recorder"))
.args(args)
.output()
.expect("run komorebi-recorder")
}
fn json(args: &[&str]) -> Value {
let output = recorder(args);
assert!(
output.status.success(),
"{args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("JSON")
}
fn text(args: &[&str]) -> String {
let output = recorder(args);
assert!(
output.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8_lossy(&output.stdout).into_owned()
}
fn one_workspace(containers: Vec<Value>, layout: &[[i64; 4]]) -> Value {
state(
vec![monitor(
1,
[0, 0, 1000, 800],
vec![workspace("one", containers, 0, layout)],
0,
)],
0,
)
}
/// Two windows; then the second is reaped by the reaper (no notification of its own) and the next
/// focus change reports the result; then a Brave window appears again.
fn session(name: &str) -> String {
let two = one_workspace(
vec![
container("a", vec![window(1, "Ghostty", Some([0, 0, 500, 800]))]),
container("b", vec![window(2, "Brave", Some([500, 0, 500, 800]))]),
],
&[[0, 0, 500, 800], [500, 0, 500, 800]],
);
let one = one_workspace(
vec![container(
"a",
vec![window(1, "Ghostty", Some([0, 0, 1000, 800]))],
)],
&[[0, 0, 1000, 800]],
);
let back = one_workspace(
vec![
container("a", vec![window(1, "Ghostty", Some([0, 0, 500, 800]))]),
container("c", vec![window(3, "Brave", Some([500, 0, 500, 800]))]),
],
&[[0, 0, 500, 800], [500, 0, 500, 800]],
);
let notification = |name: &str, notification: &str| json!({"type": name, "content": [{"type": "Accessibility", "content": notification}, 7, 1]});
let (session, _) = SessionBuilder::new(name)
.event(1.0, notification("Show", "AXWindowCreated"), Some(two))
.event(4.0, notification("FocusChange", "AXApplicationActivated"), Some(one))
.event(6.0, notification("Show", "AXWindowCreated"), Some(back))
.log(0.9, "INFO", "process_event: komorebi::process_event: processing event: Show for process 7 with notification AXWindowCreated")
.log(3.5, "INFO", "komorebi::reaper: reaping window: 2")
.log(3.6, "INFO", "komorebi::border_manager: invalidating border observer")
.log(3.9, "INFO", "process_event: komorebi::process_event: processing event: FocusChange for process 7 with notification AXApplicationActivated")
.log(3.95, "INFO", "process_event:focus_container{idx=0}: komorebi::workspace: focusing container")
.log(5.9, "INFO", "process_event: komorebi::process_event: processing event: Show for process 7 with notification AXWindowCreated")
.build();
session.dir.display().to_string()
}
#[test]
fn a_change_with_no_event_of_its_own_is_blamed_on_the_reaper_by_its_log_line() {
let dir = session("trace-reaper");
let answer = json(&["trace", &dir, "event:2", "--json"]);
let data = &answer["data"];
assert_eq!(data["event"]["seq"], 2);
assert_eq!(data["event"]["class"], "focus");
// the handler's own lines, mapped to the source that wrote them
let handler = data["handler"].as_array().expect("handler");
assert_eq!(handler.len(), 2);
assert_eq!(handler[1]["spans"], "process_event:focus_container");
assert_eq!(
handler[1]["source"]["function"],
"Workspace::focus_container"
);
// the reaper and border manager lines are ambient: other threads, in the interval
let ambient: Vec<&str> = data["ambient"]
.as_array()
.expect("ambient")
.iter()
.map(|line| line["message"].as_str().expect("message"))
.collect();
assert_eq!(
ambient,
["reaping window: 2", "invalidating border observer"]
);
let changes = data["changes"].as_array().expect("changes");
let removed = changes
.iter()
.find(|change| change["kind"] == "window-removed")
.expect("window removed");
assert_eq!(removed["attribution"]["actor"], "reaper");
assert_eq!(removed["attribution"]["confidence"], "high");
// and the evidence is the reaper's own log line (line 2 of the log)
assert_eq!(removed["attribution"]["evidence"], json!([2]));
// the surviving window growing to fill the space is the handler's re-layout
let grew = changes
.iter()
.find(|change| change["kind"] == "window-rect")
.expect("window rect");
assert_eq!(grew["attribution"]["actor"], "handler");
}
#[test]
fn the_text_trace_reads_top_to_bottom() {
let dir = session("trace-text");
let text = text(&["trace", &dir, "2"]);
let handler = text
.find("what the handler logged")
.expect("handler section");
let ambient = text
.find("logged by other threads meanwhile")
.expect("ambient section");
let changed = text
.find("what changed, and who did it")
.expect("changes section");
assert!(handler < ambient && ambient < changed, "{text}");
assert!(text.contains("reaper (high)"), "{text}");
assert!(text.contains("evidence: log:2"), "{text}");
assert!(text.contains("from komorebi/src/workspace.rs"), "{text}");
}
#[test]
fn an_event_with_no_log_says_so_instead_of_inventing_a_handler() {
let (session, _) = SessionBuilder::new("trace-no-log")
.event(
1.0,
json!({"type": "Retile"}),
Some(one_workspace(vec![], &[])),
)
.build();
let dir = session.dir.display().to_string();
let answer = json(&["trace", &dir, "event:1", "--json"]);
assert_eq!(
answer["data"]["handler"].as_array().expect("handler").len(),
0
);
let notes = answer["data"]["notes"].as_array().expect("notes");
assert!(
notes.iter().any(|note| note
.as_str()
.is_some_and(|text| text.contains("no handler lines"))),
"{notes:?}"
);
assert_eq!(
recorder(&["trace", &dir, "event:99"]).status.code(),
Some(3)
);
assert_eq!(recorder(&["trace", &dir, "log:1"]).status.code(), Some(2));
}
#[test]
fn a_window_is_followed_through_every_state() {
let dir = session("window-history");
let answer = json(&["window", &dir, "brave", "--json"]);
let windows = answer["data"]["windows"].as_array().expect("windows");
let ids: Vec<u64> = windows
.iter()
.map(|window| window["id"].as_u64().expect("id"))
.collect();
assert_eq!(ids, [2, 3]);
let entries = answer["data"]["entries"].as_array().expect("entries");
let summary: Vec<(u64, u64, &str)> = entries
.iter()
.map(|entry| {
(
entry["seq"].as_u64().expect("seq"),
entry["window_id"].as_u64().expect("window"),
entry["changes"][0].as_str().unwrap_or(""),
)
})
.collect();
assert_eq!(summary.len(), 3, "{entries:#?}");
assert_eq!((summary[0].0, summary[0].1), (1, 2));
assert!(
summary[0]
.2
.starts_with("appeared on monitor 1 workspace one")
);
assert_eq!(
(summary[1].0, summary[1].1, summary[1].2),
(2, 2, "went away")
);
assert_eq!((summary[2].0, summary[2].1), (3, 3));
// asking for one window by id narrows it
let one = json(&["window", &dir, "1", "--json"]);
let changes: Vec<&str> = one["data"]["entries"]
.as_array()
.expect("entries")
.iter()
.flat_map(|entry| entry["changes"].as_array().expect("changes").iter())
.map(|change| change.as_str().expect("text"))
.collect();
assert!(
changes.iter().any(|change| change.contains("really at")),
"{changes:?}"
);
assert_eq!(
recorder(&["window", &dir, "nothing-like-this"])
.status
.code(),
Some(3)
);
}
#[test]
fn window_history_pages_with_a_cursor() {
let dir = session("window-page");
let first = json(&["window", &dir, "brave", "--limit", "2", "--json"]);
assert_eq!(first["truncated"], true);
let cursor = first["next_cursor"].as_str().expect("cursor").to_string();
let rest = json(&["window", &dir, "brave", "--cursor", &cursor, "--json"]);
assert_eq!(
rest["data"]["entries"].as_array().expect("entries").len(),
1
);
assert_eq!(rest["truncated"], false);
}
+173
View File
@@ -0,0 +1,173 @@
//! A session recorded against komorebi for Windows, read end to end through the real commands.
//!
//! The session is built from what komorebi for Windows' source says it sends and logs, because no
//! recording of it has been read yet (see `docs/dev/windows-checkpoints.md`, W0). When a real one
//! is available this should be run against it too; until then this is what keeps the Windows rules
//! consistent with themselves.
use komorebi_recorder::analysis::flavor::Flavor;
use komorebi_recorder::testkit::SessionBuilder;
use komorebi_recorder::testkit::windows_state;
use komorebi_recorder::testkit::windows_window;
use serde_json::Value;
use serde_json::json;
use std::process::Command;
fn run(args: &[&str]) -> Value {
let output = Command::new(env!("CARGO_BIN_EXE_komorebi-recorder"))
.args(args)
.output()
.expect("run komorebi-recorder");
assert!(
output.status.success(),
"{args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("json")
}
/// The handler span komorebi for Windows opens for an event, and the line it ends with.
const FOCUS_SPAN: &str = r#"process_event{event="FocusChange" winevent="SystemForeground" hwnd=131072}: komorebi::process_event:"#;
const MOVE_SPAN: &str = r#"process_event{event="MoveResizeEnd" winevent="SystemMoveSizeEnd" hwnd=131072}: komorebi::process_event:"#;
const WINDOW: &str = "(hwnd: 131072, title: window 131072, exe: chrome.exe, class: Window)";
fn session(name: &str) -> String {
let before = windows_state(
65_537,
vec![vec![windows_window(
131_072,
"chrome.exe",
Some([0, 0, 960, 1040]),
)]],
);
let after = windows_state(
65_537,
vec![vec![windows_window(
131_072,
"chrome.exe",
Some([100, 100, 800, 600]),
)]],
);
let (session, _) = SessionBuilder::new(name)
.flavor(Flavor::Windows)
.log(2.0, "DEBUG", &format!("{FOCUS_SPAN} focusing window"))
.log(2.01, "INFO", &format!("{FOCUS_SPAN} processed: {WINDOW}"))
.event(
2.02,
json!({"type": "FocusChange", "content": ["SystemForeground",
windows_window(131_072, "chrome.exe", Some([0, 0, 960, 1040]))]}),
Some(before),
)
.log(5.0, "DEBUG", &format!("{MOVE_SPAN} moving with mouse"))
.log(5.01, "INFO", &format!("{MOVE_SPAN} processed: {WINDOW}"))
.event(
5.02,
json!({"type": "MoveResizeEnd", "content": ["SystemMoveSizeEnd",
windows_window(131_072, "chrome.exe", Some([100, 100, 800, 600]))]}),
Some(after),
)
.event(7.0, json!({"type": "SessionLocked"}), None)
.event(8.0, json!("LeftAssociatedVirtualDesktop"), None)
.build();
session.dir.display().to_string()
}
#[test]
fn events_are_read_with_their_window_handle_program_and_class() {
let dir = session("windows-flavor-events");
let answer = run(&["events", &dir, "--json"]);
let events = answer["data"]["events"].as_array().expect("events");
assert_eq!(events.len(), 4);
let focus = &events[0];
assert_eq!(focus["name"], "FocusChange");
assert_eq!(focus["family"], "window-manager");
assert_eq!(focus["window_id"], 131_072);
assert_eq!(focus["exe"], "chrome.exe");
assert_eq!(focus["notification"], "SystemForeground");
assert_eq!(focus["class"], "focus");
assert_eq!(events[1]["name"], "MoveResizeEnd");
assert_eq!(events[1]["class"], "drag");
// notifications about the machine are not commands
assert_eq!(events[2]["name"], "SessionLocked");
assert_eq!(events[2]["family"], "monitor");
assert_eq!(events[2]["class"], "lock");
assert_eq!(events[3]["family"], "monitor");
assert_eq!(events[3]["class"], "lock");
}
#[test]
fn a_handler_is_found_from_its_span_and_ends_at_its_processed_line() {
let dir = session("windows-flavor-handlers");
let answer = run(&["events", &dir, "--json"]);
let events = answer["data"]["events"].as_array().expect("events");
for index in [0, 1] {
let handler = &events[index]["handler"];
assert!(
handler.is_object(),
"event {index} has no handler: {}",
events[index]
);
assert_eq!(
handler["lines"], 2,
"the handler logged two lines: {handler}"
);
}
// the handler of the first did not swallow the second's lines
assert_ne!(
events[0]["handler"]["header_line"],
events[1]["handler"]["header_line"]
);
}
#[test]
fn the_state_is_read_by_window_handle_and_a_trace_says_what_moved() {
let dir = session("windows-flavor-trace");
let trace = run(&["trace", &dir, "event:2", "--json"]);
let changes = trace["data"]["changes"].as_array().expect("changes");
assert!(
changes.iter().any(|change| change["text"]
.as_str()
.is_some_and(|text| text.contains("131072"))),
"the move is described by the window's handle: {changes:#?}"
);
let state = run(&["state", &dir, "--at", "6", "--window", "chrome", "--json"]);
let windows = state["data"]["matches"].as_array().expect("matches");
assert_eq!(windows.len(), 1, "{state:#}");
assert_eq!(windows[0]["window"]["id"], 131_072);
}
#[test]
fn the_analysis_says_the_windows_rules_are_not_yet_checked_against_a_recording() {
let dir = session("windows-flavor-warning");
let answer = run(&["events", &dir, "--json"]);
let warnings = answer["warnings"].as_array().expect("warnings");
assert!(
warnings
.iter()
.any(|warning| warning
.as_str()
.is_some_and(|text| text.contains("komorebi for Windows")
&& text.contains("not yet checked"))),
"{warnings:?}"
);
}
#[test]
fn a_mac_session_does_not_get_that_warning() {
let (mac, _) = SessionBuilder::new("windows-flavor-mac-control")
.event(1.0, json!({"type": "Retile"}), None)
.build();
let answer = run(&["events", &mac.dir.display().to_string(), "--json"]);
let warnings = answer["warnings"].as_array().expect("warnings");
assert!(
warnings
.iter()
.all(|warning| !warning.as_str().unwrap_or("").contains("not yet checked")),
"{warnings:?}"
);
}