Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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…
brunoagatao Aug 3, 2026
fb5f410
fix(cli): prune stale worktree registrations and avoid full app boots…
brunoagatao Aug 3, 2026
8e13ede
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 3, 2026
2762d09
fix(cli): wait for worktree setup and align --worktree with Agent Man…
brunoagatao Aug 4, 2026
0d78791
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 4, 2026
627e24d
refactor(cli): tighten tui-worktree implementation and note reuse lim…
brunoagatao Aug 4, 2026
f3e93ec
fix(cli): don't force-delete pre-existing branches when reclaiming a …
brunoagatao Aug 5, 2026
e6214f7
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 5, 2026
90989d4
fix(cli): update tui-worktree to use Database.layerFromPath after ups…
brunoagatao Aug 5, 2026
4fdaa4c
refactor(cli): tighten tui-worktree, log exclude-write failures, fix …
brunoagatao Aug 5, 2026
7c25f5b
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 5, 2026
142575a
Merge branch 'main' into feat/worktree-for-cli
brunoagatao Aug 6, 2026
a8290bf
Merge branch 'main' into feat/worktree-for-cli
brunoagatao Aug 6, 2026
b57cfdc
feat(cli): add kilo worktree create/list/remove commands and TUI alias
brunoagatao Aug 6, 2026
aac78b2
Merge branch 'feat/worktree-for-cli' of github.com:Kilo-Org/kilocode …
brunoagatao Aug 6, 2026
914b67e
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 6, 2026
e344cea
fix(cli): lazy-import @/worktree in worktree.ts to unblock cli-shutdo…
brunoagatao Aug 6, 2026
7d74034
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 6, 2026
91747c0
docs: update worktree-for-cli changeset to cover create/list/remove a…
brunoagatao Aug 6, 2026
8294c69
Merge branch 'main' into feat/worktree-for-cli
brunoagatao Aug 7, 2026
b93b975
fix(cli): use Effect.tryPromise instead of Effect.promise for lazy @/…
brunoagatao Aug 7, 2026
6f9f230
Merge branch 'feat/worktree-for-cli' of github.com:Kilo-Org/kilocode …
brunoagatao Aug 7, 2026
8f70f8f
Merge remote-tracking branch 'origin/main' into feat/worktree-for-cli
brunoagatao Aug 7, 2026
0af6c2d
Merge branch 'main' into feat/worktree-for-cli
brunoagatao Aug 12, 2026
6b2a716
Merge branch 'main' into feat/worktree-for-cli
brunoagatao 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. 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 All @@ -182,6 +188,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 @@ -206,7 +213,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
183 changes: 183 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,183 @@
// 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 { UI } from "@/cli/ui"
import { Filesystem } from "@/util/filesystem"
import { errorMessage } from "@/util/error"

// Matches packages/kilo-vscode/src/agent-manager/WorktreeManager.ts's placement.
const KILO_WORKTREE_DIR = ".kilo/worktrees"

// Mirrors WorktreeManager.ts's ensureGitExclude(): keeps `.kilo/worktrees/`
// out of `git status` for repos Agent Manager hasn't touched yet.
// Exported for unit testing; not part of the module's public contract.
export async function ensureGitExclude(root: string) {
const excludePath = path.join(root, ".git", "info", "exclude")
const current = await Filesystem.readText(excludePath).catch(() => "")
if (current.includes(`${KILO_WORKTREE_DIR}/`)) return
const separator = current.length && !current.endsWith("\n") ? "\n" : ""
await Filesystem.write(
excludePath,
`${current}${separator}\n# Kilo Code agent worktrees\n${KILO_WORKTREE_DIR}/\n`,
).catch(() => {})
}

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

// Exported for unit testing; not part of the module's public contract.
export function slugify(name: string) {
return name
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
}

