diff --git a/skill-guides/orca-cli.md b/skill-guides/orca-cli.md index 32c96e862e8b..cfbbf852cc76 100644 --- a/skill-guides/orca-cli.md +++ b/skill-guides/orca-cli.md @@ -136,7 +136,9 @@ Selectors: - When several workspaces match, the error usually lists each choice's kind, host, path and exact selector; pass one of those. If it lists none, find the row with `ORCA worktree ps --json` (if `truncated`, repeat with `--limit `) and pass `identity:`, `folder:`, or `id:` when no other row has that id. A folder id that two folder workspaces share can't be selected; the error says how to repair it. - For a workspace in another environment, add `--environment ` to the command, as with any other selector. - The full id is the exact `::` value returned by `ORCA worktree create --json` or `ORCA worktree list --json`; a bare repo id is not a worktree id. -- `active` / `current` for the enclosing Orca-managed worktree from the shell cwd; when targeting a paired server with `--environment` or `--pairing-code`, use an explicit selector from that server instead. +- `active` / `current` for the Orca workspace enclosing the shell cwd, worktree or folder workspace: the innermost one wins, so a worktree nested inside a folder workspace is picked over the folder; at equal depth this terminal's own workspace wins, otherwise the error lists the choices. Pass `folder:` to get the folder itself. `worktree rm` refuses `current`/`active` and needs an explicit selector; its error prints the one `current` resolves to. `current` resolves on this machine's Orca, so it is refused with `--environment ` or `--pairing-code`; use an explicit selector from that environment instead (`--environment local` keeps it on this machine even when `ORCA_ENVIRONMENT` is set). +- `--environment` selects which Orca receives the command (`local` is this machine's own Orca); `host` is that Orca's stored location metadata. Never derive an environment from `host`. +- `worktree ps` and `worktree show` give each workspace an `address` (text: an `address:` line). Copy `address.line` as is, keeping its `--environment`, or pass `address.environment` and `address.worktree` as `--environment` and `--worktree`. If `address` is null, follow `addressUnavailable` (`one-off-connection`, `unverifiable-row` or `duplicate-folder-id`) and never construct a route yourself. `parent` names the parent's environment when it is known; with `state: unknown-environment` there is no route to it from here. - For `worktree create --parent-worktree`, folder/worktree parent context keys are also valid: `folder:`, `worktree:::`, `id:folder:`, `id:worktree:::`. `worktree set --parent-worktree` also takes the folder keys, `folder:` or `id:folder:`. On both, `path:` and `name:` record a folder workspace parent when they match one. Lineage rules: @@ -146,6 +148,8 @@ Lineage rules: - Use `--parent-worktree folder:` or `--parent-worktree worktree:::` when a folder or worktree parent context should be explicit. - Use `--no-parent` only when the new work is independent. - A parent can be in a different project from its child, such as `worktree create --repo id: --name related-task --parent-worktree id:::`. A worktree parent and child must use the same execution host (local machine, SSH target, or paired server). +- `--parent-worktree` is looked up in the child's environment. For a parent in another environment, add `--parent-environment `: to reuse a workspace from `ps`/`show` as a parent, pass its `address.environment` as `--parent-environment` and its `address.worktree` as `--parent-worktree`. Orca never searches other environments; a parent missing there is an error. `active`/`current` always mean this machine's own workspace, so they take only `--parent-environment local`. +- An address with `--environment local` means the Orca that printed it, because `local` is always the machine running the command; don't hand an address to another machine to run. To link workspaces across environments, run the command from the Orca that has both paired, such as `--environment --worktree --parent-worktree current`. - To move an existing worktree under a different parent, or make it top-level, use `worktree set` with `--parent-worktree ` or `--no-parent`. - `--no-parent` only controls Orca lineage; it does not choose the Git base. For independent top-level work, omit `--base-branch` so Orca uses the repo default base, or explicitly pass the repo default base. Never base it on the current feature branch unless the user asks for stacked work or "branch from current". diff --git a/src/cli/agent-workspace-selector.ts b/src/cli/agent-workspace-selector.ts deleted file mode 100644 index 1f6a86c0cb88..000000000000 --- a/src/cli/agent-workspace-selector.ts +++ /dev/null @@ -1,72 +0,0 @@ -import type { FolderWorkspace } from '../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../shared/project-group-types' -import type { Repo } from '../shared/repo-types' -import { resolveFolderWorkspaceHost } from '../shared/folder-workspaces/folder-workspace-execution-host' -import { LOCAL_EXECUTION_HOST_ID } from '../shared/execution-host' -import { - getCallerExecutionHostId, - hasEnclosingWorktreeOnHost, - type WorkspaceSelectionPurpose, - selectEnclosingWorktreeOnHost -} from './caller-host-worktree-selection' -import { RuntimeRpcFailureError, type RuntimeClient } from './runtime-client' -import { resolveCurrentWorktreeSelector } from './selectors' - -/** The local native folder workspace enclosing cwd, preferring the caller terminal's own folder. */ -export async function selectEnclosingNativeFolderWorkspace( - cwd: string, - client: RuntimeClient, - purpose: WorkspaceSelectionPurpose = 'worktree' -): Promise { - if (client.isRemote || getCallerExecutionHostId() !== LOCAL_EXECUTION_HOST_ID) { - return undefined - } - try { - const folders = await client.call<{ folderWorkspaces: FolderWorkspace[] }>( - 'folderWorkspace.list' - ) - const catalog = folders.result.folderWorkspaces.map((folder) => ({ - id: `folder:${folder.id}`, - path: folder.folderPath - })) - if (!hasEnclosingWorktreeOnHost(catalog, cwd, LOCAL_EXECUTION_HOST_ID)) { - return undefined - } - const [groups, repos] = await Promise.all([ - client.call<{ groups: ProjectGroup[] }>('projectGroup.list'), - client.call<{ repos: Repo[] }>('repo.list') - ]) - const state = { - folderWorkspaces: folders.result.folderWorkspaces, - projectGroups: groups.result.groups, - repos: repos.result.repos - } - const nativeCatalog = catalog.filter( - (row) => resolveFolderWorkspaceHost(state, row.id.slice('folder:'.length)).kind === 'local' - ) - const callerWorkspace = process.env.ORCA_WORKSPACE_ID ?? process.env.ORCA_WORKTREE_ID - const callerCatalog = nativeCatalog.filter((row) => row.id === callerWorkspace) - return ( - selectEnclosingWorktreeOnHost(callerCatalog, cwd, LOCAL_EXECUTION_HOST_ID, purpose) ?? - selectEnclosingWorktreeOnHost(nativeCatalog, cwd, LOCAL_EXECUTION_HOST_ID, purpose) - ) - } catch (error) { - // An older host may lack the folder catalog; a failed catalog must not select a wrong checkout. - if (!(error instanceof RuntimeRpcFailureError) || error.code !== 'method_not_found') { - throw error - } - return undefined - } -} - -/** Native folders take precedence over enclosing Git checkouts; remote cwd keeps its host rules. */ -export async function resolveCurrentAgentWorkspaceSelector( - cwd: string, - client: RuntimeClient, - purpose: WorkspaceSelectionPurpose = 'worktree' -): Promise { - return ( - (await selectEnclosingNativeFolderWorkspace(cwd, client, purpose)) ?? - resolveCurrentWorktreeSelector(cwd, client, purpose) - ) -} diff --git a/src/cli/browser/browser-command-target.ts b/src/cli/browser/browser-command-target.ts index c61b7fff5d25..80cab8468a59 100644 --- a/src/cli/browser/browser-command-target.ts +++ b/src/cli/browser/browser-command-target.ts @@ -3,8 +3,8 @@ import type { RuntimeStatus } from '../../shared/runtime-types' import { getOptionalStringFlag, getPresentStringFlag } from '../flags' import type { RuntimeClient } from '../runtime-client' import { RuntimeClientError } from '../runtime/types' +import { assertLocalCwdWorktreeSelector } from '../local-environment-selector' import { - assertLocalCwdWorktreeSelector, getBrowserWorktreeSelector, normalizeWorktreeSelectorForCaller, resolveCurrentWorktreeSelector diff --git a/src/cli/browser/browser.test.ts b/src/cli/browser/browser.test.ts index 11590397c164..8306fe8e155a 100644 --- a/src/cli/browser/browser.test.ts +++ b/src/cli/browser/browser.test.ts @@ -48,7 +48,13 @@ vi.mock('../runtime-client', async () => { import { main } from '../index' import { RuntimeClientError } from '../runtime/types' -import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from '../test-fixtures' +import { + buildWorktree, + noFolderWorkspacesFixture, + okFixture, + queueFixtures, + worktreeListFixture +} from '../test-fixtures' describe('orca cli browser page targeting', () => { beforeEach(() => { @@ -162,6 +168,7 @@ describe('orca cli browser page targeting', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), + noFolderWorkspacesFixture(), okFixture('req_snapshot', { browserPageId: 'page-1', snapshot: 'tree', @@ -178,7 +185,7 @@ describe('orca cli browser page targeting', () => { ) expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', { limit: 10_000 }) - expect(callMock).toHaveBeenNthCalledWith(2, 'browser.snapshot', { + expect(callMock).toHaveBeenNthCalledWith(3, 'browser.snapshot', { page: 'page-1', worktree: 'id:repo::/tmp/repo/feature' }) @@ -202,6 +209,7 @@ describe('orca cli browser page targeting', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), + noFolderWorkspacesFixture(), okFixture('req_switch', { switched: 2, browserPageId: 'page-2' }) ) vi.spyOn(console, 'log').mockImplementation(() => {}) @@ -212,7 +220,7 @@ describe('orca cli browser page targeting', () => { ) expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', { limit: 10_000 }) - expect(callMock).toHaveBeenNthCalledWith(2, 'browser.tabSwitch', { + expect(callMock).toHaveBeenNthCalledWith(3, 'browser.tabSwitch', { index: undefined, page: 'page-2', worktree: 'id:repo::/tmp/repo/feature' @@ -277,6 +285,7 @@ describe('orca cli browser page targeting', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), + noFolderWorkspacesFixture(), okFixture('req_open_url', { browserPageId: 'page-local' }) ) vi.spyOn(console, 'log').mockImplementation(() => {}) @@ -284,7 +293,7 @@ describe('orca cli browser page targeting', () => { await main(['open-url', '--url', 'https://example.com/login', '--json'], '/tmp/repo/feature') expect(callMock).toHaveBeenNthCalledWith( - 2, + 3, 'browser.openUrl', { url: 'https://example.com/login', @@ -300,6 +309,7 @@ describe('orca cli browser page targeting', () => { queueFixtures( callMock, worktreeListFixture([parent, workspace]), + noFolderWorkspacesFixture(), okFixture('req_tab_create', { browserPageId: 'page-1' }) ) vi.spyOn(console, 'log').mockImplementation(() => {}) @@ -308,7 +318,7 @@ describe('orca cli browser page targeting', () => { await main(['tab', 'create', '--url', 'https://example.com', '--json'], '/tmp/folder') expect(callMock).toHaveBeenNthCalledWith( - 2, + 3, 'browser.tabCreate', { url: 'https://example.com', worktree: `id:${workspace.id}` }, { timeoutMs: 60_000 } diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 0e015425400a..76a7fb888f31 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -364,7 +364,9 @@ const ORCA_CLI_MARKDOWN = [ "- When several workspaces match, the error usually lists each choice's kind, host, path and exact selector; pass one of those. If it lists none, find the row with `ORCA worktree ps --json` (if `truncated`, repeat with `--limit `) and pass `identity:`, `folder:`, or `id:` when no other row has that id. A folder id that two folder workspaces share can't be selected; the error says how to repair it.", "- For a workspace in another environment, add `--environment ` to the command, as with any other selector.", "- The full id is the exact `::` value returned by `ORCA worktree create --json` or `ORCA worktree list --json`; a bare repo id is not a worktree id.", - "- `active` / `current` for the enclosing Orca-managed worktree from the shell cwd; when targeting a paired server with `--environment` or `--pairing-code`, use an explicit selector from that server instead.", + "- `active` / `current` for the Orca workspace enclosing the shell cwd, worktree or folder workspace: the innermost one wins, so a worktree nested inside a folder workspace is picked over the folder; at equal depth this terminal's own workspace wins, otherwise the error lists the choices. Pass `folder:` to get the folder itself. `worktree rm` refuses `current`/`active` and needs an explicit selector; its error prints the one `current` resolves to. `current` resolves on this machine's Orca, so it is refused with `--environment ` or `--pairing-code`; use an explicit selector from that environment instead (`--environment local` keeps it on this machine even when `ORCA_ENVIRONMENT` is set).", + "- `--environment` selects which Orca receives the command (`local` is this machine's own Orca); `host` is that Orca's stored location metadata. Never derive an environment from `host`.", + "- `worktree ps` and `worktree show` give each workspace an `address` (text: an `address:` line). Copy `address.line` as is, keeping its `--environment`, or pass `address.environment` and `address.worktree` as `--environment` and `--worktree`. If `address` is null, follow `addressUnavailable` (`one-off-connection`, `unverifiable-row` or `duplicate-folder-id`) and never construct a route yourself. `parent` names the parent's environment when it is known; with `state: unknown-environment` there is no route to it from here.", "- For `worktree create --parent-worktree`, folder/worktree parent context keys are also valid: `folder:`, `worktree:::`, `id:folder:`, `id:worktree:::`. `worktree set --parent-worktree` also takes the folder keys, `folder:` or `id:folder:`. On both, `path:` and `name:` record a folder workspace parent when they match one.", "", "Lineage rules:", @@ -374,6 +376,8 @@ const ORCA_CLI_MARKDOWN = [ "- Use `--parent-worktree folder:` or `--parent-worktree worktree:::` when a folder or worktree parent context should be explicit.", "- Use `--no-parent` only when the new work is independent.", "- A parent can be in a different project from its child, such as `worktree create --repo id: --name related-task --parent-worktree id:::`. A worktree parent and child must use the same execution host (local machine, SSH target, or paired server).", + "- `--parent-worktree` is looked up in the child's environment. For a parent in another environment, add `--parent-environment `: to reuse a workspace from `ps`/`show` as a parent, pass its `address.environment` as `--parent-environment` and its `address.worktree` as `--parent-worktree`. Orca never searches other environments; a parent missing there is an error. `active`/`current` always mean this machine's own workspace, so they take only `--parent-environment local`.", + "- An address with `--environment local` means the Orca that printed it, because `local` is always the machine running the command; don't hand an address to another machine to run. To link workspaces across environments, run the command from the Orca that has both paired, such as `--environment --worktree --parent-worktree current`.", "- To move an existing worktree under a different parent, or make it top-level, use `worktree set` with `--parent-worktree ` or `--no-parent`.", "- `--no-parent` only controls Orca lineage; it does not choose the Git base. For independent top-level work, omit `--base-branch` so Orca uses the repo default base, or explicitly pass the repo default base. Never base it on the current feature branch unless the user asks for stacked work or \"branch from current\".", "", diff --git a/src/cli/caller-cwd-containment.ts b/src/cli/caller-cwd-containment.ts new file mode 100644 index 000000000000..861d162d62dd --- /dev/null +++ b/src/cli/caller-cwd-containment.ts @@ -0,0 +1,49 @@ +import { resolve as resolvePath } from 'node:path' +import { + isPathInsideOrEqual, + normalizeRuntimePathForComparison +} from '../shared/cross-platform-path' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../shared/execution-host' +import { resolveRealPathSync } from '../shared/real-path-sync' + +// One CLI process is one command, so the folder prefilter and ranking share each resolution. +const realPaths = new Map() + +/** A local path with symlinks resolved; a path that no longer exists keeps its lexical spelling. */ +function realPathOf(lexical: string): string { + let real = realPaths.get(lexical) + if (real === undefined) { + real = resolveRealPathSync(lexical) ?? lexical + realPaths.set(lexical, real) + } + return real +} + +/** + * Whether a workspace path contains cwd, and its comparison key for ranking. Paths on the caller's + * own filesystem compare by filesystem identity, so any symlink alias matches; a path on another + * host, or whose host is unknown, is never resolved here and compares as written. + */ +export function createCwdContainment( + cwd: string, + callerHostId: ExecutionHostId +): (path: string, onCallerFilesystem: boolean) => string | null { + const lexicalCwd = resolvePath(cwd) + const local = callerHostId === LOCAL_EXECUTION_HOST_ID + const realCwd = local ? realPathOf(lexicalCwd) : lexicalCwd + return (path, onCallerFilesystem) => { + const lexical = resolvePath(path) + const real = local && onCallerFilesystem ? realPathOf(lexical) : lexical + return isPathInsideOrEqual(real, realCwd) || isPathInsideOrEqual(lexical, lexicalCwd) + ? normalizeRuntimePathForComparison(real) + : null + } +} + +/** Unstamped rows belong to the answering Orca, as the caller-host rule treats them. */ +export function isOnCallerFilesystem(row: { + hostId?: string | null + hostUnresolved?: true +}): boolean { + return !row.hostUnresolved && (!row.hostId || row.hostId === LOCAL_EXECUTION_HOST_ID) +} diff --git a/src/cli/caller-folder-workspace.ts b/src/cli/caller-folder-workspace.ts index 090a8697225a..cf3efb61c678 100644 --- a/src/cli/caller-folder-workspace.ts +++ b/src/cli/caller-folder-workspace.ts @@ -3,11 +3,9 @@ import { getFolderSourceRepos } from '../shared/folder-workspaces/folder-workspa import type { ProjectGroup } from '../shared/project-group-types' import type { Repo } from '../shared/repo-types' import { folderWorkspaceKey, parseWorkspaceKey, type WorkspaceKey } from '../shared/workspace-scope' -import { selectEnclosingNativeFolderWorkspace } from './agent-workspace-selector' import { getOptionalStringFlag } from './flags' import { RuntimeClientError, type RuntimeClient } from './runtime-client' import { getOptionalWorktreeSelector } from './selectors' -import { selectorPurpose } from './caller-host-worktree-selection' export type FolderWorkspaceRepoChoice = { repo: string @@ -23,9 +21,8 @@ export function getCallerFolderWorkspaceKey(): WorkspaceKey | undefined { } /** - * A parent flag's value, where active/current also reaches native folder workspaces, which aren't - * catalog rows: the caller terminal's folder first (as create's no-flag inference picks it), then the - * enclosing checkout, then the enclosing folder. + * A parent flag's value. active/current follow the enclosing-workspace rule; outside every workspace a + * folder terminal still names its own folder, which isn't a cwd the catalog can contain. */ export async function getOptionalParentSelector( flags: Map, @@ -33,40 +30,25 @@ export async function getOptionalParentSelector( client: RuntimeClient ): Promise { const value = getOptionalStringFlag(flags, 'parent-worktree') - if (client.isRemote || (value !== 'active' && value !== 'current')) { - return await getOptionalWorktreeSelector(flags, 'parent-worktree', cwd, client) - } - const callerFolder = getCallerFolderWorkspaceKey() - if (callerFolder) { - return callerFolder - } try { return await getOptionalWorktreeSelector(flags, 'parent-worktree', cwd, client) } catch (error) { - // A worktree terminal's own workspace is a worktree; only other callers can mean a folder. + // A worktree terminal's own workspace is a worktree; only folder terminals fall back to a folder. const callerWorktree = process.env.ORCA_WORKTREE_ID?.trim() + const callerFolder = + callerWorktree && !callerWorktree.startsWith('folder:') + ? undefined + : getCallerFolderWorkspaceKey() if ( + client.isRemote || + (value !== 'active' && value !== 'current') || + !callerFolder || !(error instanceof RuntimeClientError) || - error.code !== 'selector_not_found' || - (callerWorktree && !callerWorktree.startsWith('folder:')) + error.code !== 'selector_not_found' ) { throw error } - // Several enclosing folders keep their choices; any other lookup failure keeps the original miss. - const enclosingFolder = await selectEnclosingNativeFolderWorkspace( - cwd, - client, - selectorPurpose('parent-worktree') - ).catch((lookupError: unknown) => { - if (lookupError instanceof RuntimeClientError && lookupError.code === 'selector_ambiguous') { - throw lookupError - } - return undefined - }) - if (!enclosingFolder) { - throw error - } - return enclosingFolder + return callerFolder } } diff --git a/src/cli/caller-host-worktree-selection.ts b/src/cli/caller-host-worktree-selection.ts index 50f459504978..de612795f829 100644 --- a/src/cli/caller-host-worktree-selection.ts +++ b/src/cli/caller-host-worktree-selection.ts @@ -1,11 +1,8 @@ import { resolve as resolvePath } from 'node:path' import type { TuiAgent } from '../shared/agent-launch/catalog/tui-agent' -import { - isPathInsideOrEqual, - normalizeRuntimePathForComparison -} from '../shared/cross-platform-path' import { projectGroupIdFromRepoId } from '../shared/folder-workspaces/folder-workspace-worktree' import { isFloatingWorkspaceId } from '../shared/floating-workspace-worktree' +import { parseWorkspaceKey } from '../shared/workspace-scope' import { LOCAL_EXECUTION_HOST_ID, parseExecutionHostId, @@ -13,13 +10,30 @@ import { type ExecutionHostId } from '../shared/execution-host' import { readOrchestrationCompatibilityEvidence } from '../shared/orchestration-compatibility-evidence' -import type { RuntimeWorktreeListResult, RuntimeWorktreeRecord } from '../shared/runtime-types' +import type { RuntimeWorktreeListResult } from '../shared/runtime-types' import type { RuntimeClient } from './runtime-client' import { RuntimeClientError } from './runtime/types' +import { refuseUnresolvedOwner, type CatalogRow } from './workspace-catalog-row' +import { createCwdContainment, isOnCallerFilesystem } from './caller-cwd-containment' + +export type { CatalogRow } + +/** Group-level folder workspaces join the catalog keyed `folder:`, beside repo-backed rows. */ +function isFolderRow(row: CatalogRow): boolean { + return parseWorkspaceKey(row.id)?.type === 'folder' +} + +/** The workspace this Orca terminal belongs to: a repo-backed id or a folder key. */ +export function getCallerWorkspaceIds( + env: Readonly> = process.env +): string[] { + return [env.ORCA_WORKTREE_ID, env.ORCA_WORKSPACE_ID].flatMap((id) => id?.trim() || []) +} + +type CallerWorkspace = string | readonly string[] | undefined -type CatalogRow = Pick & { - identity?: { key: string } - repoId?: string +function callerIdsOf(caller: CallerWorkspace): readonly string[] { + return caller === undefined ? [] : typeof caller === 'string' ? [caller] : caller } /** SSH relays stamp the caller host; otherwise use this machine. */ @@ -43,16 +57,16 @@ function enclosingCandidatesOnHost( cwd: string, hostId: ExecutionHostId ): { row: Row; comparisonPath: string }[] { - const currentPath = resolvePath(cwd) + const contains = createCwdContainment(cwd, hostId) const candidates: { row: Row; comparisonPath: string }[] = [] for (const row of catalog) { - if (!isOnCallerHost(row, hostId)) { + if (!row.hostUnresolved && !isOnCallerHost(row, hostId)) { continue } - const rawPath = resolvePath(row.path) - if (isPathInsideOrEqual(rawPath, currentPath)) { - // WSL comparison keys are not raw paths; only use them for rank and equivalence. - candidates.push({ row, comparisonPath: normalizeRuntimePathForComparison(rawPath) }) + // WSL comparison keys are not raw paths; only use them for rank and equivalence. + const comparisonPath = contains(row.path, isOnCallerFilesystem(row)) + if (comparisonPath !== null) { + candidates.push({ row, comparisonPath }) } } return candidates @@ -67,8 +81,9 @@ function worktreeSelections(rows: readonly CatalogRow[], catalog: readonly Catal hostsById.set(row.id, hosts) } return rows.map((row) => ({ - selector: - (hostsById.get(row.id)?.size ?? 0) > 1 && row.identity?.key + selector: isFolderRow(row) + ? row.id + : (hostsById.get(row.id)?.size ?? 0) > 1 && row.identity?.key ? `identity:${row.identity.key}` : `id:${row.id}`, worktreeId: row.id @@ -90,57 +105,42 @@ export function selectorPurpose(flag: string): WorkspaceSelectionPurpose { export type HostScopedWorktreeSelection = { selector: string; worktreeId: string } +/** Innermost wins; at equal depth the caller's own workspace wins; otherwise every distinct owner. */ function enclosingWorkspaceOwners( catalog: readonly CatalogRow[], cwd: string, hostId: ExecutionHostId, - callerWorktreeId?: string + caller?: CallerWorkspace ): CatalogRow[] { const candidates = enclosingCandidatesOnHost(catalog, cwd, hostId) const depth = Math.max(-1, ...candidates.map(({ comparisonPath }) => comparisonPath.length)) const innermost = candidates.filter(({ comparisonPath }) => comparisonPath.length === depth) - const caller = innermost.find(({ row }) => row.id === callerWorktreeId) - if (caller) { - return [caller.row] - } - const first = innermost[0] - if (!first) { - return [] + refuseUnresolvedOwner(innermost.map(({ row }) => row)) + const callerIds = callerIdsOf(caller) + const own = innermost.find(({ row }) => callerIds.includes(row.id)) + if (own) { + return [own.row] } const owners = new Map() - for (const { row, comparisonPath } of innermost) { - // Only the reserved same-checkout ownership tie changes; project classes remain separate. - if ( - comparisonPath === first.comparisonPath && - row.repoId === first.row.repoId && - (row.hostId ?? LOCAL_EXECUTION_HOST_ID) === (first.row.hostId ?? LOCAL_EXECUTION_HOST_ID) - ) { - const key = JSON.stringify([row.hostId ?? LOCAL_EXECUTION_HOST_ID, row.id]) - if (!owners.has(key)) { - owners.set(key, row) - } + for (const { row } of innermost) { + // Duplicate registrations of one row collapse; every other owner is a distinct choice. + const key = JSON.stringify([row.hostId ?? LOCAL_EXECUTION_HOST_ID, row.id]) + if (!owners.has(key)) { + owners.set(key, row) } } return [...owners.values()] } -export function hasEnclosingWorktreeOnHost( - catalog: readonly CatalogRow[], - cwd: string, - hostId: ExecutionHostId -): boolean { - return enclosingCandidatesOnHost(catalog, cwd, hostId).length > 0 -} - /** Workspace ownership stays separate from project inference: siblings can share a checkout. */ export function selectEnclosingWorktreeSelectionOnHost( catalog: readonly CatalogRow[], cwd: string, hostId: ExecutionHostId, - callerWorktreeId?: string, + caller?: CallerWorkspace, purpose: WorkspaceSelectionPurpose = 'worktree' ): HostScopedWorktreeSelection | undefined { - const owners = enclosingWorkspaceOwners(catalog, cwd, hostId, callerWorktreeId) + const owners = enclosingWorkspaceOwners(catalog, cwd, hostId, caller) const selections = worktreeSelections(owners, catalog) if (owners.length > 1) { const choices = selections.map(({ selector }) => selector) @@ -161,6 +161,7 @@ export function selectEnclosingWorktreeSelectionOnHost( `${action}More than one Orca workspace matched the current directory. Choose an exact ${purpose === 'parent' ? 'parent workspace' : 'workspace'}.`, { workspaces: owners.map((row, index) => ({ + kind: isFolderRow(row) ? 'folder workspace' : 'worktree', id: row.id, path: row.path, hostId: row.hostId ?? LOCAL_EXECUTION_HOST_ID, @@ -187,14 +188,14 @@ export function selectEnclosingWorktreeSelectionOnHost( } export function selectEnclosingRepoOnHost( - catalog: readonly (CatalogRow & Pick)[], + catalog: readonly CatalogRow[], cwd: string, hostId: ExecutionHostId, callerWorktreeId?: string ): string | undefined { const currentPath = resolvePath(cwd) const enclosing = enclosingCandidatesOnHost( - catalog.filter((row) => !projectGroupIdFromRepoId(row.repoId)), + catalog.filter((row) => !isFolderRow(row) && !projectGroupIdFromRepoId(row.repoId)), cwd, hostId ) @@ -233,7 +234,7 @@ export function selectEnclosingRepoOnHost( } export function selectWorktreeCreateCwdContext( - catalog: RuntimeWorktreeListResult['worktrees'], + catalog: readonly CatalogRow[], cwd: string, inferRepo: boolean, inferParent = true @@ -243,7 +244,7 @@ export function selectWorktreeCreateCwdContext( ? selectEnclosingRepoOnHost(catalog, cwd, hostId, process.env.ORCA_WORKTREE_ID) : undefined const owners = inferParent - ? enclosingWorkspaceOwners(catalog, cwd, hostId, process.env.ORCA_WORKTREE_ID) + ? enclosingWorkspaceOwners(catalog, cwd, hostId, getCallerWorkspaceIds()) : [] const selections = owners.length ? worktreeSelections(owners.slice(0, 1), catalog) : [] return { diff --git a/src/cli/enclosing-workspace-catalog.ts b/src/cli/enclosing-workspace-catalog.ts new file mode 100644 index 000000000000..36e6b2afa17d --- /dev/null +++ b/src/cli/enclosing-workspace-catalog.ts @@ -0,0 +1,69 @@ +import { createCwdContainment, isOnCallerFilesystem } from './caller-cwd-containment' +import { getCallerExecutionHostId } from './caller-host-worktree-selection' +import { resolveQualifiedFolderWorkspaceResult } from '../shared/folder-workspaces/folder-workspace-execution-host' +import type { FolderWorkspace } from '../shared/folder-workspaces/folder-workspace-types' +import type { ProjectGroup } from '../shared/project-group-types' +import type { Repo } from '../shared/repo-types' +import type { RuntimeWorktreeListResult } from '../shared/runtime-types' +import { folderWorkspaceKey } from '../shared/workspace-scope' +import type { CatalogRow } from './workspace-catalog-row' +import type { RuntimeClient } from './runtime-client' +import { RuntimeClientError } from './runtime/types' + +/** An older Orca without the folder catalog keeps its repo-backed rows; any other failure is real. */ +async function readOptional(read: Promise): Promise { + try { + return await read + } catch (error) { + if (error instanceof RuntimeClientError && error.code === 'method_not_found') { + return undefined + } + throw error + } +} + +/** + * Repo-backed rows plus the folder workspaces that enclose cwd, each with its derived host so the + * caller-host rules apply to both kinds. A folder whose host can't be derived stays in, marked + * unresolved, so selection refuses rather than silently skipping a possible owner. + */ +export async function readEnclosingWorkspaceCatalog( + client: RuntimeClient, + cwd: string +): Promise { + const [worktrees, folders] = await Promise.all([ + client.call('worktree.list', { limit: 10_000 }), + readOptional(client.call<{ folderWorkspaces: FolderWorkspace[] }>('folderWorkspace.list')) + ]) + const rows: CatalogRow[] = worktrees.result.worktrees + const allFolders = folders?.result.folderWorkspaces ?? [] + if (allFolders.length === 0) { + return rows + } + // Hosts come first: only a folder on the caller's own filesystem may be resolved locally. + const [groups, repos] = await Promise.all([ + readOptional(client.call<{ groups: ProjectGroup[] }>('projectGroup.list')), + readOptional(client.call<{ repos: Repo[] }>('repo.list')) + ]) + const contains = createCwdContainment(cwd, getCallerExecutionHostId()) + const folderRows = allFolders.flatMap((folder): CatalogRow[] => { + const host = + groups && repos + ? resolveQualifiedFolderWorkspaceResult( + { + folderWorkspaces: [folder], + projectGroups: groups.result.groups, + repos: repos.result.repos + }, + folder.id + ) + : null + const base = { id: folderWorkspaceKey(folder.id), path: folder.folderPath } + const row: CatalogRow = + host?.kind === 'selected' + ? { ...base, hostId: host.value.hostId } + : { ...base, hostUnresolved: true } + return contains(row.path, isOnCallerFilesystem(row)) === null ? [] : [row] + }) + return [...rows, ...folderRows] +} diff --git a/src/cli/enclosing-workspace-rule.test.ts b/src/cli/enclosing-workspace-rule.test.ts new file mode 100644 index 000000000000..11979dc34079 --- /dev/null +++ b/src/cli/enclosing-workspace-rule.test.ts @@ -0,0 +1,246 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, describe, expect, it, vi } from 'vitest' +import { + selectEnclosingWorktreeSelectionOnHost, + type CatalogRow +} from './caller-host-worktree-selection' +import { readEnclosingWorkspaceCatalog } from './enclosing-workspace-catalog' +import { RuntimeClient } from './runtime-client' +import { RuntimeClientError } from './runtime/types' +import { okFixture } from './test-fixtures' + +const hubFolder = { id: 'folder:hub', path: '/tmp/hub', hostId: 'local' as const } +const innerFolder = { id: 'folder:inner', path: '/tmp/hub/inner', hostId: 'local' as const } +const nested = { + id: 'repo::/tmp/hub/app', + path: '/tmp/hub/app', + hostId: 'local' as const, + repoId: 'repo' +} +const atHub = { id: 'repo::/tmp/hub', path: '/tmp/hub', hostId: 'local' as const, repoId: 'repo' } + +function select(rows: CatalogRow[], cwd: string, caller?: string[]) { + return selectEnclosingWorktreeSelectionOnHost(rows, cwd, 'local', caller)?.selector +} + +describe('one enclosing-workspace rule across worktrees and folder workspaces', () => { + it('picks the innermost workspace of either kind', () => { + expect(select([hubFolder, nested], '/tmp/hub/notes')).toBe('folder:hub') + expect(select([hubFolder, nested], '/tmp/hub/app/src')).toBe('id:repo::/tmp/hub/app') + // The caller's outer folder no longer beats a deeper one. + expect(select([hubFolder, innerFolder], '/tmp/hub/inner/x', ['folder:hub'])).toBe( + 'folder:inner' + ) + }) + + it("breaks an equal-depth tie with the caller's own workspace, otherwise refuses", () => { + expect(select([atHub, hubFolder], '/tmp/hub/x', ['folder:hub'])).toBe('folder:hub') + expect(select([hubFolder, atHub], '/tmp/hub/x', [atHub.id])).toBe('id:repo::/tmp/hub') + for (const rows of [ + [atHub, hubFolder], + [hubFolder, atHub] + ]) { + expect(() => select(rows, '/tmp/hub/x')).toThrow( + expect.objectContaining({ code: 'selector_ambiguous' }) + ) + } + }) +}) + +function clientAnswering(answer: (method: string) => ReturnType): RuntimeClient { + const client = new RuntimeClient('/tmp/orca-enclosing-rule', 60_000, null, null) + vi.spyOn(client, 'call').mockImplementation(async (method: string) => answer(method)) + return client +} + +describe('owners registered at one path', () => { + it('refuses distinct registrations without a caller, whatever their repo', () => { + const repoA = { + id: 'repo-a::checkout', + repoId: 'repo-a', + path: '/tmp/hub/app', + hostId: 'local' as const + } + const repoB = { + id: 'repo-b::checkout', + repoId: 'repo-b', + path: '/tmp/hub/app', + hostId: 'local' as const + } + for (const rows of [ + [repoA, repoB], + [repoB, repoA] + ]) { + expect(() => select(rows, '/tmp/hub/app/src')).toThrow( + expect.objectContaining({ code: 'selector_ambiguous' }) + ) + expect(select(rows, '/tmp/hub/app/src', [repoB.id])).toBe('id:repo-b::checkout') + } + }) +}) + +// Symlinks need privileges on Windows; macOS /tmp and Linux bind aliases behave like this fixture. +describe.skipIf(process.platform === 'win32')('symlink aliases on the caller filesystem', () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-enclosing-alias-'))) + const real = join(root, 'real') + const alias = join(root, 'alias') + mkdirSync(join(real, 'hub', 'app', 'src'), { recursive: true }) + symlinkSync(real, alias) + afterAll(() => rmSync(root, { recursive: true, force: true })) + + const outer = (base: string) => ({ + id: 'folder:outer', + path: join(base, 'hub'), + hostId: 'local' as const + }) + const inner = (base: string, kind: 'folder' | 'worktree') => + kind === 'folder' + ? { id: 'folder:inner', path: join(base, 'hub', 'app'), hostId: 'local' as const } + : { + id: 'repo::inner', + repoId: 'repo', + path: join(base, 'hub', 'app'), + hostId: 'local' as const + } + + it.each([ + ['folder', real, alias], + ['folder', alias, real], + ['worktree', real, alias], + ['worktree', alias, real] + ] as const)( + 'picks the deeper %s stored under one spelling from cwd under the other', + (kind, cwdBase, innerBase) => { + const cwd = join(cwdBase, 'hub', 'app', 'src') + const expected = kind === 'folder' ? 'folder:inner' : 'id:repo::inner' + expect(select([outer(cwdBase), inner(innerBase, kind)], cwd)).toBe(expected) + expect(select([inner(innerBase, kind)], cwd)).toBe(expected) + } + ) + + it.each(['folder', 'worktree'] as const)( + 'picks a %s registered through a differently named link, from cwd via a second link', + (kind) => { + const workspaceLink = join(root, `workspace-link-${kind}`) + const cwdLink = join(root, `cwd-link-${kind}`) + symlinkSync(join(real, 'hub', 'app'), workspaceLink) + symlinkSync(join(real, 'hub', 'app'), cwdLink) + const registered = + kind === 'folder' + ? { id: 'folder:inner', path: workspaceLink, hostId: 'local' as const } + : { id: 'repo::inner', repoId: 'repo', path: workspaceLink, hostId: 'local' as const } + const expected = kind === 'folder' ? 'folder:inner' : 'id:repo::inner' + for (const cwd of [join(real, 'hub', 'app', 'src'), join(cwdLink, 'src')]) { + expect(select([outer(real), registered], cwd)).toBe(expected) + } + } + ) + + it('keeps an aliased folder in the catalog prefilter', async () => { + const client = clientAnswering((method) => + method === 'worktree.list' + ? okFixture('list', { worktrees: [] }) + : method === 'folderWorkspace.list' + ? okFixture('folders', { + folderWorkspaces: [ + { id: 'inner', folderPath: join(alias, 'hub', 'app'), projectGroupId: 'g' } + ] + }) + : method === 'projectGroup.list' + ? okFixture('groups', { groups: [{ id: 'g' }] }) + : okFixture('repos', { repos: [] }) + ) + expect(await readEnclosingWorkspaceCatalog(client, join(real, 'hub', 'app', 'src'))).toEqual([ + { id: 'folder:inner', path: join(alias, 'hub', 'app'), hostId: 'local' } + ]) + }) +}) + +describe('a folder workspace whose host is unknown', () => { + const unresolvedHub = { id: 'folder:hub', path: '/tmp/hub', hostUnresolved: true as const } + + it('refuses rather than skipping it when it is the innermost owner', () => { + for (const rows of [[unresolvedHub], [unresolvedHub, atHub]]) { + expect(() => select(rows, '/tmp/hub/notes')).toThrow( + expect.objectContaining({ + code: 'selector_ambiguous', + message: expect.stringContaining("can't tell which host owns the folder workspace"), + data: expect.objectContaining({ + nextSteps: expect.arrayContaining([ + 'Pass --worktree folder:hub to target the folder workspace itself.' + ]) + }) + }) + ) + } + }) + + it('does not block a deeper worktree inside it', () => { + expect(select([unresolvedHub, nested], '/tmp/hub/app/src')).toBe('id:repo::/tmp/hub/app') + }) +}) + +describe('enclosing-workspace catalog', () => { + it('derives folder hosts and keeps only folders that enclose cwd', async () => { + const client = clientAnswering((method) => + method === 'worktree.list' + ? okFixture('list', { worktrees: [nested] }) + : method === 'folderWorkspace.list' + ? okFixture('folders', { + folderWorkspaces: [ + { id: 'hub', folderPath: '/tmp/hub', projectGroupId: 'local-group' }, + { id: 'far', folderPath: '/tmp/far', projectGroupId: 'local-group' }, + { id: 'ssh-hub', folderPath: '/tmp/hub', projectGroupId: 'ssh-group' } + ] + }) + : method === 'projectGroup.list' + ? okFixture('groups', { + groups: [{ id: 'local-group' }, { id: 'ssh-group', connectionId: 'box' }] + }) + : okFixture('repos', { repos: [] }) + ) + expect(await readEnclosingWorkspaceCatalog(client, '/tmp/hub/notes')).toEqual([ + nested, + { id: 'folder:hub', path: '/tmp/hub', hostId: 'local' }, + { id: 'folder:ssh-hub', path: '/tmp/hub', hostId: 'ssh:box' } + ]) + }) + + it('keeps an enclosing folder whose host inputs are missing, marked unresolved', async () => { + const client = clientAnswering((method) => { + if (method === 'worktree.list') { + return okFixture('list', { worktrees: [] }) + } + if (method === 'folderWorkspace.list') { + return okFixture('folders', { + folderWorkspaces: [{ id: 'hub', folderPath: '/tmp/hub', projectGroupId: 'group' }] + }) + } + throw new RuntimeClientError('method_not_found', 'Unknown method') + }) + expect(await readEnclosingWorkspaceCatalog(client, '/tmp/hub/notes')).toEqual([ + { id: 'folder:hub', path: '/tmp/hub', hostUnresolved: true } + ]) + }) + + it('falls back to worktree rows only when the folder catalog is missing', async () => { + const missing = clientAnswering((method) => { + if (method === 'worktree.list') { + return okFixture('list', { worktrees: [nested] }) + } + throw new RuntimeClientError('method_not_found', 'Unknown method') + }) + expect(await readEnclosingWorkspaceCatalog(missing, '/tmp/hub/app')).toEqual([nested]) + const down = clientAnswering((method) => { + if (method === 'worktree.list') { + return okFixture('list', { worktrees: [nested] }) + } + throw new RuntimeClientError('runtime_unavailable', 'connection closed') + }) + await expect(readEnclosingWorkspaceCatalog(down, '/tmp/hub/app')).rejects.toMatchObject({ + code: 'runtime_unavailable' + }) + }) +}) diff --git a/src/cli/execution-host-flag.ts b/src/cli/execution-host-flag.ts index e79ebb658039..3720e25fba1d 100644 --- a/src/cli/execution-host-flag.ts +++ b/src/cli/execution-host-flag.ts @@ -21,6 +21,7 @@ import { } from './host-selector-alternatives' import type { RuntimeClient } from './runtime-client' import { RuntimeClientError } from './runtime/types' +import { isLocalEnvironmentSelector } from './local-environment-selector' export type HostFlagRoutingSelection = { // Enumerating SSH targets needs the running host; defer lookup until error recovery. @@ -137,9 +138,10 @@ export async function resolveHostFlagEnvironmentId( } if (selection.environmentSelector) { const { value } = selection.environmentSelector - const selected = - findEnvironmentByName(environments, value) ?? resolveEnvironment(userDataPath, value) - if (selected.id !== environment.id) { + const selected = isLocalEnvironmentSelector(value) + ? null + : (findEnvironmentByName(environments, value) ?? resolveEnvironment(userDataPath, value)) + if (selected?.id !== environment.id) { throw new RuntimeClientError( 'invalid_argument', `${flagSpelling} and ${selection.environmentSelector.label} ${selection.environmentSelector.value} name different Orca servers.` diff --git a/src/cli/flag-help-text.ts b/src/cli/flag-help-text.ts index 8bf6104dbc90..9c29a301d430 100644 --- a/src/cli/flag-help-text.ts +++ b/src/cli/flag-help-text.ts @@ -14,7 +14,7 @@ export const FLAG_HELP_TEXT: Record = { '--direction Direction: up|down|left|right for scroll, horizontal|vertical for split', 'display-name': '--display-name Override the Orca display name', environment: - '--environment Run against a saved paired Orca server (id or name); terminal handles belong to the server that issued them', + "--environment Run against a saved paired Orca server (id or name), or `local` for this machine's own Orca over ORCA_ENVIRONMENT/ORCA_PAIRING_CODE; terminal handles belong to the server that issued them", 'pairing-code': '--pairing-code Run against a remote Orca server using an orca://pair?... code', 'element-index': '--element-index Element index from get-app-state', @@ -57,6 +57,8 @@ export const FLAG_HELP_TEXT: Record = { pages: '--pages Number of scroll pages', 'parent-worktree': '--parent-worktree Parent worktree selector such as identity:, id:::, folder:, name:, branch:, issue:, path:, or active/current', + 'parent-environment': + "--parent-environment Environment holding --parent-worktree: local, or a saved environment id or name (default: the worktree's own)", path: '--path Path argument for the command', pr: '--pr Linked GitHub pull request number; null clears on set', prompt: '--prompt Prompt text for agent-backed commands', diff --git a/src/cli/handlers/agent-launch.ts b/src/cli/handlers/agent-launch.ts index 478df4f59a3b..df4f2536ba55 100644 --- a/src/cli/handlers/agent-launch.ts +++ b/src/cli/handlers/agent-launch.ts @@ -9,8 +9,7 @@ import { import { getRequiredStringFlag } from '../flags' import { printResult } from '../format' import { RuntimeClientError } from '../runtime-client' -import { getRequiredWorktreeSelector } from '../selectors' -import { resolveCurrentAgentWorkspaceSelector } from '../agent-workspace-selector' +import { getRequiredWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors' export const AGENT_LAUNCH_HANDLERS: Record = { 'agent launch': async ({ flags, client, cwd, json, rawArgs }) => { @@ -26,7 +25,7 @@ export const AGENT_LAUNCH_HANDLERS: Record = { const selector = flags.get('worktree') const current = selector === undefined || selector === 'active' || selector === 'current' const worktree = current - ? await resolveCurrentAgentWorkspaceSelector(cwd, client, { agent: launch.agent }) + ? await resolveCurrentWorktreeSelector(cwd, client, { agent: launch.agent }) : await getRequiredWorktreeSelector(flags, 'worktree', cwd, client) const capabilities = await getAgentLaunchCapabilities(client) if (!capabilities) { diff --git a/src/cli/handlers/computer.test.ts b/src/cli/handlers/computer.test.ts index 1a681190ac00..18fdbf5456e8 100644 --- a/src/cli/handlers/computer.test.ts +++ b/src/cli/handlers/computer.test.ts @@ -15,7 +15,13 @@ vi.mock('../runtime-client', async () => { }) import { main } from '../index' -import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from '../test-fixtures' +import { + buildWorktree, + noFolderWorkspacesFixture, + okFixture, + queueFixtures, + worktreeListFixture +} from '../test-fixtures' describe('orca computer observation CLI handlers', () => { beforeEach(() => { @@ -165,6 +171,7 @@ describe('orca computer observation CLI handlers', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo', 'feature')]), + noFolderWorkspacesFixture(), okFixture('req_state', sampleSnapshot()) ) @@ -181,7 +188,7 @@ describe('orca computer observation CLI handlers', () => { '/tmp/repo/src' ) - expect(callMock).toHaveBeenNthCalledWith(2, 'computer.getAppState', { + expect(callMock).toHaveBeenNthCalledWith(3, 'computer.getAppState', { app: 'Finder', worktree: 'id:repo::/tmp/repo', noScreenshot: true, diff --git a/src/cli/handlers/environment.ts b/src/cli/handlers/environment.ts index 8c55ac12eb70..4d3383bf3528 100644 --- a/src/cli/handlers/environment.ts +++ b/src/cli/handlers/environment.ts @@ -33,6 +33,7 @@ import { type EnvironmentRemoveResult } from '../runtime/environments' import { exchangeCliPairingCode } from '../runtime/environment-pairing-exchange' +import { refuseReservedEnvironmentName } from '../local-environment-selector' import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store' export const ENVIRONMENT_HANDLERS: Record = { @@ -58,6 +59,7 @@ export const ENVIRONMENT_HANDLERS: Record = { }, 'environment add': async ({ flags, json }) => { const name = getRequiredStringFlag(flags, 'name') + refuseReservedEnvironmentName(name) const pairingCode = await exchangeCliPairingCode(getRequiredStringFlag(flags, 'pairing-code')) const environment = redactRuntimeEnvironment( addEnvironmentFromPairingCode(getDefaultUserDataPath(), { diff --git a/src/cli/handlers/file-absolute-paths.test.ts b/src/cli/handlers/file-absolute-paths.test.ts index 56b579cc9db1..28fb9147a2e6 100644 --- a/src/cli/handlers/file-absolute-paths.test.ts +++ b/src/cli/handlers/file-absolute-paths.test.ts @@ -32,7 +32,13 @@ vi.mock('../runtime-client', () => { }) import { main } from '../index' -import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from '../test-fixtures' +import { + buildWorktree, + noFolderWorkspacesFixture, + okFixture, + queueFixtures, + worktreeListFixture +} from '../test-fixtures' describe('absolute file CLI paths', () => { beforeEach(() => { @@ -55,6 +61,9 @@ describe('absolute file CLI paths', () => { if (method === 'worktree.list') { return worktreeListFixture([buildWorktree('/root/orca/workspaces/xxx', 'feature')]) } + if (method === 'folderWorkspace.list') { + return noFolderWorkspacesFixture() + } if (method === 'worktree.show') { return okFixture('req_show', { worktree: buildWorktree('/root/orca/workspaces/xxx', 'feature') @@ -75,10 +84,10 @@ describe('absolute file CLI paths', () => { expect(process.exitCode).toBeUndefined() expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', { limit: 10_000 }) - expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.show', { + expect(callMock).toHaveBeenNthCalledWith(3, 'worktree.show', { worktree: 'id:repo::/root/orca/workspaces/xxx' }) - expect(callMock).toHaveBeenNthCalledWith(3, 'files.open', { + expect(callMock).toHaveBeenNthCalledWith(4, 'files.open', { worktree: 'id:repo::/root/orca/workspaces/xxx', relativePath: 'xxx/xxx.ts', navigation: 'caller' diff --git a/src/cli/handlers/file.test.ts b/src/cli/handlers/file.test.ts index 3a8fb0089872..fdb0c6850f9b 100644 --- a/src/cli/handlers/file.test.ts +++ b/src/cli/handlers/file.test.ts @@ -45,7 +45,13 @@ vi.mock('../runtime-client', () => { }) import { main } from '../index' -import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from '../test-fixtures' +import { + buildWorktree, + noFolderWorkspacesFixture, + okFixture, + queueFixtures, + worktreeListFixture +} from '../test-fixtures' describe('orca file CLI handlers', () => { beforeEach(() => { @@ -69,6 +75,7 @@ describe('orca file CLI handlers', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo', 'feature')]), + noFolderWorkspacesFixture(), okFixture('req_open', { worktree: 'wt-1', relativePath: 'src/App.tsx', @@ -80,7 +87,7 @@ describe('orca file CLI handlers', () => { await main(['file', 'open', 'src/App.tsx'], '/tmp/repo/src') expect(callMock).toHaveBeenNthCalledWith(1, 'worktree.list', { limit: 10_000 }) - expect(callMock).toHaveBeenNthCalledWith(2, 'files.open', { + expect(callMock).toHaveBeenNthCalledWith(3, 'files.open', { worktree: 'id:repo::/tmp/repo', relativePath: 'src/App.tsx', navigation: 'caller' @@ -216,6 +223,7 @@ describe('orca file CLI handlers', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo', 'feature')]), + noFolderWorkspacesFixture(), okFixture('req_status', { entries: [ { path: 'src/App.tsx', status: 'modified', area: 'unstaged' }, @@ -246,22 +254,22 @@ describe('orca file CLI handlers', () => { await main(['file', 'open-changed'], '/tmp/repo/src') - expect(callMock).toHaveBeenNthCalledWith(2, 'git.status', { + expect(callMock).toHaveBeenNthCalledWith(3, 'git.status', { worktree: 'id:repo::/tmp/repo' }) - expect(callMock).toHaveBeenNthCalledWith(3, 'files.openDiff', { + expect(callMock).toHaveBeenNthCalledWith(4, 'files.openDiff', { worktree: 'id:repo::/tmp/repo', relativePath: 'src/App.tsx', staged: false, navigation: 'caller' }) - expect(callMock).toHaveBeenNthCalledWith(4, 'files.openDiff', { + expect(callMock).toHaveBeenNthCalledWith(5, 'files.openDiff', { worktree: 'id:repo::/tmp/repo', relativePath: 'package.json', staged: true, navigation: 'caller' }) - expect(callMock).toHaveBeenNthCalledWith(5, 'files.openDiff', { + expect(callMock).toHaveBeenNthCalledWith(6, 'files.openDiff', { worktree: 'id:repo::/tmp/repo', relativePath: 'docs/new.md', staged: false, diff --git a/src/cli/handlers/orchestration/worker-start-implicit-coordinator.test.ts b/src/cli/handlers/orchestration/worker-start-implicit-coordinator.test.ts index c87161002d5f..895772c3eaea 100644 --- a/src/cli/handlers/orchestration/worker-start-implicit-coordinator.test.ts +++ b/src/cli/handlers/orchestration/worker-start-implicit-coordinator.test.ts @@ -21,6 +21,9 @@ describe('worker-start infers its coordinator from the caller, not the worker pl if (method === 'worktree.list') { return okFixture('req_list', { worktrees: [COORDINATOR_WORKTREE] }) } + if (method === 'folderWorkspace.list') { + return okFixture('req_folders', { folderWorkspaces: [] }) + } if (method === 'terminal.resolveActive') { const worktree = params && typeof params === 'object' && 'worktree' in params ? params.worktree : undefined diff --git a/src/cli/handlers/ports.ts b/src/cli/handlers/ports.ts index 4745bc13d434..ba6e9f30c4ab 100644 --- a/src/cli/handlers/ports.ts +++ b/src/cli/handlers/ports.ts @@ -4,7 +4,6 @@ import type { RuntimeStatus, RuntimeWorktreeRecord } from '../../shared/runtime- import { WORKSPACE_SELECTOR_FOLDER_MATCH_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities' import type { WorkspacePortHostScanResult } from '../../shared/workspace-ports' import { parseWorkspaceKey } from '../../shared/workspace-scope' -import { resolveCurrentAgentWorkspaceSelector } from '../agent-workspace-selector' import type { CommandHandler, HandlerContext } from '../dispatch' import { getOptionalStringFlag } from '../flags' import { printResult } from '../format' @@ -14,7 +13,7 @@ import { RuntimeRpcFailureError, type RuntimeRpcSuccess } from '../runtime-client' -import { normalizeWorktreeSelectorForCaller } from '../selectors' +import { normalizeWorktreeSelectorForCaller, resolveCurrentWorktreeSelector } from '../selectors' type PortsTarget = { selector: string; worktreePath: string | null } @@ -106,7 +105,7 @@ async function resolvePortsTarget( const explicit = getOptionalStringFlag(flags, 'worktree') const selector = !explicit || explicit === 'active' || explicit === 'current' - ? await resolveCurrentAgentWorkspaceSelector(cwd, client, 'ports') + ? await resolveCurrentWorktreeSelector(cwd, client, 'ports') : await resolveNativeFolderPathSelector( await normalizeWorktreeSelectorForCaller(explicit, cwd, client), client diff --git a/src/cli/handlers/worktree-address-annotation.ts b/src/cli/handlers/worktree-address-annotation.ts new file mode 100644 index 000000000000..a543e1b7f9b8 --- /dev/null +++ b/src/cli/handlers/worktree-address-annotation.ts @@ -0,0 +1,30 @@ +import type { RuntimeWorktreePsSummary, RuntimeWorktreeRecord } from '../../shared/runtime-types' +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<(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 { + const [annotation] = await annotateListing(client, () => callerOrcaClient(client), [ + addressableOfShowRecord(response.result.worktree) + ]) + return { + ...response, + result: { ...response.result, worktree: { ...response.result.worktree, ...annotation } } + } +} diff --git a/src/cli/handlers/worktree-create-parent-selector.ts b/src/cli/handlers/worktree-create-parent-selector.ts index 3d6682740996..9c57522bd885 100644 --- a/src/cli/handlers/worktree-create-parent-selector.ts +++ b/src/cli/handlers/worktree-create-parent-selector.ts @@ -1,15 +1,14 @@ import { isWorkspaceKey, worktreeWorkspaceKey } from '../../shared/workspace-scope' import { getOptionalStringFlag } from '../flags' import { RuntimeClientError, type RuntimeClient } from '../runtime-client' -import { getOptionalWorktreeSelector } from '../selectors' import { getOptionalParentSelector } from '../caller-folder-workspace' -import { callerOrcaClient } from './worktree-parent-fields' +import { resolveParentEnvironment, type ParentEnvironment } from './worktree-parent-environment' export type CreateParentSelector = { parentWorktree?: string parentWorkspace?: string - /** active/current against a server: the parent is on this machine, not the server. */ - onCallerMachine?: true + /** 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.' @@ -40,10 +39,14 @@ export async function resolveCreateParentSelector( cwd: string, client: RuntimeClient ): Promise { + 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) { @@ -51,15 +54,6 @@ export async function resolveCreateParentSelector( return { parentWorkspace } } - if (client.isRemote && (rawParentWorktree === 'active' || rawParentWorktree === 'current')) { - const callerParent = await getOptionalWorktreeSelector( - flags, - 'parent-worktree', - cwd, - callerOrcaClient(client) - ) - return { parentWorktree: callerParent, onCallerMachine: true } - } const parentWorktree = await getOptionalParentSelector(flags, cwd, client) const resolvedParentWorkspace = parentWorktree ? getWorkspaceKeyParentSelector(parentWorktree) diff --git a/src/cli/handlers/worktree-parent-environment.ts b/src/cli/handlers/worktree-parent-environment.ts new file mode 100644 index 000000000000..73ae5caac228 --- /dev/null +++ b/src/cli/handlers/worktree-parent-environment.ts @@ -0,0 +1,292 @@ +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, RuntimeWorktreeRecord } from '../../shared/runtime-types' +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 '../caller-folder-workspace' +import { getOptionalStringFlag } from '../flags' +import { mayNameFolderWorkspace } from '../folder-workspace-selector' +import { isLocalEnvironmentSelector, LOCAL_ENVIRONMENT } from '../local-environment-selector' +import { RuntimeClient, RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' +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 --pairing-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, + 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 { + const status = (await client.call('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 { + 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 --pairing-code `, then run `orca worktree ps --environment --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; cwd: string; environment: ParentEnvironment } +): Promise { + 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 +>( + client: RuntimeClient, + method: 'worktree.create' | 'worktree.set', + params: Params +): Promise> { + try { + return await client.call(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 (a row's address.environment from \`orca worktree ps --environment --json\`).` + ] + : [] + ) + ) + } +} diff --git a/src/cli/handlers/worktree-parent-fields.ts b/src/cli/handlers/worktree-parent-fields.ts index 8ec382200d68..02c82850d5a3 100644 --- a/src/cli/handlers/worktree-parent-fields.ts +++ b/src/cli/handlers/worktree-parent-fields.ts @@ -1,21 +1,24 @@ -import type { RuntimeStatus, RuntimeWorktreeRecord } from '../../shared/runtime-types' +import type { RuntimeStatus } from '../../shared/runtime-types' import { parseWorkspaceKey } from '../../shared/workspace-scope' import type { CrossStoreInferredSource, CrossStoreParentRef } from '../../shared/worktree/lineage-types' -import { crossStoreParentRefOfRow } from '../../shared/worktree/lineage-row-identity' import { - assertCrossStoreLineageSupported, assertFolderParentSetSupported, supportsCrossStoreLineage } from '../../shared/worktree-runtime-capabilities' import { getOptionalStringFlag } from '../flags' import { RuntimeClient, RuntimeClientError } from '../runtime-client' -import { getOptionalWorktreeSelector, resolveWorktreeCreateCwdContext } from '../selectors' +import { resolveWorktreeCreateCwdContext } from '../selectors' import { mayNameFolderWorkspace } from '../folder-workspace-selector' import { parentCwdNextSteps, withWorktreeSelectorRecovery } from '../worktree-selector-recovery' import { getOptionalParentSelector } from '../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 @@ -24,66 +27,32 @@ export function callerOrcaClient(client: RuntimeClient): RuntimeClient { return client.isRemote ? new RuntimeClient(client.userDataPath, undefined, null, null) : client } -/** - * A parent on this machine for a workspace on the connected server. The server must advertise the - * capability before anything is sent (an older one would apply the rest and drop the parent); this - * desktop's Orca supplies its own installationId and the parent row's identity. - */ -async function resolveCallerCrossStoreParent( - client: RuntimeClient, - selector: string | undefined -): Promise { - if (!selector) { - return undefined - } - const status = (await client.call('status.get')).result - assertCrossStoreLineageSupported(status.capabilities, serverLabel(client)) - return await readCallerParentRef(client, selector) -} - -async function readCallerParentRef( - client: RuntimeClient, - selector: string -): Promise { - const local = callerOrcaClient(client) - const parent = ( - await local.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', { worktree: selector }) - ).result.worktree - const { installationId } = (await local.call<{ installationId?: string }>('worktree.lineageList')) - .result - const ref = crossStoreParentRefOfRow(installationId, parent) - if (!ref) { - throw new RuntimeClientError( - 'invalid_argument', - "Couldn't confirm the parent's machine or workspace identity. Refresh it and try again." - ) - } - return ref -} - function serverLabel(client: RuntimeClient): string { return client.environmentSelector ?? 'the connected server' } -/** `worktree create`'s parent fields. Explicit active/current against a server is a parent on this - * machine; with no parent flag, the caller's own workspace there is inferred the same way. */ +/** `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: { parentWorktree?: string; parentWorkspace?: string; onCallerMachine?: true } + explicitParent: CreateParentSelector inferredParent: string | undefined cwd: string + flags: Map cwdContext: { parentWorktree?: { selector: string }; parentAmbiguous?: true } callerTerminalHandle: string | undefined noParent: boolean } ): Promise> { const { explicitParent, inferredParent, cwdContext, noParent } = args - if (explicitParent.onCallerMachine) { - const crossStoreParent = await resolveCallerCrossStoreParent( - client, - explicitParent.parentWorktree - ) + if (explicitParent.parentEnvironment) { + const crossStoreParent = await resolveCrossEnvironmentParent(client, { + flags: args.flags, + cwd: args.cwd, + environment: explicitParent.parentEnvironment + }) return { crossStoreParent, noParent } } const targetParent = { @@ -182,7 +151,7 @@ async function inferCallerCrossStoreParent( } } -/** `worktree set`'s parent: active/current against a server names this machine's workspace. */ +/** `worktree set`'s parent; one in another environment is sent as a verified cross-store ref. */ export async function resolveSetParentFields( flags: Map, cwd: string, @@ -192,20 +161,17 @@ export async function resolveSetParentFields( 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) } } - if (client.isRemote && (raw === 'active' || raw === 'current')) { - const selector = await getOptionalWorktreeSelector( - flags, - 'parent-worktree', - cwd, - callerOrcaClient(client) - ) - return { crossStoreParent: await resolveCallerCrossStoreParent(client, selector) } - } const parentWorktree = await withWorktreeSelectorRecovery( getOptionalParentSelector(flags, cwd, client), parentCwdNextSteps(raw), diff --git a/src/cli/handlers/worktree-removal-current-refusal.ts b/src/cli/handlers/worktree-removal-current-refusal.ts new file mode 100644 index 000000000000..c210fa5f8c75 --- /dev/null +++ b/src/cli/handlers/worktree-removal-current-refusal.ts @@ -0,0 +1,67 @@ +import { getOptionalStringFlag } from '../flags' +import { assertLocalCwdWorktreeSelector } from '../local-environment-selector' +import { RuntimeClientError, type RuntimeClient } from '../runtime-client' +import { resolveCurrentWorktreeSelector } from '../selectors' +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, + cwd: string, + client: RuntimeClient +): Promise { + 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`.'] + : []) + ] + } + ) +} diff --git a/src/cli/handlers/worktree-setup-decision-recovery.ts b/src/cli/handlers/worktree-setup-decision-recovery.ts index 5af0bb10c727..924f48d5e679 100644 --- a/src/cli/handlers/worktree-setup-decision-recovery.ts +++ b/src/cli/handlers/worktree-setup-decision-recovery.ts @@ -1,3 +1,4 @@ +import { getPresentStringFlag } from '../flags' import { RuntimeClientError, RuntimeRpcFailureError } from '../runtime/types' // Hosts use generic runtime_error here; this message is the stable discriminator. @@ -44,3 +45,20 @@ export function attachCliErrorData(error: RuntimeClientError, data: unknown): Ru } return new RuntimeClientError(error.code, error.message, data) } + +/** --setup's value, refusing a contradiction with --run-hooks. */ +export function getOptionalSetupDecision( + flags: Map +): '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 +} diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.ts index 0ebafe013f1c..d1ff9d7bf722 100644 --- a/src/cli/handlers/worktree.ts +++ b/src/cli/handlers/worktree.ts @@ -33,6 +33,9 @@ import { parseCliAgent, readCliAgentLaunch } from '../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, @@ -48,7 +51,10 @@ import { import { getOptionalLinearIssueLinkFlag } from './worktree-linear-issue-link' import { getWorktreeReadFlags } from './worktree-unread-flag' import { getReviewTargetLinkFlags } from './worktree-review-link-flags' -import { withSetupDecisionRecovery } from './worktree-setup-decision-recovery' +import { + getOptionalSetupDecision, + withSetupDecisionRecovery +} from './worktree-setup-decision-recovery' import { assertGitLabLinkFlagProjectsMatch } from './worktree-gitlab-link-context' import { assertReferenceWritesSupported, @@ -70,22 +76,6 @@ function getOptionalStartupAgent(flags: Map): TuiAgent return parseCliAgent(agent) } -function getOptionalSetupDecision( - flags: Map -): '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 -} - export const WORKTREE_HANDLERS: Record = { 'worktree ps': async ({ flags, client, json }) => { const result = await client.call>( @@ -96,9 +86,10 @@ export const WORKTREE_HANDLERS: Record = { } ) await annotateOmittedHostScope(result.result) - const worktrees = result.result.worktrees.map(projectWorktreePsTerminalVerdict) + 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) + formatWorktreePs({ ...result.result, worktrees: annotate(result.result.worktrees) }) ) }, 'worktree list': async ({ flags, client, json }) => { @@ -117,13 +108,13 @@ export const WORKTREE_HANDLERS: Record = { worktree: await getRequiredWorktreeSelector(flags, 'worktree', cwd, client), matchFolderWorkspaces: true }) - printResult(result, json, formatWorktreeShow) + 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(result, json, formatWorktreeShow) + printResult(await annotateShown(client, result), json, formatWorktreeShow) }, 'worktree create': async (context) => { const { flags, client, cwd, json, rawArgs } = context @@ -201,6 +192,7 @@ export const WORKTREE_HANDLERS: Record = { explicitParent, inferredParent: envParentWorkspace, cwd, + flags, cwdContext, callerTerminalHandle, noParent @@ -213,7 +205,7 @@ export const WORKTREE_HANDLERS: Record = { return } const result = await withSetupDecisionRecovery( - client.call('worktree.create', create) + callNamingParentEnvironment(client, 'worktree.create', create) ) printHookWarning(result.result, json) printLineageSummary(result.result, json) @@ -236,7 +228,7 @@ export const WORKTREE_HANDLERS: Record = { } await assertGitLabLinkFlagProjectsMatch(flags, client, { worktree }) const parentFields = await resolveSetParentFields(flags, cwd, client) - const pending = client.call('worktree.set', { + const pending = callNamingParentEnvironment(client, 'worktree.set', { worktree, displayName: getOptionalStringFlag(flags, 'display-name'), ...reviewLinks, @@ -266,6 +258,7 @@ export const WORKTREE_HANDLERS: Record = { 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 diff --git a/src/cli/index-automation-setup.test.ts b/src/cli/index-automation-setup.test.ts index de035dc45835..a3c57b9af8cd 100644 --- a/src/cli/index-automation-setup.test.ts +++ b/src/cli/index-automation-setup.test.ts @@ -198,7 +198,10 @@ describe('automation setup CLI contract', () => { const args = createArgs.filter((arg) => arg !== '--repo' && arg !== 'id:repo-1') await main([...args, '--setup', 'run'], '/tmp/repo/feature') expect(process.exitCode).toBe(1) - expect(callMock.mock.calls.map(([method]) => method)).toEqual(['worktree.list']) + expect(callMock.mock.calls.map(([method]) => method)).toEqual([ + 'worktree.list', + 'folderWorkspace.list' + ]) expect(JSON.parse(String(output.mock.calls.at(-1)?.[0])).error.message).toBe( '--setup only applies to automations that create a new worktree per run, but this one runs in an existing worktree (with no target, create uses the current worktree). Pass --workspace-mode new-per-run or omit --setup.' ) diff --git a/src/cli/index-environment-local.test.ts b/src/cli/index-environment-local.test.ts new file mode 100644 index 000000000000..41fc18d3f247 --- /dev/null +++ b/src/cli/index-environment-local.test.ts @@ -0,0 +1,551 @@ +import { describe, expect, it, vi } from 'vitest' + +const { + callMock, + runtimeClientConstructorMock, + serveOrcaAppMock, + getDefaultUserDataPathMock, + addEnvironmentFromPairingCodeMock, + listEnvironmentsMock, + resolveEnvironmentMock, + 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(), + resolveEnvironmentMock: 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/environments', () => ({ + addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, + removeEnvironment: vi.fn(), + resolveEnvironment: resolveEnvironmentMock +})) + +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, worktreeListFixture } from './test-fixtures' + +const SAVED = [ + { id: 'srv-b', name: 'build-box' }, + { id: 'srv-old', name: 'local' } +].map((environment) => ({ + ...environment, + createdAt: 1, + updatedAt: 1, + lastUsedAt: null, + runtimeId: null, + endpoints: [], + preferredEndpointId: null +})) + +function psRow(fields: Record) { + return { + repoId: 'repo', + repo: 'repo', + branch: 'main', + isArchived: false, + isMainWorktree: false, + parentWorktreeId: null, + childWorktreeIds: [], + unread: false, + liveTerminalCount: 0, + hasAttachedPty: false, + lastOutputAt: null, + preview: '', + status: 'inactive', + agents: [], + ...fields + } +} + +async function run(args: string[], cwd = '/tmp/repo') { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + const err = vi.spyOn(console, 'error').mockImplementation(() => {}) + const prior = process.exitCode + await main(args, 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('--environment local and workspace addresses', () => { + useWorktreeAwarenessEnvironment({ + callMock, + serveOrcaAppMock, + getDefaultUserDataPathMock, + addEnvironmentFromPairingCodeMock, + listEnvironmentsMock, + spawnMock + }) + + it('routes --environment local to this machine over an ambient environment or pairing code', async () => { + for (const [name, value] of [ + ['ORCA_ENVIRONMENT', 'srv-b'], + ['ORCA_PAIRING_CODE', 'orca://pair?code=ambient-secret'] + ]) { + vi.stubEnv(name, value) + listEnvironmentsMock.mockReturnValue(SAVED) + runtimeClientConstructorMock.mockClear() + callMock.mockReset() + callMock.mockResolvedValue( + okFixture('ps', { + worktrees: [ + psRow({ + worktreeId: 'repo::/tmp/repo', + path: '/tmp/repo', + hostId: 'local', + identity: { key: 'wt2:local:abc' } + }) + ], + totalCount: 1, + truncated: false + }) + ) + const { exitCode, output } = await run(['worktree', 'ps', '--environment', 'local', '--json']) + expect(exitCode).toBeUndefined() + expect(runtimeClientConstructorMock).toHaveBeenCalledWith(null, null) + expect(JSON.parse(output).result.worktrees[0]).toMatchObject({ + hostId: 'local', + environment: { id: 'local', name: 'local' }, + address: { + environment: 'local', + worktree: 'identity:wt2:local:abc', + line: '--environment local --worktree identity:wt2:local:abc' + }, + parent: null + }) + vi.unstubAllEnvs() + } + }) + + it('lets an explicit --environment win over a stale ORCA_ENVIRONMENT', async () => { + vi.stubEnv('ORCA_ENVIRONMENT', 'removed-entry') + listEnvironmentsMock.mockReturnValue(SAVED) + callMock.mockResolvedValue(okFixture('ps', { worktrees: [], totalCount: 0, truncated: false })) + const { exitCode } = await run(['worktree', 'ps', '--environment', 'srv-b', '--json']) + expect(exitCode).toBeUndefined() + expect(runtimeClientConstructorMock).toHaveBeenLastCalledWith(undefined, 'srv-b') + expect(resolveEnvironmentMock).not.toHaveBeenCalled() + vi.unstubAllEnvs() + }) + + it.each([ + [['worktree', 'ps', '--pairing-code', 'orca://pair?code=x', '--environment', 'local']], + [['worktree', 'ps', '--host', 'runtime:srv-b', '--environment', 'local']], + [['environment', 'add', '--name', ' Local ', '--pairing-code', 'orca://pair?code=x']], + [['environment', 'stop', '--environment', 'local']] + ])('refuses %j before any request', async (args) => { + listEnvironmentsMock.mockReturnValue(SAVED) + const { exitCode, output } = await run([...args, '--json']) + expect(exitCode).toBe(1) + expect(JSON.parse(output).error.code).toBe('invalid_argument') + expect(callMock).not.toHaveBeenCalled() + expect(addEnvironmentFromPairingCodeMock).not.toHaveBeenCalled() + if (args[0] === 'environment' && args[1] === 'stop') { + expect(output).toContain('--environment srv-old') + } + }) + + it('refuses current against another environment with an inspection command', async () => { + listEnvironmentsMock.mockReturnValue(SAVED) + const { exitCode, output } = await run([ + 'worktree', + 'current', + '--environment', + 'srv-b', + '--json' + ]) + expect(exitCode).toBe(1) + expect(JSON.parse(output).error.data.nextSteps[0]).toContain( + '`orca worktree ps --environment srv-b --json`' + ) + expect(callMock).not.toHaveBeenCalled() + }) + + it('resolves current under --environment local to the folder workspace at cwd', async () => { + vi.stubEnv('ORCA_ENVIRONMENT', 'srv-b') + listEnvironmentsMock.mockReturnValue(SAVED) + callMock.mockImplementation(async (method: string) => { + if (method === 'worktree.list') { + return worktreeListFixture([]) + } + if (method === 'folderWorkspace.list') { + return okFixture('folders', { + folderWorkspaces: [{ id: 'hub-a', folderPath: '/tmp/hub', projectGroupId: 'group' }] + }) + } + if (method === 'projectGroup.list') { + return okFixture('groups', { groups: [{ id: 'group' }] }) + } + if (method === 'repo.list') { + return okFixture('repos', { repos: [] }) + } + return okFixture('show', { worktree: { id: 'folder:hub-a', path: '/tmp/hub' } }) + }) + const { exitCode, output } = await run( + ['worktree', 'current', '--environment', 'local', '--json'], + '/tmp/hub/notes' + ) + expect(exitCode).toBeUndefined() + expect(callMock).toHaveBeenCalledWith('worktree.show', { worktree: 'folder:hub-a' }) + expect(JSON.parse(output).result.worktree.address.line).toBe( + '--environment local --worktree folder:hub-a' + ) + vi.unstubAllEnvs() + }) + + it('gives a one-off pairing-code connection no address and never prints the code', async () => { + vi.stubEnv('ORCA_PAIRING_CODE', 'orca://pair?code=one-off-secret') + callMock.mockResolvedValue( + okFixture('ps', { + worktrees: [psRow({ worktreeId: 'repo::/srv/app', path: '/srv/app', hostId: 'local' })], + totalCount: 1, + truncated: false + }) + ) + for (const json of [true, false]) { + const { output } = await run(['worktree', 'ps', ...(json ? ['--json'] : [])]) + expect(output).not.toContain('one-off-secret') + if (json) { + expect(JSON.parse(output).result.worktrees[0]).toMatchObject({ + environment: { id: null, name: null }, + address: null, + addressUnavailable: 'one-off-connection' + }) + } else { + expect(output).toContain('environment: one-off connection\naddress: unavailable') + } + } + vi.unstubAllEnvs() + }) + + it('names each parent environment and never guesses a route', async () => { + listEnvironmentsMock.mockReturnValue(SAVED) + runtimeClientConstructorMock.mockClear() + const crossStore = (installationId: string, workspaceKey: string) => ({ + parent: { installationId, workspaceKey, instanceId: 'parent-instance' } + }) + callMock.mockImplementation(async (method: string) => { + if (method === 'worktree.lineageList') { + return okFixture('lineage', { installationId: 'install-local' }) + } + return okFixture('ps', { + worktrees: [ + psRow({ + worktreeId: 'repo::/srv/api', + path: '/srv/api', + hostId: 'local', + identity: { key: 'wt2:local:api' }, + crossStoreParent: crossStore('install-local', 'folder:hub-a') + }), + psRow({ + worktreeId: 'repo::/srv/web', + path: '/srv/web', + hostId: 'local', + identity: { key: 'wt2:local:web' }, + crossStoreParent: crossStore('install-c', 'folder:hub-c') + }), + psRow({ + worktreeId: 'repo::/srv/orphan', + path: '/srv/orphan', + hostId: 'runtime:unresolved-owner', + identity: { key: 'wt2:runtime%3Aunresolved-owner:x' } + }), + ...['/srv/one', '/srv/two'].map((path) => + psRow({ + workspaceKind: 'folder-workspace', + worktreeId: 'folder:twin', + path, + hostId: 'local' + }) + ) + ], + totalCount: 5, + truncated: false + }) + }) + const { output: json } = await run(['worktree', 'ps', '--environment', 'build-box', '--json']) + const [api, web, orphan, twinA, twinB] = JSON.parse(json).result.worktrees + expect(api).toMatchObject({ + environment: { id: 'srv-b', name: 'build-box' }, + address: { line: '--environment srv-b --worktree identity:wt2:local:api' }, + parent: { + state: 'known', + selector: 'folder:hub-a', + environment: { id: 'local', name: 'local' }, + address: { environment: 'local', worktree: 'folder:hub-a' } + } + }) + expect(web.parent).toEqual({ + state: 'unknown-environment', + selector: 'folder:hub-c', + environment: null, + address: null + }) + expect(orphan).toMatchObject({ + hostId: 'runtime:unresolved-owner', + environment: { id: 'srv-b' }, + address: null, + addressUnavailable: 'unverifiable-row' + }) + expect([twinA.addressUnavailable, twinB.addressUnavailable]).toEqual([ + 'duplicate-folder-id', + 'duplicate-folder-id' + ]) + // Only this machine's own Orca is asked; no other environment is dialed. + expect(runtimeClientConstructorMock.mock.calls).toEqual([ + [undefined, 'build-box'], + [null, null] + ]) + + const { output: text } = await run(['worktree', 'ps', '--environment', 'build-box']) + expect(text).toContain( + '/srv/api\nparent: folder:hub-a environment=local\nenvironment: build-box\naddress: --environment srv-b --worktree identity:wt2:local:api' + ) + expect(text).toContain('parent: folder:hub-c environment=unknown (no verified route here)') + expect(text).toContain('host=runtime:unresolved-owner') + }) + + it('gives a duplicated folder parent no address, as its own rows have none', async () => { + callMock.mockResolvedValue( + okFixture('ps', { + worktrees: [ + psRow({ + worktreeId: 'repo::/srv/child', + path: '/srv/child', + hostId: 'local', + identity: { key: 'wt2:local:child' }, + workspaceLineage: { parentWorkspaceKey: 'folder:duplicated' } + }), + ...(['local', 'ssh:box'] as const).map((hostId) => + psRow({ + workspaceKind: 'folder-workspace', + worktreeId: 'folder:duplicated', + path: '/srv/shared', + hostId + }) + ) + ], + totalCount: 3, + truncated: false + }) + ) + const { output } = await run(['worktree', 'ps', '--json']) + const [child, ...parents] = JSON.parse(output).result.worktrees + expect(parents.map((row: { addressUnavailable: string }) => row.addressUnavailable)).toEqual([ + 'duplicate-folder-id', + 'duplicate-folder-id' + ]) + expect(child.parent).toEqual({ + state: 'known', + selector: 'folder:duplicated', + environment: { id: 'local', name: 'local' }, + address: null + }) + }) + + it('surfaces a folder-catalog failure for an omitted target instead of using runtime focus', async () => { + callMock.mockImplementation(async (method: string) => { + if (method === 'worktree.list') { + return worktreeListFixture([buildWorktree('/tmp/hub/repo', 'main')]) + } + if (method === 'folderWorkspace.list') { + throw new RuntimeClientError('runtime_unavailable', 'folder catalog connection closed') + } + return okFixture('accepted', { marker: 'accepted' }) + }) + const { exitCode, output } = await run(['snapshot', '--json'], '/tmp/hub/repo/src') + expect(exitCode).toBe(1) + expect(JSON.parse(output).error.code).toBe('runtime_unavailable') + expect(callMock).not.toHaveBeenCalledWith('browser.snapshot', expect.anything()) + }) + + it('refuses omitted and explicit current when the enclosing folder host is unknown', async () => { + callMock.mockImplementation(async (method: string) => { + if (method === 'worktree.list') { + return worktreeListFixture([]) + } + if (method === 'folderWorkspace.list') { + return okFixture('folders', { + folderWorkspaces: [{ id: 'hub-a', folderPath: '/tmp/hub', projectGroupId: 'group' }] + }) + } + if (method === 'projectGroup.list' || method === 'repo.list') { + throw new RuntimeClientError('method_not_found', 'Unknown method') + } + return okFixture('accepted', { marker: 'accepted' }) + }) + for (const args of [['snapshot'], ['worktree', 'current']]) { + const { exitCode, output } = await run([...args, '--json'], '/tmp/hub/notes') + expect(exitCode).toBe(1) + expect(JSON.parse(output).error.code).toBe('selector_ambiguous') + expect(output).toContain( + 'Pass --worktree folder:hub-a to target the folder workspace itself.' + ) + } + expect(callMock).not.toHaveBeenCalledWith('browser.snapshot', expect.anything()) + expect(callMock).not.toHaveBeenCalledWith('worktree.show', expect.anything()) + }) + + it('surfaces a worktree-list method_not_found for an omitted target', async () => { + callMock.mockImplementation(async (method: string) => { + if (method === 'worktree.list') { + throw new RuntimeClientError('method_not_found', 'Unknown method: worktree.list') + } + return okFixture('accepted', { folderWorkspaces: [], marker: 'accepted' }) + }) + const { exitCode, output } = await run(['snapshot', '--json'], '/tmp/hub/repo/src') + expect(exitCode).toBe(1) + expect(JSON.parse(output).error.code).toBe('method_not_found') + expect(callMock).not.toHaveBeenCalledWith('browser.snapshot', expect.anything()) + }) + + it('quotes address values for the shell', async () => { + const row = buildWorktree('/tmp/my repo', 'main') + callMock.mockResolvedValue(okFixture('show', { worktree: { ...row, hostId: 'local' } })) + const { output } = await run(['worktree', 'show', '--worktree', `id:${row.id}`, '--json']) + expect(JSON.parse(output).result.worktree.address).toEqual({ + environment: 'local', + worktree: 'id:repo::/tmp/my repo', + line: + process.platform === 'win32' + ? '--environment local --worktree "id:repo::/tmp/my repo"' + : "--environment local --worktree 'id:repo::/tmp/my repo'" + }) + }) +}) + +describe('worktree rm needs an explicit workspace', () => { + useWorktreeAwarenessEnvironment({ + callMock, + serveOrcaAppMock, + getDefaultUserDataPathMock, + addEnvironmentFromPairingCodeMock, + listEnvironmentsMock, + spawnMock + }) + + const root = buildWorktree('/tmp/rm-repo', 'main') + const sibling = { ...root, id: `${root.id}::workspace:sibling` } + + it.each(['current', 'active'])( + 'refuses --worktree %s, naming what it resolves to, and removes nothing', + async (value) => { + for (const [rows, resolution, selectors] of [ + [[root], 'resolved', ['id:repo::/tmp/rm-repo']], + [ + [root, sibling], + 'ambiguous', + ['id:repo::/tmp/rm-repo', 'id:repo::/tmp/rm-repo::workspace:sibling'] + ], + [[], 'unresolved', []] + ] as const) { + callMock.mockReset() + callMock.mockImplementation(async (method: string) => + method === 'worktree.list' + ? worktreeListFixture([...rows]) + : okFixture('folders', { folderWorkspaces: [] }) + ) + const { exitCode, output } = await run( + ['worktree', 'rm', '--worktree', value, '--force', '--json'], + '/tmp/rm-repo/src' + ) + expect(exitCode).toBe(1) + const { error } = JSON.parse(output) + expect(error.code).toBe('invalid_argument') + expect(error.message).toContain( + `orca worktree rm needs an explicit workspace; --worktree ${value} is not accepted` + ) + expect(error.data.current).toEqual({ resolution, selectors: [...selectors] }) + expect(error.data.nextSteps.slice(0, selectors.length)).toEqual( + selectors.map((selector) => `orca worktree rm --worktree ${selector}`) + ) + if (resolution === 'resolved') { + expect(error.message).toContain(`Here, ${value} is --worktree id:repo::/tmp/rm-repo`) + } + const methods = callMock.mock.calls.map(([method]) => method) + expect(methods).not.toContain('worktree.show') + expect(methods).not.toContain('worktree.rm') + } + } + ) + + it.each(['current', 'active'])( + 'refuses --worktree %s inside a folder workspace before the folder removal path', + async (value) => { + callMock.mockReset() + callMock.mockImplementation(async (method: string) => { + if (method === 'worktree.list') { + return worktreeListFixture([]) + } + if (method === 'folderWorkspace.list') { + return okFixture('folders', { + folderWorkspaces: [{ id: 'hub-a', folderPath: '/tmp/hub', projectGroupId: 'group' }] + }) + } + if (method === 'projectGroup.list') { + return okFixture('groups', { groups: [{ id: 'group' }] }) + } + return okFixture('repos', { repos: [] }) + }) + const { exitCode, output } = await run( + ['worktree', 'rm', '--worktree', value, '--json'], + '/tmp/hub/notes' + ) + expect(exitCode).toBe(1) + const { error } = JSON.parse(output) + expect(error.code).toBe('invalid_argument') + expect(error.data.current).toEqual({ resolution: 'resolved', selectors: ['folder:hub-a'] }) + expect(error.data.nextSteps[0]).toBe('orca worktree rm --worktree folder:hub-a') + const methods = callMock.mock.calls.map(([method]) => method) + expect(methods).not.toContain('folderWorkspace.delete') + expect(methods).not.toContain('worktree.show') + } + ) + + it('keeps the environment-specific guidance when the target is another environment', async () => { + listEnvironmentsMock.mockReturnValue(SAVED) + const { exitCode, output } = await run([ + 'worktree', + 'rm', + '--worktree', + 'current', + '--environment', + 'srv-b', + '--json' + ]) + expect(exitCode).toBe(1) + expect(JSON.parse(output).error.data.nextSteps[0]).toContain( + '`orca worktree ps --environment srv-b --json`' + ) + expect(callMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/cli/index-folder-workspace-selectors.test.ts b/src/cli/index-folder-workspace-selectors.test.ts index 7b24ca627db0..f85de56c45c0 100644 --- a/src/cli/index-folder-workspace-selectors.test.ts +++ b/src/cli/index-folder-workspace-selectors.test.ts @@ -164,6 +164,15 @@ describe('path: selectors on folder workspaces', () => { expect.objectContaining({ parentWorktree: 'name:Hub', matchFolderWorkspaces: true }) ) const { error } = JSON.parse(String(log.mock.calls.at(-1)?.[0])) - expect(error).toMatchObject({ code: 'LINEAGE_PARENT_AMBIGUOUS', data: choices }) + expect(error).toMatchObject({ + code: 'LINEAGE_PARENT_AMBIGUOUS', + data: { + ...choices, + environment: 'local', + nextSteps: [ + 'Compare the choices with `orca worktree ps --environment local --json`, then pass one as --parent-worktree.' + ] + } + }) }) }) diff --git a/src/cli/index-terminal-commands.test.ts b/src/cli/index-terminal-commands.test.ts index 67945284e540..8de7a36b59a5 100644 --- a/src/cli/index-terminal-commands.test.ts +++ b/src/cli/index-terminal-commands.test.ts @@ -47,6 +47,7 @@ vi.mock('child_process', async () => { import { main } from './index' import { buildWorktree, + noFolderWorkspacesFixture, okFixture, queueFixtures, queueNoFolderAtSelector, @@ -206,13 +207,14 @@ describe('orca cli worktree awareness', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), + noFolderWorkspacesFixture(), okFixture('req_term', { terminals: [], totalCount: 0, truncated: false }) ) vi.spyOn(console, 'log').mockImplementation(() => {}) await main(['terminal', 'list', '--worktree', 'active', '--json'], '/tmp/repo/feature/src') - expect(callMock).toHaveBeenNthCalledWith(2, 'terminal.list', { + expect(callMock).toHaveBeenNthCalledWith(3, 'terminal.list', { worktree: 'id:repo::/tmp/repo/feature', limit: undefined, includeVisualLayouts: false @@ -223,6 +225,7 @@ describe('orca cli worktree awareness', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), + noFolderWorkspacesFixture(), okFixture('req_term', { terminals: [], totalCount: 0, truncated: false }) ) vi.spyOn(console, 'log').mockImplementation(() => {}) @@ -230,7 +233,7 @@ describe('orca cli worktree awareness', () => { await main(['terminal', 'list', '--worktree', 'active'], '/tmp/repo/feature/src') expect(callMock).toHaveBeenNthCalledWith( - 2, + 3, 'terminal.list', expect.objectContaining({ includeVisualLayouts: true }) ) @@ -247,6 +250,7 @@ describe('orca cli worktree awareness', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo/feature', 'feature/foo')]), + noFolderWorkspacesFixture(), okFixture('req_term', { terminals: [], visualLayouts, @@ -262,7 +266,7 @@ describe('orca cli worktree awareness', () => { ) expect(callMock).toHaveBeenNthCalledWith( - 2, + 3, 'terminal.list', expect.objectContaining({ includeVisualLayouts: true }) ) diff --git a/src/cli/index-test-harness.ts b/src/cli/index-test-harness.ts index c0f1df88d9aa..79fa58e3691f 100644 --- a/src/cli/index-test-harness.ts +++ b/src/cli/index-test-harness.ts @@ -22,6 +22,8 @@ export async function createRuntimeClientModuleMock(mocks: RuntimeClientModuleMo class RuntimeClient { readonly isRemote: boolean + readonly environmentSelector: string | null + readonly userDataPath = '/tmp/orca-user-data' call = mocks.callMock getCliStatus = vi.fn() openOrca = vi.fn() @@ -46,6 +48,7 @@ export async function createRuntimeClientModuleMock(mocks: RuntimeClientModuleMo ) } this.isRemote = Boolean(effectivePairingCode || effectiveEnvironment) + this.environmentSelector = effectiveEnvironment || null } } diff --git a/src/cli/index-workspace-owner-choice.test.ts b/src/cli/index-workspace-owner-choice.test.ts index 3d7cee625316..c09dc8b90257 100644 --- a/src/cli/index-workspace-owner-choice.test.ts +++ b/src/cli/index-workspace-owner-choice.test.ts @@ -110,7 +110,6 @@ describe('cwd workspace ownership at the real CLI boundary', () => { ['computer', 'get-app-state', '--app', 'fixture'], ['orchestration', 'check', '--peek'], ['orchestration', 'run-current'], - ['worktree', 'rm', '--worktree', 'current', '--force'], ['terminal', 'stop', '--worktree', 'current'], ['terminal', 'close', '--all', '--worktree', 'current'], [ @@ -179,6 +178,7 @@ describe('cwd workspace ownership at the real CLI boundary', () => { if (json) { expect(JSON.parse(output).error.data.workspaces).toEqual( rows.map((row) => ({ + kind: 'worktree', id: row.id, path: row.path, hostId: 'local', @@ -208,7 +208,7 @@ describe('cwd workspace ownership at the real CLI boundary', () => { expect( callMock.mock.calls.map(([method]) => method), JSON.stringify(args) - ).toEqual(['worktree.list']) + ).toEqual(['worktree.list', 'folderWorkspace.list']) } } } finally { @@ -466,7 +466,7 @@ describe('cwd workspace ownership at the real CLI boundary', () => { expect( JSON.parse(log.mock.calls.flat().join('\n')).error.data.validSelectorForms ).toEqual(rows.filter((row) => row !== outside).map((row) => `id:${row.id}`)) - expect(callMock).toHaveBeenCalledTimes(1) + expect(callMock).toHaveBeenCalledTimes(2) } } } finally { @@ -474,7 +474,7 @@ describe('cwd workspace ownership at the real CLI boundary', () => { } }) - it('retains optional no-match/unavailable fallback and deliberate scope bypasses', async () => { + it('retains optional no-match fallback, surfaces an unreadable catalog, and keeps scope bypasses', async () => { const log = vi.spyOn(console, 'log').mockImplementation(() => {}) const prior = process.exitCode const commands = [ @@ -515,6 +515,15 @@ describe('cwd workspace ownership at the real CLI boundary', () => { ? ['--pairing-code', 'remote-runtime'] : [] await main([...args, ...scope, '--json'], root.path) + // An omitted browser target must not guess past an unreadable catalog. + if (mode === 'unavailable' && action === 'browser.snapshot') { + expect(process.exitCode).toBe(1) + expect(JSON.parse(log.mock.calls.flat().join('\n')).error.code).toBe( + 'runtime_unavailable' + ) + expect(callMock).not.toHaveBeenCalledWith(action, expect.anything()) + continue + } expect(process.exitCode, JSON.stringify({ args, mode, output: log.mock.calls })).toBe( prior ) @@ -631,6 +640,9 @@ describe('cwd workspace ownership at the real CLI boundary', () => { delete process.env.ORCA_WORKSPACE_ID } callMock.mockImplementation(async (method) => { + if (method === 'worktree.list') { + return worktreeListFixture([]) + } if (method === 'folderWorkspace.list') { return okFixture('folders', { folderWorkspaces: ids.map((id) => ({ @@ -657,20 +669,20 @@ describe('cwd workspace ownership at the real CLI boundary', () => { return agentLaunchFixture('folder:r') }) await main([...command, ...(json ? ['--json'] : [])], root.path) - expect(callMock.mock.calls.slice(0, 3).map(([method]) => method)).toEqual([ + expect(callMock.mock.calls.slice(0, 4).map(([method]) => method)).toEqual([ + 'worktree.list', 'folderWorkspace.list', 'projectGroup.list', 'repo.list' ]) - expect(callMock).not.toHaveBeenCalledWith('worktree.list', expect.anything()) if (caller) { expect(process.exitCode, log.mock.calls.flat().join('')).toBe(prior) expect(callMock).toHaveBeenCalledWith( command[0] === 'ports' ? 'workspacePorts.scanHost' : 'agent.launchReplay', command[0] === 'ports' - ? { worktree: 'id:folder:r' } + ? { worktree: 'folder:r' } : expect.objectContaining({ - target: { kind: 'existing', worktree: 'id:folder:r' } + target: { kind: 'existing', worktree: 'folder:r' } }) ) } else { @@ -682,7 +694,7 @@ describe('cwd workspace ownership at the real CLI boundary', () => { output.split('Workspace choices (JSON data):\n')[1]!.split('\nNext step:')[0]! ) expect(choices.map((choice: { selector: string }) => choice.selector)).toEqual( - ids.filter((id) => id !== 'remote').map((id) => `id:folder:${id}`) + ids.filter((id) => id !== 'remote').map((id) => `folder:${id}`) ) expect( choices.every((choice: { hostId: string }) => choice.hostId === 'local') @@ -695,7 +707,7 @@ describe('cwd workspace ownership at the real CLI boundary', () => { if (!json) { expect(output.split('Workspace choices (JSON data):')).toHaveLength(2) } - expect(callMock).toHaveBeenCalledTimes(3) + expect(callMock).toHaveBeenCalledTimes(4) } } } diff --git a/src/cli/index-worktree-create-agent.test.ts b/src/cli/index-worktree-create-agent.test.ts index 50739237f689..776ff6f5b229 100644 --- a/src/cli/index-worktree-create-agent.test.ts +++ b/src/cli/index-worktree-create-agent.test.ts @@ -44,7 +44,13 @@ vi.mock('child_process', async () => { }) import { main } from './index' -import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from './test-fixtures' +import { + buildWorktree, + noFolderWorkspacesFixture, + okFixture, + queueFixtures, + worktreeListFixture +} from './test-fixtures' import { useWorktreeAwarenessEnvironment } from './index-test-harness' import { agentLaunchFixture, agentLaunchHostFixture } from './agent-launch-test-fixtures' @@ -62,6 +68,7 @@ describe('orca cli worktree awareness', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1')]), + noFolderWorkspacesFixture(), okFixture('req_create', { worktree: buildWorktree('/tmp/repo/feature', 'feature', 'abc', 'repo-1') }) @@ -73,7 +80,7 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.create', { + expect(callMock).toHaveBeenNthCalledWith(3, 'worktree.create', { repo: 'id:repo-1', name: 'feature', displayName: 'feature', @@ -100,6 +107,7 @@ describe('orca cli worktree awareness', () => { buildWorktree('/tmp/repo', 'main', 'abc', 'repo-2'), buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1') ]), + noFolderWorkspacesFixture(), agentLaunchHostFixture(), agentLaunchFixture('repo-1::/tmp/repo/agent-task', 'The inferred parent contexts conflict.'), okFixture('req_show', { @@ -131,7 +139,7 @@ describe('orca cli worktree awareness', () => { '/tmp/repo/src' ) - expect(callMock).toHaveBeenNthCalledWith(3, 'agent.launchReplay', { + expect(callMock).toHaveBeenNthCalledWith(4, 'agent.launchReplay', { target: { kind: 'create-worktree', create: { @@ -161,7 +169,7 @@ describe('orca cli worktree awareness', () => { launchSource: 'cli', operationId: expect.any(String) }) - expect(callMock).toHaveBeenNthCalledWith(4, 'worktree.show', { + expect(callMock).toHaveBeenNthCalledWith(5, 'worktree.show', { worktree: 'id:repo-1::/tmp/repo/agent-task' }) const printed = JSON.parse(String(logSpy.mock.calls[0]?.[0])) @@ -216,6 +224,7 @@ describe('orca cli worktree awareness', () => { buildWorktree('/tmp/repo', 'main', 'abc', 'repo-2'), buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1') ]), + noFolderWorkspacesFixture(), okFixture('req_status', { capabilities }), okFixture('req_create', { worktree: buildWorktree('/tmp/repo/agent-task', 'agent-task', 'abc', 'repo-1'), @@ -241,7 +250,7 @@ describe('orca cli worktree awareness', () => { '/tmp/repo/src' ) - expect(callMock).toHaveBeenNthCalledWith(3, 'worktree.create', { + expect(callMock).toHaveBeenNthCalledWith(4, 'worktree.create', { repo: 'id:repo-1', name: 'agent-task', displayName: 'agent-task', @@ -274,7 +283,8 @@ describe('orca cli worktree awareness', () => { worktreeListFixture([ buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1'), buildWorktree('/tmp/repo', 'main', 'abc', 'repo-2') - ]) + ]), + noFolderWorkspacesFixture() ) const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) const priorExitCode = process.exitCode @@ -285,7 +295,10 @@ describe('orca cli worktree awareness', () => { ) expect(process.exitCode).toBe(1) expect(JSON.parse(String(logSpy.mock.calls[0]?.[0])).error.code).toBe('selector_ambiguous') - expect(callMock.mock.calls.map(([method]) => method)).toEqual(['worktree.list']) + expect(callMock.mock.calls.map(([method]) => method)).toEqual([ + 'worktree.list', + 'folderWorkspace.list' + ]) } finally { process.exitCode = priorExitCode } diff --git a/src/cli/index-worktree-create-host-scoped-repo.test.ts b/src/cli/index-worktree-create-host-scoped-repo.test.ts index 5f0c81185766..f8c054f9c4ec 100644 --- a/src/cli/index-worktree-create-host-scoped-repo.test.ts +++ b/src/cli/index-worktree-create-host-scoped-repo.test.ts @@ -45,7 +45,13 @@ vi.mock('child_process', async () => { }) import { main } from './index' -import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from './test-fixtures' +import { + buildWorktree, + noFolderWorkspacesFixture, + okFixture, + queueFixtures, + worktreeListFixture +} from './test-fixtures' import { useWorktreeAwarenessEnvironment } from './index-test-harness' const SSH_CALLER = { @@ -87,6 +93,7 @@ describe('worktree create from a worktree another host shares an id with', () => identity: { key: 'wt2:b' } } ]), + noFolderWorkspacesFixture(), okFixture('req_create', { worktree: buildWorktree('/srv/app-child', 'child', 'abc', 'repo-1'), lineage: null, @@ -98,7 +105,7 @@ describe('worktree create from a worktree another host shares an id with', () => await main(['worktree', 'create', '--name', 'child', '--json'], '/srv/app/src') expect(callMock).toHaveBeenNthCalledWith( - 2, + 3, 'worktree.create', expect.objectContaining({ repo: 'id:repo-1', cwdParentWorktree: 'identity:wt2:b' }) ) @@ -198,7 +205,7 @@ describe('worktree create from a worktree another host shares an id with', () => } } } - // An explicit target keeps optional-parent and active/current workspace behavior. + // An explicit target keeps optional-parent inference; active/current refuse a two-owner path. delete process.env.ORCA_WORKTREE_ID for (const parent of [undefined, 'active', 'current']) { callMock.mockReset() @@ -226,14 +233,20 @@ describe('worktree create from a worktree another host shares an id with', () => ], path ) + // Two registrations own the path: an explicit current refuses, inference flags the tie. + if (parent) { + expect(process.exitCode).toBe(1) + expect(callMock).not.toHaveBeenCalledWith('worktree.create', expect.anything()) + process.exitCode = priorExitCode + continue + } expect(process.exitCode).toBe(priorExitCode) expect(callMock).toHaveBeenCalledWith( 'worktree.create', expect.objectContaining({ repo: 'id:repo-b', - ...(parent - ? { parentWorktree: `id:${root.id}` } - : { cwdParentWorktree: `id:${root.id}` }) + cwdParentWorktree: `id:${root.id}`, + cwdParentAmbiguous: true }) ) } @@ -358,100 +371,4 @@ describe('worktree create from a worktree another host shares an id with', () => } } ) - - it.each([false, true])( - 'bounds inferred-create traversal and ambiguity sorting at catalog scale (distinct=%s)', - async (distinct) => { - const path = resolve('/tmp/catalog-scale') - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - const compare = String.prototype.localeCompare - const priorExitCode = process.exitCode - const samples: { reads: number; comparisons: number }[] = [] - try { - for (const count of [1_000, 10_000]) { - const operations = { reads: 0, comparisons: 0 } - const sortSpy = vi.spyOn(String.prototype, 'localeCompare').mockImplementation(function ( - this: string, - other: string - ) { - operations.comparisons++ - return compare.call(this, other) - }) - const rows = Array.from({ length: count }, (_, index) => { - const repo = distinct ? `repo-${(index * 7919) % count}` : 'repo-a' - return { - ...buildWorktree(path, 'main'), - get id() { - operations.reads++ - return `${repo}::${path}::workspace:${index}` - }, - get repoId() { - operations.reads++ - return repo - }, - get path() { - operations.reads++ - return path - }, - get hostId() { - operations.reads++ - return 'local' - } - } - }) - callMock.mockReset() - logSpy.mockClear() - process.exitCode = priorExitCode - queueFixtures( - callMock, - worktreeListFixture(rows), - okFixture('create', { - worktree: buildWorktree(join(path, 'child'), 'child', 'abc', 'repo-a'), - lineage: null, - warnings: [] - }) - ) - await main( - ['worktree', 'create', '--name', 'child', '--no-parent', '--json'], - join(path, 'src') - ) - sortSpy.mockRestore() - expect(callMock).toHaveBeenCalledWith('worktree.list', { limit: 10_000 }) - expect(callMock.mock.calls.filter(([method]) => method === 'worktree.list')).toHaveLength( - 1 - ) - expect(operations.reads).toBeGreaterThanOrEqual(count) - expect(operations.reads).toBeLessThanOrEqual(30 * count) - if (distinct) { - expect(process.exitCode).toBe(1) - expect(callMock).not.toHaveBeenCalledWith('worktree.create', expect.anything()) - const output = JSON.parse(logSpy.mock.calls.flat().join('\n')) - expect(output.error.code).toBe('selector_ambiguous') - expect(output.error.data.projects).toHaveLength(count) - expect(operations.comparisons).toBeGreaterThan(0) - expect(operations.comparisons).toBeLessThanOrEqual( - 2 * count * Math.ceil(Math.log2(count)) - ) - } else { - expect(process.exitCode).toBe(priorExitCode) - expect(callMock).toHaveBeenCalledWith( - 'worktree.create', - expect.objectContaining({ - repo: 'id:repo-a', - noParent: true - }) - ) - expect(operations.comparisons).toBe(0) - } - samples.push(operations) - } - expect(samples[1]!.reads).toBeLessThanOrEqual(11 * samples[0]!.reads) - if (distinct) { - expect(samples[1]!.comparisons).toBeLessThanOrEqual(16 * samples[0]!.comparisons) - } - } finally { - process.exitCode = priorExitCode - } - } - ) }) diff --git a/src/cli/index-worktree-create-target.test.ts b/src/cli/index-worktree-create-target.test.ts index 358c972d34b4..f94b4ef692fc 100644 --- a/src/cli/index-worktree-create-target.test.ts +++ b/src/cli/index-worktree-create-target.test.ts @@ -44,7 +44,13 @@ vi.mock('child_process', async () => { }) import { main } from './index' -import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from './test-fixtures' +import { + buildWorktree, + noFolderWorkspacesFixture, + okFixture, + queueFixtures, + worktreeListFixture +} from './test-fixtures' import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness' import { RuntimeRpcFailureError } from './runtime-client' @@ -82,6 +88,7 @@ describe('orca cli worktree awareness', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1')]), + noFolderWorkspacesFixture(), okFixture('req_create', { worktree: buildWorktree('/tmp/repo/feature', 'feature', 'abc', 'repo-1') }) @@ -93,7 +100,7 @@ describe('orca cli worktree awareness', () => { '/tmp/repo' ) - expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.create', { + expect(callMock).toHaveBeenNthCalledWith(3, 'worktree.create', { repo: 'id:repo-1', name: 'feature', displayName: 'feature', diff --git a/src/cli/index-worktree-parent-environment.test.ts b/src/cli/index-worktree-parent-environment.test.ts new file mode 100644 index 000000000000..71fff961cc02 --- /dev/null +++ b/src/cli/index-worktree-parent-environment.test.ts @@ -0,0 +1,343 @@ +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('../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 } +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 = {} + ) { + 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('creates on B under a folder on this machine, recorded as a cross-store ref', async () => { + listEnvironmentsMock.mockReturnValue(SAVED) + const calls = serve(FOLDER_PARENT) + const { exitCode } = await run([ + 'worktree', + 'create', + '--environment', + 'srv-b', + '--repo', + 'id:repo-1', + '--name', + 'child', + '--parent-environment', + 'local', + '--parent-worktree', + 'folder:hub-a' + ]) + expect(exitCode).toBeUndefined() + const create = calls.find((call) => call.method === 'worktree.create') + expect(create?.environment).toBe('srv-b') + expect(create?.params.crossStoreParent).toEqual({ + installationId: 'install-local', + workspaceKey: 'folder:hub-a', + instanceId: 'hub-a' + }) + expect(create?.params).not.toHaveProperty('parentWorkspace') + expect(create?.params).not.toHaveProperty('parentWorktree') + }) + + it('resolves the parent on C and records it on B by saved name', async () => { + listEnvironmentsMock.mockReturnValue(SAVED) + const calls = serve(({ environment, method, params }) => + environment === 'srv-c' && method === 'worktree.show' && params.worktree === 'name:trunk' + ? { worktree: { id: 'repo-9::/gpu/trunk', instanceId: 'inst-trunk' } } + : undefined + ) + const { exitCode } = await run([ + 'worktree', + 'set', + '--environment', + 'srv-b', + '--worktree', + 'id:repo-1::/srv/child', + '--parent-environment', + 'gpu-box', + '--parent-worktree', + 'name:trunk' + ]) + expect(exitCode).toBeUndefined() + expect( + calls.find((call) => call.method === 'worktree.show' && call.environment === 'srv-c')?.params + ).toEqual({ worktree: 'name:trunk', matchFolderWorkspaces: true }) + const set = calls.find((call) => call.method === 'worktree.set') + expect(set?.environment).toBe('srv-b') + expect(set?.params.crossStoreParent).toEqual({ + installationId: 'install-srv-c', + workspaceKey: 'worktree:repo-9::/gpu/trunk', + instanceId: 'inst-trunk' + }) + }) + + 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.' + ]) + } + }) +}) diff --git a/src/cli/index-worktree-set.test.ts b/src/cli/index-worktree-set.test.ts index 40037b48646d..37673b2e353e 100644 --- a/src/cli/index-worktree-set.test.ts +++ b/src/cli/index-worktree-set.test.ts @@ -47,6 +47,7 @@ import { main } from './index' import { RuntimeRpcFailureError } from './runtime/types' import { buildWorktree, + noFolderWorkspacesFixture, okFixture, queueFixtures, worktreeListFixture, @@ -211,6 +212,7 @@ describe('orca cli worktree awareness', () => { buildWorktree('/tmp/repo', 'main', 'aaa'), buildWorktree('/tmp/repo/feature', 'feature/foo') ]), + noFolderWorkspacesFixture(), okFixture('req_1', { worktree: { id: 'repo::/tmp/repo/feature', @@ -227,7 +229,7 @@ describe('orca cli worktree awareness', () => { '/tmp/repo/feature/src' ) - expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.set', { + expect(callMock).toHaveBeenNthCalledWith(3, 'worktree.set', { worktree: 'id:repo::/tmp/repo/feature', displayName: undefined, linkedIssue: undefined, @@ -241,6 +243,7 @@ describe('orca cli worktree awareness', () => { queueFixtures( callMock, worktreeListFixture([buildWorktree('/tmp/repo/parent', 'feature/parent')]), + noFolderWorkspacesFixture(), okFixture('req_set_parent', { worktree: { ...buildWorktree('/tmp/repo/child', 'feature/child'), @@ -265,7 +268,7 @@ describe('orca cli worktree awareness', () => { '/tmp/repo/parent/src' ) - expect(callMock).toHaveBeenNthCalledWith(2, 'worktree.set', { + expect(callMock).toHaveBeenNthCalledWith(3, 'worktree.set', { worktree: 'id:repo::/tmp/repo/child', displayName: undefined, linkedIssue: undefined, diff --git a/src/cli/index.ts b/src/cli/index.ts index bd06c300c016..10ce70529641 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -16,6 +16,7 @@ import { } from './execution-host-flag' import { fetchSshTargetSummaries, listSshTargets } from './host-selector-alternatives' import { reportCliError } from './cli-error' +import { RuntimeClientError } from './runtime/types' import { cliErrorExitCode } from './cli-exit-code' import { printHelp } from './help' import type { RuntimeClient } from './runtime-client' @@ -23,6 +24,10 @@ import { COMMAND_SPECS } from './specs' import { resolveOrchestrationCliExecutable } from './runtime/orchestration-recovery-command' import { refuseConflictingSessionCallerFlags } from './session-caller-flags' import { ignoresRemoteSelection } from './remote-selection-scope' +import { + isLocalEnvironmentSelector, + refuseLocalManagementSelector +} from './local-environment-selector' export { COMMAND_SPECS } from './specs' export { buildCurrentWorktreeSelector, normalizeWorktreeSelector } from './selectors' @@ -98,15 +103,24 @@ export async function main( validateCommandAndFlags(COMMAND_SPECS, parsed) const commandSpec = findCommandSpec(COMMAND_SPECS, parsed.commandPath) refuseConflictingSessionCallerFlags(commandSpec, parsed.flags) + await refuseLocalManagementSelector(parsed.commandPath, parsed.flags) const RuntimeClientClass = await loadRuntimeClientClass() const ignoreRemoteSelection = ignoresRemoteSelection(parsed.commandPath) const pairingCode = ignoreRemoteSelection ? null : parsed.flags.get('pairing-code') const environmentSelector = ignoreRemoteSelection ? null : parsed.flags.get('environment') + // An explicit local route suppresses ambient ORCA_ENVIRONMENT and pairing codes. + const explicitLocal = isLocalEnvironmentSelector(environmentSelector) + if (explicitLocal && typeof pairingCode === 'string') { + throw new RuntimeClientError( + 'invalid_argument', + 'Use either --pairing-code or --environment, not both.' + ) + } // Eagerly resolve explicit --environment; stale ambient config must not break local-only commands. const listSshTargetsForSuggestion = async (): Promise<{ id: string; label: string }[]> => listSshTargets(new RuntimeClientClass(undefined, undefined, null, null)) const storeEnvironmentSelector = - typeof environmentSelector === 'string' + typeof environmentSelector === 'string' && !explicitLocal ? await resolveEnvironmentSelectorForStore(environmentSelector, listSshTargetsForSuggestion) : null // Select the paired connection before constructing the client; reject conflicting environments. @@ -134,7 +148,7 @@ export async function main( parsed.flags.set('host', `runtime:${hostEnvironmentId}`) } // null suppresses RuntimeClient's ORCA_PAIRING_CODE / ORCA_ENVIRONMENT default parameters. - const suppressed = ignoreRemoteSelection ? null : undefined + const suppressed = ignoreRemoteSelection || explicitLocal ? null : undefined // An explicit runtime host overrides an ambient pairing code. const remotePairingCode = hostEnvironmentId !== null ? null : typeof pairingCode === 'string' ? pairingCode : suppressed @@ -167,10 +181,11 @@ export async function main( ...(typeof worktreeSelector === 'string' ? { worktreeSelector } : {}), ...(typeof repoSelector === 'string' ? { repoSelector } : {}), remoteServerSelected: - parsed.flags.has('environment') || - parsed.flags.has('pairing-code') || - (typeof hostFlag === 'string' && hostFlag.startsWith('runtime:')) || - Boolean(process.env.ORCA_ENVIRONMENT?.trim() || process.env.ORCA_PAIRING_CODE?.trim()), + !isLocalEnvironmentSelector(parsed.flags.get('environment')) && + (parsed.flags.has('environment') || + parsed.flags.has('pairing-code') || + (typeof hostFlag === 'string' && hostFlag.startsWith('runtime:')) || + Boolean(process.env.ORCA_ENVIRONMENT?.trim() || process.env.ORCA_PAIRING_CODE?.trim())), conciseOrchestration: parsed.commandPath[0] === 'orchestration' && !parsed.flags.has('full') }) process.exitCode = cliErrorExitCode(error, parsed.commandPath) diff --git a/src/cli/local-environment-selector.ts b/src/cli/local-environment-selector.ts new file mode 100644 index 000000000000..44849c1e87dc --- /dev/null +++ b/src/cli/local-environment-selector.ts @@ -0,0 +1,75 @@ +import { normalizeTypedName } from '../shared/typed-name-normalization' +import type { RuntimeClient } from './runtime-client' +import { RuntimeClientError } from './runtime/types' +import { quoteCliCommandArgument } from './shell-command-quote' + +/** `--environment local`: the caller's own Orca, even over an ambient ORCA_ENVIRONMENT or pairing code. */ +export const LOCAL_ENVIRONMENT = 'local' + +export function isLocalEnvironmentSelector(value: unknown): value is string { + return typeof value === 'string' && normalizeTypedName(value) === LOCAL_ENVIRONMENT +} + +/** `local` is reserved, so a saved entry named local is reached only by its id. */ +export async function savedEnvironmentNamedLocal(): Promise<{ id: string } | undefined> { + const [{ getDefaultUserDataPath }, { listEnvironments }] = await Promise.all([ + import('./runtime-client.js'), + import('../shared/remote-runtime/host-store/runtime-environment-store.js') + ]) + return listEnvironments(getDefaultUserDataPath()).find((environment) => + isLocalEnvironmentSelector(environment.name) + ) +} + +/** `orca environment …` takes --environment as a saved entry to act on; local is not one. */ +export async function refuseLocalManagementSelector( + commandPath: readonly string[], + flags: Map +): Promise { + if (commandPath[0] !== 'environment' || !isLocalEnvironmentSelector(flags.get('environment'))) { + return + } + const named = await savedEnvironmentNamedLocal() + throw new RuntimeClientError( + 'invalid_argument', + `--environment local names this machine's own Orca, not a saved environment, so \`orca ${commandPath.join(' ')}\` cannot act on it.`, + { + nextSteps: [ + ...(named + ? [`A saved environment named local is reached by its id: --environment ${named.id}.`] + : []), + 'Run `orca environment list` to see saved environments.' + ] + } + ) +} + +export function refuseReservedEnvironmentName(name: string): void { + if (isLocalEnvironmentSelector(name)) { + throw new RuntimeClientError( + 'invalid_argument', + '`local` is reserved: --environment local always means this machine’s own Orca. Save the environment under another name.' + ) + } +} + +/** cwd shortcuts (current, active) resolve only on the caller's own Orca. */ +export function assertLocalCwdWorktreeSelector(selector: string, client: RuntimeClient): void { + if (!client.isRemote) { + return + } + // A paired CLI's cwd belongs to the client filesystem, so it cannot identify server worktrees. + const environment = client.environmentSelector + throw new RuntimeClientError( + 'invalid_argument', + `${selector} is a local cwd shortcut and cannot be resolved against a remote runtime. Pass an explicit server-side worktree selector such as identity:, id:::, folder:, name:, branch:, issue:, or path:.`, + { + nextSteps: [ + environment + ? `List that environment's workspaces: \`orca worktree ps --environment ${quoteCliCommandArgument(environment)} --json\`, then copy a row's address.` + : 'Save this connection with `orca environment add --name --pairing-code `, then list its workspaces with `orca worktree ps --environment --json`.', + `For this machine's own workspace, rerun with --environment local.` + ] + } + ) +} diff --git a/src/cli/root-help-text-secondary.ts b/src/cli/root-help-text-secondary.ts index 31a629da56e4..05c4f482f1ed 100644 --- a/src/cli/root-help-text-secondary.ts +++ b/src/cli/root-help-text-secondary.ts @@ -52,11 +52,11 @@ export const ROOT_HELP_TEXT_SECONDARY = [ ' orca environment show --environment [--json]', ' orca environment rm --environment [--json]', ' orca worktree list [--repo ] [--limit ] [--json]', - ' orca worktree create --name [--repo |--project [--host ]|--project-host-setup ] [--agent ] [--prompt ] [--model ] [--effort ] [--setup run|skip|inherit] [--base-branch ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--parent-worktree ] [--no-parent] [--run-hooks] [--activate] [--json]', + ' orca worktree create --name [--repo |--project [--host ]|--project-host-setup ] [--agent ] [--prompt ] [--model ] [--effort ] [--setup run|skip|inherit] [--base-branch ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--parent-worktree [--parent-environment ]] [--no-parent] [--run-hooks] [--activate] [--json]', ' orca worktree show --worktree [--json]', ' orca worktree activate --worktree [--json]', ' orca worktree current [--json]', - ' orca worktree set --worktree [--display-name ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--workspace-status ] [--unread|--read] [--parent-worktree |--no-parent] [--json]', + ' orca worktree set --worktree [--display-name ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--workspace-status ] [--unread|--read] [--parent-worktree [--parent-environment ]|--no-parent] [--json]', ' orca worktree rm --worktree [--force] [--run-hooks] [--allow-failed-archive-hook] [--json]', ' orca worktree ps [--limit ] [--agent-wait] [--json]', ' orca ports [--worktree ] [--all] [--json]', @@ -92,6 +92,7 @@ export const ROOT_HELP_TEXT_SECONDARY = [ ' --worktree Worktree selector such as identity:, id:::, folder: (where the command takes folder workspaces), name:, branch:, issue:, path:, or active/current', ' --terminal Runtime-issued terminal handle returned by `orca terminal list --json`', ' --parent-worktree Parent worktree selector such as identity:, id:::, folder:, name:, branch:, issue:, path:, or active/current', + " --parent-environment Environment holding --parent-worktree: local or a saved id/name (default: the worktree's own)", ' --no-parent Force no parent lineage for unrelated worktree creation/update', '', 'Terminal Send Options:', @@ -111,7 +112,7 @@ export const ROOT_HELP_TEXT_SECONDARY = [ 'Output Options:', ' --json Emit machine-readable JSON instead of human text', ' --pairing-code Connect to a remote Orca runtime using an orca://pair?... code', - ' --environment Connect using a saved environment id or name', + " --environment Connect using a saved environment id or name; `local` is this machine's own Orca", ' --help Show this help message', '', 'Behavior:', diff --git a/src/cli/selectors.ts b/src/cli/selectors.ts index a7cdc4b7e8c7..1a258e67ab2f 100644 --- a/src/cli/selectors.ts +++ b/src/cli/selectors.ts @@ -1,13 +1,16 @@ import { resolve as resolvePath } from 'node:path' -import type { ComputerAppQuery, RuntimeWorktreeListResult } from '../shared/runtime-types' +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, @@ -49,17 +52,6 @@ export async function normalizeWorktreeSelectorForCaller( return purpose === 'parent' ? normalized : resolveFolderWorkspaceSelector(normalized, client) } -export function assertLocalCwdWorktreeSelector(selector: string, client: RuntimeClient): void { - if (!client.isRemote) { - return - } - // A paired CLI's cwd belongs to the client filesystem, so it cannot identify server worktrees. - throw new RuntimeClientError( - 'invalid_argument', - `${selector} is a local cwd shortcut and cannot be resolved against a remote runtime. Pass an explicit server-side worktree selector such as identity:, id:::, name:, branch:, issue:, or path:.` - ) -} - export async function resolveCurrentWorktreeSelector( cwd: string, client: RuntimeClient, @@ -75,19 +67,18 @@ export async function resolveCurrentWorktreeSelection( ): Promise { assertLocalCwdWorktreeSelector('current', client) - const worktrees = await client.call('worktree.list', { limit: 10_000 }) // Preserve the repo id: duplicate registrations can make a bare path selector ambiguous. const selection = selectEnclosingWorktreeSelectionOnHost( - worktrees.result.worktrees, + await readEnclosingWorkspaceCatalog(client, cwd), cwd, getCallerExecutionHostId(), - process.env.ORCA_WORKTREE_ID, + getCallerWorkspaceIds(), purpose ) if (!selection) { throw new RuntimeClientError( 'selector_not_found', - `No Orca-managed worktree contains the current directory: ${resolvePath(cwd)}` + `No Orca workspace contains the current directory: ${resolvePath(cwd)}` ) } return selection @@ -100,8 +91,8 @@ export async function resolveWorktreeCreateCwdContext( inferParent = true ): Promise> { assertLocalCwdWorktreeSelector('current', client) - const worktrees = await client.call('worktree.list', { limit: 10_000 }) - return selectWorktreeCreateCwdContext(worktrees.result.worktrees, cwd, inferRepo, inferParent) + const catalog = await readEnclosingWorkspaceCatalog(client, cwd) + return selectWorktreeCreateCwdContext(catalog, cwd, inferRepo, inferParent) } export async function getOptionalWorktreeSelector( @@ -171,20 +162,14 @@ export async function getBrowserWorktreeSelector( if (client.isRemote) { return undefined } - const catalog = await client - .call('worktree.list', { limit: 10_000 }) - .then((response) => response.result.worktrees) - .catch(() => undefined) - // Without the catalog neither cwd nor the terminal id can be checked; keep the runtime default. - if (!catalog) { - 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, - process.env.ORCA_WORKTREE_ID, + getCallerWorkspaceIds(), purpose ) if (enclosing || isLaunchedByAnotherRuntime(process.env, client.userDataPath)) { diff --git a/src/cli/specs/core.ts b/src/cli/specs/core.ts index da512bb4c7fb..120b61001d32 100644 --- a/src/cli/specs/core.ts +++ b/src/cli/specs/core.ts @@ -1,6 +1,7 @@ import type { CommandSpec } from '../args' import { GLOBAL_FLAGS } from '../args' import { WORKTREE_LISTING_SCOPE_NOTES } from './worktree-listing-scope-notes' +import { WORKTREE_CREATE_COMMAND_SPEC } from './worktree-create' import { WORKTREE_SET_COMMAND_SPEC } from './worktree-set' import { SERVE_COMMAND_SPECS } from './serve' import { REPO_COMMAND_SPECS } from './repo' @@ -74,74 +75,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ ], examples: ['orca worktree current', 'orca worktree current --json'] }, - { - path: ['worktree', 'create'], - repeatableFlags: ['reference'], - summary: 'Create a new Orca-managed worktree', - usage: - 'orca worktree create --name [--repo |--project [--host ]|--project-host-setup ] [--agent ] [--prompt ] [--model ] [--effort ] [--surface chat|terminal] [--setup run|skip|inherit] [--base-branch ] [--branch ] [--reference ...] [--reference-site ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--parent-worktree ] [--no-parent] [--run-hooks] [--activate] [--retry-launch ] [--json]', - allowedFlags: [ - ...GLOBAL_FLAGS, - 'repo', - 'project', - 'host', - 'project-host-setup', - 'name', - 'agent', - 'prompt', - 'model', - 'effort', - 'surface', - 'retry-launch', - 'base-branch', - 'branch', - 'reference', - 'reference-site', - 'issue', - 'pr', - 'linear-issue', - 'gitlab-issue', - 'gitlab-mr', - 'comment', - 'setup', - 'parent-worktree', - 'no-parent', - 'run-hooks', - 'activate' - ], - notes: [ - 'Repeat --reference to attach full issue or review URLs, or Jira issue keys, before setup or agent startup. Use --reference-site to choose the Jira site for keys. Other providers require full URLs. Cannot combine with legacy link flags.', - 'This creates a new checkout. For a fresh agent in an existing worktree, use `orca agent launch` instead.', - 'By default, Orca records the new worktree as a child of the caller context when it can infer one from the Orca terminal or current directory.', - 'If --repo is omitted, Orca infers the repo from the current Orca-managed worktree.', - 'Use --project to create on a ready project host setup without spelling the backing repo id. --project takes the project id or the display name from `orca project list`.', - '--host is only needed when the project is set up on more than one host; with a single setup Orca uses it. When it is ambiguous the error names every host the project is set up on.', - '--host takes local, ssh:, runtime:, or the bare host name `orca host list` prints for any of them.', - 'For related work, use the inferred parent or pass --parent-worktree active, folder:, or worktree: to make the relationship explicit. Worktree ids are the full :: values returned by `orca worktree list --json`.', - 'Use --no-parent when the new worktree should be independent of the current context.', - 'Pass --branch to name the Git branch without the configured prefix (a taken name gets a numeric suffix); --base-branch selects the starting ref instead.', - '--no-parent only affects Orca lineage; omit --base-branch to use the repo default base, or pass the default base ref explicitly for independent top-level work.', - 'By default this creates the worktree and its first terminal without switching the active Orca view.', - 'Pass --agent to start an agent with the worktree, as a chat or a terminal per your Chat | CLI choice for that agent, exactly as a new agent tab does; --prompt sends initial work to it. --model and --effort pick its model and reasoning effort, and --surface chat|terminal picks chat or terminal for this launch instead of your setting.', - 'After a lost agent launch reply, re-issue the same command from the same directory on the same host with --retry-launch from the error. Never retry as a fresh launch; older hosts require inspecting the workspace first.', - 'With --agent --json, result.launch says what started: launch.outcome.kind (structured chat or terminal), launch.outcome.handle, and launch.receipt.detail for why. An Orca host older than this returns the terminal agent handle in result.agentTerminalHandle instead.', - 'Repo-defined setup hooks follow the repository setup policy; pass --setup run to force them.', - 'Pass --activate when the CLI caller intentionally wants to reveal the new worktree in the app.', - 'Passing --run-hooks is kept as a legacy alias for --setup run and reveals the worktree.', - 'Use --pr for GitHub pull requests; --gitlab-issue and --gitlab-mr write separate GitLab links. GitLab URLs must match the stored source project or remote; they cannot select a foreign project.' - ], - examples: [ - 'orca worktree create --name agent-task --agent codex --prompt "hi" --json', - 'orca worktree create --name design --no-parent --agent codex --model gpt-6-astra --effort high --prompt "Write the design doc" --json', - 'orca worktree create --repo id: --name related-task --json', - 'orca worktree create --project github:stablyai/orca --host runtime:03ef704c-b180-4b10-998d-e28fbd5de9a3 --name benchmark --json', - 'orca worktree create --repo id: --name linear-task --linear-issue https://linear.app/stably/issue/STA-335/test-issue --json', - 'orca worktree create --repo id: --name agent-task --agent codex --prompt "hi" --json', - 'orca worktree create --repo id: --name folder-child --parent-worktree folder: --json', - 'orca worktree create --repo id: --name related-task --parent-worktree active --json', - 'orca worktree create --repo id: --name independent-task --no-parent --json' - ] - }, + WORKTREE_CREATE_COMMAND_SPEC, WORKTREE_SET_COMMAND_SPEC, { path: ['worktree', 'rm'], @@ -162,7 +96,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [ 'allow-failed-archive-hook' ], notes: [ - 'For a non-root folder workspace, removes its Orca entry and stops its sessions without deleting the folder or touching Git. The folder project root cannot be removed with this command. For a group folder workspace (folder:, or a path:/name: selector that matches one), Orca forgets it and the folder stays on disk; --delete-branch, --run-hooks and --allow-failed-archive-hook are refused for it.', + 'Needs an explicit workspace: --worktree current and active are refused, and the error names the selector they resolve to right now, as `git worktree remove` needs a path. For a non-root folder workspace, removes its Orca entry and stops its sessions without deleting the folder or touching Git. The folder project root cannot be removed with this command. For a group folder workspace (folder:, or a path:/name: selector that matches one), Orca forgets it and the folder stays on disk; --delete-branch, --run-hooks and --allow-failed-archive-hook are refused for it.', 'Use --worktree "id:" with the full id from orca worktree list --json to select one folder workspace; several entries can share the same path.', 'Repo-defined orca.yaml archive hooks are skipped unless --run-hooks is passed.', 'With --run-hooks, a failed archive hook blocks the removal: nothing is stopped, deleted or deregistered, and the command exits non-zero with error code worktree_archive_hook_failed. --force does not waive this.', diff --git a/src/cli/specs/worktree-create.ts b/src/cli/specs/worktree-create.ts new file mode 100644 index 000000000000..743f4b68504b --- /dev/null +++ b/src/cli/specs/worktree-create.ts @@ -0,0 +1,74 @@ +import type { CommandSpec } from '../args' +import { GLOBAL_FLAGS } from '../args' + +export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { + path: ['worktree', 'create'], + repeatableFlags: ['reference'], + summary: 'Create a new Orca-managed worktree', + usage: + 'orca worktree create --name [--repo |--project [--host ]|--project-host-setup ] [--agent ] [--prompt ] [--model ] [--effort ] [--surface chat|terminal] [--setup run|skip|inherit] [--base-branch ] [--branch ] [--reference ...] [--reference-site ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--parent-worktree [--parent-environment ]] [--no-parent] [--run-hooks] [--activate] [--retry-launch ] [--json]', + allowedFlags: [ + ...GLOBAL_FLAGS, + 'repo', + 'project', + 'host', + 'project-host-setup', + 'name', + 'agent', + 'prompt', + 'model', + 'effort', + 'surface', + 'retry-launch', + 'base-branch', + 'branch', + 'reference', + 'reference-site', + 'issue', + 'pr', + 'linear-issue', + 'gitlab-issue', + 'gitlab-mr', + 'comment', + 'setup', + 'parent-worktree', + 'parent-environment', + 'no-parent', + 'run-hooks', + 'activate' + ], + notes: [ + 'Repeat --reference to attach full issue or review URLs, or Jira issue keys, before setup or agent startup. Use --reference-site to choose the Jira site for keys. Other providers require full URLs. Cannot combine with legacy link flags.', + 'This creates a new checkout. For a fresh agent in an existing worktree, use `orca agent launch` instead.', + 'By default, Orca records the new worktree as a child of the caller context when it can infer one from the Orca terminal or current directory.', + 'If --repo is omitted, Orca infers the repo from the current Orca-managed worktree.', + 'Use --project to create on a ready project host setup without spelling the backing repo id. --project takes the project id or the display name from `orca project list`.', + '--host is only needed when the project is set up on more than one host; with a single setup Orca uses it. When it is ambiguous the error names every host the project is set up on.', + '--host takes local, ssh:, runtime:, or the bare host name `orca host list` prints for any of them.', + 'For related work, use the inferred parent or pass --parent-worktree active, folder:, or worktree: to make the relationship explicit. Worktree ids are the full :: values returned by `orca worktree list --json`.', + "--parent-worktree is looked up in the new worktree's environment. For a parent in another environment, add --parent-environment with local or a saved environment id or name, such as a row's address.environment from `orca worktree ps --json`. No other environment is searched.", + 'Use --no-parent when the new worktree should be independent of the current context.', + 'Pass --branch to name the Git branch without the configured prefix (a taken name gets a numeric suffix); --base-branch selects the starting ref instead.', + '--no-parent only affects Orca lineage; omit --base-branch to use the repo default base, or pass the default base ref explicitly for independent top-level work.', + 'By default this creates the worktree and its first terminal without switching the active Orca view.', + 'Pass --agent to start an agent with the worktree, as a chat or a terminal per your Chat | CLI choice for that agent, exactly as a new agent tab does; --prompt sends initial work to it. --model and --effort pick its model and reasoning effort, and --surface chat|terminal picks chat or terminal for this launch instead of your setting.', + 'After a lost agent launch reply, re-issue the same command from the same directory on the same host with --retry-launch from the error. Never retry as a fresh launch; older hosts require inspecting the workspace first.', + 'With --agent --json, result.launch says what started: launch.outcome.kind (structured chat or terminal), launch.outcome.handle, and launch.receipt.detail for why. An Orca host older than this returns the terminal agent handle in result.agentTerminalHandle instead.', + 'Repo-defined setup hooks follow the repository setup policy; pass --setup run to force them.', + 'Pass --activate when the CLI caller intentionally wants to reveal the new worktree in the app.', + 'Passing --run-hooks is kept as a legacy alias for --setup run and reveals the worktree.', + 'Use --pr for GitHub pull requests; --gitlab-issue and --gitlab-mr write separate GitLab links. GitLab URLs must match the stored source project or remote; they cannot select a foreign project.' + ], + examples: [ + 'orca worktree create --name agent-task --agent codex --prompt "hi" --json', + 'orca worktree create --name design --no-parent --agent codex --model gpt-6-astra --effort high --prompt "Write the design doc" --json', + 'orca worktree create --repo id: --name related-task --json', + 'orca worktree create --project github:stablyai/orca --host runtime:03ef704c-b180-4b10-998d-e28fbd5de9a3 --name benchmark --json', + 'orca worktree create --repo id: --name linear-task --linear-issue https://linear.app/stably/issue/STA-335/test-issue --json', + 'orca worktree create --repo id: --name agent-task --agent codex --prompt "hi" --json', + 'orca worktree create --repo id: --name folder-child --parent-worktree folder: --json', + 'orca worktree create --repo id: --name related-task --parent-worktree active --json', + 'orca worktree create --environment --repo id: --name child --parent-environment local --parent-worktree folder: --json', + 'orca worktree create --repo id: --name independent-task --no-parent --json' + ] +} diff --git a/src/cli/specs/worktree-set.ts b/src/cli/specs/worktree-set.ts index 92e81cda90b4..3203a9cb2a2e 100644 --- a/src/cli/specs/worktree-set.ts +++ b/src/cli/specs/worktree-set.ts @@ -5,7 +5,7 @@ export const WORKTREE_SET_COMMAND_SPEC: CommandSpec = { path: ['worktree', 'set'], summary: 'Update Orca metadata for a worktree', usage: - 'orca worktree set --worktree [--display-name ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--workspace-status ] [--unread|--read] [--parent-worktree |--no-parent] [--json]', + 'orca worktree set --worktree [--display-name ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--workspace-status ] [--unread|--read] [--parent-worktree [--parent-environment ]|--no-parent] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'worktree', @@ -20,12 +20,14 @@ export const WORKTREE_SET_COMMAND_SPEC: CommandSpec = { 'unread', 'read', 'parent-worktree', + 'parent-environment', 'no-parent' ], notes: [ 'Workspace status ids match the board columns (defaults: todo, in-progress, in-review, completed); custom statuses use their configured id.', 'Pass --comment "" (or --comment=) to clear the comment.', 'Pass --linear-issue null to clear the Linear issue link.', + "--parent-worktree is looked up in the worktree's own environment; add --parent-environment for a parent in another environment. No other environment is searched.", 'Pass --pr null, --gitlab-issue null, or --gitlab-mr null to clear only the matching link.', 'Each link flag updates its own field and leaves unrelated links unchanged. GitLab URLs must match the stored source project or remote; they cannot select a foreign project.', 'On a folder workspace (folder:, or a path:/name: selector that matches one), only --display-name, --comment, --workspace-status and --unread/--read apply. Parent and link flags are refused; link it with orca reference add.' diff --git a/src/cli/test-fixtures.ts b/src/cli/test-fixtures.ts index 19ff66263f5a..adeceeea6f3c 100644 --- a/src/cli/test-fixtures.ts +++ b/src/cli/test-fixtures.ts @@ -97,3 +97,8 @@ export function queueNoFolderAtSelector(mock: Mock): void { }) ) } + +/** Answers the folder catalog a cwd selection reads beside worktree.list: no folder workspaces. */ +export function noFolderWorkspacesFixture(): OkFixture { + return okFixture('req_folders', { folderWorkspaces: [] }) +} diff --git a/src/cli/workspace-address.ts b/src/cli/workspace-address.ts new file mode 100644 index 000000000000..e4a2bb6b1cb7 --- /dev/null +++ b/src/cli/workspace-address.ts @@ -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 './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 +): Promise { + 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 +} + +function listingOf(rows: readonly AddressableRow[]): Listing { + const rowsById = new Map() + 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 = { + 'one-off-connection': + 'unavailable (one-off pairing-code connection; save it with `orca environment add --name --pairing-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 { + 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) +} diff --git a/src/cli/workspace-catalog-row.ts b/src/cli/workspace-catalog-row.ts new file mode 100644 index 000000000000..11b2e5e834fd --- /dev/null +++ b/src/cli/workspace-catalog-row.ts @@ -0,0 +1,37 @@ +import type { RuntimeWorktreeRecord } from '../shared/runtime-types' +import { parseWorkspaceKey } from '../shared/workspace-scope' +import { RuntimeClientError } from './runtime/types' + +/** One workspace the cwd rule can pick: a repo-backed row or a group-level folder keyed `folder:`. */ +export type CatalogRow = Pick & { + identity?: { key: string } + repoId?: string + /** A folder workspace whose owning host couldn't be derived; it may be the caller's, so it counts. */ + hostUnresolved?: true +} + +/** An innermost folder with an unknown host can't be ruled in or out, so no owner is guessed. */ +export function refuseUnresolvedOwner(innermost: readonly CatalogRow[]): void { + const unresolved = innermost.filter((row) => row.hostUnresolved) + if (unresolved.length === 0) { + return + } + throw new RuntimeClientError( + 'selector_ambiguous', + `Orca can't tell which host owns the folder workspace containing the current directory (${unresolved.map((row) => `${row.id} at ${row.path}`).join(', ')}), so it won't guess the workspace.`, + { + workspaces: innermost.map((row) => ({ + kind: parseWorkspaceKey(row.id)?.type === 'folder' ? 'folder workspace' : 'worktree', + id: row.id, + path: row.path, + hostId: row.hostUnresolved ? null : (row.hostId ?? 'local') + })), + nextSteps: [ + ...unresolved.map( + (row) => `Pass --worktree ${row.id} to target the folder workspace itself.` + ), + 'Or pass an explicit worktree selector from `orca worktree ps --json`.' + ] + } + ) +} diff --git a/src/cli/workspace-format.ts b/src/cli/workspace-format.ts index ab4e46f36aee..77a26c4fedf1 100644 --- a/src/cli/workspace-format.ts +++ b/src/cli/workspace-format.ts @@ -1,3 +1,4 @@ +import { formatAddressLines, formatParentLine, type WorkspaceAnnotation } from './workspace-address' import type { PublicKnownRuntimeEnvironment } from '../shared/remote-runtime/host-catalog/runtime-environments' import type { RuntimeRepoList, @@ -135,7 +136,13 @@ export function formatEnvironment(environment: PublicKnownRuntimeEnvironment): s ].join('\n') } -export function formatWorktreePs(result: WithAnnotatedHostScope): string { +type AnnotatedPsRow = RuntimeWorktreePsResult['worktrees'][number] & Partial + +export function formatWorktreePs( + result: WithAnnotatedHostScope< + Omit & { worktrees: AnnotatedPsRow[] } + > +): string { const scope = formatListingHostScope(result.hostScope) if (result.worktrees.length === 0) { return `No worktrees found.\n${scope}` @@ -143,7 +150,7 @@ export function formatWorktreePs(result: WithAnnotatedHostScope - `${worktree.repo} ${worktree.branch} host=${worktree.hostId ?? 'unverifiable'} ${formatWorktreePsTerminalFields(worktree)} unread:${worktree.unread ? 'yes' : 'no'}${formatWorktreePsProgramStatus(worktree.agents)}\n${worktree.path}${formatWorktreePsParent(worktree)}${worktree.preview ? `\npreview: ${worktree.preview}` : ''}` + `${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}` @@ -152,6 +159,13 @@ export function formatWorktreePs(result: WithAnnotatedHostScope): 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 +}): string { const worktree = result.worktree - return Object.entries(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 } diff --git a/src/main/git/repo-detection.ts b/src/main/git/repo-detection.ts index 4bcce65db909..2082419b5a86 100644 --- a/src/main/git/repo-detection.ts +++ b/src/main/git/repo-detection.ts @@ -2,7 +2,8 @@ import { existsSync, statSync } from 'node:fs' import { basename, dirname, resolve } from 'node:path' import { normalizeRuntimePathSeparators } from '../../shared/cross-platform-path' import { parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' -import { scanGitMarkerSync, resolveRealPathSync } from './repo-git-marker-scan' +import { scanGitMarkerSync } from './repo-git-marker-scan' +import { resolveRealPathSync } from '../../shared/real-path-sync' import { gitRepoOutput, runGitRepoCommands, diff --git a/src/main/git/repo-git-marker-scan.ts b/src/main/git/repo-git-marker-scan.ts index 683127848f60..24df3683df2f 100644 --- a/src/main/git/repo-git-marker-scan.ts +++ b/src/main/git/repo-git-marker-scan.ts @@ -1,4 +1,5 @@ import { readFileSync, realpathSync, statSync } from 'node:fs' +import { resolveRealPathSync } from '../../shared/real-path-sync' import { dirname, isAbsolute, join, relative } from 'node:path' import { normalizeRuntimePathSeparators } from '../../shared/cross-platform-path' import { resolveGitMetadataPath } from '../../shared/git/metadata/git-metadata-path' @@ -27,18 +28,6 @@ export function scanGitMarkerSync(path: string): GitMarkerScanResult { return scanGitMarkerAncestorsSync(path) } -export function resolveRealPathSync(path: string): string | null { - try { - return realpathSync.native(path) - } catch { - try { - return realpathSync(path) - } catch { - return null - } - } -} - function scanGitMarkerAncestorsSync(path: string): GitMarkerScanResult { for (const candidate of ancestorDirectories(path)) { if (!isInsideDotGitMarker(candidate, path)) { diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-refusal.test.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-refusal.test.ts index 7a2911b0a4a0..e0fbdd2460a5 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-refusal.test.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-cwd-refusal.test.ts @@ -225,6 +225,9 @@ describe('CLI cwd refusal through production creation and durable failed receipt if (method === 'worktree.list') { return worktreeListFixture(catalog) } + if (method === 'folderWorkspace.list') { + return okFixture('folders', { folderWorkspaces: [] }) + } if (method === 'status.get') { return route === 'legacy' ? okFixture('status', { capabilities: [] }) @@ -499,6 +502,9 @@ describe('CLI cwd refusal through production creation and durable failed receipt if (method === 'worktree.list') { return worktreeListFixture(rows) } + if (method === 'folderWorkspace.list') { + return okFixture('folders', { folderWorkspaces: [] }) + } if (method === 'status.get') { return agentLaunchHostFixture() } diff --git a/src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts b/src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts index efa818362238..2796ac939df7 100644 --- a/src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts @@ -43,6 +43,9 @@ it('checks its own Run with A identity but refuses ambiguous identity before cho if (method === 'worktree.list') { return okFixture('req_list', { worktrees: [] }) } + if (method === 'folderWorkspace.list') { + return okFixture('req_folders', { folderWorkspaces: [] }) + } if (method === 'terminal.resolveActive') { try { const handle = await runtime.resolveActiveTerminal( diff --git a/src/shared/real-path-sync.ts b/src/shared/real-path-sync.ts new file mode 100644 index 000000000000..cc519801999d --- /dev/null +++ b/src/shared/real-path-sync.ts @@ -0,0 +1,14 @@ +import { realpathSync } from 'node:fs' + +/** The path with symlinks resolved, or null when it doesn't exist or can't be read. */ +export function resolveRealPathSync(path: string): string | null { + try { + return realpathSync.native(path) + } catch { + try { + return realpathSync(path) + } catch { + return null + } + } +} diff --git a/tests/e2e/agent-launch-cli.unit.test.ts b/tests/e2e/agent-launch-cli.unit.test.ts index 791aa9d3538e..2a74aacde397 100644 --- a/tests/e2e/agent-launch-cli.unit.test.ts +++ b/tests/e2e/agent-launch-cli.unit.test.ts @@ -300,11 +300,17 @@ describe('CLI launch through host surface creation and replay admission', () => }) it.each([undefined, 'current'])( - 'uses the innermost native folder for %s before Git fallback', + 'uses the innermost enclosing folder workspace for %s', async (selector) => { const client = hostClient(runtimeStub()) vi.spyOn(console, 'log').mockImplementation(() => {}) const call = vi.mocked(client.call) + call.mockResolvedValueOnce({ + id: 'list', + ok: true, + result: { worktrees: [], totalCount: 0, truncated: false }, + _meta: { runtimeId: 'runtime-1' } + }) call.mockResolvedValueOnce({ id: 'folders', ok: true, @@ -327,10 +333,9 @@ describe('CLI launch through host surface creation and replay admission', () => cwd: '/tmp/repo/nested/deeper', json: true }) - expect(call).not.toHaveBeenCalledWith('worktree.list', expect.anything()) expect(call).toHaveBeenCalledWith( 'agent.launchReplay', - expect.objectContaining({ target: { kind: 'existing', worktree: 'id:folder:nested' } }) + expect.objectContaining({ target: { kind: 'existing', worktree: 'folder:nested' } }) ) } )