mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-16 03:09:33 +01:00
feat(files): follow the agent into a worktree outside the session folder
#772 made the Files panel follow an agent into a worktree inside the session's folder. A worktree beside the repository (git worktree add ../feature, or an EnterWorktree into one that already exists there) stayed unfollowed, since serving it needs a second confinement root. findOutsideWorktree() answers that case without running git. The nearest .git above the pane must name <common dir>/worktrees/<id> of the session's own repository, and that registry entry must name the candidate back (or the .git folder must be the common dir itself). It refuses /, the home folder and above, any folder holding workingDir and Docker case workspaces, and multi-user mode applies the owner's folderAllowedForUser rule. The answer is liveWorktree with outside: true and the folder's real path. The file routes serve an absolute path inside that worktree, and only while the folder still resolves to the recorded path. A relative path still resolves against workingDir alone. The browser routes such paths to the editable preview, and root-relative markdown refs resolve from the top of the worktree. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e9b2ecd552
commit
c9b79097b0
18 files changed
+1030
-56
No files matched your search
+181
-11
@@ -13,11 +13,15 @@
|
||||
* than by running `git worktree list`: this runs from the pane watcher whenever a directory
|
||||
* changes, and a file read starts no process, no repository config and no filter.
|
||||
*
|
||||
* Only a folder strictly below `workingDir` is ever an answer: the file routes already serve
|
||||
* A folder strictly below `workingDir` is the plain answer: the file routes already serve
|
||||
* everything under it, so following a pane there widens nothing, and a planted `.git` file can
|
||||
* only move where the listing STARTS inside that same folder. A worktree outside it
|
||||
* (`git worktree add ../feature`) stays unfollowed, since listing it would need a second
|
||||
* confinement root.
|
||||
* only move where the listing STARTS inside that same folder.
|
||||
*
|
||||
* A worktree OUTSIDE `workingDir` (`git worktree add ../feature`, or an EnterWorktree that a
|
||||
* `WorktreeCreate` hook places beside the repository) is a second confinement root, so it is
|
||||
* answered only when the caller passes {@link OutsideWorktreeOptions}, and only when the session's
|
||||
* own repository vouches for it ({@link findOutsideWorktree}). The answer then carries
|
||||
* `outside: true`, and the file routes serve absolute paths inside it.
|
||||
*
|
||||
* That answer is lexical and only as fresh as the last time the pane moved: a symlink can take the
|
||||
* folder's place afterwards without moving the pane. So nothing here is a confinement decision.
|
||||
@@ -32,15 +36,37 @@
|
||||
*/
|
||||
|
||||
import { constants, promises as fs } from 'node:fs';
|
||||
import { basename, dirname, join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { basename, dirname, join, resolve, sep } from 'node:path';
|
||||
import { probePathKind } from './utils/bounded-path-probe.js';
|
||||
|
||||
/** A linked worktree a session's pane is in. */
|
||||
export interface LiveWorktree {
|
||||
/** The worktree folder's name, for display. */
|
||||
name: string;
|
||||
/** Absolute path, spelled like the session's `workingDir`. */
|
||||
/**
|
||||
* Absolute path. Spelled like the session's `workingDir` for a worktree inside it; the real
|
||||
* path (no symlink in any component) for one outside it.
|
||||
*/
|
||||
path: string;
|
||||
/**
|
||||
* The worktree lies outside `workingDir`, so it is a second root the file routes serve
|
||||
* ABSOLUTE paths from. Absent for a worktree inside `workingDir`.
|
||||
*/
|
||||
outside?: true;
|
||||
}
|
||||
|
||||
/** What {@link findLiveWorktree} needs to answer a worktree outside `workingDir`. */
|
||||
export interface OutsideWorktreeOptions {
|
||||
/** Overrides `os.homedir()` (tests). */
|
||||
home?: string;
|
||||
/** Host paths of every Docker case workspace: a container can write there, so none is followed. */
|
||||
dockerWorkspaces?: () => Promise<string[]>;
|
||||
/**
|
||||
* Narrows which worktree may be followed. Multi-user mode passes the owner's folder rule
|
||||
* (`folderAllowedForUser`), so a regular user's session cannot list another user's checkout.
|
||||
*/
|
||||
allowRoot?: (root: string) => boolean | Promise<boolean>;
|
||||
}
|
||||
|
||||
/** More than any real `.git` file. It is read only to recognise the first line. */
|
||||
@@ -82,15 +108,22 @@ async function classifyDotGit(dir: string): Promise<'worktree' | 'stop' | 'none'
|
||||
}
|
||||
|
||||
/**
|
||||
* The linked worktree strictly below `workingDir` that holds `cwd`, if any. Walks up from `cwd`
|
||||
* and stops at `workingDir`, at a repository or submodule of its own, or at anything it cannot
|
||||
* read. `workingDir` itself is never an answer: a session started in a worktree is already
|
||||
* listing it. Never throws.
|
||||
* The linked worktree that holds `cwd`, if any. Walks up from `cwd` and stops at `workingDir`,
|
||||
* at a repository or submodule of its own, or at anything it cannot read. `workingDir` itself is
|
||||
* never an answer: a session started in a worktree is already listing it. When `cwd` lies outside
|
||||
* `workingDir` and `outside` is given, {@link findOutsideWorktree} answers instead. Never throws.
|
||||
*/
|
||||
export async function findLiveWorktree(workingDir: string, cwd: string | undefined): Promise<LiveWorktree | undefined> {
|
||||
export async function findLiveWorktree(
|
||||
workingDir: string,
|
||||
cwd: string | undefined,
|
||||
outside?: OutsideWorktreeOptions
|
||||
): Promise<LiveWorktree | undefined> {
|
||||
if (!cwd?.startsWith('/')) return undefined;
|
||||
const root = workingDir.length > 1 ? workingDir.replace(/\/+$/, '') : workingDir;
|
||||
const under = root === '/' ? '/' : `${root}/`;
|
||||
if (cwd !== root && !cwd.startsWith(under)) {
|
||||
return outside ? findOutsideWorktree(root, cwd, outside).catch(() => undefined) : undefined;
|
||||
}
|
||||
for (let dir = cwd; dir !== root && dir.startsWith(under); dir = dirname(dir)) {
|
||||
const found = await classifyDotGit(dir);
|
||||
if (found === 'worktree') return { name: basename(dir), path: dir };
|
||||
@@ -98,3 +131,140 @@ export async function findLiveWorktree(workingDir: string, cwd: string | undefin
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** True when `child` is `parent` or lies below it. Both must already be real paths. */
|
||||
const isSameOrUnder = (child: string, parent: string): boolean =>
|
||||
child === parent || child.startsWith(parent === sep ? parent : parent + sep);
|
||||
|
||||
/** The real path of `p` once a bounded probe has answered for it, else null. */
|
||||
async function realPathBounded(p: string): Promise<string | null> {
|
||||
const kind = await probePathKind(p);
|
||||
if (kind !== 'directory' && kind !== 'file') return null;
|
||||
try {
|
||||
return await fs.realpath(p);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The text of a small regular file, refusing a symlink as the last component and a FIFO
|
||||
* (O_NOFOLLOW, O_NONBLOCK, then judged on the handle), like {@link classifyDotGit}. Null for
|
||||
* anything else.
|
||||
*/
|
||||
async function readSmallFile(path: string): Promise<string | null> {
|
||||
if ((await probePathKind(path)) !== 'file') return null;
|
||||
let handle: fs.FileHandle | undefined;
|
||||
try {
|
||||
handle = await fs.open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||
if (!(await handle.stat()).isFile()) return null;
|
||||
const { buffer, bytesRead } = await handle.read(Buffer.alloc(MAX_DOT_GIT_FILE_BYTES), 0, MAX_DOT_GIT_FILE_BYTES, 0);
|
||||
return buffer.toString('utf8', 0, bytesRead);
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
await handle?.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/** The `gitdir:` value of a `.git` file's text, resolved against the folder that holds it. */
|
||||
function gitDirOf(text: string, dir: string): string | null {
|
||||
const raw = /^gitdir:[ \t]*(.+?)[ \t]*$/m.exec(text)?.[1];
|
||||
return raw ? resolve(dir, raw) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The real path of the git common dir of the repository whose top level is `workingDir`: its
|
||||
* `.git` folder, or, for a linked worktree, the folder its `commondir` file names. Null when
|
||||
* `workingDir` is not the top level of a repository or worktree: a session in a subfolder
|
||||
* follows no worktree outside it.
|
||||
*/
|
||||
async function sessionCommonDir(workingDir: string): Promise<string | null> {
|
||||
const dotGit = join(workingDir, '.git');
|
||||
const kind = await probePathKind(dotGit);
|
||||
if (kind === 'directory') return realPathBounded(dotGit);
|
||||
if (kind !== 'file') return null;
|
||||
const text = await readSmallFile(dotGit);
|
||||
const gitDir = text ? gitDirOf(text, workingDir) : null;
|
||||
if (!gitDir) return null;
|
||||
// A linked worktree's git dir names the common dir in `commondir`; a submodule's git dir
|
||||
// has none and is its own common dir.
|
||||
const commonDir = await readSmallFile(join(gitDir, 'commondir'));
|
||||
return realPathBounded(commonDir ? resolve(gitDir, commonDir.trim()) : gitDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* The worktree outside `workingDir` that holds `cwd`, when the session's own repository vouches
|
||||
* for it. `cwd` comes from the pane, which a prompt-injected agent controls, so every rule below
|
||||
* keeps it from widening what the file routes serve beyond a worktree of the session's repository:
|
||||
*
|
||||
* - The walk up from `cwd` stops at the first `.git`. That folder is a candidate only when its
|
||||
* `.git` FILE names `<common dir>/worktrees/<id>` of the session's repository AND that
|
||||
* entry's own `gitdir` file names the candidate back. A `.git` FOLDER is a candidate only when
|
||||
* it IS the session's common dir (the main worktree, for a session started in a linked one).
|
||||
* These are the files `git worktree list` reads, read here without starting git: this runs
|
||||
* from the pane watcher on every directory change.
|
||||
* - `/`, the home folder and anything above it, and any folder holding `workingDir` are
|
||||
* refused, as is a folder at, inside or around a Docker case workspace.
|
||||
* - `allowRoot`, when given, has the last word (multi-user mode).
|
||||
*
|
||||
* Every path is compared as a real path, and the answer is the real path. The file routes check
|
||||
* on each request that the folder still resolves to itself, so a symlink swapped in later is
|
||||
* refused there. A forged registry entry needs write access to the session's own `.git`, which
|
||||
* an agent running as this user already has, along with read access to everything it could list.
|
||||
*/
|
||||
export async function findOutsideWorktree(
|
||||
workingDir: string,
|
||||
cwd: string,
|
||||
opts: OutsideWorktreeOptions
|
||||
): Promise<LiveWorktree | undefined> {
|
||||
// The nearest folder at or above `cwd` that holds a `.git`, and what that `.git` is.
|
||||
let dir = cwd;
|
||||
let kind: 'directory' | 'file';
|
||||
for (;;) {
|
||||
const probed = await probePathKind(join(dir, '.git'));
|
||||
if (probed === 'unknown') return undefined;
|
||||
if (probed === 'directory' || probed === 'file') {
|
||||
kind = probed;
|
||||
break;
|
||||
}
|
||||
const parent = dirname(dir);
|
||||
if (parent === dir) return undefined;
|
||||
dir = parent;
|
||||
}
|
||||
|
||||
const commonDir = await sessionCommonDir(workingDir);
|
||||
if (!commonDir) return undefined;
|
||||
const real = await realPathBounded(dir);
|
||||
if (!real) return undefined;
|
||||
|
||||
if (kind === 'directory') {
|
||||
// The main worktree: its `.git` folder is the session's common dir itself.
|
||||
if ((await realPathBounded(join(dir, '.git'))) !== commonDir) return undefined;
|
||||
} else {
|
||||
const text = await readSmallFile(join(dir, '.git'));
|
||||
const gitDir = text && isLinkedWorktreeGitFile(text) ? gitDirOf(text, dir) : null;
|
||||
const realGitDir = gitDir ? await realPathBounded(gitDir) : null;
|
||||
if (!realGitDir || dirname(realGitDir) !== join(commonDir, 'worktrees')) return undefined;
|
||||
// The registry entry must name this folder back, as `git worktree list` would report it.
|
||||
const back = await readSmallFile(join(realGitDir, 'gitdir'));
|
||||
const backDir = back ? await realPathBounded(dirname(resolve(realGitDir, back.trim()))) : null;
|
||||
if (backDir !== real) return undefined;
|
||||
}
|
||||
|
||||
const realWorkingDir = await realPathBounded(workingDir);
|
||||
if (!realWorkingDir || isSameOrUnder(realWorkingDir, real) || isSameOrUnder(real, realWorkingDir)) return undefined;
|
||||
const home = (await realPathBounded(opts.home ?? homedir())) ?? resolve(opts.home ?? homedir());
|
||||
if (real === sep || isSameOrUnder(home, real)) return undefined;
|
||||
if (opts.dockerWorkspaces) {
|
||||
const workspaces = await opts.dockerWorkspaces().catch(() => null);
|
||||
// An unreadable list could hide a container's workspace, so it fails closed.
|
||||
if (!workspaces) return undefined;
|
||||
for (const workspace of workspaces) {
|
||||
const realWorkspace = (await realPathBounded(workspace)) ?? resolve(workspace);
|
||||
if (isSameOrUnder(real, realWorkspace) || isSameOrUnder(realWorkspace, real)) return undefined;
|
||||
}
|
||||
}
|
||||
if (opts.allowRoot && !(await opts.allowRoot(real))) return undefined;
|
||||
return { name: basename(real), path: real, outside: true };
|
||||
}
|
||||
Reference in new issue
Block a user