Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion config/scripts/vitest-real-agent-home-write-guard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { writeFile } from 'node:fs/promises'
import { homedir, tmpdir, userInfo } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { takeRealAgentHomeWriteViolations } from './vitest-real-agent-home-write-guard'
import {
clearInheritedAgentStateEnv,
takeRealAgentHomeWriteViolations
} from './vitest-real-agent-home-write-guard'

// Why never-created paths: each sits under a missing folder or is a forced no-op removal, so even
// with the guard off (the ablation) nothing lands in the real home.
Expand All @@ -17,6 +20,29 @@ afterEach(() => {
})

describe('vitest real-agent-home write guard', () => {
it.each([undefined, '', '0', 'true', '1'])(
'keeps only the explicitly opted-in Claude profile for %s',
(value) => {
vi.stubEnv('ORCA_REAL_CLAUDE_CLI_TEST', value)
vi.stubEnv('CLAUDE_CONFIG_DIR', '/tmp/explicit-claude-profile')
vi.stubEnv('CODEX_HOME', '/tmp/inherited-codex-profile')
vi.stubEnv('ORCA_USER_DATA_PATH', '/tmp/inherited-orca-state')
vi.stubEnv('ORCA_CODEX_LAUNCH_PREFLIGHT', '/tmp/inherited-live-cli')

clearInheritedAgentStateEnv()

expect(process.env.CLAUDE_CONFIG_DIR).toBe(
value === '1' ? '/tmp/explicit-claude-profile' : undefined
)
expect(process.env.CODEX_HOME).toBeUndefined()
expect(process.env.ORCA_USER_DATA_PATH).toBeUndefined()
expect(process.env.ORCA_CODEX_LAUNCH_PREFLIGHT).toBeUndefined()
expect(() => rmSync(missingRealFolder('.claude'), { force: true })).toThrow(
/real-agent-home guard/
)
}
)

it('refuses a named-import sync write under the real ~/.codex', () => {
const target = join(missingRealFolder('.codex'), 'config.toml')
expect(() => writeFileSync(target, '[projects."/tmp/x"]\n')).toThrow(/real-agent-home guard/)
Expand Down
16 changes: 11 additions & 5 deletions config/scripts/vitest-real-agent-home-write-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,18 @@ declare global {
}
const state = (globalThis.orcaRealAgentHomeWriteGuard ??= install())
// Why after install: the guard keeps the inherited paths as roots; tests that need one set their own.
const inheritedEnvToUnset = realAgentSuiteOptedIn()
? []
: [...INHERITED_STATE_ENV, ...INHERITED_LIVE_CLI_ENV]
for (const name of inheritedEnvToUnset) {
delete process.env[name]
export function clearInheritedAgentStateEnv(): void {
const inheritedEnvToUnset = realAgentSuiteOptedIn()
? []
: [...INHERITED_STATE_ENV, ...INHERITED_LIVE_CLI_ENV]
for (const name of inheritedEnvToUnset) {
if (name === 'CLAUDE_CONFIG_DIR' && process.env.ORCA_REAL_CLAUDE_CLI_TEST === '1') {
continue
}
delete process.env[name]
}
}
clearInheritedAgentStateEnv()

/** Drains recorded violations; only the guard's own self-test should need this. */
export function takeRealAgentHomeWriteViolations(): string[] {
Expand Down
28 changes: 27 additions & 1 deletion src/main/claude/claude-real-cli-test-gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,25 @@ describe('resolveRealClaudeCliGate', () => {
expect(runClaude.mock.calls).toEqual([[['--version']], [['auth', 'status', '--json']]])
})

it('reads the final account report after the CLI configuration warning', () => {
const warning = [
'Claude configuration file not found at: /home/dev/.claude/.claude.json',
'A backup file exists at: /home/dev/.claude/backups/.claude.json.backup.123',
'You can manually restore it by running: cp /home/dev/.claude/backups/.claude.json.backup.123 /home/dev/.claude/.claude.json',
''
].join('\n')
const runClaude = vi.fn((args: readonly string[]): ClaudeCliProbeResult =>
args[0] === '--version'
? { status: 0, stdout: '2.1.0\n' }
: { status: 0, stdout: warning + warning + JSON.stringify({ loggedIn: true }) }
)

expect(resolveRealClaudeCliGate({ [REAL_CLAUDE_CLI_TEST_ENV]: '1' }, runClaude)).toEqual({
skipReason: null,
authStatus: { loggedIn: true }
})
})

it('still skips when opted in but no claude binary answers', () => {
const runClaude = vi.fn((): ClaudeCliProbeResult => ({ status: null, stdout: '' }))

Expand All @@ -57,7 +76,14 @@ describe('resolveRealClaudeCliGate', () => {

it.each([
['a failed auth probe', { status: 1, stdout: '' }],
['unparseable auth output', { status: 0, stdout: 'not json' }]
['unparseable auth output', { status: 0, stdout: 'not json' }],
['malformed JSON', { status: 0, stdout: '{"loggedIn":' }],
['trailing output', { status: 0, stdout: '{"loggedIn":true}\nnot json' }],
['two JSON objects', { status: 0, stdout: '{"loggedIn":false}\n{"loggedIn":true}' }],
['another JSON value before an object', { status: 0, stdout: 'true\n{"loggedIn":true}' }],
['an array before an object', { status: 0, stdout: '[]\n{"loggedIn":true}' }],
['a JSON array', { status: 0, stdout: '[{"loggedIn":true}]' }],
['an unrelated JSON value', { status: 0, stdout: 'true' }]
])('runs with no account report after %s', (_label, authResult) => {
const runClaude = vi.fn((args: readonly string[]): ClaudeCliProbeResult =>
args[0] === '--version' ? { status: 0, stdout: '2.1.0\n' } : authResult
Expand Down
17 changes: 15 additions & 2 deletions src/main/claude/claude-real-cli-test-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,26 @@ export type RealClaudeCliGate = {
}

function parseAuthStatus(stdout: string): RealClaudeAuthStatus | null {
const start = stdout.search(/[[{]/)
if (start === -1) {
return null
}
// CLI warnings may precede the report, but another JSON value makes it ambiguous.
for (const line of stdout.slice(0, start).split('\n')) {
try {
JSON.parse(line)
return null
} catch {
continue
}
}
let parsed: unknown
try {
parsed = JSON.parse(stdout)
parsed = JSON.parse(stdout.slice(start))
} catch {
return null
}
if (!parsed || typeof parsed !== 'object') {
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return null
}
const status: RealClaudeAuthStatus = {}
Expand Down
3 changes: 2 additions & 1 deletion src/main/claude/claude-structured-journal-prompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ export class ClaudeJournalPrompts {
const append = (identity: AgentJournalItemIdentity, body: ClaudeJournalPrompt['body']) => {
const options = { ...producer, turnScope }
if (this.deps.sink.tryAppendItem) {
admitted &&= this.deps.sink.tryAppendItem(identity, body, options).accepted
const admission = this.deps.sink.tryAppendItem(identity, body, options)
admitted &&= admission.accepted
} else {
this.deps.sink.appendItem(identity, body, options)
}
Expand Down
198 changes: 119 additions & 79 deletions src/main/claude/claude-structured-prompt-ownership.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,89 +255,129 @@ describe('Claude live prompt ownership', () => {
).toBe(false)
})

it('rejects a grouped prompt batch without partially revising its first row', () => {
const tombstones: string[] = []
const appendTombstone = vi.fn(
(identity: Parameters<StructuredAgentSessionEventSink['appendTombstone']>[0]) => {
tombstones.push(agentJournalItemKey(identity))
}
)
let rowAdmission = 0
const tryAppendTombstone = vi.fn(
(identity: Parameters<StructuredAgentSessionEventSink['appendTombstone']>[0]) => {
rowAdmission += 1
if (rowAdmission === 2) {
it.each([0, 1, null] as const)(
'rejects a grouped prompt batch without partial revision after row %s admission refusal',
async (refusedAt) => {
const tombstones: string[] = []
const appendTombstone = vi.fn(
(identity: Parameters<StructuredAgentSessionEventSink['appendTombstone']>[0]) => {
tombstones.push(agentJournalItemKey(identity))
}
)
let rowAdmission = 0
const tryAppendTombstone = vi.fn(
(identity: Parameters<StructuredAgentSessionEventSink['appendTombstone']>[0]) => {
rowAdmission += 1
if (rowAdmission === 2) {
return { accepted: false as const, reason: 'backpressure' as const }
}
appendTombstone(identity)
return { accepted: true as const }
}
)
const tryAppendLifecycleBatch = vi.fn(
(
_settlementId: string,
mutations: Parameters<
NonNullable<StructuredAgentSessionEventSink['tryAppendLifecycleBatch']>
>[1]
) => {
expect(mutations[1]).toMatchObject({
kind: 'item',
body: { resolution: { state: 'cancelled' } }
})
return { accepted: false as const, reason: 'backpressure' as const }
}
appendTombstone(identity)
return { accepted: true as const }
}
)
const tryAppendLifecycleBatch = vi.fn(
(
_settlementId: string,
mutations: Parameters<
NonNullable<StructuredAgentSessionEventSink['tryAppendLifecycleBatch']>
>[1]
) => {
expect(mutations[1]).toMatchObject({
kind: 'item',
body: { resolution: { state: 'cancelled' } }
})
return { accepted: false as const, reason: 'backpressure' as const }
)
const admittedRows = new Map<string, AgentJournalItemBody>()
let admissionAttempts = 0
const tryAppendItem = vi.fn(
(
identity: Parameters<StructuredAgentSessionEventSink['appendItem']>[0],
body: AgentJournalItemBody
) => {
if (admissionAttempts++ === refusedAt) {
return { accepted: false as const, reason: 'backpressure' as const }
}
admittedRows.set(agentJournalItemKey(identity), body)
return { accepted: true as const }
}
)
const bindPromptItemId = vi.fn()
const written = vi.fn(async () => ({ ok: true as const }))
const prompts = new ClaudeJournalPrompts({
sink: {
appendItem: () => {},
tryAppendItem,
appendTombstone,
tryAppendTombstone,
tryAppendLifecycleBatch,
publish: () => {},
written
},
bindPromptItemId,
producerOf: () => ({ agentId: 'agent-grouped', producerKind: 'agent' }),
questionItems: (input) => {
const item = claudeQuestionItems(input)[0]
return item
? [
{
...item,
identity: { provider: 'orca', clientMessageId: 'group:first' }
},
{
...item,
identity: { provider: 'orca', clientMessageId: 'group:second' }
}
]
: []
},
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
})
const prompt: ClaudePendingPrompt = {
requestId: 'grouped-request',
promptKey: 'grouped-request',
toolUseId: 'tool-grouped',
toolName: 'AskUserQuestion',
kind: 'question',
input: {
questions: [
{ question: 'First?', options: [{ label: 'Yes' }] },
{ question: 'Second?', options: [{ label: 'No' }] }
]
},
suggestions: [],
questionIds: ['First?', 'Second?'],
settle: vi.fn()
}
)
const prompts = new ClaudeJournalPrompts({
sink: {
appendItem: () => {},
appendTombstone,
tryAppendTombstone,
tryAppendLifecycleBatch,
publish: () => {}
},
questionItems: (input) => {
const item = claudeQuestionItems(input)[0]
return item
? [
{
...item,
identity: { provider: 'orca', clientMessageId: 'group:first' }
},
{
...item,
identity: { provider: 'orca', clientMessageId: 'group:second' }
}
]
: []
},
turnScope: () => AGENT_JOURNAL_THREAD_SCOPE
})
const prompt: ClaudePendingPrompt = {
requestId: 'grouped-request',
promptKey: 'grouped-request',
toolUseId: 'tool-grouped',
toolName: 'AskUserQuestion',
kind: 'question',
input: {
questions: [
{ question: 'First?', options: [{ label: 'Yes' }] },
{ question: 'Second?', options: [{ label: 'No' }] }
]
},
suggestions: [],
questionIds: ['First?', 'Second?'],
settle: vi.fn()
}
prompts.handle({ type: 'prompt', sessionId: 'session-1', prompt })
prompts.handle({ type: 'prompt', sessionId: 'session-1', prompt })
await prompts.whenWritten(prompt.promptKey)

expect(prompts.cancel(prompt.promptKey)).toEqual({
accepted: false,
reason: 'backpressure'
})
expect(tryAppendLifecycleBatch).toHaveBeenCalledOnce()
expect(tryAppendTombstone).not.toHaveBeenCalled()
expect(tombstones).toEqual([])
})
expect(tryAppendItem.mock.calls.map(([identity]) => agentJournalItemKey(identity))).toEqual([
'orca:group%3Afirst',
'orca:group%3Asecond'
])
expect([...admittedRows.keys()]).toEqual(
['orca:group%3Afirst', 'orca:group%3Asecond'].filter((_, index) => index !== refusedAt)
)
expect(bindPromptItemId.mock.calls).toEqual([
['orca:group%3Afirst', prompt.promptKey],
['orca:group%3Asecond', prompt.promptKey]
])
expect(written).toHaveBeenCalledTimes(refusedAt === null ? 1 : 0)
expect([...prompts.openCards()]).toEqual(
refusedAt === null ? [{ promptKey: prompt.promptKey, asker: 'agent-grouped' }] : []
)

expect(prompts.cancel(prompt.promptKey)).toEqual({
accepted: false,
reason: 'backpressure'
})
expect(tryAppendLifecycleBatch).toHaveBeenCalledOnce()
expect(tryAppendTombstone).not.toHaveBeenCalled()
expect(tombstones).toEqual([])
}
)

it('keeps every backpressured prompt cancellation retry in its owned entry', () => {
let backpressured = true
Expand Down
4 changes: 3 additions & 1 deletion src/main/claude/claude-structured-real-cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import {
realClaudeAuthStatus,
realClaudeAvailable,
realClaudeCliGate,
realClaudeCommand
realClaudeCommand,
realClaudeLaunchHome
} from './claude-real-cli-availability-test-support'
import {
ClaudeStructuredSessionAdapter,
Expand All @@ -34,6 +35,7 @@ function realAdapter(
pathToClaudeCodeExecutable: command,
options: { ...CLAUDE_STRUCTURED_BASE_OPTIONS, sessionId: providerSessionId },
cwd,
env: realClaudeLaunchHome().env,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
claudeConfigDir,
providerSessionId,
resumeLeafUuid: null,
Expand Down
Loading