Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
907f7df
feat(cli): add --worktree flag to create/reuse a git worktree for the…
bagatao-anaconda Aug 3, 2026
fb5f410
fix(cli): prune stale worktree registrations and avoid full app boots…
bagatao-anaconda Aug 3, 2026
8e13ede
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda Aug 3, 2026
2762d09
fix(cli): wait for worktree setup and align --worktree with Agent Man…
bagatao-anaconda Aug 4, 2026
0d78791
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda Aug 4, 2026
627e24d
refactor(cli): tighten tui-worktree implementation and note reuse lim…
bagatao-anaconda Aug 4, 2026
f3e93ec
fix(cli): don't force-delete pre-existing branches when reclaiming a …
bagatao-anaconda Aug 5, 2026
e6214f7
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda Aug 5, 2026
90989d4
fix(cli): update tui-worktree to use Database.layerFromPath after ups…
bagatao-anaconda Aug 5, 2026
4fdaa4c
refactor(cli): tighten tui-worktree, log exclude-write failures, fix …
bagatao-anaconda Aug 5, 2026
7c25f5b
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda Aug 5, 2026
142575a
Merge branch 'main' into feat/worktree-for-cli
bagatao-anaconda Aug 6, 2026
a8290bf
Merge branch 'main' into feat/worktree-for-cli
bagatao-anaconda Aug 6, 2026
b57cfdc
feat(cli): add kilo worktree create/list/remove commands and TUI alias
bagatao-anaconda Aug 6, 2026
aac78b2
Merge branch 'feat/worktree-for-cli' of github.com:Kilo-Org/kilocode …
bagatao-anaconda Aug 6, 2026
914b67e
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda Aug 6, 2026
e344cea
fix(cli): lazy-import @/worktree in worktree.ts to unblock cli-shutdo…
bagatao-anaconda Aug 6, 2026
7d74034
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda Aug 6, 2026
91747c0
docs: update worktree-for-cli changeset to cover create/list/remove a…
bagatao-anaconda Aug 6, 2026
8294c69
Merge branch 'main' into feat/worktree-for-cli
bagatao-anaconda Aug 7, 2026
b93b975
fix(cli): use Effect.tryPromise instead of Effect.promise for lazy @/…
bagatao-anaconda Aug 7, 2026
6f9f230
Merge branch 'feat/worktree-for-cli' of github.com:Kilo-Org/kilocode …
bagatao-anaconda Aug 7, 2026
8f70f8f
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
bagatao-anaconda Aug 7, 2026
0af6c2d
Merge branch 'main' into feat/worktree-for-cli
bagatao-anaconda Aug 12, 2026
6b2a716
Merge branch 'main' into feat/worktree-for-cli
bagatao-anaconda Aug 13, 2026
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
5 changes: 5 additions & 0 deletions .changeset/worktree-for-cli.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kilocode/cli": minor
---

