Skip to content
Python

Feature worktrees for the Code coworker, with settings

Rohit C Prasadc33fe00495f8
diff --git a/coworker/agents/code.py b/coworker/agents/code.py
index 59ffa586..ff609b11 100644
--- a/coworker/agents/code.py
+++ b/coworker/agents/code.py
@@ -18,11 +18,12 @@ second way of doing something the repo already does. Don't guess at APIs, signat
read them (`grep`, `read_file`, `git_log`), in meaningful chunks, and batch independent reads \
into one request instead of one per turn.
-2. Every feature gets its own branch and worktree. For any change beyond a trivial fix, start \
-with `start_worktree(task)`: it creates a worktree on a fresh branch cut from the up-to-date \
-base branch, following the user's worktree settings, and moves this session into it, so every \
-later command runs there. Never edit the user's checkout in place when a worktree is possible; \
-if the folder is not a git repository, say so and work in place.
+2. Every change gets its own branch and worktree — a feature, a fix, a test, however small. \
+Before the first edit, call `start_worktree(task)`: it creates a worktree on a fresh branch cut \
+from the up-to-date base branch, following the user's worktree settings, and moves this session \
+into it, so every later command runs there. "Tiny" is not a reason to skip it; the user's \
+checkout is never edited in place. The only exceptions: the folder is not a git repository \
+(say so and work in place), or the user explicitly asks for an in-place edit this time.
3. Fan broad questions out; keep the change in your own hands. For questions spanning many \
files ("where is X handled?", "how does the Y flow work?") use `explore` — a read-only \
diff --git a/coworker/conversations.py b/coworker/conversations.py
index fc61db63..5745ebd9 100644
--- a/coworker/conversations.py
+++ b/coworker/conversations.py
@@ -119,6 +119,7 @@ class ConversationStore:
"ALTER TABLE sessions ADD COLUMN actor TEXT",
"ALTER TABLE sessions ADD COLUMN usage TEXT",
"ALTER TABLE sessions ADD COLUMN spawn TEXT",
+ "ALTER TABLE sessions ADD COLUMN worktree TEXT",
):
try:
self._conn.execute(ddl)
@@ -465,8 +466,19 @@ class ConversationStore:
),
usage=_load_grants(row["usage"] if "usage" in row.keys() else None),
spawn=_load_grants(row["spawn"] if "spawn" in row.keys() else None),
+ worktree=_load_grants(row["worktree"] if "worktree" in row.keys() else None),
)
+ def set_worktree(self, session_id: str, worktree: dict) -> None:
+ """Persist the feature worktree `start_worktree` moved this session into (Code
+ coworker, 2026-11-07). Like `spawn`, the per-turn upsert never names this column."""
+ with self._lock:
+ self._conn.execute(
+ "UPDATE sessions SET worktree = ? WHERE session_id = ?",
+ (json.dumps(worktree or {}), session_id),
+ )
+ self._conn.commit()
+
def set_spawn(self, session_id: str, spawn: dict) -> None:
"""Persist what a configuration started this session with (spec §10). Like
`team`, the per-turn upsert never names this column."""
@@ -548,6 +560,7 @@ class ConversationStore:
team=_load_grants(r["team"] if "team" in r.keys() else None),
usage=_load_grants(r["usage"] if "usage" in r.keys() else None),
spawn=_load_grants(r["spawn"] if "spawn" in r.keys() else None),
+ worktree=_load_grants(r["worktree"] if "worktree" in r.keys() else None),
)
for r in rows
]
diff --git a/coworker/server/app.py b/coworker/server/app.py
index 9db748c1..32269ef0 100644
--- a/coworker/server/app.py
+++ b/coworker/server/app.py
@@ -2718,6 +2718,17 @@ def create_app(manager: SessionManager) -> FastAPI:
def settings_set_scratch_base(body: dict) -> dict[str, Any]:
return manager.set_scratch_base(str((body or {}).get("path", "")))
+ # Feature worktrees (Code coworker, 2026-11-07): the global defaults, and a per-repo
+ # override keyed by the repo (any path inside it).
+ @app.post("/v1/settings/worktrees")
+ def settings_set_worktrees(body: dict) -> dict[str, Any]:
+ return manager.set_worktree_settings(body or {})
+
+ @app.post("/v1/settings/worktrees/repo")
+ def settings_set_worktrees_repo(body: dict) -> dict[str, Any]:
+ b = body or {}
+ return manager.set_worktree_override(str(b.get("path", "")), b.get("settings") or {})
+
@app.post("/v1/settings/nav-layout")
def settings_set_nav_layout(body: dict) -> dict[str, Any]:
return manager.set_nav_layout(str((body or {}).get("nav_layout", "")))
@@ -3349,6 +3360,10 @@ def create_app(manager: SessionManager) -> FastAPI:
# Context panel (FB-015): occupancy on reconnect, so a reopened
# session shows its meter before any new turn runs.
"context": engine.context_snapshot(),
+ # The branch the shell is on (a reopened session has no folder pick
+ # to learn it from) and the feature worktree, if start_worktree made one.
+ "branch": manager.session_branch(session_id),
+ "worktree": manager.session_worktree(session_id),
},
}
)
diff --git a/coworker/server/manager.py b/coworker/server/manager.py
index 261b3744..5c520a01 100644
--- a/coworker/server/manager.py
+++ b/coworker/server/manager.py
@@ -1012,6 +1012,9 @@ class SessionManager:
extra_tools=[
*(extra_tools or []),
*self._team_tools_for(session_id, ag, record, ws),
+ # The Code coworker's feature worktrees (2026-11-07): policy-driven, so
+ # the model never runs `git worktree` by hand.
+ *(self._worktree_tools(session_id) if ag.name == "code" else []),
]
or None,
secrets=self.secrets,
@@ -5548,6 +5551,7 @@ class SessionManager:
"auto_approve_reviewer": self.auto_approve_reviewer(),
# Whether each decision-model reviewer has a key (env or saved), never the key.
"auto_approve_reviewer_keys": self.reviewer_key_status(),
+ **self.worktree_settings_payload(),
"scratch_base": self._prefs.get("scratch_base")
or self.DEFAULT_SCRATCH_BASE,
# Real on-disk secrets location, so the UI shows the OS-native path instead of a
@@ -5935,6 +5939,182 @@ class SessionManager:
self._save_prefs()
return {"ok": True, "onboarded": bool(value)}
+ # -- feature worktrees (Code coworker, owner ruling 2026-11-07) ----------------------
+ def worktree_settings(self, workspace: Optional[str] = None):
+ """The effective settings: global `worktree_*` prefs overlaid with the repo's
+ override (keyed by project key — shared by every worktree of one repo)."""
+ from .. import worktrees as wt
+ from ..projects import project_key
+
+ key = project_key(workspace) if workspace else None
+ return wt.settings_from_prefs(self._prefs, key)
+
+ def worktree_settings_payload(self) -> dict[str, Any]:
+ from .. import worktrees as wt
+
+ return {
+ **wt.settings_from_prefs(self._prefs).payload(),
+ "worktree_overrides": dict(self._prefs.get("worktree_overrides") or {}),
+ }
+
+ def set_worktree_settings(self, body: dict[str, Any]) -> dict[str, Any]:
+ from .. import worktrees as wt
+
+ try:
+ changes = wt.validate_settings(body)
+ except ValueError as exc:
+ return {"ok": False, "error": str(exc)}
+ for k, v in changes.items():
+ self._prefs[f"worktree_{k}"] = v
+ self._save_prefs()
+ return {"ok": True, **self.get_settings()}
+
+ def set_worktree_override(self, path: str, settings: dict[str, Any]) -> dict[str, Any]:
+ """Per-repo override, keyed by the repo's project key; an empty body clears it."""
+ from .. import worktrees as wt
+ from ..projects import project_key
+
+ if not path:
+ return {"ok": False, "error": "a repo path is needed"}
+ key = project_key(path)
+ overrides = dict(self._prefs.get("worktree_overrides") or {})
+ if not settings:
+ overrides.pop(key, None)
+ else:
+ try:
+ overrides[key] = wt.validate_settings(settings)
+ except ValueError as exc:
+ return {"ok": False, "error": str(exc)}
+ self._prefs["worktree_overrides"] = overrides
+ self._save_prefs()
+ return {"ok": True, "key": key, **self.get_settings()}
+
+ def session_branch(self, session_id: str) -> Optional[str]:
+ engine = self._engines.get(session_id)
+ executor = getattr(engine, "executor", None) if engine else None
+ cwd = getattr(executor, "cwd", None)
+ return _git_branch(Path(cwd)) if cwd else None
+
+ def session_worktree(self, session_id: str) -> Optional[dict[str, Any]]:
+ record = self.session_store.load(session_id)
+ return dict(record.worktree) if record and record.worktree else None
+
+ def start_worktree(self, session_id: str, task: str) -> dict[str, Any]:
+ """Create the task's feature worktree by policy and move the session into it —
+ roots, shell cwd, persisted workspace — like promote_workspace, but for a real
+ repo. The engine rebuilds after the turn (relative anchoring, git tools, env
+ snapshot follow the new primary); until then the shell is already there."""
+ from .. import worktrees as wt
+
+ engine = self._engines.get(session_id)
+ if engine is None:
+ return {"ok": False, "error": "no live session"}
+ executor = getattr(engine, "executor", None)
+ cwd = str(executor.cwd) if executor is not None and getattr(executor, "cwd", None) else None
+ if not cwd:
+ return {"ok": False, "error": "this session has no working folder"}
+ record = self.session_store.load(session_id)
+ existing = (record.worktree if record else None) or {}
+ if existing.get("path") and Path(cwd).resolve() == Path(str(existing["path"])).resolve():
+ return {"ok": True, "already": True, **existing,
+ "note": "this session already works in its feature worktree"}
+ root = wt.repo_root(cwd)
+ if root is None:
+ return {"ok": False, "error": "this folder is not a git repository — work in place and say so"}
+ if any(p.name == "worktrees" and p.parent.name == ".openworker" for p in Path(cwd).resolve().parents):
+ return {"ok": False, "error": "this session is already inside a feature worktree"}
+ settings = self.worktree_settings(str(root))
+ try:
+ info = wt.create_worktree(root, task, settings)
+ except wt.WorktreeError as exc:
+ return {"ok": False, "error": str(exc)}
+ resolved = Path(info["path"]).resolve()
+ roots = getattr(engine, "roots", None)
+ if roots is not None:
+ # The worktree becomes the writable primary; the original checkout stays
+ # readable but is no longer writable — "never edit the checkout in place"
+ # is enforced by the roots, not by hoping the model remembers.
+ kept = []
+ for r in roots:
+ if r.path == resolved:
+ continue
+ if Path(str(r.path)).resolve() == root.resolve():
+ kept.append(RootDir(path=r.path, writable=False, label=r.label))
+ else:
+ kept.append(r)
+ roots[:] = [RootDir(path=resolved, writable=True, label="worktree"), *kept]
+ try:
+ res = executor.run(f"cd {shlex.quote(str(resolved))}", timeout=15)
+ if res.get("exit_code") != 0:
+ executor.cwd = str(resolved)
+ except Exception:
+ executor.cwd = str(resolved)
+ self.save(session_id, engine)
+ self.session_store.set_worktree(session_id, info)
+ self.session_store.touch_workspace(str(resolved))
+ self._promotion_rebuild.add(session_id)
+ if self._loop is not None:
+ asyncio.run_coroutine_threadsafe(
+ self.broadcast_session(session_id, {"type": "workspace_changed", "data": {
+ "workspace": str(resolved), "branch": info["branch"], "worktree": info}}),
+ self._loop,
+ )
+ return {"ok": True, **info}
+
+ def _worktree_tools(self, session_id: str) -> list[Any]:
+ """`start_worktree` for the Code coworker (engine-side policy, not model-side git)."""
+ import aisuite as ai
+
+ def start_worktree(task: str) -> dict:
+ """Create this task's own feature worktree on a fresh branch and move this
+ session into it, following the user's worktree settings (location, branch
+ prefix, fetch-first, setup command). Call it once at the start of any change
+ beyond a trivial fix, before editing. Returns the worktree path, branch and
+ base. In this turn, the shell is already in the worktree but `git_status` /
+ `git_diff` / `git_log` keep pointing at the original checkout until your next
+ turn — use `run_shell` for git until then. If the folder is not a git repo it
+ says so: then work in place.
+
+ Args:
+ task (str): What the feature or fix is, in a few words — it names the
+ branch (e.g. "add login page" → <prefix>add-login-page).
+ """
+ res = self.start_worktree(session_id, task)
+ if not res.get("ok"):
+ return {"error": res.get("error", "could not create a worktree")}
+ out = {k: res[k] for k in ("path", "branch", "base", "start", "fetched") if k in res}
+ if res.get("warnings"):
+ out["warnings"] = res["warnings"]
+ if res.get("setup"):
+ out["setup"] = {"exit_code": res["setup"].get("exit_code"), "output": res["setup"].get("output", "")[-600:]}
+ if res.get("already"):
+ out["note"] = res.get("note")
+ else:
+ out["note"] = ("the session now works in this worktree; this turn, use run_shell for "
+ "git — the git tools re-point at your next turn")
+ return out
+
+ return [ai.tool(start_worktree, metadata=ai.ToolMetadata(
+ category="git", risk_level="medium", capabilities=["write"], requires_approval=True))]
+
+ def _remove_feature_worktree(self, session_id: str, record=None) -> None:
+ """Policy cleanup (owner ruling 2026-11-07): on archive/delete, remove the session's
+ feature worktree when settings say so — never one with uncommitted changes; the
+ branch always stays."""
+ from .. import worktrees as wt
+
+ record = record if record is not None else self.session_store.load(session_id)
+ info = (record.worktree if record else {}) or {}
+ path, root = str(info.get("path") or ""), str(info.get("repo_root") or "")
+ if not path or not root:
+ return
+ if not self.worktree_settings(root).cleanup_on_archive:
+ return
+ try:
+ wt.remove_worktree(root, path) # False when dirty: left alone on purpose
+ except Exception:
+ pass
+
def set_scratch_base(self, path: str) -> dict[str, Any]:
"""Set + persist the common area where each Cowork conversation's scratch directory is
created (default ~/OpenWorker). The raw value is stored so the UI shows it as entered;
@@ -9819,6 +9999,7 @@ class SessionManager:
ok = self.session_store.set_flags(session_id, pinned=pinned, archived=archived)
if ok and archived:
self._remove_spawn_worktree(session_id)
+ self._remove_feature_worktree(session_id)
return {"ok": ok, "session_id": session_id}
def delete_session(self, session_id: str) -> dict[str, Any]:
@@ -9834,6 +10015,7 @@ class SessionManager:
pass
record = self.session_store.load(session_id)
self._remove_spawn_worktree(session_id, record)
+ self._remove_feature_worktree(session_id, record)
ok = self.session_store.delete(session_id)
# ...and its recorded turns and steps (observability §11, the session-delete cascade).
self.recorder.delete_session(session_id)
diff --git a/coworker/sessions.py b/coworker/sessions.py
index 3f6888f1..0cbcbdd2 100644
--- a/coworker/sessions.py
+++ b/coworker/sessions.py
@@ -56,6 +56,11 @@ class SessionRecord:
# user's standing rules for this session only; `worktree` is removed on archive
# or delete (the clone stays). {} for every other session.
spawn: dict[str, Any] = field(default_factory=dict)
+ # Feature worktree (Code coworker, 2026-11-07): the record `start_worktree` left —
+ # {path, branch, base, start, fetched, repo_root, location, created, setup,
+ # warnings}. {} when the session works in place. Cleaned up on archive/delete by
+ # policy (never while dirty; the branch always stays).
+ worktree: dict[str, Any] = field(default_factory=dict)
USAGE_FIELDS = ("input", "output", "cache_read", "cache_write")
diff --git a/coworker/worktrees.py b/coworker/worktrees.py
new file mode 100644
index 00000000..e3e04fae
--- /dev/null
+++ b/coworker/worktrees.py
@@ -0,0 +1,298 @@
+"""Feature worktrees for the Code coworker (owner ruling 2026-11-07).
+
+A task gets its own branch and worktree, cut from the freshly fetched base branch, so
+the user's checkout is never edited in place. The policy lives here, not in the model's
+hands: where the worktree goes, how the branch is named, whether to fetch first, the
+`.git/info/exclude` entry (the user's `.gitignore` is never touched), the optional
+per-repo setup command, and when a worktree may be removed (never while dirty).
+
+Locations:
+- in_repo (default): `<repo>/.openworker/worktrees/<slug>` — near the editor, travels with
+ the repo, cleans up with it.
+- sibling: `<repo parent>/<repo name>-worktrees/<slug>`.
+- custom: `<custom dir>/<repo name>/<slug>`.
+
+All git calls go through `_run_git` (never raises); failures come back as WorktreeError
+with a sentence the agent can relay.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import subprocess
+import time
+from dataclasses import dataclass, asdict
+from pathlib import Path
+from typing import Any, Optional
+
+LOCATIONS = ("in_repo", "sibling", "custom")
+IN_REPO_DIR = Path(".openworker") / "worktrees"
+EXCLUDE_LINE = ".openworker/"
+_SETUP_TIMEOUT_S = 900
+_FETCH_TIMEOUT_S = 120
+
+
+class WorktreeError(RuntimeError):
+ pass
+
+
+@dataclass
+class WorktreeSettings:
+ location: str = "in_repo"
+ custom_dir: str = ""
+ branch_prefix: str = "" # "" = derive from the git user name's initials
+ fetch_first: bool = True
+ cleanup_on_archive: bool = True
+ prune_days: int = 14
+ setup_command: str = ""
+
+ def payload(self) -> dict[str, Any]:
+ return {f"worktree_{k}": v for k, v in asdict(self).items()}
+
+
+_PREF_KEYS = tuple(WorktreeSettings.__dataclass_fields__)
+
+
+def settings_from_prefs(prefs: dict[str, Any], project_key: Optional[str] = None) -> WorktreeSettings:
+ """Global `worktree_*` prefs, overlaid with the repo's override (keyed by project
+ key) when there is one. Unknown or malformed values fall back to the defaults."""
+ s = WorktreeSettings()
+ layers: list[dict[str, Any]] = [{k[len("worktree_"):]: v for k, v in prefs.items()
+ if k.startswith("worktree_") and k != "worktree_overrides"}]
+ overrides = prefs.get("worktree_overrides") or {}
+ if project_key and isinstance(overrides, dict) and isinstance(overrides.get(project_key), dict):
+ layers.append(overrides[project_key])
+ for layer in layers:
+ for k in _PREF_KEYS:
+ if k not in layer or layer[k] is None:
+ continue
+ v = layer[k]
+ if k == "location":
+ if v in LOCATIONS:
+ s.location = v
+ elif k in ("fetch_first", "cleanup_on_archive"):
+ setattr(s, k, bool(v))
+ elif k == "prune_days":
+ try:
+ s.prune_days = max(1, int(v))
+ except (TypeError, ValueError):
+ pass
+ else:
+ setattr(s, k, str(v))
+ return s
+
+
+def validate_settings(body: dict[str, Any]) -> dict[str, Any]:
+ """The subset of `body` that is a valid settings change, normalized. Raises
+ ValueError with a user-facing sentence on a bad value."""
+ out: dict[str, Any] = {}
+ if "location" in body:
+ if body["location"] not in LOCATIONS:
+ raise ValueError("where worktrees go must be in_repo, sibling or custom")
+ out["location"] = body["location"]
+ if "custom_dir" in body:
+ out["custom_dir"] = str(body["custom_dir"] or "").strip()
+ if out.get("location") == "custom" and not out.get("custom_dir", body.get("custom_dir")):
+ raise ValueError("a custom location needs a folder")
+ if "branch_prefix" in body:
+ prefix = str(body["branch_prefix"] or "").strip()
+ if prefix and not re.fullmatch(r"[A-Za-z0-9._/-]{1,40}", prefix):
+ raise ValueError("the branch prefix may only use letters, digits, . _ - and /")
+ out["branch_prefix"] = prefix
+ for k in ("fetch_first", "cleanup_on_archive"):
+ if k in body:
+ out[k] = bool(body[k])
+ if "prune_days" in body:
+ try:
+ days = int(body["prune_days"])
+ except (TypeError, ValueError):
+ raise ValueError("prune days must be a whole number") from None
+ if days < 1:
+ raise ValueError("prune days must be at least 1")
+ out["prune_days"] = days
+ if "setup_command" in body:
+ out["setup_command"] = str(body["setup_command"] or "").strip()
+ return out
+
+
+# -- git ---------------------------------------------------------------------------------
+
+def _git(args: list[str], cwd: Any = None, timeout: int = 60) -> tuple[str, str]:
+ from .connectors.integration_tools import _run_git
+
+ return _run_git(args, cwd=cwd, timeout=timeout)
+
+
+def repo_root(path: str | Path) -> Optional[Path]:
+ """The repository's top level for `path`, or None when it is not inside a git repo."""
+ out, err = _git(["-C", str(path), "rev-parse", "--show-toplevel"])
+ if err or not out.strip():
+ return None
+ return Path(out.strip())
+
+
+def common_dir(root: Path) -> Path:
+ out, _ = _git(["-C", str(root), "rev-parse", "--git-common-dir"])
+ p = Path(out.strip() or ".git")
+ return p if p.is_absolute() else (root / p)
+
+
+def default_branch(root: Path) -> str:
+ """origin's HEAD (main/master/…) when known, else the current branch, else main."""
+ out, err = _git(["-C", str(root), "symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
+ if not err and out.strip():
+ return out.strip().split("/", 1)[-1]
+ out, err = _git(["-C", str(root), "rev-parse", "--abbrev-ref", "HEAD"])
+ if not err and out.strip() and out.strip() != "HEAD":
+ return out.strip()
+ return "main"
+
+
+def has_remote(root: Path, name: str = "origin") -> bool:
+ out, err = _git(["-C", str(root), "remote", "get-url", name])
+ return not err and bool(out.strip())
+
+
+def derive_prefix(root: Optional[Path]) -> str:
+ """`<initials>/` from git's user.name ("Rohit C Prasad" → "rp/"), else "ow/"."""
+ out, err = _git(["-C", str(root), "config", "user.name"] if root else ["config", "user.name"])
+ name = "" if err else out.strip()
+ words = [w for w in re.split(r"\s+", name) if w]
+ if len(words) >= 2:
+ return f"{words[0][0]}{words[-1][0]}".lower() + "/"
+ if words:
+ return words[0][:2].lower() + "/"
+ return "ow/"
+
+
+def slugify(text: str, limit: int = 40) -> str:
+ s = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-")
+ s = re.sub(r"-{2,}", "-", s)[:limit].strip("-")
+ return s or "work"
+
+
+def plan_path(root: Path, slug: str, s: WorktreeSettings) -> Path:
+ if s.location == "sibling":
+ return root.parent / f"{root.name}-worktrees" / slug
+ if s.location == "custom" and s.custom_dir:
+ return Path(s.custom_dir).expanduser() / root.name / slug
+ return root / IN_REPO_DIR / slug
+
+
+def _branch_exists(root: Path, branch: str) -> bool:
+ out, _ = _git(["-C", str(root), "branch", "--list", branch])
+ return bool(out.strip())
+
+
+def _unique(root: Path, branch: str, path: Path) -> tuple[str, Path]:
+ cand_branch, cand_path, n = branch, path, 1
+ while _branch_exists(root, cand_branch) or cand_path.exists():
+ n += 1
+ cand_branch, cand_path = f"{branch}-{n}", path.with_name(f"{path.name}-{n}")
+ return cand_branch, cand_path
+
+
+def ensure_excluded(root: Path) -> bool:
+ """Keep `.openworker/` out of git status via `.git/info/exclude` — never the user's
+ `.gitignore`. Returns whether a line was added."""
+ exclude = common_dir(root) / "info" / "exclude"
+ try:
+ existing = exclude.read_text(encoding="utf-8") if exclude.is_file() else ""
+ if EXCLUDE_LINE in existing.splitlines():
+ return False
+ exclude.parent.mkdir(parents=True, exist_ok=True)
+ with exclude.open("a", encoding="utf-8") as f:
+ if existing and not existing.endswith("\n"):
+ f.write("\n")
+ f.write(EXCLUDE_LINE + "\n")
+ return True
+ except OSError:
+ return False
+
+
+def create_worktree(root: Path, task: str, s: WorktreeSettings) -> dict[str, Any]:
+ """A worktree on a new branch for `task`, by policy. Returns the record the session
+ keeps: path, branch, base, start, fetched, repo_root, created, setup, warnings."""
+ warnings: list[str] = []
+ prefix = s.branch_prefix or derive_prefix(root)
+ if not prefix.endswith("/"):
+ prefix += "/"
+ slug = slugify(task)
+ base = default_branch(root)
+ start, fetched = base, False
+ if s.fetch_first and has_remote(root):
+ _, err = _git(["-C", str(root), "fetch", "origin", base], timeout=_FETCH_TIMEOUT_S)
+ if err:
+ warnings.append(f"could not fetch origin/{base} ({err.strip()[:120]}); branched from the local {base}")
+ else:
+ start, fetched = f"origin/{base}", True
+ branch, path = _unique(root, prefix + slug, plan_path(root, slug, s))
+ path.parent.mkdir(parents=True, exist_ok=True)
+ _, err = _git(["-C", str(root), "worktree", "add", "-b", branch, str(path), start], timeout=_FETCH_TIMEOUT_S)
+ if err:
+ raise WorktreeError(f"git could not create the worktree: {err.strip()[:200]}")
+ if s.location == "in_repo":
+ ensure_excluded(root)
+ setup: Optional[dict[str, Any]] = None
+ if s.setup_command:
+ try:
+ proc = subprocess.run(
+ s.setup_command, shell=True, cwd=str(path), capture_output=True, text=True,
+ timeout=_SETUP_TIMEOUT_S, env={**os.environ},
+ )
+ tail = (proc.stdout + proc.stderr)[-1500:]
+ setup = {"command": s.setup_command, "exit_code": proc.returncode, "output": tail}
+ if proc.returncode != 0:
+ warnings.append(f"the setup command exited {proc.returncode}")
+ except subprocess.TimeoutExpired:
+ setup = {"command": s.setup_command, "exit_code": None, "output": "timed out"}
+ warnings.append("the setup command timed out")
+ return {
+ "path": str(path),
+ "branch": branch,
+ "base": base,
+ "start": start,
+ "fetched": fetched,
+ "repo_root": str(root),
+ "location": s.location,
+ "created": time.time(),
+ "setup": setup,
+ "warnings": warnings,
+ }
+
+
+def is_clean(path: str | Path) -> bool:
+ """No uncommitted changes and no untracked files — the only state a worktree may be
+ removed in without the person's say-so."""
+ out, err = _git(["-C", str(path), "status", "--porcelain"])
+ return not err and not out.strip()
+
+
+def remove_worktree(root: str | Path, path: str | Path, *, force: bool = False) -> bool:
+ """Remove a worktree (its branch stays — unmerged work is never deleted). Without
+ `force`, a dirty worktree is left alone and False is returned."""
+ p = Path(path)
+ if not p.is_dir():
+ _git(["-C", str(root), "worktree", "prune"])
+ return True
+ if not force and not is_clean(p):
+ return False
+ _, err = _git(["-C", str(root), "worktree", "remove", "--force", str(p)])
+ if err and p.is_dir():
+ return False
+ _git(["-C", str(root), "worktree", "prune"])
+ return True
+
+
+def is_stale(record: dict[str, Any], prune_days: int, now: Optional[float] = None) -> bool:
+ """Untouched for `prune_days`: the worktree directory's newest mtime is older."""
+ p = Path(str(record.get("path") or ""))
+ if not p.is_dir():
+ return False
+ now = now or time.time()
+ try:
+ newest = max((f.stat().st_mtime for f in p.rglob("*") if ".git" not in f.parts), default=p.stat().st_mtime)
+ except OSError:
+ return False
+ return (now - newest) > prune_days * 86400
diff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsx
index beac2655..bd052d6c 100644
--- a/surfaces/gui/src/App.tsx
+++ b/surfaces/gui/src/App.tsx
@@ -956,10 +956,19 @@ export function App() {
// A subagent started/finished/is waiting — the rail refetches the registry.
setAgentTaskKey((k) => k + 1);
break;
+ case "workspace_changed":
+ // start_worktree moved the session into its feature worktree: the folder and
+ // branch the Environment block shows follow it (Code coworker, 2026-11-07).
+ if (d.workspace) setWorkspace(d.workspace);
+ if (typeof d.branch === "string") setBranch(d.branch);
+ break;
case "ready":
setPreparingSandbox(null);
setSandboxInfo(d.sandbox || null);
if (d.context) setContextInfo(d.context);
+ // Server truth on the branch (a reopened session has no folder pick to learn
+ // it from): the Environment block's branch tag survives reopen.
+ if (typeof d.branch === "string") setBranch(d.branch || null);
setSessionRefused(false);
setConnected(true);
if (d.model) setModel(d.model);
diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.ts
index 5407bd5d..4c1e5d1a 100644
--- a/surfaces/gui/src/api.ts
+++ b/surfaces/gui/src/api.ts
@@ -1207,6 +1207,14 @@ export interface ModelSettings {
onboarded: boolean;
surfaces: SurfaceVisibility;
scratch_base: string;
+ // Feature worktrees (Code coworker): present on servers from 2026-11-07.
+ worktree_location?: "in_repo" | "sibling" | "custom";
+ worktree_custom_dir?: string;
+ worktree_branch_prefix?: string;
+ worktree_fetch_first?: boolean;
+ worktree_cleanup_on_archive?: boolean;
+ worktree_prune_days?: number;
+ worktree_setup_command?: string;
secrets_path: string; // OS-native on-disk location the server reports (not hardcoded)
// Sidebar layout preference (§7): "flat" = the persona accordions / today's list; "grouped" =
// bounded per-persona cards. Defaults to "flat" (absent → flat) so the GUI is robust to an older
@@ -1478,6 +1486,32 @@ export async function setSessionsPeek(
return res.json();
}
+// Feature worktrees (Code coworker, 2026-11-07): where they go, how branches are named,
+// fetch-first, cleanup, and the optional per-repo setup command.
+export interface WorktreeSettings {
+ worktree_location: "in_repo" | "sibling" | "custom";
+ worktree_custom_dir: string;
+ worktree_branch_prefix: string;
+ worktree_fetch_first: boolean;
+ worktree_cleanup_on_archive: boolean;
+ worktree_prune_days: number;
+ worktree_setup_command: string;
+}
+
+export async function setWorktreeSettings(
+ changes: Partial<{
+ location: string; custom_dir: string; branch_prefix: string; fetch_first: boolean;
+ cleanup_on_archive: boolean; prune_days: number; setup_command: string;
+ }>,
+): Promise<{ ok: boolean; error?: string } & Partial<WorktreeSettings>> {
+ const res = await fetch(`${httpBase()}/v1/settings/worktrees`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(changes),
+ });
+ return res.json();
+}
+
export async function setScratchBase(
path: string,
): Promise<{ ok: boolean; error?: string; scratch_base?: string }> {
diff --git a/surfaces/gui/src/components/SettingsView.tsx b/surfaces/gui/src/components/SettingsView.tsx
index c9f02422..077faf51 100644
--- a/surfaces/gui/src/components/SettingsView.tsx
+++ b/surfaces/gui/src/components/SettingsView.tsx
@@ -35,6 +35,7 @@ import {
setOnboarded,
setPdfSettings,
setScratchBase,
+ setWorktreeSettings,
setSessionsPeek,
setWorkspaceTrusted,
type CompactionSettings,
@@ -111,6 +112,113 @@ export type SetTab =
| "slack"
| "github";
+// Feature worktrees (Code coworker, owner ruling 2026-11-07): where a task's worktree
+// goes, how its branch is named, fetch-first, cleanup, and the per-repo setup command.
+// Six fields with defaults most people never touch; saved as one change.
+function WorktreesCard() {
+ const { t } = useTranslation();
+ const [settings, setSettings] = useState<ModelSettings | null>(null);
+ const [draft, setDraft] = useState<{
+ location: "in_repo" | "sibling" | "custom"; custom_dir: string; branch_prefix: string;
+ fetch_first: boolean; cleanup_on_archive: boolean; prune_days: number; setup_command: string;
+ } | null>(null);
+ const [msg, setMsg] = useState<string | null>(null);
+ const desktop = isTauri();
+
+ const refresh = () =>
+ getSettings()
+ .then((s) => {
+ setSettings(s);
+ setDraft({
+ location: s.worktree_location || "in_repo",
+ custom_dir: s.worktree_custom_dir || "",
+ branch_prefix: s.worktree_branch_prefix || "",
+ fetch_first: s.worktree_fetch_first !== false,
+ cleanup_on_archive: s.worktree_cleanup_on_archive !== false,
+ prune_days: s.worktree_prune_days || 14,
+ setup_command: s.worktree_setup_command || "",
+ });
+ })
+ .catch(() => setSettings(null));
+ useEffect(() => {
+ refresh();
+ }, []);
+
+ if (!settings || !draft) return null;
+ const set = <K extends keyof typeof draft>(k: K, v: (typeof draft)[K]) => setDraft({ ...draft, [k]: v });
+ const save = async () => {
+ setMsg(null);
+ const res = await setWorktreeSettings(draft);
+ setMsg(res.ok ? t("settings.worktrees_saved") : res.error || t("settings.files_save_error"));
+ if (res.ok) refresh();
+ };
+
+ return (
+ <div className={CARD + " p-4 mb-4"} data-testid="worktrees-card">
+ <div className={FIELD_LABEL}>{t("settings.worktrees_title")}</div>
+ <div className={FIELD_HELP}>{t("settings.worktrees_help")}</div>
+
+ <div className="mt-3 flex items-center gap-2">
+ <label className="text-ui text-muted w-40 shrink-0">{t("settings.worktrees_where")}</label>
+ <select
+ className={INPUT}
+ data-testid="worktree-location"
+ value={draft.location}
+ onChange={(e) => set("location", e.target.value as typeof draft.location)}
+ >
+ <option value="in_repo">{t("settings.worktrees_in_repo")}</option>
+ <option value="sibling">{t("settings.worktrees_sibling")}</option>
+ <option value="custom">{t("settings.worktrees_custom")}</option>
+ </select>
+ </div>
+ {draft.location === "custom" && (
+ <div className="mt-2 flex items-center gap-2">
+ <label className="text-ui text-muted w-40 shrink-0">{t("settings.worktrees_custom_dir")}</label>
+ <input className={INPUT} type="text" value={draft.custom_dir} spellCheck={false}
+ onChange={(e) => set("custom_dir", e.target.value)} />
+ {desktop && (
+ <button className={BTN_BORDERED} onClick={async () => { const p = await pickFolder(); if (p) set("custom_dir", p); }}>
+ {t("settings.files_browse")}
+ </button>
+ )}
+ </div>
+ )}
+ <div className="mt-2 flex items-center gap-2">
+ <label className="text-ui text-muted w-40 shrink-0">{t("settings.worktrees_prefix")}</label>
+ <input className={INPUT} type="text" value={draft.branch_prefix} spellCheck={false}
+ placeholder={t("settings.worktrees_prefix_placeholder")}
+ onChange={(e) => set("branch_prefix", e.target.value)} />
+ </div>
+ <div className="mt-2 flex items-center gap-2">
+ <label className="text-ui text-muted w-40 shrink-0">{t("settings.worktrees_setup")}</label>
+ <input className={INPUT} type="text" value={draft.setup_command} spellCheck={false}
+ placeholder={t("settings.worktrees_setup_placeholder")}
+ onChange={(e) => set("setup_command", e.target.value)} />
+ </div>
+ <label className="mt-3 flex items-start gap-2 text-ui text-ink cursor-pointer">
+ <input type="checkbox" className="mt-1" checked={draft.fetch_first}
+ onChange={(e) => set("fetch_first", e.target.checked)} />
+ <span>{t("settings.worktrees_fetch_first")}</span>
+ </label>
+ <label className="mt-2 flex items-start gap-2 text-ui text-ink cursor-pointer">
+ <input type="checkbox" className="mt-1" checked={draft.cleanup_on_archive}
+ onChange={(e) => set("cleanup_on_archive", e.target.checked)} />
+ <span>{t("settings.worktrees_cleanup")}</span>
+ </label>
+ <div className="mt-2 flex items-center gap-2">
+ <label className="text-ui text-muted w-40 shrink-0">{t("settings.worktrees_prune")}</label>
+ <input className={INPUT + " max-w-[6rem]"} type="number" min={1} value={draft.prune_days}
+ onChange={(e) => set("prune_days", Math.max(1, Number(e.target.value) || 1))} />
+ <span className="text-meta text-muted">{t("settings.worktrees_prune_unit")}</span>
+ </div>
+ <div className="mt-3 flex items-center gap-2">
+ <button className={BTN_ACCENT} onClick={save} data-testid="worktrees-save">{t("settings.files_save")}</button>
+ {msg && <span className="text-ui text-muted">{msg}</span>}
+ </div>
+ </div>
+ );
+}
+
const CARD = "rounded-xl2 border border-line bg-panel";
const FIELD_LABEL = "text-ui font-medium text-ink";
const FIELD_HELP = "text-meta text-muted mt-1.5 leading-relaxed";
@@ -973,6 +1081,8 @@ function AppearanceSection() {
<FilesCard />
+ <WorktreesCard />
+
<TrustedWorkspacesCard />
{desktop && (
diff --git a/surfaces/gui/src/components/SettingsView.worktrees.test.tsx b/surfaces/gui/src/components/SettingsView.worktrees.test.tsx
new file mode 100644
index 00000000..0bda5ea4
--- /dev/null
+++ b/surfaces/gui/src/components/SettingsView.worktrees.test.tsx
@@ -0,0 +1,42 @@
+// The Worktrees settings card (Code coworker, 2026-11-07): renders the saved values and
+// sends one change with every field.
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../api", async (importOriginal) => {
+ const real = await importOriginal<typeof import("../api")>();
+ return {
+ ...real,
+ getSettings: vi.fn().mockResolvedValue({
+ provider: "openai", model: "m", models: ["m"], scratch_base: "/tmp/s",
+ worktree_location: "sibling", worktree_branch_prefix: "rp/", worktree_prune_days: 7,
+ worktree_fetch_first: true, worktree_cleanup_on_archive: false, worktree_setup_command: "npm install",
+ }),
+ setWorktreeSettings: vi.fn().mockResolvedValue({ ok: true }),
+ };
+});
+
+vi.mock("../tauri", () => ({ isTauri: () => false, pickFolder: vi.fn() }));
+
+afterEach(cleanup);
+
+describe("WorktreesCard", () => {
+ it("shows the saved settings and saves the whole draft", async () => {
+ const { SettingsView } = await import("./SettingsView");
+ const api = await import("../api");
+ render(<SettingsView initialTab="appearance" />);
+ const card = await screen.findByTestId("worktrees-card");
+ expect((card.querySelector('[data-testid="worktree-location"]') as HTMLSelectElement).value).toBe("sibling");
+ expect(card.textContent).toContain("Feature worktrees");
+
+ fireEvent.change(card.querySelector('[data-testid="worktree-location"]')!, { target: { value: "in_repo" } });
+ fireEvent.click(screen.getByTestId("worktrees-save"));
+ await waitFor(() => expect(api.setWorktreeSettings).toHaveBeenCalled());
+ const sent = (api.setWorktreeSettings as any).mock.calls[0][0];
+ expect(sent.location).toBe("in_repo");
+ expect(sent.branch_prefix).toBe("rp/");
+ expect(sent.prune_days).toBe(7);
+ expect(sent.cleanup_on_archive).toBe(false);
+ expect(sent.setup_command).toBe("npm install");
+ });
+});
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index 77d23629..c5239d90 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -478,6 +478,22 @@
"files_pick_folder": "Pick a folder",
"files_save": "Save",
"files_save_error": "Couldn't save.",
+ "worktrees_title": "Feature worktrees",
+ "worktrees_help": "The Code coworker gives each task its own branch and worktree, so your checkout is never edited in place. These are the defaults; a repo can override them.",
+ "worktrees_where": "Where they go",
+ "worktrees_in_repo": "Inside the repo (.openworker/worktrees)",
+ "worktrees_sibling": "Next to the repo (<repo>-worktrees)",
+ "worktrees_custom": "A folder I choose",
+ "worktrees_custom_dir": "Folder",
+ "worktrees_prefix": "Branch prefix",
+ "worktrees_prefix_placeholder": "your initials, e.g. rp/ (from your git name when empty)",
+ "worktrees_setup": "After creating, run",
+ "worktrees_setup_placeholder": "e.g. npm install — dependencies don't carry across worktrees",
+ "worktrees_fetch_first": "Fetch the base branch before branching, so every task starts from fresh main",
+ "worktrees_cleanup": "Remove a worktree when its session is archived — never one with uncommitted changes",
+ "worktrees_prune": "Prune untouched after",
+ "worktrees_prune_unit": "days",
+ "worktrees_saved": "Saved.",
"files_saved": "Saved.",
"files_title": "Files",
"gallery_open": "Browse the Persona Gallery",
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index db15c978..5473d223 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -459,6 +459,22 @@
"files_pick_folder": "选择文件夹",
"files_save": "保存",
"files_save_error": "无法保存。",
+ "worktrees_title": "功能工作树",
+ "worktrees_help": "Code 同事会为每个任务创建独立的分支和工作树,不会直接改动你的检出目录。这里是默认设置;仓库可以单独覆盖。",
+ "worktrees_where": "存放位置",
+ "worktrees_in_repo": "仓库内部(.openworker/worktrees)",
+ "worktrees_sibling": "仓库旁边(<仓库名>-worktrees)",
+ "worktrees_custom": "我选择的文件夹",
+ "worktrees_custom_dir": "文件夹",
+ "worktrees_prefix": "分支前缀",
+ "worktrees_prefix_placeholder": "你的姓名缩写,例如 rp/(留空时取自 git 用户名)",
+ "worktrees_setup": "创建后运行",
+ "worktrees_setup_placeholder": "例如 npm install——依赖不会在工作树之间共享",
+ "worktrees_fetch_first": "创建分支前先拉取基础分支,让每个任务都从最新的 main 开始",
+ "worktrees_cleanup": "会话归档时移除工作树——有未提交改动的绝不移除",
+ "worktrees_prune": "清理闲置超过",
+ "worktrees_prune_unit": "天的工作树",
+ "worktrees_saved": "已保存。",
"files_saved": "已保存。",
"files_title": "文件",
"gallery_open": "浏览角色画廊",
diff --git a/surfaces/gui/src/types.ts b/surfaces/gui/src/types.ts
index 0b6f757a..372b9250 100644
--- a/surfaces/gui/src/types.ts
+++ b/surfaces/gui/src/types.ts
@@ -29,6 +29,7 @@ export type EventType =
| "export_notice"
| "memory_saved"
| "agent_task"
+ | "workspace_changed"
| "compacting"
| "compacted"
| "continuation"
diff --git a/tests/test_server.py b/tests/test_server.py
index 65b590be..5006320f 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -71,7 +71,7 @@ def test_agents_and_memory_rest(tmp_path):
# ships:false personas (teams, ops, design) need OPENWORKER_UNSHIPPED=1.
names = [a["name"] for a in agents]
assert names[0] == "cowork"
- assert set(names) == {"cowork", "security", "cloud-posture", "dep-audit", "reviewer"}
+ assert set(names) == {"cowork", "code", "security", "cloud-posture", "dep-audit", "reviewer"}
assert "skills" in client.get("/v1/skills").json() # catalog (may be empty)
added = client.post("/v1/memory", json={"content": "prefer pathlib"}).json()
diff --git a/tests/test_start_worktree.py b/tests/test_start_worktree.py
new file mode 100644
index 00000000..9113abc1
--- /dev/null
+++ b/tests/test_start_worktree.py
@@ -0,0 +1,119 @@
+"""`start_worktree` (Code coworker, 2026-11-07): the session moves into its feature
+worktree — roots, shell cwd, persisted record — and cleanup on archive respects dirt.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from coworker.sessions import SessionRecord
+from coworker.server.manager import SessionManager
+from coworker.roots import RootDir
+
+
+def _git(*args, cwd):
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)
+
+
+def repo(tmp_path) -> Path:
+ root = tmp_path / "proj"
+ root.mkdir()
+ _git("init", "-q", "-b", "main", cwd=root)
+ _git("config", "user.email", "[email protected]", cwd=root)
+ _git("config", "user.name", "Test User", cwd=root)
+ (root / "app.py").write_text("print('hi')\n", encoding="utf-8")
+ _git("add", ".", cwd=root)
+ _git("commit", "-q", "-m", "init", cwd=root)
+ return root
+
+
+class _Shell:
+ """The slice of an executor start_worktree touches: a cwd and a `cd` command."""
+
+ def __init__(self, cwd: str):
+ self.cwd = cwd
+ self.ran: list[str] = []
+
+ def run(self, command: str, timeout: int = 15):
+ self.ran.append(command)
+ if command.startswith("cd "):
+ self.cwd = command[3:].strip().strip("'")
+ return {"exit_code": 0, "stdout": "", "stderr": ""}
+
+
+def _manager_with_session(tmp_path, repo, monkeypatch) -> tuple[SessionManager, str, SimpleNamespace]:
+ mgr = SessionManager(workspace=str(tmp_path), data_dir=tmp_path / "data")
+ sid = "sess-wt"
+ mgr.session_store.save(SessionRecord(session_id=sid, workspace=str(repo), model="m", mode="auto", agent="code"))
+ engine = SimpleNamespace(
+ executor=_Shell(str(repo)),
+ roots=[RootDir(path=repo.resolve(), writable=True, label="workspace")],
+ )
+ mgr._engines[sid] = engine
+ monkeypatch.setattr(mgr, "save", lambda *a, **k: None) # the real save needs a full engine
+ return mgr, sid, engine
+
+
+def test_start_worktree_moves_the_session_in(tmp_path, repo, monkeypatch):
+ mgr, sid, engine = _manager_with_session(tmp_path, repo, monkeypatch)
+ res = mgr.start_worktree(sid, "add a login page")
+ assert res["ok"], res
+ path = Path(res["path"])
+ assert path == repo / ".openworker" / "worktrees" / "add-a-login-page"
+ assert res["branch"].endswith("/add-a-login-page")
+ # The shell moved, the worktree is the writable primary, the checkout went read-only.
+ assert Path(engine.executor.cwd).resolve() == path.resolve()
+ assert engine.roots[0].path == path.resolve() and engine.roots[0].writable
+ original = [r for r in engine.roots if Path(str(r.path)).resolve() == repo.resolve()]
+ assert original and original[0].writable is False
+ # Persisted on the record, and the engine is marked for the post-turn rebuild.
+ assert mgr.session_worktree(sid)["branch"] == res["branch"]
+ assert sid in mgr._promotion_rebuild
+ # A second call is a no-op that says so.
+ again = mgr.start_worktree(sid, "something else")
+ assert again["ok"] and again.get("already")
+
+
+def test_start_worktree_refuses_a_plain_folder(tmp_path, monkeypatch):
+ plain = tmp_path / "plain"
+ plain.mkdir()
+ mgr, sid, engine = _manager_with_session(tmp_path, plain, monkeypatch)
+ res = mgr.start_worktree(sid, "anything")
+ assert not res["ok"] and "not a git repository" in res["error"]
+ assert engine.executor.cwd == str(plain) # nothing moved
+
+
+def test_archive_removes_a_clean_worktree_but_keeps_a_dirty_one(tmp_path, repo, monkeypatch):
+ mgr, sid, engine = _manager_with_session(tmp_path, repo, monkeypatch)
+ res = mgr.start_worktree(sid, "cleanup check")
+ path = Path(res["path"])
+ (path / "wip.txt").write_text("unfinished", encoding="utf-8")
+ mgr.set_session_flags(sid, archived=True)
+ assert path.is_dir(), "a dirty worktree must survive archive"
+ (path / "wip.txt").unlink()
+ mgr.set_session_flags(sid, archived=False)
+ mgr.set_session_flags(sid, archived=True)
+ assert not path.exists()
+ # The branch is still there.
+ out = subprocess.run(["git", "branch", "--list", res["branch"]], cwd=repo, capture_output=True, text=True).stdout
+ assert res["branch"] in out
+
+
+def test_worktree_settings_round_trip_and_repo_override(tmp_path, repo):
+ mgr = SessionManager(workspace=str(tmp_path), data_dir=tmp_path / "data")
+ assert mgr.get_settings()["worktree_location"] == "in_repo"
+ bad = mgr.set_worktree_settings({"location": "moon"})
+ assert not bad["ok"]
+ ok = mgr.set_worktree_settings({"location": "sibling", "branch_prefix": "rp/", "prune_days": 30})
+ assert ok["ok"] and ok["worktree_location"] == "sibling" and ok["worktree_prune_days"] == 30
+ over = mgr.set_worktree_override(str(repo), {"location": "in_repo"})
+ assert over["ok"]
+ assert mgr.worktree_settings(str(repo)).location == "in_repo" # the repo's override wins
+ assert mgr.worktree_settings(str(tmp_path)).location == "sibling" # elsewhere, the global
+ cleared = mgr.set_worktree_override(str(repo), {})
+ assert cleared["ok"] and mgr.worktree_settings(str(repo)).location == "sibling"
diff --git a/tests/test_worktrees.py b/tests/test_worktrees.py
new file mode 100644
index 00000000..c12c5878
--- /dev/null
+++ b/tests/test_worktrees.py
@@ -0,0 +1,105 @@
+"""Feature worktrees (Code coworker, 2026-11-07): the policy module on real temp repos."""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from coworker import worktrees as wt
+
+
+def _git(*args, cwd):
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)
+
+
+def repo(tmp_path) -> Path:
+ root = tmp_path / "proj"
+ root.mkdir()
+ _git("init", "-q", "-b", "main", cwd=root)
+ _git("config", "user.email", "[email protected]", cwd=root)
+ _git("config", "user.name", "Rohit C Prasad", cwd=root)
+ (root / "README.md").write_text("hi\n", encoding="utf-8")
+ _git("add", ".", cwd=root)
+ _git("commit", "-q", "-m", "init", cwd=root)
+ return root
+
+
+def test_settings_merge_prefs_and_repo_override():
+ prefs = {"worktree_location": "sibling", "worktree_prune_days": "7",
+ "worktree_overrides": {"/k": {"location": "custom", "custom_dir": "/tmp/x"}}}
+ s = wt.settings_from_prefs(prefs)
+ assert s.location == "sibling" and s.prune_days == 7 and s.fetch_first is True
+ o = wt.settings_from_prefs(prefs, project_key="/k")
+ assert o.location == "custom" and o.custom_dir == "/tmp/x" and o.prune_days == 7
+ bad = wt.settings_from_prefs({"worktree_location": "moon", "worktree_prune_days": "x"})
+ assert bad.location == "in_repo" and bad.prune_days == 14
+
+
+def test_validate_settings_rejects_what_it_should():
+ assert wt.validate_settings({"location": "sibling", "prune_days": "3", "branch_prefix": "rp/"}) == {
+ "location": "sibling", "prune_days": 3, "branch_prefix": "rp/"}
+ with pytest.raises(ValueError):
+ wt.validate_settings({"location": "custom", "custom_dir": ""})
+ with pytest.raises(ValueError):
+ wt.validate_settings({"branch_prefix": "bad prefix!"})
+ with pytest.raises(ValueError):
+ wt.validate_settings({"prune_days": 0})
+
+
+def test_prefix_comes_from_the_git_user_name(repo):
+ assert wt.derive_prefix(repo) == "rp/"
+ assert wt.slugify("Add the plan dock above the composer!") == "add-the-plan-dock-above-the-composer"
+
+
+def test_create_in_repo_worktree_excludes_and_names_by_policy(repo):
+ info = wt.create_worktree(repo, "Add a login page", wt.WorktreeSettings())
+ path = Path(info["path"])
+ assert path == repo / ".openworker" / "worktrees" / "add-a-login-page"
+ assert path.is_dir() and (path / "README.md").is_file()
+ assert info["branch"] == "rp/add-a-login-page" and info["base"] == "main"
+ assert info["fetched"] is False # no origin: branched from the local main, no warning
+ assert info["warnings"] == []
+ exclude = (repo / ".git" / "info" / "exclude").read_text(encoding="utf-8")
+ assert ".openworker/" in exclude.splitlines()
+ # The user's checkout is untouched and git status stays clean there.
+ status = subprocess.run(["git", "status", "--porcelain"], cwd=repo, capture_output=True, text=True).stdout
+ assert status.strip() == ""
+ # A second task with the same words gets a distinct branch and folder.
+ again = wt.create_worktree(repo, "Add a login page", wt.WorktreeSettings())
+ assert again["branch"] == "rp/add-a-login-page-2"
+ assert Path(again["path"]).name == "add-a-login-page-2"
+
+
+def test_sibling_and_custom_locations_and_setup_command(repo, tmp_path):
+ info = wt.create_worktree(repo, "sibling task", wt.WorktreeSettings(location="sibling"))
+ assert Path(info["path"]) == repo.parent / "proj-worktrees" / "sibling-task"
+ custom = tmp_path / "elsewhere"
+ info = wt.create_worktree(
+ repo, "custom task",
+ wt.WorktreeSettings(location="custom", custom_dir=str(custom), setup_command="echo ready > setup.txt"),
+ )
+ assert Path(info["path"]) == custom / "proj" / "custom-task"
+ assert (Path(info["path"]) / "setup.txt").read_text().strip() == "ready"
+ assert info["setup"]["exit_code"] == 0
+
+
+def test_not_a_repo_is_reported_not_guessed(tmp_path):
+ plain = tmp_path / "plain"
+ plain.mkdir()
+ assert wt.repo_root(plain) is None
+
+
+def test_removal_never_touches_a_dirty_worktree(repo):
+ info = wt.create_worktree(repo, "clean me", wt.WorktreeSettings())
+ path = Path(info["path"])
+ (path / "wip.txt").write_text("unfinished", encoding="utf-8")
+ assert wt.is_clean(path) is False
+ assert wt.remove_worktree(repo, path) is False and path.is_dir()
+ (path / "wip.txt").unlink()
+ assert wt.remove_worktree(repo, path) is True and not path.exists()
+ # The branch survives: unmerged work is never deleted with its folder.
+ branches = subprocess.run(["git", "branch", "--list", info["branch"]], cwd=repo, capture_output=True, text=True).stdout
+ assert info["branch"] in branches