Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,29 @@ Minimum `libvcs>=0.47.0,<0.48.0` (was `>=0.46.0,<0.47.0`).

### What's new

#### Apply checkout policy to linked worktrees (#578)

{ref}`cli-worktree-sync` and {ref}`cli-sync` with `--include-worktrees`
resolve typed targets, honor drift and dirty policy, and retain native
recovery results. Existing tag and commit checkouts move when their target
changes. Parent Git options, selected remotes, and explicit detachment apply
to worktree planning and updates. Missing worktrees fetch and create under the
same native ownership lock; requested lock failures retain the completed
creation result.

Configured discard requires `--yes`; included worktree policies are checked
before the main checkout changes. JSON and NDJSON retain exact recovery
locations after restoration or conflict, and human output shows recovery
identity. Read-only worktree planning and `--dry-run` previews never fetch and
exit cleanly when remote targets have not been fetched yet; live `worktree sync`
exits `1` when any worktree is blocked or errors.

`worktree sync` and `sync --include-worktrees` stop owned native processes on
timeout or Ctrl-C and report retained recovery tokens. Each linked checkout
has a separate deadline; standalone `worktree sync` accepts `--timeout`.
Interrupted metadata remains unknown, and a timeout skips remaining worktrees
for that repository.

#### Preserve Mercurial fetch and push remotes during sync (#590)

Mercurial remotes reach native sync with separate fetch and push URLs, both
Expand Down
11 changes: 11 additions & 0 deletions MIGRATION
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,17 @@ the worker and its native descendants before the command continues or exits.
Interrupted JSON/NDJSON events report unknown state and `retained_recoveries`
discovered by a separately bounded inspection. Discovery can include tokens
from earlier operations; it does not restore or release them automatically.
The same ownership applies to `sync --include-worktrees` and `worktree sync`.
Each linked checkout has a separate deadline; standalone `worktree sync`
accepts `--timeout`. A timed-out worktree prevents further worktrees for that
repository from starting. Interrupted worktree metadata remains unknown when
the worker did not return it.

### Guarded worktree creation

Worktree creation fetches configured remotes before selecting its initial
target. A failed requested worktree lock returns an error with completed
creation state; inspect that result before retrying an occupied destination.

### Explicit checkout policy and sync results

Expand Down
4 changes: 3 additions & 1 deletion docs/cli/sync.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ synchronized with remote repositories.

## Timeouts and interruption

`--timeout` bounds each repository sync. On timeout or Ctrl-C, vcspull stops
`--timeout` bounds each main checkout and each included worktree separately.
On timeout or Ctrl-C, vcspull stops
its worker and native process group before continuing or exiting. Progress
and output are streamed to the parent process, which owns the terminal and
JSON output. CLI synchronization requires POSIX process groups.
An included worktree timeout skips the remaining worktrees for that repository.

A stopped update can leave partially changed files. Its result remains
unknown unless the worker returned a complete native result. Retained
Expand Down
51 changes: 39 additions & 12 deletions docs/cli/worktree/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ prune

Worktrees are configured as a list under a repository entry. Each worktree
requires a `dir` (relative to workspace root or absolute) and exactly one
ref type: `tag`, `branch`, or `commit`.
ref type: `tag`, `branch`, `commit`, or native `rev`.

