Skip to content

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

feat(list): add JSON schema 2 behind [list] json-schema (#3357)

Maximilian Roos56e20a4a78d6
diff --git a/CLAUDE.md b/CLAUDE.md
index 092539b76..4bc72da2d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -105,7 +105,7 @@ Why: silent "lookup" paths that walk to the wire (alias dispatch, hook context b
What currently reaches the wire:
-- `wt list --full`, `wt list statusline` — CI status; also plain `wt list` when `[list] columns` names `ci`, which forces the column (and its fetch) on without `--full`
+- `wt list --full`, `wt list statusline` — CI status; also plain `wt list` (any format) when `[list] columns` names `ci`, which forces the column (and its fetch) on without `--full`
- `wt switch` (interactive picker, no target) — per-row CI status, primed from the local cache then fetched live and streamed into the rows; once a row's CI fetch surfaces an open PR/MR, a per-row background `gh pr view <n> --json comments` (`glab api …/notes` on GitLab) fills that row's `comments` preview tab — the same fetch a `--prs` row makes, spawned once per row from `progressive_handler` (see `picker::prs::spawn_comments_fetch`). The `comments` tab is the only PR data fetched lazily here; `pr` rides the CI call and `log` is the local `git log`
- generating a branch summary with a `commit.generation` command
- generating a commit message with a `commit.generation` command
diff --git a/dev/config.example.toml b/dev/config.example.toml
index ed0040447..651b428e2 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -99,6 +99,8 @@
# branches = false # Include branches without worktrees (--branches)
# remotes = false # Include remote-only branches (--remotes)
#
+# json-schema = 1 # JSON output schema: 1 (current, bare array) or 2 (envelope); unset emits 1 with a warning
+#
# columns = ["branch", "status", "ci", "path"] # Columns to show, in order — built-ins or custom headers (omit for the default set)
#
# task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disables
@@ -138,8 +140,10 @@
# needs an LLM command (`[commit.generation]`), `url` needs a `[list] url`
# template — since listing can't supply the data.
#
-# The selection drives the table and the `wt switch` picker; `wt list --format
-# json` ignores it and emits every field.
+# The selection drives the table and the `wt switch` picker. `wt list --format
+# json` always emits every field, but a listed gated column (`ci`, `summary`)
+# still forces its data collection on, so the JSON carries the same data the
+# table shows.
#
# #### Custom columns [experimental]
#
diff --git a/docs/content/config.md b/docs/content/config.md
index 9aaaf61cc..3c90f7e1c 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -186,6 +186,8 @@ full = false # Show CI status and LLM summaries (--full)
branches = false # Include branches without worktrees (--branches)
remotes = false # Include remote-only branches (--remotes)
+json-schema = 1 # JSON output schema: 1 (current, bare array) or 2 (envelope); unset emits 1 with a warning
+
columns = ["branch", "status", "ci", "path"] # Columns to show, in order — built-ins or custom headers (omit for the default set)
task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disables
@@ -226,8 +228,10 @@ named one. A column whose data source is missing still stays hidden — `summary
needs an LLM command (`[commit.generation]`), `url` needs a `[list] url`
template — since listing can't supply the data.
-The selection drives the table and the `wt switch` picker; `wt list --format
-json` ignores it and emits every field.
+The selection drives the table and the `wt switch` picker. `wt list --format
+json` always emits every field, but a listed gated column (`ci`, `summary`)
+still forces its data collection on, so the JSON carries the same data the
+table shows.
#### Custom columns
diff --git a/docs/content/list.md b/docs/content/list.md
index a09cfbbff..c64bdc07c 100644
--- a/docs/content/list.md
+++ b/docs/content/list.md
@@ -217,7 +217,84 @@ These appear across all columns while the table is loading:
## JSON output
-Query structured data with `--format=json`:
+`--format=json` emits structured data in one of two schemas while the format
+migrates: `[list] json-schema = 2` selects the envelope format below, `= 1`
+the original bare-array format. Unset emits schema 1 with a warning; a future
+release flips the default to schema 2 and later removes schema 1.
+
+### Schema 2
+
+One envelope object. Items carry independent facts; rendered strings
+(including the collapsed Status value) live under `display`:
+
+```json
+{
+ "schema": 2,
+ "repo": {
+ "default_branch": "main",
+ "forge": {"url": "https://github.com/org/repo", "provider": "github",
+ "host": "github.com", "owner": "org", "name": "repo", "remote": "origin"}
+ },
+ "collected": {"ci": false, "summary": false},
+ "items": [
+ {
+ "branch": "feature",
+ "head": {"sha": "05a4a45d…", "short_sha": "05a4a45", "subject": "Add login page",
+ "committed_at": "2025-01-01T08:00:00Z"},
+ "worktree": {"path": "/home/user/repo.feature", "main": false, "current": true,
+ "previous": false, "detached": false, "branch_mismatch": false,
+ "changes": {"staged": false, "modified": true, "untracked": false,
+ "renamed": false, "deleted": false, "conflicted": false,
+ "diff": {"added": 10, "deleted": 2}}},
+ "default_branch": {"ahead": 3, "behind": 1, "diff": {"added": 50, "deleted": 20},
+ "orphan": false, "integration": null, "merge_conflicts": false},
+ "upstream": {"remote": "origin", "branch": "feature", "ahead": 0, "behind": 2},
+ "display": {"state": "diverged", "symbols": "!↕", "statusline": "feature …"}
+ }
+ ]
+}
+```
+
+How "no value" reads:
+
+- **Absent** — nothing to report: not applicable (`worktree` on a branch-only
+ row), not requested this run (the envelope's `collected` records what was),
+ or determined-empty (no PR, no lock, not integrated).
+- **`null`** — requested but not determined: a task timed out, the branch was
+ too stale for the expensive checks, or a forge fetch failed. This is the
+ JSON form of the table's `·` placeholder.
+
+jq treats absent and `null` identically in path expressions, so filters need
+no null checks; `has()` distinguishes the two when it matters.
+
+Item fields:
+
+| Field | Description |
+|-------|-------------|
+| `branch` | Branch name; null for a detached-HEAD worktree. Remote rows carry the bare name with the remote in `remote` |
+| `remote` | Remote name, present only on remote-only branch rows |
+| `head` | `{sha, short_sha, subject, committed_at}`; null for unborn branches. `committed_at` is RFC 3339 UTC |
+| `worktree` | `{path, main, current, previous, detached, locked, prunable, branch_mismatch, operation, changes}`; absent on branch-only rows. `locked`/`prunable` are `{reason}` objects and can co-occur; `operation` is `"rebase"` or `"merge"`; `changes` holds the five working-tree flags plus `conflicted` and `diff {added, deleted}` |
+| `default_branch` | Relation to the default branch: `{ahead, behind, diff, orphan, integration, merge_conflicts}`; absent on the default branch itself. `integration.reason` is one of `same_commit`, `ancestor`, `no_added_changes`, `trees_match`, `merge_adds_nothing`, `patch_id_match`; a dirty tree skips the checks, leaving `integration` null |
+| `upstream` | Tracking branch: `{remote, branch, ahead, behind}`; absent when none is configured |
+| `pr` | Open PR/MR: `{number, url, review, mergeable, repo}`; collected with `--full` or a listed `ci` column. `review` uses the schema 1 `ci.review_state` vocabulary; `mergeable` is false when the forge reports conflicts, null otherwise |
+| `checks` | CI pipeline: `{status, source, stale}`; `status` is `passed`, `running`, or `failed` — null when a conflicts report masks it |
+| `dev_server` | `{url, listening}` from the project's `list.url` template |
+| `summary` | LLM branch summary (requires `[list] summary = true`) |
+| `vars` | Per-branch variables from [`wt config state vars`](@/config.md#wt-config-state-vars) |
+| `display` | Rendered strings: `state` (schema 1's `main_state` vocabulary), `symbols`, `statusline` (with ANSI colors), `columns` (custom-column cells keyed by header) |
+
+Schema 1 names map directly: `commit` → `head`, `working_tree` →
+`worktree.changes`, `main` + `main_state` → `default_branch` +
+`display.state`, `remote` → `upstream`, `ci` → `pr` + `checks`, `url` +
+`url_active` → `dev_server`, `statusline`/`symbols`/`columns` → `display.*`,
+and the per-item `repo` moves to the envelope's `repo.forge`.
+
+{{ terminal(cmd="# Current worktree path (for scripts)|||wt list --format=json | jq -r '.items[] | select(.worktree.current) | .worktree.path'||||||# Branches with uncommitted changes|||wt list --format=json | jq '.items[] | select(.worktree.changes.modified)'||||||# Integrated branches (safe to remove)|||wt list --format=json | jq '.items[] | select(.display.state == __WT_QUOT__integrated__WT_QUOT__ or .display.state == __WT_QUOT__empty__WT_QUOT__) | .branch'||||||# Worktrees ahead of upstream (needs pushing)|||wt list --format=json | jq '.items[] | select(.upstream.ahead > 0) | .branch'") }}
+
+### Schema 1
+
+The original bare-array format, and the default while unset:
{{ terminal(cmd="# Current worktree path (for scripts)|||wt list --format=json | jq -r '.[] | select(.is_current) | .path'||||||# Branches with uncommitted changes|||wt list --format=json | jq '.[] | select(.working_tree.modified)'||||||# Worktrees with merge conflicts|||wt list --format=json | jq '.[] | select(.operation_state == __WT_QUOT__conflicts__WT_QUOT__)'||||||# Branches ahead of main (needs merging)|||wt list --format=json | jq '.[] | select(.main.ahead > 0) | .branch'||||||# Integrated branches (safe to remove)|||wt list --format=json | jq '.[] | select(.main_state == __WT_QUOT__integrated__WT_QUOT__ or .main_state == __WT_QUOT__empty__WT_QUOT__) | .branch'||||||# Branches without worktrees|||wt list --format=json --branches | jq '.[] | select(.kind == __WT_QUOT__branch__WT_QUOT__) | .branch'||||||# Worktrees ahead of remote (needs pushing)|||wt list --format=json | jq '.[] | select(.remote.ahead > 0) | {branch, ahead: .remote.ahead}'||||||# Stale CI (local changes not reflected in CI)|||wt list --format=json --full | jq '.[] | select(.ci.stale) | .branch'") }}
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 4550246f0..2dfc19435 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -185,6 +185,8 @@ full = false # Show CI status and LLM summaries (--full)
branches = false # Include branches without worktrees (--branches)
remotes = false # Include remote-only branches (--remotes)
+json-schema = 1 # JSON output schema: 1 (current, bare array) or 2 (envelope); unset emits 1 with a warning
+
columns = ["branch", "status", "ci", "path"] # Columns to show, in order — built-ins or custom headers (omit for the default set)
task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disables
@@ -225,8 +227,10 @@ named one. A column whose data source is missing still stays hidden — `summary
needs an LLM command (`[commit.generation]`), `url` needs a `[list] url`
template — since listing can't supply the data.
-The selection drives the table and the `wt switch` picker; `wt list --format
-json` ignores it and emits every field.
+The selection drives the table and the `wt switch` picker. `wt list --format
+json` always emits every field, but a listed gated column (`ci`, `summary`)
+still forces its data collection on, so the JSON carries the same data the
+table shows.
#### Custom columns [experimental]
diff --git a/skills/worktrunk/reference/list.md b/skills/worktrunk/reference/list.md
index 2094d3f63..9367fbda6 100644
--- a/skills/worktrunk/reference/list.md
+++ b/skills/worktrunk/reference/list.md
@@ -202,7 +202,96 @@ These appear across all columns while the table is loading:
## JSON output
-Query structured data with `--format=json`:
+`--format=json` emits structured data in one of two schemas while the format
+migrates: `[list] json-schema = 2` selects the envelope format below, `= 1`
+the original bare-array format. Unset emits schema 1 with a warning; a future
+release flips the default to schema 2 and later removes schema 1.
+
+### Schema 2
+
+One envelope object. Items carry independent facts; rendered strings
+(including the collapsed Status value) live under `display`:
+
+```json
+{
+ "schema": 2,
+ "repo": {
+ "default_branch": "main",
+ "forge": {"url": "https://github.com/org/repo", "provider": "github",
+ "host": "github.com", "owner": "org", "name": "repo", "remote": "origin"}
+ },
+ "collected": {"ci": false, "summary": false},
+ "items": [
+ {
+ "branch": "feature",
+ "head": {"sha": "05a4a45d…", "short_sha": "05a4a45", "subject": "Add login page",
+ "committed_at": "2025-01-01T08:00:00Z"},
+ "worktree": {"path": "/home/user/repo.feature", "main": false, "current": true,
+ "previous": false, "detached": false, "branch_mismatch": false,
+ "changes": {"staged": false, "modified": true, "untracked": false,
+ "renamed": false, "deleted": false, "conflicted": false,
+ "diff": {"added": 10, "deleted": 2}}},
+ "default_branch": {"ahead": 3, "behind": 1, "diff": {"added": 50, "deleted": 20},
+ "orphan": false, "integration": null, "merge_conflicts": false},
+ "upstream": {"remote": "origin", "branch": "feature", "ahead": 0, "behind": 2},
+ "display": {"state": "diverged", "symbols": "!↕", "statusline": "feature …"}
+ }
+ ]
+}
+```
+
+How "no value" reads:
+
+- **Absent** — nothing to report: not applicable (`worktree` on a branch-only
+ row), not requested this run (the envelope's `collected` records what was),
+ or determined-empty (no PR, no lock, not integrated).
+- **`null`** — requested but not determined: a task timed out, the branch was
+ too stale for the expensive checks, or a forge fetch failed. This is the
+ JSON form of the table's `·` placeholder.
+
+jq treats absent and `null` identically in path expressions, so filters need
+no null checks; `has()` distinguishes the two when it matters.
+
+Item fields:
+
+| Field | Description |
+|-------|-------------|
+| `branch` | Branch name; null for a detached-HEAD worktree. Remote rows carry the bare name with the remote in `remote` |
+| `remote` | Remote name, present only on remote-only branch rows |
+| `head` | `{sha, short_sha, subject, committed_at}`; null for unborn branches. `committed_at` is RFC 3339 UTC |
+| `worktree` | `{path, main, current, previous, detached, locked, prunable, branch_mismatch, operation, changes}`; absent on branch-only rows. `locked`/`prunable` are `{reason}` objects and can co-occur; `operation` is `"rebase"` or `"merge"`; `changes` holds the five working-tree flags plus `conflicted` and `diff {added, deleted}` |
+| `default_branch` | Relation to the default branch: `{ahead, behind, diff, orphan, integration, merge_conflicts}`; absent on the default branch itself. `integration.reason` is one of `same_commit`, `ancestor`, `no_added_changes`, `trees_match`, `merge_adds_nothing`, `patch_id_match`; a dirty tree skips the checks, leaving `integration` null |
+| `upstream` | Tracking branch: `{remote, branch, ahead, behind}`; absent when none is configured |
+| `pr` | Open PR/MR: `{number, url, review, mergeable, repo}`; collected with `--full` or a listed `ci` column. `review` uses the schema 1 `ci.review_state` vocabulary; `mergeable` is false when the forge reports conflicts, null otherwise |
+| `checks` | CI pipeline: `{status, source, stale}`; `status` is `passed`, `running`, or `failed` — null when a conflicts report masks it |
+| `dev_server` | `{url, listening}` from the project's `list.url` template |
+| `summary` | LLM branch summary (requires `[list] summary = true`) |
+| `vars` | Per-branch variables from [`wt config state vars`](https://worktrunk.dev/config/#wt-config-state-vars) |
+| `display` | Rendered strings: `state` (schema 1's `main_state` vocabulary), `symbols`, `statusline` (with ANSI colors), `columns` (custom-column cells keyed by header) |
+
+Schema 1 names map directly: `commit` → `head`, `working_tree` →
+`worktree.changes`, `main` + `main_state` → `default_branch` +
+`display.state`, `remote` → `upstream`, `ci` → `pr` + `checks`, `url` +
+`url_active` → `dev_server`, `statusline`/`symbols`/`columns` → `display.*`,
+and the per-item `repo` moves to the envelope's `repo.forge`.
+
+```bash
+# Current worktree path (for scripts)
+$ wt list --format=json | jq -r '.items[] | select(.worktree.current) | .worktree.path'
+
+# Branches with uncommitted changes
+$ wt list --format=json | jq '.items[] | select(.worktree.changes.modified)'
+
+# Integrated branches (safe to remove)
+$ wt list --format=json | jq '.items[] | select(.display.state == "integrated" or .display.state == "empty") | .branch'
+
+# Worktrees ahead of upstream (needs pushing)
+$ wt list --format=json | jq '.items[] | select(.upstream.ahead > 0) | .branch'
+```
+
+### Schema 1
+
+The original bare-array format, and the default while unset:
```bash
# Current worktree path (for scripts)
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 2eaaf62de..db4e855e5 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -945,7 +945,96 @@ These appear across all columns while the table is loading:
## JSON output
-Query structured data with `--format=json`:
+`--format=json` emits structured data in one of two schemas while the format
+migrates: `[list] json-schema = 2` selects the envelope format below, `= 1`
+the original bare-array format. Unset emits schema 1 with a warning; a future
+release flips the default to schema 2 and later removes schema 1.
+
+### Schema 2
+
+One envelope object. Items carry independent facts; rendered strings
+(including the collapsed Status value) live under `display`:
+
+```json
+{
+ "schema": 2,
+ "repo": {
+ "default_branch": "main",
+ "forge": {"url": "https://github.com/org/repo", "provider": "github",
+ "host": "github.com", "owner": "org", "name": "repo", "remote": "origin"}
+ },
+ "collected": {"ci": false, "summary": false},
+ "items": [
+ {
+ "branch": "feature",
+ "head": {"sha": "05a4a45d…", "short_sha": "05a4a45", "subject": "Add login page",
+ "committed_at": "2025-01-01T08:00:00Z"},
+ "worktree": {"path": "/home/user/repo.feature", "main": false, "current": true,
+ "previous": false, "detached": false, "branch_mismatch": false,
+ "changes": {"staged": false, "modified": true, "untracked": false,
+ "renamed": false, "deleted": false, "conflicted": false,
+ "diff": {"added": 10, "deleted": 2}}},
+ "default_branch": {"ahead": 3, "behind": 1, "diff": {"added": 50, "deleted": 20},
+ "orphan": false, "integration": null, "merge_conflicts": false},
+ "upstream": {"remote": "origin", "branch": "feature", "ahead": 0, "behind": 2},
+ "display": {"state": "diverged", "symbols": "!↕", "statusline": "feature …"}
+ }
+ ]
+}
+```
+
+How "no value" reads:
+
+- **Absent** — nothing to report: not applicable (`worktree` on a branch-only
+ row), not requested this run (the envelope's `collected` records what was),
+ or determined-empty (no PR, no lock, not integrated).
+- **`null`** — requested but not determined: a task timed out, the branch was
+ too stale for the expensive checks, or a forge fetch failed. This is the
+ JSON form of the table's `·` placeholder.
+
+jq treats absent and `null` identically in path expressions, so filters need
+no null checks; `has()` distinguishes the two when it matters.
+
+Item fields:
+
+| Field | Description |
+|-------|-------------|
+| `branch` | Branch name; null for a detached-HEAD worktree. Remote rows carry the bare name with the remote in `remote` |
+| `remote` | Remote name, present only on remote-only branch rows |
+| `head` | `{sha, short_sha, subject, committed_at}`; null for unborn branches. `committed_at` is RFC 3339 UTC |
+| `worktree` | `{path, main, current, previous, detached, locked, prunable, branch_mismatch, operation, changes}`; absent on branch-only rows. `locked`/`prunable` are `{reason}` objects and can co-occur; `operation` is `"rebase"` or `"merge"`; `changes` holds the five working-tree flags plus `conflicted` and `diff {added, deleted}` |
+| `default_branch` | Relation to the default branch: `{ahead, behind, diff, orphan, integration, merge_conflicts}`; absent on the default branch itself. `integration.reason` is one of `same_commit`, `ancestor`, `no_added_changes`, `trees_match`, `merge_adds_nothing`, `patch_id_match`; a dirty tree skips the checks, leaving `integration` null |
+| `upstream` | Tracking branch: `{remote, branch, ahead, behind}`; absent when none is configured |
+| `pr` | Open PR/MR: `{number, url, review, mergeable, repo}`; collected with `--full` or a listed `ci` column. `review` uses the schema 1 `ci.review_state` vocabulary; `mergeable` is false when the forge reports conflicts, null otherwise |
+| `checks` | CI pipeline: `{status, source, stale}`; `status` is `passed`, `running`, or `failed` — null when a conflicts report masks it |
+| `dev_server` | `{url, listening}` from the project's `list.url` template |
+| `summary` | LLM branch summary (requires `[list] summary = true`) |
+| `vars` | Per-branch variables from [`wt config state vars`](@/config.md#wt-config-state-vars) |
+| `display` | Rendered strings: `state` (schema 1's `main_state` vocabulary), `symbols`, `statusline` (with ANSI colors), `columns` (custom-column cells keyed by header) |
+
+Schema 1 names map directly: `commit` → `head`, `working_tree` →
+`worktree.changes`, `main` + `main_state` → `default_branch` +
+`display.state`, `remote` → `upstream`, `ci` → `pr` + `checks`, `url` +
+`url_active` → `dev_server`, `statusline`/`symbols`/`columns` → `display.*`,
+and the per-item `repo` moves to the envelope's `repo.forge`.
+
+```console
+# Current worktree path (for scripts)
+$ wt list --format=json | jq -r '.items[] | select(.worktree.current) | .worktree.path'
+
+# Branches with uncommitted changes
+$ wt list --format=json | jq '.items[] | select(.worktree.changes.modified)'
+
+# Integrated branches (safe to remove)
+$ wt list --format=json | jq '.items[] | select(.display.state == "integrated" or .display.state == "empty") | .branch'
+
+# Worktrees ahead of upstream (needs pushing)
+$ wt list --format=json | jq '.items[] | select(.upstream.ahead > 0) | .branch'
+```
+
+### Schema 1
+
+The original bare-array format, and the default while unset:
```console
# Current worktree path (for scripts)
@@ -1913,6 +2002,8 @@ full = false # Show CI status and LLM summaries (--full)
branches = false # Include branches without worktrees (--branches)
remotes = false # Include remote-only branches (--remotes)
+json-schema = 1 # JSON output schema: 1 (current, bare array) or 2 (envelope); unset emits 1 with a warning
+
columns = ["branch", "status", "ci", "path"] # Columns to show, in order — built-ins or custom headers (omit for the default set)
task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disables
@@ -1953,8 +2044,10 @@ named one. A column whose data source is missing still stays hidden — `summary
needs an LLM command (`[commit.generation]`), `url` needs a `[list] url`
template — since listing can't supply the data.
-The selection drives the table and the `wt switch` picker; `wt list --format
-json` ignores it and emits every field.
+The selection drives the table and the `wt switch` picker. `wt list --format
+json` always emits every field, but a listed gated column (`ci`, `summary`)
+still forces its data collection on, so the JSON carries the same data the
+table shows.
#### Custom columns [experimental]
diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rs
index 89b4e5d2d..08c923e7b 100644
--- a/src/commands/list/collect/execution.rs
+++ b/src/commands/list/collect/execution.rs
@@ -159,13 +159,18 @@ impl ExpectedResults {
/// default up front lets the gate resolve normally instead of showing `·`
/// forever.
///
-/// **Not seeded by this function:** `item.counts`. The ahead/behind counts
-/// are the only field that leaks directly into JSON output (`JsonMain` at
-/// `json_output.rs:~305`), so seeding them with `(0, 0)` would falsely
-/// claim "in sync" in `wt list --format=json` output. Callers that need to
-/// resolve gate 3 (main_state) for items without counts should instead
-/// pre-seed `status_symbols.main_state` directly — see
-/// [`seed_unborn_main_state`].
+/// **Not seeded by this function:** `item.counts`. Seeding the ahead/behind
+/// counts with `(0, 0)` would falsely claim "in sync" in JSON output
+/// (`JsonMain` / `JsonDefaultBranch`). Callers that need to resolve gate 3
+/// (main_state) for items without counts should instead pre-seed
+/// `status_symbols.main_state` directly — see [`seed_unborn_main_state`].
+///
+/// **Seeds are recorded on [`ListItem::seeded`]**: several seeded fields DO
+/// reach schema-2 JSON (`orphan`, `upstream`, `merge_conflicts`, the
+/// integration signals), where a conservative default would read as a
+/// determined fact. `json_v2` consults the flags and emits null
+/// (undetermined) for seeded families; the table keeps rendering the
+/// conservative value.
///
/// Non-status-feeding tasks (`BranchDiff`, `CiStatus`, `UrlStatus`,
/// `SummaryGenerate`) are rendered by their own columns with their own
@@ -181,37 +186,43 @@ pub(super) fn seed_skipped_task_defaults(item: &mut ListItem, kind: TaskKind) {
| TaskKind::SummaryGenerate => {}
TaskKind::AheadBehind => {
- // Seed `is_orphan` (safe — not in JSON) but NOT `counts`
- // (leaks to `JsonMain`). Gate 3 callers that need counts-less
- // resolution use `seed_unborn_main_state` to pre-seed
+ // Seed `is_orphan` but NOT `counts` (leaks to JSON as a false
+ // "in sync"). Gate 3 callers that need counts-less resolution
+ // use `seed_unborn_main_state` to pre-seed
// `status_symbols.main_state` directly.
item.is_orphan = Some(false);
+ item.seeded.orphan = true;
}
TaskKind::Upstream => {
- // Safe to seed: `UpstreamStatus::default()` has
- // `remote: None`, so `active()` returns `None` and
- // `upstream_to_json` elides the `remote` JSON key. No leak.
+ // `UpstreamStatus::default()` has `remote: None`, so `active()`
+ // returns `None` and the upstream renders as "no upstream".
item.upstream = Some(UpstreamStatus::default());
+ item.seeded.upstream = true;
}
TaskKind::CommittedTreesMatch => {
// Conservative: don't claim integrated if we haven't checked.
item.committed_trees_match = Some(false);
+ item.seeded.integration = true;
}
TaskKind::HasFileChanges => {
// Conservative: assume unique changes exist.
item.has_file_changes = Some(true);
+ item.seeded.integration = true;
}
TaskKind::WouldMergeAdd => {
// Conservative: assume the merge would add changes.
item.would_merge_add = Some(true);
item.is_patch_id_match = Some(false);
+ item.seeded.integration = true;
}
TaskKind::IsAncestor => {
// Conservative: don't claim merged if we haven't checked.
item.is_ancestor = Some(false);
+ item.seeded.integration = true;
}
TaskKind::MergeTreeConflicts => {
item.has_merge_tree_conflicts = Some(false);
+ item.seeded.merge_conflicts = true;
}
TaskKind::UserMarker => {
item.user_marker = Some(None);
@@ -541,6 +552,82 @@ mod tests {
use super::*;
use crate::commands::list::collect::build_worktree_item;
+ /// Every seed arm must point the negative direction: `json_v2` trusts a
+ /// positive `check_integration` match even when sibling signals were
+ /// seeded, which is only sound while no seed can fabricate a match.
+ #[test]
+ fn test_seeds_never_fabricate_integration() {
+ use strum::IntoEnumIterator;
+ use worktrunk::git::{IntegrationSignals, check_integration};
+
+ for kind in TaskKind::iter() {
+ let mut item = ListItem::new_branch("a".repeat(40), "feature".to_string());
+ seed_skipped_task_defaults(&mut item, kind);
+ let signals = IntegrationSignals {
+ is_same_commit: item.counts.map(|c| c.ahead == 0 && c.behind == 0),
+ is_ancestor: item.is_ancestor,
+ has_added_changes: item.has_file_changes,
+ trees_match: item.committed_trees_match,
+ would_merge_add: item.would_merge_add,
+ is_patch_id_match: item.is_patch_id_match,
+ };
+ assert!(
+ check_integration(&signals).is_none(),
+ "{kind:?} seed must not fabricate an integration match"
+ );
+ }
+ }
+
+ /// Producer → consumer: seeding marks the fact families, and schema-2
+ /// JSON reports them as null (undetermined) rather than presenting the
+ /// conservative defaults as determined facts.
+ #[test]
+ fn test_seeded_families_serialize_as_null() {
+ use strum::IntoEnumIterator;
+
+ use crate::commands::list::json_v2::JsonItemV2;
+ use crate::commands::list::model::{AheadBehind, Collected};
+
+ // Seed every skippable task on one item — the drain-timeout worst
+ // case — then load counts (never seeded) so the integration signals
+ // are all `Some`: without the flags this would read as determined
+ // not-integrated.
+ let mut item = ListItem::new_branch("a".repeat(40), "feature".to_string());
+ for kind in TaskKind::iter() {
+ seed_skipped_task_defaults(&mut item, kind);
+ }
+ item.counts = Some(AheadBehind {
+ ahead: 1,
+ behind: 0,
+ });
+
+ let mut all_vars = std::collections::HashMap::new();
+ let json = serde_json::to_value(JsonItemV2::from_list_item(
+ &item,
+ &mut all_vars,
+ Some("main"),
+ Collected::default(),
+ None,
+ &[],
+ ))
+ .unwrap();
+
+ let db = &json["default_branch"];
+ assert!(db["orphan"].is_null(), "seeded orphan must be null");
+ assert!(
+ db["merge_conflicts"].is_null(),
+ "seeded merge_conflicts must be null"
+ );
+ assert!(
+ db.get("integration").is_some_and(|v| v.is_null()),
+ "seeded integration must be null"
+ );
+ assert!(
+ json.get("upstream").is_some_and(|v| v.is_null()),
+ "seeded upstream must be null"
+ );
+ }
+
#[test]
fn test_skip_url_status_suppresses_placeholder_and_task() {
let test = worktrunk::testing::TestRepo::new();
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index fac94296a..698c47811 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -1127,6 +1127,7 @@ pub fn collect(
status_symbols: StatusSymbols::default(),
statusline: None,
custom_values: Vec::new(),
+ seeded: super::model::SeededFacts::default(),
kind: ItemKind::Worktree(Box::new(worktree_data)),
}
})
@@ -1216,8 +1217,11 @@ pub fn collect(
// a listed `summary` that `Default` alone wouldn't plan (LLM command set,
// `[list] summary` off): without it the picker would hide a column `wt list`
// shows. CI is already covered — the picker is always `show_full`.
- // - `--format json` → `all_columns` (source `Default`), ignoring the
- // selection: its every-field contract (`src/cli/mod.rs`) needs the full set.
+ // - `--format json` → `all_columns` unioned with the selection's forced-on
+ // columns: the every-field contract (`src/cli/mod.rs`) needs the full
+ // set, never a narrowing — but a listed `ci` forces the fetch on, so
+ // JSON reports the same data the table shows (and `collected.ci` says
+ // so).
//
// So a branch/path `ls` alias over many dirty worktrees runs no `git status`
// / diffs / ahead-behind walks (#3133), while a default column gated off by
@@ -1246,12 +1250,12 @@ pub fn collect(
render_table && progressive_handler.is_none() && !selected_columns.is_empty();
let tasks = if prune_to_selection {
listed_plan()
- } else if progressive_handler.is_some() {
+ } else {
+ // Picker and JSON: the full set plus the selection's forced-on
+ // columns (a no-op when nothing is selected).
let mut tasks = full_plan();
tasks.extend(listed_plan());
tasks
- } else {
- full_plan()
};
// The picker primes its CI cells from the local cache so the column paints
@@ -1296,6 +1300,13 @@ pub fn collect(
// keeps rows untruncated rather than wrapping at a guessed width
let max_width = crate::display::terminal_width().unwrap_or(usize::MAX);
+ // Which gated fact families the plan requested — recorded on `ListData`
+ // so JSON output can distinguish "not requested" from "undetermined".
+ let collected = super::model::Collected {
+ ci: tasks.contains(&TaskKind::CiStatus),
+ summary: tasks.contains(&TaskKind::SummaryGenerate),
+ };
+
// Create collection options from the planned task set. `integration_targets`
// is patched in after the parallel phase below extracts it — at this
// point we haven't yet resolved it, but task spawning doesn't happen
@@ -2025,6 +2036,7 @@ pub fn collect(
Ok(Some(super::model::ListData {
items,
custom_columns,
+ collected,
}))
}
@@ -2123,6 +2135,7 @@ pub fn build_worktree_item(
status_symbols: StatusSymbols::default(),
statusline: None,
custom_values: Vec::new(),
+ seeded: super::model::SeededFacts::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(
wt,
is_main,
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index dde4097d4..31e452d1e 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -869,6 +869,7 @@ impl Task for UpstreamTask {
item_idx: ctx.item_idx,
upstream: UpstreamStatus {
remote,
+ upstream_short: Some(upstream_branch),
ahead,
behind,
},
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rs
index 03497e81e..2838296f6 100644
--- a/src/commands/list/json_output.rs
+++ b/src/commands/list/json_output.rs
@@ -388,22 +388,13 @@ impl JsonItem {
let symbols = Some(format_raw_symbols(&item.status_symbols)).filter(|s| !s.is_empty());
// Per-branch vars data (pre-fetched, moved out to avoid cloning)
- let vars = item
- .branch
- .as_deref()
- .and_then(|b| all_vars.remove(b))
- .unwrap_or_default();
+ let vars = super::json_v2::take_vars(item.branch.as_deref(), all_vars);
// Summary: flatten Option<Option<String>> → Option<String>
let summary = item.summary.as_ref().and_then(|s| s.clone());
// Rendered custom column values, keyed by header; empty cells omitted
- let columns = custom_columns
- .iter()
- .zip(&item.custom_values)
- .filter(|(_, value)| !value.is_empty())
- .map(|(column, value)| (column.name.clone(), value.clone()))
- .collect();
+ let columns = super::json_v2::columns_map(custom_columns, &item.custom_values);
JsonItem {
branch: item.branch.clone(),
@@ -488,9 +479,7 @@ impl JsonCi {
/// a self-hosted instance whose host can't be auto-detected still report the
/// right provider.
pub(crate) fn from_pr_status(pr: &PrStatus, provider_override: Option<&str>) -> Self {
- let repo = pr.url.as_deref().and_then(|url| {
- worktrunk::git::remote_ref::repo_info_from_ref_url_with_provider(url, provider_override)
- });
+ let repo = super::json_v2::pr_target_repo(pr.url.as_deref(), provider_override);
Self {
status: pr.ci_status.into(),
source: pr.source,
@@ -516,7 +505,9 @@ impl JsonCi {
/// simply absent from the output string, not replaced by a placeholder.
/// This matches the per-symbol atomic model: machine consumers see only the
/// symbols that have been computed so far.
-fn format_raw_symbols(symbols: &super::model::StatusSymbols) -> String {
+///
+/// Shared with `json_v2` (the `display.symbols` field).
+pub(crate) fn format_raw_symbols(symbols: &super::model::StatusSymbols) -> String {
let mut result = String::new();
// Working tree symbols (gate 1)
@@ -774,6 +765,7 @@ mod tests {
remote: Some("origin".to_string()),
ahead: 3,
behind: 2,
+ ..Default::default()
};
let branch = Some("feature".to_string());
let json = upstream_to_json(&upstream, &branch);
@@ -791,6 +783,7 @@ mod tests {
remote: None,
ahead: 0,
behind: 0,
+ ..Default::default()
};
let branch = Some("feature".to_string());
let json = upstream_to_json(&upstream, &branch);
@@ -803,6 +796,7 @@ mod tests {
remote: Some("origin".to_string()),
ahead: 1,
behind: 0,
+ ..Default::default()
};
let branch = None;
let json = upstream_to_json(&upstream, &branch);
diff --git a/src/commands/list/json_v2.rs b/src/commands/list/json_v2.rs
new file mode 100644
index 000000000..00940c88d
--- /dev/null
+++ b/src/commands/list/json_v2.rs
@@ -0,0 +1,1271 @@
+//! Schema-2 JSON output for `wt list --format=json` and
+//! `wt list statusline --format=json`.
+//!
+//! One envelope over per-item orthogonal facts, with presentation
+//! quarantined under `display`. Selected by `[list] json-schema = 2`;
+//! schema 1 is the bare-array format in [`super::json_output`].
+//!
+//! ## The absence rule
+//!
+//! - **Absent** — nothing to report: not applicable to this row, not
+//! requested this run (the envelope's `collected` records what was
+//! requested), or determined-empty (no PR, no lock, not integrated).
+//! - **`null`** — requested and applicable, but not determined: a gate timed
+//! out, the branch fell past the staleness cutoff, or a forge fetch failed.
+//! - **Value** — determined.
+//!
+//! [`Tri`] encodes the rule. jq treats absent and `null` identically in path
+//! expressions, so filters stay one-liners; careful consumers distinguish via
+//! `has()`. This is the JSON spelling of the table's `·` placeholder,
+//! generalizing the care schema 1 takes only for `working_tree`.
+
+use std::collections::{BTreeMap, HashMap};
+use std::path::PathBuf;
+
+use schemars::JsonSchema;
+use serde::Serialize;
+use worktrunk::git::{
+ GitRepoInfo, IntegrationReason, IntegrationSignals, Repository, check_integration,
+};
+
+use super::ci_status::{CiSource, CiStatus, PrStatus, ReviewState};
+use super::custom_columns::ResolvedCustomColumn;
+use super::json_output::{JsonDiff, format_raw_symbols};
+use super::model::{ActiveGitOperation, BranchScope, Collected, ItemKind, ListItem, WorktreeData};
+
+/// Tri-state field encoding the absence rule (see module docs).
+#[derive(Debug, Clone, PartialEq)]
+pub enum Tri<T> {
+ /// Nothing to report — the field is skipped entirely.
+ Absent,
+ /// Requested and applicable but not determined — serializes as `null`.
+ Unknown,
+ /// Determined.
+ Known(T),
+}
+
+impl<T> Tri<T> {
+ pub fn is_absent(&self) -> bool {
+ matches!(self, Tri::Absent)
+ }
+}
+
+impl<T: Serialize> Serialize for Tri<T> {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ match self {
+ // Absent is normally skipped via `skip_serializing_if`; a bare
+ // serialization (e.g. `serde_json::to_value` on the enum alone)
+ // degrades to null.
+ Tri::Absent | Tri::Unknown => serializer.serialize_none(),
+ Tri::Known(v) => v.serialize(serializer),
+ }
+ }
+}
+
+impl<T: JsonSchema> JsonSchema for Tri<T> {
+ fn schema_name() -> std::borrow::Cow<'static, str> {
+ Option::<T>::schema_name()
+ }
+
+ fn schema_id() -> std::borrow::Cow<'static, str> {
+ Option::<T>::schema_id()
+ }
+
+ fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ Option::<T>::json_schema(generator)
+ }
+}
+
+/// Root envelope.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonEnvelope {
+ /// Output schema version. The unversioned bare-array format is 1.
+ pub schema: u32,
+
+ /// Repo-wide facts, hoisted out of the items.
+ pub repo: JsonRepo,
+
+ /// Which gated fact families this run requested.
+ pub collected: Collected,
+
+ /// One entry per row, in table order.
+ pub items: Vec<JsonItemV2>,
+}
+
+/// Repo-wide facts.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonRepo {
+ /// The branch every `default_branch` object measures against; absent
+ /// when detection failed.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub default_branch: Option<String>,
+
+ /// Forge metadata derived from the primary remote; absent when no
+ /// remote URL parses.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub forge: Option<GitRepoInfo>,
+}
+
+/// One list row: a worktree, a local branch, or a remote-only branch.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonItemV2 {
+ /// Branch name; null for a detached-HEAD worktree. Remote rows carry
+ /// the bare branch name, with the remote in `remote`.
+ pub branch: Option<String>,
+
+ /// Remote name for remote-only branch rows; absent on local rows.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub remote: Option<String>,
+
+ /// HEAD commit; null for unborn branches.
+ pub head: Option<JsonHead>,
+
+ /// Worktree facts; absent on branch-only rows.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub worktree: Option<JsonWorktreeV2>,
+
+ /// Relation to the default branch; absent on the default branch itself.
+ #[serde(skip_serializing_if = "Tri::is_absent")]
+ pub default_branch: Tri<JsonDefaultBranch>,
+
+ /// Tracking-branch relation; absent when no upstream is configured,
+ /// null while unresolved.
+ #[serde(skip_serializing_if = "Tri::is_absent")]
+ pub upstream: Tri<JsonUpstream>,
+
+ /// Open PR/MR; absent when none exists (or CI wasn't collected), null
+ /// when the forge fetch failed.
+ #[serde(skip_serializing_if = "Tri::is_absent")]
+ pub pr: Tri<JsonPr>,
+
+ /// CI pipeline state; absent when no CI exists (or CI wasn't
+ /// collected), null when the forge fetch failed.
+ #[serde(skip_serializing_if = "Tri::is_absent")]
+ pub checks: Tri<JsonChecks>,
+
+ /// Dev server from the project's `list.url` template; absent when not
+ /// configured.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dev_server: Option<JsonDevServer>,
+
+ /// LLM-generated branch summary; absent when summaries are off or none
+ /// was produced, null while pending.
+ #[serde(skip_serializing_if = "Tri::is_absent")]
+ pub summary: Tri<String>,
+
+ /// Custom variables stored via `wt config state vars`.
+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]
+ pub vars: BTreeMap<String, String>,
+
+ /// Presentation: rendered strings for humans and prompt tools.
+ pub display: JsonDisplay,
+}
+
+/// HEAD commit facts.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonHead {
+ /// Full commit SHA.
+ pub sha: String,
+
+ /// Abbreviated per `core.abbrev`, auto-extended for ambiguous prefixes.
+ pub short_sha: String,
+
+ /// Commit subject (first line); null when not loaded (e.g. prunable
+ /// worktrees).
+ pub subject: Option<String>,
+
+ /// Committer time, RFC 3339 UTC; null when not loaded.
+ pub committed_at: Option<String>,
+}
+
+/// Worktree facts. Location attributes (`locked`, `prunable`,
+/// `branch_mismatch`) are independent fields — unlike schema 1's single
+/// `state`, they can co-occur.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonWorktreeV2 {
+ /// Filesystem path.
+ pub path: PathBuf,
+
+ /// This is the main worktree.
+ pub main: bool,
+
+ /// This is the worktree the command ran from.
+ pub current: bool,
+
+ /// This was the previous worktree (`wt switch -`).
+ pub previous: bool,
+
+ /// HEAD is detached.
+ pub detached: bool,
+
+ /// Present when the worktree is locked.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub locked: Option<JsonReason>,
+
+ /// Present when git considers the worktree prunable.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub prunable: Option<JsonReason>,
+
+ /// The checked-out branch doesn't match the branch this worktree was
+ /// created for.
+ pub branch_mismatch: bool,
+
+ /// In-progress operation: `"rebase"` or `"merge"`; absent when none,
+ /// null while unresolved.
+ #[serde(skip_serializing_if = "Tri::is_absent")]
+ pub operation: Tri<&'static str>,
+
+ /// Working-tree state; null while unresolved.
+ pub changes: Option<JsonChanges>,
+}
+
+/// Reason payload for `locked` / `prunable`.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonReason {
+ /// Reason git records; null when none was given.
+ pub reason: Option<String>,
+}
+
+/// Working-tree change facts.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonChanges {
+ /// Has staged files.
+ pub staged: bool,
+ /// Has modified (unstaged) files.
+ pub modified: bool,
+ /// Has untracked files.
+ pub untracked: bool,
+ /// Has renamed files.
+ pub renamed: bool,
+ /// Has deleted files.
+ pub deleted: bool,
+ /// Tracked files carry merge conflicts; null while unresolved.
+ pub conflicted: Option<bool>,
+ /// Lines added/deleted vs HEAD; null while unresolved.
+ pub diff: Option<JsonDiff>,
+}
+
+/// Relation to the default branch — independent facts, not the table's
+/// priority-collapsed symbol (that lives in `display.state`).
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonDefaultBranch {
+ /// Commits ahead; null while unresolved (and for orphans).
+ pub ahead: Option<usize>,
+
+ /// Commits behind; null while unresolved (and for orphans).
+ pub behind: Option<usize>,
+
+ /// Lines added/deleted vs the default branch; null while unresolved.
+ pub diff: Option<JsonDiff>,
+
+ /// No merge-base with the default branch; null while unresolved.
+ pub orphan: Option<bool>,
+
+ /// How committed content is integrated; absent when determined
+ /// not-integrated, null when undetermined (dirty trees skip the
+ /// expensive checks).
+ #[serde(skip_serializing_if = "Tri::is_absent")]
+ pub integration: Tri<JsonIntegration>,
+
+ /// A merge into the default branch would conflict (local `merge-tree`
+ /// simulation); null while unresolved.
+ pub merge_conflicts: Option<bool>,
+}
+
+/// Why committed content counts as integrated.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonIntegration {
+ /// Which check matched: `"same_commit"`, `"ancestor"`,
+ /// `"no_added_changes"`, `"trees_match"`, `"merge_adds_nothing"`, or
+ /// `"patch_id_match"`.
+ pub reason: &'static str,
+}
+
+/// Tracking-branch relation.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonUpstream {
+ /// Remote name.
+ pub remote: String,
+
+ /// Branch name on the remote; null when only the remote is known.
+ pub branch: Option<String>,
+
+ /// Commits ahead of the upstream.
+ pub ahead: usize,
+
+ /// Commits behind the upstream.
+ pub behind: usize,
+}
+
+/// Open PR/MR facts.
+#[derive(Debug, PartialEq, Serialize, JsonSchema)]
+pub struct JsonPr {
+ /// Forge number; null when the forge reported none.
+ pub number: Option<u64>,
+
+ /// URL to the PR/MR page; null when the forge reported none.
+ pub url: Option<String>,
+
+ /// Review state; absent when the forge reports no review signal.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub review: Option<ReviewState>,
+
+ /// Whether the PR merges cleanly into its target: false when the forge
+ /// reports conflicts, null otherwise (the fetch records only the
+ /// conflicted case).
+ pub mergeable: Option<bool>,
+
+ /// The repository the PR/MR targets (the upstream for fork PRs);
+ /// absent when the URL doesn't parse.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub repo: Option<GitRepoInfo>,
+}
+
+/// CI pipeline facts.
+#[derive(Debug, PartialEq, Serialize, JsonSchema)]
+pub struct JsonChecks {
+ /// `"passed"`, `"running"`, or `"failed"`; null when a conflicts report
+ /// masked the pipeline outcome.
+ pub status: Option<&'static str>,
+
+ /// `"pr"` or `"branch"` (branch workflow).
+ pub source: CiSource,
+
+ /// Local HEAD is not what CI ran against.
+ pub stale: bool,
+}
+
+/// Dev server facts.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonDevServer {
+ /// URL from the project's `list.url` template.
+ pub url: String,
+
+ /// The URL's port is listening; null while unresolved.
+ pub listening: Option<bool>,
+}
+
+/// Presentation strings. Everything here is a rendering of facts that
+/// appear elsewhere in the item.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JsonDisplay {
+ /// The table's collapsed default-branch state (one value per row,
+ /// highest priority wins); absent when none applies or unresolved.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub state: Option<&'static str>,
+
+ /// Raw status glyphs without ANSI (e.g. `"+!⊂"`).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub symbols: Option<String>,
+
+ /// Pre-formatted one-line status with ANSI colors, for prompt tools.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub statusline: Option<String>,
+
+ /// Rendered `[list.custom-columns]` cells keyed by header; empty cells
+ /// omitted.
+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]
+ pub columns: BTreeMap<String, String>,
+}
+
+/// `IntegrationReason` wire values. Schema 2 uses snake_case throughout;
+/// the enum's own serde rename (kebab-case) is shared with other surfaces,
+/// so the mapping lives here instead of on the enum.
+fn integration_reason_str(reason: IntegrationReason) -> &'static str {
+ match reason {
+ IntegrationReason::SameCommit => "same_commit",
+ IntegrationReason::Ancestor => "ancestor",
+ IntegrationReason::NoAddedChanges => "no_added_changes",
+ IntegrationReason::TreesMatch => "trees_match",
+ IntegrationReason::MergeAddsNothing => "merge_adds_nothing",
+ IntegrationReason::PatchIdMatch => "patch_id_match",
+ }
+}
+
+/// Build the schema-2 envelope.
+///
+/// Vars come from the bulk config snapshot like schema 1 (see
+/// [`super::json_output::to_json_items`] for the rationale).
+pub fn to_json_envelope(
+ items: &[ListItem],
+ custom_columns: &[ResolvedCustomColumn],
+ repo: &Repository,
+ collected: Collected,
+) -> JsonEnvelope {
+ let mut all_vars = repo.all_vars_from_snapshot().unwrap_or_default();
+ let default_branch = repo.default_branch();
+ let ci_provider_override = repo.forge_platform_override();
+
+ let json_items = items
+ .iter()
+ .map(|item| {
+ JsonItemV2::from_list_item(
+ item,
+ &mut all_vars,
+ default_branch.as_deref(),
+ collected,
+ ci_provider_override.as_deref(),
+ custom_columns,
+ )
+ })
+ .collect();
+
+ envelope_with_items(repo, default_branch, collected, json_items)
+}
+
+/// Wrap pre-built items in the envelope. Used directly by the statusline
+/// path, which builds its single item with pre-fetched vars instead of the
+/// bulk snapshot.
+///
+/// `default_branch` is threaded in rather than resolved here: it must be
+/// the same value the items were measured against, and on item-less paths
+/// (the statusline outside a worktree) the caller passes `None` so this
+/// never triggers detection — `Repository::default_branch()` may reach the
+/// network once per fresh repo, which an every-prompt surface must not do.
+pub fn envelope_with_items(
+ repo: &Repository,
+ default_branch: Option<String>,
+ collected: Collected,
+ items: Vec<JsonItemV2>,
+) -> JsonEnvelope {
+ JsonEnvelope {
+ schema: 2,
+ repo: JsonRepo {
+ default_branch,
+ forge: repo.repo_info(),
+ },
+ collected,
+ items,
+ }
+}
+
+impl JsonItemV2 {
+ pub(crate) fn from_list_item(
+ item: &ListItem,
+ all_vars: &mut HashMap<String, BTreeMap<String, String>>,
+ default_branch: Option<&str>,
+ collected: Collected,
+ ci_provider_override: Option<&str>,
+ custom_columns: &[ResolvedCustomColumn],
+ ) -> Self {
+ let (worktree_data, remote_scope) = match &item.kind {
+ ItemKind::Worktree(data) => (Some(data.as_ref()), false),
+ ItemKind::Branch(scope) => (None, *scope == BranchScope::Remote),
+ };
+
+ // Remote rows store the remote-qualified short name ("origin/feature");
+ // split it into the remote and the bare branch name.
+ let (branch, remote) = match (&item.branch, remote_scope) {
+ (Some(name), true) => match name.split_once('/') {
+ Some((remote, branch)) => (Some(branch.to_string()), Some(remote.to_string())),
+ None => (Some(name.clone()), None),
+ },
+ (name, _) => (name.clone(), None),
+ };
+
+ // HEAD — null for unborn branches (no sentinel strings).
+ let head =
+ (!item.head.is_empty() && item.head != worktrunk::git::NULL_OID).then(|| JsonHead {
+ sha: item.head.clone(),
+ short_sha: item.short_sha.clone(),
+ subject: item.commit.as_ref().map(|c| c.commit_message.clone()),
+ committed_at: item
+ .commit
+ .as_ref()
+ .and_then(|c| worktrunk::utils::format_timestamp_iso8601_opt(c.timestamp)),
+ });
+
+ let worktree = worktree_data.map(json_worktree);
+
+ // The default branch itself gets no relation object. Matching on the
+ // worktree's main flag alone would miss a branch-only row for the
+ // default branch, so compare names too.
+ let is_default_branch_row = worktree_data.is_some_and(|d| d.is_main)
+ || (item.branch.is_some() && item.branch.as_deref() == default_branch);
+ let default_branch = if is_default_branch_row {
+ Tri::Absent
+ } else {
+ Tri::Known(json_default_branch(item, worktree_data))
+ };
+
+ // Upstream: task unresolved (or seeded on skip) → null; resolved
+ // with no upstream configured → absent.
+ let upstream = match &item.upstream {
+ None => Tri::Unknown,
+ Some(_) if item.seeded.upstream => Tri::Unknown,
+ Some(status) => match status.active() {
+ Some(active) => Tri::Known(JsonUpstream {
+ remote: active.remote.to_string(),
+ branch: active.branch.map(str::to_string),
+ ahead: active.ahead,
+ behind: active.behind,
+ }),
+ None => Tri::Absent,
+ },
+ };
+
+ // PR and checks, split from the fetched PrStatus.
+ let (pr, checks) = if !collected.ci {
+ (Tri::Absent, Tri::Absent)
+ } else {
+ match &item.pr_status {
+ // Requested but the task never reported (timeout).
+ None => (Tri::Unknown, Tri::Unknown),
+ // Determined: no PR and no branch workflow.
+ Some(None) => (Tri::Absent, Tri::Absent),
+ Some(Some(status)) => pr_and_checks(status, ci_provider_override),
+ }
+ };
+
+ let dev_server = item.url.clone().map(|url| JsonDevServer {
+ url,
+ listening: item.url_active,
+ });
+
+ let summary = if !collected.summary {
+ Tri::Absent
+ } else {
+ match &item.summary {
+ None => Tri::Unknown,
+ Some(None) => Tri::Absent,
+ Some(Some(s)) => Tri::Known(s.clone()),
+ }
+ };
+
+ let vars = take_vars(item.branch.as_deref(), all_vars);
+ let columns = columns_map(custom_columns, &item.custom_values);
+
+ let display = JsonDisplay {
+ state: item.status_symbols.main_state.and_then(|s| s.as_json_str()),
+ symbols: Some(format_raw_symbols(&item.status_symbols)).filter(|s| !s.is_empty()),
+ statusline: item.statusline.clone(),
+ columns,
+ };
+
+ JsonItemV2 {
+ branch,
+ remote,
+ head,
+ worktree,
+ default_branch,
+ upstream,
+ pr,
+ checks,
+ dev_server,
+ summary,
+ vars,
+ display,
+ }
+ }
+}
+
+fn json_worktree(data: &WorktreeData) -> JsonWorktreeV2 {
+ // Empty lock/prune reasons (git records the state without a message)
+ // become `reason: null`.
+ let reason = |r: &Option<String>| {
+ r.as_ref().map(|reason| JsonReason {
+ reason: Some(reason.clone()).filter(|r| !r.is_empty()),
+ })
+ };
+
+ let operation = match data.git_operation {
+ None => Tri::Unknown,
+ Some(ActiveGitOperation::None) => Tri::Absent,
+ Some(ActiveGitOperation::Rebase) => Tri::Known("rebase"),
+ Some(ActiveGitOperation::Merge) => Tri::Known("merge"),
+ };
+
+ let changes = data.working_tree_status.map(|wt| JsonChanges {
+ staged: wt.staged,
+ modified: wt.modified,
+ untracked: wt.untracked,
+ renamed: wt.renamed,
+ deleted: wt.deleted,
+ conflicted: data.has_conflicts,
+ diff: data.working_tree_diff.map(JsonDiff::from),
+ });
+
+ JsonWorktreeV2 {
+ path: data.path.clone(),
+ main: data.is_main,
+ current: data.is_current,
+ previous: data.is_previous,
+ detached: data.detached,
+ locked: reason(&data.locked),
+ prunable: reason(&data.prunable),
+ branch_mismatch: data.branch_worktree_mismatch,
+ operation,
+ changes,
+ }
+}
+
+fn json_default_branch(item: &ListItem, worktree_data: Option<&WorktreeData>) -> JsonDefaultBranch {
+ // Integration is a committed-content fact, so it comes from the same
+ // signal fields `wt remove` consults (`check_integration`), not from the
+ // table's `main_state` — that collapse folds in working-tree cleanliness,
+ // which belongs to `worktree.changes`, and would make a dirty
+ // squash-merged branch read differently from a dirty same-commit one.
+ //
+ // - a positive match on loaded signals → the reason (a dirty tree can be
+ // integrated: the probes run on the committed HEAD regardless)
+ // - no match with every signal loaded → absent (determined not-integrated)
+ // - any signal unloaded, or seeded on skip → null (undetermined)
+ // Orphans get sentinel counts `{0, 0}` from `AheadBehindTask` (there is
+ // no merge-base to count against — the table short-circuits them at its
+ // orphan tier for the same reason). Guard both readings of the counts:
+ // the sentinel is not a same-commit match, and 0/0 is not a real
+ // ahead/behind.
+ let is_orphan = if item.seeded.orphan {
+ None
+ } else {
+ item.is_orphan
+ };
+ let counts = match is_orphan {
+ Some(false) => item.counts,
+ _ => None,
+ };
+ let signals = IntegrationSignals {
+ is_same_commit: match is_orphan {
+ Some(false) => counts.map(|c| c.ahead == 0 && c.behind == 0),
+ // Unrelated histories cannot be the same commit; unknown
+ // orphanness leaves it unknown.
+ Some(true) => Some(false),
+ None => None,
+ },
+ is_ancestor: item.is_ancestor,
+ has_added_changes: item.has_file_changes,
+ trees_match: item.committed_trees_match,
+ would_merge_add: item.would_merge_add,
+ is_patch_id_match: item.is_patch_id_match,
+ };
+ let signals_loaded = signals.is_same_commit.is_some()
+ && signals.is_ancestor.is_some()
+ && signals.has_added_changes.is_some()
+ && signals.trees_match.is_some()
+ && signals.would_merge_add.is_some()
+ && signals.is_patch_id_match.is_some();
+ let integration = match check_integration(&signals) {
+ // Positive matches are trustworthy even when other signals were
+ // seeded: every seed points the negative direction, so a match can
+ // only come from a computed signal.
+ Some(reason) => Tri::Known(JsonIntegration {
+ reason: integration_reason_str(reason),
+ }),
+ // "Not integrated" is a determination only when every signal was
+ // genuinely computed — a seeded signal means a probe never ran.
+ None if item.seeded.integration => Tri::Unknown,
+ None if signals_loaded => Tri::Absent,
+ None => Tri::Unknown,
+ };
+
+ // Prefer the dirty-tree conflict probe when it ran and found a dirty
+ // tree; otherwise the committed-HEAD merge-tree simulation.
+ let merge_conflicts = if item.seeded.merge_conflicts {
+ None
+ } else {
+ match worktree_data.and_then(|d| d.has_working_tree_conflicts) {
+ Some(Some(conflicts)) => Some(conflicts),
+ _ => item.has_merge_tree_conflicts,
+ }
+ };
+
+ JsonDefaultBranch {
+ ahead: counts.map(|c| c.ahead),
+ behind: counts.map(|c| c.behind),
+ diff: item.branch_diff.map(|bd| JsonDiff::from(bd.diff)),
+ orphan: is_orphan,
+ integration,
+ merge_conflicts,
+ }
+}
+
+/// Split a fetched [`PrStatus`] into the PR facts and the pipeline facts.
+fn pr_and_checks(
+ status: &PrStatus,
+ provider_override: Option<&str>,
+) -> (Tri<JsonPr>, Tri<JsonChecks>) {
+ let checks = match status.ci_status {
+ // A fetch error means we know neither whether a PR exists nor what
+ // the pipeline did.
+ CiStatus::Error => return (Tri::Unknown, Tri::Unknown),
+ CiStatus::NoCI => Tri::Absent,
+ CiStatus::Conflicts => Tri::Known(JsonChecks {
+ // The fetch discards the pipeline outcome when the forge
+ // reports conflicts (see `pr.mergeable`).
+ status: None,
+ source: status.source,
+ stale: status.is_stale,
+ }),
+ CiStatus::Passed | CiStatus::Running | CiStatus::Failed => Tri::Known(JsonChecks {
+ status: Some(status.ci_status.into()),
+ source: status.source,
+ stale: status.is_stale,
+ }),
+ };
+
+ let pr = if status.source == CiSource::PullRequest {
+ let repo = pr_target_repo(status.url.as_deref(), provider_override);
+ Tri::Known(JsonPr {
+ number: status.number.map(|r| r.number),
+ url: status.url.clone(),
+ review: status.review_state,
+ // The fetch collapses forge mergeability into the status enum,
+ // so only the conflicted case is recoverable here.
+ mergeable: (status.ci_status == CiStatus::Conflicts).then_some(false),
+ repo,
+ })
+ } else {
+ Tri::Absent
+ };
+
+ (pr, checks)
+}
+
+/// Move a branch's vars out of the pre-fetched map. Shared by both schemas
+/// so the move-don't-clone semantics can't drift.
+pub(crate) fn take_vars(
+ branch: Option<&str>,
+ all_vars: &mut HashMap<String, BTreeMap<String, String>>,
+) -> BTreeMap<String, String> {
+ branch.and_then(|b| all_vars.remove(b)).unwrap_or_default()
+}
+
+/// Rendered custom-column cells keyed by header, empty cells omitted.
+/// Shared by both schemas.
+pub(crate) fn columns_map(
+ custom_columns: &[ResolvedCustomColumn],
+ values: &[String],
+) -> BTreeMap<String, String> {
+ custom_columns
+ .iter()
+ .zip(values)
+ .filter(|(_, value)| !value.is_empty())
+ .map(|(column, value)| (column.name.clone(), value.clone()))
+ .collect()
+}
+
+/// The repository a PR/MR targets, derived from its URL. Shared by both
+/// schemas so the provider-override plumbing can't drift.
+pub(crate) fn pr_target_repo(
+ url: Option<&str>,
+ provider_override: Option<&str>,
+) -> Option<GitRepoInfo> {
+ url.and_then(|url| {
+ worktrunk::git::remote_ref::repo_info_from_ref_url_with_provider(url, provider_override)
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use insta::assert_snapshot;
+
+ use super::*;
+ use crate::commands::list::ci_status::PrRef;
+ use crate::commands::list::model::{AheadBehind, SeededFacts, UpstreamStatus};
+
+ fn item_with(branch: &str) -> ListItem {
+ ListItem::new_branch("a".repeat(40), branch.to_string())
+ }
+
+ fn to_value(item: &JsonItemV2) -> serde_json::Value {
+ serde_json::to_value(item).unwrap()
+ }
+
+ fn convert(item: &ListItem, collected: Collected) -> JsonItemV2 {
+ let mut all_vars = HashMap::new();
+ JsonItemV2::from_list_item(item, &mut all_vars, Some("main"), collected, None, &[])
+ }
+
+ fn pr_status(ci_status: CiStatus, source: CiSource) -> PrStatus {
+ PrStatus {
+ ci_status,
+ source,
+ is_stale: false,
+ is_priming: false,
+ url: None,
+ number: None,
+ review_state: None,
+ title: None,
+ body: None,
+ author: None,
+ comment_count: None,
+ updated_at: None,
+ }
+ }
+
+ #[test]
+ fn test_absence_rule_unresolved_vs_determined() {
+ // Fresh branch item: nothing resolved. Gated families absent (not
+ // requested); ungated families null (requested, undetermined).
+ let item = item_with("feature");
+ let json = to_value(&convert(&item, Collected::default()));
+
+ // Not requested → absent.
+ assert!(json.get("pr").is_none());
+ assert!(json.get("checks").is_none());
+ assert!(json.get("summary").is_none());
+ // Requested but unresolved → null.
+ assert!(json.get("upstream").is_some_and(|v| v.is_null()));
+ let db = json.get("default_branch").unwrap();
+ assert!(db.get("ahead").unwrap().is_null());
+ assert!(db.get("orphan").unwrap().is_null());
+ assert!(db.get("integration").is_some_and(|v| v.is_null()));
+ assert!(db.get("merge_conflicts").unwrap().is_null());
+ // Branch row → no worktree, no remote.
+ assert!(json.get("worktree").is_none());
+ assert!(json.get("remote").is_none());
+ }
+
+ #[test]
+ fn test_requested_ci_without_result_is_null() {
+ let item = item_with("feature");
+ let json = to_value(&convert(
+ &item,
+ Collected {
+ ci: true,
+ summary: false,
+ },
+ ));
+ assert!(json.get("pr").is_some_and(|v| v.is_null()));
+ assert!(json.get("checks").is_some_and(|v| v.is_null()));
+ }
+
+ #[test]
+ fn test_determined_no_pr_is_absent() {
+ let mut item = item_with("feature");
+ item.pr_status = Some(None);
+ let json = to_value(&convert(
+ &item,
+ Collected {
+ ci: true,
+ summary: false,
+ },
+ ));
+ assert!(json.get("pr").is_none());
+ assert!(json.get("checks").is_none());
+ }
+
+ #[test]
+ fn test_pr_and_checks_split() {
+ let status = PrStatus {
+ is_stale: true,
+ url: Some("https://github.com/org/repo/pull/7".to_string()),
+ number: Some(PrRef::pr(7)),
+ review_state: Some(ReviewState::Approved),
+ ..pr_status(CiStatus::Passed, CiSource::PullRequest)
+ };
+ let (pr, checks) = pr_and_checks(&status, None);
+ assert_eq!(
+ pr,
+ Tri::Known(JsonPr {
+ number: Some(7),
+ url: Some("https://github.com/org/repo/pull/7".to_string()),
+ review: Some(ReviewState::Approved),
+ mergeable: None,
+ repo: pr_target_repo(Some("https://github.com/org/repo/pull/7"), None),
+ })
+ );
+ assert_eq!(
+ checks,
+ Tri::Known(JsonChecks {
+ status: Some("passed"),
+ source: CiSource::PullRequest,
+ stale: true,
+ })
+ );
+ }
+
+ #[test]
+ fn test_conflicts_becomes_pr_mergeable() {
+ let status = PrStatus {
+ number: Some(PrRef::pr(9)),
+ ..pr_status(CiStatus::Conflicts, CiSource::PullRequest)
+ };
+ let (pr, checks) = pr_and_checks(&status, None);
+ assert_eq!(
+ pr,
+ Tri::Known(JsonPr {
+ number: Some(9),
+ url: None,
+ review: None,
+ mergeable: Some(false),
+ repo: None,
+ })
+ );
+ // Conflicts masks the pipeline outcome.
+ assert_eq!(
+ checks,
+ Tri::Known(JsonChecks {
+ status: None,
+ source: CiSource::PullRequest,
+ stale: false,
+ })
+ );
+ }
+
+ #[test]
+ fn test_fetch_error_is_unknown() {
+ let status = pr_status(CiStatus::Error, CiSource::Branch);
+ let (pr, checks) = pr_and_checks(&status, None);
+ assert_eq!(pr, Tri::Unknown);
+ assert_eq!(checks, Tri::Unknown);
+ }
+
+ #[test]
+ fn test_branch_workflow_has_checks_but_no_pr() {
+ let status = pr_status(CiStatus::Failed, CiSource::Branch);
+ let (pr, checks) = pr_and_checks(&status, None);
+ assert!(pr.is_absent());
+ assert_eq!(
+ checks,
+ Tri::Known(JsonChecks {
+ status: Some("failed"),
+ source: CiSource::Branch,
+ stale: false,
+ })
+ );
+ }
+
+ #[test]
+ fn test_remote_row_splits_branch_and_remote() {
+ let mut item = item_with("origin/feature");
+ item.kind = ItemKind::Branch(BranchScope::Remote);
+ let json = to_value(&convert(&item, Collected::default()));
+ assert_eq!(json["branch"], "feature");
+ assert_eq!(json["remote"], "origin");
+ }
+
+ #[test]
+ fn test_unborn_branch_head_is_null() {
+ let mut item = item_with("new");
+ item.head = worktrunk::git::NULL_OID.to_string();
+ let json = to_value(&convert(&item, Collected::default()));
+ assert!(json["head"].is_null());
+ }
+
+ #[test]
+ fn test_default_branch_row_has_no_relation() {
+ let item = item_with("main");
+ let json = to_value(&convert(&item, Collected::default()));
+ assert!(json.get("default_branch").is_none());
+ }
+
+ /// Seed every integration signal to "not integrated" — the state after
+ /// a full drain with no positive match.
+ fn load_not_integrated_signals(item: &mut ListItem) {
+ item.is_orphan = Some(false);
+ item.counts = Some(AheadBehind {
+ ahead: 1,
+ behind: 0,
+ });
+ item.is_ancestor = Some(false);
+ item.has_file_changes = Some(true);
+ item.committed_trees_match = Some(false);
+ item.would_merge_add = Some(true);
+ item.is_patch_id_match = Some(false);
+ }
+
+ #[test]
+ fn test_orphan_sentinel_counts_do_not_fabricate_integration() {
+ // AheadBehindTask reports orphans with sentinel counts {0, 0}; the
+ // sentinel must not read as a same-commit match nor as real counts.
+ let mut item = item_with("orphan");
+ item.is_orphan = Some(true);
+ item.counts = Some(AheadBehind {
+ ahead: 0,
+ behind: 0,
+ });
+ let json = to_value(&convert(&item, Collected::default()));
+ let db = &json["default_branch"];
+ assert_eq!(db["orphan"], true);
+ assert!(db["ahead"].is_null(), "sentinel counts must not serialize");
+ assert!(db["behind"].is_null());
+ assert!(
+ db.get("integration").is_some_and(|v| v.is_null()),
+ "orphan sentinel must not fabricate same_commit"
+ );
+ }
+
+ #[test]
+ fn test_integration_same_commit_from_signals() {
+ let mut item = item_with("feature");
+ item.is_orphan = Some(false);
+ item.counts = Some(AheadBehind {
+ ahead: 0,
+ behind: 0,
+ });
+ let json = to_value(&convert(&item, Collected::default()));
+ // A positive match fires even with the other signals unloaded.
+ assert_eq!(
+ json["default_branch"]["integration"]["reason"],
+ "same_commit"
+ );
+ }
+
+ #[test]
+ fn test_integration_positive_match_ignores_cleanliness() {
+ // Integration is a committed-content fact: a squash-merged branch
+ // reports its reason even though new uncommitted edits exist (the
+ // dirty tree lives in worktree.changes, not here).
+ let mut item = item_with("feature");
+ load_not_integrated_signals(&mut item);
+ item.committed_trees_match = Some(true);
+ let json = to_value(&convert(&item, Collected::default()));
+ assert_eq!(
+ json["default_branch"]["integration"]["reason"],
+ "trees_match"
+ );
+ }
+
+ #[test]
+ fn test_integration_all_signals_loaded_not_integrated_is_absent() {
+ let mut item = item_with("feature");
+ load_not_integrated_signals(&mut item);
+ let json = to_value(&convert(&item, Collected::default()));
+ // Every signal computed and none matched: determined → absent.
+ assert!(json["default_branch"].get("integration").is_none());
+ }
+
+ #[test]
+ fn test_integration_partial_signals_is_null() {
+ let mut item = item_with("feature");
+ load_not_integrated_signals(&mut item);
+ item.would_merge_add = None; // probe still pending
+ let json = to_value(&convert(&item, Collected::default()));
+ assert!(
+ json["default_branch"]
+ .get("integration")
+ .is_some_and(|v| v.is_null()),
+ "unloaded signal cannot rule integration out"
+ );
+ }
+
+ #[test]
+ fn test_seeded_facts_serialize_as_null() {
+ // Seeded conservative defaults (timeout, unborn branch) must not
+ // read as determined facts.
+ let mut item = item_with("feature");
+ load_not_integrated_signals(&mut item);
+ item.is_orphan = Some(false);
+ item.has_merge_tree_conflicts = Some(false);
+ item.upstream = Some(UpstreamStatus::default());
+ item.seeded = SeededFacts {
+ orphan: true,
+ upstream: true,
+ merge_conflicts: true,
+ integration: true,
+ };
+ let json = to_value(&convert(&item, Collected::default()));
+ let db = &json["default_branch"];
+ assert!(db["orphan"].is_null());
+ assert!(db["merge_conflicts"].is_null());
+ assert!(db.get("integration").is_some_and(|v| v.is_null()));
+ assert!(json.get("upstream").is_some_and(|v| v.is_null()));
+ }
+
+ #[test]
+ fn test_seeded_integration_still_reports_positive_match() {
+ // Seeds all point the negative direction, so a computed positive
+ // signal stays trustworthy even when siblings were seeded.
+ let mut item = item_with("feature");
+ load_not_integrated_signals(&mut item);
+ item.is_ancestor = Some(true);
+ item.seeded.integration = true;
+ let json = to_value(&convert(&item, Collected::default()));
+ assert_eq!(json["default_branch"]["integration"]["reason"], "ancestor");
+ }
+
+ #[test]
+ fn test_upstream_known_with_branch() {
+ let mut item = item_with("feature");
+ item.upstream = Some(UpstreamStatus {
+ remote: Some("origin".to_string()),
+ upstream_short: Some("origin/feature".to_string()),
+ ahead: 2,
+ behind: 1,
+ });
+ let json = to_value(&convert(&item, Collected::default()));
+ assert_eq!(json["upstream"]["remote"], "origin");
+ assert_eq!(json["upstream"]["branch"], "feature");
+ assert_eq!(json["upstream"]["ahead"], 2);
+ }
+
+ #[test]
+ fn test_no_upstream_configured_is_absent() {
+ let mut item = item_with("feature");
+ item.upstream = Some(UpstreamStatus::default());
+ let json = to_value(&convert(&item, Collected::default()));
+ assert!(json.get("upstream").is_none());
+ }
+
+ fn worktree_item(branch: &str, data: WorktreeData) -> ListItem {
+ let mut item = item_with(branch);
+ item.kind = ItemKind::Worktree(Box::new(data));
+ item
+ }
+
+ /// The derived schema must generate cleanly — `Tri<T>`'s JsonSchema
+ /// delegation to `Option<T>` is only exercised here until the schema
+ /// export ships.
+ #[test]
+ fn test_schema_generates() {
+ let schema = schemars::schema_for!(JsonEnvelope);
+ let json = serde_json::to_value(&schema).unwrap();
+ assert!(json["properties"]["items"].is_object());
+ }
+
+ #[test]
+ fn test_integration_reason_str_covers_every_reason() {
+ let cases = [
+ (IntegrationReason::SameCommit, "same_commit"),
+ (IntegrationReason::Ancestor, "ancestor"),
+ (IntegrationReason::NoAddedChanges, "no_added_changes"),
+ (IntegrationReason::TreesMatch, "trees_match"),
+ (IntegrationReason::MergeAddsNothing, "merge_adds_nothing"),
+ (IntegrationReason::PatchIdMatch, "patch_id_match"),
+ ];
+ for (reason, expected) in cases {
+ assert_eq!(integration_reason_str(reason), expected);
+ }
+ }
+
+ #[test]
+ fn test_remote_row_without_slash_keeps_name() {
+ let mut item = item_with("weird");
+ item.kind = ItemKind::Branch(BranchScope::Remote);
+ let json = to_value(&convert(&item, Collected::default()));
+ assert_eq!(json["branch"], "weird");
+ assert!(json.get("remote").is_none());
+ }
+
+ #[test]
+ fn test_loaded_item_serializes_gated_families() {
+ // One item with every gated family loaded: PR + checks through the
+ // envelope path, dev server, and a produced summary.
+ let mut item = item_with("feature");
+ item.pr_status = Some(Some(PrStatus {
+ url: Some("https://github.com/org/repo/pull/7".to_string()),
+ number: Some(PrRef::pr(7)),
+ ..pr_status(CiStatus::Passed, CiSource::PullRequest)
+ }));
+ item.url = Some("http://127.0.0.1:3000".to_string());
+ item.url_active = Some(true);
+ item.summary = Some(Some("Adds the login page".to_string()));
+ let collected = Collected {
+ ci: true,
+ summary: true,
+ };
+ let json = to_value(&convert(&item, collected));
+ assert_eq!(json["pr"]["number"], 7);
+ assert_eq!(json["checks"]["status"], "passed");
+ assert_eq!(json["dev_server"]["url"], "http://127.0.0.1:3000");
+ assert_eq!(json["dev_server"]["listening"], true);
+ assert_eq!(json["summary"], "Adds the login page");
+ }
+
+ #[test]
+ fn test_summary_requested_arms() {
+ // Requested but pending → null; produced-nothing → absent.
+ let collected = Collected {
+ ci: false,
+ summary: true,
+ };
+ let json = to_value(&convert(&item_with("feature"), collected));
+ assert!(json.get("summary").is_some_and(|v| v.is_null()));
+
+ let mut item = item_with("feature");
+ item.summary = Some(None);
+ let json = to_value(&convert(&item, collected));
+ assert!(json.get("summary").is_none());
+ }
+
+ #[test]
+ fn test_operation_arms() {
+ let unresolved = worktree_item("feature", WorktreeData::default());
+ let json = to_value(&convert(&unresolved, Collected::default()));
+ assert!(
+ json["worktree"]
+ .get("operation")
+ .is_some_and(|v| v.is_null())
+ );
+
+ for (op, expected) in [
+ (ActiveGitOperation::Rebase, "rebase"),
+ (ActiveGitOperation::Merge, "merge"),
+ ] {
+ let item = worktree_item(
+ "feature",
+ WorktreeData {
+ git_operation: Some(op),
+ ..Default::default()
+ },
+ );
+ let json = to_value(&convert(&item, Collected::default()));
+ assert_eq!(json["worktree"]["operation"], expected);
+ }
+ }
+
+ #[test]
+ fn test_dirty_tree_conflict_probe_wins() {
+ let mut item = worktree_item(
+ "feature",
+ WorktreeData {
+ has_working_tree_conflicts: Some(Some(true)),
+ ..Default::default()
+ },
+ );
+ item.has_merge_tree_conflicts = Some(false);
+ let json = to_value(&convert(&item, Collected::default()));
+ assert_eq!(json["default_branch"]["merge_conflicts"], true);
+ }
+
+ #[test]
+ fn test_no_ci_checks_absent_pr_known() {
+ let status = PrStatus {
+ number: Some(PrRef::pr(4)),
+ ..pr_status(CiStatus::NoCI, CiSource::PullRequest)
+ };
+ let (pr, checks) = pr_and_checks(&status, None);
+ assert!(checks.is_absent(), "no CI configured is determined-empty");
+ assert_eq!(
+ pr,
+ Tri::Known(JsonPr {
+ number: Some(4),
+ url: None,
+ review: None,
+ mergeable: None,
+ repo: None,
+ })
+ );
+ }
+
+ #[test]
+ fn test_envelope_snapshot_shape() {
+ // Serialize a minimal envelope to pin the top-level shape.
+ let envelope = JsonEnvelope {
+ schema: 2,
+ repo: JsonRepo {
+ default_branch: Some("main".to_string()),
+ forge: None,
+ },
+ collected: Collected {
+ ci: false,
+ summary: false,
+ },
+ items: vec![],
+ };
+ assert_snapshot!(serde_json::to_string_pretty(&envelope).unwrap(), @r#"
+ {
+ "schema": 2,
+ "repo": {
+ "default_branch": "main"
+ },
+ "collected": {
+ "ci": false,
+ "summary": false
+ },
+ "items": []
+ }
+ "#);
+ }
+}
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index 317fdf1fa..3b36d7580 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -1500,6 +1500,7 @@ mod tests {
remote: Some("origin".to_string()),
ahead: 4,
behind: 2,
+ ..Default::default()
}),
pr_status: None,
url: None,
@@ -1510,6 +1511,7 @@ mod tests {
status_symbols: StatusSymbols::default(),
statusline: None,
custom_values: Vec::new(),
+ seeded: Default::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
path: PathBuf::from("/test/path"),
detached: false,
@@ -1625,6 +1627,7 @@ mod tests {
status_symbols: StatusSymbols::default(),
statusline: None,
custom_values: Vec::new(),
+ seeded: Default::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
path: PathBuf::from("/test"),
detached: false,
@@ -1754,6 +1757,7 @@ mod tests {
status_symbols: StatusSymbols::default(),
statusline: None,
custom_values: Vec::new(),
+ seeded: Default::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
path: PathBuf::from("/test/wt"),
detached: false,
@@ -2221,6 +2225,7 @@ mod tests {
status_symbols: StatusSymbols::default(),
statusline: None,
custom_values: Vec::new(),
+ seeded: Default::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
path: PathBuf::from(path),
detached: false,
@@ -2348,6 +2353,7 @@ mod tests {
remote: Some("origin".to_string()),
ahead: 0,
behind: 0,
+ ..Default::default()
});
super::super::model::ListItem {
head: "a620bcfe".to_string(),
@@ -2375,6 +2381,7 @@ mod tests {
status_symbols: StatusSymbols::default(),
statusline: None,
custom_values: Vec::new(),
+ seeded: Default::default(),
kind: ItemKind::Worktree(Box::new(WorktreeData {
path: PathBuf::from(path),
detached: false,
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 12713c71e..f0daa7d99 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -123,6 +123,7 @@ pub(crate) mod collect;
pub(crate) mod columns;
pub(crate) mod custom_columns;
pub mod json_output;
+pub mod json_v2;
pub(crate) mod layout;
pub mod model;
pub mod progressive;
@@ -151,6 +152,11 @@ pub fn handle_list(
) -> anyhow::Result<()> {
let render_target = RenderTarget::detect(format, progressive_flag);
+ // Resolve the JSON schema before collecting, so the unset-nag lands
+ // above the output rather than after a long collection.
+ let json_schema =
+ matches!(render_target, RenderTarget::Json).then(|| resolve_json_schema(&repo));
+
let list_data = collect::collect(
&repo,
collect::ShowConfig::DeferredToParallel {
@@ -164,22 +170,89 @@ pub fn handle_list(
let Some(ListData {
items,
custom_columns,
+ collected,
}) = list_data
else {
return Ok(());
};
- if matches!(render_target, RenderTarget::Json) {
- let json_items = json_output::to_json_items(&items, &custom_columns, &repo);
- let json =
- serde_json::to_string_pretty(&json_items).context("Failed to serialize to JSON")?;
- println!("{}", json);
+ match json_schema {
+ // Table modes already rendered inside `collect()`.
+ None => {}
+ Some(2) => print_json(&json_v2::to_json_envelope(
+ &items,
+ &custom_columns,
+ &repo,
+ collected,
+ ))?,
+ Some(_) => print_json(&json_output::to_json_items(&items, &custom_columns, &repo))?,
}
- // Table modes already rendered inside `collect()`.
Ok(())
}
+/// Serialize a JSON answer to stdout (pretty, one trailing newline).
+pub(crate) fn print_json<T: serde::Serialize>(value: &T) -> anyhow::Result<()> {
+ let json = serde_json::to_string_pretty(value).context("Failed to serialize to JSON")?;
+ println!("{}", json);
+ Ok(())
+}
+
+/// Resolve `[list] json-schema` (per-project resolved config) to 1 or 2.
+///
+/// Unset defaults to schema 1 and nags once per process; an out-of-range
+/// value warns and defaults to schema 1, matching how config load treats a
+/// type error in the same key (warn and degrade, never brick a command).
+/// Both messages honor warning suppression — on the statusline, stderr
+/// would corrupt the consumer's prompt, and the same user sees the nag on
+/// their next interactive run. The nag names both settings so the fix is
+/// copyable from the warning itself.
+pub(crate) fn resolve_json_schema(repo: &Repository) -> u8 {
+ use std::sync::Once;
+
+ use color_print::cformat;
+ use worktrunk::styling::{eprintln, hint_message, warning_message};
+
+ static WARNED: Once = Once::new();
+ match repo.config().list.json_schema {
+ Some(v @ (1 | 2)) => v,
+ Some(other) => {
+ WARNED.call_once(|| {
+ if worktrunk::config::warnings_suppressed() {
+ return;
+ }
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "[list] json-schema is <bold>{other}</>, expected 1 or 2; using schema 1"
+ ))
+ );
+ });
+ 1
+ }
+ None => {
+ WARNED.call_once(|| {
+ if worktrunk::config::warnings_suppressed() {
+ return;
+ }
+ eprintln!(
+ "{}",
+ warning_message(
+ "JSON output is schema 1; a future release switches the default to schema 2"
+ )
+ );
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To keep this format set <underline>[list] json-schema = 1</>; to adopt the new one, <underline>json-schema = 2</>"
+ ))
+ );
+ });
+ 1
+ }
+ }
+}
+
#[derive(Default)]
pub(super) struct SummaryMetrics {
worktrees: usize,
diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rs
index 787b5f7dd..0a755b028 100644
--- a/src/commands/list/model/item.rs
+++ b/src/commands/list/model/item.rs
@@ -292,16 +292,59 @@ pub struct ListItem {
/// columns are configured.
pub custom_values: Vec<String>,
+ /// Which fact families hold *seeded* conservative defaults rather than
+ /// computed results (see `seed_skipped_task_defaults`). The table wants
+ /// the conservative values; schema-2 JSON reports the seeded families as
+ /// null (undetermined) instead of presenting a seed as a determined fact.
+ pub seeded: SeededFacts,
+
// Type-specific data (worktree vs branch)
pub kind: ItemKind,
}
+/// Per-fact-family record of seeded (not computed) values on a [`ListItem`].
+///
+/// Set by `seed_skipped_task_defaults` when a task is skipped (unborn
+/// branch, collect timeout, unplanned task). Consumed by schema-2 JSON
+/// output, whose absence rule distinguishes "determined" from
+/// "undetermined" — a distinction the conservative seeds would otherwise
+/// erase.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct SeededFacts {
+ /// `is_orphan` was seeded (`AheadBehind` skipped).
+ pub orphan: bool,
+ /// `upstream` was seeded (`Upstream` skipped).
+ pub upstream: bool,
+ /// `has_merge_tree_conflicts` was seeded (`MergeTreeConflicts` skipped).
+ pub merge_conflicts: bool,
+ /// One of the integration signals was seeded (`IsAncestor`,
+ /// `CommittedTreesMatch`, `HasFileChanges`, or `WouldMergeAdd` skipped).
+ pub integration: bool,
+}
+
/// Container for list command results.
pub struct ListData {
pub items: Vec<ListItem>,
/// Resolved `[list.custom-columns]` definitions; each item's `custom_values`
/// uses the same indexing.
pub custom_columns: Vec<crate::commands::list::custom_columns::ResolvedCustomColumn>,
+ /// Which gated fact families this run's task plan requested. Lets JSON
+ /// output distinguish "absent because not requested" from "requested but
+ /// undetermined".
+ pub collected: Collected,
+}
+
+/// Fact families whose collection is gated (`--full`, `[list] summary`,
+/// a listed `ci`/`summary` column). Ungated families (working tree, counts,
+/// diffs) are always requested. Serialized as-is into the schema-2 JSON
+/// envelope's `collected` field, disambiguating "absent because not
+/// requested".
+#[derive(Debug, Clone, Copy, Default, serde::Serialize, schemars::JsonSchema)]
+pub struct Collected {
+ /// Forge CI/PR data was fetched.
+ pub ci: bool,
+ /// LLM branch summaries were generated.
+ pub summary: bool,
}
impl ListItem {
@@ -339,6 +382,7 @@ impl ListItem {
status_symbols: StatusSymbols::default(),
statusline: None,
custom_values: Vec::new(),
+ seeded: SeededFacts::default(),
kind: ItemKind::Branch(scope),
}
}
diff --git a/src/commands/list/model/mod.rs b/src/commands/list/model/mod.rs
index 97b09aaa7..0e805b086 100644
--- a/src/commands/list/model/mod.rs
+++ b/src/commands/list/model/mod.rs
@@ -22,7 +22,7 @@ pub mod statusline_segment;
// via `crate::commands::list::model::...` paths. The allow is needed because
// rustc doesn't track re-export usage across module boundaries.
#[allow(unused_imports)]
-pub use item::{BranchScope, ItemKind, ListData, ListItem, WorktreeData};
+pub use item::{BranchScope, Collected, ItemKind, ListData, ListItem, SeededFacts, WorktreeData};
#[allow(unused_imports)]
pub use state::{ActiveGitOperation, Divergence, MainState, OperationState, WorktreeState};
#[allow(unused_imports)]
diff --git a/src/commands/list/model/stats.rs b/src/commands/list/model/stats.rs
index fae1770be..87d487947 100644
--- a/src/commands/list/model/stats.rs
+++ b/src/commands/list/model/stats.rs
@@ -34,6 +34,10 @@ pub struct BranchDiffTotals {
#[derive(Default, Clone, Debug)]
pub struct UpstreamStatus {
pub(crate) remote: Option<String>,
+ /// Upstream short name as git reports it (e.g. `origin/feature`).
+ /// `None` when no upstream is configured; may also be `None` on
+ /// pre-existing constructions that only carry the remote.
+ pub(crate) upstream_short: Option<String>,
pub(crate) ahead: usize,
pub(crate) behind: usize,
}
@@ -41,6 +45,9 @@ pub struct UpstreamStatus {
/// Active upstream tracking information (when a remote is configured).
pub struct ActiveUpstream<'a> {
pub remote: &'a str,
+ /// Branch name on the remote (the upstream short name with the remote
+ /// prefix removed); `None` when only the remote is known.
+ pub branch: Option<&'a str>,
pub ahead: usize,
pub behind: usize,
}
@@ -50,6 +57,11 @@ impl UpstreamStatus {
pub fn active(&self) -> Option<ActiveUpstream<'_>> {
self.remote.as_deref().map(|remote| ActiveUpstream {
remote,
+ branch: self
+ .upstream_short
+ .as_deref()
+ .and_then(|short| short.strip_prefix(remote))
+ .and_then(|rest| rest.strip_prefix('/')),
ahead: self.ahead,
behind: self.behind,
})
@@ -66,6 +78,7 @@ mod tests {
remote: Some("origin".to_string()),
ahead: 3,
behind: 2,
+ ..Default::default()
};
let active = status.active().unwrap();
assert_eq!(active.remote, "origin");
@@ -79,6 +92,7 @@ mod tests {
remote: None,
ahead: 0,
behind: 0,
+ ..Default::default()
};
assert!(status.active().is_none());
}
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index 51a1ab803..bedce267f 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -1943,6 +1943,7 @@ mod tests {
remote: remote.map(String::from),
ahead: a,
behind: b,
+ ..Default::default()
});
LocalContent::from_item(&item).upstream_diverged
};
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index b827bc216..c8a8b36be 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -843,11 +843,55 @@ fn run_json() -> Result<()> {
let repo = Repository::current().context("Not in a git repository")?;
+ // Warnings are suppressed on this surface, so an unset (or invalid) key
+ // resolves to schema 1 silently; the nag reaches the same user on their
+ // next interactive `wt list --format=json`.
+ let json_schema = list::resolve_json_schema(&repo);
+
+ // The statusline renders the full column set condensed (status, diffs,
+ // ahead/behind, upstream, CI, URL — see `format_statusline_segments`) but no
+ // LLM summary, so its plan is every column's tasks under full gates: CI runs,
+ // summary doesn't. URL is gated on a configured template like everywhere else.
+ let url_template = repo.url_template();
+ let gates = list::columns::ColumnGates {
+ show_full: true,
+ summary_enabled: false,
+ has_llm_command: false,
+ has_url_template: url_template.is_some(),
+ };
+ let options = CollectOptions {
+ url_template,
+ // Match `wt list --full`: include untracked files in the working
+ // diff (`HEAD±`) so the segment counts the same lines `wt step
+ // diff` would show, consistent with the rest of the statusline data.
+ include_untracked_in_working_diff: true,
+ ..CollectOptions::for_columns(list::columns::all_columns(), &gates)
+ };
+ // What the schema-2 envelope reports as requested — read from the task
+ // plan itself (like `collect()` does), so it can't drift from the gates.
+ let collected = list::model::Collected {
+ ci: options.tasks.contains(&list::collect::TaskKind::CiStatus),
+ summary: options
+ .tasks
+ .contains(&list::collect::TaskKind::SummaryGenerate),
+ };
+ let print_empty = || -> Result<()> {
+ if json_schema == 2 {
+ // `default_branch: None`: with no items there is no relation to
+ // report, and resolving it here could reach the network on a
+ // fresh clone — this path runs on every prompt redraw.
+ let envelope = list::json_v2::envelope_with_items(&repo, None, collected, vec![]);
+ list::print_json(&envelope)
+ } else {
+ println!("[]");
+ Ok(())
+ }
+ };
+
// Verify we're in a worktree
if repo.worktree_at(&cwd).git_dir().is_err() {
- // Not in a worktree - return empty array (consistent with wt list)
- println!("[]");
- return Ok(());
+ // Not in a worktree - emit an empty result (consistent with wt list)
+ return print_empty();
}
// Get current worktree info
@@ -862,8 +906,7 @@ fn run_json() -> Result<()> {
});
let Some(wt) = current_worktree else {
- println!("[]");
- return Ok(());
+ return print_empty();
};
// Determine if this is the primary worktree
@@ -876,28 +919,6 @@ fn run_json() -> Result<()> {
// Build item with identity fields
let mut item = list::build_worktree_item(wt, is_home, true, false);
- // Load URL template from project config (if configured)
- let url_template = repo.url_template();
-
- // The statusline renders the full column set condensed (status, diffs,
- // ahead/behind, upstream, CI, URL — see `format_statusline_segments`) but no
- // LLM summary, so its plan is every column's tasks under full gates: CI runs,
- // summary doesn't. URL is gated on a configured template like everywhere else.
- let gates = list::columns::ColumnGates {
- show_full: true,
- summary_enabled: false,
- has_llm_command: false,
- has_url_template: url_template.is_some(),
- };
- let options = CollectOptions {
- url_template,
- // Match `wt list --full`: include untracked files in the working
- // diff (`HEAD±`) so the segment counts the same lines `wt step
- // diff` would show, consistent with the rest of the statusline data.
- include_untracked_in_working_diff: true,
- ..CollectOptions::for_columns(list::columns::all_columns(), &gates)
- };
-
// Populate computed fields (parallel git operations)
list::populate_item(&repo, &mut item, options)?;
@@ -911,21 +932,36 @@ fn run_json() -> Result<()> {
}
// No custom columns: the statusline path never expands `[list.custom-columns]`
// (prompt hot path; its compact format has no column grid).
- let repo_metadata = repo.repo_info();
let ci_provider_override = repo.forge_platform_override();
- let json_item = json_output::JsonItem::from_list_item(
- &item,
- &mut all_vars,
- repo_metadata.as_ref(),
- ci_provider_override.as_deref(),
- &[],
- );
-
- // Output as JSON array (consistent with wt list --format=json)
- let output = serde_json::to_string_pretty(&[json_item])?;
- println!("{output}");
- Ok(())
+ // Output follows `wt list --format=json`: schema 1 is a bare
+ // single-item array, schema 2 a single-item envelope.
+ if json_schema == 2 {
+ // `populate_item` resolved the default branch for its counts, so
+ // this read is a cache hit, never a fresh detection.
+ let default_branch = repo.default_branch();
+ let json_item = list::json_v2::JsonItemV2::from_list_item(
+ &item,
+ &mut all_vars,
+ default_branch.as_deref(),
+ collected,
+ ci_provider_override.as_deref(),
+ &[],
+ );
+ let envelope =
+ list::json_v2::envelope_with_items(&repo, default_branch, collected, vec![json_item]);
+ list::print_json(&envelope)
+ } else {
+ let repo_metadata = repo.repo_info();
+ let json_item = json_output::JsonItem::from_list_item(
+ &item,
+ &mut all_vars,
+ repo_metadata.as_ref(),
+ ci_provider_override.as_deref(),
+ &[],
+ );
+ list::print_json(&[json_item])
+ }
}
/// Filter out branch segment if directory already shows it via worktrunk template.
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index d659c8626..a9fb66590 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -60,7 +60,10 @@ pub fn suppress_warnings() {
let _ = SUPPRESS_WARNINGS.set(());
}
-fn warnings_suppressed() -> bool {
+/// Whether [`suppress_warnings`] latched this process. Consulted by warning
+/// emitters outside this module (e.g. the `wt list` JSON schema nag) so
+/// suppressed surfaces like the statusline stay clean.
+pub fn warnings_suppressed() -> bool {
SUPPRESS_WARNINGS.get().is_some()
}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index aefa83209..2a5718607 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -138,6 +138,7 @@ pub use deprecation::format_migration_diff;
pub use deprecation::migrate_content;
pub use deprecation::normalize_template_vars;
pub use deprecation::suppress_warnings;
+pub use deprecation::warnings_suppressed;
pub use deprecation::{
DEPRECATED_SECTION_KEYS, DeprecatedSection, UnknownKeyKind, classify_unknown_key,
key_belongs_in, nested_key_belongs_in, warn_unknown_fields,
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index f4168a559..0fe67b543 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -178,6 +178,12 @@ pub struct ListConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<bool>,
+ /// JSON output schema for `wt list --format=json` (1 or 2).
+ /// Schema 2 wraps items in an envelope of per-item facts (see the
+ /// `wt list` JSON docs). Unset emits schema 1 with a warning.
+ #[serde(rename = "json-schema", skip_serializing_if = "Option::is_none")]
+ pub json_schema: Option<u8>,
+
/// Per-task timeout in milliseconds.
/// Kills individual git commands that exceed this duration. Applies to both
/// `wt list` and the `wt switch` picker. Set to 0 to explicitly disable
@@ -285,6 +291,7 @@ impl Merge for ListConfig {
branches: other.branches.or(self.branches),
remotes: other.remotes.or(self.remotes),
summary: other.summary.or(self.summary),
+ json_schema: other.json_schema.or(self.json_schema),
task_timeout_ms: other.task_timeout_ms.or(self.task_timeout_ms),
timeout_ms: other.timeout_ms.or(self.timeout_ms),
columns,
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 5cacd5487..07ee6e7f6 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -276,6 +276,7 @@ fn test_list_config_serde() {
branches: Some(false),
remotes: None,
summary: None,
+ json_schema: None,
task_timeout_ms: Some(500),
timeout_ms: None,
columns: vec!["branch".into(), "ci".into(), "path".into()],
@@ -628,16 +629,18 @@ fn test_merge_list_config() {
branches: Some(false),
remotes: None,
summary: Some(true),
+ json_schema: None,
task_timeout_ms: Some(1000),
timeout_ms: Some(2000),
columns: vec!["branch".into(), "ci".into()],
custom_columns: Default::default(),
};
let override_config = ListConfig {
- full: None, // Should fall back to base
- branches: Some(true), // Should override
- remotes: Some(true), // Should override (base was None)
- summary: None, // Should fall back to base
+ full: None, // Should fall back to base
+ branches: Some(true), // Should override
+ remotes: Some(true), // Should override (base was None)
+ summary: None, // Should fall back to base
+ json_schema: None,
task_timeout_ms: None, // Should fall back to base
timeout_ms: None, // Should fall back to base
columns: Vec::new(), // Empty → fall back to base
@@ -1100,6 +1103,7 @@ fn test_list_config_accessor_methods_with_values() {
branches: Some(true),
remotes: Some(false),
summary: Some(true),
+ json_schema: None,
task_timeout_ms: Some(5000),
timeout_ms: Some(3000),
columns: Vec::new(),
diff --git a/src/utils.rs b/src/utils.rs
index 4fc3b1f36..f8e88154a 100644
--- a/src/utils.rs
+++ b/src/utils.rs
@@ -38,6 +38,16 @@ pub fn escape_controls(s: &str) -> Cow<'_, str> {
Cow::Owned(out)
}
+/// Format a Unix timestamp as ISO 8601 UTC (e.g., "2025-01-01T00:00:00Z"),
+/// or `None` when the timestamp is out of chrono's representable range.
+///
+/// The one ISO 8601 formatter wt has — diagnostics, logs, and schema-2
+/// `wt list --format=json` all derive from it.
+pub fn format_timestamp_iso8601_opt(timestamp: i64) -> Option<String> {
+ chrono::DateTime::from_timestamp(timestamp, 0)
+ .map(|dt| dt.format("%Y-%m-%dT%H:%M:%SZ").to_string())
+}
+
/// Format a Unix timestamp as ISO 8601 string (e.g., "2025-01-01T00:00:00Z").
///
/// Used for human-readable timestamps in diagnostic reports and logs.
@@ -45,12 +55,9 @@ pub fn escape_controls(s: &str) -> Cow<'_, str> {
/// If the timestamp is out of range for chrono's date handling, returns an
/// explicit placeholder string rather than a misleading value.
pub fn format_timestamp_iso8601(timestamp: u64) -> String {
- let Ok(timestamp) = i64::try_from(timestamp) else {
- return format!("invalid-timestamp({timestamp})");
- };
-
- chrono::DateTime::from_timestamp(timestamp, 0)
- .map(|dt| dt.format("%Y-%m-%dT%H:%M:%SZ").to_string())
+ i64::try_from(timestamp)
+ .ok()
+ .and_then(format_timestamp_iso8601_opt)
.unwrap_or_else(|| format!("invalid-timestamp({timestamp})"))
}
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 28a7044c6..bfffee55b 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -225,6 +225,93 @@ fn test_list_json_with_metadata(mut repo: TestRepo) {
});
}
+/// Schema 2 (`[list] json-schema = 2`): envelope with repo facts and
+/// per-item orthogonal facts. Pins the full shape, including the absence
+/// rule (locked reason present, integration null vs absent).
+#[rstest]
+fn test_list_json_schema_2_envelope(mut repo: TestRepo) {
+ repo.write_test_config("[list]\njson-schema = 2\n");
+
+ repo.add_worktree("feature-detached");
+ repo.add_worktree("locked-feature");
+ repo.lock_worktree("locked-feature", Some("Testing"));
+
+ assert_cmd_snapshot!({
+ let mut cmd = list_snapshots::command(&repo, repo.root_path());
+ cmd.arg("--format=json");
+ cmd
+ });
+}
+
+/// `[list] json-schema` selects the output schema: unset emits schema 1
+/// plus a one-time nag, an explicit value is silent, and anything except
+/// 1 or 2 is an error.
+#[rstest]
+fn test_list_json_schema_selection(repo: TestRepo) {
+ // Unset → schema 1 (bare array) + nag on stderr.
+ let output = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
+ assert!(!json.is_empty(), "schema 1 root is a bare array");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("json-schema"),
+ "unset key should nag: {stderr}"
+ );
+
+ // Explicit 1 → schema 1, no nag.
+ repo.write_test_config("[list]\njson-schema = 1\n");
+ let output = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
+ assert!(!json.is_empty());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !stderr.contains("json-schema"),
+ "explicit value should not nag: {stderr}"
+ );
+
+ // Explicit 2 → envelope, no nag.
+ repo.write_test_config("[list]\njson-schema = 2\n");
+ let output = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(json["schema"], 2);
+ assert_eq!(json["repo"]["default_branch"], "main");
+ assert!(json["items"].as_array().is_some_and(|i| !i.is_empty()));
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(!stderr.contains("json-schema"), "no nag with a value set");
+
+ // Invalid value → warn and degrade to schema 1, like a config type
+ // error (config problems never brick a command).
+ repo.write_test_config("[list]\njson-schema = 3\n");
+ let output = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "invalid value must not fail");
+ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
+ assert!(!json.is_empty(), "degrades to schema 1");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("expected 1 or 2"),
+ "invalid value should warn: {stderr}"
+ );
+}
+
/// `repo_url` is derived locally from the primary remote, converting an SSH
/// remote to its HTTPS web URL without shelling out to a forge.
#[rstest]
diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rs
index 9877f51cb..cf43fd134 100644
--- a/tests/integration_tests/statusline.rs
+++ b/tests/integration_tests/statusline.rs
@@ -462,6 +462,72 @@ fn test_statusline_json_basic(repo: TestRepo) {
);
}
+/// `[list] json-schema = 2` switches the statusline JSON to the envelope,
+/// with the same single-item contract as the schema-1 array. An unset key
+/// stays silent here — the statusline surface suppresses warnings.
+#[rstest]
+fn test_statusline_json_schema_2(repo: TestRepo) {
+ repo.write_test_config("[list]\njson-schema = 2\n");
+
+ let output = run_statusline(&repo, &["--format=json"], None);
+ let parsed: Value = serde_json::from_str(&output).expect("should be valid JSON");
+
+ assert_eq!(parsed["schema"], 2);
+ assert_eq!(
+ parsed["collected"],
+ serde_json::json!({"ci": true, "summary": false}),
+ "statusline collects with full gates, no summaries"
+ );
+ let items = parsed["items"].as_array().expect("envelope items");
+ assert_eq!(items.len(), 1, "one item: the current worktree");
+
+ let item = &items[0];
+ assert_eq!(item["branch"], "main");
+ assert!(item["worktree"]["current"].as_bool().unwrap());
+ assert!(item["worktree"]["main"].as_bool().unwrap());
+ assert!(
+ item.get("default_branch").is_none(),
+ "the default branch row carries no relation to itself"
+ );
+ assert!(item["head"]["sha"].is_string());
+ assert!(
+ item["display"]["statusline"].is_string(),
+ "pre-rendered statusline lives under display"
+ );
+}
+
+/// Outside a worktree the JSON surface emits an empty result in the
+/// selected schema, and the schema-2 empty envelope skips default-branch
+/// detection (no `default_branch` key — nothing to relate to).
+#[rstest]
+fn test_statusline_json_outside_worktree(repo: TestRepo) {
+ let git_dir = repo.root_path().join(".git");
+
+ let output = run_statusline_from_dir(&repo, &["--format=json"], None, &git_dir);
+ assert_eq!(output.trim(), "[]", "schema 1 empty result is a bare array");
+
+ repo.write_test_config("[list]\njson-schema = 2\n");
+ let output = run_statusline_from_dir(&repo, &["--format=json"], None, &git_dir);
+ let parsed: Value = serde_json::from_str(&output).expect("should be valid JSON");
+ assert_eq!(parsed["schema"], 2);
+ assert_eq!(parsed["items"], serde_json::json!([]));
+ assert!(
+ parsed["repo"].get("default_branch").is_none(),
+ "item-less path must not attempt default-branch detection"
+ );
+}
+
+/// An invalid `[list] json-schema` degrades to schema 1 silently here —
+/// the statusline surface suppresses warnings, so a config typo must not
+/// corrupt the prompt.
+#[rstest]
+fn test_statusline_json_invalid_schema_degrades_silently(repo: TestRepo) {
+ repo.write_test_config("[list]\njson-schema = 7\n");
+ let output = run_statusline(&repo, &["--format=json"], None);
+ let parsed: Value = serde_json::from_str(&output).expect("should be valid JSON");
+ assert!(parsed.is_array(), "degrades to the schema 1 array");
+}
+
#[rstest]
fn test_statusline_json_with_changes(repo: TestRepo) {
// Create uncommitted changes
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index b9f3d63c4..4b976119e 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -165,6 +165,8 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  # branches = false # Include branches without worktrees (--branches)
  # remotes = false # Include remote-only branches (--remotes)
  #
+  # json-schema = 1 # JSON output schema: 1 (current, bare array) or 2 (envelope); unset emits 1 with a warning
+  #
  # columns = ["branch", "status", "ci", "path"] # Columns to show, in order — built-ins or custom headers (omit for the default set)
  #
  # task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disables
@@ -204,8 +206,10 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  # needs an LLM command (`[commit.generation]`), `url` needs a `[list] url`
  # template — since listing can't supply the data.
  #
-  # The selection drives the table and the `wt switch` picker; `wt list --format
-  # json` ignores it and emits every field.
+  # The selection drives the table and the `wt switch` picker. `wt list --format
+  # json` always emits every field, but a listed gated column (`ci`, `summary`)
+  # still forces its data collection on, so the JSON carries the same data the
+  # table shows.
  #
  # #### Custom columns [experimental]
  #
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 3d6dc850d..f79874de2 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -213,6 +213,8 @@ Persistent flag values for wt list. Override on command line as needed.
  branches = false # Include branches without worktrees (--branches)
  remotes = false # Include remote-only branches (--remotes)
 
+  json-schema = 1 # JSON output schema: 1 (current, bare array) or 2 (envelope); unset emits 1 with a warning
+ 
  columns = ["branch", "status", "ci", "path"] # Columns to show, in order — built-ins or custom headers (omit for the default set)
 
  task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disables
@@ -252,8 +254,10 @@ named one. A column whose data source is missing still stays hidden — summ
needs an LLM command ([commit.generation]), url needs a [list] url
template — since listing can't supply the data.
-The selection drives the table and the wt switch picker; wt list --format
-json ignores it and emits every field.
+The selection drives the table and the wt switch picker. wt list --format
+json always emits every field, but a listed gated column (ci, summary)
+still forces its data collection on, so the JSON carries the same data the
+table shows.
Custom columns [experimental]
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
index af7479155..c59b0a7a2 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
@@ -271,7 +271,92 @@ These appear across all columns while the table is loading:
JSON output
-Query structured data with --format=json:
+--format=json emits structured data in one of two schemas while the format
+migrates: [list] json-schema = 2 selects the envelope format below, = 1
+the original bare-array format. Unset emits schema 1 with a warning; a future
+release flips the default to schema 2 and later removes schema 1.
+
+Schema 2
+
+One envelope object. Items carry independent facts; rendered strings
+(including the collapsed Status value) live under display:
+
+  {
+   "schema": 2,
+   "repo": {
+   "default_branch": "main",
+   "forge": {"url": "https://github.com/org/repo", "provider": "github",
+   "host": "github.com", "owner": "org", "name": "repo", "remote": "origin"}
+   },
+   "collected": {"ci": false, "summary": false},
+   "items": [
+   {
+   "branch": "feature",
+   "head": {"sha": "05a4a45d…", "short_sha": "05a4a45", "subject": "Add login page",
+   "committed_at": "2025-01-01T08:00:00Z"},
+   "worktree": {"path": "/home/user/repo.feature", "main": false, "current": true,
+   "previous": false, "detached": false, "branch_mismatch": false,
+   "changes": {"staged": false, "modified": true, "untracked": false,
+   "renamed": false, "deleted": false, "conflicted": false,
+   "diff": {"added": 10, "deleted": 2}}},
+   "default_branch": {"ahead": 3, "behind": 1, "diff": {"added": 50, "deleted": 20},
+   "orphan": false, "integration": null, "merge_conflicts": false},
+   "upstream": {"remote": "origin", "branch": "feature", "ahead": 0, "behind": 2},
+   "display": {"state": "diverged", "symbols": "!↕", "statusline": "feature …"}
+   }
+   ]
+  }
+
+How "no value" reads:
+
+- Absent — nothing to report: not applicable (worktree on a branch-only
+ row), not requested this run (the envelope's collected records what was),
+ or determined-empty (no PR, no lock, not integrated).
+- null — requested but not determined: a task timed out, the branch was
+ too stale for the expensive checks, or a forge fetch failed. This is the
+ JSON form of the table's · placeholder.
+
+jq treats absent and null identically in path expressions, so filters need
+no null checks; has() distinguishes the two when it matters.
+
+Item fields:
+
+ Field Description
+ ────────────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+ branch Branch name; null for a detached-HEAD worktree. Remote rows carry the bare name with the remote in remote
+ remote Remote name, present only on remote-only branch rows
+ head {sha, short_sha, subject, committed_at}; null for unborn branches. committed_at is RFC 3339 UTC
+ worktree {path, main, current, previous, detached, locked, prunable, branch_mismatch, operation, changes}; absent on branch-only rows. locked/prunable are {reason} objects and can co-occur; operation is "rebase" or "merge"; changes holds the five working-tree flags plus conflicted and diff {added, deleted}
+ default_branch Relation to the default branch: {ahead, behind, diff, orphan, integration, merge_conflicts}; absent on the default branch itself. integration.reason is one of same_commit, ancestor, no_added_changes, trees_match, merge_adds_nothing, patch_id_match; a dirty tree skips the checks, leaving integration null
+ upstream Tracking branch: {remote, branch, ahead, behind}; absent when none is configured
+ pr Open PR/MR: {number, url, review, mergeable, repo}; collected with --full or a listed ci column. review uses the schema 1 ci.review_state vocabulary; mergeable is false when the forge reports conflicts, null otherwise
+ checks CI pipeline: {status, source, stale}; status is passed, running, or failed — null when a conflicts report masks it
+ dev_server {url, listening} from the project's list.url template
+ summary LLM branch summary (requires [list] summary = true)
+ vars Per-branch variables from wt config state vars
+ display Rendered strings: state (schema 1's main_state vocabulary), symbols, statusline (with ANSI colors), columns (custom-column cells keyed by header)
+
+Schema 1 names map directly: commit → head, working_tree →
+worktree.changes, main + main_state → default_branch +
+display.state, remote → upstream, ci → pr + checks, url +
+url_active → dev_server, statusline/symbols/columns → display.*,
+and the per-item repo moves to the envelope's repo.forge.
+
+  # Current worktree path (for scripts)
+  wt list --format=json | jq -r '.items[] | select(.worktree.current) | .worktree.path'
+  
+  # Branches with uncommitted changes
+  wt list --format=json | jq '.items[] | select(.worktree.changes.modified)'
+  
+  # Integrated branches (safe to remove)
+  wt list --format=json | jq '.items[] | select(.display.state == "integrated" or .display.state == "empty") | .branch'
+  
+  # Worktrees ahead of upstream (needs pushing)
+  wt list --format=json | jq '.items[] | select(.upstream.ahead > 0) | .branch'
+
+Schema 1
+
+The original bare-array format, and the default while unset:
  # Current worktree path (for scripts)
  wt list --format=json | jq -r '.[] | select(.is_current) | .path'
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
index befc89d3e..4858ef42e 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
@@ -334,7 +334,117 @@ These appear across all columns while the table is loading:
JSON output
-Query structured data with --format=json:
+--format=json emits structured data in one of two schemas while the format
+migrates: [list] json-schema = 2 selects the envelope format below, = 1
+the original bare-array format. Unset emits schema 1 with a warning; a future
+release flips the default to schema 2 and later removes schema 1.
+
+Schema 2
+
+One envelope object. Items carry independent facts; rendered strings
+(including the collapsed Status value) live under display:
+
+  {
+   "schema": 2,
+   "repo": {
+   "default_branch": "main",
+   "forge": {"url": "https://github.com/org/repo", "provider": "github",
+   "host": "github.com", "owner": "org", "name": "repo", "remote": "origin"}
+   },
+   "collected": {"ci": false, "summary": false},
+   "items": [
+   {
+   "branch": "feature",
+   "head": {"sha": "05a4a45d…", "short_sha": "05a4a45", "subject": "Add login
+  page",
+   "committed_at": "2025-01-01T08:00:00Z"},
+   "worktree": {"path": "/home/user/repo.feature", "main": false, "current":
+  true,
+   "previous": false, "detached": false, "branch_mismatch": false,
+   "changes": {"staged": false, "modified": true, "untracked": false,
+   "renamed": false, "deleted": false, "conflicted": false,
+   "diff": {"added": 10, "deleted": 2}}},
+   "default_branch": {"ahead": 3, "behind": 1, "diff": {"added": 50, "deleted":
+  20},
+   "orphan": false, "integration": null, "merge_conflicts": false},
+   "upstream": {"remote": "origin", "branch": "feature", "ahead": 0, "behind":
+  2},
+   "display": {"state": "diverged", "symbols": "!↕", "statusline": "feature …"}
+   }
+   ]
+  }
+
+How "no value" reads:
+
+- Absent — nothing to report: not applicable (worktree on a branch-only
+ row), not requested this run (the envelope's collected records what was),
+ or determined-empty (no PR, no lock, not integrated).
+- null — requested but not determined: a task timed out, the branch was
+ too stale for the expensive checks, or a forge fetch failed. This is the
+ JSON form of the table's · placeholder.
+
+jq treats absent and null identically in path expressions, so filters need
+no null checks; has() distinguishes the two when it matters.
+
+Item fields:
+
+ Field Description
+ ─────── ──────────────────────────────────────────────────────────────────────
+ branch Branch name; null for a detached-HEAD worktree. Remote rows carry the
+ bare name with the remote in remote
+ remote Remote name, present only on remote-only branch rows
+ head {sha, short_sha, subject, committed_at}; null for unborn branches.
+ committed_at is RFC 3339 UTC
+ worktre {path, main, current, previous, detached, locked, prunable, branch_mis
+ e match, operation, changes}; absent on branch-only rows. locked/
+ prunable are {reason} objects and can co-occur; operation is "rebase"
+ or "merge"; changes holds the five working-tree flags plus conflicted
+ and diff {added, deleted}
+ default Relation to the default branch:
+ _branch {ahead, behind, diff, orphan, integration, merge_conflicts}; absent on
+ the default branch itself. integration.reason is one of same_commit,
+ ancestor, no_added_changes, trees_match, merge_adds_nothing,
+ patch_id_match; a dirty tree skips the checks, leaving integration
+ null
+ upstrea Tracking branch: {remote, branch, ahead, behind}; absent when none is
+ m configured
+ pr Open PR/MR: {number, url, review, mergeable, repo}; collected with
+ --full or a listed ci column. review uses the schema 1 ci.review_state
+ vocabulary; mergeable is false when the forge reports conflicts, null
+ otherwise
+ checks CI pipeline: {status, source, stale}; status is passed, running, or
+ failed — null when a conflicts report masks it
+ dev_ser {url, listening} from the project's list.url template
+ ver
+ summary LLM branch summary (requires [list] summary = true)
+ vars Per-branch variables from wt config state vars
+ display Rendered strings: state (schema 1's main_state vocabulary), symbols,
+ statusline (with ANSI colors), columns (custom-column cells keyed by
+ header)
+
+Schema 1 names map directly: commit → head, working_tree →
+worktree.changes, main + main_state → default_branch +
+display.state, remote → upstream, ci → pr + checks, url +
+url_active → dev_server, statusline/symbols/columns → display.*,
+and the per-item repo moves to the envelope's repo.forge.
+
+  # Current worktree path (for scripts)
+  wt list --format=json | jq -r '.items[] | select(.worktree.current) | 
+  .worktree.path'
+  
+  # Branches with uncommitted changes
+  wt list --format=json | jq '.items[] | select(.worktree.changes.modified)'
+  
+  # Integrated branches (safe to remove)
+  wt list --format=json | jq '.items[] | select(.display.state == "integrated" 
+  or .display.state == "empty") | .branch'
+  
+  # Worktrees ahead of upstream (needs pushing)
+  wt list --format=json | jq '.items[] | select(.upstream.ahead > 0) | .branch'
+
+Schema 1
+
+The original bare-array format, and the default while unset:
  # Current worktree path (for scripts)
  wt list --format=json | jq -r '.[] | select(.is_current) | .path'
diff --git a/tests/snapshots/integration__integration_tests__list__list_json_schema_2_envelope.snap b/tests/snapshots/integration__integration_tests__list__list_json_schema_2_envelope.snap
new file mode 100644
index 000000000..e1dfd5593
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__list_json_schema_2_envelope.snap
@@ -0,0 +1,330 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--format=json"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+{
+ "schema": 2,
+ "repo": {
+ "default_branch": "main"
+ },
+ "collected": {
+ "ci": false,
+ "summary": false
+ },
+ "items": [
+ {
+ "branch": "main",
+ "head": {
+ "sha": "05a4a45d0b981dad5c27db59dca482836d59f89e",
+ "short_sha": "05a4a45",
+ "subject": "Initial commit",
+ "committed_at": "2025-01-01T08:00:00Z"
+ },
+ "worktree": {
+ "path": "_REPO_",
+ "main": true,
+ "current": true,
+ "previous": false,
+ "detached": false,
+ "branch_mismatch": false,
+ "changes": {
+ "staged": false,
+ "modified": false,
+ "untracked": false,
+ "renamed": false,
+ "deleted": false,
+ "conflicted": false,
+ "diff": {
+ "added": 0,
+ "deleted": 0
+ }
+ }
+ },
+ "upstream": {
+ "remote": "origin",
+ "branch": "main",
+ "ahead": 0,
+ "behind": 0
+ },
+ "display": {
+ "state": "is_main",
+ "symbols": "^|",
+ "statusline": "main \u001b[2m^\u001b[22m\u001b[2m|\u001b[22m"
+ }
+ },
+ {
+ "branch": "feature-a",
+ "head": {
+ "sha": "1b87d4731ea707905d15a726e193531c20affa14",
+ "short_sha": "1b87d47",
+ "subject": "Add feature-a file",
+ "committed_at": "2025-01-01T08:00:00Z"
+ },
+ "worktree": {
+ "path": "_REPO_.feature-a",
+ "main": false,
+ "current": false,
+ "previous": false,
+ "detached": false,
+ "branch_mismatch": false,
+ "changes": {
+ "staged": false,
+ "modified": false,
+ "untracked": false,
+ "renamed": false,
+ "deleted": false,
+ "conflicted": false,
+ "diff": {
+ "added": 0,
+ "deleted": 0
+ }
+ }
+ },
+ "default_branch": {
+ "ahead": 1,
+ "behind": 0,
+ "diff": {
+ "added": 1,
+ "deleted": 0
+ },
+ "orphan": false,
+ "merge_conflicts": false
+ },
+ "display": {
+ "state": "ahead",
+ "symbols": "↑",
+ "statusline": "feature-a \u001b[2m↑\u001b[22m \u001b[32m↑1\u001b[0m ^\u001b[32m+1\u001b[0m"
+ }
+ },
+ {
+ "branch": "feature-b",
+ "head": {
+ "sha": "f62940fcec424585adf98625e722fdf990810614",
+ "short_sha": "f62940f",
+ "subject": "Add feature-b file",
+ "committed_at": "2025-01-01T08:00:00Z"
+ },
+ "worktree": {
+ "path": "_REPO_.feature-b",
+ "main": false,
+ "current": false,
+ "previous": false,
+ "detached": false,
+ "branch_mismatch": false,
+ "changes": {
+ "staged": false,
+ "modified": false,
+ "untracked": false,
+ "renamed": false,
+ "deleted": false,
+ "conflicted": false,
+ "diff": {
+ "added": 0,
+ "deleted": 0
+ }
+ }
+ },
+ "default_branch": {
+ "ahead": 1,
+ "behind": 0,
+ "diff": {
+ "added": 1,
+ "deleted": 0
+ },
+ "orphan": false,
+ "merge_conflicts": false
+ },
+ "display": {
+ "state": "ahead",
+ "symbols": "↑",
+ "statusline": "feature-b \u001b[2m↑\u001b[22m \u001b[32m↑1\u001b[0m ^\u001b[32m+1\u001b[0m"
+ }
+ },
+ {
+ "branch": "feature-c",
+ "head": {
+ "sha": "345c7c93ad7c3d8f5b08380898d78e024019599c",
+ "short_sha": "345c7c9",
+ "subject": "Add feature-c file",
+ "committed_at": "2025-01-01T08:00:00Z"
+ },
+ "worktree": {
+ "path": "_REPO_.feature-c",
+ "main": false,
+ "current": false,
+ "previous": false,
+ "detached": false,
+ "branch_mismatch": false,
+ "changes": {
+ "staged": false,
+ "modified": false,
+ "untracked": false,
+ "renamed": false,
+ "deleted": false,
+ "conflicted": false,
+ "diff": {
+ "added": 0,
+ "deleted": 0
+ }
+ }
+ },
+ "default_branch": {
+ "ahead": 1,
+ "behind": 0,
+ "diff": {
+ "added": 1,
+ "deleted": 0
+ },
+ "orphan": false,
+ "merge_conflicts": false
+ },
+ "display": {
+ "state": "ahead",
+ "symbols": "↑",
+ "statusline": "feature-c \u001b[2m↑\u001b[22m \u001b[32m↑1\u001b[0m ^\u001b[32m+1\u001b[0m"
+ }
+ },
+ {
+ "branch": "feature-detached",
+ "head": {
+ "sha": "05a4a45d0b981dad5c27db59dca482836d59f89e",
+ "short_sha": "05a4a45",
+ "subject": "Initial commit",
+ "committed_at": "2025-01-01T08:00:00Z"
+ },
+ "worktree": {
+ "path": "_REPO_.feature-detached",
+ "main": false,
+ "current": false,
+ "previous": false,
+ "detached": false,
+ "branch_mismatch": false,
+ "changes": {
+ "staged": false,
+ "modified": false,
+ "untracked": false,
+ "renamed": false,
+ "deleted": false,
+ "conflicted": false,
+ "diff": {
+ "added": 0,
+ "deleted": 0
+ }
+ }
+ },
+ "default_branch": {
+ "ahead": 0,
+ "behind": 0,
+ "diff": {
+ "added": 0,
+ "deleted": 0
+ },
+ "orphan": false,
+ "integration": {
+ "reason": "same_commit"
+ },
+ "merge_conflicts": false
+ },
+ "display": {
+ "state": "empty",
+ "symbols": "_",
+ "statusline": "feature-detached \u001b[2m_\u001b[22m"
+ }
+ },
+ {
+ "branch": "locked-feature",
+ "head": {
+ "sha": "05a4a45d0b981dad5c27db59dca482836d59f89e",
+ "short_sha": "05a4a45",
+ "subject": "Initial commit",
+ "committed_at": "2025-01-01T08:00:00Z"
+ },
+ "worktree": {
+ "path": "_REPO_.locked-feature",
+ "main": false,
+ "current": false,
+ "previous": false,
+ "detached": false,
+ "locked": {
+ "reason": "Testing"
+ },
+ "branch_mismatch": false,
+ "changes": {
+ "staged": false,
+ "modified": false,
+ "untracked": false,
+ "renamed": false,
+ "deleted": false,
+ "conflicted": false,
+ "diff": {
+ "added": 0,
+ "deleted": 0
+ }
+ }
+ },
+ "default_branch": {
+ "ahead": 0,
+ "behind": 0,
+ "diff": {
+ "added": 0,
+ "deleted": 0
+ },
+ "orphan": false,
+ "integration": {
+ "reason": "same_commit"
+ },
+ "merge_conflicts": false
+ },
+ "display": {
+ "state": "empty",
+ "symbols": "_⊞",
+ "statusline": "locked-feature \u001b[33m⊞\u001b[39m\u001b[2m_\u001b[22m"
+ }
+ }
+ ]
+}
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__list__list_json_tree_matches_main_after_merge.snap b/tests/snapshots/integration__integration_tests__list__list_json_tree_matches_main_after_merge.snap
index 053f7eff0..72f2b0836 100644
--- a/tests/snapshots/integration__integration_tests__list__list_json_tree_matches_main_after_merge.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_json_tree_matches_main_after_merge.snap
@@ -243,3 +243,5 @@ exit_code: 0
]
----- stderr -----
+▲ JSON output is schema 1; a future release switches the default to schema 2
+↳ To keep this format set [list] json-schema = 1; to adopt the new one, json-schema = 2
diff --git a/tests/snapshots/integration__integration_tests__list__list_json_with_display_fields.snap b/tests/snapshots/integration__integration_tests__list__list_json_with_display_fields.snap
index ffc6b0126..b48f03f7f 100644
--- a/tests/snapshots/integration__integration_tests__list__list_json_with_display_fields.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_json_with_display_fields.snap
@@ -282,3 +282,5 @@ exit_code: 0
]
----- stderr -----
+▲ JSON output is schema 1; a future release switches the default to schema 2
+↳ To keep this format set [list] json-schema = 1; to adopt the new one, json-schema = 2
diff --git a/tests/snapshots/integration__integration_tests__list__list_json_with_git_operation.snap b/tests/snapshots/integration__integration_tests__list__list_json_with_git_operation.snap
index a5ceb3394..4313d5886 100644
--- a/tests/snapshots/integration__integration_tests__list__list_json_with_git_operation.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_json_with_git_operation.snap
@@ -243,3 +243,5 @@ exit_code: 0
]
----- stderr -----
+▲ JSON output is schema 1; a future release switches the default to schema 2
+↳ To keep this format set [list] json-schema = 1; to adopt the new one, json-schema = 2
diff --git a/tests/snapshots/integration__integration_tests__list__list_json_with_metadata.snap b/tests/snapshots/integration__integration_tests__list__list_json_with_metadata.snap
index fe5e08397..f7f1db5db 100644
--- a/tests/snapshots/integration__integration_tests__list__list_json_with_metadata.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_json_with_metadata.snap
@@ -283,3 +283,5 @@ exit_code: 0
]
----- stderr -----
+▲ JSON output is schema 1; a future release switches the default to schema 2
+↳ To keep this format set [list] json-schema = 1; to adopt the new one, json-schema = 2
diff --git a/tests/snapshots/integration__integration_tests__list__list_json_with_user_marker.snap b/tests/snapshots/integration__integration_tests__list__list_json_with_user_marker.snap
index 39ef572e7..629a3f100 100644
--- a/tests/snapshots/integration__integration_tests__list__list_json_with_user_marker.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_json_with_user_marker.snap
@@ -281,3 +281,5 @@ exit_code: 0
]
----- stderr -----
+▲ JSON output is schema 1; a future release switches the default to schema 2
+↳ To keep this format set [list] json-schema = 1; to adopt the new one, json-schema = 2