// `InstanceStore.Interface.provide` already loads the instance context and
// scopes an effect to it; this just adds the AppRuntime execution and 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>) {
Comment thread
brunoagatao marked this conversation as resolved.
Resolved
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), with a `cancel()` to drop the timer/listener
* on early failure. */
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)
}
// Intentionally not `unref()`'d: this timer is the timeout guarantee for a
// launcher process that has nothing else keeping the event loop alive, so
// letting it be collected would let the process exit 0 on a stalled boot.
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 }
}

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 slug = slugify(name)
if (!slug) throw new Error(`Invalid worktree name "${name}"`)
return withInstance(root, async (run) => {
const ctx = await run(InstanceState.context)
const directory = path.join(ctx.worktree, KILO_WORKTREE_DIR, slug)
Comment thread
brunoagatao marked this conversation as resolved.
Resolved

// 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).
const existing = await run(Worktree.Service.use((svc) => svc.list()))
const registered = existing.some((w) => samePath(w.directory, directory))
const exists = await Filesystem.exists(directory)

if (registered && exists) {
if (!(await Filesystem.exists(path.join(directory, ".git")))) {
throw new Error(`"${directory}" is registered but was never fully checked out. Remove it and retry.`)
}
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 `--worktree <name>` run would need to, so the name
// is free to reuse below.
if (registered) {
await run(Worktree.Service.use((svc) => svc.remove({ directory }))).catch((error) => {
Comment thread
brunoagatao marked this conversation as resolved.
Resolved
throw new Error(`Failed to reclaim stale worktree "${slug}": ${errorMessage(error)}`)
})
}

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
brunoagatao marked this conversation as resolved.
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.defaultLayer),
),
)
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
brunoagatao marked this conversation as resolved.
Resolved
if (args.worktree) return resolveWorktree(args.worktree, root)
if (args.session && !args.project) return resolveSessionWorktree(args.session, root)
return Promise.resolve(root)
}
18 changes: 18 additions & 0 deletions packages/opencode/src/worktree/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ export const Event = {
message: Schema.String,
},
}),
// kilocode_change start - fires after start scripts finish, unlike Ready
SetupReady: EventV2.define({
type: "worktree.setup.ready",
schema: { name: Schema.String, branch: Schema.optional(Schema.String) },
}),
// kilocode_change end
}

export const Info = Schema.Struct({
Expand Down Expand Up @@ -293,6 +299,18 @@ export 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
67 changes: 67 additions & 0 deletions packages/opencode/test/kilocode/cli/cmd/tui-worktree.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { describe, expect, test } from "bun:test"
import path from "path"
import { mkdtemp, rm } from "fs/promises"
import { tmpdir as osTmpdir } from "os"
import { ensureGitExclude, slugify } from "@/kilocode/cli/cmd/tui-worktree"
import { Filesystem } from "@/util/filesystem"

describe("slugify", () => {
test("lowercases and dashes non-alphanumeric runs", () => {
expect(slugify("My Feature!")).toBe("my-feature")
expect(slugify("fix_bug--123")).toBe("fix-bug-123")
})

test("trims leading/trailing dashes", () => {
expect(slugify("--hello--")).toBe("hello")
})

test("returns empty for names with no alphanumeric characters", () => {
expect(slugify("!!!")).toBe("")
expect(slugify(" ")).toBe("")
})
})

describe("ensureGitExclude", () => {
async function withRepo(fn: (root: string) => Promise<void>) {
const root = await mkdtemp(path.join(osTmpdir(), "tui-worktree-exclude-"))
try {
await fn(root)
} finally {
await rm(root, { recursive: true, force: true })
}
}

test("appends the exclude entry when the file exists but is empty", () =>
withRepo(async (root) => {
const excludePath = path.join(root, ".git", "info", "exclude")
await Filesystem.write(excludePath, "")
await ensureGitExclude(root)
const content = await Filesystem.readText(excludePath)
expect(content).toContain(".kilo/worktrees/")
}))

test("preserves existing content and adds a newline before the new entry", () =>
withRepo(async (root) => {
const excludePath = path.join(root, ".git", "info", "exclude")
await Filesystem.write(excludePath, "*.log")
await ensureGitExclude(root)
const content = await Filesystem.readText(excludePath)
expect(content).toContain("*.log")
expect(content).toContain(".kilo/worktrees/")
}))

test("is idempotent when the entry already exists", () =>
withRepo(async (root) => {
const excludePath = path.join(root, ".git", "info", "exclude")
await Filesystem.write(excludePath, "")
await ensureGitExclude(root)
await ensureGitExclude(root)
const content = await Filesystem.readText(excludePath)
expect(content.match(/\.kilo\/worktrees\//g)?.length).toBe(1)
}))

test("does not throw when .git/info is missing", () =>
withRepo(async (root) => {
await ensureGitExclude(root)
}))
})
Loading