```yaml
~/code/:
Expand Down Expand Up @@ -68,12 +68,17 @@ ref type: `tag`, `branch`, or `commit`.
|-------|----------|-------------|
| `dir` | yes | Worktree path (relative to workspace root or absolute) |
| `tag` | one of | Tag to checkout (creates detached HEAD) |
| `branch` | one of | Branch to checkout (can be updated/pulled) |
| `branch` | one of | Branch to follow with fast-forward updates |
| `commit` | one of | Commit SHA to checkout (creates detached HEAD) |
| `rev` | one of | Native revision expression; attachment follows its resolved kind |
| `remote` | no | Fetch source for a branch target |
| `sync` | no | Drift and dirty policies described in {ref}`cli-worktree-sync` |
| `detach` | no | Keep the resolved target detached, including a branch |
| `lock` | no | Lock the worktree to prevent accidental removal |
| `lock_reason` | no | Reason for locking (implies `lock: true`) |

Exactly one of `tag`, `branch`, or `commit` must be specified per entry.
Exactly one of `tag`, `branch`, `commit`, or `rev` must be specified per entry.
Worktrees inherit the parent repository's Git transport options and remotes.

## Integration with vcspull sync

Expand Down Expand Up @@ -105,14 +110,32 @@ Each worktree entry emits:

```json
{
"reason": "worktree",
"worktree_path": "~/code/myproject-v2.0",
"ref_type": "tag",
"ref_value": "v2.0.0",
"action": "unchanged",
"exists": true,
"is_dirty": false,
"detail": "tag worktree already exists",
"error": null
"detail": "already at configured target",
"error": null,
"position": {
"revision": "3b8a1f2c9d0e4b5a6c7d8e9f0a1b2c3d4e5f6a7b",
"ref_name": "3b8a1f2c9d0e4b5a6c7d8e9f0a1b2c3d4e5f6a7b",
"ref_kind": "commit",
"follows": false,
"mixed": false,
"switched": false
},
"target_position": {
"revision": "3b8a1f2c9d0e4b5a6c7d8e9f0a1b2c3d4e5f6a7b",
"ref_name": "v2.0.0",
"ref_kind": "tag",
"follows": false,
"mixed": false,
"switched": false
},
"drifted": false
}
```

Expand All @@ -133,13 +156,17 @@ log aggregation.

vcspull refuses to touch work it could destroy:

**Uncommitted changes stop updates.** If a worktree has uncommitted changes,
vcspull will not update or remove it — commit or stash first. These entries
show as blocked (`⚠`) in {ref}`vcspull worktree list <cli-worktree-list>`.

**Unknown refs stop creation.** If a configured tag, branch, or commit
doesn't exist in the repository, the entry is reported as an error (`✗`)
rather than guessed at. Fetch from the remote to make the ref available.
**Dirty policy governs updates.** Updates abort on local changes by default.
Configure `sync.dirty: preserve` to retain and restore them, or configure
`discard` and pass `--yes` to authorize their removal. See
{ref}`cli-worktree-sync` for recovery output and drift policy. Worktree
pruning still refuses dirty checkouts.

**Unknown refs stop creation.** `vcspull worktree list` and `--dry-run`
inspect local metadata only, reporting unfetched refs as errors (`✗`) without
contacting remotes. `vcspull worktree sync` fetches configured remotes before
creating missing worktrees or updating branches, and reports an error (`✗`) if
the target still cannot be resolved.

**Locks guard against removal.** Worktrees created with `lock: true` or
`lock_reason` are locked via `git worktree lock`, preventing accidental
Expand Down
105 changes: 99 additions & 6 deletions docs/cli/worktree/sync.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,65 @@ Sync all configured worktrees:
$ vcspull worktree sync '*'
```

