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.mdindex 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 bWhat 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` commanddiff --git a/dev/config.example.toml b/dev/config.example.tomlindex 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.mdindex 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 — `summaryneeds 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 columnsdiff --git a/docs/content/list.md b/docs/content/list.mdindex 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.mdindex 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 — `summaryneeds 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.mdindex 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.rsindex 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 — `summaryneeds 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.rsindex 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.rsindex 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 widthlet 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.rsindex 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.rsindex 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.rsnew file mode 100644index 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.rsindex 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.rsindex 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_dataelse {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.rsindex 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.rsindex 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.rsindex 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.rsindex 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.rsindex 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 worktreeif 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 fieldslet 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.rsindex 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.rsindex 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.rsindex 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.rsindex 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 basetimeout_ms: None, // Should fall back to basecolumns: 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.rsindex 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.rsindex 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.rsindex 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 changesdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snapindex 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 [2m~/.config/worktrunk/config.toml[0m with the following content:[107m [0m [2m# branches = false # Include branches without worktrees (--branches)[0m[107m [0m [2m# remotes = false # Include remote-only branches (--remotes)[0m[107m [0m [2m#[0m+[107m [0m [2m# json-schema = 1 # JSON output schema: 1 (current, bare array) or 2 (envelope); unset emits 1 with a warning[0m+[107m [0m [2m#[0m[107m [0m [2m# columns = ["branch", "status", "ci", "path"] # Columns to show, in order — built-ins or custom headers (omit for the default set)[0m[107m [0m [2m#[0m[107m [0m [2m# task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disables[0m@@ -204,8 +206,10 @@ Creates [2m~/.config/worktrunk/config.toml[0m with the following content:[107m [0m [2m# needs an LLM command (`[commit.generation]`), `url` needs a `[list] url`[0m[107m [0m [2m# template — since listing can't supply the data.[0m[107m [0m [2m#[0m-[107m [0m [2m# The selection drives the table and the `wt switch` picker; `wt list --format[0m-[107m [0m [2m# json` ignores it and emits every field.[0m+[107m [0m [2m# The selection drives the table and the `wt switch` picker. `wt list --format[0m+[107m [0m [2m# json` always emits every field, but a listed gated column (`ci`, `summary`)[0m+[107m [0m [2m# still forces its data collection on, so the JSON carries the same data the[0m+[107m [0m [2m# table shows.[0m[107m [0m [2m#[0m[107m [0m [2m# #### Custom columns [experimental][0m[107m [0m [2m#[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex 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 [2mwt list[0m. Override on command line as needed.[107m [0m [2mbranches = [0m[2m[33mfalse[0m[2m [0m[2m# Include branches without worktrees (--branches)[0m[107m [0m [2mremotes = [0m[2m[33mfalse[0m[2m [0m[2m# Include remote-only branches (--remotes)[0m[107m [0m+[107m [0m [2mjson-schema = [0m[2m[33m1[0m[2m [0m[2m# JSON output schema: 1 (current, bare array) or 2 (envelope); unset emits 1 with a warning[0m+[107m [0m[107m [0m [2mcolumns = [[0m[2m[32m"branch"[0m[2m, [0m[2m[32m"status"[0m[2m, [0m[2m[32m"ci"[0m[2m, [0m[2m[32m"path"[0m[2m] [0m[2m# Columns to show, in order — built-ins or custom headers (omit for the default set)[0m[107m [0m[107m [0m [2mtask-timeout-ms = [0m[2m[33m0[0m[2m [0m[2m# Kill individual git commands after N ms; 0 disables[0m@@ -252,8 +254,10 @@ named one. A column whose data source is missing still stays hidden — [2msummneeds an LLM command ([2m[commit.generation][0m), [2murl[0m needs a [2m[list] url[0mtemplate — since listing can't supply the data.-The selection drives the table and the [2mwt switch[0m picker; [2mwt list --format[0m-json[2m ignores it and emits every field.[0m+The selection drives the table and the [2mwt switch[0m picker. [2mwt list --format[0m+json[2m always emits every field, but a listed gated column ([0mci[2m, [0msummary[2m)[0m+still forces its data collection on, so the JSON carries the same data the+table shows.[1mCustom columns [experimental][0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snapindex 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:[1m[32mJSON output[0m-Query structured data with [2m--format=json[0m:+[2m--format=json[0m emits structured data in one of two schemas while the format+migrates: [2m[list] json-schema = 2[0m selects the envelope format below, [2m= 1[0m+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.++[32mSchema 2[0m++One envelope object. Items carry independent facts; rendered strings+(including the collapsed Status value) live under [2mdisplay[0m:++[107m [0m [2m{[0m+[107m [0m [2m "schema": 2,[0m+[107m [0m [2m "repo": {[0m+[107m [0m [2m "default_branch": "main",[0m+[107m [0m [2m "forge": {"url": "https://github.com/org/repo", "provider": "github",[0m+[107m [0m [2m "host": "github.com", "owner": "org", "name": "repo", "remote": "origin"}[0m+[107m [0m [2m },[0m+[107m [0m [2m "collected": {"ci": false, "summary": false},[0m+[107m [0m [2m "items": [[0m+[107m [0m [2m {[0m+[107m [0m [2m "branch": "feature",[0m+[107m [0m [2m "head": {"sha": "05a4a45d…", "short_sha": "05a4a45", "subject": "Add login page",[0m+[107m [0m [2m "committed_at": "2025-01-01T08:00:00Z"},[0m+[107m [0m [2m "worktree": {"path": "/home/user/repo.feature", "main": false, "current": true,[0m+[107m [0m [2m "previous": false, "detached": false, "branch_mismatch": false,[0m+[107m [0m [2m "changes": {"staged": false, "modified": true, "untracked": false,[0m+[107m [0m [2m "renamed": false, "deleted": false, "conflicted": false,[0m+[107m [0m [2m "diff": {"added": 10, "deleted": 2}}},[0m+[107m [0m [2m "default_branch": {"ahead": 3, "behind": 1, "diff": {"added": 50, "deleted": 20},[0m+[107m [0m [2m "orphan": false, "integration": null, "merge_conflicts": false},[0m+[107m [0m [2m "upstream": {"remote": "origin", "branch": "feature", "ahead": 0, "behind": 2},[0m+[107m [0m [2m "display": {"state": "diverged", "symbols": "!↕", "statusline": "feature …"}[0m+[107m [0m [2m }[0m+[107m [0m [2m ][0m+[107m [0m [2m}[0m++How "no value" reads:++- [1mAbsent[0m — nothing to report: not applicable ([2mworktree[0m on a branch-only+ row), not requested this run (the envelope's [2mcollected[0m records what was),+ or determined-empty (no PR, no lock, not integrated).+- [1m[2mnull[0m[0m — 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 [2m·[0m placeholder.++jq treats absent and [2mnull[0m identically in path expressions, so filters need+no null checks; [2mhas()[0m distinguishes the two when it matters.++Item fields:++ Field Description+ ────────────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────+ [2mbranch[0m Branch name; null for a detached-HEAD worktree. Remote rows carry the bare name with the remote in [2mremote[0m+ [2mremote[0m Remote name, present only on remote-only branch rows+ [2mhead[0m [2m{sha, short_sha, subject, committed_at}[0m; null for unborn branches. [2mcommitted_at[0m is RFC 3339 UTC+ [2mworktree[0m [2m{path, main, current, previous, detached, locked, prunable, branch_mismatch, operation, changes}[0m; absent on branch-only rows. [2mlocked[0m/[2mprunable[0m are [2m{reason}[0m objects and can co-occur; [2moperation[0m is [2m"rebase"[0m or [2m"merge"[0m; [2mchanges[0m holds the five working-tree flags plus [2mconflicted[0m and [2mdiff {added, deleted}[0m+ [2mdefault_branch[0m Relation to the default branch: [2m{ahead, behind, diff, orphan, integration, merge_conflicts}[0m; absent on the default branch itself. [2mintegration.reason[0m is one of [2msame_commit[0m, [2mancestor[0m, [2mno_added_changes[0m, [2mtrees_match[0m, [2mmerge_adds_nothing[0m, [2mpatch_id_match[0m; a dirty tree skips the checks, leaving [2mintegration[0m null+ [2mupstream[0m Tracking branch: [2m{remote, branch, ahead, behind}[0m; absent when none is configured+ [2mpr[0m Open PR/MR: [2m{number, url, review, mergeable, repo}[0m; collected with [2m--full[0m or a listed [2mci[0m column. [2mreview[0m uses the schema 1 [2mci.review_state[0m vocabulary; [2mmergeable[0m is false when the forge reports conflicts, null otherwise+ [2mchecks[0m CI pipeline: [2m{status, source, stale}[0m; [2mstatus[0m is [2mpassed[0m, [2mrunning[0m, or [2mfailed[0m — null when a conflicts report masks it+ [2mdev_server[0m [2m{url, listening}[0m from the project's [2mlist.url[0m template+ [2msummary[0m LLM branch summary (requires [2m[list] summary = true[0m)+ [2mvars[0m Per-branch variables from [2mwt config state vars[0m+ [2mdisplay[0m Rendered strings: [2mstate[0m (schema 1's [2mmain_state[0m vocabulary), [2msymbols[0m, [2mstatusline[0m (with ANSI colors), [2mcolumns[0m (custom-column cells keyed by header)++Schema 1 names map directly: [2mcommit[0m → [2mhead[0m, [2mworking_tree[0m →+[2mworktree.changes[0m, [2mmain[0m + [2mmain_state[0m → [2mdefault_branch[0m ++[2mdisplay.state[0m, [2mremote[0m → [2mupstream[0m, [2mci[0m → [2mpr[0m + [2mchecks[0m, [2murl[0m ++[2murl_active[0m → [2mdev_server[0m, [2mstatusline[0m/[2msymbols[0m/[2mcolumns[0m → [2mdisplay.*[0m,+and the per-item [2mrepo[0m moves to the envelope's [2mrepo.forge[0m.++[107m [0m [2m# Current worktree path (for scripts)[0m+[107m [0m [2m[0m[2m[34mwt[0m[2m list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[36m-r[0m[2m [0m[2m[32m'.items[] | select(.worktree.current) | .worktree.path'[0m+[107m [0m [0m+[107m [0m [2m# Branches with uncommitted changes[0m+[107m [0m [2m[0m[2m[34mwt[0m[2m list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[32m'.items[] | select(.worktree.changes.modified)'[0m+[107m [0m [0m+[107m [0m [2m# Integrated branches (safe to remove)[0m+[107m [0m [2m[0m[2m[34mwt[0m[2m list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[32m'.items[] | select(.display.state == "integrated" or .display.state == "empty") | .branch'[0m+[107m [0m [0m+[107m [0m [2m# Worktrees ahead of upstream (needs pushing)[0m+[107m [0m [2m[0m[2m[34mwt[0m[2m list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[32m'.items[] | select(.upstream.ahead > 0) | .branch'[0m++[32mSchema 1[0m++The original bare-array format, and the default while unset:[107m [0m [2m# Current worktree path (for scripts)[0m[107m [0m [2m[0m[2m[34mwt[0m[2m list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[36m-r[0m[2m [0m[2m[32m'.[] | select(.is_current) | .path'[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snapindex 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:[1m[32mJSON output[0m-Query structured data with [2m--format=json[0m:+[2m--format=json[0m emits structured data in one of two schemas while the format+migrates: [2m[list] json-schema = 2[0m selects the envelope format below, [2m= 1[0m+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.++[32mSchema 2[0m++One envelope object. Items carry independent facts; rendered strings+(including the collapsed Status value) live under [2mdisplay[0m:++[107m [0m [2m{[0m+[107m [0m [2m "schema": 2,[0m+[107m [0m [2m "repo": {[0m+[107m [0m [2m "default_branch": "main",[0m+[107m [0m [2m "forge": {"url": "https://github.com/org/repo", "provider": "github",[0m+[107m [0m [2m "host": "github.com", "owner": "org", "name": "repo", "remote": "origin"}[0m+[107m [0m [2m },[0m+[107m [0m [2m "collected": {"ci": false, "summary": false},[0m+[107m [0m [2m "items": [[0m+[107m [0m [2m {[0m+[107m [0m [2m "branch": "feature",[0m+[107m [0m [2m "head": {"sha": "05a4a45d…", "short_sha": "05a4a45", "subject": "Add login+[107m [0m page",[0m+[107m [0m [2m "committed_at": "2025-01-01T08:00:00Z"},[0m+[107m [0m [2m "worktree": {"path": "/home/user/repo.feature", "main": false, "current":+[107m [0m true,[0m+[107m [0m [2m "previous": false, "detached": false, "branch_mismatch": false,[0m+[107m [0m [2m "changes": {"staged": false, "modified": true, "untracked": false,[0m+[107m [0m [2m "renamed": false, "deleted": false, "conflicted": false,[0m+[107m [0m [2m "diff": {"added": 10, "deleted": 2}}},[0m+[107m [0m [2m "default_branch": {"ahead": 3, "behind": 1, "diff": {"added": 50, "deleted":+[107m [0m 20},[0m+[107m [0m [2m "orphan": false, "integration": null, "merge_conflicts": false},[0m+[107m [0m [2m "upstream": {"remote": "origin", "branch": "feature", "ahead": 0, "behind":+[107m [0m 2},[0m+[107m [0m [2m "display": {"state": "diverged", "symbols": "!↕", "statusline": "feature …"}[0m+[107m [0m [2m }[0m+[107m [0m [2m ][0m+[107m [0m [2m}[0m++How "no value" reads:++- [1mAbsent[0m — nothing to report: not applicable ([2mworktree[0m on a branch-only+ row), not requested this run (the envelope's [2mcollected[0m records what was),+ or determined-empty (no PR, no lock, not integrated).+- [1m[2mnull[0m[0m — 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 [2m·[0m placeholder.++jq treats absent and [2mnull[0m identically in path expressions, so filters need+no null checks; [2mhas()[0m distinguishes the two when it matters.++Item fields:++ Field Description+ ─────── ──────────────────────────────────────────────────────────────────────+ [2mbranch[0m Branch name; null for a detached-HEAD worktree. Remote rows carry the+ bare name with the remote in [2mremote[0m+ [2mremote[0m Remote name, present only on remote-only branch rows+ [2mhead[0m [2m{sha, short_sha, subject, committed_at}[0m; null for unborn branches.+ [2mcommitted_at[0m is RFC 3339 UTC+ [2mworktre[0m [2m{path, main, current, previous, detached, locked, prunable, branch_mis[0m+ [2me[0m [2mmatch, operation, changes}[0m; absent on branch-only rows. [2mlocked[0m/+ [2mprunable[0m are [2m{reason}[0m objects and can co-occur; [2moperation[0m is [2m"rebase"[0m+ or [2m"merge"[0m; [2mchanges[0m holds the five working-tree flags plus [2mconflicted[0m+ and [2mdiff {added, deleted}[0m+ [2mdefault[0m Relation to the default branch:+ [2m_branch[0m [2m{ahead, behind, diff, orphan, integration, merge_conflicts}[0m; absent on+ the default branch itself. [2mintegration.reason[0m is one of [2msame_commit[0m,+ [2mancestor[0m, [2mno_added_changes[0m, [2mtrees_match[0m, [2mmerge_adds_nothing[0m,+ [2mpatch_id_match[0m; a dirty tree skips the checks, leaving [2mintegration[0m+ null+ [2mupstrea[0m Tracking branch: [2m{remote, branch, ahead, behind}[0m; absent when none is+ [2mm[0m configured+ [2mpr[0m Open PR/MR: [2m{number, url, review, mergeable, repo}[0m; collected with+ [2m--full[0m or a listed [2mci[0m column. [2mreview[0m uses the schema 1 [2mci.review_state[0m+ vocabulary; [2mmergeable[0m is false when the forge reports conflicts, null+ otherwise+ [2mchecks[0m CI pipeline: [2m{status, source, stale}[0m; [2mstatus[0m is [2mpassed[0m, [2mrunning[0m, or+ [2mfailed[0m — null when a conflicts report masks it+ [2mdev_ser[0m [2m{url, listening}[0m from the project's [2mlist.url[0m template+ [2mver[0m+ [2msummary[0m LLM branch summary (requires [2m[list] summary = true[0m)+ [2mvars[0m Per-branch variables from [2mwt config state vars[0m+ [2mdisplay[0m Rendered strings: [2mstate[0m (schema 1's [2mmain_state[0m vocabulary), [2msymbols[0m,+ [2mstatusline[0m (with ANSI colors), [2mcolumns[0m (custom-column cells keyed by+ header)++Schema 1 names map directly: [2mcommit[0m → [2mhead[0m, [2mworking_tree[0m →+[2mworktree.changes[0m, [2mmain[0m + [2mmain_state[0m → [2mdefault_branch[0m ++[2mdisplay.state[0m, [2mremote[0m → [2mupstream[0m, [2mci[0m → [2mpr[0m + [2mchecks[0m, [2murl[0m ++[2murl_active[0m → [2mdev_server[0m, [2mstatusline[0m/[2msymbols[0m/[2mcolumns[0m → [2mdisplay.*[0m,+and the per-item [2mrepo[0m moves to the envelope's [2mrepo.forge[0m.++[107m [0m [2m# Current worktree path (for scripts)[0m+[107m [0m [2m[0m[2m[34mwt[0m[2m list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[36m-r[0m[2m [0m[2m[32m'.items[] | select(.worktree.current) | [0m+[107m [0m [2m[32m.worktree.path'[0m+[107m [0m [0m+[107m [0m [2m# Branches with uncommitted changes[0m+[107m [0m [2m[0m[2m[34mwt[0m[2m list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[32m'.items[] | select(.worktree.changes.modified)'[0m+[107m [0m [0m+[107m [0m [2m# Integrated branches (safe to remove)[0m+[107m [0m [2m[0m[2m[34mwt[0m[2m list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[32m'.items[] | select(.display.state == "integrated" [0m+[107m [0m [2m[32mor .display.state == "empty") | .branch'[0m+[107m [0m [0m+[107m [0m [2m# Worktrees ahead of upstream (needs pushing)[0m+[107m [0m [2m[0m[2m[34mwt[0m[2m list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[32m'.items[] | select(.upstream.ahead > 0) | .branch'[0m++[32mSchema 1[0m++The original bare-array format, and the default while unset:[107m [0m [2m# Current worktree path (for scripts)[0m[107m [0m [2m[0m[2m[34mwt[0m[2m list [0m[2m[36m--format=json[0m[2m [0m[2m[36m|[0m[2m [0m[2m[34mjq[0m[2m [0m[2m[36m-r[0m[2m [0m[2m[32m'.[] | select(.is_current) | .path'[0mdiff --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.snapnew file mode 100644index 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.snapindex 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 -----+[33m▲[39m [33mJSON output is schema 1; a future release switches the default to schema 2[39m+[2m↳[22m [2mTo keep this format set [4m[list] json-schema = 1[24m; to adopt the new one, [4mjson-schema = 2[24m[22mdiff --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.snapindex 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 -----+[33m▲[39m [33mJSON output is schema 1; a future release switches the default to schema 2[39m+[2m↳[22m [2mTo keep this format set [4m[list] json-schema = 1[24m; to adopt the new one, [4mjson-schema = 2[24m[22mdiff --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.snapindex 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 -----+[33m▲[39m [33mJSON output is schema 1; a future release switches the default to schema 2[39m+[2m↳[22m [2mTo keep this format set [4m[list] json-schema = 1[24m; to adopt the new one, [4mjson-schema = 2[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__list__list_json_with_metadata.snap b/tests/snapshots/integration__integration_tests__list__list_json_with_metadata.snapindex 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 -----+[33m▲[39m [33mJSON output is schema 1; a future release switches the default to schema 2[39m+[2m↳[22m [2mTo keep this format set [4m[list] json-schema = 1[24m; to adopt the new one, [4mjson-schema = 2[24m[22mdiff --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.snapindex 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 -----+[33m▲[39m [33mJSON output is schema 1; a future release switches the default to schema 2[39m+[2m↳[22m [2mTo keep this format set [4m[list] json-schema = 1[24m; to adopt the new one, [4mjson-schema = 2[24m[22m