test: prune terminal, workspace and scanner policy cases

This commit is contained in:
OrcaWin
2026-11-12 06:18:19 -08:00
parent 49981823c0
commit cb42e216b2
10 changed files with 2 additions and 834 deletions
-2
View File
@@ -58,7 +58,6 @@ on:
- 'src/main/ai-vault/discovery/session-file-discovery.ts'
- 'src/main/ai-vault/discovery/session-json-file.ts'
- 'src/main/ai-vault/discovery/session-path-absence.ts'
- 'src/main/ai-vault/discovery/session-scanner-agent-root-overrides.test.ts'
- 'src/main/ai-vault/discovery/session-scanner-agent-sources.ts'
- 'src/main/ai-vault/discovery/session-scanner-candidates.ts'
- 'src/main/ai-vault/discovery/session-scanner-directory-reader.test.ts'
@@ -204,7 +203,6 @@ on:
- 'src/main/ai-vault/discovery/session-file-discovery.ts'
- 'src/main/ai-vault/discovery/session-json-file.ts'
- 'src/main/ai-vault/discovery/session-path-absence.ts'
- 'src/main/ai-vault/discovery/session-scanner-agent-root-overrides.test.ts'
- 'src/main/ai-vault/discovery/session-scanner-agent-sources.ts'
- 'src/main/ai-vault/discovery/session-scanner-candidates.ts'
- 'src/main/ai-vault/discovery/session-scanner-directory-reader.test.ts'
@@ -1,98 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
const {
callMock,
runtimeClientConstructorMock,
serveOrcaAppMock,
getDefaultUserDataPathMock,
addEnvironmentFromPairingCodeMock,
listEnvironmentsMock,
spawnMock
} = vi.hoisted(() => ({
callMock: vi.fn(),
runtimeClientConstructorMock: vi.fn(),
serveOrcaAppMock: vi.fn(),
getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'),
addEnvironmentFromPairingCodeMock: vi.fn(),
listEnvironmentsMock: vi.fn(),
spawnMock: vi.fn()
}))
vi.mock('../runtime/client', async () => {
const { createRuntimeClientModuleMock } = await import('../index-test-harness.js')
return createRuntimeClientModuleMock({
callMock,
runtimeClientConstructorMock,
serveOrcaAppMock,
getDefaultUserDataPathMock
})
})
vi.mock('../runtime/metadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getDefaultUserDataPath: getDefaultUserDataPathMock
}))
vi.mock('../runtime/launch', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
serveOrcaApp: serveOrcaAppMock
}))
vi.mock('../runtime/environments', () => ({
addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock,
removeEnvironment: vi.fn(),
resolveEnvironment: vi.fn()
}))
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 { okFixture, queueFixtures } from '../test-fixtures'
import { useWorktreeAwarenessEnvironment } from '../index-test-harness'
function readFixture(overrides: Record<string, unknown> = {}) {
return okFixture('req_terminal_read', {
terminal: {
handle: 'term_abc',
status: 'running',
tail: ['clear'],
truncated: false,
nextCursor: null,
...overrides
}
})
}
describe('orca terminal read --screen', () => {
useWorktreeAwarenessEnvironment({
callMock,
serveOrcaAppMock,
getDefaultUserDataPathMock,
addEnvironmentFromPairingCodeMock,
listEnvironmentsMock,
spawnMock
})
// Older hosts strip the unknown screen key and return a stream read.
it("refuses to pass an older host's stream off as a screen read", async () => {
queueFixtures(callMock, readFixture({ tail: ['cclclecleaclear'] }))
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
const priorExitCode = process.exitCode
await main(['terminal', 'read', '--terminal', 'term_abc', '--screen', '--json'], '/tmp/repo')
expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain(
'does not support --screen reads'
)
expect(process.exitCode).toBe(1)
process.exitCode = priorExitCode
})
})
@@ -1,26 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RuntimeClient } from '../runtime/client'
import { parseArgs } from '../args'
import { TERMINAL_HANDLERS } from './terminal'
afterEach(() => vi.restoreAllMocks())
describe('terminal set-pane-title', () => {
it.each([{ args: [] }, { args: ['--title'] }])(
'refuses a missing title before resolving a terminal (%j)',
async ({ args }) => {
const client = new RuntimeClient()
const call = vi.spyOn(client, 'call')
const parsed = parseArgs(['terminal', 'set-pane-title', ...args])
await expect(
TERMINAL_HANDLERS['terminal set-pane-title']({
flags: parsed.flags,
client,
cwd: '/tmp',
json: true
})
).rejects.toMatchObject({ code: 'invalid_argument' })
expect(call).not.toHaveBeenCalled()
}
)
})
-64
View File
@@ -1,64 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RuntimeClient } from '../runtime/client'
import type { CliStatusResult } from '../../shared/runtime-session-contracts'
import '../../shared/protocol-version'
import { TERMINAL_SPLIT_RETRY_RUNTIME_CAPABILITY } from '../../shared/terminal/runtime-policy/terminal-runtime-capabilities'
import { TERMINAL_HANDLERS } from './terminal'
function splitClient(
call: RuntimeClient['call'],
capabilities: NonNullable<CliStatusResult['runtime']['capabilities']>
): RuntimeClient {
const client = new RuntimeClient('/tmp/orca-split-test', 60_000, null, null)
vi.spyOn(client, 'call').mockImplementation(call)
vi.spyOn(client, 'getCliStatus').mockResolvedValue({
id: 'status',
ok: true,
result: {
app: { running: true, pid: 123 },
runtime: { state: 'ready', reachable: true, runtimeId: 'runtime-1', capabilities },
graph: { state: 'ready' }
},
_meta: { runtimeId: 'runtime-1' }
})
return client
}
function retrySplit(client: RuntimeClient, splitId = 'leaf-1') {
return TERMINAL_HANDLERS['terminal split']({
flags: new Map([
['terminal', 'term_1'],
['command', 'agent --task 1'],
['retry-split', splitId]
]),
client,
cwd: '/tmp/worktree',
json: true
})
}
describe('terminal split --retry-split', () => {
afterEach(() => {
vi.restoreAllMocks()
})
// An older host strips `retrySplit` and splits again, starting a second copy of the command.
it('refuses rather than splitting again on a host without the capability', async () => {
const call = vi.fn()
await expect(retrySplit(splitClient(call, []))).rejects.toThrow(
/does not support --retry-split/
)
expect(call).not.toHaveBeenCalled()
})
// An unset shell variable gives a blank id; dropping it would split again and re-run --command.
it('refuses a blank retry id instead of making a fresh split', async () => {
const call = vi.fn()
await expect(
retrySplit(splitClient(call, [TERMINAL_SPLIT_RETRY_RUNTIME_CAPABILITY]), '')
).rejects.toThrow(/--retry-split/)
expect(call).not.toHaveBeenCalled()
})
})
-92
View File
@@ -28,98 +28,6 @@ function terminalClient(
return client
}
describe('terminal close CLI', () => {
afterEach(() => {
vi.restoreAllMocks()
process.exitCode = ORIGINAL_EXIT_CODE
})
it.each([
[
'its SSH provider is no longer registered',
false,
'Closed terminal term-remote. The PTY was not confirmed stopped: its SSH provider is no longer registered.'
],
[
'Request "pty.shutdown" timed out after 14250ms',
true,
'Closed terminal term-remote. The PTY was not confirmed stopped: Request "pty.shutdown" timed out after 14250ms. The kill retries when the host reconnects.'
],
// An older host never reports a recorded kill, so the same reason promises nothing.
[
'Request "pty.shutdown" timed out after 14250ms',
false,
'Closed terminal term-remote. The PTY was not confirmed stopped: Request "pty.shutdown" timed out after 14250ms.'
]
])(
'reports an unverifiable stop (%s, kill recorded: %s) as a committed close with exit code 1',
async (ptyStopReason, pendingKillRecorded, message) => {
process.exitCode = undefined
const close = {
handle: 'term-remote',
tabId: 'tab-1',
ptyKilled: false,
ptyStopVerdict: 'unverifiable' as const,
ptyStopReason,
...(pendingKillRecorded ? { pendingKillRecorded: true as const } : {})
}
const call = vi.fn().mockResolvedValue({
id: 'req-close',
ok: true,
result: { close },
_meta: { runtimeId: 'runtime-1' }
})
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal close']({
flags: new Map([['terminal', close.handle]]),
client: terminalClient(call),
cwd: '/tmp/worktree',
json: true
})
expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toMatchObject({
ok: false,
error: { code: 'terminal_stop_unverifiable', message, data: { close } }
})
expect(process.exitCode).toBe(1)
}
)
it('fails JSON when bulk close cannot verify every PTY stopped', async () => {
process.exitCode = undefined
const call = vi.fn().mockResolvedValue({
result: {
closed: 2,
stopped: 1,
retiredSurfaces: true,
ptyStopVerdict: 'unverifiable',
ptyStopReason: 'the SSH host disconnected'
}
})
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await TERMINAL_HANDLERS['terminal close']({
flags: new Map<string, string | true>([
['worktree', 'id:repo::/worktree'],
['all', true]
]),
client: terminalClient(call),
cwd: '/tmp/worktree',
json: true
})
expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toMatchObject({
ok: false,
error: {
code: 'terminal_stop_unverifiable',
data: { close: { closed: 2, stopped: 1, ptyStopVerdict: 'unverifiable' } }
}
})
expect(process.exitCode).toBe(1)
})
})
describe('terminal send CLI', () => {
afterEach(() => {
vi.restoreAllMocks()
@@ -6,80 +6,19 @@ import { selectEnclosingWorktreeSelectionOnHost } from './caller-host-worktree-s
import type { CatalogRow } from './workspace-catalog-row'
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<typeof okFixture>): 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.
// Symlinks need privileges on Windows.
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')
@@ -155,65 +94,3 @@ describe.skipIf(process.platform === 'win32')('symlink aliases on the caller fil
])
})
})
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('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'
})
})
})
@@ -1,51 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
selectEnclosingWorktreeOnHost,
selectWorktreeIdOnHost
} from './caller-host-worktree-selection'
const PATH = '/srv/app'
function row(hostId: 'local' | `ssh:${string}` | undefined, id: string, identityKey?: string) {
return {
id,
path: PATH,
...(hostId ? { hostId } : {}),
...(identityKey ? { identity: { key: identityKey } } : {})
}
}
const TWINS = [
row('ssh:host-a', `repo-a::${PATH}`),
row('ssh:host%20d', `repo-d::${PATH}`),
row('local', `repo-l::${PATH}`)
]
describe('implicit worktree selection is scoped to the caller host (#21210)', () => {
it('keeps a runtime-stamped local checkout for a local caller', () => {
const rows = [
TWINS[0]!,
{ id: `repo-r::${PATH}`, path: PATH, hostId: 'runtime:env-1' as const }
]
expect(selectEnclosingWorktreeOnHost(rows, `${PATH}/src`, 'local')).toBe(`id:repo-r::${PATH}`)
expect(selectEnclosingWorktreeOnHost(rows, PATH, 'ssh:host%20d')).toBeUndefined()
})
it('never adopts another host or an unstamped row for an SSH caller', () => {
expect(
selectEnclosingWorktreeOnHost([TWINS[0]!, row(undefined, 'repo-u::x')], PATH, 'ssh:host-z')
).toBeUndefined()
})
it('names the exact identity when another host shares the bare id', () => {
const twins = [
row('ssh:host-a', `repo-1::${PATH}`, 'wt2:a'),
row('ssh:host%20d', `repo-1::${PATH}`, 'wt2:d')
]
expect(selectEnclosingWorktreeOnHost(twins, PATH, 'ssh:host%20d')).toBe('identity:wt2:d')
expect(selectWorktreeIdOnHost(twins, `repo-1::${PATH}`, 'ssh:host%20d')).toBe('identity:wt2:d')
expect(selectWorktreeIdOnHost(twins, `repo-1::${PATH}`, 'ssh:host-z')).toBeUndefined()
})
})
@@ -1,291 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
const {
callMock,
runtimeClientConstructorMock,
serveOrcaAppMock,
getDefaultUserDataPathMock,
addEnvironmentFromPairingCodeMock,
listEnvironmentsMock,
spawnMock
} = vi.hoisted(() => ({
callMock: vi.fn(),
runtimeClientConstructorMock: vi.fn(),
serveOrcaAppMock: vi.fn(),
getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'),
addEnvironmentFromPairingCodeMock: vi.fn(),
listEnvironmentsMock: vi.fn(),
spawnMock: vi.fn()
}))
vi.mock('../runtime/client', async () => {
const { createRuntimeClientModuleMock } = await import('../index-test-harness.js')
return createRuntimeClientModuleMock({
callMock,
runtimeClientConstructorMock,
serveOrcaAppMock,
getDefaultUserDataPathMock
})
})
vi.mock('../runtime/metadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
getDefaultUserDataPath: getDefaultUserDataPathMock
}))
vi.mock('../runtime/launch', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
serveOrcaApp: serveOrcaAppMock
}))
vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({
listEnvironments: listEnvironmentsMock
}))
vi.mock('child_process', async () => {
const { createChildProcessModuleMock } = await import('../index-test-harness.js')
return createChildProcessModuleMock(spawnMock)
})
import { main } from '../index'
import { useWorktreeAwarenessEnvironment } from '../index-test-harness'
import { RuntimeClientError } from '../runtime/types'
import { buildWorktree, okFixture } from '../test-fixtures'
const SAVED = [
{ id: 'srv-b', name: 'build-box' },
{ id: 'srv-c', name: 'gpu-box' }
].map((environment) => ({
...environment,
createdAt: 1,
updatedAt: 1,
lastUsedAt: null,
runtimeId: null,
endpoints: [],
preferredEndpointId: null
}))
const CROSS_MACHINE = 'worktree.lineage.crossMachine'
type Call = { environment: string; method: string; params: Record<string, unknown> }
type Answer = (call: Call) => unknown
/** Answers each request by the environment its client routes to; `local` is the caller's Orca. */
function serve(answer: Answer): Call[] {
const calls: Call[] = []
callMock.mockImplementation(async function (
this: { environmentSelector: string | null },
method: string,
params: Record<string, unknown> = {}
) {
const call = { environment: this.environmentSelector ?? 'local', method, params }
calls.push(call)
const result = answer(call)
if (result instanceof Error) {
throw result
}
if (result !== undefined) {
return okFixture(method, result)
}
if (method === 'status.get') {
return okFixture(method, { capabilities: [CROSS_MACHINE, 'worktree.set.folder-parent.v1'] })
}
if (method === 'worktree.create' || method === 'worktree.set') {
return okFixture(method, { worktree: buildWorktree('/srv/child', 'child', 'abc', 'repo-1') })
}
if (method === 'worktree.lineageList') {
return okFixture(method, { installationId: `install-${call.environment}` })
}
return okFixture(method, {})
})
return calls
}
const FOLDER_PARENT: Answer = ({ method, params }) =>
method === 'worktree.show' && params.worktree === 'folder:hub-a'
? { worktree: { id: 'folder:hub-a', path: '/Users/me/Projects Hub' } }
: undefined
const MUTATIONS = new Set(['worktree.create', 'worktree.set'])
async function run(args: string[], cwd = '/tmp/elsewhere') {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
const err = vi.spyOn(console, 'error').mockImplementation(() => {})
const prior = process.exitCode
await main([...args, '--json'], cwd)
const exitCode = process.exitCode
process.exitCode = prior
const output = [...log.mock.calls, ...err.mock.calls].flat().join('\n')
log.mockRestore()
err.mockRestore()
return { exitCode, output }
}
describe('--parent-environment', () => {
useWorktreeAwarenessEnvironment({
callMock,
serveOrcaAppMock,
getDefaultUserDataPathMock,
addEnvironmentFromPairingCodeMock,
listEnvironmentsMock,
spawnMock
})
it('by default looks only in the child environment and says where it looked', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const calls = serve(({ method }) =>
method === 'worktree.set'
? new RuntimeClientError('LINEAGE_PARENT_NOT_FOUND', 'Parent not found.')
: undefined
)
const { exitCode, output } = await run([
'worktree',
'set',
'--environment',
'srv-b',
'--worktree',
'id:repo-1::/srv/child',
'--parent-worktree',
'folder:hub-a'
])
expect(exitCode).toBe(1)
const error = JSON.parse(output).error
expect(error.code).toBe('LINEAGE_PARENT_NOT_FOUND')
expect(error.data.environment).toBe('srv-b')
expect(error.data.nextSteps.join('\n')).toContain('--parent-environment')
expect(new Set(calls.map((call) => call.environment))).toEqual(new Set(['srv-b']))
})
it('refuses a caller-relative parent in another environment before any request', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const calls = serve(() => undefined)
const { output } = await run([
'worktree',
'create',
'--repo',
'id:repo-1',
'--name',
'child',
'--parent-environment',
'srv-b',
'--parent-worktree',
'current'
])
expect(JSON.parse(output).error.code).toBe('invalid_argument')
expect(calls).toEqual([])
})
it('refuses --parent-environment without a parent or with --no-parent', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const calls = serve(() => undefined)
for (const parentFlags of [['--no-parent'], []]) {
const { output } = await run([
'worktree',
'set',
'--worktree',
'id:repo-1::/srv/child',
'--parent-environment',
'srv-b',
...parentFlags
])
expect(JSON.parse(output).error.code).toBe('invalid_argument')
}
expect(calls).toEqual([])
})
it('fails each preflight before any mutating request', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const setOnB = (parentEnvironment: string) => [
'worktree',
'set',
'--environment',
'srv-b',
'--worktree',
'id:repo-1::/srv/child',
'--parent-environment',
parentEnvironment,
'--parent-worktree',
'folder:hub-a'
]
const cases: [string, string, Answer][] = [
['srv-z', 'environment_not_paired', FOLDER_PARENT],
[
'srv-c',
'environment_unavailable',
({ environment }) =>
environment === 'srv-c'
? new RuntimeClientError('remote_runtime_unavailable', 'Could not connect.')
: undefined
],
[
'local',
'incompatible_runtime',
(call) =>
call.method === 'status.get' && call.environment === 'srv-b'
? { capabilities: [] }
: FOLDER_PARENT(call)
],
[
'local',
'LINEAGE_PARENT_NOT_FOUND',
({ method }) =>
method === 'worktree.show'
? new RuntimeClientError('selector_not_found', 'No match.')
: undefined
]
]
for (const [parentEnvironment, code, answer] of cases) {
const calls = serve(answer)
const { output } = await run(setOnB(parentEnvironment))
expect(JSON.parse(output).error.code, parentEnvironment).toBe(code)
expect(calls.filter((call) => MUTATIONS.has(call.method))).toEqual([])
if (code === 'environment_not_paired') {
expect(calls).toEqual([])
}
}
})
it('names the searched environment and lists it when the parent is ambiguous', async () => {
listEnvironmentsMock.mockReturnValue(SAVED)
const ambiguous = (code: string) =>
new RuntimeClientError(code, 'Several workspaces match name:B Ambiguous.', {
candidates: [{ selector: 'folder:one' }, { selector: 'folder:two' }],
nextSteps: ['Run `orca worktree ps --json` to compare the choices.']
})
const parent = ['--parent-worktree', 'name:B Ambiguous', '--parent-environment', 'srv-b']
const cases: [string[], Answer][] = [
// Same environment as the child: the runtime refuses the set or create.
[
['worktree', 'set', '--environment', 'srv-b', '--worktree', 'id:repo-1::/srv/child'],
({ method }) =>
method === 'worktree.set' ? ambiguous('LINEAGE_PARENT_AMBIGUOUS') : undefined
],
[
['worktree', 'create', '--environment', 'srv-b', '--repo', 'id:repo-1', '--name', 'c'],
({ method }) =>
method === 'worktree.create' ? ambiguous('LINEAGE_PARENT_AMBIGUOUS') : undefined
],
// Another environment: the lookup there finds several.
[
['worktree', 'set', '--worktree', 'id:repo-1::/tmp/child'],
({ environment, method }) =>
environment === 'srv-b' && method === 'worktree.show'
? ambiguous('selector_ambiguous')
: undefined
]
]
for (const [command, answer] of cases) {
serve(answer)
const { output } = await run([...command, ...parent])
const error = JSON.parse(output).error
expect(error.code, command[1]).toBe('LINEAGE_PARENT_AMBIGUOUS')
expect(error.data.environment).toBe('srv-b')
expect(error.data.candidates).toEqual([
{ selector: 'folder:one' },
{ selector: 'folder:two' }
])
expect(error.data.nextSteps).toEqual([
'Compare the choices with `orca worktree ps --environment srv-b --json`, then pass one as --parent-worktree.'
])
}
})
})
@@ -1,56 +0,0 @@
import { homedir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { AiVaultScanOptions } from '../session-scanner-types'
/** Exercise root consumers: module-time constants can bypass an otherwise correct override validator (#13082). */
const NO_OPTIONS: AiVaultScanOptions = {}
const NO_WSL: readonly string[] = []
async function rootDirsFor(
agent: 'codex' | 'copilot' | 'devin' | 'openclaw' | 'kimi' | 'grok',
env: Record<string, string>
): Promise<string[]> {
vi.resetModules()
for (const [key, value] of Object.entries(env)) {
vi.stubEnv(key, value)
}
const sources = await import('./session-scanner-agent-sources.js')
const source = sources.AI_VAULT_AGENT_SOURCES[agent]
if (!source) {
throw new Error(`no source table entry for ${agent}`)
}
return source.rootDirs(NO_OPTIONS, NO_WSL)
}
describe('agent scan roots from environment overrides', () => {
afterEach(() => {
vi.unstubAllEnvs()
vi.resetModules()
})
it('finds Devin transcripts in a relocated platform data directory', async () => {
const dataDir = join(homedir(), 'relocated-agent-data')
const roots = await rootDirsFor('devin', {
DEVIN_HOME: '',
[process.platform === 'win32' ? 'APPDATA' : 'XDG_DATA_HOME']: dataDir
})
expect(roots).toEqual(
['transcripts', 'agent_logs'].map((dir) => join(dataDir, 'devin', 'cli', dir))
)
})
it('keeps an explicit transcript root isolated and discovers both WSL layouts', async () => {
const { AI_VAULT_AGENT_SOURCES } = await import('./session-scanner-agent-sources')
const custom = join(homedir(), 'custom-devin')
const wslHome = join(homedir(), 'wsl-home')
expect(
AI_VAULT_AGENT_SOURCES.devin?.rootDirs({ devinTranscriptsDir: custom }, [wslHome])
).toEqual([
custom,
join(wslHome, '.local', 'share', 'devin', 'cli', 'transcripts'),
join(wslHome, '.local', 'share', 'devin', 'cli', 'agent_logs')
])
})
})
@@ -1,36 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { walkSessionFiles } from './session-scanner-discovery'
let tempRoot: string | null = null
afterEach(async () => {
if (tempRoot) {
await rm(tempRoot, { recursive: true, force: true })
tempRoot = null
}
})
describe('walkSessionFiles directory reader', () => {
it('uses the injected reader for the root and nested directories', async () => {
tempRoot = await mkdtemp(join(tmpdir(), 'orca-session-reader-'))
const nested = join(tempRoot, '2026', '08', '09')
await mkdir(nested, { recursive: true })
const rollout = join(nested, 'rollout-session.jsonl')
await writeFile(rollout, '{}\n')
const readDirectory = vi.fn((dirPath: string) => readdir(dirPath, { withFileTypes: true }))
await expect(
walkSessionFiles(tempRoot, 'codex', [], {
extensions: new Set(['.jsonl']),
readDirectory
})
).resolves.toEqual([rollout])
expect(readDirectory).toHaveBeenCalledTimes(4)
})
it('does not turn cancellation into an unreadable-directory miss', async () => {
const controller = new AbortController()
const cancelled = new Error('scan cancelled')