Files
deepseek-harness/packages/experimental/worktree
LegGasai 0c8078e196 feat(forge): name worktree branches, start them from remote branches, and show changes being read (#8536)
* feat(forge): name worktree branches, start them from remote branches, and show changes being read

The New Session worktree option's base menu now searches local branches and
each remote's branches, pins the current branch and every remote's default
branch, and names each remote group by its repository. Its last row opens a
dialog that names the new branch, starting from `worktreePrefix` and checking
Git's branch-name rules; the Host refuses an invalid or taken name. A request
records the full ref of its base and the optional name; every attempt uses the
name.

A remote-tracking base is fetched first: the worktree service gains a
`fetch` request field and a `fetch` phase, fetching only that branch without
tags. A failed fetch leaves the message waiting with Retry, Use the last
fetched version, and Continue without a worktree; a taken name offers Rename.

While the changes view reads changes it has not shown yet, it says
"Reading changes" above file card placeholders, and the files menu names no
count.

* fix(worktree): forward only the declared create_worktree arguments

The create_worktree parameter object is open, and the tool passed it to the
worktree runtime unchanged. Now that a runtime request can ask to fetch, an
undeclared `fetch: true` from the model would have fetched, or refused a local
`from`. The tool now forwards only `name` and `from`, so it never fetches.

* docs(forge): say that only generated worktree branch names come from the Session id

* fix(forge): keep the collapsed change request status on one line

In the Session panel the collapsed card's number line kept every part at
full width inside a clipping row, so a narrow panel cut the most urgent
flag off without an ellipsis, such as "有冲突" after "3 项检查失败".

The number and status now form one MarqueeText line as wide as the row.
While the line with failed checks does not fit, they take the shorter
wording without their count; a line that still does not fit ends in an
ellipsis and crawls into view with the title while the pointer rests on
the card's head. The line measures again when its width or the fonts
change. Expanded cards keep their branch names as before.

* fix(forge): hide remote credentials and read the branch a tag shares its name with

The base menu named an unrecognized remote's group by its fetch URL as
`git remote -v` prints it, so a token in the URL, such as
`https://oauth2:[email protected]/...`, reached the browser and showed
in the menu. The group now shows the URL without its user name and password.

Inspection read the checked-out branch with `symbolic-ref --short HEAD`,
which prints `heads/main` while a tag is also named `main`; the New Session
option then requested `refs/heads/heads/main` and every worktree attempt
failed. Inspection now reads the full ref and takes the name under
`refs/heads/`, so the option, the pinned current branch, and the checkout
row name `main`. HEAD that names a ref outside `refs/heads/` reads as no
branch.

* test(worktree): set up nested remotes and line endings the CI runners' Git accepts

Git 2.55 on the CI runners refuses `git remote add team` next to an
existing `team/fork` remote; the check runs only in `git remote add`, so
the longest-remote case now writes the second remote with `git config`, as
configuration written earlier or by hand holds it. The test clone also
turns off `core.autocrlf`, as `repository` does, because the Windows
runner's global setting checked the fetched file out with CRLF.
2026-11-16 16:13:00 +00:00
..

description, kind
description kind
Create and enter a retained Git worktree under the calling Session file policy. package-reference

@deepseek-ai/dsh-experimental-worktree

English | 中文

Summary

Create an isolated checkout from a local commit and continue the same Session in it. Each operation creates a new named branch and leaves the source checkout intact. The existing sandbox governs all writes. Leaving the checkout retains its files and branch.

Table of Contents


Use this package

Mount the service alongside workingDirectory, fs, subprocess, sandbox, sandboxPolicy, and sessionProjections providers. Archive cleanup additionally needs workspaceRegistry and sessionQuery, and uses sessionProjectionCache when it is mounted; without the first two the service only creates and restores. Add the tool package when models need the operation.

- name: '@deepseek-ai/dsh-experimental-worktree'
- name: '@deepseek-ai/dsh-experimental-tool-worktree'

ctx.worktrees.create(agent, { name?, from?, fetch? }, signal?, onPhase?) creates a new branch and checkout, then enters the canonical checkout directory through ctx.workingDirectory.set. from resolves to a local commit before creation and defaults to HEAD. With fetch: true, from must be the full name of a remote-tracking branch, refs/remotes/<remote>/<branch>, of a configured remote, the longest remote name winning when names nest; creation first runs git fetch --no-tags --no-recurse-submodules --no-write-fetch-head --no-auto-maintenance <remote> +refs/heads/<branch>:<from>, so only that branch is fetched, then resolves the fetched commit. The fetch runs under the Session's sandbox policy and the command deadline, without prompts, and a failed fetch creates nothing; staged, unstaged, untracked, and ignored source files are not copied. baseCommit reports the resolved commit object name; repository-local replacement refs still apply to the checked-out content. Checkout disables configured Git clean, smudge, and process filters without changing repository configuration. An existing branch or checkout path is an error. The returned record contains path, branch, baseCommit, and repositoryRoot. An optional fourth argument, onPhase, receives fetch first when the request asks to fetch, prepare before validation, directory allocation, and branch creation, and checkout before the files are written and the checkout is entered; it must not throw.

ctx.worktrees.restore(agent, { path, branch, baseCommit, repositoryRoot }, signal?, onPhase?) checks a removed worktree out again at its recorded directory. It validates the recorded repository root, full commit object name, branch, and canonical target inside the configured pool before mutation. It removes only the missing target's unlocked registration with git worktree remove; other worktrees and locked registrations remain unchanged. It then checks out the branch when it still exists, or creates the branch again at baseCommit when it does not, and reports which happened as branchRecreated. An existing directory is an error. The calling Session's working directory does not change, and changes that were never committed are not recovered. Checkout disables filters as creation does. onPhase receives prepare before validation, target-registration cleanup, and branch creation, and checkout before the files are written; it must not throw.

Every creation appends a plugin:worktree/created record to the Session log after the directory change, so the worktree projection lists the Session's checkouts with owned false for one inside a fork-inherited prefix. When the Workspace archives a Session, the service registers one scheduled cleanup for the first checkout that Session created itself and returns; the inspection runs in the background. While retainOnArchive is on, archiving registers nothing and every checkout stays; the field is volatile and read at each archive, and the Forge panel edits it as a switch on the bundle's worktree row of the Plugins page. The checkout is retained while any unarchived Session refers to it, by a recorded creation or by a working directory inside it (a Session beneath an archived subagent ancestor counts as archived; cold Sessions are read from the projection cache or their log), and while the creator's sandbox policy is read-only. An eligible checkout is removed with a non-force git worktree remove under the creator's policy after a second use check inside the path lock, which also holds ensure and set into that path through working-directory/access; the branch and its commits remain. Tracked changes, untracked files, an initialized submodule (a repository in the checkout's administrative modules directory), locks, detached HEAD, a mismatched branch, and targets outside the configured pool retain the checkout. Ignored files and edits to skip-worktree or assume-unchanged files do not: git status reports neither, and Git discards them with the checkout. A committed embedded repository is not inspected; Git refuses that removal, so the attempt settles as failed. Inspection stops reading git status at its first entry and streams the worktree listing, keeping its entries in memory while it looks for the checkout; neither output is bounded by maxOutputBytes. Processes are not consulted: a process still writing there makes Git refuse, and an idle one fails its next command. Unarchiving cancels an unadmitted removal and waits for an admitted one. cleanupOf(session, revision) reads the attempt, or waits for a named revision to settle, as scheduled, retained, removed, or failed; a failure leaves the Session archived and logs a warning. Checkouts created before this event existed, and Sessions archived earlier, are not swept.

Expected failures throw WorktreeError with a stable code: WORKTREE_INVALID_ARGUMENT for a name Git or the pool rules reject, an empty start revision, or a restoration record that violates a documented constraint, while a start revision or base commit Git cannot resolve fails as WORKTREE_COMMAND_FAILED; WORKTREE_ALREADY_EXISTS for an existing branch or path; WORKTREE_LOCKED for a locked registration; WORKTREE_COMMAND_FAILED, WORKTREE_OUTPUT_TOO_LARGE, and WORKTREE_TIMEOUT for a command that exits unsuccessfully, exceeds maxOutputBytes, or exceeds timeoutMs; and WORKTREE_UNAVAILABLE after service disposal. A failure after directory allocation adds the retained-artifact context to its message and keeps the original error's name and code; caller cancellation stays an AbortError.

The default checkout directory is <current checkout root>/.agents/worktrees/<name>. The returned repositoryRoot is the top-level directory of the caller’s current checkout; when it is a linked checkout, the pool is nested inside it. Omitted names join the dsh- prefix, the first eight hexadecimal digits of the UUID in the Session id, a hyphen, and four random hexadecimal digits, such as dsh-6b1f02c4-9a3e; a Session id without a UUID gets eight random hexadecimal digits after the prefix. generatedWorktreeName exports the same rule for callers that name a worktree before creating it. The service writes a .gitignore containing * and a trailing newline only when its allocation creates the pool; existing files and ignore rules are preserved. Each Git and Node command runs under its own timeoutMs deadline, 5 minutes by default, so checking out a large repository on a slow filesystem can finish; cancellation still stops the running command. Relative directory, generated namePrefix, executable choices, process limits, and retainOnArchive are configurable in the configuration catalog.


Understand the implementation

Implementation internals — click to expand

Git and directory allocation run through the mounted subprocess and sandbox providers with the calling Session's existing file policy. Creation does not widen write access to the destination or shared Git administration directory. Directory creation claims the destination exclusively; cancellation and failed setup can leave retained artifacts, whose path appears in the error. Service disposal aborts pending operations and waits for their settlement.

Source Responsibility
src/index.ts Resolve the source revision, create the checkout, and publish the new working directory
src/process.ts Confine literal argv, cap output, and await process termination
src/directory.ts Claim the destination and initialize a newly created pool's ignore file

No runtime invariant companion is published: Git owns checkout registration and the working-directory service owns the Session directory; this package retains no independent projection of either.


Further Exploration


Model Experience

Indirectly, through the worktree tool's creation result and the working-directory service's recorded Session context.

KV Cache effect

This package contributes no prompt text. Its consumers own the appended tool result and recorded directory context.

Known Limitations and Deferred Work

  • Retained artifacts — leaving a worktree keeps its branch and files, and archive cleanup never deletes a branch. Setup failures can also retain partial artifacts, and a failed removal can leave a partial directory for the retained branch to be restored over.
  • Local revisions unless asked — creation fetches only the one remote branch a request asks for; it does not fetch other commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. On Git that meets the execution requirements, missing local objects cause creation to fail.
  • Filtered representations — checkout skips configured filters to avoid executing repository-configured programs or triggering implicit downloads. Git LFS pointers and encrypted blobs stay in their stored representation; hydration or decryption is a separate user-controlled operation.
  • Execution requirements — the subprocess provider must offer Git and Node in the same execution world as the filesystem provider. Git must honor GIT_NO_LAZY_FETCH, which Git 2.45 and the 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4, and 2.44.1 maintenance releases do; older releases ignore it and proceed instead of failing, so creation can fetch missing partial-clone objects from a promisor remote. The git --no-lazy-fetch option would reject these releases, but it exists only in Git 2.45 and later and also rejects the patched maintenance releases. The existing sandbox must permit all checkout and shared Git metadata writes.

Dev Note

Working context for maintainers — click to expand

The sandboxed Node child supplies exclusive directory creation, which the filesystem service does not expose, and identifies whether this service created the pool. The filesystem contract permits bare providers such as fs-local to ignore sandboxPolicy on writes; createIfAbsent protects a file but neither enforces permissions nor identifies who created its directory. Keeping directory allocation and ignore-file creation under the same process sandbox as Git preserves refusal of existing checkout paths and the condition for creating .gitignore.