Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(session): switch git worktrees mid-session via workspace tool

Cursor Agent173d0c6ddcaf
diff --git a/assets/skills/workspace.md b/assets/skills/workspace.md
new file mode 100644
index 00000000..ea0f666b
--- /dev/null
+++ b/assets/skills/workspace.md
@@ -0,0 +1,45 @@
+---
+name: workspace
+description: Switch this graff session among git worktrees without restarting. Use when several checkouts exist and file tools must follow a different tree.
+---
+
+# workspace
+
+One session, many trees. The actuator is the `workspace` tool (or `/workspace`
+for you). This skill is the playbook. Loading it does not move the cwd.
+
+## Why a tool
+
+`read_file`, `edit_file`, and `write_file` resolve against the process cwd (or
+a subagent's isolated `agent_cwd`). `bash` inherits that cwd too. A `cd` inside
+one bash call dies with the shell — the next file tool is still in the old
+tree. `graff -w` only creates a scratch worktree at **startup**. Mid-session
+switch is `workspace action=use`.
+
+## Pull, do not dump
+
+1. `workspace action=list` (or `/workspace`) — one line per tree. Star is here.
+2. `workspace action=use path=<folder or unique fragment>` — chdir this
+ session. Example: `path=cursor-peer-pull-554f` matches a Claude worktree
+ named that, or `path=cursor/peer-pull-554f` matches the branch.
+3. If the match is ambiguous, name more of the path. Do not guess.
+
+Do not paste every worktree path into the next user turn. The list result is
+enough. Do not `git worktree list` via bash when this tool exists.
+
+## What moves, what does not
+
+Moves: process cwd, the prompt's cwd badge, presence identity (peer rooms
+follow the new folder), tool-output spill.
+
+Does not move: conversation history, the standing goal, loaded tool schemas,
+subagents already running (they keep their assigned tree). Project files
+(`CLAUDE.md`, `.harness/`) stay the ones composed at session start until
+`/clear` or a restart. After a switch, prefer paths relative to the new cwd.
+
+## Do not
+
+- Spawn a new graff per worktree when a switch will do.
+- Process-wide chdir from a subagent (the tool refuses).
+- Treat this as `graff worktree merge` — that lands a `-w` scratch tab.
+- Invent a font or OSC sequence; the tree is a directory, not a theme.
diff --git a/build.zig b/build.zig
index aa34267a..57c33db2 100644
--- a/build.zig
+++ b/build.zig
@@ -130,6 +130,7 @@ pub fn build(b: *std.Build) void {
.{ .import = "skill_doc_creator", .path = "assets/skills/skill-creator.md" },
.{ .import = "skill_doc_mcp_config", .path = "assets/skills/mcp-config.md" },
.{ .import = "skill_doc_jspace", .path = "assets/skills/jspace.md" },
+ .{ .import = "skill_doc_workspace", .path = "assets/skills/workspace.md" },
}) |asset| {
exe.root_module.addAnonymousImport(asset.import, .{ .root_source_file = b.path(asset.path) });
unit_tests.root_module.addAnonymousImport(asset.import, .{ .root_source_file = b.path(asset.path) });
diff --git a/docs/adr/0006-workspace-switch-is-a-tool.md b/docs/adr/0006-workspace-switch-is-a-tool.md
new file mode 100644
index 00000000..ead94448
--- /dev/null
+++ b/docs/adr/0006-workspace-switch-is-a-tool.md
@@ -0,0 +1,31 @@
+# 0006. Mid-session workspace switch is a tool, not a skill-only protocol
+
+Status: accepted 2026-08-18
+
+## Context
+
+A session can sit next to several git worktrees (Claude `.claude/worktrees/`,
+`graff -w` tabs, `git worktree add`). Users asked to change which tree file
+tools see without restarting, and whether a loadable skill (like `jspace`)
+would be enough.
+
+`read_file` / `edit_file` / `bash` bind to process cwd, or to a subagent's
+isolated `agent_cwd`. A bash `cd` does not move the next native file call.
+`graff -w` only enters a tree at startup. A skill body cannot chdir.
+
+## Decision
+
+- A folded native tool `workspace` (`list` / `use`) plus `/workspace` actually
+ chdir the **root** session, update `g_cwd_display`, rebind presence, and
+ retarget tool-output spill.
+- Subagents are refused: their cwd is per-agent on purpose so siblings do not
+ share a process-wide chdir.
+- A bundled `workspace` skill is the on-demand playbook (when to list/use).
+ Loading the skill does not move the cwd.
+- Do not dump every worktree path into history; list is a tool result.
+
+## Consequences
+
+- Project instructions composed at startup stay until `/clear` or restart.
+- `-w` auto-commit unhooks on switch (`g_worktree_branch` clears).
+- Revisit if file tools grow an explicit root path that makes chdir unnecessary.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index b73dcadd..4942224f 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -16,6 +16,7 @@ record only when you need the evidence or the edge cases.
| [0003](0003-codegraff-wire-follows-model-capability.md) | Codegraff uses Responses + WS for GPT-5.6 and grok-4.6 aliases; Claude, Gemini, and other aliases stay on Chat Completions. |
| [0004](0004-peer-speech-is-a-working-set.md) | Peer speech is pull: a one-line `[peer]` wake in history, bodies in the inbox ring; compact drops spent injects and never treats them as the human. |
| [0005](0005-standing-goal-lives-in-the-prefix.md) | Standing goal is one prefix line; the user-message essay injects on change only, never every N turns. |
+| [0006](0006-workspace-switch-is-a-tool.md) | Mid-session worktree switch is a real `workspace` tool; a skill cannot move file-tool cwd. |
## When to write one
diff --git a/lean-proofs/Graff/ToolCatalog.lean b/lean-proofs/Graff/ToolCatalog.lean
index 4554c788..10046fff 100644
--- a/lean-proofs/Graff/ToolCatalog.lean
+++ b/lean-proofs/Graff/ToolCatalog.lean
@@ -41,7 +41,8 @@ def metaTools : List String :=
"attempt_completion", "load_tool_schemas", "clock_sleep"]
def rootExtras : List String :=
- ["subagent", "workflow", "agent_output", "learn_candidate", "peer_message"]
+ ["subagent", "workflow", "agent_output", "learn_candidate", "peer_message",
+ "workspace"]
def filterKeep (keep : String → Bool) : List String → List String
| [] => []
diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.py
index df260ef0..967e3689 100644
--- a/sdk/py/harness_sdk.py
+++ b/sdk/py/harness_sdk.py
@@ -14,7 +14,7 @@ import urllib.request
from typing import Iterator, Optional
MODELS = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "openai/gpt-oss-120b"]
-TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "imagegen"]
+TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"]
PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "minimax", "xiaomi", "kilo", "groq", "mistral", "kimi", "moonshot", "xai", "zai", "fugu", "fireworks", "mlx", "lmstudio", "codex"]
diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.ts
index 1dca47e6..c1d9e0b3 100644
--- a/sdk/ts/harness.ts
+++ b/sdk/ts/harness.ts
@@ -12,7 +12,7 @@ import type { Readable, Writable } from "node:stream";
export const HARNESS_VERSION = "0.12";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-4.6" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "openai/gpt-oss-120b" | (string & {});
-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "imagegen";
+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";
export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kilo" | "groq" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";
/** Events streamed by `harness --json` (one JSON object per stdout line), each
@@ -661,4 +661,4 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {
}
export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "openai/gpt-oss-120b"];
-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "imagegen"];
+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];
diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.ts
index ee37050b..2e1a29f0 100644
--- a/sdk/ts/remote.ts
+++ b/sdk/ts/remote.ts
@@ -10,7 +10,7 @@
export const HARNESS_VERSION = "0.12";
export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-4.6" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "openai/gpt-oss-120b" | (string & {});
-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "imagegen";
+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";
export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kilo" | "groq" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";
/** Events streamed by the bridge (same `--json` contract as the stdio SDK).
@@ -508,4 +508,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat
}
export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "openai/gpt-oss-120b"];
-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "imagegen"];
+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];
diff --git a/spec/kernels/tool_catalog.json b/spec/kernels/tool_catalog.json
index b2ea09c9..68cd8d87 100644
--- a/spec/kernels/tool_catalog.json
+++ b/spec/kernels/tool_catalog.json
@@ -28,7 +28,8 @@
"workflow",
"agent_output",
"learn_candidate",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"optional": [
"imagegen"
@@ -85,7 +86,8 @@
"subagent",
"workflow",
"agent_output",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"imagegen"
@@ -147,7 +149,8 @@
"workflow",
"agent_output",
"learn_candidate",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"imagegen"
@@ -209,7 +212,8 @@
"subagent",
"workflow",
"agent_output",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"imagegen"
@@ -272,7 +276,8 @@
"workflow",
"agent_output",
"learn_candidate",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"imagegen"
@@ -334,6 +339,7 @@
"workflow",
"agent_output",
"peer_message",
+ "workspace",
"imagegen"
],
"blocked": []
@@ -394,6 +400,7 @@
"agent_output",
"learn_candidate",
"peer_message",
+ "workspace",
"imagegen"
],
"blocked": []
@@ -454,6 +461,7 @@
"workflow",
"agent_output",
"peer_message",
+ "workspace",
"imagegen"
],
"blocked": []
@@ -515,6 +523,7 @@
"agent_output",
"learn_candidate",
"peer_message",
+ "workspace",
"imagegen"
],
"blocked": []
@@ -946,7 +955,8 @@
"subagent",
"workflow",
"agent_output",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"bash",
@@ -1008,7 +1018,8 @@
"workflow",
"agent_output",
"learn_candidate",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"bash",
@@ -1070,7 +1081,8 @@
"subagent",
"workflow",
"agent_output",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"bash",
@@ -1133,7 +1145,8 @@
"workflow",
"agent_output",
"learn_candidate",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"bash",
@@ -1194,7 +1207,8 @@
"subagent",
"workflow",
"agent_output",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"bash",
@@ -1256,7 +1270,8 @@
"workflow",
"agent_output",
"learn_candidate",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"bash",
@@ -1318,7 +1333,8 @@
"subagent",
"workflow",
"agent_output",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"bash",
@@ -1381,7 +1397,8 @@
"workflow",
"agent_output",
"learn_candidate",
- "peer_message"
+ "peer_message",
+ "workspace"
],
"blocked": [
"bash",
diff --git a/spec/kernels/tool_catalog.md b/spec/kernels/tool_catalog.md
index 0cfdb770..a45edad8 100644
--- a/spec/kernels/tool_catalog.md
+++ b/spec/kernels/tool_catalog.md
@@ -24,7 +24,7 @@ run the keep-list.
|---|---|
| base | `bash` `bash_output` `bash_kill` `read_file` `edit_file` `write_file` `webfetch` `skill` `codedb` |
| meta (root) | `todo_write` `todo_read` `eval` `note_constraint` `ask_user` `attempt_completion` `load_tool_schemas` `clock_sleep` |
-| root extras | `subagent` `workflow` `agent_output` `learn_candidate` `peer_message` |
+| root extras | `subagent` `workflow` `agent_output` `learn_candidate` `peer_message` `workspace` |
| optional | `imagegen` |
| local (`#330`) | `bash` `bash_output` `bash_kill` `read_file` `edit_file` `write_file` `codedb` `imagegen` |
| lean keep | `bash` `read_file` `edit_file` `write_file` `codedb` `subagent` `attempt_completion` `load_tool_schemas` |
diff --git a/spec/ref/tool_catalog.py b/spec/ref/tool_catalog.py
index 130f46c8..44ff887e 100644
--- a/spec/ref/tool_catalog.py
+++ b/spec/ref/tool_catalog.py
@@ -58,6 +58,7 @@ ROOT_EXTRAS = (
"agent_output",
"learn_candidate",
"peer_message",
+ "workspace",
)
ROOT_UNIVERSE = BASE_TOOLS + META_TOOLS + ROOT_EXTRAS
diff --git a/src/agent_tool_render.zig b/src/agent_tool_render.zig
index 17a7ac3f..fe0fafba 100644
--- a/src/agent_tool_render.zig
+++ b/src/agent_tool_render.zig
@@ -70,6 +70,9 @@ fn toolDetail(t: ToolInvocation) []const u8 {
if (act.len > 0 and !std.mem.eql(u8, act, "send")) break :blk "action";
}
break :blk "text";
+ } else if (std.mem.eql(u8, t.name, "workspace")) blk: {
+ if (stringField(t.input, "path")) |p| if (p.len > 0) break :blk "path";
+ break :blk "action";
} else return "";
const detail = stringField(t.input, field) orelse return "";
const end = std.mem.indexOfScalar(u8, detail, '\n') orelse detail.len;
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index d74aea01..db727471 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -38,7 +38,8 @@ const eval_control = @import("agent_eval_control.zig");
const goal_state = @import("goal_state.zig");
const task_outcome = @import("task_outcome.zig");
const goal_todo = @import("goal_todo.zig"); // todo_write's replace path + the omitted-completed preserve rule
-const peer_channel = @import("peer_channel.zig"); // #469: peer_message's handler
+const peer_channel = @import("peer_channel.zig");
+const workspace_switch = @import("workspace_switch.zig");
pub const toolInvalidatesEval = eval_control.toolInvalidatesEval;
pub const gateTool = @import("agent_tool_gate.zig").gateTool;
pub const firstWord = @import("agent_tool_gate.zig").firstWord;
@@ -303,6 +304,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
if (!self.sub) native_fold.markIfFolded(call.name);
// #469: sideways coordination between co-resident root sessions.
if (std.mem.eql(u8, call.name, peer_channel.tool_name)) return peer_channel.handleMessage(self, call);
+ if (std.mem.eql(u8, call.name, workspace_switch.tool_name)) return workspace_switch.handle(self, call);
if (std.mem.eql(u8, call.name, "attempt_completion")) {
if (!self.review_mode and self.eval_cmd != null and (!self.eval_verified or self.eval_repair_pending)) {
const message = if (self.eval_repair_pending)
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index e4e7232f..e974da04 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -64,6 +64,7 @@ pub const commands = [_]Item{
.{ .name = "/save", .usage = "/save [name]", .desc = "write the conversation to <name>.session.json (default: current)" },
.{ .name = "/resume", .usage = "/resume [name]", .desc = "restore a saved conversation (no arg → interactive picker)" },
.{ .name = "/sessions", .desc = "list saved sessions in the cwd" },
+ .{ .name = "/workspace", .usage = "/workspace [list|use <name>]", .desc = "list git worktrees or switch this session into one (file tools follow)" },
.{ .name = "/todo", .desc = "show the current task list" },
.{ .name = "/jobs", .desc = "list background jobs" },
.{ .name = "/cost", .desc = "session token usage and cost" },
diff --git a/src/commands_session.zig b/src/commands_session.zig
index 5638809a..e128262a 100644
--- a/src/commands_session.zig
+++ b/src/commands_session.zig
@@ -32,6 +32,7 @@ const style = &ansi.style;
const exec = @import("exec.zig");
const execTool = exec.execTool;
const commands_sandbox = @import("commands_sandbox.zig"); // #554 /snapshot + /rewind <id>
+const workspace_switch = @import("workspace_switch.zig");
const fleet = @import("fleet.zig");
const promoteAgents = fleet.promoteAgents;
@@ -86,6 +87,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
// #554: claims /snapshot, and /rewind ONLY when its argument is a snapshot
// id — a numeric /rewind falls through to the conversation rewind below.
if (try commands_sandbox.tryHandle(root, arena, line, out)) return true;
+ if (try workspace_switch.slashCommand(root, arena, line, out)) return true;
if (std.mem.eql(u8, line, "/clear")) {
root.messages = std.json.Array.init(arena);
root.last_context_tokens = 0;
diff --git a/src/help.zig b/src/help.zig
index aaaf5c1c..2845f91d 100644
--- a/src/help.zig
+++ b/src/help.zig
@@ -28,7 +28,7 @@ const peers_blurb =
;
pub const sections = [_]Section{
- .{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/rename", "/rewind", "/snapshot" } },
+ .{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/workspace", "/rename", "/rewind", "/snapshot" } },
.{ .title = "the model", .names = &.{ "/model", "/models", "/effort", "/reasoning", "/fast", "/thinking", "/keepcontext", "/fallback", "/routes" } },
.{ .title = "working autonomously", .names = &.{ "/goal", "/loop", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },
.{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek" }, .blurb = peers_blurb },
diff --git a/src/native_fold.zig b/src/native_fold.zig
index 545f51ad..993ccc68 100644
--- a/src/native_fold.zig
+++ b/src/native_fold.zig
@@ -50,6 +50,7 @@ pub const folded = [_][]const u8{
"todo_write",
"todo_read",
"peer_message",
+ "workspace",
"note_constraint",
"agent_output",
"skill",
diff --git a/src/presence.zig b/src/presence.zig
index c51791bf..756e97ac 100644
--- a/src/presence.zig
+++ b/src/presence.zig
@@ -1,23 +1,8 @@
-//! Cross-session presence registry (#469): the disk + lifecycle half that
-//! worktree_lease.zig's pure #320 logic never got wired to. Every root session
-//! writes a small owner record (pid + start identity + worktree identity +
-//! current goal) into the per-user registry at birth and removes it at exit.
-//! Liveness is PROBED via proc_identity (#413), never trusted from the file,
-//! so a crashed session's record reaps itself on the next read — no heartbeat
-//! thread, no reaper daemon.
-//!
-//! Adherence is structural, not prompt-level:
-//! - announce/retire/goal updates are wired into session_run + goal_flow, so
-//! a session cannot forget to register;
-//! - agent_tool_gate refuses the FIRST index/worktree-mutating git command
-//! issued while a live foreign session co-owns this worktree — under
-//! --yolo too, where no approvals prompt exists — until the command is
-//! re-issued. That re-issue is the deliberate acknowledgment the #469
-//! incident (two --yolo sessions, one staging renames under the other)
-//! never had a chance to make.
-//!
-//! No locking, no arbitration (#469 v1 non-goals): the registry carries
-//! presence + intent; humans and agents still serialize the work.
+//! Cross-session presence registry (#469): disk + lifecycle for worktree_lease.
+//! Each root session writes pid + start-id + worktree identity + goal into
+//! ~/.graff/live; liveness is probed via proc_identity, never the file.
+//! announce/retire/goal are wired into session_run + goal_flow. The first
+//! shared-tree mutation against a live peer checkpoints once. No locking.
const std = @import("std");
const builtin = @import("builtin");
@@ -273,13 +258,29 @@ pub fn announce(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, sess
return duplicate;
}
-/// Remove our record. Best-effort: a crashed session leaves it behind and the
-/// next listPeers probes it dead and reaps it — retire is hygiene, not
-/// correctness.
-/// Free the gpa-owned globals. finalizeSession calls this at exit: a Debug
-/// build's SafeAllocator reports any gpa allocation still held at process end
-/// as a leak (and exits non-zero), and these five strings are otherwise
-/// exactly that. After deinit the module is inert.
+pub fn rebind(io: Io, gpa: Allocator, arena: Allocator) void {
+ if (builtin.is_test or g_own_name == null) return;
+ const identity = worktree_lease.currentIdentity(gpa, io, arena);
+ if (identity.id.len == 0 or std.mem.eql(u8, identity.id, g_identity)) return;
+ if (g_identity.len > 0) gpa.free(g_identity);
+ g_identity = gpa.dupe(u8, identity.id) catch return;
+ if (g_chan) |c| gpa.free(c);
+ var chan_buf: [chan_name_max]u8 = undefined;
+ g_chan = gpa.dupe(u8, chanName(&chan_buf, g_identity)) catch null;
+ g_inbox_off = 0;
+ if (g_dir) |dir_path| if (g_chan) |chan| {
+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch {
+ writeOwn(io, arena);
+ return;
+ };
+ defer dir.close(io);
+ if (dir.readFileAlloc(io, chan, arena, .limited(16 * 1024 * 1024)) catch null) |text|
+ g_inbox_off = @intCast(text.len);
+ };
+ writeOwn(io, arena);
+}
+
+/// retire is hygiene; deinit frees gpa-owned globals for the exit leak check.
pub fn deinit(gpa: Allocator) void {
if (g_dir) |p| gpa.free(p);
if (g_identity.len > 0) gpa.free(g_identity);
diff --git a/src/repl_model_commands.zig b/src/repl_model_commands.zig
index ece320d4..9f7cde0a 100644
--- a/src/repl_model_commands.zig
+++ b/src/repl_model_commands.zig
@@ -115,8 +115,8 @@ pub fn runCommand(self: *Model, line: []const u8) void {
self.push(.info, "`/loop` schedules repeated runs in the main session, not the chat repl") catch {};
} else if (eqlAny(cmd, &.{ "/trace", "/trajectory" })) {
self.push(.info, "trace/trajectory logging is a main-session feature") catch {};
- } else if (eqlAny(cmd, &.{ "/save", "/resume", "/sessions" })) {
- self.push(.info, "the chat repl is ephemeral — session save/resume/list lives in the main `graff` session") catch {};
+ } else if (eqlAny(cmd, &.{ "/save", "/resume", "/sessions", "/workspace", "/ws" })) {
+ self.push(.info, "the chat repl is ephemeral — session save/resume/list/workspace lives in the main `graff` session") catch {};
} else if (std.mem.eql(u8, cmd, "/images")) {
self.push(.info, "/images opens image URLs from tool output (e.g. a `gh issue view` result); the chat repl runs no tools — use the main `graff` session for it") catch {};
} else if (eqlAny(cmd, &.{ "/image", "/paste" })) {
diff --git a/src/repl_util.zig b/src/repl_util.zig
index f40d1f25..0123de63 100644
--- a/src/repl_util.zig
+++ b/src/repl_util.zig
@@ -18,7 +18,7 @@ pub const HELP_CHAT =
\\ /goal <text> standing objective (tracked as a checklist)
\\ /plan /strict /yolo /keepcontext /title modes
\\ /rename <name> /animation enso|braille|dragon
- \\ /bash /save /resume /sessions /trace /trajectory
+ \\ /bash /save /resume /sessions /workspace /trace /trajectory
\\ /agents /skills /hooks /mcp /loop /review /image /paste /key
\\
\\Type a message and press enter to send it to the model. Toggles accept
diff --git a/src/schema.zig b/src/schema.zig
index 14e397c2..03b86ce9 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -14,7 +14,8 @@ const mcp = @import("mcp.zig");
const pricing = @import("pricing.zig");
const learn_store = @import("learn_store.zig");
const skill_docs = @import("skill_docs.zig"); // SKILL.md playbooks: the `skill` tool's name/desc/schema live there
-const peer_channel = @import("peer_channel.zig"); // #469: the peer_message tool's name/desc/schema live there
+const peer_channel = @import("peer_channel.zig");
+const workspace_switch = @import("workspace_switch.zig");
const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate (layer 1 lives here, layer 2 in exec.zig)
const tool_gates = @import("tool_gates.zig"); // #352: the additive twin — optional tools that only exist when startup found their backing capability
const imagegen = @import("imagegen.zig"); // #352: name/desc/schema as plain strings, like skill_docs, so this catalog needs one entry and no import cycle
@@ -200,12 +201,9 @@ const learn_candidate_spec = ToolSpec{
,
};
-pub const root_specs = base_specs ++ meta_specs ++ [_]ToolSpec{ subagent_spec, workflow_spec, agent_output_spec, learn_candidate_spec, peer_spec };
const peer_spec = ToolSpec{ .name = peer_channel.tool_name, .desc = peer_channel.tool_desc, .schema = peer_channel.tool_schema };
-
-// The common catalog (clock_sleep off) is static too. Previously every root
-// startup allocated and filled a filtered ToolSpec array before rendering even
-// one provider catalog.
+const workspace_spec = ToolSpec{ .name = workspace_switch.tool_name, .desc = workspace_switch.tool_desc, .schema = workspace_switch.tool_schema };
+pub const root_specs = base_specs ++ meta_specs ++ [_]ToolSpec{ subagent_spec, workflow_spec, agent_output_spec, learn_candidate_spec, peer_spec, workspace_spec };
/// The root catalog minus the named optional entries, built once at compile
/// time. The length check is the guard: each name must match EXACTLY one
/// spec, so a rename or a duplicated entry is a compile error rather than a
@@ -226,7 +224,7 @@ const root_specs_without_clock = rootSpecsWithout(&.{"clock_sleep"});
const root_specs_without_learning = rootSpecsWithout(&.{"learn_candidate"});
const root_specs_without_optional = rootSpecsWithout(&.{ "clock_sleep", "learn_candidate" });
-pub const meta_names = [_][]const u8{ "todo_write", "todo_read", "ask_user", "eval", "attempt_completion", "clock_sleep", "note_constraint", mcp_schema_gate.tool_name, peer_channel.tool_name };
+pub const meta_names = [_][]const u8{ "todo_write", "todo_read", "ask_user", "eval", "attempt_completion", "clock_sleep", "note_constraint", mcp_schema_gate.tool_name, peer_channel.tool_name, workspace_switch.tool_name };
pub fn isMetaName(name: []const u8) bool {
for (meta_names) |m| if (std.mem.eql(u8, name, m)) return true;
diff --git a/src/session_run.zig b/src/session_run.zig
index e44eefc7..f55bebe4 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -435,6 +435,7 @@ pub fn finalizeSession(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer
// skips this and gets reaped by the next reader's liveness probe instead.
presence.retire(io);
presence.deinit(gpa); // its gpa-owned globals must not reach the exit-time leak check
+ @import("workspace_switch.zig").deinitDisplay(gpa);
if (!json_mode and root.messages.items.len > 0) {
const sink = engine_sink.writerSink(out);
if (session.saveSession(root, arena, root.session_name)) |_| {
diff --git a/src/skill_docs.zig b/src/skill_docs.zig
index b0ab60d3..d2ed4374 100644
--- a/src/skill_docs.zig
+++ b/src/skill_docs.zig
@@ -9,9 +9,9 @@
//! like fleet.zig's agent personas — bundled < personal < project — and
//! disclosure is progressive: only the descriptions ride in the system prompt
//! (promptCatalog), while bodies stay on disk until the `skill` tool loads one
-//! (execSkill). Three skills are embedded in the binary so a fresh install
-//! already knows how to write more (skill-creator), how to change MCP
-//! config (mcp-config), and how to run a long-horizon working set (jspace).
+//! (execSkill). Bundled skills teach writing more (skill-creator), MCP
+//! config (mcp-config), long-horizon control (jspace), and mid-session
+//! worktree switch (workspace).
const std = @import("std");
const Io = std.Io;
@@ -63,7 +63,7 @@ const desc_cap = 160; // per-skill description budget in the system prompt — t
/// a schema.ToolSpec) so schema.zig's catalog needs one entry and no import
/// cycle. The description must stay free of characters needing JSON escapes.
pub const tool_name = "skill";
-pub const tool_desc = "Load a skill: the full instructions for one kind of task, kept out of your context until you need them. The system prompt lists only skill names and descriptions, so call this to read the body BEFORE doing work a skill covers, then follow it. Omit name to list every available skill. Skills come from .harness/skills/ (this project), ~/.harness/skills/ (yours), .claude/skills/, plus bundled skill-creator, mcp-config, and jspace.";
+pub const tool_desc = "Load a skill: the full instructions for one kind of task, kept out of your context until you need them. The system prompt lists only skill names and descriptions, so call this to read the body BEFORE doing work a skill covers, then follow it. Omit name to list every available skill. Skills come from .harness/skills/ (this project), ~/.harness/skills/ (yours), .claude/skills/, plus bundled skill-creator, mcp-config, jspace, and workspace.";
pub const tool_schema =
\\{"type": "object", "properties": {"name": {"type": "string", "description": "Skill name to load; omit to list every available skill"}}}
;
@@ -99,6 +99,7 @@ const embedded = [_]Embedded{
.{ .fallback = "skill-creator", .bytes = @embedFile("skill_doc_creator") },
.{ .fallback = "mcp-config", .bytes = @embedFile("skill_doc_mcp_config") },
.{ .fallback = "jspace", .bytes = @embedFile("skill_doc_jspace") },
+ .{ .fallback = "workspace", .bytes = @embedFile("skill_doc_workspace") },
};
/// Skills compiled into the binary: every install has these, no files needed.
@@ -325,10 +326,11 @@ test "parseDoc: no frontmatter keeps the filename and the whole file as body" {
}
test "bundled skills: both parse at comptime with a trigger description" {
- try std.testing.expectEqual(@as(usize, 3), builtins.len);
+ try std.testing.expectEqual(@as(usize, 4), builtins.len);
try std.testing.expectEqualStrings("skill-creator", builtins[0].name);
try std.testing.expectEqualStrings("mcp-config", builtins[1].name);
try std.testing.expectEqualStrings("jspace", builtins[2].name);
+ try std.testing.expectEqualStrings("workspace", builtins[3].name);
for (builtins) |sk| {
try std.testing.expect(sk.desc.len > 40); // a trigger, not a topic word
try std.testing.expect(sk.body.len > 500);
@@ -341,6 +343,7 @@ test "bundled skills: both parse at comptime with a trigger description" {
try std.testing.expect(std.mem.indexOf(u8, builtins[1].body, ".mcp.json") != null);
try std.testing.expect(std.mem.indexOf(u8, builtins[1].body, "/mcp trust") != null);
try std.testing.expect(std.mem.indexOf(u8, builtins[2].body, "action=inbox") != null);
+ try std.testing.expect(std.mem.indexOf(u8, builtins[3].body, "action=use") != null);
}
test "tool_desc stays JSON-escape-free (it is spliced into a raw schema string)" {
@@ -348,6 +351,7 @@ test "tool_desc stays JSON-escape-free (it is spliced into a raw schema string)"
try std.testing.expect(std.mem.indexOf(u8, tool_desc, "skill-creator") != null);
try std.testing.expect(std.mem.indexOf(u8, tool_desc, "mcp-config") != null);
try std.testing.expect(std.mem.indexOf(u8, tool_desc, "jspace") != null);
+ try std.testing.expect(std.mem.indexOf(u8, tool_desc, "workspace") != null);
}
test "insert: a later tier shadows the same name, others append" {
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 0defce03..c6286e16 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -126,6 +126,7 @@ const peer_context = @import("peer_context.zig"); // ADR 0004 / #563 slice F
const peer_context_compact_test = @import("peer_context_compact_test.zig");
const peer_inbox = @import("peer_inbox.zig"); // Claude-style list/inbox pull
const peer_target = @import("peer_target.zig"); // exact DM / goal targeting
+const workspace_switch = @import("workspace_switch.zig"); // ADR 0006 mid-session worktree switch
// #345: the global-vs-project MCP config merge. mcp.zig does reference its
// decls, but the hook makes the coverage explicit rather than contingent on
@@ -257,6 +258,7 @@ test {
_ = peer_context_compact_test;
_ = peer_inbox;
_ = peer_target;
+ _ = workspace_switch;
_ = shutdown_trace;
_ = credential_store;
_ = engine_events;
diff --git a/src/workspace_switch.zig b/src/workspace_switch.zig
new file mode 100644
index 00000000..8fad624f
--- /dev/null
+++ b/src/workspace_switch.zig
@@ -0,0 +1,374 @@
+//! Mid-session workspace switch: list git worktrees and chdir the root
+//! session so read_file/edit_file/bash follow the new tree.
+//!
+//! A skill cannot do this. File tools resolve against process cwd (or a
+//! subagent's isolated agent_cwd). `cd` inside bash does not move them.
+//! `graff -w` creates a scratch tree at startup; this module switches among
+//! trees that already exist (Claude worktrees, `git worktree add`, -w tabs).
+//!
+//! Surfaces:
+//! - workspace tool: action=list | use (folded; agent-thread only)
+//! - /workspace [list|use <name>]: the human's own switch
+//! - bundled `workspace` skill: when to load the tool, not the actuator
+
+const std = @import("std");
+const builtin = @import("builtin");
+
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const agent_mod = @import("agent.zig");
+const tools_mod = @import("tools.zig");
+const main_mod = @import("main.zig");
+const jobs = @import("jobs.zig");
+const presence = @import("presence.zig");
+const tool_spill = @import("tool_spill.zig");
+
+const Agent = agent_mod.Agent;
+const ToolCall = tools_mod.ToolCall;
+const ExecResult = tools_mod.ExecResult;
+
+pub const tool_name = "workspace";
+pub const tool_desc = "List this repo's git worktrees or switch the session into one. action=list (default) or use. path is a worktree path, its last folder, or a unique name fragment. File tools and bash follow the new cwd. Root session only — a subagent stays in its assigned tree. Do not bash-cd to switch.";
+pub const tool_schema =
+ \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["list", "use"], "description": "list (default): the repo's git worktrees. use: chdir this session into one."}, "path": {"type": "string", "description": "worktree path, last folder, or unique fragment (required for use)"}}}
+;
+
+pub const Entry = struct {
+ path: []const u8,
+ head: []const u8 = "",
+ branch: []const u8 = "",
+};
+
+pub const Resolve = union(enum) {
+ one: Entry,
+ already: Entry,
+ none,
+ ambiguous: []const Entry,
+};
+
+var g_cwd_owned: ?[]u8 = null;
+
+pub fn deinitDisplay(gpa: Allocator) void {
+ if (g_cwd_owned) |old| gpa.free(old);
+ g_cwd_owned = null;
+}
+
+fn adoptDisplay(gpa: Allocator, path: []const u8) void {
+ const owned = gpa.dupe(u8, path) catch return;
+ if (g_cwd_owned) |old| gpa.free(old);
+ g_cwd_owned = owned;
+ main_mod.g_cwd_display = owned;
+}
+
+fn basename(path: []const u8) []const u8 {
+ const trimmed = std.mem.trimEnd(u8, path, "/");
+ if (std.mem.lastIndexOfScalar(u8, trimmed, '/')) |i| return trimmed[i + 1 ..];
+ return trimmed;
+}
+
+fn branchShort(ref: []const u8) []const u8 {
+ const prefix = "refs/heads/";
+ if (std.mem.startsWith(u8, ref, prefix)) return ref[prefix.len..];
+ return ref;
+}
+
+/// Parse `git worktree list --porcelain`. Ignores bare/detached/locked extras.
+pub fn parsePorcelain(arena: Allocator, text: []const u8) []Entry {
+ var list: std.ArrayList(Entry) = .empty;
+ var cur: Entry = .{ .path = "" };
+ var lines = std.mem.splitScalar(u8, text, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0) {
+ if (cur.path.len > 0) list.append(arena, cur) catch {};
+ cur = .{ .path = "" };
+ continue;
+ }
+ if (std.mem.startsWith(u8, line, "worktree ")) {
+ if (cur.path.len > 0) list.append(arena, cur) catch {};
+ cur = .{ .path = std.mem.trim(u8, line["worktree ".len..], " \t") };
+ } else if (std.mem.startsWith(u8, line, "HEAD ")) {
+ cur.head = std.mem.trim(u8, line["HEAD ".len..], " \t");
+ } else if (std.mem.startsWith(u8, line, "branch ")) {
+ cur.branch = branchShort(std.mem.trim(u8, line["branch ".len..], " \t"));
+ }
+ }
+ if (cur.path.len > 0) list.append(arena, cur) catch {};
+ return list.items;
+}
+
+fn samePath(a: []const u8, b: []const u8) bool {
+ const left = std.mem.trimEnd(u8, a, "/");
+ const right = std.mem.trimEnd(u8, b, "/");
+ return std.mem.eql(u8, left, right);
+}
+
+fn matches(entry: Entry, want: []const u8) bool {
+ if (samePath(entry.path, want)) return true;
+ if (std.mem.eql(u8, basename(entry.path), want)) return true;
+ if (std.mem.eql(u8, entry.branch, want)) return true;
+ return std.mem.indexOf(u8, entry.path, want) != null or std.mem.indexOf(u8, entry.branch, want) != null;
+}
+
+pub fn resolve(arena: Allocator, entries: []const Entry, want: []const u8, current: []const u8) Resolve {
+ const needle = std.mem.trim(u8, want, " \t");
+ if (needle.len == 0 or entries.len == 0) return .none;
+ var hits: std.ArrayList(Entry) = .empty;
+ for (entries) |e| {
+ if (matches(e, needle)) hits.append(arena, e) catch {};
+ }
+ if (hits.items.len == 0) return .none;
+ if (hits.items.len == 1) {
+ if (current.len > 0 and samePath(hits.items[0].path, current)) return .{ .already = hits.items[0] };
+ return .{ .one = hits.items[0] };
+ }
+ return .{ .ambiguous = hits.items };
+}
+
+pub fn formatList(arena: Allocator, entries: []const Entry, current: []const u8) []const u8 {
+ if (entries.len == 0) return "no git worktrees here — this cwd is not a repository, or git worktree list failed";
+ var buf: std.ArrayList(u8) = .empty;
+ buf.appendSlice(arena, "git worktrees (star = this session). workspace action=use path=<folder or fragment> to switch.\n") catch {};
+ for (entries) |e| {
+ const star: []const u8 = if (current.len > 0 and samePath(e.path, current)) "* " else " ";
+ const br = if (e.branch.len > 0) e.branch else "(detached)";
+ const line = std.fmt.allocPrint(arena, "{s}{s} {s}\n", .{ star, e.path, br }) catch continue;
+ buf.appendSlice(arena, line) catch {};
+ }
+ return buf.items;
+}
+
+fn currentAbs(io: Io, arena: Allocator) []const u8 {
+ var cwd_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const n = Io.Dir.cwd().realPath(io, &cwd_buf) catch return main_mod.g_cwd_display;
+ return arena.dupe(u8, cwd_buf[0..n]) catch main_mod.g_cwd_display;
+}
+
+fn listEntries(gpa: Allocator, io: Io, arena: Allocator) []Entry {
+ const listed = jobs.runCapped(gpa, io, &.{ "git", "worktree", "list", "--porcelain" }, 64 * 1024, 4096, 15_000) catch return &.{};
+ defer {
+ gpa.free(listed.stdout);
+ gpa.free(listed.stderr);
+ }
+ if (listed.term != .exited or listed.term.exited != 0) return &.{};
+ return parsePorcelain(arena, listed.stdout);
+}
+
+fn enterPath(gpa: Allocator, io: Io, arena: Allocator, path: []const u8) ![]const u8 {
+ if (builtin.os.tag == .windows) return error.Unsupported;
+ const z = try arena.dupeSentinel(u8, path, 0);
+ if (std.posix.system.chdir(z.ptr) != 0) return error.ChdirFailed;
+ const abs = currentAbs(io, arena);
+ adoptDisplay(gpa, abs);
+ main_mod.g_worktree_branch = null;
+ tool_spill.enable(.{ .io = io, .dir = .cwd(), .base_abs = main_mod.g_cwd_display });
+ presence.rebind(io, gpa, arena);
+ return abs;
+}
+
+fn run(gpa: Allocator, io: Io, arena: Allocator, from_sub: bool, action: []const u8, path: []const u8) ExecResult {
+ if (from_sub) return .{
+ .text = "workspace switch is root-session only — a subagent stays in its assigned tree",
+ .is_error = true,
+ };
+ const current = currentAbs(io, arena);
+ if (std.mem.eql(u8, action, "list") or action.len == 0) {
+ return .{ .text = formatList(arena, listEntries(gpa, io, arena), current), .is_error = false };
+ }
+ if (!std.mem.eql(u8, action, "use")) return .{
+ .text = "workspace action must be list or use",
+ .is_error = true,
+ };
+ if (path.len == 0) return .{
+ .text = "workspace use needs path — a worktree folder or unique fragment. action=list to see them.",
+ .is_error = true,
+ };
+ const entries = listEntries(gpa, io, arena);
+ return switch (resolve(arena, entries, path, current)) {
+ .none => .{
+ .text = tryText(arena, "no worktree matches \"{s}\" — action=list to see them", .{path}),
+ .is_error = true,
+ },
+ .ambiguous => |hits| .{
+ .text = tryText(arena, "more than one worktree matches \"{s}\":\n{s}", .{ path, formatList(arena, hits, current) }),
+ .is_error = true,
+ },
+ .already => |e| .{
+ .text = tryText(arena, "already at {s} ({s})", .{ e.path, if (e.branch.len > 0) e.branch else "detached" }),
+ .is_error = false,
+ },
+ .one => |e| blk: {
+ const abs = enterPath(gpa, io, arena, e.path) catch |err| break :blk .{
+ .text = tryText(arena, "could not enter {s}: {t}", .{ e.path, err }),
+ .is_error = true,
+ };
+ break :blk .{
+ .text = tryText(arena, "now at {s} ({s}) — read_file, edit_file, and bash use this tree. Project instructions stay the ones from session start until /clear.", .{ abs, if (e.branch.len > 0) e.branch else "detached" }),
+ .is_error = false,
+ };
+ },
+ };
+}
+
+fn tryText(arena: Allocator, comptime fmt: []const u8, args: anytype) []const u8 {
+ return std.fmt.allocPrint(arena, fmt, args) catch "workspace: out of memory";
+}
+
+pub fn handle(self: *Agent, call: ToolCall) !ExecResult {
+ const obj = tools_mod.json_args.object(call.input);
+ const action = if (obj) |o| (tools_mod.json_args.str(o, "action") orelse "list") else "list";
+ const path = if (obj) |o| (tools_mod.json_args.str(o, "path") orelse "") else "";
+ return run(self.gpa, self.io, self.arena, self.sub or self.agent_cwd != null, action, path);
+}
+
+fn isSlash(line: []const u8) bool {
+ return std.mem.eql(u8, line, "/workspace") or std.mem.eql(u8, line, "/ws") or
+ std.mem.startsWith(u8, line, "/workspace ") or std.mem.startsWith(u8, line, "/ws ");
+}
+
+/// /workspace [list|use <name>]. Bare lists.
+pub fn slashCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {
+ if (!isSlash(line)) return false;
+ const rest = if (std.mem.startsWith(u8, line, "/workspace"))
+ std.mem.trim(u8, line["/workspace".len..], " \t")
+ else
+ std.mem.trim(u8, line["/ws".len..], " \t");
+ var action: []const u8 = "list";
+ var path: []const u8 = "";
+ if (rest.len > 0) {
+ if (std.mem.startsWith(u8, rest, "use ") or std.mem.startsWith(u8, rest, "cd ")) {
+ action = "use";
+ path = std.mem.trim(u8, rest[3..], " \t");
+ } else if (std.mem.eql(u8, rest, "use") or std.mem.eql(u8, rest, "cd")) {
+ action = "use";
+ } else if (std.mem.eql(u8, rest, "list") or std.mem.eql(u8, rest, "ls")) {
+ action = "list";
+ } else {
+ action = "use";
+ path = rest;
+ }
+ }
+ const result = run(root.gpa, root.io, arena, false, action, path);
+ try out.writeAll(result.text);
+ if (result.text.len == 0 or result.text[result.text.len - 1] != '\n') try out.writeAll("\n");
+ try out.flush();
+ return true;
+}
+
+const sample_porcelain =
+ \\worktree /Users/rach/codegraff
+ \\HEAD abcdef0123456789
+ \\branch refs/heads/main
+ \\
+ \\worktree /Users/rach/codegraff/.claude/worktrees/cursor-peer-pull-554f
+ \\HEAD d93214eb7fb782c3
+ \\branch refs/heads/cursor/peer-pull-554f
+ \\
+ \\worktree /Users/rach/codegraff/.graff/worktrees/agent1
+ \\HEAD 1111111111111111
+ \\branch refs/heads/worktree-agent1
+ \\
+;
+
+test "parsePorcelain: path, short branch, ignores extras" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const extra =
+ \\worktree /tmp/repo
+ \\HEAD deadbeef
+ \\detached
+ \\
+ ;
+ const rows = parsePorcelain(a, extra);
+ try std.testing.expectEqual(@as(usize, 1), rows.len);
+ try std.testing.expectEqualStrings("/tmp/repo", rows[0].path);
+ try std.testing.expectEqualStrings("", rows[0].branch);
+ const all = parsePorcelain(a, sample_porcelain);
+ try std.testing.expectEqual(@as(usize, 3), all.len);
+ try std.testing.expectEqualStrings("cursor/peer-pull-554f", all[1].branch);
+ try std.testing.expectEqualStrings("cursor-peer-pull-554f", basename(all[1].path));
+}
+
+test "resolve: unique fragment, basename, branch, already, none, ambiguous" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const rows = parsePorcelain(a, sample_porcelain);
+ const here = rows[0].path;
+ switch (resolve(a, rows, "cursor-peer-pull-554f", here)) {
+ .one => |e| try std.testing.expectEqualStrings(rows[1].path, e.path),
+ else => return error.TestUnexpectedResult,
+ }
+ switch (resolve(a, rows, "cursor/peer-pull-554f", here)) {
+ .one => |e| try std.testing.expectEqualStrings(rows[1].path, e.path),
+ else => return error.TestUnexpectedResult,
+ }
+ switch (resolve(a, rows, here, here)) {
+ .already => |e| try std.testing.expectEqualStrings(here, e.path),
+ else => return error.TestUnexpectedResult,
+ }
+ try std.testing.expect(resolve(a, rows, "no-such-tree", here) == .none);
+ switch (resolve(a, rows, "codegraff", here)) {
+ .ambiguous => |hits| try std.testing.expect(hits.len >= 2),
+ else => return error.TestUnexpectedResult,
+ }
+}
+
+test "formatList: stars the current tree and stays pull (no dump of bodies)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const rows = parsePorcelain(a, sample_porcelain);
+ const text = formatList(a, rows, rows[1].path);
+ try std.testing.expect(std.mem.indexOf(u8, text, "* /Users/rach/codegraff/.claude/worktrees/cursor-peer-pull-554f") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "action=use") != null);
+ try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, formatList(a, &.{}, ""), '*'));
+}
+
+test "run: subagent is refused; bad action and empty use name the fix" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ const sub = run(gpa, io, a, true, "list", "");
+ try std.testing.expect(sub.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, sub.text, "root-session only") != null);
+ const bad = run(gpa, io, a, false, "send", "");
+ try std.testing.expect(bad.is_error);
+ const empty = run(gpa, io, a, false, "use", "");
+ try std.testing.expect(empty.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, empty.text, "action=list") != null);
+}
+
+test "enterPath: chdir then restore; display follows the new tree" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var orig = try Io.Dir.cwd().openDir(io, ".", .{});
+ defer orig.close(io);
+ defer _ = std.posix.system.fchdir(orig.handle);
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ if (std.posix.system.fchdir(tmp.dir.handle) != 0) return error.ChdirFailed;
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const n = Io.Dir.cwd().realPath(io, &path_buf) catch return error.SkipZigTest;
+ const dest = try a.dupe(u8, path_buf[0..n]);
+ _ = std.posix.system.fchdir(orig.handle);
+ const saved = main_mod.g_cwd_display;
+ const saved_branch = main_mod.g_worktree_branch;
+ defer {
+ main_mod.g_cwd_display = saved;
+ main_mod.g_worktree_branch = saved_branch;
+ deinitDisplay(gpa);
+ tool_spill.resetForTest();
+ }
+ const abs = try enterPath(gpa, io, a, dest);
+ try std.testing.expectEqualStrings(dest, abs);
+ try std.testing.expectEqualStrings(dest, main_mod.g_cwd_display);
+}