Skip to content

feat(cli): create worktrees on a per-workspace environment recipe - #17026

Open
aon wants to merge 1 commit into
stablyai:mainfrom
aon:feat/cli-worktree-create-recipe
Open

aon wants to merge 1 commit into
stablyai:mainfrom
aon:feat/cli-worktree-create-recipe

Conversation

@aon

@aon aon commented Aug 28, 2026 •

Copy link
Copy Markdown

ELI5

The app can already spin up a fresh VM for a workspace ("Run on"). Now the CLI can too, and deleting the workspace tears the VM down.

What Changed

orca worktree create --recipe <id> provisions the repo's environmentRecipes entry from orca.yaml and adopts the provisioned-root checkout it produces. worktree rm over RPC now runs the recipe destroy.

Why

Recipe provisioning was reachable only from the desktop composer, so an agent handing work off over the CLI could not target a per-workspace environment. Destroy lived in the renderer delete flow, which never runs for CLI or mobile removals — those leaked the VM.

Linked Issue

Fixes #17292

Visual Proof

N/A — CLI and RPC surface only, no UI change.

Testing

pnpm tc, pnpm run check:code-quality:changed, and the 63 unit tests across the four touched suites pass on macOS. Added an e2e spec that creates and removes a provisioned-root workspace over RPC.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Written with Claude Code (Opus).

Review

  • Cross-platform: no new platform branches; the recipe path is provisioned-root SSH only and reuses adoptProvisionedRootSshCheckout. Flag parsing and path handling are unchanged.
  • SSH / remote / local: recipeId is an optional param, so an older host ignores it. worktree.create --recipe and worktree.rm are now long-poll RPCs — rm unconditionally, which changes its transport classification for every caller, not just recipe workspaces.
  • Agents / integrations: --agent launches after adoption; a failed startup terminal degrades to a warning on the result instead of failing the create.
  • Performance: worktree.rm adds one showManagedWorktree lookup before removal to resolve the workspace id while the selector still maps.
  • Security: recipe scripts run on the host machine, gated by the repo's own orca.yaml plus the approved-plugin recipe list; diagnostics go through redactEphemeralVmRecipeDiagnosticText before surfacing.
  • UI: no renderer changes.

Author

X: @agustin_aon

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Recipe create and worktree.rm are classified as long-poll RPCs so provisioning (minutes) survives the 30 s socket idle timer. recipeId is an optional param, so older hosts ignore it rather than reject the call.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

`orca worktree create --recipe <id>` provisions the repo's
`environmentRecipes` entry from orca.yaml and adopts the resulting
provisioned-root checkout, mirroring the composer's "Run on" target.
`worktree rm` over RPC now runs the recipe destroy, which previously
only happened in the renderer delete flow.
@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds worktree create --recipe support for provisioned-root SSH recipes. The flow validates recipe requests, provisions an ephemeral runtime, registers and adopts the remote checkout, and persists workspace metadata. Workspace removal runs recipe cleanup and removes adopted projects. Recipe create and removal RPC calls use long-poll handling. CLI specifications, documentation, provenance fields, unit tests, and end-to-end tests are added.

Merge Risk: 🟠 High · up to 8c206

