Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(worktree): a location from the git-shared settings file cannot leave the repo's folder
review9fa879d0d9a2
diff --git a/CLAUDE.md b/CLAUDE.mdindex f4bd527c4..13df8fae6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5282,6 +5282,23 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord meaand `addAgentNode` parents the node BEFORE `setNodes`, never inside the updater, because theupdater runs at render time and a zustand-flushed SyncLane render may already have mirrored`nodesRef` back to a list without the fresh frame (the `nodesEpoch` lesson).+ - **Where a worktree may land** (`@shared/worktree-location`) — `worktree.basePath` can come from+ `.nodeterm/settings.json`, the git-SHARED project settings file, i.e. written by anyone who can+ commit to the repository, and `git worktree add` writes the whole tree there. Pointed at+ `../../.claude/skills`, the issue card's one click checked the repo out into+ `~/.claude/skills/issue-N-…/` and a root `SKILL.md` became a skill in every Claude session. Two+ layers, both for ALL create paths (dialog, `open-worktree`, issue card):+ `sharedWorktreeLocationRefusal` (renderer) refuses a location the SHARED file produced unless it+ stays inside the folder holding the repository — a sibling that is not hidden, or anywhere in+ the repository but its `.git` — and names the fix (a local override in Project Settings). It+ judges only the path that setting derives for the branch: a path the person typed in the dialog+ or passed as `--path` is theirs. `sharedBasePathOf` is the one reading of provenance (`source:+ 'shared'`). `open-worktree` refuses before its dry run. The core backstop+ (`core/worktree-target.ts`, in `GitService.worktreeAdd`, so relay and browser clients pass it+ too) works on REAL paths, because a symlink committed into the repository defeats any lexical+ rule: never inside the repository's `.git`, and never REDIRECTED into a hidden folder directly+ under the home directory — a location that names such a folder outright (a person's own+ `/home/me/.worktrees`) is allowed, so the backstop is not a blanket refusal.- **A worktree per GitHub issue** (`@shared/issue-worktree`) — "Start with agent in a newworktree ▸" on an issue card and its summary modal: branch `issue-<N>-<slug>` at the templatedpath, off the SAME base the New worktree dialog defaults to (`effectiveWorktreeBaseRef`: the@@ -5308,10 +5325,17 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord meamatch is case-insensitive, git's lookup is not; the new folder is the app's, so `createdByApp`is true exactly as the dialog's "Existing branch" mode sets it) — beside the next free `-2` …`-20`; a name or folder that is merely taken moves to the next suffix and the notice says why.- Never the main checkout, never a prunable registration. Reuse is re-checked at the dialog's click- (a frame on that folder now, else a worktree git still lists), and one `runExclusive` key per- issue covers the planning AND a dialog-confirmed create, so a second click cannot race the first- for the same `-2`. Disabled WITH its reason on a relay tab, an SSH project, a cwd-less+ Never the main checkout, never a prunable registration, and never a frame bound to ANOTHER+ repository (`issueWorktreeFrames` filters by `worktree.repoPath`, as the worktree store does — a+ foreign or hostile frame on an `issue-<N>-…` branch would otherwise be the preselected "Reuse").+ A branch that exists only on a REMOTE (`status.remoteBranches`, as fresh as the last fetch) is+ TAKEN, never checked out: a same-named local branch would diverge from it, its push would be+ rejected, and #1008's branch link could point at someone else's pull request. Reuse is+ re-checked at the dialog's click (a frame of this repo on that folder now, else a worktree git+ still lists), and one `runExclusive` key per issue covers the planning AND a dialog-confirmed+ create, so a second click cannot race the first for the same `-2`. The reuse-or-new dialog is a+ tracked confirm (`confirmFlags.issueWorktree`, read by `confirmBusy()`): it never opens over+ another confirm, and an agent's destructive verb is refused while it is up. Disabled WITH its reason on a relay tab, an SSH project, a cwd-lessproject and a folder with no repository (`issueWorktreeRefusal`). **There is no `--worktree`flag**: an agent composes `open-worktree --branch issue-<N>-<slug>` then `open-agent --group<groupId> --issue #N`, and both agent bodies render that convention from `issueWorktreeBranch`.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 6a56c038a..acba91dea 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -314,6 +314,13 @@ anything else. Board-level fields survive every transform — `pullLinks` is oneagainst the renderer's dispositions — deliberately cross-layer, because that is the only way"every verb" is checked rather than remembered.+- **A location from `.nodeterm/settings.json` is hostile input.** That file is committed to the+ repository, so anyone who can commit wrote it. A worktree location it produces must pass+ `sharedWorktreeLocationRefusal` (`src/shared/worktree-location.ts`) on every create path, and+ every `git worktree add` passes the real-path backstop in `GitService.worktreeAdd`. If you add+ another setting that names a place on disk the app will WRITE to, give it the same two layers:+ a lexical rule keyed on `source: 'shared'`, and a check on real paths where the write happens.+- **A node you just created is not in `nodesRef` yet, and a `setNodes` updater is not "now".**`nodesRef` mirrors React state at render time, so a frame made this tick is invisible to the nextline that looks it up — and an updater runs at RENDER time, after any zustand write may alreadydiff --git a/src/core/git-service.ts b/src/core/git-service.tsindex ea4c83e5b..58ac252dd 100644--- a/src/core/git-service.ts+++ b/src/core/git-service.ts@@ -14,6 +14,7 @@ import { platform } from './platform'import { directExecutableInvocation } from './exec-path'import { ghPath } from './gh-path'import { gitEnv } from './git-env'+import { worktreeTargetRefusal } from './worktree-target'import {isValidCloneUrl,expandCloneUrl,@@ -315,6 +316,11 @@ export class GitService {// `wtPath` is computed from the LOCAL data dir, so adding it through a remote git would create a// worktree at a nonsense path on the host. Refuse (see `isRemoteRepo`).if (isRemoteRepo(repoPath)) return Promise.resolve(REMOTE_WORKTREE_REFUSAL())+ // Every caller's backstop (dialog, `open-worktree`, the issue card, a relay or browser client):+ // never into the repository's `.git`, never REDIRECTED by a symlink into a hidden folder of the+ // home directory (see `worktree-target.ts`). Judged on real paths, which no renderer can see.+ const refusal = worktreeTargetRefusal(wtPath, repoPath)+ if (refusal) return Promise.resolve({ ok: false, message: refusal })return worktreeOps.worktreeAdd(git, repoPath, wtPath, branch, baseRef, isNew)}worktreeMerge(diff --git a/src/core/worktree-target.test.ts b/src/core/worktree-target.test.tsnew file mode 100644index 000000000..9b21f49da--- /dev/null+++ b/src/core/worktree-target.test.ts@@ -0,0 +1,93 @@+// The core backstop, against a real filesystem and real git: a symlink committed into a repository+// (or sitting in its folder) must not carry a `git worktree add` into a hidden folder of the home+// directory, where agent CLIs load skills and configuration. The rule is lexical-proof only because+// it is judged on REAL paths — which is why it lives in core, beside git.+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { realPathOf, worktreeTargetRefusal } from './worktree-target'+import { GitService } from './git-service'++let root: string+let home: string+let repo: string+const prevHome = process.env.HOME++beforeAll(() => {+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'nt-wt-target-')))+ home = path.join(root, 'home')+ repo = path.join(home, 'code', 'repo')+ fs.mkdirSync(path.join(home, '.claude', 'skills'), { recursive: true })+ fs.mkdirSync(repo, { recursive: true })+ const git = (...args: string[]): void => {+ execFileSync('git', args, { cwd: repo, stdio: 'ignore' })+ }+ git('init', '-b', 'main')+ git('config', 'user.email', '[email protected]')+ git('config', 'user.name', 't')+ git('commit', '--allow-empty', '-m', 'init')+})++afterEach(() => {+ if (prevHome === undefined) delete process.env.HOME+ else process.env.HOME = prevHome+})++afterAll(() => fs.rmSync(root, { recursive: true, force: true }))++describe('realPathOf', () => {+ it.skipIf(process.platform === 'win32')('resolves the deepest existing ancestor and re-appends the rest', () => {+ const link = path.join(repo, 'via-link')+ fs.symlinkSync(path.join(home, '.claude', 'skills'), link)+ try {+ expect(realPathOf(path.join(link, 'issue-1', 'deeper'))).toBe(+ path.join(home, '.claude', 'skills', 'issue-1', 'deeper')+ )+ } finally {+ fs.unlinkSync(link)+ }+ })+})++// Symlink creation needs Developer Mode or elevation on Windows; the rule itself is platform-neutral+// and covered by the pure tests in @shared/worktree-location.+describe.skipIf(process.platform === 'win32')('worktreeTargetRefusal + GitService.worktreeAdd', () => {+ it('refuses a target a symlink redirects into ~/.claude, and git never runs', async () => {+ const link = path.join(repo, 'tools')+ fs.symlinkSync(path.join(home, '.claude', 'skills'), link)+ try {+ const target = path.join(link, 'issue-1-x')+ expect(worktreeTargetRefusal(target, repo, home)).toContain('~/.claude')+ process.env.HOME = home+ const res = await new GitService().worktreeAdd(repo, target, 'issue-1-x', 'main', true)+ expect(res.ok).toBe(false)+ expect(res.message).toContain('~/.claude')+ expect(fs.existsSync(path.join(home, '.claude', 'skills', 'issue-1-x'))).toBe(false)+ const branches = execFileSync('git', ['branch', '--list', 'issue-1-x'], { cwd: repo, encoding: 'utf8' })+ expect(branches.trim()).toBe('')+ } finally {+ fs.unlinkSync(link)+ }+ })++ it('refuses a target inside the repository\'s .git folder', async () => {+ process.env.HOME = home+ const res = await new GitService().worktreeAdd(repo, path.join(repo, '.git', 'wt'), 'wt-git', 'main', true)+ expect(res.ok).toBe(false)+ expect(res.message).toContain('.git folder')+ })++ it('still creates an ordinary worktree beside the repository (the backstop is not a blanket refusal)', async () => {+ process.env.HOME = home+ const target = path.join(home, 'code', 'repo.worktrees', 'issue-2')+ const res = await new GitService().worktreeAdd(repo, target, 'issue-2', 'main', true)+ expect(res).toMatchObject({ ok: true })+ expect(fs.existsSync(path.join(target, '.git'))).toBe(true)+ })++ it('allows a hidden home folder the path names outright', () => {+ expect(worktreeTargetRefusal(path.join(home, '.worktrees', 'x'), repo, home)).toBeNull()+ })+})diff --git a/src/core/worktree-target.ts b/src/core/worktree-target.tsnew file mode 100644index 000000000..e94e6f6f6--- /dev/null+++ b/src/core/worktree-target.ts@@ -0,0 +1,45 @@+import fs from 'fs'+import os from 'os'+import path from 'path'+import { worktreeRedirectRefusal } from '../shared/worktree-location'++/**+ * `p` with every symlink on the way resolved. The worktree folder does not exist yet, so the+ * deepest EXISTING ancestor is resolved and the rest re-appended — which is exactly where+ * `git worktree add` (a `mkdir -p` that follows links) will create it.+ */+export function realPathOf(p: string): string {+ let cur = path.resolve(p)+ const rest: string[] = []+ for (;;) {+ try {+ return path.join(fs.realpathSync.native(cur), ...rest)+ } catch {+ const parent = path.dirname(cur)+ if (parent === cur) return path.resolve(p)+ rest.unshift(path.basename(cur))+ cur = parent+ }+ }+}++/**+ * The backstop every `git worktree add` passes (`GitService.worktreeAdd`): refuse a target inside+ * the repository's `.git`, or one a symlink REDIRECTS into a hidden folder of the home directory.+ * The rule itself is `worktreeRedirectRefusal` (@shared/worktree-location); this only supplies the+ * real paths. A relative target is resolved the way git resolves it: against the repository.+ */+export function worktreeTargetRefusal(+ wtPath: string,+ repoPath: string,+ home: string = os.homedir()+): string | null {+ const requested = path.resolve(repoPath, wtPath)+ return worktreeRedirectRefusal({+ requested,+ real: realPathOf(requested),+ realRepo: realPathOf(repoPath),+ home,+ realHome: realPathOf(home)+ })+}diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex a62328702..16c03b47a 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -480,12 +480,15 @@ import {type IssueRef} from '@shared/github-issue-ref'import { planIssueWorktree } from '@shared/issue-worktree'+import { sharedBasePathOf, sharedWorktreeLocationRefusal } from '@shared/worktree-location'import {frameAgentPlacement,issueWorktreeChoiceCopy,+ issueWorktreeFrames,issueWorktreeRefusal,issueWorktreeRenamedNotice,runExclusive,+ type IssueWorktreeAsk,type IssueWorktreeChoice,type IssueWorktreeMenuAnswer} from '../lib/issueWorktree'@@ -1839,7 +1842,8 @@ export function Canvas() {merge: false,peer: false,closeProject: false,- deleteProject: false+ deleteProject: false,+ issueWorktree: false})// Every confirm setter flips its flag AT CALL TIME. Assigning the mirror during RENDER (what this// used to do) is a tick too late: two agent verbs arriving in separate IPC events before React@@ -1938,6 +1942,7 @@ export function Canvas() {f.peer ||f.closeProject ||f.deleteProject ||+ f.issueWorktree ||removePendingRef.current)}, [])@@ -6266,6 +6271,19 @@ export function Canvas() {async (v: WorktreeCreateValue) => {const target = worktreeDialogif (!target) return+ // The dialog's suggested path can come from the git-shared settings file: a location it+ // produced must stay beside the repository (@shared/worktree-location). A path the person+ // typed is theirs — the rule judges only the one the shared setting derives for this branch.+ const locationRefusal = sharedWorktreeLocationRefusal({+ path: v.path,+ repoRoot: v.repoPath,+ branch: v.branch,+ sharedBasePath: sharedBasePathOf(projectLaunchInfoNow(target.projectId)?.resolved.worktree)+ })+ if (locationRefusal) {+ setWorktreeError(locationRefusal)+ return+ }setWorktreeBusy(true)setWorktreeError(null)// A REJECTED ipc is not the same as a failed op, and both have to land here. The Server@@ -10234,12 +10252,13 @@ export function Canvas() {// ---- GitHub issue → agent session in its OWN worktree ("Start with agent in a new worktree ▸") ----/** The reuse-or-new question, when the issue already has a worktree (or its branch exists). */- const [issueWorktreeAsk, setIssueWorktreeAsk] = useState<{- message: string- options: { value: IssueWorktreeChoice; label: string }[]- value: IssueWorktreeChoice- run: (choice: IssueWorktreeChoice) => void- } | null>(null)+ const [issueWorktreeAsk, setIssueWorktreeAskState] = useState<IssueWorktreeAsk | null>(null)+ // Tracked like every other confirm (`confirmFlags` / `confirmBusy()`): while it is open an agent's+ // destructive verb is refused rather than stacked over it, and it does not open over another one.+ const setIssueWorktreeAsk = useCallback((v: IssueWorktreeAsk | null) => {+ confirmFlags.current.issueWorktree = !!v+ setIssueWorktreeAskState(v)+ }, [])/** Issues with a start in flight (`runExclusive`) — planning AND a dialog-confirmed create. */const issueWorktreeInFlightRef = useRef(new Set<string>())@@ -10414,15 +10433,20 @@ export function Canvas() {const ran = await runExclusive(issueWorktreeInFlightRef.current, key, async () => {// Local branches, so a taken name is seen before git refuses it. An unreadable list comes// back empty: git then has the last word, and its refusal is what the notice shows.- const branches = await api.git.status(repoRoot).then(- (st) => st.branches ?? null,- () => null- )- const bound = boundGroups(nodesRef.current)- .filter((b) => !staleGroupIds.includes(b.groupId))- .map((b) => ({ groupId: b.groupId, branch: b.worktree.branch, path: b.worktree.path }))+ const status = await api.git.status(repoRoot).catch(() => null)const plan = await planIssueWorktree(- { number: start.ref.number, title: issue.title, repoRoot, template, entries, branches, bound },+ {+ number: start.ref.number,+ title: issue.title,+ repoRoot,+ template,+ entries,+ branches: status?.branches ?? null,+ // A name that exists on a remote is taken (→ `-k`), never checked out.+ remoteBranches: status?.remoteBranches ?? [],+ bound: issueWorktreeFrames(nodesRef.current, repoRoot, staleGroupIds),+ sharedBasePath: sharedBasePathOf(pw)+ },(path) => api.fs.exists(path))// The canvas may have moved on while git and the filesystem answered: everything below@@ -10437,6 +10461,13 @@ export function Canvas() {return}const { existing, alternative } = plan+ if (confirmBusy()) {+ setNotice({+ kind: 'info',+ text: `Another confirmation is open — answer it, then start #${issue.number} again.`+ })+ return+ }const copy = issueWorktreeChoiceCopy(start.ref.number, existing, alternative, baseRef)setIssueWorktreeAsk({...copy,@@ -10453,11 +10484,11 @@ export function Canvas() {}// A frame bound to this worktree now — the one the plan found, or one that adopted the// orphan while the dialog was open — takes the agent. Never a second frame on one folder.- const live = boundGroups(nodesRef.current).find(- (b) =>- normWorktreePath(b.worktree.path) === normWorktreePath(existing.path) &&- !useWorktrees.getState().staleGroupIds.includes(b.groupId)- )+ const live = issueWorktreeFrames(+ nodesRef.current,+ repoRoot,+ useWorktrees.getState().staleGroupIds+ ).find((b) => normWorktreePath(b.path) === normWorktreePath(existing.path))if (live) {openIssueAgentInFrame(live.groupId, issue, start, agentId, accountId)return@@ -13086,6 +13117,19 @@ export function Canvas() {reply({ ok: false, error: 'open-worktree: could not derive a worktree path — pass --path' })return}+ // A location the git-shared settings file produced must stay beside the repository+ // (@shared/worktree-location). An explicit `--path` is the caller's own and not judged.+ // Before the dry run, which must refuse what the real call refuses.+ const locationRefusal = sharedWorktreeLocationRefusal({+ path: wtPath,+ repoRoot,+ branch,+ sharedBasePath: args.path?.trim() ? undefined : sharedBasePathOf(pw)+ })+ if (locationRefusal) {+ reply({ ok: false, error: `open-worktree: ${locationRefusal}` })+ return+ }if (dryRun) {reply({ok: true,@@ -16890,7 +16934,7 @@ export function Canvas() {options: issueWorktreeAsk.options,value: issueWorktreeAsk.value,onChange: (value) =>- setIssueWorktreeAsk((ask) => (ask ? { ...ask, value: value as IssueWorktreeChoice } : ask))+ setIssueWorktreeAskState((ask) => (ask ? { ...ask, value: value as IssueWorktreeChoice } : ask))}}confirmLabel="Start agent"danger={false}diff --git a/src/renderer/canvas/issue-binding.source.test.ts b/src/renderer/canvas/issue-binding.source.test.tsindex c3587a7d2..afb60d891 100644--- a/src/renderer/canvas/issue-binding.source.test.ts+++ b/src/renderer/canvas/issue-binding.source.test.ts@@ -143,7 +143,7 @@ describe('Start with agent (issue card)', () => {// Exactly one read of the title: the slug input of `planIssueWorktree` (@shared/issue-worktree// owns every rule about it — allowlist, cap, check-ref-format; proven there against git).expect(body.match(/issue\.title/g) ?? []).toHaveLength(1)- expect(body).toMatch(/planIssueWorktree\(\s*\{ number: start\.ref\.number, title: issue\.title,/)+ expect(body).toMatch(/planIssueWorktree\(\s*\{\s*number: start\.ref\.number,\s*title: issue\.title,/)expect(body).not.toMatch(/issue\.body/)// The frame is named after the NUMBER, not the title.expect(body).toContain('title: `Issue #${start.ref.number}`')diff --git a/src/renderer/canvas/issue-worktree.source.test.ts b/src/renderer/canvas/issue-worktree.source.test.tsindex fc7c29cdd..a81408e96 100644--- a/src/renderer/canvas/issue-worktree.source.test.ts+++ b/src/renderer/canvas/issue-worktree.source.test.ts@@ -143,8 +143,10 @@ describe('Start with agent in a new worktree', () => {it('reuse is re-validated at the click: a live, non-stale frame on that folder, else a still-listed worktree', () => {const inRun = body.slice(body.indexOf('run: (choice) => {'))- expect(inRun).toContain('normWorktreePath(b.worktree.path) === normWorktreePath(existing.path)')- expect(inRun).toContain('!useWorktrees.getState().staleGroupIds.includes(b.groupId)')+ // A frame of THIS repository on that folder, not stale — `issueWorktreeFrames` owns both filters.+ expect(inRun).toMatch(+ /issueWorktreeFrames\(\s*nodesRef\.current,\s*repoRoot,\s*useWorktrees\.getState\(\)\.staleGroupIds\s*\)\.find\(\(b\) => normWorktreePath\(b\.path\) === normWorktreePath\(existing\.path\)\)/+ )expect(inRun).toContain("existing.kind === 'bound' || !listed || listed.prunable || !listed.branch")})@@ -190,3 +192,65 @@ describe('the setup hold is one rule', () => {)})})++describe('a worktree location from the git-shared settings file (all three create paths)', () => {+ it('open-worktree refuses it BEFORE its dry run, unless the caller passed an explicit --path', () => {+ const body = between("case 'open-worktree': {", "case 'close-worktree': {")+ const check = body.indexOf('const locationRefusal = sharedWorktreeLocationRefusal({')+ expect(check).toBeGreaterThan(-1)+ expect(check).toBeLessThan(body.indexOf('if (dryRun) {'))+ expect(check).toBeLessThan(body.indexOf('createBoundWorktree('))+ expect(body).toContain('sharedBasePath: args.path?.trim() ? undefined : sharedBasePathOf(pw)')+ // …and the refusal is ACTED on there: replied, returned, before the dry run and before git.+ const refuse = body.indexOf('if (locationRefusal) {\n reply({ ok: false, error: `open-worktree: ${locationRefusal}` })\n return')+ expect(refuse).toBeGreaterThan(check)+ expect(refuse).toBeLessThan(body.indexOf('if (dryRun) {'))+ })++ it('the New worktree dialog refuses it at submit, before git', () => {+ const body = between('const createWorktreeAndGroup = useCallback(', 'const bindExistingWorktree = useCallback(')+ const check = body.indexOf('sharedWorktreeLocationRefusal({')+ expect(check).toBeGreaterThan(-1)+ expect(check).toBeLessThan(body.indexOf('createBoundWorktree('))+ expect(body).toContain('sharedBasePath: sharedBasePathOf(projectLaunchInfoNow(target.projectId)?.resolved.worktree)')+ const refuse = body.indexOf('if (locationRefusal) {\n setWorktreeError(locationRefusal)\n return')+ expect(refuse).toBeGreaterThan(check)+ expect(refuse).toBeLessThan(body.indexOf('createBoundWorktree('))+ })++ it('the issue action hands the planner the shared basePath, the remote branches and only THIS repo\'s frames', () => {+ const body = between('const startIssueAgentInWorktree = useCallback(', 'const issueWorktreeMenu = useCallback(')+ expect(body).toContain('sharedBasePath: sharedBasePathOf(pw)')+ expect(body).toContain('remoteBranches: status?.remoteBranches ?? []')+ expect(body).toContain('bound: issueWorktreeFrames(nodesRef.current, repoRoot, staleGroupIds)')+ // The reuse check at the dialog's click filters by repository too.+ const inRun = body.slice(body.indexOf('run: (choice) => {'))+ expect(inRun).toContain('issueWorktreeFrames(')+ expect(inRun).not.toContain('boundGroups(')+ })++ it('the core backstop runs before every git worktree add', () => {+ const git = readFileSync(new URL('../../core/git-service.ts', import.meta.url), 'utf8')+ const add = git.slice(git.indexOf(' worktreeAdd(\n'), git.indexOf(' worktreeMerge('))+ const check = add.indexOf('const refusal = worktreeTargetRefusal(wtPath, repoPath)')+ expect(check).toBeGreaterThan(-1)+ expect(check).toBeLessThan(add.indexOf('worktreeOps.worktreeAdd('))+ })+})++describe('the reuse-or-new dialog is a tracked confirm', () => {+ it('flips its confirmFlags entry at call time, and confirmBusy() reads it', () => {+ expect(code(src)).toMatch(/confirmFlags = useRef\(\{[^}]*issueWorktree: false/)+ const busy = between('const confirmBusy = useCallback(', 'const nodeTypes = useMemo(')+ expect(busy).toContain('f.issueWorktree ||')+ const setter = between('const setIssueWorktreeAsk = useCallback(', 'const issueWorktreeInFlightRef')+ expect(setter).toContain('confirmFlags.current.issueWorktree = !!v')+ })++ it('does not open over another confirm', () => {+ const body = between('const startIssueAgentInWorktree = useCallback(', 'const issueWorktreeMenu = useCallback(')+ const busy = body.indexOf('if (confirmBusy()) {')+ expect(busy).toBeGreaterThan(-1)+ expect(busy).toBeLessThan(body.indexOf('setIssueWorktreeAsk({'))+ })+})diff --git a/src/renderer/lib/issueWorktree.test.ts b/src/renderer/lib/issueWorktree.test.tsindex bd08a9196..f537f2a64 100644--- a/src/renderer/lib/issueWorktree.test.ts+++ b/src/renderer/lib/issueWorktree.test.ts@@ -3,6 +3,7 @@ import { createAgentNode, terminalNodeSize } from '../state/workspace'import { GROUP_PAD_TOP, GROUP_PAD_X } from './coldOpen'import {frameAgentPlacement,+ issueWorktreeFrames,runExclusive,ISSUE_WORKTREE_LABEL,ISSUE_WORKTREE_NO_REPO_HINT,@@ -106,7 +107,7 @@ describe('issueWorktreeChoiceCopy', () => {describe('issueWorktreeRenamedNotice', () => {it('says why the new worktree has a suffix', () => {expect(issueWorktreeRenamedNotice('issue-12-fix', 'issue-12-fix-2')).toBe(- 'issue-12-fix was already taken (a branch or folder of that name exists), so the new worktree is issue-12-fix-2.'+ 'issue-12-fix was already taken (a local or remote branch, or a folder, of that name exists), so the new worktree is issue-12-fix-2.')})})@@ -160,3 +161,27 @@ describe('runExclusive', () => {expect(inFlight.has('k')).toBe(false)})})++describe('issueWorktreeFrames', () => {+ const frame = (id: string, repoPath: string, branch: string) => ({+ id,+ type: 'group',+ data: { worktree: { repoPath, branch, baseRef: 'main', path: `/wt/${branch}`, createdByApp: true } }+ })++ it('offers only frames bound to a worktree of THIS repository, and never a stale one', () => {+ const nodes = [+ frame('mine', '/work/repo', 'issue-12-fix'),+ frame('mine-trailing-slash', '/work/repo/', 'issue-12-b'),+ // Another repository's frame (a pasted or hostile project.json) — never "Reuse".+ frame('foreign', '/elsewhere/other', 'issue-12-fix'),+ frame('stale', '/work/repo', 'issue-12-gone'),+ { id: 'plain', type: 'group', data: {} },+ { id: 'term', type: 'terminal', data: {} }+ ]+ expect(issueWorktreeFrames(nodes, '/work/repo', ['stale']).map((f) => f.groupId)).toEqual([+ 'mine',+ 'mine-trailing-slash'+ ])+ })+})diff --git a/src/renderer/lib/issueWorktree.ts b/src/renderer/lib/issueWorktree.tsindex 9c5202338..1fdc121ea 100644--- a/src/renderer/lib/issueWorktree.ts+++ b/src/renderer/lib/issueWorktree.ts@@ -1,5 +1,11 @@import type { ReactNode } from 'react'-import type { IssueWorktreeExisting, IssueWorktreeTarget } from '@shared/issue-worktree'+import type {+ IssueWorktreeBoundGroup,+ IssueWorktreeExisting,+ IssueWorktreeTarget+} from '@shared/issue-worktree'+import { boundGroups, type ScmScopeNode } from '@shared/scm-scope'+import { normWorktreePath } from '@shared/worktree-reconcile'import type { MenuItem } from '../components/ContextMenu'import { WORKTREE_NO_CWD_HINT, WORKTREE_SSH_HINT } from './addMenuSpec'import { groupSizeFor, groupSlot } from './coldOpen'@@ -88,7 +94,7 @@ export function issueWorktreeChoiceCopy(/** The notice after a start that created a worktree under a different name than the usual one. */export function issueWorktreeRenamedNotice(wanted: string, created: string): string {- return `${wanted} was already taken (a branch or folder of that name exists), so the new worktree is ${created}.`+ return `${wanted} was already taken (a local or remote branch, or a folder, of that name exists), so the new worktree is ${created}.`}/** What the canvas answers for one issue card: the agent rows, or why there are none. */@@ -147,3 +153,28 @@ export async function runExclusive(}return true}++/** The reuse-or-new dialog's state. */+export interface IssueWorktreeAsk {+ message: string+ options: { value: IssueWorktreeChoice; label: string }[]+ value: IssueWorktreeChoice+ run: (choice: IssueWorktreeChoice) => void+}++/**+ * The worktree frames on this canvas that may be REUSED for an issue: bound to a worktree of THIS+ * repository and not stale. A frame bound to another repository's worktree (the worktree store+ * skips those too) is never offered — a hostile or foreign frame whose branch happens to read+ * `issue-<N>-…` would otherwise be the preselected "Reuse".+ */+export function issueWorktreeFrames(+ nodes: readonly ScmScopeNode[],+ repoRoot: string,+ staleGroupIds: readonly string[]+): IssueWorktreeBoundGroup[] {+ const repo = normWorktreePath(repoRoot)+ return boundGroups(nodes as ScmScopeNode[])+ .filter((b) => normWorktreePath(b.worktree.repoPath ?? '') === repo && !staleGroupIds.includes(b.groupId))+ .map((b) => ({ groupId: b.groupId, branch: b.worktree.branch, path: b.worktree.path }))+}diff --git a/src/shared/issue-worktree.test.ts b/src/shared/issue-worktree.test.tsindex 26c4333b4..6c0145314 100644--- a/src/shared/issue-worktree.test.ts+++ b/src/shared/issue-worktree.test.ts@@ -9,7 +9,7 @@ import {planIssueWorktree,type IssueWorktreeInput} from './issue-worktree'-import { computeWorktreePath, DEFAULT_WORKTREE_PATH_TEMPLATE, isValidGitRef } from './worktree'+import { computeWorktreePath, DEFAULT_WORKTREE_PATH_TEMPLATE, effectiveWorktreeTemplate, isValidGitRef } from './worktree'// Issue titles are writable by anyone on a public repository. Every one of these must come out as// a branch in the `[a-z0-9-]` alphabet that git accepts, and never as anything else.@@ -324,6 +324,42 @@ describe('planIssueWorktree', () => {expect(plan).toMatchObject({ kind: 'create', target: { branch: 'issue-12-fix-login-2' } })})+ it('treats a branch that exists only on a remote as TAKEN — never a diverging local twin', async () => {+ const plan = await planIssueWorktree(+ base({ remoteBranches: ['origin/issue-12-fix-login', 'origin/main'] }),+ nothingOnDisk+ )+ expect(plan).toEqual({+ kind: 'create',+ target: { branch: 'issue-12-fix-login-2', path: wt('issue-12-fix-login-2') },+ renamedFrom: 'issue-12-fix-login'+ })+ // …on any remote, and for the suffixes too; it is never offered as "check it out".+ const skipped = await planIssueWorktree(+ base({ remoteBranches: ['upstream/Issue-12-Fix-Login', 'origin/issue-12-fix-login-2'] }),+ nothingOnDisk+ )+ expect(skipped).toMatchObject({ kind: 'create', target: { branch: 'issue-12-fix-login-3' } })+ })++ it('refuses a location from the SHARED settings file that leaves the repository\'s folder', async () => {+ for (const sharedBasePath of ['../../.claude/skills', '/home/u/.codex', '../../../../tmp', '.git/hooks']) {+ // As in the app: the template IS what the shared basePath expands to.+ const template = effectiveWorktreeTemplate({ basePath: sharedBasePath }, undefined)+ const plan = await planIssueWorktree(+ base({ repoRoot: '/home/u/code/repo', template, sharedBasePath }),+ nothingOnDisk+ )+ expect(plan.kind, sharedBasePath).toBe('refused')+ if (plan.kind === 'refused') expect(plan.reason).toContain('.nodeterm/settings.json')+ }+ // The same shared setting pointing beside the repository is fine.+ const ok = effectiveWorktreeTemplate({ basePath: '../wt' }, undefined)+ expect(+ (await planIssueWorktree(base({ repoRoot: '/home/u/code/repo', template: ok, sharedBasePath: '../wt' }), nothingOnDisk)).kind+ ).toBe('create')+ })+it('refuses when every suffix is taken, when there is no repository, or no path', async () => {expect((await planIssueWorktree(base(), async () => true)).kind).toBe('refused')expect((await planIssueWorktree(base({ repoRoot: ' ' }), nothingOnDisk)).kind).toBe('refused')diff --git a/src/shared/issue-worktree.ts b/src/shared/issue-worktree.tsindex f6a4fccde..cf0628dd4 100644--- a/src/shared/issue-worktree.ts+++ b/src/shared/issue-worktree.ts@@ -1,5 +1,6 @@import { computeWorktreePath, type WorktreeEntry } from './worktree'import { normWorktreePath } from './worktree-reconcile'+import { sharedWorktreeLocationRefusal } from './worktree-location'// "Start with agent in a new worktree" on a GitHub issue card: the branch it creates, and what it// does when that branch (or its folder) is already taken.@@ -128,6 +129,18 @@ export interface IssueWorktreeInput {entries: readonly WorktreeEntry[]/** Local branch names; null or empty when they could not be read (git then has the last word). */branches: readonly string[] | null+ /**+ * Remote-tracking branches as git lists them (`origin/issue-12-fix`). A name that exists on a+ * remote is TAKEN: creating a same-named local branch from the base would diverge from it, the+ * later push would be rejected, and a pull request from that remote branch — someone else's — would+ * share this session's branch name. The planner moves to `-k` rather than basing on it: starting+ * an agent on another person's branch is not what "start in a NEW worktree" asks for. Only as+ * fresh as the last fetch.+ */+ remoteBranches?: readonly string[]+ /** `worktree.basePath` — ONLY when it came from the git-shared settings file (see+ * @shared/worktree-location): the location it produces must pass `sharedWorktreeLocationRefusal`. */+ sharedBasePath?: string/** Non-stale worktree-bound group frames on this canvas. */bound: readonly IssueWorktreeBoundGroup[]}@@ -157,6 +170,15 @@ export async function planIssueWorktree(reason: 'No worktree location could be derived from the worktree path setting. Nothing was created.'}}+ // Every candidate (`-k` included) lives in the same folder, so one check on the wanted name+ // judges them all — before anything else is planned.+ const location = sharedWorktreeLocationRefusal({+ path: pathFor(canonical),+ repoRoot,+ branch: canonical,+ sharedBasePath: input.sharedBasePath+ })+ if (location) return { kind: 'refused', reason: location }const known = new Set<string>()for (const b of input.branches ?? []) known.add(b.toLowerCase())@@ -164,6 +186,10 @@ export async function planIssueWorktree(// A frame's binding counts too: `entries` may be a failed (empty) read, and a bound branch or// folder is taken whatever git managed to list.for (const g of input.bound) known.add(g.branch.toLowerCase())+ for (const r of input.remoteBranches ?? []) {+ const slash = r.indexOf('/')+ if (slash > 0 && slash < r.length - 1) known.add(r.slice(slash + 1).toLowerCase())+ }// Every name this module builds is lower-case already; `known` is folded on the way in.const branchTaken = (b: string): boolean => known.has(b)const entryPaths = new Set(diff --git a/src/shared/worktree-location.test.ts b/src/shared/worktree-location.test.tsnew file mode 100644index 000000000..44c50c3d2--- /dev/null+++ b/src/shared/worktree-location.test.ts@@ -0,0 +1,127 @@+import { describe, expect, it } from 'vitest'+import { sharedBasePathOf, sharedWorktreeLocationRefusal, worktreeRedirectRefusal } from './worktree-location'+import { computeWorktreePath, effectiveWorktreeTemplate } from './worktree'++const REPO = '/home/u/code/repo'+/** The path a SHARED basePath produces for a branch — what every create path computes. */+const derived = (repoRoot: string, basePath: string, branch = 'issue-12-fix'): string =>+ computeWorktreePath(repoRoot, branch, effectiveWorktreeTemplate({ basePath }, undefined))+const judge = (basePath: string, repoRoot = REPO, branch = 'issue-12-fix'): string | null =>+ sharedWorktreeLocationRefusal({+ path: derived(repoRoot, basePath, branch),+ repoRoot,+ branch,+ sharedBasePath: basePath+ })++describe('sharedWorktreeLocationRefusal — a location from the git-shared settings file', () => {+ it.each([+ ['../../.claude/skills', 'climbs to ~/.claude/skills'],+ ['../../.codex/prompts', 'climbs to ~/.codex'],+ ['../../.ssh', 'climbs to ~/.ssh'],+ ['../../.config/nvim/pack/x/start', 'climbs into ~/.config'],+ ['../../../../etc/cron.d', 'leaves the holding folder'],+ ['/home/u/.claude/skills', 'absolute, hidden home folder'],+ ['/tmp/worktrees', 'absolute, outside the holding folder'],+ ['../../somewhere-else', 'a non-hidden folder above the holder'],+ ['.git', 'git\'s own folder'],+ ['.git/hooks', 'inside git\'s own folder'],+ ['../.hidden-worktrees', 'a hidden sibling of the repository']+ ])('refuses %j (%s)', (basePath) => {+ const reason = judge(basePath)+ expect(reason).toMatch(/shared settings \(\.nodeterm\/settings\.json/)+ expect(reason).toContain('Project Settings')+ expect(reason).toContain('Nothing was created')+ })++ it('refuses a hidden home folder when the repository sits directly in the home directory', () => {+ // The holder IS home here, so "inside the holder" alone would admit ~/.claude.+ expect(judge('../.claude/skills', '/home/u/repo')).not.toBeNull()+ })++ it.each([+ ['..'], // `../<branch>`: a plain sibling of the repository+ ['../worktrees'],+ ['../repo.worktrees'],+ ['.worktrees'], // nested inside the repository — its own content already applies to it+ ['wt'],+ ['../../code/wt'] // climbs out and back into the holding folder+ ])('allows %j, which stays beside or inside the repository', (basePath) => {+ expect(judge(basePath)).toBeNull()+ })++ it('judges only the location the shared setting produced — a typed or explicit path is the person\'s', () => {+ expect(+ sharedWorktreeLocationRefusal({+ path: '/tmp/my-own-choice',+ repoRoot: REPO,+ branch: 'issue-12-fix',+ sharedBasePath: '../../.claude/skills'+ })+ ).toBeNull()+ })++ it('does nothing for a local override or no setting', () => {+ const path = derived(REPO, '../../.claude/skills')+ expect(sharedWorktreeLocationRefusal({ path, repoRoot: REPO, branch: 'issue-12-fix', sharedBasePath: undefined })).toBeNull()+ expect(sharedWorktreeLocationRefusal({ path, repoRoot: REPO, branch: 'issue-12-fix', sharedBasePath: ' ' })).toBeNull()+ })++ it('refuses the same climb written with Windows separators', () => {+ expect(judge('..\\..\\.claude\\skills', 'C:\\Users\\u\\code\\repo')).not.toBeNull()+ expect(judge('..\\worktrees', 'C:\\Users\\u\\code\\repo')).toBeNull()+ })+})++describe('worktreeRedirectRefusal — the core backstop, on real paths', () => {+ const base = { home: '/home/u', realHome: '/home/u', realRepo: '/home/u/code/repo' }++ it('refuses a symlink that carries the checkout into a hidden home folder', () => {+ const reason = worktreeRedirectRefusal({+ ...base,+ requested: '/home/u/code/repo/tools/issue-1',+ real: '/home/u/.claude/skills/issue-1'+ })+ expect(reason).toContain('~/.claude')+ expect(reason).toContain('Nothing was created')+ })++ it('refuses anything inside the repository\'s .git folder', () => {+ expect(worktreeRedirectRefusal({ ...base, requested: '/x', real: '/home/u/code/repo/.git/x' })).not.toBeNull()+ expect(worktreeRedirectRefusal({ ...base, requested: '/x', real: '/home/u/code/repo/.git' })).not.toBeNull()+ })++ it('allows a hidden home folder the requested path names outright (a person\'s own template)', () => {+ expect(+ worktreeRedirectRefusal({ ...base, requested: '/home/u/.worktrees/x', real: '/home/u/.worktrees/x' })+ ).toBeNull()+ })++ it('allows ordinary locations, including symlinks that land somewhere ordinary (/tmp → /private/tmp)', () => {+ expect(+ worktreeRedirectRefusal({ ...base, requested: '/home/u/code/repo.worktrees/x', real: '/home/u/code/repo.worktrees/x' })+ ).toBeNull()+ expect(worktreeRedirectRefusal({ ...base, requested: '/tmp/wt/x', real: '/private/tmp/wt/x' })).toBeNull()+ })++ it('compares against the REAL home too (a home directory that is itself a link)', () => {+ expect(+ worktreeRedirectRefusal({+ home: '/home/u',+ realHome: '/data/home/u',+ realRepo: '/data/home/u/code/repo',+ requested: '/home/u/code/repo/tools/x',+ real: '/data/home/u/.codex/x'+ })+ ).toContain('~/.codex')+ })+})++describe('sharedBasePathOf', () => {+ it('answers the value only when it came from the shared file', () => {+ expect(sharedBasePathOf({ basePath: { value: '../../.claude', source: 'shared' } })).toBe('../../.claude')+ expect(sharedBasePathOf({ basePath: { value: '/mine', source: 'local' } })).toBeUndefined()+ expect(sharedBasePathOf({})).toBeUndefined()+ expect(sharedBasePathOf(undefined)).toBeUndefined()+ })+})diff --git a/src/shared/worktree-location.ts b/src/shared/worktree-location.tsnew file mode 100644index 000000000..861d1f262--- /dev/null+++ b/src/shared/worktree-location.ts@@ -0,0 +1,131 @@+import { computeWorktreePath, effectiveWorktreeTemplate } from './worktree'++// WHERE a new worktree may be created, when the answer came from someone other than the person at+// this machine.+//+// A project's worktree location (`worktree.basePath`) can come from `.nodeterm/settings.json` — the+// SHARED project settings file, committed to the repository and therefore written by anyone who can+// commit to it. `git worktree add` then writes the whole repository tree into that folder. Pointed at+// `../../.claude/skills`, one click on "Start with agent in a new worktree" checked the repo out into+// `~/.claude/skills/issue-N-…/`, and a root `SKILL.md` became a skill in every Claude session on the+// machine; `~/.codex`, `~/.config/…/plugins` and friends work the same way.+//+// Two layers, because a lexical check alone is not enough:+// - `sharedWorktreeLocationRefusal` (renderer, every create path): a location the SHARED file+// produced must stay inside the folder that holds the repository, and must not enter a hidden+// folder there unless it is inside the repository itself. A path the person typed (the New+// worktree dialog) or an agent passed explicitly (`open-worktree --path`) is not judged here —+// it did not come from the file.+// - `worktreeRedirectRefusal` (core, every `git worktree add`): after symlinks are resolved. A+// committed symlink inside the repository (`repo/tools -> ~/.claude/skills`) passes any lexical+// rule; only the REAL path shows where the checkout lands.++function norm(p: string): string {+ const s = p.trim().replace(/\\/g, '/').replace(/\/+$/, '')+ return s || '/'+}++/** `p`'s segments below `base`, or null when `p` is not strictly inside `base`. */+function segmentsBelow(base: string, p: string): string[] | null {+ const b = norm(base)+ const c = norm(p)+ const prefix = b === '/' ? '/' : `${b}/`+ if (c === b || !c.startsWith(prefix)) return null+ return c.slice(prefix.length).split('/').filter(Boolean)+}++function parentOf(p: string): string {+ const n = norm(p)+ const i = n.lastIndexOf('/')+ return i <= 0 ? '/' : n.slice(0, i)+}++const SHARED_FILE = '.nodeterm/settings.json'++/**+ * The project's `worktree.basePath` value when — and only when — it came from the SHARED file.+ * The one reading of provenance every create path uses (`ResolvedProjectSettings.worktree`); a+ * local override answers undefined, so it is never judged by the shared-location rule.+ */+export function sharedBasePathOf(+ worktree: { basePath?: { value: string; source: string } } | undefined+): string | undefined {+ const bp = worktree?.basePath+ return bp && bp.source === 'shared' && typeof bp.value === 'string' ? bp.value : undefined+}++/**+ * Refuse a worktree location that came from the project's SHARED settings file and leaves the folder+ * that holds the repository (or enters a hidden folder there). `null` = allowed.+ *+ * `sharedBasePath` is the `worktree.basePath` value ONLY when its source is the shared file (pass+ * undefined for a local override or no setting). Only the location that setting PRODUCES for this+ * branch is judged, so a path someone typed or passed explicitly is left alone.+ */+export function sharedWorktreeLocationRefusal(args: {+ path: string+ repoRoot: string+ branch: string+ sharedBasePath: string | undefined+}): string | null {+ const basePath = args.sharedBasePath?.trim()+ if (!basePath || !args.path.trim() || !args.repoRoot.trim()) return null+ const derived = computeWorktreePath(args.repoRoot, args.branch, effectiveWorktreeTemplate({ basePath }, undefined))+ if (!derived || norm(derived) !== norm(args.path)) return null+ const repo = norm(args.repoRoot)+ const holder = parentOf(repo)+ const below = segmentsBelow(holder, args.path)+ const repoName = repo.slice(repo.lastIndexOf('/') + 1)+ const inRepo = !!below && below[0] === repoName+ const allowed =+ !!below &&+ (inRepo+ ? below[1] !== '.git' // never into git's own folder+ : below.every((seg) => !seg.startsWith('.')))+ if (allowed) return null+ return (+ `This project's shared settings (${SHARED_FILE}, part of the repository, so anyone who can ` ++ `commit to it wrote it) put new worktrees at ${norm(args.path)}. A location from the shared ` ++ `file is only used inside ${holder} (the folder that holds this repository) and outside hidden ` ++ `folders there. To use that location, set it for this machine in Project Settings → Worktree. ` ++ 'Nothing was created.'+ )+}++/**+ * The core backstop for EVERY `git worktree add`, judged on real (symlink-resolved) paths:+ * - never inside the repository's own `.git` folder;+ * - never REDIRECTED into a hidden folder directly under the home directory (`~/.claude`,+ * `~/.codex`, `~/.ssh`, `~/.config`, …) — i.e. the real location is in one while the requested+ * path did not name it. That is a symlink carrying the checkout somewhere agent CLIs and other+ * tools load skills, plugins and configuration from; nobody configures that on purpose. A+ * location that names such a folder outright (a person's own `/home/me/.worktrees` template) is+ * theirs, and the renderer rule above already refuses one that came from the shared file.+ * `null` = allowed.+ */+export function worktreeRedirectRefusal(args: {+ requested: string+ real: string+ realRepo: string+ home: string+ realHome: string+}): string | null {+ const real = norm(args.real)+ if (segmentsBelow(`${norm(args.realRepo)}/.git`, real) || norm(`${args.realRepo}/.git`) === real) {+ return `Refusing to create a worktree inside the repository's .git folder (${real}). Nothing was created.`+ }+ const hiddenTop = (p: string, home: string): string | null => {+ if (!home.trim()) return null+ const seg = segmentsBelow(home, p)?.[0]+ return seg && seg.startsWith('.') ? seg : null+ }+ const landed = hiddenTop(real, args.realHome) ?? hiddenTop(real, args.home)+ if (!landed) return null+ const named = hiddenTop(args.requested, args.home) ?? hiddenTop(args.requested, args.realHome)+ if (named === landed) return null+ return (+ `Refusing to create a worktree at ${norm(args.requested)}: it resolves to ${real}, inside ` ++ `~/${landed}, a hidden folder of your home directory where tools load skills and ` ++ 'configuration from (a symbolic link on the way points there). Nothing was created.'+ )+}