Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
Merge upstream main into the session worktree isolation branch
renwanga8669a04468b2
diff --cc apps/desktop/electron/main/ipc/worktree-ipc.tsindex ed289415a,000000000..f7c1ce765mode 100644,000000..100644--- a/apps/desktop/electron/main/ipc/worktree-ipc.ts+++ b/apps/desktop/electron/main/ipc/worktree-ipc.ts@@@ -1,127 -1,0 +1,127 @@@+/**- * Isolated-session worktree channels (ADR 0328).++ * Isolated-session worktree channels (ADR 0329).+ *+ * A thin pass-through to host-core's `worktree.*` methods: host-core owns every+ * git command and every worktree path. The renderer names a session or a+ * project and never receives a worktree path; "Reveal" resolves the path here+ * and hands it straight to the OS file manager.+ */+import { ErrorCodes, IPC } from "@pi-desktop/shared";+import type { HostProcess } from "../host-process";+import type { Logger } from "../logger";+import type { IpcRegistrar } from "./types";++export type WorktreeIpcDependencies = {+ registrar: IpcRegistrar;+ getHost: () => HostProcess | null;+ logger: Pick<Logger, "app">;+ openPath: (path: string) => Promise<string>;+ stripWinLongPrefix: (path: string) => string;+};++function requiredText(input: unknown, field: string): string {+ const value =+ input && typeof input === "object" ? (input as Record<string, unknown>)[field] : undefined;+ const text = typeof value === "string" ? value.trim() : "";+ if (!text) {+ throw Object.assign(new Error(`${field} required`), {+ errorCode: ErrorCodes.INVALID_ARGUMENT,+ });+ }+ return text;+}++export function registerWorktreeIpc({+ registrar,+ getHost,+ logger,+ openPath,+ stripWinLongPrefix,+}: WorktreeIpcDependencies): void {+ const host = (): HostProcess => {+ const current = getHost();+ if (!current) throw new Error("host unavailable");+ return current;+ };++ registrar.handle(IPC.invoke.worktreeProbe, async (input: unknown) =>+ host().call("worktree.probe", { projectPath: requiredText(input, "projectPath") }),+ );++ registrar.handle(IPC.invoke.worktreePreview, async (input: unknown) => {+ const result = await host().call<{ preview: unknown }>("worktree.preview", {+ sessionId: requiredText(input, "sessionId"),+ });+ return result.preview;+ });++ registrar.handle(IPC.invoke.worktreeMerge, async (input: unknown) => {+ const sessionId = requiredText(input, "sessionId");+ const result = await host().call<{ outcome: unknown }>("worktree.merge", {+ sessionId,+ previewToken: requiredText(input, "previewToken"),+ });+ logger.app("session", "info", "isolated session merged into project", { sessionId });+ return result.outcome;+ });++ registrar.handle(IPC.invoke.worktreeBehind, async (input: unknown) => {+ const result = await host().call<{ commits: number }>("worktree.behind", {+ sessionId: requiredText(input, "sessionId"),+ });+ return result.commits;+ });++ registrar.handle(IPC.invoke.worktreeBehindAll, async () =>+ host().call("worktree.behindAll", {}),+ );++ registrar.handle(IPC.invoke.worktreeSync, async (input: unknown) => {+ const sessionId = requiredText(input, "sessionId");+ const result = await host().call<{ outcome: unknown }>("worktree.sync", { sessionId });+ logger.app("session", "info", "isolated session synced from project", { sessionId });+ return result.outcome;+ });++ registrar.handle(IPC.invoke.worktreePendingWork, async (input: unknown) => {+ const result = await host().call<{ pending: unknown }>("worktree.pendingWork", {+ sessionId: requiredText(input, "sessionId"),+ });+ return result.pending;+ });++ registrar.handle(IPC.invoke.worktreeSetupLog, async (input: unknown) =>+ host().call("worktree.setupLog", { sessionId: requiredText(input, "sessionId") }),+ );++ registrar.handle(IPC.invoke.worktreeReveal, async (input: unknown) => {+ const result = await host().call<{ path: string }>("worktree.location", {+ sessionId: requiredText(input, "sessionId"),+ });+ const openError = await openPath(stripWinLongPrefix(result.path));+ if (openError) throw new Error(openError);+ return { ok: true };+ });++ registrar.handle(IPC.invoke.worktreeSetupCommandGet, async (input: unknown) =>+ host().call("worktree.setupCommand.get", {+ projectPath: requiredText(input, "projectPath"),+ }),+ );++ registrar.handle(IPC.invoke.worktreeSetupCommandSet, async (input: unknown) => {+ const command =+ input && typeof input === "object"+ ? (input as Record<string, unknown>).command+ : undefined;+ if (command !== undefined && command !== null && typeof command !== "string") {+ throw Object.assign(new Error("command must be a string"), {+ errorCode: ErrorCodes.INVALID_ARGUMENT,+ });+ }+ return host().call("worktree.setupCommand.set", {+ projectPath: requiredText(input, "projectPath"),+ command: typeof command === "string" ? command : null,+ });+ });+}diff --cc apps/desktop/electron/main/runtime/session-launch.tsindex a44f86cdb,70a5c0471..3461c2e70--- a/apps/desktop/electron/main/runtime/session-launch.ts+++ b/apps/desktop/electron/main/runtime/session-launch.ts@@@ -421,16 -402,7 +421,16 @@@ export function createSessionLaunchRunt? session.projectPath.trim(): undefined;const localInstructionRoot = remoteWorkspace ? undefined : projectPath;- // ADR 0328: an isolated session reads and writes files in its worktree.- let projectInstructions = await loadInstructionChain(localInstructionRoot);++ // ADR 0329: an isolated session reads and writes files in its worktree.+ // `projectPath` stays the project identity (memory, skills, plugins, MCP,+ // subagents, group context); only files follow `workspaceRoot`. Remote+ // workspaces are never isolated.+ const workspaceRoot = remoteWorkspace+ ? undefined+ : await isolatedWorkspaceRoot(sessionId, session);+ let projectInstructions = await loadInstructionChain(+ remoteWorkspace ? undefined : (workspaceRoot ?? projectPath),+ );if (remoteWorkspace) {projectInstructions = await loadRemoteWorkspaceInstructions(remoteBoot!.workspaceFiles, remoteWorkspace, projectInstructions,@@@ -450,9 -422,7 +450,9 @@@} | null;}>("project.group.context", { path: projectPath });const groupRoots = result.context?.roots ?? [];- const groupRootGuide = groupRoots.length > 1+ // An isolated session's root is its worktree; the group's other roots- // are outside it and are not advertised (ADR 0328).++ // are outside it and are not advertised (ADR 0329).+ const groupRootGuide = !workspaceRoot && groupRoots.length > 1? [`Primary root: ${groupRoots[0]?.path ?? projectPath}`,...groupRoots.slice(1).map((root) => `Additional root: ${root.path}`),diff --cc apps/desktop/electron/main/runtime/sidecar.tsindex 15d026c63,9edc060ae..f032fb8e2--- a/apps/desktop/electron/main/runtime/sidecar.ts+++ b/apps/desktop/electron/main/runtime/sidecar.ts@@@ -364,31 -364,12 +364,31 @@@ export function createSidecarRuntime(const s = new AgentSidecar((text) => logger.child("agent", text));wireSidecar(s);- s.setProjectInstructionResolver(async ({ projectPath, path }) => {+ // The directory a session's file tools work in: its isolated worktree- // (ADR 0328), resolved by host-core from its own registry, or its project.++ // (ADR 0329), resolved by host-core from its own registry, or its project.+ const sessionFileRoot = async (sessionId: string): Promise<string | null> => {+ const host = runtimeState.host;+ if (!host) return null;+ const res = await host.call<{+ session: { projectPath?: string; worktree?: unknown } | null;+ }>("session.get", { id: sessionId });+ if (res?.session?.worktree) {+ const location = await host.call<{ path?: string }>("worktree.location", { sessionId });+ return location.path?.trim() || null;+ }+ return res?.session?.projectPath?.trim() || null;+ };+ s.setProjectInstructionResolver(async ({ sessionId, projectPath, path }) => {// The root is registered by Electron main from the host-owned session// record. The sidecar can provide a target path, never an arbitrary root.const instructions = projectPath?.startsWith("remote-project:")? await loadInstructionChain(undefined) : await loadInstructionChain(projectPath, path);if (!projectPath || !runtimeState.host) return instructions;- // An isolated session registers its worktree as the root (ADR 0328); the++ // An isolated session registers its worktree as the root (ADR 0329); the+ // group context stays keyed by the session's project, and the group's+ // other roots are not advertised inside the worktree.+ const project = sessionProjects.get(sessionId) ?? projectPath;+ const isolated = project !== projectPath;try {const result = await runtimeState.host.call<{context?: {diff --cc apps/desktop/src/components/Sidebar.tsxindex 94f263981,0665f25cf..da63090e9--- a/apps/desktop/src/components/Sidebar.tsx+++ b/apps/desktop/src/components/Sidebar.tsx@@@ -2587,10 -2621,9 +2643,11 @@@ export function Sidebar(onOpenSession={openSessionFromHover}keepVisible={keepSessionHoverCardVisible}scheduleHide={scheduleSessionHoverCardHide}+ registerDismissGuard={registerSessionHoverCardDismissGuard}/>) : null}+ <WorktreeDialogs />+ <WorktreeBehindWatcher />{renameFor ? (<SessionRenameDialogsession={renameFor}diff --cc apps/desktop/src/features/worktree/WorktreeBehind.tsxindex 904aaa870,000000000..23686f6c7mode 100644,000000..100644--- a/apps/desktop/src/features/worktree/WorktreeBehind.tsx+++ b/apps/desktop/src/features/worktree/WorktreeBehind.tsx@@@ -1,85 -1,0 +1,85 @@@+import { useEffect } from "react";+import { useTranslation } from "react-i18next";+import type { SessionSummary } from "@pi-desktop/shared";+import { Badge } from "../../components/ui";+import { api } from "../../lib/api";+import { useAppStore } from "../../stores/app-store";+import { useWorktreeUi } from "./worktree-ui-store";++/** A refocused window re-reads the counts at most this often. */+export const BEHIND_FOCUS_REFRESH_MS = 15_000;++/**+ * Changes whenever an isolated session appears, goes away, changes status, or+ * finishes a turn: the moments its "behind" count can change from inside the+ * app. Commits made outside the app are picked up on window focus.+ */+export function isolatedSessionsKey(sessions: readonly SessionSummary[]): string {+ return sessions+ .filter((session) => session.worktree && session.worktree.status !== "missing")+ .map((session) => `${session.id}:${session.worktree?.status}:${session.updatedAt}`)+ .sort()+ .join("|");+}++/**- * Keeps the per-session "behind" counts current (ADR 0328). The sidebar list++ * Keeps the per-session "behind" counts current (ADR 0329). The sidebar list+ * never waits for git: the counts are read in the background and the marker+ * appears when they arrive. Renders nothing.+ */+export function WorktreeBehindWatcher() {+ const key = useAppStore((s) => isolatedSessionsKey(s.sessions));+ const revision = useWorktreeUi((s) => s.behindRevision);+ const refreshBehind = useWorktreeUi((s) => s.refreshBehind);++ useEffect(() => {+ const { setBehind } = useWorktreeUi.getState();+ if (!key) {+ setBehind({});+ return;+ }+ // A slower, older answer never overwrites a newer one.+ let current = true;+ api+ .getWorktreeBehindAll()+ .then((result) => {+ if (!current) return;+ setBehind(result.counts);+ // A conflict resolved outside the app cleared its badge on the host.+ if (result.statusesChanged) void useAppStore.getState().refreshSessions();+ })+ .catch(() => undefined);+ return () => {+ current = false;+ };+ }, [key, revision]);++ useEffect(() => {+ let last = Date.now();+ const onFocus = () => {+ if (Date.now() - last < BEHIND_FOCUS_REFRESH_MS) return;+ last = Date.now();+ refreshBehind();+ };+ window.addEventListener("focus", onFocus);+ return () => window.removeEventListener("focus", onFocus);+ }, [refreshBehind]);++ return null;+}++/** "↓2" next to the badge of a session that lacks project commits. */+export function WorktreeBehindMarker({ sessionId }: { sessionId: string }) {+ const { t } = useTranslation();+ const count = useWorktreeUi((s) => s.behind[sessionId] ?? 0);+ if (count <= 0) return null;+ return (+ <span+ className="thread-item-worktree"+ title={t("worktree.badge.behindTitle", { count })}+ data-worktree-behind={count}+ >+ <Badge tone="neutral">{t("worktree.badge.behind", { count })}</Badge>+ </span>+ );+}diff --cc apps/desktop/src/features/worktree/worktree-ui-store.tsindex 7eed2d3f1,000000000..e656657c5mode 100644,000000..100644--- a/apps/desktop/src/features/worktree/worktree-ui-store.ts+++ b/apps/desktop/src/features/worktree/worktree-ui-store.ts@@@ -1,36 -1,0 +1,36 @@@+import { create } from "zustand";+- /** The one worktree dialog that is open, if any (ADR 0328). */++/** The one worktree dialog that is open, if any (ADR 0329). */+export type WorktreeDialog =+ | { kind: "merge"; sessionId: string; title: string }+ | { kind: "setupLog"; sessionId: string; title: string }+ | { kind: "setupCommand"; projectPath: string; projectName: string };++type WorktreeUiState = {+ dialog: WorktreeDialog | null;+ open: (dialog: WorktreeDialog) => void;+ close: () => void;+ /** Project commits each isolated session lacks, for the sidebar marker. */+ behind: Record<string, number>;+ setBehind: (counts: Record<string, number>) => void;+ setBehindFor: (sessionId: string, count: number) => void;+ /** Bumped after a merge or sync so the counts are read again. */+ behindRevision: number;+ refreshBehind: () => void;+};++/**+ * Dialog and "behind" state shared by the sidebar parts of isolated sessions.+ * Kept out of the central app store on purpose.+ */+export const useWorktreeUi = create<WorktreeUiState>((set) => ({+ dialog: null,+ open: (dialog) => set({ dialog }),+ close: () => set({ dialog: null }),+ behind: {},+ setBehind: (counts) => set({ behind: counts }),+ setBehindFor: (sessionId, count) =>+ set((state) => (state.behind[sessionId] === count ? state : { behind: { ...state.behind, [sessionId]: count } })),+ behindRevision: 0,+ refreshBehind: () => set((state) => ({ behindRevision: state.behindRevision + 1 })),+}));diff --cc apps/desktop/src/lib/api.tsindex d80dbc48b,b6fa7423c..476b42ecc--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@@ -351,12 -343,6 +351,12 @@@ async function invoke<T>(channel: strinreturn result.data;}+/** `session.create` input: summary fields plus the isolation switch. */+export type CreateSessionInput = Partial<SessionSummary> & {- /** Run the session in its own git worktree (ADR 0328). */++ /** Run the session in its own git worktree (ADR 0329). */+ isolated?: boolean;+};+function normalizeSession(session: SessionSummary): SessionSummary {return {...safeSessionSummary(session),@@@ -617,34 -603,10 +617,34 @@@ export const api =...result,sessions: result.sessions.map(normalizeSession),})),- createSession: (input?: Partial<SessionSummary>) =>- invoke<{ session: SessionSummary }>(IPC.invoke.sessionCreate, input ?? {}).then(- (result) => ({ ...result, session: normalizeSession(result.session) }),- ),+ createSession: (input?: CreateSessionInput) =>+ invoke<{ session: SessionSummary; worktree?: CreatedSessionWorktree }>(+ IPC.invoke.sessionCreate,+ input ?? {},+ ).then((result) => ({ ...result, session: normalizeSession(result.session) })),- /** Isolated sessions in git worktrees (ADR 0328). No call returns a path. */++ /** Isolated sessions in git worktrees (ADR 0329). No call returns a path. */+ probeWorktree: (projectPath: string) =>+ invoke<WorktreeProbeResult>(IPC.invoke.worktreeProbe, { projectPath }),+ previewWorktreeMerge: (sessionId: string) =>+ invoke<WorktreeMergePreview>(IPC.invoke.worktreePreview, { sessionId }),+ mergeWorktree: (sessionId: string, previewToken: string) =>+ invoke<WorktreeMergeOutcome>(IPC.invoke.worktreeMerge, { sessionId, previewToken }),+ getWorktreeBehind: (sessionId: string) =>+ invoke<number>(IPC.invoke.worktreeBehind, { sessionId }),+ /** Project commits each isolated session lacks, keyed by session id. */+ getWorktreeBehindAll: () => invoke<WorktreeBehindCounts>(IPC.invoke.worktreeBehindAll),+ syncWorktree: (sessionId: string) =>+ invoke<WorktreeSyncOutcome>(IPC.invoke.worktreeSync, { sessionId }),+ getWorktreePendingWork: (sessionId: string) =>+ invoke<WorktreePendingWork>(IPC.invoke.worktreePendingWork, { sessionId }),+ getWorktreeSetupLog: (sessionId: string) =>+ invoke<WorktreeSetupLog>(IPC.invoke.worktreeSetupLog, { sessionId }),+ revealWorktree: (sessionId: string) =>+ invoke<{ ok: boolean }>(IPC.invoke.worktreeReveal, { sessionId }),+ getWorktreeSetupCommand: (projectPath: string) =>+ invoke<{ command: string | null }>(IPC.invoke.worktreeSetupCommandGet, { projectPath }),+ setWorktreeSetupCommand: (projectPath: string, command: string | null) =>+ invoke<{ ok: boolean }>(IPC.invoke.worktreeSetupCommandSet, { projectPath, command }),forkSession: (sessionId: string, title?: string, throughMessageId?: string) =>invoke<{ session: SessionDetail }>(IPC.invoke.sessionFork, {sessionId,diff --cc apps/desktop/src/lib/session-create.tsindex 3f0b442bb,bfc4687fc..d20238015--- a/apps/desktop/src/lib/session-create.ts+++ b/apps/desktop/src/lib/session-create.ts@@@ -19,13 -19,8 +19,13 @@@ export function sessionIsReusableEmptyrunning?: boolean;liveMessageCount?: number;submitted?: boolean;- /** The request asks for an isolated session (ADR 0328). */++ /** The request asks for an isolated session (ADR 0329). */+ isolated?: boolean;} = {},): boolean {+ // An isolated request always gets its own worktree, and an empty isolated- // session is never handed out for an ordinary request (ADR 0328).++ // session is never handed out for an ordinary request (ADR 0329).+ if (options.isolated === true || session.worktree) return false;if (session.messageCount > 0) return false;if (options.running === true) return false;if ((options.liveMessageCount ?? 0) > 0) return false;diff --cc apps/desktop/src/stores/app-state.tsindex df1bcb998,9ad9dea03..026b8f9ec--- a/apps/desktop/src/stores/app-state.ts+++ b/apps/desktop/src/stores/app-state.ts@@@ -208,12 -208,7 +208,12 @@@ export type AppState =id: string,opts?: { record?: boolean } & NavigationOptions,) => Promise<void>;- newSession: (options?: { projectPath?: string | null; remoteProject?: RemoteProjectTarget }) => Promise<void>;+ newSession: (options?: {+ projectPath?: string | null;+ remoteProject?: RemoteProjectTarget;- /** Create an isolated session in its own git worktree (ADR 0328). */++ /** Create an isolated session in its own git worktree (ADR 0329). */+ isolated?: boolean;+ }) => Promise<void>;forkSession: (id: string) => Promise<void>;forkAssistantMessage: (messageId: string) => Promise<void>;configureActiveSession: (config: {diff --cc apps/desktop/src/stores/runtime/session-coordination.tsindex 195a7e0e8,e71947a39..3e9fefe36--- a/apps/desktop/src/stores/runtime/session-coordination.ts+++ b/apps/desktop/src/stores/runtime/session-coordination.ts@@@ -37,8 -37,6 +37,8 @@@ export type PersistSessionOptions =intent?: number;projectPath?: string | null;draftConfiguration?: DraftSessionConfiguration | null;- /** Run the new session in its own git worktree (ADR 0328). */++ /** Run the new session in its own git worktree (ADR 0329). */+ isolated?: boolean;};export type SessionCoordination = {diff --cc apps/desktop/src/styles/worktree.cssindex 358d15105,000000000..2cdc8691cmode 100644,000000..100644--- a/apps/desktop/src/styles/worktree.css+++ b/apps/desktop/src/styles/worktree.css@@@ -1,58 -1,0 +1,58 @@@- /* Isolated sessions in git worktrees (ADR 0328). */++/* Isolated sessions in git worktrees (ADR 0329). */++.thread-item-worktree {+ display: inline-flex;+ flex-shrink: 0;+ margin-inline-end: 4px;+}++.worktree-dialog-body {+ display: flex;+ flex-direction: column;+ gap: 8px;+ overflow-wrap: anywhere;+}++.worktree-dialog-body p {+ margin: 0;+}++.worktree-file-list {+ max-height: 220px;+ margin: 0;+ padding: 8px 12px;+ overflow: auto;+ list-style: none;+ border: 1px solid var(--ds-border-default);+ border-radius: var(--radius-xs);+ background: var(--ds-bg-inset);+ font-size: var(--text-sm);+}++.worktree-setup-log {+ max-height: 320px;+ margin: 0;+ padding: 8px 12px;+ overflow: auto;+ white-space: pre-wrap;+ border: 1px solid var(--ds-border-default);+ border-radius: var(--radius-xs);+ background: var(--ds-bg-inset);+ font-size: var(--text-sm);+}++/* Why "New isolated session" is unavailable, under the disabled item. */+.worktree-menu-reason {+ max-width: 260px;+ margin: -2px 0 4px;+ padding: 0 8px 0 30px;+ color: var(--ds-text-muted);+ font-size: var(--text-sm);+ white-space: normal;+ overflow-wrap: anywhere;+}++.worktree-delete-loss {+ margin-inline-start: 6px;+ color: var(--ds-error);+}diff --cc apps/desktop/test/browser-preview-tool.test.mjsindex 9c7a68f62,18584b58f..56bacc40c--- a/apps/desktop/test/browser-preview-tool.test.mjs+++ b/apps/desktop/test/browser-preview-tool.test.mjs@@@ -53,18 -53,9 +53,18 @@@ test("main serves BrowserPreview from imainSource.indexOf("sidecar = s;"),);assert.match(handler, /async \(\{ args, sessionId \}\)/);- assert.match(handler, /host\?\.call\("session\.get", \{ id: sessionId \}\)/);- assert.match(handler, /res\?\.session\?\.projectPath/);+ assert.match(handler, /root = await sessionFileRoot\(sessionId\)/);assert.doesNotMatch(handler, /workspace\.get/);+ // The root comes from the durable session: its project, or the worktree of an- // isolated session resolved by host-core (ADR 0328).++ // isolated session resolved by host-core (ADR 0329).+ const resolver = mainSource.slice(+ mainSource.indexOf("const sessionFileRoot = async"),+ mainSource.indexOf('s.setLocalTool("BrowserPreview"'),+ );+ assert.match(resolver, /"session\.get", \{ id: sessionId \}/);+ assert.match(resolver, /res\?\.session\?\.projectPath/);+ assert.match(resolver, /"worktree\.location", \{ sessionId \}/);+ assert.doesNotMatch(resolver, /workspace\.get/);assert.match(handler, /browserHost\.previewWorkspaceFile\(sessionId, raw, root\)/);assert.ok(handler.indexOf("resolveLocalFile(raw, root)") <diff --cc apps/desktop/test/isolated-session-launch.test.mjsindex b113acc7f,000000000..03e4de778mode 100644,000000..100644--- a/apps/desktop/test/isolated-session-launch.test.mjs+++ b/apps/desktop/test/isolated-session-launch.test.mjs@@@ -1,136 -1,0 +1,136 @@@+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import test from "node:test";+import { pathToFileURL } from "node:url";+import { repositoryRoot } from "../../../scripts/e2e/boot.mjs";++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");+- // ADR 0328: an isolated session reads files (AGENTS.md) from its worktree while++// ADR 0329: an isolated session reads files (AGENTS.md) from its worktree while+// project-keyed configuration (group instructions, memory) stays on the project.+test("an isolated session launches in its worktree with its project's configuration", async () => {+ const temp = await mkdtemp(join(root, "apps/desktop/.isolated-launch-test-"));+ const priorHome = process.env.HOME;+ process.env.HOME = temp;+ try {+ const project = join(temp, "project");+ const worktree = join(temp, "worktrees", "project-1", "s1");+ await mkdir(project, { recursive: true });+ await mkdir(worktree, { recursive: true });+ await writeFile(join(project, "AGENTS.md"), "MAIN CHECKOUT RULES\n");+ await writeFile(join(worktree, "AGENTS.md"), "SESSION BRANCH RULES\n");++ const bundle = join(temp, "session-launch.mjs");+ await build({+ entryPoints: [join(root, "apps/desktop/electron/main/runtime/session-launch.ts")],+ outfile: bundle,+ bundle: true,+ platform: "node",+ format: "esm",+ packages: "external",+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ const { createSessionLaunchRuntime } = await import(pathToFileURL(bundle).href);++ const provider = {+ id: "fixture-provider",+ name: "Fixture provider",+ authKind: "none",+ apiStyle: "openai-completions",+ baseUrl: "http://127.0.0.1:11434/v1",+ enabled: true,+ defaultModelId: "fixture-model",+ models: [],+ };+ const groupContextPaths = [];+ let locationAvailable = true;+ const host = {+ isAvailable: () => true,+ async call(method, input) {+ if (method === "commandShells.list") {+ const shell = { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true };+ return { configuredId: "bash", effective: shell, fallback: false, choices: [shell] };+ }+ if (method === "providers.list") return { providers: [provider] };+ if (method === "providers.getSecret") return { value: "" };+ if (method === "skills.disabledBuiltins") return { disabled: [] };+ if (method === "skills.active") return { skills: [] };+ if (method === "mcp.active") return { servers: [] };+ if (method === "agents.active") return { subagents: [] };+ if (method === "agents.disabledBuiltins") return { disabled: [] };+ if (method === "worktree.location") {+ assert.deepEqual(input, { sessionId: "session-fixture" });+ if (!locationAvailable) throw new Error("the isolated worktree folder no longer exists");+ return { path: worktree };+ }+ if (method === "project.group.context") {+ groupContextPaths.push(input.path);+ return {+ context: {+ roots: [{ path: project }, { path: join(temp, "other-root") }],+ instructions: "GROUP NOTES",+ memory: { content: "PROJECT MEMORY" },+ },+ };+ }+ throw new Error("Unexpected fixture Host method: " + method);+ },+ };+ const launchRuntime = createSessionLaunchRuntime({+ runtimeState: { host, sidecar: { setVendorAuthBindings() {} }, agentHostBridge: null },+ logger: { app() {} },+ userMcp: { setRecords() {}, async toolsForProject() { return []; } },+ plugins: { getTools: () => [], getSkills: () => [], listLoaded: () => [], getAgentExtensions: () => [] },+ sessionProjects: new Map(),+ dataDir: temp,+ vendorOAuth: { async bindingFor() { return undefined; } },+ modelsDevCatalog: { async ensureLoaded() {}, configureAccount() {}, findModel() { return undefined; } },+ getWorkspacePath: () => null,+ pluginActiveInProject: () => true,+ bindingForModel: () => undefined,+ effectiveSubagentModelConfig: () => ({ modelConfig: undefined, capabilities: {} }),+ normalizeThinkingLevel: () => "off",+ });+ const settings = { defaultProviderId: provider.id, defaultModelId: provider.defaultModelId };+ const launch = (session) =>+ launchRuntime.resolveAgentRuntimeLaunch(+ "session-fixture",+ { providerId: provider.id, modelId: provider.defaultModelId, projectPath: project, ...session },+ settings,+ );+ const text = (instructions) => JSON.stringify(instructions?.entries ?? []);++ const isolated = await launch({ worktree: { branch: "pi-desktop/s1", status: "active" } });+ assert.equal(isolated.projectPath, project);+ assert.equal(isolated.workspaceRoot, worktree);+ assert.equal(isolated.sidecarParams.projectPath, project);+ assert.equal(isolated.sidecarParams.workspaceRoot, worktree);+ const isolatedText = text(isolated.sidecarParams.projectInstructions);+ assert.match(isolatedText, /SESSION BRANCH RULES/);+ assert.doesNotMatch(isolatedText, /MAIN CHECKOUT RULES/);+ assert.match(isolatedText, /GROUP NOTES/);+ assert.doesNotMatch(isolatedText, /Additional root/);+ assert.equal(isolated.sidecarParams.projectMemory, "PROJECT MEMORY");+ assert.deepEqual(groupContextPaths, [project]);++ const ordinary = await launch({});+ assert.equal(ordinary.workspaceRoot, undefined);+ assert.equal("workspaceRoot" in ordinary.sidecarParams, false);+ const ordinaryText = text(ordinary.sidecarParams.projectInstructions);+ assert.match(ordinaryText, /MAIN CHECKOUT RULES/);+ assert.match(ordinaryText, /Additional root/);++ locationAvailable = false;+ await assert.rejects(+ launch({ worktree: { branch: "pi-desktop/s1", status: "missing" } }),+ /no longer exists/,+ );+ } finally {+ if (priorHome === undefined) delete process.env.HOME;+ else process.env.HOME = priorHome;+ await rm(temp, { recursive: true, force: true });+ }+});diff --cc apps/desktop/test/session-create.test.mjsindex 4dcc4b70f,a3a737c02..e645da7a1--- a/apps/desktop/test/session-create.test.mjs+++ b/apps/desktop/test/session-create.test.mjs@@@ -28,15 -28,6 +28,15 @@@ test("an empty latest session is reusab);});- test("isolated sessions are never reused for a new task (ADR 0328)", () => {++test("isolated sessions are never reused for a new task (ADR 0329)", () => {+ const empty = { messageCount: 0 };+ const emptyIsolated = { messageCount: 0, worktree: { branch: "pi-desktop/a", status: "active" } };+ assert.equal(sessionIsReusableEmpty(emptyIsolated), false, "ordinary + must not pick an isolated session");+ assert.equal(sessionIsReusableEmpty(emptyIsolated, { isolated: true }), false);+ assert.equal(sessionIsReusableEmpty(empty, { isolated: true }), false, "isolation always creates a worktree");+ assert.equal(sessionIsReusableEmpty(empty, { isolated: false }), true);+});+test("empty sessions have a whole, already-known transcript window", () => {assert.deepEqual(EMPTY_SESSION_WINDOW, {messageStart: 0,diff --cc apps/desktop/test/worktree-ui.test.mjsindex 5a329dbb8,000000000..4670b3f69mode 100644,000000..100644--- a/apps/desktop/test/worktree-ui.test.mjs+++ b/apps/desktop/test/worktree-ui.test.mjs@@@ -1,377 -1,0 +1,377 @@@+import assert from "node:assert/strict";+import test, { after, before } from "node:test";+import { fileURLToPath } from "node:url";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import i18n from "i18next";+import { I18nextProvider } from "react-i18next";+import { catalogs } from "@pi-desktop/i18n";+import { IPC } from "@pi-desktop/shared";+import { createServer } from "vite";+- // ADR 0328 renderer surface: badge, menus, create flow, merge failures, and++// ADR 0329 renderer surface: badge, menus, create flow, merge failures, and+// the rule that an ordinary "+" never reuses an empty isolated session.++let server;+let modules;+const en = catalogs.en.worktree;+const previousDocument = globalThis.document;+const previousWindow = globalThis.window;++before(async () => {+ server = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)),+ configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false },+ esbuild: { jsx: "automatic" },+ appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ modules = {+ sidebar: await server.ssrLoadModule("/src/components/Sidebar.tsx"),+ parts: await server.ssrLoadModule("/src/features/worktree/WorktreeSidebarParts.tsx"),+ actions: await server.ssrLoadModule("/src/features/worktree/worktree-actions.ts"),+ store: await server.ssrLoadModule("/src/stores/app-store.ts"),+ behind: await server.ssrLoadModule("/src/features/worktree/WorktreeBehind.tsx"),+ worktreeUi: await server.ssrLoadModule("/src/features/worktree/worktree-ui-store.ts"),+ shared: await import("@pi-desktop/shared"),+ };+ // Same interpolation setting as the app (main.tsx): React escapes output.+ await i18n.init({+ lng: "en",+ resources: { en: { translation: catalogs.en } },+ interpolation: { escapeValue: false },+ });+});++after(async () => {+ globalThis.document = previousDocument;+ globalThis.window = previousWindow;+ await server?.close();+});++const wrap = (element) => renderToStaticMarkup(createElement(I18nextProvider, { i18n }, element));++/** Route renderer `invoke` calls to `handlers[channel]`. */+function stubBridge(handlers) {+ const calls = [];+ globalThis.window = {+ piDesktop: {+ async invoke(channel, payload) {+ calls.push({ channel, payload });+ const handler = handlers[channel];+ if (!handler) return { ok: false, error: { code: "INTERNAL", message: `no stub for ${channel}` } };+ try {+ return { ok: true, data: await handler(payload) };+ } catch (error) {+ return { ok: false, error: { code: error.code, message: error.message, details: error.details } };+ }+ },+ },+ };+ return calls;+}++test("the sidebar badges isolated sessions and leaves ordinary ones unchanged", () => {+ const { Sidebar } = modules.sidebar;+ const { useAppStore } = modules.store;+ const at = "2020-01-01T00:00:00Z";+ const session = (id, worktree) => ({ id, title: id, projectPath: "/open", createdAt: at, updatedAt: at, worktree });+ Object.assign(useAppStore.getInitialState(), {+ sessions: [+ session("plain"),+ session("isolated", { branch: "pi-desktop/a", status: "active", setupStatus: "none" }),+ session("conflicted", { branch: "pi-desktop/b", status: "conflict" }),+ session("vanished", { branch: "pi-desktop/c", status: "missing" }),+ session("broken-setup", { branch: "pi-desktop/d", status: "active", setupStatus: "failed" }),+ ],+ sessionMeta: {},+ projectMeta: {},+ openProjectPaths: ["/open"],+ openProjects: [],+ workspace: null,+ activeProjectPath: null,+ activeSessionId: null,+ selectingSessionId: null,+ page: "chat",+ projectCollapsed: {},+ sessionView: { sort: "recent", archived: false },+ });+ globalThis.document = { documentElement: { dataset: { theme: "light" } } };+ const html = wrap(+ createElement(Sidebar, {+ collapsed: false,+ onToggle() {},+ sidebarWidth: 275,+ onWidthChange() {},+ onWidthCommit() {},+ }),+ );+ const row = (id) => {+ const start = html.indexOf(`data-sidebar-session-row="${id}"`);+ const next = html.indexOf("data-sidebar-session-row=", start + 1);+ return html.slice(start, next === -1 ? undefined : next);+ };+ assert.doesNotMatch(row("plain"), /thread-item-worktree/);+ assert.match(row("isolated"), /data-worktree-status="active"/);+ assert.ok(row("isolated").includes(en.badge.isolated));+ assert.ok(row("isolated").includes("pi-desktop/a"), "the branch is named in the badge title");+ assert.match(row("conflicted"), /badge-warning[^>]*>Conflict</);+ assert.match(row("vanished"), /badge-error[^>]*>Folder missing</);+ assert.ok(row("broken-setup").includes(en.badge.setupFailed));+});++test("only isolated sessions get worktree menu items, disabled while running or missing", () => {+ const { WorktreeSessionMenuItems, WorktreeProjectMenuItems } = modules.parts;+ const props = { sessionId: "s1", title: "Task", running: false, onDone() {} };+ assert.equal(wrap(createElement(WorktreeSessionMenuItems, props)), "");++ const idle = wrap(+ createElement(WorktreeSessionMenuItems, {+ ...props,+ worktree: { branch: "pi-desktop/s1", status: "active", setupStatus: "failed" },+ }),+ );+ assert.match(idle, /data-action="worktree-merge"/);+ assert.doesNotMatch(idle, /data-action="worktree-merge"[^>]*disabled/);+ assert.match(idle, /data-action="worktree-reveal"/);+ assert.match(idle, /data-action="worktree-setup-log"/);+ // "Sync from project" waits for the behind count before it can be used.+ assert.match(idle, /data-action="worktree-sync"[^>]*disabled/);+ assert.ok(idle.includes(en.sync.menu));++ const running = wrap(+ createElement(WorktreeSessionMenuItems, {+ ...props,+ running: true,+ worktree: { branch: "pi-desktop/s1", status: "active", setupStatus: "none" },+ }),+ );+ assert.match(running, /data-action="worktree-merge"[^>]*disabled/);+ assert.doesNotMatch(running, /worktree-setup-log/);++ const missing = wrap(+ createElement(WorktreeSessionMenuItems, {+ ...props,+ worktree: { branch: "pi-desktop/s1", status: "missing" },+ }),+ );+ assert.match(missing, /data-action="worktree-merge"[^>]*disabled/);+ assert.match(missing, /data-action="worktree-reveal"[^>]*disabled/);++ const project = wrap(+ createElement(WorktreeProjectMenuItems, { projectPath: "/p", projectName: "P", onDone() {} }),+ );+ assert.ok(project.includes(en.newIsolatedSession));+ assert.ok(project.includes(en.setupCommand.menu));+ // Before the probe answers the item cannot be clicked.+ assert.match(project, /data-action="new-isolated-session"[^>]*disabled/);+});++test("the isolated-session menu item explains why a project cannot host one", () => {+ const { isolationAvailability } = modules.actions;+ const t = i18n.t.bind(i18n);+ assert.deepEqual(isolationAvailability("checking", t), { disabled: true });+ assert.deepEqual(isolationAvailability("unknown", t), { disabled: false });+ assert.deepEqual(isolationAvailability({ available: true, uncommittedChanges: true }, t), { disabled: false });+ assert.deepEqual(+ isolationAvailability({ available: false, errorCode: "WORKTREE_DETACHED_HEAD", message: "raw" }, t),+ { disabled: true, reason: en.errors.detachedHead },+ );+ assert.deepEqual(+ isolationAvailability({ available: false, errorCode: "WORKTREE_INTERNAL", message: "git exploded" }, t),+ { disabled: true, reason: "git exploded" },+ );+});++test("creating an isolated session probes first and explains every refusal", async () => {+ const { createIsolatedSession } = modules.actions;+ const { useAppStore } = modules.store;+ const t = i18n.t.bind(i18n);+ const created = [];+ const toasts = [];+ useAppStore.setState({+ newSession: async (options) => {+ created.push(options);+ },+ showToast: (message, options) => toasts.push({ message, variant: options?.variant }),+ });++ stubBridge({+ [IPC.invoke.worktreeProbe]: () => ({ available: false, errorCode: "WORKTREE_NOT_GIT", message: "raw" }),+ });+ await createIsolatedSession("/plain", t);+ assert.deepEqual(created, []);+ assert.deepEqual(toasts, [{ message: en.errors.notGit, variant: "error" }]);++ toasts.length = 0;+ const calls = stubBridge({+ [IPC.invoke.worktreeProbe]: () => ({ available: true, uncommittedChanges: true }),+ });+ await createIsolatedSession("/repo", t);+ assert.deepEqual(calls[0].payload, { projectPath: "/repo" });+ assert.deepEqual(created, [{ projectPath: "/repo", isolated: true }]);+ assert.deepEqual(toasts, [{ message: en.uncommittedNotIncluded, variant: "info" }]);++ toasts.length = 0;+ useAppStore.setState({+ newSession: async () => {+ throw Object.assign(new Error("git 2.20 is older than the required 2.29"), {+ code: "WORKTREE_GIT_TOO_OLD",+ });+ },+ });+ stubBridge({+ [IPC.invoke.worktreeProbe]: () => ({ available: true, uncommittedChanges: false }),+ });+ await createIsolatedSession("/repo", t);+ assert.deepEqual(toasts, [{ message: en.errors.gitTooOld, variant: "error" }]);+});++test("merge failures keep conflicts in the session and re-preview a changed session", () => {+ const { mergeFailureState } = modules.actions;+ const t = i18n.t.bind(i18n);+ const conflict = Object.assign(new Error("merge conflict"), {+ code: "WORKTREE_CONFLICT",+ details: { errorCode: "WORKTREE_CONFLICT", files: ["src/a.ts", "README.md"] },+ });+ assert.deepEqual(mergeFailureState(conflict, t), {+ phase: "conflict",+ files: ["src/a.ts", "README.md"],+ });+ assert.deepEqual(mergeFailureState({ code: "WORKTREE_CHANGED_SINCE_PREVIEW" }, t), {+ phase: "reload",+ notice: en.errors.changedSincePreview,+ });+ assert.deepEqual(mergeFailureState({ code: "WORKTREE_PROJECT_DIRTY" }, t), {+ phase: "failed",+ message: en.errors.projectDirty,+ });+ assert.deepEqual(mergeFailureState(new Error("unexpected host failure"), t), {+ phase: "failed",+ message: "unexpected host failure",+ });+});++test("the delete loss note stays empty until unmerged work is known", () => {+ const { WorktreeDeleteLossNote } = modules.parts;+ // Before the pending-work answer arrives only the ordinary armed label shows.+ assert.equal(wrap(createElement(WorktreeDeleteLossNote, { sessionId: "s1" })), "");+ assert.ok(en.deleteLoss.length > 0);+});++test("syncing from the project reports new commits, an up-to-date session, and conflicts", async () => {+ const { syncIsolatedSession } = modules.actions;+ const { useAppStore } = modules.store;+ const t = i18n.t.bind(i18n);+ const toasts = [];+ let refreshed = 0;+ useAppStore.setState({+ showToast: (message, options) => toasts.push({ message, variant: options?.variant }),+ refreshSessions: async () => {+ refreshed += 1;+ },+ });++ stubBridge({ [IPC.invoke.worktreeSync]: () => ({ result: "synced", commits: 3 }) });+ await syncIsolatedSession("s1", t);+ stubBridge({ [IPC.invoke.worktreeSync]: () => ({ result: "upToDate" }) });+ await syncIsolatedSession("s1", t);+ stubBridge({+ [IPC.invoke.worktreeSync]: () => {+ throw Object.assign(new Error("merge conflict"), {+ code: "WORKTREE_CONFLICT",+ details: { errorCode: "WORKTREE_CONFLICT", files: ["f.txt", "g.txt"] },+ });+ },+ });+ await syncIsolatedSession("s1", t);++ assert.deepEqual(toasts, [+ { message: i18n.t("worktree.sync.success", { count: 3 }), variant: "success" },+ { message: en.sync.upToDate, variant: "info" },+ { message: i18n.t("worktree.sync.conflict", { files: "f.txt, g.txt" }), variant: "error" },+ ]);+ // The badge follows: the list is refreshed after every attempt.+ assert.equal(refreshed, 3);+});++test("the behind marker shows only for sessions that lack project commits", () => {+ const { WorktreeBadge } = modules.parts;+ const { isolatedSessionsKey } = modules.behind;+ const { useWorktreeUi } = modules.worktreeUi;+ const active = { branch: "pi-desktop/a", status: "active", setupStatus: "none" };+ // Server rendering reads the store's initial state (as the sidebar test does).+ Object.assign(useWorktreeUi.getInitialState(), { behind: { s1: 3, s2: 0 } });++ const behind = wrap(createElement(WorktreeBadge, { worktree: active, sessionId: "s1" }));+ assert.match(behind, /data-worktree-behind="3"/);+ assert.ok(behind.includes(i18n.t("worktree.badge.behind", { count: 3 })));+ assert.ok(behind.includes(i18n.t("worktree.badge.behindTitle", { count: 3 }).replaceAll('"', """)));+ assert.doesNotMatch(wrap(createElement(WorktreeBadge, { worktree: active, sessionId: "s2" })), /data-worktree-behind/);+ assert.doesNotMatch(wrap(createElement(WorktreeBadge, { worktree: active })), /data-worktree-behind/);+ assert.doesNotMatch(+ wrap(createElement(WorktreeBadge, { worktree: { ...active, status: "missing" }, sessionId: "s1" })),+ /data-worktree-behind/,+ );++ // The counts are re-read when an isolated session appears, changes status,+ // or finishes a turn; ordinary sessions never trigger it.+ const at = "2020-01-01T00:00:00Z";+ const plain = { id: "p", updatedAt: at };+ const isolated = { id: "s1", updatedAt: at, worktree: active };+ const base = isolatedSessionsKey([plain, isolated]);+ assert.equal(isolatedSessionsKey([isolated]), base);+ assert.equal(isolatedSessionsKey([plain]), "");+ assert.notEqual(isolatedSessionsKey([{ ...isolated, updatedAt: "2020-01-02T00:00:00Z" }]), base);+ assert.notEqual(isolatedSessionsKey([{ ...isolated, worktree: { ...active, status: "merged" } }]), base);+ assert.equal(isolatedSessionsKey([{ ...isolated, worktree: { ...active, status: "missing" } }]), "");+});++test("a conflicted session hides the behind marker and cannot sync until it resolves", () => {+ const { WorktreeBadge, WorktreeSessionMenuItems } = modules.parts;+ const { useWorktreeUi } = modules.worktreeUi;+ Object.assign(useWorktreeUi.getInitialState(), { behind: { s1: 3 } });+ const conflicted = { branch: "pi-desktop/s1", status: "conflict", setupStatus: "none" };++ const badge = wrap(createElement(WorktreeBadge, { worktree: conflicted, sessionId: "s1" }));+ assert.match(badge, /data-worktree-status="conflict"/);+ assert.doesNotMatch(badge, /data-worktree-behind/);++ const menu = wrap(+ createElement(WorktreeSessionMenuItems, {+ sessionId: "s1",+ title: "Task",+ running: false,+ onDone() {},+ worktree: conflicted,+ }),+ );+ const sync = menu.slice(menu.indexOf('data-action="worktree-sync"') - 200, menu.indexOf("</button>", menu.indexOf('data-action="worktree-sync"')));+ assert.match(sync, /disabled=""/);+ assert.ok(sync.includes(en.sync.resolveFirst), sync);+ assert.doesNotMatch(sync, /aria-busy/);+ // Merging stays available: it concludes the resolution.+ assert.doesNotMatch(menu, /data-action="worktree-merge"[^>]*disabled/);+});++test("every actionable worktree error has a localized message in every locale", () => {+ const { worktreeErrorMessage } = modules.actions;+ const { WorktreeErrorCodes } = modules.shared;+ const t = i18n.t.bind(i18n);+ // Conflicts list their files and a changed session is previewed again.+ const handledElsewhere = new Set(["WORKTREE_CONFLICT"]);+ for (const code of Object.values(WorktreeErrorCodes)) {+ if (handledElsewhere.has(code)) continue;+ const message = worktreeErrorMessage(Object.assign(new Error("raw git output"), { code }), t);+ assert.notEqual(message, "raw git output", `${code} shows the raw host message`);+ }+ for (const [locale, catalog] of Object.entries(catalogs)) {+ assert.deepEqual(+ Object.keys(catalog.worktree.errors).sort(),+ Object.keys(en.errors).sort(),+ `${locale} worktree errors`,+ );+ assert.match(catalog.worktree.sync.conflict, /\{\{files\}\}/, `${locale} sync conflict`);+ }+});diff --cc crates/host-core/src/data_relocation.rsindex 1db88b23d,b450924da..b39525389--- a/crates/host-core/src/data_relocation.rs+++ b/crates/host-core/src/data_relocation.rs@@@ -336,9 -336,6 +336,9 @@@ fn relocate_database(roots: &Roots) ->("artifacts", "path", false),("turn_queue", "attachments_json", true),("scheduled_tasks", "config_json", true),- // Isolated-session worktrees live under the data directory (ADR 0328);++ // Isolated-session worktrees live under the data directory (ADR 0329);+ // host-core repairs git's back-links on the next start.+ ("worktrees", "path", false),] {if !column_exists(&transaction, table, column)? {continue;diff --cc crates/host-core/src/db/schema.rsindex c23bf809d,dc2b2a4af..2237f0519--- a/crates/host-core/src/db/schema.rs+++ b/crates/host-core/src/db/schema.rs@@@ -42,9 -42,7 +42,9 @@@ CREATE TABLE projectsname TEXT NOT NULL,pinned INTEGER NOT NULL DEFAULT 0,created_at INTEGER NOT NULL,- last_opened_at INTEGER NOT NULL+ last_opened_at INTEGER NOT NULL,- -- Optional command run in every new isolated worktree (schema v24, ADR 0328).++ -- Optional command run in every new isolated worktree (schema v24, ADR 0329).+ worktree_setup_command TEXT);CREATE TABLE providers (diff --cc crates/host-core/src/db/tests.rsindex 8f524583b,765e42b10..8f5ed4f1e--- a/crates/host-core/src/db/tests.rs+++ b/crates/host-core/src/db/tests.rs@@@ -178,118 -178,6 +178,118 @@@ fn v22_database_migrates_session_title_);}- /// v24 adds the isolated-session worktree registry (ADR 0328). A v23 database++/// v24 adds the isolated-session worktree registry (ADR 0329). A v23 database+/// keeps its projects and sessions, gains the nullable setup-command column+/// and the `worktrees` table, and leaves a pre-migration backup.+#[test]+fn v23_database_gains_worktree_registry_without_losing_projects() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ let session_id = {+ let db = Database::open(&path).unwrap();+ db.conn()+ .execute(+ "INSERT INTO projects (path, name, pinned, created_at, last_opened_at)+ VALUES ('/work/app', 'app', 1, 1, 2)",+ [],+ )+ .unwrap();+ let session =+ crate::sessions::create_session(&db, Some("Kept".into()), None, None, None, None)+ .unwrap();+ db.conn()+ .execute_batch(+ "DROP TABLE worktrees;+ ALTER TABLE projects DROP COLUMN worktree_setup_command;",+ )+ .unwrap();+ db.conn().pragma_update(None, "user_version", 23).unwrap();+ session.id+ };++ let db = Database::open(&path).unwrap();+ assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);+ assert!(migration_backup_path(&path, 23).exists());+ let (name, pinned, command): (String, i64, Option<String>) = db+ .conn()+ .query_row(+ "SELECT name, pinned, worktree_setup_command FROM projects WHERE path = '/work/app'",+ [],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .unwrap();+ assert_eq!((name.as_str(), pinned, command), ("app", 1, None));+ assert!(crate::sessions::get_session(&db, &session_id)+ .unwrap()+ .is_some());+ let worktrees: i64 = db+ .conn()+ .query_row("SELECT COUNT(*) FROM worktrees", [], |row| row.get(0))+ .unwrap();+ assert_eq!(worktrees, 0);+}++/// Deleting a session through any path must keep the worktree row, with its+/// session cleared, so the orphan cleanup can still remove the directory and+/// branch that exist on disk.+#[test]+fn deleting_a_session_orphans_its_worktree_rows_instead_of_dropping_them() {+ let dir = tempfile::tempdir().unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let session = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();+ db.conn()+ .execute(+ "INSERT INTO worktrees (id, session_id, delegation_id, path, common_dir, branch,+ owner_branch, status, created_at, updated_at)+ VALUES ('w1', ?1, NULL, '/data/worktrees/p/s1', '/repo/.git', 'pi-desktop/s1',+ 'main', 'active', 1, 1)",+ params![session.id],+ )+ .unwrap();+ assert!(crate::sessions::delete_session(&db, &session.id).unwrap());+ let session_id: Option<String> = db+ .conn()+ .query_row(+ "SELECT session_id FROM worktrees WHERE id = 'w1'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(session_id, None);+}++/// A session owns at most one worktree of its own plus one per delegation,+/// and two active worktrees never share a port block.+#[test]+fn worktree_registry_enforces_one_row_per_owner_and_unique_ports() {+ let dir = tempfile::tempdir().unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let session = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();+ let insert = |id: &str, delegation: Option<&str>, port: Option<i64>| {+ db.conn().execute(+ "INSERT INTO worktrees (id, session_id, delegation_id, path, common_dir, branch,+ owner_branch, status, port_base, created_at, updated_at)+ VALUES (?1, ?2, ?3, '/w/' || ?1, '/repo/.git', 'pi-desktop/' || ?1, 'main',+ 'active', ?4, 1, 1)",+ params![id, session.id, delegation, port],+ )+ };+ insert("a", None, Some(41000)).unwrap();+ assert!(+ insert("b", None, Some(41010)).is_err(),+ "second own worktree"+ );+ insert("c", Some("d1"), Some(41010)).unwrap();+ assert!(+ insert("e", Some("d1"), None).is_err(),+ "second worktree for one delegation"+ );+ assert!(+ insert("f", Some("d2"), Some(41000)).is_err(),+ "shared port block"+ );+}+/// v21 owns the session checklist. A real v20 database has neither the/// `sessions` stamps nor the `session_todo` table, so the upgrade must add/// both, keep the v20 rows, leave a readable pre-migration backup, and staydiff --cc crates/host-core/src/db/worktree_migration.rsindex 325ce5f99,000000000..d184dbcafmode 100644,000000..100644--- a/crates/host-core/src/db/worktree_migration.rs+++ b/crates/host-core/src/db/worktree_migration.rs@@@ -1,72 -1,0 +1,72 @@@+use super::{create_migration_backup, Connection, Context, Path, Result};+use rusqlite::Transaction;++/// Registry of git worktrees that host-core created for isolated sessions and- /// their Write/Edit delegates (ADR 0328).++/// their Write/Edit delegates (ADR 0329).+///+/// `session_id` uses `ON DELETE SET NULL`, not `CASCADE`: a session removed by+/// any path leaves an orphan row that the cleanup pass turns into a link-safe+/// removal of the directory and branch. A cascade would drop the only record+/// of a worktree that still exists on disk.+///+/// Shared verbatim by the fresh schema and the v23 -> v24 migration;+/// `IF NOT EXISTS` keeps a second run harmless.+pub(crate) const WORKTREE_DDL: &str = r#"+CREATE TABLE IF NOT EXISTS worktrees (+ id TEXT PRIMARY KEY,+ session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,+ delegation_id TEXT,+ path TEXT NOT NULL UNIQUE,+ -- Canonical common git directory: serialization key, and where branches are+ -- deleted after the worktree directory is gone.+ common_dir TEXT NOT NULL,+ -- Project directory relative to the repository top level ('' at the top).+ prefix TEXT NOT NULL DEFAULT '',+ branch TEXT NOT NULL,+ owner_branch TEXT NOT NULL,+ status TEXT NOT NULL+ CHECK (status IN ('creating', 'active', 'conflict', 'merged', 'missing')),+ setup_status TEXT+ CHECK (setup_status IS NULL+ OR setup_status IN ('none', 'running', 'ok', 'failed')),+ setup_log TEXT,+ port_base INTEGER,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+);+CREATE UNIQUE INDEX IF NOT EXISTS idx_worktrees_session_delegation+ ON worktrees(session_id, IFNULL(delegation_id, ''))+ WHERE session_id IS NOT NULL;+CREATE UNIQUE INDEX IF NOT EXISTS idx_worktrees_port_base+ ON worktrees(port_base) WHERE port_base IS NOT NULL;+CREATE INDEX IF NOT EXISTS idx_worktrees_orphans+ ON worktrees(updated_at) WHERE session_id IS NULL;+"#;++fn migrate_v23_to_v24_tx(tx: &Transaction<'_>) -> Result<()> {+ let has_setup_command: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info('projects')+ WHERE name = 'worktree_setup_command')",+ [],+ |row| row.get(0),+ )?;+ if !has_setup_command {+ tx.execute_batch("ALTER TABLE projects ADD COLUMN worktree_setup_command TEXT;")?;+ }+ tx.execute_batch(WORKTREE_DDL)?;+ tx.pragma_update(None, "user_version", 24i64)?;+ Ok(())+}++pub(crate) fn migrate_v23_to_v24(conn: &Connection, path: &Path) -> Result<()> {+ let backup = create_migration_backup(conn, path, 23)?;+ let tx = conn.unchecked_transaction()?;+ migrate_v23_to_v24_tx(&tx)?;+ tx.commit().with_context(|| {+ format!(+ "commit schema v23 to v24 migration; backup {} remains",+ backup.display()+ )+ })?;+ Ok(())+}diff --cc crates/host-core/src/main.rsindex 8c9d71e30,bcc75a0ba..36e8c7eda--- a/crates/host-core/src/main.rs+++ b/crates/host-core/src/main.rs@@@ -98,11 -97,5 +98,11 @@@ async fn main() -> anyhow::Result<()>review::sweep(&data_dir, &live);}}+ // Drop half-created worktrees, mark vanished ones, repair links after a- // moved data directory, and remove orphans (ADR 0328).++ // moved data directory, and remove orphans (ADR 0329).+ tokio::spawn(session_worktrees::lifecycle::reconcile(+ state.clone(),+ session_worktrees::git::GitRunner::default(),+ ));rpc::serve(state).await}diff --cc crates/host-core/src/rpc/mod.rsindex 8bd0d8aaf,76cf50788..52001553d--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@@ -1288,13 -1287,6 +1288,13 @@@ fn resolve_tool_workspace) -> Result<Option<String>, JsonRpcError> {match sessions::session_summary(&state.db, session_id) {Ok(Some(summary)) => {+ // An isolated session's root is its worktree and never falls back- // to the main checkout (ADR 0328).++ // to the main checkout (ADR 0329).+ match crate::session_worktrees::lifecycle::tool_root(&state.db, session_id) {+ Ok(Some(root)) => return Ok(Some(root.to_string_lossy().into_owned())),+ Ok(None) => {}+ Err(error) => return Err(worktree_rpc::to_rpc(error)),+ }if let Some(project_path) = summary.project_path {return Ok(Some(project_path));}@@@ -2512,32 -2504,7 +2512,32 @@@ async fn handle_request"session.create" => {let thinking_level = thinking_level_param(¶ms)?;let permission_parent = permission_parent_param(¶ms)?;- // ADR 0328: an isolated session gets its own git worktree.++ // ADR 0329: an isolated session gets its own git worktree.+ let isolated = params+ .get("isolated")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ let isolated_project = if isolated {+ Some(+ params+ .get("projectPath")+ .and_then(|v| v.as_str())+ .map(str::to_string)+ .ok_or_else(|| {+ rpc_err(+ 1002,+ "an isolated session needs a projectPath",+ "INVALID_PARAMS",+ )+ })?,+ )+ } else {+ None+ };let st = state.lock().await;+ if let Some(project) = isolated_project.as_deref() {+ worktree_rpc::ensure_local_project(&st.db, project)?;+ }let permission_mode = if let Some(parent_id) = permission_parent {Some(sessions::session_permission_mode(&st.db, &parent_id)@@@ -2769,9 -2714,6 +2769,9 @@@.get("id").and_then(|v| v.as_str()).ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;- // Delete = discard for isolated sessions (ADR 0328); a git failure++ // Delete = discard for isolated sessions (ADR 0329); a git failure+ // keeps the session.+ worktree_rpc::remove_before_delete(&state, id).await?;let st = state.lock().await;let ok = sessions::delete_session(&st.db, id).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;@@@ -4175,28 -4102,11 +4175,28 @@@// Admission follows permission so approval waits do not occupy// execution capacity. Keep this permit through review, the// runner, and bookkeeping so every accepted call is bounded.- // A subagent working in its own worktree (ADR 0328) is not- let tool_budget = {++ // A subagent working in its own worktree (ADR 0329) is not+ // stopped while its session's worktree is held for a merge.+ let (tool_budget, own_worktree) = {let st = state.lock().await;- st.tool_budget.clone()+ let own = matches!(+ crate::session_worktrees::delegate::tool_root(+ &st.db,+ &p.session_id,+ p.delegation_id.as_deref(),+ ),+ Ok(Some(_))+ );+ (st.tool_budget.clone(), own)};- let _tool_permit = match tool_budget.acquire(&p.session_id, &p.tool_name).await {+ let admitted = if own_worktree {+ tool_budget+ .acquire_in_own_worktree(&p.session_id, &p.tool_name)+ .await+ } else {+ tool_budget.acquire(&p.session_id, &p.tool_name).await+ };+ let _tool_permit = match admitted {Ok(permit) => permit,Err(error) => {tracing::warn!(@@@ -4391,20 -4292,6 +4391,20 @@@}}- // ADR 0328: a session that resolved its merge conflict (or++ // ADR 0329: a session that resolved its merge conflict (or+ // aborted the merge) drops its conflict badge before the turn+ // ends and the sidebar refreshes.+ if p.delegation_id.is_none()+ && matches!(p.tool_name.as_str(), "Write" | "Edit" | "Bash")+ {+ crate::session_worktrees::lifecycle::refresh_conflict_status(+ &state,+ &crate::session_worktrees::git::GitRunner::default(),+ &p.session_id,+ )+ .await;+ }+let st = state.lock().await;// Scratch files are temp by definition: keep them out of the// artifacts table so the work panel file list only showsdiff --cc crates/host-core/src/rpc/remote_tools.rsindex d1fe3d8ae,235ca70ff..908dd6352--- a/crates/host-core/src/rpc/remote_tools.rs+++ b/crates/host-core/src/rpc/remote_tools.rs@@@ -340,8 -340,6 +340,8 @@@ pub(super) async fn handletimeout_ms: tools::effective_timeout_ms(&p.tool_name, p.timeout_ms),cancellation: cancellation.clone(),output_tx: Some(tx),- // Remote workspaces are never isolated (ADR 0328).++ // Remote workspaces are never isolated (ADR 0329).+ extra_env: Vec::new(),})} else {Nonediff --cc crates/host-core/src/rpc/remote_tools_tests.rsindex 937f4d539,de0c5de97..6cde9950c--- a/crates/host-core/src/rpc/remote_tools_tests.rs+++ b/crates/host-core/src/rpc/remote_tools_tests.rs@@@ -341,46 -341,3 +341,46 @@@ async fn approved_remote_write_is_dispa"CAPABILITY_UNAVAILABLE");}+- /// ADR 0328: a remote-host project cannot host an isolated session; the++/// ADR 0329: a remote-host project cannot host an isolated session; the+/// probe says why and creation is refused before a session exists.+#[tokio::test]+async fn remote_projects_cannot_create_isolated_sessions() {+ let (_dir, state, tx, _rx) = fixture();+ let (path, _id) = create(&state, &tx).await;+ let probe = handle_request(+ state.clone(),+ "worktree.probe",+ json!({"projectPath": path}),+ tx.clone(),+ )+ .await+ .unwrap();+ assert_eq!(probe["available"], false);+ assert_eq!(probe["errorCode"], "WORKTREE_REMOTE_UNSUPPORTED");+ let before = handle_request(state.clone(), "session.list", json!({}), tx.clone())+ .await+ .unwrap()["sessions"]+ .as_array()+ .unwrap()+ .len();+ let refused = handle_request(+ state.clone(),+ "session.create",+ json!({"projectPath": path, "isolated": true}),+ tx.clone(),+ )+ .await+ .unwrap_err();+ assert_eq!(+ refused.data.unwrap()["errorCode"],+ "WORKTREE_REMOTE_UNSUPPORTED"+ );+ let after = handle_request(state.clone(), "session.list", json!({}), tx.clone())+ .await+ .unwrap()["sessions"]+ .as_array()+ .unwrap()+ .len();+ assert_eq!(before, after);+}diff --cc crates/host-core/src/rpc/worktree_rpc.rsindex bc0406d18,000000000..2f6a9a6a8mode 100644,000000..100644--- a/crates/host-core/src/rpc/worktree_rpc.rs+++ b/crates/host-core/src/rpc/worktree_rpc.rs@@@ -1,265 -1,0 +1,265 @@@+//! `worktree.*` methods and the isolated-session hooks of `session.create` and- //! `session.delete` (ADR 0328). Callers name a session or a project; no++//! `session.delete` (ADR 0329). Callers name a session or a project; no+//! method accepts a worktree path.++use std::path::Path;+use std::sync::Arc;++use serde_json::{json, Value};+use tokio::sync::Mutex;++use super::{rpc_err, JsonRpcError};+use crate::session_worktrees::git::GitRunner;+use crate::session_worktrees::{delegate, lifecycle, merge, probe, registry, WorktreeError};+use crate::sessions;+use crate::state::AppState;++/// Numeric JSON-RPC code shared by every `WORKTREE_*` error; `errorCode`+/// carries the specific reason.+const WORKTREE_RPC_CODE: i64 = 1025;++pub(super) fn to_rpc(error: WorktreeError) -> JsonRpcError {+ let mut data = json!({ "errorCode": error.code });+ if !error.files.is_empty() {+ data["files"] = json!(error.files);+ }+ JsonRpcError {+ code: WORKTREE_RPC_CODE,+ message: error.message,+ data: Some(data),+ }+}++/// Code of a refusal to isolate a remote-host project: its path names a+/// workspace on another machine, not a local git checkout.+const REMOTE_UNSUPPORTED: &str = "WORKTREE_REMOTE_UNSUPPORTED";++/// Isolated sessions need a local checkout; remote-host projects run their+/// tools on the remote machine and are refused before anything is created.+pub(super) fn ensure_local_project(+ db: &crate::db::Database,+ project_path: &str,+) -> Result<(), JsonRpcError> {+ let remote = db+ .remote_workspace_for_path(project_path)+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;+ match remote {+ Some(_) => Err(to_rpc(WorktreeError::new(+ REMOTE_UNSUPPORTED,+ "isolated sessions are not available for remote projects",+ ))),+ None => Ok(()),+ }+}++fn str_param<'a>(params: &'a Value, name: &str) -> Result<&'a str, JsonRpcError> {+ params+ .get(name)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .ok_or_else(|| rpc_err(1002, format!("{name} required"), "INVALID_PARAMS"))+}++pub(super) async fn handle(+ state: &Arc<Mutex<AppState>>,+ method: &str,+ params: Value,+) -> Result<Value, JsonRpcError> {+ let git = GitRunner::default();+ match method {+ // Whether a project can host isolated sessions, for the create switch+ // (PRD R6) and the "uncommitted changes are not included" notice (R2b).+ "worktree.probe" => {+ let project = str_param(¶ms, "projectPath")?;+ if let Err(error) = ensure_local_project(&state.lock().await.db, project) {+ let data = error.data.unwrap_or_default();+ return Ok(json!({+ "available": false,+ "errorCode": data["errorCode"],+ "message": error.message,+ }));+ }+ match probe::probe(&git, Path::new(project)).await {+ Ok(_) => {+ let dirty = !merge::worktree_status(&git, Path::new(project))+ .await+ .map_err(to_rpc)?+ .is_empty();+ Ok(json!({ "available": true, "uncommittedChanges": dirty }))+ }+ Err(error) => Ok(json!({+ "available": false,+ "errorCode": error.code(),+ "message": error.to_string(),+ })),+ }+ }+ "worktree.preview" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let preview = lifecycle::preview_session(state, &git, session_id)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "preview": preview }))+ }+ "worktree.merge" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let token = str_param(¶ms, "previewToken")?;+ let outcome = lifecycle::merge_session(state, &git, session_id, token)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "outcome": outcome }))+ }+ // "Sync from project": `behind` sizes the menu item, `sync` merges+ // the project's branch into the session worktree.+ "worktree.behind" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let commits = lifecycle::behind_session(state, &git, session_id)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "commits": commits }))+ }+ "worktree.behindAll" => {+ let behind = lifecycle::behind_all(state, &git).await.map_err(to_rpc)?;+ Ok(json!(behind))+ }+ "worktree.sync" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let outcome = lifecycle::sync_session(state, &git, session_id)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "outcome": outcome }))+ }+ "worktree.pendingWork" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let pending = lifecycle::pending_work(state, &git, session_id)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "pending": pending }))+ }+ "worktree.setupLog" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let st = state.lock().await;+ let row = registry::for_owner(&st.db, session_id, None)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;+ Ok(json!({+ "setupStatus": row.as_ref().and_then(|row| row.setup_status),+ "log": row.and_then(|row| row.setup_log),+ }))+ }+ // For Electron Main's "Reveal in folder" only; never forwarded to+ // the renderer.+ "worktree.location" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let st = state.lock().await;+ let root = lifecycle::tool_root(&st.db, session_id)+ .map_err(to_rpc)?+ .ok_or_else(|| {+ to_rpc(WorktreeError::new(+ "WORKTREE_NOT_ISOLATED",+ "the session has no isolated worktree",+ ))+ })?;+ Ok(json!({ "path": root }))+ }+ // Called by the agent runtime for Write/Edit subagents of an+ // isolated session; `delegationId` is the subagent's chain id.+ "worktree.delegate.create" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let delegation_id = str_param(¶ms, "delegationId")?;+ let worktree =+ delegate::create_delegate_worktree(state, &git, session_id, delegation_id)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "worktree": worktree }))+ }+ "worktree.delegate.settle" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let delegation_id = str_param(¶ms, "delegationId")?;+ let merge = params+ .get("merge")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ let settlement =+ delegate::settle_delegate_worktree(state, &git, session_id, delegation_id, merge)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "settlement": settlement }))+ }+ "worktree.setupCommand.get" => {+ let project = str_param(¶ms, "projectPath")?;+ let st = state.lock().await;+ let command = lifecycle::setup_command(&st.db, project)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;+ Ok(json!({ "command": command }))+ }+ "worktree.setupCommand.set" => {+ let project = str_param(¶ms, "projectPath")?;+ let command = params.get("command").and_then(Value::as_str);+ let st = state.lock().await;+ let updated = lifecycle::set_setup_command(&st.db, project, command)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;+ if !updated {+ return Err(rpc_err(1007, "project not found", "NOT_FOUND"));+ }+ Ok(json!({ "ok": true }))+ }+ _ => Err(rpc_err(+ -32601,+ format!("method not found: {method}"),+ "NOT_FOUND",+ )),+ }+}++/// Give a just-created session its worktree. On failure the session is+/// deleted again, so no half-created isolated session remains (design §5.1).+pub(super) async fn isolate_new_session(+ state: &Arc<Mutex<AppState>>,+ session_id: &str,+ project_path: &str,+) -> Result<lifecycle::CreatedWorktree, JsonRpcError> {+ match lifecycle::create_session_worktree(state, &GitRunner::default(), session_id, project_path)+ .await+ {+ Ok(created) => Ok(created),+ Err(error) => {+ let st = state.lock().await;+ if let Err(cleanup) = sessions::delete_session(&st.db, session_id) {+ tracing::warn!(%cleanup, "could not delete a session whose worktree failed");+ }+ Err(to_rpc(error))+ }+ }+}++/// Remove an isolated session's worktrees and branches before the session row+/// is deleted. A failure keeps the session (nothing is half-removed silently).+pub(super) async fn remove_before_delete(+ state: &Arc<Mutex<AppState>>,+ session_id: &str,+) -> Result<(), JsonRpcError> {+ let has_worktrees = {+ let st = state.lock().await;+ !registry::for_session(&st.db, session_id)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?+ .is_empty()+ };+ if !has_worktrees {+ return Ok(());+ }+ lifecycle::remove_session_worktrees(state, &GitRunner::default(), session_id)+ .await+ .map_err(to_rpc)+}++/// After any deletion, remove worktrees orphaned by other deletion paths.+pub(super) fn spawn_orphan_cleanup(state: &Arc<Mutex<AppState>>) {+ let state = state.clone();+ tokio::spawn(async move {+ lifecycle::cleanup_orphans(&state, &GitRunner::default()).await;+ });+}++#[cfg(test)]+mod tests;diff --cc crates/host-core/src/rpc/worktree_rpc/tests.rsindex 17892807c,000000000..e641ab5c6mode 100644,000000..100644--- a/crates/host-core/src/rpc/worktree_rpc/tests.rs+++ b/crates/host-core/src/rpc/worktree_rpc/tests.rs@@@ -1,389 -1,0 +1,389 @@@- //! Representative user path through the real RPC entry point (ADR 0328):++//! Representative user path through the real RPC entry point (ADR 0329):+//! probe -> create isolated session -> agent writes and runs Bash in the+//! worktree -> preview -> merge -> delete.++use std::collections::HashMap;+use std::fs;+use std::path::{Path, PathBuf};+use std::sync::Arc;++use serde_json::{json, Value};+use tokio::sync::{mpsc, Mutex};++use super::super::{handle_request, requires_external_path_permission, resolve_tool_workspace};+use crate::session_worktrees::lifecycle;+use crate::session_worktrees::test_support::{git_cmd, init_repo};+use crate::state::AppState;++async fn call(state: &Arc<Mutex<AppState>>, method: &str, params: Value) -> Result<Value, Value> {+ handle_request(state.clone(), method, params, mpsc::unbounded_channel().0)+ .await+ .map_err(|error| {+ json!({+ "code": error.code,+ "errorCode": error.data.as_ref().and_then(|data| data.get("errorCode")).cloned(),+ })+ })+}++fn tool_options(+ bash: Option<crate::tools::BashExecutionOptions>,+) -> crate::tools::ToolExecutionOptions<'static> {+ crate::tools::ToolExecutionOptions {+ timeout_ms: None,+ bash_options: bash,+ allow_external_paths: false,+ hashline: None,+ }+}++fn canonical(path: &Path) -> PathBuf {+ crate::workspace::simple_canonicalize(path).unwrap()+}++#[tokio::test]+async fn isolated_session_user_path_from_create_to_delete() {+ let dir = tempfile::tempdir().unwrap();+ let project = init_repo(&dir.path().join("project"));+ fs::write(project.join("f.txt"), "base\n").unwrap();+ git_cmd(&project, &["add", "f.txt"]);+ git_cmd(&project, &["commit", "-q", "-m", "f"]);+ let data = dir.path().join("data");+ fs::create_dir_all(&data).unwrap();+ let mut app = AppState::open(&data).unwrap();+ app.handshook = true;+ let state = Arc::new(Mutex::new(app));+ let project_text = project.to_string_lossy().into_owned();++ let probe = call(+ &state,+ "worktree.probe",+ json!({ "projectPath": project_text }),+ )+ .await+ .unwrap();+ assert_eq!(probe["available"], true);+ assert_eq!(probe["uncommittedChanges"], false);++ let created = call(+ &state,+ "session.create",+ json!({ "projectPath": project_text, "isolated": true, "title": "Feature" }),+ )+ .await+ .unwrap();+ let session_id = created["session"]["id"].as_str().unwrap().to_string();+ let branch = created["session"]["worktree"]["branch"]+ .as_str()+ .unwrap()+ .to_string();+ assert_eq!(created["worktree"]["worktree"]["status"], "active");+ let listed = call(&state, "session.list", json!({})).await.unwrap();+ let row = listed["sessions"]+ .as_array()+ .unwrap()+ .iter()+ .find(|session| session["id"] == session_id.as_str())+ .unwrap();+ assert_eq!(row["worktree"]["branch"], branch.as_str());++ // Every tool of the session resolves to the worktree, not the project.+ let (root, env) = {+ let st = state.lock().await;+ (+ PathBuf::from(resolve_tool_workspace(&st, &session_id).unwrap().unwrap()),+ lifecycle::tool_env(&st.db, &session_id),+ )+ };+ assert!(!canonical(&root).starts_with(canonical(&project)));++ let written = crate::tools::execute_tool_with_path_access(+ Some(&root),+ None,+ "Write",+ &json!({ "path": "f.txt", "content": "isolated\n" }),+ tool_options(None),+ )+ .await;+ assert!(written.ok, "{:?}", written.content);+ assert_eq!(fs::read_to_string(project.join("f.txt")).unwrap(), "base\n");++ // The main checkout is outside the root, so it needs the existing+ // external-path permission; isolation does not weaken containment.+ assert!(requires_external_path_permission(+ Some(&root.to_string_lossy()),+ None,+ "Write",+ &json!({ "path": project.join("f.txt").to_string_lossy() }),+ ));++ let env_map: HashMap<_, _> = env.iter().cloned().collect();+ // Bash runs in the default command shell: PowerShell on Windows.+ let shell_id = crate::tools::shell::default_shell_id();+ let probe = if crate::tools::shell::dialect_for_id(shell_id) == Some("powershell") {+ "(Get-Location).Path; Write-Output $env:PI_PORT"+ } else {+ "pwd; printf %s \"$PI_PORT\""+ };+ let bash = crate::tools::execute_tool_with_path_access(+ Some(&root),+ None,+ "Bash",+ &json!({ "command": probe }),+ tool_options(Some(crate::tools::BashExecutionOptions {+ session_id: session_id.clone(),+ tool_call_id: "t1".into(),+ command_shell_id: shell_id.into(),+ timeout_ms: None,+ cancellation: None,+ output_tx: None,+ extra_env: env,+ })),+ )+ .await;+ assert!(bash.ok, "{:?}", bash.content);+ let stdout = bash.content["stdout"].as_str().unwrap();+ assert!(stdout.contains(&env_map["PI_PORT"]), "{stdout}");+ assert_eq!(+ canonical(Path::new(stdout.lines().next().unwrap().trim())),+ canonical(&root)+ );++ let preview = call(+ &state,+ "worktree.preview",+ json!({ "sessionId": session_id }),+ )+ .await+ .unwrap();+ let files = preview["preview"]["files"].as_array().unwrap();+ assert!(files.iter().any(|file| file["path"] == "f.txt"));+ let token = preview["preview"]["previewToken"]+ .as_str()+ .unwrap()+ .to_string();++ let stale = call(+ &state,+ "worktree.merge",+ json!({ "sessionId": session_id, "previewToken": "stale" }),+ )+ .await+ .unwrap_err();+ assert_eq!(stale["code"], 1025);+ assert_eq!(stale["errorCode"], "WORKTREE_CHANGED_SINCE_PREVIEW");++ let merged = call(+ &state,+ "worktree.merge",+ json!({ "sessionId": session_id, "previewToken": token }),+ )+ .await+ .unwrap();+ assert_eq!(merged["outcome"]["result"], "merged");+ assert_eq!(+ fs::read_to_string(project.join("f.txt")).unwrap(),+ "isolated\n"+ );+ assert!(git_cmd(&project, &["log", "--format=%s", "-1"]).contains("pi: Feature"));++ let moved = call(+ &state,+ "session.moveProject",+ json!({ "sessionId": session_id, "projectPath": dir.path().to_string_lossy() }),+ )+ .await+ .unwrap_err();+ assert_eq!(moved["errorCode"], "WORKTREE_MOVE_UNSUPPORTED");++ let pending = call(+ &state,+ "worktree.pendingWork",+ json!({ "sessionId": session_id }),+ )+ .await+ .unwrap();+ assert_eq!(pending["pending"]["unmergedCommits"], 0);+ assert_eq!(pending["pending"]["uncommittedChanges"], false);++ let deleted = call(&state, "session.delete", json!({ "id": session_id }))+ .await+ .unwrap();+ assert_eq!(deleted["ok"], true);+ assert!(!root.exists());+ assert!(!git_cmd(&project, &["branch", "--list"]).contains(&branch));+}++#[tokio::test]+async fn an_isolated_session_is_not_created_for_a_project_without_git() {+ let dir = tempfile::tempdir().unwrap();+ let plain = dir.path().join("plain");+ fs::create_dir_all(&plain).unwrap();+ let data = dir.path().join("data");+ fs::create_dir_all(&data).unwrap();+ let mut app = AppState::open(&data).unwrap();+ app.handshook = true;+ let state = Arc::new(Mutex::new(app));++ let probe = call(&state, "worktree.probe", json!({ "projectPath": plain }))+ .await+ .unwrap();+ assert_eq!(probe["available"], false);+ assert_eq!(probe["errorCode"], "WORKTREE_NOT_GIT");++ let error = call(+ &state,+ "session.create",+ json!({ "projectPath": plain, "isolated": true }),+ )+ .await+ .unwrap_err();+ assert_eq!(error["errorCode"], "WORKTREE_NOT_GIT");+ let listed = call(&state, "session.list", json!({})).await.unwrap();+ assert!(listed["sessions"].as_array().unwrap().is_empty());++ // Without `isolated`, the same project creates an ordinary session.+ let ordinary = call(&state, "session.create", json!({ "projectPath": plain }))+ .await+ .unwrap();+ assert!(ordinary["session"].get("worktree").is_none());+}++/// Through `tools.execute`: an agent Write that resolves the last conflict+/// clears the session's conflict badge in `session.list`.+#[tokio::test]+async fn resolving_a_conflict_through_a_tool_call_clears_the_badge() {+ let dir = tempfile::tempdir().unwrap();+ let project = init_repo(&dir.path().join("project"));+ fs::write(project.join("f.txt"), "base\n").unwrap();+ git_cmd(&project, &["add", "f.txt"]);+ git_cmd(&project, &["commit", "-q", "-m", "f"]);+ let data = dir.path().join("data");+ fs::create_dir_all(&data).unwrap();+ let mut app = AppState::open(&data).unwrap();+ app.handshook = true;+ let state = Arc::new(Mutex::new(app));+ let project_text = project.to_string_lossy().into_owned();+ call(+ &state,+ "settings.set",+ json!({ "defaultPermissionMode": "auto" }),+ )+ .await+ .unwrap();+ let created = call(+ &state,+ "session.create",+ json!({ "projectPath": project_text, "isolated": true, "mode": "agent" }),+ )+ .await+ .unwrap();+ let session_id = created["session"]["id"].as_str().unwrap().to_string();+ let root = {+ let st = state.lock().await;+ PathBuf::from(resolve_tool_workspace(&st, &session_id).unwrap().unwrap())+ };+ fs::write(root.join("f.txt"), "session\n").unwrap();+ fs::write(project.join("f.txt"), "project\n").unwrap();+ git_cmd(&project, &["commit", "-q", "-am", "project"]);+ let preview = call(+ &state,+ "worktree.preview",+ json!({ "sessionId": session_id }),+ )+ .await+ .unwrap();+ let token = preview["preview"]["previewToken"].clone();+ let refused = call(+ &state,+ "worktree.merge",+ json!({ "sessionId": session_id, "previewToken": token }),+ )+ .await+ .unwrap_err();+ assert_eq!(refused["errorCode"], "WORKTREE_CONFLICT");+ let badge = |listed: &Value| {+ listed["sessions"]+ .as_array()+ .unwrap()+ .iter()+ .find(|session| session["id"] == session_id.as_str())+ .unwrap()["worktree"]["status"]+ .clone()+ };+ assert_eq!(+ badge(&call(&state, "session.list", json!({})).await.unwrap()),+ "conflict"+ );++ let written = call(+ &state,+ "tools.execute",+ json!({+ "sessionId": session_id,+ "toolCallId": "resolve-1",+ "mode": "agent",+ "toolName": "Write",+ "args": { "path": "f.txt", "content": "both\n" },+ }),+ )+ .await+ .unwrap();+ assert_eq!(written["ok"], true, "{written}");+ assert_eq!(+ badge(&call(&state, "session.list", json!({})).await.unwrap()),+ "active"+ );+}++/// `worktree.behind` and `worktree.sync` through the RPC entry point.+#[tokio::test]+async fn sync_from_project_through_rpc() {+ let dir = tempfile::tempdir().unwrap();+ let project = init_repo(&dir.path().join("project"));+ fs::write(project.join("f.txt"), "base\n").unwrap();+ git_cmd(&project, &["add", "f.txt"]);+ git_cmd(&project, &["commit", "-q", "-m", "f"]);+ let data = dir.path().join("data");+ fs::create_dir_all(&data).unwrap();+ let mut app = AppState::open(&data).unwrap();+ app.handshook = true;+ let state = Arc::new(Mutex::new(app));+ let created = call(+ &state,+ "session.create",+ json!({ "projectPath": project.to_string_lossy(), "isolated": true }),+ )+ .await+ .unwrap();+ let session_id = created["session"]["id"].as_str().unwrap().to_string();+ assert_eq!(behind(&state, &session_id).await, 0);+ fs::write(project.join("g.txt"), "new\n").unwrap();+ git_cmd(&project, &["add", "g.txt"]);+ git_cmd(&project, &["commit", "-q", "-m", "g"]);+ assert_eq!(behind(&state, &session_id).await, 1);++ let synced = call(&state, "worktree.sync", json!({ "sessionId": session_id }))+ .await+ .unwrap();+ assert_eq!(+ synced["outcome"],+ json!({ "result": "synced", "commits": 1 })+ );+ let root = {+ let st = state.lock().await;+ PathBuf::from(resolve_tool_workspace(&st, &session_id).unwrap().unwrap())+ };+ assert_eq!(fs::read_to_string(root.join("g.txt")).unwrap(), "new\n");+ let again = call(&state, "worktree.sync", json!({ "sessionId": session_id }))+ .await+ .unwrap();+ assert_eq!(again["outcome"], json!({ "result": "upToDate" }));+}++async fn behind(state: &Arc<Mutex<AppState>>, session_id: &str) -> Value {+ call(state, "worktree.behind", json!({ "sessionId": session_id }))+ .await+ .unwrap()["commits"]+ .clone()+}diff --cc crates/host-core/src/session_worktrees/delegate.rsindex e36dd53bd,000000000..99dab6f41mode 100644,000000..100644--- a/crates/host-core/src/session_worktrees/delegate.rs+++ b/crates/host-core/src/session_worktrees/delegate.rs@@@ -1,447 -1,0 +1,447 @@@- //! Worktrees for the Write/Edit subagents of an isolated session (ADR 0328,++//! Worktrees for the Write/Edit subagents of an isolated session (ADR 0329,+//! PRD R7/R7a).+//!+//! A delegate worktree branches from the session branch; the session worktree+//! is its owner. When the subagent ends its work is merged back with the same+//! algorithm as "Merge into project" (`merge::land`): conflicts stay in the+//! delegate worktree and the session worktree is only fast-forwarded. The+//! session is held while its worktree changes (`SessionHold`), so the parent's+//! tools do not interleave with the merge; anything git+//! still refuses keeps the subagent branch for a later retry, never forced.+//!+//! The runtime names a delegate by its chain id, so a resumed subagent keeps+//! its worktree (and any conflict it has to resolve).++use std::path::{Path, PathBuf};+use std::time::Duration;++use serde::Serialize;++use super::git::GitRunner;+use super::include::copy_included;+use super::lifecycle::{+ discard_failed_creation, ensure_branch_free, env_for, missing_error, port_is_free, run_setup,+ setup_command, short_id, unmerged_commits, SharedState, WorktreeSummary,+};+use super::merge::{self, commit_all, commits_ahead, land, merge_in_progress};+use super::probe::BRANCH_NAMESPACE;+use super::registry::{self, NewWorktree, SetupStatus, WorktreeRow, WorktreeStatus};+use super::remove::{drop_admin_entry, remove_worktree};+use super::{repo_lock, WorktreeError};+use crate::db::Database;+use crate::sessions;+use crate::tool_budget::{SessionExclusivePermit, ToolPermit};++/// What happened to a subagent's worktree when it ended; reported to the+/// parent agent in the delegate report.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase", tag = "result")]+pub enum DelegateSettlement {+ /// The subagent had no worktree (read-only, or not an isolated session).+ None,+ /// Nothing changed; the worktree and branch were removed.+ NoChanges,+ /// Its commits are now on the session branch; worktree and branch removed.+ Merged { commits: u64 },+ /// A conflict with the session branch stays in the subagent's worktree.+ Conflict { files: Vec<String> },+ /// git refused the fast-forward (or the session was busy); kept for retry.+ NotMerged { reason: String },+ /// The run did not complete; its changes are kept for a resume.+ Kept,+}++/// Tool root of a delegate that has its own worktree; `None` for every other+/// call (no delegation id, or a delegate without a worktree).+pub fn tool_root(+ db: &Database,+ session_id: &str,+ delegation_id: Option<&str>,+) -> Result<Option<PathBuf>, WorktreeError> {+ let Some(delegation_id) = delegation_id else {+ return Ok(None);+ };+ let Some(row) = registry::for_owner(db, session_id, Some(delegation_id))? else {+ return Ok(None);+ };+ let root = row.workspace_root();+ if row.status == WorktreeStatus::Missing || !root.is_dir() {+ return Err(missing_error());+ }+ Ok(Some(root))+}++/// Shell environment of a delegate's own worktree, else the session's.+pub fn tool_env(+ db: &Database,+ session_id: &str,+ delegation_id: Option<&str>,+) -> Vec<(String, String)> {+ let row =+ delegation_id.and_then(|id| registry::for_owner(db, session_id, Some(id)).ok().flatten());+ match row {+ Some(row) => {+ let project = sessions::session_summary(db, session_id)+ .ok()+ .flatten()+ .and_then(|summary| summary.project_path);+ env_for(&row, project.as_deref())+ }+ None => super::lifecycle::tool_env(db, session_id),+ }+}++async fn session_row(state: &SharedState, session_id: &str) -> Result<WorktreeRow, WorktreeError> {+ let st = state.lock().await;+ let row = registry::for_owner(&st.db, session_id, None)?.ok_or_else(|| {+ WorktreeError::new(+ "WORKTREE_NOT_ISOLATED",+ "the session has no isolated worktree",+ )+ })?;+ if row.status == WorktreeStatus::Missing || !Path::new(&row.path).is_dir() {+ return Err(missing_error());+ }+ Ok(row)+}++/// How long a subagent's create/merge waits for the session's in-flight tools+/// before it falls back to holding only the write permit.+const SESSION_QUIET_WAIT: Duration = Duration::from_secs(5);++/// Keeps the session's own tools away from its worktree while held.+enum SessionHold {+ /// No tool of the session runs; new ones wait.+ Exclusive { _permit: SessionExclusivePermit },+ /// A long tool (for example a test run in Bash) kept running: only the+ /// parent's Write/Edit are held back. git refuses what still collides,+ /// which keeps the subagent branch instead of forcing it.+ Writes { _permit: ToolPermit },+}++/// Commit the session worktree's uncommitted work while holding the session+/// (see `SessionHold`), so no tool of the parent lands mid-commit.+async fn checkpoint_session(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+ session: &WorktreeRow,+ message: &str,+) -> Result<SessionHold, WorktreeError> {+ let budget = state.lock().await.tool_budget.clone();+ let hold = match budget+ .acquire_session_exclusive(session_id, SESSION_QUIET_WAIT)+ .await+ {+ Some(permit) => SessionHold::Exclusive { _permit: permit },+ None => {+ let permit = budget.acquire(session_id, "Write").await.map_err(|_| {+ WorktreeError::new(+ "WORKTREE_BUSY",+ "the session is busy writing files; try again",+ )+ })?;+ SessionHold::Writes { _permit: permit }+ }+ };+ let root = Path::new(&session.path);+ if merge_in_progress(git, root).await? {+ return Err(WorktreeError::new(+ "WORKTREE_BUSY",+ "the session has an unfinished merge conflict; resolve it first",+ ));+ }+ commit_all(git, root, message).await?;+ Ok(hold)+}++/// Re-create a vanished delegate worktree on its existing branch so the+/// subagent's committed work survives a resume; `None` when the branch is+/// gone too. The caller holds the repo lock.+async fn reattach(+ state: &SharedState,+ git: &GitRunner,+ session: &WorktreeRow,+ row: WorktreeRow,+) -> Result<Option<WorktreeRow>, WorktreeError> {+ let common_dir = Path::new(&row.common_dir);+ let branch_exists = git+ .run_git_dir(+ common_dir,+ &[+ "show-ref",+ "--verify",+ "--quiet",+ &merge::head_ref(&row.branch),+ ],+ )+ .await+ .is_ok();+ if !branch_exists {+ return Ok(None);+ }+ drop_admin_entry(common_dir, Path::new(&row.path))?;+ git.run(+ Path::new(&session.path),+ &["worktree", "add", "-q", &row.path, &row.branch],+ )+ .await?;+ git.run(+ Path::new(&row.path),+ &[+ "worktree",+ "lock",+ "--reason",+ "PI-Desktop subagent",+ &row.path,+ ],+ )+ .await?;+ let st = state.lock().await;+ registry::set_status(&st.db, &row.id, WorktreeStatus::Active)?;+ Ok(Some(registry::get(&st.db, &row.id)?.unwrap_or(row)))+}+/// Create (or, for a resumed subagent, reuse) a delegate worktree branched from+/// the session's current state.+pub async fn create_delegate_worktree(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+ delegation_id: &str,+) -> Result<WorktreeSummary, WorktreeError> {+ let session = session_row(state, session_id).await?;+ let existing = registry::for_owner(&state.lock().await.db, session_id, Some(delegation_id))?;+ if let Some(row) = existing {+ let _guard = repo_lock::lock(Path::new(&row.common_dir)).await;+ if row.status != WorktreeStatus::Creating {+ if Path::new(&row.path).is_dir() {+ // A re-attach that failed after `worktree add` left the+ // folder back but the row `missing`; the folder decides.+ if row.status == WorktreeStatus::Missing {+ let st = state.lock().await;+ registry::set_status(&st.db, &row.id, WorktreeStatus::Active)?;+ return Ok(summary(®istry::get(&st.db, &row.id)?.unwrap_or(row)));+ }+ return Ok(summary(&row));+ }+ if let Some(row) = reattach(state, git, &session, row.clone()).await? {+ return Ok(summary(&row));+ }+ }+ remove_worktree(git, &row).await?;+ registry::remove(&state.lock().await.db, &row.id)?;+ }++ let _guard = repo_lock::lock(Path::new(&session.common_dir)).await;+ {+ // The subagent starts from what the parent has written so far.+ let _permit = checkpoint_session(+ state,+ git,+ session_id,+ &session,+ "pi: checkpoint before subagent",+ )+ .await?;+ }++ let name = format!("{}-{}", short_id(session_id), short_id(delegation_id));+ let parent = Path::new(&session.path)+ .parent()+ .ok_or_else(|| WorktreeError::new("WORKTREE_INTERNAL", "session worktree has no parent"))?;+ let root = parent.join(&name);+ if root.exists() {+ return Err(WorktreeError::new(+ "WORKTREE_PATH_EXISTS",+ format!("{} already exists", root.display()),+ ));+ }+ let branch = format!("{BRANCH_NAMESPACE}/{name}");+ ensure_branch_free(git, Path::new(&session.path), &branch).await?;+ let root_text = root.to_string_lossy().into_owned();+ let project_path = sessions::session_summary(&state.lock().await.db, session_id)?+ .and_then(|summary| summary.project_path);++ let row = {+ let st = state.lock().await;+ let port = registry::next_port_base(&st.db, port_is_free)?;+ registry::insert(+ &st.db,+ &NewWorktree {+ session_id,+ delegation_id: Some(delegation_id),+ path: &root_text,+ common_dir: &session.common_dir,+ prefix: &session.prefix,+ branch: &branch,+ owner_branch: &session.branch,+ port_base: port,+ },+ )?+ };++ let session_root = Path::new(&session.path);+ let created: Result<(), WorktreeError> = async {+ git.run(+ session_root,+ &[+ "worktree",+ "add",+ "-q",+ "-b",+ &branch,+ &root_text,+ &merge::head_ref(&session.branch),+ ],+ )+ .await?;+ git.run(+ &root,+ &[+ "worktree",+ "lock",+ "--reason",+ &format!("PI-Desktop subagent {delegation_id}"),+ &root_text,+ ],+ )+ .await?;+ if let Some(project) = project_path.as_deref() {+ let toplevel = git+ .run(Path::new(project), &["rev-parse", "--show-toplevel"])+ .await?;+ copy_included(git, Path::new(toplevel.trim()), &root).await?;+ }+ Ok(())+ }+ .await;+ if let Err(error) = created {+ discard_failed_creation(state, git, &row).await;+ return Err(error);+ }++ let (row, command) = {+ let st = state.lock().await;+ registry::set_status(&st.db, &row.id, WorktreeStatus::Active)?;+ let command = match project_path.as_deref() {+ Some(project) => setup_command(&st.db, project)?,+ None => None,+ };+ let status = if command.is_some() {+ SetupStatus::Running+ } else {+ SetupStatus::None+ };+ registry::set_setup_status(&st.db, &row.id, status, None)?;+ (registry::get(&st.db, &row.id)?.unwrap_or(row), command)+ };+ if let (Some(command), Some(project)) = (command, project_path) {+ tokio::spawn(run_setup(state.clone(), row.clone(), project, command));+ }+ Ok(summary(&row))+}++/// Settle a subagent's worktree when it ends. `merge` is true for a completed+/// run; a failed or stopped run keeps changes for a resume.+pub async fn settle_delegate_worktree(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+ delegation_id: &str,+ merge: bool,+) -> Result<DelegateSettlement, WorktreeError> {+ let Some(row) = registry::for_owner(&state.lock().await.db, session_id, Some(delegation_id))?+ else {+ return Ok(DelegateSettlement::None);+ };+ let _guard = repo_lock::lock(Path::new(&row.common_dir)).await;+ let worktree = Path::new(&row.path);+ if !worktree.is_dir() {+ // The folder vanished; its branch may still hold committed work,+ // which a resume re-attaches instead of deleting.+ if unmerged_commits(git, &row).await? > 0 {+ registry::set_status(&state.lock().await.db, &row.id, WorktreeStatus::Missing)?;+ return Ok(DelegateSettlement::Kept);+ }+ drop_row(state, git, &row).await?;+ return Ok(DelegateSettlement::NoChanges);+ }++ let resolving = merge_in_progress(git, worktree).await?;+ if !merge {+ let changed = resolving+ || commits_ahead(git, &row).await? > 0+ || !merge::worktree_status(git, worktree).await?.is_empty();+ if changed {+ return Ok(DelegateSettlement::Kept);+ }+ drop_row(state, git, &row).await?;+ return Ok(DelegateSettlement::NoChanges);+ }++ // An unfinished merge is concluded by `land` once its markers are gone;+ // committing it here could seal unresolved conflict markers.+ if !resolving {+ commit_all(git, worktree, "pi: subagent changes").await?;+ }+ let commits = commits_ahead(git, &row).await?;+ if commits == 0 && !resolving {+ drop_row(state, git, &row).await?;+ return Ok(DelegateSettlement::NoChanges);+ }++ let session = session_row(state, session_id).await?;+ let permit = match checkpoint_session(+ state,+ git,+ session_id,+ &session,+ "pi: checkpoint before merging subagent",+ )+ .await+ {+ Ok(permit) => permit,+ Err(error) => {+ return Ok(DelegateSettlement::NotMerged {+ reason: error.message,+ })+ }+ };+ let landed = land(git, &row, Path::new(&session.path), "pi: subagent changes").await;+ drop(permit);+ match landed {+ Ok(()) => {+ drop_row(state, git, &row).await?;+ Ok(DelegateSettlement::Merged { commits })+ }+ Err(error) if error.code == "WORKTREE_CONFLICT" => {+ registry::set_status(&state.lock().await.db, &row.id, WorktreeStatus::Conflict)?;+ Ok(DelegateSettlement::Conflict { files: error.files })+ }+ Err(error) => Ok(DelegateSettlement::NotMerged {+ reason: error.message,+ }),+ }+}++/// Remove a delegate worktree, branch, and row; the caller holds the repo lock.+async fn drop_row(+ state: &SharedState,+ git: &GitRunner,+ row: &WorktreeRow,+) -> Result<(), WorktreeError> {+ remove_worktree(git, row).await?;+ registry::remove(&state.lock().await.db, &row.id)?;+ Ok(())+}++fn summary(row: &WorktreeRow) -> WorktreeSummary {+ WorktreeSummary {+ branch: row.branch.clone(),+ status: row.status,+ setup_status: row.setup_status,+ }+}++#[cfg(test)]+mod tests;diff --cc crates/host-core/src/session_worktrees/git.rsindex 5ac386114,000000000..9e8ca9f8cmode 100644,000000..100644--- a/crates/host-core/src/session_worktrees/git.rs+++ b/crates/host-core/src/session_worktrees/git.rs@@@ -1,364 -1,0 +1,364 @@@- //! The only way host-core runs git for isolated worktrees (ADR 0328).++//! The only way host-core runs git for isolated worktrees (ADR 0329).+//!+//! Every invocation is non-interactive and hardened, because host-core runs+//! these commands on the user's behalf without a permission card:+//!+//! - hooks are disabled. A relative `core.hooksPath` (husky style) resolves+//! inside the worktree, so a hook file written with Write/Edit alone would+//! otherwise run here and bypass the Bash permission;+//! - `core.fsmonitor` is disabled, since it is a config-defined command;+//! - `safe.bareRepository=explicit` refuses implicitly discovered bare+//! repositories;+//! - variables that redirect git to another repository or index are removed.++use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::Duration;++use tokio::process::Command;++#[cfg(windows)]+const NULL_HOOKS_PATH: &str = "NUL";+#[cfg(not(windows))]+const NULL_HOOKS_PATH: &str = "/dev/null";++pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120);++/// Environment that would point git at another repository, index, or config.+const REDIRECT_ENV: &[&str] = &[+ "GIT_DIR",+ "GIT_WORK_TREE",+ "GIT_INDEX_FILE",+ "GIT_COMMON_DIR",+ "GIT_OBJECT_DIRECTORY",+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",+ "GIT_NAMESPACE",+ "GIT_CEILING_DIRECTORIES",+ "GIT_CONFIG_PARAMETERS",+ "GIT_CONFIG_COUNT",+];++#[derive(Debug, thiserror::Error)]+pub enum GitError {+ #[error("git executable was not found")]+ Missing,+ #[error("git could not be started: {0}")]+ Spawn(std::io::Error),+ #[error("git {args} timed out after {secs}s")]+ Timeout { args: String, secs: u64 },+ #[error("git {args} failed with exit code {status}: {stderr}")]+ Failed {+ args: String,+ status: i32,+ stdout: String,+ stderr: String,+ },+}++impl GitError {+ pub fn code(&self) -> &'static str {+ match self {+ GitError::Missing => "WORKTREE_GIT_MISSING",+ GitError::Spawn(_) | GitError::Failed { .. } => "WORKTREE_GIT_FAILED",+ GitError::Timeout { .. } => "WORKTREE_GIT_TIMEOUT",+ }+ }+}++/// Raw result of a git command that is allowed to exit non-zero.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct GitOutput {+ pub status: i32,+ pub stdout: String,+ pub stderr: String,+}++impl GitOutput {+ pub fn success(&self) -> bool {+ self.status == 0+ }+}++#[derive(Debug, Clone)]+pub struct GitRunner {+ program: PathBuf,+ path_env: Option<String>,+ timeout: Duration,+}++impl Default for GitRunner {+ fn default() -> Self {+ Self {+ program: PathBuf::from("git"),+ // GUI launches lack the terminal PATH; use the login PATH the Bash+ // tool already uses (D181) so the same git is found.+ path_env: crate::tools::shell::user_login_path().map(str::to_string),+ timeout: DEFAULT_TIMEOUT,+ }+ }+}++impl GitRunner {+ #[cfg(test)]+ pub fn with_program(program: impl Into<PathBuf>) -> Self {+ Self {+ program: program.into(),+ ..Self::default()+ }+ }++ /// Run git in `dir` and return stdout; a non-zero exit is an error.+ pub async fn run(&self, dir: &Path, args: &[&str]) -> Result<String, GitError> {+ Self::checked(args, self.output(dir, args).await?)+ }++ /// Run git against an explicit git directory (`--git-dir`), for work that+ /// must not depend on a working tree that may already be gone.+ pub async fn run_git_dir(&self, git_dir: &Path, args: &[&str]) -> Result<String, GitError> {+ Self::checked(+ args,+ self.spawn(self.command(Location::GitDir(git_dir), args), args, None)+ .await?,+ )+ }++ fn checked(args: &[&str], output: GitOutput) -> Result<String, GitError> {+ if output.success() {+ Ok(output.stdout)+ } else {+ Err(GitError::Failed {+ args: args.join(" "),+ status: output.status,+ stdout: output.stdout,+ stderr: output.stderr.trim().to_string(),+ })+ }+ }++ /// Run git in `dir` and return its exit status and output.+ pub async fn output(&self, dir: &Path, args: &[&str]) -> Result<GitOutput, GitError> {+ self.spawn(self.command(Location::WorkTree(dir), args), args, None)+ .await+ }++ /// Like `output`, with `input` written to git's stdin (for `--stdin`).+ pub async fn output_with_input(+ &self,+ dir: &Path,+ args: &[&str],+ input: Vec<u8>,+ ) -> Result<GitOutput, GitError> {+ let mut command = self.command(Location::WorkTree(dir), args);+ command.stdin(Stdio::piped());+ self.spawn(command, args, Some(input)).await+ }++ async fn spawn(+ &self,+ mut command: Command,+ args: &[&str],+ input: Option<Vec<u8>>,+ ) -> Result<GitOutput, GitError> {+ let mut child = command.spawn().map_err(|error| {+ if error.kind() == std::io::ErrorKind::NotFound {+ GitError::Missing+ } else {+ GitError::Spawn(error)+ }+ })?;+ if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {+ // Written concurrently with reading output so a large input cannot+ // deadlock against a full output pipe.+ tokio::spawn(async move {+ use tokio::io::AsyncWriteExt;+ let _ = stdin.write_all(&input).await;+ });+ }+ let output = tokio::time::timeout(self.timeout, child.wait_with_output())+ .await+ .map_err(|_| GitError::Timeout {+ args: args.join(" "),+ secs: self.timeout.as_secs(),+ })?+ .map_err(GitError::Spawn)?;+ Ok(GitOutput {+ // A signal-terminated git has no code; report it as a failure.+ status: output.status.code().unwrap_or(-1),+ stdout: String::from_utf8_lossy(&output.stdout).into_owned(),+ stderr: String::from_utf8_lossy(&output.stderr).into_owned(),+ })+ }++ fn command(&self, location: Location<'_>, args: &[&str]) -> Command {+ let mut command = Command::new(&self.program);+ match location {+ Location::WorkTree(dir) => {+ command.arg("-C").arg(dir);+ }+ Location::GitDir(git_dir) => {+ let mut flag = std::ffi::OsString::from("--git-dir=");+ flag.push(git_dir);+ command.arg(flag);+ }+ }+ command.args([+ "-c",+ &format!("core.hooksPath={NULL_HOOKS_PATH}"),+ "-c",+ "core.fsmonitor=false",+ "-c",+ "safe.bareRepository=explicit",+ ]);+ #[cfg(windows)]+ command.args(["-c", "core.longpaths=true"]);+ command.args(args);+ for name in REDIRECT_ENV {+ command.env_remove(name);+ }+ command+ .env("GIT_TERMINAL_PROMPT", "0")+ // Background reads must not take the index lock (git-status(1),+ // "BACKGROUND REFRESH"); required locks are unaffected.+ .env("GIT_OPTIONAL_LOCKS", "0")+ // Stable, parseable messages regardless of the user's locale.+ .env("LC_ALL", "C");+ if let Some(path) = self.path_env.as_deref() {+ command.env("PATH", path);+ }+ command+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);+ #[cfg(windows)]+ command.creation_flags(0x0800_0000);+ command+ }+}++#[derive(Clone, Copy)]+enum Location<'a> {+ WorkTree(&'a Path),+ GitDir(&'a Path),+}++/// Parse `git version 2.51.0`, `git version 2.39.3 (Apple Git-146)`, or+/// `git version 2.45.1.windows.1` into `(major, minor)`.+pub fn parse_version(text: &str) -> Option<(u32, u32)> {+ let version = text.trim().strip_prefix("git version ")?;+ let mut parts = version.split(|c: char| c == '.' || c.is_whitespace());+ let major = parts.next()?.parse().ok()?;+ let minor = parts.next()?.parse().ok()?;+ Some((major, minor))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::session_worktrees::test_support::init_repo;++ #[test]+ fn parses_release_vendor_and_windows_versions() {+ assert_eq!(parse_version("git version 2.51.0\n"), Some((2, 51)));+ assert_eq!(+ parse_version("git version 2.39.3 (Apple Git-146)"),+ Some((2, 39))+ );+ assert_eq!(parse_version("git version 2.45.1.windows.1"), Some((2, 45)));+ assert_eq!(parse_version("not git"), None);+ }++ #[tokio::test]+ async fn a_missing_executable_is_reported_as_missing() {+ let dir = tempfile::tempdir().unwrap();+ let git = GitRunner::with_program(dir.path().join("no-such-git"));+ let error = git.run(dir.path(), &["--version"]).await.unwrap_err();+ assert_eq!(error.code(), "WORKTREE_GIT_MISSING");+ }++ /// AC13: a hook file the agent could write with Write/Edit alone (a+ /// relative, husky-style `core.hooksPath` inside the worktree) must not run+ /// when host-core commits, checks out, or merges. Git for Windows runs+ /// such a hook through its bundled `sh` without an executable bit.+ #[tokio::test]+ async fn host_initiated_commit_and_merge_never_run_repository_hooks() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(dir.path());+ let git = GitRunner::default();+ git.run(&repo, &["config", "core.hooksPath", ".husky/_"])+ .await+ .unwrap();+ let marker = dir.path().join("hook-ran");+ // `sh` on Windows takes forward slashes.+ let marker_for_sh = marker.display().to_string().replace('\\', "/");+ let hooks = repo.join(".husky/_");+ std::fs::create_dir_all(&hooks).unwrap();+ for hook in [+ "pre-commit",+ "prepare-commit-msg",+ "commit-msg",+ "post-commit",+ "pre-merge-commit",+ "post-merge",+ "post-checkout",+ ] {+ let script = hooks.join(hook);+ std::fs::write(+ &script,+ format!("#!/bin/sh\necho {hook} >> '{marker_for_sh}'\nexit 1\n"),+ )+ .unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ }+ std::fs::write(repo.join("a.txt"), "a").unwrap();+ commit_all_with(&git, &repo, "a").await;+ git.run(&repo, &["checkout", "-q", "-b", "side", "HEAD~1"])+ .await+ .unwrap();+ std::fs::write(repo.join("b.txt"), "b").unwrap();+ commit_all_with(&git, &repo, "b").await;+ git.run(&repo, &["merge", "-q", "--no-edit", "main"])+ .await+ .unwrap();+ assert!(+ !marker.exists(),+ "a repository hook ran during a host git command: {:?}",+ std::fs::read_to_string(&marker).ok()+ );+ }++ async fn commit_all_with(git: &GitRunner, repo: &Path, message: &str) {+ git.run(repo, &["add", "-A", "--", ".", ":!.husky"])+ .await+ .unwrap();+ git.run(repo, &["commit", "-q", "-m", message])+ .await+ .unwrap();+ }++ #[test]+ fn every_command_removes_repository_redirect_variables() {+ let runner = GitRunner::default();+ let command = runner.command(Location::WorkTree(Path::new(".")), &["status"]);+ let envs: Vec<_> = command.as_std().get_envs().collect();+ for name in REDIRECT_ENV {+ assert!(+ envs.iter()+ .any(|(key, value)| *key == std::ffi::OsStr::new(name) && value.is_none()),+ "{name} is not removed"+ );+ }+ let args: Vec<_> = command+ .as_std()+ .get_args()+ .map(|arg| arg.to_string_lossy().into_owned())+ .collect();+ assert!(args.contains(&format!("core.hooksPath={NULL_HOOKS_PATH}")));+ assert!(args.contains(&"core.fsmonitor=false".to_string()));+ assert!(args.contains(&"safe.bareRepository=explicit".to_string()));+ }+}diff --cc crates/host-core/src/session_worktrees/lifecycle.rsindex eea714e6f,000000000..54cc474abmode 100644,000000..100644--- a/crates/host-core/src/session_worktrees/lifecycle.rs+++ b/crates/host-core/src/session_worktrees/lifecycle.rs@@@ -1,885 -1,0 +1,885 @@@- //! Isolated-session worktree lifecycle (ADR 0328): create, resolve, merge,++//! Isolated-session worktree lifecycle (ADR 0329): create, resolve, merge,+//! remove, orphan cleanup, and startup reconciliation.+//!+//! The global `AppState` lock is held only for short registry reads and+//! writes, never across a git command or the setup command.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::Arc;++use anyhow::Result;+use rusqlite::params;+use serde::Serialize;+use serde_json::json;+use tokio::sync::Mutex;++use super::git::GitRunner;+use super::include::{copy_included, IncludeReport};+use super::merge::{self, MergeOutcome, MergePreview, SyncOutcome};+use super::probe::{probe, BRANCH_NAMESPACE};+use super::registry::{self, NewWorktree, SetupStatus, WorktreeRow, WorktreeStatus};+use super::remove::remove_worktree;+use super::{fnv1a64, repo_lock, WorktreeError};+use crate::db::Database;+use crate::sessions;+use crate::state::AppState;++pub type SharedState = Arc<Mutex<AppState>>;++/// Bound for the per-project setup command (dependency installs can be slow).+pub const SETUP_TIMEOUT_MS: u64 = 30 * 60 * 1000;+const SETUP_LOG_LIMIT: usize = 16 * 1024;++/// What the renderer needs to badge a session row; no filesystem paths.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WorktreeSummary {+ pub branch: String,+ pub status: WorktreeStatus,+ pub setup_status: Option<SetupStatus>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct CreatedWorktree {+ pub worktree: WorktreeSummary,+ pub included: IncludeReport,+ /// The main checkout had uncommitted changes that were not carried over.+ pub project_had_uncommitted_changes: bool,+}++/// Unmerged work that deleting the session would lose (delete confirmation).+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PendingWork {+ pub unmerged_commits: u64,+ pub uncommitted_changes: bool,+}++pub fn worktrees_dir(data_dir: &Path) -> PathBuf {+ data_dir.join("worktrees")+}++/// `<sanitized repository name>-<hash of its canonical path>`: readable, and+/// distinct for two repositories with the same folder name.+fn project_key(toplevel: &Path) -> String {+ let name: String = toplevel+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_default()+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' {+ c+ } else {+ '-'+ }+ })+ .take(24)+ .collect();+ let hash = fnv1a64(toplevel.to_string_lossy().as_bytes());+ format!(+ "{}-{:08x}",+ if name.is_empty() { "repo" } else { &name },+ hash as u32+ )+}++pub(super) fn short_id(id: &str) -> String {+ id.chars()+ .filter(char::is_ascii_alphanumeric)+ .take(12)+ .collect()+}++pub(super) fn port_is_free(port: u16) -> bool {+ std::net::TcpListener::bind(("127.0.0.1", port)).is_ok()+}++// ---- project setting --------------------------------------------------------++pub fn setup_command(db: &Database, project_path: &str) -> Result<Option<String>> {+ let path =+ crate::db::canonical_project_path(project_path).unwrap_or_else(|| project_path.to_string());+ Ok(db+ .conn()+ .query_row(+ "SELECT worktree_setup_command FROM projects WHERE path = ?1",+ params![path],+ |row| row.get::<_, Option<String>>(0),+ )+ .ok()+ .flatten()+ .filter(|command| !command.trim().is_empty()))+}++/// Returns false when the project is not registered.+pub fn set_setup_command(db: &Database, project_path: &str, command: Option<&str>) -> Result<bool> {+ let path =+ crate::db::canonical_project_path(project_path).unwrap_or_else(|| project_path.to_string());+ let command = command.map(str::trim).filter(|command| !command.is_empty());+ Ok(db.conn().execute(+ "UPDATE projects SET worktree_setup_command = ?2 WHERE path = ?1",+ params![path, command],+ )? > 0)+}++// ---- resolution (sync, called under the AppState lock) ----------------------++fn own_row(db: &Database, session_id: &str) -> Result<Option<WorktreeRow>, WorktreeError> {+ Ok(registry::for_owner(db, session_id, None)?)+}++/// The tool root of an isolated session, or `None` for every other session.+/// An isolated session never falls back to the main checkout.+pub fn tool_root(db: &Database, session_id: &str) -> Result<Option<PathBuf>, WorktreeError> {+ let Some(row) = own_row(db, session_id)? else {+ return Ok(None);+ };+ match row.status {+ WorktreeStatus::Creating => Err(WorktreeError::new(+ "WORKTREE_NOT_READY",+ "the isolated worktree is still being created",+ )),+ WorktreeStatus::Missing => Err(missing_error()),+ _ => {+ let root = row.workspace_root();+ if root.is_dir() {+ Ok(Some(root))+ } else {+ Err(missing_error())+ }+ }+ }+}++pub(super) fn missing_error() -> WorktreeError {+ WorktreeError::new(+ "WORKTREE_MISSING",+ "the isolated worktree folder no longer exists; delete this session",+ )+}++/// `PI_PORT`, `PI_PROJECT_ROOT`, and `PI_WORKTREE_ROOT` for an isolated+/// session's shell commands (PRD R2d); empty for every other session.+pub fn tool_env(db: &Database, session_id: &str) -> Vec<(String, String)> {+ let Ok(Some(row)) = own_row(db, session_id) else {+ return Vec::new();+ };+ let project = sessions::session_summary(db, session_id)+ .ok()+ .flatten()+ .and_then(|summary| summary.project_path);+ env_for(&row, project.as_deref())+}++pub(super) fn env_for(row: &WorktreeRow, project: Option<&str>) -> Vec<(String, String)> {+ let mut env = vec![(+ "PI_WORKTREE_ROOT".to_string(),+ row.workspace_root().to_string_lossy().into_owned(),+ )];+ if let Some(project) = project {+ env.push(("PI_PROJECT_ROOT".to_string(), project.to_string()));+ }+ if let Some(port) = row.port_base {+ env.push(("PI_PORT".to_string(), port.to_string()));+ }+ env+}++/// Badges for the given sessions' own worktrees, keyed by session id.+pub fn summaries(db: &Database) -> Result<HashMap<String, WorktreeSummary>> {+ let mut statement = db.conn().prepare_cached(+ "SELECT session_id, branch, status, setup_status FROM worktrees+ WHERE session_id IS NOT NULL AND delegation_id IS NULL",+ )?;+ let rows = statement+ .query_map([], |row| {+ Ok((+ row.get::<_, String>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, Option<String>>(3)?,+ ))+ })?+ .collect::<rusqlite::Result<Vec<_>>>()?;+ let mut out = HashMap::new();+ for (session_id, branch, status, setup) in rows {+ let Some(status) = parse_status(&status) else {+ continue;+ };+ out.insert(+ session_id,+ WorktreeSummary {+ branch,+ status,+ setup_status: setup.as_deref().and_then(parse_setup),+ },+ );+ }+ Ok(out)+}++fn parse_status(value: &str) -> Option<WorktreeStatus> {+ WorktreeStatus::parse(value).ok()+}++fn parse_setup(value: &str) -> Option<SetupStatus> {+ SetupStatus::parse(value).ok()+}++fn summary_of(row: &WorktreeRow) -> WorktreeSummary {+ WorktreeSummary {+ branch: row.branch.clone(),+ status: row.status,+ setup_status: row.setup_status,+ }+}++// ---- create -----------------------------------------------------------------++/// Refuse a branch name that already exists, so cleanup after a failed+/// creation never deletes a branch this call did not create.+pub(super) async fn ensure_branch_free(+ git: &GitRunner,+ repo_dir: &Path,+ branch: &str,+) -> Result<(), WorktreeError> {+ let taken = git+ .output(+ repo_dir,+ &["show-ref", "--verify", "--quiet", &merge::head_ref(branch)],+ )+ .await?+ .success();+ if taken {+ return Err(WorktreeError::new(+ "WORKTREE_PATH_EXISTS",+ format!("branch `{branch}` already exists"),+ ));+ }+ Ok(())+}++/// Undo a failed creation. The row (still `creating`) stays when cleanup+/// fails, so the startup or orphan pass retries it instead of leaving an+/// unrecorded directory and branch behind.+pub(super) async fn discard_failed_creation(+ state: &SharedState,+ git: &GitRunner,+ row: &WorktreeRow,+) {+ match remove_worktree(git, row).await {+ Ok(()) => {+ let st = state.lock().await;+ if let Err(error) = registry::remove(&st.db, &row.id) {+ tracing::warn!(%error, "could not unregister a failed worktree creation");+ }+ }+ Err(error) => {+ tracing::warn!(%error, path = %row.path, "could not clean up a failed worktree creation")+ }+ }+}++/// Create the session's own worktree from the project's current branch tip,+/// copy `.worktreeinclude` files, and start the optional setup command in the+/// background. On failure nothing is left behind.+pub async fn create_session_worktree(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+ project_path: &str,+) -> Result<CreatedWorktree, WorktreeError> {+ let project = Path::new(project_path);+ let repo = probe(git, project).await?;+ let project_had_uncommitted_changes = !merge::worktree_status(git, project).await?.is_empty();+ let _guard = repo_lock::lock(&repo.common_dir).await;++ let data_dir = state.lock().await.data_dir.clone();+ let parent = worktrees_dir(&data_dir).join(project_key(&repo.toplevel));+ std::fs::create_dir_all(&parent)?;+ let parent = crate::workspace::simple_canonicalize(&parent)?;+ let name = short_id(session_id);+ let root = parent.join(&name);+ if root.exists() {+ return Err(WorktreeError::new(+ "WORKTREE_PATH_EXISTS",+ format!("{} already exists", root.display()),+ ));+ }+ let branch = format!("{BRANCH_NAMESPACE}/{name}");+ ensure_branch_free(git, project, &branch).await?;+ let root_text = root.to_string_lossy().into_owned();+ let common_dir = repo.common_dir.to_string_lossy().into_owned();++ let row = {+ let st = state.lock().await;+ let port = registry::next_port_base(&st.db, port_is_free)?;+ registry::insert(+ &st.db,+ &NewWorktree {+ session_id,+ delegation_id: None,+ path: &root_text,+ common_dir: &common_dir,+ prefix: &repo.prefix,+ branch: &branch,+ owner_branch: &repo.branch,+ port_base: port,+ },+ )?+ };++ let created: Result<IncludeReport, WorktreeError> = async {+ git.run(+ project,+ &[+ "worktree",+ "add",+ "-q",+ "-b",+ &branch,+ &root_text,+ &merge::head_ref(&repo.branch),+ ],+ )+ .await?;+ git.run(+ &root,+ &[+ "worktree",+ "lock",+ "--reason",+ &format!("PI-Desktop session {session_id}"),+ &root_text,+ ],+ )+ .await?;+ copy_included(git, &repo.toplevel, &root).await+ }+ .await;++ let included = match created {+ Ok(included) => included,+ Err(error) => {+ discard_failed_creation(state, git, &row).await;+ return Err(error);+ }+ };++ let (row, command) = {+ let st = state.lock().await;+ registry::set_status(&st.db, &row.id, WorktreeStatus::Active)?;+ let command = setup_command(&st.db, project_path)?;+ let status = if command.is_some() {+ SetupStatus::Running+ } else {+ SetupStatus::None+ };+ registry::set_setup_status(&st.db, &row.id, status, None)?;+ let row = registry::get(&st.db, &row.id)?.unwrap_or(row);+ (row, command)+ };+ if let Some(command) = command {+ tokio::spawn(run_setup(+ state.clone(),+ row.clone(),+ project_path.to_string(),+ command,+ ));+ }+ Ok(CreatedWorktree {+ worktree: summary_of(&row),+ included,+ project_had_uncommitted_changes,+ })+}++pub(super) async fn run_setup(+ state: SharedState,+ row: WorktreeRow,+ project_path: String,+ command: String,+) {+ let shell_id = {+ let st = state.lock().await;+ let configured = st+ .db+ .get_setting("app")+ .ok()+ .flatten()+ .and_then(|settings| {+ settings+ .get("defaultCommandShell")+ .and_then(|value| value.as_str())+ .map(str::to_string)+ });+ crate::tools::shell::catalog(configured.as_deref())+ .effective+ .map(|option| option.id)+ .unwrap_or_else(|| crate::tools::shell::default_shell_id().to_string())+ };+ let root = row.workspace_root();+ let result = crate::tools::execute_tool_with_path_access(+ Some(&root),+ None,+ "Bash",+ &json!({ "command": command }),+ crate::tools::ToolExecutionOptions {+ timeout_ms: Some(SETUP_TIMEOUT_MS),+ bash_options: Some(crate::tools::BashExecutionOptions {+ session_id: row.session_id.clone().unwrap_or_default(),+ tool_call_id: format!("worktree-setup-{}", row.id),+ command_shell_id: shell_id,+ timeout_ms: Some(SETUP_TIMEOUT_MS),+ cancellation: None,+ output_tx: None,+ extra_env: env_for(&row, Some(&project_path)),+ }),+ allow_external_paths: false,+ hashline: None,+ },+ )+ .await;+ let log = setup_log(&result.content);+ let status = if result.ok {+ SetupStatus::Ok+ } else {+ SetupStatus::Failed+ };+ let st = state.lock().await;+ if let Err(error) = registry::set_setup_status(&st.db, &row.id, status, Some(&log)) {+ tracing::warn!(%error, "could not record the worktree setup result");+ }+}++fn setup_log(content: &serde_json::Value) -> String {+ let text = match content {+ serde_json::Value::String(text) => text.clone(),+ value => {+ let stdout = value.get("stdout").and_then(|v| v.as_str()).unwrap_or("");+ let stderr = value.get("stderr").and_then(|v| v.as_str()).unwrap_or("");+ let exit = value+ .get("exitCode")+ .map(|code| code.to_string())+ .unwrap_or_default();+ format!(+ "{stdout}{}{stderr}\n[exit {exit}]",+ if stderr.is_empty() { "" } else { "\n" }+ )+ }+ };+ if text.len() <= SETUP_LOG_LIMIT {+ return text;+ }+ let mut start = text.len() - SETUP_LOG_LIMIT;+ while !text.is_char_boundary(start) {+ start += 1;+ }+ format!("[earlier output omitted]\n{}", &text[start..])+}++// ---- merge ------------------------------------------------------------------++struct MergeTarget {+ row: WorktreeRow,+ project_path: String,+ title: String,+}++async fn merge_target(state: &SharedState, session_id: &str) -> Result<MergeTarget, WorktreeError> {+ let st = state.lock().await;+ let row = own_row(&st.db, session_id)?.ok_or_else(|| {+ WorktreeError::new(+ "WORKTREE_NOT_ISOLATED",+ "the session has no isolated worktree",+ )+ })?;+ if row.status == WorktreeStatus::Missing || !Path::new(&row.path).is_dir() {+ return Err(missing_error());+ }+ let summary = sessions::session_summary(&st.db, session_id)?+ .ok_or_else(|| WorktreeError::new("WORKTREE_NOT_ISOLATED", "session not found"))?;+ let project_path = summary+ .project_path+ .ok_or_else(|| WorktreeError::new("WORKTREE_NOT_ISOLATED", "the session has no project"))?;+ Ok(MergeTarget {+ row,+ project_path,+ title: summary.title,+ })+}++fn ensure_idle(db: &Database, session_id: &str) -> Result<(), WorktreeError> {+ if sessions::session_has_running_turn(db, session_id)? {+ return Err(WorktreeError::new(+ "WORKTREE_BUSY",+ "the session is running; wait for it to finish",+ ));+ }+ Ok(())+}++pub async fn preview_session(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> Result<MergePreview, WorktreeError> {+ let target = merge_target(state, session_id).await?;+ merge::preview(git, &target.row).await+}++pub async fn merge_session(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+ preview_token: &str,+) -> Result<MergeOutcome, WorktreeError> {+ let target = merge_target(state, session_id).await?;+ ensure_idle(&state.lock().await.db, session_id)?;+ let _guard = repo_lock::lock(Path::new(&target.row.common_dir)).await;+ let result = merge::merge(+ git,+ &target.row,+ Path::new(&target.project_path),+ &target.title,+ preview_token,+ )+ .await;+ let status = match &result {+ Ok(MergeOutcome::Merged { .. }) => Some(WorktreeStatus::Merged),+ Err(error) if error.code == "WORKTREE_CONFLICT" => Some(WorktreeStatus::Conflict),+ _ => None,+ };+ match status {+ Some(status) => {+ let st = state.lock().await;+ registry::set_status(&st.db, &target.row.id, status)?;+ }+ // A failure after the resolution was concluded (for example a dirty+ // project) must not leave a stale conflict badge.+ None if result.is_err() => {+ refresh_conflict_status(state, git, session_id).await;+ }+ None => {}+ }+ result+}++/// How many project commits "Sync from project" would bring in; for the+/// session menu.+pub async fn behind_session(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> Result<u64, WorktreeError> {+ let target = merge_target(state, session_id).await?;+ // Opening the menu also picks up a conflict resolved outside the app.+ refresh_conflict_status(state, git, session_id).await;+ merge::commits_behind(git, &target.row).await+}++/// How many sessions `behind_all` checks at once.+const BEHIND_CONCURRENCY: usize = 8;++/// Result of `behind_all`.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct BehindCounts {+ pub counts: HashMap<String, u64>,+ /// A conflict badge was cleared (resolved outside the app), so the+ /// renderer should refresh its session list.+ pub statuses_changed: bool,+}++/// Project commits each isolated session lacks, keyed by session id, for the+/// sidebar's "behind" marker. Sessions whose count cannot be read (missing+/// folder, owner branch gone) are left out. Conflicted sessions are checked+/// for a resolution first. Runs git outside the state lock, a few sessions at+/// a time; the renderer calls it in the background, never while rendering.+pub async fn behind_all(+ state: &SharedState,+ git: &GitRunner,+) -> Result<BehindCounts, WorktreeError> {+ let rows = registry::all(&state.lock().await.db)?;+ let limit = Arc::new(tokio::sync::Semaphore::new(BEHIND_CONCURRENCY));+ let mut tasks = tokio::task::JoinSet::new();+ for row in rows {+ let Some(session_id) = row.session_id.clone() else {+ continue;+ };+ if row.delegation_id.is_some()+ || matches!(+ row.status,+ WorktreeStatus::Missing | WorktreeStatus::Creating+ )+ || !Path::new(&row.path).is_dir()+ {+ continue;+ }+ let (state, git, limit) = (state.clone(), git.clone(), limit.clone());+ tasks.spawn(async move {+ let _slot = limit.acquire_owned().await.ok();+ let cleared = row.status == WorktreeStatus::Conflict+ && refresh_conflict_status(&state, &git, &session_id).await;+ let count = merge::commits_behind(&git, &row).await.ok();+ (session_id, count, cleared)+ });+ }+ let mut result = BehindCounts::default();+ while let Some(joined) = tasks.join_next().await {+ let Ok((session_id, count, cleared)) = joined else {+ continue;+ };+ result.statuses_changed |= cleared;+ if let Some(count) = count {+ result.counts.insert(session_id, count);+ }+ }+ Ok(result)+}+- /// "Sync from project" (ADR 0328): merge the project's branch into the++/// "Sync from project" (ADR 0329): merge the project's branch into the+/// session's worktree so the session continues on current code. The project+/// checkout is never touched; a conflict stays in the worktree and marks the+/// session, exactly like a merge into the project.+pub async fn sync_session(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> Result<SyncOutcome, WorktreeError> {+ let target = merge_target(state, session_id).await?;+ ensure_idle(&state.lock().await.db, session_id)?;+ let _guard = repo_lock::lock(Path::new(&target.row.common_dir)).await;+ let result =+ merge::sync_from_owner(git, &target.row, &merge::commit_message(&target.title)).await;+ let status = match &result {+ Ok(_) => WorktreeStatus::Active,+ Err(error) if error.code == "WORKTREE_CONFLICT" => WorktreeStatus::Conflict,+ Err(_) => {+ refresh_conflict_status(state, git, session_id).await;+ return result;+ }+ };+ let st = state.lock().await;+ registry::set_status(&st.db, &target.row.id, status)?;+ result+}++/// After the session's own Write/Edit/Bash call: clear a `conflict` badge+/// once the agent resolved every conflict (the merge itself still concludes+/// on "Merge into project") or abandoned the merge. Cheap for every other+/// session: one registry read, no git. Failures only log; the badge then+/// stays until the next merge attempt.+///+/// Returns whether the status was cleared.+pub async fn refresh_conflict_status(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> bool {+ let row = match registry::for_owner(&state.lock().await.db, session_id, None) {+ Ok(Some(row)) if row.status == WorktreeStatus::Conflict => row,+ Ok(_) => return false,+ Err(error) => {+ tracing::warn!(%error, "could not read the worktree registry");+ return false;+ }+ };+ let root = Path::new(&row.path);+ let settled = async {+ Ok::<bool, WorktreeError>(+ !merge::merge_in_progress(git, root).await?+ || merge::conflicts_resolved(git, root).await?,+ )+ }+ .await;+ match settled {+ Ok(true) => {+ let st = state.lock().await;+ match registry::set_status(&st.db, &row.id, WorktreeStatus::Active) {+ Ok(_) => true,+ Err(error) => {+ tracing::warn!(%error, "could not clear the worktree conflict status");+ false+ }+ }+ }+ Ok(false) => false,+ Err(error) => {+ tracing::warn!(%error, path = %row.path, "could not check worktree conflicts");+ false+ }+ }+}++// ---- remove -----------------------------------------------------------------++/// Commits on `row`'s branch that its owner branch lacks. When the owner+/// branch is gone, counts commits no other local branch has, so the delete+/// confirmation never reports lost work as zero. Runs in the repository, so+/// it also works when the worktree folder vanished.+pub(super) async fn unmerged_commits(+ git: &GitRunner,+ row: &WorktreeRow,+) -> Result<u64, WorktreeError> {+ let common_dir = Path::new(&row.common_dir);+ let branch = merge::head_ref(&row.branch);+ let branch_exists = git+ .run_git_dir(common_dir, &["show-ref", "--verify", "--quiet", &branch])+ .await+ .is_ok();+ if !branch_exists {+ return Ok(0);+ }+ let range = format!("{}..{}", merge::head_ref(&row.owner_branch), branch);+ let count = match git+ .run_git_dir(common_dir, &["rev-list", "--count", &range])+ .await+ {+ Ok(count) => count,+ Err(_) => {+ // Every branch of this session (its own and its subagents') goes+ // away with it, so none of them may count as keeping the work.+ let mut args = vec![+ "rev-list".to_string(),+ "--count".to_string(),+ branch.clone(),+ "--not".to_string(),+ ];+ args.push(format!("--exclude={}", row.branch));+ if let Some(session_id) = row.session_id.as_deref() {+ let session_branch = format!("{BRANCH_NAMESPACE}/{}", short_id(session_id));+ args.push(format!("--exclude={session_branch}"));+ args.push(format!("--exclude={session_branch}-*"));+ }+ args.push("--branches".to_string());+ let args: Vec<&str> = args.iter().map(String::as_str).collect();+ git.run_git_dir(common_dir, &args).await?+ }+ };+ count.trim().parse().map_err(|_| {+ WorktreeError::new(+ "WORKTREE_GIT_FAILED",+ format!("unexpected rev-list output: {}", count.trim()),+ )+ })+}++/// Unmerged commits and uncommitted changes across every worktree of the+/// session, for the delete confirmation.+pub async fn pending_work(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> Result<PendingWork, WorktreeError> {+ let rows = registry::for_session(&state.lock().await.db, session_id)?;+ let mut pending = PendingWork::default();+ for row in rows {+ // Counted from the repository, so a vanished folder whose branch+ // still holds commits is still reported before it is deleted.+ pending.unmerged_commits += unmerged_commits(git, &row).await?;+ let root = Path::new(&row.path);+ if root.is_dir() && !merge::worktree_status(git, root).await?.is_empty() {+ pending.uncommitted_changes = true;+ }+ }+ Ok(pending)+}++/// Remove every worktree and branch of a session (delete = discard, PRD R5).+/// Stops at the first failure so the session and the remaining rows stay.+pub async fn remove_session_worktrees(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> Result<(), WorktreeError> {+ let rows = {+ let st = state.lock().await;+ ensure_idle(&st.db, session_id)?;+ registry::for_session(&st.db, session_id)?+ };+ for row in rows.iter().rev() {+ remove_row(state, git, row).await?;+ }+ Ok(())+}++async fn remove_row(+ state: &SharedState,+ git: &GitRunner,+ row: &WorktreeRow,+) -> Result<(), WorktreeError> {+ let _guard = repo_lock::lock(Path::new(&row.common_dir)).await;+ remove_worktree(git, row).await?;+ let st = state.lock().await;+ registry::remove(&st.db, &row.id)?;+ Ok(())+}++/// Remove worktrees whose session was deleted by any path (ON DELETE SET+/// NULL). Returns how many were removed; failures stay for the next pass.+pub async fn cleanup_orphans(state: &SharedState, git: &GitRunner) -> usize {+ let orphans = match registry::orphans(&state.lock().await.db) {+ Ok(rows) => rows,+ Err(error) => {+ tracing::warn!(%error, "could not list orphaned worktrees");+ return 0;+ }+ };+ let mut removed = 0;+ for row in orphans {+ match remove_row(state, git, &row).await {+ Ok(()) => removed += 1,+ Err(error) => {+ tracing::warn!(%error, path = %row.path, "could not remove an orphaned worktree")+ }+ }+ }+ removed+}++/// Startup pass: drop half-created worktrees, mark vanished ones missing,+/// repair git's links after a moved data directory, and clean orphans.+pub async fn reconcile(state: SharedState, git: GitRunner) {+ let rows = match registry::all(&state.lock().await.db) {+ Ok(rows) => rows,+ Err(error) => {+ tracing::warn!(%error, "could not read the worktree registry");+ return;+ }+ };+ for row in rows {+ if row.session_id.is_none() {+ continue;+ }+ if row.status == WorktreeStatus::Creating {+ if let Err(error) = remove_row(&state, &git, &row).await {+ tracing::warn!(%error, path = %row.path, "could not drop a half-created worktree");+ }+ continue;+ }+ let root = Path::new(&row.path);+ if !root.is_dir() {+ let st = state.lock().await;+ let _ = registry::set_status(&st.db, &row.id, WorktreeStatus::Missing);+ continue;+ }+ let common_dir = Path::new(&row.common_dir);+ if common_dir.is_dir() {+ let _guard = repo_lock::lock(common_dir).await;+ if let Err(error) = git+ .run_git_dir(common_dir, &["worktree", "repair", &row.path])+ .await+ {+ tracing::warn!(%error, path = %row.path, "git worktree repair failed");+ }+ }+ }+ cleanup_orphans(&state, &git).await;+}++#[cfg(test)]+mod tests;diff --cc crates/host-core/src/session_worktrees/merge.rsindex 93cac55a3,000000000..3b4c94fa8mode 100644,000000..100644--- a/crates/host-core/src/session_worktrees/merge.rs+++ b/crates/host-core/src/session_worktrees/merge.rs@@@ -1,625 -1,0 +1,625 @@@- //! Preview and "Merge into project" (ADR 0328 decision 4, PRD R4).++//! Preview and "Merge into project" (ADR 0329 decision 4, PRD R4).+//!+//! The project never enters a merge-in-progress state: the owner branch is+//! merged into the session branch inside the worktree, where conflicts stay,+//! and the project branch is only fast-forwarded. git itself refuses a+//! fast-forward that would overwrite uncommitted or untracked project files.++use std::collections::BTreeMap;+use std::path::Path;++use serde::Serialize;++use super::git::GitRunner;+use super::registry::WorktreeRow;+use super::{fnv1a64, WorktreeError};++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PreviewCommit {+ pub sha: String,+ pub subject: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PreviewFile {+ /// `A`, `M`, `D`, ... for committed changes; `?` for untracked files.+ pub status: String,+ pub path: String,+ /// Not committed yet; committed on the session branch when merging.+ pub uncommitted: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MergePreview {+ pub branch: String,+ pub owner_branch: String,+ pub commits: Vec<PreviewCommit>,+ pub files: Vec<PreviewFile>,+ /// True when the worktree holds an unfinished conflict resolution.+ pub conflict: bool,+ /// Opaque; `merge` refuses when the session changed since this preview.+ pub preview_token: String,+}++impl MergePreview {+ pub fn is_empty(&self) -> bool {+ self.commits.is_empty() && self.files.is_empty() && !self.conflict+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase", tag = "result")]+pub enum MergeOutcome {+ Merged { commits: usize, files: usize },+ NothingToMerge,+}++pub async fn preview(git: &GitRunner, row: &WorktreeRow) -> Result<MergePreview, WorktreeError> {+ let worktree = Path::new(&row.path);+ let range = format!("{}..{}", head_ref(&row.owner_branch), head_ref(&row.branch));+ let log = git+ .run(worktree, &["log", "-z", "--format=%H%x1f%s", &range])+ .await?;+ let commits = log+ .split('\0')+ .filter(|record| !record.trim().is_empty())+ .filter_map(|record| {+ let (sha, subject) = record.trim_start_matches('\n').split_once('\u{1f}')?;+ Some(PreviewCommit {+ sha: sha.to_string(),+ subject: subject.to_string(),+ })+ })+ .collect();++ let symmetric = format!(+ "{}...{}",+ head_ref(&row.owner_branch),+ head_ref(&row.branch)+ );+ let diff = git+ .run(+ worktree,+ &["diff", "-z", "--no-renames", "--name-status", &symmetric],+ )+ .await?;+ let mut files: Vec<PreviewFile> = Vec::new();+ let mut fields = diff.split('\0').filter(|field| !field.is_empty());+ while let (Some(status), Some(path)) = (fields.next(), fields.next()) {+ files.push(PreviewFile {+ status: status.chars().take(1).collect(),+ path: path.to_string(),+ uncommitted: false,+ });+ }++ let status = worktree_status(git, worktree).await?;+ for (code, path) in parse_porcelain(&status) {+ let entry = PreviewFile {+ status: code,+ path,+ uncommitted: true,+ };+ match files.iter_mut().find(|file| file.path == entry.path) {+ Some(existing) => *existing = entry,+ None => files.push(entry),+ }+ }+ files.sort_by(|a, b| a.path.cmp(&b.path));++ let conflict = merge_in_progress(git, worktree).await?;+ let head = git.run(worktree, &["rev-parse", "HEAD"]).await?;+ let content = content_fingerprint(git, worktree, &status).await?;+ let token = format!(+ "{:016x}",+ fnv1a64(+ format!(+ "{}\n{}\n{}\n{:016x}",+ head.trim(),+ conflict,+ status,+ content+ )+ .as_bytes()+ )+ );+ Ok(MergePreview {+ branch: row.branch.clone(),+ owner_branch: row.owner_branch.clone(),+ commits,+ files,+ conflict,+ preview_token: token,+ })+}++/// Merge the session branch into the project's current branch. `project` is+/// the project directory (any directory of the main checkout).+pub async fn merge(+ git: &GitRunner,+ row: &WorktreeRow,+ project: &Path,+ title: &str,+ preview_token: &str,+) -> Result<MergeOutcome, WorktreeError> {+ let current = preview(git, row).await?;+ if current.preview_token != preview_token {+ return Err(WorktreeError::new(+ "WORKTREE_CHANGED_SINCE_PREVIEW",+ "the session changed after the preview; review the changes again",+ ));+ }+ if current.is_empty() {+ return Ok(MergeOutcome::NothingToMerge);+ }+ land(git, row, project, &commit_message(title)).await?;+ Ok(MergeOutcome::Merged {+ commits: current.commits.len(),+ files: current.files.len(),+ })+}++/// Land `row`'s branch on its owner branch, which is checked out in+/// `owner_checkout` (the project for a session, the session worktree for a+/// subagent). Uncommitted work is committed with `message` first; the owner+/// branch is merged into `row`'s branch inside its own worktree, where a+/// conflict stays; the owner checkout is only fast-forwarded, and git refuses+/// to overwrite uncommitted files there. Shared by "Merge into project" and- /// the subagent merge-back (ADR 0328).++/// the subagent merge-back (ADR 0329).+pub async fn land(+ git: &GitRunner,+ row: &WorktreeRow,+ owner_checkout: &Path,+ message: &str,+) -> Result<(), WorktreeError> {+ let worktree = Path::new(&row.path);+ // Checked before anything is committed, so a refusal changes nothing.+ let checked_out = git+ .output(owner_checkout, &["symbolic-ref", "--quiet", "HEAD"])+ .await?;+ if !checked_out.success() || checked_out.stdout.trim() != head_ref(&row.owner_branch) {+ return Err(WorktreeError::new(+ "WORKTREE_OWNER_BRANCH_CHANGED",+ format!(+ "the target is no longer on `{}`; check that branch out again to merge",+ row.owner_branch+ ),+ ));+ }++ if merge_in_progress(git, worktree).await? {+ conclude_resolved_merge(git, worktree).await?;+ }+ commit_all(git, worktree, message).await?;++ // One retry covers the owner branch moving between the two steps.+ for attempt in 0..2 {+ sync_owner_into_session(git, worktree, &row.owner_branch).await?;+ let forwarded = git+ .output(+ owner_checkout,+ &["merge", "--ff-only", "--no-edit", &head_ref(&row.branch)],+ )+ .await?;+ if forwarded.success() {+ return Ok(());+ }+ let owner_contained = git+ .output(+ owner_checkout,+ &[+ "merge-base",+ "--is-ancestor",+ &head_ref(&row.owner_branch),+ &head_ref(&row.branch),+ ],+ )+ .await?+ .success();+ if owner_contained || attempt == 1 {+ return Err(WorktreeError::new(+ "WORKTREE_PROJECT_DIRTY",+ format!(+ "uncommitted changes in the target would be overwritten: {}",+ forwarded.stderr.trim()+ ),+ ));+ }+ }+ unreachable!("the loop returns on its second attempt")+}++/// Commit every change in `worktree` with `message`; nothing to do when clean.+pub async fn commit_all(+ git: &GitRunner,+ worktree: &Path,+ message: &str,+) -> Result<bool, WorktreeError> {+ if worktree_status(git, worktree).await?.is_empty() {+ return Ok(false);+ }+ git.run(worktree, &["add", "-A"]).await?;+ git.run(worktree, &["commit", "-q", "-m", message])+ .await+ .map_err(|error| WorktreeError::new("WORKTREE_COMMIT_FAILED", error.to_string()))?;+ Ok(true)+}++/// Commits on `row`'s branch that its owner branch does not have yet.+pub async fn commits_ahead(git: &GitRunner, row: &WorktreeRow) -> Result<u64, WorktreeError> {+ let range = format!("{}..{}", head_ref(&row.owner_branch), head_ref(&row.branch));+ let count = git+ .run(Path::new(&row.path), &["rev-list", "--count", &range])+ .await?;+ Ok(count.trim().parse().unwrap_or(0))+}++/// Commits on `row`'s owner branch that its branch does not have yet, that+/// is, what "Sync from project" would bring in.+pub async fn commits_behind(git: &GitRunner, row: &WorktreeRow) -> Result<u64, WorktreeError> {+ let range = format!("{}..{}", head_ref(&row.branch), head_ref(&row.owner_branch));+ let count = git+ .run(Path::new(&row.path), &["rev-list", "--count", &range])+ .await?;+ Ok(count.trim().parse().unwrap_or(0))+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase", tag = "result")]+pub enum SyncOutcome {+ /// The owner branch's new commits are now on the session branch.+ Synced {+ commits: u64,+ },+ UpToDate,+}++/// "Sync from project": bring the owner branch's new commits into `row`'s+/// branch without touching the owner checkout. Uncommitted session work is+/// committed with `message` first; a conflict stays in the worktree, and an+/// unfinished resolution is concluded first (the same rules as `land`).+pub async fn sync_from_owner(+ git: &GitRunner,+ row: &WorktreeRow,+ message: &str,+) -> Result<SyncOutcome, WorktreeError> {+ let worktree = Path::new(&row.path);+ if merge_in_progress(git, worktree).await? {+ conclude_resolved_merge(git, worktree).await?;+ }+ let behind = commits_behind(git, row).await?;+ if behind == 0 {+ return Ok(SyncOutcome::UpToDate);+ }+ commit_all(git, worktree, message).await?;+ sync_owner_into_session(git, worktree, &row.owner_branch).await?;+ Ok(SyncOutcome::Synced { commits: behind })+}++/// Merge the owner branch into the session branch inside the worktree. A+/// conflict stays in the worktree and is reported with its files.+async fn sync_owner_into_session(+ git: &GitRunner,+ worktree: &Path,+ owner_branch: &str,+) -> Result<(), WorktreeError> {+ let merged = git+ .output(worktree, &["merge", "--no-edit", &head_ref(owner_branch)])+ .await?;+ if merged.success() {+ return Ok(());+ }+ let files = unmerged_files(git, worktree).await?;+ if !files.is_empty() {+ return Err(WorktreeError::conflict(files));+ }+ // Not a content conflict (for example an untracked file in the way):+ // leave the worktree as it was.+ let _ = git.output(worktree, &["merge", "--abort"]).await;+ Err(WorktreeError::new(+ "WORKTREE_MERGE_FAILED",+ merged.stderr.trim().to_string(),+ ))+}++/// Finish a merge whose conflicts were resolved in the worktree. Text files+/// the agent edited but did not `git add` count as resolved once they no+/// longer contain conflict markers (see `resolved_by_edit`).+async fn conclude_resolved_merge(git: &GitRunner, worktree: &Path) -> Result<(), WorktreeError> {+ let stages = conflict_stages(git, worktree).await?;+ let mut unresolved = Vec::new();+ for file in unmerged_files(git, worktree).await? {+ let file_stages = stages.get(&file).map(Vec::as_slice).unwrap_or(&[]);+ if resolved_by_edit(git, worktree, &file, file_stages).await? {+ git.run(worktree, &["add", "--", &file]).await?;+ } else {+ unresolved.push(file);+ }+ }+ if !unresolved.is_empty() {+ return Err(WorktreeError::conflict(unresolved));+ }+ git.run(worktree, &["add", "-A"]).await?;+ git.run(worktree, &["commit", "-q", "--no-edit"])+ .await+ .map_err(|error| WorktreeError::new("WORKTREE_COMMIT_FAILED", error.to_string()))?;+ Ok(())+}++/// Whether every conflict of an unfinished merge in `worktree` is resolved,+/// by the same rule `land` uses to conclude it (`resolved_by_edit`).+pub async fn conflicts_resolved(git: &GitRunner, worktree: &Path) -> Result<bool, WorktreeError> {+ let stages = conflict_stages(git, worktree).await?;+ for file in unmerged_files(git, worktree).await? {+ let file_stages = stages.get(&file).map(Vec::as_slice).unwrap_or(&[]);+ if !resolved_by_edit(git, worktree, &file, file_stages).await? {+ return Ok(false);+ }+ }+ Ok(true)+}++pub async fn unmerged_files(+ git: &GitRunner,+ worktree: &Path,+) -> Result<Vec<String>, WorktreeError> {+ let output = git+ .run(worktree, &["diff", "-z", "--name-only", "--diff-filter=U"])+ .await?;+ let mut files: Vec<String> = output+ .split('\0')+ .filter(|file| !file.is_empty())+ .map(str::to_string)+ .collect();+ files.dedup();+ Ok(files)+}++pub async fn merge_in_progress(git: &GitRunner, worktree: &Path) -> Result<bool, WorktreeError> {+ Ok(git+ .output(worktree, &["rev-parse", "-q", "--verify", "MERGE_HEAD"])+ .await?+ .success())+}++pub async fn worktree_status(git: &GitRunner, worktree: &Path) -> Result<String, WorktreeError> {+ Ok(git+ .run(+ worktree,+ &["status", "--porcelain=v1", "-z", "--untracked-files=all"],+ )+ .await?)+}++/// `XY path\0` entries; renames and copies carry the source as an extra field.+fn parse_porcelain(status: &str) -> Vec<(String, String)> {+ let mut entries = Vec::new();+ let mut fields = status.split('\0').filter(|field| !field.is_empty());+ while let Some(field) = fields.next() {+ if field.len() < 4 {+ continue;+ }+ let (code, path) = field.split_at(3);+ let code = code.trim();+ if code.contains('R') || code.contains('C') {+ fields.next();+ }+ let short = if code == "??" {+ "?".to_string()+ } else {+ code.chars().find(|c| *c != ' ').unwrap_or('M').to_string()+ };+ entries.push((short, path.to_string()));+ }+ entries+}++/// Default length of git's conflict markers (`conflict-marker-size`).+const MARKER_SIZE: usize = 7;++fn has_conflict_markers(content: &[u8], size: usize) -> bool {+ let text = String::from_utf8_lossy(content);+ let is_marker = |line: &str, mark: char| {+ let run = line.chars().take_while(|c| *c == mark).count();+ run == size && matches!(line[run..].chars().next(), None | Some(' ') | Some('\r'))+ };+ text.lines()+ .any(|line| is_marker(line, '<') || is_marker(line, '>'))+}++/// How git merged `path`: whether it writes conflict markers (the default+/// text driver) and with which marker length. `merge=binary`, `-merge`, and+/// custom drivers leave one side in the file without markers.+async fn marker_rules(+ git: &GitRunner,+ worktree: &Path,+ path: &str,+) -> Result<Option<usize>, WorktreeError> {+ let output = git+ .run(+ worktree,+ &[+ "check-attr",+ "-z",+ "merge",+ "conflict-marker-size",+ "--",+ path,+ ],+ )+ .await?;+ let fields: Vec<&str> = output.split('\0').collect();+ let mut merge = "unspecified";+ let mut size = MARKER_SIZE;+ for entry in fields.chunks(3) {+ if let [_, attribute, value] = entry {+ match *attribute {+ "merge" => merge = value,+ "conflict-marker-size" => {+ if let Ok(parsed) = value.parse::<usize>() {+ if parsed > 0 {+ size = parsed;+ }+ }+ }+ _ => {}+ }+ }+ }+ Ok(matches!(merge, "unspecified" | "set" | "text").then_some(size))+}++/// Full ref of a local branch, so a tag with the same short name is never+/// picked instead (git resolves `refs/tags/<name>` before `refs/heads/`).+pub fn head_ref(branch: &str) -> String {+ format!("refs/heads/{branch}")+}++/// Conflict stages (1 base, 2 ours, 3 theirs) of each unmerged path.+async fn conflict_stages(+ git: &GitRunner,+ worktree: &Path,+) -> Result<BTreeMap<String, Vec<char>>, WorktreeError> {+ let output = git.run(worktree, &["ls-files", "-u", "-z"]).await?;+ let mut stages: BTreeMap<String, Vec<char>> = BTreeMap::new();+ for record in output.split('\0').filter(|record| !record.is_empty()) {+ // `<mode> <object> <stage>\t<path>`+ let Some((meta, path)) = record.split_once('\t') else {+ continue;+ };+ if let Some(stage) = meta.rsplit(' ').next().and_then(|s| s.chars().next()) {+ stages.entry(path.to_string()).or_default().push(stage);+ }+ }+ Ok(stages)+}++/// Whether an unstaged conflicted file may be treated as resolved: only a+/// text file changed on both sides and merged by git's text driver, which+/// fills it with conflict markers, once those markers are gone. Binary,+/// delete/modify, add/delete, and `merge=binary` / `-merge` / custom-driver+/// conflicts leave no markers, so they need an explicit `git add`/`git rm`.+async fn resolved_by_edit(+ git: &GitRunner,+ worktree: &Path,+ path: &str,+ stages: &[char],+) -> Result<bool, WorktreeError> {+ if !(stages.contains(&'2') && stages.contains(&'3')) {+ return Ok(false);+ }+ let file = worktree.join(path);+ match std::fs::symlink_metadata(&file) {+ Ok(metadata) if metadata.is_file() => {}+ _ => return Ok(false),+ }+ let Some(size) = marker_rules(git, worktree, path).await? else {+ return Ok(false);+ };+ Ok(match std::fs::read(&file) {+ Ok(content) => !content.contains(&0) && !has_conflict_markers(&content, size),+ Err(_) => false,+ })+}++/// Hash of the worktree's uncommitted content: the tracked diff against+/// `HEAD` plus every untracked file, so a re-edit that leaves `git status`+/// unchanged still invalidates a preview.+async fn content_fingerprint(+ git: &GitRunner,+ worktree: &Path,+ status: &str,+) -> Result<u64, WorktreeError> {+ let diff = git+ .run(+ worktree,+ &["diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv"],+ )+ .await?;+ let untracked: Vec<String> = parse_porcelain(status)+ .into_iter()+ .filter(|(code, _)| code == "?")+ .map(|(_, path)| path)+ .collect();+ let worktree = worktree.to_path_buf();+ // File reads block, so they run off the async workers.+ tokio::task::spawn_blocking(move || {+ let mut hash = fnv1a64(diff.as_bytes());+ for path in untracked {+ hash = fnv_extend(hash, path.as_bytes());+ hash = fnv_extend(hash, &[0]);+ hash = untracked_entry_hash(hash, &worktree.join(&path));+ }+ hash+ })+ .await+ .map_err(|error| WorktreeError::new("WORKTREE_INTERNAL", error.to_string()))+}++/// Bytes of one untracked file read into a preview token. Larger files add+/// their size and modification time instead, so a huge file cannot stall the+/// host; the agent cannot change one without changing either.+const FINGERPRINT_FILE_LIMIT: u64 = 16 * 1024 * 1024;++fn fnv_extend(mut hash: u64, bytes: &[u8]) -> u64 {+ for byte in bytes {+ hash ^= u64::from(*byte);+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);+ }+ hash+}++/// Never follows a link and never opens anything but a regular file, so a+/// link to `/dev/zero` or a FIFO cannot hang or exhaust the host.+fn untracked_entry_hash(hash: u64, path: &Path) -> u64 {+ use std::io::Read;+ let Ok(metadata) = std::fs::symlink_metadata(path) else {+ return fnv_extend(hash, b"missing");+ };+ if metadata.file_type().is_symlink() {+ let target = std::fs::read_link(path).unwrap_or_default();+ return fnv_extend(+ fnv_extend(hash, b"link:"),+ target.to_string_lossy().as_bytes(),+ );+ }+ if !metadata.is_file() {+ return fnv_extend(hash, b"special");+ }+ let modified = metadata+ .modified()+ .ok()+ .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())+ .map_or(0, |duration| duration.as_nanos());+ let hash = fnv_extend(hash, &metadata.len().to_le_bytes());+ if metadata.len() > FINGERPRINT_FILE_LIMIT {+ return fnv_extend(hash, &modified.to_le_bytes());+ }+ let Ok(file) = std::fs::File::open(path) else {+ return fnv_extend(hash, b"unreadable");+ };+ let mut reader = file.take(FINGERPRINT_FILE_LIMIT);+ let mut buffer = [0u8; 64 * 1024];+ let mut hash = hash;+ loop {+ match reader.read(&mut buffer) {+ Ok(0) | Err(_) => break hash,+ Ok(read) => hash = fnv_extend(hash, &buffer[..read]),+ }+ }+}++pub fn commit_message(title: &str) -> String {+ let title = title.trim();+ if title.is_empty() {+ "pi: session changes".to_string()+ } else {+ format!("pi: {}", title.chars().take(72).collect::<String>())+ }+}++#[cfg(test)]+mod tests;diff --cc crates/host-core/src/session_worktrees/mod.rsindex 92cdbaddd,000000000..090d191f7mode 100644,000000..100644--- a/crates/host-core/src/session_worktrees/mod.rs+++ b/crates/host-core/src/session_worktrees/mod.rs@@@ -1,90 -1,0 +1,90 @@@+//! Git worktrees for isolated sessions and their Write/Edit delegates- //! (ADR 0328). host-core owns every worktree path and every git command; the++//! (ADR 0329). host-core owns every worktree path and every git command; the+//! renderer and the agent runtime only name a session or delegation.++pub mod delegate;+pub mod git;+pub mod include;+pub mod lifecycle;+pub mod merge;+pub mod probe;+pub mod registry;+pub mod remove;+mod repo_lock;++#[cfg(test)]+pub(crate) mod test_support;++use git::GitError;+use probe::ProbeError;++/// A failure that reaches the RPC surface with a stable `WORKTREE_*` code.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct WorktreeError {+ pub code: &'static str,+ pub message: String,+ /// Conflicting files for `WORKTREE_CONFLICT`; empty otherwise.+ pub files: Vec<String>,+}++impl WorktreeError {+ pub fn new(code: &'static str, message: impl Into<String>) -> Self {+ Self {+ code,+ message: message.into(),+ files: Vec::new(),+ }+ }++ pub fn conflict(files: Vec<String>) -> Self {+ Self {+ code: "WORKTREE_CONFLICT",+ message: format!(+ "merge conflict in {} file(s); resolve them in the session and merge again",+ files.len()+ ),+ files,+ }+ }+}++impl std::fmt::Display for WorktreeError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}: {}", self.code, self.message)+ }+}++impl From<GitError> for WorktreeError {+ fn from(error: GitError) -> Self {+ Self::new(error.code(), error.to_string())+ }+}++impl From<ProbeError> for WorktreeError {+ fn from(error: ProbeError) -> Self {+ Self::new(error.code(), error.to_string())+ }+}++impl From<anyhow::Error> for WorktreeError {+ fn from(error: anyhow::Error) -> Self {+ Self::new("WORKTREE_INTERNAL", error.to_string())+ }+}++impl From<std::io::Error> for WorktreeError {+ fn from(error: std::io::Error) -> Self {+ Self::new("WORKTREE_IO", error.to_string())+ }+}++/// FNV-1a: a stable hash for directory names and preview tokens. The std+/// hasher is not stable across Rust releases, and these values persist.+pub(crate) fn fnv1a64(bytes: &[u8]) -> u64 {+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;+ for byte in bytes {+ hash ^= u64::from(*byte);+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);+ }+ hash+}diff --cc crates/host-core/src/session_worktrees/probe.rsindex 943f93473,000000000..7d7d71350mode 100644,000000..100644--- a/crates/host-core/src/session_worktrees/probe.rs+++ b/crates/host-core/src/session_worktrees/probe.rs@@@ -1,191 -1,0 +1,191 @@@+//! Decide whether a project can host isolated sessions, and where its- //! repository lives (ADR 0328, PRD R6).++//! repository lives (ADR 0329, PRD R6).++use std::path::{Path, PathBuf};++use serde::Serialize;++use super::git::{parse_version, GitError, GitRunner};++/// `git worktree repair` (used after a project or data directory moves) was+/// added in git 2.29.0.+pub const MIN_GIT_VERSION: (u32, u32) = (2, 29);++/// Every branch host-core creates lives under this namespace.+pub const BRANCH_NAMESPACE: &str = "pi-desktop";++/// Where an isolatable project lives inside its repository.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct RepoInfo {+ /// Canonical repository top level (`git rev-parse --show-toplevel`).+ pub toplevel: PathBuf,+ /// Project directory relative to `toplevel`, `/`-separated with a+ /// trailing slash, empty when the project is the top level.+ pub prefix: String,+ /// Canonical common git directory; the key for per-repository+ /// serialization of mutating git commands.+ pub common_dir: PathBuf,+ /// Branch currently checked out in the project.+ pub branch: String,+}++#[derive(Debug, thiserror::Error)]+pub enum ProbeError {+ #[error("git {found_major}.{found_minor} is older than the required 2.29")]+ GitTooOld { found_major: u32, found_minor: u32 },+ #[error("the project is not inside a git working tree")]+ NotGit,+ #[error("the repository has no commits yet")]+ NoCommits,+ #[error("the project is on a detached HEAD; check out a branch first")]+ DetachedHead,+ #[error("a branch named `pi-desktop` exists, so `pi-desktop/...` branches cannot be created")]+ BranchNamespaceTaken,+ #[error(transparent)]+ Git(#[from] GitError),+}++impl ProbeError {+ pub fn code(&self) -> &'static str {+ match self {+ ProbeError::GitTooOld { .. } => "WORKTREE_GIT_TOO_OLD",+ ProbeError::NotGit => "WORKTREE_NOT_GIT",+ ProbeError::NoCommits => "WORKTREE_NO_COMMITS",+ ProbeError::DetachedHead => "WORKTREE_DETACHED_HEAD",+ ProbeError::BranchNamespaceTaken => "WORKTREE_BRANCH_NAMESPACE_TAKEN",+ ProbeError::Git(error) => error.code(),+ }+ }+}++pub async fn probe(git: &GitRunner, project: &Path) -> Result<RepoInfo, ProbeError> {+ let version = git.run(project, &["--version"]).await?;+ if let Some((major, minor)) = parse_version(&version) {+ if (major, minor) < MIN_GIT_VERSION {+ return Err(ProbeError::GitTooOld {+ found_major: major,+ found_minor: minor,+ });+ }+ }++ let inside = git+ .output(project, &["rev-parse", "--is-inside-work-tree"])+ .await?;+ if !inside.success() || inside.stdout.trim() != "true" {+ return Err(ProbeError::NotGit);+ }++ let has_commit = git+ .output(+ project,+ &["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],+ )+ .await?;+ if !has_commit.success() {+ return Err(ProbeError::NoCommits);+ }++ // The full ref, not `--short`: that prints `heads/<name>` when a tag+ // shares the branch's name.+ let head = git+ .output(project, &["symbolic-ref", "--quiet", "HEAD"])+ .await?;+ let branch = match head.stdout.trim().strip_prefix("refs/heads/") {+ Some(branch) if head.success() => branch.to_string(),+ _ => return Err(ProbeError::DetachedHead),+ };++ let namespace = git+ .output(+ project,+ &[+ "show-ref",+ "--verify",+ "--quiet",+ &format!("refs/heads/{BRANCH_NAMESPACE}"),+ ],+ )+ .await?;+ if namespace.success() {+ return Err(ProbeError::BranchNamespaceTaken);+ }++ let toplevel = git.run(project, &["rev-parse", "--show-toplevel"]).await?;+ let prefix = git.run(project, &["rev-parse", "--show-prefix"]).await?;+ let common_dir = git.run(project, &["rev-parse", "--git-common-dir"]).await?;+ Ok(RepoInfo {+ toplevel: canonical(Path::new(toplevel.trim())),+ prefix: prefix.trim().to_string(),+ // Relative from a subdirectory (for example `../../.git`); git 2.29+ // has no `--path-format=absolute`, so resolve it here.+ common_dir: canonical(&project.join(common_dir.trim())),+ branch,+ })+}++fn canonical(path: &Path) -> PathBuf {+ crate::workspace::simple_canonicalize(path).unwrap_or_else(|_| path.to_path_buf())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::session_worktrees::test_support::{git_cmd, init_repo};++ async fn probe_code(path: &Path) -> &'static str {+ probe(&GitRunner::default(), path)+ .await+ .map(|_| "OK")+ .unwrap_or_else(|error| error.code())+ }++ #[tokio::test]+ async fn rejects_projects_that_cannot_host_a_worktree() {+ let dir = tempfile::tempdir().unwrap();+ let plain = dir.path().join("plain");+ std::fs::create_dir_all(&plain).unwrap();+ assert_eq!(probe_code(&plain).await, "WORKTREE_NOT_GIT");++ let empty = dir.path().join("empty");+ std::fs::create_dir_all(&empty).unwrap();+ git_cmd(&empty, &["init", "-q", "-b", "main"]);+ assert_eq!(probe_code(&empty).await, "WORKTREE_NO_COMMITS");++ let detached = init_repo(&dir.path().join("detached"));+ git_cmd(&detached, &["checkout", "-q", "--detach"]);+ assert_eq!(probe_code(&detached).await, "WORKTREE_DETACHED_HEAD");++ let taken = init_repo(&dir.path().join("taken"));+ git_cmd(&taken, &["branch", "pi-desktop"]);+ assert_eq!(probe_code(&taken).await, "WORKTREE_BRANCH_NAMESPACE_TAKEN");+ }++ #[tokio::test]+ async fn reports_root_prefix_branch_and_absolute_common_dir() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ let info = probe(&GitRunner::default(), &repo).await.unwrap();+ assert_eq!(info.toplevel, canonical(&repo));+ assert_eq!(info.prefix, "");+ assert_eq!(info.branch, "main");+ assert_eq!(info.common_dir, canonical(&repo.join(".git")));+ }++ /// AC20 / design §15 F1–F3: a project that is a monorepo subdirectory.+ #[tokio::test]+ async fn a_repository_subdirectory_reports_its_prefix_and_shared_common_dir() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("mono"));+ let app = repo.join("packages/app");+ std::fs::create_dir_all(&app).unwrap();+ std::fs::write(app.join("a.txt"), "a").unwrap();+ git_cmd(&repo, &["add", "-A"]);+ git_cmd(&repo, &["commit", "-q", "-m", "app"]);+ let info = probe(&GitRunner::default(), &app).await.unwrap();+ assert_eq!(info.toplevel, canonical(&repo));+ assert_eq!(info.prefix, "packages/app/");+ assert_eq!(info.common_dir, canonical(&repo.join(".git")));+ }+}diff --cc crates/host-core/src/session_worktrees/registry.rsindex 126118877,000000000..00be75b0emode 100644,000000..100644--- a/crates/host-core/src/session_worktrees/registry.rs+++ b/crates/host-core/src/session_worktrees/registry.rs@@@ -1,377 -1,0 +1,377 @@@- //! Rows of the `worktrees` table (schema v24, ADR 0328).++//! Rows of the `worktrees` table (schema v24, ADR 0329).++use anyhow::{anyhow, Result};+use rusqlite::{params, OptionalExtension, Row};+use serde::Serialize;++use crate::db::{now_ms, Database};++/// Each worktree owns `PORT_BLOCK` consecutive ports starting at its base.+pub const PORT_BLOCK: i64 = 10;+pub const PORT_RANGE_START: i64 = 41_000;+/// Base of the last block; the range ends at `PORT_RANGE_LAST_BASE + 9`.+pub const PORT_RANGE_LAST_BASE: i64 = 48_990;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum WorktreeStatus {+ Creating,+ Active,+ Conflict,+ Merged,+ Missing,+}++impl WorktreeStatus {+ pub fn as_str(self) -> &'static str {+ match self {+ WorktreeStatus::Creating => "creating",+ WorktreeStatus::Active => "active",+ WorktreeStatus::Conflict => "conflict",+ WorktreeStatus::Merged => "merged",+ WorktreeStatus::Missing => "missing",+ }+ }++ pub(crate) fn parse(value: &str) -> Result<Self> {+ Ok(match value {+ "creating" => WorktreeStatus::Creating,+ "active" => WorktreeStatus::Active,+ "conflict" => WorktreeStatus::Conflict,+ "merged" => WorktreeStatus::Merged,+ "missing" => WorktreeStatus::Missing,+ other => return Err(anyhow!("unknown worktree status {other}")),+ })+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum SetupStatus {+ None,+ Running,+ Ok,+ Failed,+}++impl SetupStatus {+ pub fn as_str(self) -> &'static str {+ match self {+ SetupStatus::None => "none",+ SetupStatus::Running => "running",+ SetupStatus::Ok => "ok",+ SetupStatus::Failed => "failed",+ }+ }++ pub(crate) fn parse(value: &str) -> Result<Self> {+ Ok(match value {+ "none" => SetupStatus::None,+ "running" => SetupStatus::Running,+ "ok" => SetupStatus::Ok,+ "failed" => SetupStatus::Failed,+ other => return Err(anyhow!("unknown worktree setup status {other}")),+ })+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WorktreeRow {+ pub id: String,+ /// `None` once the owning session was deleted (orphan awaiting cleanup).+ pub session_id: Option<String>,+ /// `None` for the session's own worktree.+ pub delegation_id: Option<String>,+ /// Worktree root (the directory `git worktree add` created).+ pub path: String,+ pub common_dir: String,+ /// Project directory relative to the repository top level.+ pub prefix: String,+ pub branch: String,+ pub owner_branch: String,+ pub status: WorktreeStatus,+ pub setup_status: Option<SetupStatus>,+ /// Bounded tail of the setup command output.+ pub setup_log: Option<String>,+ pub port_base: Option<i64>,+ pub created_at: i64,+ pub updated_at: i64,+}++impl WorktreeRow {+ /// The tool root: the worktree plus the project's repository prefix, so an+ /// isolated session sees the same scope as a non-isolated one.+ pub fn workspace_root(&self) -> std::path::PathBuf {+ let root = std::path::Path::new(&self.path);+ if self.prefix.is_empty() {+ root.to_path_buf()+ } else {+ root.join(self.prefix.trim_end_matches('/'))+ }+ }+}++pub struct NewWorktree<'a> {+ pub session_id: &'a str,+ pub delegation_id: Option<&'a str>,+ pub path: &'a str,+ pub common_dir: &'a str,+ pub prefix: &'a str,+ pub branch: &'a str,+ pub owner_branch: &'a str,+ pub port_base: Option<i64>,+}++const COLUMNS: &str = "id, session_id, delegation_id, path, common_dir, prefix, branch,+ owner_branch, status, setup_status, setup_log, port_base,+ created_at, updated_at";++fn from_row(row: &Row<'_>) -> rusqlite::Result<(WorktreeRow, String, Option<String>)> {+ Ok((+ WorktreeRow {+ id: row.get(0)?,+ session_id: row.get(1)?,+ delegation_id: row.get(2)?,+ path: row.get(3)?,+ common_dir: row.get(4)?,+ prefix: row.get(5)?,+ branch: row.get(6)?,+ owner_branch: row.get(7)?,+ status: WorktreeStatus::Creating,+ setup_status: None,+ setup_log: row.get(10)?,+ port_base: row.get(11)?,+ created_at: row.get(12)?,+ updated_at: row.get(13)?,+ },+ row.get(8)?,+ row.get(9)?,+ ))+}++fn finish(raw: (WorktreeRow, String, Option<String>)) -> Result<WorktreeRow> {+ let (mut row, status, setup) = raw;+ row.status = WorktreeStatus::parse(&status)?;+ row.setup_status = setup.as_deref().map(SetupStatus::parse).transpose()?;+ Ok(row)+}++fn query_many(db: &Database, sql: &str, args: impl rusqlite::Params) -> Result<Vec<WorktreeRow>> {+ let mut statement = db.conn().prepare_cached(sql)?;+ let rows = statement+ .query_map(args, from_row)?+ .collect::<rusqlite::Result<Vec<_>>>()?;+ rows.into_iter().map(finish).collect()+}++/// Insert a row in `creating` state. The unique indexes reject a second+/// worktree for the same owner and a port block already held by another row.+pub fn insert(db: &Database, new: &NewWorktree<'_>) -> Result<WorktreeRow> {+ let id = uuid::Uuid::new_v4().to_string();+ let now = now_ms();+ db.conn().execute(+ "INSERT INTO worktrees (id, session_id, delegation_id, path, common_dir, prefix,+ branch, owner_branch, status, setup_status, port_base,+ created_at, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'creating', NULL, ?9, ?10, ?10)",+ params![+ id,+ new.session_id,+ new.delegation_id,+ new.path,+ new.common_dir,+ new.prefix,+ new.branch,+ new.owner_branch,+ new.port_base,+ now+ ],+ )?;+ get(db, &id)?.ok_or_else(|| anyhow!("inserted worktree {id} not found"))+}++pub fn get(db: &Database, id: &str) -> Result<Option<WorktreeRow>> {+ let raw = db+ .conn()+ .prepare_cached(&format!("SELECT {COLUMNS} FROM worktrees WHERE id = ?1"))?+ .query_row(params![id], from_row)+ .optional()?;+ raw.map(finish).transpose()+}++/// The worktree of a session (`delegation_id = None`) or of one delegation.+pub fn for_owner(+ db: &Database,+ session_id: &str,+ delegation_id: Option<&str>,+) -> Result<Option<WorktreeRow>> {+ let raw = db+ .conn()+ .prepare_cached(&format!(+ "SELECT {COLUMNS} FROM worktrees+ WHERE session_id = ?1 AND IFNULL(delegation_id, '') = IFNULL(?2, '')"+ ))?+ .query_row(params![session_id, delegation_id], from_row)+ .optional()?;+ raw.map(finish).transpose()+}++/// Every worktree of a session, its own first, then delegations by age.+pub fn for_session(db: &Database, session_id: &str) -> Result<Vec<WorktreeRow>> {+ query_many(+ db,+ &format!(+ "SELECT {COLUMNS} FROM worktrees WHERE session_id = ?1+ ORDER BY delegation_id IS NOT NULL, created_at"+ ),+ params![session_id],+ )+}++/// Rows whose session was deleted by any path; awaiting link-safe removal.+pub fn orphans(db: &Database) -> Result<Vec<WorktreeRow>> {+ query_many(+ db,+ &format!("SELECT {COLUMNS} FROM worktrees WHERE session_id IS NULL ORDER BY updated_at"),+ [],+ )+}++pub fn set_status(db: &Database, id: &str, status: WorktreeStatus) -> Result<bool> {+ Ok(db.conn().execute(+ "UPDATE worktrees SET status = ?2, updated_at = ?3 WHERE id = ?1",+ params![id, status.as_str(), now_ms()],+ )? > 0)+}++pub fn set_setup_status(+ db: &Database,+ id: &str,+ status: SetupStatus,+ log: Option<&str>,+) -> Result<bool> {+ Ok(db.conn().execute(+ "UPDATE worktrees SET setup_status = ?2, setup_log = COALESCE(?3, setup_log),+ updated_at = ?4+ WHERE id = ?1",+ params![id, status.as_str(), log, now_ms()],+ )? > 0)+}++/// Every row, for startup reconciliation.+pub fn all(db: &Database) -> Result<Vec<WorktreeRow>> {+ query_many(+ db,+ &format!("SELECT {COLUMNS} FROM worktrees ORDER BY created_at"),+ [],+ )+}++pub fn remove(db: &Database, id: &str) -> Result<bool> {+ Ok(db+ .conn()+ .execute("DELETE FROM worktrees WHERE id = ?1", params![id])?+ > 0)+}++/// Lowest port block not held by any row whose first port `is_free` accepts.+/// The unique index on `port_base` still guards the insert against a race.+pub fn next_port_base(db: &Database, is_free: impl Fn(u16) -> bool) -> Result<Option<i64>> {+ let used: std::collections::HashSet<i64> = db+ .conn()+ .prepare_cached("SELECT port_base FROM worktrees WHERE port_base IS NOT NULL")?+ .query_map([], |row| row.get(0))?+ .collect::<rusqlite::Result<_>>()?;+ let mut base = PORT_RANGE_START;+ while base <= PORT_RANGE_LAST_BASE {+ if !used.contains(&base) && u16::try_from(base).is_ok_and(&is_free) {+ return Ok(Some(base));+ }+ base += PORT_BLOCK;+ }+ Ok(None)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn db_with_session() -> (tempfile::TempDir, Database, String) {+ let dir = tempfile::tempdir().unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let session = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();+ (dir, db, session.id)+ }++ fn new<'a>(session: &'a str, delegation: Option<&'a str>, path: &'a str) -> NewWorktree<'a> {+ NewWorktree {+ session_id: session,+ delegation_id: delegation,+ path,+ common_dir: "/repo/.git",+ prefix: "",+ branch: "pi-desktop/x",+ owner_branch: "main",+ port_base: None,+ }+ }++ #[test]+ fn rows_round_trip_by_owner_and_status() {+ let (_dir, db, session) = db_with_session();+ let own = insert(&db, &new(&session, None, "/w/own")).unwrap();+ let delegate = insert(&db, &new(&session, Some("d1"), "/w/d1")).unwrap();+ assert_eq!(own.status, WorktreeStatus::Creating);+ assert_eq!(for_owner(&db, &session, None).unwrap().unwrap().id, own.id);+ assert_eq!(+ for_owner(&db, &session, Some("d1")).unwrap().unwrap().id,+ delegate.id+ );+ assert!(set_status(&db, &own.id, WorktreeStatus::Conflict).unwrap());+ assert!(set_setup_status(&db, &own.id, SetupStatus::Failed, Some("boom")).unwrap());+ let reloaded = get(&db, &own.id).unwrap().unwrap();+ assert_eq!(reloaded.status, WorktreeStatus::Conflict);+ assert_eq!(reloaded.setup_status, Some(SetupStatus::Failed));+ assert_eq!(reloaded.setup_log.as_deref(), Some("boom"));+ let listed: Vec<_> = for_session(&db, &session)+ .unwrap()+ .into_iter()+ .map(|row| row.id)+ .collect();+ assert_eq!(listed, vec![own.id.clone(), delegate.id]);+ assert!(remove(&db, &own.id).unwrap());+ assert!(get(&db, &own.id).unwrap().is_none());+ }++ #[test]+ fn deleted_sessions_leave_listed_orphans() {+ let (_dir, db, session) = db_with_session();+ let row = insert(&db, &new(&session, None, "/w/own")).unwrap();+ assert!(orphans(&db).unwrap().is_empty());+ crate::sessions::delete_session(&db, &session).unwrap();+ let orphaned = orphans(&db).unwrap();+ assert_eq!(orphaned.len(), 1);+ assert_eq!(orphaned[0].id, row.id);+ assert_eq!(orphaned[0].session_id, None);+ }++ #[test]+ fn port_blocks_skip_held_and_busy_bases() {+ let (_dir, db, session) = db_with_session();+ assert_eq!(+ next_port_base(&db, |_| true).unwrap(),+ Some(PORT_RANGE_START)+ );+ let mut held = new(&session, None, "/w/own");+ held.port_base = Some(PORT_RANGE_START);+ insert(&db, &held).unwrap();+ // The second block is held by another program right now.+ let busy = (PORT_RANGE_START + PORT_BLOCK) as u16;+ assert_eq!(+ next_port_base(&db, |port| port != busy).unwrap(),+ Some(PORT_RANGE_START + 2 * PORT_BLOCK)+ );+ assert_eq!(next_port_base(&db, |_| false).unwrap(), None);+ }+}diff --cc crates/host-core/src/session_worktrees/remove.rsindex 8a4714d8e,000000000..2c77f32e9mode 100644,000000..100644--- a/crates/host-core/src/session_worktrees/remove.rs+++ b/crates/host-core/src/session_worktrees/remove.rs@@@ -1,241 -1,0 +1,241 @@@- //! Link-safe removal of a worktree and its branch (ADR 0328 decision 6).++//! Link-safe removal of a worktree and its branch (ADR 0329 decision 6).+//!+//! Git for Windows follows a directory junction inside the worktree during+//! `git worktree remove --force` and deletes the junction target's files+//! (openai/codex#34702, #49995). host-core therefore empties the worktree+//! itself first, removing every symbolic link or junction as a link, and only+//! then lets git drop the (now link-free) directory and its metadata.++use std::fs;+use std::io;+use std::path::Path;++use super::git::GitRunner;+use super::registry::WorktreeRow;+use super::WorktreeError;++/// Delete everything inside `root` except its `.git` link file. Links are+/// removed as links; their targets are never traversed.+pub fn clear_contents(root: &Path) -> io::Result<()> {+ let entries = match fs::read_dir(root) {+ Ok(entries) => entries,+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error),+ };+ for entry in entries {+ let entry = entry?;+ if entry.file_name() == ".git" {+ continue;+ }+ remove_entry(&entry.path())?;+ }+ Ok(())+}++fn remove_entry(path: &Path) -> io::Result<()> {+ let metadata = fs::symlink_metadata(path)?;+ if metadata.file_type().is_symlink() || is_reparse_point(&metadata) {+ remove_link(path, &metadata)+ } else if metadata.is_dir() {+ // Documented not to follow symbolic links, and protected against+ // symlink TOCTOU races on the supported platforms.+ fs::remove_dir_all(path)+ } else {+ fs::remove_file(path)+ }+}++#[cfg(windows)]+fn is_reparse_point(metadata: &fs::Metadata) -> bool {+ use std::os::windows::fs::MetadataExt;+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;+ metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0+}++#[cfg(not(windows))]+fn is_reparse_point(_metadata: &fs::Metadata) -> bool {+ false+}++#[cfg(windows)]+fn remove_link(path: &Path, metadata: &fs::Metadata) -> io::Result<()> {+ use std::os::windows::fs::MetadataExt;+ const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;+ // Directory symlinks and junctions are directory entries; removing the+ // entry removes the link, not the target.+ if metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 {+ fs::remove_dir(path)+ } else {+ fs::remove_file(path)+ }+}++#[cfg(not(windows))]+fn remove_link(path: &Path, _metadata: &fs::Metadata) -> io::Result<()> {+ fs::remove_file(path)+}++/// Remove a registered worktree directory, git's metadata for it, and its+/// branch. The registry row is left to the caller.+pub async fn remove_worktree(git: &GitRunner, row: &WorktreeRow) -> Result<(), WorktreeError> {+ let root = Path::new(&row.path);+ let common_dir = Path::new(&row.common_dir);+ let repository_exists = common_dir.is_dir();+ if root.exists() {+ if repository_exists {+ // Not locked when creation failed half-way; that is fine.+ let _ = git.output(root, &["worktree", "unlock", &row.path]).await;+ }+ clear_contents(root)?;+ if repository_exists {+ git.run_git_dir(common_dir, &["worktree", "remove", "--force", &row.path])+ .await?;+ }+ if root.exists() {+ fs::remove_dir_all(root)?;+ }+ }+ if repository_exists {+ drop_admin_entry(common_dir, root)?;+ let ref_name = format!("refs/heads/{}", row.branch);+ let exists = git+ .run_git_dir(common_dir, &["show-ref", "--verify", "--quiet", &ref_name])+ .await+ .is_ok();+ if exists {+ git.run_git_dir(common_dir, &["branch", "-D", &row.branch])+ .await?;+ }+ }+ Ok(())+}++/// When the worktree directory vanished on its own, git still lists it and+/// keeps its branch "checked out". Drop only the metadata entry whose+/// `gitdir` names this worktree, which is what `git worktree prune` would do+/// for it, without pruning any other worktree.+pub(super) fn drop_admin_entry(common_dir: &Path, root: &Path) -> io::Result<()> {+ let admin = common_dir.join("worktrees");+ let entries = match fs::read_dir(&admin) {+ Ok(entries) => entries,+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error),+ };+ // git records the resolved path (for example `/private/var/...` for+ // `/var/...` on macOS); the root itself may be gone, so resolve its parent.+ let mut expected = vec![root.join(".git")];+ if let (Some(parent), Some(name)) = (root.parent(), root.file_name()) {+ if let Ok(parent) = crate::workspace::simple_canonicalize(parent) {+ expected.push(parent.join(name).join(".git"));+ }+ }+ for entry in entries {+ let entry = entry?;+ let Ok(gitdir) = fs::read_to_string(entry.path().join("gitdir")) else {+ continue;+ };+ if expected.iter().any(|path| Path::new(gitdir.trim()) == path) {+ fs::remove_dir_all(entry.path())?;+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::session_worktrees::registry::{WorktreeRow, WorktreeStatus};+ use crate::session_worktrees::test_support::{git_cmd, init_repo, link_dir, try_link_file};++ fn row_for(repo: &Path, worktree: &Path, branch: &str) -> WorktreeRow {+ WorktreeRow {+ id: "w".into(),+ session_id: Some("s".into()),+ delegation_id: None,+ path: worktree.to_string_lossy().into_owned(),+ common_dir: repo.join(".git").to_string_lossy().into_owned(),+ prefix: String::new(),+ branch: branch.into(),+ owner_branch: "main".into(),+ status: WorktreeStatus::Active,+ setup_status: None,+ setup_log: None,+ port_base: None,+ created_at: 0,+ updated_at: 0,+ }+ }++ /// AC14: a link to a directory outside the worktree survives removal. On+ /// Windows the directory links are junctions, which Git for Windows+ /// follows during `git worktree remove --force`.+ #[tokio::test]+ async fn removal_deletes_links_without_touching_their_targets() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ let outside = dir.path().join("outside");+ fs::create_dir_all(outside.join("nested")).unwrap();+ fs::write(outside.join("KEEP_ME.txt"), "keep").unwrap();+ fs::write(outside.join("nested/KEEP_TOO.txt"), "keep").unwrap();+ let worktree = dir.path().join("wt");+ git_cmd(+ &repo,+ &[+ "worktree",+ "add",+ "-q",+ "-b",+ "pi-desktop/t",+ worktree.to_str().unwrap(),+ "main",+ ],+ );+ link_dir(&outside, &worktree.join("linked"));+ fs::create_dir_all(worktree.join("deep")).unwrap();+ link_dir(&outside, &worktree.join("deep/linked"));+ try_link_file(&outside.join("KEEP_ME.txt"), &worktree.join("file-link"));++ remove_worktree(+ &GitRunner::default(),+ &row_for(&repo, &worktree, "pi-desktop/t"),+ )+ .await+ .unwrap();++ assert!(!worktree.exists());+ assert!(outside.join("KEEP_ME.txt").is_file());+ assert!(outside.join("nested/KEEP_TOO.txt").is_file());+ assert!(!git_cmd(&repo, &["branch", "--list", "pi-desktop/t"]).contains("pi-desktop/t"));+ assert_eq!(git_cmd(&repo, &["worktree", "list"]).lines().count(), 1);+ }++ #[tokio::test]+ async fn a_worktree_whose_directory_vanished_is_unregistered_and_its_branch_dropped() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ let worktree = dir.path().join("wt");+ git_cmd(+ &repo,+ &[+ "worktree",+ "add",+ "-q",+ "-b",+ "pi-desktop/gone",+ worktree.to_str().unwrap(),+ "main",+ ],+ );+ fs::remove_dir_all(&worktree).unwrap();++ remove_worktree(+ &GitRunner::default(),+ &row_for(&repo, &worktree, "pi-desktop/gone"),+ )+ .await+ .unwrap();++ assert_eq!(git_cmd(&repo, &["worktree", "list"]).lines().count(), 1);+ assert!(!git_cmd(&repo, &["branch", "--list"]).contains("pi-desktop/gone"));+ }+}diff --cc crates/host-core/src/sessions.rsindex 0a3b7ff5f,5ea64fea6..685963495--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@@ -137,10 -137,6 +137,10 @@@ pub struct SessionSummary/// deleting the task frees its sessions back into the ordinary lists.#[serde(default)]pub scheduled_run: bool,- /// The session's isolated worktree (ADR 0328); absent for every other++ /// The session's isolated worktree (ADR 0329); absent for every other+ /// session. Filled in by the list and single-summary reads.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub worktree: Option<crate::session_worktrees::lifecycle::WorktreeSummary>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@@ -1464,8 -1446,6 +1464,8 @@@ pub fn create_session_with_optionscreated_at: ms_to_ts(now),// The run row that owns this transcript is written after creation.scheduled_run: false,- // A new or forked session starts without a worktree (ADR 0328).++ // A new or forked session starts without a worktree (ADR 0329).+ worktree: None,})}@@@ -1828,8 -1804,6 +1828,8 @@@ pub fn fork_session_throughcreated_at,// A fork is the user's own conversation, not the automation's transcript.scheduled_run: false,- // A new or forked session starts without a worktree (ADR 0328).++ // A new or forked session starts without a worktree (ADR 0329).+ worktree: None,};let messages = records.into_iter().map(record_to_ui).collect();Ok(ForkSessionResult::Created(Box::new(SessionDetail {diff --cc crates/host-core/src/tool_budget.rsindex d42ce6de3,1fef9e988..45da954a9--- a/crates/host-core/src/tool_budget.rs+++ b/crates/host-core/src/tool_budget.rs@@@ -143,9 -89,6 +143,9 @@@ pub struct ToolBudgetSnapshotstruct Request {session_id: String,class: ToolClass,- /// Runs in a subagent's own worktree (ADR 0328), so holding the session++ /// Runs in a subagent's own worktree (ADR 0329), so holding the session+ /// for work in the session worktree does not need to stop it.+ own_worktree: bool,}#[derive(Default)]@@@ -401,45 -304,6 +401,45 @@@ impl ToolBudget}}+ /// Hold `session_id` alone: wait (at most `wait`) until none of its tools+ /// is in flight, then keep every new tool of that session queued until+ /// the permit drops. Used around git operations on an isolated session's- /// worktree (ADR 0328) so a Bash or Write call cannot interleave with++ /// worktree (ADR 0329) so a Bash or Write call cannot interleave with+ /// them. `None` when the session stayed busy; other sessions and global+ /// capacity are unaffected either way.+ pub async fn acquire_session_exclusive(+ &self,+ session_id: &str,+ wait: Duration,+ ) -> Option<SessionExclusivePermit> {+ let deadline = tokio::time::Instant::now() + wait;+ // Dropped on every exit, including cancellation of this future.+ let _pending = PendingExclusive::register(self, session_id);+ loop {+ // Registered before the check, so a release in between still wakes us.+ let released = self.released.notified();+ tokio::pin!(released);+ released.as_mut().enable();+ {+ let mut state = self.lock();+ let busy = state+ .sessions+ .get(session_id)+ .is_some_and(|usage| usage.active > usage.own_worktree);+ if !busy && !state.exclusive.contains(session_id) {+ state.exclusive.insert(session_id.to_string());+ return Some(SessionExclusivePermit {+ budget: self.clone(),+ session_id: session_id.to_string(),+ });+ }+ }+ if tokio::time::timeout_at(deadline, released).await.is_err() {+ return None;+ }+ }+ }+pub fn snapshot(&self) -> ToolBudgetSnapshot {let state = self.lock();ToolBudgetSnapshot {diff --cc crates/host-core/src/tools/mod.rsindex 64d8e9176,a57f182d3..4a77ec1db--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@@ -214,10 -214,6 +214,10 @@@ struct ToolRunnerStartConfigscratch_dir: Option<PathBuf>,#[serde(default)]env_path: Option<String>,+ /// Session-scoped variables such as `PI_PORT` for an isolated worktree- /// (ADR 0328). Empty for every other call.++ /// (ADR 0329). Empty for every other call.+ #[serde(default)]+ extra_env: Vec<(String, String)>,}fn path_has_nul(path: &Path) -> bool {@@@ -571,10 -564,6 +571,10 @@@ pub struct ToolsExecuteParams/// permission mode. `inherit` and absent behave identically.#[serde(default)]pub permission_scope: Option<String>,- /// Chain id of a Write/Edit subagent with its own worktree (ADR 0328).++ /// Chain id of a Write/Edit subagent with its own worktree (ADR 0329).+ /// host-core resolves it against its registry; an unknown id is ignored.+ #[serde(default)]+ pub delegation_id: Option<String>,#[serde(default)]pub expected_command_shell_id: Option<String>,#[serde(default)]@@@ -772,8 -761,6 +772,8 @@@ pub struct BashExecutionOptionspub timeout_ms: Option<u64>,pub cancellation: Option<watch::Receiver<bool>>,pub output_tx: Option<mpsc::UnboundedSender<String>>,- /// Extra environment for the command, e.g. `PI_PORT` (ADR 0328).++ /// Extra environment for the command, e.g. `PI_PORT` (ADR 0329).+ pub extra_env: Vec<(String, String)>,}impl BashExecutionOptions {diff --cc docs/adr/0329-session-worktree-isolation.mdindex cd57384f7,000000000..5f50e5666mode 100644,000000..100644--- a/docs/adr/0329-session-worktree-isolation.md+++ b/docs/adr/0329-session-worktree-isolation.md@@@ -1,129 -1,0 +1,129 @@@- # ADR 0328: Isolate parallel sessions of one project in git worktrees++# ADR 0329: Isolate parallel sessions of one project in git worktrees++- Status: Accepted+- Date: 2026-10-12+- Deciders: PI-Desktop maintainers+- Related: ADR 0062 (parallel delegates), ADR 0089 (delegation tools),+ D114 (per-session scratch), `docs/spec/03-runtime/03-tools-and-permissions.md` §4d++## Context++Several sessions of one project can run at the same time, but they all+resolve the same tool root (`resolve_tool_workspace`, `crates/host-core/src/rpc/mod.rs`).+Writes are serialized only per session; two sessions editing one file are+guarded only by the Edit content tag, and they share one build tree and one+git state. Subagents of one session share the same root as well.++Every mainstream agent product that offers parallel local work isolates it in+a git worktree: Claude Code (`--worktree`, subagent `isolation: worktree`),+Cursor (Agents Window, `/worktree`), Codex (Local / Worktree with Handoff),+VS Code (Agents window "New Worktree"), Windsurf / Devin Desktop, Conductor,+and JetBrains IDEs. Four of the six desktop products place worktrees outside+the project directory.++## Decision++1. An isolated session is opt-in per new session, default off. It owns one git+ worktree on branch `pi-desktop/<id>`, created by host-core under+ `~/.pi-desktop/worktrees/<project-key>/` from the project's current branch+ tip. Uncommitted project changes are not carried over.+2. host-core owns all git execution, worktree paths, and the `worktrees`+ registry (schema v24). The renderer and the agent runtime send only a+ session id and, for subagents, a delegation id; they never send a worktree+ path.+3. Tool containment is unchanged in mechanism: the isolated session's root is+ its worktree (or `<worktree>/<prefix>` when the project is a repository+ subdirectory), so the main checkout is "outside workspace" and needs the+ existing permission. Project identity (skills, plugins, MCP, memory,+ subagent catalog, group context) stays keyed by the project path; only+ files, instruction files, and the shell run in the worktree.+4. "Merge into project" preserves the session's commits. It first shows the+ commit count and changed files for confirmation, then merges the project+ branch into the session branch inside the worktree (conflicts stay there),+ then fast-forwards the project branch. The project never enters a+ merge-in-progress state and git refuses to overwrite uncommitted project+ changes.+5. Inside an isolated session, a subagent whose tools include Write or Edit+ gets its own temporary worktree and is merged back automatically with the+ same algorithm; a conflict is reported to the parent, which can resume the+ subagent to resolve it. Other subagents share the session worktree.+6. Deleting an isolated session removes its worktrees and branches after a+ loss warning; there is no separate discard. Removal deletes links as links+ before calling git, because Git for Windows follows directory junctions+ during `git worktree remove --force` (openai/codex#34702, #49995).+7. Every git command host-core runs disables hooks and `core.fsmonitor` and+ sets `safe.bareRepository=explicit`. A relative `core.hooksPath` resolves+ inside the worktree, so a hook written with Write/Edit alone would+ otherwise run when host-core commits or merges, bypassing the Bash+ permission.+8. New worktrees copy ignored files listed in `.worktreeinclude` (the format+ Claude Code and Conductor read), then run an optional per-project setup+ command with `PI_PROJECT_ROOT`, `PI_WORKTREE_ROOT`, and `PI_PORT` (a block+ of 10 ports per worktree, after Conductor's `CONDUCTOR_PORT`).+9. Minimum git version is 2.29 (`git worktree repair`). Relative worktree+ links are not used because they raise the repository format version.+10. "Sync from project" merges the project branch into an isolated session's+ worktree with the rules of decision 4 (pending session work is committed+ first, conflicts stay in the worktree) and never touches the project.+ Without it a session only receives other sessions' work, including their+ conflict resolutions, when it is merged, so it keeps working on stale+ code. The sidebar marks a session that lacks project commits (`↓N`); the+ counts come from one background host call (`worktree.behindAll`) when+ isolated sessions change, after a merge or sync, and on window focus, so+ rendering the list never waits for git.+11. The conflict status follows the worktree, not only the next merge: after+ each Write, Edit, or Bash call of a conflicted session, after a failed+ merge or sync, when the session menu opens, and in the background behind+ check, host-core clears the status once every conflict is resolved (by+ the rule the merge uses to conclude it) or the merge was aborted. Text+ conflicts merged by git's text driver count as resolved when their+ markers (of the file's `conflict-marker-size`) are gone; binary,+ add/delete, modify/delete, and `merge=binary` / `-merge` / custom-driver+ conflicts need an explicit `git add` or `git rm`.+12. While host-core commits or merges in a session worktree for a subagent,+ it holds the session's own tools (new calls queue, also while the hold is+ awaited). Calls of subagents rooted in their own worktrees are not held.+ It waits at most five seconds for tools already running, then falls back+ to holding only the session's write permit, so a long Bash run never+ blocks subagents. The runtime gives these host calls a 10-minute+ deadline so it never reports a merge that is still running as failed.++## Alternatives considered++- Worktrees inside the project (`.pi/worktrees/`, Claude Code's choice):+ rejected after verification; test runners (vitest default `exclude`),+ `tsc` (default `include: **/*`), watchers, and `git clean -ffdx` see or+ delete the copies.+- Apply changes as uncommitted edits instead of merging the branch: rejected+ by the user in favor of keeping history.+- Merging directly in the project: rejected; a conflict would leave the+ project half-merged.+- No automatic subagent merge-back (Claude Code, VS Code, Codex): rejected by+ the user in favor of zero-click integration, with serialization and a+ no-force fallback as safeguards.+- Per-project file locks without worktrees: rejected; it cannot isolate builds+ or git state.++## Consequences++- Project history contains "Merge branch …" and checkpoint commits.+- Automatic commits do not run the project's pre-commit hooks.+- MCP stdio servers stay per project with the main checkout as cwd, so MCP+ tools are not isolated.+- Builds that reach outside the repository by relative path need links made+ by the setup command.+- Isolation is a development boundary, not a security boundary; Bash can+ still reach the main checkout through absolute paths.++## Validation++host-core tests against real temporary git repositories cover creation,+merge (including conflicts, markerless conflicts, and dirty-project refusal),+sync from project, behind counts, conflict-status refresh, the session hold,+hook suppression, link-safe removal, orphan cleanup, `.worktreeinclude`, port+assignment, and repository-subdirectory projects; IPC, renderer, and Electron+user-path tests cover the sidebar. `pnpm test:e2e:worktree-live` runs the+lifecycle against a real model. The hook-suppression, link-safe removal, and+`.worktreeinclude` link tests also run on Windows with directory junctions,+where Git for Windows runs hooks without an executable bit and lists files+inside a junction. Long paths and locked-file removal require Windows E2E.diff --cc docs/adr/README.mdindex 2dbc6dea1,63d92b95e..0efb820a2--- a/docs/adr/README.md+++ b/docs/adr/README.md@@@ -373,7 -373,7 +373,8 @@@ Each ADR includes| 0325 | [Smooth Windows main-window corner compositing](0325-windows-window-corner-compositing.md) | Proposed (implementation candidate; Windows E2E pending) || 0326 | [Verified SSH Host installation and daily startup](0326-verified-ssh-host-installation.md) | Accepted for experimental implementation (amends ADR 0292; Linux SSH qualification and publication pending) || 0327 | [Automatic remote Host version realignment](0327-remote-host-version-realignment.md) | Accepted for experimental implementation (amends ADR 0326 item 6; Linux SSH qualification pending) |- | 0328 | [Isolate parallel sessions of one project in git worktrees](0328-session-worktree-isolation.md) | Accepted (Windows E2E pending) |+ | 0328 | [Open arbitrary local files in the embedded Browser](0328-browser-arbitrary-local-files.md) | Accepted (D657; amends ADR 0170; issue #1627) |++| 0329 | [Isolate parallel sessions of one project in git worktrees](0329-session-worktree-isolation.md) | Accepted (Windows E2E pending) || plugin-fetch-redirect-policy | [Host-enforced plugin fetch redirect policy](plugin-fetch-redirect-policy.md) | Accepted (implementation candidate for #1475) || local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation |diff --cc docs/spec/03-runtime/01-ipc-protocol.mdindex ce1286ecc,a5ee9d72f..940751cb0--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@@ -943,12 -947,6 +947,12 @@@ type SessionSummary =supportedThinkingLevels?: ThinkingLevel[];updatedAt: string;createdAt: string;- /** Isolated sessions only (ADR 0328); never carries a filesystem path. */++ /** Isolated sessions only (ADR 0329); never carries a filesystem path. */+ worktree?: {+ branch: string;+ status: "creating" | "active" | "conflict" | "merged" | "missing";+ setupStatus?: "none" | "running" | "ok" | "failed" | null;+ };};type SessionMessageOrigin = {@@@ -1062,9 -1062,7 +1068,9 @@@ through one Electron-only allowlisted cMinimal interface:- `session/list`-- `session/create`+- `session/create` — optional `isolated: true` with a `projectPath` creates- the session in its own git worktree (ADR 0328); a refusal surfaces the host's++ the session in its own git worktree (ADR 0329); a refusal surfaces the host's+ `WORKTREE_*` code- `session/open(sessionId)` — validate and select an existing durable sessionthrough the reviewed desktop-control path; it does not create or mutate thesession@@@ -1414,25 -1421,6 +1429,25 @@@ type ProjectMemoryEntry =};```- ## 9a. Session worktree API (ADR 0328)++## 9a. Session worktree API (ADR 0329)++Thin forwards to the host `worktree.*` methods+(06-host-rpc-protocol §4); errors keep the host's `WORKTREE_*` code.++- `worktree/probe({ projectPath })` → whether the project can host isolated+ sessions, with the refusal code, or whether it has uncommitted changes+- `worktree/preview({ sessionId })` / `worktree/merge({ sessionId, previewToken })`+- `worktree/behind({ sessionId })` → commit count, and+ `worktree/sync({ sessionId })` — "Sync from project"; `worktree/behindAll()`+ → `{ counts: { [sessionId]: count }, statusesChanged }` for the sidebar marker+- `worktree/pendingWork({ sessionId })` — unmerged work a delete discards+- `worktree/setupLog({ sessionId })`+- `worktree/reveal({ sessionId })` — Electron Main resolves the folder with+ `worktree.location` and opens it in the OS file manager; the path is never+ returned to the renderer+- `worktree/setupCommand/get({ projectPath })` /+ `worktree/setupCommand/set({ projectPath, command })`+## 10. Tool Permission APIWhen a tool requires confirmation:diff --cc docs/spec/03-runtime/02-agent-runtime.mdindex 07a4042fe,af6b8df8e..d785da5ea--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@@ -1191,20 -1196,6 +1196,20 @@@ turn open and delivers the reports wheruntime dispose, or a parent fatal error (D352) abort a still-runningdelegate.- **Isolated worktrees (ADR 0328).** In an isolated session, a delegate whose++**Isolated worktrees (ADR 0329).** In an isolated session, a delegate whose+tools include `Write` or `Edit` gets its own worktree before its first turn+(`worktree.delegate.create`, keyed by the delegation chain id, so a resumed+delegate reuses it), and its `tools.execute` calls carry that id as+`delegationId`. When the run ends the runtime calls+`worktree.delegate.settle` before publishing the report: a completed run is+merged back into the session worktree, a failed or stopped run keeps its+changes, and the outcome (merged, no changes, conflict with files, not merged+with reason, or kept) is appended to the report so the parent knows whether to+resume the delegate. Host-core briefly holds the session's own tools while it+commits and merges in the session worktree, waiting at most a few seconds for+tools already running. Read-only and Bash-only delegates, and every delegate+of a non-isolated session, are unchanged.+### 5f.1 Delegate permission scope (ADR 0089)A delegate's tool calls flow through the same host `tools.execute` path as the@@@ -1666,15 -1657,6 +1671,15 @@@ view project-list menu provides an `AGEregistered project root. Its IPC does not accept arbitrary renderer file paths.Saves affect the next prompt without restarting the application.- For an isolated session (ADR 0328) the launch metadata carries a separate++For an isolated session (ADR 0329) the launch metadata carries a separate+`workspaceRoot`, its git worktree: the instruction chain and its path+resolution are rooted there, so the agent follows the worktree's own+`AGENTS.md` files. `projectPath` stays the project identity for memory,+skills, plugins, MCP servers, subagent definitions, the custom system prompt,+and group context. The system prompt adds a short isolated-workspace note+(work only in the worktree, use the `PI_PORT` block, leave branch changes and+merging to the user, and how to resolve a merge conflict).+## 8. Concurrency| Scope | MVP policy |diff --cc docs/spec/03-runtime/03-tools-and-permissions.mdindex c4005863f,61793d533..30db403c7--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@@ -364,37 -364,6 +364,37 @@@ Serialization also protects the snapshomutate: without the per-session permit, a concurrent record could land between avalidation and its write.- ## 4e. Isolated session worktrees (ADR 0328)++## 4e. Isolated session worktrees (ADR 0329)++A session created with `isolated: true` in a git project owns a dedicated+worktree at `<data_dir>/worktrees/<project-key>/<id>` on branch+`pi-desktop/<id>`, created from the project's current `HEAD` (uncommitted+project changes are not copied; git-ignored files listed in+`.worktreeinclude` are, without following links). For such a session:++- the worktree replaces the project path as `workspaceRoot` for every rule in+ §4–§5, so file tools, Bash's working directory, review snapshots, and+ artifacts resolve inside it; it never falls back to the main checkout+ (a missing worktree fails with a `WORKTREE_*` error);+- `AGENTS.md` instructions are read from the worktree, while project identity+ (memory, skills, plugins, MCP, subagents) stays keyed to the project path;+- Bash receives `PI_PORT` (first port of a 10-port block in 41000–48999),+ `PI_PROJECT_ROOT`, and `PI_WORKTREE_ROOT`;+- the optional per-project setup command runs once in each new worktree, with+ the same variables, in the user's default command shell+ (`defaultCommandShell`, otherwise the platform default: Windows PowerShell on+ Windows, bash elsewhere). It is not translated between dialects, so on+ Windows it must use PowerShell syntax (`$env:PI_PORT`, `;` rather than+ `&&` on Windows PowerShell 5.1) unless a POSIX shell such as Git Bash is+ the configured default;+- git hooks and fsmonitor are disabled for host-run git commands in the+ worktree, and removal never follows links out of it.++Merging into the project is an explicit user action (preview, then merge with+the preview token); it syncs the project branch into the worktree and only+fast-forwards the project, so conflicts stay in the worktree. Deleting an+isolated session discards its worktree and branch.+## 5. Bash RulesHost execution baseline:diff --cc docs/spec/03-runtime/06-host-rpc-protocol.mdindex f1b11c0cc,1016141ea..1f7e58323--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@@ -296,10 -296,6 +296,10 @@@ to later refresh and inference; the ven`inheritPermissionFromSessionId`; when present, the host copies the existingsession's persisted permission mode atomically, while omission preserves theexisting `inherit` default. Missing/null thinking level defaults to `off`.- Optional `isolated: true` (ADR 0328) also requires `projectPath` and gives++ Optional `isolated: true` (ADR 0329) also requires `projectPath` and gives+ the new session its own git worktree before it returns; if the worktree+ cannot be created the session is deleted again and the call fails with a+ `WORKTREE_*` error (§7).- `session.fork` — accepts `sessionId`, an optional caller-provided display`title`, and optional `throughMessageId`; createsone independent session from the source's current active canonical@@@ -603,51 -597,6 +603,51 @@@ Session summaries/details always returmay return `thinking`; host storage maps it to a canonical content block ratherthan appending it to answer `content`.- ### Session worktrees (ADR 0328)++### Session worktrees (ADR 0329)++Additive `worktree.*` methods; no protocol version bump. Failures use code+1025 with a `WORKTREE_*` string code.++- `worktree.probe({ projectPath })` → `{ available, uncommittedChanges }`, or+ `{ available: false, errorCode, message }` when the project cannot host+ isolated sessions (not git, no commits, detached `HEAD`, git missing or+ older than 2.29, a remote-host project — `WORKTREE_REMOTE_UNSUPPORTED`, …).+ `session.create` refuses `isolated: true` for a remote-host project with the+ same code before any session is created.+- `worktree.preview({ sessionId })` → `{ preview }` with the commits and files+ that would land and a `previewToken`.+- `worktree.merge({ sessionId, previewToken })` → `{ outcome }`. A stale token+ is `WORKTREE_CHANGED_SINCE_PREVIEW`; a dirty project is+ `WORKTREE_PROJECT_DIRTY`; a conflict is `WORKTREE_CONFLICT` and leaves the+ worktree conflicted and the project untouched.+- `worktree.behind({ sessionId })` → `{ commits }`, project-branch commits the+ session does not have yet.+- `worktree.behindAll()` → `{ counts, statusesChanged }`: the same count for+ every isolated session keyed by session id (sessions whose count cannot be+ read are omitted), computed a few sessions at a time. Conflicted sessions+ are checked for a resolution first; `statusesChanged` asks the renderer to+ refresh its session list. The renderer reads it in the background for the+ sidebar marker.+- `worktree.sync({ sessionId })` → `{ outcome }` (`synced` with `commits`, or+ `upToDate`): "Sync from project" merges the project branch into the session+ worktree after committing pending session work. The project checkout is not+ touched; a conflict is `WORKTREE_CONFLICT`, stays in the worktree, and marks+ the session like a merge conflict.+- `worktree.pendingWork({ sessionId })` → `{ pending }`, the unmerged work a+ delete would discard.+- `worktree.setupLog({ sessionId })` → `{ setupStatus, log }`.+- `worktree.location({ sessionId })` → `{ path }`; Electron Main uses it for+ "Reveal in folder" and never forwards it to the renderer.+- `worktree.setupCommand.get({ projectPath })` → `{ command }`;+ `worktree.setupCommand.set({ projectPath, command })` → `{ ok }` (unknown+ project is `NOT_FOUND`). The command runs once in each new worktree.+- `worktree.delegate.create({ sessionId, delegationId })` → `{ worktree }` and+ `worktree.delegate.settle({ sessionId, delegationId, merge })` →+ `{ settlement }` — agent-runtime only, for `Write`/`Edit` delegates of an+ isolated session (03-tools-and-permissions §10.2). Both use a 10-minute+ transport deadline (`WORKTREE_DELEGATE_RPC_TIMEOUT_MS`) because they may+ wait for the session's tools before committing and merging.+### Tools- `tools.list`- `tools.execute`@@@ -877,9 -826,6 +877,9 @@@ type ToolsExecuteParams =expectedCommandShellDialect?: "powershell" | "cmd" | "posix"/** Bash only: host default 60000; accepted override 1000..21600000. */timeoutMs?: number+ /** Isolated `Write`/`Edit` delegate chain id; re-roots the call to that- * delegate's worktree (ADR 0328). Omitted for every other call. */++ * delegate's worktree (ADR 0329). Omitted for every other call. */+ delegationId?: string}```diff --cc docs/spec/04-ux/01-ui-ia.mdindex 993b37094,352c54a71..438f881aa--- a/docs/spec/04-ux/01-ui-ia.md+++ b/docs/spec/04-ux/01-ui-ia.md@@@ -235,28 -235,6 +235,28 @@@ destination, chat as the home surface,delete remain separate actions. Rename edits the task label only; archivenever removes the transcript. Open folder is a project action, not aconversation action.- - **Isolated sessions** (ADR 0328): the project menu offers **New isolated++- **Isolated sessions** (ADR 0329): the project menu offers **New isolated+ session**. Opening the menu probes the project: the item stays disabled+ until the answer arrives, and for an unsuitable project (not git, no+ commits, detached `HEAD`, missing or old git) it stays disabled with the+ reason shown under it. Creating probes again; a dirty project gets an info+ toast that uncommitted changes are not included. The menu also+ holds **Worktree setup command…**. An isolated row shows an `Isolated` badge+ (or `Conflict`, `Folder missing`, `Setup failed`) and adds **Merge into+ project…** (preview of commits and files, then merge; conflicting files are+ listed and stay in the session; the `Conflict` badge clears as soon as the+ session resolves or abandons the conflict, and the next merge concludes it),+ **Sync from project** (labelled with the number of new project commits+ when the menu opens, disabled when there are none or while the session is+ conflicted, which also hides the `↓N` marker; it merges the project's+ branch into the session so the session continues on current code, and a+ conflict stays in the session like a merge conflict; a row that lacks project+ commits shows a `↓N` marker next to its badge, read in the background when+ isolated sessions change, after a merge or sync, and on window focus at most+ every 15 seconds, so rendering the list never waits for git), **Show worktree folder**, and **Setup log**.+ Its delete confirmation states that unmerged work will be lost. Isolated+ sessions are never reused as the empty draft and cannot move to another+ project; forks are ordinary sessions.- **Temporary-task attachments**: selecting a saved attachment opens its filepreview even without an open project. Back returns to the no-project browsingstate. Branches preserve referenced pasted/imported inputs as child-owneddiff --cc docs/spec/06-delivery/04-e2e-test-plan.mdindex d930ecc0e,b540c3b40..c0946c40b--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@@ -340,49 -371,6 +371,49 @@@session IPC contract tests, and real-model desktop acceptance. A local modelfixture or mocked component result is not real-model acceptance evidence.+### E2E-WORKTREE-isolated-session-lifecycle++- **Preconditions:** Isolated desktop profile and data directory, git 2.29+, a+ git project on a branch with at least one commit, a configured model, and an+ optional `.worktreeinclude` listing one ignored file.+- **Steps:** Create two isolated sessions from the project menu and run a+ file-editing prompt in each at the same time. Run a Bash command that prints+ `PI_PORT` / `PI_WORKTREE_ROOT`. Merge the first session into the project;+ edit the same line in the project and in the second session, then merge the+ second. Resolve the conflict in the second session and merge again, then+ use **Sync from project** in the first session. In one+ isolated session, start two writing subagents in parallel. Finally delete+ an isolated session with unmerged work, and restart the app once while a+ session exists. Open the menu of a non-git project.+- **Expected:** Each session's edits land only in its own worktree; the project+ checkout and `git status` stay clean until a merge, and the ignored include+ file is present in each worktree. The two sessions get distinct ports. The+ first merge fast-forwards the project and a success toast names the branch.+ The conflicting merge lists the files, leaves the project untouched, and+ marks the row `Conflict`; after resolution the badge clears and the merge+ lands. The first session's row shows `↓N`; Sync from project shows the new+ commits, clears the marker, and brings the resolution+ into the first session without touching the project. Writing+ subagents edit in separate worktrees and completed runs merge back into the+ session. Delete warns about unmerged work and removes the worktree folder+ and `pi-desktop/<id>` branch without touching files linked from it. After+ restart the session reopens in its worktree; a manually removed worktree+ shows `Folder missing` and never falls back to the project. In the non-git+ project **New isolated session** is disabled with the reason under it.+- **Windows checks:** a worktree containing a directory junction is deleted+ without following the junction; a deep path beyond 260 characters is+ created and removed; deleting while a file in the worktree is locked fails+ visibly and can be retried.+- **Specs linked:** `03-runtime/03-tools-and-permissions.md` §4e, §10.2;- `03-runtime/06-host-rpc-protocol.md`; `04-ux/01-ui-ia.md` §3.2; ADR 0328.++ `03-runtime/06-host-rpc-protocol.md`; `04-ux/01-ui-ia.md` §3.2; ADR 0329.+- **Coverage:** host-core `session_worktrees` tests (create, merge, conflict,+ removal, link safety, reconcile, delegates), worktree IPC contract tests,+ renderer `worktree-ui` tests, and agent-runtime delegate tests. The Windows+ checks need a Windows host. `pnpm test:e2e:worktree-live`+ (`scripts/e2e-worktree-live.mjs`) runs the steps above against a real model+ at protocol level, without the renderer.+- **Status:** Partially automated+### E2E-CONVERSATION-minimap-jump-leaves-follow- **Preconditions:** One Desktop conversation long enough that the transcriptdiff --cc docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex 1121e74e7,05c0dd23c..d5701d788--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@@ -770,12 -770,6 +770,12 @@@ type SessionSummary =supportedThinkingLevels?: ThinkingLevel[];updatedAt: string;createdAt: string;- /** Isolated sessions only (ADR 0328); never carries a filesystem path. */++ /** Isolated sessions only (ADR 0329); never carries a filesystem path. */+ worktree?: {+ branch: string;+ status: "creating" | "active" | "conflict" | "merged" | "missing";+ setupStatus?: "none" | "running" | "ok" | "failed" | null;+ };};type UiMessage = {@@@ -869,8 -863,7 +869,8 @@@ ID、或会话无法解析出默认目�最小接口:- `session/list`-- `session/create`+- `session/create` — 可选的 `isolated: true` 配合 `projectPath` 会在专属 git worktree 中创建- 会话(ADR 0328);拒绝时返回主机的 `WORKTREE_*` 代码++ 会话(ADR 0329);拒绝时返回主机的 `WORKTREE_*` 代码- `session/fork({ sessionId, title?, throughMessageId? }) -> { session: SessionDetail }`- `session/get`- `session/delete`@@@ -1114,23 -1107,6 +1114,23 @@@ type ProjectRecord =};```- ## 9a. 会话 worktree API(ADR 0328)++## 9a. 会话 worktree API(ADR 0329)++对主机 `worktree.*` 方法的薄转发(06-host-rpc-protocol §4);错误保留主机的+`WORKTREE_*` 代码。++- `worktree/probe({ projectPath })` → 项目能否承载隔离会话(不能时给出拒绝代码),以及是否+ 有未提交改动+- `worktree/preview({ sessionId })` / `worktree/merge({ sessionId, previewToken })`+- `worktree/behind({ sessionId })` → 提交数,以及 `worktree/sync({ sessionId })` — “从项目同步”;`worktree/behindAll()`+ → `{ counts: { [sessionId]: count }, statusesChanged }`,用于侧边栏标记+- `worktree/pendingWork({ sessionId })` — 删除时会丢弃的未合并工作+- `worktree/setupLog({ sessionId })`+- `worktree/reveal({ sessionId })` — Electron Main 通过 `worktree.location` 解析文件夹并在+ 系统文件管理器中打开;路径绝不返回给渲染器+- `worktree/setupCommand/get({ projectPath })` /+ `worktree/setupCommand/set({ projectPath, command })`+## 10. 工具权限 API当工具需要确认时:diff --cc docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 53956a9cc,0a71c906d..e387bc872--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@@ -835,14 -835,6 +835,14 @@@ details 会说明该委托丢失了历�跑时停止调用工具,运行时保持持久回合打开,并在它们完成时交回报告。用户Stop、`TaskStop`、运行时销毁或父级终态错误(D352)会中止仍在运行的委托。- **隔离 worktree(ADR 0328)。** 在隔离会话中,工具包含 `Write` 或 `Edit` 的委托在首个回合++**隔离 worktree(ADR 0329)。** 在隔离会话中,工具包含 `Write` 或 `Edit` 的委托在首个回合+前获得自己的 worktree(`worktree.delegate.create`,以委托链 id 为键,续跑的委托会复用它),+其 `tools.execute` 调用以 `delegationId` 携带该 id。运行结束时,运行时在发布报告前调用+`worktree.delegate.settle`:完成的运行合回会话 worktree,失败或停止的运行保留改动,结果+(已合并、无改动、冲突及文件、未合并及原因、已保留)附加到报告中,让父级知道是否需要+续跑该委托。host-core 在会话 worktree 中提交和合并时,会短暂挡住会话自己的工具,对已经+在运行的工具最多等待几秒。只读和仅 Bash 的委托,以及非隔离会话的所有委托,行为不变。+### 5f.1 委托权限作用域(ADR 0089)委托的工具调用与父级走同一条 host `tools.execute` 路径。当定义声明了@@@ -1150,12 -1142,6 +1150,12 @@@ sidecar 从不直接读取工作区指�注册的项目根。其 IPC 不接受任意渲染器文件路径。保存会影响下一个提示,而无需重新启动应用程序。- 对隔离会话(ADR 0328),启动元数据另带 `workspaceRoot`,即其 git worktree:指令链及其++对隔离会话(ADR 0329),启动元数据另带 `workspaceRoot`,即其 git worktree:指令链及其+路径解析都以它为根,代理因此遵循 worktree 自己的 `AGENTS.md`。`projectPath` 仍是记忆、+技能、插件、MCP 服务器、子代理定义、自定义系统提示和分组上下文的项目身份。系统提示会+增加一段简短的隔离工作区说明(只在 worktree 中工作、使用 `PI_PORT` 端口块、把切换分支和+合并留给用户,以及如何解决合并冲突)。+## 8. 并发| 适用范围 | MVP 政策 |diff --cc docs/zh-CN/spec/03-runtime/03-tools-and-permissions.mdindex 6e781ecf0,a96854fed..e0760a896--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md@@@ -302,32 -302,6 +302,32 @@@ type ReviewChange =`patch`)——返回带有错误专属恢复提示的终止工具结果,代理随后停止并报告准确的不匹配。不要手动编辑旧的 unified-diff 块头,也不要继续修复循环。- ## 4e. 隔离会话 worktree(ADR 0328)++## 4e. 隔离会话 worktree(ADR 0329)++在 git 项目中以 `isolated: true` 创建的会话拥有专属 worktree,位于+`<data_dir>/worktrees/<project-key>/<id>`,分支为 `pi-desktop/<id>`,从项目当前+`HEAD` 创建(项目中未提交的改动不会被复制;`.worktreeinclude` 列出的 git 忽略文件会被+复制,且不跟随链接)。对这类会话:++- worktree 取代项目路径成为 §4–§5 所有规则的 `workspaceRoot`,文件工具、Bash 工作+ 目录、审阅快照和产物都在其中解析;绝不回退到主检出(worktree 丢失时返回+ `WORKTREE_*` 错误);+- `AGENTS.md` 指令从 worktree 读取,而项目身份(记忆、技能、插件、MCP、子代理)仍以+ 项目路径为键;+- Bash 获得 `PI_PORT`(41000–48999 中一个 10 端口块的首端口)、`PI_PROJECT_ROOT`+ 和 `PI_WORKTREE_ROOT`;+- 可选的项目初始化命令在每个新 worktree 中运行一次,带同样的变量,使用用户的默认命令+ shell(`defaultCommandShell`,未设置时用平台默认:Windows 上为 Windows PowerShell,+ 其他平台为 bash)。命令不会在方言之间转换,因此在 Windows 上必须使用 PowerShell 语法+ (`$env:PI_PORT`;Windows PowerShell 5.1 用 `;` 而不是 `&&`),除非默认 shell 配置为+ Git Bash 等 POSIX shell;+- 宿主在 worktree 中运行的 git 命令禁用 hooks 和 fsmonitor,删除时绝不跟随链接越出+ worktree。++合并到项目是显式的用户操作(先预览,再携带预览令牌合并):先把项目分支同步进+worktree,项目只做快进,因此冲突留在 worktree 中。删除隔离会话即丢弃其 worktree+和分支。+## 5. Bash 规则主机执行基线:diff --cc docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.mdindex e9df69a66,0d6cf9393..3de0badd3--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md@@@ -226,8 -226,7 +226,8 @@@ type ToolBudgetHealth =### 会议- `session.list`- `session.create` — 接受可选的 `thinkingLevel`; missing/null 默认值- 至 `off`。可选的 `isolated: true`(ADR 0328)同时要求 `projectPath`,并在返回前为新会话-至 `off`++至 `off`。可选的 `isolated: true`(ADR 0329)同时要求 `projectPath`,并在返回前为新会话+创建专属 git worktree;无法创建时会话会被删除,调用以 `WORKTREE_*` 错误(§7)失败。- `session.fork` — accepts `sessionId`, an optional caller-provided display`title`, and optional `throughMessageId`; createsone independent session from the source's current active canonical@@@ -410,40 -409,6 +410,40 @@@ off | minimal | low | medium | high | x可能会返回 `thinking`;主机存储将其映射到规范内容块,而不是而不是将其附加到答案 `content` 中。- ### 会话 worktree(ADR 0328)++### 会话 worktree(ADR 0329)++新增的 `worktree.*` 方法为增量 RPC,不升协议版本。失败使用代码 1025 及 `WORKTREE_*`+字符串代码。++- `worktree.probe({ projectPath })` → `{ available, uncommittedChanges }`;项目无法承载+ 隔离会话时(非 git、无提交、分离 `HEAD`、缺少 git 或低于 2.29、远程主机项目——+ `WORKTREE_REMOTE_UNSUPPORTED` 等)返回+ `{ available: false, errorCode, message }`。`session.create` 对远程主机项目的 `isolated: true` 以同一代码拒绝,+ 不会创建任何会话。+- `worktree.preview({ sessionId })` → `{ preview }`,包含将要合入的提交、文件及+ `previewToken`。+- `worktree.merge({ sessionId, previewToken })` → `{ outcome }`。令牌过期为+ `WORKTREE_CHANGED_SINCE_PREVIEW`;项目有未提交改动为 `WORKTREE_PROJECT_DIRTY`;冲突为+ `WORKTREE_CONFLICT`,worktree 保持冲突状态,项目不受影响。+- `worktree.behind({ sessionId })` → `{ commits }`,即会话尚未包含的项目分支提交数。+- `worktree.behindAll()` → `{ counts, statusesChanged }`:以会话 id 为键给出每个隔离会话的同一计数+ (读不到的会话省略),每次并发检查少量会话。处于冲突状态的会话会先检查是否已解决;+ `statusesChanged` 提示渲染层刷新会话列表。渲染层在后台读取,用于侧边栏标记。+- `worktree.sync({ sessionId })` → `{ outcome }`(`synced` 及 `commits`,或 `upToDate`):+ “从项目同步”先提交会话中待提交的工作,再把项目分支合入会话 worktree。不改动项目检出;+ 冲突为 `WORKTREE_CONFLICT`,留在 worktree 中,并像合并冲突一样标记会话。+- `worktree.pendingWork({ sessionId })` → `{ pending }`,即删除会丢弃的未合并工作。+- `worktree.setupLog({ sessionId })` → `{ setupStatus, log }`。+- `worktree.location({ sessionId })` → `{ path }`;仅供 Electron Main 的“在文件夹中显示”+ 使用,绝不转发给渲染器。+- `worktree.setupCommand.get({ projectPath })` → `{ command }`;+ `worktree.setupCommand.set({ projectPath, command })` → `{ ok }`(未知项目为+ `NOT_FOUND`)。该命令在每个新 worktree 中运行一次。+- `worktree.delegate.create({ sessionId, delegationId })` → `{ worktree }` 和+ `worktree.delegate.settle({ sessionId, delegationId, merge })` → `{ settlement }`——仅供+ agent-runtime 为隔离会话中的 `Write`/`Edit` 子代理使用(03-tools-and-permissions §10.2)。两者使用+ 10 分钟的传输期限(`WORKTREE_DELEGATE_RPC_TIMEOUT_MS`),因为提交和合并前可能要等待会话的工具。+### 工具- `tools.list`- `tools.execute`@@@ -611,9 -576,6 +611,9 @@@ type ToolsExecuteParams =expectedCommandShellDialect?: "powershell" | "cmd" | "posix"/** Bash only: host default 60000; accepted override 1000..21600000. */timeoutMs?: number+ /** Isolated `Write`/`Edit` delegate chain id; re-roots the call to that- * delegate's worktree (ADR 0328). Omitted for every other call. */++ * delegate's worktree (ADR 0329). Omitted for every other call. */+ delegationId?: string}```diff --cc docs/zh-CN/spec/04-ux/01-ui-ia.mdindex 3dcee9621,acf539e48..dc61495f1--- a/docs/zh-CN/spec/04-ux/01-ui-ia.md+++ b/docs/zh-CN/spec/04-ux/01-ui-ia.md@@@ -185,15 -185,6 +185,15 @@@- **对话操作**:pin/unpin、archive/restore 和删除保留单独的行动。存档永远不会删除文字记录。打开的文件夹是项目行动,而不是对话行动。- - **隔离会话**(ADR 0328):项目菜单提供 **新建隔离会话**。打开菜单时探测项目:结果返回前该项++- **隔离会话**(ADR 0329):项目菜单提供 **新建隔离会话**。打开菜单时探测项目:结果返回前该项+ 保持置灰;对不适用的项目(非 git、无提交、分离 `HEAD`、缺少 git 或版本过旧)保持置灰,+ 并在下方显示原因。创建时会再次探测;项目有未提交改动时显示信息提示,说明这些改动不会+ 带入。菜单还包含+ **Worktree 初始化命令…**。隔离会话行显示 `Isolated` 徽标(或 `Conflict`、+ `Folder missing`、`Setup failed`),并增加 **合并到项目…**(先预览提交和文件,再合并;+ 冲突文件会列出并留在会话中;会话一旦解决或放弃冲突,`Conflict` 徽标即消失,下次合并时完成该合并)、**从项目同步**(打开菜单时显示项目新提交的数量,没有新提交或会话处于冲突状态时置灰,冲突状态下也不显示 `↓N` 标记;把项目分支合入会话,让会话基于最新代码继续开发,冲突像合并冲突一样留在会话中;缺少项目提交的会话行在徽标旁显示 `↓N` 标记,它在隔离会话变化、合并或同步之后以及窗口获得焦点时(最多每 15 秒一次)于后台读取,渲染列表从不等待 git)、**显示 worktree 文件夹** 和 **初始化日志**。删除确认会说明+ 未合并的工作将丢失。隔离会话不会被当作空草稿复用,也不能移动到其他项目;分叉得到的+ 是普通会话。- **排序**:面向用户的模式为最近更新、创建日期、最旧首先是姓名。固定的行先于未固定的行。项目组通过拖动标题或在该标题上按 `ArrowUp`/`ArrowDown` 切换到 `manual`。会话 `manual` 仍是兼容性值。diff --cc docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 2c64120b5,a3dda6d9d..cb1bec3d0--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@@ -9387,33 -9403,6 +9403,33 @@@ Follow the [current S3 acceptance scenasession IPC contract tests, and real-model desktop acceptance. A local modelfixture or mocked component result is not real-model acceptance evidence.+### E2E-WORKTREE-isolated-session-lifecycle++- **前置条件:** 隔离的桌面配置和数据目录、git 2.29+、一个处于分支上且至少有一次提交的+ git 项目、已配置的模型,以及可选的 `.worktreeinclude`(列出一个被忽略的文件)。+- **步骤:** 从项目菜单创建两个隔离会话,同时在两者中运行修改文件的提示。运行打印+ `PI_PORT` / `PI_WORKTREE_ROOT` 的 Bash 命令。把第一个会话合并到项目;在项目和第二个+ 会话中修改同一行,再合并第二个会话。在第二个会话中解决冲突后再次合并,然后在第一个会话中使用**从项目同步**。在一个隔离会话+ 中并行启动两个写文件的子代理。最后删除一个含未合并工作的隔离会话,并在会话存在时重启+ 一次应用。打开一个非 git 项目的菜单。+- **预期:** 每个会话的修改只落在自己的 worktree 中;在合并前项目检出和 `git status`+ 保持干净,每个 worktree 中都有被 include 的忽略文件。两个会话获得不同端口。第一次合并+ 快进项目,成功提示中给出分支名。冲突的合并会列出文件、不改动项目,并把该行标为+ `Conflict`;解决后徽标消失、合并成功。第一个会话行显示 `↓N`;从项目同步会显示新提交数并清除该标记,并把冲突解决结果带入第一个会话,不改动项目。写文件的子代理在各自的 worktree 中编辑,完成的运行合回会话。+ 删除时提示未合并工作将丢失,并删除 worktree 文件夹和 `pi-desktop/<id>` 分支,不触碰其中+ 链接指向的文件。重启后会话在其 worktree 中重新打开;被手动删除的 worktree 显示+ `Folder missing`,且绝不回退到项目目录。在非 git 项目中 **新建隔离会话** 置灰,并在下方+ 显示原因。+- **Windows 检查:** 含目录 junction 的 worktree 删除时不跟随 junction;超过 260 字符的深+ 路径能创建和删除;worktree 中有文件被锁定时删除会明确失败并可重试。+- **关联规范:** `03-runtime/03-tools-and-permissions.md` §4e、§10.2;- `03-runtime/06-host-rpc-protocol.md`;`04-ux/01-ui-ia.md` §3.2;ADR 0328。++ `03-runtime/06-host-rpc-protocol.md`;`04-ux/01-ui-ia.md` §3.2;ADR 0329。+- **覆盖:** host-core `session_worktrees` 测试(创建、合并、冲突、删除、链接安全、启动+ 对账、子代理)、worktree IPC 契约测试、渲染层 `worktree-ui` 测试和 agent-runtime 子代理+ 测试。Windows 检查需要 Windows 主机。`pnpm test:e2e:worktree-live`+ (`scripts/e2e-worktree-live.mjs`)在协议层用真实模型执行上述步骤,不经过渲染层。+- **状态:** Partially automated+### E2E-HOOKS-cancel-and-dispose- **#816 扩展验收:** 命令弹窗显示期间 Stop,真实渲染层移除弹窗,后续弹窗和 execdiff --cc packages/agent-runtime/src/runtime.test.tsindex 94615848e,ae5998edb..8b700a01d--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@@ -11825,181 -12046,3 +12051,181 @@@ describe("local runtime with a remote tawait runtime.dispose();});});+- describe("isolated session workspace (ADR 0328)", () => {++describe("isolated session workspace (ADR 0329)", () => {+ const systemPrompt = (runtime: DesktopAgentRuntime): string =>+ (runtime as unknown as { agent: { state: { systemPrompt: string } } }).agent.state+ .systemPrompt;++ it("tells the model about the worktree only in an isolated session", () => {+ const isolated = createRuntime({ projectPath: "/work/app", workspaceRoot: "/data/wt/app/s1" });+ const ordinary = createRuntime({ projectPath: "/work/app" });+ expect(systemPrompt(isolated)).toContain(isolatedWorkspaceGuidance());+ expect(systemPrompt(isolated)).toContain("PI_PORT");+ expect(systemPrompt(ordinary)).not.toContain("Isolated session:");+ });++ it("works in the worktree while the project stays its identity", () => {+ const runtime = createRuntime({ projectPath: "/work/app", workspaceRoot: "/data/wt/app/s1" });+ const internals = runtime as unknown as { extensionCwd(): string; projectPath?: string };+ expect(internals.extensionCwd()).toBe("/data/wt/app/s1");+ expect(internals.projectPath).toBe("/work/app");+ expect(+ (createRuntime({ projectPath: "/work/app" }) as unknown as { extensionCwd(): string })+ .extensionCwd(),+ ).toBe("/work/app");+ });++ it("is not reused for another worktree or for a non-isolated launch", () => {+ const runtime = createRuntime({ projectPath: "/work/app", workspaceRoot: "/data/wt/app/s1" });+ expect(runtimeMatches(runtime)).toBe(true);+ expect(runtimeMatches(runtime, { workspaceRoot: "/data/wt/app/s2" })).toBe(false);+ expect(runtimeMatches(runtime, { workspaceRoot: undefined })).toBe(false);+ });+});+- describe("isolated-session subagent worktrees (ADR 0328)", () => {++describe("isolated-session subagent worktrees (ADR 0329)", () => {+ const writer: SubagentDefinition = {+ name: "fixer",+ description: "Implement a change.",+ tools: ["Read", "Edit", "Write"],+ prompt: "Implement it.",+ source: "builtin",+ };+ const shellOnly: SubagentDefinition = {+ name: "test-runner",+ description: "Run tests.",+ tools: ["Read", "Grep", "Bash"],+ prompt: "Run them.",+ source: "builtin",+ };+ const tool = (runtime: DesktopAgentRuntime, name: string) =>+ (runtime as any).agent.state.tools.find((entry: any) => entry.name === name);++ function worktreeHost(settlement: unknown, createError?: Error) {+ return {+ call: vi.fn(async (method: string, _params?: unknown) => {+ if (method === "worktree.delegate.create") {+ if (createError) throw createError;+ return { worktree: { branch: "pi-desktop/s-d", status: "active" } };+ }+ if (method === "worktree.delegate.settle") return { settlement };+ if (method === "tools.execute") return { ok: true, content: {} };+ return undefined;+ }),+ onNotification: vi.fn(() => () => {}),+ };+ }+ const calls = (host: ReturnType<typeof worktreeHost>, method: string) =>+ host.call.mock.calls.filter(([name]) => name === method).map(([, params]) => params as any);++ async function runToEnd(runtime: DesktopAgentRuntime, agent: string, id: string) {+ const started = await tool(runtime, "Task").execute(id, { agent, task: "Do it." });+ const delegationId = (started.details as any).delegationId as string;+ const waited = await tool(runtime, "TaskWait").execute(`${id}-wait`, { delegationIds: [delegationId] });+ return { started, delegationId, text: waited.content[0].text as string };+ }++ beforeEach(() => {+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = false;+ subagentRuns.constructorError = undefined;+ subagentRuns.result = undefined;+ });++ it("gives a writing delegate its own worktree, routes its tools there, and reports the merge", async () => {+ const host = worktreeHost({ result: "merged", commits: 2 });+ const runtime = createRuntime({+ subagents: [writer, shellOnly],+ host: host as never,+ projectPath: "/work/app",+ workspaceRoot: "/data/wt/app/s1",+ });+ const { delegationId, text } = await runToEnd(runtime, "fixer", "task-w");+ const [create] = calls(host, "worktree.delegate.create");+ expect(create).toEqual({ sessionId: "session-1", delegationId });++ const write = subagentRuns.calls[0].tools.find((entry: any) => entry.name === "Write");+ await write.execute("write-1", { path: "a.txt", content: "x" }, undefined, undefined);+ expect(calls(host, "tools.execute").at(-1)).toEqual(+ expect.objectContaining({ delegationId }),+ );+ expect((runtime as any).delegateWorktrees.size).toBe(0);++ expect(calls(host, "worktree.delegate.settle")).toEqual([+ { sessionId: "session-1", delegationId, merge: true },+ ]);+ expect(text).toContain("Isolated worktree: merged 2 commit(s) into the session workspace.");+ await runtime.dispose();+ });++ it("leaves Bash-only delegates and non-isolated sessions on the shared workspace", async () => {+ const host = worktreeHost({ result: "merged", commits: 1 });+ const isolated = createRuntime({+ subagents: [writer, shellOnly],+ host: host as never,+ projectPath: "/work/app",+ workspaceRoot: "/data/wt/app/s1",+ });+ await runToEnd(isolated, "test-runner", "task-b");+ const ordinary = createRuntime({ subagents: [writer], host: host as never, projectPath: "/work/app" });+ await runToEnd(ordinary, "fixer", "task-o");+ expect(calls(host, "worktree.delegate.create")).toEqual([]);+ expect(calls(host, "worktree.delegate.settle")).toEqual([]);+ const write = subagentRuns.calls[1].tools.find((entry: any) => entry.name === "Write");+ await write.execute("write-o", { path: "a.txt", content: "x" }, undefined, undefined);+ expect(calls(host, "tools.execute").at(-1)).not.toHaveProperty("delegationId");+ await isolated.dispose();+ await ordinary.dispose();+ });++ it("keeps an unfinished run's work and tells the parent how to resolve a conflict", async () => {+ const conflictHost = worktreeHost({ result: "conflict", files: ["src/a.ts"] });+ const runtime = createRuntime({+ subagents: [writer],+ host: conflictHost as never,+ projectPath: "/work/app",+ workspaceRoot: "/data/wt/app/s1",+ });+ const { delegationId, text } = await runToEnd(runtime, "fixer", "task-c");+ expect(text).toContain("NOT merged");+ expect(text).toContain("src/a.ts");+ expect(text).toContain(`Task(resume: "${delegationId}")`);++ const keptHost = worktreeHost({ result: "kept" });+ const failing = createRuntime({+ subagents: [writer],+ host: keptHost as never,+ projectPath: "/work/app",+ workspaceRoot: "/data/wt/app/s1",+ });+ subagentRuns.result = { agentName: "fixer", status: "failed", report: "boom", turns: 1, toolCalls: 1 };+ const failed = await runToEnd(failing, "fixer", "task-f");+ expect(calls(keptHost, "worktree.delegate.settle")[0].merge).toBe(false);+ expect(failed.text).toContain("changes were kept unmerged");+ await runtime.dispose();+ await failing.dispose();+ });++ it("does not start a writing delegate whose worktree cannot be created", async () => {+ const host = worktreeHost({ result: "none" }, new Error("the session has an unfinished merge conflict"));+ const runtime = createRuntime({+ subagents: [writer],+ host: host as never,+ projectPath: "/work/app",+ workspaceRoot: "/data/wt/app/s1",+ });+ const result = await tool(runtime, "Task").execute("task-x", { agent: "fixer", task: "Do it." });+ expect(result.details.error).toContain("Could not prepare an isolated worktree");+ expect(result.details.error).toContain("unfinished merge conflict");+ expect(subagentRuns.calls).toHaveLength(0);+ await runtime.dispose();+ });++ it("describes every settlement in the report", () => {+ const resume = 'Task(resume: "d1")';+ expect(delegateWorktreeNote({ result: "noChanges" }, resume)).toContain("no file changes");+ expect(delegateWorktreeNote({ result: "notMerged", reason: "busy" }, resume)).toContain("busy");+ expect(delegateWorktreeNote({ result: "none" }, resume)).toBe("");+ });+});diff --cc packages/agent-runtime/src/runtime.tsindex 0d54d6d9d,5da3b4ba2..93d1d0251--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@@ -513,11 -513,6 +513,11 @@@ export type DelegationStatus*/export type DelegationRecord = {delegationId: string;+ /**+ * Chain id under which host-core keeps this Write/Edit subagent's own git- * worktree in an isolated session (ADR 0328); absent otherwise.++ * worktree in an isolated session (ADR 0329); absent otherwise.+ */+ worktreeKey?: string;/** Original Task transcript snapshot, available after its immediate result. */taskMessage?: UiMessage;taskTurnId?: string;@@@ -986,11 -981,6 +986,11 @@@ export type AgentRuntimeOptions =projectPath?: string;/** Remote tool root. Model requests and runtime state remain on this machine. */remoteWorkspace?: { hostKey: string; path: string };+ /**- * An isolated session's git worktree (ADR 0328). Files, the extension cwd,++ * An isolated session's git worktree (ADR 0329). Files, the extension cwd,+ * and edit bookkeeping use it; `projectPath` stays the project identity.+ */+ workspaceRoot?: string;/** Instructions resolved from the session's workspace. */projectInstructions?: ProjectInstructions;/** Durable project context loaded from host-owned project memory. */@@@ -1732,50 -1721,6 +1732,50 @@@ function estimateVisibleResponseOutputTreturn Math.max(1, Math.ceil(Array.from(visible).length / 4));}- /** host-core's `worktree.delegate.settle` result (ADR 0328). */++/** host-core's `worktree.delegate.settle` result (ADR 0329). */+export type DelegateWorktreeSettlement =+ | { result: "none" }+ | { result: "noChanges" }+ | { result: "merged"; commits: number }+ | { result: "conflict"; files: string[] }+ | { result: "notMerged"; reason: string }+ | { result: "kept" };++/** The line appended to a delegate's report about its worktree. */+export function delegateWorktreeNote(settlement: DelegateWorktreeSettlement, resume: string): string {+ switch (settlement.result) {+ case "merged":+ return `Isolated worktree: merged ${settlement.commits} commit(s) into the session workspace.`;+ case "noChanges":+ return "Isolated worktree: no file changes; the worktree was removed.";+ case "conflict":+ return `Isolated worktree: NOT merged. These files conflict with the session workspace: ${settlement.files.join(", ")}. Continue with ${resume} to resolve them in the subagent's worktree; the merge is retried when it ends.`;+ case "notMerged":+ return `Isolated worktree: not merged yet (${settlement.reason}). Continue with ${resume} to retry.`;+ case "kept":+ return `Isolated worktree: the run did not complete, so its changes were kept unmerged. Continue with ${resume} to finish them.`;+ default:+ return "";+ }+}++/**- * System-prompt rules for an isolated session (ADR 0328): the workspace is a++ * System-prompt rules for an isolated session (ADR 0329): the workspace is a+ * separate git worktree that the user merges from the app.+ */+export function isolatedWorkspaceGuidance(): string {+ return [+ "Isolated session: the advertised workspace is a separate git worktree on its own branch; the user's main project checkout is outside it.",+ "Edit, build, and test only inside this workspace and never change files in the main checkout.",+ "The worktree is a fresh checkout, so install dependencies first when a build or test needs them.",+ "Start dev servers only on the 10 ports beginning at the PI_PORT environment variable.",+ "Do not switch branches, rebase, or reset in this worktree; the user merges its branch into the project from the app.",+ "To resolve a merge conflict here, remove the conflict markers from text files, and stage binary or deleted files with git add or git rm.",+ "MCP tools act on the main project, not on this workspace.",+ "Subagents that can Write or Edit work in their own worktrees and are merged back when they finish; their report states the merge result.",+ ].join(" ");+}+export class DesktopAgentRuntime {private agent: Agent;private models: Models;@@@ -1843,8 -1788,6 +1843,8 @@@* resolves the delegate's permission under it instead of the session mode.*/private delegatePermissionScopes = new Map<string, SubagentPermission>();- /** Worktree key of the delegate executing one tool call (ADR 0328). */++ /** Worktree key of the delegate executing one tool call (ADR 0329). */+ private delegateWorktrees = new Map<string, string>();/** Serializes same-path mutations across the parent and its delegates. */private writeLocks = new PathMutex();/** Complete tool registry; only the active subset is sent to the provider. */@@@ -2043,8 -1986,6 +2045,8 @@@this.remoteWorkspace = opts.remoteWorkspace;this.scratchDir = opts.remoteWorkspace ? undefined : opts.scratchDir;this.projectPath = opts.remoteWorkspace?.path ?? (opts.projectPath?.trim() || undefined);- // Remote workspaces are never isolated (ADR 0328).++ // Remote workspaces are never isolated (ADR 0329).+ this.workspaceRoot = opts.remoteWorkspace ? undefined : opts.workspaceRoot?.trim() || undefined;this.customSystemPrompt = opts.customSystemPrompt;this.baseProjectInstructions = opts.projectInstructions;this.projectInstructions = opts.projectInstructions;@@@ -2096,8 -2037,6 +2098,8 @@@ Do not invent objections or turn specul`Your scratch directory for this session is \`${formatScratchDirForShell(this.commandShell, this.scratchDir)}\` (in Bash: ${shellScratchVariable(this.commandShell)}). Store ad-hoc temporary and intermediate files there using absolute paths. Workspace writes must be task-related project files or required toolchain outputs. Scratch persists across turns and is deleted with the session.`,]: []),- // Isolated session (ADR 0328).++ // Isolated session (ADR 0329).+ ...(this.workspaceRoot ? [isolatedWorkspaceGuidance()] : []),];// A custom SYSTEM.md replaces only the product persona line, never the// operational rules in the default parts: tool guidance, delegation@@@ -4777,30 -4707,6 +4780,30 @@@);}const delegationId = randomUUID();- // ADR 0328: in an isolated session a delegate that can write files gets++ // ADR 0329: in an isolated session a delegate that can write files gets+ // its own worktree, keyed by its chain so a resume reuses it.+ const worktreeKey = this.delegateNeedsWorktree(declaredToolNames)+ ? resumedChain?.delegateSessionId ?? delegationId+ : undefined;+ if (worktreeKey) {+ try {+ await this.host.call("worktree.delegate.create", {+ sessionId: this.sessionId,+ delegationId: worktreeKey,+ });+ } catch (error) {+ return this.subagentToolError(+ toolCallId,+ `Could not prepare an isolated worktree for the ${definition.name} subagent: ${+ error instanceof Error ? error.message : String(error)+ }. No work was started.`,+ );+ }+ if (this.disposed || this.runCancelled || this.turnHadError || resumeEpoch !== this.turnEpoch) {+ void this.settleDelegateWorktree(worktreeKey, false, delegationId);+ return this.subagentToolError(toolCallId, "The parent turn ended before delegation could start.");+ }+ }const controller = new AbortController();const thinkingLevel: SubagentThinkingLevel =definition.thinkingLevel === "omit"@@@ -5005,58 -4906,6 +5008,58 @@@}));}+ /**+ * Only inside an isolated session, and only for delegates that can edit+ * files (Write/Edit); Bash-only and read-only delegates share the session- * worktree (ADR 0328, Q11).++ * worktree (ADR 0329, Q11).+ */+ private delegateNeedsWorktree(toolNames: readonly string[]): boolean {+ return (+ this.workspaceRoot !== undefined &&+ toolNames.some((name) => name === "Write" || name === "Edit")+ );+ }++ /**+ * Settle a delegate's worktree before its report is published: a completed+ * run is merged back into the session worktree, anything else is kept for a+ * resume. The outcome is appended to the report the parent reads.+ */+ private async finishDelegation(+ record: DelegationRecord,+ result: SubagentRunResult,+ ): Promise<void> {+ if (record.worktreeKey && record.status === "running") {+ const note = await this.settleDelegateWorktree(+ record.worktreeKey,+ result.status === "completed",+ record.delegationId,+ );+ if (note) result = { ...result, report: result.report ? `${result.report}\n\n${note}` : note };+ }+ this.settleDelegation(record, result);+ }++ /** Ask host-core to settle a delegate worktree; returns a report note. */+ private async settleDelegateWorktree(+ worktreeKey: string,+ merge: boolean,+ delegationId: string,+ ): Promise<string> {+ const resume = `Task(resume: "${delegationId}")`;+ try {+ const { settlement } = await this.host.call<{ settlement: DelegateWorktreeSettlement }>(+ "worktree.delegate.settle",+ { sessionId: this.sessionId, delegationId: worktreeKey, merge },+ );+ return delegateWorktreeNote(settlement, resume);+ } catch (error) {+ return `Isolated worktree: merge-back failed (${+ error instanceof Error ? error.message : String(error)+ }); the subagent's changes are kept. Continue with ${resume} to retry.`;+ }+ }+/** Records a settled run and wakes every TaskWait waiting on it. */private settleDelegation(record: DelegationRecord,diff --cc packages/agent-runtime/src/sidecar.tsindex 4bcf17145,980fdb2ed..c591dabaf--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@@ -124,8 -124,6 +124,8 @@@ type RuntimeParams =/** Session-bound workspace root supplied by Electron main. */projectPath?: string;remoteWorkspace?: { hostKey: string; path: string };- /** An isolated session's worktree root, supplied by Electron main (ADR 0328). */++ /** An isolated session's worktree root, supplied by Electron main (ADR 0329). */+ workspaceRoot?: string;customSystemPrompt?: CustomSystemPrompt;projectInstructions?: ProjectInstructions;projectMemory?: string;diff --cc packages/shared/src/protocol.test.tsindex 324b609b1,ae7a30f58..7d0d746d7--- a/packages/shared/src/protocol.test.ts+++ b/packages/shared/src/protocol.test.ts@@@ -249,14 -247,6 +249,14 @@@ describe("Plan protocol contracts", ());});- it("lets a subagent worktree merge outlast its permit waits (ADR 0328)", () => {++ it("lets a subagent worktree merge outlast its permit waits (ADR 0329)", () => {+ for (const method of ["worktree.delegate.create", "worktree.delegate.settle"]) {+ expect(rpcTimeoutMs(method, {})).toBe(WORKTREE_DELEGATE_RPC_TIMEOUT_MS);+ }+ expect(WORKTREE_DELEGATE_RPC_TIMEOUT_MS).toBeGreaterThan(5_000 + TOOL_QUEUE_WAIT_MS + 3 * 120_000);+ expect(rpcTimeoutMs("worktree.merge", {})).toBe(130_000);+ });+it("outlasts the whole model request a manual compaction spends (#795)", () => {// One summary prompt plus the sidecar's retry budget: every attempt that// stops producing events is cut by the stream watchdog, and each retry paysdiff --cc packages/shared/src/protocol.tsindex b85fd60ce,e1f65328f..b8cf71270--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@@ -136,21 -136,6 +136,21 @@@ export const IPC =/** Validate and select a durable session from a reviewed host operation. */sessionOpen: "pi-desktop/session/open",sessionDelete: "pi-desktop/session/delete",- /** Isolated sessions in git worktrees (ADR 0328). */++ /** Isolated sessions in git worktrees (ADR 0329). */+ worktreeProbe: "pi-desktop/worktree/probe",+ worktreePreview: "pi-desktop/worktree/preview",+ worktreeMerge: "pi-desktop/worktree/merge",+ worktreePendingWork: "pi-desktop/worktree/pendingWork",+ /** "Sync from project": project commits the session lacks, and the sync. */+ worktreeBehind: "pi-desktop/worktree/behind",+ worktreeSync: "pi-desktop/worktree/sync",+ /** Behind counts of every isolated session, for the sidebar marker. */+ worktreeBehindAll: "pi-desktop/worktree/behindAll",+ worktreeSetupLog: "pi-desktop/worktree/setupLog",+ /** Opens the worktree folder in the OS file manager; no path is returned. */+ worktreeReveal: "pi-desktop/worktree/reveal",+ worktreeSetupCommandGet: "pi-desktop/worktree/setupCommand/get",+ worktreeSetupCommandSet: "pi-desktop/worktree/setupCommand/set",sessionRename: "pi-desktop/session/rename",/** Deterministic first-prompt title for a session that is still untitled. */sessionDeriveTitle: "pi-desktop/session/deriveTitle",diff --cc packages/shared/src/rpc-timeouts.tsindex 503894459,0df025f53..943866a10--- a/packages/shared/src/rpc-timeouts.ts+++ b/packages/shared/src/rpc-timeouts.ts@@@ -55,15 -55,6 +55,15 @@@ export const AGENT_COMPACT_RPC_TIMEOUT_COMPACTION_SUMMARY_RETRY_BUDGET_MS +COMMAND_RPC_BUFFER_MS;+/**- * `worktree.delegate.create` / `.settle` (ADR 0328) checkpoint and merge in a++ * `worktree.delegate.create` / `.settle` (ADR 0329) checkpoint and merge in a+ * session worktree: up to 5s waiting for the session to go quiet, up to+ * `TOOL_QUEUE_WAIT_MS` for its write permit, then a handful of git commands,+ * each bounded by host-core. Under the flat default the runtime gave up while+ * the host was still merging and reported work as kept that had landed.+ */+export const WORKTREE_DELEGATE_RPC_TIMEOUT_MS = 10 * 60_000;+/*** `configSync.syncNow` is a Host-owned multi-step operation. It has no* whole-request deadline: individual S3 requests retain their own bounds, anddiff --cc packages/shared/src/types/sessions.tsindex facf6ba41,34dc4b6c8..a76795597--- a/packages/shared/src/types/sessions.ts+++ b/packages/shared/src/types/sessions.ts@@@ -69,11 -68,6 +69,11 @@@ export type SessionSummary =* Older hosts omit it, so `undefined` means an ordinary conversation.*/scheduledRun?: boolean;+ /**- * Present only for an isolated session (ADR 0328): its tools run in its own++ * Present only for an isolated session (ADR 0329): its tools run in its own+ * git worktree. Older hosts and ordinary sessions omit it.+ */+ worktree?: SessionWorktreeSummary;updatedAt: string;createdAt: string;};diff --cc packages/shared/src/types/worktree.tsindex b9b45af0f,000000000..3ae6b6ed2mode 100644,000000..100644--- a/packages/shared/src/types/worktree.ts+++ b/packages/shared/src/types/worktree.ts@@@ -1,107 -1,0 +1,107 @@@+/**- * Isolated sessions in git worktrees (ADR 0328). Host-core owns every++ * Isolated sessions in git worktrees (ADR 0329). Host-core owns every+ * worktree path and git command; these shapes carry no filesystem path.+ */++export type WorktreeStatus = "creating" | "active" | "conflict" | "merged" | "missing";++export type WorktreeSetupStatus = "none" | "running" | "ok" | "failed";++/** Badge data attached to `SessionSummary.worktree` for isolated sessions. */+export type SessionWorktreeSummary = {+ branch: string;+ status: WorktreeStatus;+ setupStatus?: WorktreeSetupStatus | null;+};++/** Machine-readable `errorCode` values of `worktree.*` and isolated sessions. */+export const WorktreeErrorCodes = {+ GIT_MISSING: "WORKTREE_GIT_MISSING",+ GIT_TOO_OLD: "WORKTREE_GIT_TOO_OLD",+ GIT_FAILED: "WORKTREE_GIT_FAILED",+ GIT_TIMEOUT: "WORKTREE_GIT_TIMEOUT",+ NOT_GIT: "WORKTREE_NOT_GIT",+ NO_COMMITS: "WORKTREE_NO_COMMITS",+ DETACHED_HEAD: "WORKTREE_DETACHED_HEAD",+ BRANCH_NAMESPACE_TAKEN: "WORKTREE_BRANCH_NAMESPACE_TAKEN",+ NOT_ISOLATED: "WORKTREE_NOT_ISOLATED",+ NOT_READY: "WORKTREE_NOT_READY",+ MISSING: "WORKTREE_MISSING",+ BUSY: "WORKTREE_BUSY",+ CONFLICT: "WORKTREE_CONFLICT",+ CHANGED_SINCE_PREVIEW: "WORKTREE_CHANGED_SINCE_PREVIEW",+ OWNER_BRANCH_CHANGED: "WORKTREE_OWNER_BRANCH_CHANGED",+ PROJECT_DIRTY: "WORKTREE_PROJECT_DIRTY",+ MERGE_FAILED: "WORKTREE_MERGE_FAILED",+ COMMIT_FAILED: "WORKTREE_COMMIT_FAILED",+ MOVE_UNSUPPORTED: "WORKTREE_MOVE_UNSUPPORTED",+ PATH_EXISTS: "WORKTREE_PATH_EXISTS",+ /** The project lives on a remote host; isolation needs a local checkout. */+ REMOTE_UNSUPPORTED: "WORKTREE_REMOTE_UNSUPPORTED",+} as const;++export type WorktreeErrorCode = (typeof WorktreeErrorCodes)[keyof typeof WorktreeErrorCodes];++/** `worktree.probe`: whether a project can host isolated sessions. */+export type WorktreeProbeResult =+ | { available: true; uncommittedChanges: boolean }+ | { available: false; errorCode: WorktreeErrorCode | string; message: string };++export type WorktreeIncludeReport = {+ copied: string[];+ skippedLinks: string[];+};++/** Extra result of `session.create` with `isolated: true`. */+export type CreatedSessionWorktree = {+ worktree: SessionWorktreeSummary;+ included: WorktreeIncludeReport;+ projectHadUncommittedChanges: boolean;+};++export type WorktreePreviewCommit = { sha: string; subject: string };++export type WorktreePreviewFile = {+ /** `A`, `M`, `D`, ... for committed changes; `?` for untracked files. */+ status: string;+ path: string;+ /** Committed on the session branch when the merge runs. */+ uncommitted: boolean;+};++/** `worktree.preview`: what "Merge into project" would land. */+export type WorktreeMergePreview = {+ branch: string;+ ownerBranch: string;+ commits: WorktreePreviewCommit[];+ files: WorktreePreviewFile[];+ conflict: boolean;+ previewToken: string;+};++export type WorktreeMergeOutcome =+ | { result: "merged"; commits: number; files: number }+ | { result: "nothingToMerge" };++/** `worktree.sync`: "Sync from project" brings the project's new commits in. */+export type WorktreeSyncOutcome =+ | { result: "synced"; commits: number }+ | { result: "upToDate" };++/** `worktree.behindAll`: the sidebar's behind counts, keyed by session id. */+export type WorktreeBehindCounts = {+ counts: Record<string, number>;+ /** A conflict was found resolved; the session list should be refreshed. */+ statusesChanged: boolean;+};++/** `worktree.pendingWork`: what deleting the session would lose. */+export type WorktreePendingWork = {+ unmergedCommits: number;+ uncommittedChanges: boolean;+};++export type WorktreeSetupLog = {+ setupStatus: WorktreeSetupStatus | null;+ log: string | null;+};diff --cc scripts/e2e-worktree-live.mjsindex 4c7370981,000000000..c96ee6668mode 100644,000000..100644--- a/scripts/e2e-worktree-live.mjs+++ b/scripts/e2e-worktree-live.mjs@@@ -1,328 -1,0 +1,328 @@@+#!/usr/bin/env node+/**- * Live-model E2E for isolated sessions (ADR 0328,++ * Live-model E2E for isolated sessions (ADR 0329,+ * E2E-WORKTREE-isolated-session-lifecycle), protocol level: a real host-core+ * and agent runtime with a real model, a throwaway git project, and a+ * throwaway data directory. Nothing outside the temp directory is touched.+ *+ * Env (no defaults: this sends real prompts with a real key), either+ * PI_DESKTOP_TEST_API_KEY, PI_DESKTOP_TEST_BASE_URL (OpenAI-compatible) and+ * PI_DESKTOP_TEST_MODEL, or PI_DESKTOP_TEST_PROVIDER_DATA_DIR: a *copy* of a+ * PI-Desktop data directory whose default provider and model are used (the+ * copy may be migrated). Optional: PI_DESKTOP_HOST_BIN, PI_DESKTOP_KEEP_TEMP.+ */+import { execFileSync } from "node:child_process";+import { randomUUID } from "node:crypto";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { DesktopAgentRuntime } from "../packages/agent-runtime/dist/runtime.js";+import { PROTOCOL_VERSION } from "../packages/shared/dist/protocol.js";+import { Host, resolveHostBinary } from "./e2e/host.mjs";++/** The default provider of a copied data directory; the key stays in memory. */+async function providerFromDataDir(dir) {+ const source = new Host(resolveHostBinary(), dir, { quiet: true });+ await source.start(PROTOCOL_VERSION);+ try {+ const settings = await source.call("settings.get");+ const values = settings.settings ?? settings;+ const { providers } = await source.call("providers.list");+ const provider =+ providers.find((entry) => entry.id === values.defaultProviderId) ?? providers.find((entry) => entry.enabled);+ if (!provider) throw new Error("the data directory has no provider");+ const { value } = await source.call("providers.getSecret", { id: provider.id });+ if (!value) throw new Error(`provider ${provider.name} has no API key`);+ return {+ name: provider.name,+ baseUrl: provider.baseUrl,+ model: provider.id === values.defaultProviderId && values.defaultModelId ? values.defaultModelId : provider.defaultModelId,+ apiKey: value,+ apiStyle: provider.apiStyle ?? "chat_completions",+ protocol: provider.protocol ?? "openai_compatible",+ headers: provider.headers,+ };+ } finally {+ await source.stop();+ }+}++let live;+if (process.env.PI_DESKTOP_TEST_PROVIDER_DATA_DIR?.trim()) {+ live = await providerFromDataDir(process.env.PI_DESKTOP_TEST_PROVIDER_DATA_DIR.trim());+} else {+ const REQUIRED_ENV = ["PI_DESKTOP_TEST_API_KEY", "PI_DESKTOP_TEST_BASE_URL", "PI_DESKTOP_TEST_MODEL"];+ const missingEnv = REQUIRED_ENV.filter((name) => !process.env[name]?.trim());+ if (missingEnv.length > 0) {+ console.error(`missing required environment variables: ${missingEnv.join(", ")}`);+ process.exit(1);+ }+ live = {+ name: "Live",+ baseUrl: process.env.PI_DESKTOP_TEST_BASE_URL,+ model: process.env.PI_DESKTOP_TEST_MODEL,+ apiKey: process.env.PI_DESKTOP_TEST_API_KEY,+ apiStyle: "chat_completions",+ protocol: "openai_compatible",+ };+}+console.log(`model: ${live.name} / ${live.model} (${live.apiStyle})`);+// The host inherits this process's environment and the live model runs Bash+// with it, so the key must not be in it (`env` would print it).+for (const name of Object.keys(process.env)) {+ if (name.startsWith("PI_DESKTOP_TEST_")) delete process.env[name];+}++const temp = mkdtempSync(join(tmpdir(), "pi-worktree-live-"));+const dataDir = join(temp, "data");+const project = join(temp, "project");+mkdirSync(dataDir);+mkdirSync(project);++const git = (cwd, ...args) => execFileSync("git", args, { cwd, encoding: "utf8" });+git(project, "init", "-q", "-b", "main");+git(project, "config", "user.email", "[email protected]");+git(project, "config", "user.name", "E2E");+writeFileSync(join(project, "f.txt"), "line one\nline two\n");+writeFileSync(join(project, ".gitignore"), ".env\n");+writeFileSync(join(project, ".worktreeinclude"), ".env\n");+git(project, "add", "-A");+git(project, "commit", "-q", "-m", "base");+writeFileSync(join(project, ".env"), "SECRET=local\n");++const results = [];+function record(id, ok, detail = "") {+ results.push({ id, ok });+ console.log(`${ok ? "PASS" : "FAIL"} ${id}${detail ? ` — ${detail}` : ""}`);+}+const read = (path) => (existsSync(path) ? readFileSync(path, "utf8") : null);+const firstLine = (path) => read(path)?.split("\n")[0]?.trim();+const projectClean = () => git(project, "status", "--porcelain") === "";++const host = new Host(resolveHostBinary(), dataDir, { quiet: true });+const runtimes = new Map();+let provider;++// The platform's default command shell, as host-core resolves it: Windows+// PowerShell on Windows (the `bash` id does not exist there), bash elsewhere.+const windows = process.platform === "win32";+const commandShell = windows+ ? { id: "windows-powershell", label: "Windows PowerShell", dialect: "powershell", available: true, isDefault: true }+ : { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true };+const portCommand = windows+ ? 'Set-Content -NoNewline -Path port.txt -Value "$env:PI_PORT|$env:PI_WORKTREE_ROOT"'+ : "printf '%s|%s' \"$PI_PORT\" \"$PI_WORKTREE_ROOT\" > port.txt";++const writer = {+ name: "writer",+ description: "Creates or edits files exactly as instructed.",+ tools: ["Read", "Write", "Edit"],+ prompt: "Do exactly the file change you are asked to do, then reply DONE.",+ source: "user",+};++async function isolatedSession(title) {+ const created = await host.call("session.create", {+ title,+ mode: "agent",+ projectPath: project,+ isolated: true,+ }, 120_000);+ const sessionId = created.session.id;+ const { path } = await host.call("worktree.location", { sessionId });+ return { sessionId, title, root: path, worktree: created.worktree };+}++async function prompt(session, text, { subagents } = {}) {+ let runtime = runtimes.get(session.sessionId);+ const turn = await host.call("session.beginTurn", { sessionId: session.sessionId });+ const userMessageId = randomUUID();+ await host.call("session.appendMessage", {+ sessionId: session.sessionId,+ turnId: turn.turnId,+ message: { id: userMessageId, role: "user", content: text, createdAt: new Date().toISOString(), status: "complete" },+ });+ const events = [];+ if (!runtime) {+ runtime = new DesktopAgentRuntime({+ host,+ sessionId: session.sessionId,+ turnId: turn.turnId,+ mode: "agent",+ projectPath: project,+ workspaceRoot: session.root,+ subagents,+ provider: {+ id: provider.provider.id,+ name: live.name,+ baseUrl: live.baseUrl,+ modelId: live.model,+ apiKey: live.apiKey,+ authKind: "api_key_and_base_url",+ apiStyle: live.apiStyle,+ ...(live.headers ? { headers: live.headers } : {}),+ supportsReasoning: false,+ supportedThinkingLevels: ["off"],+ },+ thinkingLevel: "off",+ commandShell,+ onEvent: (e) => session.events?.push(e.event),+ });+ runtimes.set(session.sessionId, runtime);+ }+ session.events = events;+ let status = "completed";+ try {+ await runtime.prompt(text, userMessageId, turn.turnId);+ if (events.some((event) => event.type === "error")) status = "error";+ } catch (error) {+ status = "error";+ console.error(`prompt failed in ${session.sessionId}:`, error instanceof Error ? error.message : error);+ } finally {+ for (const event of events) {+ if (event.type === "message_end" && event.message.role === "assistant") {+ await host.call("session.appendMessage", { sessionId: session.sessionId, turnId: turn.turnId, message: event.message }).catch(() => {});+ }+ }+ await host.call("session.endTurn", { turnId: turn.turnId, status, createNotification: false });+ const tools = events.filter((event) => event.type === "tool_start").map((event) => event.toolName ?? event.name);+ const errors = events.filter((event) => event.type === "error").map((event) => event.error?.code ?? event.error?.message ?? "error");+ const reply = events.findLast((event) => event.type === "message_end" && event.message.role === "assistant")?.message.content;+ console.log(` [${session.title}] ${status}; events=${events.length}; tools=${tools.join(",") || "-"}; errors=${errors.join(",") || "-"}; reply=${String(reply ?? "").slice(0, 120).replace(/\s+/g, " ")}`);+ }+ return events;+}++async function merge(session) {+ const { preview } = await host.call("worktree.preview", { sessionId: session.sessionId }, 120_000);+ return host.call("worktree.merge", { sessionId: session.sessionId, previewToken: preview.previewToken }, 120_000);+}++try {+ await host.start(PROTOCOL_VERSION);+ provider = await host.call("providers.create", {+ name: live.name,+ baseUrl: live.baseUrl,+ defaultModelId: live.model,+ secretValue: live.apiKey,+ type: "openai_compatible",+ protocol: live.protocol,+ apiStyle: live.apiStyle,+ authKind: "api_key_and_base_url",+ });++ // Throwaway profile: tools run without approval cards (session.create does+ // not accept a permission mode of its own).+ await host.call("settings.set", { defaultPermissionMode: "auto" });++ const probe = await host.call("worktree.probe", { projectPath: project });+ record("probe-git-project", probe.available === true && probe.uncommittedChanges === false);++ // 1. Two isolated sessions edit the same file at the same time.+ const a = await isolatedSession("Session A");+ const b = await isolatedSession("Session B");+ record("worktrees-outside-project", !a.root.startsWith(project) && !b.root.startsWith(project) && a.root !== b.root);+ record("include-file-copied", read(join(a.root, ".env")) === "SECRET=local\n" && read(join(b.root, ".env")) === "SECRET=local\n");+ const task = (letter) =>+ `In the current workspace: 1) Use Edit or Write so that the first line of f.txt is exactly "${letter}" ` ++ `(keep the second line). 2) Create ${letter.toLowerCase()}.txt containing exactly "from-${letter.toLowerCase()}". ` ++ `3) Run this Bash command: ${portCommand} . Then reply DONE.`;+ await Promise.all([prompt(a, task("A")), prompt(b, task("B"))]);+ record("parallel-edits-isolated",+ firstLine(join(a.root, "f.txt")) === "A" && firstLine(join(b.root, "f.txt")) === "B" &&+ read(join(a.root, "a.txt"))?.trim() === "from-a" && read(join(b.root, "b.txt"))?.trim() === "from-b" &&+ !existsSync(join(a.root, "b.txt")) && !existsSync(join(b.root, "a.txt")),+ `A=${firstLine(join(a.root, "f.txt"))} B=${firstLine(join(b.root, "f.txt"))}`);+ record("project-untouched", projectClean() && firstLine(join(project, "f.txt")) === "line one");+ const [portA, rootA] = (read(join(a.root, "port.txt")) ?? "").split("|");+ const [portB] = (read(join(b.root, "port.txt")) ?? "").split("|");+ record("distinct-ports-and-root", Boolean(portA) && Boolean(portB) && portA !== portB && rootA === a.root,+ `A=${portA} B=${portB}`);++ // 2. Merge A, then B conflicts on the same line.+ const mergedA = await merge(a);+ record("merge-a", mergedA.outcome?.result === "merged" && firstLine(join(project, "f.txt")) === "A" &&+ read(join(project, "a.txt"))?.trim() === "from-a");+ const { counts } = await host.call("worktree.behindAll", {});+ record("behind-marker-after-merge", counts[b.sessionId] >= 1 && counts[a.sessionId] === 0, JSON.stringify(counts));+ let conflict;+ try {+ await merge(b);+ } catch (error) {+ conflict = error;+ }+ record("merge-b-conflicts-in-worktree",+ conflict?.errorCode === "WORKTREE_CONFLICT" && projectClean() && firstLine(join(project, "f.txt")) === "A" &&+ !existsSync(join(project, ".git", "MERGE_HEAD")),+ conflict?.errorCode ?? "no conflict");++ // 3. The agent resolves the conflict in its worktree; the merge lands.+ // Both sessions wrote port.txt too, so it conflicts alongside f.txt.+ const conflictFiles = conflict?.rpc?.data?.files ?? [];+ record("conflict-lists-files", conflictFiles.includes("f.txt") && conflictFiles.includes("port.txt"), conflictFiles.join(","));+ await prompt(b,+ "The workspace has unresolved git merge conflicts in: " + conflictFiles.join(", ") + ". Resolve all of them: " ++ 'f.txt must be exactly two lines, "AB" and "line two"; for every other conflicted file keep this session\'s ' ++ "own version. Remove every conflict marker. Do not run git commands. Then reply DONE.");+ let mergedB;+ try {+ mergedB = await merge(b);+ } catch (error) {+ console.error(error.message);+ }+ record("merge-b-after-resolution", mergedB?.outcome?.result === "merged" && firstLine(join(project, "f.txt")) === "AB" &&+ read(join(project, "b.txt"))?.trim() === "from-b" && projectClean());++ // 3b. Session A still has its pre-resolution code; "Sync from project"+ // brings B's resolution in without touching the project.+ const { commits: behindA } = await host.call("worktree.behind", { sessionId: a.sessionId });+ const syncA = await host.call("worktree.sync", { sessionId: a.sessionId }, 120_000);+ record("sync-brings-resolution-into-a",+ behindA > 0 && syncA.outcome?.result === "synced" && firstLine(join(a.root, "f.txt")) === "AB" && projectClean(),+ `behind=${behindA} A=${firstLine(join(a.root, "f.txt"))}`);++ // 4. Two writing subagents in parallel inside one isolated session.+ const c = await isolatedSession("Session C");+ await prompt(c,+ "Use the Task tool to start two `writer` subagents in parallel (two Task calls in one message). " ++ 'The first creates c1.txt containing exactly "one"; the second creates c2.txt containing exactly "two". ' ++ "Wait for both reports with TaskWait, then reply DONE. Do not create the files yourself.",+ { subagents: [writer] });+ // Project plus the three session worktrees; no subagent worktree is left.+ const worktreeCount = git(project, "worktree", "list").split("\n").filter(Boolean).length;+ const delegateRows = { length: worktreeCount - 4 };+ record("subagents-merged-back",+ read(join(c.root, "c1.txt"))?.trim() === "one" && read(join(c.root, "c2.txt"))?.trim() === "two" && delegateRows.length === 0,+ `c1=${read(join(c.root, "c1.txt"))?.trim()} c2=${read(join(c.root, "c2.txt"))?.trim()} delegates=${delegateRows.length}`);++ // 5. Delete with unmerged work discards worktree and branch only.+ const { pending } = await host.call("worktree.pendingWork", { sessionId: c.sessionId });+ record("pending-work-reported", pending.unmergedCommits > 0 || pending.uncommittedChanges === true);+ const branchC = c.worktree?.worktree?.branch;+ await runtimes.get(c.sessionId)?.dispose();+ runtimes.delete(c.sessionId);+ await host.call("session.delete", { id: c.sessionId }, 120_000);+ record("delete-discards-worktree", !existsSync(c.root) && !git(project, "branch", "--list").includes(branchC ?? "pi-desktop/none") &&+ !existsSync(join(project, "c1.txt")));++ // 6. Restart keeps an isolated session in its worktree.+ for (const runtime of runtimes.values()) await runtime.dispose();+ runtimes.clear();+ await host.restart(PROTOCOL_VERSION);+ const { path: afterRestart } = await host.call("worktree.location", { sessionId: a.sessionId });+ record("restart-keeps-worktree", afterRestart === a.root && existsSync(afterRestart));+} catch (error) {+ console.error(error instanceof Error ? error.stack : error);+ record("harness", false, error instanceof Error ? error.message : String(error));+} finally {+ for (const runtime of runtimes.values()) await runtime.dispose().catch(() => {});+ await host.stop().catch(() => {});+ if (process.env.PI_DESKTOP_KEEP_TEMP) {+ console.log(`kept ${temp} (its data directory holds the provider key; delete it when done)`);+ }+ else rmSync(temp, { recursive: true, force: true });+}++const failed = results.filter((result) => !result.ok);+console.log(`\nSummary: ${results.length - failed.length} / ${results.length} passed`);+process.exit(failed.length === 0 ? 0 : 1);