Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(voice): a workspace's repository by voice, safe worktree archiving, and forking an agent's conversation (#638)
Ruben Lütkec48115cffbce
diff --git a/docs/igentic-workspaces.md b/docs/igentic-workspaces.mdindex 9dcdb30413..4f033b6099 100644--- a/docs/igentic-workspaces.md+++ b/docs/igentic-workspaces.md@@ -67,6 +67,20 @@ worker tools and does not grant Society agents any new capability.when a new prompt is typed into that session, and reports a finished turn,never verified work. A task sent through `send` is followed without it.+`fork` opens a copy of a session that continues the same conversation beside the+original, and with `worktree` in a new git worktree and branch, so two agents can+work on one task without touching each other's files.++The repository of a workspace has its own voice tool, `workspace-git`. Like the+actions above it names a workspace, never a path. It reads the branch, sync state+and changed files (`state`), the checkouts and archived worktrees (`worktrees`)+and the pull requests with their checks (`pull_requests`); it creates a worktree,+commits, pushes and opens a pull request. `worktree_archive` removes a checkout+only after saving its uncommitted work into a snapshot ref+(`refs/dodaios/archived-worktrees/…`), and `worktree_restore` brings it back at+its old path with those files uncommitted again. Ignored files are not part of a+snapshot.+For example, a request to fix an installer in a named project can address abackground workspace while the user continues viewing another project. Theorchestrator never temporarily changes global selection to make a delivery.diff --git a/jarvis/agentic_ide/git_ops.py b/jarvis/agentic_ide/git_ops.pyindex 0cf5ec7163..504d65f9a6 100644--- a/jarvis/agentic_ide/git_ops.py+++ b/jarvis/agentic_ide/git_ops.py@@ -93,9 +93,15 @@ def gh_available() -> bool:def _run(- args: list[str], cwd: Path, *, timeout: float = _GIT_TIMEOUT_S, program: str = "git"+ args: list[str],+ cwd: Path,+ *,+ timeout: float = _GIT_TIMEOUT_S,+ program: str = "git",+ extra_env: dict[str, str] | None = None,) -> subprocess.CompletedProcess[str]:env = dict(os.environ)+ env.update(extra_env or {})# Never block on a credential or editor prompt nobody can see.env["GIT_TERMINAL_PROMPT"] = "0"env.setdefault("GIT_EDITOR", "true")@@ -131,8 +137,15 @@ def _reason(result: subprocess.CompletedProcess[str]) -> str:return lines[-1] if lines else f"exited with {result.returncode}"-def _ok(args: list[str], cwd: Path, *, timeout: float = _GIT_TIMEOUT_S, what: str = "") -> str:- result = _run(args, cwd, timeout=timeout)+def _ok(+ args: list[str],+ cwd: Path,+ *,+ timeout: float = _GIT_TIMEOUT_S,+ what: str = "",+ extra_env: dict[str, str] | None = None,+) -> str:+ result = _run(args, cwd, timeout=timeout, extra_env=extra_env)if result.returncode != 0:prefix = f"Git could not {what}: " if what else "Git: "raise GitError(prefix + _reason(result))@@ -443,8 +456,11 @@ def brief(folder: str | Path) -> dict[str, Any] | None:if root is None:return Noneinfo = RepoInfo(folder=str(path), is_repo=True, root=str(root))+ # No optional locks: the board reads every workspace at once while agents+ # run their own git commands there, and must never make one of them fail.status = _run(- ["status", "--porcelain=v2", "--branch", "--untracked-files=normal"],+ ["--no-optional-locks", "status", "--porcelain=v2", "--branch",+ "--untracked-files=normal"],root,timeout=_BRIEF_TIMEOUT_S,)diff --git a/jarvis/agentic_ide/github_pulls.py b/jarvis/agentic_ide/github_pulls.pyindex 07565ba11c..01c195c781 100644--- a/jarvis/agentic_ide/github_pulls.py+++ b/jarvis/agentic_ide/github_pulls.py@@ -10,9 +10,11 @@ API. Failures come back as one sentence — GitHub's own where it has onefrom __future__ import annotationsfrom dataclasses import dataclass+from pathlib import Pathfrom typing import Any-from jarvis.agentic_ide import github_link+from jarvis.agentic_ide import git_ops, github_link+from jarvis.agentic_ide.git_ops import GitErrorfrom jarvis.agentic_ide.github_link import GitHubError_REPOSITORY_ID = """@@ -76,3 +78,44 @@ def create(_first_error(payload) or "GitHub could not open the pull request.", code="refused")return CreatedPullRequest(number=int(created.get("number") or 0), url=str(created["url"]))+++def open_for_branch(+ folder: str | Path, *, branch: str = "", title: str = "", draft: bool = False+) -> str:+ """Push ``branch`` (default: the checked-out one) if needed and open its pull request.++ Uses the GitHub connection the Git tab already reads with; without one (or+ before a repository was picked for the folder) the GitHub CLI opens it.+ Returns the pull request's URL.+ """+ path = Path(folder)+ cred = github_link.credential()+ repo = github_link.bound_repository(path)+ wanted = git_ops.normalize_branch(branch)+ info = git_ops.inspect(path)+ if cred is None or not repo:+ if wanted and wanted != info.branch:+ raise GitError("Connect GitHub to open this pull request.", code="not_connected")+ return git_ops.create_pull_request(path, title=title, draft=draft)+ head_branch = wanted or info.branch+ if not info.is_repo or not head_branch:+ raise GitError("Check out a branch before opening a pull request.", code="detached")+ if head_branch == info.default_branch:+ raise GitError(+ f"{head_branch} is the default branch — open the pull request from a feature branch.",+ code="invalid",+ )+ upstream = git_ops.push(path, head_branch)+ head = upstream.partition("/")[2] or head_branch+ base_ref = f"origin/{info.default_branch}"+ if base_ref not in info.remote_branches:+ base_ref = info.default_branch+ subject = title.strip() or git_ops.first_subject(path, head_branch, base_ref)+ try:+ created = create(+ repo, cred.token, head=head, base=info.default_branch, title=subject, draft=draft+ )+ except GitHubError as exc:+ raise GitError(str(exc), code=exc.code) from exc+ return created.urldiff --git a/jarvis/agentic_ide/orchestration.py b/jarvis/agentic_ide/orchestration.pyindex bc0146063b..09f4073ded 100644--- a/jarvis/agentic_ide/orchestration.py+++ b/jarvis/agentic_ide/orchestration.py@@ -57,7 +57,9 @@ _TARGET_KEYS = ("project_id", "workspace_id", "terminal_id")# A send of the same prompt to the same pane counts as a retry only this soon;# a later "continue" or "/compact" is a new instruction and must be typed._RETRY_WINDOW_S = 120-_PANE_ACTIONS = frozenset({"observe", "respond", "keys", "interrupt", "restart", "close"})+_PANE_ACTIONS = frozenset(+ {"observe", "respond", "keys", "interrupt", "restart", "close", "fork"}+)# A pane whose agent process is gone (exited, or could not start). A send there# types nothing; restart brings the same pane back on its own conversation._STOPPED = frozenset({"exited", "error"})@@ -471,7 +473,17 @@ class WorkspaceOrchestrator:"from, so its end cannot be reported. Nothing is watched; use status ""to look again.",}- await followthrough.watch(term, origin)+ armed = await followthrough.watch(term, origin)+ if snapshot(term)["availability"] != "busy":+ # It finished while the watch was being set up: that end is already+ # in the watch's starting point and would never be reported.+ if getattr(term, "delegation_result", None) is armed:+ term.delegation_result = None+ return {+ **reply, "state": snapshot(term)["availability"], "status": "not_running",+ "reason": "That agent just finished, so there is nothing to wait for. "+ "Its state is above; observe it for what it wrote.",+ }return {**reply, "status": "watching","reason": "Its result is handed to this conversation when it stops or asks. Tell "@@ -916,6 +928,35 @@ class WorkspaceOrchestrator:return {"status": "pressed", "target": target, "keys": keys, "agent": term.name}if action == "restart":return await self._restart(owner, term, target)+ if action == "fork":+ in_worktree = args.get("worktree") is True+ copy = await self.registry.fork_terminal(+ term.name,+ workspace_id=owner.id,+ worktree=in_worktree,+ name=str(args.get("name") or "").strip() or None,+ )+ await self._announce(+ lambda: terminals_added_event(+ owner, [copy], source_layer="agentic_ide.orchestration"+ )+ )+ return {+ "status": "forked",+ "target": target,+ "agent": term.name,+ "copy": {+ "terminal_id": "pane:" + copy.history_id,+ "name": copy.name,+ **({"folder": copy.folder, "branch": copy.branch} if in_worktree else {}),+ },+ "reason": (+ "The copy continues the same conversation"+ + (" in its own worktree and branch" if in_worktree else "")+ + ". The original is untouched. Send the copy its next task by its "+ "terminal_id."+ ),+ }if action == "close":from .fleet_actions import terminals_closed_event@@ -1391,6 +1432,7 @@ class WorkspaceOrchestrator:to_created = action == "send" and str(args.get("terminal_id") or "") in createdif (args.get("_requires_new") or creation) and not to_created and action not in {"inspect", "create", "open_workspace", "context", "observe", "status", "watch",+ "git",}:# A NEW request cannot borrow an idle pane for its new task, but it# may also carry independent work for an agent the user NAMED@@ -1429,6 +1471,10 @@ class WorkspaceOrchestrator:return self.resolve(args, graph)if action == "create":return await self.create(args, trace_id=trace_id)+ if action == "git":+ from . import workspace_git++ return await workspace_git.run(self, args)if action in {"status", "watch"}:from . import task_statediff --git a/jarvis/agentic_ide/workspace_git.py b/jarvis/agentic_ide/workspace_git.pynew file mode 100644index 0000000000..3d9e6bbcca--- /dev/null+++ b/jarvis/agentic_ide/workspace_git.py@@ -0,0 +1,209 @@+"""Git for a coding workspace, addressed like every other workspace action.++A request names a workspace (or leaves it out for the visible one), never a+path: the folder comes from the workspace, so no operation can be pointed+elsewhere on the machine. Reads describe the repository; the other operations+create, put away and restore worktrees, commit, push and open a pull request.+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++from . import git_ops, git_overview, github_pulls, worktree_archive+from .git_ops import GitError++READ_OPS = frozenset({"state", "worktrees", "pull_requests"})+OPS = (+ "state",+ "worktrees",+ "pull_requests",+ "worktree_create",+ "worktree_archive",+ "worktree_restore",+ "commit",+ "push",+ "pull_request",+)+#: How many changed paths a spoken state answer carries.+_STATE_CHANGES = 20+#: How many pull requests one answer lists.+_PULL_REQUESTS = 15+++def _state(folder: str) -> dict[str, Any]:+ info = git_ops.inspect(folder)+ if not info.git_available:+ raise GitError("Git is not installed on this machine.", code="missing")+ if not info.is_repo:+ raise GitError(f"{Path(folder).name} is not a git repository.", code="not_repo")+ changes = [+ {"path": change.path, "staged": change.index, "unstaged": change.worktree}+ for change in info.changes[:_STATE_CHANGES]+ ]+ return {+ "branch": info.branch,+ "detached": info.detached,+ "default_branch": info.default_branch,+ "upstream": info.upstream,+ "ahead": info.ahead,+ "behind": info.behind,+ "staged": info.staged,+ "unstaged": info.unstaged,+ "untracked": info.untracked,+ "conflicted": info.conflicted,+ "lines_added": info.insertions,+ "lines_removed": info.deletions,+ "changes": changes,+ "more_changes": max(0, len(info.changes) - len(changes)),+ "linked_worktree": info.is_worktree,+ }+++def _worktrees(folder: str) -> dict[str, Any]:+ info = git_ops.inspect(folder)+ if not info.is_repo:+ raise GitError(f"{Path(folder).name} is not a git repository.", code="not_repo")+ return {+ "worktrees": [+ {+ "folder": tree.path,+ "branch": tree.branch,+ "main": tree.main,+ "here": tree.current,+ **({"locked": True} if tree.locked else {}),+ **({"folder_missing": True} if tree.prunable else {}),+ }+ for tree in info.worktrees+ ],+ "archived": [entry.to_dict() for entry in worktree_archive.archived(folder)],+ }+++def _pull_requests(folder: str) -> dict[str, Any]:+ """The repository's open pull requests and the ones of its local branches."""+ seen = git_overview.overview(folder)+ if not seen.available:+ raise GitError(seen.reason or "This folder has no repository.", code="not_repo")+ rows: dict[int, dict[str, Any]] = {}+ for pr in [*(pr for branch in seen.branches for pr in branch.pull_requests),+ *seen.pull_requests]:+ rows.setdefault(pr.number, {+ "number": pr.number,+ "title": pr.title,+ "state": pr.state,+ "branch": pr.head,+ "into": pr.base,+ "url": pr.url,+ "checks": pr.ci.state,+ **({"failed_checks": pr.ci.failed} if pr.ci.failed else {}),+ **({"running_checks": pr.ci.running + pr.ci.pending}+ if pr.ci.running or pr.ci.pending else {}),+ **({"conflicting": True} if pr.conflicting else {}),+ **({"review": pr.review} if pr.review else {}),+ **({"merge_queue_position": pr.queue_position}+ if pr.queue_position is not None else {}),+ **({"here": True} if pr.head == seen.branch else {}),+ })+ listed = sorted(rows.values(), key=lambda row: (not row.get("here"), -row["number"]))+ return {+ "branch": seen.branch,+ "github": (+ {"connected": True, "repository": seen.github.repo}+ if seen.github.available+ else {"connected": False, "reason": seen.github.reason}+ ),+ "pull_requests": listed[:_PULL_REQUESTS],+ "more_pull_requests": max(0, len(listed) - _PULL_REQUESTS),+ }+++def _perform(op: str, folder: str, args: dict[str, Any], open_folders: list[str]) -> dict[str, Any]:+ """Run one operation on the worker thread. Raises ``GitError`` with its reason."""+ if op == "state":+ return _state(folder)+ if op == "worktrees":+ return _worktrees(folder)+ if op == "pull_requests":+ return _pull_requests(folder)+ if op == "worktree_create":+ made = git_ops.prepare(+ folder, "new_worktree",+ branch=str(args.get("branch") or ""), base=str(args.get("base") or ""),+ )+ return {+ **made.to_dict(),+ "next_step": (+ "To start agents in it, call workspace-orchestrate open_workspace with this "+ "folder. Nothing runs there yet."+ ),+ }+ if op == "worktree_archive":+ entry = worktree_archive.archive(+ folder, str(args.get("worktree") or ""), open_folders=open_folders,+ drop_ignored=args.get("drop_ignored") is True,+ )+ return {+ "archived": entry.to_dict(),+ "message": (+ f"Archived {entry.branch or Path(entry.path).name}. "+ + ("Its uncommitted, non-ignored work is saved with it. "+ if entry.uncommitted else "")+ + "The branch and its commits are untouched; worktree_restore brings it back."+ ),+ }+ if op == "worktree_restore":+ return worktree_archive.restore(folder, str(args.get("worktree") or "")).to_dict()+ if op == "commit":+ sha = git_ops.commit_all(folder, str(args.get("message") or ""))+ return {"commit": sha, "message": f"Committed as {sha}."}+ if op == "push":+ upstream = git_ops.push(folder, str(args.get("branch") or ""))+ # What GitHub is known to hold for this folder is now out of date.+ git_overview.clear_github(folder)+ return {"upstream": upstream, "message": f"Pushed to {upstream}."}+ if op == "pull_request":+ url = github_pulls.open_for_branch(+ folder,+ branch=str(args.get("branch") or ""),+ title=str(args.get("title") or ""),+ draft=args.get("draft") is True,+ )+ git_overview.clear_github(folder)+ return {"url": url, "message": "Pull request opened."}+ raise ValueError("Unknown git operation.")+++async def run(orchestrator: Any, args: dict[str, Any]) -> dict[str, Any]:+ """Resolve the workspace a request names and run one git operation in its folder."""+ op = str(args.get("op") or "").strip()+ if op not in OPS:+ raise ValueError(f"op must be one of {', '.join(OPS)}.")+ graph = await asyncio.to_thread(orchestrator.graph)+ picked = orchestrator._workspace(args, graph, "")+ if isinstance(picked, dict):+ return picked+ project, workspace = picked+ target = {+ "project_id": project["id"],+ "workspace_id": workspace["id"],+ "workspace": workspace["name"],+ }+ open_folders: list[str] = []+ for session in orchestrator.registry.sessions:+ open_folders.append(session.folder)+ open_folders.extend(pane.cwd(session.folder) for pane in session.terminals)+ try:+ result = await asyncio.to_thread(_perform, op, workspace["folder"], args, open_folders)+ except GitError as exc:+ # Git's own refusal, in one sentence: nothing else happened.+ return {+ "status": "not_accepted", "success": False, "op": op,+ "code": exc.code, "reason": str(exc), **target,+ }+ return {"status": "ok", "op": op, **target, **result}+++__all__ = ["OPS", "READ_OPS", "run"]diff --git a/jarvis/agentic_ide/worktree_archive.py b/jarvis/agentic_ide/worktree_archive.pynew file mode 100644index 0000000000..b6eb4bd2cd--- /dev/null+++ b/jarvis/agentic_ide/worktree_archive.py@@ -0,0 +1,357 @@+"""Put a linked worktree away without losing what was in it, and bring it back.++Removing a worktree with uncommitted work discards that work. Archiving saves+it first: every tracked change and every untracked file that is not ignored is+written into one snapshot commit, kept under a ref of its own, and only then is+the checkout removed. The branch and its commits stay where they are.+Restoring recreates the checkout at its old path and puts the saved files back+as uncommitted changes.++Ignored files (build output, virtual environments, ``.env``) are not part of a+snapshot; they are not part of the repository either.+"""++from __future__ import annotations++import json+import os+import re+import secrets+import tempfile+import time+from dataclasses import asdict, dataclass+from pathlib import Path+from typing import Any++from loguru import logger++from . import git_ops+from .git_ops import GitError, Prepared++#: Snapshots live outside ``refs/heads`` so they never show up as branches.+ARCHIVE_REF_PREFIX = "refs/dodaios/archived-worktrees/"+_SUBJECT_MARK = "archived-worktree "+# The snapshot is made by the app, also on a machine with no git identity set.+_SNAPSHOT_IDENTITY = {+ "GIT_AUTHOR_NAME": "Dodaios",+ "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "Dodaios",+ "GIT_COMMITTER_EMAIL": "[email protected]",+}+++@dataclass(slots=True)+class ArchivedWorktree:+ """One worktree that was put away and can be restored."""++ name: str+ branch: str+ path: str+ #: The commit the worktree was on when it was archived.+ head: str+ archived_at: int+ #: Whether the snapshot holds work that was never committed.+ uncommitted: bool = False++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++def _git(args: list[str], cwd: Path, *, what: str = "", env: dict[str, str] | None = None) -> str:+ """Run git like :func:`git_ops._ok`, optionally with extra environment."""+ return git_ops._ok(args, cwd, what=what, extra_env=env)+++#: How many untracked entries are looked into for a repository of their own.+_NESTED_SCAN_LIMIT = 20_000+#: How many ignored entries a refusal names.+_IGNORED_NAMED = 8+_NO_SNAPSHOT_YET = "0" * 40+++def _slug(text: str) -> str:+ """A ref-safe label: no ``..``, no trailing dot, no ``.lock`` ending."""+ slug = re.sub(r"[^A-Za-z0-9_-]+", "-", text).strip("-")+ return slug or "worktree"+++def _unsaved_by_a_snapshot(tree_path: Path) -> tuple[list[str], list[str]]:+ """What a snapshot would NOT hold: nested repositories, and ignored entries.++ A repository inside the worktree (a submodule, a clone someone made there)+ is recorded as a pointer only, never with its files; ignored files are not+ recorded at all. Removing the checkout would delete both.+ """+ nested: list[str] = []+ modules = git_ops._run(["submodule", "status"], tree_path)+ if modules.returncode == 0:+ nested.extend(+ line.split()[1] for line in modules.stdout.splitlines()+ if line.strip() and not line.startswith("-") and len(line.split()) > 1+ )+ listed = git_ops._run(+ ["ls-files", "--others", "--exclude-standard", "--directory"], tree_path+ )+ seen = 0+ for entry in listed.stdout.splitlines() if listed.returncode == 0 else []:+ if not entry.endswith("/"):+ continue+ top = tree_path / entry+ if (top / ".git").exists():+ nested.append(entry.rstrip("/"))+ continue+ for current, folders, _files in os.walk(top):+ seen += 1 + len(folders)+ if ".git" in folders or Path(current, ".git").is_file():+ nested.append(os.path.relpath(current, tree_path).replace(os.sep, "/"))+ break+ if seen > _NESTED_SCAN_LIMIT:+ break+ ignored_listing = git_ops._run(+ ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory"], tree_path+ )+ ignored = (+ [line for line in ignored_listing.stdout.splitlines() if line.strip()]+ if ignored_listing.returncode == 0 else []+ )+ return nested, ignored+++def _main_root(folder: str | Path) -> tuple[Path, git_ops.RepoInfo]:+ path = git_ops._folder(folder)+ info = git_ops.inspect(path)+ if not info.is_repo:+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")+ return Path(info.main_root or info.root), info+++def _find_tree(info: git_ops.RepoInfo, worktree: str) -> git_ops.Worktree:+ """The linked worktree named by its path, its folder name or its branch."""+ wanted = str(worktree or "").strip()+ if not wanted:+ raise GitError("Name the worktree by its branch or its folder.", code="invalid")+ linked = [tree for tree in info.worktrees if not tree.main]+ for tree in linked:+ if git_ops._same_path(tree.path, wanted):+ return tree+ branch = git_ops.normalize_branch(wanted)+ matches = [+ tree for tree in linked+ if tree.branch == branch or Path(tree.path).name.casefold() == wanted.casefold()+ ]+ if len(matches) == 1:+ return matches[0]+ if any(tree.main and (tree.branch == branch or git_ops._same_path(tree.path, wanted))+ for tree in info.worktrees):+ raise GitError("The main checkout cannot be archived.", code="invalid")+ names = ", ".join(tree.branch or Path(tree.path).name for tree in linked) or "none"+ raise GitError(+ f"No linked worktree is called {wanted}. Linked worktrees: {names}.", code="not_found"+ )+++def archive(+ folder: str | Path, worktree: str, *, open_folders: list[str], drop_ignored: bool = False+) -> ArchivedWorktree:+ """Save a linked worktree's work to a snapshot, then remove the checkout.++ Refuses whatever the snapshot could not bring back: a repository nested in+ the worktree, and, unless ``drop_ignored``, ignored files (they are not+ part of a snapshot and removing the checkout deletes them).+ """+ main_root, info = _main_root(folder)+ tree = _find_tree(info, worktree)+ tree_path = Path(tree.path)+ if git_ops.worktree_in_use(tree_path, open_folders):+ raise GitError(+ "A workspace or agent is still open in this worktree. Close it first.", code="in_use"+ )+ if not tree_path.is_dir():+ raise GitError(+ f"The folder {tree_path} is gone; there is nothing to save.", code="prunable"+ )+ if tree.locked:+ raise GitError("This worktree is locked and stays where it is.", code="locked")+ nested, ignored = _unsaved_by_a_snapshot(tree_path)+ if nested:+ raise GitError(+ "This worktree holds a repository of its own ("+ + ", ".join(nested[:_IGNORED_NAMED])+ + "); a snapshot would not save its files. Commit and push it, or move it "+ "out, before archiving.",+ code="nested_repository",+ )+ if ignored and not drop_ignored:+ more = len(ignored) - _IGNORED_NAMED+ raise GitError(+ "Ignored files are not part of a snapshot and would be deleted with the "+ "checkout: " + ", ".join(ignored[:_IGNORED_NAMED])+ + (f" and {more} more" if more > 0 else "")+ + ". Copy what is still needed, then archive again with drop_ignored.",+ code="ignored_files",+ )+ head = _git(["rev-parse", "HEAD"], tree_path, what="read the worktree").strip()+ head_tree = _git(["rev-parse", "HEAD^{tree}"], tree_path).strip()+ with tempfile.TemporaryDirectory(prefix="worktree-archive-") as scratch:+ # A private index: the worktree's own staging area is left untouched.+ index = {"GIT_INDEX_FILE": str(Path(scratch) / "index")}+ _git(["read-tree", "HEAD"], tree_path, env=index, what="snapshot the worktree")+ _git(["add", "--all"], tree_path, env=index, what="snapshot the worktree")+ saved_tree = _git(["write-tree"], tree_path, env=index).strip()+ stamp = int(time.time())+ label = tree.branch or tree_path.name+ entry = ArchivedWorktree(+ name=f"{_slug(label)}-{stamp}-{secrets.token_hex(2)}",+ branch=tree.branch,+ path=str(tree_path),+ head=head,+ archived_at=stamp,+ uncommitted=saved_tree != head_tree,+ )+ subject = _SUBJECT_MARK + json.dumps(+ {"branch": entry.branch, "path": entry.path}, ensure_ascii=True+ )+ commit = _git(+ ["commit-tree", saved_tree, "-p", head, "-m", subject],+ main_root, env=_SNAPSHOT_IDENTITY, what="save the snapshot",+ ).strip()+ # The listing reads the time from the snapshot itself; report the same one.+ written = _git(["show", "-s", "--format=%ct", commit], main_root).strip()+ entry.archived_at = int(written) if written.isdigit() else stamp+ ref = ARCHIVE_REF_PREFIX + entry.name+ # Only as a new ref: a snapshot never replaces another one.+ _git(["update-ref", ref, commit, _NO_SNAPSHOT_YET], main_root, what="save the snapshot")+ try:+ _git(["worktree", "remove", "--force", str(tree_path)], main_root,+ what="remove the worktree")+ except GitError as exc:+ # The work is saved either way; say so, and keep the snapshot.+ raise GitError(+ f"{exc} The snapshot {entry.name} was saved and the worktree is still there.",+ code="not_removed",+ ) from exc+ logger.info("Agentic IDE git: archived worktree {} as {}", tree_path, entry.name)+ return entry+++def archived(folder: str | Path) -> list[ArchivedWorktree]:+ """Every archived worktree of ``folder``'s repository, newest first."""+ main_root, _info = _main_root(folder)+ listing = git_ops._run(+ [+ "for-each-ref",+ "--sort=-committerdate",+ "--format=%(refname)%09%(parent)%09%(committerdate:unix)%09%(tree)%09%(contents:subject)",+ ARCHIVE_REF_PREFIX,+ ],+ main_root,+ )+ if listing.returncode != 0:+ logger.warning(+ "Agentic IDE git: archived worktrees of {} could not be listed: {}",+ main_root, git_ops._reason(listing),+ )+ return []+ entries: list[ArchivedWorktree] = []+ for line in listing.stdout.splitlines():+ ref, parent, stamp, saved_tree, subject = ([*line.split("\t", 4), "", "", "", ""])[:5]+ if not ref.startswith(ARCHIVE_REF_PREFIX) or not subject.startswith(_SUBJECT_MARK):+ continue+ try:+ meta = json.loads(subject[len(_SUBJECT_MARK):])+ except ValueError: # a ref someone else put here: not one of ours+ continue+ head = parent.split(" ")[0]+ head_tree = git_ops._run(["rev-parse", f"{head}^{{tree}}"], main_root)+ entries.append(+ ArchivedWorktree(+ name=ref[len(ARCHIVE_REF_PREFIX):],+ branch=str(meta.get("branch") or ""),+ path=str(meta.get("path") or ""),+ head=head,+ archived_at=int(stamp) if stamp.isdigit() else 0,+ uncommitted=head_tree.returncode != 0 or head_tree.stdout.strip() != saved_tree,+ )+ )+ return entries+++def _find_archived(entries: list[ArchivedWorktree], name: str) -> ArchivedWorktree:+ wanted = str(name or "").strip()+ if not wanted:+ raise GitError("Name the archived worktree by its name or branch.", code="invalid")+ exact = [entry for entry in entries if entry.name == wanted]+ branch = git_ops.normalize_branch(wanted)+ matches = exact or [+ entry for entry in entries+ if entry.branch == branch or Path(entry.path).name.casefold() == wanted.casefold()+ ]+ if not matches:+ known = ", ".join(entry.name for entry in entries) or "none"+ raise GitError(+ f"No archived worktree is called {wanted}. Archived: {known}.", code="not_found"+ )+ # The same branch may have been archived more than once: the newest wins.+ return matches[0]+++def restore(folder: str | Path, name: str) -> Prepared:+ """Recreate an archived worktree at its old path with its saved files."""+ main_root, info = _main_root(folder)+ entry = _find_archived(archived(main_root), name)+ target = Path(entry.path)+ if target.exists():+ raise GitError(+ f"The folder {target} exists again; move it away before restoring.", code="exists"+ )+ ref = ARCHIVE_REF_PREFIX + entry.name+ branch = next((b for b in info.branches if entry.branch and b.name == entry.branch), None)+ tip = (+ git_ops._run(["rev-parse", f"refs/heads/{entry.branch}"], main_root).stdout.strip()+ if branch else ""+ )+ # The saved files belong on top of the commit they were made on. A branch+ # that moved on, is open elsewhere or is gone gets a detached checkout there.+ on_branch = bool(branch) and not branch.worktree and tip == entry.head+ if git_ops._inside(target, main_root / git_ops.WORKTREE_DIR):+ git_ops._exclude_worktree_dir(main_root)+ target.parent.mkdir(parents=True, exist_ok=True)+ add = ["worktree", "add", str(target), entry.branch] if on_branch else [+ "worktree", "add", "--detach", str(target), entry.head,+ ]+ _git(add, main_root, what="recreate the worktree")+ if entry.uncommitted:+ # Working files only: the saved changes come back uncommitted, as they+ # were, and files that had been untracked are untracked again.+ try:+ _git(["restore", f"--source={ref}", "--worktree", "--", "."], target,+ what="put the saved files back")+ except GitError:+ # Half a restore would block the next try: take the checkout away+ # again. The snapshot is untouched and can be restored once more.+ git_ops._run(["worktree", "remove", "--force", str(target)], main_root)+ raise+ cleared = git_ops._run(["update-ref", "-d", ref], main_root)+ if cleared.returncode != 0:+ # The files are back; a leftover snapshot only shows up in the list.+ logger.warning(+ "Agentic IDE git: snapshot {} could not be cleared after its restore: {}",+ entry.name, git_ops._reason(cleared),+ )+ logger.info("Agentic IDE git: restored worktree {} from {}", target, entry.name)+ if on_branch:+ message = f"Restored {entry.branch} to {target}."+ elif entry.branch:+ message = (+ f"Restored to {target} at the commit it was archived on, not on {entry.branch}: "+ "that branch moved on, is open elsewhere or no longer exists."+ )+ else:+ message = f"Restored to {target} at the commit it was archived on."+ return Prepared(+ folder=str(target), branch=entry.branch if on_branch else "", created=True,+ message=message,+ )+++__all__ = ["ARCHIVE_REF_PREFIX", "ArchivedWorktree", "archive", "archived", "restore"]diff --git a/jarvis/brain/tool_gateway.py b/jarvis/brain/tool_gateway.pyindex ac8d24faec..abe8045a54 100644--- a/jarvis/brain/tool_gateway.py+++ b/jarvis/brain/tool_gateway.py@@ -173,6 +173,12 @@ class BrainSupervisorToolGateway:name: tool for name, tool in tools.items() if not name.startswith("agentic-ide-")}tools[self._workspace_tool.name] = self._workspace_tool+ # The same addressed service also answers for a workspace's repository.+ workspaces = getattr(self._workspace_tool, "gateway", None)+ if workspaces is not None:+ from jarvis.brain.workspace_git_tool import WorkspaceGitTool++ tools[WorkspaceGitTool.name] = WorkspaceGitTool(workspaces)return toolsdef voice_catalog(self) -> tuple[SupervisorToolDescriptor, ...]:diff --git a/jarvis/brain/workspace_git_tool.py b/jarvis/brain/workspace_git_tool.pynew file mode 100644index 0000000000..b2a4ca2b34--- /dev/null+++ b/jarvis/brain/workspace_git_tool.py@@ -0,0 +1,113 @@+"""Application-owned git tool for coding workspaces, independent of any voice provider."""++from __future__ import annotations++from jarvis.core.protocols import ExecutionContext, ToolResult, WorkspaceOrchestrationGateway++# Operations that only look; everything else changes the repository.+_READS = frozenset({"state", "worktrees", "pull_requests"})+_OPS = (+ "state",+ "worktrees",+ "pull_requests",+ "worktree_create",+ "worktree_archive",+ "worktree_restore",+ "commit",+ "push",+ "pull_request",+)+++class WorkspaceGitTool:+ name = "workspace-git"+ # The user's own repository actions: carried out when asked and logged.+ risk_tier = "monitor"+ is_action_tool = True+ description = (+ "Git for a coding workspace. state: branch, ahead/behind and the changed files. "+ "worktrees: its checkouts and the archived ones. pull_requests: the open pull "+ "requests and the ones of its branches, with their checks, review and merge-queue "+ "state (here marks the checked-out branch's). worktree_create: a new worktree on "+ "branch (a new branch from base, or an existing one); only when the user asks for a "+ "worktree. worktree_archive: put a worktree away (name it by branch or folder) with "+ "its uncommitted work saved; the branch and its commits stay. Ignored files are not "+ "saved: it refuses while there are any and names them; pass drop_ignored only "+ "after the user agreed to lose them. worktree_restore: "+ "bring an archived worktree back at its old path. commit: stage everything that is "+ "not ignored and commit with message. push: the checked-out branch, or branch. "+ "pull_request: push if needed and open one (title, draft). Name the workspace as in "+ "workspace-orchestrate (workspace or workspace_id); without one the visible workspace "+ "is used. A refusal carries git's own reason and changed nothing: pass it on. Say the "+ "result in a sentence and never read out file lists unless the user asks."+ )+ schema = {+ "type": "object",+ "additionalProperties": False,+ "properties": {+ "op": {"type": "string", "enum": list(_OPS)},+ **{+ key: {"type": "string"}+ for key in ("project", "workspace", "project_id", "workspace_id")+ },+ "branch": {+ "type": "string",+ "description": (+ "worktree_create: the branch (omit for a suggested name); push and "+ "pull_request: another branch than the checked-out one."+ ),+ },+ "base": {+ "type": "string",+ "description": "worktree_create: what a new branch starts from (default HEAD).",+ },+ "worktree": {+ "type": "string",+ "description": (+ "worktree_archive: branch or folder of the worktree; worktree_restore: "+ "name or branch of the archived one."+ ),+ },+ "drop_ignored": {+ "type": "boolean",+ "description": (+ "worktree_archive: delete the worktree's ignored files with it. Only "+ "after the user agreed."+ ),+ },+ "message": {"type": "string", "description": "commit: the commit message."},+ "title": {"type": "string", "description": "pull_request: its title."},+ "draft": {"type": "boolean", "description": "pull_request: open it as a draft."},+ },+ "required": ["op"],+ }++ def __init__(self, gateway: WorkspaceOrchestrationGateway) -> None:+ self.gateway = gateway++ def risk_tier_for_args(self, args: dict) -> str:+ return "safe" if args.get("op") in _READS else "monitor"++ def read_only_for_args(self, args: dict) -> bool:+ return args.get("op") in _READS++ def describe_args(self, args: dict) -> dict:+ detail = args.get("message") or args.get("title") or args.get("worktree") or ""+ return {+ "level": "read" if args.get("op") in _READS else "modify",+ "project": str(args.get("project_id") or args.get("project") or ""),+ "workspace": str(args.get("workspace_id") or args.get("workspace") or ""),+ "agent": str(args.get("branch") or ""),+ "task": f"{args.get('op') or ''} {detail}".strip()[:240],+ }++ async def execute(self, args: dict, ctx: ExecutionContext) -> ToolResult:+ try:+ result = await self.gateway.run({**args, "action": "git"}, trace_id=str(ctx.trace_id))+ except ValueError as exc:+ # Invalid arguments go back to the model as the tool error.+ return ToolResult(success=False, output=None, error=str(exc))+ return ToolResult(+ success=result.get("success") is not False and result.get("status") == "ok",+ output=result,+ )diff --git a/jarvis/brain/workspace_tool.py b/jarvis/brain/workspace_tool.pyindex 856ce8a7e3..6f04855dc9 100644--- a/jarvis/brain/workspace_tool.py+++ b/jarvis/brain/workspace_tool.py@@ -71,7 +71,10 @@ class WorkspaceOrchestrationTool:"presses keys such as enter, escape, up/down, digits, shift+tab (permission mode); ""interrupt stops its current turn; restart starts a stopped or failed agent again ""under the same terminal_id on its own conversation (a running one is left alone, so "- "a repeat is harmless); close removes it. These are the user's own app "+ "a repeat is harmless); close removes it; fork opens a copy that continues the "+ "same conversation beside it, and with worktree=true in a new git worktree and "+ "branch (name), so two agents can work on one task or one can try another way "+ "without touching the other's files. These are the user's own app ""actions: run them when asked, without asking back. A send refused because the agent ""is not running (stopped: true) types nothing: when the user wants that agent to do ""the task, restart it and resend with the same request_id and prompt. "@@ -142,6 +145,7 @@ class WorkspaceOrchestrationTool:"interrupt","restart","close",+ "fork",],},**{@@ -217,7 +221,8 @@ class WorkspaceOrchestrationTool:"type": "string","description": ("create: optional name for a single new agent; open_workspace: the new "- "workspace's tab name."+ "workspace's tab name; fork with worktree: the branch name (suggested "+ "when omitted)."),},"agents": {@@ -236,6 +241,13 @@ class WorkspaceOrchestrationTool:"type": "string","description": "open_workspace: absolute path of the folder to open.",},+ "worktree": {+ "type": "boolean",+ "description": (+ "fork: run the copy in a new git worktree on a new branch instead of "+ "the same folder."+ ),+ },"keys": {"type": "array","maxItems": 10,diff --git a/jarvis/live/coordination.py b/jarvis/live/coordination.pyindex f971b424be..a6d31e5fd4 100644--- a/jarvis/live/coordination.py+++ b/jarvis/live/coordination.py@@ -18,8 +18,12 @@ WORK_STATUS_RULE: Final[str] = ("or its branch alone, workspace-orchestrate status with that workspace is enough. ""Say the takeaway in a sentence or two and name who ""needs the user; never read out lists, diffs or code. When the user wants to "- "hear when an agent they started themselves is done, call watch for it; a "+ "hear when an agent they started themselves is done, call workspace-orchestrate "+ "watch for it; a ""task you sent is reported back on its own. "+ "A workspace's repository is workspace-git: its changed files, its worktrees, a new "+ "worktree when the user asks for one, putting one away or bringing it back, commit, "+ "push and pull request. ")diff --git a/jarvis/live/tools.py b/jarvis/live/tools.pyindex cc302bfade..ae9c6b4efc 100644--- a/jarvis/live/tools.py+++ b/jarvis/live/tools.py@@ -57,7 +57,9 @@ _APPROVAL_LOCALES = ("de", "en", "es", "pt")_RECENT_SEGMENTS = 4_REQUEST_TEXT_CHARS = 1200# Declared before every other tool so the size budget never drops them.-_PRIORITY_TOOLS = frozenset({"workspace-orchestrate", "find-app-action", "run-app-action"})+_PRIORITY_TOOLS = frozenset(+ {"workspace-orchestrate", "workspace-git", "find-app-action", "run-app-action"}+)# Declared under its canonical name in every mode (see ``declarations``)._DIRECT_TOOLS = frozenset({"computer", "take_appshot"})# One screen, one mouse: these never run side by side, and a result thatdiff --git a/jarvis/ui/web/agentic_ide_git_routes.py b/jarvis/ui/web/agentic_ide_git_routes.pyindex 6d93ddd6db..823476c536 100644--- a/jarvis/ui/web/agentic_ide_git_routes.py+++ b/jarvis/ui/web/agentic_ide_git_routes.py@@ -489,40 +489,10 @@ def delete_branch(req: DeleteBranchRequest) -> dict:def _create_pull_request(folder: Path, req: BranchPullRequestRequest) -> str:- """Push the branch if needed and open its pull request. Returns the URL.-- Uses the GitHub connection the Git tab already reads with; without one (or- before a repository was picked for the folder) the GitHub CLI opens it.- """- cred = github_link.credential()- repo = github_link.bound_repository(folder)- wanted = git_ops.normalize_branch(req.branch)- info = git_ops.inspect(folder)- if cred is None or not repo:- if wanted and wanted != info.branch:- raise GitError("Connect GitHub to open this pull request.", code="not_connected")- return git_ops.create_pull_request(folder, title=req.title, draft=req.draft)- branch = wanted or info.branch- if not info.is_repo or not branch:- raise GitError("Check out a branch before opening a pull request.", code="detached")- if branch == info.default_branch:- raise GitError(- f"{branch} is the default branch — open the pull request from a feature branch.",- code="invalid",- )- upstream = git_ops.push(folder, branch)- head = upstream.partition("/")[2] or branch- base_ref = f"origin/{info.default_branch}"- if base_ref not in info.remote_branches:- base_ref = info.default_branch- title = req.title.strip() or git_ops.first_subject(folder, branch, base_ref)- try:- created = github_pulls.create(- repo, cred.token, head=head, base=info.default_branch, title=title, draft=req.draft- )- except github_link.GitHubError as exc:- raise GitError(str(exc), code=exc.code) from exc- return created.url+ """Push the branch if needed and open its pull request. Returns the URL."""+ return github_pulls.open_for_branch(+ folder, branch=req.branch, title=req.title, draft=req.draft+ )@router.post("/branch/pull-request", summary="Open a pull request for a workspace's branch")diff --git a/tests/contract/test_workspace_git.py b/tests/contract/test_workspace_git.pynew file mode 100644index 0000000000..4e7b72aca7--- /dev/null+++ b/tests/contract/test_workspace_git.py@@ -0,0 +1,280 @@+"""A workspace's repository is reached by naming the workspace, never a path."""++from __future__ import annotations++import shutil+import subprocess+import time+from pathlib import Path+from types import SimpleNamespace+from uuid import uuid4++import jsonschema+import pytest++from jarvis.agentic_ide import git_ops, library, resume_store+from jarvis.agentic_ide.folders import probe_project+from jarvis.agentic_ide.orchestration import WorkspaceOrchestrator+from jarvis.agentic_ide.session import Registry, Session, Terminal+from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+from jarvis.brain.workspace_git_tool import WorkspaceGitTool+from jarvis.brain.workspace_tool import WorkspaceOrchestrationTool+from jarvis.live.state import LiveLedger+from tests.fakes.fake_pty_manager import FakePtyManager++pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed")+++def _git(cwd: Path, *args: str) -> str:+ return subprocess.run(+ ["git", *args], cwd=cwd, capture_output=True, text=True, check=True, encoding="utf-8"+ ).stdout.strip()+++def _is_dir(path: str | Path) -> bool:+ return Path(path).is_dir()+++def _read(path: Path) -> str:+ return path.read_text(encoding="utf-8")+++def _write(path: Path, text: str) -> None:+ path.write_text(text, encoding="utf-8")+++def rig(tmp_path, monkeypatch):+ for key in ("GIT_AUTHOR_NAME", "GIT_COMMITTER_NAME"):+ monkeypatch.setenv(key, "Test")+ for key in ("GIT_AUTHOR_EMAIL", "GIT_COMMITTER_EMAIL"):+ monkeypatch.setenv(key, "[email protected]")+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(tmp_path / "gitconfig"))+ monkeypatch.setattr(library, "_root", lambda: tmp_path / "library")+ monkeypatch.setattr(resume_store, "_store_path", lambda: tmp_path / "snapshot.json")+ registry = Registry(pty_manager=FakePtyManager())+ for name in ("Plain", "Repo"):+ path = tmp_path / name+ path.mkdir()+ if name == "Repo":+ git_ops.init_repository(path)+ (path / "app.py").write_text("print('hi')\n", encoding="utf-8")+ _git(path, "add", "--all")+ _git(path, "commit", "-m", "feat: app")+ project = library.ensure_project(path)+ workspace = Session(+ id=uuid4().hex,+ folder=str(path),+ name=name,+ profile=probe_project(path),+ terminals=[Terminal("t1", "Alex", "codex", "Codex", 0, status="live",+ activity="idle", activity_at=time.time())],+ created_at=1,+ project_id=project.id,+ )+ registry._sessions[workspace.id] = workspace+ registry._active = workspace.id+ ledger = LiveLedger(tmp_path / "receipts.db")+ orchestrator = WorkspaceOrchestrator(registry, SimpleNamespace(), ledger)+ yield orchestrator, registry, tmp_path / "Repo"+ ledger.close()+++async def git(rig, op, **args):+ return await rig[0].run({"action": "git", "op": op, **args})+++async def test_state_describes_the_visible_workspace_repository(rig):+ repo = rig[2]+ (repo / "app.py").write_text("print('changed')\n", encoding="utf-8")+ (repo / "new.txt").write_text("x\n", encoding="utf-8")+ state = await git(rig, "state")+ assert state["status"] == "ok" and state["workspace"] == "Repo"+ assert state["branch"] == "main" and state["unstaged"] == 1 and state["untracked"] == 1+ assert {change["path"] for change in state["changes"]} == {"app.py", "new.txt"}+ assert state["more_changes"] == 0 and state["linked_worktree"] is False+++async def test_a_folder_without_a_repository_is_refused_with_the_reason(rig):+ refused = await git(rig, "state", workspace="Plain")+ assert refused["status"] == "not_accepted" and refused["code"] == "not_repo"+ assert refused["workspace"] == "Plain" and "not a git repository" in refused["reason"]+ unknown = await git(rig, "state", workspace="No such workspace")+ assert unknown["status"] != "ok" and "branch" not in unknown+++async def test_a_worktree_is_created_put_away_with_its_work_and_brought_back(rig):+ made = await git(rig, "worktree_create", branch="feature")+ assert made["status"] == "ok" and made["created"] and made["branch"] == "feature"+ tree = Path(made["folder"])+ assert _is_dir(tree) and "open_workspace" in made["next_step"]+ _write(tree / "notes.md", "unsaved\n")++ listed = await git(rig, "worktrees")+ assert [w["branch"] for w in listed["worktrees"]] == ["main", "feature"]+ assert listed["archived"] == []++ archived = await git(rig, "worktree_archive", worktree="feature")+ assert archived["status"] == "ok" and archived["archived"]["uncommitted"] is True+ assert not _is_dir(tree) and "saved" in archived["message"]+ listed = await git(rig, "worktrees")+ assert [w["branch"] for w in listed["worktrees"]] == ["main"]+ assert [entry["branch"] for entry in listed["archived"]] == ["feature"]++ restored = await git(rig, "worktree_restore", worktree="feature")+ assert restored["status"] == "ok" and Path(restored["folder"]) == tree+ assert _read(tree / "notes.md") == "unsaved\n"+++async def test_a_worktree_somebody_has_open_is_not_archived(rig):+ orchestrator, registry, _repo = rig+ made = await git(rig, "worktree_create", branch="busy")+ registry.session.terminals[0].folder = made["folder"] # an agent runs inside it+ refused = await git(rig, "worktree_archive", worktree="busy")+ assert refused["status"] == "not_accepted" and refused["code"] == "in_use"+ assert _is_dir(made["folder"])+++async def test_commit_reports_the_new_commit_and_refuses_an_empty_one(rig):+ repo = rig[2]+ (repo / "new.txt").write_text("x\n", encoding="utf-8")+ done = await git(rig, "commit", message="feat: add new file")+ assert done["status"] == "ok" and done["commit"] == _git(repo, "rev-parse", "--short", "HEAD")+ again = await git(rig, "commit", message="feat: nothing")+ assert again["status"] == "not_accepted" and again["code"] == "clean"+ unnamed = await git(rig, "commit")+ assert unnamed["status"] == "not_accepted" and unnamed["code"] == "invalid"+++async def test_push_and_pull_request_pass_on_gits_own_refusal(rig, monkeypatch):+ pushed = await git(rig, "push")+ assert pushed["status"] == "not_accepted" and pushed["code"] == "no_remote"+ monkeypatch.setattr(git_ops, "gh_available", lambda: False)+ opened = await git(rig, "pull_request", title="Add the thing")+ assert opened["status"] == "not_accepted" and "url" not in opened+++async def test_an_unknown_operation_is_an_argument_error(rig):+ with pytest.raises(ValueError, match="op must be one of"):+ await git(rig, "rebase")+++def test_reads_are_safe_and_changes_are_logged_actions(rig):+ tool = WorkspaceGitTool(rig[0])+ for op in ("state", "worktrees", "pull_requests"):+ jsonschema.validate({"op": op}, tool.schema)+ assert tool.risk_tier_for_args({"op": op}) == "safe"+ assert tool.describe_args({"op": op})["level"] == "read"+ for op in ("worktree_create", "worktree_archive", "worktree_restore", "commit", "push",+ "pull_request"):+ jsonschema.validate({"op": op}, tool.schema)+ assert tool.risk_tier_for_args({"op": op}) == "monitor"+ with pytest.raises(jsonschema.ValidationError):+ jsonschema.validate({"op": "state", "folder": "C:/elsewhere"}, tool.schema)+++async def test_the_tool_answers_through_the_workspace_gateway(rig):+ tool = WorkspaceGitTool(rig[0])+ ctx = SimpleNamespace(trace_id=uuid4(), user_utterance="which branch", config={})+ ok = await tool.execute({"op": "state"}, ctx)+ assert ok.success and ok.output["branch"] == "main"+ refused = await tool.execute({"op": "state", "workspace": "Plain"}, ctx)+ assert refused.success is False and refused.output["code"] == "not_repo"+ bad = await tool.execute({"op": "rebase"}, ctx)+ assert bad.success is False and "op must be one of" in bad.error+++def test_voice_gets_the_git_tool_next_to_the_workspace_tool(rig):+ manager = SimpleNamespace(_tools={}, _config=SimpleNamespace(computer_use=None))+ gateway = BrainSupervisorToolGateway(+ manager, workspace_tool=WorkspaceOrchestrationTool(rig[0])+ )+ names = {descriptor.name for descriptor in gateway.voice_catalog()}+ assert {"workspace-orchestrate", "workspace-git"} <= names+ assert "workspace-git" not in {d.name for d in gateway.catalog()} # voice only+++async def test_pull_requests_lists_the_branch_ones_first_with_their_checks(rig, monkeypatch):+ from jarvis.agentic_ide import git_overview+ from jarvis.agentic_ide.git_overview import (+ BranchRow,+ CiStatus,+ GitHubState,+ PullRequest,+ RepoOverview,+ )++ mine = PullRequest(+ number=12, title="Add the thing", url="https://example.invalid/pr/12", state="open",+ base="main", head="feature", ci=CiStatus(state="failing", failed=2, running=1),+ review="changes_requested", queue_position=None,+ )+ other = PullRequest(+ number=40, title="Someone else", url="https://example.invalid/pr/40", state="open",+ base="main", head="other", ci=CiStatus(state="passing"), queue_position=3,+ conflicting=True,+ )+ seen = RepoOverview(+ available=True, branch="feature", default_branch="main",+ branches=[BranchRow(name="feature", current=True, pull_requests=[mine])],+ pull_requests=[other, mine],+ github=GitHubState(available=True, repo="owner/repo"),+ )+ monkeypatch.setattr(git_overview, "overview", lambda folder: seen)+ listed = await git(rig, "pull_requests")+ assert listed["status"] == "ok" and listed["github"] == {+ "connected": True, "repository": "owner/repo",+ }+ first, second = listed["pull_requests"]+ assert first == {+ "number": 12, "title": "Add the thing", "state": "open", "branch": "feature",+ "into": "main", "url": "https://example.invalid/pr/12", "checks": "failing",+ "failed_checks": 2, "running_checks": 1, "review": "changes_requested", "here": True,+ }+ assert second["number"] == 40 and second["merge_queue_position"] == 3+ assert second["conflicting"] is True and "here" not in second+ assert listed["more_pull_requests"] == 0+++async def test_pull_requests_says_when_github_is_not_connected(rig, monkeypatch):+ from jarvis.agentic_ide import git_overview+ from jarvis.agentic_ide.git_overview import GitHubState, RepoOverview++ seen = RepoOverview(+ available=True, branch="main",+ github=GitHubState(available=False, reason="Sign in to GitHub to see pull requests."),+ )+ monkeypatch.setattr(git_overview, "overview", lambda folder: seen)+ listed = await git(rig, "pull_requests")+ assert listed["status"] == "ok" and listed["pull_requests"] == []+ assert listed["github"] == {+ "connected": False, "reason": "Sign in to GitHub to see pull requests.",+ }+ gone = RepoOverview(available=False, reason="The workspace folder is missing.")+ monkeypatch.setattr(git_overview, "overview", lambda folder: gone)+ refused = await git(rig, "pull_requests")+ assert refused["status"] == "not_accepted" and "missing" in refused["reason"]+++async def test_archiving_names_ignored_files_and_needs_the_users_word_to_drop_them(rig):+ made = await git(rig, "worktree_create", branch="scratch")+ tree = Path(made["folder"])+ _write(rig[2] / ".git" / "info" / "exclude", "secret.env" + chr(10))+ _write(tree / "secret.env", "TOKEN=x")+ refused = await git(rig, "worktree_archive", worktree="scratch")+ assert refused["status"] == "not_accepted" and refused["code"] == "ignored_files"+ assert "secret.env" in refused["reason"] and _is_dir(tree)+ done = await git(rig, "worktree_archive", worktree="scratch", drop_ignored=True)+ assert done["status"] == "ok" and not _is_dir(tree)+++async def test_opening_a_pull_request_refreshes_what_github_is_known_to_hold(rig, monkeypatch):+ from jarvis.agentic_ide import git_overview, github_pulls++ cleared = []+ monkeypatch.setattr(github_pulls, "open_for_branch", lambda folder, **kw: "https://x/pr/1")+ monkeypatch.setattr(git_overview, "clear_github", cleared.append)+ opened = await git(rig, "pull_request", title="Add the thing")+ assert opened["status"] == "ok" and opened["url"] == "https://x/pr/1"+ assert [Path(folder) for folder in cleared] == [rig[2]]diff --git a/tests/contract/test_workspace_orchestration.py b/tests/contract/test_workspace_orchestration.pyindex 0d1f9a2e97..8fd0dcf0c1 100644--- a/tests/contract/test_workspace_orchestration.py+++ b/tests/contract/test_workspace_orchestration.py@@ -1074,3 +1074,82 @@ def test_status_is_a_read_and_watch_is_a_logged_action(rig):assert tool.risk_tier_for_args({"action": "status"}) == "safe"assert tool.describe_args({"action": "status"})["level"] == "read"assert tool.risk_tier_for_args({"action": "watch"}) == "monitor"+++# --- A copy of an agent's conversation, optionally in its own worktree ----------------+++async def test_fork_opens_a_copy_of_the_named_agent_and_addresses_it(rig, monkeypatch):+ orchestrator, registry, sessions = rig+ owner = registry.session+ asked = []++ async def fork(wanted, *, workspace_id=None, worktree=False, name=None, direction="right"):+ asked.append((wanted, workspace_id, worktree, name))+ copy = Terminal("t9", "Alex 2", "codex", "Codex", 1, status="live")+ if worktree:+ copy.folder, copy.branch = "/repo/.worktrees/try-b", "try-b"+ owner.terminals.append(copy)+ return copy++ monkeypatch.setattr(registry, "fork_terminal", fork)+ plain = await orchestrator.run(+ {"action": "fork", "workspace": owner.name, "agent": "Alex"}+ )+ assert plain["status"] == "forked" and plain["agent"] == "Alex"+ assert plain["copy"]["name"] == "Alex 2" and plain["copy"]["terminal_id"].startswith("pane:")+ assert "folder" not in plain["copy"]+ apart = await orchestrator.run(+ {"action": "fork", "workspace": owner.name, "agent": "Alex", "worktree": True,+ "name": " try-b "}+ )+ assert apart["copy"]["branch"] == "try-b" and "own worktree" in apart["reason"]+ assert asked == [("Alex", owner.id, False, None), ("Alex", owner.id, True, "try-b")]+ assert not sessions.calls # nothing is typed into either pane+++async def test_a_fork_the_app_refuses_is_passed_on_with_its_reason(rig, monkeypatch):+ from jarvis.agentic_ide.session import SessionError++ orchestrator, registry, _sessions = rig++ async def refuse(wanted, **_kwargs):+ raise SessionError("Alex is a plain terminal — it has no chat to fork.")++ monkeypatch.setattr(registry, "fork_terminal", refuse)+ result = await orchestrator.run(+ {"action": "fork", "workspace": registry.session.name, "agent": "Alex"}+ )+ assert result["status"] == "not_accepted" and "no chat to fork" in result["reason"]+++def test_fork_is_a_logged_action_with_a_valid_schema(rig):+ import jsonschema++ tool = WorkspaceOrchestrationTool(rig[0])+ jsonschema.validate({"action": "fork", "agent": "Alex", "worktree": True}, tool.schema)+ assert tool.risk_tier_for_args({"action": "fork"}) == "monitor"+++async def test_a_job_that_ends_while_the_watch_is_set_up_is_not_watched_forever(+ rig, reportable, monkeypatch+):+ from jarvis.agentic_ide import followthrough++ orchestrator, registry, _sessions = rig+ term = registry.session.terminals[0]+ term.activity = "working"+ real = followthrough.watch++ async def finishes_meanwhile(pane, origin):+ armed = await real(pane, origin)+ pane.activity = "idle" # its end is now part of the watch's starting point+ return armed++ monkeypatch.setattr(followthrough, "watch", finishes_meanwhile)+ with _Origin("voice"):+ result = await orchestrator.run(+ {"action": "watch", "workspace": registry.session.name, "agent": term.name}+ )+ assert result["status"] == "not_running" and "just finished" in result["reason"]+ assert term.delegation_result is Nonediff --git a/tests/unit/agentic_ide/test_worktree_archive.py b/tests/unit/agentic_ide/test_worktree_archive.pynew file mode 100644index 0000000000..75cf8a985d--- /dev/null+++ b/tests/unit/agentic_ide/test_worktree_archive.py@@ -0,0 +1,237 @@+"""Archiving a worktree keeps what was in it; restoring brings it back as it was."""++from __future__ import annotations++import shutil+import subprocess+from pathlib import Path++import pytest++from jarvis.agentic_ide import git_ops, worktree_archive+from jarvis.agentic_ide.git_ops import GitError++pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed")++[email protected](autouse=True)+def _identity(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ monkeypatch.setenv("GIT_AUTHOR_NAME", "Test")+ monkeypatch.setenv("GIT_AUTHOR_EMAIL", "[email protected]")+ monkeypatch.setenv("GIT_COMMITTER_NAME", "Test")+ monkeypatch.setenv("GIT_COMMITTER_EMAIL", "[email protected]")+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(tmp_path / "gitconfig"))+++def _git(cwd: Path, *args: str) -> str:+ return subprocess.run(+ ["git", *args], cwd=cwd, capture_output=True, text=True, check=True, encoding="utf-8"+ ).stdout.strip()+++def _status(cwd: Path) -> set[str]:+ """``git status --porcelain`` lines with their leading status columns intact."""+ out = subprocess.run(+ ["git", "status", "--porcelain"], cwd=cwd, capture_output=True, text=True, check=True,+ encoding="utf-8",+ ).stdout+ return set(out.splitlines())+++def repo(tmp_path: Path) -> Path:+ root = tmp_path / "p"+ root.mkdir()+ git_ops.init_repository(root)+ (root / "app.py").write_text("print('hi')\n", encoding="utf-8")+ (root / "old.txt").write_text("to be deleted\n", encoding="utf-8")+ (root / ".gitignore").write_text("build/\n", encoding="utf-8")+ _git(root, "add", "--all")+ _git(root, "commit", "-m", "feat: app")+ return root+++def tree(repo: Path) -> Path:+ """A linked worktree on ``feature`` with one commit of its own and unsaved work."""+ made = git_ops.prepare(repo, "new_worktree", branch="feature")+ path = Path(made.folder)+ (path / "done.txt").write_text("committed on the branch\n", encoding="utf-8")+ _git(path, "add", "done.txt")+ _git(path, "commit", "-m", "feat: done")+ (path / "app.py").write_text("print('changed')\n", encoding="utf-8")+ (path / "notes.md").write_text("never added\n", encoding="utf-8")+ (path / "old.txt").unlink()+ (path / "build").mkdir()+ (path / "build" / "out.bin").write_text("ignored\n", encoding="utf-8")+ return path+++def test_archive_saves_the_work_and_removes_only_the_checkout(repo: Path, tree: Path) -> None:+ tip = _git(repo, "rev-parse", "feature")+ entry = worktree_archive.archive(repo, "feature", open_folders=[str(repo)], drop_ignored=True)+ assert not tree.exists()+ assert entry.branch == "feature" and entry.uncommitted and entry.head == tip+ assert _git(repo, "rev-parse", "feature") == tip # the branch and its commit stay+ assert "feature" in _git(repo, "branch", "--list", "feature")+ listed = worktree_archive.archived(repo)+ assert [item.to_dict() for item in listed] == [entry.to_dict()]+ # A snapshot is not a branch and does not show up as one.+ assert entry.name not in _git(repo, "branch", "--all")+++def test_restore_brings_back_the_files_as_uncommitted_changes(repo: Path, tree: Path) -> None:+ worktree_archive.archive(repo, str(tree), open_folders=[], drop_ignored=True)+ restored = worktree_archive.restore(repo, "feature")+ assert Path(restored.folder) == tree and restored.branch == "feature" and restored.created+ assert (tree / "app.py").read_text(encoding="utf-8") == "print('changed')\n"+ assert (tree / "notes.md").read_text(encoding="utf-8") == "never added\n"+ assert (tree / "done.txt").exists() and not (tree / "old.txt").exists()+ # Nothing was committed or staged: unstaged edits and an untracked file.+ assert _status(tree) == {" M app.py", " D old.txt", "?? notes.md"}+ assert worktree_archive.archived(repo) == []+ assert not (tree / "build").exists() # ignored files are not part of a snapshot+++def test_a_clean_worktree_round_trips_without_changes(repo: Path) -> None:+ path = Path(git_ops.prepare(repo, "new_worktree", branch="tidy").folder)+ entry = worktree_archive.archive(repo, "tidy", open_folders=[])+ assert entry.uncommitted is False and not path.exists()+ worktree_archive.restore(repo, entry.name)+ assert path.is_dir() and _git(path, "status", "--porcelain") == ""+++def test_archive_works_on_a_machine_without_a_git_identity(+ repo: Path, tree: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ for key in ("GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL"):+ monkeypatch.delenv(key)+ entry = worktree_archive.archive(repo, "feature", open_folders=[], drop_ignored=True)+ assert entry.uncommitted and not tree.exists()+++def test_a_branch_that_moved_on_is_restored_detached_at_the_archived_commit(+ repo: Path, tree: Path+) -> None:+ entry = worktree_archive.archive(repo, "feature", open_folders=[], drop_ignored=True)+ _git(repo, "switch", "feature")+ (repo / "later.txt").write_text("after the archive\n", encoding="utf-8")+ _git(repo, "add", "later.txt")+ _git(repo, "commit", "-m", "feat: later")+ _git(repo, "switch", "main")+ restored = worktree_archive.restore(repo, entry.name)+ assert restored.branch == "" and "moved on" in restored.message+ assert _git(tree, "rev-parse", "HEAD") == entry.head+ assert (tree / "notes.md").exists() and not (tree / "later.txt").exists()+++def test_what_must_not_be_archived_is_refused_and_nothing_is_lost(repo: Path, tree: Path) -> None:+ with pytest.raises(GitError) as in_use:+ worktree_archive.archive(repo, "feature", open_folders=[str(tree / "sub")])+ assert in_use.value.code == "in_use" and (tree / "notes.md").exists()+ with pytest.raises(GitError) as main:+ worktree_archive.archive(repo, "main", open_folders=[])+ assert main.value.code == "invalid"+ with pytest.raises(GitError) as unknown:+ worktree_archive.archive(repo, "nope", open_folders=[])+ assert unknown.value.code == "not_found" and "feature" in str(unknown.value)+ assert worktree_archive.archived(repo) == []+++def test_restore_refuses_an_occupied_path_and_keeps_the_snapshot(repo: Path, tree: Path) -> None:+ entry = worktree_archive.archive(repo, "feature", open_folders=[], drop_ignored=True)+ tree.mkdir(parents=True)+ with pytest.raises(GitError) as taken:+ worktree_archive.restore(repo, entry.name)+ assert taken.value.code == "exists"+ assert [item.name for item in worktree_archive.archived(repo)] == [entry.name]+ with pytest.raises(GitError) as unknown:+ worktree_archive.restore(repo, "nope")+ assert unknown.value.code == "not_found"+++def test_archiving_the_same_branch_twice_restores_the_newest(repo: Path, tree: Path) -> None:+ first = worktree_archive.archive(repo, "feature", open_folders=[], drop_ignored=True)+ worktree_archive.restore(repo, first.name)+ (tree / "notes.md").write_text("second round\n", encoding="utf-8")+ second = worktree_archive.archive(repo, "feature", open_folders=[], drop_ignored=True)+ assert [item.name for item in worktree_archive.archived(repo)] == [second.name]+ worktree_archive.restore(repo, "feature")+ assert (tree / "notes.md").read_text(encoding="utf-8") == "second round\n"+++# --- what a snapshot cannot bring back is never deleted silently ---------------------+++def test_ignored_files_stop_the_archive_until_the_user_agrees(repo: Path, tree: Path) -> None:+ with pytest.raises(GitError) as refused:+ worktree_archive.archive(repo, "feature", open_folders=[])+ assert refused.value.code == "ignored_files" and "build/" in str(refused.value)+ assert (tree / "build" / "out.bin").exists() and (tree / "notes.md").exists()+ assert worktree_archive.archived(repo) == []+ entry = worktree_archive.archive(repo, "feature", open_folders=[], drop_ignored=True)+ assert entry.uncommitted and not tree.exists()+++def test_a_repository_nested_in_the_worktree_is_never_archived(repo: Path, tree: Path) -> None:+ nested = tree / "vendor" / "lib"+ nested.mkdir(parents=True)+ _git(nested, "init", "-q")+ (nested / "work.txt").write_text("only here", encoding="utf-8")+ with pytest.raises(GitError) as refused:+ worktree_archive.archive(repo, "feature", open_folders=[], drop_ignored=True)+ assert refused.value.code == "nested_repository" and "vendor" in str(refused.value)+ assert (nested / "work.txt").exists()+ assert worktree_archive.archived(repo) == []+++def test_two_archives_in_one_second_never_share_a_snapshot(repo: Path, monkeypatch) -> None:+ first = Path(git_ops.prepare(repo, "new_worktree", branch="fix/a").folder)+ second = Path(git_ops.prepare(repo, "new_worktree", branch="fix.a").folder)+ (first / "one.txt").write_text("one", encoding="utf-8")+ (second / "two.txt").write_text("two", encoding="utf-8")+ monkeypatch.setattr(worktree_archive.time, "time", lambda: 1_800_000_000)+ a = worktree_archive.archive(repo, "fix/a", open_folders=[])+ b = worktree_archive.archive(repo, "fix.a", open_folders=[])+ assert a.name != b.name+ assert {item.branch for item in worktree_archive.archived(repo)} == {"fix/a", "fix.a"}+ worktree_archive.restore(repo, a.name)+ assert (first / "one.txt").read_text(encoding="utf-8") == "one"+++def test_a_restore_that_fails_halfway_can_be_tried_again(+ repo: Path, tree: Path, monkeypatch+) -> None:+ entry = worktree_archive.archive(repo, "feature", open_folders=[], drop_ignored=True)+ real = worktree_archive._git+ state = {"fail": True}++ def flaky(args, cwd, **kwargs):+ if args[0] == "restore" and state["fail"]:+ raise GitError("Git could not put the saved files back: disk full")+ return real(args, cwd, **kwargs)++ monkeypatch.setattr(worktree_archive, "_git", flaky)+ with pytest.raises(GitError):+ worktree_archive.restore(repo, entry.name)+ assert not tree.exists() # no half-restored checkout is left in the way+ assert [item.name for item in worktree_archive.archived(repo)] == [entry.name]+ state["fail"] = False+ worktree_archive.restore(repo, entry.name)+ assert (tree / "notes.md").read_text(encoding="utf-8") == "never added\n"+++def test_reading_the_brief_state_takes_no_optional_locks(repo: Path, monkeypatch) -> None:+ seen = []+ real = git_ops._run++ def spy(args, cwd, **kwargs):+ seen.append(list(args))+ return real(args, cwd, **kwargs)++ monkeypatch.setattr(git_ops, "_run", spy)+ state = git_ops.brief(repo)+ assert state is not None and state["branch"] == "main"+ status = next(args for args in seen if "status" in args)+ assert status[0] == "--no-optional-locks"