From 0d5527c1f85e4812cf73370458087fc7e2fb16d7 Mon Sep 17 00:00:00 2001 From: Austin Gregg-Smith Date: Sat, 21 Nov 2026 09:17:21 +0000 Subject: [PATCH 01/13] feat(events): append one JSON line per launch to an event log dl and dla now write ${XDG_STATE_HOME:-~/.local/state}/devlaunch/events.jsonl, always on, off with DEVLAUNCH_EVENTS=0. dl writes launch, session_end, stop, kill, remove and prune; dla adds aid_start (its own stages plus dl's launch) and aid_end. A write error is dropped and never fails the command. Core hands the launch over through a hook on timing::begin and a new timing::ready, so core still renders nothing. The public-API rows for timing::Ready, begin and ready are hand-written; CI's public-api job checks them. The Python suite now scopes XDG_STATE_HOME so a test run does not write into the developer's own log. --- CHANGELOG.md | 9 + README.md | 6 +- docs/performance.md | 37 ++ rust/devlaunch-core/public-api.rest.txt | 15 +- rust/devlaunch-core/src/flows/launch.rs | 9 + rust/devlaunch-core/src/timing.rs | 274 +++++++++++++-- rust/dl/src/commands.rs | 24 +- rust/dl/src/events.rs | 434 ++++++++++++++++++++++++ rust/dl/src/lib.rs | 7 +- rust/dl/tests/launch.rs | 106 ++++++ rust/dl/tests/lifecycle.rs | 11 + rust/dla/src/main.rs | 14 +- rust/dla/src/rewrite.rs | 5 + rust/dla/tests/rewrite.rs | 40 +++ test/conftest.py | 6 + 15 files changed, 963 insertions(+), 34 deletions(-) create mode 100644 rust/dl/src/events.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index ab6497cb..4aedd7ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **`dl` and `dla` keep an event log.** Each launch, session end, `stop`, `kill`, `rm` + and `prune` appends one JSON line to `$XDG_STATE_HOME/devlaunch/events.jsonl` + (`~/.local/state/devlaunch/events.jsonl` by default), with the start's seconds, + whether it was cold, and its stages. `dla` adds `aid_start` and `aid_end` lines. + `DEVLAUNCH_EVENTS=0` turns it off. A line that cannot be written never fails the + command. See [The event log](docs/performance.md#the-event-log). + ## [0.64.3] - 2026-11-18 ### Fixed diff --git a/README.md b/README.md index 1d1a7872..dfd8831a 100644 --- a/README.md +++ b/README.md @@ -566,14 +566,16 @@ Images are yours: `docker system df` is what shows those. | `NVIM_SPLIT=1` | In Herdr, open `$VISUAL`, then `$EDITOR`, or `nvim` in a vertical split beside an agent launched with `dla` or `dl`. Off by default. The agent pane keeps focus. Requires the pane shell installed by `dl --herdr-setup`. See [docs/workspace-tools.md](docs/workspace-tools.md) | | `HERDR_AGENT=` | Written, not read: a `dla` launch that starts an agent, or a `dl -- ` whose command is one, names it here so a session manager can see it. See [docs/workspace-tools.md](docs/workspace-tools.md) | | `DEVLAUNCH_TIMING=1\|json` | Write a timing summary to stderr. See [docs/performance.md](docs/performance.md) | +| `DEVLAUNCH_EVENTS=0` | Do not append to the event log, `$XDG_STATE_HOME/devlaunch/events.jsonl` (`~/.local/state` without it). On by default: one JSON line per launch, stop, kill, remove and prune. See [docs/performance.md](docs/performance.md#the-event-log) | | `DEVPOD_SSH_CONFIG=` | devpod's own, honoured rather than set: it is where `devpod up` publishes host aliases, so it is where `dl` looks for them. See [docs/cli.md](docs/cli.md) | | `CLAUDE_CONFIG_DIR=` | Claude Code's own, honoured rather than set: it is where the host keeps its Claude configuration, so it is where `dl` reads the login to forward. It replaces `~/.claude` rather than being tried before it, exactly as Claude Code treats it. See [docs/workspace-tools.md](docs/workspace-tools.md) | | `DEVLAUNCH_CLAUDE_PROFILES_DIR=` | Where `--claude-profile` looks, and it wins over the row below. For scoping a scratch run away from real credentials | | `CLAUDE_PROFILES_DIR=` | Honoured rather than set: the profile directory `claude-as` manages. Defaults to `~/.claude-profiles`. Nothing `dl` deletes reaches it | Every switch here reads the same values: anything but empty, `0`, `false` or `no` counts as -set. On a "no" variable that means turn it off; on an opt-in one it means turn it on. Eight -rows are not switches and do not follow it: `DEVLAUNCH_AID_AGENT`, `DEVPOD_SSH_CONFIG`, +set. On a "no" variable that means turn it off; on an opt-in one it means turn it on. Nine +rows are not switches and do not follow it: `DEVLAUNCH_EVENTS` is on unless it is `0`, +`false`, `no` or `off`, so an empty value keeps the log on, `DEVLAUNCH_AID_AGENT`, `DEVPOD_SSH_CONFIG`, `CLAUDE_CONFIG_DIR`, `DEVLAUNCH_CLAUDE_PROFILES_DIR` and `CLAUDE_PROFILES_DIR` take a value, `DEVLAUNCH_TIMING` counts only empty and `0` as off, so `false` and `no` turn it on, `DEVLAUNCH_AID_REMOTE_CONTROL` takes `1`/`true`/`on`/`yes` or `0`/`false`/`off`/`no` and refuses anything else rather than guessing, and `HERDR_AGENT` is diff --git a/docs/performance.md b/docs/performance.md index d90cec3b..0e30a999 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -176,6 +176,43 @@ dl-timing: devpod ssh 1.952s dl-timing: total 2.444s (in-process, excluding interpreter startup) ``` +### The event log + +`DEVLAUNCH_TIMING` answers a question asked before the launch. The event log +answers one asked afterwards: how long did starts take this week, and how many +were cold. Every `dl` and `dla` appends one JSON object per line to +`$XDG_STATE_HOME/devlaunch/events.jsonl`, or `~/.local/state/devlaunch/events.jsonl` +when `XDG_STATE_HOME` is unset. Nobody has to set anything first. +`DEVLAUNCH_EVENTS=0` turns it off. + +A line that cannot be written is dropped and the command goes on. A full disk or +a read-only state directory costs the log and nothing else. Each line is one +append, so two commands at once do not mix their lines. + +| `ev` | Written when | Fields beyond `ts`, `ev`, `ws`, `repo`, `branch` | +|---|---|---| +| `launch` | The workspace is ready and the session is about to start, or an `up` has finished | `cold`, `seconds`, `stages`, `verb` | +| `session_end` | The session a `launch` started has ended | `seconds` (of the session), `exit` | +| `stop`, `kill`, `remove`, `prune` | The verb has finished | `seconds`, `exit` | +| `aid_start` | `dla` has handed its start to `dl` and the workspace is ready | `cold`, `seconds`, `stages`, `agent`, `resume` | +| `aid_end` | `dla` has ended | `seconds`, `exit`, `agent` | + +`ts` is UTC ISO 8601 to the millisecond. `ws` is the workspace id when the launch +knew it, else the target as typed. `repo` and `branch` are set when the target +is `owner/repo@branch`. `cold` is true when the launch's `devpod up` created the +workspace. `seconds` on a `launch` is the wall time from the top of the command, +and `stages` holds the same named stages as the timing document, in seconds. On +an `aid_start`, `stages` holds `dla`'s own steps (`pick`, `pr_lookup`, `prompt`, +`boot_wait`) and `dl`, the launch inside it. The `aid` names are what `dla` was +called before, and what readers of older logs already look for. + +```json +{"ts":"2026-11-21T09:13:05.340Z","ev":"aid_start","ws":"devlaunch-main-3j1t","repo":"blooop/devlaunch","branch":"main","cold":false,"seconds":0.043923,"stages":{"pick":0.00007,"pr_lookup":0.00005,"prompt":1e-6,"dl":0.023009},"agent":"claude","resume":false} +``` + +A picked batch (`dl` with no target, then a verb) logs its launch but not its +`stop`, `kill` or `remove`. + ### The same launch, machine-readable `DEVLAUNCH_TIMING=json` swaps that prose for one document on a single diff --git a/rust/devlaunch-core/public-api.rest.txt b/rust/devlaunch-core/public-api.rest.txt index 8b8b815e..04c021e1 100644 --- a/rust/devlaunch-core/public-api.rest.txt +++ b/rust/devlaunch-core/public-api.rest.txt @@ -3560,5 +3560,18 @@ pub fn devlaunch_core::timing::Report::eq(&self, &devlaunch_core::timing::Report impl core::fmt::Debug for devlaunch_core::timing::Report pub fn devlaunch_core::timing::Report::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl core::marker::StructuralPartialEq for devlaunch_core::timing::Report -pub fn devlaunch_core::timing::begin() +pub struct devlaunch_core::timing::Ready +pub devlaunch_core::timing::Ready::cold: bool +pub devlaunch_core::timing::Ready::seconds: f64 +pub devlaunch_core::timing::Ready::stages: alloc::vec::Vec<(&'static str, f64)> +pub devlaunch_core::timing::Ready::workspace_id: core::option::Option +impl core::clone::Clone for devlaunch_core::timing::Ready +pub fn devlaunch_core::timing::Ready::clone(&self) -> devlaunch_core::timing::Ready +impl core::cmp::PartialEq for devlaunch_core::timing::Ready +pub fn devlaunch_core::timing::Ready::eq(&self, &devlaunch_core::timing::Ready) -> bool +impl core::fmt::Debug for devlaunch_core::timing::Ready +pub fn devlaunch_core::timing::Ready::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::marker::StructuralPartialEq for devlaunch_core::timing::Ready +pub fn devlaunch_core::timing::begin(core::option::Option) pub fn devlaunch_core::timing::emit() -> core::option::Option +pub fn devlaunch_core::timing::ready(core::option::Option<&str>) diff --git a/rust/devlaunch-core/src/flows/launch.rs b/rust/devlaunch-core/src/flows/launch.rs index e93b6ed8..821ba306 100644 --- a/rust/devlaunch-core/src/flows/launch.rs +++ b/rust/devlaunch-core/src/flows/launch.rs @@ -2203,6 +2203,12 @@ fn up_under_stage( // This launch is the one paying for the `up`, so no prewarm saved it from // anything — whether or not one was fired. timing::observe_attach(timing::AttachShape::Miss); + // A create is what the event log calls a cold launch: devpod did not list + // this workspace, so this `up` builds it rather than starting it. + timing::observe_up( + request.naming.identity(), + matches!(request.naming, Naming::Create { .. }), + ); // The build runs for minutes in the foreground; it leads a process group of // its own so a Ctrl-C (or `kill -INT `) tears the whole build down with // `dl` rather than orphaning it holding the launch lock. @@ -4189,6 +4195,9 @@ pub(crate) fn attach_workspace( forward: &mut dyn FnMut(&str), notices: &mut dyn Notices, ) -> Result { + // Ready before the attach stage opens: what follows is the session, which + // lasts as long as somebody works in it and is no part of the start. + timing::ready(Some(workspace_id)); timing::stage_result(timing::Stage::Attach, || { // First, and unconditionally on the way to every session: the terminal is // about to belong to something else, and after that this process may not diff --git a/rust/devlaunch-core/src/timing.rs b/rust/devlaunch-core/src/timing.rs index fcfbfa45..938b7054 100644 --- a/rust/devlaunch-core/src/timing.rs +++ b/rust/devlaunch-core/src/timing.rs @@ -326,7 +326,9 @@ pub(crate) enum Entry { /// rather than a flag inside it that other fields would have to agree with. #[derive(Debug)] pub(crate) struct Registry { - mode: Mode, + /// `None` when nobody asked for the stderr report and the registry exists + /// only so the [`Ready`] snapshot has stages to carry. + mode: Option, started: Instant, entries: Vec, /// Insertion-ordered, which is the order the document reports: a reader @@ -335,6 +337,16 @@ pub(crate) struct Registry { open: Vec, seam: Seam, attach_shape: Option, + /// Whether this launch ran a `devpod up` that created the workspace. + created: bool, + /// The workspace that `up` was for, so a [`ready`] whose caller names none + /// can still say which one it was. + upped: Option, + /// Who hears about [`ready`], if anyone does. + on_ready: Option, + /// Whether [`ready`] has already been heard this command: a launch is ready + /// once, however many arms call it. + readied: bool, } impl Registry { @@ -348,7 +360,10 @@ impl Registry { /// A handoff stage needs the keystroke stamp *and* a non-negative gap from /// it; a stamp ahead of this clock describes two clocks that disagree, not a /// handoff that took negative time. - pub(crate) fn start(mode: Mode, seam: Seam, now_epoch: f64) -> Self { + /// + /// `mode` is `None` for a run that wants no stderr report, only the stages + /// a [`Ready`] carries. + pub(crate) fn starting(mode: Option, seam: Seam, now_epoch: f64) -> Self { let mut registry = Self { mode, started: Instant::now(), @@ -357,6 +372,10 @@ impl Registry { open: Vec::new(), seam, attach_shape: None, + created: false, + upped: None, + on_ready: None, + readied: false, }; if let Some(gap) = seam .keystroke @@ -456,10 +475,59 @@ impl Registry { self.attach_shape = Some(shape); } - /// The run's report. Consuming, because nothing records after it. - pub(crate) fn finish(self) -> Report { + /// [`Registry::starting`] with a report asked for: what the tests drive. + #[cfg(test)] + pub(crate) fn start(mode: Mode, seam: Seam, now_epoch: f64) -> Self { + Self::starting(Some(mode), seam, now_epoch) + } + + /// Record the workspace this launch's `devpod up` is for, and whether that + /// `up` creates it. + pub(crate) fn observe_up(&mut self, workspace_id: Option<&str>, created: bool) { + self.upped = workspace_id.map(str::to_owned); + self.created = created; + } + + /// The launch as it stands now, the first time it is asked; `None` after. + /// + /// A stage still on the clock is charged up to this instant, so a snapshot + /// taken inside an arm reports what that arm has cost so far. + pub(crate) fn ready(&mut self, workspace_id: Option<&str>) -> Option { + if self.readied { + return None; + } + self.readied = true; + let now = Instant::now(); + let running = self.open.last().map(|open| (open.stage, open.since)); + let stages = self + .stages + .iter() + .enumerate() + .map(|(index, record)| { + let mut seconds = record.seconds; + if let Some((stage, since)) = running + && stage == index + { + seconds += now.saturating_duration_since(since); + } + (record.stage.name(), round6(seconds)) + }) + .collect(); + Some(Ready { + workspace_id: workspace_id + .map(str::to_owned) + .or_else(|| self.upped.clone()), + seconds: round6(now.saturating_duration_since(self.started)), + cold: self.created, + stages, + }) + } + + /// The run's report, or `None` when nobody asked for one. Consuming, + /// because nothing records after it. + pub(crate) fn finish(self) -> Option { let total = self.started.elapsed(); - match self.mode { + Some(match self.mode? { Mode::Prose => Report::Prose(Prose { spans: self.entries, total, @@ -486,7 +554,7 @@ impl Registry { .collect(), prewarm: self.prewarm().as_ref().map(PrewarmReport::from), }), - } + }) } /// What this launch can say about the prewarm that preceded it. @@ -548,6 +616,24 @@ enum Prewarm { }, } +/// The moment a launch hands its workspace over, as [`ready`] sees it. +/// +/// Data for the binary's event log, and nothing here writes it: core renders no +/// output (#251), so the binary installs a hook at [`begin`] and decides what to +/// do with this. +#[derive(Debug, Clone, PartialEq)] +pub struct Ready { + /// The workspace handed over, when the caller of [`ready`] knew it. + pub workspace_id: Option, + /// Seconds from [`begin`] to this moment. + pub seconds: f64, + /// Whether this launch's `devpod up` created the workspace, rather than + /// finding it or starting one devpod already knew. + pub cold: bool, + /// Each [`Stage`] this launch met, by name, with its seconds so far. + pub stages: Vec<(&'static str, f64)>, +} + /// A run's report: the bytes the binary writes, and the data behind them. #[derive(Debug, Clone, PartialEq)] pub enum Report { @@ -744,13 +830,26 @@ fn with_registry(with: impl FnOnce(&mut Registry) -> T) -> Option { registry().as_mut().map(with) } -/// Start recording iff `DEVLAUNCH_TIMING` asks for it. +/// Start recording if `DEVLAUNCH_TIMING` asks for it, or if `on_ready` is +/// given. /// /// Called once at the top of the command, replacing any registry left from an /// earlier one in the same process, so one command's spans never leak into the /// next command's summary. -pub fn begin() { - install(Mode::from_env().map(|mode| Registry::start(mode, Seam::from_env(), now_epoch()))); +/// +/// `on_ready` is the binary's event log. With it, the stages are recorded even +/// when no stderr report was asked for, so [`Ready`] can carry them; [`emit`] +/// still answers `None` then. That costs a mutex and a push per span, beside a +/// subprocess spawn. Without it and without the variable, nothing records. +pub fn begin(on_ready: Option) { + let mode = Mode::from_env(); + if mode.is_none() && on_ready.is_none() { + install(None); + return; + } + let mut registry = Registry::starting(mode, Seam::from_env(), now_epoch()); + registry.on_ready = on_ready; + install(Some(registry)); } /// Install `registry` as the process's, replacing whatever was there. @@ -766,7 +865,30 @@ pub(crate) fn install(registry_to_install: Option) { /// The report for this run, and stop recording; `None` if recording never began. pub fn emit() -> Option { RECORDING.store(false, Ordering::Relaxed); - registry().take().map(Registry::finish) + registry().take().and_then(Registry::finish) +} + +/// Say the workspace is ready, and tell the hook [`begin`] was given. +/// +/// The first call in a command is heard; later ones are not, so an arm that +/// calls it and a caller that calls it again after the arm do not count one +/// launch twice. The hook runs after the registry is released, so it may read +/// the clock but must not wait on anything. +pub fn ready(workspace_id: Option<&str>) { + let heard = with_registry(|registry| { + let hook = registry.on_ready?; + registry.ready(workspace_id).map(|ready| (hook, ready)) + }) + .flatten(); + if let Some((hook, ready)) = heard { + hook(&ready); + } +} + +/// Record the workspace this launch's `devpod up` is for, and whether it +/// creates it, for [`Ready`]. +pub(crate) fn observe_up(workspace_id: Option<&str>, created: bool) { + with_registry(|registry| registry.observe_up(workspace_id, created)); } /// Record a measurement somebody else took, under `label`. @@ -972,7 +1094,7 @@ mod tests { const TICK: Duration = Duration::from_millis(30); fn document_of(registry: Registry) -> Document { - match registry.finish() { + match registry.finish().expect("a mode was asked for") { Report::Document(document) => document, Report::Prose(prose) => panic!("asked for a document, got {prose:?}"), } @@ -1035,7 +1157,7 @@ mod tests { registry.record("devpod status", Duration::from_millis(454)); registry.record("devpod ssh", Duration::from_millis(1952)); - let lines = registry.finish().lines(); + let lines = registry.finish().expect("a mode was asked for").lines(); assert_eq!(lines[0], "dl-timing: devpod status 0.454s"); assert_eq!(lines[1], "dl-timing: devpod ssh 1.952s"); @@ -1052,6 +1174,7 @@ mod tests { fn a_run_that_recorded_nothing_still_reports_its_total() { let lines = Registry::start(Mode::Prose, Seam::default(), now_epoch()) .finish() + .expect("a mode was asked for") .lines(); assert_eq!(lines.len(), 1); @@ -1060,13 +1183,15 @@ mod tests { #[test] fn the_prose_summary_carries_no_document_and_the_document_no_prose() { - let prose = Registry::start(Mode::Prose, Seam::default(), now_epoch()).finish(); + let prose = Registry::start(Mode::Prose, Seam::default(), now_epoch()) + .finish() + .expect("a mode was asked for"); assert!(prose.document().is_none()); for line in prose.lines() { assert!(!line.contains(JSON_PREFIX), "{line:?}"); } - let document = recording().finish(); + let document = recording().finish().expect("a mode was asked for"); assert_eq!(document.lines().len(), 1); assert!(document.lines()[0].starts_with(JSON_PREFIX)); assert!(!document.lines()[0].contains("dl-timing: ")); @@ -1081,7 +1206,7 @@ mod tests { registry.record("devpod ssh", Duration::from_millis(500)); registry.leave(Stage::Tools, Outcome::Ok); - let lines = registry.finish().lines(); + let lines = registry.finish().expect("a mode was asked for").lines(); assert_eq!(lines.len(), 2); assert_eq!(lines[0], "dl-timing: devpod ssh 0.500s"); @@ -1092,7 +1217,11 @@ mod tests { #[test] fn the_document_is_one_marked_line_of_parseable_json() { - let line = recording().finish().lines().remove(0); + let line = recording() + .finish() + .expect("a mode was asked for") + .lines() + .remove(0); let json = line .strip_prefix(&format!("{JSON_PREFIX} ")) @@ -1113,7 +1242,11 @@ mod tests { registry.enter(Stage::Tools); registry.record("devpod ssh", Duration::from_millis(500)); registry.leave(Stage::Tools, Outcome::Ok); - let line = registry.finish().lines().remove(0); + let line = registry + .finish() + .expect("a mode was asked for") + .lines() + .remove(0); let json = line .strip_prefix(&format!("{JSON_PREFIX} ")) @@ -1145,7 +1278,11 @@ mod tests { #[test] fn a_document_with_no_prewarm_omits_the_key_rather_than_emptying_it() { - let line = recording().finish().lines().remove(0); + let line = recording() + .finish() + .expect("a mode was asked for") + .lines() + .remove(0); assert!(!line.contains("prewarm"), "{line:?}"); } @@ -1568,7 +1705,10 @@ mod tests { prewarm_fired: Some(now - 35.0), }; - let lines = Registry::start(Mode::Prose, seam, now).finish().lines(); + let lines = Registry::start(Mode::Prose, seam, now) + .finish() + .expect("a mode was asked for") + .lines(); assert_eq!(lines.len(), 1); assert!(lines[0].starts_with("dl-timing: total "), "{:?}", lines[0]); @@ -1687,7 +1827,11 @@ mod tests { let mut registry = prewarmed(Some(now - 5.0), Some(now - 35.0), now); registry.observe_attach(AttachShape::Hit); - let line = registry.finish().lines().remove(0); + let line = registry + .finish() + .expect("a mode was asked for") + .lines() + .remove(0); let json = line .strip_prefix(&format!("{JSON_PREFIX} ")) @@ -1919,7 +2063,7 @@ mod tests { // with each other about it. The rules themselves are pinned above, on // `Mode::requested` and `Seam::parse`. global(|| { - begin(); + begin(None); let asked = Mode::from_env(); let report = emit(); @@ -1933,4 +2077,92 @@ mod tests { } }); } + + // --- the ready snapshot: what the event log is handed ------------------ + + #[test] + fn ready_carries_the_stages_so_far_the_workspace_and_whether_it_was_created() { + let mut registry = Registry::starting(None, Seam::default(), now_epoch()); + registry.enter(Stage::HostPrep); + std::thread::sleep(TICK); + registry.leave(Stage::HostPrep, Outcome::Ok); + registry.enter(Stage::DevpodUp); + registry.observe_up(Some("repo-main"), true); + std::thread::sleep(TICK); + + let ready = registry.ready(None).expect("the first ask"); + + assert_eq!( + ready.workspace_id.as_deref(), + Some("repo-main"), + "named by the `up` when the caller names nothing" + ); + assert!(ready.cold, "the `up` created it"); + let names: Vec<&str> = ready.stages.iter().map(|(name, _)| *name).collect(); + assert_eq!(names, ["host-prep", "devpod-up"]); + // The stage still on the clock is charged up to the snapshot, not + // reported as the zero it was when it opened. + for (name, seconds) in &ready.stages { + assert!(*seconds >= TICK.as_secs_f64(), "{name}: {seconds}"); + } + assert!(ready.seconds >= 2.0 * TICK.as_secs_f64(), "{ready:?}"); + } + + #[test] + fn a_launch_is_ready_once_and_warm_unless_an_up_created_it() { + let mut registry = Registry::starting(None, Seam::default(), now_epoch()); + + let first = registry.ready(None).expect("the first ask"); + assert!(!first.cold); + assert!(first.stages.is_empty()); + assert_eq!(registry.ready(Some("again")), None); + } + + #[test] + fn a_registry_nobody_asked_a_report_of_reports_nothing() { + let registry = Registry::starting(None, Seam::default(), now_epoch()); + + assert_eq!(registry.finish(), None); + } + + static HEARD: Mutex> = Mutex::new(Vec::new()); + + fn hear(ready: &Ready) { + HEARD + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(ready.clone()); + } + + #[test] + fn the_hook_hears_ready_once_and_emit_still_reports_only_what_was_asked() { + global(|| { + HEARD.lock().unwrap_or_else(PoisonError::into_inner).clear(); + let mut registry = Registry::starting(None, Seam::default(), now_epoch()); + registry.on_ready = Some(hear); + install(Some(registry)); + + { + let _stage = stage(Stage::Tools); + let _span = span("tools tar"); + } + ready(Some("ws")); + ready(Some("ws")); + + assert_eq!(emit(), None, "no DEVLAUNCH_TIMING, so no report"); + let heard = std::mem::take(&mut *HEARD.lock().unwrap_or_else(PoisonError::into_inner)); + assert_eq!(heard.len(), 1, "{heard:?}"); + assert_eq!(heard[0].workspace_id.as_deref(), Some("ws")); + assert_eq!(heard[0].stages.len(), 1); + assert_eq!(heard[0].stages[0].0, "tools"); + }); + } + + #[test] + fn ready_with_nothing_installed_is_silent() { + global(|| { + ready(Some("ws")); + assert_eq!(emit(), None); + }); + } } diff --git a/rust/dl/src/commands.rs b/rust/dl/src/commands.rs index 019aecfc..479f0540 100644 --- a/rust/dl/src/commands.rs +++ b/rust/dl/src/commands.rs @@ -134,13 +134,16 @@ pub(crate) fn dispatch( yes, force, force_worktrees, - } => render_prune( - runner, - &mut context, - cache, - yes, - insisted(force, force_worktrees), - ), + } => { + crate::events::workspace(None, "prune"); + render_prune( + runner, + &mut context, + cache, + yes, + insisted(force, force_worktrees), + ) + } Command::Reconcile { yes } => render_reconcile(runner, &mut context, refresh, yes), Command::Purge { yes } => render_purge(&mut context, cache, yes), Command::RefreshStale => render_refresh_stale(runner, &mut context, cache, refresh), @@ -240,6 +243,7 @@ pub(crate) fn dispatch( } let after = verb.after_removal(); let word = verb.word(); + crate::events::workspace(Some(&target), word); let ending = render_workspace( runner, &mut context, @@ -254,6 +258,12 @@ pub(crate) fn dispatch( None, resume, ); + // An `up` starts no session, so its launch is ready when it has + // finished, and only if it worked. `timing::ready` fires once, so an + // `up` that reached a ready point of its own is not counted twice. + if word == "up" && ending.code() == 0 { + devlaunch_core::timing::ready(None); + } hangup::after_the_command(after, word, ending) } } diff --git a/rust/dl/src/events.rs b/rust/dl/src/events.rs new file mode 100644 index 00000000..8d82e743 --- /dev/null +++ b/rust/dl/src/events.rs @@ -0,0 +1,434 @@ +//! The event log: one JSON object per line, appended to +//! `${XDG_STATE_HOME:-~/.local/state}/devlaunch/events.jsonl`, so a usage review +//! can measure how long a start takes without anybody having set +//! `DEVLAUNCH_TIMING` in advance. +//! +//! Always on. `DEVLAUNCH_EVENTS=0` turns it off. What is written: +//! +//! - `launch`: the workspace is ready, written the moment the session is about +//! to start (or the `up` has finished). `seconds` is the wall time from the +//! top of the command, `cold` says the `up` created the workspace, and +//! `stages` holds the named [`timing`] stages in seconds. +//! - `session_end`: the session a `launch` started has ended. `seconds` is how +//! long it lasted and `exit` is how it ended. +//! - `stop`, `kill`, `remove`, `prune`: the verb ran; `seconds` is how long it took. +//! - `aid_start` and `aid_end`: the same two moments for `dla`, which runs dl in +//! process. `aid` is dla's name from before it was dla, and the name the +//! readers of this file already filter on. +//! +//! **Writing it never fails a command.** Every I/O error is dropped where it +//! happens: a log that cannot be written costs the log and nothing else. Each +//! line goes in one `write` on a file opened for append, so two `dl` processes +//! writing at once do not interleave inside a line. +//! +//! The file is the binary's, not core's. Core renders no output (#251) and hands +//! the stages over as a [`timing::Ready`] through the hook [`timing::begin`] +//! takes; this module is that hook. + +use std::io::Write as _; +use std::path::PathBuf; +use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use devlaunch_core::domain::spec::{self, WorkspaceSpec}; +use devlaunch_core::timing; +use serde_json::{Map, Value, json}; + +/// The switch. Unset, or anything but an off word, keeps the log on. +pub const ENV_VAR: &str = "DEVLAUNCH_EVENTS"; + +/// Whether `raw`, the value of [`ENV_VAR`], leaves the log on. +pub(crate) fn wanted(raw: Option<&str>) -> bool { + let value = raw.unwrap_or("").trim().to_ascii_lowercase(); + !matches!(value.as_str(), "0" | "false" | "no" | "off") +} + +/// The hook for [`timing::begin`]: `Some` unless the log is switched off. +pub(crate) fn hook() -> Option { + wanted(devlaunch_core::osext::env_str(ENV_VAR).as_deref()) + .then_some(on_ready as fn(&timing::Ready)) +} + +/// The log file: `$XDG_STATE_HOME/devlaunch/events.jsonl`, or the +/// `~/.local/state` the XDG spec falls back to. `None` with neither. +pub(crate) fn path() -> Option { + let state = devlaunch_core::osext::env_str("XDG_STATE_HOME") + .map(PathBuf::from) + // The spec says a relative value is invalid and is to be ignored. + .filter(|path| path.is_absolute()) + .or_else(|| devlaunch_core::osext::home_dir().map(|home| home.join(".local/state")))?; + Some(state.join("devlaunch").join("events.jsonl")) +} + +// --- what one command has seen ----------------------------------------------- + +/// The workspace verb this command runs, as the dispatch saw it. +#[derive(Debug, Clone)] +struct Verb { + word: &'static str, + target: Option, + started: Instant, +} + +/// When the launch was ready, and which workspace it was. +#[derive(Debug, Clone)] +struct Readied { + at: Instant, + workspace_id: Option, + target: Option, +} + +/// What `dla` knows that dl does not: when it started, what its own steps cost, +/// and which agent it starts. +#[derive(Debug, Clone)] +struct Dla { + started: Instant, + stages: Vec<(&'static str, f64)>, + agent: Option, + resume: bool, + workspace_id: Option, + target: Option, +} + +#[derive(Debug, Default)] +struct Seen { + verb: Option, + readied: Option, + dla: Option, +} + +static SEEN: Mutex = Mutex::new(Seen { + verb: None, + readied: None, + dla: None, +}); + +fn seen() -> MutexGuard<'static, Seen> { + SEEN.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// A new command: forget the last one's verb and readiness. dla's half stays, +/// because dla sets it before the command it hands to dl begins. +pub(crate) fn begin() { + let mut seen = seen(); + seen.verb = None; + seen.readied = None; +} + +/// The workspace verb this command runs, and the target it names (`prune` +/// names none). +pub(crate) fn workspace(target: Option<&str>, word: &'static str) { + seen().verb = Some(Verb { + word, + target: target.map(str::to_owned), + started: Instant::now(), + }); +} + +/// The command ended with `exit`. Write what its verb ended. +pub(crate) fn end(exit: i32) { + if !wanted(devlaunch_core::osext::env_str(ENV_VAR).as_deref()) { + return; + } + let (verb, readied) = { + let seen = seen(); + (seen.verb.clone(), seen.readied.clone()) + }; + let lifecycle = verb.as_ref().and_then(|verb| match verb.word { + "stop" => Some("stop"), + "kill" => Some("kill"), + "rm" | "rme" => Some("remove"), + "prune" => Some("prune"), + _ => None, + }); + if let (Some(ev), Some(verb)) = (lifecycle, &verb) { + let mut event = base(ev, verb.target.as_deref(), None); + event.insert("seconds".into(), seconds(verb.started.elapsed())); + event.insert("exit".into(), exit.into()); + append(&Value::Object(event)); + return; + } + // An `up` is ready when it ends; there is no session after it. + let upped = verb.as_ref().is_some_and(|verb| verb.word == "up"); + if let Some(readied) = readied.filter(|_| !upped) { + let mut event = base( + "session_end", + readied.target.as_deref(), + readied.workspace_id.as_deref(), + ); + event.insert("seconds".into(), seconds(readied.at.elapsed())); + event.insert("exit".into(), exit.into()); + append(&Value::Object(event)); + } +} + +/// [`timing::begin`]'s hook: the launch is ready. +fn on_ready(ready: &timing::Ready) { + let now = Instant::now(); + let (target, dla) = { + let mut seen = seen(); + let target = seen.verb.as_ref().and_then(|verb| verb.target.clone()); + seen.readied = Some(Readied { + at: now, + workspace_id: ready.workspace_id.clone(), + target: target.clone(), + }); + if let Some(dla) = seen.dla.as_mut() { + dla.workspace_id = ready.workspace_id.clone(); + dla.target.clone_from(&target); + } + (target, seen.dla.clone()) + }; + let verb = { + let seen = seen(); + seen.verb.as_ref().map(|verb| verb.word) + }; + append(&launch_event(ready, target.as_deref(), verb)); + if let Some(dla) = dla { + append(&aid_start_event(&dla, ready, target.as_deref(), now)); + } +} + +/// The `launch` line for `ready`. +fn launch_event(ready: &timing::Ready, target: Option<&str>, verb: Option<&str>) -> Value { + let mut event = base("launch", target, ready.workspace_id.as_deref()); + event.insert("cold".into(), ready.cold.into()); + event.insert("seconds".into(), ready.seconds.into()); + event.insert("stages".into(), stages(&ready.stages)); + if let Some(verb) = verb { + event.insert("verb".into(), verb.into()); + } + Value::Object(event) +} + +/// The `aid_start` line: dla's own steps, then dl's launch as one more stage. +fn aid_start_event(dla: &Dla, ready: &timing::Ready, target: Option<&str>, now: Instant) -> Value { + let mut event = base( + "aid_start", + target.or(dla.target.as_deref()), + ready.workspace_id.as_deref(), + ); + let mut steps = dla.stages.clone(); + steps.push(("dl", ready.seconds)); + event.insert("cold".into(), ready.cold.into()); + event.insert( + "seconds".into(), + seconds(now.saturating_duration_since(dla.started)), + ); + event.insert("stages".into(), stages(&steps)); + event.insert("agent".into(), dla.agent.clone().into()); + event.insert("resume".into(), dla.resume.into()); + Value::Object(event) +} + +// --- dla's half --------------------------------------------------------------- + +/// dla's view of one start, which it fills in before it hands the line to dl. +/// +/// `dla` calls [`DlaStart::begin`] at its top, [`DlaStart::stage`] after each of +/// its own steps, and [`DlaStart::hand_over`] just before `dl::run`. The `aid_start` +/// line is written when dl's launch is ready, and [`dla_end`] writes `aid_end`. +#[derive(Debug)] +pub struct DlaStart { + started: Instant, + last: Instant, + stages: Vec<(&'static str, f64)>, +} + +impl DlaStart { + /// The clock starts now. + pub fn begin() -> Self { + let now = Instant::now(); + Self { + started: now, + last: now, + stages: Vec::new(), + } + } + + /// Charge the time since the last stage (or the start) to `name`. + pub fn stage(&mut self, name: &'static str) { + let now = Instant::now(); + let took = now.saturating_duration_since(self.last); + self.last = now; + self.stages.push((name, round(took.as_secs_f64()))); + } + + /// Hand the start to dl, with the agent it starts and whether it resumes one. + pub fn hand_over(self, agent: Option<&str>, resume: bool) { + seen().dla = Some(Dla { + started: self.started, + stages: self.stages, + agent: agent.map(str::to_owned), + resume, + workspace_id: None, + target: None, + }); + } +} + +/// dla ended with `exit`: write `aid_end`, if dla handed a start over. +pub fn dla_end(exit: i32) { + let Some(dla) = seen().dla.take() else { + return; + }; + if !wanted(devlaunch_core::osext::env_str(ENV_VAR).as_deref()) { + return; + } + let mut event = base( + "aid_end", + dla.target.as_deref(), + dla.workspace_id.as_deref(), + ); + event.insert("seconds".into(), seconds(dla.started.elapsed())); + event.insert("exit".into(), exit.into()); + event.insert("agent".into(), dla.agent.into()); + append(&Value::Object(event)); +} + +// --- one line --------------------------------------------------------------- + +/// The fields every line has: when, what, and which workspace. +/// +/// `ws` is the workspace id when the launch knew it, else the target as typed. +/// `repo` and `branch` come from the target when it is `owner/repo[@branch]`. +fn base(ev: &str, target: Option<&str>, workspace_id: Option<&str>) -> Map { + let (repo, branch) = match target.map(spec::parse) { + Some(WorkspaceSpec::OwnerRepo { + owner, + repo, + branch, + }) => (Some(format!("{owner}/{repo}")), branch.map(str::to_owned)), + _ => (None, None), + }; + let mut event = Map::new(); + event.insert("ts".into(), iso8601(SystemTime::now()).into()); + event.insert("ev".into(), ev.into()); + event.insert("ws".into(), workspace_id.or(target).into()); + event.insert("repo".into(), repo.into()); + event.insert("branch".into(), branch.into()); + event +} + +fn stages(stages: &[(&str, f64)]) -> Value { + Value::Object( + stages + .iter() + .map(|(name, seconds)| ((*name).to_owned(), json!(seconds))) + .collect(), + ) +} + +fn seconds(took: Duration) -> Value { + round(took.as_secs_f64()).into() +} + +/// Seconds to the microsecond, as the timing document reports them. +fn round(seconds: f64) -> f64 { + (seconds * 1e6).round() / 1e6 +} + +/// Append `event` as one line. Every error is dropped: see the module docs. +fn append(event: &Value) { + let Some(path) = path() else { return }; + let Ok(mut line) = serde_json::to_string(event) else { + return; + }; + line.push('\n'); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + else { + return; + }; + let _ = file.write_all(line.as_bytes()); +} + +/// `at` as ISO-8601 in UTC, to the millisecond: `2026-11-21T09:30:00.123Z`. +pub(crate) fn iso8601(at: SystemTime) -> String { + let since = at.duration_since(UNIX_EPOCH).unwrap_or_default(); + let secs = since.as_secs(); + let (year, month, day) = civil_from_days((secs / 86_400) as i64); + let of_day = secs % 86_400; + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z", + of_day / 3600, + of_day % 3600 / 60, + of_day % 60, + since.subsec_millis() + ) +} + +/// The proleptic Gregorian date `days` after 1970-01-01, by Howard Hinnant's +/// `civil_from_days`. +fn civil_from_days(days: i64) -> (i64, u32, u32) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = (doy - (153 * mp + 2) / 5 + 1) as u32; + let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + let year = yoe + era * 400 + i64::from(month <= 2); + (year, month, day) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_log_is_on_unless_switched_off() { + assert!(wanted(None)); + assert!(wanted(Some(""))); + assert!(wanted(Some("1"))); + for off in ["0", "false", "no", "off", " OFF "] { + assert!(!wanted(Some(off)), "{off:?}"); + } + } + + #[test] + fn a_timestamp_is_iso_8601_utc() { + assert_eq!(iso8601(UNIX_EPOCH), "1970-01-01T00:00:00.000Z"); + // 2026-11-21T09:30:05.250Z, a date past a leap day and a month end. + let at = UNIX_EPOCH + Duration::from_millis(1_795_253_405_250); + assert_eq!(iso8601(at), "2026-11-21T09:30:05.250Z"); + let leap = UNIX_EPOCH + Duration::from_secs(951_782_400); + assert_eq!(iso8601(leap), "2000-02-29T00:00:00.000Z"); + } + + #[test] + fn a_launch_line_carries_the_triple_the_stages_and_whether_it_was_cold() { + let ready = timing::Ready { + workspace_id: Some("repo-main".to_owned()), + seconds: 4.5, + cold: true, + stages: vec![("host-prep", 1.25), ("devpod-up", 3.0)], + }; + + let line = launch_event(&ready, Some("owner/repo@main"), Some("attach")); + + assert_eq!(line["ev"], "launch"); + assert_eq!(line["ws"], "repo-main"); + assert_eq!(line["repo"], "owner/repo"); + assert_eq!(line["branch"], "main"); + assert_eq!(line["cold"], true); + assert_eq!(line["seconds"], 4.5); + assert_eq!(line["stages"], json!({"host-prep": 1.25, "devpod-up": 3.0})); + assert_eq!(line["verb"], "attach"); + } + + #[test] + fn a_bare_workspace_name_is_the_ws_and_names_no_repo() { + let line = base("stop", Some("repo-main"), None); + + assert_eq!(line["ws"], "repo-main"); + assert_eq!(line["repo"], Value::Null); + assert_eq!(line["branch"], Value::Null); + } +} diff --git a/rust/dl/src/lib.rs b/rust/dl/src/lib.rs index b93722cc..77726a7c 100644 --- a/rust/dl/src/lib.rs +++ b/rust/dl/src/lib.rs @@ -25,6 +25,7 @@ mod cli; mod commands; +pub mod events; mod hangup; mod herdr_editor; mod herdr_environment; @@ -587,9 +588,13 @@ pub fn run_resumable(argv: &[String], resume: AgentResume) -> i32 { fn run_with(argv: &[String], resume: Option) -> i32 { // Timing is per-command: begin() here so a second run in the same process // starts a fresh summary, and the report is written however the command ended. - timing::begin(); + // The event log rides the same clock: its hook writes the `launch` line when + // the workspace is ready, and `events::end` writes what the command ended. + timing::begin(events::hook()); + events::begin(); let ending = one_command(argv, resume); report_timing(); + events::end(ending); ending } diff --git a/rust/dl/tests/launch.rs b/rust/dl/tests/launch.rs index bd0dfe05..b6880ffb 100644 --- a/rust/dl/tests/launch.rs +++ b/rust/dl/tests/launch.rs @@ -2778,3 +2778,109 @@ fn a_removal_names_a_damaged_record_once_and_drops_devpods_warning_from_the_dele run.err ); } + +// =========================================================================== +// The event log: one JSON line per launch, under XDG_STATE_HOME +// =========================================================================== + +/// The lines of the event log under `state`, the world's XDG state directory. +fn events_under(state: &Path) -> Vec { + let path = state.join("devlaunch/events.jsonl"); + let Ok(text) = std::fs::read_to_string(&path) else { + return Vec::new(); + }; + text.lines() + .map(|line| serde_json::from_str(line).expect("each line is one JSON object")) + .collect() +} + +/// The event log at the XDG default, `~/.local/state`, with `HOME` the world's. +fn events(world: &World) -> Vec { + events_under(&world.path("home/.local/state")) +} + +#[test] +fn a_warm_attach_logs_a_warm_launch_and_then_the_end_of_its_session() { + let world = World::with(&["--warm"]); + world.dl(&["blooop/devlaunch@main"]).exited(0); + + let lines = events(&world); + let names: Vec<&str> = lines + .iter() + .map(|line| line["ev"].as_str().unwrap()) + .collect(); + assert_eq!(names, ["launch", "session_end"]); + let launch = &lines[0]; + assert_eq!(launch["ws"], MAIN); + assert_eq!(launch["repo"], "blooop/devlaunch"); + assert_eq!(launch["branch"], "main"); + assert_eq!(launch["cold"], false); + assert!( + launch["seconds"].as_f64().is_some_and(|s| s >= 0.0), + "{launch}" + ); + assert!(launch["stages"].is_object(), "{launch}"); + let ts = launch["ts"].as_str().expect("a timestamp"); + assert!( + ts.ends_with('Z') && ts.len() == "2026-11-21T09:30:05.250Z".len(), + "{ts}" + ); + assert_eq!(lines[1]["ws"], MAIN); + assert_eq!(lines[1]["exit"], 0); +} + +#[test] +fn a_cold_launch_is_logged_as_cold() { + let world = World::with(&[]); + world.dl(&["blooop/devlaunch@cold"]).exited(0); + + let lines = events(&world); + let launch = lines + .iter() + .find(|line| line["ev"] == "launch") + .expect("a launch line"); + assert_eq!(launch["ws"], COLD); + assert_eq!(launch["cold"], true); + assert!( + launch["stages"] + .as_object() + .is_some_and(|stages| !stages.is_empty()), + "a cold launch has stages: {launch}" + ); +} + +#[test] +fn an_up_logs_one_launch_and_no_session() { + let world = World::with(&["--stopped"]); + world.dl(&[MAIN, "up"]).exited(0); + + let lines = events(&world); + let names: Vec<&str> = lines + .iter() + .map(|line| line["ev"].as_str().unwrap()) + .collect(); + assert_eq!(names, ["launch"]); + assert_eq!(lines[0]["verb"], "up"); +} + +#[test] +fn the_event_log_follows_xdg_state_home() { + let world = World::with(&["--warm"]); + let state = world.path("state"); + world + .dl_with(&[MAIN], &[("XDG_STATE_HOME", &state.display().to_string())]) + .exited(0); + + assert_eq!(events_under(&state).len(), 2); + assert!(events(&world).is_empty(), "nothing under ~/.local/state"); +} + +#[test] +fn devlaunch_events_off_writes_no_log() { + let world = World::with(&["--warm"]); + world + .dl_with(&[MAIN], &[("DEVLAUNCH_EVENTS", "0")]) + .exited(0); + + assert!(!world.path("home/.local/state/devlaunch").exists()); +} diff --git a/rust/dl/tests/lifecycle.rs b/rust/dl/tests/lifecycle.rs index 166a477b..cb4aa7a5 100644 --- a/rust/dl/tests/lifecycle.rs +++ b/rust/dl/tests/lifecycle.rs @@ -834,6 +834,17 @@ fn a_stop_addresses_the_workspace_and_says_nothing() { "devpod stop someones-project", ] ); + // The event log has the stop, and how it ended. + let log = std::fs::read_to_string(world.root.join("home/.local/state/devlaunch/events.jsonl")) + .expect("the stop is logged"); + let lines: Vec = log + .lines() + .map(|line| serde_json::from_str(line).expect("one JSON object")) + .collect(); + assert_eq!(lines.len(), 1, "{log}"); + assert_eq!(lines[0]["ev"], "stop"); + assert_eq!(lines[0]["ws"], "someones-project"); + assert_eq!(lines[0]["exit"], 0); } #[test] diff --git a/rust/dla/src/main.rs b/rust/dla/src/main.rs index 4e7dadd4..39d84cc1 100644 --- a/rust/dla/src/main.rs +++ b/rust/dla/src/main.rs @@ -129,6 +129,9 @@ fn run(argv: &[String]) -> i32 { println!("dla {}{}", dl::VERSION, dl::BUILD_MARKER); return 0; } + // The event log's clock for this start: dla's own steps are charged as stages + // below, and dl writes the `aid_start` line when its launch is ready. + let mut start = dl::events::DlaStart::begin(); // `dl::env_str`, not `std::env::var(..).ok()`: that call reports a value which // is not valid UTF-8 as *unset*, so `DEVLAUNCH_AID_AGENT=$'\xff'` used to name @@ -196,6 +199,7 @@ fn run(argv: &[String]) -> i32 { return 1; } }; + start.stage("pick"); // The interactive default: an agent line with no prompt, on a terminal, boots // the workspace in the background while the prompt is typed here instead of in // a shell. Anything else — an inline prompt, a verb line, a pipe — comes back @@ -209,6 +213,7 @@ fn run(argv: &[String]) -> i32 { Ok(spec) => parsed.with_spec(spec), Err(code) => return code, }; + start.stage("pr_lookup"); let (parsed, boot) = match interactive::collect_prompt(parsed, argv, environment, pickers) { interactive::Collected::Launch(parsed, boot) => (*parsed, boot), // 130, the code a Ctrl-C at the prompt editor ends with, because a cancel @@ -218,6 +223,7 @@ fn run(argv: &[String]) -> i32 { return 130; } }; + start.stage("prompt"); let session = new_session_id(); let Some(launch) = rewrite::build_launch(&parsed, &dl::workspace_id_of, session.as_deref()) else { @@ -245,12 +251,16 @@ fn run(argv: &[String]) -> i32 { // dl runs, the workspace is up and the launch is the fast attach. if let Some(boot) = boot { boot.finish(); + start.stage("boot_wait"); } name_agent_for_session_manager(parsed.agent()); - match launch.resume { + start.hand_over(parsed.agent(), parsed.resumes()); + let code = match launch.resume { Some(resume) => dl::run_resumable(&launch.dl_args, resume), None => dl::run(&launch.dl_args), - } + }; + dl::events::dla_end(code); + code } /// A fresh UUID v4, for the session dla names before it starts it. diff --git a/rust/dla/src/rewrite.rs b/rust/dla/src/rewrite.rs index a6e6bc13..7ce4fd70 100644 --- a/rust/dla/src/rewrite.rs +++ b/rust/dla/src/rewrite.rs @@ -757,6 +757,11 @@ impl DlaArgs { } } + /// Whether this line resumes an agent session rather than starting one. + pub(crate) fn resumes(&self) -> bool { + matches!(self.task, Task::Resume { .. }) + } + /// The same line with the prompt the interactive editor collected. /// /// A retired-spelling line is returned unchanged — it has no prompt to replace, diff --git a/rust/dla/tests/rewrite.rs b/rust/dla/tests/rewrite.rs index b486bf9f..c7a36947 100644 --- a/rust/dla/tests/rewrite.rs +++ b/rust/dla/tests/rewrite.rs @@ -360,6 +360,46 @@ fn a_fresh_claude_session_is_named() { assert_eq!(&id[14..15], "4", "not a v4 uuid: {id}"); } +#[test] +fn a_start_logs_dls_launch_then_dlas_own_start_and_end() { + // The event log, as the usage review reads it: dl's `launch`, then dla's + // `aid_start` with dla's own steps and dl's launch as stages, then the end of + // dl's session and of dla's. + let world = World::with(&["--warm"]); + world.dla(&[MAIN, "hi"]).exited(0); + + let log = std::fs::read_to_string(world.root.join("home/.local/state/devlaunch/events.jsonl")) + .expect("the start is logged"); + let lines: Vec = log + .lines() + .map(|line| serde_json::from_str(line).expect("one JSON object")) + .collect(); + let names: Vec<&str> = lines + .iter() + .map(|line| line["ev"].as_str().unwrap()) + .collect(); + assert_eq!( + names, + ["launch", "aid_start", "session_end", "aid_end"], + "{log}" + ); + let start = &lines[1]; + assert_eq!(start["ws"], MAIN); + assert_eq!(start["agent"], "claude"); + assert_eq!(start["resume"], false); + assert_eq!(start["cold"], false); + let stages = start["stages"].as_object().expect("stages"); + for stage in ["pick", "pr_lookup", "prompt", "dl"] { + assert!(stages.contains_key(stage), "{stage} in {log}"); + } + assert!( + start["seconds"].as_f64() >= stages["dl"].as_f64(), + "dla's start includes dl's launch: {log}" + ); + assert_eq!(lines[3]["agent"], "claude"); + assert_eq!(lines[3]["exit"], 0); +} + #[test] fn a_prompt_reaches_the_agent_as_one_argument_through_dls_own_launch() { // The whole of dla, observed from outside: the rewritten command line on stderr, diff --git a/test/conftest.py b/test/conftest.py index e6441472..d625afe4 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -76,10 +76,16 @@ def isolated_devlaunch_cache(tmp_path_factory, monkeypatch): assertions. The scratch-run recipe in AGENTS.md still declines to scope it, because scoping it hides the host's gh login, which the suite has already given up in no_gh_token_forwarding below and a real `dl-next` run has not. + + XDG_STATE_HOME goes with them too: every `dl` appends to the event log under + it, and a suite run would otherwise add its launches and removals to the + developer's own `~/.local/state/devlaunch/events.jsonl`, which a usage review + reads as real starts. """ root = tmp_path_factory.mktemp("xdg") monkeypatch.setenv("XDG_CACHE_HOME", str(root / "cache")) monkeypatch.setenv("XDG_CONFIG_HOME", str(root / "config")) + monkeypatch.setenv("XDG_STATE_HOME", str(root / "state")) @pytest.fixture(autouse=True) From 01700da20385dc7d0cff42802d50b953a91aae1f Mon Sep 17 00:00:00 2001 From: Austin Gregg-Smith Date: Sat, 21 Nov 2026 19:04:19 +0000 Subject: [PATCH 02/13] fix: launch and aid_start could get different timestamps from one ready Each line read the clock on its own, so the two writes could straddle a millisecond and give launch a ts before aid_start. The usage review pairs them with an ASOF JOIN on l.ts >= a.ts, which then dropped or mispaired the start. One ready now reads the clock once and both lines carry it. --- rust/dl/src/events.rs | 96 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 86 insertions(+), 10 deletions(-) diff --git a/rust/dl/src/events.rs b/rust/dl/src/events.rs index 8d82e743..734f99bb 100644 --- a/rust/dl/src/events.rs +++ b/rust/dl/src/events.rs @@ -142,7 +142,7 @@ pub(crate) fn end(exit: i32) { _ => None, }); if let (Some(ev), Some(verb)) = (lifecycle, &verb) { - let mut event = base(ev, verb.target.as_deref(), None); + let mut event = base(ev, SystemTime::now(), verb.target.as_deref(), None); event.insert("seconds".into(), seconds(verb.started.elapsed())); event.insert("exit".into(), exit.into()); append(&Value::Object(event)); @@ -153,6 +153,7 @@ pub(crate) fn end(exit: i32) { if let Some(readied) = readied.filter(|_| !upped) { let mut event = base( "session_end", + SystemTime::now(), readied.target.as_deref(), readied.workspace_id.as_deref(), ); @@ -183,15 +184,43 @@ fn on_ready(ready: &timing::Ready) { let seen = seen(); seen.verb.as_ref().map(|verb| verb.word) }; - append(&launch_event(ready, target.as_deref(), verb)); + for event in ready_events( + ready, + target.as_deref(), + verb, + dla.as_ref(), + now, + SystemTime::now(), + ) { + append(&event); + } +} + +/// The lines one ready writes: `launch`, then `aid_start` when dla handed a +/// start over. Both carry `at` as their `ts`. +fn ready_events( + ready: &timing::Ready, + target: Option<&str>, + verb: Option<&str>, + dla: Option<&Dla>, + now: Instant, + at: SystemTime, +) -> Vec { + let mut events = vec![launch_event(ready, target, verb, at)]; if let Some(dla) = dla { - append(&aid_start_event(&dla, ready, target.as_deref(), now)); + events.push(aid_start_event(dla, ready, target, now, at)); } + events } /// The `launch` line for `ready`. -fn launch_event(ready: &timing::Ready, target: Option<&str>, verb: Option<&str>) -> Value { - let mut event = base("launch", target, ready.workspace_id.as_deref()); +fn launch_event( + ready: &timing::Ready, + target: Option<&str>, + verb: Option<&str>, + at: SystemTime, +) -> Value { + let mut event = base("launch", at, target, ready.workspace_id.as_deref()); event.insert("cold".into(), ready.cold.into()); event.insert("seconds".into(), ready.seconds.into()); event.insert("stages".into(), stages(&ready.stages)); @@ -202,9 +231,16 @@ fn launch_event(ready: &timing::Ready, target: Option<&str>, verb: Option<&str>) } /// The `aid_start` line: dla's own steps, then dl's launch as one more stage. -fn aid_start_event(dla: &Dla, ready: &timing::Ready, target: Option<&str>, now: Instant) -> Value { +fn aid_start_event( + dla: &Dla, + ready: &timing::Ready, + target: Option<&str>, + now: Instant, + at: SystemTime, +) -> Value { let mut event = base( "aid_start", + at, target.or(dla.target.as_deref()), ready.workspace_id.as_deref(), ); @@ -277,6 +313,7 @@ pub fn dla_end(exit: i32) { } let mut event = base( "aid_end", + SystemTime::now(), dla.target.as_deref(), dla.workspace_id.as_deref(), ); @@ -292,7 +329,12 @@ pub fn dla_end(exit: i32) { /// /// `ws` is the workspace id when the launch knew it, else the target as typed. /// `repo` and `branch` come from the target when it is `owner/repo[@branch]`. -fn base(ev: &str, target: Option<&str>, workspace_id: Option<&str>) -> Map { +fn base( + ev: &str, + at: SystemTime, + target: Option<&str>, + workspace_id: Option<&str>, +) -> Map { let (repo, branch) = match target.map(spec::parse) { Some(WorkspaceSpec::OwnerRepo { owner, @@ -302,7 +344,7 @@ fn base(ev: &str, target: Option<&str>, workspace_id: Option<&str>) -> Map (None, None), }; let mut event = Map::new(); - event.insert("ts".into(), iso8601(SystemTime::now()).into()); + event.insert("ts".into(), iso8601(at).into()); event.insert("ev".into(), ev.into()); event.insert("ws".into(), workspace_id.or(target).into()); event.insert("repo".into(), repo.into()); @@ -411,7 +453,12 @@ mod tests { stages: vec![("host-prep", 1.25), ("devpod-up", 3.0)], }; - let line = launch_event(&ready, Some("owner/repo@main"), Some("attach")); + let line = launch_event( + &ready, + Some("owner/repo@main"), + Some("attach"), + SystemTime::now(), + ); assert_eq!(line["ev"], "launch"); assert_eq!(line["ws"], "repo-main"); @@ -423,9 +470,38 @@ mod tests { assert_eq!(line["verb"], "attach"); } + #[test] + fn the_launch_and_aid_start_lines_of_one_ready_share_a_timestamp() { + let ready = timing::Ready { + workspace_id: Some("repo-main".to_owned()), + seconds: 4.5, + cold: false, + stages: vec![], + }; + let started = Instant::now(); + let dla = Dla { + started, + stages: vec![], + agent: Some("claude".to_owned()), + resume: false, + workspace_id: None, + target: None, + }; + let at = UNIX_EPOCH + Duration::from_millis(1_795_253_405_999); + + let lines = ready_events(&ready, Some("repo-main"), None, Some(&dla), started, at); + + assert_eq!(lines.len(), 2); + assert_eq!(lines[0]["ev"], "launch"); + assert_eq!(lines[1]["ev"], "aid_start"); + for line in &lines { + assert_eq!(line["ts"], "2026-11-21T09:30:05.999Z"); + } + } + #[test] fn a_bare_workspace_name_is_the_ws_and_names_no_repo() { - let line = base("stop", Some("repo-main"), None); + let line = base("stop", SystemTime::now(), Some("repo-main"), None); assert_eq!(line["ws"], "repo-main"); assert_eq!(line["repo"], Value::Null); From e7904d2351dcb080afe160a9f1d2c723f893b2b6 Mon Sep 17 00:00:00 2001 From: Austin Gregg-Smith Date: Sat, 21 Nov 2026 19:05:07 +0000 Subject: [PATCH 03/13] fix: aid_end lost the workspace when dla failed before ready Dla's target was filled only when the launch was ready, so a start that failed first (an unknown workspace) wrote aid_end with ws null. aid_end now takes the target from the verb dl dispatched, which is known before ready. The copy of the target on dla's record goes, since the verb already holds it. --- rust/dl/src/events.rs | 20 ++++++++------------ rust/dla/tests/rewrite.rs | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/rust/dl/src/events.rs b/rust/dl/src/events.rs index 734f99bb..0d9a44c2 100644 --- a/rust/dl/src/events.rs +++ b/rust/dl/src/events.rs @@ -87,7 +87,6 @@ struct Dla { agent: Option, resume: bool, workspace_id: Option, - target: Option, } #[derive(Debug, Default)] @@ -176,7 +175,6 @@ fn on_ready(ready: &timing::Ready) { }); if let Some(dla) = seen.dla.as_mut() { dla.workspace_id = ready.workspace_id.clone(); - dla.target.clone_from(&target); } (target, seen.dla.clone()) }; @@ -238,12 +236,7 @@ fn aid_start_event( now: Instant, at: SystemTime, ) -> Value { - let mut event = base( - "aid_start", - at, - target.or(dla.target.as_deref()), - ready.workspace_id.as_deref(), - ); + let mut event = base("aid_start", at, target, ready.workspace_id.as_deref()); let mut steps = dla.stages.clone(); steps.push(("dl", ready.seconds)); event.insert("cold".into(), ready.cold.into()); @@ -298,14 +291,18 @@ impl DlaStart { agent: agent.map(str::to_owned), resume, workspace_id: None, - target: None, }); } } /// dla ended with `exit`: write `aid_end`, if dla handed a start over. pub fn dla_end(exit: i32) { - let Some(dla) = seen().dla.take() else { + let (dla, target) = { + let mut seen = seen(); + let target = seen.verb.as_ref().and_then(|verb| verb.target.clone()); + (seen.dla.take(), target) + }; + let Some(dla) = dla else { return; }; if !wanted(devlaunch_core::osext::env_str(ENV_VAR).as_deref()) { @@ -314,7 +311,7 @@ pub fn dla_end(exit: i32) { let mut event = base( "aid_end", SystemTime::now(), - dla.target.as_deref(), + target.as_deref(), dla.workspace_id.as_deref(), ); event.insert("seconds".into(), seconds(dla.started.elapsed())); @@ -485,7 +482,6 @@ mod tests { agent: Some("claude".to_owned()), resume: false, workspace_id: None, - target: None, }; let at = UNIX_EPOCH + Duration::from_millis(1_795_253_405_999); diff --git a/rust/dla/tests/rewrite.rs b/rust/dla/tests/rewrite.rs index c7a36947..9304ece3 100644 --- a/rust/dla/tests/rewrite.rs +++ b/rust/dla/tests/rewrite.rs @@ -400,6 +400,23 @@ fn a_start_logs_dls_launch_then_dlas_own_start_and_end() { assert_eq!(lines[3]["exit"], 0); } +#[test] +fn a_start_that_fails_before_ready_ends_naming_the_workspace_it_was_given() { + let world = World::with(&["--warm"]); + world.dla(&["no-such-workspace-zz", "hi"]).exited(1); + + let log = std::fs::read_to_string(world.root.join("home/.local/state/devlaunch/events.jsonl")) + .expect("the end is logged"); + let lines: Vec = log + .lines() + .map(|line| serde_json::from_str(line).expect("one JSON object")) + .collect(); + assert_eq!(lines.len(), 1, "{log}"); + assert_eq!(lines[0]["ev"], "aid_end", "{log}"); + assert_eq!(lines[0]["ws"], "no-such-workspace-zz", "{log}"); + assert_eq!(lines[0]["exit"], 1, "{log}"); +} + #[test] fn a_prompt_reaches_the_agent_as_one_argument_through_dls_own_launch() { // The whole of dla, observed from outside: the rewritten command line on stderr, From 271680882f63aadb2157e8932f9563dcf96fe142 Mon Sep 17 00:00:00 2001 From: Austin Gregg-Smith Date: Sat, 21 Nov 2026 19:07:27 +0000 Subject: [PATCH 04/13] fix: dl code created a workspace and logged no launch code and dotfiles start no session, so they reached neither attach_workspace nor the up-only ready call: no launch line was written. A Verb now says whether it is ready without a session; the dispatch fires the ready for all three, and the event state writes no session_end after them. --- docs/performance.md | 2 +- rust/dl/src/cli.rs | 17 +++++++++++++++++ rust/dl/src/commands.rs | 14 ++++++++------ rust/dl/src/events.rs | 21 ++++++++++++--------- rust/dl/tests/launch.rs | 16 ++++++++++++++++ 5 files changed, 54 insertions(+), 16 deletions(-) diff --git a/docs/performance.md b/docs/performance.md index 0e30a999..463dcdcc 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -191,7 +191,7 @@ append, so two commands at once do not mix their lines. | `ev` | Written when | Fields beyond `ts`, `ev`, `ws`, `repo`, `branch` | |---|---|---| -| `launch` | The workspace is ready and the session is about to start, or an `up` has finished | `cold`, `seconds`, `stages`, `verb` | +| `launch` | The workspace is ready and the session is about to start, or an `up`, `code` or `dotfiles` has finished | `cold`, `seconds`, `stages`, `verb` | | `session_end` | The session a `launch` started has ended | `seconds` (of the session), `exit` | | `stop`, `kill`, `remove`, `prune` | The verb has finished | `seconds`, `exit` | | `aid_start` | `dla` has handed its start to `dl` and the workspace is ready | `cold`, `seconds`, `stages`, `agent`, `resume` | diff --git a/rust/dl/src/cli.rs b/rust/dl/src/cli.rs index 773e9596..1ffab2b6 100644 --- a/rust/dl/src/cli.rs +++ b/rust/dl/src/cli.rs @@ -349,6 +349,23 @@ impl Verb { } } + /// Whether this verb brings the workspace up and ends there, with no session + /// after it: its launch is ready when it has finished, not when a session + /// starts. Exhaustive, so a new verb has to answer. + pub(crate) fn ready_without_a_session(&self) -> bool { + match self { + Verb::Up | Verb::Code | Verb::Dotfiles => true, + Verb::Attach { .. } + | Verb::Run(..) + | Verb::Recreate + | Verb::Restart + | Verb::Reset + | Verb::Stop + | Verb::Kill + | Verb::Remove { .. } => false, + } + } + /// What this verb asks of the calling shell once it is done. /// /// Only `rme` asks for anything, and the question is asked of the *verb* rather diff --git a/rust/dl/src/commands.rs b/rust/dl/src/commands.rs index 479f0540..c1358be6 100644 --- a/rust/dl/src/commands.rs +++ b/rust/dl/src/commands.rs @@ -135,7 +135,7 @@ pub(crate) fn dispatch( force, force_worktrees, } => { - crate::events::workspace(None, "prune"); + crate::events::workspace(None, "prune", false); render_prune( runner, &mut context, @@ -243,7 +243,8 @@ pub(crate) fn dispatch( } let after = verb.after_removal(); let word = verb.word(); - crate::events::workspace(Some(&target), word); + let sessionless = verb.ready_without_a_session(); + crate::events::workspace(Some(&target), word, sessionless); let ending = render_workspace( runner, &mut context, @@ -258,10 +259,11 @@ pub(crate) fn dispatch( None, resume, ); - // An `up` starts no session, so its launch is ready when it has - // finished, and only if it worked. `timing::ready` fires once, so an - // `up` that reached a ready point of its own is not counted twice. - if word == "up" && ending.code() == 0 { + // `up`, `code` and `dotfiles` start no session, so their launch is + // ready when they have finished, and only if they worked. + // `timing::ready` fires once, so one that reached a ready point of its + // own is not counted twice. + if sessionless && ending.code() == 0 { devlaunch_core::timing::ready(None); } hangup::after_the_command(after, word, ending) diff --git a/rust/dl/src/events.rs b/rust/dl/src/events.rs index 0d9a44c2..afab40c1 100644 --- a/rust/dl/src/events.rs +++ b/rust/dl/src/events.rs @@ -6,9 +6,9 @@ //! Always on. `DEVLAUNCH_EVENTS=0` turns it off. What is written: //! //! - `launch`: the workspace is ready, written the moment the session is about -//! to start (or the `up` has finished). `seconds` is the wall time from the -//! top of the command, `cold` says the `up` created the workspace, and -//! `stages` holds the named [`timing`] stages in seconds. +//! to start (or an `up`, `code` or `dotfiles` has finished). `seconds` is the +//! wall time from the top of the command, `cold` says the `up` created the +//! workspace, and `stages` holds the named [`timing`] stages in seconds. //! - `session_end`: the session a `launch` started has ended. `seconds` is how //! long it lasted and `exit` is how it ended. //! - `stop`, `kill`, `remove`, `prune`: the verb ran; `seconds` is how long it took. @@ -66,6 +66,7 @@ pub(crate) fn path() -> Option { #[derive(Debug, Clone)] struct Verb { word: &'static str, + sessionless: bool, target: Option, started: Instant, } @@ -114,11 +115,12 @@ pub(crate) fn begin() { seen.readied = None; } -/// The workspace verb this command runs, and the target it names (`prune` -/// names none). -pub(crate) fn workspace(target: Option<&str>, word: &'static str) { +/// The workspace verb this command runs, the target it names (`prune` names +/// none), and whether it is ready with no session after it. +pub(crate) fn workspace(target: Option<&str>, word: &'static str, sessionless: bool) { seen().verb = Some(Verb { word, + sessionless, target: target.map(str::to_owned), started: Instant::now(), }); @@ -147,9 +149,10 @@ pub(crate) fn end(exit: i32) { append(&Value::Object(event)); return; } - // An `up` is ready when it ends; there is no session after it. - let upped = verb.as_ref().is_some_and(|verb| verb.word == "up"); - if let Some(readied) = readied.filter(|_| !upped) { + // An `up`, `code` or `dotfiles` is ready when it ends; there is no session + // after it. + let sessionless = verb.as_ref().is_some_and(|verb| verb.sessionless); + if let Some(readied) = readied.filter(|_| !sessionless) { let mut event = base( "session_end", SystemTime::now(), diff --git a/rust/dl/tests/launch.rs b/rust/dl/tests/launch.rs index b6880ffb..8bb357c6 100644 --- a/rust/dl/tests/launch.rs +++ b/rust/dl/tests/launch.rs @@ -2863,6 +2863,22 @@ fn an_up_logs_one_launch_and_no_session() { assert_eq!(lines[0]["verb"], "up"); } +#[test] +fn a_code_or_dotfiles_logs_one_launch_and_no_session() { + for verb in ["code", "dotfiles"] { + let world = World::with(&["--stopped"]); + world.dl(&[MAIN, verb]).exited(0); + + let lines = events(&world); + let names: Vec<&str> = lines + .iter() + .map(|line| line["ev"].as_str().unwrap()) + .collect(); + assert_eq!(names, ["launch"], "dl {verb}: {lines:?}"); + assert_eq!(lines[0]["verb"], verb); + } +} + #[test] fn the_event_log_follows_xdg_state_home() { let world = World::with(&["--warm"]); From 0b150b3f800d3809841cc919651fc30ab85f425f Mon Sep 17 00:00:00 2001 From: Austin Gregg-Smith Date: Sat, 21 Nov 2026 19:09:02 +0000 Subject: [PATCH 05/13] fix: a picked up logged no launch and a picked stop logged nothing The verb was recorded only on the named-target route; the picker went straight to render_workspace. The record and the sessionless ready now live in render_workspace, so both routes go through them. A picked batch still writes one line, and docs/performance.md says which. --- docs/performance.md | 6 ++- rust/dl/src/commands.rs | 62 ++++++++++++++++++++++------- rust/dl/tests/picker.rs | 86 ++++++++++++++++++++++++++++++++++++++--- 3 files changed, 132 insertions(+), 22 deletions(-) diff --git a/docs/performance.md b/docs/performance.md index 463dcdcc..fe209c4b 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -210,8 +210,10 @@ called before, and what readers of older logs already look for. {"ts":"2026-11-21T09:13:05.340Z","ev":"aid_start","ws":"devlaunch-main-3j1t","repo":"blooop/devlaunch","branch":"main","cold":false,"seconds":0.043923,"stages":{"pick":0.00007,"pr_lookup":0.00005,"prompt":1e-6,"dl":0.023009},"agent":"claude","resume":false} ``` -A picked batch (`dl` with no target, then a verb) logs its launch but not its -`stop`, `kill` or `remove`. +A picked workspace logs the same lines as a named one. A picked batch (several +rows marked for one verb) writes one line, not one per workspace: the `launch` of +the first workspace that came up, or the `stop`, `kill` or `remove` of the last +one, timed from that workspace's start. ### The same launch, machine-readable diff --git a/rust/dl/src/commands.rs b/rust/dl/src/commands.rs index c1358be6..52149a09 100644 --- a/rust/dl/src/commands.rs +++ b/rust/dl/src/commands.rs @@ -243,8 +243,6 @@ pub(crate) fn dispatch( } let after = verb.after_removal(); let word = verb.word(); - let sessionless = verb.ready_without_a_session(); - crate::events::workspace(Some(&target), word, sessionless); let ending = render_workspace( runner, &mut context, @@ -259,13 +257,6 @@ pub(crate) fn dispatch( None, resume, ); - // `up`, `code` and `dotfiles` start no session, so their launch is - // ready when they have finished, and only if they worked. - // `timing::ready` fires once, so one that reached a ready point of its - // own is not counted twice. - if sessionless && ending.code() == 0 { - devlaunch_core::timing::ready(None); - } hangup::after_the_command(after, word, ending) } } @@ -865,6 +856,49 @@ fn render_workspace<'r>( // before the verb it is holding up gets anywhere. let mut opening = render::Saying; let mut cold = ColdPath::new(runner, &mut opening); + let word = verb.word(); + // Here rather than in the dispatch, so a named target and a picked one are + // logged alike. A picked batch is several calls; the event state keeps the + // last verb, and the first ready. + let sessionless = verb.ready_without_a_session(); + crate::events::workspace(Some(target), word, sessionless); + let ending = render_verb( + runner, + context, + cache, + refresh, + &mut cold, + target, + verb, + devcontainer, + claude_profile, + recognised, + resume, + ); + // `up`, `code` and `dotfiles` start no session, so their launch is ready + // when they have finished, and only if they worked. `timing::ready` fires + // once, so one that reached a ready point of its own is not counted twice. + if sessionless && ending.code() == 0 { + devlaunch_core::timing::ready(None); + } + ending +} + +/// [`render_workspace`]'s verb, run against the target. +#[allow(clippy::too_many_arguments)] +fn render_verb<'r>( + runner: &'r dyn Runner, + context: &mut CommandContext<'r>, + cache: &Path, + refresh: &mut Refresh<'_>, + cold: &mut ColdPath<'r, '_>, + target: &str, + verb: Verb, + devcontainer: Option<&DevcontainerPath>, + claude_profile: Option<&str>, + recognised: Option, + resume: Option, +) -> Ending { // The word the line used, asked of the verb rather than written out per arm. // Two of the three arms are one word each and could be spelled here, but // `Family::Remove` covers both `rm` and `rme`, and a notice that quotes a word @@ -874,12 +908,12 @@ fn render_workspace<'r>( Family::Stop => { devcontainer_ignored(devcontainer.is_some(), word); claude_profile_ignored(claude_profile.is_some(), word); - render_stop(runner, context, refresh, &mut cold, target) + render_stop(runner, context, refresh, cold, target) } Family::Kill => { devcontainer_ignored(devcontainer.is_some(), word); claude_profile_ignored(claude_profile.is_some(), word); - render_kill(runner, context, cache, refresh, &mut cold, target, word) + render_kill(runner, context, cache, refresh, cold, target, word) } Family::Remove { force } => { devcontainer_ignored(devcontainer.is_some(), word); @@ -889,7 +923,7 @@ fn render_workspace<'r>( context, cache, refresh, - &mut cold, + cold, target, removal_of(force), word, @@ -902,7 +936,7 @@ fn render_workspace<'r>( context, cache, refresh, - &mut cold, + cold, target, &launched, devcontainer, @@ -910,7 +944,7 @@ fn render_workspace<'r>( recognised, resume, ); - after_the_session(runner, context, cache, refresh, &mut cold, target, rm, ran) + after_the_session(runner, context, cache, refresh, cold, target, rm, ran) } } } diff --git a/rust/dl/tests/picker.rs b/rust/dl/tests/picker.rs index f2bdf464..bc10e063 100644 --- a/rust/dl/tests/picker.rs +++ b/rust/dl/tests/picker.rs @@ -503,6 +503,56 @@ fn a_batch_of_marked_rows_is_named_and_counted_before_the_first_one_goes() { ); } +#[test] +fn a_picked_verb_is_in_the_event_log_as_a_named_one_is() { + let world = World::new(); + let (screen, said) = Screen::run_in( + &world, + Some("xterm-256color"), + &["stop"], + "wayfinder", + |screen| screen.row_of("blooop-devlaunch").is_none(), + Dismiss::Take, + ); + + let events = world.events(); + let stops: Vec<&serde_json::Value> = events + .iter() + .filter(|event| event["ev"] == "stop") + .collect(); + assert_eq!( + stops.len(), + 1, + "a picked stop wrote {events:?}; dl said {said:?} from this screen:\n{screen}" + ); + assert_eq!(stops[0]["ws"], "blooop-wayfinder", "{events:?}"); +} + +#[test] +fn a_picked_up_logs_a_launch_that_names_its_verb() { + let world = World::new(); + let (screen, said) = Screen::run_in( + &world, + Some("xterm-256color"), + &["up"], + "wayfinder", + |screen| screen.row_of("blooop-devlaunch").is_none(), + Dismiss::Take, + ); + + let events = world.events(); + let launches: Vec<&serde_json::Value> = events + .iter() + .filter(|event| event["ev"] == "launch") + .collect(); + assert_eq!( + launches.len(), + 1, + "a picked up wrote {events:?}; dl said {said:?} from this screen:\n{screen}" + ); + assert_eq!(launches[0]["verb"], "up", "{events:?}"); +} + /// How the picker is left once the screen has been taken. #[derive(Clone, Copy)] enum Dismiss { @@ -579,6 +629,26 @@ impl Screen { dismiss: Dismiss, ) -> (Self, Vec, String, Vec) { let world = World::new(); + let (screen, afterwards) = Self::run_in(&world, term, args, keys, settled, dismiss); + ( + screen, + world.devpod_calls(), + afterwards, + world.devpod_terms(), + ) + } + + /// [`Self::run_under`] in a world the caller keeps, for a test that reads + /// more of it afterwards: the screen, and what `dl` wrote once the picker + /// had given the screen back. + fn run_in( + world: &World, + term: Option<&str>, + args: &[&str], + keys: &str, + settled: impl Fn(&Screen) -> bool, + dismiss: Dismiss, + ) -> (Self, String) { let pair = native_pty_system() .openpty(PtySize { rows: ROWS, @@ -661,12 +731,7 @@ impl Screen { let _ = collecting_bytes.join(); let afterwards = Self::afterwards(&drawn.lock().expect("the collected bytes").clone()); - ( - screen, - world.devpod_calls(), - afterwards, - world.devpod_terms(), - ) + (screen, afterwards) } /// The bytes a terminal received, as the grid it would be showing. @@ -951,6 +1016,15 @@ exit 0 .collect() } + /// Every line of the event log at the XDG default under this world's `HOME`. + fn events(&self) -> Vec { + std::fs::read_to_string(self.root.join("home/.local/state/devlaunch/events.jsonl")) + .unwrap_or_default() + .lines() + .map(|line| serde_json::from_str(line).expect("each line is one JSON object")) + .collect() + } + /// `dl ` against this world, environment and all. /// /// The same scratch `HOME`/`XDG_*`/`DEVPOD_HOME` shape `tests/read_side.rs` From ddff7ef5adeb11b6d6ecbc3eacf668f208dd255a Mon Sep 17 00:00:00 2001 From: Austin Gregg-Smith Date: Sat, 21 Nov 2026 19:10:10 +0000 Subject: [PATCH 06/13] docs: timing comments said unset DEVLAUNCH_TIMING records nothing With the event log on by default, the timing registry records a launch's stages even when DEVLAUNCH_TIMING is unset; only DEVLAUNCH_EVENTS=0 as well leaves it off. DEVLAUNCH_TIMING now controls only the stderr report. --- docs/performance.md | 5 +++-- rust/devlaunch-core/src/timing.rs | 20 ++++++++++++-------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/docs/performance.md b/docs/performance.md index fe209c4b..7f890161 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -142,8 +142,9 @@ be the cost of starting a bash per stage, which is small. A warm launch makes no ## Measuring launch time Set `DEVLAUNCH_TIMING=1` and a `dl` command ends with one summary on stderr, -naming each subprocess round trip and the total. Unset (or `0`) records nothing -and prints nothing. +naming each subprocess round trip and the total. Unset (or `0`) prints nothing. +The stages are still recorded for [the event log](#the-event-log) unless +`DEVLAUNCH_EVENTS=0`. **Every second quoted in this section came off one host on 2026-08-14, over three sessions that day (`d3b8ffb`, `5510b1e`, `461f740`), and that host was diff --git a/rust/devlaunch-core/src/timing.rs b/rust/devlaunch-core/src/timing.rs index 938b7054..3c277cce 100644 --- a/rust/devlaunch-core/src/timing.rs +++ b/rust/devlaunch-core/src/timing.rs @@ -2,9 +2,11 @@ //! //! Set `DEVLAUNCH_TIMING=1` and every dl process ends with one summary on //! stderr: a `dl-timing: