refactor(cli): group workspace, terminal, and host owners (#41543)

This commit is contained in:
Neil
2026-11-12 05:07:58 -08:00
committed by GitHub
parent 16f71c87b8
commit 95a7ce652d
121 changed files with 824 additions and 1178 deletions
@@ -0,0 +1,37 @@
import type { RuntimeClient } from '../runtime/client'
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree/id'
import { WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities'
const FOLDER_SETUP_UNSUPPORTED_WARNING =
'Setup did not run: this host runs an older Orca without folder workspace setup. Update Orca on that host to run it.'
/** An older host makes folder workspaces without running setup; say so rather than imply it ran. */
export async function folderSetupUnsupportedWarning(
client: RuntimeClient,
worktreeId: string | undefined,
create: { setupDecision?: unknown; runHooks?: unknown }
): Promise<string | null> {
const setupRequested = create.setupDecision === 'run' || create.runHooks === true
if (!setupRequested || !worktreeId?.includes(FOLDER_WORKSPACE_INSTANCE_SEPARATOR)) {
return null
}
const status = await client.call<RuntimeStatus>('status.get').catch(() => null)
return status && !status.result.capabilities?.includes(WORKTREE_FOLDER_SETUP_RUNTIME_CAPABILITY)
? FOLDER_SETUP_UNSUPPORTED_WARNING
: null
}
/** Joins the warning onto a create result, so text output and --json both carry it. */
export async function withFolderSetupSupportWarning<
T extends { worktree?: { id?: string }; warning?: string }
>(
client: RuntimeClient,
result: T,
create: { setupDecision?: unknown; runHooks?: unknown }
): Promise<T> {
const warning = await folderSetupUnsupportedWarning(client, result.worktree?.id, create)
return warning
? { ...result, warning: result.warning ? `${result.warning} ${warning}` : warning }
: result
}
@@ -0,0 +1,162 @@
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import type {
RuntimeWorktreeRecord,
RuntimeWorktreeRemoveResult,
RuntimeWorktreeSetResult
} from '../../shared/runtime-worktree-contracts'
import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types'
import { FOLDER_WORKSPACE_UNIQUE_ID_MUTATION_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities'
import { folderIdOfSelector, folderWorkspaceKey } from '../../shared/workspace-scope'
import { formatWorktreeShow } from './workspace-format'
import { printResult } from '../command-result-output'
import { getOptionalStringFlag, getOptionalStringFlagAllowingEmpty } from '../flags'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
import { getWorktreeReadFlags } from './worktree-unread-flag'
type Flags = Map<string, string | boolean>
const LINK_FLAGS = ['issue', 'pr', 'linear-issue', 'gitlab-issue', 'gitlab-mr'] as const
/** Refuses, before any request, a flag that has no folder workspace meaning. */
function refuseFolderFlags(flags: Flags, refusals: readonly [string, string][]): void {
const refused = refusals.find(([flag]) => flags.has(flag))
if (refused) {
throw new RuntimeClientError('invalid_argument', `--${refused[0]} ${refused[1]}`)
}
}
async function showFolderWorkspace(
client: RuntimeClient,
folderId: string
): Promise<RuntimeRpcSuccess<{ worktree: RuntimeWorktreeRecord }>> {
return client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
worktree: folderWorkspaceKey(folderId),
matchFolderWorkspaces: true
})
}
/** Older Orcas edit the first folder that shares an id and delete every one, so they are refused before any change. */
async function assertUniqueIdMutationSupported(client: RuntimeClient): Promise<void> {
const status = await client.call<RuntimeStatus>('status.get')
if (
!status.result.capabilities?.includes(FOLDER_WORKSPACE_UNIQUE_ID_MUTATION_RUNTIME_CAPABILITY)
) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca cannot change folder workspaces from the CLI safely. Update Orca on the computer that owns the folder workspace. Nothing was changed.'
)
}
}
function folderGone(folderId: string): RuntimeClientError {
return new RuntimeClientError(
'selector_not_found',
`Folder workspace ${folderWorkspaceKey(folderId)} no longer exists. Run orca worktree ps --json to list workspaces.`
)
}
/** `worktree set` on a folder workspace, through the folder workspace update RPC. False for any other selector. */
export async function setIfFolderWorkspace(
client: RuntimeClient,
flags: Flags,
selector: string,
json: boolean
): Promise<boolean> {
const folderId = folderIdOfSelector(selector)
if (folderId === undefined) {
return false
}
printResult(await setFolderWorkspace(client, flags, folderId), json, formatWorktreeShow)
return true
}
async function setFolderWorkspace(
client: RuntimeClient,
flags: Flags,
folderId: string
): Promise<RuntimeRpcSuccess<RuntimeWorktreeSetResult>> {
const key = folderWorkspaceKey(folderId)
refuseFolderFlags(flags, [
[
'parent-worktree',
`does not apply: a folder workspace cannot have a parent. To nest a worktree under it, run orca worktree set --worktree <child> --parent-worktree ${key}.`
],
['no-parent', 'does not apply: a folder workspace never has a parent.'],
...LINK_FLAGS.map((flag): [string, string] => [
flag,
`does not apply to a folder workspace. Link it with orca reference add <url> --worktree ${key}.`
])
])
const displayName = getOptionalStringFlag(flags, 'display-name')
const comment = getOptionalStringFlagAllowingEmpty(flags, 'comment')
const workspaceStatus = getOptionalStringFlag(flags, 'workspace-status')
const { isUnread } = getWorktreeReadFlags(flags)
await assertUniqueIdMutationSupported(client)
const updated = await client.call<{ folderWorkspace: FolderWorkspace | null }>(
'folderWorkspace.update',
{
folderWorkspaceId: folderId,
requireUniqueId: true,
updates: {
...(displayName !== undefined ? { name: displayName } : {}),
...(comment !== undefined ? { comment } : {}),
...(workspaceStatus !== undefined ? { workspaceStatus } : {}),
...(isUnread !== undefined ? { isUnread } : {})
}
}
)
if (!updated.result.folderWorkspace) {
throw folderGone(folderId)
}
return showFolderWorkspace(client, folderId)
}
/** `worktree rm` on a folder workspace: Orca forgets it; the folder stays on disk. False for any other selector. */
export async function removeIfFolderWorkspace(
client: RuntimeClient,
flags: Flags,
selector: string,
json: boolean
): Promise<boolean> {
const folderId = folderIdOfSelector(selector)
if (folderId === undefined) {
return false
}
printResult(
await removeFolderWorkspace(client, flags, folderId),
json,
() => 'removed: true\nOrca no longer lists this folder workspace; the folder stays on disk.'
)
return true
}
async function removeFolderWorkspace(
client: RuntimeClient,
flags: Flags,
folderId: string
): Promise<RuntimeRpcSuccess<RuntimeWorktreeRemoveResult>> {
const noGit = 'does not apply: a folder workspace has no branch or archive hooks.'
refuseFolderFlags(flags, [
['delete-branch', noGit],
['run-hooks', noGit],
['allow-failed-archive-hook', noGit]
])
await assertUniqueIdMutationSupported(client)
const removal = await client.call<{ deleted: boolean }>('folderWorkspace.delete', {
folderWorkspaceId: folderId,
requireUniqueId: true
})
if (!removal.result.deleted) {
throw folderGone(folderId)
}
return { ...removal, result: { removed: true } }
}
export function refuseFolderWorkspaceActivation(folderId: string): never {
throw new RuntimeClientError(
'invalid_argument',
`Activating a folder workspace from the CLI is not supported yet. Open it from the Orca sidebar, or inspect it with orca worktree show --worktree ${folderWorkspaceKey(folderId)} --json.`
)
}
@@ -0,0 +1,291 @@
import { describe, expect, it, vi } from 'vitest'
const {
callMock,
runtimeClientConstructorMock,
serveOrcaAppMock,
getDefaultUserDataPathMock,
addEnvironmentFromPairingCodeMock,
listEnvironmentsMock,
spawnMock
} = vi.hoisted(() => ({
callMock: vi.fn(),
runtimeClientConstructorMock: vi.fn(),
serveOrcaAppMock: vi.fn(),
getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'),
addEnvironmentFromPairingCodeMock: vi.fn(),
listEnvironmentsMock: vi.fn(),
spawnMock: vi.fn()
}))
vi.mock('../runtime/client', async () => {
const { createRuntimeClientModuleMock } = await import('../index-test-harness.js')
return createRuntimeClientModuleMock({
callMock,
runtimeClientConstructorMock,
serveOrcaAppMock,
getDefaultUserDataPathMock
})
})
vi.mock('../runtime/metadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getDefaultUserDataPath: getDefaultUserDataPathMock
}))
vi.mock('../runtime/launch', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
serveOrcaApp: serveOrcaAppMock
}))
vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({
listEnvironments: listEnvironmentsMock
}))
vi.mock('child_process', async () => {
const { createChildProcessModuleMock } = await import('../index-test-harness.js')
return createChildProcessModuleMock(spawnMock)
})
import { main } from '../index'
import { useWorktreeAwarenessEnvironment } from '../index-test-harness'
import { RuntimeClientError } from '../runtime/types'
import { buildWorktree, okFixture } from '../test-fixtures'
const SAVED = [
{ id: 'srv-b', name: 'build-box' },
{ id: 'srv-c', name: 'gpu-box' }
].map((environment) => ({
...environment,
createdAt: 1,
updatedAt: 1,
lastUsedAt: null,
runtimeId: null,
endpoints: [],
preferredEndpointId: null
}))
const CROSS_MACHINE = 'worktree.lineage.crossMachine'
type Call = { environment: string; method: string; params: Record<string, unknown> }
type Answer = (call: Call) => unknown
/** Answers each request by the environment its client routes to; `local` is the caller's Orca. */
function serve(answer: Answer): Call[] {
const calls: Call[] = []
callMock.mockImplementation(async function (
this: { environmentSelector: string | null },
method: string,
params: Record<string, unknown> = {}
) {
const call = { environment: this.environmentSelector ?? 'local', method, params }
calls.push(call)
const result = answer(call)
if (result instanceof Error) {
throw result
}
if (result !== undefined) {
return okFixture(method, result)
}
if (method === 'status.get') {
return okFixture(method, { capabilities: [CROSS_MACHINE, 'worktree.set.folder-parent.v1'] })
}
if (method === 'worktree.create' || method === 'worktree.set') {
return okFixture(method, { worktree: buildWorktree('/srv/child', 'child', 'abc', 'repo-1') })
}
if (method === 'worktree.lineageList') {
return okFixture(method, { installationId: `install-${call.environment}` })
}
return okFixture(method, {})
})
return calls
}
const FOLDER_PARENT: Answer = ({ method, params }) =>
method === 'worktree.show' && params.worktree === 'folder:hub-a'
? { worktree: { id: 'folder:hub-a', path: '/Users/me/Projects Hub' } }
: undefined
const MUTATIONS = new Set(['worktree.create', 'worktree.set'])
async function run(args: string[], cwd = '/tmp/elsewhere') {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const err = vi.spyOn(console, 'error').mockImplementation(() => {})
const prior = process.exitCode
await main([...args, '--json'], cwd)
const exitCode = process.exitCode
process.exitCode = prior
const output = [...log.mock.calls, ...err.mock.calls].flat().join('\n')
log.mockRestore()
err.mockRestore()
return { exitCode, output }
}
describe('--parent-environment', () => {
useWorktreeAwarenessEnvironment({
callMock,
serveOrcaAppMock,
getDefaultUserDataPathMock,
addEnvironmentFromPairingCodeMock,
listEnvironmentsMock,
spawnMock
})
it('by default looks only in the child environment and says where it looked', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const calls = serve(({ method }) =>
method === 'worktree.set'
? new RuntimeClientError('LINEAGE_PARENT_NOT_FOUND', 'Parent not found.')
: undefined
)
const { exitCode, output } = await run([
'worktree',
'set',
'--environment',
'srv-b',
'--worktree',
'id:repo-1::/srv/child',
'--parent-worktree',
'folder:hub-a'
])
expect(exitCode).toBe(1)
const error = JSON.parse(output).error
expect(error.code).toBe('LINEAGE_PARENT_NOT_FOUND')
expect(error.data.environment).toBe('srv-b')
expect(error.data.nextSteps.join('\n')).toContain('--parent-environment')
expect(new Set(calls.map((call) => call.environment))).toEqual(new Set(['srv-b']))
})
it('refuses a caller-relative parent in another environment before any request', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const calls = serve(() => undefined)
const { output } = await run([
'worktree',
'create',
'--repo',
'id:repo-1',
'--name',
'child',
'--parent-environment',
'srv-b',
'--parent-worktree',
'current'
])
expect(JSON.parse(output).error.code).toBe('invalid_argument')
expect(calls).toEqual([])
})
it('refuses --parent-environment without a parent or with --no-parent', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const calls = serve(() => undefined)
for (const parentFlags of [['--no-parent'], []]) {
const { output } = await run([
'worktree',
'set',
'--worktree',
'id:repo-1::/srv/child',
'--parent-environment',
'srv-b',
...parentFlags
])
expect(JSON.parse(output).error.code).toBe('invalid_argument')
}
expect(calls).toEqual([])
})
it('fails each preflight before any mutating request', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const setOnB = (parentEnvironment: string) => [
'worktree',
'set',
'--environment',
'srv-b',
'--worktree',
'id:repo-1::/srv/child',
'--parent-environment',
parentEnvironment,
'--parent-worktree',
'folder:hub-a'
]
const cases: [string, string, Answer][] = [
['srv-z', 'environment_not_paired', FOLDER_PARENT],
[
'srv-c',
'environment_unavailable',
({ environment }) =>
environment === 'srv-c'
? new RuntimeClientError('remote_runtime_unavailable', 'Could not connect.')
: undefined
],
[
'local',
'incompatible_runtime',
(call) =>
call.method === 'status.get' && call.environment === 'srv-b'
? { capabilities: [] }
: FOLDER_PARENT(call)
],
[
'local',
'LINEAGE_PARENT_NOT_FOUND',
({ method }) =>
method === 'worktree.show'
? new RuntimeClientError('selector_not_found', 'No match.')
: undefined
]
]
for (const [parentEnvironment, code, answer] of cases) {
const calls = serve(answer)
const { output } = await run(setOnB(parentEnvironment))
expect(JSON.parse(output).error.code, parentEnvironment).toBe(code)
expect(calls.filter((call) => MUTATIONS.has(call.method))).toEqual([])
if (code === 'environment_not_paired') {
expect(calls).toEqual([])
}
}
})
it('names the searched environment and lists it when the parent is ambiguous', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const ambiguous = (code: string) =>
new RuntimeClientError(code, 'Several workspaces match name:B Ambiguous.', {
candidates: [{ selector: 'folder:one' }, { selector: 'folder:two' }],
nextSteps: ['Run `orca worktree ps --json` to compare the choices.']
})
const parent = ['--parent-worktree', 'name:B Ambiguous', '--parent-environment', 'srv-b']
const cases: [string[], Answer][] = [
// Same environment as the child: the runtime refuses the set or create.
[
['worktree', 'set', '--environment', 'srv-b', '--worktree', 'id:repo-1::/srv/child'],
({ method }) =>
method === 'worktree.set' ? ambiguous('LINEAGE_PARENT_AMBIGUOUS') : undefined
],
[
['worktree', 'create', '--environment', 'srv-b', '--repo', 'id:repo-1', '--name', 'c'],
({ method }) =>
method === 'worktree.create' ? ambiguous('LINEAGE_PARENT_AMBIGUOUS') : undefined
],
// Another environment: the lookup there finds several.
[
['worktree', 'set', '--worktree', 'id:repo-1::/tmp/child'],
({ environment, method }) =>
environment === 'srv-b' && method === 'worktree.show'
? ambiguous('selector_ambiguous')
: undefined
]
]
for (const [command, answer] of cases) {
serve(answer)
const { output } = await run([...command, ...parent])
const error = JSON.parse(output).error
expect(error.code, command[1]).toBe('LINEAGE_PARENT_AMBIGUOUS')
expect(error.data.environment).toBe('srv-b')
expect(error.data.candidates).toEqual([
{ selector: 'folder:one' },
{ selector: 'folder:two' }
])
expect(error.data.nextSteps).toEqual([
'Compare the choices with `orca worktree ps --environment srv-b --json`, then pass one as --parent-worktree.'
])
}
})
})
@@ -0,0 +1,47 @@
import { win32 } from 'node:path'
import type * as NodePath from 'node:path'
import { describe, expect, it, vi } from 'vitest'
// Exercise production UNC resolution on every CI host; keep matching and elections real.
vi.mock('node:path', async (importOriginal) => {
const actual = await importOriginal<typeof NodePath>()
return { ...actual, resolve: actual.win32.resolve }
})
import {
selectEnclosingRepoOnHost,
selectEnclosingWorktreeSelectionOnHost
} from '../workspace-selection/caller-host-worktree-selection'
import { buildWorktree } from '../test-fixtures'
import { toSshExecutionHostId } from '../../shared/execution-host'
const UPPER = String.raw`\\wsl.localhost\Ubuntu\home\Alice\App`
const LOWER = String.raw`\\wsl$\Ubuntu\home\alice\app`
const upper = buildWorktree(UPPER, 'main', 'abc', 'repo-a')
const lower = buildWorktree(LOWER, 'main', 'abc', 'repo-b')
describe('WSL enclosing selection with Windows path resolution on every platform', () => {
it('excludes case-distinct directories before caller preference in either order', () => {
for (const rows of [
[upper, lower],
[lower, upper]
]) {
for (const owner of [upper, lower]) {
for (const caller of [undefined, upper.id, lower.id]) {
const cwd = win32.join(owner.path, 'src')
expect(selectEnclosingWorktreeSelectionOnHost(rows, cwd, 'local', caller)).toEqual({
selector: `id:${owner.id}`,
worktreeId: owner.id
})
expect(selectEnclosingRepoOnHost(rows, cwd, 'local', caller)).toBe(owner.repoId)
}
}
}
const wrongDistro = { ...upper, path: UPPER.replace('Ubuntu', 'Debian') }
const wrongHost = { ...upper, hostId: toSshExecutionHostId('other') }
expect(
selectEnclosingWorktreeSelectionOnHost([wrongDistro, wrongHost], UPPER, 'local')
).toBeUndefined()
expect(selectEnclosingRepoOnHost([wrongDistro, wrongHost], UPPER, 'local')).toBeUndefined()
})
})
+299
View File
@@ -0,0 +1,299 @@
import { isUnresolvedOwnerHostId, parseExecutionHostId } from '../../shared/execution-host'
import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store'
import { parseWorkspaceKey } from '../../shared/workspace-scope'
import type { CrossStoreParentRef } from '../../shared/worktree/lineage-types'
import { LOCAL_ENVIRONMENT } from '../hosts/local-environment-selector'
import type { RuntimeClient } from '../runtime/client'
import { quoteCliCommandArgument } from '../shell-command-quote'
/** Which Orca answered: `local`, a saved environment, or a one-off pairing-code connection (id null). */
export type WorkspaceEnvironment = { id: string | null; name: string | null }
/** A copyable route to one workspace; `environment` is the exact `--environment` value. */
export type WorkspaceAddress = { environment: string; worktree: string; line: string }
export type AddressUnavailableReason =
| 'one-off-connection'
| 'unverifiable-row'
| 'duplicate-folder-id'
export type WorkspaceParentAnnotation = {
state: 'known' | 'unknown-environment'
selector: string
environment: WorkspaceEnvironment | null
address: WorkspaceAddress | null
}
export type WorkspaceAnnotation = {
environment: WorkspaceEnvironment
address: WorkspaceAddress | null
addressUnavailable?: AddressUnavailableReason
parent: WorkspaceParentAnnotation | null
}
/** The row facts an address needs, from a `worktree ps` row or a `worktree show` record. */
export type AddressableRow = {
id: string
hostId?: string | null
identityKey?: string
parentWorktreeId?: string | null
parentFolderKey?: string | null
crossStoreParent?: CrossStoreParentRef | null
}
export type AddressContext = {
environment: WorkspaceEnvironment
/** The caller's own store, read only when some row has a parent in another store. */
localInstallationId?: string
}
const LOCAL: WorkspaceEnvironment = { id: LOCAL_ENVIRONMENT, name: LOCAL_ENVIRONMENT }
/** The environment the client routes to; a saved route is named by its stored id and name. */
export function describeClientEnvironment(client: RuntimeClient): WorkspaceEnvironment {
if (!client.isRemote) {
return LOCAL
}
const selector = client.environmentSelector
if (!selector) {
return { id: null, name: null }
}
const saved = listEnvironments(client.userDataPath).find(
(environment) => environment.id === selector || environment.name === selector
)
return saved ? { id: saved.id, name: saved.name } : { id: selector, name: selector }
}
export async function readAddressContext(
client: RuntimeClient,
rows: readonly AddressableRow[],
readLocalInstallationId: () => Promise<string | undefined>
): Promise<AddressContext> {
const environment = describeClientEnvironment(client)
if (!rows.some((row) => row.crossStoreParent)) {
return { environment }
}
// Only the caller's own store is verified here; other environments are never dialed.
const localInstallationId = await readLocalInstallationId().catch(() => undefined)
return { environment, localInstallationId }
}
export function environmentLabel(environment: WorkspaceEnvironment | null): string {
return environment?.name ?? 'one-off connection'
}
function addressOf(environment: string, worktree: string): WorkspaceAddress {
return {
environment,
worktree,
line: `--environment ${quoteCliCommandArgument(environment)} --worktree ${quoteCliCommandArgument(worktree)}`
}
}
function folderIdOf(id: string): string | undefined {
const parsed = parseWorkspaceKey(id)
return parsed?.type === 'folder' ? parsed.folderWorkspaceId : undefined
}
/** A workspace key recorded on lineage, as the selector `--worktree` takes. */
function selectorOfWorkspaceKey(key: string): string {
const parsed = parseWorkspaceKey(key)
return parsed?.type === 'worktree' ? `id:${parsed.worktreeId}` : key
}
type Listing = {
rowsById: ReadonlyMap<string, readonly AddressableRow[]>
}
function listingOf(rows: readonly AddressableRow[]): Listing {
const rowsById = new Map<string, AddressableRow[]>()
for (const row of rows) {
rowsById.set(row.id, [...(rowsById.get(row.id) ?? []), row])
}
return { rowsById }
}
/** The selector naming this row alone in its environment, or why none can. */
function rowSelector(
row: AddressableRow,
listing: Listing
): { selector: string } | { unavailable: AddressUnavailableReason } {
const sharing = listing.rowsById.get(row.id)?.length ?? 1
if (isUnresolvedOwnerHostId(row.hostId)) {
return { unavailable: 'unverifiable-row' }
}
if (folderIdOf(row.id) !== undefined) {
return sharing > 1 ? { unavailable: 'duplicate-folder-id' } : { selector: row.id }
}
if (row.identityKey) {
return { selector: `identity:${row.identityKey}` }
}
const host = row.hostId ? parseExecutionHostId(row.hostId) : null
if (!host || sharing > 1) {
return { unavailable: 'unverifiable-row' }
}
return { selector: `id:${row.id}` }
}
function parentOf(
row: AddressableRow,
listing: Listing,
context: AddressContext
): WorkspaceParentAnnotation | null {
const route = context.environment.id
const sameEnvironment = (selector: string, parentRow?: AddressableRow) => {
const resolved = parentRow ? rowSelector(parentRow, listing) : { selector }
return {
state: 'known' as const,
selector,
environment: context.environment,
address: route && 'selector' in resolved ? addressOf(route, resolved.selector) : null
}
}
if (row.parentWorktreeId) {
// A worktree parent shares its child's host.
const parentRow = listing.rowsById
.get(row.parentWorktreeId)
?.find((candidate) => (candidate.hostId ?? null) === (row.hostId ?? null))
return sameEnvironment(`id:${row.parentWorktreeId}`, parentRow)
}
if (row.parentFolderKey) {
// A listed copy carries the duplicate-folder-id check, so a shared id gets no address.
return sameEnvironment(row.parentFolderKey, listing.rowsById.get(row.parentFolderKey)?.[0])
}
const ref = row.crossStoreParent
if (!ref) {
return null
}
const selector = selectorOfWorkspaceKey(ref.workspaceKey)
if (context.localInstallationId && ref.installationId === context.localInstallationId) {
return {
state: 'known',
selector,
environment: LOCAL,
address: addressOf(LOCAL_ENVIRONMENT, selector)
}
}
return { state: 'unknown-environment', selector, environment: null, address: null }
}
/** Annotations for every row of one listing, aligned by index. */
export function annotateWorkspaces(
rows: readonly AddressableRow[],
context: AddressContext
): WorkspaceAnnotation[] {
const listing = listingOf(rows)
return rows.map((row) => {
const parent = parentOf(row, listing, context)
const route = context.environment.id
if (!route) {
return {
environment: context.environment,
address: null,
addressUnavailable: 'one-off-connection',
parent
}
}
const selected = rowSelector(row, listing)
return 'selector' in selected
? { environment: context.environment, address: addressOf(route, selected.selector), parent }
: {
environment: context.environment,
address: null,
addressUnavailable: selected.unavailable,
parent
}
})
}
const UNAVAILABLE_TEXT: Record<AddressUnavailableReason, string> = {
'one-off-connection':
'unavailable (one-off pairing-code connection; save it with `orca environment add --name <name> --pairing-code <code>`)',
'unverifiable-row': "unavailable (this row's host or identity can't be verified)",
'duplicate-folder-id':
'unavailable (several folder workspaces share this id; remove one in the Orca app and add its folder again)'
}
/** `environment:` and `address:` lines, each on its own line. */
export function formatAddressLines(annotation: WorkspaceAnnotation): string {
return `\nenvironment: ${environmentLabel(annotation.environment)}\naddress: ${
annotation.address?.line ??
UNAVAILABLE_TEXT[annotation.addressUnavailable ?? 'unverifiable-row']
}`
}
/** The `parent:` line, naming the parent's environment when it differs from the row's. */
export function formatParentLine(annotation: WorkspaceAnnotation): string {
const { parent } = annotation
if (!parent) {
return ''
}
if (parent.state === 'unknown-environment') {
return `\nparent: ${parent.selector} environment=unknown (no verified route here)`
}
const differs = parent.environment?.id !== annotation.environment.id
return `\nparent: ${parent.selector}${differs ? ` environment=${environmentLabel(parent.environment)}` : ''}`
}
type PsRowFacts = {
worktreeId: string
hostId?: string | null
identity?: { key: string }
parentWorktreeId: string | null
workspaceLineage?: { parentWorkspaceKey: string } | null
crossStoreParent?: { parent: CrossStoreParentRef }
}
type ShowRecordFacts = {
id: string
hostId?: string | null
identity?: { key: string }
parentWorktreeId?: string | null
workspaceLineage?: { parentWorkspaceKey: string } | null
crossStoreLineage?: { parent: CrossStoreParentRef } | null
}
export function addressableOfPsRow(row: PsRowFacts): AddressableRow {
return {
id: row.worktreeId,
hostId: row.hostId,
identityKey: row.identity?.key,
parentWorktreeId: row.parentWorktreeId,
parentFolderKey: row.workspaceLineage?.parentWorkspaceKey ?? null,
crossStoreParent: row.crossStoreParent?.parent ?? null
}
}
export function addressableOfShowRecord(record: ShowRecordFacts): AddressableRow {
return {
id: record.id,
hostId: record.hostId,
identityKey: record.identity?.key,
parentWorktreeId: record.parentWorktreeId ?? null,
parentFolderKey: record.workspaceLineage?.parentWorkspaceKey ?? null,
crossStoreParent: record.crossStoreLineage?.parent ?? null
}
}
/** The JSON fields one row gains; `addressUnavailable` appears only beside a null address. */
export function annotationFields(annotation: WorkspaceAnnotation): WorkspaceAnnotation {
return {
environment: annotation.environment,
parent: annotation.parent,
address: annotation.address,
...(annotation.addressUnavailable ? { addressUnavailable: annotation.addressUnavailable } : {})
}
}
/** Annotates a listing answered by `client`; the caller's own store is read through `localClient`. */
export async function annotateListing(
client: RuntimeClient,
localClient: () => RuntimeClient,
rows: readonly AddressableRow[]
): Promise<WorkspaceAnnotation[]> {
const context = await readAddressContext(client, rows, async () => {
const response = await localClient().call<{ installationId?: string }>('worktree.lineageList')
return response.result.installationId
})
return annotateWorkspaces(rows, context).map(annotationFields)
}
+103
View File
@@ -0,0 +1,103 @@
import { formatAddressLines, formatParentLine, type WorkspaceAnnotation } from './workspace-address'
import type {
RuntimeWorktreeListResult,
RuntimeWorktreePsResult,
RuntimeWorktreeRecord
} from '../../shared/runtime-worktree-contracts'
import {
formatListingHostScope,
type WithAnnotatedHostScope
} from '../hosts/omitted-host-scope-selectors'
import { formatWorktreePsTerminalFields } from './worktree-ps-terminal-verdict'
import { formatWorktreePsProgramStatus } from './worktree-ps-program-status'
type AnnotatedPsRow = RuntimeWorktreePsResult['worktrees'][number] & Partial<WorkspaceAnnotation>
export function formatWorktreePs(
result: WithAnnotatedHostScope<
Omit<RuntimeWorktreePsResult, 'worktrees'> & { worktrees: AnnotatedPsRow[] }
>
): string {
const scope = formatListingHostScope(result.hostScope)
if (result.worktrees.length === 0) {
return `No worktrees found.\n${scope}`
}
const body = result.worktrees
.map(
(worktree) =>
`${worktree.repo} ${worktree.branch} host=${worktree.hostId ?? 'unverifiable'} ${formatWorktreePsTerminalFields(worktree)} unread:${worktree.unread ? 'yes' : 'no'}${formatWorktreePsProgramStatus(worktree.agents)}\n${worktree.path}${formatWorktreePsLocation(worktree)}${worktree.preview ? `\npreview: ${worktree.preview}` : ''}`
)
.join('\n\n')
const bodyWithScope = `${body}\n\n${scope}`
return result.truncated
? `${bodyWithScope}\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}`
: bodyWithScope
}
function formatWorktreePsLocation(worktree: AnnotatedPsRow): string {
const annotation = workspaceAnnotationOf(worktree)
return annotation
? `${formatParentLine(annotation)}${formatAddressLines(annotation)}`
: formatWorktreePsParent(worktree)
}
/** The parent line, in the sidebar's precedence: worktree, then folder workspace, then another machine. */
function formatWorktreePsParent(worktree: RuntimeWorktreePsResult['worktrees'][number]): string {
const parent =
worktree.parentWorktreeId ??
worktree.workspaceLineage?.parentWorkspaceKey ??
(worktree.crossStoreParent
? `${worktree.crossStoreParent.parent.workspaceKey} on another machine`
: null)
return parent ? `\nparent: ${parent}` : ''
}
export function formatWorktreeList(
result: WithAnnotatedHostScope<RuntimeWorktreeListResult>
): string {
const scope = formatListingHostScope(result.hostScope)
if (result.worktrees.length === 0) {
return `No worktrees found.\n${scope}`
}
const body = result.worktrees
.map((worktree) => {
const childCount = worktree.childWorktreeIds?.length ?? 0
return `${String(worktree.id)} ${String(worktree.branch)} host=${String(worktree.hostId ?? 'unverifiable')} ${String(worktree.path)}\ndisplayName: ${String(worktree.displayName ?? '')}\nparentWorktreeId: ${String(worktree.parentWorktreeId ?? 'null')}\nchildWorktreeIds: ${childCount > 0 ? worktree.childWorktreeIds.join(',') : '[]'}\nlinkedIssue: ${String(worktree.linkedIssue ?? 'null')}\ncomment: ${String(worktree.comment ?? '')}`
})
.join('\n\n')
const bodyWithScope = `${body}\n\n${scope}`
return result.truncated
? `${bodyWithScope}\ntruncated: showing ${result.worktrees.length} of ${result.totalCount}`
: bodyWithScope
}
const ANNOTATION_KEYS = new Set(['environment', 'address', 'addressUnavailable', 'parent'])
function workspaceAnnotationOf(record: Partial<WorkspaceAnnotation>): WorkspaceAnnotation | null {
const { environment, address, addressUnavailable, parent } = record
return environment
? {
environment,
address: address ?? null,
parent: parent ?? null,
...(addressUnavailable ? { addressUnavailable } : {})
}
: null
}
export function formatWorktreeShow(result: {
worktree: RuntimeWorktreeRecord & Partial<WorkspaceAnnotation>
}): string {
const worktree = result.worktree
const annotation = workspaceAnnotationOf(worktree)
const fields = Object.entries(worktree)
.filter(([key]) => !annotation || !ANNOTATION_KEYS.has(key))
.map(
([key, value]) =>
`${key}: ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`
)
.join('\n')
return annotation
? `${fields}${formatParentLine(annotation)}${formatAddressLines(annotation)}`
: fields
}
+22
View File
@@ -0,0 +1,22 @@
import type { CommandHandler } from '../dispatch'
import { printResult } from '../command-result-output'
import { getRequiredWorktreeSelector } from '../workspace-selection/workspace-selector'
import { folderIdOfSelector } from '../../shared/workspace-scope'
import { refuseFolderWorkspaceActivation } from './folder-workspace-mutations'
export const WORKTREE_ACTIVATE_HANDLERS: Record<string, CommandHandler> = {
// Opening a workspace is the request that wakes a sleeping recipe VM behind it (#36923).
'worktree activate': async ({ flags, client, cwd, json }) => {
const worktree = await getRequiredWorktreeSelector(flags, 'worktree', cwd, client)
const folderId = folderIdOfSelector(worktree)
if (folderId !== undefined) {
refuseFolderWorkspaceActivation(folderId)
}
const result = await client.call<{ worktreeId: string }>('worktree.activate', {
worktree,
// A paired caller's default is its own view; the CLI opens the workspace on its host.
navigation: 'host'
})
printResult(result, json, ({ worktreeId }) => `Activated ${worktreeId}`)
}
}
@@ -0,0 +1,33 @@
import type {
RuntimeWorktreePsSummary,
RuntimeWorktreeRecord
} from '../../shared/runtime-worktree-contracts'
import type { RuntimeClient } from '../runtime/client'
import { addressableOfPsRow, addressableOfShowRecord, annotateListing } from './workspace-address'
import { callerOrcaClient } from './worktree-parent-fields'
/** Annotates `worktree ps` rows; the returned function applies them to any rows aligned by index. */
export async function annotatePsRows(
client: RuntimeClient,
rows: readonly RuntimeWorktreePsSummary[]
): Promise<<Row>(aligned: Row[]) => Row[]> {
const annotations = await annotateListing(
client,
() => callerOrcaClient(client),
rows.map(addressableOfPsRow)
)
return (aligned) => aligned.map((row, index) => ({ ...row, ...annotations[index] }))
}
/** A `worktree show` record with its environment, address and parent. */
export async function annotateShown<
Response extends { result: { worktree: RuntimeWorktreeRecord } }
>(client: RuntimeClient, response: Response): Promise<Response> {
const [annotation] = await annotateListing(client, () => callerOrcaClient(client), [
addressableOfShowRecord(response.result.worktree)
])
return {
...response,
result: { ...response.result, worktree: { ...response.result.worktree, ...annotation } }
}
}
@@ -0,0 +1,151 @@
// Use agent.launch for surface/model/effort; older hosts fall back to the create startup terminal.
import {
folderSetupUnsupportedWarning,
withFolderSetupSupportWarning
} from './folder-setup-support-warning'
import type { AgentLaunchResult } from '../../shared/agent-launch/contracts/agent-launch-intent'
import {
AGENT_LAUNCH_LOCAL_PRESENTATION_RUNTIME_CAPABILITY,
AGENT_LAUNCH_PROMPT_CARRY_RUNTIME_CAPABILITY
} from '../../shared/agent-launch/contracts/agent-launch-runtime-capability'
import type {
RuntimeWorktreeCreateResult,
RuntimeWorktreeRecord
} from '../../shared/runtime-worktree-contracts'
import {
callAgentLaunch,
formatAgentLaunch,
hasLaunchModelFlags,
getAgentLaunchCapabilities,
type CliAgentLaunch,
SURFACE_UNSUPPORTED_MESSAGE
} from '../agents/agent-launch-request'
import { formatWorktreeShow } from './workspace-format'
import { printResult } from '../command-result-output'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import { printLineageSummary } from './worktree-lineage-summary'
import { printHookWarning } from './worktree-removal-warnings'
import { withSetupDecisionRecovery } from './worktree-setup-decision-recovery'
import { withCliAgentLaunchRecovery } from '../agents/agent-launch-recovery'
type WorktreeAgentLaunchResult = Pick<
RuntimeWorktreeCreateResult,
'lineage' | 'workspaceLineage' | 'crossStoreLineage'
> & {
/** Absent only when the host could not show the worktree it just created. */
worktree?: RuntimeWorktreeRecord
launch: AgentLaunchResult
}
export async function createWorktreeWithAgent(args: {
client: RuntimeClient
flags: Map<string, string | boolean>
create: Record<string, unknown>
launch: CliAgentLaunch
json: boolean
rawArgs?: readonly string[]
}): Promise<void> {
const { client, flags, create, launch, json, rawArgs } = args
const capabilities = await getAgentLaunchCapabilities(client)
if (
!capabilities?.includes(AGENT_LAUNCH_LOCAL_PRESENTATION_RUNTIME_CAPABILITY) ||
(launch.prompt && !capabilities.includes(AGENT_LAUNCH_PROMPT_CARRY_RUNTIME_CAPABILITY))
) {
if (launch.operationId) {
throw new RuntimeClientError(
'agent_session_operation_unknown',
'This host cannot replay the earlier launch. Return to the original execution host; do not retry without --retry-launch.'
)
}
if (hasLaunchModelFlags(flags)) {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca host cannot start an agent on a chosen model or effort. Update Orca on the execution host, or omit --model and --effort.'
)
}
if (launch.surface) {
throw new RuntimeClientError('incompatible_runtime', SURFACE_UNSUPPORTED_MESSAGE)
}
const params = {
...create,
startupAgent: launch.agent,
startupPrompt: launch.prompt?.text ?? '',
launchSource: 'cli'
}
const response = await withSetupDecisionRecovery(
withCliAgentLaunchRecovery(
client.call<RuntimeWorktreeCreateResult>('worktree.create', params),
{
rawArgs,
params
}
)
)
const created = {
...response,
result: await withFolderSetupSupportWarning(client, response.result, create)
}
printHookWarning(created.result, json)
printLineageSummary(created.result, json)
printResult(created, json, formatWorktreeShow)
return
}
const launched = await withSetupDecisionRecovery(
callAgentLaunch(
client,
launch,
{
target: { kind: 'create-worktree', create },
presentation: create.activate === true ? 'focused' : 'background'
},
capabilities,
rawArgs
),
launch.operationId !== undefined
)
const worktree = await showLaunchedWorktree(client, launched.result.worktreeId)
const setupWarning = await folderSetupUnsupportedWarning(
client,
launched.result.worktreeId,
create
)
if (setupWarning) {
// stderr keeps --json output parseable while still reporting the skipped setup.
console.error(`warning: ${setupWarning}`)
}
const result: WorktreeAgentLaunchResult = {
...(worktree
? {
worktree,
lineage: worktree.lineage,
workspaceLineage: worktree.workspaceLineage ?? null,
crossStoreLineage: worktree.crossStoreLineage ?? null
}
: { lineage: null }),
launch: launched.result
}
printLineageSummary(result, json)
printResult({ ...launched, result }, json, (value) =>
[
...(value.worktree ? [formatWorktreeShow({ worktree: value.worktree })] : []),
formatAgentLaunch(value.launch)
].join('\n')
)
}
/** Reporting, never a reason to fail: the agent already runs, and a retry would start a second. */
async function showLaunchedWorktree(
client: RuntimeClient,
worktreeId: string
): Promise<RuntimeWorktreeRecord | undefined> {
try {
const shown = await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
worktree: `id:${worktreeId}`
})
return shown.result.worktree
} catch {
return undefined
}
}
@@ -0,0 +1,82 @@
import { isWorkspaceKey, worktreeWorkspaceKey } from '../../shared/workspace-scope'
import { getOptionalStringFlag } from '../flags'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import { getOptionalParentSelector } from '../workspace-selection/caller-folder-workspace'
import { resolveParentEnvironment, type ParentEnvironment } from './worktree-parent-environment'
export type CreateParentSelector = {
parentWorktree?: string
parentWorkspace?: string
/** The parent is in another environment than the child, resolved there and sent as a ref. */
parentEnvironment?: ParentEnvironment
}
const CREATE_PARENT_CONFLICT_MESSAGE = 'Choose either one parent selector or --no-parent.'
export function assertWorktreeParentFlagsCompatible(
flags: Map<string, string | boolean>,
conflictMessage: string = CREATE_PARENT_CONFLICT_MESSAGE
): void {
if (flags.has('parent-worktree') && flags.get('no-parent') === true) {
throw new RuntimeClientError('invalid_argument', conflictMessage)
}
const parentWorktree = flags.get('parent-worktree')
if (
flags.has('parent-worktree') &&
(typeof parentWorktree !== 'string' || parentWorktree === '')
) {
throw new RuntimeClientError('invalid_argument', 'Missing required --parent-worktree')
}
}
export function getWorkspaceKeyParentSelector(selector: string): string | undefined {
const rawSelector = selector.startsWith('id:') ? selector.slice('id:'.length) : selector
return isWorkspaceKey(rawSelector) ? rawSelector : undefined
}
export async function resolveCreateParentSelector(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<CreateParentSelector> {
const parentEnvironment = resolveParentEnvironment(flags, client)
const rawParentWorktree = getOptionalStringFlag(flags, 'parent-worktree')
if (!rawParentWorktree) {
return {}
}
if (parentEnvironment) {
return { parentWorktree: rawParentWorktree, parentEnvironment }
}
const parentWorkspace = getWorkspaceKeyParentSelector(rawParentWorktree)
if (parentWorkspace) {
// The public parent flag can name either kind; runtime workspace keys preserve folder lineage.
return { parentWorkspace }
}
const parentWorktree = await getOptionalParentSelector(flags, cwd, client)
const resolvedParentWorkspace = parentWorktree
? getWorkspaceKeyParentSelector(parentWorktree)
: undefined
if (resolvedParentWorkspace) {
// active/current can resolve to a folder workspace.
return { parentWorkspace: resolvedParentWorkspace }
}
return {
parentWorktree
}
}
export function getEnvParentWorkspace(): string | undefined {
const workspaceId = process.env.ORCA_WORKSPACE_ID
if (typeof workspaceId === 'string' && isWorkspaceKey(workspaceId)) {
return workspaceId
}
const worktreeId = process.env.ORCA_WORKTREE_ID
if (typeof worktreeId === 'string' && worktreeId.length > 0) {
return isWorkspaceKey(worktreeId) ? worktreeId : worktreeWorkspaceKey(worktreeId)
}
return undefined
}
@@ -0,0 +1,55 @@
import { parseRemoteProjectRefCandidate } from '../../main/gitlab/projects/project-ref-parser'
import type { Repo } from '../../shared/repo-types'
import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts'
import { parseGitLabIssueOrMRLink, type ProjectSlug } from '../../shared/new-workspace/gitlab-links'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import type { CliRepoTarget } from './worktree-project-target'
export async function assertGitLabLinkFlagProjectsMatch(
flags: Map<string, string | boolean>,
client: RuntimeClient,
target: CliRepoTarget | { worktree: string }
): Promise<void> {
const projects = ['gitlab-issue', 'gitlab-mr'].flatMap((name) => {
const value = flags.get(name)
const link =
typeof value === 'string' && /^https?:\/\//i.test(value.trim())
? parseGitLabIssueOrMRLink(value)
: null
return link ? [link.slug] : []
})
if (projects.length === 0) {
return
}
let project: ProjectSlug | null = null
let repoTarget: CliRepoTarget
if ('worktree' in target) {
const result = await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', target)
const context = result.result.worktree.linkedTaskSourceContext
const identity = context?.providerIdentity
if (context?.provider === 'gitlab' && identity?.provider === 'gitlab' && identity.webUrl) {
project = parseRemoteProjectRefCandidate(identity.webUrl)
}
repoTarget = { repo: `id:${result.result.worktree.repoId}` }
} else {
repoTarget = target
}
if (!project) {
const result = await client.call<{ repo: Repo }>('repo.show', repoTarget)
const remoteUrl = result.result.repo.gitRemoteIdentity?.remoteUrl
project = remoteUrl ? parseRemoteProjectRefCandidate(remoteUrl) : null
}
// Numeric slots cannot retain a pasted URL's foreign host or project.
if (
!project ||
projects.some((link) => link.host !== project.host || link.path !== project.path)
) {
throw new RuntimeClientError(
'invalid_argument',
'The GitLab URL must match the workspace source project or the repository’s stored remote. Use a number for an item in that project; URLs cannot choose a different project.'
)
}
}
@@ -0,0 +1,65 @@
import { parseGitLabIssueOrMRLink } from '../../shared/new-workspace/gitlab-links'
import { RuntimeClientError } from '../runtime/types'
import { getOptionalWorktreeLinkFlagValue } from './worktree-link-flag-value'
export type GitLabLinkKind = 'issue' | 'mr'
const FLAG_BY_KIND: Record<GitLabLinkKind, string> = {
issue: 'gitlab-issue',
mr: 'gitlab-mr'
}
// GitLab issues and merge requests have separate number namespaces.
const PREFIX_BY_KIND: Record<GitLabLinkKind, string> = {
issue: '#',
mr: '!'
}
function parseNumericReference(input: string, kind: GitLabLinkKind): number | null {
const wrongPrefix = PREFIX_BY_KIND[kind === 'issue' ? 'mr' : 'issue']
if (input.startsWith(wrongPrefix)) {
return null
}
const digits = input.startsWith(PREFIX_BY_KIND[kind]) ? input.slice(1) : input
if (!/^\d+$/.test(digits)) {
return null
}
const parsed = Number.parseInt(digits, 10)
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null
}
export function getOptionalGitLabLinkFlag(
flags: Map<string, string | boolean>,
kind: GitLabLinkKind,
options: { allowNull?: boolean } = {}
): number | null | undefined {
const name = FLAG_BY_KIND[kind]
const value = getOptionalWorktreeLinkFlagValue(flags, name, {
...options,
createHint: `a GitLab ${kind === 'issue' ? 'issue' : 'merge request'} number or URL`
})
if (value == null) {
return value
}
const trimmed = value.trim()
if (/^https?:\/\//i.test(trimmed)) {
const link = parseGitLabIssueOrMRLink(trimmed)
if (link?.type === kind && Number.isSafeInteger(link.number) && link.number > 0) {
return link.number
}
throw new RuntimeClientError('invalid_argument', badValueMessage(name, kind))
}
const number = parseNumericReference(trimmed, kind)
if (number === null) {
throw new RuntimeClientError('invalid_argument', badValueMessage(name, kind))
}
return number
}
function badValueMessage(name: string, kind: GitLabLinkKind): string {
return kind === 'issue'
? `Pass a GitLab issue number like 42 or #42, a GitLab issue URL, or null to clear --${name}.`
: `Pass a GitLab merge request number like 42 or !42, a GitLab merge request URL, or null to clear --${name}.`
}
@@ -0,0 +1,22 @@
import type { HandlerGroup } from '../handler-group-manifest'
export const WORKTREE_HANDLER_GROUPS: readonly HandlerGroup[] = [
{
name: 'worktree',
keys: [
'worktree ps',
'worktree list',
'worktree show',
'worktree current',
'worktree create',
'worktree set',
'worktree rm'
],
load: async () => (await import('./worktree.js')).WORKTREE_HANDLERS
},
{
name: 'worktree-activate',
keys: ['worktree activate'],
load: async () => (await import('./worktree-activate.js')).WORKTREE_ACTIVATE_HANDLERS
}
]
@@ -0,0 +1,80 @@
import type {
RuntimeWorktreeCreateResult,
RuntimeWorktreeRecord
} from '../../shared/runtime-worktree-contracts'
function getLineageSourceLabel(source: string): string {
switch (source) {
case 'terminal-context':
return 'terminal'
case 'cwd-context':
return 'cwd'
case 'orchestration-context':
return 'orchestration'
case 'env-workspace':
return 'environment'
case 'explicit-cli-flag':
return 'explicit flag'
case 'active-workspace':
return 'active context'
default:
return 'manual action'
}
}
/** The summary line for a parent saved in another Orca store. */
export function formatCrossStoreParentLine(
lineage: NonNullable<RuntimeWorktreeCreateResult['crossStoreLineage']>
): string {
return `parent: ${lineage.parent.workspaceKey} on another machine (${lineage.capture.confidence} from ${getLineageSourceLabel(lineage.capture.source)})`
}
export function formatFolderParentLine(
lineage: NonNullable<RuntimeWorktreeCreateResult['workspaceLineage']>
): string {
return `parent: ${lineage.parentWorkspaceKey} (folder workspace)`
}
/** The parent `worktree set` attached; same-store lineage fields stay null for both kinds. */
export function printSetParentLine(
worktree: RuntimeWorktreeRecord,
parentFields: { crossStoreParent?: unknown; parentWorktree?: string }
): void {
if (parentFields.crossStoreParent && worktree.crossStoreLineage) {
console.error(formatCrossStoreParentLine(worktree.crossStoreLineage))
} else if (parentFields.parentWorktree && worktree.workspaceLineage) {
console.error(formatFolderParentLine(worktree.workspaceLineage))
}
}
export function printLineageSummary(
result: Pick<RuntimeWorktreeCreateResult, 'lineage' | 'workspaceLineage'> &
Partial<Pick<RuntimeWorktreeCreateResult, 'warnings' | 'crossStoreLineage'>>,
json: boolean
): void {
if (json) {
return
}
for (const warning of result.warnings ?? []) {
console.error(`warning: ${warning.message}`)
}
if (result.crossStoreLineage) {
console.error(formatCrossStoreParentLine(result.crossStoreLineage))
return
}
if (result.workspaceLineage) {
const { parentWorkspaceKey, capture } = result.workspaceLineage
console.error(
`parent: ${parentWorkspaceKey} (${capture.confidence} from ${getLineageSourceLabel(capture.source)})`
)
return
}
if (result.lineage) {
const { parentWorktreeId, capture } = result.lineage
console.error(
`parent: ${parentWorktreeId} (${capture.confidence} from ${getLineageSourceLabel(capture.source)})`
)
return
}
console.error('parent: none')
}
@@ -0,0 +1,36 @@
import {
buildLinearIssueLinkUpdates,
LINEAR_ISSUE_LINK_CLEARED,
type LinearIssueLinkUpdates
} from '../../shared/linear/links'
import { RuntimeClientError } from '../runtime/types'
import { getOptionalWorktreeLinkFlagValue } from './worktree-link-flag-value'
export function getOptionalLinearIssueLinkFlag(
flags: Map<string, string | boolean>,
name: string,
options: { allowNull?: boolean } = {}
): LinearIssueLinkUpdates | undefined {
const value = getOptionalWorktreeLinkFlagValue(flags, name, {
...options,
createHint: 'a Linear issue identifier or URL'
})
if (value === undefined) {
return undefined
}
if (value === null) {
return { ...LINEAR_ISSUE_LINK_CLEARED }
}
// Only literal null unlinks; blank flag values must not inherit the text-field builder's clear behavior.
const updates = value.trim() === '' ? null : buildLinearIssueLinkUpdates(value)
if (!updates) {
throw new RuntimeClientError(
'invalid_argument',
'Pass a Linear issue identifier like STA-335, a Linear issue URL, or null to clear.'
)
}
return updates
}
@@ -0,0 +1,25 @@
import { RuntimeClientError } from '../runtime/types'
export function getOptionalWorktreeLinkFlagValue(
flags: Map<string, string | boolean>,
name: string,
options: { allowNull?: boolean; createHint?: string } = {}
): string | null | undefined {
if (!flags.has(name)) {
return undefined
}
const value = flags.get(name)
if (typeof value !== 'string' || value.length === 0) {
throw new RuntimeClientError('invalid_argument', `Missing value for --${name}`)
}
if (value.trim().toLowerCase() !== 'null') {
return value
}
if (!options.allowNull) {
throw new RuntimeClientError(
'invalid_argument',
`Omit --${name} on create, or pass ${options.createHint ?? 'a valid link reference'}.`
)
}
return null
}
@@ -0,0 +1,295 @@
import { isRecoverableRemoteRuntimeConnectionError } from '../../shared/remote-runtime/remote-runtime-client-error-classification'
import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store'
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import type { RuntimeWorktreeRecord } from '../../shared/runtime-worktree-contracts'
import type { CrossStoreParentRef } from '../../shared/worktree/lineage-types'
import { crossStoreParentRefOfRow } from '../../shared/worktree/lineage-row-identity'
import {
supportsCrossStoreLineage,
WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY
} from '../../shared/worktree-runtime-capabilities'
import { getOptionalParentSelector } from '../workspace-selection/caller-folder-workspace'
import { getOptionalStringFlag } from '../flags'
import { mayNameFolderWorkspace } from '../workspace-selection/folder-workspace-selector'
import { isLocalEnvironmentSelector, LOCAL_ENVIRONMENT } from '../hosts/local-environment-selector'
import { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
import { quoteCliCommandArgument } from '../shell-command-quote'
import { describeClientEnvironment, environmentLabel } from './workspace-address'
import { attachCliErrorData } from './worktree-setup-decision-recovery'
/** The Orca a parent lives in: `local` or a saved environment's id. */
export type ParentEnvironment = { route: string; name: string }
const LOCAL: ParentEnvironment = { route: LOCAL_ENVIRONMENT, name: LOCAL_ENVIRONMENT }
function isCallerRelative(selector: string | undefined): boolean {
return selector === 'active' || selector === 'current'
}
function savedParentEnvironment(userDataPath: string, value: string): ParentEnvironment {
const saved = listEnvironments(userDataPath)
const byId = saved.find((environment) => environment.id === value)
const byName = saved.filter((environment) => environment.name === value)
const found = byId ?? (byName.length === 1 ? byName[0] : undefined)
if (found) {
return { route: found.id, name: found.name }
}
if (byName.length > 1) {
throw new RuntimeClientError(
'invalid_argument',
`--parent-environment ${value} is ambiguous: ${byName.length} saved environments have that name. Use the environment id.`,
{ nextSteps: byName.map((environment) => `--parent-environment ${environment.id}`) }
)
}
throw new RuntimeClientError(
'environment_not_paired',
`--parent-environment ${value} is not a saved environment here, so its workspaces can't be reached from this machine.`,
{
environment: value,
knownEnvironments: saved.map(({ id, name }) => ({ id, name })),
nextSteps: [
'Pass local, or the id or name of a saved environment from `orca environment list`.',
'Pair it first with `orca environment add --name <name> --pairing-code <code>`.'
]
}
)
}
/**
* Which environment `--parent-worktree` names, when that differs from the child's. Undefined keeps
* same-environment parents. A caller-relative parent (active/current) is always on the caller's own
* Orca, so against another environment it is implicitly `local`.
*/
export function resolveParentEnvironment(
flags: Map<string, string | boolean>,
client: RuntimeClient
): ParentEnvironment | undefined {
const parentSelector = getOptionalStringFlag(flags, 'parent-worktree')
const value = getOptionalStringFlag(flags, 'parent-environment')
if (flags.has('parent-environment')) {
if (value === undefined) {
throw new RuntimeClientError('invalid_argument', 'Missing required --parent-environment')
}
if (flags.get('no-parent') === true || !parentSelector) {
throw new RuntimeClientError(
'invalid_argument',
'--parent-environment says where --parent-worktree lives; pass it with --parent-worktree, not with --no-parent or alone.'
)
}
}
const named = value
? isLocalEnvironmentSelector(value)
? LOCAL
: savedParentEnvironment(client.userDataPath, value)
: undefined
if (isCallerRelative(parentSelector) && named && named.route !== LOCAL_ENVIRONMENT) {
throw new RuntimeClientError(
'invalid_argument',
`--parent-worktree ${parentSelector} names the workspace containing this terminal or cwd, which is on this machine's own Orca, not ${named.name}.`,
{
nextSteps: [
`Drop --parent-environment, or pass --parent-environment local.`,
`For a workspace in ${named.name}, list it with \`orca worktree ps --environment ${quoteCliCommandArgument(named.route)} --json\` and pass its address.worktree as --parent-worktree.`
]
}
)
}
const parentEnvironment = named ?? (isCallerRelative(parentSelector) ? LOCAL : undefined)
return parentEnvironment && parentEnvironment.route !== describeClientEnvironment(client).id
? parentEnvironment
: undefined
}
function parentEnvironmentClient(
client: RuntimeClient,
environment: ParentEnvironment
): RuntimeClient {
return new RuntimeClient(
client.userDataPath,
undefined,
null,
environment.route === LOCAL_ENVIRONMENT ? null : environment.route
)
}
/** Refuses before any request: an older child Orca would apply the rest and drop the parent. */
async function assertChildSavesCrossStoreParents(client: RuntimeClient): Promise<void> {
const status = (await client.call<RuntimeStatus>('status.get')).result
if (supportsCrossStoreLineage(status.capabilities)) {
return
}
const environment = describeClientEnvironment(client)
throw new RuntimeClientError(
'incompatible_runtime',
`Update Orca in ${environmentLabel(environment)} to nest workspaces under a parent in another environment. Nothing was changed.`,
{ environment: environment.id, requires: WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY }
)
}
function unavailableError(error: unknown, environment: ParentEnvironment): unknown {
if (!(error instanceof RuntimeClientError) || !isRecoverableRemoteRuntimeConnectionError(error)) {
return error
}
return new RuntimeClientError(
'environment_unavailable',
`${environment.name} didn't answer, so the parent couldn't be checked. Nothing was changed. (${error.message})`,
{
environment: environment.route,
nextSteps: [`orca status --environment ${quoteCliCommandArgument(environment.route)} --json`]
}
)
}
type ParentLookupCode = 'LINEAGE_PARENT_NOT_FOUND' | 'LINEAGE_PARENT_AMBIGUOUS'
function isParentLookupCode(code: string): code is ParentLookupCode {
return code === 'LINEAGE_PARENT_NOT_FOUND' || code === 'LINEAGE_PARENT_AMBIGUOUS'
}
/** The lineage code for a parent lookup's own error, as the runtime reports an explicit parent. */
function parentLookupCode(error: RuntimeClientError): ParentLookupCode | undefined {
if (isParentLookupCode(error.code)) {
return error.code
}
return error.code === 'selector_not_found'
? 'LINEAGE_PARENT_NOT_FOUND'
: error.code === 'selector_ambiguous'
? 'LINEAGE_PARENT_AMBIGUOUS'
: undefined
}
/**
* Error data for a parent miss or ambiguity: the environment searched, and recovery that lists that
* environment. Inherited steps are dropped because they inspect the caller's default route.
*/
function searchedEnvironmentData(
error: RuntimeClientError,
code: ParentLookupCode,
environment: { route: string | null; name: string },
extraSteps: readonly string[] = []
): Record<string, unknown> {
const list = environment.route
? `orca worktree ps --environment ${quoteCliCommandArgument(environment.route)} --json`
: undefined
const listStep = list
? code === 'LINEAGE_PARENT_AMBIGUOUS'
? `Compare the choices with \`${list}\`, then pass one as --parent-worktree.`
: list
: 'This one-off connection has no listing route; save it with `orca environment add --name <name> --pairing-code <code>`, then run `orca worktree ps --environment <name> --json`.'
return {
...(error.data && typeof error.data === 'object' ? error.data : {}),
environment: environment.route,
nextSteps: [listStep, ...extraSteps]
}
}
function parentLookupError(error: unknown, environment: ParentEnvironment): unknown {
if (!(error instanceof RuntimeClientError)) {
return error
}
const code = parentLookupCode(error)
if (!code) {
return error
}
const message =
code === 'LINEAGE_PARENT_NOT_FOUND'
? `No workspace in ${environment.name} matched the parent selector. Nothing was changed; no other environment was searched.`
: `${error.message} (in ${environment.name}; nothing was changed)`
return new RuntimeClientError(code, message, searchedEnvironmentData(error, code, environment))
}
/**
* The verified ref a child saves for a parent in another environment, built as the app builds it:
* the parent store's own installationId plus the parent row's identity. No other environment is
* searched, and every check runs before the child is changed.
*/
export async function resolveCrossEnvironmentParent(
client: RuntimeClient,
args: { flags: Map<string, string | boolean>; cwd: string; environment: ParentEnvironment }
): Promise<CrossStoreParentRef> {
const { flags, cwd, environment } = args
await assertChildSavesCrossStoreParents(client)
const parentClient = parentEnvironmentClient(client, environment)
try {
const raw = getOptionalStringFlag(flags, 'parent-worktree') ?? ''
// active/current keep their own cwd recovery; only an explicit selector's miss is the parent's.
const selector = isCallerRelative(raw)
? ((await getOptionalParentSelector(flags, cwd, parentClient)) ?? raw)
: raw
const parent = await parentClient
.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
worktree: selector,
...(mayNameFolderWorkspace(selector) ? { matchFolderWorkspaces: true } : {})
})
.catch((error: unknown) => {
throw parentLookupError(error, environment)
})
const { installationId } = (
await parentClient.call<{ installationId?: string }>('worktree.lineageList')
).result
const ref = crossStoreParentRefOfRow(installationId, parent.result.worktree)
if (!installationId) {
throw new RuntimeClientError(
'incompatible_runtime',
`Update Orca in ${environment.name} so workspaces in other environments can name it as a parent. Nothing was changed.`,
{
environment: environment.route,
requires: WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY
}
)
}
if (!ref) {
throw new RuntimeClientError(
'invalid_argument',
"Couldn't confirm the parent's workspace identity. Refresh it in the Orca app and try again."
)
}
return ref
} catch (error) {
throw unavailableError(error, environment)
}
}
/** Sends a create/set; a miss or ambiguity on its same-environment parent names where it looked
* and how to list it, and a miss says how to name a parent elsewhere. */
export async function callNamingParentEnvironment<
T,
Params extends { parentWorktree?: string; parentWorkspace?: string; crossStoreParent?: unknown } =
Record<string, unknown>
>(
client: RuntimeClient,
method: 'worktree.create' | 'worktree.set',
params: Params
): Promise<RuntimeRpcSuccess<T>> {
try {
return await client.call<T>(method, params)
} catch (error) {
const parentSelector = params.parentWorktree ?? params.parentWorkspace
// A selector_* error here may be the child's own selector; only lineage codes name the parent.
if (
!(error instanceof RuntimeClientError) ||
!isParentLookupCode(error.code) ||
!parentSelector ||
params.crossStoreParent
) {
throw error
}
const code = error.code
const environment = describeClientEnvironment(client)
throw attachCliErrorData(
error,
searchedEnvironmentData(
error,
code,
{ route: environment.id, name: environmentLabel(environment) },
code === 'LINEAGE_PARENT_NOT_FOUND'
? [
`Only ${environmentLabel(environment)} was searched for "${parentSelector}". For a parent in another environment, add --parent-environment <local|environment-id> (a row's address.environment from \`orca worktree ps --environment <id> --json\`).`
]
: []
)
)
}
}
@@ -0,0 +1,197 @@
import type { RuntimeStatus } from '../../shared/runtime-session-contracts'
import { parseWorkspaceKey } from '../../shared/workspace-scope'
import type {
CrossStoreInferredSource,
CrossStoreParentRef
} from '../../shared/worktree/lineage-types'
import {
assertFolderParentSetSupported,
supportsCrossStoreLineage
} from '../../shared/worktree-runtime-capabilities'
import { getOptionalStringFlag } from '../flags'
import { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import { resolveWorktreeCreateCwdContext } from '../workspace-selection/workspace-selector'
import { mayNameFolderWorkspace } from '../workspace-selection/folder-workspace-selector'
import { parentCwdNextSteps, withWorktreeSelectorRecovery } from './worktree-selector-recovery'
import { getOptionalParentSelector } from '../workspace-selection/caller-folder-workspace'
import type { CreateParentSelector } from './worktree-create-parent-selector'
import {
resolveCrossEnvironmentParent,
resolveParentEnvironment
} from './worktree-parent-environment'
const CALLER_PARENT_INFERENCE_BUDGET_MS = 3_000
/** This machine's own Orca, where a caller-relative parent (active, current, this terminal) lives. */
export function callerOrcaClient(client: RuntimeClient): RuntimeClient {
return client.isRemote ? new RuntimeClient(client.userDataPath, undefined, null, null) : client
}
function serverLabel(client: RuntimeClient): string {
return client.environmentSelector ?? 'the connected server'
}
/** `worktree create`'s parent fields. A parent in another environment (--parent-environment, or
* active/current against a server) is sent as a verified cross-store ref; with no parent flag, the
* caller's own workspace is inferred on this machine's Orca. */
export async function resolveCreateParentFields(
client: RuntimeClient,
args: {
explicitParent: CreateParentSelector
inferredParent: string | undefined
cwd: string
flags: Map<string, string | boolean>
cwdContext: { parentWorktree?: { selector: string }; parentAmbiguous?: true }
callerTerminalHandle: string | undefined
noParent: boolean
}
): Promise<Record<string, unknown>> {
const { explicitParent, inferredParent, cwdContext, noParent } = args
if (explicitParent.parentEnvironment) {
const crossStoreParent = await resolveCrossEnvironmentParent(client, {
flags: args.flags,
cwd: args.cwd,
environment: explicitParent.parentEnvironment
})
return { crossStoreParent, noParent }
}
const targetParent = {
parentWorktree: explicitParent.parentWorktree,
// The runtime classifies path:/name: parents by kind; older runtimes strip this.
...(explicitParent.parentWorktree && mayNameFolderWorkspace(explicitParent.parentWorktree)
? { matchFolderWorkspaces: true }
: {}),
...(explicitParent.parentWorkspace ? { parentWorkspace: explicitParent.parentWorkspace } : {}),
noParent
}
if (client.isRemote) {
const inferParent =
!explicitParent.parentWorktree && !explicitParent.parentWorkspace && !noParent
return {
...targetParent,
...(inferParent
? await inferCallerCrossStoreParent(
client,
{ envParentWorkspace: inferredParent, callerTerminalHandle: args.callerTerminalHandle },
args.cwd
)
: {})
}
}
return {
...targetParent,
...(inferredParent ? { envParentWorkspace: inferredParent } : {}),
...(cwdContext.parentWorktree ? { cwdParentWorktree: cwdContext.parentWorktree.selector } : {}),
// Older hosts ignore the observation and keep this first-row cwd parent.
...(cwdContext.parentAmbiguous ? { cwdParentAmbiguous: cwdContext.parentAmbiguous } : {}),
callerTerminalHandle: args.callerTerminalHandle
}
}
/** No parent flag against a server: this machine's Orca resolves the caller's env, terminal and cwd
* context exactly as its same-machine create would. Short of a valid parent it creates unnested with
* one note, and noParent keeps the server's own create-time inference from nesting it anyway. */
async function inferCallerCrossStoreParent(
client: RuntimeClient,
context: { envParentWorkspace: string | undefined; callerTerminalHandle: string | undefined },
cwd: string
): Promise<Record<string, unknown>> {
// Optional nesting must not hold up the server create behind a stalled Orca on this machine.
const startedAt = Date.now()
const local = new RuntimeClient(
client.userDataPath,
CALLER_PARENT_INFERENCE_BUDGET_MS,
null,
null
)
let localTimedOut = false
// No Orca running here, or cwd outside its workspaces: no cwd context.
const cwdContext = await resolveWorktreeCreateCwdContext(cwd, local, false).catch(
(error: unknown): Awaited<ReturnType<typeof resolveWorktreeCreateCwdContext>> => {
localTimedOut = error instanceof RuntimeClientError && error.code === 'runtime_timeout'
return {}
}
)
if (!context.envParentWorkspace && !context.callerTerminalHandle && !cwdContext.parentWorktree) {
return {}
}
const notNested = (reason: string): Record<string, unknown> => {
console.error(`note: not nested: ${reason}`)
return { noParent: true }
}
// The budget is this machine's: time spent on the server's status doesn't count.
const remainingMs = CALLER_PARENT_INFERENCE_BUDGET_MS - (Date.now() - startedAt)
if (localTimedOut || remainingMs <= 0) {
return notNested("this machine's Orca didn't answer in time.")
}
try {
const status = (await client.call<RuntimeStatus>('status.get')).result
if (!supportsCrossStoreLineage(status.capabilities)) {
return notNested(`${serverLabel(client)} needs an Orca update to nest across machines.`)
}
const resolved = (
await local.call<
{ parent: CrossStoreParentRef; source: CrossStoreInferredSource } | { reason: string }
>(
'worktree.resolveCallerParent',
{
...context,
cwdParentWorktree: cwdContext.parentWorktree?.selector,
...(cwdContext.parentAmbiguous ? { cwdParentAmbiguous: true } : {})
},
{ timeoutMs: remainingMs }
)
).result
if ('reason' in resolved) {
return notNested(resolved.reason)
}
return { crossStoreParent: resolved.parent, crossStoreParentInferredFrom: resolved.source }
} catch (error) {
return notNested(error instanceof Error ? error.message : String(error))
}
}
/** `worktree set`'s parent; one in another environment is sent as a verified cross-store ref. */
export async function resolveSetParentFields(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<{
crossStoreParent?: CrossStoreParentRef
parentWorktree?: string
matchFolderWorkspaces?: true
}> {
const environment = resolveParentEnvironment(flags, client)
if (environment) {
return {
crossStoreParent: await resolveCrossEnvironmentParent(client, { flags, cwd, environment })
}
}
const raw = getOptionalStringFlag(flags, 'parent-worktree')
const rawKey = raw?.startsWith('id:') ? raw.slice('id:'.length) : raw
if (rawKey && parseWorkspaceKey(rawKey)?.type === 'folder') {
return { parentWorktree: await assertFolderParentSetSupportedBy(client, rawKey) }
}
const parentWorktree = await withWorktreeSelectorRecovery(
getOptionalParentSelector(flags, cwd, client),
parentCwdNextSteps(raw),
raw
)
if (parentWorktree && parseWorkspaceKey(parentWorktree)?.type === 'folder') {
return { parentWorktree: await assertFolderParentSetSupportedBy(client, parentWorktree) }
}
return parentWorktree && mayNameFolderWorkspace(parentWorktree)
? { parentWorktree, matchFolderWorkspaces: true }
: { parentWorktree }
}
/** An older host refuses a folder parent as "not found"; say it needs an update instead. */
async function assertFolderParentSetSupportedBy(
client: RuntimeClient,
folderKey: string
): Promise<string> {
const status = (await client.call<RuntimeStatus>('status.get')).result
assertFolderParentSetSupported(status.capabilities, client.environmentSelector ?? 'this machine')
return folderKey
}
@@ -0,0 +1,193 @@
import { normalizeExecutionHostId, type ParsedExecutionHost } from '../../shared/execution-host'
import type { ProjectHostSetup } from '../../shared/project-types'
import { hostFilterMatchesHostId, resolveHostFlagTarget } from '../hosts/execution-host-flag'
import { findProjectSetups, setupHostId } from '../projects/project-selector'
import type { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/types'
import { getPresentStringFlag } from '../flags'
import { getFolderWorkspaceMissingRepoError } from '../workspace-selection/caller-folder-workspace'
export type ProjectCreateTarget = {
repoSelector: string
/** Repo ids can be shared across hosts. */
repoHostId: string
setup: ProjectHostSetup
}
export function hasWorkspaceProjectTarget(flags: Map<string, string | boolean>): boolean {
return flags.has('project') || flags.has('host') || flags.has('project-host-setup')
}
export function assertWorkspaceTargetFlagsCompatible(flags: Map<string, string | boolean>): void {
const hasProjectTarget = hasWorkspaceProjectTarget(flags)
if (flags.has('repo') && hasProjectTarget) {
throw new RuntimeClientError(
'invalid_argument',
'Choose either --repo or project target flags, not both.'
)
}
if (flags.has('host') && !flags.has('project') && !flags.has('project-host-setup')) {
throw new RuntimeClientError(
'invalid_argument',
'--host requires --project unless --project-host-setup is provided.'
)
}
}
// Prefer the exact runtime stamp over its local alias when both setups exist.
function selectSetupOnHost(
candidates: readonly ProjectHostSetup[],
host: ParsedExecutionHost | undefined,
selectorLabel: string
): ProjectHostSetup | undefined {
if (host) {
return (
candidates.find((candidate) => normalizeExecutionHostId(candidate.hostId) === host.id) ??
candidates.find((candidate) => hostFilterMatchesHostId(host, candidate.hostId))
)
}
// Infer a sole host, but never choose between multiple hosts without an explicit selector.
const hostIds = new Set(candidates.map(setupHostId))
if (hostIds.size <= 1) {
return candidates[0]
}
throw new RuntimeClientError(
'invalid_argument',
`Ambiguous ${selectorLabel}: it is set up on ${hostIds.size} hosts. Pass --host to choose one.`,
{
knownProjectHostSetups: candidates.map(summarizeSetup),
nextSteps: [
...candidates.map(
(candidate) => `Use --host ${setupHostId(candidate)} for ${candidate.path}.`
),
'Run `orca host list` to see every machine you can target and the flag for each.'
]
}
)
}
function summarizeSetup(setup: ProjectHostSetup): {
id: string
hostId: string
path: string
} {
return { id: setup.id, hostId: setupHostId(setup), path: setup.path }
}
export async function resolveProjectCreateTarget(
flags: Map<string, string | boolean>,
client: RuntimeClient
): Promise<ProjectCreateTarget | undefined> {
const projectHostSetupId = getPresentStringFlag(flags, 'project-host-setup')
const projectId = getPresentStringFlag(flags, 'project')
const host = await resolveHostFlagTarget(flags, client)
if (!projectHostSetupId && !projectId && !host) {
return undefined
}
let result: Awaited<ReturnType<typeof client.call<{ setups: ProjectHostSetup[] }>>>
try {
result = await client.call<{ setups: ProjectHostSetup[] }>('projectHostSetup.list')
} catch (error) {
if (error instanceof RuntimeClientError && error.code === 'method_not_found') {
throw new RuntimeClientError(
'incompatible_runtime',
'This Orca server does not support project host setup yet. Update Orca on the server and try again.'
)
}
throw error
}
const ready = result.result.setups.filter((candidate) => candidate.setupState === 'ready')
// Match against every setup so an exact id with no ready setup never falls through to a name.
const candidates =
projectId === undefined || projectHostSetupId
? []
: (await findProjectSetups(client, result.result.setups, projectId)).filter(
(candidate) => candidate.setupState === 'ready'
)
// Setup ids are scoped to a host, so --host must disambiguate them too.
const setup = projectHostSetupId
? selectSetupOnHost(
ready.filter((candidate) => candidate.id === projectHostSetupId),
host,
`--project-host-setup ${projectHostSetupId}`
)
: selectSetupOnHost(candidates, host, `--project ${projectId}`)
if (!setup) {
if (projectHostSetupId) {
throw new RuntimeClientError(
'invalid_argument',
`Project host setup is not ready or was not found: ${projectHostSetupId}${host ? ` on ${host.id}` : ''}`
)
}
if (candidates.length === 0) {
throw new RuntimeClientError(
'invalid_argument',
`No ready setup found for --project ${projectId} on any host.`,
{
nextSteps: [
'Run `orca project list` for project ids and names, and `orca project setups` for where each is set up.'
]
}
)
}
throw new RuntimeClientError(
'invalid_argument',
`Project is not set up on the selected host: ${projectId}${host ? ` on ${host.id}` : ''}`,
{
knownProjectHostSetups: candidates.map(summarizeSetup),
nextSteps: candidates.map(
(candidate) => `Use --host ${setupHostId(candidate)} for ${candidate.path}.`
)
}
)
}
return {
repoSelector: `id:${setup.repoId}`,
repoHostId: setupHostId(setup),
setup
}
}
// Why the worktree id, not the selector: a host-scoped `identity:` selector carries no repo id.
function getRepoSelectorFromWorktreeId(worktreeId: string | undefined): string | undefined {
const separatorIndex = worktreeId?.indexOf('::') ?? -1
if (!worktreeId || separatorIndex <= 0) {
return undefined
}
return `id:${worktreeId.slice(0, separatorIndex)}`
}
/** Forward repoHostId with the repo in every lookup; the same repo can exist on multiple hosts. */
export type CliRepoTarget = { repo: string; repoHostId?: string }
export async function getCreateRepoTarget(
flags: Map<string, string | boolean>,
cwdParentWorktree: { worktreeId: string } | undefined,
client: RuntimeClient,
resolvedParentWorkspace?: string
): Promise<CliRepoTarget> {
const projectTarget = await resolveProjectCreateTarget(flags, client)
if (projectTarget) {
return { repo: projectTarget.repoSelector, repoHostId: projectTarget.repoHostId }
}
const explicitRepo = getPresentStringFlag(flags, 'repo')
if (explicitRepo) {
return { repo: explicitRepo }
}
const inferredRepo = getRepoSelectorFromWorktreeId(cwdParentWorktree?.worktreeId)
if (inferredRepo) {
return { repo: inferredRepo }
}
const folderError = await getFolderWorkspaceMissingRepoError(
client,
flags,
resolvedParentWorkspace
)
if (folderError) {
throw folderError
}
throw new RuntimeClientError(
'invalid_argument',
'Missing repo selector. Pass --repo or run from inside an Orca-managed worktree.'
)
}
@@ -0,0 +1,24 @@
import type { RuntimeWorktreeAgentRow } from '../../shared/runtime-worktree-contracts'
import {
programStatusAttentionLabel,
resolveProgramStatusPresentation
} from '../../shared/program-status/presentation'
/** A block takes precedence over progress. */
export function formatWorktreePsProgramStatus(
agents: readonly RuntimeWorktreeAgentRow[] | undefined
): string {
let progress: number | undefined
for (const agent of agents ?? []) {
const presentation = resolveProgramStatusPresentation({
state: agent.state,
programStatus: agent.programStatus,
toolName: agent.toolName ?? undefined
})
if (presentation.attention) {
return ` (${programStatusAttentionLabel(presentation.attention)})`
}
progress ??= presentation.progress
}
return progress === undefined ? '' : ` ${progress}%`
}
@@ -0,0 +1,38 @@
import type { RuntimeWorktreePsSummary } from '../../shared/runtime-worktree-contracts'
type TerminalCounts = Pick<
RuntimeWorktreePsSummary,
'liveTerminalCount' | 'hasAttachedPty' | 'unverifiableTerminalCount'
>
/** `none`: the host reports no terminal for the row. Never `exited`, which needs proof of an exit. */
type TerminalVerdict = 'live' | 'unverifiable' | 'none'
function terminalVerdict(row: TerminalCounts): TerminalVerdict {
if (row.liveTerminalCount > 0) {
return 'live'
}
// Absent count: a host that predates it, which cannot tell no terminals from lost contact.
if (row.unverifiableTerminalCount === undefined || row.unverifiableTerminalCount > 0) {
return 'unverifiable'
}
return 'none'
}
export function formatWorktreePsTerminalFields(row: TerminalCounts): string {
if (terminalVerdict(row) === 'unverifiable') {
return 'live:unverifiable pty:unverifiable'
}
const unverifiable = row.unverifiableTerminalCount ?? 0
if (unverifiable === 0) {
return `live:${row.liveTerminalCount} pty:${row.hasAttachedPty ? 'yes' : 'no'}`
}
return `live:${row.liveTerminalCount}+${unverifiable} unverifiable pty:${row.hasAttachedPty ? 'yes' : 'unverifiable'}`
}
/** Preserve numeric/boolean fields for existing scripts; terminalVerdict distinguishes unknown values. */
export function projectWorktreePsTerminalVerdict<TRow extends TerminalCounts>(
row: TRow
): TRow & { terminalVerdict: TerminalVerdict } {
return { ...row, terminalVerdict: terminalVerdict(row) }
}
@@ -0,0 +1,68 @@
import { getOptionalStringFlag } from '../flags'
import { assertLocalCwdWorktreeSelector } from '../hosts/local-environment-selector'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import { resolveCurrentWorktreeSelector } from '../workspace-selection/workspace-selector'
import { quoteCliCommandArgument } from '../shell-command-quote'
/** What current/active names right now: one selector, the ambiguous choices, or nothing. */
async function describeCurrent(
cwd: string,
client: RuntimeClient
): Promise<{ selectors: string[]; resolution: 'resolved' | 'ambiguous' | 'unresolved' }> {
try {
return {
selectors: [await resolveCurrentWorktreeSelector(cwd, client, 'current')],
resolution: 'resolved'
}
} catch (error) {
const data =
error instanceof RuntimeClientError && error.code === 'selector_ambiguous' ? error.data : null
const choices =
typeof data === 'object' && data !== null && 'validSelectorForms' in data
? data.validSelectorForms
: undefined
return Array.isArray(choices) && choices.every((choice) => typeof choice === 'string')
? { selectors: choices, resolution: 'ambiguous' }
: { selectors: [], resolution: 'unresolved' }
}
}
/**
* Removal needs an explicit workspace, as `git worktree remove` needs a path: a cwd shortcut could
* delete a different workspace than the one the caller has in mind. Shared by every `worktree rm`
* kind, so it runs before the command decides between a worktree and a folder workspace.
*/
export async function refuseCurrentForRemoval(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<void> {
const value = getOptionalStringFlag(flags, 'worktree')
if (value !== 'current' && value !== 'active') {
return
}
// Remote cwd can't be resolved; that refusal already names the environment to list.
assertLocalCwdWorktreeSelector(value, client)
const { selectors, resolution } = await describeCurrent(cwd, client)
const flagsFor = selectors.map((selector) => `--worktree ${quoteCliCommandArgument(selector)}`)
const named =
resolution === 'resolved'
? ` Here, ${value} is ${flagsFor[0]}; pass that instead.`
: resolution === 'ambiguous'
? ` Here, ${value} matches more than one workspace; pass the one you mean.`
: ''
throw new RuntimeClientError(
'invalid_argument',
`orca worktree rm needs an explicit workspace; --worktree ${value} is not accepted for removal.${named}`,
{
current: { resolution, selectors },
nextSteps: [
...flagsFor.map((flag) => `orca worktree rm ${flag}`),
...(resolution === 'unresolved'
? ['Find the workspace with `orca worktree ps --json` and pass its `address.worktree`.']
: [])
]
}
)
}
@@ -0,0 +1,70 @@
import { z } from 'zod'
import { WORKTREE_REMOVE_BRANCH_POLICY_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities'
import type { RuntimeWorktreeRemoveResult } from '../../shared/runtime-worktree-contracts'
import { worktreeRemovalReplyTimeoutMs } from '../../shared/worktree/archive-hook-removal-gate'
import { RuntimeClientError } from '../runtime/types'
import type { RuntimeClient } from '../runtime/client'
import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope'
export type WorktreeRemovalRequest = {
worktree: string
hostId: string
force: boolean
deleteBranch?: boolean
runHooks: boolean
allowFailedArchiveHook: boolean
}
/** Callers act on the exit status, so ask the host for Git's outcome rather than acceptance. */
export async function requestWorktreeRemoval(
client: RuntimeClient,
request: WorktreeRemovalRequest
): Promise<RuntimeRpcSuccess<RuntimeWorktreeRemoveResult>> {
let dispatched = false
const { deleteBranch, ...legacyRequest } = request
const legacy = {
...legacyRequest,
// --force also waives PTY-stop proof.
allowUnverifiedPtyStop: request.force,
waitForBackgroundRemoval: true
}
try {
return await client.call<RuntimeWorktreeRemoveResult>('worktree.rm', legacy, {
timeoutMs: worktreeRemovalReplyTimeoutMs(request.runHooks),
requestSelection: {
paramsForStatus: (raw) => {
const parsed = BranchPolicyStatus.safeParse(raw)
if (!parsed.success) {
throw new RuntimeClientError(
'invalid_runtime_response',
'The Orca host returned an invalid status response.'
)
}
if (
parsed.data.capabilities?.includes(WORKTREE_REMOVE_BRANCH_POLICY_RUNTIME_CAPABILITY)
) {
return deleteBranch === undefined ? legacy : { ...legacy, deleteBranch }
}
console.error(
'warning: This Orca host is older and uses its existing branch policy. Keep-by-default and --delete-branch do not apply.'
)
return legacy
},
onDispatch: () => {
dispatched = true
}
}
})
} catch (error) {
// The host keeps deleting after this client stops waiting.
if (dispatched && error instanceof RuntimeClientError && error.code === 'runtime_timeout') {
throw new RuntimeClientError(
'worktree_removal_in_progress',
`Stopped waiting, but Orca may still be deleting the checkout. Check \`orca worktree show --worktree ${request.worktree}\` before retrying.`
)
}
throw error
}
}
const BranchPolicyStatus = z.object({ capabilities: z.array(z.string()).optional() })
@@ -0,0 +1,36 @@
import {
formatArchiveHookOverride,
type ArchiveHookOverride
} from '../../shared/worktree/archive-hook-removal-gate'
type HookWarningResult = {
warning?: string
archiveHookOverride?: ArchiveHookOverride
}
type PreservedBranchResult = {
preservedBranch?: {
branchName: string
}
}
export function printHookWarning(result: HookWarningResult, json: boolean): void {
if (json) {
return
}
if (result.warning) {
console.error(`warning: ${result.warning}`)
}
// A waived archive failure must remain visible after the checkout is deleted.
if (result.archiveHookOverride) {
console.error(`warning: ${formatArchiveHookOverride(result.archiveHookOverride)}`)
}
}
export function printPreservedBranchWarning(result: PreservedBranchResult, json: boolean): void {
if (!json && result.preservedBranch) {
console.error(
`warning: local branch "${result.preservedBranch.branchName}" was kept because Git could not safely delete it`
)
}
}
@@ -0,0 +1,41 @@
import { getOptionalNullableNumberFlag, getOptionalNumberFlag } from '../flags'
import { RuntimeClientError } from '../runtime/types'
import { getOptionalWorktreeLinkFlagValue } from './worktree-link-flag-value'
import { getOptionalGitLabLinkFlag } from './worktree-gitlab-link'
type ReviewTargetLinks = {
linkedIssue: number | null | undefined
linkedPR?: number | null
linkedGitLabIssue?: number | null
linkedGitLabMR?: number | null
}
// Only set may clear a link; create uses non-nullable flags.
export function getReviewTargetLinkFlags(
flags: Map<string, string | boolean>,
options: { nullable?: boolean } = {}
): ReviewTargetLinks {
const getFlag = options.nullable ? getOptionalNullableNumberFlag : getOptionalNumberFlag
const value = getOptionalWorktreeLinkFlagValue(flags, 'pr', {
allowNull: options.nullable,
createHint: 'a positive pull request number'
})
const linkedPR = value == null ? value : Number(value)
if (
typeof value === 'string' &&
typeof linkedPR === 'number' &&
(!/^\d+$/.test(value.trim()) || !Number.isSafeInteger(linkedPR) || linkedPR <= 0)
) {
throw new RuntimeClientError('invalid_argument', 'Pass a positive safe integer for --pr.')
}
const linkedGitLabIssue = getOptionalGitLabLinkFlag(flags, 'issue', {
allowNull: options.nullable
})
const linkedGitLabMR = getOptionalGitLabLinkFlag(flags, 'mr', { allowNull: options.nullable })
return {
linkedIssue: getFlag(flags, 'issue'),
...(linkedPR === undefined ? {} : { linkedPR }),
...(linkedGitLabIssue === undefined ? {} : { linkedGitLabIssue }),
...(linkedGitLabMR === undefined ? {} : { linkedGitLabMR })
}
}
@@ -0,0 +1,93 @@
import { parseWorkspaceKey } from '../../shared/workspace-scope'
import { RuntimeClientError } from '../runtime/types'
import { attachCliErrorData } from './worktree-setup-decision-recovery'
// The runtime omits the typed selector from not-found errors; add it and its grammar at the CLI boundary.
export const WORKTREE_SELECTOR_FORMS = [
'id:<repo-id>::<absolute-path>',
'folder:<folder-id>',
'path:<absolute-path>',
'name:<display-name>',
'branch:<branch>',
'identity:<identity-key>',
'issue:<number>',
'current',
'active'
] as const
export type WorktreeSelectorRecovery = {
selector: string
validSelectorForms: readonly string[]
suggestions: readonly string[]
nextSteps: readonly string[]
}
const PREFIXES = ['id:', 'folder:', 'path:', 'name:', 'branch:', 'identity:', 'issue:']
function suggestForms(selector: string): string[] {
if (parseWorkspaceKey(selector.replace(/^id:/, ''))?.type === 'folder') {
// A folder id is complete on its own; only listing can show the right one.
return []
}
if (selector.startsWith('id:')) {
// A worktree id is `<repo-id>::<path>`; the repo id alone names no checkout.
return selector.includes('::')
? []
: [`id:${selector.slice(3)}::<absolute-path>`, 'path:<absolute-path>']
}
if (PREFIXES.some((prefix) => selector.startsWith(prefix))) {
return []
}
return selector.startsWith('/') || /^[A-Za-z]:[\\/]/.test(selector)
? [`path:${selector}`]
: [`id:${selector}::<absolute-path>`, `name:${selector}`, `branch:${selector}`]
}
export function worktreeSelectorRecovery(selector: string): WorktreeSelectorRecovery {
const suggestions = suggestForms(selector)
return {
selector,
validSelectorForms: WORKTREE_SELECTOR_FORMS,
suggestions,
nextSteps: [
`No Orca workspace matched the worktree selector "${selector}".`,
...(suggestions.length > 0 ? [`Did you mean: ${suggestions.join(', ')}`] : []),
`Valid selector forms: ${WORKTREE_SELECTOR_FORMS.join(', ')}.`,
'List the exact values, folder workspaces included, with `orca worktree ps --json` (add `--environment <id>` for a workspace in another environment); a bare repository id is not a worktree id.'
]
}
}
export async function withWorktreeSelectorRecovery<T>(
pending: Promise<T>,
nextSteps: readonly string[],
selector?: string
): Promise<T> {
try {
return await pending
} catch (error) {
if (
!nextSteps.length ||
!(error instanceof RuntimeClientError) ||
error.code !== 'selector_not_found'
) {
throw error
}
const data = error.data && typeof error.data === 'object' ? error.data : {}
const previousSteps =
'nextSteps' in data && Array.isArray(data.nextSteps)
? data.nextSteps.filter((step: unknown): step is string => typeof step === 'string')
: []
throw attachCliErrorData(error, {
...data,
...(selector ? { selector } : {}),
validSelectorForms: WORKTREE_SELECTOR_FORMS,
nextSteps: [...nextSteps, ...previousSteps]
})
}
}
export const parentCwdNextSteps = (selector?: string): string[] => [
`The parent selector "${selector}" could not be resolved. Run from an Orca-managed worktree or pass an explicit parent selector.`
]
@@ -0,0 +1,64 @@
import { getPresentStringFlag } from '../flags'
import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types'
// Hosts use generic runtime_error here; this message is the stable discriminator.
const SETUP_DECISION_REQUIRED = 'Setup decision required for this repository'
const SETUP_DECISION_NEXT_STEP =
'Pass --setup run to run the setup script, or --setup skip to create without it.'
/** Only the CLI answers setup prompts with --setup; desktop and mobile have their own UI. */
export async function withSetupDecisionRecovery<T>(
create: Promise<T>,
replayingLaunch = false
): Promise<T> {
try {
return await create
} catch (error) {
throw attachSetupDecisionRecovery(error, replayingLaunch)
}
}
function attachSetupDecisionRecovery(error: unknown, replayingLaunch: boolean): unknown {
if (!(error instanceof RuntimeClientError) || error.message !== SETUP_DECISION_REQUIRED) {
return error
}
const data = {
...(error.data && typeof error.data === 'object' ? error.data : {}),
nextSteps: [
SETUP_DECISION_NEXT_STEP,
...(replayingLaunch && error instanceof RuntimeRpcFailureError
? [
'This launch was refused before creation. Remove --retry-launch for the changed request so Orca uses a new launch ID.'
]
: [])
]
}
return attachCliErrorData(error, data)
}
export function attachCliErrorData(error: RuntimeClientError, data: unknown): RuntimeClientError {
if (error instanceof RuntimeRpcFailureError) {
return new RuntimeRpcFailureError({
...error.response,
error: { ...error.response.error, data }
})
}
return new RuntimeClientError(error.code, error.message, data)
}
/** --setup's value, refusing a contradiction with --run-hooks. */
export function getOptionalSetupDecision(
flags: Map<string, string | boolean>
): 'run' | 'skip' | 'inherit' | undefined {
const setup = getPresentStringFlag(flags, 'setup')
if (setup !== undefined && setup !== 'run' && setup !== 'skip' && setup !== 'inherit') {
throw new RuntimeClientError('invalid_argument', '--setup must be one of: run, skip, inherit')
}
if (flags.get('run-hooks') === true && setup !== undefined && setup !== 'run') {
throw new RuntimeClientError(
'invalid_argument',
'Choose either --run-hooks or --setup run, not contradictory setup flags.'
)
}
return setup
}
@@ -0,0 +1,25 @@
import { RuntimeClientError } from '../runtime/types'
export function getWorktreeReadFlags(flags: Map<string, string | boolean>): {
isUnread?: boolean
acknowledgeAttention?: true
} {
const unread = flags.get('unread')
const read = flags.get('read')
// Reject valued booleans instead of silently ignoring --unread=x or --read x.
for (const [name, value] of [
['unread', unread],
['read', read]
] as const) {
if (typeof value === 'string') {
throw new RuntimeClientError('invalid_argument', `--${name} takes no value.`)
}
}
if (unread === true && read === true) {
throw new RuntimeClientError('invalid_argument', 'Choose either --unread or --read, not both.')
}
if (unread === true) {
return { isUnread: true }
}
return read === true ? { isUnread: false, acknowledgeAttention: true } : {}
}
+308
View File
@@ -0,0 +1,308 @@
import { withFolderSetupSupportWarning } from './folder-setup-support-warning'
import { withWorktreeSelectorRecovery } from './worktree-selector-recovery'
import type {
RuntimeWorktreeListResult,
RuntimeWorktreePsResult,
RuntimeWorktreeRecord,
RuntimeWorktreeSetResult,
RuntimeWorktreeCreateResult
} from '../../shared/runtime-worktree-contracts'
import type { CommandHandler } from '../dispatch'
import { printHookWarning, printPreservedBranchWarning } from './worktree-removal-warnings'
import { requestWorktreeRemoval } from './worktree-removal-request'
import { removeIfFolderWorkspace, setIfFolderWorkspace } from './folder-workspace-mutations'
import { formatWorktreeList, formatWorktreePs, formatWorktreeShow } from './workspace-format'
import { printResult } from '../command-result-output'
import {
annotateOmittedHostScope,
type WithAnnotatedHostScope
} from '../hosts/omitted-host-scope-selectors'
import { RuntimeClientError } from '../runtime/types'
import {
getOptionalPositiveIntegerFlag,
getOptionalStringFlag,
getOptionalStringFlagAllowingEmpty,
getPresentStringFlag,
getRequiredStringFlag
} from '../flags'
import {
getRequiredWorktreeSelector,
resolveWorktreeCreateCwdContext,
resolveCurrentWorktreeSelector
} from '../workspace-selection/workspace-selector'
import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent'
import { parseCliAgent, readCliAgentLaunch } from '../agents/agent-launch-request'
import { createWorktreeWithAgent } from './worktree-create-agent-launch'
import { printLineageSummary, printSetParentLine } from './worktree-lineage-summary'
import { resolveCreateParentFields, resolveSetParentFields } from './worktree-parent-fields'
import { callNamingParentEnvironment } from './worktree-parent-environment'
import { annotatePsRows, annotateShown } from './worktree-address-annotation'
import { refuseCurrentForRemoval } from './worktree-removal-current-refusal'
import { projectWorktreePsTerminalVerdict } from './worktree-ps-terminal-verdict'
import {
assertWorkspaceTargetFlagsCompatible,
hasWorkspaceProjectTarget,
getCreateRepoTarget,
type CliRepoTarget
} from './worktree-project-target'
import {
assertWorktreeParentFlagsCompatible,
getEnvParentWorkspace,
resolveCreateParentSelector
} from './worktree-create-parent-selector'
import { getOptionalLinearIssueLinkFlag } from './worktree-linear-issue-link'
import { getWorktreeReadFlags } from './worktree-unread-flag'
import { getReviewTargetLinkFlags } from './worktree-review-link-flags'
import {
getOptionalSetupDecision,
withSetupDecisionRecovery
} from './worktree-setup-decision-recovery'
import { assertGitLabLinkFlagProjectsMatch } from './worktree-gitlab-link-context'
import {
assertReferenceWritesSupported,
getCreateReferenceInputs,
resolveReferenceInputs
} from '../reference-input'
function getOptionalStartupAgent(flags: Map<string, string | boolean>): TuiAgent | undefined {
const agent = getPresentStringFlag(flags, 'agent')
if (agent === undefined) {
const needsAgent = ['prompt', 'model', 'effort', 'surface', 'retry-launch'].find((name) =>
flags.has(name)
)
if (needsAgent) {
throw new RuntimeClientError('invalid_argument', `--${needsAgent} requires --agent`)
}
return undefined
}
return parseCliAgent(agent)
}
export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
'worktree ps': async ({ flags, client, json }) => {
const result = await client.call<WithAnnotatedHostScope<RuntimeWorktreePsResult>>(
'worktree.ps',
{
limit: getOptionalPositiveIntegerFlag(flags, 'limit'),
...(json && flags.has('agent-wait') ? { includeAgentWait: true } : {})
}
)
await annotateOmittedHostScope(result.result)
const annotate = await annotatePsRows(client, result.result.worktrees)
const worktrees = annotate(result.result.worktrees.map(projectWorktreePsTerminalVerdict))
printResult({ ...result, result: { ...result.result, worktrees } }, json, () =>
formatWorktreePs({ ...result.result, worktrees: annotate(result.result.worktrees) })
)
},
'worktree list': async ({ flags, client, json }) => {
const result = await client.call<WithAnnotatedHostScope<RuntimeWorktreeListResult>>(
'worktree.list',
{
repo: getOptionalStringFlag(flags, 'repo'),
limit: getOptionalPositiveIntegerFlag(flags, 'limit')
}
)
await annotateOmittedHostScope(result.result)
printResult(result, json, formatWorktreeList)
},
'worktree show': async ({ flags, client, cwd, json }) => {
const result = await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
worktree: await getRequiredWorktreeSelector(flags, 'worktree', cwd, client),
matchFolderWorkspaces: true
})
printResult(await annotateShown(client, result), json, formatWorktreeShow)
},
'worktree current': async ({ client, cwd, json }) => {
const result = await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
worktree: await resolveCurrentWorktreeSelector(cwd, client, 'current')
})
printResult(await annotateShown(client, result), json, formatWorktreeShow)
},
'worktree create': async (context) => {
const { flags, client, cwd, json, rawArgs } = context
const referenceInputs = getCreateReferenceInputs(flags)
assertWorktreeParentFlagsCompatible(flags)
assertWorkspaceTargetFlagsCompatible(flags)
const branchNameOverride = getPresentStringFlag(flags, 'branch')
const reviewLinks = getReviewTargetLinkFlags(flags)
const callerTerminalHandle = process.env.ORCA_TERMINAL_HANDLE || undefined
const explicitParent = await resolveCreateParentSelector(flags, cwd, client)
const explicitParentWorktree = explicitParent.parentWorktree
const explicitParentWorkspace = explicitParent.parentWorkspace
const startupAgent = getOptionalStartupAgent(flags)
// Read before any request, so a bad prompt, model or effort creates nothing.
const agentLaunch = startupAgent
? readCliAgentLaunch(flags, startupAgent, { createsWorktree: true })
: undefined
const setupDecision = getOptionalSetupDecision(flags)
const noParent = flags.get('no-parent') === true
const inferParent = !explicitParentWorktree && !explicitParentWorkspace && !noParent
const envParentWorkspace = inferParent ? getEnvParentWorkspace() : undefined
let cwdContext: Awaited<ReturnType<typeof resolveWorktreeCreateCwdContext>> = {}
const needsCwdRepoInference = !flags.has('repo') && !hasWorkspaceProjectTarget(flags)
if (inferParent || needsCwdRepoInference) {
try {
// Cwd preserves parent/repo inference when agent shells lose ORCA_TERMINAL_HANDLE.
cwdContext = await resolveWorktreeCreateCwdContext(
cwd,
client,
needsCwdRepoInference,
inferParent
)
} catch (error) {
if (
needsCwdRepoInference &&
error instanceof RuntimeClientError &&
error.code === 'selector_ambiguous'
) {
throw error
}
cwdContext = {}
}
}
const linearIssueLink = getOptionalLinearIssueLinkFlag(flags, 'linear-issue')
const activate = flags.get('activate') === true || flags.get('run-hooks') === true
const name = getRequiredStringFlag(flags, 'name')
const repoTarget: CliRepoTarget = cwdContext.repoId
? { repo: `id:${cwdContext.repoId}` }
: await getCreateRepoTarget(flags, undefined, client, explicitParentWorkspace)
await assertGitLabLinkFlagProjectsMatch(flags, client, repoTarget)
const linkedItems = referenceInputs
? await resolveReferenceInputs(context, referenceInputs)
: undefined
if (linkedItems) {
await assertReferenceWritesSupported(client)
}
const create = {
// Older hosts drop `repoHostId` and keep refusing an id on several hosts, as before.
...repoTarget,
name,
displayName: name,
displayNameKind: 'user',
baseBranch: getOptionalStringFlag(flags, 'base-branch'),
branchNameOverride,
...reviewLinks,
...linearIssueLink,
...(linkedItems ? { linkedItems } : {}),
comment: getOptionalStringFlag(flags, 'comment'),
runHooks: flags.get('run-hooks') === true,
activate,
// CLI activation targets its runtime's desktop, never unrelated paired viewers.
...(activate ? { navigation: 'host' as const } : {}),
...(setupDecision ? { setupDecision } : {}),
...(await resolveCreateParentFields(client, {
explicitParent,
inferredParent: envParentWorkspace,
cwd,
flags,
cwdContext,
callerTerminalHandle,
noParent
})),
// Always request CLI provenance, including hand-typed creates without a terminal handle.
cliProvenanceRequest: callerTerminalHandle ? { callerTerminalHandle } : {}
}
if (agentLaunch) {
await createWorktreeWithAgent({ client, flags, create, launch: agentLaunch, json, rawArgs })
return
}
const result = await withSetupDecisionRecovery(
callNamingParentEnvironment<RuntimeWorktreeCreateResult>(client, 'worktree.create', create)
)
const created = {
...result,
result: await withFolderSetupSupportWarning(client, result.result, create)
}
printHookWarning(created.result, json)
printLineageSummary(created.result, json)
printResult(created, json, formatWorktreeShow)
},
'worktree set': async ({ flags, client, cwd, json }) => {
assertWorktreeParentFlagsCompatible(
flags,
'Choose either --parent-worktree or --no-parent, not both.'
)
const parentSelector = getOptionalStringFlag(flags, 'parent-worktree')
const readFlags = getWorktreeReadFlags(flags)
const reviewLinks = getReviewTargetLinkFlags(flags, { nullable: true })
const linearIssueLink = getOptionalLinearIssueLinkFlag(flags, 'linear-issue', {
allowNull: true
})
const worktree = await getRequiredWorktreeSelector(flags, 'worktree', cwd, client)
if (await setIfFolderWorkspace(client, flags, worktree, json)) {
return
}
await assertGitLabLinkFlagProjectsMatch(flags, client, { worktree })
const parentFields = await resolveSetParentFields(flags, cwd, client)
const pending = callNamingParentEnvironment<RuntimeWorktreeSetResult>(client, 'worktree.set', {
worktree,
displayName: getOptionalStringFlag(flags, 'display-name'),
...reviewLinks,
...linearIssueLink,
// An explicit empty value clears the stored comment.
comment: getOptionalStringFlagAllowingEmpty(flags, 'comment'),
workspaceStatus: getOptionalStringFlag(flags, 'workspace-status'),
...readFlags,
...parentFields,
noParent: flags.get('no-parent') === true
})
const result = await withWorktreeSelectorRecovery(
pending,
parentSelector
? [
`Orca could not find the worktree selector "${worktree}" or the parent selector "${parentSelector}". The server did not identify which selector failed.`,
'Check both selectors with orca worktree show --worktree <selector> --json.'
]
: []
)
if (!json) {
for (const warning of result.result.warnings ?? []) {
console.error(`warning: ${warning.message}`)
}
printSetParentLine(result.result.worktree, parentFields)
}
printResult(result, json, formatWorktreeShow)
},
'worktree rm': async ({ flags, client, cwd, json }) => {
await refuseCurrentForRemoval(flags, cwd, client)
const worktree = await getRequiredWorktreeSelector(flags, 'worktree', cwd, client)
if (await removeIfFolderWorkspace(client, flags, worktree, json)) {
return
}
const resolved = await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
worktree
})
const hostId = resolved.result.worktree.hostId
if (!hostId) {
throw new RuntimeClientError(
'worktree_host_unresolved',
'Orca cannot tell which host owns this workspace. Refresh projects and try again.'
)
}
if (flags.get('allow-failed-archive-hook') === true && flags.get('run-hooks') !== true) {
throw new RuntimeClientError(
'invalid_argument',
'--allow-failed-archive-hook waives a FAILED archive hook, but without --run-hooks no hook runs at all. Pass --run-hooks too, or drop the waiver.'
)
}
const result = await requestWorktreeRemoval(client, {
worktree,
hostId,
force: flags.get('force') === true,
deleteBranch: flags.get('delete-branch') === true,
runHooks: flags.get('run-hooks') === true,
// Archive failure waivers protect user data separately from --force's PTY-stop waiver.
allowFailedArchiveHook: flags.get('allow-failed-archive-hook') === true
})
printHookWarning(result.result, json)
printPreservedBranchWarning(result.result, json)
printResult(result, json, (value) =>
// Hosts that predate waiting answer on acceptance.
value.removing
? 'removed: false\nOrca is still deleting the checkout in the background.'
: value.removed === true
? 'removed: true'
: 'Removal is not confirmed.'
)
}
}