Files
orca/src/cli/selectors.ts
T
Jinwoo Hong 4fabde28b1 feat(cli): one enclosing-workspace rule, --environment local, copyable addresses, and --parent-environment (#39733)
* feat(cli): one enclosing-workspace rule, --environment local, and copyable workspace addresses

current/active and cwd inference now pick the innermost workspace of either kind (worktree or
folder workspace); at equal depth the caller terminal's own workspace wins, otherwise the choice
is refused as ambiguous. --environment local names this machine's own Orca over an ambient
ORCA_ENVIRONMENT or pairing code. worktree ps/show/current print an environment: line and an
address: line (JSON environment, address, addressUnavailable, parent) that always carries its
--environment, and name a parent's environment only when it is verified.

* test: answer the folder catalog read in agent launch cwd tests

* feat(cli): worktree rm refuses current/active and names the selector to pass

Removal needs an explicit workspace, as git worktree remove needs a path. The refusal runs before
rm decides between a worktree and a folder workspace, and reports what current resolves to now
(one selector, the ambiguous choices, or none) in text and as invalid_argument data.

* fix(cli): keep the remote-environment guidance when rm refuses current

* fix(cli): surface folder-catalog failures for omitted targets; no address for a duplicated folder parent

* fix(cli): surface a worktree-list failure for omitted browser and terminal targets too

* test(cli): folder rm refuses current/active before the folder removal path

* fix(cli): refuse a cwd owner whose folder host can't be derived instead of skipping it

* fix(cli): compare cwd owners by filesystem identity, refuse every equal-path tie, surface worktree-list failures

Paths on the caller's own filesystem compare by realpath (reusing resolveRealPathSync), so /tmp
and /private/tmp aliases find the deeper owner in both the folder prefilter and ranking; other
hosts' paths stay lexical. Equal-depth owners with different repo registrations now refuse without
a caller instead of picking by catalog order. An omitted target no longer swallows worktree.list
method_not_found; only the optional folder reads fall back.

* fix(cli): read the realpath helper from shared so the packaged CLI ships it

* refactor(cli): move the catalog row type and unresolved-owner refusal out of the selection/catalog cycle

* fix(cli): resolve every caller-filesystem workspace path, not only basename matches

A workspace registered through a differently named symlink was skipped by the basename gate.
Containment now realpaths cwd and each row on the caller's own filesystem once per command,
shared by the folder prefilter and ranking; folder hosts are derived first so another host's
paths are never resolved locally.

* test: answer the folder catalog read in the ambiguous orchestration-check caller test

* feat(cli): --parent-environment names where a worktree's parent lives

worktree create and worktree set take --parent-environment <local|saved id|name>
next to --parent-worktree. The parent is resolved in that environment only, and
sent to the child as a verified cross-store ref after the child's cross-machine
capability check. Without the flag, the parent stays in the child's environment;
active/current always mean this machine's own Orca.

Preflight failures happen before any change: environment_not_paired,
environment_unavailable, LINEAGE_PARENT_NOT_FOUND / LINEAGE_PARENT_AMBIGUOUS
naming the searched environment, and incompatible_runtime with data.environment
and data.requires.

* fix(cli): parent lookup errors name and list the environment searched

LINEAGE_PARENT_AMBIGUOUS and LINEAGE_PARENT_NOT_FOUND now always carry
data.environment and a listing command for the environment the parent was
looked up in, for parents in another environment and in the child's own. Steps
inherited from the runtime listed the caller's default route instead.

* docs(cli): a local address names the Orca that printed it
2026-11-08 04:08:07 -05:00

279 lines
8.8 KiB
TypeScript

import { resolve as resolvePath } from 'node:path'
import type { ComputerAppQuery } from '../shared/runtime-types'
import { resolveFolderWorkspaceSelector } from './folder-workspace-selector'
import { resolveCallerDistroPathSelector } from './wsl-caller-path-selector'
import type { RuntimeClient } from './runtime-client'
import { RuntimeClientError } from './runtime/types'
import { assertLocalCwdWorktreeSelector } from './local-environment-selector'
import { isLaunchedByAnotherRuntime } from './runtime/runtime-source-fence'
import { getOptionalStringFlag, getPresentStringFlag, getRequiredStringFlag } from './flags'
import { readEnclosingWorkspaceCatalog } from './enclosing-workspace-catalog'
import {
getCallerExecutionHostId,
getCallerWorkspaceIds,
resolveCallerPaneWorktreeSelector,
selectWorktreeCreateCwdContext,
selectEnclosingWorktreeSelectionOnHost,
selectCallerTerminalWorkspace,
selectorPurpose,
type WorkspaceSelectionPurpose,
type HostScopedWorktreeSelection
} from './caller-host-worktree-selection'
export type ComputerCliTarget = {
session?: string
worktree?: string
app: ComputerAppQuery
}
export function buildCurrentWorktreeSelector(cwd: string): string {
return `path:${resolvePath(cwd)}`
}
export function normalizeWorktreeSelector(selector: string, cwd: string): string {
if (selector === 'active' || selector === 'current') {
return buildCurrentWorktreeSelector(cwd)
}
return selector
}
/** A parent keeps its selector: the runtime's parent resolver classifies it by kind, with parent rules. */
export async function normalizeWorktreeSelectorForCaller(
selector: string,
cwd: string,
client: RuntimeClient,
purpose: WorkspaceSelectionPurpose = 'worktree'
): Promise<string> {
const normalized = await resolveCallerDistroPathSelector(
normalizeWorktreeSelector(selector, cwd),
cwd,
client
)
return purpose === 'parent' ? normalized : resolveFolderWorkspaceSelector(normalized, client)
}
export async function resolveCurrentWorktreeSelector(
cwd: string,
client: RuntimeClient,
purpose: WorkspaceSelectionPurpose = 'worktree'
): Promise<string> {
return (await resolveCurrentWorktreeSelection(cwd, client, purpose)).selector
}
export async function resolveCurrentWorktreeSelection(
cwd: string,
client: RuntimeClient,
purpose: WorkspaceSelectionPurpose = 'worktree'
): Promise<HostScopedWorktreeSelection> {
assertLocalCwdWorktreeSelector('current', client)
// Preserve the repo id: duplicate registrations can make a bare path selector ambiguous.
const selection = selectEnclosingWorktreeSelectionOnHost(
await readEnclosingWorkspaceCatalog(client, cwd),
cwd,
getCallerExecutionHostId(),
getCallerWorkspaceIds(),
purpose
)
if (!selection) {
throw new RuntimeClientError(
'selector_not_found',
`No Orca workspace contains the current directory: ${resolvePath(cwd)}`
)
}
return selection
}
export async function resolveWorktreeCreateCwdContext(
cwd: string,
client: RuntimeClient,
inferRepo: boolean,
inferParent = true
): Promise<ReturnType<typeof selectWorktreeCreateCwdContext>> {
assertLocalCwdWorktreeSelector('current', client)
const catalog = await readEnclosingWorkspaceCatalog(client, cwd)
return selectWorktreeCreateCwdContext(catalog, cwd, inferRepo, inferParent)
}
export async function getOptionalWorktreeSelector(
flags: Map<string, string | boolean>,
name: string,
cwd: string,
client: RuntimeClient
): Promise<string | undefined> {
const value = getOptionalStringFlag(flags, name)
if (!value) {
return undefined
}
if (value === 'active' || value === 'current') {
assertLocalCwdWorktreeSelector(value, client)
return await resolveCurrentWorktreeSelector(cwd, client, selectorPurpose(name))
}
return await normalizeWorktreeSelectorForCaller(value, cwd, client, selectorPurpose(name))
}
export async function getRequiredWorktreeSelector(
flags: Map<string, string | boolean>,
name: string,
cwd: string,
client: RuntimeClient
): Promise<string> {
const value = getRequiredStringFlag(flags, name)
if (value === 'active' || value === 'current') {
assertLocalCwdWorktreeSelector(value, client)
return await resolveCurrentWorktreeSelector(cwd, client, selectorPurpose(name))
}
return await normalizeWorktreeSelectorForCaller(value, cwd, client, selectorPurpose(name))
}
async function optionalCurrentWorktreeSelector(
cwd: string,
client: RuntimeClient,
purpose: WorkspaceSelectionPurpose = 'worktree'
) {
try {
return await resolveCurrentWorktreeSelector(cwd, client, purpose)
} catch (error) {
if (error instanceof RuntimeClientError && error.code === 'selector_ambiguous') {
throw error
}
return undefined
}
}
// Remote commands leave worktree unset to use server-side focus.
export async function getBrowserWorktreeSelector(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient,
purpose: WorkspaceSelectionPurpose = 'worktree'
): Promise<string | undefined> {
const value = getOptionalStringFlag(flags, 'worktree')
if (value === 'all') {
return undefined
}
if (value) {
if (value === 'active' || value === 'current') {
assertLocalCwdWorktreeSelector(value, client)
return await resolveCurrentWorktreeSelector(cwd, client, purpose)
}
return await normalizeWorktreeSelectorForCaller(value, cwd, client)
}
if (client.isRemote) {
return undefined
}
// The folder reads fall back on their own; a worktree-list failure surfaces rather than retargeting.
const catalog = await readEnclosingWorkspaceCatalog(client, cwd)
const hostId = getCallerExecutionHostId()
const enclosing = selectEnclosingWorktreeSelectionOnHost(
catalog,
cwd,
hostId,
getCallerWorkspaceIds(),
purpose
)
if (enclosing || isLaunchedByAnotherRuntime(process.env, client.userDataPath)) {
return enclosing?.selector
}
// An Orca terminal knows its workspace; without this an unmanaged cwd lands in the focused one.
return selectCallerTerminalWorkspace(catalog, hostId)
}
export async function getTerminalHandle(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient,
options: { requireUnambiguous?: boolean; purpose?: WorkspaceSelectionPurpose } = {}
): Promise<string> {
const explicit = getPresentStringFlag(flags, 'terminal')
if (explicit) {
return explicit
}
const worktree = await getBrowserWorktreeSelector(flags, cwd, client, options.purpose)
const response = await client.call<{ handle: string }>('terminal.resolveActive', {
worktree,
...(options.requireUnambiguous ? { requireUnambiguous: true } : {})
})
return response.result.handle
}
export async function getComputerCommandTarget(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<ComputerCliTarget> {
const app = getRequiredStringFlag(flags, 'app')
const session = getOptionalStringFlag(flags, 'session')
const worktree = getOptionalStringFlag(flags, 'worktree')
if (session && worktree) {
throw new RuntimeClientError(
'invalid_argument',
'Computer-use targeting accepts either --session or --worktree, not both'
)
}
if (session) {
return { session, app }
}
return {
app,
worktree: await getBrowserWorktreeSelector(flags, cwd, client)
}
}
export type EmulatorCliTarget = {
worktree?: string
device?: string
emulator?: string // Orca id from list
}
export async function getEmulatorWorktreeSelector(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<string | undefined> {
const explicit = getOptionalStringFlag(flags, 'worktree')
if (explicit === 'all') {
return undefined
}
if (explicit) {
if (explicit === 'active' || explicit === 'current') {
assertLocalCwdWorktreeSelector(explicit, client)
return resolveCurrentWorktreeSelector(cwd, client)
}
return explicit
}
if (client.isRemote) {
return undefined
}
const terminalWorktreeId = process.env.ORCA_WORKTREE_ID
if (terminalWorktreeId?.trim()) {
const scoped = await resolveCallerPaneWorktreeSelector(terminalWorktreeId, client)
if (scoped) {
return scoped
}
}
const folderWorkspaceId = process.env.ORCA_WORKSPACE_ID?.trim()
if (folderWorkspaceId?.startsWith('folder:')) {
return folderWorkspaceId
}
return optionalCurrentWorktreeSelector(cwd, client)
}
export async function getEmulatorCommandTarget(
flags: Map<string, string | boolean>,
cwd: string,
client: RuntimeClient
): Promise<EmulatorCliTarget> {
const device = getOptionalStringFlag(flags, 'device')
const emulator = getOptionalStringFlag(flags, 'emulator')
const worktree = await getEmulatorWorktreeSelector(flags, cwd, client)
if (device || emulator) {
return {
device: device || undefined,
emulator: emulator || undefined,
worktree
}
}
return { worktree }
}