Skip to content

feat(kimi-code): add -w, --worktree [name] flag for isolated sessions#818

Open
rrva wants to merge 34 commits into
MoonshotAI:mainfrom
rrva:feat/worktree-cli-flag
Open

feat(kimi-code): add -w, --worktree [name] flag for isolated sessions#818
rrva wants to merge 34 commits into
MoonshotAI:mainfrom
rrva:feat/worktree-cli-flag

Conversation

@rrva

@rrva rrva commented Jun 16, 2026

Copy link
Copy Markdown

Related Issue

Closes #828

Problem

Users running multiple Kimi Code sessions on the same repository need a way to avoid file conflicts and branch-switching overhead. The legacy Kimi CLI already supports this with a worktree flag, and users expect the same capability in Kimi Code CLI.

What changed

  • Added "-w, --worktree [name]" to create a new git worktree for the session.
  • New worktrees live under "/.kimi/worktrees/" with a detached HEAD checkout at the current HEAD.
  • Auto-generates a three-word slug name (e.g. amber-drifting-cloud) when no name is supplied.
  • Validates conflicts: --worktree cannot combine with --session or --continue.
  • Persists worktree_path and parent_repo_path in session metadata.
  • Cleans up the worktree on exit when the session is empty, so abandoned worktrees do not accumulate.
  • Added unit tests for the worktree utilities and CLI option parsing/conflict detection.
  • Updated CLI reference docs in English and Chinese.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue, or explained the problem above.
  • I have added tests that prove my feature works.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

Verification

  • pnpm --filter @moonshot-ai/kimi-code typecheck
  • pnpm --filter @moonshot-ai/kimi-code exec vitest run test/cli test/tui test/utils
  • pnpm exec oxlint --tsconfig=apps/kimi-code/tsconfig.json

Add a CLI flag that creates a new git worktree under
<repo-root>/.kimi/worktrees/<name> and runs the session inside it.
When no name is given, a kimi-<timestamp> name is generated. The
worktree is created in detached HEAD at the current HEAD.

- New worktree utility module with create/remove/list/find helpers.
- Conflict validation against --session and --continue.
- Persist worktree_path and parent_repo_path in session metadata.
- Clean up the worktree on exit when the session is empty.
- Add CLI parsing tests and worktree utility unit tests.

Inspired by the upstream kimi-cli worktree feature.
@changeset-bot

changeset-bot Bot commented Jun 16, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 7c4b24d

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 5 packages
Name Type
@moonshot-ai/agent-core Minor
@moonshot-ai/kimi-code Minor
@moonshot-ai/acp-adapter Patch
@moonshot-ai/migration-legacy Patch
@moonshot-ai/server Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b7db693578

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/kimi-code/src/utils/git/worktree.ts Outdated
Comment thread apps/kimi-code/src/utils/git/worktree.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 895e65e2de

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/kimi-code/src/main.ts Outdated
Comment thread apps/kimi-code/src/main.ts Outdated
rrva added 3 commits June 16, 2026 18:12
@rrva rrva force-pushed the feat/worktree-cli-flag branch from 895e65e to a74eb19 Compare June 16, 2026 16:12

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a74eb192b7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/kimi-code/src/main.ts Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ed15942c78

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/kimi-code/src/cli/run-shell.ts Outdated
Comment thread apps/kimi-code/src/main.ts Outdated
@rrva rrva force-pushed the feat/worktree-cli-flag branch from ed15942 to 91be1d7 Compare June 16, 2026 17:03

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 91be1d7b83

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/kimi-code/src/tui/kimi-tui.ts Outdated
- Keep .kimi/ out of the parent git index via .git/info/exclude.
- Preserve the caller's subdirectory when entering a worktree session.
- Delay worktree creation until after update preflight returns continue.
- Skip prompt-mode worktree cleanup on turn failures; leave worktrees inspectable.
- Track lifetime session content so /new does not delete earlier-session worktrees.
- Emit resume hints with cd '<worktree>' for worktree sessions.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6a86ada5cb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/kimi-code/src/tui/kimi-tui.ts
Comment thread apps/kimi-code/src/main.ts Outdated
Comment thread apps/kimi-code/src/cli/run-shell.ts Outdated
rrva added 2 commits June 16, 2026 19:25
When a user ran /new inside a worktree session, createSessionFromCurrentState()
did not pass the startup metadata, so the replacement session lost worktreePath
and parentRepoPath. The TUI then no longer surfaced worktree context in the
system prompt or subagents. Forward the startup metadata into replacement
sessions and add a test covering the /new path.
- Set everHadSessionContent when entries are appended/pushed and before the
  transcript is cleared, so /new after an earlier session does not delete the
  worktree.