Add `kilo --worktree <name>` to create (or reuse) a git worktree and start the TUI there, placed at `.kilo/worktrees/<name>` alongside worktrees created by the VS Code extension's Agent Manager. Also adds `kilo worktree create/list/remove` for managing worktrees without launching the TUI, and a `/worktree` command in the TUI to list and remove them. Resuming an explicit `--session <id>` now tries to restart in the worktree the session was originally created in, if it still exists.
16 changes: 15 additions & 1 deletion packages/opencode/src/cli/cmd/tui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,12 @@ export const TuiThreadCommand = cmd({
type: "boolean",
describe: "fetch session from cloud and continue locally (use with --session)",
})
// kilocode_change start - create/reuse a git worktree before starting
.option("worktree", {
type: "string",
describe: "create (or reuse) a git worktree with this name and start kilo there",
})
// kilocode_change end
.option("prompt", {
type: "string",
describe: "prompt to use",
Expand Down Expand Up @@ -262,6 +268,7 @@ export const TuiThreadCommand = cmd({
const { importCloudSession, localSessionID, validateCloudFork } = await import("@/kilocode/cloud-session")
const { KiloTuiThreadDaemon } = await import("@/kilocode/cli/cmd/tui/thread")
const { preload } = await import("@/kilocode/cli/cmd/tui")
const { resolveTuiDirectory } = await import("@/kilocode/cli/cmd/tui-worktree")
// kilocode_change end
const unguard = win32InstallCtrlCGuard()
const shutdown = {
Expand All @@ -286,7 +293,14 @@ export const TuiThreadCommand = cmd({

// Resolve relative --project paths from PWD, then use the real cwd after
// chdir so the thread and worker share the same directory key.
const next = resolveThreadDirectory(args.project)
// kilocode_change start - `--worktree <name>` creates/reuses a worktree; resuming
// an explicit `--session <id>` tries to restart in that session's worktree
const next = await resolveTuiDirectory(args, resolveThreadDirectory(args.project)).catch((error) => {
UI.error(errorMessage(error))
process.exitCode = 1
})
if (!next) return
// kilocode_change end
const file = await target()
// kilocode_change start
const preloads = preload(typeof KILO_WORKER_PATH !== "undefined", () =>
Expand Down
216 changes: 216 additions & 0 deletions packages/opencode/src/kilocode/cli/cmd/tui-worktree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
// kilocode_change - new file
// Supports `kilo --worktree <name>` (create/reuse a git worktree before the TUI
// starts, placed at `.kilo/worktrees/<name>` to match Agent Manager's own
// worktrees) and resuming an explicit `--session <id>` in the worktree it was
// created in.
import path from "path"
import type { Effect } from "effect"
import * as Log from "@opencode-ai/core/util/log"
import { UI } from "@/cli/ui"
import { Filesystem } from "@/util/filesystem"
import { errorMessage } from "@/util/error"

const log = Log.create({ service: "kilocode.tui-worktree" })

// Matches packages/kilo-vscode/src/agent-manager/WorktreeManager.ts's placement
// and its ensureGitExclude(), keeping `.kilo/worktrees/` out of `git status`.
const KILO_WORKTREE_DIR = ".kilo/worktrees"

// Exported for tests.
export async function ensureGitExclude(root: string) {
const excludePath = path.join(root, ".git", "info", "exclude")
const current = (await Filesystem.readText(excludePath).catch(() => "")).replace(/\s+$/, "")
if (current.includes(`${KILO_WORKTREE_DIR}/`)) return
const prefix = current ? `${current}\n\n` : ""
await Filesystem.write(excludePath, `${prefix}# Kilo Code agent worktrees\n${KILO_WORKTREE_DIR}/\n`).catch((err) =>
log.error("failed to update .git/info/exclude", { excludePath, err }),
)
}

function samePath(a: string, b: string) {
return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b
}

// Exported for tests.
export function slugify(name: string) {
return name
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
}

// `InstanceStore.Interface.provide` loads (and caches) the instance context and
// scopes an effect to it; this adds the AppRuntime execution plus a matching
// `disposeDirectory` once the caller is done with `root`.
async function withInstance<A>(
root: string,
fn: (run: <T>(effect: Effect.Effect<T, any, any>) => Promise<T>) => Promise<A>,
) {
const { AppRuntime } = await import("@/effect/app-runtime")
const { InstanceStore } = await import("@/project/instance-store")
const run = <T>(effect: Effect.Effect<T, any, any>) =>
AppRuntime.runPromise(InstanceStore.Service.use((store) => store.provide({ directory: root }, effect)))
try {
return await fn(run)
} finally {
await AppRuntime.runPromise(InstanceStore.Service.use((store) => store.disposeDirectory(root)))
}
}

type WaitResult = { ok: true } | { ok: false; message: string }

/** Waits for `directory`'s `worktree.setup.ready`/`worktree.failed` event (full
* readiness, not just checkout); `cancel()` drops the timer/listener early. */
function waitForWorktreeEvent(
bus: typeof import("@/bus/global").GlobalBus,
event: typeof import("@/worktree").Worktree.Event,
directory: string,
timeoutMs: number,
) {
const deferred = Promise.withResolvers<WaitResult>()
let handler = (_e: { directory?: string; payload?: any }) => {}
const cleanup = () => {
clearTimeout(timer)
bus.off("event", handler)
}
// Not `unref()`'d: it's the only thing keeping the launcher's event loop
// alive while waiting, so a collected timer would let it exit 0 on a stall.
const timer = setTimeout(() => {
cleanup()
deferred.resolve({ ok: false, message: "Timed out waiting for the worktree to finish setting up" })
}, timeoutMs)
handler = (e) => {
if (e.directory !== directory) return
if (e.payload?.type === event.SetupReady.type) {
cleanup()
deferred.resolve({ ok: true })
} else if (e.payload?.type === event.Failed.type) {
cleanup()
deferred.resolve({ ok: false, message: e.payload.properties?.message ?? "Worktree setup failed" })
}
}
bus.on("event", handler)
return { promise: deferred.promise, cancel: cleanup }
}

// Exported for `kilo worktree create` (worktree.ts), which calls this and
// exits instead of going on to launch the TUI.
export async function resolveWorktree(name: string, root: string, timeoutMs = 10 * 60_000) {
const { Worktree } = await import("@/worktree")
const { GlobalBus } = await import("@/bus/global")
const { InstanceState } = await import("@/effect/instance-state")
const { primaryWorktree } = await import("@/kilocode/primary-worktree")
const { Git } = await import("@/git")
const slug = slugify(name)
if (!slug) throw new Error(`Invalid worktree name "${name}"`)
return withInstance(root, async (run) => {
const ctx = await run(InstanceState.context)
// ctx.worktree is whichever checkout the command runs in. Creating under
// it unconditionally would nest `.kilo/worktrees/<name>` inside another
// worktree and branch off that worktree's HEAD instead of the primary
// checkout's — refuse rather than get this wrong.
const primary = await run(primaryWorktree(ctx.worktree))
if (primary && !samePath(primary, ctx.worktree))
throw new Error(
`Cannot create worktree "${slug}" from inside another worktree (${ctx.worktree}). Run this from the primary checkout at ${primary} instead.`,
)

const directory = path.join(ctx.worktree, KILO_WORKTREE_DIR, slug)
// Trust neither signal alone: a directory can exist without a live git
// registration (orphaned), and a registration can outlive its directory
// (deleted out-of-band, or pruned).
const registered = (await run(Worktree.Service.use((svc) => svc.list()))).some((w) =>
samePath(w.directory, directory),
)
const exists = await Filesystem.exists(directory)

if (registered && exists) {
// Assumes whatever created it already finished setting up; a worktree
// still booting when its own process was interrupted won't be detected.
UI.println(`Using existing worktree "${slug}" at ${directory}`)
return directory
}
if (exists) throw new Error(`"${directory}" already exists but is not a registered git worktree.`)
// Registered but missing: reclaim the dead registration (and its branch)
// the same way a fresh run would need to, so the name is free to reuse.
if (registered) {
await run(Worktree.Service.use((svc) => svc.remove({ directory }))).catch((error) => {
Comment thread
bagatao-anaconda marked this conversation as resolved.
throw new Error(`Failed to reclaim stale worktree "${slug}": ${errorMessage(error)}`)
})
}

// `createFromInfo` below passes `branch: slug` straight to `git worktree
// add -b`, which fails outright if that branch already exists — e.g. one
// left behind by `git worktree prune` (which drops the registration but
// never deletes the branch). Clear it first so the name can be reused, but
// only with `-d` (not `-D`): it refuses unless the branch is fully merged,
// so we never silently discard unmerged work from an interrupted worktree
// or an unrelated branch that happens to share the name.
const runGit = (args: string[]) => run(Git.Service.use((git) => git.run(args, { cwd: ctx.worktree })))
const branchRef = await runGit(["show-ref", "--verify", "--quiet", `refs/heads/${slug}`])
if (branchRef.exitCode === 0) {
Comment thread
bagatao-anaconda marked this conversation as resolved.
const deleted = await runGit(["branch", "-d", slug])
if (deleted.exitCode !== 0) {
const message = deleted.stderr.toString("utf8").trim() || deleted.text().trim()
throw new Error(
`Branch "${slug}" already exists${message ? ` (${message})` : ""}. Remove it (e.g. \`git branch -D ${slug}\` if you're sure it's safe to discard) and retry.`,
)
}
}

await ensureGitExclude(ctx.worktree)
UI.println(`Creating worktree "${slug}"...`)
const wait = waitForWorktreeEvent(GlobalBus, Worktree.Event, directory, timeoutMs)
await run(Worktree.Service.use((svc) => svc.createFromInfo({ name: slug, branch: slug, directory }))).catch(
Comment thread
bagatao-anaconda marked this conversation as resolved.
(error) => {
wait.cancel()
throw error
},
)
const result = await wait.promise
if (!result.ok) throw new Error(`Failed to create worktree "${slug}": ${result.message}`)
UI.println(`Worktree ready at ${directory}`)
return directory
})
}

// Reads only the session's `directory` column against a throwaway
// Database-only layer instead of the full AppRuntime (Plugin/LSP/MCP/Provider/
// Observability/etc), since `--session <id>` is common and shouldn't pay for
// bootstrapping the whole app graph in the launcher process just for this.
async function resolveSessionWorktree(sessionID: string, fallback: string) {
try {
const { Effect, Schema } = await import("effect")
const { Database } = await import("@opencode-ai/core/database/database")
const { SessionTable } = await import("@opencode-ai/core/session/sql")
const { eq } = await import("drizzle-orm")
const { SessionID } = await import("@/session/schema")
const id = Schema.decodeUnknownSync(SessionID)(sessionID)
const row = await Effect.runPromise(
Database.Service.use(({ db }) => db.select().from(SessionTable).where(eq(SessionTable.id, id)).get()).pipe(
Effect.provide(Database.layerFromPath(Database.path())),
),
)
const directory = row?.directory
if (!directory || directory === fallback) return fallback
if (!(await Filesystem.exists(directory))) return fallback
UI.println(`Resuming session in its original worktree: ${directory}`)
return directory
} catch {
// Unknown session, missing directory, or lookup failure: fall back to the
// resolved cwd and let normal session validation report the real error.
return fallback
}
}

/**
* Resolves the directory to launch the TUI in: creates/reuses `--worktree
* <name>`, or when resuming an explicit `--session <id>` without `--project`,
* tries that session's original worktree. Otherwise returns `root` unchanged.
*/
export function resolveTuiDirectory(args: { worktree?: string; session?: string; project?: string }, root: string) {
Comment thread
bagatao-anaconda marked this conversation as resolved.
if (args.worktree) return resolveWorktree(args.worktree, root)
if (args.session && !args.project) return resolveSessionWorktree(args.session, root)
return Promise.resolve(root)
}
99 changes: 99 additions & 0 deletions packages/opencode/src/kilocode/cli/cmd/worktree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// kilocode_change - new file
// `kilo worktree list`/`remove`: CLI-side counterpart to `kilo --worktree <name>`
// (tui-worktree.ts) and the TUI's `/worktree` alias for the workspaces dialog
// (packages/tui/src/app.tsx). All three go through the same `Worktree.Service`.
import path from "path"
import { Effect } from "effect"
import { cmd } from "@/cli/cmd/cmd"
import { CliError, effectCmd, fail } from "@/cli/effect-cmd"
import { UI } from "@/cli/ui"
import { errorMessage } from "@/util/error"
import { slugify } from "@/kilocode/cli/cmd/tui-worktree"

const wrapErr = (message: string) => <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(Effect.mapError((error) => new CliError({ message: `${message}: ${errorMessage(error)}` })))

// Lazy: this module is imported eagerly by KiloCli.register (see setup.ts), so
// `@/worktree`'s heavier transitive graph (Project, Provider, ...) must not
// load until a handler actually runs, matching tui-worktree.ts's own imports.
// `tryPromise` (not `promise`): a failed dynamic import must flow through each
// call site's own `wrapErr`, not become an unrecoverable defect.
const importWorktree = Effect.tryPromise(() => import("@/worktree"))

const listWorktrees = importWorktree.pipe(
Effect.flatMap(({ Worktree }) => Worktree.Service.use((svc) => svc.list())),
wrapErr("Failed to list worktrees"),
)

export const WorktreeCommand = cmd({
command: "worktree",
describe: "manage git worktrees",
builder: (yargs) =>
yargs.command(WorktreeCreateCommand).command(WorktreeListCommand).command(WorktreeRemoveCommand).demandCommand(),
async handler() {},
})

export const WorktreeCreateCommand = cmd({
command: "create <name>",
describe: "create (or reuse) a git worktree by name",
builder: (yargs) => yargs.positional("name", { type: "string", demandOption: true }),
async handler(args) {
// Plain cmd(), not effectCmd(): resolveWorktree loads/disposes its own
// instance context (it's shared with `kilo --worktree`'s pre-TUI-launch
// path in tui-worktree.ts), so it can't run inside effectCmd's own.
const { resolveWorktree } = await import("@/kilocode/cli/cmd/tui-worktree")
const directory = await resolveWorktree(args.name, process.cwd()).catch((error) => {
UI.error(errorMessage(error))
process.exitCode = 1
})
// Prints only the resolved path on stdout (status messages already went
// to stderr via resolveWorktree's own UI.println calls), so scripts can
// do e.g. `cd "$(kilo worktree create foo)"`.
if (directory) console.log(directory)
},
})

export const WorktreeListCommand = effectCmd({
command: "list",
describe: "list git worktrees for the current project",
handler: Effect.fn("Cli.worktree.list")(function* () {
const list = yield* listWorktrees
if (!list.length) {
UI.println("No worktrees found.")
return
}
// Data rows go to stdout (like `kilo session list`'s table/JSON), not
// UI.println's stderr, so `kilo worktree list | ...` actually captures them.
for (const w of list) console.log(`${w.name}${w.branch ? ` (${w.branch})` : ""} ${w.directory}`)
}),
})

export const WorktreeRemoveCommand = effectCmd({
command: "remove <name>",
// Worktree.Service.remove() force-deletes (`git branch -D`) the worktree's
// branch too, with no way to opt out (matches the TUI workspaces dialog's
// existing semantics) — make that explicit rather than surprise users.
describe: "remove a git worktree by name, deleting its branch too",
builder: (yargs) => yargs.positional("name", { type: "string", demandOption: true }),
handler: Effect.fn("Cli.worktree.remove")(function* (args) {
const slug = slugify(args.name)
if (!slug) {
yield* fail(`Invalid worktree name "${args.name}"`)
return
}
const list = yield* listWorktrees
// Matches the reuse logic in tui-worktree.ts: list() remaps `name` to the
// project ID when a worktree's basename collides with the primary
// checkout's, so also match on the directory basename.
const found = list.find((w) => w.name.toLowerCase() === slug || path.basename(w.directory).toLowerCase() === slug)
if (!found) {
yield* fail(`No worktree named "${args.name}" found.`)
return
}
const removeMsg = `Failed to remove worktree "${args.name}"`
const { Worktree } = yield* importWorktree.pipe(wrapErr(removeMsg))
yield* Worktree.Service.use((svc) => svc.remove({ directory: found.directory })).pipe(wrapErr(removeMsg))
const branchNote = found.branch ? ` and branch "${found.branch}"` : ""
UI.println(`Removed worktree "${found.name}" at ${found.directory}${branchNote}`)
}),
})
2 changes: 2 additions & 0 deletions packages/opencode/src/kilocode/cli/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { DaemonCommand } from "@/kilocode/cli/cmd/daemon"
import { DevSetupCommand, DevAliasCommand } from "@/kilocode/cli/dev-setup"
import { RemoteCommand } from "@/cli/cmd/remote"
import { ConfigCommand as ConfigCLICommand } from "@/cli/cmd/config"
import { WorktreeCommand } from "@/kilocode/cli/cmd/worktree"

const log = Log.create({ service: "kilocode.cli" })

Expand Down Expand Up @@ -56,6 +57,7 @@ export namespace KiloCli {
.command(RemoteCommand)
.command(DaemonCommand)
.command(ConfigCLICommand)
.command(WorktreeCommand)
if (InstallationBuildKind !== "release") cli.command(DevSetupCommand).command(DevAliasCommand)
// Safe self-reference: `cli` is a typed parameter and yargs `.command()` returns the same
// instance, so the help command can resolve the fully-built root at handler time. This also
Expand Down
12 changes: 12 additions & 0 deletions packages/opencode/src/worktree/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,18 @@ const layer: Layer.Layer<
})

yield* runStartScripts(info.directory, { projectID, extra })

// kilocode_change start - signal full readiness once setup also completes
GlobalBus.emit("event", {
directory: info.directory,
project: ctx.project.id,
workspace: workspaceID,
payload: {
type: Event.SetupReady.type,
properties: { name: info.name, ...(info.branch ? { branch: info.branch } : {}) },
},
})
// kilocode_change end
})

const createFromInfo = Effect.fn("Worktree.createFromInfo")(function* (info: Info, startCommand?: string) {
Expand Down
Loading
Loading