The sync subcommand:
- Creates missing worktrees at the configured `dir`
- Pulls latest changes for `branch` worktrees
- Leaves `tag` and `commit` worktrees unchanged (they're immutable)
- Skips worktrees with uncommitted changes (BLOCKED)
Missing worktrees fetch configured remotes and establish their initial target
with Git's linked-worktree operation. Creation holds the repository's ownership
lock through fetch, target selection, worktree creation, and lock setup. Existing
worktrees follow their configured `branch`, `tag`, `commit`, or native `rev`;
changing a tag or commit target moves the checkout to that resolved commit.
Branch updates are fast-forward only. A matching commit is not drift, even
when its branch or tag name differs. `detach: true` keeps a branch target
detached, and `remote` chooses the branch's fetch source.

Each worktree accepts the same `sync` policies as {ref}`cli-sync`:
`drift: keep` leaves an existing checkout untouched; `drift: warn` also logs
when its resolved target differs. The default `dirty: abort` blocks updates
with local changes. `dirty: preserve` retains native recovery material and
restores changes, including the Git index. Conflicts retain their recovery
token and make the operation fail.

`dirty: discard` requires explicit invocation consent, including clean or
missing checkouts:

```console
$ vcspull worktree sync --yes '*'
```

For {ref}`cli-sync` with `--include-worktrees`, the same `--yes` authorizes
configured discard. Worktree consent is checked before the main checkout
changes. Main and linked checkouts are synchronized serially.

Both commands print retained recovery identity after success or failure.
JSON and NDJSON include update/preservation states, ordered errors,
conflicts, and the exact token location required by libvcs recovery. Tokens
remain retained until explicitly released through libvcs; synchronization
does not automatically restore interrupted operations into their source.

## Timeouts and interruption

A requested worktree lock that fails reports an error even when the checkout
was created. Inspect `update_state` before retrying; failed creation can leave
refs or a partial checkout.

Each worktree has its own deadline, including native creation and update.
Set it with `--timeout` or `VCSPULL_SYNC_TIMEOUT_SECONDS`; the default is
10 seconds:

```console
$ vcspull worktree sync --timeout 60 '*'
```

Timeout or Ctrl-C stops the owned worker and its native process group before
the command continues or exits. A timeout skips the remaining worktrees for
that repository. Ctrl-C reports completed entries and retained recovery
material before exiting. An interrupted worker that did not report metadata
leaves `exists` and `is_dirty` unknown (`null` in JSON), not clean or missing.
See {ref}`cli-sync` for recovery inspection and process-group limits.

## Dry run

Preview what would happen without making changes:
Preview local target metadata without fetching or changing checkouts. An
unavailable target produces an error plan; execution may resolve it after
fetching:

```console
$ vcspull worktree sync --dry-run '*'
Expand All @@ -56,8 +106,51 @@ $ vcspull worktree sync 'django*'
$ vcspull worktree sync --json '*'
```

Each synchronized entry includes native position, update/preservation state,
recovery metadata, and ordered errors:

```json
[
{
"reason": "worktree",
"worktree_path": "~/code/myproject-dev",
"ref_type": "branch",
"ref_value": "develop",
"action": "update",
"exists": true,
"is_dirty": false,
"detail": "worktree updated",
"error": null,
"position": {
"revision": "1111111111111111111111111111111111111111",
"ref_name": "develop",
"ref_kind": "branch",
"follows": true,
"mixed": false,
"switched": false
},
"target_position": {
"revision": "2222222222222222222222222222222222222222",
"ref_name": "develop",
"ref_kind": "branch",
"follows": true,
"mixed": false,
"switched": false
},
"drifted": true,
"update_state": "completed",
"preservation_state": "not-needed",
"recovery": null,
"conflicts": [],
"errors": []
}
]
```

## NDJSON output

Stream one JSON object per line as each worktree completes:

```console
$ vcspull worktree sync --ndjson '*'
```
47 changes: 46 additions & 1 deletion src/vcspull/_internal/sync_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ class SyncOutcome:
Deserialized synchronization result from the worker, if reported.
retained_recoveries : tuple[SyncResult, ...]
Retained recovery records discovered by post-failure inspection.
worktree : dict[str, t.Any] | None
Serialized worktree plan entry returned by a ``"worktree"`` worker.
"""

status: t.Literal["synced", "failed", "timed_out"]
Expand All @@ -51,6 +53,7 @@ class SyncOutcome:
duration: float = 0.0
result: SyncResult | None = None
retained_recoveries: tuple[SyncResult, ...] = ()
worktree: dict[str, t.Any] | None = None


class SyncInterrupted(KeyboardInterrupt):
Expand Down Expand Up @@ -315,14 +318,20 @@ def run_sync_process(
timeout: float,
is_human: bool,
yes: bool = False,
worktree: collections.abc.Mapping[str, t.Any] | None = None,
) -> SyncOutcome:
"""Run one owned mutation process; inspect retained records after a timeout."""
if os.name != "posix":
message = "bounded CLI sync requires POSIX process-group ownership"
raise RuntimeError(message)
started = time.monotonic()
exchange = _exchange(
{"repo": dict(repo), "yes": yes, "operation": "sync"},
{
"repo": dict(repo),
"yes": yes,
"operation": "worktree" if worktree is not None else "sync",
"worktree": dict(worktree) if worktree is not None else None,
},
timeout=timeout,
progress_callback=progress_callback,
is_human=is_human,
Expand Down Expand Up @@ -414,6 +423,7 @@ def run_sync_process(
duration=time.monotonic() - started,
result=result,
retained_recoveries=retained,
worktree=terminal.get("worktree"),
)
if interrupted:
raise SyncInterrupted(outcome)
Expand Down Expand Up @@ -448,6 +458,41 @@ def emit(self, record: logging.LogRecord) -> None:
try:
from vcspull.cli.sync import SyncFailedError, guess_vcs, update_repo

if request["operation"] == "worktree":
from vcspull._internal.worktree_sync import (
WorktreeAction,
sync_worktree,
worktree_entry_data,
)

settings = request["worktree"]
entry = sync_worktree(
pathlib.Path(settings["repo_path"]),
settings["config"],
pathlib.Path(settings["workspace_root"]),
allow_discard=request["yes"],
repo_config=settings["repo_config"],
)
worktree_result = (
entry.result if entry.result is not None else SyncResult()
)
if (
entry.action in (WorktreeAction.ERROR, WorktreeAction.BLOCKED)
and worktree_result.ok
):
worktree_result.add_error(
"worktree", entry.error or entry.detail or "worktree failed"
)
send(
{
"event": "result",
"ok": worktree_result.ok,
"error": entry.error,
"result": _result_data(worktree_result),
"worktree": worktree_entry_data(entry),
}
)
return
if request["operation"] == "inspect":
from vcspull._internal.sync import create_sync_project

Expand Down
Loading