This change lets CLI/RPC workspace operations provision external VMs and remove their owning projects. If environment cleanup fails, the operation can still report success after local ownership is deleted, potentially stranding resources and preventing reliable recovery; the authorization boundary for these broader effects also needs explicit confirmation. The PR is not merge-ready without addressing or accepting these risks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.53% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 18 files. (2 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise, specific, and accurately describes the primary change: CLI support for creating worktrees with per-workspace environment recipes.
Description check ✅ Passed The description follows the repository template and covers the change, rationale, linked issue, testing, compatibility, security, performance, visual proof, AI disclosure, and checklist items.
Full details: Docstring Coverage

Explanation

Docstring coverage is 23.53% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 18 files. (2 skipped: 1 unsupported, 1 too large.)

  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.ts (1)

25278-25294: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Confirm the intent of the numeric-only forwarding for linked identifiers.

linkedIssue, linkedPR, linkedGitLabIssue, and linkedGitLabMR now forward only when the value is a number. An explicit null is no longer written to the new worktree metadata. This is safe on a create path, because absent metadata reads back as unlinked. The sibling fields linkedBitbucketPR, linkedAzureDevOpsPR, and linkedGiteaPR still use !== undefined, so the file now mixes two guard styles for the same class of field. Align the guards, or add a short comment stating why only these four are numeric-gated.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d09240ec-1ddb-4a65-9ea2-753d03cbe24f

📥 Commits

Reviewing files that changed from the base of the PR and between 94e7586 and 8c20641.

📒 Files selected for processing (20)
  • skill-guides/orca-cli.md
  • src/cli/bundled-skill-guides.ts
  • src/cli/handlers/worktree.ts
  • src/cli/specs/core.ts
  • src/cli/specs/worktree.ts
  • src/main/ephemeral-vm-recipe-workspace-create.test.ts
  • src/main/ephemeral-vm-recipe-workspace-create.ts
  • src/main/index.ts
  • src/main/ipc/repos/project-host-setup-handlers.ts
  • src/main/provisioned-root-ssh-adoption.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/worktree-create-schemas.ts
  • src/main/runtime/rpc/methods/worktree-rm-host-qualification.test.ts
  • src/main/runtime/rpc/methods/worktree.test.ts
  • src/main/runtime/rpc/methods/worktree.ts
  • src/main/runtime/runtime-rpc-long-poll-transport.test.ts
  • src/main/runtime/runtime-rpc.ts
  • tests/e2e/ephemeral-vm-provisioned-root-rpc-create.spec.ts
  • tests/e2e/ephemeral-vm-provisioned-root.spec.ts
  • tests/e2e/helpers/provisioned-root-recipe-repo.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +201 to +207
const recipeId = getOptionalStringFlag(flags, 'recipe')
if (recipeId && (flags.has('host') || flags.has('project-host-setup'))) {
throw new RuntimeClientError(
'invalid_argument',
'--recipe provisions its own environment; it cannot combine with --host or --project-host-setup.'
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject a supplied --recipe without a value.

When --recipe is empty or has no value, getOptionalStringFlag returns undefined. The handler then creates a normal workspace and can bypass the --host conflict check. Use getPresentStringFlag(flags, 'recipe') so an explicitly supplied invalid recipe flag fails.

Proposed fix
-    const recipeId = getOptionalStringFlag(flags, 'recipe')
+    const recipeId = getPresentStringFlag(flags, 'recipe')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const recipeId = getOptionalStringFlag(flags, 'recipe')
if (recipeId && (flags.has('host') || flags.has('project-host-setup'))) {
throw new RuntimeClientError(
'invalid_argument',
'--recipe provisions its own environment; it cannot combine with --host or --project-host-setup.'
)
}
const recipeId = getPresentStringFlag(flags, 'recipe')
if (recipeId && (flags.has('host') || flags.has('project-host-setup'))) {
throw new RuntimeClientError(
'invalid_argument',
'--recipe provisions its own environment; it cannot combine with --host or --project-host-setup.'
)
}

Comment on lines +227 to +245
const registration = await addRemoteRepoFromPath(deps.store, {
connectionId: sshTargetId,
remotePath: projectRoot,
kind: 'git'
})
if ('error' in registration) {
throw new Error(registration.error)
}
try {
const aligned = alignRepoWithRequestedProject(
deps.store,
registration.repo,
args.projectId,
'imported-existing-folder',
args.projectProviderIdentity
)
invalidateAuthorizedRootsCache()
deps.onRepoRegistered?.()
return { repo: aligned.repo }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Roll back a new repository registration after adoption failure.

registerProvisionedRootRepo discards registration.alreadyExisted. If adoptProvisionedRootSshCheckout fails after this function returns, the outer catch destroys the runtime and SSH target but leaves a newly registered remote repository in the store. Return the fresh-registration state or a rollback callback. Invoke it from the outer catch only for new registrations, and invalidate the authorized-roots cache after removal.

Comment on lines +29532 to +29572
async createManagedWorktreeOnRecipe(
args: Parameters<OrcaRuntimeService['createManagedWorktree']>[0] & { recipeId: string }
): Promise<CreateWorktreeResult> {
const createRecipeWorkspace = this.createProvisionedRootRecipeWorkspaceFn
if (!createRecipeWorkspace) {
throw new Error('Environment recipes are not supported by this Orca runtime.')
}
if (!this.store) {
throw new Error('runtime_unavailable')
}
if (args.sparseCheckout) {
throw new Error('Provisioned-root recipes do not support sparse checkout.')
}
const repo = await this.resolveRepoSelector(args.repoSelector)
if (isFolderRepo(repo)) {
throw new Error('Environment recipes require a git repository.')
}
if (repo.connectionId) {
throw new Error('Environment recipes run from a local repository checkout.')
}
const settings = this.store.getSettings()
if (args.startupAgent && !isTuiAgentEnabled(args.startupAgent, settings.disabledTuiAgents)) {
throw new Error('Selected agent is disabled. Choose an enabled agent before creating.')
}
const sanitizedName = sanitizeWorktreeName(args.name)
const username =
!args.branchNameOverride && settings.branchPrefix === 'git-username'
? await resolveLocalGitUsername(repo.path)
: ''
const branchName = await resolveCreateBranchName(
repo.path,
args.branchNameOverride,
sanitizedName,
settings,
username
)
const setupForRepo = getProjectHostSetupForRepo(this.listProjectHostSetups(), repo)
const project = this.listProjects().find((entry) => entry.id === setupForRepo.projectId)
const lineageInput =
args.lineage || args.comment ? { ...args.lineage, comment: args.comment } : undefined
const lineageResolution = await this.resolveLineageForWorktreeCreate(lineageInput)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Description: Check whether the recipe create path receives nameWasGenerated and whether retirement runs anywhere in it.
set -euo pipefail

rg -n 'createManagedWorktreeOnRecipe' --type=ts -C6
rg -n 'nameWasGenerated' --type=ts -C3
rg -n 'retireGeneratedWorktreeName' --type=ts -C3

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

set -euo pipefail
printf '%s\n' '--- relevant repository conventions ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print | sort
printf '%s\n' '--- changed method and nearby create path ---'
sed -n '29480,29670p' src/main/runtime/orca-runtime.ts
printf '%s\n' '--- nameWasGenerated references ---'
rg -n -C4 --glob '*.ts' 'nameWasGenerated|retireGeneratedWorktreeName|createManagedWorktreeOnRecipe' . || true
printf '%s\n' '--- RPC or CLI callers ---'
rg -n -C5 --glob '*.ts' 'createManagedWorktreeOnRecipe|createManagedWorktree\(' src || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

set -euo pipefail
printf '%s\n' '--- applicable conventions ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src.md
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src-main-daemon.md
printf '%s\n' '--- provisioned-root create caller ---'
sed -n '45,165p' src/renderer/src/store/slices/worktrees/create/create-worktree.ts
printf '%s\n' '--- recipe RPC dispatch ---'
rg -n -C8 --glob '*.ts' 'recipeId|createManagedWorktreeOnRecipe|provisionedRoot' src/main src/renderer/src/store/slices/worktrees/create
printf '%s\n' '--- retirement and candidate selection ---'
sed -n '190,245p' src/main/worktree-name-retirement.ts
rg -n -C5 --glob '*.ts' 'isGeneratedWorktreeCreateName|getGeneratedWorktreeCreateRetryCandidate|retiredNameRegistry|createRetiredNameLookup' src mobile

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

set -euo pipefail
printf '%s\n' '--- adoption handler and runtime handoff ---'
rg -n -C10 --glob '*.ts' 'adoptProvisionedRoot' src/main src/preload src/renderer | head -160
printf '%s\n' '--- generated-name retirement flow ---'
rg -n -C6 --glob '*.ts' 'function isGeneratedWorktreeCreateName|export function isGeneratedWorktreeCreateName|function getGeneratedWorktreeCreateRetryCandidate|export function getGeneratedWorktreeCreateRetryCandidate|retiredNames|retiredName' src mobile | head -240
printf '%s\n' '--- exact retirement implementation ---'
sed -n '200,240p' src/main/worktree-name-retirement.ts
printf '%s\n' '--- runtime create retirement setup ---'
sed -n '25510,25535p' src/main/runtime/orca-runtime.ts
sed -n '25842,25865p' src/main/runtime/orca-runtime.ts

Repository: stablyai/orca

Length of output: 37876


Retire generated workspace names for recipe creates.

The provisioned-root request forwards nameWasGenerated, but createManagedWorktreeOnRecipe never calls retireGeneratedWorktreeName after creation. A later generated-name create can reuse that name.

@tatwizard

Copy link
Copy Markdown

+1 for getting this merged. We're about to run per-workspace environments on boat.dev sandboxes, and we need to create them from the CLI, because our agents hand off work through orca worktree create. Right now that means provisioning by hand in the desktop app. The worktree rm destroy fix matters just as much to us: without it, every CLI teardown leaves a billed sandbox running.

The branch now conflicts with main and is about 4.4k commits behind. Would a maintainer be able to take a look once it's rebased? Happy to help test against a boat.dev recipe.

This branch has not been deployed

No deployments
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.

[Feature]: CLI cannot create a worktree on a per-workspace environment recipe

2 participants