Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions apps/supercode-cli/server/src/nova/workspaces/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ engine-managed clone location, never a browser-supplied path.
| `/lookup` | `{threadId}` | `{workspace}` (or `{workspace:null}`) |
| `/clone` | `{repositoryFullName:"owner/name",confirmed:true}` | `{project}` |
| `/branches` | `{projectId,fetch?:boolean}` | `{branches}` |
| `/worktrees` | `{projectId}` | `{worktrees}` |
| `/ignored-files` | `{projectId}` | `{paths}` (names only, no contents) |
| `/create` | `{projectId,threadId,sourceRef,mode,newBranch?,copyIgnored?}` | `{workspace}` |
| `/get` | `{workspaceId}` | `{workspace}` |
Expand All @@ -116,6 +117,26 @@ Branch listing is local unless `fetch:true` explicitly requests a refresh from
the configured remotes. Ignored-file listing returns only copy-candidate names
for user consent, not file bytes.

`/worktrees` reads Git's actual local `worktree list --porcelain -z` for an
approved project, not browser cache. Each entry contains
`{path,branch,head,main,locked,prunable,workspaceId?,threadId?}`. `branch` is the
short local branch name or null for detached HEAD; `head` is the commit ID
(all zeroes for an unborn branch). `main` identifies Git's primary checkout,
not necessarily the approved project directory. Bare entries have an empty
`head` and null branch. Paths, including spaces and newlines, are preserved.
The companion remains required for local discovery and uses the same pairing,
exact-Origin, Host and project authorization as other routes.

External linked worktrees, including missing/prunable entries, are discovery
only: listing never registers them, reads their files, or grants write access.
Only an existing, validated engine binding adds `workspaceId` and `threadId`;
stale or ambiguous bindings omit both. Listing does not attach a checkout to a
new thread. Reuse a known thread deliberately, or create a separate worktree.
Discovery is limited to 256 worktrees, 1 MiB of Git output, and 1024 immediate
registry entries; it never scans home directories. Limit failures return 409
rather than a misleading partial list. Git failures also return a sanitized
409 rather than an empty successful list.

Use `/lookup` after pairing again to recover a thread's existing workspace.
Workspace IDs may be persisted as nonsecret browser state; bearer tokens should
not be persisted beyond the browser session. Lookup remains authenticated and
Expand Down
59 changes: 58 additions & 1 deletion apps/supercode-cli/server/src/nova/workspaces/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { tmpdir } from "node:os"
import { join } from "node:path"
import { promisify } from "node:util"

import { NovaWorkspaceGit } from "./git"
import { NovaWorkspaceGit, parseGitWorktrees } from "./git"
import type { PublishInput } from "./git"

