graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Task workspaces copy ignored files and run project scripts
justrach2069c6ca4f26
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b83db71b..2657fc5e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,7 +10,11 @@ The release workflow uses a tag's section here as its release notes (ahand-written `docs/releases/<tag>.md` wins if present), so keeping this filecurrent is part of cutting a release.-## Unreleased+## v0.0.302.3++- Task workspaces copy gitignored files (`.worktreeinclude` or Conductor `file_include_globs`) and run setup/run/archive scripts (ADR 0153). Desktop Tools: New task workspace, Run, Archive.++## v0.0.302.2- Persistent `shell` / `bash_output` jobs snapshot immediately (`wait_ms` ignored) and stay on `/jobs`; the 15s still-running poll no longer holds the turn (ADR 0152). Finite jobs still wait until exit.- `graff login zai` (aliases `glm`, `z.ai`) signs in to a Z.AI Coding Plan and routes chat to `/api/coding/paas/v4` without `ZAI_CODING=1` (ADR 0151).diff --git a/apps/native/app/api/worktree/route.ts b/apps/native/app/api/worktree/route.tsnew file mode 100644index 00000000..ffeced0e--- /dev/null+++ b/apps/native/app/api/worktree/route.ts@@ -0,0 +1,63 @@+import { spawn } from "node:child_process";+import { graffBin, parseCreate, runCommand, sanitizeSlug, slugFromCheckout } from "@/lib/worktree-cli";+import { resolveRoot } from "@/lib/server-root";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++function run(bin: string, args: string[], cwd: string, timeoutMs: number): Promise<{ code: number; stdout: string; stderr: string }> {+ return new Promise((resolve, reject) => {+ const child = spawn(bin, args, { cwd, env: process.env });+ let stdout = "";+ let stderr = "";+ const timer = setTimeout(() => {+ child.kill("SIGTERM");+ reject(new Error("worktree command timed out"));+ }, timeoutMs);+ child.stdout?.on("data", (chunk: Buffer) => { stdout += chunk.toString(); });+ child.stderr?.on("data", (chunk: Buffer) => { stderr += chunk.toString(); });+ child.on("error", err => { clearTimeout(timer); reject(err); });+ child.on("close", code => {+ clearTimeout(timer);+ resolve({ code: code ?? 1, stdout, stderr });+ });+ });+}++export async function POST(req: Request) {+ try {+ if (Number(req.headers.get("content-length")) > 16384) return Response.json({ error: "Message too large" }, { status: 413 });+ const body = await req.json();+ const resolved = resolveRoot(typeof body.root === "string" ? body.root : undefined);+ if ("error" in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });+ const bin = graffBin();+ const action = body.action;+ if (action === "create") {+ const name = sanitizeSlug(typeof body.name === "string" ? body.name : "");+ if (!name) return Response.json({ error: "workspace name must be 1-64 letters, digits, '.', '_' or '-'" }, { status: 400 });+ const result = await run(bin, ["worktree", "create", name], resolved.root, 120_000);+ const parsed = parseCreate(result.stdout);+ if (result.code !== 0 || !parsed) {+ return Response.json({ error: result.stderr.trim() || result.stdout.trim() || "create failed" }, { status: 502 });+ }+ return Response.json(parsed);+ }+ if (action === "archive") {+ const name = sanitizeSlug(typeof body.name === "string" ? body.name : "")+ ?? slugFromCheckout(resolved.root);+ if (!name) return Response.json({ error: "not a task workspace" }, { status: 400 });+ const result = await run(bin, ["worktree", "archive", name], resolved.root, 60_000);+ if (result.code !== 0) return Response.json({ error: result.stderr.trim() || result.stdout.trim() || "archive failed" }, { status: 502 });+ return Response.json({ ok: true, output: result.stdout.trim() });+ }+ if (action === "run") {+ const name = sanitizeSlug(typeof body.name === "string" ? body.name : "")+ ?? slugFromCheckout(resolved.root);+ if (!name) return Response.json({ error: "not a task workspace" }, { status: 400 });+ return Response.json({ ok: true, name, command: runCommand(name) });+ }+ return Response.json({ error: "Unknown worktree action" }, { status: 400 });+ } catch (error) {+ return Response.json({ error: error instanceof Error ? error.message : "Worktree unavailable" }, { status: 502 });+ }+}diff --git a/apps/native/components/site/HarnessChrome.tsx b/apps/native/components/site/HarnessChrome.tsxindex 22ad1652..b11e7016 100644--- a/apps/native/components/site/HarnessChrome.tsx+++ b/apps/native/components/site/HarnessChrome.tsx@@ -7,6 +7,7 @@ import { IconSidebarLeftOpen } from "@/lib/icons";import type { PointerEvent, MouseEvent, ReactNode } from "react";import type { Chat } from "./harness-types";import reviewStyles from "./ChangesPane.module.css";+import { archiveTaskWorkspace, createTaskWorkspace, runTaskWorkspace } from "./harness-task-workspace";type Props = {navigationToggle?: ReactNode; sidebarVisible?: boolean;@@ -55,6 +56,9 @@ export default function HarnessChrome({navigationToggle, sidebarVisible = false,<ActionMenu label="Workspace tools" text="Tools" className="shrink-0"><button type="button" aria-label="Review workspace changes" aria-pressed={changesOpen} onClick={openChanges}>Review</button>{onReviews && <button type="button" aria-label="GitHub reviews" aria-pressed={reviewsOpen} onClick={onReviews}>Reviews</button>}+ <button type="button" aria-label="New task workspace" onClick={() => void createTaskWorkspace(chatCwd).catch(err => window.alert(String(err.message || err)))}>New task workspace</button>+ <button type="button" aria-label="Run workspace script" onClick={() => void runTaskWorkspace(chatCwd, () => { if (!terminalVisible) toggleTerminal(); }).catch(err => window.alert(String(err.message || err)))}>Run</button>+ <button type="button" aria-label="Archive task workspace" onClick={() => void archiveTaskWorkspace(chatCwd).catch(err => window.alert(String(err.message || err)))}>Archive</button><button type="button" aria-label="Toggle terminal" aria-pressed={terminalVisible} onClick={toggleTerminal}>Terminal <span className="ml-auto text-ink-3">⌘J</span></button><button type="button" aria-label="Browser" aria-pressed={browserOpen} onClick={onBrowser}>Browser{pinCount > 0 ? ` (${pinCount})` : ""}</button><button type="button" aria-label="Files" aria-pressed={filesOpen && !changesOpen} onClick={onFiles}>Files</button>diff --git a/apps/native/components/site/TerminalPane.tsx b/apps/native/components/site/TerminalPane.tsxindex a9c34845..7bca98f7 100644--- a/apps/native/components/site/TerminalPane.tsx+++ b/apps/native/components/site/TerminalPane.tsx@@ -38,6 +38,8 @@ export default function TerminalPane({cwd,visible,onHide}:{cwd:string;visible:booff=bridge.terminalSubscribe!(event=>{if(!ready)queued.push(event);else deliver(event);});const result=await request('open',{cwd});if(disposed){void request('detach',{id:result.id});return;}id.current=result.id;term.options.disableStdin=result.exit!==null;setStatus(result.exit===null?'Shell ready':`Shell exited (${result.exit})`);setError('');+ const boot=sessionStorage.getItem('graff.terminal.command');+ if(boot&&result.exit===null){sessionStorage.removeItem('graff.terminal.command');void send('input',{data:boot.endsWith('\n')?boot:`${boot}\n`});}if(result.history)term.write(result.history);ready=true;for(const event of queued)if(event.seq>result.seq)deliver(event);queued.length=0;const fitVisible=()=>{if(shown.current&&host.current?.clientWidth){fit.fit();void send('resize',{cols:term.cols,rows:term.rows});}};@@ -46,6 +48,15 @@ export default function TerminalPane({cwd,visible,onHide}:{cwd:string;visible:boreturn()=>{disposed=true;off();resize?.disconnect();theme?.disconnect();terminal.current?.dispose();terminal.current=null;if(id.current)void request('detach',{id:id.current});id.current=null;};},[cwd,generation,start]);useEffect(()=>{if(visible)terminal.current?.focus();},[visible]);+ useEffect(()=>{+ const onCommand=(event:Event)=>{+ const command=(event as CustomEvent<{command?:string}>).detail?.command;+ if(!command||!id.current)return;+ void desktop()?.terminal?.('input',{id:id.current,data:command.endsWith('\n')?command:`${command}\n`});+ };+ window.addEventListener('graff-terminal-command',onCommand);+ return()=>window.removeEventListener('graff-terminal-command',onCommand);+ },[]);const end=async()=>{if(id.current)await desktop()?.terminal?.('close',{id:id.current});id.current=null;setGeneration(n=>n+1);};return <section data-workspace-terminal aria-label="Workspace terminal" hidden={!visible} className="relative shrink-0 overflow-hidden rounded-xl border border-line bg-page text-ink" style={{height,maxHeight:'65dvh'}}><div role="separator" aria-label="Resize terminal" aria-orientation="horizontal" tabIndex={0} aria-valuenow={height} aria-valuemin={120} aria-valuemax={Math.round(innerHeight*.65)}diff --git a/apps/native/components/site/harness-task-workspace.ts b/apps/native/components/site/harness-task-workspace.tsnew file mode 100644index 00000000..1d356a5c--- /dev/null+++ b/apps/native/components/site/harness-task-workspace.ts@@ -0,0 +1,33 @@+async function post(action: string, root: string | undefined, name?: string) {+ const response = await fetch("/api/worktree", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ action, root, name }),+ });+ const body = await response.json() as { error?: string; path?: string; command?: string; output?: string };+ if (!response.ok) throw new Error(body.error || "Worktree request failed");+ return body;+}++export async function createTaskWorkspace(root?: string): Promise<string | null> {+ const typed = window.prompt("New task workspace name");+ if (typed == null) return null;+ const created = await post("create", root, typed);+ if (created.path) window.dispatchEvent(new CustomEvent("graff-open-workspace", { detail: { cwd: created.path } }));+ return created.path ?? null;+}++export async function runTaskWorkspace(root: string | undefined, showTerminal: () => void): Promise<void> {+ const body = await post("run", root);+ if (body.command) {+ sessionStorage.setItem("graff.terminal.command", body.command);+ showTerminal();+ window.dispatchEvent(new CustomEvent("graff-terminal-command", { detail: { command: body.command } }));+ }+}++export async function archiveTaskWorkspace(root?: string): Promise<void> {+ if (!window.confirm("Archive this task workspace? Dirty or unique-commit trees stay.")) return;+ const body = await post("archive", root);+ if (body.output && !body.output.startsWith("✓")) window.alert(body.output);+}diff --git a/apps/native/components/site/useDesktopWorkspace.ts b/apps/native/components/site/useDesktopWorkspace.tsindex 69e8f463..b25ad2e3 100644--- a/apps/native/components/site/useDesktopWorkspace.ts+++ b/apps/native/components/site/useDesktopWorkspace.ts@@ -3,6 +3,14 @@ import { desktop } from '@/lib/desktop';export function useDesktopWorkspace(ready: boolean, open: (target: { cwd: string; file?: string }) => void) {const ref = useRef(open); ref.current = open;+ useEffect(() => {+ const onOpen = (event: Event) => {+ const cwd = (event as CustomEvent<{ cwd?: string }>).detail?.cwd;+ if (typeof cwd === "string" && cwd) ref.current({ cwd });+ };+ window.addEventListener("graff-open-workspace", onOpen);+ return () => window.removeEventListener("graff-open-workspace", onOpen);+ }, []);useEffect(() => {if (ready) return desktop()?.workspaceSubscribe?.(target => ref.current(target));}, [ready]);diff --git a/apps/native/lib/worktree-cli.test.ts b/apps/native/lib/worktree-cli.test.tsnew file mode 100644index 00000000..2352e447--- /dev/null+++ b/apps/native/lib/worktree-cli.test.ts@@ -0,0 +1,29 @@+import { test } from "bun:test";+import assert from "node:assert/strict";+import { parseCreate, runCommand, sanitizeSlug, slugFromCheckout } from "./worktree-cli";++test("sanitizeSlug matches the engine's workspace names", () => {+ assert.equal(sanitizeSlug("tokyo"), "tokyo");+ assert.equal(sanitizeSlug(" task-a "), "task-a");+ assert.equal(sanitizeSlug("a/b"), null);+ assert.equal(sanitizeSlug(".."), null);+ assert.equal(sanitizeSlug(""), null);+});++test("parseCreate reads graff worktree create output", () => {+ const got = parseCreate(+ "✓ workspace tokyo\n path /repo/.graff/worktrees/tokyo\n branch worktree-tokyo\n copied 2 gitignored file(s)\n setup ok\n",+ );+ assert.deepEqual(got, {+ name: "tokyo",+ path: "/repo/.graff/worktrees/tokyo",+ branch: "worktree-tokyo",+ copied: 2,+ });+});++test("slugFromCheckout reads a task worktree folder", () => {+ assert.equal(slugFromCheckout("/repo/.graff/worktrees/tokyo"), "tokyo");+ assert.equal(slugFromCheckout("/repo"), null);+ assert.equal(runCommand("tokyo"), "graff worktree run tokyo");+});diff --git a/apps/native/lib/worktree-cli.ts b/apps/native/lib/worktree-cli.tsnew file mode 100644index 00000000..bcf05f94--- /dev/null+++ b/apps/native/lib/worktree-cli.ts@@ -0,0 +1,43 @@+import { existsSync } from "node:fs";+import path from "node:path";++export type CreateResult = {+ name: string;+ path: string;+ branch: string;+ copied: number;+};++/** Same binary the ACP route uses. */+export function graffBin(fromCwd = process.cwd()): string {+ const built = path.resolve(fromCwd, "../../zig-out/bin/graff");+ return process.env.GRAFF_BIN || (existsSync(built) ? built : "graff");+}++export function slugFromCheckout(checkout: string): string | null {+ const parts = checkout.replace(/\\/g, "/").split("/");+ const i = parts.lastIndexOf("worktrees");+ if (i >= 0 && parts[i - 1] === ".graff" && parts[i + 1]) return parts[i + 1];+ return null;+}++export function sanitizeSlug(raw: string): string | null {+ const t = raw.trim();+ if (!t || t.length > 64) return null;+ if (!/^[A-Za-z0-9._-]+$/.test(t)) return null;+ if (t === "." || t === "..") return null;+ return t;+}++export function parseCreate(stdout: string): CreateResult | null {+ const name = stdout.match(/^✓ workspace (\S+)/m)?.[1];+ const dest = stdout.match(/^ {2}path (.+)$/m)?.[1]?.trim();+ const branch = stdout.match(/^ {2}branch (\S+)/m)?.[1];+ if (!name || !dest || !branch) return null;+ const copied = Number(stdout.match(/^ {2}copied (\d+)/m)?.[1] ?? "0");+ return { name, path: dest, branch, copied };+}++export function runCommand(name: string): string {+ return `graff worktree run ${name}`;+}diff --git a/assets/skills/workspace.md b/assets/skills/workspace.mdindex 49dd3033..e7c566c4 100644--- a/assets/skills/workspace.md+++ b/assets/skills/workspace.md@@ -27,6 +27,11 @@ A new independent task is `workspace action=create`.from the remote base, then enter it. Optional `base` is a branch or commit(default `origin/main` after fetch). Independent work gets its own tree;same-branch collaboration stays in one workspace (`isolation: shared_cwd`).+ Create copies gitignored files matching `.worktreeinclude` (else+ `file_include_globs`, else `.env*`) from the main checkout, then runs+ `scripts.setup` from `.graff/workspace.toml` or `.conductor/settings.toml`.+ `graff worktree run <name>` is the run script; `archive` runs `scripts.archive`+ before removing a clean duplicate (ADR 0153). Desktop Tools: New task workspace, Run, Archive.4. 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 isdiff --git a/docs/adr/0146-concurrent-sessions-auto-isolate.md b/docs/adr/0146-concurrent-sessions-auto-isolate.mdindex 2b489c7a..e6393222 100644--- a/docs/adr/0146-concurrent-sessions-auto-isolate.md+++ b/docs/adr/0146-concurrent-sessions-auto-isolate.md@@ -37,4 +37,5 @@ Finish is not archive.The second concurrent agent never contends on the first agent's `index.lock`.A first session still owns the folder it started in. Experiment-pool pre-mint(ADR 0037) still skips mid-turn `worktree add` when seats are reserved.-Setup scripts stay #1123. Stale-tree reaping stays #1118.+Setup/run/archive scripts and `.worktreeinclude` copy are ADR 0153. Stale-tree+reaping stays #1118. Desktop review/merge-back stays #1124.diff --git a/docs/adr/0153-task-workspaces-copy-and-scripts.md b/docs/adr/0153-task-workspaces-copy-and-scripts.mdnew file mode 100644index 00000000..9bd6a16a--- /dev/null+++ b/docs/adr/0153-task-workspaces-copy-and-scripts.md@@ -0,0 +1,36 @@+# 0153. Task workspaces copy gitignored files and run project scripts++Status: accepted 2026-09-21++## Context++Raw `git worktree add` checks out tracked files only. Coding-agent workspaces+need the rest of a local project: `.env.local`, a one-time `pnpm install`, a+dev server, and teardown that is not "the agent finished a turn."++Conductor documents this as `.worktreeinclude` / Files to copy, plus+`scripts.setup` / `scripts.run` / `scripts.archive` in+`.conductor/settings.toml`. Finish is still not archive (ADR 0147): dirty or+unique-commit trees stay.++## Decision++- After `graff worktree create` / `workspace action=create` / auto-isolate,+ copy gitignored files from the **main checkout** that match `.worktreeinclude`+ (else `file_include_globs` in `.graff/workspace.toml` or+ `.conductor/settings.toml`, else `.env*`). Tracked files are already there.+ Untracked files that Git does not ignore are not copied.+- Then run `scripts.setup` from `.graff/workspace.toml`, falling back to+ `.conductor/settings.toml`. Setup failure keeps the workspace.+- `graff worktree run <name>` runs `scripts.run` from that checkout.+- `graff worktree archive` runs `scripts.archive` only when the tree is+ actually going to be removed.+- Scripts see `GRAFF_WORKSPACE_*` and Conductor aliases+ (`CONDUCTOR_WORKSPACE_NAME`, `CONDUCTOR_WORKSPACE_PATH`, `CONDUCTOR_ROOT_PATH`,+ `CONDUCTOR_PORT`) so an existing Conductor project file works.++## Consequences++A Conductor-configured repo is usable as a graff task workspace without a+second clone. Desktop review/merge-back UX stays #1124. Stale-tree reaping+stays #1118. Finish still does not archive.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 0505443e..57210333 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -174,6 +174,7 @@ record only when you need the evidence or the edge cases.| [0150](0150-subagent-briefs-are-structured.md) | Child briefs are headed sections plus a harness environment header; the judge stays a bare prompt. || [0151](0151-zai-coding-plan-login.md) | Z.AI Coding Plan is a `sub_login` like Kimi/xAI: `graff login zai` uses ZCode's public CLI OAuth broker, then provisions a Graff-named API key onto `/api/coding/paas/v4`. || [0152](0152-persistent-shells-snapshot-once.md) | Persistent shells snapshot immediately (`wait_ms` ignored) and stay on `/jobs`; do not poll. Finite jobs still wait until exit (ADR 0010). |+| [0153](0153-task-workspaces-copy-and-scripts.md) | Task workspaces copy gitignored include files from the main checkout and run setup/run/archive scripts (Conductor-shaped `.worktreeinclude` / `.conductor/settings.toml`). Finish is still not archive. |## When to write onediff --git a/src/cli.zig b/src/cli.zigindex 63bca8cc..c09cc5a9 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -335,6 +335,7 @@ pub const usage_text =\\ graff learn [help] local mutate/evaluate/promote/rollback engine\\ graff worktree list list -w tabs and experiment-pool trees (tagged)\\ graff worktree create <name> [base] mint a task workspace from the remote base (origin/main after fetch; optional base)+ \\ graff worktree run <name> run the workspace run script from that checkout\\ graff worktree archive <name> remove a clean duplicate checkout; dirty or unique-commit trees stay\\ graff worktree merge <name> squash-land worktree-<name> onto the current branch + clean up\\ graff worktree remove <name> discard worktree-<name> (drops its scratch work) + delete the branchdiff --git a/src/main.zig b/src/main.zigindex 10336d1d..ab01050a 100644--- a/src/main.zig+++ b/src/main.zig@@ -596,5 +596,5 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("subagent_recovery.zig");_ = @import("acp_agent_activity.zig");_ = @import("read_image.zig");- _ = .{ @import("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig"), @import("issue_cmd.zig"), @import("shell_tool.zig"), @import("acp_ask.zig"), @import("side_steer.zig"), @import("task_workspace_tests.zig") };+ _ = .{ @import("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig"), @import("issue_cmd.zig"), @import("shell_tool.zig"), @import("acp_ask.zig"), @import("side_steer.zig"), @import("task_workspace_tests.zig"), @import("workspace_prepare_tests.zig") };}diff --git a/src/task_workspace.zig b/src/task_workspace.zigindex 0f0c371a..df05bebb 100644--- a/src/task_workspace.zig+++ b/src/task_workspace.zig@@ -16,6 +16,7 @@ const main_mod = @import("main.zig");const tool_spill = @import("tool_spill.zig");const agent_worktree = @import("agent_worktree.zig");const worktree_prune = @import("worktree_prune.zig");+const workspace_prepare = @import("workspace_prepare.zig");pub const CreateError = error{ NotAGitRepo, InvalidName, NameCollision, CreateFailed, Unsupported };pub const ArchiveError = error{ InvalidName, NotFound, ArchiveFailed };@@ -45,6 +46,9 @@ pub const Workspace = struct {path: []const u8,branch: []const u8,base: []const u8 = "",+ copied: usize = 0,+ setup_ran: bool = false,+ setup_ok: bool = true,};pub const AutoOpts = struct {@@ -233,11 +237,15 @@ pub fn create(gpa: Allocator, io: Io, arena: Allocator, opts: CreateOpts) (Creatconst base = resolveCreateBase(gpa, io, arena, opts.cwd, opts.base);try mintOnce(gpa, io, arena, opts.cwd, named.path, named.branch, base);const path = try absPath(io, arena, dest);+ const prep = workspace_prepare.afterCreate(gpa, io, arena, opts.cwd, path, named.name);return .{.name = named.name,.path = path,.branch = named.branch,.base = readHead(gpa, io, arena, path),+ .copied = prep.copied,+ .setup_ran = prep.setup_ran,+ .setup_ok = prep.setup_ok,};}@@ -280,6 +288,7 @@ pub fn archive(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8, slug:const contained = ranOk(refs) and worktree_prune.containedElsewhere(refs.stdout, own);const reason = agent_worktree.worktreeKeepReason(ranOk(st), st.stdout, worktree_prune.containmentBase(head, contained), head);if (reason != .removed) return .{ .removed = false, .reason = reason, .path = path, .branch = named.branch };+ workspace_prepare.beforeArchive(gpa, io, arena, cwd, path, named.name);if (runCapped(gpa, io, &.{ "git", "-C", cwd, "worktree", "remove", dest }, 8192, 8192, 30_000)) |r| {defer {gpa.free(r.stdout);diff --git a/src/workspace_prepare.zig b/src/workspace_prepare.zignew file mode 100644index 00000000..74c4f4e7--- /dev/null+++ b/src/workspace_prepare.zig@@ -0,0 +1,239 @@+//! After minting a task worktree: copy selected gitignored files and run+//! project scripts. Same shape as Conductor (`.worktreeinclude`, setup/run/+//! archive) without taking Conductor's product surface.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const gitignore = @import("gitignore.zig");+const process_runner = @import("process_runner.zig");+const runCapped = process_runner.runCapped;+const runCappedWithOptions = process_runner.runCappedWithOptions;+const ranOk = process_runner.ranOk;+const worktree_lease = @import("worktree_lease.zig");+const worktree_prune = @import("worktree_prune.zig");++const max_copy_bytes: std.Io.Limit = .limited(1 << 20);+const max_walk: usize = 4000;+const max_copies: usize = 256;+const setup_ms: u64 = 10 * 60 * 1000;+const archive_ms: u64 = 60 * 1000;+const run_ms: u64 = 0; // wait until exit (jobs cap)++pub const Scripts = struct {+ setup: []const u8 = "",+ run: []const u8 = "",+ archive: []const u8 = "",+};++pub const Report = struct {+ copied: usize = 0,+ setup_ran: bool = false,+ setup_ok: bool = true,+};++pub fn mainCheckout(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8) []const u8 {+ const common = worktree_lease.gitCommonDirAt(gpa, io, arena, cwd);+ const main_path = worktree_prune.mainWorktreePath(common);+ if (main_path.len > 0) return main_path;+ return cwd;+}++pub fn parseScripts(text: []const u8) Scripts {+ return .{+ .setup = tomlString(text, "setup") orelse "",+ .run = tomlString(text, "run") orelse "",+ .archive = tomlString(text, "archive") orelse "",+ };+}++pub fn parseIncludeGlobs(text: []const u8) ?[]const u8 {+ return tomlString(text, "file_include_globs");+}++/// `.worktreeinclude` wins; else `file_include_globs`; else `.env*`.+pub fn includeText(arena: Allocator, io: Io, root: []const u8) []const u8 {+ if (readOptional(io, arena, root, ".worktreeinclude")) |t| return t;+ if (readOptional(io, arena, root, ".graff/workspace.toml")) |t| {+ if (parseIncludeGlobs(t)) |g| return g;+ }+ if (readOptional(io, arena, root, ".conductor/settings.toml")) |t| {+ if (parseIncludeGlobs(t)) |g| return g;+ }+ return ".env*\n.env\n";+}++pub fn loadScripts(arena: Allocator, io: Io, root: []const u8) Scripts {+ if (readOptional(io, arena, root, ".graff/workspace.toml")) |t| {+ const s = parseScripts(t);+ if (s.setup.len + s.run.len + s.archive.len > 0) return s;+ }+ if (readOptional(io, arena, root, ".conductor/settings.toml")) |t| return parseScripts(t);+ return .{};+}++pub fn afterCreate(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8, dest: []const u8, name: []const u8) Report {+ const root = mainCheckout(gpa, io, arena, cwd);+ var report: Report = .{};+ report.copied = copyIgnored(gpa, io, arena, root, dest);+ const scripts = loadScripts(arena, io, root);+ if (scripts.setup.len == 0) return report;+ report.setup_ran = true;+ report.setup_ok = runScript(gpa, io, arena, scripts.setup, dest, root, name, setup_ms);+ return report;+}++pub fn beforeArchive(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8, dest: []const u8, name: []const u8) void {+ const root = mainCheckout(gpa, io, arena, cwd);+ const scripts = loadScripts(arena, io, root);+ if (scripts.archive.len == 0) return;+ _ = runScript(gpa, io, arena, scripts.archive, dest, root, name, archive_ms);+}++pub fn runNamed(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8, dest: []const u8, name: []const u8) bool {+ const root = mainCheckout(gpa, io, arena, cwd);+ const scripts = loadScripts(arena, io, root);+ if (scripts.run.len == 0) return false;+ return runScript(gpa, io, arena, scripts.run, dest, root, name, run_ms);+}++pub fn workspacePort(name: []const u8) u16 {+ var h: u32 = 2166136261;+ for (name) |c| h = (h ^ c) *% 16777619;+ return @intCast(40_000 + h % 10_000);+}++fn tomlString(text: []const u8, key: []const u8) ?[]const u8 {+ var i: usize = 0;+ while (i + key.len + 1 < text.len) : (i += 1) {+ if (!std.mem.eql(u8, text[i .. i + key.len], key)) continue;+ if (i > 0) {+ const prev = text[i - 1];+ if (std.ascii.isAlphanumeric(prev) or prev == '_' or prev == '.') continue;+ }+ var j = i + key.len;+ while (j < text.len and (text[j] == ' ' or text[j] == '\t')) j += 1;+ if (j >= text.len or text[j] != '=') continue;+ j += 1;+ while (j < text.len and (text[j] == ' ' or text[j] == '\t')) j += 1;+ if (j + 2 < text.len and std.mem.eql(u8, text[j .. j + 3], "\"\"\"")) {+ const start = j + 3;+ const end = std.mem.indexOfPos(u8, text, start, "\"\"\"") orelse return null;+ return std.mem.trim(u8, text[start..end], "\r\n");+ }+ if (j < text.len and text[j] == '"') {+ const start = j + 1;+ const end = std.mem.indexOfScalarPos(u8, text, start, '"') orelse return null;+ return text[start..end];+ }+ }+ return null;+}++fn readOptional(io: Io, arena: Allocator, root: []const u8, rel: []const u8) ?[]const u8 {+ const path = std.fs.path.join(arena, &.{ root, rel }) catch return null;+ return Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 * 1024)) catch null;+}++fn skipName(name: []const u8) bool {+ const names = [_][]const u8{ ".git", "node_modules", "zig-out", "zig-cache", ".next", "dist", "target", ".graff", ".worktrees" };+ for (names) |n| if (std.mem.eql(u8, name, n)) return true;+ return false;+}++fn gitIgnored(gpa: Allocator, io: Io, root: []const u8, rel: []const u8) bool {+ const r = runCapped(gpa, io, &.{ "git", "-C", root, "check-ignore", "-q", "--", rel }, 256, 256, 15_000) catch return false;+ defer {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ }+ return ranOk(r);+}++fn copyFile(io: Io, arena: Allocator, src: []const u8, dest: []const u8) bool {+ if ((Io.Dir.cwd().statFile(io, dest, .{}) catch null) != null) return false;+ const data = Io.Dir.cwd().readFileAlloc(io, src, arena, max_copy_bytes) catch return false;+ if (std.fs.path.dirname(dest)) |dir| Io.Dir.cwd().createDirPath(io, dir) catch return false;+ Io.Dir.cwd().writeFile(io, .{ .sub_path = dest, .data = data }) catch return false;+ return true;+}++fn copyIgnored(gpa: Allocator, io: Io, arena: Allocator, src_root: []const u8, dest_root: []const u8) usize {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const abs_n = Io.Dir.cwd().realPathFile(io, src_root, &buf) catch 0;+ const src = if (abs_n > 0) arena.dupe(u8, buf[0..abs_n]) catch src_root else src_root;+ const include = includeText(arena, io, src);+ const rules = gitignore.parse(arena, include, src) catch return 0;+ var n: usize = 0;+ var walked: usize = 0;+ walkCopy(gpa, io, arena, src, dest_root, src, rules, &n, &walked) catch {};+ return n;+}++fn walkCopy(+ gpa: Allocator,+ io: Io,+ arena: Allocator,+ src_root: []const u8,+ dest_root: []const u8,+ dir_abs: []const u8,+ rules: []const gitignore.Rule,+ n: *usize,+ walked: *usize,+) !void {+ if (n.* >= max_copies or walked.* >= max_walk) return;+ var dir = Io.Dir.cwd().openDir(io, dir_abs, .{ .iterate = true, .follow_symlinks = false }) catch return;+ defer dir.close(io);+ var it = dir.iterate();+ while (it.next(io) catch null) |ent| {+ if (ent.kind == .sym_link) continue;+ if (skipName(ent.name)) continue;+ walked.* += 1;+ if (walked.* > max_walk or n.* >= max_copies) return;+ const child = try std.fs.path.join(arena, &.{ dir_abs, ent.name });+ const rel = gitignore.relTo(child, src_root) orelse continue;+ if (std.mem.startsWith(u8, rel, ".graff/worktrees/") or std.mem.startsWith(u8, rel, ".worktrees/")) continue;+ if (ent.kind == .directory) {+ try walkCopy(gpa, io, arena, src_root, dest_root, child, rules, n, walked);+ continue;+ }+ if (ent.kind != .file) continue;+ switch (try gitignore.verdict(arena, rules, child, false)) {+ .ignore => {},+ else => continue,+ }+ if (!gitIgnored(gpa, io, src_root, rel)) continue;+ const dest = try std.fs.path.join(arena, &.{ dest_root, rel });+ if (copyFile(io, arena, child, dest)) n.* += 1;+ }+}++fn runScript(+ gpa: Allocator,+ io: Io,+ arena: Allocator,+ cmd: []const u8,+ dest: []const u8,+ root: []const u8,+ name: []const u8,+ deadline_ms: u64,+) bool {+ const port = workspacePort(name);+ const n1 = std.fmt.allocPrint(arena, "GRAFF_WORKSPACE_NAME={s}", .{name}) catch return false;+ const n2 = std.fmt.allocPrint(arena, "GRAFF_WORKSPACE_PATH={s}", .{dest}) catch return false;+ const n3 = std.fmt.allocPrint(arena, "GRAFF_ROOT_PATH={s}", .{root}) catch return false;+ const n4 = std.fmt.allocPrint(arena, "CONDUCTOR_WORKSPACE_NAME={s}", .{name}) catch return false;+ const n5 = std.fmt.allocPrint(arena, "CONDUCTOR_WORKSPACE_PATH={s}", .{dest}) catch return false;+ const n6 = std.fmt.allocPrint(arena, "CONDUCTOR_ROOT_PATH={s}", .{root}) catch return false;+ const n7 = std.fmt.allocPrint(arena, "CONDUCTOR_PORT={d}", .{port}) catch return false;+ const n8 = std.fmt.allocPrint(arena, "GRAFF_WORKSPACE_PORT={d}", .{port}) catch return false;+ const r = runCappedWithOptions(gpa, io, &.{+ "env", n1, n2, n3, n4, n5, n6, n7, n8, "/bin/sh", "-c", cmd,+ }, 64 * 1024, 16 * 1024, deadline_ms, .{ .cwd = .{ .path = dest } }) catch return false;+ defer {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ }+ return ranOk(r);+}diff --git a/src/workspace_prepare_tests.zig b/src/workspace_prepare_tests.zignew file mode 100644index 00000000..eb33fc10--- /dev/null+++ b/src/workspace_prepare_tests.zig@@ -0,0 +1,110 @@+//! Isolation tests for `workspace_prepare.zig`.+const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;++const prep = @import("workspace_prepare.zig");+const ws = @import("task_workspace.zig");+const process_runner = @import("process_runner.zig");+const runCapped = process_runner.runCapped;+const ranOk = process_runner.ranOk;++test "parseScripts reads Conductor and graff toml" {+ const s = prep.parseScripts(+ \\[scripts]+ \\setup = "pnpm install"+ \\run = "pnpm dev --port $CONDUCTOR_PORT"+ \\archive = "./script/workspace-archive.sh"+ \\+ );+ try std.testing.expectEqualStrings("pnpm install", s.setup);+ try std.testing.expectEqualStrings("pnpm dev --port $CONDUCTOR_PORT", s.run);+ try std.testing.expectEqualStrings("./script/workspace-archive.sh", s.archive);+ const globs = prep.parseIncludeGlobs(+ \\file_include_globs = """+ \\.env.local+ \\certs/local/**+ \\"""+ \\+ ) orelse return error.TestUnexpectedResult;+ try std.testing.expect(std.mem.indexOf(u8, globs, ".env.local") != null);+ try std.testing.expect(std.mem.indexOf(u8, globs, "certs/local/**") != null);+}++test "workspacePort is stable per name and stays in 40000-49999" {+ const a = prep.workspacePort("tokyo");+ const b = prep.workspacePort("tokyo");+ const c = prep.workspacePort("warsaw");+ try std.testing.expectEqual(a, b);+ try std.testing.expect(a != c);+ try std.testing.expect(a >= 40_000 and a < 50_000);+ try std.testing.expect(c >= 40_000 and c < 50_000);+}++test "create copies gitignored include files and runs setup" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ const a = std.testing.allocator;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const tmp_root = try tmp.dir.realPathFileAlloc(io, ".", a);+ defer a.free(tmp_root);+ const root = try std.fmt.allocPrint(a, "{s}/repo", .{tmp_root});+ defer a.free(root);+ try Io.Dir.cwd().createDirPath(io, root);+ try git(io, a, &.{ "init", "-q", "-b", "main", root });+ try git(io, a, &.{ "-C", root, "config", "user.email", "t@t" });+ try git(io, a, &.{ "-C", root, "config", "user.name", "t" });+ try write(io, root, "f", "x\n");+ try write(io, root, ".gitignore", ".env.local\ntracked-secret\nscratch.txt\n");+ try write(io, root, ".worktreeinclude", ".env.local\n");+ try write(io, root, ".env.local", "SECRET=1\n");+ try write(io, root, "scratch.txt", "nope\n");+ try write(io, root, ".graff/workspace.toml",+ \\[scripts]+ \\setup = "printf ready > .graff-setup"+ \\archive = "printf gone > ../archive-ran"+ \\+ );+ try git(io, a, &.{ "-C", root, "add", "f", ".gitignore", ".worktreeinclude", ".graff/workspace.toml" });+ try git(io, a, &.{ "-C", root, "commit", "-m", "i" });++ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const ar = arena.allocator();+ const one = try ws.create(a, io, ar, .{ .slug = "tokyo", .cwd = root });+ try std.testing.expect(one.copied >= 1);+ try std.testing.expect(one.setup_ran);+ try std.testing.expect(one.setup_ok);+ const copied = try std.fs.path.join(a, &.{ one.path, ".env.local" });+ defer a.free(copied);+ const body = try Io.Dir.cwd().readFileAlloc(io, copied, a, .limited(64));+ defer a.free(body);+ try std.testing.expectEqualStrings("SECRET=1\n", body);+ const skipped = try std.fs.path.join(a, &.{ one.path, "scratch.txt" });+ defer a.free(skipped);+ try std.testing.expect((Io.Dir.cwd().statFile(io, skipped, .{}) catch null) == null);+ const setup_mark = try std.fs.path.join(a, &.{ one.path, ".graff-setup" });+ defer a.free(setup_mark);+ const mark = try Io.Dir.cwd().readFileAlloc(io, setup_mark, a, .limited(64));+ defer a.free(mark);+ try std.testing.expectEqualStrings("ready", mark);+}++fn write(io: Io, root: []const u8, rel: []const u8, data: []const u8) !void {+ const path = try std.fs.path.join(std.testing.allocator, &.{ root, rel });+ defer std.testing.allocator.free(path);+ if (std.fs.path.dirname(path)) |dir| try Io.Dir.cwd().createDirPath(io, dir);+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = data });+}++fn git(io: Io, a: std.mem.Allocator, argv: []const []const u8) !void {+ var args: std.ArrayList([]const u8) = .empty;+ defer args.deinit(a);+ try args.append(a, "git");+ try args.appendSlice(a, argv);+ const r = try runCapped(a, io, args.items, 4096, 4096, 15_000);+ defer a.free(r.stdout);+ defer a.free(r.stderr);+ try std.testing.expect(ranOk(r));+}diff --git a/src/worktree_cmd.zig b/src/worktree_cmd.zigindex 16a698ee..677a4c9f 100644--- a/src/worktree_cmd.zig+++ b/src/worktree_cmd.zig@@ -1,4 +1,4 @@-//! `graff worktree <list|merge|remove|prune>` and the per-turn worktree+//! `graff worktree <list|create|run|archive|merge|remove|prune>` and the per-turn worktree//! checkpoint commit for `-w` sessions. Moved out of jobs.zig (600-line cap)//! when the background-job pool grew its idle lifecycle (#199); jobs.zig//! re-exports both entry points, so callers are unchanged.@@ -177,6 +177,32 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [return;};try out.print("✓ workspace {s}\n path {s}\n branch {s}\n", .{ wt.name, wt.path, wt.branch });+ if (wt.copied > 0) try out.print(" copied {d} gitignored file(s)\n", .{wt.copied});+ if (wt.setup_ran) try out.print(" setup {s}\n", .{if (wt.setup_ok) "ok" else "failed (workspace kept)"});+ return;+ }++ if (std.mem.eql(u8, action, "run")) {+ const name = if (args.len > 1) args[1] else "";+ if (name.len == 0) {+ try out.writeAll("usage: graff worktree run <name>\n");+ return;+ }+ const dest = try std.fmt.allocPrint(arena, ".graff/worktrees/{s}", .{name});+ if ((Io.Dir.cwd().statFile(io, dest, .{}) catch null) == null) {+ try out.print("✗ no such task workspace {s} — `graff worktree list`\n", .{name});+ return;+ }+ const path = blk: {+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = Io.Dir.cwd().realPathFile(io, dest, &path_buf) catch 0;+ break :blk if (n > 0) try arena.dupe(u8, path_buf[0..n]) else dest;+ };+ if (!@import("workspace_prepare.zig").runNamed(gpa, io, arena, ".", path, name)) {+ try out.writeAll("✗ no run script — add scripts.run to .graff/workspace.toml or .conductor/settings.toml\n");+ return;+ }+ try out.print("✓ run finished in {s}\n", .{path});return;}@@ -204,7 +230,7 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [return worktree_prune.pruneCommand(gpa, io, arena, out, args[1..]);}- try out.print("unknown worktree command '{s}' — use: graff worktree list | create <name> [base] | archive <name> | merge <name> | remove <name> | prune [older-than <days>]\n", .{action});+ try out.print("unknown worktree command '{s}' — use: graff worktree list | create <name> [base] | run <name> | archive <name> | merge <name> | remove <name> | prune [older-than <days>]\n", .{action});}test { // split-out module: unreferenced, its tests silently never run