- Fall back to the worktree root when the mirrored caller subdirectory does not
  exist in the detached worktree; clean up the worktree if chdir still fails.
- Use quoteShellArg for the cd path in worktree resume hints so paths with
  shell metacharacters are safe to paste.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4710074370

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/kimi-code/src/utils/git/worktree.ts Outdated
Comment thread apps/kimi-code/src/tui/kimi-tui.ts Outdated
- Resolve the worktree exclude via `git rev-parse --git-path info/exclude`
  instead of `--git-dir`. When the repo root is itself a linked worktree,
  `--git-dir` points at `.git/worktrees/<name>`, but Git reads the local
  exclude from the common git dir; the old path wrote `.kimi/` to a file Git
  never consults, so `git status` in the parent worktree still showed `?? .kimi/`.
- Carry the current/resumed session's worktree metadata into replacement
  sessions when startup metadata is absent. A worktree session resumed with
  `-r` (no `--worktree`) has undefined startup metadata, so `/new` previously
  dropped worktreePath/parentRepoPath and lost the worktree system-prompt
  context for agents/subagents.

Both paths gain regression tests (linked-worktree exclude resolution; resumed
session /new metadata carry-forward).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 42902f6c8d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

return;
}
const excludePath = resolve(repoRoot, excludePathResult.stdout);
const marker = '.kimi/';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Limit the local exclude to worktree storage

When a repository already has untracked .kimi content unrelated to these session worktrees, appending .kimi/ to the shared info/exclude hides the entire directory from git status for every checkout using this common git dir. Running kimi -w can therefore silently stop Git from reporting files the user may intend to add; exclude only the storage path such as .kimi/worktrees/ instead of the whole .kimi/ tree.

Useful? React with 👍 / 👎.

rrva added 8 commits June 17, 2026 10:42
Add a CLI flag that creates a new git worktree under
<repo-root>/.kimi/worktrees/<name> and runs the session inside it.
When no name is given, a kimi-<timestamp> name is generated. The
worktree is created in detached HEAD at the current HEAD.

- New worktree utility module with create/remove/list/find helpers.
- Conflict validation against --session and --continue.
- Persist worktree_path and parent_repo_path in session metadata.
- Clean up the worktree on exit when the session is empty.
- Add CLI parsing tests and worktree utility unit tests.

Inspired by the upstream kimi-cli worktree feature.
- Make prepareWorktree synchronous; it performs no async work.
- Log best-effort worktree cleanup failures instead of swallowing them.
- Keep .kimi/ out of the parent git index via .git/info/exclude.
- Preserve the caller's subdirectory when entering a worktree session.
- Delay worktree creation until after update preflight returns continue.
- Skip prompt-mode worktree cleanup on turn failures; leave worktrees inspectable.
- Track lifetime session content so /new does not delete earlier-session worktrees.
- Emit resume hints with cd '<worktree>' for worktree sessions.
When a user ran /new inside a worktree session, createSessionFromCurrentState()
did not pass the startup metadata, so the replacement session lost worktreePath
and parentRepoPath. The TUI then no longer surfaced worktree context in the
system prompt or subagents. Forward the startup metadata into replacement
sessions and add a test covering the /new path.
rrva and others added 5 commits June 17, 2026 10:42
- Set everHadSessionContent when entries are appended/pushed and before the
  transcript is cleared, so /new after an earlier session does not delete the
  worktree.
- Fall back to the worktree root when the mirrored caller subdirectory does not
  exist in the detached worktree; clean up the worktree if chdir still fails.
- Use quoteShellArg for the cd path in worktree resume hints so paths with
  shell metacharacters are safe to paste.
- Resolve the worktree exclude via `git rev-parse --git-path info/exclude`
  instead of `--git-dir`. When the repo root is itself a linked worktree,
  `--git-dir` points at `.git/worktrees/<name>`, but Git reads the local
  exclude from the common git dir; the old path wrote `.kimi/` to a file Git
  never consults, so `git status` in the parent worktree still showed `?? .kimi/`.