const exec = promisify(execFile)
Expand Down Expand Up @@ -49,6 +49,63 @@ async function fixture(options: { unborn?: boolean; publishPr?: ConstructorParam
const publication = (workspaceId: string, extra: Partial<PublishInput> = {}): PublishInput => ({ workspaceId, action: "commit", branch: "feature/test", baseBranch: "main", remote: "origin", message: "selected changes", files: ["a.txt"], ...extra })

describe("NovaWorkspaceGit", () => {
test("discovers real external, detached, locked and missing worktrees without registering them", async () => {
const f = await fixture()
const external = join(f.root, "external tree with spaces\nand newline")
const missing = join(f.root, "missing tree")
await git(f.repo, "worktree", "add", "-b", "external/topic", external)
await git(f.repo, "worktree", "lock", "--reason", "keep this tree", external)
await git(f.repo, "worktree", "add", "--detach", missing)
await fs.rm(missing, { recursive: true })
const managed = await f.create()
const head = await git(f.repo, "rev-parse", "HEAD")
const trees = await f.engine.worktrees(f.project.id)
expect(trees).toHaveLength(4)
expect(trees[0]).toEqual({ path: f.repo, branch: "main", head, main: true, locked: false, prunable: false })
expect(trees.find(tree => tree.path === external)).toEqual({ path: external, branch: "external/topic", head, main: false, locked: true, prunable: false })
expect(trees.find(tree => tree.path === missing)).toEqual({ path: missing, branch: null, head, main: false, locked: false, prunable: true })
expect(trees.find(tree => tree.path === managed.path)).toMatchObject({ branch: null, workspaceId: managed.id, threadId: managed.threadId })
expect(await f.engine.lookup("external")).toBeNull()
await expect(f.engine.get(external)).rejects.toThrow("Invalid registry ID")
await expect(f.engine.worktrees("unknown")).rejects.toThrow("Unknown project")
const linkedEngine = new NovaWorkspaceGit({ roots: [external], home: f.home })
const linkedProject = (await linkedEngine.listProjects())[0]!
const linkedTrees = await linkedEngine.worktrees(linkedProject.id)
expect(linkedTrees[0]?.main).toBe(true)
expect(linkedTrees.find(tree => tree.path === external)?.main).toBe(false)
expect(linkedTrees.every(tree => !tree.workspaceId && !tree.threadId)).toBe(true)
})

test("omits stale and ambiguous engine metadata without hiding Git entries", async () => {
const f = await fixture()
const managed = await f.create()
const bindingFile = join(f.home, ".nova/worktrees", "binding-" + managed.id + ".json")
const binding = JSON.parse(await fs.readFile(bindingFile, "utf8"))
await fs.writeFile(bindingFile, JSON.stringify({ ...binding, gitDir: "/stale" }))
expect((await f.engine.worktrees(f.project.id)).find(tree => tree.path === managed.path)?.workspaceId).toBeUndefined()
await fs.rm(managed.path, { recursive: true })
expect((await f.engine.worktrees(f.project.id)).find(tree => tree.path === managed.path)).toMatchObject({ prunable: true })
await f.create("current-one", "current")
await f.create("current-two", "current")
await f.create("current-three", "current")
const current = (await f.engine.worktrees(f.project.id))[0]!
expect(current.workspaceId).toBeUndefined()
expect(current.threadId).toBeUndefined()
})

test("lists unborn repositories and rejects malformed or oversized NUL porcelain", async () => {
const f = await fixture({ unborn: true })
expect(await f.engine.worktrees(f.project.id)).toEqual([{ path: f.repo, branch: "main", head: "0".repeat(40), main: true, locked: false, prunable: false }])
const block = "worktree /safe path\0HEAD " + "a".repeat(40) + "\0detached\0\0"
expect(parseGitWorktrees(block)[0]?.branch).toBeNull()
expect(parseGitWorktrees("worktree /bare\0bare\0\0")[0]?.head).toBe("")
for (const malformed of ["", block.slice(0, -1), block + block, block.replace("/safe path", "relative"), block.replace("detached", "branch refs/heads/main\0detached"), block.replace("detached", "locked"), block.replace("detached", "unknown value"), block.replace("HEAD ", "HEAD not-a-hash")]) {
expect(() => parseGitWorktrees(malformed)).toThrow("Invalid Git worktree listing")
}
expect(() => parseGitWorktrees("x".repeat(1024 * 1024 + 1))).toThrow("discovery limits")
expect(() => parseGitWorktrees(Array.from({ length: 257 }, (_, i) => block.replace("/safe path", "/tree-" + i)).join(""))).toThrow("discovery limits")
})

test("creates an explicitly requested new working branch without switching the original checkout", async () => {
const f = await fixture()
const workspace = await f.create("named-worktree", "worktree", { newBranch: "nova/new-feature" })
Expand Down
96 changes: 94 additions & 2 deletions apps/supercode-cli/server/src/nova/workspaces/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,58 @@ function canonical(path: string): string {
}
export type Project = { id: string; name: string; path: string; repositoryFullName: string | null; isGit: boolean }
export type Branch = { name: string; ref: string; sha: string; remote: boolean; checkedOut: boolean; current: boolean }
export type Worktree = { path: string; branch: string | null; head: string; main: boolean; locked: boolean; prunable: boolean; workspaceId?: string; threadId?: string }
const MAX_WORKTREES = 256
const MAX_WORKTREE_BYTES = 1024 * 1024

export function parseGitWorktrees(output: string): Worktree[] {
const invalid = () => { throw new Error("Invalid Git worktree listing") }
if (Buffer.byteLength(output) > MAX_WORKTREE_BYTES) throw new Error("Git worktree listing exceeds discovery limits")
if (!output || !output.endsWith("\0\0")) return invalid()
const result: Worktree[] = []
const paths = new Set<string>()
for (const block of output.slice(0, -2).split("\0\0")) {
if (result.length >= MAX_WORKTREES) throw new Error("Git worktree listing exceeds discovery limits")
const fields = block.split("\0")
const first = fields.shift()!
if (!first.startsWith("worktree ")) return invalid()
const path = first.slice(9)
if (!isAbsolute(path) || paths.has(path)) return invalid()
paths.add(path)
const values = new Map<string, string>()
for (const field of fields) {
const space = field.indexOf(" ")
const key = space < 0 ? field : field.slice(0, space)
const value = space < 0 ? "" : field.slice(space + 1)
if (!["HEAD", "branch", "detached", "bare", "locked", "prunable"].includes(key) || values.has(key)) return invalid()
if (["bare", "detached"].includes(key) && value) return invalid()
values.set(key, value)
}
const head = values.get("HEAD") ?? ""
const branch = values.get("branch")
if (values.has("bare")) {
if (head || branch !== undefined || values.has("detached")) return invalid()
} else if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(head) || (branch === undefined) === !values.has("detached")) return invalid()
if (branch !== undefined && (!branch.startsWith("refs/heads/") || branch.length <= 11 || /[\x00-\x20\x7f]/.test(branch))) return invalid()
result.push({ path, branch: branch?.slice(11) ?? null, head, main: result.length === 0, locked: values.has("locked"), prunable: values.has("prunable") })
}
return result
}
export type Workspace = { id: string; projectId: string; threadId: string; path: string; sourceRef: string; baseSha: string; branch: string | null; mode: "current" | "worktree" }
export type PublishInput = { workspaceId: string; action: "commit" | "push" | "pr"; branch: string; baseBranch: string; remote: string; message: string; files: string[]; title?: string; body?: string }
export type Preview = PublishInput & { id: string; head: string; diff: string; expiresAt: string }
type StoredPreview = { preview: Preview; fingerprint: string; remoteHeads: string; indexTree?: string; receipt?: { commitSha: string; branch: string; prUrl?: string }; stage?: "committed" | "attached" | "pushed" | "pr-started" | "done" }
type PrPublisher = (input: { cwd: string; branch: string; baseBranch: string; remote: string; title: string; body: string }) => Promise<string>

async function run(cwd: string, args: string[], env?: NodeJS.ProcessEnv, input?: Buffer, timeout = 30_000) {
async function run(cwd: string, args: string[], env?: NodeJS.ProcessEnv, input?: Buffer, timeout = 30_000, maxBuffer = 16 * 1024 * 1024) {
const config = ["-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null"]
const environment = { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_LITERAL_PATHSPECS: args[0] === "check-ignore" ? "0" : "1", ...env }
const filters = await exec("git", [...config, "-C", cwd, "config", "--name-only", "--get-regexp", "^filter\\."], { env: environment, timeout: 5000, maxBuffer: 1024 * 1024 }).then(result => result.stdout).catch(error => { if (error.code === 1) return ""; throw error })
for (const key of filters.split("\n")) {
const match = key.match(/^filter\.(.+)\.(?:clean|smudge|process|required)$/)
if (match) for (const attribute of ["clean", "smudge", "process", "required"]) config.push("-c", "filter." + match[1] + "." + attribute + "=" + (attribute === "required" ? "false" : ""))
}
const pending = exec("git", [...config, "-C", cwd, ...args], { env: environment, timeout, maxBuffer: 16 * 1024 * 1024 })
const pending = exec("git", [...config, "-C", cwd, ...args], { env: environment, timeout, maxBuffer })
pending.child.stdin?.end(input)
const result = await pending
return result.stdout.replace(/\n$/, "")
Expand Down Expand Up @@ -167,6 +204,61 @@ export class NovaWorkspaceGit {
})
}

async worktrees(projectId: string): Promise<Worktree[]> {
const project = await this.project(projectId)
if (!project.isGit) return []
if (await fs.realpath(project.path) !== project.path) throw new Error("Project root or ancestors cannot be symlinks")
let output: string
try {
output = await run(project.path, ["worktree", "list", "--porcelain", "-z"], undefined, undefined, 10_000, MAX_WORKTREE_BYTES)
} catch (error) {
if ((error as { code?: string }).code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") throw new Error("Git worktree listing exceeds discovery limits")
throw error
}
const worktrees = parseGitWorktrees(output)
if (!await exists(this.registry)) return worktrees
const directory = await fs.opendir(this.registry).catch(error => {
if (error.code === "ENOENT") return null
throw error
})
if (!directory) return worktrees
let entries = 0
const ambiguous = new Set<string>()
for await (const entry of directory) {
if (++entries > 1024) throw new Error("Workspace registry exceeds discovery limits")
if (!entry.isFile() || !/^[0-9a-f]{32}\.json$/.test(entry.name)) continue
const id = entry.name.slice(0, -5)
const stat = await fs.lstat(join(this.registry, entry.name))
if (!stat.isFile() || stat.size > 64 * 1024) continue
let workspace: Workspace
try {
const manifest = await this.load<Workspace>(id)
if (manifest.projectId !== projectId || !/^[a-zA-Z0-9_-]{1,128}$/.test(manifest.threadId) || hash(projectId + ":" + manifest.threadId).slice(0, 32) !== id) continue
if (!["current", "worktree"].includes(manifest.mode)) continue
const candidate = worktrees.find(tree => tree.path === manifest.path && !tree.prunable)
if (!candidate) continue
const bindingStat = await fs.lstat(join(this.registry, "binding-" + id + ".json"))
if (!bindingStat.isFile() || bindingStat.size > 64 * 1024) continue
const binding = await this.load<Workspace>("binding-" + id)
if (binding.projectId !== projectId || binding.threadId !== manifest.threadId || binding.mode !== manifest.mode || binding.sourceRef !== manifest.sourceRef) continue
workspace = await this.get(id)
} catch {
continue
}
const tree = worktrees.find(tree => tree.path === workspace.path)!
if (ambiguous.has(tree.path)) continue
if (tree.workspaceId) {
ambiguous.add(tree.path)
delete tree.workspaceId
delete tree.threadId
continue
}
tree.workspaceId = workspace.id
tree.threadId = workspace.threadId
}
return worktrees
}

async fetchBranches(projectId: string): Promise<Branch[]> {
const project = await this.project(projectId)
if (!project.isGit) return []
Expand Down
20 changes: 20 additions & 0 deletions apps/supercode-cli/server/src/nova/workspaces/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ function fixture() {
cloneRepository: call("cloneRepository", { id: "cloned-project" }),
lookup: call("lookup", { id: "workspace" }),
branches: call("branches", ["main"]),
worktrees: call("worktrees", [{ path: "/explicit-root", branch: "main", head: "a".repeat(40), main: true, locked: false, prunable: false }]),
fetchBranches: call("fetchBranches", ["main", "origin/topic"]),
ignoredFiles: call("ignoredFiles", [".env.local"]),
create: call("create", { id: "workspace" }),
Expand Down Expand Up @@ -47,6 +48,24 @@ function fixture() {
}

describe("workspace companion protocol", () => {
test("protects discovery with pairing, exact origin and strict project-only input", async () => {
const f = fixture()
expect((await f.post("/worktrees", { projectId: "project" })).status).toBe(401)
const { token } = await f.pair()
expect((await f.post("/worktrees", { projectId: "project" }, token, otherOrigin)).status).toBe(403)
expect((await f.post("/worktrees", { projectId: "project" }, token, origin + "/")).status).toBe(403)
for (const body of [{}, { projectId: "project", path: "/arbitrary" }, { projectId: "project", threadId: "new-thread" }, { projectId: 42 }]) {
expect((await f.post("/worktrees", body, token)).status).toBe(400)
}
expect(f.calls).toEqual([])
f.service.worktrees = async () => { throw new Error("Unknown project") }
const unknown = await f.post("/worktrees", { projectId: "unknown" }, token)
expect(unknown.status).toBe(409)
expect(await unknown.json()).toEqual({ error: "Unknown project" })
f.service.worktrees = async () => { throw new Error("private Git stderr") }
expect(await (await f.post("/worktrees", { projectId: "project" }, token)).json()).toEqual({ error: "Workspace operation failed" })
})

test("validates explicit project roots and exact origins", () => {
expect(approvedWorkspaceOrigin(origin)).toBe(true)
expect(approvedWorkspaceOrigin(otherOrigin)).toBe(true)
Expand Down Expand Up @@ -160,6 +179,7 @@ describe("workspace companion protocol", () => {
const cases: [string, unknown, string, unknown[], unknown][] = [
["lookup", { threadId: "thread" }, "lookup", ["thread"], { workspace: { id: "workspace" } }],
["branches", { projectId: "project" }, "branches", ["project"], { branches: ["main"] }],
["worktrees", { projectId: "project" }, "worktrees", ["project"], { worktrees: [{ path: "/explicit-root", branch: "main", head: "a".repeat(40), main: true, locked: false, prunable: false }] }],
["branches", { projectId: "project", fetch: false }, "branches", ["project"], { branches: ["main"] }],
["branches", { projectId: "project", fetch: true }, "fetchBranches", ["project"], { branches: ["main", "origin/topic"] }],
["ignored-files", { projectId: "project" }, "ignoredFiles", ["project"], { paths: [".env.local"] }],
Expand Down
6 changes: 6 additions & 0 deletions apps/supercode-cli/server/src/nova/workspaces/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import { NovaWorkspaceGit } from "./git"
const MAX_BODY = 2 * 1024 * 1024
const SESSION_MS = 60 * 60 * 1000
const SAFE_WORKSPACE_ERRORS = new Set([
"Git worktree listing exceeds discovery limits",
"Workspace registry exceeds discovery limits",
"Invalid Git worktree listing",
"Project root or ancestors cannot be symlinks",
"Use a GitHub repository name in owner/name format",
"Another repository clone is in progress",
"Managed clone destination already exists; no files were overwritten",
Expand Down Expand Up @@ -90,6 +94,7 @@ export interface WorkspaceService {
cloneRepository(repositoryFullName: string): Promise<unknown>
lookup(threadId: string): Promise<unknown>
branches(projectId: string): Promise<unknown>
worktrees(projectId: string): Promise<unknown>
fetchBranches(projectId: string): Promise<unknown>
ignoredFiles(projectId: string): Promise<unknown>
create(input: CreateWorkspaceInput): Promise<unknown>
Expand Down Expand Up @@ -243,6 +248,7 @@ export function startWorkspaceCompanion(options: {
return reply({ branches: input.fetch ? await service.fetchBranches(input.projectId) : await service.branches(input.projectId) })
}
case "/ignored-files": return reply({ paths: await service.ignoredFiles(projectInput.parse(body).projectId) })
case "/worktrees": return reply({ worktrees: await service.worktrees(projectInput.parse(body).projectId) })
case "/create": return reply({ workspace: await service.create(createInput.parse(body)) })
case "/get": return reply({ workspace: await service.get(workspaceInput.parse(body).workspaceId) })
case "/files": return reply({ paths: await service.files(workspaceInput.parse(body).workspaceId) })
Expand Down
Loading
Loading