Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

refactor(trace): decouple human trace.log from machine trace.jsonl (#3297)

Maximilian Roosc1c76b150d5f
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.md
index 5cb067cc0..0a414fa4b 100644
--- a/benches/CLAUDE.md
+++ b/benches/CLAUDE.md
@@ -172,10 +172,10 @@ cargo run -p wt-perf -- invalidate /tmp/wt-perf-typical-8/main
### Generating traces
-`wt-perf timeline` runs a `wt` invocation, captures `[wt-trace]` records,
-and renders. Default mode is a sorted text timeline; `--chrome` emits
-Chrome Trace Format JSON for Perfetto/chrome://tracing. `--cold`
-invalidates caches first.
+`wt-perf timeline` runs a `wt` invocation with `-vv` (which writes the
+machine `trace.jsonl`), reads that back, and renders. Default mode is a
+sorted text timeline; `--chrome` emits Chrome Trace Format JSON for
+Perfetto/chrome://tracing. `--cold` invalidates caches first.
```bash
# Text timeline of one wt invocation
@@ -194,16 +194,16 @@ cargo run -p wt-perf -- timeline --chrome -- list --progressive > trace.json
piped to /dev/null, so TTY-gated events (`Skeleton rendered`, `First
result received`) won't fire without it.
-For Chrome JSON from a log already captured to disk (e.g. a CI artifact),
-pipe through `wt-perf trace` instead:
+For Chrome JSON from a `trace.jsonl` already captured to disk (e.g. a CI
+artifact), feed it to `wt-perf trace` instead:
```bash
-RUST_LOG=debug wt list --progressive --branches 2> captured.log
-cargo run -p wt-perf -- trace < captured.log > trace.json
+wt -vv list --progressive --branches
+cargo run -p wt-perf -- trace .git/wt/logs/trace.jsonl > trace.json
```
-The text-timeline summary reports `traced` (first → last `[wt-trace]`
-record, what the spans actually cover) and `wall` (externally-measured
+The text-timeline summary reports `traced` (first → last record, what the
+spans actually cover) and `wall` (externally-measured
spawn → wait, the true process duration). The gap between them is
prelude/epilogue not visible to the trace — process spawn, dyld, code
that runs before `init_logging` registers the trace epoch, and the exit
@@ -311,8 +311,8 @@ trace_processor trace.json -q /tmp/q.sql
```bash
# Trace on rust-lang/rust (must run benchmark first to clone)
-RUST_LOG=debug cargo run --release -q -- -C target/bench-repos/rust list --progressive --branches 2>&1 \
- | cargo run -p wt-perf -- trace > rust-trace.json
+cargo run --release -q -- -vv -C target/bench-repos/rust list --progressive --branches
+cargo run -p wt-perf -- trace target/bench-repos/rust/.git/wt/logs/trace.jsonl > rust-trace.json
```
## Key Performance Insights
diff --git a/docs/content/config.md b/docs/content/config.md
index 098ffd90d..333dcb19f 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -1091,10 +1091,11 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
| File | Created when |
|------|-------------|
| `trace.log` | Running with `-vv` |
+| `trace.jsonl` | Running with `-vv` |
| `subprocess.log` | Running with `-vv` |
| `diagnostic.md` | Running with `-vv` |
-`trace.log` captures debug-level records at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews. `wt config state logs profile` summarizes one into a performance report (where time went, parallelism, redundant commands). `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log` and a rendered performance profile; `wt` prints a `gh gist create` command pointing at it. All three are overwritten on each `-vv` run.
+`trace.log` is the human-readable trace at `-vv` — each command's start (`$ …`) and completion (`✓`/`✗ … 12.3ms`), in-process spans, milestones, and bounded subprocess previews. `trace.jsonl` is the same event stream as one JSON object per line, for machines (`jq`, chrome://tracing); `wt config state logs profile` reads it to summarize a performance report (where time went, parallelism, redundant commands). `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log` and a rendered performance profile; `wt` prints a `gh gist create` command pointing at it. All four are overwritten on each `-vv` run.
### Location
@@ -1130,7 +1131,7 @@ Usage: <b><span class=c>wt config state logs</span></b> <span class=c>[OPTIONS]<
<b><span class=g>Commands:</span></b>
<b><span class=c>get</span></b> List all log file paths
- <b><span class=c>profile</span></b> Performance profile from a trace log
+ <b><span class=c>profile</span></b> Performance profile from a trace
<b><span class=c>clear</span></b> Clear all log files
<b><span class=g>Options:</span></b>
diff --git a/docs/content/faq.md b/docs/content/faq.md
index 01921f0d3..fa1567036 100644
--- a/docs/content/faq.md
+++ b/docs/content/faq.md
@@ -95,19 +95,20 @@ Three verbosity levels. Each is a superset of the previous one.
|-------|--------|-------------------------|----------|
| (none) | Warnings only | — | Normal use |
| `-v` | + Info: hook output, alias template variable resolution | — | Debugging hooks/aliases |
-| `-vv` | Same as `-v` | + `trace.log`, `subprocess.log`, `diagnostic.md` | Filing a bug |
+| `-vv` | Same as `-v` | + `trace.log`, `trace.jsonl`, `subprocess.log`, `diagnostic.md` | Filing a bug |
-At `-vv`, debug-level records (`$ cmd` headers, `[wt-trace]` timing, bounded subprocess preview) route to `trace.log` instead of stderr — so the terminal stays readable while the deep trace lands on disk. A one-line pointer on stderr shows where the files went.
+At `-vv`, debug-level records (command lines, in-process spans, bounded subprocess preview) route to `trace.log` instead of stderr — so the terminal stays readable while the deep trace lands on disk. A one-line pointer on stderr shows where the files went.
-The three `-vv` files have distinct audiences:
+The `-vv` files have distinct audiences:
-- **`trace.log`** — bounded preview (~1K lines), `[wt-trace]` records, gistable.
+- **`trace.log`** — the human trace (bounded ~1K lines, gistable): each command's start (`$ git status`) and finish (`✓ git status [wt] 12.3ms`, `✗` on failure), spans, and milestones.
+- **`trace.jsonl`** — the same records as one JSON object per line, for machines (`jq`, chrome://tracing). `wt config state logs profile` reads it.
- **`subprocess.log`** — raw uncapped stdout/stderr of every subprocess `wt` spawns (multi-MB possible, e.g. full `git log -p` output). The deep-dive escape hatch.
- **`diagnostic.md`** — markdown bug-report bundle that inlines `trace.log` and a rendered performance profile (subprocess time by command type, slowest calls, repeated calls). `wt` prints a `gh gist create` command pointing at it.
`RUST_LOG` overrides the flag baseline when set (`RUST_LOG=debug wt -v` lifts `-v` to debug-on-stderr).
-The flags only reach a command you type; shell completion runs as its own process with nowhere to pass one. Set `WORKTRUNK_VERBOSE=0|1|2` to apply the level to *every* invocation, completion included — it's the env-var equivalent of `-v`/`-vv`, so level 2 writes the same `trace.log`/`subprocess.log`/`diagnostic.md` files. An explicit `-v`/`-vv` on a command raises the level further but never lowers this baseline. To profile a slow tab-completion, run it the way your shell does — e.g. `WORKTRUNK_VERBOSE=2 COMPLETE=fish wt -- wt switch ''` — then render the result with `wt config state logs profile`.
+The flags only reach a command you type; shell completion runs as its own process with nowhere to pass one. Set `WORKTRUNK_VERBOSE=0|1|2` to apply the level to *every* invocation, completion included — it's the env-var equivalent of `-v`/`-vv`, so level 2 writes the same `trace.log`/`trace.jsonl`/`subprocess.log`/`diagnostic.md` files. An explicit `-v`/`-vv` on a command raises the level further but never lowers this baseline. To profile a slow tab-completion, run it the way your shell does — e.g. `WORKTRUNK_VERBOSE=2 COMPLETE=fish wt -- wt switch ''` — then render the result with `wt config state logs profile`.
## What files does Worktrunk create?
@@ -156,7 +157,8 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`
| `.git/wt/cache/summary/{branch}/{hash}.json` | Cached LLM branch summaries, content-addressed by diff hash | `wt list --full`, `wt switch` (when `[list] summary = true`) |
| `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` |
| `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |
-| `.git/wt/logs/trace.log` | Debug log for issue reporting | Running with `-vv` |
+| `.git/wt/logs/trace.log` | Human debug trace for issue reporting | Running with `-vv` |
+| `.git/wt/logs/trace.jsonl` | Machine trace (one JSON object per record) | Running with `-vv` |
| `.git/wt/logs/subprocess.log` | Raw uncapped subprocess stdout/stderr (may be multi-MB) | Running with `-vv` |
| `.git/wt/logs/diagnostic.md` | Diagnostic report for issue reporting | Running with `-vv` |
| `.git/wt/trash/<name>-<timestamp>` | Staged worktree contents pending background deletion | `wt remove` |
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index a7d33cd7b..9e82b97ea 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -1126,10 +1126,11 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
| File | Created when |
|------|-------------|
| `trace.log` | Running with `-vv` |
+| `trace.jsonl` | Running with `-vv` |
| `subprocess.log` | Running with `-vv` |
| `diagnostic.md` | Running with `-vv` |
-`trace.log` captures debug-level records at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews. `wt config state logs profile` summarizes one into a performance report (where time went, parallelism, redundant commands). `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log` and a rendered performance profile; `wt` prints a `gh gist create` command pointing at it. All three are overwritten on each `-vv` run.
+`trace.log` is the human-readable trace at `-vv` — each command's start (`$ …`) and completion (`✓`/`✗ … 12.3ms`), in-process spans, milestones, and bounded subprocess previews. `trace.jsonl` is the same event stream as one JSON object per line, for machines (`jq`, chrome://tracing); `wt config state logs profile` reads it to summarize a performance report (where time went, parallelism, redundant commands). `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log` and a rendered performance profile; `wt` prints a `gh gist create` command pointing at it. All four are overwritten on each `-vv` run.
### Location
@@ -1175,7 +1176,7 @@ Usage: wt config state logs [OPTIONS] [COMMAND]
Commands:
get List all log file paths
- profile Performance profile from a trace log
+ profile Performance profile from a trace
clear Clear all log files
Options:
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 899b56c26..2848a9e74 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -88,19 +88,20 @@ Three verbosity levels. Each is a superset of the previous one.
|-------|--------|-------------------------|----------|
| (none) | Warnings only | — | Normal use |
| `-v` | + Info: hook output, alias template variable resolution | — | Debugging hooks/aliases |
-| `-vv` | Same as `-v` | + `trace.log`, `subprocess.log`, `diagnostic.md` | Filing a bug |
+| `-vv` | Same as `-v` | + `trace.log`, `trace.jsonl`, `subprocess.log`, `diagnostic.md` | Filing a bug |
-At `-vv`, debug-level records (`$ cmd` headers, `[wt-trace]` timing, bounded subprocess preview) route to `trace.log` instead of stderr — so the terminal stays readable while the deep trace lands on disk. A one-line pointer on stderr shows where the files went.
+At `-vv`, debug-level records (command lines, in-process spans, bounded subprocess preview) route to `trace.log` instead of stderr — so the terminal stays readable while the deep trace lands on disk. A one-line pointer on stderr shows where the files went.
-The three `-vv` files have distinct audiences:
+The `-vv` files have distinct audiences:
-- **`trace.log`** — bounded preview (~1K lines), `[wt-trace]` records, gistable.
+- **`trace.log`** — the human trace (bounded ~1K lines, gistable): each command's start (`$ git status`) and finish (`✓ git status [wt] 12.3ms`, `✗` on failure), spans, and milestones.
+- **`trace.jsonl`** — the same records as one JSON object per line, for machines (`jq`, chrome://tracing). `wt config state logs profile` reads it.
- **`subprocess.log`** — raw uncapped stdout/stderr of every subprocess `wt` spawns (multi-MB possible, e.g. full `git log -p` output). The deep-dive escape hatch.
- **`diagnostic.md`** — markdown bug-report bundle that inlines `trace.log` and a rendered performance profile (subprocess time by command type, slowest calls, repeated calls). `wt` prints a `gh gist create` command pointing at it.
`RUST_LOG` overrides the flag baseline when set (`RUST_LOG=debug wt -v` lifts `-v` to debug-on-stderr).
-The flags only reach a command you type; shell completion runs as its own process with nowhere to pass one. Set `WORKTRUNK_VERBOSE=0|1|2` to apply the level to *every* invocation, completion included — it's the env-var equivalent of `-v`/`-vv`, so level 2 writes the same `trace.log`/`subprocess.log`/`diagnostic.md` files. An explicit `-v`/`-vv` on a command raises the level further but never lowers this baseline. To profile a slow tab-completion, run it the way your shell does — e.g. `WORKTRUNK_VERBOSE=2 COMPLETE=fish wt -- wt switch ''` — then render the result with `wt config state logs profile`.
+The flags only reach a command you type; shell completion runs as its own process with nowhere to pass one. Set `WORKTRUNK_VERBOSE=0|1|2` to apply the level to *every* invocation, completion included — it's the env-var equivalent of `-v`/`-vv`, so level 2 writes the same `trace.log`/`trace.jsonl`/`subprocess.log`/`diagnostic.md` files. An explicit `-v`/`-vv` on a command raises the level further but never lowers this baseline. To profile a slow tab-completion, run it the way your shell does — e.g. `WORKTRUNK_VERBOSE=2 COMPLETE=fish wt -- wt switch ''` — then render the result with `wt config state logs profile`.
## What files does Worktrunk create?
@@ -149,7 +150,8 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`
| `.git/wt/cache/summary/{branch}/{hash}.json` | Cached LLM branch summaries, content-addressed by diff hash | `wt list --full`, `wt switch` (when `[list] summary = true`) |
| `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` |
| `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |
-| `.git/wt/logs/trace.log` | Debug log for issue reporting | Running with `-vv` |
+| `.git/wt/logs/trace.log` | Human debug trace for issue reporting | Running with `-vv` |
+| `.git/wt/logs/trace.jsonl` | Machine trace (one JSON object per record) | Running with `-vv` |
| `.git/wt/logs/subprocess.log` | Raw uncapped subprocess stdout/stderr (may be multi-MB) | Running with `-vv` |
| `.git/wt/logs/diagnostic.md` | Diagnostic report for issue reporting | Running with `-vv` |
| `.git/wt/trash/<name>-<timestamp>` | Staged worktree contents pending background deletion | `wt remove` |
diff --git a/src/cli/config.rs b/src/cli/config.rs
index a6de88d4d..731ae85cc 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -854,10 +854,11 @@ All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the
| File | Created when |
|------|-------------|
| `trace.log` | Running with `-vv` |
+| `trace.jsonl` | Running with `-vv` |
| `subprocess.log` | Running with `-vv` |
| `diagnostic.md` | Running with `-vv` |
-`trace.log` captures debug-level records at `-vv` — commands, `[wt-trace]` records, bounded subprocess previews. `wt config state logs profile` summarizes one into a performance report (where time went, parallelism, redundant commands). `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log` and a rendered performance profile; `wt` prints a `gh gist create` command pointing at it. All three are overwritten on each `-vv` run.
+`trace.log` is the human-readable trace at `-vv` — each command's start (`$ …`) and completion (`✓`/`✗ … 12.3ms`), in-process spans, milestones, and bounded subprocess previews. `trace.jsonl` is the same event stream as one JSON object per line, for machines (`jq`, chrome://tracing); `wt config state logs profile` reads it to summarize a performance report (where time went, parallelism, redundant commands). `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that inlines `trace.log` and a rendered performance profile; `wt` prints a `gh gist create` command pointing at it. All four are overwritten on each `-vv` run.
## Location
@@ -1301,13 +1302,13 @@ $ wt config state logs --format=json | jq '.hook_output[] | select(.branch | sta
)]
Get,
- /// Performance profile from a trace log
+ /// Performance profile from a trace
#[command(
- after_long_help = r#"Summarize where a single `wt` invocation spent its time, reading the `[wt-trace]` records captured to `trace.log` by a `-vv` run.
+ after_long_help = r#"Summarize where a single `wt` invocation spent its time, reading the records captured to `trace.jsonl` by a `-vv` run.
-Reads `.git/wt/logs/trace.log` by default, or a log file given as an argument (e.g. a CI artifact, or `-` for stdin). The report answers three questions: where time goes (subprocess time by command type, plus the slowest individual jobs), how parallel the run was (concurrency factor and peak concurrency), and where work was wasted (commands re-run with the same context). For a `wt list` capture it also shows derived latencies (time to skeleton, time to first result) and a timeline of collect milestones; the skeleton/first-result markers need a terminal (TTY) capture. `--format=json` emits the same data for scripting.
+Reads `.git/wt/logs/trace.jsonl` by default, or a trace given as an argument (e.g. a CI artifact, or `-` for stdin). The report answers three questions: where time goes (subprocess time by command type, plus the slowest individual jobs), how parallel the run was (concurrency factor and peak concurrency), and where work was wasted (commands re-run with the same context). For a `wt list` capture it also shows derived latencies (time to skeleton, time to first result) and a timeline of collect milestones; the skeleton/first-result markers need a terminal (TTY) capture. `--format=json` emits the same data for scripting.
-For an interactive timeline or a Perfetto trace, use the `wt-perf` helper (`cargo run -p wt-perf -- timeline`); both share the same trace parser.
+For an interactive timeline or a Perfetto trace, use the `wt-perf` helper (`cargo run -p wt-perf -- timeline`); both read the same `trace.jsonl`.
## Examples
@@ -1319,8 +1320,8 @@ $ wt config state logs profile
Profile a trace from elsewhere (e.g. a CI artifact), by path or on stdin:
```console
-$ wt config state logs profile ci-run.log
-$ wt config state logs profile - < ci-run.log
+$ wt config state logs profile ci-run.jsonl
+$ wt config state logs profile - < ci-run.jsonl
```
JSON for scripting:
@@ -1329,7 +1330,7 @@ $ wt config state logs profile --format=json | jq '.by_type[0]'
```"#
)]
Profile {
- /// Trace log to read (defaults to `.git/wt/logs/trace.log`; `-` for stdin)
+ /// Trace to read (defaults to `.git/wt/logs/trace.jsonl`; `-` for stdin)
file: Option<std::path::PathBuf>,
},
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 3515e8484..6ce680c96 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -646,7 +646,7 @@ pub fn handle_logs_list(format: SwitchFormat) -> anyhow::Result<()> {
}
/// `wt config state logs profile [FILE]` — summarize where a `-vv` run spent its
-/// time, from the `[wt-trace]` records in `trace.log` (or a given file / stdin).
+/// time, from the records in `trace.jsonl` (or a given file / stdin).
pub fn handle_logs_profile(file: Option<PathBuf>, format: SwitchFormat) -> anyhow::Result<()> {
let (input, source) = match file {
Some(ref p) if p.as_os_str() == "-" => {
@@ -656,21 +656,20 @@ pub fn handle_logs_profile(file: Option<PathBuf>, format: SwitchFormat) -> anyho
(buf, "stdin".to_string())
}
Some(p) => {
- let content = std::fs::read_to_string(&p).with_context(|| {
- format!("Failed to read trace log {}", format_path_for_display(&p))
- })?;
+ let content = std::fs::read_to_string(&p)
+ .with_context(|| format!("Failed to read trace {}", format_path_for_display(&p)))?;
(content, format_path_for_display(&p).to_string())
}
None => {
let repo = Repository::current().map_err(|_| {
anyhow::anyhow!(cformat!(
- "Not inside a git repository, so there's no default <bold>.git/wt/logs/trace.log</> to read; pass a trace log path or <bold>-</> for stdin"
+ "Not inside a git repository, so there's no default <bold>.git/wt/logs/trace.jsonl</> to read; pass a trace path or <bold>-</> for stdin"
))
})?;
- let path = repo.wt_logs_dir().join("trace.log");
+ let path = repo.wt_logs_dir().join("trace.jsonl");
let content = std::fs::read_to_string(&path).map_err(|_| {
anyhow::anyhow!(cformat!(
- "No trace log at <bold>{}</>; run a command with <bold>-vv</> to capture one",
+ "No trace at <bold>{}</>; run a command with <bold>-vv</> to capture one",
format_path_for_display(&path)
))
})?;
@@ -681,7 +680,7 @@ pub fn handle_logs_profile(file: Option<PathBuf>, format: SwitchFormat) -> anyho
let entries = worktrunk::trace::parse_lines(&input);
if entries.is_empty() {
anyhow::bail!(cformat!(
- "No [wt-trace] records in {source}; run a command with <bold>-vv</> to capture a trace"
+ "No trace records in {source}; run a command with <bold>-vv</> to capture a trace"
));
}
diff --git a/src/completion.rs b/src/completion.rs
index 95a4e401a..dc6ab7b5d 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -32,10 +32,10 @@ pub(crate) fn maybe_handle_env_completion() -> bool {
// Completion exits before `main`'s `logging::init`, so the normal
// `-v`/`-vv` pipeline never runs here. `WORKTRUNK_VERBOSE` opts this
// short-lived subprocess into the same logging as a flagged command — the
- // env-var equivalent of `-vv` — so `[wt-trace]` timing and `$ git …`
- // records for a slow completion land in `.git/wt/logs/` just as `-vv`
- // writes them. Left unset, completion stays silent so stray stderr never
- // lands above the user's prompt.
+ // env-var equivalent of `-vv` — so humanized timing (`✓ git …`) and
+ // `$ git …` start records for a slow completion land in `.git/wt/logs/`
+ // just as `-vv` writes them. Left unset, completion stays silent so stray
+ // stderr never lands above the user's prompt.
let completion_verbose = crate::logging::env_verbose_level();
if completion_verbose > 0 {
crate::logging::init(completion_verbose);
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index d4a6d2dcb..4a02b47c6 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -19,7 +19,7 @@
//! 2. **Environment** — wt version, OS, git version, shell integration
//! 3. **Worktrees** — Raw `git worktree list --porcelain` output
//! 4. **Config** — User and project config contents
-//! 5. **Performance profile** — Rendered view of `trace.log`: where time went,
+//! 5. **Performance profile** — Rendered view of `trace.jsonl`: where time went,
//! parallelism, and same-context cache misses (omitted if no records)
//! 6. **Verbose log** — Debug log output, truncated to ~50KB if large
//!
@@ -35,7 +35,7 @@
//! # File Location
//!
//! Reports are written to `<git-common-dir>/wt/logs/diagnostic.md` (typically
-//! `.git/wt/logs/diagnostic.md`). Companion log files (`trace.log`, `subprocess.log`) live in the same directory.
+//! `.git/wt/logs/diagnostic.md`). Companion log files (`trace.log`, `trace.jsonl`, `subprocess.log`) live in the same directory.
//!
//! # Usage
//!
@@ -181,7 +181,13 @@ impl DiagnosticReport {
.as_deref()
.map(|content| truncate_log(content.trim()))
.filter(|s| !s.is_empty());
- let performance_profile = trace_content.as_deref().and_then(render_trace_profile);
+ // The profile is derived from the machine `trace.jsonl` (the human
+ // `trace.log` inlined above is no longer parseable).
+ let performance_profile = crate::log_files::TRACE_JSONL
+ .path()
+ .and_then(|path| std::fs::read_to_string(&path).ok())
+ .as_deref()
+ .and_then(render_trace_profile);
// Forward slashes on both platforms so the rendered markdown reads the
// same in bug reports regardless of where it was produced.
let subprocess_log_path = crate::log_files::SUBPROCESS
@@ -317,15 +323,15 @@ fn is_gh_installed() -> bool {
}
/// Render the captured trace as a human-readable performance profile for the
-/// report — a derived view of `trace.log` (where time went, parallelism,
+/// report — a derived view of `trace.jsonl` (where time went, parallelism,
/// same-context cache misses), ANSI-stripped for the markdown bundle. `None`
-/// when the capture has no `[wt-trace]` records, so the section is omitted.
-fn render_trace_profile(trace_content: &str) -> Option<String> {
- let entries = worktrunk::trace::parse_lines(trace_content);
+/// when the capture has no trace records, so the section is omitted.
+fn render_trace_profile(trace_jsonl: &str) -> Option<String> {
+ let entries = worktrunk::trace::parse_lines(trace_jsonl);
if entries.is_empty() {
return None;
}
- let rendered = worktrunk::trace::Profile::from_entries(&entries).render_text("trace.log");
+ let rendered = worktrunk::trace::Profile::from_entries(&entries).render_text("trace.jsonl");
Some(rendered.ansi_strip().to_string())
}
@@ -475,8 +481,8 @@ mod tests {
#[test]
fn test_render_trace_profile_summarizes_records() {
- let trace = r#"[wt-trace] ts=1000 tid=1 context=main cmd="git status" dur_us=12000 ok=true
-[wt-trace] ts=1000 tid=2 context=feature cmd="git status" dur_us=8000 ok=true
+ let trace = r#"{"kind":"cmd_completed","ts":1000,"tid":1,"context":"main","cmd":"git status","dur_us":12000,"ok":true}
+{"kind":"cmd_completed","ts":1000,"tid":2,"context":"feature","cmd":"git status","dur_us":8000,"ok":true}
"#;
let rendered = render_trace_profile(trace).expect("records present");
assert!(rendered.contains("PERFORMANCE PROFILE"), "{rendered}");
diff --git a/src/log_files.rs b/src/log_files.rs
index bdbf84a81..8c6ee1766 100644
--- a/src/log_files.rs
+++ b/src/log_files.rs
@@ -2,20 +2,22 @@
//!
//! At `-vv`, three files are written in the repo's `.git/wt/logs/` directory:
//!
-//! - [`TRACE`] → `trace.log`: structured records, `$ cmd [context]`
-//! headers, and bounded subprocess previews. High-signal, bounded size —
-//! safe to embed in `diagnostic.md` bug reports.
+//! - [`TRACE`] → `trace.log`: the human trace — a command's start echo
+//! `$ cmd [context]` paired with its finish line `✓ cmd [context] dur`
+//! (`✗` on failure), in-process spans (`◷ name dur`), milestones
+//! (`· event`), and bounded subprocess previews. High-signal, bounded
+//! size — safe to embed in `diagnostic.md` bug reports.
//! - [`TRACE_JSONL`] → `trace.jsonl`: the same event stream as `trace.log`
-//! (minus the command output), but one JSON object per line instead of the
-//! text grammar. Each event's fields serialize generically: a `[wt-trace]`
+//! (minus the command output), but one JSON object per line — the machine
+//! format. Each event's fields serialize generically: a `[wt-trace]`
//! record comes through rich (`cmd`, `seq`, `dur_us`, …), a free-form
//! `log::*` line as `{"message":…}` until its call site is given fields.
-//! Machine-first (agents, `jq`); written alongside `trace.log`, not in
-//! place of it.
+//! Machine-first (agents, `jq`, `src/trace/parse.rs`); written alongside
+//! `trace.log`, not in place of it.
//! - [`SUBPROCESS`] → `subprocess.log`: raw, uncapped subprocess
//! stdout/stderr bodies captured by `shell_exec::Cmd`, each block
//! introduced by a `$ cmd … [seq=N tid=T]` header whose `seq` joins it to
-//! the command's `[wt-trace]` record in `trace.log`. Potentially multi-MB
+//! the command's record in `trace.jsonl`. Potentially multi-MB
//! (full `git log -p` / patch-id output); opt-in for deep dives.
//!
//! Direct user-facing output (`info_message` / `eprintln!` from command
diff --git a/src/logging.rs b/src/logging.rs
index fe0b62ade..8d9276efd 100644
--- a/src/logging.rs
+++ b/src/logging.rs
@@ -6,11 +6,17 @@
//!
//! | layer | filter | format |
//! | ---------------- | --------------------------------------------------- | ----------------- |
-//! | stderr | `$RUST_LOG` or flag baseline (`Off`/`Info`/`Info`) | styled with ANSI |
-//! | `trace.log` | `-vv` only, excludes `SUBPROCESS_FULL_TARGET` | plain text |
-//! | `trace.jsonl` | `-vv` only, excludes both subprocess targets | one JSON object per event |
+//! | stderr | `$RUST_LOG` or flag baseline (`Off`/`Info`/`Info`) | human, ANSI-styled |
+//! | `trace.log` | `-vv` only, excludes `SUBPROCESS_FULL_TARGET` | human, plain text |
+//! | `trace.jsonl` | `-vv` only, excludes both subprocess targets | one JSON object per event (machine) |
//! | `subprocess.log` | `-vv` only, includes only `SUBPROCESS_FULL_TARGET` | raw bodies + `$ cmd … seq=N` headers |
//!
+//! The two human routes (stderr, `trace.log`) render `[wt-trace]` records as
+//! readable lines (`✓ git status [wt] 12.3ms`); `trace.jsonl` is the sole
+//! machine sink, carrying the full structured fields that `src/trace/parse.rs`
+//! and `wt-perf` consume. So the human and machine formats are decoupled — the
+//! human lines never carry `key=value` clutter, and a parser never reads them.
+//!
//! At `-vv` the stderr layer keeps its Info baseline — `-vv` is a strict
//! superset of `-v`, with Debug-level records (the noisy ones, including
//! the bounded subprocess preview) routed to the file layers only.
@@ -30,6 +36,7 @@
use std::borrow::Cow;
use std::fmt::{self, Write as _};
+use std::time::Duration;
use color_print::cformat;
use tracing::{Event, Subscriber};
@@ -101,16 +108,31 @@ fn event_message(event: &Event<'_>) -> String {
/// Pure helper: render a single log message for stderr with the thread
/// label and the styling rules `StderrFormat` applies. Factored out so the
-/// branches (`$ cmd [ctx]`, `$ cmd`, ` ! err`, plain) can be unit-tested
-/// without standing up a `tracing` subscriber.
+/// branches (`$ cmd [ctx]`, `✓ cmd [ctx] dur`, ` ! err`, plain) can be
+/// unit-tested without standing up a `tracing` subscriber.
fn style_stderr_line(thread_num: char, msg: &str) -> String {
- if let Some(rest) = msg.strip_prefix("$ ") {
- // Standalone tools (gh, glab) emit no `[ctx]` suffix.
- let (command, worktree) = match rest.find(" [") {
+ // Command framing lines share one shape: a leading glyph, then the
+ // command, then an optional `[context]` and trailing detail. `$` opens a
+ // command; `✓`/`✗` report its completion (the humanized wt-trace records).
+ // Bolding the command on all three makes a start line and its finish line
+ // read as a pair.
+ let framed = ['$', '✓', '✗'].into_iter().find_map(|glyph| {
+ msg.strip_prefix(glyph)?
+ .strip_prefix(' ')
+ .map(|r| (glyph, r))
+ });
+ if let Some((glyph, rest)) = framed {
+ // The command ends at the earliest separator: ` [` before a context,
+ // or ` ` before a duration (standalone tools like gh emit neither).
+ let boundary = [rest.find(" ["), rest.find(" ")]
+ .into_iter()
+ .flatten()
+ .min();
+ let (command, tail) = match boundary {
Some(pos) => (&rest[..pos], &rest[pos..]),
None => (rest, ""),
};
- cformat!("<dim>[{thread_num}]</> $ <bold>{command}</>{worktree}")
+ cformat!("<dim>[{thread_num}]</> {glyph} <bold>{command}</>{tail}")
} else if msg.starts_with(" ! ") {
cformat!("<dim>[{thread_num}]</> <red>{msg}</>")
} else {
@@ -118,11 +140,12 @@ fn style_stderr_line(thread_num: char, msg: &str) -> String {
}
}
-/// Stderr formatter: replicates the legacy env_logger styling pre-migration.
+/// Stderr formatter for the human routes.
///
-/// `$ cmd [worktree]` headers bold the command. ` ! …` continuation lines
-/// (subprocess stderr) are reddened. Everything else gets the thread-label
-/// prefix.
+/// `$ cmd [worktree]` start lines and `✓`/`✗ cmd …` finish lines bold the
+/// command (so a command's start and finish read as a pair). ` ! …`
+/// continuation lines (subprocess stderr) are reddened. Everything else gets
+/// the thread-label prefix.
struct StderrFormat;
impl<S, N> FormatEvent<S, N> for StderrFormat
@@ -142,15 +165,16 @@ where
}
}
-/// Render an event to its single-line text payload — `[wt-trace]` grammar
-/// for events under [`WT_TRACE_TARGET`], the raw `message` field for
-/// everything else. Shared between the stderr and `trace.log` formatters so
-/// `[wt-trace]` records appear in both routes (`-vv` writes to the file;
-/// `RUST_LOG=debug -v` surfaces them on stderr).
+/// Render an event to its single-line human text payload — the humanized
+/// `[wt-trace]` line ([`format_wt_trace`]) for events under
+/// [`WT_TRACE_TARGET`], the raw `message` field for everything else. Shared
+/// between the stderr and `trace.log` formatters so `[wt-trace]` records read
+/// the same in both routes (`-vv` writes to the file; `RUST_LOG=debug -v`
+/// surfaces them on stderr).
///
/// Control bytes are escaped here ([`escape_controls`]) — this is the single
/// chokepoint feeding both human-facing routes, so raw NUL/ESC from subprocess
-/// output (e.g. the bounded preview of `git … -z`, or a `cmd=`/`err=` field
+/// output (e.g. the bounded preview of `git … -z`, or a `cmd`/`err` field
/// carrying captured bytes) can't ride into the terminal or `trace.log`, and
/// thus can't break the gist upload of the `diagnostic.md` that inlines
/// `trace.log`. `subprocess.log` keeps raw bytes verbatim: it renders via
@@ -173,13 +197,13 @@ fn render_event_message(event: &Event<'_>) -> String {
}
/// `trace.log` formatter: plain `[<thread>] <message>`, no ANSI, one line
-/// per event. Matches the on-disk layout pre-migration.
+/// per event — the human-readable trace artifact.
///
-/// Events under [`WT_TRACE_TARGET`] are rendered via the dedicated
-/// `[wt-trace] key=value` grammar in [`format_wt_trace`]; everything else
-/// falls through to the legacy message-prefix shape. This is the only place
-/// the `[wt-trace]` text format lives — emit sites in `trace::emit` carry
-/// structured fields, not pre-formatted strings.
+/// Events under [`WT_TRACE_TARGET`] are rendered as humanized lines by
+/// [`format_wt_trace`]; everything else falls through to the message-prefix
+/// shape. This is the only place the human trace line lives — emit sites in
+/// `trace::emit` carry structured fields, not pre-formatted strings, and the
+/// machine grammar lives in `trace.jsonl`.
struct TraceFileFormat;
impl<S, N> FormatEvent<S, N> for TraceFileFormat
@@ -199,24 +223,21 @@ where
}
}
-/// Captured fields from a single `WT_TRACE_TARGET` event. The visitor reads
-/// each field by name and stores its value typed — the layer renderer then
-/// composes the final `[wt-trace] …` line in the exact field order
-/// downstream parsers expect.
+/// Captured fields from a single `WT_TRACE_TARGET` event, for the human
+/// `trace.log` / stderr render. The visitor reads each field by name and
+/// stores its value typed; the layer renderer then composes the humanized
+/// line.
///
-/// Unknown fields are dropped; the wt-trace grammar is closed (every key
-/// has a fixed meaning).
+/// Only the fields the human line shows are captured — `ts`/`tid`/`seq` are
+/// machine-only (the `[thread]` prefix already names the thread) and stay in
+/// `trace.jsonl`, which serializes every field via its own generic visitor.
+/// Unknown fields are dropped; the wt-trace grammar is closed (every key has
+/// a fixed meaning).
#[derive(Default)]
struct WtTraceFields {
kind: Option<String>,
- ts: Option<u64>,
- tid: Option<u64>,
- seq: Option<u64>,
dur_us: Option<u64>,
ok: Option<bool>,
- /// `true` when the command consumed stdin uncaptured by `cmd`; rendered as a
- /// trailing `stdin=true` only when true (omitted otherwise, like `context`).
- stdin: Option<bool>,
context: Option<String>,
cmd: Option<String>,
err: Option<String>,
@@ -226,20 +247,14 @@ struct WtTraceFields {
impl tracing::field::Visit for WtTraceFields {
fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
- match field.name() {
- "ts" => self.ts = Some(value),
- "tid" => self.tid = Some(value),
- "seq" => self.seq = Some(value),
- "dur_us" => self.dur_us = Some(value),
- _ => {}
+ if field.name() == "dur_us" {
+ self.dur_us = Some(value);
}
}
fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
- match field.name() {
- "ok" => self.ok = Some(value),
- "stdin" => self.stdin = Some(value),
- _ => {}
+ if field.name() == "ok" {
+ self.ok = Some(value);
}
}
@@ -273,77 +288,47 @@ impl WtTraceFields {
}
}
-/// Render structured fields as the `[wt-trace] key=value …` text wt-perf
-/// and the integration tests parse. The field order per `kind` is the
-/// contract; see `src/trace/parse.rs` for the consumer.
+/// Render a `[wt-trace]` event as a human line for `trace.log` / stderr, with
+/// one rendering of `cmd [context]` across every line type so a command's
+/// start echo (`$ …`) and finish record (`✓ …`/`✗ …`) read as a pair:
+///
+/// ```text
+/// ✓ git status [worktree] 12.3ms cmd_completed, ok=true
+/// ✗ git merge-base [main] 1.1s cmd_completed, ok=false
+/// ✗ git rev-list [.] 100ms fatal: … cmd_errored
+/// · Showed skeleton instant (milestone)
+/// ◷ build_hook_context 8.2ms span (in-process)
+/// ```
///
-/// A malformed event (missing required fields, unknown `kind`) renders the
-/// best-effort string `[wt-trace] kind=<…> <repr>` so a future-added kind
-/// produces a noticeable but parseable line rather than silently vanishing.
+/// The leading glyph names the line type at a glance; durations render via
+/// `Duration`'s compact `Debug` (`999µs`/`12.3ms`/`1.5s`). Machine fields
+/// (`ts`/`tid`/`seq`) live only in `trace.jsonl` (see [`event_json`]). A
+/// malformed or future `kind` renders a best-effort `· <kind>` line rather
+/// than vanishing.
fn format_wt_trace(f: &WtTraceFields) -> String {
- // `ts` and `tid` are required for every kind; default to 0 to keep the
- // line shape valid if a future emit site forgets one — the parser will
- // still accept it, and the missing field shows up as `0` in the
- // timeline rather than disappearing.
- let ts = f.ts.unwrap_or(0);
- let tid = f.tid.unwrap_or(0);
+ let dur = |dur_us: Option<u64>| format!("{:?}", Duration::from_micros(dur_us.unwrap_or(0)));
+ let with_context = |cmd: &str| match &f.context {
+ Some(ctx) => format!("{cmd} [{ctx}]"),
+ None => cmd.to_string(),
+ };
+ let cmd = || with_context(f.cmd.as_deref().unwrap_or(""));
match f.kind.as_deref() {
Some("cmd_completed") => {
- let seq = f.seq.unwrap_or(0);
- let cmd = f.cmd.as_deref().unwrap_or("");
- let dur_us = f.dur_us.unwrap_or(0);
- let ok = f.ok.unwrap_or(false);
- // Only commands that read stdin carry the marker; omit it otherwise
- // so the overwhelmingly common no-stdin record stays lean.
- let stdin = if f.stdin == Some(true) {
- " stdin=true"
- } else {
- ""
- };
- match &f.context {
- Some(ctx) => format!(
- r#"[wt-trace] ts={ts} tid={tid} seq={seq} context={ctx} cmd="{cmd}" dur_us={dur_us} ok={ok}{stdin}"#
- ),
- None => {
- format!(
- r#"[wt-trace] ts={ts} tid={tid} seq={seq} cmd="{cmd}" dur_us={dur_us} ok={ok}{stdin}"#
- )
- }
- }
+ let glyph = if f.ok.unwrap_or(false) { '✓' } else { '✗' };
+ format!("{glyph} {} {}", cmd(), dur(f.dur_us))
}
Some("cmd_errored") => {
- let seq = f.seq.unwrap_or(0);
- let cmd = f.cmd.as_deref().unwrap_or("");
- let dur_us = f.dur_us.unwrap_or(0);
- let err = f.err.as_deref().unwrap_or("");
- let stdin = if f.stdin == Some(true) {
- " stdin=true"
- } else {
- ""
- };
- match &f.context {
- Some(ctx) => format!(
- r#"[wt-trace] ts={ts} tid={tid} seq={seq} context={ctx} cmd="{cmd}" dur_us={dur_us} err="{err}"{stdin}"#
- ),
- None => format!(
- r#"[wt-trace] ts={ts} tid={tid} seq={seq} cmd="{cmd}" dur_us={dur_us} err="{err}"{stdin}"#
- ),
- }
+ format!(
+ "✗ {} {} {}",
+ cmd(),
+ dur(f.dur_us),
+ f.err.as_deref().unwrap_or("")
+ )
}
- Some("instant") => {
- let event = f.event.as_deref().unwrap_or("");
- format!(r#"[wt-trace] ts={ts} tid={tid} event="{event}""#)
- }
- Some("span") => {
- let name = f.span.as_deref().unwrap_or("");
- let dur_us = f.dur_us.unwrap_or(0);
- format!(r#"[wt-trace] ts={ts} tid={tid} span="{name}" dur_us={dur_us}"#)
- }
- other => format!(
- r#"[wt-trace] ts={ts} tid={tid} kind={kind:?}"#,
- kind = other.unwrap_or("<unknown>")
- ),
+ Some("instant") => format!("· {}", f.event.as_deref().unwrap_or("")),
+ Some("span") => format!("◷ {} {}", f.span.as_deref().unwrap_or(""), dur(f.dur_us)),
+ other => format!("· {}", other.unwrap_or("<unknown>")),
}
}
@@ -831,28 +816,46 @@ mod tests {
/// the assertions don't tangle with `cformat!`'s exact escape bytes.
#[test]
fn style_stderr_covers_each_shape() {
+ let stripped = |t, msg| style_stderr_line(t, msg).ansi_strip().into_owned();
+
// `$ cmd [ctx]` — git path with worktree context.
- let cmd_ctx = style_stderr_line('a', "$ git status [feature]")
- .ansi_strip()
- .into_owned();
- assert_eq!(cmd_ctx, "[a] $ git status [feature]");
-
- // `$ cmd` with no `[ctx]` — standalone tools (gh, glab) emit this
- // shape; was line 109 in the codecov gap.
- let cmd_no_ctx = style_stderr_line('b', "$ gh pr list")
- .ansi_strip()
- .into_owned();
- assert_eq!(cmd_no_ctx, "[b] $ gh pr list");
+ assert_eq!(
+ stripped('a', "$ git status [feature]"),
+ "[a] $ git status [feature]"
+ );
+
+ // `$ cmd` with no `[ctx]` — standalone tools (gh, glab) emit this shape.
+ assert_eq!(stripped('b', "$ gh pr list"), "[b] $ gh pr list");
+
+ // `✓ cmd [ctx] dur` — a finish line pairs with its `$` start line
+ // (same `cmd [ctx]` rendering, command bolded under the new glyph).
+ assert_eq!(
+ stripped('c', "✓ git status [feature] 12.3ms"),
+ "[c] ✓ git status [feature] 12.3ms"
+ );
+
+ // `✗ cmd [ctx] dur err` — a failed command; the duration and error
+ // tail stay unbolded (command boundary is the earliest of ` [` / ` `).
+ assert_eq!(
+ stripped('d', "✗ git rev-list [.] 100ms fatal: bad revision"),
+ "[d] ✗ git rev-list [.] 100ms fatal: bad revision"
+ );
+
+ // `✓ cmd dur` with no `[ctx]` — boundary falls on the ` ` before dur.
+ assert_eq!(
+ stripped('e', "✓ gh pr list 45ms"),
+ "[e] ✓ gh pr list 45ms"
+ );
// ` ! …` — subprocess stderr continuation, red-styled.
- let err = style_stderr_line('c', " ! fatal: bad ref")
- .ansi_strip()
- .into_owned();
- assert_eq!(err, "[c] ! fatal: bad ref");
-
- // Plain — everything else falls through with just the thread prefix.
- let plain = style_stderr_line('d', "hello").ansi_strip().into_owned();
- assert_eq!(plain, "[d] hello");
+ assert_eq!(
+ stripped('f', " ! fatal: bad ref"),
+ "[f] ! fatal: bad ref"
+ );
+
+ // `· event` (instant) and plain text fall through with just the prefix.
+ assert_eq!(stripped('g', "· Showed skeleton"), "[g] · Showed skeleton");
+ assert_eq!(stripped('h', "hello"), "[h] hello");
}
/// Drive `WtTraceFields::Visit` end-to-end via a temporary subscriber:
@@ -883,12 +886,12 @@ mod tests {
let events: Arc<Mutex<Vec<WtTraceFields>>> = Arc::new(Mutex::new(Vec::new()));
let subscriber = Registry::default().with(Capture(events.clone()));
tracing::subscriber::with_default(subscriber, || {
- // u64 (ts/tid/dur_us) + unknown_u64 → `_` arm in record_u64
+ // u64 (dur_us) + ignored u64 (ts/tid are machine-only now, dropped
+ // by the human visitor's non-`dur_us` arm)
tracing::debug!(
target: WT_TRACE_TARGET,
+ dur_us = 12300u64,
ts = 7u64,
- tid = 3u64,
- unknown_u64 = 42u64,
);
// bool (ok)
tracing::debug!(target: WT_TRACE_TARGET, ok = true);
@@ -904,164 +907,88 @@ mod tests {
});
let captured = events.lock().unwrap();
- assert_eq!(captured[0].ts, Some(7));
- assert_eq!(captured[0].tid, Some(3));
+ assert_eq!(captured[0].dur_us, Some(12300));
assert_eq!(captured[1].ok, Some(true));
assert_eq!(captured[2].cmd.as_deref(), Some("git status"));
assert_eq!(captured[3].err.as_deref(), Some("fatal: bad ref"));
}
- /// Lock the `[wt-trace]` wire grammar produced by `format_wt_trace`.
- /// wt-perf and the integration suite parse these lines; any drift here
- /// breaks downstream tooling, so each `kind` gets a fixture assertion.
+ /// Lock the humanized line `format_wt_trace` produces for each `kind`.
+ /// This is the human `trace.log` / stderr render; the machine grammar
+ /// lives in `trace.jsonl` (`event_json`), parsed by `src/trace/parse.rs`.
#[test]
fn format_wt_trace_renders_each_kind() {
- // cmd_completed with context
+ // cmd_completed with context (ok=true → ✓), duration compacted by
+ // Duration's Debug (12300µs → 12.3ms).
let f = WtTraceFields {
kind: Some("cmd_completed".into()),
- ts: Some(100),
- tid: Some(3),
- seq: Some(1),
context: Some("worktree".into()),
cmd: Some("git status".into()),
dur_us: Some(12300),
ok: Some(true),
..Default::default()
};
- assert_eq!(
- format_wt_trace(&f),
- r#"[wt-trace] ts=100 tid=3 seq=1 context=worktree cmd="git status" dur_us=12300 ok=true"#
- );
+ assert_eq!(format_wt_trace(&f), "✓ git status [worktree] 12.3ms");
- // cmd_completed without context
+ // cmd_completed without context (ok=false → ✗)
let f = WtTraceFields {
kind: Some("cmd_completed".into()),
- ts: Some(100),
- tid: Some(3),
- seq: Some(2),
cmd: Some("gh pr list".into()),
dur_us: Some(45200),
ok: Some(false),
..Default::default()
};
- assert_eq!(
- format_wt_trace(&f),
- r#"[wt-trace] ts=100 tid=3 seq=2 cmd="gh pr list" dur_us=45200 ok=false"#
- );
+ assert_eq!(format_wt_trace(&f), "✗ gh pr list 45.2ms");
- // cmd_errored with context
+ // cmd_errored with context — the error message tails the line
let f = WtTraceFields {
kind: Some("cmd_errored".into()),
- ts: Some(100),
- tid: Some(3),
- seq: Some(3),
context: Some("main".into()),
cmd: Some("git merge-base".into()),
dur_us: Some(100000),
- err: Some("fatal: ...".into()),
+ err: Some("fatal: no merge base".into()),
..Default::default()
};
assert_eq!(
format_wt_trace(&f),
- r#"[wt-trace] ts=100 tid=3 seq=3 context=main cmd="git merge-base" dur_us=100000 err="fatal: ...""#
+ "✗ git merge-base [main] 100ms fatal: no merge base"
);
// cmd_errored without context (standalone tools like gh)
let f = WtTraceFields {
kind: Some("cmd_errored".into()),
- ts: Some(100),
- tid: Some(3),
- seq: Some(4),
cmd: Some("gh pr list".into()),
dur_us: Some(1000),
err: Some("network down".into()),
..Default::default()
};
- assert_eq!(
- format_wt_trace(&f),
- r#"[wt-trace] ts=100 tid=3 seq=4 cmd="gh pr list" dur_us=1000 err="network down""#
- );
+ assert_eq!(format_wt_trace(&f), "✗ gh pr list 1ms network down");
- // cmd_completed reading stdin — `stdin=true` trails the record; a
- // stdin-less record (stdin None/Some(false)) omits the field entirely,
- // as every fixture above shows.
- let f = WtTraceFields {
- kind: Some("cmd_completed".into()),
- ts: Some(100),
- tid: Some(3),
- seq: Some(5),
- cmd: Some("git patch-id --verbatim".into()),
- dur_us: Some(640),
- ok: Some(true),
- stdin: Some(true),
- ..Default::default()
- };
- assert_eq!(
- format_wt_trace(&f),
- r#"[wt-trace] ts=100 tid=3 seq=5 cmd="git patch-id --verbatim" dur_us=640 ok=true stdin=true"#
- );
-
- // cmd_errored reading stdin — `stdin=true` trails the err field.
- let f = WtTraceFields {
- kind: Some("cmd_errored".into()),
- ts: Some(100),
- tid: Some(3),
- seq: Some(6),
- cmd: Some("claude -p".into()),
- dur_us: Some(900),
- err: Some("boom".into()),
- stdin: Some(true),
- ..Default::default()
- };
- assert_eq!(
- format_wt_trace(&f),
- r#"[wt-trace] ts=100 tid=3 seq=6 cmd="claude -p" dur_us=900 err="boom" stdin=true"#
- );
-
- // instant
+ // instant (milestone) — `·`, no duration
let f = WtTraceFields {
kind: Some("instant".into()),
- ts: Some(100),
- tid: Some(3),
event: Some("Showed skeleton".into()),
..Default::default()
};
- assert_eq!(
- format_wt_trace(&f),
- r#"[wt-trace] ts=100 tid=3 event="Showed skeleton""#
- );
+ assert_eq!(format_wt_trace(&f), "· Showed skeleton");
- // span
+ // span (in-process) — `◷` with duration
let f = WtTraceFields {
kind: Some("span".into()),
- ts: Some(100),
- tid: Some(3),
span: Some("build_hook_context".into()),
dur_us: Some(8200),
..Default::default()
};
- assert_eq!(
- format_wt_trace(&f),
- r#"[wt-trace] ts=100 tid=3 span="build_hook_context" dur_us=8200"#
- );
+ assert_eq!(format_wt_trace(&f), "◷ build_hook_context 8.2ms");
- // Defensive fallback: a future kind not yet known to the renderer
- // emits a parseable record rather than silently vanishing.
+ // Defensive fallback: a future/unknown kind renders a visible line
+ // rather than silently vanishing.
let f = WtTraceFields {
kind: Some("future_kind".into()),
- ts: Some(100),
- tid: Some(3),
..Default::default()
};
- assert_eq!(
- format_wt_trace(&f),
- r#"[wt-trace] ts=100 tid=3 kind="future_kind""#
- );
- let f = WtTraceFields::default();
- assert_eq!(
- format_wt_trace(&f),
- r#"[wt-trace] ts=0 tid=0 kind="<unknown>""#
- );
+ assert_eq!(format_wt_trace(&f), "· future_kind");
+ assert_eq!(format_wt_trace(&WtTraceFields::default()), "· <unknown>");
}
/// `event_json` serializes whatever typed fields an event carries, then
diff --git a/src/trace/emit.rs b/src/trace/emit.rs
index 7d700f02c..6b1ee9a92 100644
--- a/src/trace/emit.rs
+++ b/src/trace/emit.rs
@@ -1,43 +1,38 @@
-//! Authoritative emitter for the `[wt-trace]` log grammar.
+//! Authoritative emitter for `[wt-trace]` records.
//!
-//! `[wt-trace]` records are structured single-line `key=value` text emitted on
-//! top of `tracing` and parsed downstream by [`super::parse`] and the
-//! `wt-perf` binary. This module is the single source of truth for the
-//! grammar — any field or formatting change happens here and in `parse.rs`
-//! together.
-//!
-//! # Format
+//! Records emit as `tracing` events under [`WT_TRACE_TARGET`] with typed
+//! structured fields; the logging layers in `src/logging.rs` render them two
+//! ways. This module is the single source of truth for the fields — any field
+//! change happens here.
//!
-//! ```text
-//! [wt-trace] ts=1234567 tid=3 seq=1 context=worktree cmd="git status" dur_us=12300 ok=true
-//! [wt-trace] ts=1234567 tid=3 seq=2 cmd="gh pr list" dur_us=45200 ok=false
-//! [wt-trace] ts=1234567 tid=3 seq=3 context=main cmd="git merge-base" dur_us=100000 err="fatal: ..."
-//! [wt-trace] ts=1234567 tid=3 seq=4 cmd="git patch-id --verbatim" dur_us=640 ok=true stdin=true
-//! [wt-trace] ts=1234567 tid=3 event="Showed skeleton"
-//! [wt-trace] ts=1234567 tid=3 span="build_hook_context" dur_us=8200
-//! ```
+//! # Two renderings, decoupled
//!
-//! `stdin=true` (command records only) marks a command that consumed stdin not
-//! captured in `cmd`; it trails `ok`/`err` and is omitted when false. See
-//! [`CommandTrace::reads_stdin`].
+//! - **Human** (`trace.log`, and stderr at `RUST_LOG=debug`): a readable line
+//! per record, where a command's start echo and finish record pair up —
+//! `✓ git status [worktree] 12.3ms` / `✗ …`, `· Showed skeleton`,
+//! `◷ build_hook_context 8.2ms`. Rendered by `logging.rs::format_wt_trace`.
+//! - **Machine** (`trace.jsonl`): one JSON object per record, carrying every
+//! field — `{"kind":"cmd_completed","ts":…,"tid":…,"seq":…,"cmd":…,"dur_us":…,"ok":…}`.
+//! Rendered by `logging.rs::event_json`, and parsed back by [`super::parse`]
+//! and the `wt-perf` binary. This is the sole format any tool reads.
//!
-//! `seq` is a process-global monotonic command counter (command records only).
-//! The same value is printed into the per-command header in `subprocess.log`,
-//! so a raw output block there joins back to its command record here.
+//! Keeping the human and machine formats separate means the readable lines
+//! never carry `key=value` clutter and a parser never reads them.
//!
-//! # Emission model
+//! # Fields
//!
-//! Records emit as `tracing` events under [`WT_TRACE_TARGET`] with typed
-//! structured fields (`kind`, `ts`, `tid`, `seq`, `cmd`, `dur_us`, `ok`, `err`,
-//! `event`, `span`, `context`). The text grammar is produced downstream by
-//! the `trace.log` layer's `FormatEvent` impl in
-//! `src/logging.rs::TraceFileFormat`, which reads the structured fields
-//! and renders the exact `[wt-trace] key=value …` lines wt-perf and the
-//! integration suite parse.
+//! Typed structured fields on each event: `kind`, `ts`, `tid`, `seq`, `cmd`,
+//! `dur_us`, `ok`, `err`, `event`, `span`, `context`, `stdin`. `seq` is a
+//! process-global monotonic command counter (command records only); the same
+//! value is printed into the per-command header in `subprocess.log`, so a raw
+//! output block there joins back to its command record via the `seq` field in
+//! `trace.jsonl`. `stdin` (command records, [`CommandTrace::reads_stdin`])
+//! marks a command that consumed stdin the `cmd` string doesn't capture, so the
+//! cache analysis in `super::profile` can skip it — `trace.jsonl` carries it;
+//! the human line omits it.
//!
-//! This split — structured fields at the emission site, grammar rendering
-//! at the layer — means the wire format lives in one place
-//! (`logging.rs`) and emit sites carry no string-formatting noise.
+//! This split — structured fields at the emission site, rendering at the
+//! layer — means emit sites carry no string-formatting noise.
//!
//! # The subprocess chokepoint: [`CommandTrace`]
//!
@@ -121,9 +116,9 @@ pub fn thread_id() -> u64 {
}
/// Process-global monotonic command counter. Each [`CommandTrace`] claims the
-/// next value at construction; the same `seq` is printed into the `[wt-trace]`
-/// record in `trace.log` and the per-command header in `subprocess.log`, so a
-/// raw output block can be joined back to its command record. Claimed at
+/// next value at construction; the same `seq` is recorded in the `trace.jsonl`
+/// record and the per-command header in `subprocess.log`, so a raw output block
+/// can be joined back to its command record. Claimed at
/// construction (outside any verbosity gate) so the sequence is dense
/// regardless of whether the file layers are active. Starts at 1.
static CMD_SEQ: AtomicU64 = AtomicU64::new(1);
@@ -270,7 +265,7 @@ impl CommandTrace {
}
/// The command's monotonic sequence number — the key shared by this
- /// command's `[wt-trace]` record (`trace.log`) and its raw output block
+ /// command's `trace.jsonl` record and its raw output block
/// (`subprocess.log`).
pub(crate) fn seq(&self) -> u64 {
self.seq
diff --git a/src/trace/mod.rs b/src/trace/mod.rs
index f0a0d985b..d3543694c 100644
--- a/src/trace/mod.rs
+++ b/src/trace/mod.rs
@@ -20,8 +20,8 @@
//! # fire even though wt-perf pipes wt's stdout to /dev/null)
//! cargo run -p wt-perf -- timeline --chrome -- list --progressive > trace.json
//!
-//! # From a log already captured to disk
-//! cargo run -p wt-perf -- trace < captured.log > trace.json
+//! # From a trace.jsonl already captured to disk
+//! cargo run -p wt-perf -- trace .git/wt/logs/trace.jsonl > trace.json
//!
//! # Analyze with SQL (requires: curl -LO https://get.perfetto.dev/trace_processor)
//! trace_processor trace.json -Q 'SELECT name, COUNT(*), SUM(dur)/1e6 as ms FROM slice GROUP BY name'
diff --git a/src/trace/parse.rs b/src/trace/parse.rs
index 0291c440d..a5fff4b5b 100644
--- a/src/trace/parse.rs
+++ b/src/trace/parse.rs
@@ -1,33 +1,31 @@
-//! Parse wt-trace log lines into structured entries.
+//! Parse `trace.jsonl` records into structured entries.
//!
-//! Trace lines are emitted by `shell_exec::Cmd` with this format:
-//! ```text
-//! [wt-trace] ts=1234567 tid=3 seq=1 context=worktree cmd="git status" dur_us=12300 ok=true
-//! [wt-trace] ts=1234567 tid=3 seq=2 cmd="gh pr list" dur_us=45200 ok=false
-//! [wt-trace] ts=1234567 tid=3 seq=3 context=main cmd="git merge-base" dur_us=100000 err="fatal: ..."
-//! [wt-trace] ts=1234567 tid=3 seq=4 cmd="git patch-id --verbatim" dur_us=640 ok=true stdin=true
-//! ```
-//!
-//! `stdin=true` (command records only) flags a command that consumed stdin not
-//! captured in `cmd` — a `stdin_bytes` buffer or an upstream pipe. It trails the
-//! `ok`/`err` field and is omitted entirely when false, so older records parse
-//! as `reads_stdin: false`. The cache analysis uses it to skip dedup for
-//! commands whose real input the command string doesn't show.
+//! `trace.jsonl` is the machine-readable trace sink (`-vv` writes it alongside
+//! the human `trace.log`). Each line is one JSON object — a `[wt-trace]` record
+//! serialized by `src/logging.rs::TraceJsonlFormat`. The objects dispatch on a
+//! `kind` field:
//!
-//! `seq` (a per-command counter, command records only) is parsed leniently —
-//! it's dropped as an unknown key, since no consumer needs it; it correlates a
-//! `trace.log` record with its raw output block in `subprocess.log`.
-//!
-//! Instant events (milestones without duration) use this format:
//! ```text
-//! [wt-trace] ts=1234567 tid=3 event="Showed skeleton"
+//! {"kind":"cmd_completed","ts":1234567,"tid":3,"seq":1,"context":"worktree","cmd":"git status","dur_us":12300,"ok":true}
+//! {"kind":"cmd_errored","ts":1234567,"tid":3,"seq":3,"context":"main","cmd":"git merge-base","dur_us":100000,"err":"fatal: ..."}
+//! {"kind":"instant","ts":1234567,"tid":3,"event":"Showed skeleton"}
+//! {"kind":"span","ts":1234567,"tid":3,"span":"build_hook_context","dur_us":8200}
//! ```
//!
-//! The `ts` (timestamp in microseconds since trace epoch) and `tid` (thread ID) fields
-//! enable concurrency analysis and Chrome Trace Format export for visualizing
-//! thread utilization in tools like chrome://tracing or Perfetto.
+//! `seq` (a per-command counter, command records only) is ignored here — no
+//! consumer needs it; it correlates a record with its raw output block in
+//! `subprocess.log`. `stdin` (bool, command records, omitted → `false`) flags a
+//! command that consumed stdin the `cmd` string doesn't capture; the cache
+//! analysis skips such commands from dedup.
+//!
+//! `trace.jsonl` also carries free-form `log::*` / `tracing::*` lines as
+//! `{"message":...}` (no `kind`); those — and the `$ cmd` start echoes — are
+//! skipped, since they aren't trace records.
//!
-//! Duration is specified in microseconds via `dur_us`.
+//! The `ts` (microseconds since trace epoch) and `tid` (thread ID) fields enable
+//! concurrency analysis and Chrome Trace Format export for visualizing thread
+//! utilization in tools like chrome://tracing or Perfetto. Duration is `dur_us`,
+//! in microseconds.
use std::time::Duration;
@@ -42,10 +40,11 @@ pub enum TraceEntryKind {
duration: Duration,
/// Command result
result: TraceResult,
- /// Whether the command consumed stdin not captured in `command` (a
- /// `stdin_bytes` buffer or an upstream pipe). `false` for older records
- /// without the `stdin` field. The cache analysis treats a stdin-reading
- /// command as inherently unique — its real input isn't in `command`.
+ /// Whether the command consumed stdin the `command` string doesn't
+ /// capture (a `stdin_bytes` buffer or an upstream pipe). The cache
+ /// analysis skips these — two runs with identical `(command, context)`
+ /// may be entirely different work. From the `stdin` JSON field
+ /// (omitted → `false`).
reads_stdin: bool,
},
/// An instant event (milestone marker with no duration)
@@ -64,7 +63,7 @@ pub enum TraceEntryKind {
},
}
-/// A parsed trace entry from a wt-trace log line.
+/// A parsed trace entry from a `trace.jsonl` record.
#[derive(Debug, Clone, PartialEq)]
pub struct TraceEntry {
/// Optional context (typically worktree name for git commands)
@@ -101,110 +100,70 @@ impl TraceEntry {
}
}
-/// Parse a single trace line.
+/// Parse a single `trace.jsonl` line into a [`TraceEntry`].
///
-/// Returns `None` if the line doesn't match the expected format.
-/// The `[wt-trace]` marker can appear anywhere in the line (to handle log prefixes).
-///
-/// Supports three entry types:
-/// - Command events: `cmd="..." dur_us=... ok=true/false` or `err="..."`
-/// - Instant events: `event="..."`
-/// - Span events: `span="..." dur_us=...`
+/// Returns `None` when the line isn't a JSON object, carries no recognized
+/// `kind`, or is missing a field that `kind` requires. Non-record lines
+/// (free-form `{"message":...}`, the `$ cmd` echoes) have no `kind` and are
+/// skipped this way.
fn parse_line(line: &str) -> Option<TraceEntry> {
- // Find the [wt-trace] marker anywhere in the line
- let marker = "[wt-trace] ";
- let marker_pos = line.find(marker)?;
- let rest = &line[marker_pos + marker.len()..];
-
- // Parse key=value pairs
- let mut context = None;
- let mut command = None;
- let mut event = None;
- let mut span = None;
- let mut duration = None;
- let mut result = None;
- let mut start_time_us = None;
- let mut thread_id = None;
- let mut reads_stdin = false;
-
- let mut remaining = rest;
-
- while !remaining.is_empty() {
- remaining = remaining.trim_start();
- if remaining.is_empty() {
- break;
- }
-
- // Find key=
- let eq_pos = remaining.find('=')?;
- let key = &remaining[..eq_pos];
- remaining = &remaining[eq_pos + 1..];
-
- // Parse value (quoted or unquoted)
- let value = if remaining.starts_with('"') {
- // Quoted value - find closing quote
- remaining = &remaining[1..];
- let end_quote = remaining.find('"')?;
- let val = &remaining[..end_quote];
- remaining = &remaining[end_quote + 1..];
- val
- } else {
- // Unquoted value - ends at space or end
- let end = remaining.find(' ').unwrap_or(remaining.len());
- let val = &remaining[..end];
- remaining = &remaining[end..];
- val
- };
-
- match key {
- "context" => context = Some(value.to_string()),
- "cmd" => command = Some(value.to_string()),
- "event" => event = Some(value.to_string()),
- "span" => span = Some(value.to_string()),
- "dur_us" => {
- let us: u64 = value.parse().ok()?;
- duration = Some(Duration::from_micros(us));
- }
- "ok" => {
- let success = value == "true";
- result = Some(TraceResult::Completed { success });
- }
- "err" => {
- result = Some(TraceResult::Error {
- message: value.to_string(),
- });
- }
- "ts" => {
- start_time_us = value.parse().ok();
- }
- "tid" => {
- thread_id = value.parse().ok();
- }
- "stdin" => {
- reads_stdin = value == "true";
- }
- _ => {} // Ignore unknown keys for forward compatibility
- }
+ let line = line.trim();
+ // Cheap reject before handing the line to serde — most non-record lines
+ // (start echoes, blank lines) don't even start with `{`.
+ if !line.starts_with('{') {
+ return None;
}
+ let value: serde_json::Value = serde_json::from_str(line).ok()?;
+ let obj = value.as_object()?;
+
+ let context = obj
+ .get("context")
+ .and_then(|v| v.as_str())
+ .map(str::to_string);
+ let start_time_us = obj.get("ts").and_then(serde_json::Value::as_u64);
+ let thread_id = obj.get("tid").and_then(serde_json::Value::as_u64);
+
+ let dur = || -> Option<Duration> {
+ obj.get("dur_us")
+ .and_then(serde_json::Value::as_u64)
+ .map(Duration::from_micros)
+ };
- // Determine the entry kind based on what was parsed
- let kind = if let Some(event_name) = event {
- // Instant event
- TraceEntryKind::Instant { name: event_name }
- } else if let Some(span_name) = span {
- // In-process span - requires span and dur_us
- TraceEntryKind::Span {
- name: span_name,
- duration: duration?,
- }
- } else {
- // Command event - requires cmd, dur_us, and result
- TraceEntryKind::Command {
- command: command?,
- duration: duration?,
- result: result?,
+ // `stdin` is omitted from records that didn't read it → `false`.
+ let reads_stdin = obj
+ .get("stdin")
+ .and_then(serde_json::Value::as_bool)
+ .unwrap_or(false);
+
+ let kind = match obj.get("kind")?.as_str()? {
+ "cmd_completed" => TraceEntryKind::Command {
+ command: obj.get("cmd")?.as_str()?.to_string(),
+ duration: dur()?,
+ result: TraceResult::Completed {
+ success: obj.get("ok")?.as_bool()?,
+ },
reads_stdin,
- }
+ },
+ "cmd_errored" => TraceEntryKind::Command {
+ command: obj.get("cmd")?.as_str()?.to_string(),
+ duration: dur()?,
+ result: TraceResult::Error {
+ message: obj
+ .get("err")
+ .and_then(|v| v.as_str())
+ .unwrap_or_default()
+ .to_string(),
+ },
+ reads_stdin,
+ },
+ "instant" => TraceEntryKind::Instant {
+ name: obj.get("event")?.as_str()?.to_string(),
+ },
+ "span" => TraceEntryKind::Span {
+ name: obj.get("span")?.as_str()?.to_string(),
+ duration: dur()?,
+ },
+ _ => return None, // Unknown kind — forward-compatible skip
};
Some(TraceEntry {
@@ -215,7 +174,7 @@ fn parse_line(line: &str) -> Option<TraceEntry> {
})
}
-/// Parse multiple lines, filtering to only valid trace entries.
+/// Parse multiple lines, filtering to only valid trace records.
pub fn parse_lines(input: &str) -> Vec<TraceEntry> {
input.lines().filter_map(parse_line).collect()
}
@@ -226,7 +185,7 @@ mod tests {
#[test]
fn test_parse_basic() {
- let line = r#"[wt-trace] cmd="git status" dur_us=12300 ok=true"#;
+ let line = r#"{"kind":"cmd_completed","cmd":"git status","dur_us":12300,"ok":true}"#;
let entry = parse_line(line).unwrap();
assert_eq!(entry.context, None);
@@ -243,8 +202,7 @@ mod tests {
#[test]
fn test_parse_with_context() {
- let line =
- r#"[wt-trace] context=main cmd="git merge-base HEAD origin/main" dur_us=45200 ok=true"#;
+ let line = r#"{"kind":"cmd_completed","context":"main","cmd":"git merge-base HEAD origin/main","dur_us":45200,"ok":true}"#;
let entry = parse_line(line).unwrap();
assert_eq!(entry.context, Some("main".to_string()));
@@ -256,7 +214,7 @@ mod tests {
#[test]
fn test_parse_error() {
- let line = r#"[wt-trace] cmd="git rev-list" dur_us=100000 err="fatal: bad revision""#;
+ let line = r#"{"kind":"cmd_errored","cmd":"git rev-list","dur_us":100000,"err":"fatal: bad revision"}"#;
let entry = parse_line(line).unwrap();
assert!(!entry.is_success());
@@ -268,7 +226,7 @@ mod tests {
#[test]
fn test_parse_ok_false() {
- let line = r#"[wt-trace] cmd="git diff" dur_us=5000 ok=false"#;
+ let line = r#"{"kind":"cmd_completed","cmd":"git diff","dur_us":5000,"ok":false}"#;
let entry = parse_line(line).unwrap();
assert!(!entry.is_success());
@@ -282,70 +240,69 @@ mod tests {
}
#[test]
- fn test_parse_non_trace_line() {
- assert!(parse_line("some random log line").is_none());
- assert!(parse_line("[other-tag] something").is_none());
- }
-
- #[test]
- fn test_parse_with_log_prefix() {
- // Real output has thread ID prefix like "[a] "
- let line = r#"[a] [wt-trace] cmd="git status" dur_us=5000 ok=true"#;
- let entry = parse_line(line).unwrap();
+ fn test_parse_reads_stdin() {
+ // `stdin:true` is carried onto the Command; omitted → false.
+ let with = parse_line(
+ r#"{"kind":"cmd_completed","cmd":"git patch-id","dur_us":640,"ok":true,"stdin":true}"#,
+ )
+ .unwrap();
assert!(matches!(
- &entry.kind,
- TraceEntryKind::Command { command, .. } if command == "git status"
+ with.kind,
+ TraceEntryKind::Command {
+ reads_stdin: true,
+ ..
+ }
+ ));
+ let without =
+ parse_line(r#"{"kind":"cmd_completed","cmd":"git status","dur_us":10,"ok":true}"#)
+ .unwrap();
+ assert!(matches!(
+ without.kind,
+ TraceEntryKind::Command {
+ reads_stdin: false,
+ ..
+ }
));
}
#[test]
- fn test_parse_stdin_marker() {
- // `stdin=true` marks a command whose input came via stdin; its absence
- // (older records, stdin-less commands) parses as `reads_stdin: false`.
- let with = r#"[wt-trace] cmd="git patch-id --verbatim" dur_us=640 ok=true stdin=true"#;
- let TraceEntryKind::Command { reads_stdin, .. } = parse_line(with).unwrap().kind else {
- panic!("expected command");
- };
- assert!(reads_stdin);
-
- let without = r#"[wt-trace] cmd="git status" dur_us=5000 ok=true"#;
- let TraceEntryKind::Command { reads_stdin, .. } = parse_line(without).unwrap().kind else {
+ fn test_parse_embedded_quote_in_command() {
+ // The escaping win JSON buys us: a literal `"` in the command, where
+ // the old `cmd="value"` text grammar would truncate the parse.
+ let line = r#"{"kind":"cmd_completed","cmd":"git commit -m \"wip\"","dur_us":1,"ok":true}"#;
+ let entry = parse_line(line).unwrap();
+ let TraceEntryKind::Command { command, .. } = &entry.kind else {
panic!("expected command");
};
- assert!(!reads_stdin);
+ assert_eq!(command, r#"git commit -m "wip""#);
}
#[test]
- fn test_parse_unknown_keys_ignored() {
- // Unknown keys should be ignored for forward compatibility
- let line =
- r#"[wt-trace] future_field=xyz cmd="git status" dur_us=5000 ok=true extra=ignored"#;
- let entry = parse_line(line).unwrap();
- assert!(matches!(
- &entry.kind,
- TraceEntryKind::Command { command, .. } if command == "git status"
- ));
- assert!(entry.is_success());
+ fn test_parse_non_record_lines() {
+ // Not JSON at all (a `$ cmd` echo, a blank line).
+ assert!(parse_line("$ git status [main]").is_none());
+ assert!(parse_line("").is_none());
+ // JSON, but a free-form `log::*` message with no `kind`.
+ assert!(parse_line(r#"{"message":"fsmonitor: skipping","level":"warn"}"#).is_none());
+ // JSON with an unknown future kind — skipped, not an error.
+ assert!(parse_line(r#"{"kind":"future_kind","ts":1}"#).is_none());
}
#[test]
- fn test_parse_trailing_whitespace() {
- // Trailing whitespace should be handled (exercises trim_start + break)
- let line = "[wt-trace] cmd=\"git status\" dur_us=5000 ok=true ";
- let entry = parse_line(line).unwrap();
- assert!(matches!(
- &entry.kind,
- TraceEntryKind::Command { command, .. } if command == "git status"
- ));
+ fn test_parse_missing_required_field() {
+ // `cmd_completed` without `dur_us` / `ok` can't form a Command.
+ assert!(parse_line(r#"{"kind":"cmd_completed","cmd":"git status"}"#).is_none());
+ // `span` without `dur_us`.
+ assert!(parse_line(r#"{"kind":"span","span":"config_load"}"#).is_none());
}
#[test]
fn test_parse_lines() {
let input = r#"
DEBUG some other log
-[wt-trace] cmd="git status" dur_us=10000 ok=true
-more noise
-[wt-trace] cmd="git diff" dur_us=20000 ok=true
+{"kind":"cmd_completed","cmd":"git status","dur_us":10000,"ok":true}
+{"message":"noise","level":"debug"}
+{"kind":"cmd_completed","cmd":"git diff","dur_us":20000,"ok":true}
"#;
let entries = parse_lines(input);
assert_eq!(entries.len(), 2);
@@ -361,7 +318,7 @@ more noise
#[test]
fn test_parse_with_timestamp_and_thread_id() {
- let line = r#"[wt-trace] ts=1736600000000000 tid=5 context=feature cmd="git status" dur_us=12300 ok=true"#;
+ let line = r#"{"kind":"cmd_completed","ts":1736600000000000,"tid":5,"context":"feature","cmd":"git status","dur_us":12300,"ok":true}"#;
let entry = parse_line(line).unwrap();
assert_eq!(entry.start_time_us, Some(1736600000000000));
@@ -376,8 +333,8 @@ more noise
#[test]
fn test_parse_without_timestamp_and_thread_id() {
- // Traces without ts/tid should parse with None values
- let line = r#"[wt-trace] cmd="git status" dur_us=12300 ok=true"#;
+ // Records without ts/tid parse with None values.
+ let line = r#"{"kind":"cmd_completed","cmd":"git status","dur_us":12300,"ok":true}"#;
let entry = parse_line(line).unwrap();
assert_eq!(entry.start_time_us, None);
@@ -388,23 +345,13 @@ more noise
));
}
- #[test]
- fn test_parse_partial_new_fields() {
- // Only ts provided, no tid
- let line = r#"[wt-trace] ts=1736600000000000 cmd="git status" dur_us=12300 ok=true"#;
- let entry = parse_line(line).unwrap();
-
- assert_eq!(entry.start_time_us, Some(1736600000000000));
- assert_eq!(entry.thread_id, None);
- }
-
// ========================================================================
// Instant event tests
// ========================================================================
#[test]
fn test_parse_instant_event() {
- let line = r#"[wt-trace] ts=1736600000000000 tid=3 event="Showed skeleton""#;
+ let line = r#"{"kind":"instant","ts":1736600000000000,"tid":3,"event":"Showed skeleton"}"#;
let entry = parse_line(line).unwrap();
assert_eq!(entry.start_time_us, Some(1736600000000000));
@@ -418,7 +365,7 @@ more noise
#[test]
fn test_parse_instant_event_with_context() {
- let line = r#"[wt-trace] ts=1736600000000000 tid=3 context=main event="Skeleton rendered""#;
+ let line = r#"{"kind":"instant","ts":1736600000000000,"tid":3,"context":"main","event":"Skeleton rendered"}"#;
let entry = parse_line(line).unwrap();
assert_eq!(entry.context, Some("main".to_string()));
@@ -428,27 +375,14 @@ more noise
));
}
- #[test]
- fn test_parse_instant_event_minimal() {
- // Instant event with only the required field
- let line = r#"[wt-trace] event="Started""#;
- let entry = parse_line(line).unwrap();
-
- assert!(matches!(
- &entry.kind,
- TraceEntryKind::Instant { name } if name == "Started"
- ));
- assert_eq!(entry.start_time_us, None);
- assert_eq!(entry.thread_id, None);
- }
-
// ========================================================================
// Span event tests
// ========================================================================
#[test]
fn test_parse_span_event() {
- let line = r#"[wt-trace] ts=1736600000000000 tid=3 span="config_load" dur_us=8200"#;
+ let line =
+ r#"{"kind":"span","ts":1736600000000000,"tid":3,"span":"config_load","dur_us":8200}"#;
let entry = parse_line(line).unwrap();
assert_eq!(entry.start_time_us, Some(1736600000000000));
@@ -461,26 +395,14 @@ more noise
assert!(entry.is_success());
}
- #[test]
- fn test_parse_span_minimal() {
- let line = r#"[wt-trace] span="repo_open" dur_us=1500"#;
- let entry = parse_line(line).unwrap();
-
- let TraceEntryKind::Span { name, duration } = &entry.kind else {
- panic!("expected span");
- };
- assert_eq!(name, "repo_open");
- assert_eq!(*duration, Duration::from_micros(1500));
- }
-
#[test]
fn test_parse_lines_mixed() {
let input = r#"
-[wt-trace] event="Started"
-[wt-trace] cmd="git status" dur_us=10000 ok=true
-[wt-trace] event="Showed skeleton"
-[wt-trace] cmd="git diff" dur_us=20000 ok=true
-[wt-trace] event="Done"
+{"kind":"instant","event":"Started"}
+{"kind":"cmd_completed","cmd":"git status","dur_us":10000,"ok":true}
+{"kind":"instant","event":"Showed skeleton"}
+{"kind":"cmd_completed","cmd":"git diff","dur_us":20000,"ok":true}
+{"kind":"span","span":"repo_open","dur_us":1500}
"#;
let entries = parse_lines(input);
assert_eq!(entries.len(), 5);
@@ -494,6 +416,8 @@ more noise
assert!(
matches!(&entries[3].kind, TraceEntryKind::Command { command, .. } if command == "git diff")
);
- assert!(matches!(&entries[4].kind, TraceEntryKind::Instant { name } if name == "Done"));
+ assert!(
+ matches!(&entries[4].kind, TraceEntryKind::Span { name, .. } if name == "repo_open")
+ );
}
}
diff --git a/src/trace/profile.rs b/src/trace/profile.rs
index 4b044cb44..ae4720d65 100644
--- a/src/trace/profile.rs
+++ b/src/trace/profile.rs
@@ -1,4 +1,4 @@
-//! Aggregate `[wt-trace]` records into a performance profile.
+//! Aggregate trace records into a performance profile.
//!
//! Where [`parse`](super::parse) turns trace lines into [`TraceEntry`] values and
//! [`chrome`](super::chrome) exports them for Perfetto, this module answers the
@@ -70,7 +70,7 @@ fn ser_opt_dur_us<S: serde::Serializer>(d: &Option<Duration>, s: S) -> Result<S:
}
}
-/// A performance profile derived from a set of `[wt-trace]` records.
+/// A performance profile derived from a set of trace records.
///
/// The struct IS the canonical result: `--format=json` serializes it directly
/// (durations as `*_us` microseconds), and [`Profile::render_text`] renders the
diff --git a/tests/helpers/wt-perf/src/main.rs b/tests/helpers/wt-perf/src/main.rs
index 589579df3..3ee7f17e2 100644
--- a/tests/helpers/wt-perf/src/main.rs
+++ b/tests/helpers/wt-perf/src/main.rs
@@ -41,12 +41,13 @@ enum Commands {
repo: PathBuf,
},
- /// Parse trace logs and output Chrome Trace Format JSON
+ /// Parse a trace.jsonl and output Chrome Trace Format JSON
#[command(after_long_help = r#"EXAMPLES:
- # Generate trace from wt command
- # --progressive is required — without it, TTY-gated events (Skeleton
- # rendered, First result received) don't fire when stdout is a pipe.
- RUST_LOG=debug wt list --progressive 2>&1 | wt-perf trace > trace.json
+ # Capture a trace, then convert it. --progressive is required — without it,
+ # TTY-gated events (Skeleton rendered, First result received) don't fire
+ # when stdout is a pipe.
+ wt -vv list --progressive
+ wt-perf trace .git/wt/logs/trace.jsonl > trace.json
# Then either:
# - Open trace.json in chrome://tracing or https://ui.perfetto.dev
@@ -59,31 +60,27 @@ enum Commands {
curl -LO https://get.perfetto.dev/trace_processor && chmod +x trace_processor
"#)]
Trace {
- /// Path to trace log file (reads from stdin if omitted)
+ /// Path to a trace.jsonl file (reads from stdin if omitted)
file: Option<PathBuf>,
},
- /// Analyze trace logs for duplicate commands (cache effectiveness)
+ /// Analyze a trace.jsonl for duplicate commands (cache effectiveness)
#[command(after_long_help = r#"EXAMPLES:
# Check cache effectiveness for wt list
- RUST_LOG=debug wt list --progressive 2>&1 | wt-perf cache-check
-
- # From a file
- wt-perf cache-check trace.log
+ wt -vv list --progressive
+ wt-perf cache-check .git/wt/logs/trace.jsonl
"#)]
CacheCheck {
- /// Path to trace log file (reads from stdin if omitted)
+ /// Path to a trace.jsonl file (reads from stdin if omitted)
file: Option<PathBuf>,
},
/// Run a `wt` command with tracing on and render a timeline.
///
- /// Sets `RUST_LOG=debug` on the child so `[wt-trace]` records emit on
- /// stderr alongside the rest of debug output, parses out the trace
- /// records, sorts them by start time, and prints a column-aligned
- /// timeline to stdout. With `--chrome`, emits Chrome Trace Format JSON
- /// instead — pipe to a file and open in chrome://tracing or
- /// https://ui.perfetto.dev.
+ /// Runs the child with `-vv` so it writes `trace.jsonl`, reads that back,
+ /// sorts the records by start time, and prints a column-aligned timeline
+ /// to stdout. With `--chrome`, emits Chrome Trace Format JSON instead —
+ /// pipe to a file and open in chrome://tracing or https://ui.perfetto.dev.
#[command(after_long_help = r#"EXAMPLES:
# Text timeline of `wt list` in the current repo
wt-perf timeline -- list
@@ -243,16 +240,22 @@ fn resolve_wt_binary() -> PathBuf {
candidate
}
-/// Run a `wt` command with `RUST_LOG=debug`, capture stderr, and render.
+/// Run a `wt -vv` command and render the `trace.jsonl` it writes.
+///
+/// `-vv` writes the machine trace to `<git-common-dir>/wt/logs/trace.jsonl` in
+/// the repo wt operated on (the humanized stderr/`trace.log` isn't parseable).
+/// We locate that repo the same way wt does — a `-C` in the args, else the
+/// cwd — and read the file back after the run.
fn run_timeline(cold: bool, repo: Option<PathBuf>, chrome: bool, wt_args: &[String]) {
let wt = resolve_wt_binary();
+ // The trace lands in the repo wt operates on — resolved from `-C`/cwd the
+ // same way wt resolves it, so we never read a different repo than wt wrote.
+ // `--repo` governs only `--cold` invalidation.
+ let trace_dir = wt_target_dir(wt_args);
if cold {
- let path = repo
- .clone()
- .unwrap_or_else(|| std::env::current_dir().unwrap());
- let path = canonicalize(&path).unwrap_or_else(|e| {
- eprintln!("Invalid repo path {}: {}", path.display(), e);
+ let path = canonicalize(repo.as_deref().unwrap_or(&trace_dir)).unwrap_or_else(|e| {
+ eprintln!("Invalid --cold repo path: {e}");
std::process::exit(1);
});
if !path.join(".git").exists() {
@@ -262,6 +265,18 @@ fn run_timeline(cold: bool, repo: Option<PathBuf>, chrome: bool, wt_args: &[Stri
invalidate_caches_auto(&path);
}
+ let jsonl = trace_jsonl_path(&trace_dir).unwrap_or_else(|| {
+ eprintln!(
+ "Could not locate a git repository for the trace at {} — run from inside a repo or pass a `-C <path>` in the wt args.",
+ trace_dir.display()
+ );
+ std::process::exit(1);
+ });
+ // Drop any prior run's trace first, so an early-exiting child (e.g. clap
+ // intercepting `--help`/`--version` before `init_logging`) surfaces the
+ // absent-file error below rather than a stale timeline.
+ let _ = std::fs::remove_file(&jsonl);
+
// Measure spawn → wait wall externally. The trace can't see the
// process prelude (argv parsing, dyld, the time before `init_logging`
// registers the logger and the trace_epoch is set) or the epilogue
@@ -271,8 +286,8 @@ fn run_timeline(cold: bool, repo: Option<PathBuf>, chrome: bool, wt_args: &[Stri
// doesn't mix `4.5ms` and `19.161583ms`.
let started = Instant::now();
let output = Command::new(&wt)
+ .arg("-vv")
.args(wt_args)
- .env("RUST_LOG", "debug")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
@@ -283,17 +298,23 @@ fn run_timeline(cold: bool, repo: Option<PathBuf>, chrome: bool, wt_args: &[Stri
});
let wall = Duration::from_micros(started.elapsed().as_micros() as u64);
- let stderr = String::from_utf8_lossy(&output.stderr);
- let entries = worktrunk::trace::parse_lines(&stderr);
+ let content = std::fs::read_to_string(&jsonl).unwrap_or_else(|e| {
+ eprintln!("Failed to read {}: {e}", jsonl.display());
+ eprintln!("wt exited with {}; check that the command runs past `init_logging` (e.g. avoid `--version`/`--help`).", output.status);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ if !stderr.is_empty() {
+ eprintln!("--- wt stderr ---\n{stderr}");
+ }
+ std::process::exit(1);
+ });
+ let entries = worktrunk::trace::parse_lines(&content);
if entries.is_empty() {
eprintln!(
- "No [wt-trace] entries captured. wt exited with {}; check that the command runs past `init_logging` (e.g. avoid `--version`/`--help`).",
+ "No trace records in {}. wt exited with {}.",
+ jsonl.display(),
output.status,
);
- if !output.stderr.is_empty() {
- eprintln!("--- wt stderr ---\n{stderr}");
- }
std::process::exit(1);
}
@@ -309,6 +330,47 @@ fn run_timeline(cold: bool, repo: Option<PathBuf>, chrome: bool, wt_args: &[Stri
}
}
+/// The repo wt will operate on, mirroring wt's own resolution: a `-C <path>` /
+/// `-C<path>` in the args (wt's global flag), else the current directory. This
+/// is the directory whose `trace.jsonl` wt writes, so reading it back can't
+/// drift to a different repo.
+fn wt_target_dir(wt_args: &[String]) -> PathBuf {
+ let mut args = wt_args.iter();
+ while let Some(arg) = args.next() {
+ if arg == "-C" {
+ if let Some(path) = args.next() {
+ return PathBuf::from(path);
+ }
+ } else if let Some(path) = arg.strip_prefix("-C") {
+ return PathBuf::from(path);
+ }
+ }
+ std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
+}
+
+/// `<git-common-dir>/wt/logs/trace.jsonl` for the repo at `dir`, or `None`
+/// when `dir` isn't inside a git repository. The common dir is shared across
+/// linked worktrees, so this resolves to the same file wt writes.
+fn trace_jsonl_path(dir: &std::path::Path) -> Option<PathBuf> {
+ let out = Command::new("git")
+ .arg("-C")
+ .arg(dir)
+ .args(["rev-parse", "--git-common-dir"])
+ .output()
+ .ok()?;
+ if !out.status.success() {
+ return None;
+ }
+ let common = String::from_utf8(out.stdout).ok()?;
+ let common = PathBuf::from(common.trim());
+ let common = if common.is_absolute() {
+ common
+ } else {
+ dir.join(common)
+ };
+ Some(common.join("wt").join("logs").join("trace.jsonl"))
+}
+
/// Render parsed entries as a column-aligned, start-time-sorted timeline.
///
/// `wall` is the externally-measured spawn → wait duration. The trace
@@ -380,9 +442,7 @@ fn render_timeline(entries: &[TraceEntry], wall: Duration) -> String {
} else {
out.push_str("0 subprocesses\n");
}
- out.push_str(&format!(
- "traced: {traced:?} (first → last [wt-trace] record)\n"
- ));
+ out.push_str(&format!("traced: {traced:?} (first → last record)\n"));
out.push_str(&format!(
"wall: {wall:?} (spawn → wait; +{untraced:?} untraced prelude/epilogue)\n"
));
@@ -455,9 +515,9 @@ fn read_trace_entries(file: Option<&std::path::Path>) -> Vec<worktrunk::trace::T
if entries.is_empty() {
eprintln!(
- "No [wt-trace] entries found in input.\n\
- Run the target command with RUST_LOG=debug to emit trace records.\n\
- See `wt-perf <subcommand> --help` for the capture pipeline."
+ "No trace records found in input.\n\
+ Capture one by running the target command with `-vv`, then read\n\
+ `.git/wt/logs/trace.jsonl`. See `wt-perf <subcommand> --help`."
);
std::process::exit(1);
}
@@ -483,6 +543,19 @@ fn cache_check(entries: &[worktrunk::trace::TraceEntry]) {
mod tests {
use super::*;
+ /// `wt_target_dir` mirrors wt's `-C` resolution so the trace is read from
+ /// the repo wt wrote it to. Covers the space form (`-C path`), the attached
+ /// form (`-C<path>`), first-occurrence wins, and the cwd fallback.
+ #[test]
+ fn wt_target_dir_resolves_minus_c() {
+ let s = |v: &[&str]| wt_target_dir(&v.iter().map(|s| s.to_string()).collect::<Vec<_>>());
+ assert_eq!(s(&["-C", "/tmp/repo", "list"]), PathBuf::from("/tmp/repo"));
+ assert_eq!(s(&["-C/tmp/repo", "list"]), PathBuf::from("/tmp/repo"));
+ assert_eq!(s(&["-C", "/a", "-C", "/b"]), PathBuf::from("/a")); // first wins
+ // No `-C` → current directory (not the literal "list" argument).
+ assert_eq!(s(&["list"]), std::env::current_dir().unwrap());
+ }
+
fn span(name: &str, ts_us: u64, dur_us: u64, tid: u64) -> TraceEntry {
TraceEntry {
context: None,
@@ -540,7 +613,7 @@ mod tests {
4.200 280µs 38 span user_config_load
1 subprocess totaling 4ms (slowest: 4ms git rev-parse HEAD [repo])
- traced: 4.48ms (first → last [wt-trace] record)
+ traced: 4.48ms (first → last record)
wall: 6ms (spawn → wait; +1.52ms untraced prelude/epilogue)
"
);
@@ -556,7 +629,7 @@ mod tests {
0.000 1ms 1 cmd git foo (ok=false)
1 subprocess totaling 1ms (slowest: 1ms git foo (ok=false))
- traced: 1ms (first → last [wt-trace] record)
+ traced: 1ms (first → last record)
wall: 2ms (spawn → wait; +1ms untraced prelude/epilogue)
"
);
diff --git a/tests/integration_tests/analyze_trace.rs b/tests/integration_tests/analyze_trace.rs
index ea242f372..632043ace 100644
--- a/tests/integration_tests/analyze_trace.rs
+++ b/tests/integration_tests/analyze_trace.rs
@@ -12,12 +12,12 @@ fn wt_perf_bin() -> std::path::PathBuf {
/// Test that the binary produces Chrome Trace Format JSON for sample trace input.
#[test]
fn test_wt_perf_trace_from_stdin() {
- let sample_trace = r#"[wt-trace] ts=1000000 tid=1 cmd="git status" dur_us=10000 ok=true
-[wt-trace] ts=1010000 tid=1 cmd="git status" dur_us=15000 ok=true
-[wt-trace] ts=1025000 tid=1 cmd="git diff" dur_us=100000 ok=true
-[wt-trace] ts=1025000 tid=2 event="Showed skeleton"
-[wt-trace] ts=1125000 tid=1 cmd="git merge-base HEAD main" dur_us=500000 ok=true
-[wt-trace] ts=1625000 tid=1 cmd="gh pr list" dur_us=200000 ok=true"#;
+ let sample_trace = r#"{"kind":"cmd_completed","ts":1000000,"tid":1,"cmd":"git status","dur_us":10000,"ok":true}
+{"kind":"cmd_completed","ts":1010000,"tid":1,"cmd":"git status","dur_us":15000,"ok":true}
+{"kind":"cmd_completed","ts":1025000,"tid":1,"cmd":"git diff","dur_us":100000,"ok":true}
+{"kind":"instant","ts":1025000,"tid":2,"event":"Showed skeleton"}
+{"kind":"cmd_completed","ts":1125000,"tid":1,"cmd":"git merge-base HEAD main","dur_us":500000,"ok":true}
+{"kind":"cmd_completed","ts":1625000,"tid":1,"cmd":"gh pr list","dur_us":200000,"ok":true}"#;
let mut child = Command::new(wt_perf_bin())
.arg("trace")
@@ -108,8 +108,8 @@ fn test_wt_perf_trace_empty_input() {
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
- stderr.contains("No [wt-trace] entries found"),
- "Should indicate no trace entries"
+ stderr.contains("No trace records found"),
+ "Should indicate no trace records"
);
}
@@ -118,12 +118,12 @@ fn test_wt_perf_trace_empty_input() {
fn test_wt_perf_trace_from_file() {
// Create a temp file with sample trace data
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
- let log_file = temp_dir.path().join("trace.log");
+ let log_file = temp_dir.path().join("trace.jsonl");
- let sample_trace = r#"[wt-trace] ts=1000000 tid=1 cmd="git rev-parse" dur_us=5000 ok=true
-[wt-trace] ts=1005000 tid=1 cmd="git status" dur_us=10000 ok=true
-[wt-trace] ts=1015000 tid=1 event="Skeleton displayed"
-[wt-trace] ts=1015000 tid=2 cmd="git diff" dur_us=50000 ok=true"#;
+ let sample_trace = r#"{"kind":"cmd_completed","ts":1000000,"tid":1,"cmd":"git rev-parse","dur_us":5000,"ok":true}
+{"kind":"cmd_completed","ts":1005000,"tid":1,"cmd":"git status","dur_us":10000,"ok":true}
+{"kind":"instant","ts":1015000,"tid":1,"event":"Skeleton displayed"}
+{"kind":"cmd_completed","ts":1015000,"tid":2,"cmd":"git diff","dur_us":50000,"ok":true}"#;
std::fs::write(&log_file, sample_trace).expect("Failed to write sample log");
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index d9625693a..0c817e763 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -57,10 +57,11 @@ fn test_complete_switch_shows_branches(repo: TestRepo) {
/// `WORKTRUNK_VERBOSE` reaches the completion subprocess, which exits before
/// `main`'s `logging::init` and is otherwise silent. It is the env-var
/// equivalent of `-v`/`-vv`, so at level 2 completion writes the same
-/// `[wt-trace]` timing and `$ git …` records to `.git/wt/logs/trace.log` that
-/// `-vv` produces — the only way to profile a slow tab-completion, since the
-/// shell invokes completion with nowhere to pass `-vv`. Unset, completion
-/// writes nothing and keeps the candidate output clean.
+/// humanized timing (`✓ git …`) and `$ git …` start records to
+/// `.git/wt/logs/trace.log` that `-vv` produces — the only way to profile a
+/// slow tab-completion, since the shell invokes completion with nowhere to
+/// pass `-vv`. Unset, completion writes nothing and keeps the candidate output
+/// clean.
#[rstest]
fn test_completion_honors_worktrunk_verbose(repo: TestRepo) {
repo.commit("initial");
@@ -102,8 +103,8 @@ fn test_completion_honors_worktrunk_verbose(repo: TestRepo) {
let trace = std::fs::read_to_string(&trace_log)
.expect("WORKTRUNK_VERBOSE=2 should write trace.log during completion");
assert!(
- trace.contains("[wt-trace]"),
- "completion trace should capture [wt-trace] timing: {trace}"
+ trace.contains("✓ git"),
+ "completion trace should capture humanized command timing: {trace}"
);
assert!(
trace.contains("$ git"),
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 7f88f0a8a..52990cfe3 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -334,15 +334,15 @@ fn test_state_bare_logs(repo: TestRepo) {
/// A synthetic `-vv` trace: two parallel `git status` runs, an in-process span,
/// a failed `git diff`, and a `git config` run twice in the same context (the
/// cache-miss the profile flags), bracketed by milestone events.
-const PROFILE_FIXTURE_TRACE: &str = r#"[wt-trace] ts=1000 tid=1 event="List collect started"
-[wt-trace] ts=1000 tid=1 context=main cmd="git status --porcelain" dur_us=12000 ok=true
-[wt-trace] ts=1000 tid=2 context=feature cmd="git status --porcelain" dur_us=8000 ok=true
-[wt-trace] ts=500 tid=1 span="user_config_load" dur_us=2000
-[wt-trace] ts=13000 tid=1 event="Skeleton rendered"
-[wt-trace] ts=13000 tid=1 context=main cmd="git diff --shortstat" dur_us=5000 ok=false
-[wt-trace] ts=1000 tid=1 context=main cmd="git config --list" dur_us=4000 ok=true
-[wt-trace] ts=6000 tid=1 context=main cmd="git config --list" dur_us=3000 ok=true
-[wt-trace] ts=18000 tid=1 event="All results drained"
+const PROFILE_FIXTURE_TRACE: &str = r#"{"kind":"instant","ts":1000,"tid":1,"event":"List collect started"}
+{"kind":"cmd_completed","ts":1000,"tid":1,"context":"main","cmd":"git status --porcelain","dur_us":12000,"ok":true}
+{"kind":"cmd_completed","ts":1000,"tid":2,"context":"feature","cmd":"git status --porcelain","dur_us":8000,"ok":true}
+{"kind":"span","ts":500,"tid":1,"span":"user_config_load","dur_us":2000}
+{"kind":"instant","ts":13000,"tid":1,"event":"Skeleton rendered"}
+{"kind":"cmd_completed","ts":13000,"tid":1,"context":"main","cmd":"git diff --shortstat","dur_us":5000,"ok":false}
+{"kind":"cmd_completed","ts":1000,"tid":1,"context":"main","cmd":"git config --list","dur_us":4000,"ok":true}
+{"kind":"cmd_completed","ts":6000,"tid":1,"context":"main","cmd":"git config --list","dur_us":3000,"ok":true}
+{"kind":"instant","ts":18000,"tid":1,"event":"All results drained"}
"#;
/// Run `wt config state logs profile <args>` with `input` on stdin.
@@ -516,18 +516,15 @@ fn test_logs_profile_file_missing(repo: TestRepo) {
let output = cmd.output().unwrap();
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
- assert!(
- stderr.contains("Failed to read trace log"),
- "stderr: {stderr}"
- );
+ assert!(stderr.contains("Failed to read trace"), "stderr: {stderr}");
}
-/// With no argument, the profile reads the repo's `.git/wt/logs/trace.log`.
+/// With no argument, the profile reads the repo's `.git/wt/logs/trace.jsonl`.
#[rstest]
fn test_logs_profile_default_path(repo: TestRepo) {
let logs_dir = repo.root_path().join(".git/wt/logs");
std::fs::create_dir_all(&logs_dir).unwrap();
- std::fs::write(logs_dir.join("trace.log"), PROFILE_FIXTURE_TRACE).unwrap();
+ std::fs::write(logs_dir.join("trace.jsonl"), PROFILE_FIXTURE_TRACE).unwrap();
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
@@ -540,13 +537,13 @@ fn test_logs_profile_default_path(repo: TestRepo) {
assert!(stdout.contains("BY COMMAND TYPE"), "stdout: {stdout}");
}
-/// An input with no `[wt-trace]` records fails, pointing at `-vv`.
+/// An input with no trace records fails, pointing at `-vv`.
#[rstest]
fn test_logs_profile_no_records(repo: TestRepo) {
let output = profile_from_stdin(&repo, &["-"], "not a trace line\nanother line\n");
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
- assert!(stderr.contains("No [wt-trace] records"), "stderr: {stderr}");
+ assert!(stderr.contains("No trace records"), "stderr: {stderr}");
assert!(stderr.contains("-vv"), "stderr: {stderr}");
}
@@ -587,7 +584,7 @@ fn test_logs_profile_real_capture_has_key_intervals(repo: TestRepo) {
);
}
-/// Without a trace log, the error names the missing file and points at `-vv`.
+/// Without a trace, the error names the missing file and points at `-vv`.
#[rstest]
fn test_logs_profile_missing(repo: TestRepo) {
let mut cmd = wt_command();
@@ -597,13 +594,13 @@ fn test_logs_profile_missing(repo: TestRepo) {
let output = cmd.output().unwrap();
assert!(!output.status.success());
let stderr = String::from_utf8_lossy(&output.stderr);
- assert!(stderr.contains("No trace log at"), "stderr: {stderr}");
+ assert!(stderr.contains("No trace at"), "stderr: {stderr}");
assert!(stderr.contains("-vv"), "stderr: {stderr}");
}
/// With no FILE argument and no surrounding git repository, the error explains
-/// the absent default trace log and points at the path / `-` (stdin)
-/// alternatives, rather than surfacing a bare git "not a repository" error.
+/// the absent default trace and points at the path / `-` (stdin) alternatives,
+/// rather than surfacing a bare git "not a repository" error.
/// `wt_command()`'s default cwd is a process-scoped tempdir outside any repo.
#[rstest]
fn test_logs_profile_no_repo() {
@@ -619,7 +616,7 @@ fn test_logs_profile_no_repo() {
);
// The `-` is bold-wrapped (`\x1b[1m-\x1b[22m`), so assert on the surrounding
// unstyled text rather than a substring that crosses the ANSI boundary.
- assert!(stderr.contains("pass a trace log path"), "stderr: {stderr}");
+ assert!(stderr.contains("pass a trace path"), "stderr: {stderr}");
assert!(stderr.contains("for stdin"), "stderr: {stderr}");
}
diff --git a/tests/integration_tests/diagnostic.rs b/tests/integration_tests/diagnostic.rs
index cb5a8b860..476635af9 100644
--- a/tests/integration_tests/diagnostic.rs
+++ b/tests/integration_tests/diagnostic.rs
@@ -254,17 +254,17 @@ fn test_diagnostic_trace_log_contains_git_commands(mut repo: TestRepo) {
trace_section.contains("git worktree list"),
"Trace log should contain git worktree list command"
);
+ // Records are humanized: a ✓/✗ glyph reports each command's outcome with a
+ // compact duration, replacing the old `[wt-trace] … dur_us=… ok=…` grammar.
assert!(
- trace_section.contains("[wt-trace]"),
- "Trace log should contain wt-trace entries"
+ trace_section.contains("✓ git worktree list")
+ || trace_section.contains("✗ git worktree list"),
+ "Trace log should contain the humanized git worktree list completion record"
);
+ // In-process spans are humanized too (◷ glyph + duration).
assert!(
- trace_section.contains("dur_us="),
- "Trace log should contain command durations in microseconds"
- );
- assert!(
- trace_section.contains("ok="),
- "Trace log should contain success/failure indicators"
+ trace_section.contains("◷ init_logging"),
+ "Trace log should contain the init_logging span record"
);
}
@@ -332,8 +332,8 @@ fn test_log_files_created(mut repo: TestRepo) {
let trace = fs::read_to_string(&trace_log).unwrap();
assert!(!trace.is_empty(), "trace.log should not be empty");
assert!(
- trace.contains("[wt-trace]"),
- "trace.log should contain trace entries"
+ trace.contains("◷ init_logging"),
+ "trace.log should contain humanized trace records"
);
}
@@ -349,8 +349,8 @@ fn test_vv_splits_full_and_bounded_output(repo: TestRepo) {
let output = fs::read_to_string(logs_dir.join("subprocess.log")).unwrap();
assert!(
- trace.contains("[wt-trace]"),
- "trace.log should contain [wt-trace] records at -vv"
+ trace.contains("◷ init_logging"),
+ "trace.log should contain humanized trace records at -vv"
);
// Captured stdout is emitted line-by-line with the ` ` / ` ! `
// continuation prefix used by log_output. Full subprocess output lives
@@ -359,25 +359,27 @@ fn test_vv_splits_full_and_bounded_output(repo: TestRepo) {
output.lines().any(|l| l.contains(" worktree ")),
"subprocess.log should contain `git worktree list --porcelain` stdout lines at -vv"
);
- // Structured trace records stay in trace.log only, not subprocess.log.
+ // Trace records stay in trace.log only, not subprocess.log (which holds
+ // raw bodies under their `$ cmd … [seq=N tid=T]` headers).
assert!(
- !output.contains("[wt-trace]"),
- "subprocess.log should not contain [wt-trace] records"
+ !output.contains("◷ init_logging"),
+ "subprocess.log should not contain trace records"
);
}
/// Each command's block in `subprocess.log` is introduced by a
/// `$ cmd … [seq=N tid=T]` header, and that `seq` also tags the command's
-/// `[wt-trace]` record in `trace.log` — so an otherwise-undelimited raw output
-/// block can be segmented and joined back to its timed command record. Guards
-/// the segmentation + correlation contract the two files share.
+/// record in the machine `trace.jsonl` — so an otherwise-undelimited raw output
+/// block can be segmented and joined back to its timed command record. (The
+/// humanized `trace.log` drops `seq`; the join lives in `trace.jsonl`.) Guards
+/// the segmentation + correlation contract the files share.
#[rstest]
fn test_vv_subprocess_log_headers_join_trace(repo: TestRepo) {
repo.wt_command().args(["list", "-vv"]).output().unwrap();
let logs_dir = repo.root_path().join(".git").join("wt/logs");
let subprocess = fs::read_to_string(logs_dir.join("subprocess.log")).unwrap();
- let trace = fs::read_to_string(logs_dir.join("trace.log")).unwrap();
+ let trace = fs::read_to_string(logs_dir.join("trace.jsonl")).unwrap();
// Pick a known captured command (`wt list` runs `git worktree list
// --porcelain`) so the join can be checked by command identity, not just by
@@ -396,16 +398,14 @@ fn test_vv_subprocess_log_headers_join_trace(repo: TestRepo) {
.and_then(|s| s.parse().ok())
.expect("the subprocess.log header should carry a numeric seq");
- // The [wt-trace] record carrying that seq must be the SAME command —
+ // The trace.jsonl record carrying that seq must be the SAME command —
// asserting both `seq` and `cmd` closes the gap where a dense seq coincides
- // with an unrelated record.
+ // with an unrelated record. (serde_json emits compact `"key":value`.)
assert!(
trace.lines().any(|l| {
- l.contains("[wt-trace]")
- && l.contains(&format!("seq={seq} "))
- && l.contains(r#"cmd="git worktree list"#)
+ l.contains(&format!(r#""seq":{seq},"#)) && l.contains(r#""cmd":"git worktree list"#)
}),
- "trace.log should carry the [wt-trace] record for `git worktree list` with seq={seq} to join the subprocess.log block:\n{header}"
+ "trace.jsonl should carry the record for `git worktree list` with seq={seq} to join the subprocess.log block:\n{header}"
);
}
@@ -543,15 +543,15 @@ fn test_vv_debug_pipeline_silent_on_stderr(repo: TestRepo) {
);
// The full subprocess stdout still lands in subprocess.log, and trace.log
- // still captures the `$ cmd` / `[wt-trace]` records — confirm both so a
+ // still captures the humanized trace records — confirm both so a
// regression that disables the file sinks fails loudly here too.
assert!(
raw.lines().any(|l| l.contains("refs/heads/many-branch-")),
"subprocess.log should contain the captured for-each-ref stdout"
);
assert!(
- trace.contains("[wt-trace]"),
- "trace.log should contain [wt-trace] records at -vv"
+ trace.contains("◷ init_logging"),
+ "trace.log should contain humanized trace records at -vv"
);
// Stderr at -vv should announce each file's full path on its own line, so
@@ -578,16 +578,17 @@ fn test_vv_debug_pipeline_silent_on_stderr(repo: TestRepo) {
/// where `-v`/`-vv` hardcoded `filter_level(...)` and silently dropped
/// `RUST_LOG`.
///
-/// The probe is the `[wt-trace]` grammar — those records are emitted at
-/// `log::debug!`, so they're suppressed at the Info baseline `-v` selects
-/// and surface when `RUST_LOG=debug` raises it. (At `-v 0` the same
+/// The probe is the `◷ init_logging` span record — emitted at `log::debug!`,
+/// unique to the trace stream (so it can't be confused with normal output),
+/// and present on every run. It's suppressed at the Info baseline `-v` selects
+/// and surfaces when `RUST_LOG=debug` raises it. (At `-v 0` the same
/// `RUST_LOG=debug` path is already covered by
/// `test_rust_log_debug_fallback_without_vv`; at `-vv` the baseline is
/// already Debug so there's no flag/env conflict to assert.)
#[rstest]
fn test_rust_log_overrides_verbose_flag(repo: TestRepo) {
- // Baseline: -v alone caps at Info, so debug-level [wt-trace] records
- // are dropped from stderr.
+ // Baseline: -v alone caps at Info, so debug-level trace records are
+ // dropped from stderr.
let info_only = repo
.wt_command()
.args(["list", "-v"])
@@ -597,11 +598,11 @@ fn test_rust_log_overrides_verbose_flag(repo: TestRepo) {
.expect("wt list -v");
let info_stderr = String::from_utf8_lossy(&info_only.stderr);
assert!(
- !info_stderr.contains("[wt-trace]"),
- "-v alone (Info baseline) should not surface [wt-trace] records: {info_stderr}"
+ !info_stderr.contains("init_logging"),
+ "-v alone (Info baseline) should not surface trace records: {info_stderr}"
);
- // RUST_LOG=debug + -v raises the level: [wt-trace] records appear.
+ // RUST_LOG=debug + -v raises the level: trace records appear.
let with_env = repo
.wt_command()
.args(["list", "-v"])
@@ -611,8 +612,8 @@ fn test_rust_log_overrides_verbose_flag(repo: TestRepo) {
.expect("wt list -v");
let env_stderr = String::from_utf8_lossy(&with_env.stderr);
assert!(
- env_stderr.contains("[wt-trace]"),
- "RUST_LOG=debug at -v should surface [wt-trace] records on stderr: {env_stderr}"
+ env_stderr.contains("init_logging"),
+ "RUST_LOG=debug at -v should surface trace records on stderr: {env_stderr}"
);
}
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 06d97243d..ef4698434 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -77,7 +77,7 @@ fn test_switch_create_shows_progress_when_forced(repo: TestRepo) {
}
/// `git worktree add` runs through the delayed-stream path (`Cmd::delayed_stream`),
-/// which historically spawned a raw child and emitted no `[wt-trace]` record — it
+/// which historically spawned a raw child and emitted no trace record — it
/// surfaced only as an unattributed gap in the `wt-perf` timeline. Assert the
/// streamed command is now traced, pinning the `CommandTrace` chokepoint
/// (`src/trace/emit.rs`) against regression. The record is emitted whether the
@@ -86,12 +86,11 @@ fn test_switch_create_shows_progress_when_forced(repo: TestRepo) {
fn test_switch_create_traces_worktree_add(repo: TestRepo) {
use worktrunk::trace::{TraceEntryKind, parse_lines};
- // RUST_LOG=debug routes `[wt-trace]` records to stderr (the same channel
- // `wt-perf timeline` reads).
+ // -vv writes the machine `trace.jsonl` (the records `wt-perf timeline`
+ // reads), parsed back here the same way.
let output = repo
.wt_command()
- .args(["switch", "--create", "feature-traced", "--no-cd"])
- .env("RUST_LOG", "debug")
+ .args(["-vv", "switch", "--create", "feature-traced", "--no-cd"])
.output()
.expect("wt switch should run");
assert!(
@@ -100,8 +99,9 @@ fn test_switch_create_traces_worktree_add(repo: TestRepo) {
String::from_utf8_lossy(&output.stderr)
);
- let stderr = String::from_utf8_lossy(&output.stderr);
- let commands: Vec<String> = parse_lines(&stderr)
+ let trace = std::fs::read_to_string(repo.root_path().join(".git/wt/logs/trace.jsonl"))
+ .expect("-vv should write trace.jsonl");
+ let commands: Vec<String> = parse_lines(&trace)
.into_iter()
.filter_map(|e| match e.kind {
TraceEntryKind::Command { command, .. } => Some(command),
@@ -111,7 +111,7 @@ fn test_switch_create_traces_worktree_add(repo: TestRepo) {
assert!(
commands.iter().any(|c| c.contains("worktree add")),
- "expected a [wt-trace] command record for `git worktree add`; \
+ "expected a trace command record for `git worktree add`; \
got command records:\n{}",
commands.join("\n")
);
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
index ee659892a..566495777 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_logs.snap
@@ -40,7 +40,7 @@ Usage: wt config state logs [OPTIONS] [COMMAND]
Commands:
get List all log file paths
- profile Performance profile from a trace log
+ profile Performance profile from a trace
clear Clear all log files
Options:
@@ -104,10 +104,12 @@ All post-* hooks (post-start, post-switch, post-commit, post-merge) run
File Created when
────────────── ────────────────
trace.log Running with -vv
+ trace.jsonl Running with -vv
subprocess.log Running with -vv
diagnostic.md Running with -vv
-trace.log captures debug-level records at -vv — commands, [wt-trace] records, bounded subprocess previews. wt config state logs profile summarizes one into a performance report (where time went, parallelism, redundant commands). subprocess.log holds the raw uncapped subprocess stdout/stderr bodies. diagnostic.md is a markdown bug-report bundle that inlines trace.log and a rendered performance profile; wt prints a gh gist create command pointing at it. All three are overwritten on each -vv run.
+trace.log is the human-readable trace at -vv — each command's start ($ …) and completion (✓/✗ … 12.3ms), in-process spans, milestones, and bounded subprocess previews. trace.jsonl is the same event stream as one JSON object per line, for machines (jq, chrome://tracing); wt config state logs profile reads it to summarize a performance report (where time went, parallelism, redundant commands). subprocess.log holds the raw uncapped subprocess stdout/stderr bodies. diagnostic.md is a markdown
+bug-report bundle that inlines trace.log and a rendered performance profile; wt prints a gh gist create command pointing at it. All four are overwritten on each -vv run.
Location
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_logs_profile.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_logs_profile.snap
index ee1fb2c22..129e192ee 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_state_logs_profile.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_logs_profile.snap
@@ -35,13 +35,13 @@ info:
success: true
exit_code: 0
----- stdout -----
-wt config state logs profile - Performance profile from a trace log
+wt config state logs profile - Performance profile from a trace
Usage: wt config state logs profile [OPTIONS] [FILE]
Arguments:
[FILE]
- Trace log to read (defaults to .git/wt/logs/trace.log; - for stdin)
+ Trace to read (defaults to .git/wt/logs/trace.jsonl; - for stdin)
Options:
-h, --help
@@ -67,12 +67,12 @@ Usage: wt config state logs profile [OPTIONS] [FILE]
-y, --yes
Skip approval prompts
-Summarize where a single wt invocation spent its time, reading the [wt-trace] records captured to trace.log by a -vv run.
+Summarize where a single wt invocation spent its time, reading the records captured to trace.jsonl by a -vv run.
-Reads .git/wt/logs/trace.log by default, or a log file given as an argument (e.g. a CI artifact, or - for stdin). The report answers three questions: where time goes (subprocess time by command type, plus the slowest individual jobs), how parallel the run was (concurrency factor and peak concurrency), and where work was wasted (commands re-run with the same context). For a wt list capture it also shows derived latencies (time to skeleton, time to first result) and a timeline of collect
+Reads .git/wt/logs/trace.jsonl by default, or a trace given as an argument (e.g. a CI artifact, or - for stdin). The report answers three questions: where time goes (subprocess time by command type, plus the slowest individual jobs), how parallel the run was (concurrency factor and peak concurrency), and where work was wasted (commands re-run with the same context). For a wt list capture it also shows derived latencies (time to skeleton, time to first result) and a timeline of collect
milestones; the skeleton/first-result markers need a terminal (TTY) capture. --format=json emits the same data for scripting.
-For an interactive timeline or a Perfetto trace, use the wt-perf helper (cargo run -p wt-perf -- timeline); both share the same trace parser.
+For an interactive timeline or a Perfetto trace, use the wt-perf helper (cargo run -p wt-perf -- timeline); both read the same trace.jsonl.
Examples
@@ -81,8 +81,8 @@ Profile the last -vv run in this repo:
  wt config state logs profile
Profile a trace from elsewhere (e.g. a CI artifact), by path or on stdin:
-  wt config state logs profile ci-run.log
-  wt config state logs profile - < ci-run.log
+  wt config state logs profile ci-run.jsonl
+  wt config state logs profile - < ci-run.jsonl
JSON for scripting:
  wt config state logs profile --format=json | jq '.by_type[0]'