- Carry the current/resumed session's worktree metadata into replacement
  sessions when startup metadata is absent. A worktree session resumed with
  `-r` (no `--worktree`) has undefined startup metadata, so `/new` previously
  dropped worktreePath/parentRepoPath and lost the worktree system-prompt
  context for agents/subagents.

Both paths gain regression tests (linked-worktree exclude resolution; resumed
session /new metadata carry-forward).
Resolve conflicts in the CLI worktree flag vs. --add-dir work: keep both
the worktree (worktree/worktreePath/parentRepoPath, session metadata,
worktreeInfo prompt context) and add-dir (addDirs, additionalDirsInfo)
additions across cli options, run-prompt, kimi-tui session creation, the
agent profile and prepared system-prompt context.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Lq7uYgKb7JmZJyc9WaY1U5

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0379c3ad9c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/kimi-code/src/main.ts Outdated
// leaks. Print mode intentionally leaves the worktree inspectable even on
// failure, so we do not clean it up here.
if (
validated.uiMode !== 'print' &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clean up prompt worktrees before session creation

When kimi -w -p ... fails before runPrompt creates a session, for example because no model is configured and requireConfiguredModel throws, this condition skips cleanup solely because the mode is print. At that point there is no saved prompt session or output to inspect, so the empty registered worktree under .kimi/worktrees/ is left behind on every retry; only skip cleanup for print-mode failures after a prompt session has actually been created.

Useful? React with 👍 / 👎.

rrva and others added 7 commits June 23, 2026 14:03
# Conflicts:
#	packages/agent-core/src/profile/context.ts
#	packages/agent-core/src/session/index.ts
Reduce the worktree feature's contact with churn-heavy central files so
unrelated edits there stop colliding with this branch on merge.

- cli/worktree-runtime.ts: WorktreeRuntime + prepare/cleanup/metadata helpers.
  main.ts now only prepares the runtime, threads it to the runners, and cleans
  up on startup failure via a one-line hook.
- Stop mutating CLIOptions with runtime worktreePath/parentRepoPath. The live
  worktree is passed as an explicit execution context to runPrompt/runShell and
  on to the TUI (startup sessionMetadata), keeping options.ts about user input.
- cli/resume-hint.ts: single formatResumeCommand used by both runners.
- profile/worktree-info.ts: move getWorktreeInfoFromSessionMetadata out of
  profile/context.ts (today's conflict site) so AGENTS.md context changes and
  worktree parsing no longer share a file. Re-exported via the profile barrel,
  so session/index.ts and subagent-host.ts are unchanged.
- tui/session-worktree.ts: extract the worktree session-metadata helpers out of
  kimi-tui.ts.

No behavior change; typecheck, lint, and the affected runner/TUI/profile tests
pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016StL8FmeoycvbQQfbupec4
Two P2 findings from the PR MoonshotAI#818 review:

- Narrow the local git exclude from `.kimi/` to `.kimi/worktrees/`. The whole
  `.kimi/` directory was hidden from `git status`, which also silently hid
  unrelated untracked content another tool might keep there. The marker now
  covers only the worktree storage dir, so other `.kimi/` content stays visible
  while the parent checkout still ignores the worktrees.

- Clean up an empty worktree when `kimi -w -p` fails before a session is
  created. Print mode is documented to leave the worktree inspectable, but that
  only makes sense once a session exists; a pre-session failure (e.g. no model
  configured) previously leaked an empty registered worktree. runPrompt now
  reports session creation via an onSessionCreated hook so main.ts cleans up
  only pre-session failures and still preserves post-session worktrees.

Both verified end-to-end against the built CLI; full cli/tui/utils suites pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016StL8FmeoycvbQQfbupec4
# Conflicts:
#	apps/kimi-code/src/tui/kimi-tui.ts
# Conflicts:
#	apps/kimi-code/src/cli/run-shell.ts
# Conflicts:
#	apps/kimi-code/src/main.ts
#	apps/kimi-code/test/cli/main.test.ts
#	apps/kimi-code/test/cli/run-prompt.test.ts
#	packages/agent-core/src/session/index.ts
#	packages/agent-core/src/session/subagent-host.ts
@rrva

rrva commented Jul 1, 2026

Copy link
Copy Markdown
Author

@wbxl2000 wdyt?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: add -w, --worktree [name] flag for isolated sessions

1 participant