mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 19:07:41 +00:00
Chats follow an account switch for worker results too (#37126)
* Read the Claude account route off the main thread for chat reads and sends Chat option reads, model-list reads and every send resolved the selected Claude account through the router's synchronous state-file read. Route them through an async twin that shares the same login cache. A relaunch for a removed account no longer prepares (and recreates) its folder. * Chats follow an account switch for worker results too A coordinator chat that had started any worker kept answering every message on the account it used before a switch, until every worker it started finished and every result was read. Every new turn, including a worker's result, now launches on the selected account. A reply already running finishes where it started, and a chat whose own background work is still running keeps its process until that work ends. This removes the per-account result tracking that held the old account (the parent-work query, the response index and its queued and usage-limit carve-outs, the input account recipe on the startup attempt, and the read-only journal restore that only fed it), plus the journal index and change-feed fields only it read. A relaunch can no longer prepare, and so recreate, a removed account's folder. The record still saves the account each launch actually ran on, for Session History. * Chats reading the Claude account at the same time share one read of its state file * Test worker results after an account switch through the real account choice, next to a user's message * Pass the mailbox pointer's sender snapshot in the account-switch worker test * Import worker custody helpers once in the process listing, and build the expected homes without a shared object
This commit is contained in:
@@ -33,15 +33,30 @@ const oauthAccount = z.object({
|
||||
organizationName: text
|
||||
})
|
||||
|
||||
export function claudeStateFile(configDir: string | undefined, userHome = homedir()): string {
|
||||
export function claudeStateFile(
|
||||
configDir: string | undefined,
|
||||
userHome = homedir(),
|
||||
exists: (path: string) => boolean = existsSync
|
||||
): string {
|
||||
return resolveClaudeGlobalConfigFile({
|
||||
env: { CLAUDE_CONFIG_DIR: configDir },
|
||||
homeDir: userHome,
|
||||
style: process.platform === 'win32' ? 'win32' : 'posix',
|
||||
exists: existsSync
|
||||
exists
|
||||
})
|
||||
}
|
||||
|
||||
/** Same file as claudeStateFile, without blocking main on the legacy-file check. */
|
||||
export async function claudeStateFileAsync(
|
||||
configDir: string | undefined,
|
||||
userHome = homedir()
|
||||
): Promise<string> {
|
||||
const legacy = claudeStateFile(configDir, userHome, () => true)
|
||||
return (await stat(legacy).catch(() => null))
|
||||
? legacy
|
||||
: claudeStateFile(configDir, userHome, () => false)
|
||||
}
|
||||
|
||||
// Cache large, frequently rewritten state files across account-list refreshes.
|
||||
const logins = new Map<
|
||||
string,
|
||||
@@ -96,6 +111,12 @@ export function readClaudeFolderLogin(stateFile: string, maxAgeMs = 0): ClaudeFo
|
||||
return login
|
||||
}
|
||||
|
||||
// Concurrent chat reads of one state-file revision share a single read and parse.
|
||||
const pendingLogins = new Map<
|
||||
string,
|
||||
{ mtimeMs: number; size: number; login: Promise<ClaudeFolderLogin | null> }
|
||||
>()
|
||||
|
||||
/** Avoid blocking main on state files across WSL shares. */
|
||||
export async function readClaudeFolderLoginAsync(
|
||||
stateFile: string
|
||||
@@ -103,28 +124,38 @@ export async function readClaudeFolderLoginAsync(
|
||||
const current = await stat(stateFile).catch(() => null)
|
||||
if (!current) {
|
||||
logins.delete(stateFile)
|
||||
pendingLogins.delete(stateFile)
|
||||
return null
|
||||
}
|
||||
const recent = logins.get(stateFile)
|
||||
if (recent?.mtimeMs === current.mtimeMs && recent.size === current.size) {
|
||||
return recent.login
|
||||
}
|
||||
let login: ClaudeFolderLogin | null = null
|
||||
const pending = pendingLogins.get(stateFile)
|
||||
if (pending?.mtimeMs === current.mtimeMs && pending.size === current.size) {
|
||||
return pending.login
|
||||
}
|
||||
const read = { mtimeMs: current.mtimeMs, size: current.size, login: readStateLogin(stateFile) }
|
||||
pendingLogins.set(stateFile, read)
|
||||
const login = await read.login
|
||||
// A read superseded by a newer revision (or a deleted file) must not repopulate the cache.
|
||||
if (pendingLogins.get(stateFile) === read) {
|
||||
pendingLogins.delete(stateFile)
|
||||
logins.set(stateFile, { mtimeMs: read.mtimeMs, size: read.size, readAt: Date.now(), login })
|
||||
}
|
||||
return login
|
||||
}
|
||||
|
||||
async function readStateLogin(stateFile: string): Promise<ClaudeFolderLogin | null> {
|
||||
try {
|
||||
const state: unknown = JSON.parse(await readFile(stateFile, 'utf8'))
|
||||
if (state && typeof state === 'object' && !Array.isArray(state)) {
|
||||
login = claudeStateLogin(Object.fromEntries(Object.entries(state)))
|
||||
return claudeStateLogin(Object.fromEntries(Object.entries(state)))
|
||||
}
|
||||
} catch {
|
||||
// Treat unreadable state as signed out.
|
||||
}
|
||||
logins.set(stateFile, {
|
||||
mtimeMs: current.mtimeMs,
|
||||
size: current.size,
|
||||
readAt: Date.now(),
|
||||
login
|
||||
})
|
||||
return login
|
||||
return null
|
||||
}
|
||||
|
||||
/** Removes current profiles only; legacy `claude-accounts/` folders stay untouched. */
|
||||
|
||||
@@ -74,7 +74,7 @@ async function launchHomes(f: ReturnType<typeof coveredAccount>) {
|
||||
.CLAUDE_CONFIG_DIR,
|
||||
chat: await resolveClaudeStructuredLaunchHome(f.router, chatEnv, '/recorded'),
|
||||
chatEnv: chatEnv.CLAUDE_CONFIG_DIR,
|
||||
chatRecord: resolveStructuredClaudeAccountHomePath({
|
||||
chatRecord: await resolveStructuredClaudeAccountHomePath({
|
||||
launchEnv: {},
|
||||
wslDistro: null,
|
||||
getClaudeConfigDirectory: () => f.router.systemDefaultHome()
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { lstat } from 'node:fs/promises'
|
||||
import type { ClaudeProfileRouter } from './claude-profile-router'
|
||||
import {
|
||||
claudeStateFileAsync,
|
||||
isSameClaudeLogin,
|
||||
readClaudeFolderLoginAsync
|
||||
} from './claude-account-folder'
|
||||
import { claudeProfileMissing } from './claude-profile-launch-errors'
|
||||
|
||||
/** `routedHome` without blocking main: chat reads run once per options read and send. */
|
||||
export async function claudeRoutedHomeAsync(
|
||||
router: Pick<
|
||||
ClaudeProfileRouter,
|
||||
'selectedProfile' | 'savedAccount' | 'userConfigDir' | 'userHome'
|
||||
>,
|
||||
availability: 'checked' | 'identity' = 'checked'
|
||||
): Promise<string | null> {
|
||||
const profile = router.selectedProfile()
|
||||
if (!profile) {
|
||||
return null
|
||||
}
|
||||
const login = (configDir: string | undefined) =>
|
||||
claudeStateFileAsync(configDir, router.userHome).then(readClaudeFolderLoginAsync)
|
||||
if (!(await login(profile.home))) {
|
||||
// Reuse a matching System default login until the account signs in separately.
|
||||
const saved = router.savedAccount(profile.accountId)
|
||||
const systemDefault = await login(router.userConfigDir())
|
||||
if (saved && systemDefault && isSameClaudeLogin(saved, systemDefault)) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
if (availability === 'checked' && !(await lstat(profile.home).catch(() => null))?.isDirectory()) {
|
||||
throw claudeProfileMissing()
|
||||
}
|
||||
return profile.home
|
||||
}
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
installClaudeProfileRouter
|
||||
} from './claude-profile-installed-router'
|
||||
import { ClaudeObservedConfigDirs } from './claude-observed-config-dirs'
|
||||
import { claudeRoutedHomeAsync } from './claude-profile-routed-home'
|
||||
|
||||
vi.mock('@orca/process-host', () => ({ runProcess: vi.fn() }))
|
||||
const command = vi.hoisted(() => ({ path: '/unused-claude' }))
|
||||
@@ -218,6 +219,7 @@ describe('ClaudeProfileRouter', () => {
|
||||
expect(f.router.terminalEnv()).toEqual({ ORCA_CLAUDE_PROFILE_POINTER: f.router.pointerPath })
|
||||
expect(f.router.routedHome()).toBeNull()
|
||||
expect(f.router.routedHome('identity')).toBeNull()
|
||||
await expect(claudeRoutedHomeAsync(f.router)).resolves.toBeNull()
|
||||
expect(readFileSync(f.router.pointerPath, 'utf8')).toBe('')
|
||||
expect(f.router.coveredBySystemDefault('a')).toBe(true)
|
||||
|
||||
@@ -231,6 +233,7 @@ describe('ClaudeProfileRouter', () => {
|
||||
expect(f.router.coveredBySystemDefault('a')).toBe(false)
|
||||
expect(f.router.routedHome()).toBe(f.home('a'))
|
||||
expect(f.router.routedHome('identity')).toBe(f.home('a'))
|
||||
await expect(claudeRoutedHomeAsync(f.router)).resolves.toBe(f.home('a'))
|
||||
})
|
||||
|
||||
it('tells whether a terminal opened before routing runs another account than the selected one', () => {
|
||||
@@ -425,6 +428,8 @@ describe('ClaudeProfileRouter', () => {
|
||||
expect(() => f.router.preparation()).toThrow(CLAUDE_PROFILE_MISSING_MESSAGE)
|
||||
expect(() => f.router.routedHome()).toThrow(CLAUDE_PROFILE_MISSING_MESSAGE)
|
||||
expect(f.router.routedHome('identity')).toBe(f.home('b'))
|
||||
await expect(claudeRoutedHomeAsync(f.router)).rejects.toThrow(CLAUDE_PROFILE_MISSING_MESSAGE)
|
||||
await expect(claudeRoutedHomeAsync(f.router, 'identity')).resolves.toBe(f.home('b'))
|
||||
expect(f.router.terminalEnv()).toEqual({ ORCA_CLAUDE_PROFILE_POINTER: f.router.pointerPath })
|
||||
f.router.publish()
|
||||
expect(readFileSync(f.router.pointerPath, 'utf8')).toBe(f.home('b'))
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from '../../shared/claude-profile-routing'
|
||||
import { claudeProfileMissing } from './claude-profile-launch-errors'
|
||||
import type { GlobalSettings } from '../../shared/global-settings-types'
|
||||
import type { ClaudeManagedAccount } from '../../shared/managed-account-types'
|
||||
import { probeRecentClaudeCliVersion } from '../claude/claude-hook-event-versions'
|
||||
import { writeFileAtomically } from '../codex-accounts/fs-utils'
|
||||
import { resolveClaudeCommand } from '../codex-cli/command'
|
||||
@@ -88,11 +89,11 @@ export class ClaudeProfileRouter {
|
||||
})
|
||||
}
|
||||
|
||||
private get userHome(): string {
|
||||
get userHome(): string {
|
||||
return this.args.userHome ?? homedir()
|
||||
}
|
||||
|
||||
private selectedProfile(): ClaudeProfileDescriptor | null {
|
||||
selectedProfile(): ClaudeProfileDescriptor | null {
|
||||
const id = getSelectedClaudeAccountIdForTarget(this.args.getSettings(), { runtime: 'host' })
|
||||
return id ? this.describe(id) : null
|
||||
}
|
||||
@@ -115,11 +116,15 @@ export class ClaudeProfileRouter {
|
||||
if (this.accountLogin(accountId)) {
|
||||
return false
|
||||
}
|
||||
const saved = findClaudeAccount(this.args.getSettings(), accountId)
|
||||
const saved = this.savedAccount(accountId)
|
||||
const systemDefault = this.systemDefaultLogin()
|
||||
return Boolean(saved && systemDefault && isSameClaudeLogin(saved, systemDefault))
|
||||
}
|
||||
|
||||
savedAccount(accountId: string): ClaudeManagedAccount | undefined {
|
||||
return findClaudeAccount(this.args.getSettings(), accountId)
|
||||
}
|
||||
|
||||
systemDefaultHome(): string {
|
||||
return resolveClaudeDefaultHome(this.userHome, this.userConfigDir())
|
||||
}
|
||||
@@ -187,17 +192,6 @@ export class ClaudeProfileRouter {
|
||||
return this.preparation()
|
||||
}
|
||||
|
||||
/** Prepare an observed receiving route without mutating selection or adopting a System-default alias. */
|
||||
async prepareReceivingAccount(accountId: string): Promise<string> {
|
||||
const profile = this.describe(accountId)
|
||||
await prepareClaudeProfileForLaunch(
|
||||
profile,
|
||||
(value) => this.setUp(value),
|
||||
this.args.refreshWaitMs
|
||||
)
|
||||
return profile.home
|
||||
}
|
||||
|
||||
accountHome(accountId: string): string {
|
||||
return this.describe(accountId).home
|
||||
}
|
||||
|
||||
+4
-23
@@ -1,40 +1,21 @@
|
||||
import { CLAUDE_INJECTED_CONFIG_DIR_ENV } from '../../shared/claude-profile-routing'
|
||||
import type { ClaudeAccountRecipe } from '../../shared/agent-session-acquired-account'
|
||||
import type { ClaudeProfileRouter } from '../claude-accounts/claude-profile-router'
|
||||
import { claudeProfileMissing } from '../claude-accounts/claude-profile-launch-errors'
|
||||
import { applyClaudeEnvPatch } from '../claude-accounts/environment'
|
||||
import { resolveStructuredClaudeAccountHomePath } from '../runtime/structured-agent-account-home'
|
||||
|
||||
/** Only actual preparation produces a receipt; selection is never backfilled as acquisition. */
|
||||
export async function prepareClaudeReceivingAccount(
|
||||
/** The account a launch runs under is the current selection; the receipt records what it used. */
|
||||
export async function prepareClaudeLaunchAccount(
|
||||
router: ClaudeProfileRouter | undefined,
|
||||
env: Record<string, string>,
|
||||
recordHome: string,
|
||||
receiving?: ClaudeAccountRecipe
|
||||
recordHome: string
|
||||
): Promise<ClaudeAccountRecipe> {
|
||||
if (receiving?.route === 'managed') {
|
||||
if (!router) {
|
||||
throw claudeProfileMissing()
|
||||
}
|
||||
const home = await router.prepareReceivingAccount(receiving.accountId)
|
||||
applyClaudeEnvPatch(env, { CLAUDE_CONFIG_DIR: home, [CLAUDE_INJECTED_CONFIG_DIR_ENV]: home })
|
||||
return { ...receiving, home }
|
||||
}
|
||||
if (receiving) {
|
||||
if (receiving.configDir === null) {
|
||||
delete env.CLAUDE_CONFIG_DIR
|
||||
} else {
|
||||
env.CLAUDE_CONFIG_DIR = receiving.configDir
|
||||
}
|
||||
return receiving
|
||||
}
|
||||
if (!router) {
|
||||
return { route: 'system', home: recordHome, configDir: env.CLAUDE_CONFIG_DIR ?? null }
|
||||
}
|
||||
const preparation = await router.prepareLaunch()
|
||||
const home =
|
||||
preparation.provenance === 'system'
|
||||
? resolveStructuredClaudeAccountHomePath({
|
||||
? await resolveStructuredClaudeAccountHomePath({
|
||||
launchEnv: env,
|
||||
wslDistro: null,
|
||||
getClaudeConfigDirectory: () => router.systemDefaultHome()
|
||||
@@ -97,7 +97,6 @@ export async function resolveClaudeAcquisitionLaunch(args: {
|
||||
.resolveLaunch({
|
||||
identity: launchIdentity,
|
||||
spawnToken: input.spawnToken,
|
||||
...(input.accountRecipe ? { accountRecipe: input.accountRecipe } : {}),
|
||||
...(input.permissionMode ? { permissionMode: input.permissionMode } : {})
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
|
||||
@@ -60,8 +60,8 @@ it('launches each acquisition under the current selection, not the account it wa
|
||||
})
|
||||
const home = join(root, 'claude-profiles', 'a', 'home')
|
||||
// Dispatch identity names the selected account before its folder exists; availability reads refuse.
|
||||
expect(read('identity')).toBe(home)
|
||||
expect(() => read()).toThrow(CLAUDE_PROFILE_MISSING_MESSAGE)
|
||||
await expect(read('identity')).resolves.toBe(home)
|
||||
await expect(read()).rejects.toThrow(CLAUDE_PROFILE_MISSING_MESSAGE)
|
||||
expect(runSetup).not.toHaveBeenCalled()
|
||||
const record = {
|
||||
...agentSessionRecordFixture(),
|
||||
@@ -95,23 +95,17 @@ it('launches each acquisition under the current selection, not the account it wa
|
||||
writeFileSync(join(root, 'claude-profiles', 'a', 'profile.json'), '{}')
|
||||
const routed = await resolve({ identity })
|
||||
expect(routed.claudeConfigDir).toBe(home)
|
||||
expect(read()).toBe(home)
|
||||
expect(read('identity')).toBe(home)
|
||||
await expect(read()).resolves.toBe(home)
|
||||
await expect(read('identity')).resolves.toBe(home)
|
||||
expect(routed.env).toMatchObject({
|
||||
CLAUDE_CONFIG_DIR: home,
|
||||
ORCA_CLAUDE_INJECTED_CONFIG_DIR: home
|
||||
})
|
||||
|
||||
const receipt = routed.accountRecipe
|
||||
expect(receipt).toEqual({ route: 'managed', accountId: 'a', home })
|
||||
expect(routed.accountRecipe).toEqual({ route: 'managed', accountId: 'a', home })
|
||||
settings.activeClaudeManagedAccountId = null
|
||||
expect((await resolve({ identity })).claudeConfigDir).toBe(resolvePath('/user/own'))
|
||||
const prepareAccount = vi.spyOn(router, 'prepareReceivingAccount')
|
||||
expect((await resolve({ identity, accountRecipe: receipt })).claudeConfigDir).toBe(home)
|
||||
expect(prepareAccount).toHaveBeenCalledWith('a')
|
||||
expect(settings.activeClaudeManagedAccountId).toBeNull()
|
||||
prepareAccount.mockRestore()
|
||||
expect(read()).toBe(resolvePath('/user/own'))
|
||||
await expect(read()).resolves.toBe(resolvePath('/user/own'))
|
||||
})
|
||||
|
||||
function routedResumeFixture(rewind?: AgentSessionRewindRecord, transcriptFiles = false) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { join } from 'node:path'
|
||||
import type { ClaudeProfileRouter } from '../../../claude-accounts/claude-profile-router'
|
||||
import { AgentSessionPreSpawnError } from '../../../native-chat/agent-session-wire/structured-agent-session-adapter-errors'
|
||||
import { resolveSessionFilePath } from '../../../native-chat/session-file-resolver'
|
||||
import { prepareClaudeReceivingAccount } from '../../claude-receiving-account'
|
||||
import { prepareClaudeLaunchAccount } from '../../claude-launch-account'
|
||||
|
||||
/** Follow the current account selection and pin its environment for this launch. */
|
||||
export async function resolveClaudeStructuredLaunchHome(
|
||||
@@ -10,7 +10,7 @@ export async function resolveClaudeStructuredLaunchHome(
|
||||
env: Record<string, string>,
|
||||
recordHome: string
|
||||
): Promise<string> {
|
||||
return (await prepareClaudeReceivingAccount(router, env, recordHome)).home
|
||||
return (await prepareClaudeLaunchAccount(router, env, recordHome)).home
|
||||
}
|
||||
|
||||
async function claudeTranscriptExists(input: {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ClaudeAccountRecipe } from '../../../../shared/agent-session-acquired-account'
|
||||
import { prepareClaudeReceivingAccount } from '../../claude-receiving-account'
|
||||
import { prepareClaudeLaunchAccount } from '../../claude-launch-account'
|
||||
import { assertStructuredAgentResolutionCurrent } from '../../../native-chat/structured-agent-command-resolution'
|
||||
import { activeProviderContext } from '../../../../shared/agent-session/agent-session-provider-context'
|
||||
import { getClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router'
|
||||
@@ -233,8 +233,7 @@ export function claudeStructuredLaunchPart(
|
||||
hasTranscript: deps.hasTranscript
|
||||
}))
|
||||
// Fixed homes can be checked before the final account-routing recheck.
|
||||
const resumedWithoutRouter =
|
||||
router || basis.accountRecipe ? undefined : await resumes(accountHome.path)
|
||||
const resumedWithoutRouter = router ? undefined : await resumes(accountHome.path)
|
||||
// Resolve auth after awaited launch preparation; account routing is rechecked below.
|
||||
const { command, prefixArgs, env } = await resolveClaudeStructuredInvocation(
|
||||
envDeps,
|
||||
@@ -250,12 +249,7 @@ export function claudeStructuredLaunchPart(
|
||||
sources,
|
||||
{ runtimeOnPath: false }
|
||||
)
|
||||
const accountRecipe = await prepareClaudeReceivingAccount(
|
||||
router,
|
||||
env,
|
||||
accountHome.path,
|
||||
basis.accountRecipe
|
||||
)
|
||||
const accountRecipe = await prepareClaudeLaunchAccount(router, env, accountHome.path)
|
||||
const launchHome = accountRecipe.home
|
||||
const resumesTranscript = resumedWithoutRouter ?? (await resumes(launchHome))
|
||||
if (fork?.throughEntryId && !resumesTranscript) {
|
||||
|
||||
@@ -471,7 +471,7 @@ describe('one account, one catalog key', () => {
|
||||
const launchAccountHome = async (record: AgentSessionRecord) =>
|
||||
HOME(
|
||||
'CLAUDE_CONFIG_DIR',
|
||||
resolveStructuredClaudeAccountHomePath({
|
||||
await resolveStructuredClaudeAccountHomePath({
|
||||
launchEnv: {},
|
||||
wslDistro: record.location.wslDistro,
|
||||
getClaudeConfigDirectory: () => router.systemDefaultHome()
|
||||
|
||||
@@ -41,18 +41,12 @@ CREATE TABLE IF NOT EXISTS journal_set_aside (
|
||||
}
|
||||
|
||||
// JSON rows preserve unreadable records byte-for-byte.
|
||||
export const AGENT_SESSION_CLEAR_SUCCESSOR_INDEX_SQL = `
|
||||
CREATE INDEX IF NOT EXISTS idx_agent_session_clear_successor
|
||||
ON agent_session_records(CASE WHEN json_valid(record_json) THEN json_extract(record_json, '$.conversationCommand.replacementSessionId') END);
|
||||
`
|
||||
|
||||
export function createAgentSessionRecordTablesSql(): string {
|
||||
return `
|
||||
CREATE TABLE IF NOT EXISTS agent_session_records (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
record_json TEXT NOT NULL
|
||||
);
|
||||
${AGENT_SESSION_CLEAR_SUCCESSOR_INDEX_SQL}
|
||||
CREATE TABLE IF NOT EXISTS agent_session_operations (
|
||||
operation_key TEXT PRIMARY KEY,
|
||||
row_json TEXT NOT NULL
|
||||
|
||||
@@ -5,7 +5,6 @@ import Database from '../../sqlite/sync-database'
|
||||
import { hardenSqliteDatabaseFiles } from '../../sqlite/harden-database-files'
|
||||
import {
|
||||
createAgentSessionRecordTablesSql,
|
||||
AGENT_SESSION_CLEAR_SUCCESSOR_INDEX_SQL,
|
||||
createJournalTablesSql,
|
||||
JOURNAL_DB_OLDEST_RELEASED_VERSION,
|
||||
JOURNAL_DB_SCHEMA_VERSION
|
||||
@@ -75,7 +74,8 @@ export function openJournalDatabase(dbPath: string): OpenJournalDatabase {
|
||||
ensureQueuedMessagesTable(probe)
|
||||
ensureCommandReceiptsTable(probe)
|
||||
ensureJournalOutcomeTables(probe)
|
||||
probe.exec(AGENT_SESSION_CLEAR_SUCCESSOR_INDEX_SQL)
|
||||
// An earlier build indexed clear successors for a query that no longer exists; writes stop paying for it.
|
||||
probe.exec('DROP INDEX IF EXISTS idx_agent_session_clear_successor')
|
||||
ensureAgentSessionAttachmentClaimTables(probe)
|
||||
hardenSqliteDatabaseFiles(dbPath)
|
||||
transferred = true
|
||||
|
||||
@@ -2,15 +2,13 @@ import type Database from '../../sqlite/sync-database'
|
||||
import type { JournalRow } from './journal-row-schema'
|
||||
import type { JournalOutcomeSource } from './journal-outcome-format'
|
||||
|
||||
type JournalOutcomeKeys = { itemIds: string[]; submissionIds: string[]; queueCardIds: string[] }
|
||||
|
||||
/** In-process change index only; the public wire still contains items and submissions. Each array
|
||||
* names the sequence's touched keys; `deleted` repeats the ones it removed. */
|
||||
export type JournalOutcomeReadRow = JournalOutcomeKeys & {
|
||||
/** In-process change index only; the public wire still contains items and submissions. */
|
||||
export type JournalOutcomeReadRow = {
|
||||
kind: 'outcome'
|
||||
epoch: string
|
||||
seq: number
|
||||
deleted: JournalOutcomeKeys
|
||||
itemIds: string[]
|
||||
submissionIds: string[]
|
||||
}
|
||||
export type JournalReadRow = JournalRow | JournalOutcomeReadRow
|
||||
/** `through` is the highest sequence the read covered, which may store no record of its own. */
|
||||
@@ -28,15 +26,14 @@ export function readJournalOutcomeGroups(
|
||||
.prepare(`SELECT DISTINCT seq FROM journal_outcomes
|
||||
WHERE generation = ? AND seq > ? AND seq <= ? ORDER BY seq LIMIT ?`)
|
||||
.all(source.generation, after, source.through, limit ?? -1)
|
||||
const touched = db.prepare(`SELECT field, entry_key, deleted FROM journal_outcomes
|
||||
WHERE generation = ? AND seq = ? AND field IN ('items', 'submissions', 'queue.cards')
|
||||
ORDER BY field, entry_key`)
|
||||
const touched = db.prepare(`SELECT field, entry_key FROM journal_outcomes
|
||||
WHERE generation = ? AND seq = ? AND field IN ('items', 'submissions') ORDER BY field, entry_key`)
|
||||
return groups.map(({ seq }) => {
|
||||
if (typeof seq !== 'number') {
|
||||
throw new Error('invalid journal outcome group')
|
||||
}
|
||||
const keys = emptyOutcomeKeys()
|
||||
const deleted = emptyOutcomeKeys()
|
||||
const itemIds: string[] = []
|
||||
const submissionIds: string[] = []
|
||||
for (const entry of touched.iterate(source.generation, seq)) {
|
||||
if (typeof entry.entry_key !== 'string') {
|
||||
throw new Error('invalid journal outcome key')
|
||||
@@ -45,21 +42,12 @@ export function readJournalOutcomeGroups(
|
||||
if (typeof key !== 'string') {
|
||||
throw new Error('invalid journal public outcome key')
|
||||
}
|
||||
const field =
|
||||
entry.field === 'items'
|
||||
? 'itemIds'
|
||||
: entry.field === 'submissions'
|
||||
? 'submissionIds'
|
||||
: 'queueCardIds'
|
||||
keys[field].push(key)
|
||||
if (entry.deleted === 1) {
|
||||
deleted[field].push(key)
|
||||
if (entry.field === 'items') {
|
||||
itemIds.push(key)
|
||||
} else {
|
||||
submissionIds.push(key)
|
||||
}
|
||||
}
|
||||
return { kind: 'outcome', epoch, seq, ...keys, deleted }
|
||||
return { kind: 'outcome', epoch, seq, itemIds, submissionIds }
|
||||
})
|
||||
}
|
||||
|
||||
function emptyOutcomeKeys(): JournalOutcomeKeys {
|
||||
return { itemIds: [], submissionIds: [], queueCardIds: [] }
|
||||
}
|
||||
|
||||
@@ -2,10 +2,7 @@ import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
agentJournalItemKey,
|
||||
agentJournalSubmissionKey
|
||||
} from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { AgentJournalItemIdentity } from '../../../shared/agent-session-journal-identity'
|
||||
import {
|
||||
type AgentJournalMessageItem,
|
||||
@@ -119,49 +116,6 @@ describe('projectJournalBatch', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('names touched card keys and deleted keys per outcome sequence; a Stop mark touches no item', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-history-outcome-keys-'))
|
||||
const journal = await outcomeJournals.open({
|
||||
identity: IDENTITY,
|
||||
stateDirectory: root,
|
||||
now: tick
|
||||
})
|
||||
try {
|
||||
const queued: AgentJournalMessageItem = {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'queued' }]
|
||||
}
|
||||
await journal.queuedMessages.insert({ messageId: 'card-1', body: queued })
|
||||
await journal.appendItem(item(1), body('item-1'), {
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
const cursor = journal.cursor()
|
||||
await journal.queuedMessages.withdraw(['card-1'])
|
||||
await journal.appendTombstone(item(1), { fence: 1 })
|
||||
await journal.appendStopEvent({ reason: 'user-stop' }, 1)
|
||||
const since = journal.readSince(cursor)
|
||||
if (!since.ok) {
|
||||
throw new Error(`expected rows, got reset ${since.reset}`)
|
||||
}
|
||||
const none = { itemIds: [], submissionIds: [], queueCardIds: [] }
|
||||
expect(since.rows).toEqual([
|
||||
expect.objectContaining({ kind: 'outcome', queueCardIds: ['card-1'], deleted: none }),
|
||||
expect.objectContaining({
|
||||
kind: 'outcome',
|
||||
itemIds: [agentJournalItemKey(item(1))],
|
||||
deleted: { ...none, itemIds: [agentJournalItemKey(item(1))] }
|
||||
}),
|
||||
expect.objectContaining({ kind: 'outcome', itemIds: [], queueCardIds: [], deleted: none })
|
||||
])
|
||||
} finally {
|
||||
await journal.close()
|
||||
await closeTestJournalHostDatabase(root)
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('publishes touched items at their current reduced state, not as a delta', async () => {
|
||||
await appendItems(1)
|
||||
const cursor = fixture.journal.cursor()
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type {
|
||||
AgentJournalRenderItem,
|
||||
AgentJournalSubmission
|
||||
} from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { latestNativeChatUsageLimitCut } from '../../../shared/native-chat/native-chat-usage-limit-cut'
|
||||
import { isAgentSessionContextClear } from '../../../shared/agent-session/agent-session-context-clear'
|
||||
import { isRootAgentJournalItem } from '../../../shared/agent-session/journal/agent-session-journal-producer'
|
||||
import { isStructuredAgentSessionCommandTurn } from '../../../shared/agent-session/structured-agent-session-command-entry'
|
||||
import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record'
|
||||
import type { AgentSessionJournal } from '../agent-session-journal/journal-store'
|
||||
|
||||
/** Index only the current request window; the canonical cut reader still decides recovery. */
|
||||
export class StructuredAccountRecovery {
|
||||
private readonly groups = new Map<string, Map<string, AgentJournalRenderItem>>()
|
||||
private readonly pending = new Map<string, AgentJournalSubmission>()
|
||||
private requests: AgentJournalRenderItem[] = []
|
||||
private latest: AgentJournalRenderItem | null = null
|
||||
private building = true
|
||||
private floor = 0
|
||||
|
||||
reset(): void {
|
||||
this.groups.clear()
|
||||
this.pending.clear()
|
||||
this.requests = []
|
||||
this.latest = null
|
||||
this.building = true
|
||||
this.floor = 0
|
||||
}
|
||||
|
||||
ready(): void {
|
||||
this.building = false
|
||||
for (const key of this.groups.keys()) {
|
||||
if (key !== this.latest?.itemId) {
|
||||
this.groups.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
submission(submission: AgentJournalSubmission | undefined): void {
|
||||
if (!submission) {
|
||||
return
|
||||
}
|
||||
if (submission.dispatchState === 'pending') {
|
||||
this.pending.set(submission.clientMessageId, submission)
|
||||
} else {
|
||||
this.pending.delete(submission.clientMessageId)
|
||||
}
|
||||
}
|
||||
|
||||
item(journal: AgentSessionJournal, item: AgentJournalRenderItem): void {
|
||||
if (!isRootAgentJournalItem(item)) {
|
||||
return
|
||||
}
|
||||
if (isAgentSessionContextClear(item.body)) {
|
||||
if (item.sequence > this.floor) {
|
||||
this.floor = item.sequence
|
||||
this.groups.clear()
|
||||
this.requests = []
|
||||
this.latest = null
|
||||
}
|
||||
return
|
||||
}
|
||||
if (item.sequence <= this.floor) {
|
||||
return
|
||||
}
|
||||
const turn = readAgentJournalTurn(item.body)
|
||||
if (turn && !isStructuredAgentSessionCommandTurn(turn, journal.itemBody)) {
|
||||
if (item.sequence >= (this.latest?.sequence ?? 0)) {
|
||||
if (!this.building && this.latest?.itemId !== item.itemId) {
|
||||
this.groups.clear()
|
||||
}
|
||||
this.latest = item
|
||||
}
|
||||
}
|
||||
const scope = turn
|
||||
? item.itemId
|
||||
: item.turnScope?.kind === 'turn'
|
||||
? item.turnScope.turnItemId
|
||||
: null
|
||||
if (scope && (this.building || scope === this.latest?.itemId)) {
|
||||
const group = this.groups.get(scope) ?? new Map<string, AgentJournalRenderItem>()
|
||||
group.set(item.itemId, item)
|
||||
this.groups.set(scope, group)
|
||||
}
|
||||
if (item.body.kind === 'message' && item.body.role === 'user') {
|
||||
this.requests = this.requests.filter((entry) => entry.itemId !== item.itemId)
|
||||
}
|
||||
if (
|
||||
item.body.kind === 'message' &&
|
||||
item.body.role === 'user' &&
|
||||
!item.body.command &&
|
||||
item.turnScope?.kind !== 'turn'
|
||||
) {
|
||||
this.requests = [...this.requests.filter((entry) => entry.itemId !== item.itemId), item]
|
||||
.sort((a, b) => b.sequence - a.sequence)
|
||||
.slice(0, 2)
|
||||
}
|
||||
}
|
||||
|
||||
allows(journal: AgentSessionJournal, next: AgentJournalSubmission): boolean {
|
||||
const key = journal.canonicalItemId(agentJournalSubmissionKey(next.clientMessageId))
|
||||
const items = [
|
||||
...(this.groups.get(this.latest?.itemId ?? '')?.values() ?? []),
|
||||
...this.requests.filter((item) => item.itemId !== key)
|
||||
].sort((a, b) => a.sequence - b.sequence)
|
||||
return (
|
||||
latestNativeChatUsageLimitCut(
|
||||
items,
|
||||
[...this.pending.values()].filter(
|
||||
(submission) => submission.clientMessageId !== next.clientMessageId
|
||||
)
|
||||
) !== null
|
||||
)
|
||||
}
|
||||
}
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
import { existsSync, rmSync } from 'node:fs'
|
||||
import { dirname } from 'node:path'
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { acquiredAgentSessionAccount } from '../../../shared/agent-session-acquired-account'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { dispatchReportMailbox } from '../../runtime/orchestration/dispatch-report-mailbox'
|
||||
import { OrchestrationStructuredMailboxPointerDelivery } from '../../runtime/orchestration/structured-mailbox-pointer-delivery'
|
||||
import { createStructuredMailboxPointerHost } from '../../runtime/orchestration/structured-mailbox-pointer-host'
|
||||
import { HOST_TEST_NOW } from './structured-agent-session-host-test-data'
|
||||
import {
|
||||
createReceivingCallerFixture,
|
||||
PARENT,
|
||||
WORKER
|
||||
} from './structured-agent-session-receiving-callers.test-support'
|
||||
|
||||
type Fixture = Awaited<ReturnType<typeof createReceivingCallerFixture>>
|
||||
type Worker = Awaited<ReturnType<Fixture['createWorker']>>
|
||||
|
||||
function journal(f: Fixture) {
|
||||
return f.rig.host.collaboratorsForTests().sessions.get(PARENT)?.journal
|
||||
}
|
||||
|
||||
function settledState(f: Fixture, id: string) {
|
||||
const submission = journal(f)?.submission(id)
|
||||
return submission?.dispatchState === 'pending' ? undefined : submission
|
||||
}
|
||||
|
||||
/** Production report transaction -> pointer wake -> host start/handover, as a coordinator receives a result. */
|
||||
async function reportResult(f: Fixture, worker: Worker) {
|
||||
const db = f.runtime.getOrchestrationDb()
|
||||
const mailbox = dispatchReportMailbox(db, worker.dispatch)
|
||||
await f.report(worker)
|
||||
expect(f.nudges).toHaveBeenCalledWith(mailbox, 'worker_done')
|
||||
const pointer = new OrchestrationStructuredMailboxPointerDelivery({
|
||||
getDb: () => db,
|
||||
getMessageWaiters: () => undefined,
|
||||
resolveStructuredTarget: (handle) => f.runtime.mailTarget(handle),
|
||||
getCliCommand: () => 'orca-dev',
|
||||
senderSnapshot: () => ({ name: null, agent: null }),
|
||||
host: createStructuredMailboxPointerHost()
|
||||
})
|
||||
const unsubscribe = await f.rig.host.subscribe({
|
||||
id: 'result-pointer-wake',
|
||||
sessionId: PARENT,
|
||||
emit: () => pointer.onJournalActivity(PARENT)
|
||||
})
|
||||
expect(pointer.deliverForHandle(mailbox)).toBe(true)
|
||||
const notices = () => {
|
||||
const current = journal(f)
|
||||
return (current?.submissions() ?? []).filter((submission) => {
|
||||
const body = current?.itemBody(agentJournalSubmissionKey(submission.clientMessageId))
|
||||
return body?.kind === 'message' && body.from?.orchestration?.message === 'mail-notice'
|
||||
})
|
||||
}
|
||||
return {
|
||||
unsubscribe,
|
||||
notices,
|
||||
/** The worker's result mail, while the coordinator has not been handed it. */
|
||||
undelivered: () =>
|
||||
db.getUnreadMessages(mailbox, ['worker_done']).filter((row) => row.delivered_at === null),
|
||||
settled: async () => {
|
||||
let settled: ReturnType<typeof notices>[number] | undefined
|
||||
await vi.waitFor(() => {
|
||||
settled = notices().find((notice) => notice.dispatchState !== 'pending')
|
||||
expect(settled).toBeDefined()
|
||||
})
|
||||
return settled
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function coordinatorWithWorker(f: Fixture) {
|
||||
await f.found()
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(f.homeA)
|
||||
f.runtime.getOrchestrationDb().createRun({
|
||||
objective: 'coordinate a worker',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: PARENT
|
||||
})
|
||||
return f.createWorker(WORKER)
|
||||
}
|
||||
|
||||
describe('a coordinator chat whose worker is still running when the account is switched', () => {
|
||||
it('answers the worker result on the new account when it arrives first, and keeps that agent for the next message', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(HOST_TEST_NOW)
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
const worker = await coordinatorWithWorker(f)
|
||||
f.selectB()
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
|
||||
// Nothing has replaced the agent on A when the result arrives.
|
||||
const result = await reportResult(f, worker)
|
||||
try {
|
||||
expect((await result.settled())?.dispatchState).toBe('accepted')
|
||||
} finally {
|
||||
result.unsubscribe()
|
||||
}
|
||||
expect(f.rig.adapter.closeSession).toHaveBeenCalledWith(PARENT, undefined)
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(f.homeB)
|
||||
expect(f.launches.at(-1)).toBe(f.homeB.path)
|
||||
expect(f.rig.adapter.acquire).toHaveBeenCalledTimes(1)
|
||||
expect(result.undelivered()).toEqual([])
|
||||
|
||||
await f.send('keep going')
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(f.homeB)
|
||||
expect(f.rig.adapter.acquire).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('answers a result that arrives after its process ended on the new account, not the one it last ran on', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(HOST_TEST_NOW)
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
const worker = await coordinatorWithWorker(f)
|
||||
// A cold start reads only saved state, as it does after a restart.
|
||||
await f.rig.host.close(PARENT, 'evict')
|
||||
expect(
|
||||
acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe
|
||||
).toMatchObject({ route: 'managed', accountId: 'a', home: f.homeA.path })
|
||||
f.selectB()
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
|
||||
const result = await reportResult(f, worker)
|
||||
try {
|
||||
expect((await result.settled())?.dispatchState).toBe('accepted')
|
||||
} finally {
|
||||
result.unsubscribe()
|
||||
}
|
||||
expect(f.launches.at(-1)).toBe(f.homeB.path)
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(f.homeB)
|
||||
expect(f.rig.adapter.acquire).toHaveBeenCalledTimes(1)
|
||||
expect(
|
||||
acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe
|
||||
).toMatchObject({ route: 'managed', accountId: 'b', home: f.homeB.path })
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('a worker result launches a resting coordinator exactly as a message from the user does', () => {
|
||||
const cases: {
|
||||
name: string
|
||||
arrange: (f: Fixture) => void
|
||||
/** The folder the Claude process starts under; none when launch refuses first. */
|
||||
home: (f: Fixture) => string | undefined
|
||||
outcome: { dispatchState: 'accepted' } | { dispatchState: 'rejected'; rejection: string }
|
||||
/** Brings back a refused result: a later message from the user that runs. */
|
||||
recover?: (f: Fixture) => void
|
||||
}[] = [
|
||||
{
|
||||
name: 'the account it ran on was removed',
|
||||
arrange: (f) => {
|
||||
f.selectB()
|
||||
f.removeAccount('a')
|
||||
rmSync(dirname(f.homeA.path), { recursive: true, force: true })
|
||||
},
|
||||
home: (f) => f.homeB.path,
|
||||
outcome: { dispatchState: 'accepted' }
|
||||
},
|
||||
{
|
||||
name: 'the selected account is signed out',
|
||||
arrange: (f) => {
|
||||
f.selectB()
|
||||
f.signedOut.add(f.homeB.path)
|
||||
},
|
||||
home: (f) => f.homeB.path,
|
||||
outcome: { dispatchState: 'rejected', rejection: 'notSignedIn' }
|
||||
},
|
||||
{
|
||||
name: 'its history is only under the account it ran on',
|
||||
arrange: (f) => {
|
||||
f.selectB()
|
||||
f.transcripts.add(f.homeA.path)
|
||||
},
|
||||
// Under A it would resume; the refusal is what launching under B finds.
|
||||
home: () => undefined,
|
||||
outcome: { dispatchState: 'rejected', rejection: 'historyInOtherAccount' },
|
||||
recover: (f) => f.select('a')
|
||||
},
|
||||
{
|
||||
name: 'System default is selected',
|
||||
arrange: (f) => f.select(null),
|
||||
home: (f) => f.systemHome.path,
|
||||
outcome: { dispatchState: 'accepted' }
|
||||
}
|
||||
]
|
||||
|
||||
it.each(cases)('$name', async ({ arrange, home, outcome, recover }) => {
|
||||
let clock = HOST_TEST_NOW
|
||||
vi.spyOn(Date, 'now').mockImplementation(() => clock)
|
||||
const outcomes: unknown[] = []
|
||||
for (const path of ['user message', 'worker result'] as const) {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
const worker = await coordinatorWithWorker(f)
|
||||
await f.rig.host.close(PARENT, 'evict')
|
||||
arrange(f)
|
||||
f.launches.length = 0
|
||||
|
||||
if (path === 'user message') {
|
||||
const id = await f.accept('continue')
|
||||
await vi.waitFor(() => expect(settledState(f, id)).toBeDefined())
|
||||
expect(f.launches.at(-1)).toBe(home(f))
|
||||
expect(existsSync(f.homeA.path)).toBe(f.accounts().includes('a'))
|
||||
outcomes.push(settledState(f, id))
|
||||
continue
|
||||
}
|
||||
const result = await reportResult(f, worker)
|
||||
try {
|
||||
outcomes.push(await result.settled())
|
||||
expect(f.launches.at(-1)).toBe(home(f))
|
||||
expect(existsSync(f.homeA.path)).toBe(f.accounts().includes('a'))
|
||||
if (outcome.dispatchState === 'accepted') {
|
||||
expect(result.undelivered()).toEqual([])
|
||||
continue
|
||||
}
|
||||
// A refused result is never marked handed over; it stays owed to the coordinator.
|
||||
expect(result.undelivered()).toHaveLength(1)
|
||||
if (recover) {
|
||||
recover(f)
|
||||
expect(result.undelivered()).toHaveLength(1)
|
||||
// The user's message comes after the refused result.
|
||||
f.rig.clock.now += 1_000
|
||||
clock += 1_000
|
||||
await f.turn(await f.send('back on a'), 'completed')
|
||||
await vi.waitFor(() =>
|
||||
expect(result.notices().filter((n) => n.dispatchState === 'accepted')).toHaveLength(1)
|
||||
)
|
||||
await vi.waitFor(() => expect(result.undelivered()).toEqual([]))
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(f.homeA)
|
||||
}
|
||||
} finally {
|
||||
result.unsubscribe()
|
||||
}
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
const expected = {
|
||||
dispatchState: outcome.dispatchState,
|
||||
...(outcome.dispatchState === 'rejected'
|
||||
? { rejection: expect.objectContaining({ kind: outcome.rejection }) }
|
||||
: {})
|
||||
}
|
||||
expect(outcomes).toEqual([expect.objectContaining(expected), expect.objectContaining(expected)])
|
||||
})
|
||||
})
|
||||
@@ -45,7 +45,6 @@ export async function acquireOwner(
|
||||
throw new AgentSessionPreSpawnError(error)
|
||||
}
|
||||
const permissionMode = await input.launchPermissionMode?.(record)
|
||||
const accountRecipe = await input.launchAccountRecipe?.(record)
|
||||
try {
|
||||
await input.assertNoTerminalWriter?.(record)
|
||||
} catch (error) {
|
||||
@@ -65,7 +64,6 @@ export async function acquireOwner(
|
||||
// Retry the existing reservation instead of spawning a second child.
|
||||
spawnToken,
|
||||
...(permissionMode ? { permissionMode } : {}),
|
||||
...(accountRecipe ? { accountRecipe } : {}),
|
||||
...(input.eventSink ? { events: input.eventSink } : {}),
|
||||
...(input.acquireSignal ? { signal: input.acquireSignal } : {}),
|
||||
...(input.startupOptions ? { startupOptions: input.startupOptions } : {}),
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { AttachFlowInput } from './structured-agent-session-attach-flow'
|
||||
import type { StructuredAgentSessionAttachContext } from './structured-agent-session-attach-context'
|
||||
import type { StructuredAgentSessionAttachLock } from './structured-agent-session-attach-lock'
|
||||
import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account'
|
||||
|
||||
export function structuredAgentSessionAttachAccount(
|
||||
context: StructuredAgentSessionAttachContext,
|
||||
startedFor: string | undefined,
|
||||
lock: StructuredAgentSessionAttachLock
|
||||
): NonNullable<AttachFlowInput['launchAccountRecipe']> {
|
||||
return async (record) => {
|
||||
const { account } = await lock.commit(async () => {
|
||||
const current = context.deps.store.requireWritableRecord(record.sessionId)
|
||||
const session = context.sessions.get(record.sessionId)
|
||||
const next = startedFor ? session?.journal.submission(startedFor) : undefined
|
||||
return {
|
||||
account: structuredAgentSessionReceivingAccount(
|
||||
context.deps,
|
||||
current,
|
||||
session,
|
||||
next,
|
||||
'identity'
|
||||
)
|
||||
}
|
||||
})
|
||||
return (await lock.wait(account)).recipe
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { ClaudeAccountRecipe } from '../../../shared/agent-session-acquired-account'
|
||||
import { refuse } from '../../../shared/agent-session/failures/agent-session-wire-refusals'
|
||||
import {
|
||||
settlePostAcquisitionAttachFailure,
|
||||
@@ -81,7 +80,6 @@ export type AttachFlowInput = {
|
||||
attempt: StructuredAgentSessionStartupAttempt
|
||||
) => StructuredAgentSessionStartupProgress
|
||||
startupOptions?: Readonly<Record<string, string>>
|
||||
launchAccountRecipe?: (record: AgentSessionRecord) => Promise<ClaudeAccountRecipe | undefined>
|
||||
launchPermissionMode?: (
|
||||
record: AgentSessionRecord
|
||||
) => Promise<AgentChatPermissionChoice | undefined>
|
||||
|
||||
-2
@@ -1,5 +1,4 @@
|
||||
import { prepareStructuredAgentSessionAttach } from './structured-agent-session-attach-preparation'
|
||||
import { structuredAgentSessionAttachAccount } from './structured-agent-session-attach-account'
|
||||
import {
|
||||
publishAttachedChild,
|
||||
readBoundChildRewind,
|
||||
@@ -207,7 +206,6 @@ async function runAttachUnderAbort(
|
||||
},
|
||||
...(options.startupOptions ? { startupOptions: options.startupOptions } : {}),
|
||||
launchPermissionMode: structuredAgentSessionAttachPermission(context, options, lock),
|
||||
launchAccountRecipe: structuredAgentSessionAttachAccount(context, options.startedFor, lock),
|
||||
assertNoTerminalWriter: async (record) => {
|
||||
await lock.wait(Promise.resolve(context.deps.assertNoTerminalWriter?.(record)))
|
||||
},
|
||||
|
||||
@@ -6,7 +6,6 @@ import type {
|
||||
StructuredAgentSessionHostDeps,
|
||||
StructuredAgentSessionHostSession
|
||||
} from './structured-agent-session-host-types'
|
||||
import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account'
|
||||
|
||||
/** The caller already owns the conversation; every projection of this invocation shares this scope. */
|
||||
export function structuredAgentSessionCatalogScopeOwned(
|
||||
@@ -20,8 +19,7 @@ export function structuredAgentSessionCatalogScopeOwned(
|
||||
getRecord: (id) => deps.store.getRecord(id) ?? undefined,
|
||||
drivesRecord: () => true,
|
||||
liveAccountHome: () => session?.child?.accountHome,
|
||||
launchAccountHome: async (record) =>
|
||||
(await structuredAgentSessionReceivingAccount(deps, record, session)).home
|
||||
launchAccountHome: async (record) => (await deps.launchAccountHome?.(record)) ?? null
|
||||
},
|
||||
params
|
||||
)
|
||||
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
import { mkdirSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { agentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home'
|
||||
import type { AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-identity'
|
||||
import {
|
||||
ClaudeProfileRouter,
|
||||
type ClaudeProfileRouterSettings
|
||||
} from '../../claude-accounts/claude-profile-router'
|
||||
import { installClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router'
|
||||
import { claudeProfileMarkerPath } from '../../claude-accounts/claude-profile-paths'
|
||||
import { CLAUDE_STRUCTURED_AGENT } from '../../claude/structured/claude-structured-agent-definition'
|
||||
import { claudeInitializationAuthError } from '../../claude/structured/claude-structured-init-proof'
|
||||
import type { AgentSessionRecordStore } from '../../runtime/agent-session/records/agent-session-record-store'
|
||||
import { resolveStructuredClaudeAccountHomePath } from '../../runtime/structured-agent-account-home'
|
||||
import { createClaudeStructuredLaunchResolver } from '../../runtime/structured-agent-launch-composition.test-support'
|
||||
import type { StructuredAgentSessionHostDeps } from './structured-agent-session-host-types'
|
||||
|
||||
const savedAccount = (id: string) => ({
|
||||
id,
|
||||
email: `${id}@example.test`,
|
||||
authMethod: 'subscription-oauth' as const,
|
||||
managedAuthPath: '/unused',
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
lastAuthenticatedAt: 0
|
||||
})
|
||||
|
||||
const home = (path: string) => agentSessionAccountHome(CLAUDE_STRUCTURED_AGENT, path)
|
||||
|
||||
/** The real Claude account router, desired-home read and launch resolution, with accounts a and b
|
||||
* saved and a selected; only what the Claude CLI finds in a folder is scripted. */
|
||||
export function createClaudeAccountRouting() {
|
||||
let router: ClaudeProfileRouter | undefined
|
||||
const settings: ClaudeProfileRouterSettings = {
|
||||
claudeManagedAccounts: [savedAccount('a'), savedAccount('b')],
|
||||
activeClaudeManagedAccountId: 'a',
|
||||
activeClaudeManagedAccountIdsByRuntime: undefined,
|
||||
agentStatusHooksEnabled: false,
|
||||
disabledTuiAgents: []
|
||||
}
|
||||
// The production resolver hop: only dispatch identity skips the availability check.
|
||||
const launchAccountHome: NonNullable<
|
||||
StructuredAgentSessionHostDeps['launchAccountHome']
|
||||
> = async (_record, purpose) =>
|
||||
home(
|
||||
await resolveStructuredClaudeAccountHomePath({
|
||||
launchEnv: {},
|
||||
wslDistro: null,
|
||||
...(purpose === 'identity' ? { purpose } : {}),
|
||||
getClaudeConfigDirectory: () => router?.systemDefaultHome() ?? ''
|
||||
})
|
||||
)
|
||||
|
||||
const install = (
|
||||
root: string,
|
||||
store: () => Pick<AgentSessionRecordStore, 'getRecord' | 'pinLaunchDirectory'>
|
||||
) => {
|
||||
const installed = new ClaudeProfileRouter({
|
||||
getSettings: () => settings,
|
||||
dataRoot: root,
|
||||
userHome: join(root, 'personal'),
|
||||
env: {},
|
||||
runSetup: async ({ profile }) => {
|
||||
mkdirSync(profile.home, { recursive: true })
|
||||
writeFileSync(claudeProfileMarkerPath(profile), '{}')
|
||||
return { outcome: 'prepared', warnings: [], surfaces: {} }
|
||||
}
|
||||
})
|
||||
router = installed
|
||||
installClaudeProfileRouter(installed)
|
||||
const homeA = home(installed.accountHome('a'))
|
||||
const homeB = home(installed.accountHome('b'))
|
||||
const systemHome = home(installed.systemDefaultHome())
|
||||
for (const { path } of [homeA, homeB, systemHome]) {
|
||||
mkdirSync(path, { recursive: true })
|
||||
}
|
||||
// What the scripted Claude CLI finds in each folder it is launched under.
|
||||
const signedOut = new Set<string>()
|
||||
const transcripts = new Set<string>()
|
||||
const launches: string[] = []
|
||||
const resolveLaunch = createClaudeStructuredLaunchResolver({
|
||||
store: {
|
||||
getRecord: (id) => store().getRecord(id),
|
||||
pinLaunchDirectory: (id, directory) => store().pinLaunchDirectory(id, directory)
|
||||
},
|
||||
resolveLaunchArgs: () => [],
|
||||
resolveCommand: () => ({ command: '/usr/local/bin/claude', prefixArgs: [] }),
|
||||
resolveInheritedEnv: async () => ({ PATH: '/usr/bin' }),
|
||||
resolveAuthPolicy: () => ({ account: 'system' }),
|
||||
hasTranscript: async ({ claudeConfigDir }) => transcripts.has(claudeConfigDir)
|
||||
})
|
||||
return {
|
||||
homeA,
|
||||
homeB,
|
||||
systemHome,
|
||||
signedOut,
|
||||
transcripts,
|
||||
/** The folder each started Claude process ran under, in order. */
|
||||
launches,
|
||||
/** Resolve the launch as the Claude adapter's acquisition does, then start the scripted CLI. */
|
||||
launch: async (input: { identity: AgentSessionJournalIdentity; spawnToken: string }) => {
|
||||
const launch = await resolveLaunch(input)
|
||||
launches.push(launch.claudeConfigDir)
|
||||
if (signedOut.has(launch.claudeConfigDir)) {
|
||||
// The init frame a signed-out Claude CLI reports.
|
||||
throw claudeInitializationAuthError({ account: { tokenSource: 'none' } }, launch.account)
|
||||
}
|
||||
return {
|
||||
accountHome: home(launch.claudeConfigDir),
|
||||
...(launch.accountRecipe ? { accountRecipe: launch.accountRecipe } : {})
|
||||
}
|
||||
},
|
||||
/** Switch the selected Claude account; null is System default. */
|
||||
select: (account: 'a' | 'b' | null) => {
|
||||
settings.activeClaudeManagedAccountId = account
|
||||
},
|
||||
accounts: () => settings.claudeManagedAccounts.map((account) => account.id),
|
||||
removeAccount: (account: 'a' | 'b') => {
|
||||
settings.claudeManagedAccounts = settings.claudeManagedAccounts.filter(
|
||||
(saved) => saved.id !== account
|
||||
)
|
||||
},
|
||||
uninstall: () => installClaudeProfileRouter(undefined)
|
||||
}
|
||||
}
|
||||
return { launchAccountHome, install }
|
||||
}
|
||||
+10
-31
@@ -6,13 +6,10 @@ import { revealStructuredAgentSession } from './structured-agent-session-reveal'
|
||||
import type { StructuredAgentSessionClientDelivery } from './structured-agent-session-client-delivery'
|
||||
import type { AgentSessionExecutionLocation } from '../../../shared/agent-session/lifecycle/agent-session-record'
|
||||
import * as providerSupport from './structured-agent-session-provider-support'
|
||||
import type { OpenedStructuredAgentSessionConversation } from './structured-agent-session-conversation-open'
|
||||
import type {
|
||||
StructuredAgentSessionHostDeps,
|
||||
StructuredAgentSessionHostSession
|
||||
} from './structured-agent-session-host-types'
|
||||
import { restoreStructuredAgentSessionRead } from './structured-agent-session-read-restore'
|
||||
import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account'
|
||||
|
||||
type ReadContext = {
|
||||
deps: StructuredAgentSessionHostDeps
|
||||
@@ -20,32 +17,10 @@ type ReadContext = {
|
||||
serialize: <T>(id: string, task: () => Promise<T>) => Promise<T>
|
||||
readCommands: StructuredAgentSessionClientDelivery['readCommandsSettled']
|
||||
conversation: (id: string) => Promise<StructuredAgentSessionHostSession>
|
||||
adoptOpened: (id: string, opened: OpenedStructuredAgentSessionConversation) => Promise<void>
|
||||
}
|
||||
|
||||
/** Readers share the conversation owner; inventory never founds a journal or prepares a provider. */
|
||||
export function createStructuredAgentSessionConversationReads(context: () => ReadContext) {
|
||||
const sessionOwned = async (id: string, current: () => boolean = () => true) => {
|
||||
const { deps, sessions, adoptOpened } = context()
|
||||
const record = deps.store.requireWritableRecord(id)
|
||||
let session = sessions.get(id)
|
||||
if (!session) {
|
||||
const opened = await restoreStructuredAgentSessionRead(deps, id)
|
||||
if (opened) {
|
||||
if (current()) {
|
||||
await adoptOpened(id, opened)
|
||||
session = opened.session
|
||||
} else {
|
||||
await opened.session.journal.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
return { record, session }
|
||||
}
|
||||
const prospectiveAccountHomeOwned = async (id: string) => {
|
||||
const { record, session } = await sessionOwned(id)
|
||||
return (await structuredAgentSessionReceivingAccount(context().deps, record, session)).home
|
||||
}
|
||||
const readModelCatalog = createStructuredAgentSessionCatalogReads(() => ({
|
||||
deps: context().deps,
|
||||
serialize: context().serialize,
|
||||
@@ -66,11 +41,11 @@ export function createStructuredAgentSessionConversationReads(context: () => Rea
|
||||
if (!context().deps.store.getRecord(record.sessionId)) {
|
||||
return structuredAgentSessionCatalogScopeOwned(context().deps, params, undefined)
|
||||
}
|
||||
const { session } = await sessionOwned(record.sessionId, params.operation?.current)
|
||||
if (params.operation?.current() === false) {
|
||||
return null
|
||||
}
|
||||
return structuredAgentSessionCatalogScopeOwned(context().deps, params, session)
|
||||
return structuredAgentSessionCatalogScopeOwned(
|
||||
context().deps,
|
||||
params,
|
||||
context().sessions.get(record.sessionId)
|
||||
)
|
||||
}
|
||||
}))
|
||||
return {
|
||||
@@ -90,7 +65,11 @@ export function createStructuredAgentSessionConversationReads(context: () => Rea
|
||||
holdsSessions: () => context().deps.store.holdsRecords(),
|
||||
onSessionsHeld: (listener: () => void) => context().deps.store.onFirstRecord(listener),
|
||||
prospectiveAccountHome: (id: string) => {
|
||||
return context().serialize(id, () => prospectiveAccountHomeOwned(id))
|
||||
const { deps, serialize } = context()
|
||||
return serialize(
|
||||
id,
|
||||
async () => (await deps.launchAccountHome?.(deps.store.requireWritableRecord(id))) ?? null
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { selectableStructuredSubmission } from './structured-agent-session-input-selection'
|
||||
import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account'
|
||||
// Open conversations with queued sends always need delivery; opening also wakes leftover recovery.
|
||||
|
||||
import { isQueuedAgentJournalSubmission } from '../../../shared/agent-session/requests/agent-session-queued-submission'
|
||||
@@ -140,17 +139,7 @@ export function createStructuredAgentSessionConversationDelivery(input: {
|
||||
},
|
||||
launchAccountHome: async () => {
|
||||
const record = deps.store.getRecord(sessionId)
|
||||
return record
|
||||
? (
|
||||
await structuredAgentSessionReceivingAccount(
|
||||
deps,
|
||||
record,
|
||||
session,
|
||||
next,
|
||||
'identity'
|
||||
)
|
||||
).home
|
||||
: null
|
||||
return record ? ((await deps.launchAccountHome?.(record, 'identity')) ?? null) : null
|
||||
},
|
||||
logger: deps.logger
|
||||
})
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { AgentSessionRecordReader } from '../../runtime/orchestration/structured-session-lineage'
|
||||
import type { NativeResponseEvidence } from '../../runtime/orchestration/structured-parent-account-work'
|
||||
import type { AgentModelCatalogSource } from '../agent-model-catalog/agent-model-catalog-service-contract'
|
||||
import type { StructuredAgentSessionDeliveryLoop } from './structured-agent-session-delivery-loop'
|
||||
import type {
|
||||
@@ -206,12 +204,6 @@ export type StructuredAgentSessionHostDeps = {
|
||||
record: AgentSessionRecord,
|
||||
purpose?: 'read' | 'identity'
|
||||
) => Promise<AgentSessionAccountHome | null>
|
||||
parentAccountWork?: (
|
||||
record: AgentSessionRecord,
|
||||
root: string,
|
||||
response: NativeResponseEvidence,
|
||||
reader: AgentSessionRecordReader
|
||||
) => boolean
|
||||
conversationNaming?: StructuredAgentSessionConversationNaming
|
||||
/** Carries the user's chat name into the agent's own conversation; never delays the caller. */
|
||||
nameProviderConversation?: (record: AgentSessionRecord) => void
|
||||
|
||||
@@ -148,8 +148,7 @@ export class StructuredAgentSessionHost {
|
||||
serialize: this.serialize,
|
||||
readCommands: (id, commandsOnRequest) =>
|
||||
this.clientDelivery.readCommandsSettled(id, commandsOnRequest),
|
||||
conversation: (id) => this.lifetime.conversation(id),
|
||||
adoptOpened: this.conversationDelivery.adoptOpened
|
||||
conversation: (id) => this.lifetime.conversation(id)
|
||||
}))
|
||||
sessionAgent = this.reads.sessionAgent
|
||||
readModelCatalog = this.reads.readModelCatalog
|
||||
|
||||
@@ -1,317 +0,0 @@
|
||||
import { isQueuedAgentJournalSubmission } from '../../../shared/agent-session/requests/agent-session-queued-submission'
|
||||
import {
|
||||
isJournalStopOrResumeRow,
|
||||
type JournalRow
|
||||
} from '../agent-session-journal/journal-row-schema'
|
||||
import { isAgentSessionContextClear } from '../../../shared/agent-session/agent-session-context-clear'
|
||||
import { StructuredQueuedNativeResponses } from './structured-agent-session-queued-native-responses'
|
||||
import { StructuredAccountRecovery } from './structured-agent-session-account-recovery'
|
||||
import { readWholeAgentSessionFailureFact } from '../../../shared/agent-session/failures/agent-session-failure'
|
||||
import {
|
||||
agentJournalSubmissionKey,
|
||||
parseAgentJournalItemKey
|
||||
} from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { isRootAgentJournalItem } from '../../../shared/agent-session/journal/agent-session-journal-producer'
|
||||
import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record'
|
||||
import type { AgentJournalCursor } from '../../../shared/agent-session-journal-identity'
|
||||
import type {
|
||||
AgentJournalItemBody,
|
||||
AgentJournalRenderItem
|
||||
} from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import type { AgentSessionJournal } from '../agent-session-journal/journal-store'
|
||||
import type {
|
||||
JournalOutcomeReadRow,
|
||||
JournalReadRow
|
||||
} from '../agent-session-journal/journal-read-row'
|
||||
|
||||
type Notice = { fence: number; clientMessageId: string; mailbox: string; messages: string[] }
|
||||
|
||||
/** Replayable projection, not a saved obligation: initial history once, then changed row keys only. */
|
||||
export class StructuredNativeResponses {
|
||||
readonly recovery = new StructuredAccountRecovery()
|
||||
private readonly queued = new StructuredQueuedNativeResponses()
|
||||
private readonly signedOutFences = new Set<number>()
|
||||
private cursor: AgentJournalCursor | null = null
|
||||
private executionFence: number | undefined
|
||||
private readonly submissionKeys = new Map<string, string>()
|
||||
private readonly notices = new Map<string, Notice>()
|
||||
private readonly turns = new Map<string, Set<string>>()
|
||||
private readonly resolved = new Set<string>()
|
||||
private readonly pending = new Set<string>()
|
||||
private readonly noticesByUser = new Map<string, Set<string>>()
|
||||
|
||||
read(
|
||||
journal: AgentSessionJournal,
|
||||
executionFence?: number
|
||||
): {
|
||||
pending: Iterable<string>
|
||||
disposed: ReadonlySet<string>
|
||||
} {
|
||||
const next = journal.cursor()
|
||||
const fenceChanged = this.executionFence !== executionFence
|
||||
if (
|
||||
!fenceChanged &&
|
||||
this.cursor?.epoch === next.epoch &&
|
||||
this.cursor.sequence === next.sequence
|
||||
) {
|
||||
return this.result()
|
||||
}
|
||||
const changes = this.cursor ? journal.readSince(this.cursor) : null
|
||||
if (!changes?.ok) {
|
||||
this.recovery.reset()
|
||||
this.signedOutFences.clear()
|
||||
this.submissionKeys.clear()
|
||||
this.notices.clear()
|
||||
this.turns.clear()
|
||||
this.resolved.clear()
|
||||
this.pending.clear()
|
||||
this.noticesByUser.clear()
|
||||
for (const submission of journal.submissions()) {
|
||||
this.observeSubmission(journal, submission.clientMessageId)
|
||||
}
|
||||
journal.visitItemsWithLinkage((id, _sequence, body, item) =>
|
||||
this.observe(journal, id, body, item)
|
||||
)
|
||||
this.queued.reset(journal)
|
||||
} else {
|
||||
for (const row of changes.rows) {
|
||||
if (row.kind === 'outcome') {
|
||||
this.changedOutcome(journal, row)
|
||||
} else {
|
||||
this.changed(journal, row)
|
||||
}
|
||||
}
|
||||
if (changes.rows.some(rewritesHistory)) {
|
||||
this.recovery.reset()
|
||||
for (const submission of journal.submissions()) {
|
||||
this.recovery.submission(submission)
|
||||
}
|
||||
journal.visitItemsWithLinkage((id) => {
|
||||
const item = journal.item(id)
|
||||
if (item) {
|
||||
this.recovery.item(journal, item)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
if (executionFence !== undefined && (fenceChanged || !changes?.ok)) {
|
||||
this.disposeEndedExecution(journal, executionFence)
|
||||
}
|
||||
this.executionFence = executionFence
|
||||
this.recovery.ready()
|
||||
this.cursor = changes?.ok ? { epoch: next.epoch, sequence: changes.through } : next
|
||||
return this.result()
|
||||
}
|
||||
|
||||
private changed(journal: AgentSessionJournal, row: JournalRow): void {
|
||||
this.queued.changed(journal, row)
|
||||
if (row.kind === 'submission' || row.kind === 'dispatch') {
|
||||
this.observeSubmission(journal, row.clientMessageId)
|
||||
} else if (row.kind === 'item' || row.kind === 'tombstone') {
|
||||
if (row.kind === 'tombstone' && row.retireSubmission) {
|
||||
const identity = parseAgentJournalItemKey(row.itemId)
|
||||
if (identity?.provider === 'orca') {
|
||||
this.disposeNotice(identity.clientMessageId)
|
||||
}
|
||||
}
|
||||
this.observeKey(journal, row.itemId)
|
||||
} else if (row.kind === 'lifecycle-batch') {
|
||||
for (const mutation of row.mutations) {
|
||||
this.observeKey(journal, mutation.itemId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** An outcome sequence names touched keys; each is re-read at its current value, as typed rows were. */
|
||||
private changedOutcome(journal: AgentSessionJournal, row: JournalOutcomeReadRow): void {
|
||||
for (const id of row.queueCardIds) {
|
||||
this.queued.changedCard(journal, id)
|
||||
}
|
||||
for (const clientMessageId of row.submissionIds) {
|
||||
// Only a rewind retiring an Orca send deletes a submission: the typed tombstone's retireSubmission.
|
||||
if (row.deleted.submissionIds.includes(clientMessageId)) {
|
||||
this.disposeNotice(clientMessageId)
|
||||
} else {
|
||||
this.observeSubmission(journal, clientMessageId)
|
||||
}
|
||||
}
|
||||
for (const itemId of row.itemIds) {
|
||||
this.observeKey(journal, itemId)
|
||||
}
|
||||
}
|
||||
|
||||
private observeKey(journal: AgentSessionJournal, key: string): void {
|
||||
const item = journal.item(journal.canonicalItemId(key))
|
||||
if (item) {
|
||||
const clientMessageId = this.submissionKeys.get(journal.canonicalItemId(key))
|
||||
if (clientMessageId) {
|
||||
this.observeSubmission(journal, clientMessageId)
|
||||
}
|
||||
this.observe(journal, key, item.body, item)
|
||||
}
|
||||
}
|
||||
|
||||
private observe(
|
||||
journal: AgentSessionJournal,
|
||||
key: string,
|
||||
body: AgentJournalItemBody,
|
||||
item: Pick<AgentJournalRenderItem, 'agentId'>
|
||||
): void {
|
||||
if (!isRootAgentJournalItem(item)) {
|
||||
return
|
||||
}
|
||||
const rendered = journal.item(journal.canonicalItemId(key))
|
||||
if (rendered) {
|
||||
this.recovery.item(journal, rendered)
|
||||
}
|
||||
if (
|
||||
body.kind === 'status' &&
|
||||
readWholeAgentSessionFailureFact(body.failure)?.kind === 'notSignedIn'
|
||||
) {
|
||||
const fence = journal.itemFence(key)
|
||||
if (fence !== undefined) {
|
||||
this.signedOutFences.add(fence)
|
||||
}
|
||||
}
|
||||
if (isAgentSessionContextClear(body) && body.kind === 'status' && body.contextClear) {
|
||||
for (const notice of this.notices.values()) {
|
||||
if (notice.fence <= body.contextClear.afterFence) {
|
||||
for (const message of notice.messages) {
|
||||
this.resolved.add(message)
|
||||
this.pending.delete(message)
|
||||
}
|
||||
this.notices.delete(notice.clientMessageId)
|
||||
}
|
||||
}
|
||||
}
|
||||
const source = body.kind === 'message' ? body.from?.orchestration : undefined
|
||||
if (source?.message === 'mail-notice') {
|
||||
const clientMessageId = this.submissionKeys.get(journal.canonicalItemId(key))
|
||||
if (clientMessageId) {
|
||||
this.notices.set(clientMessageId, {
|
||||
clientMessageId,
|
||||
fence: identityFence(journal, clientMessageId),
|
||||
mailbox: source.mailbox,
|
||||
messages: source.messages.map((message) => message.messageId)
|
||||
})
|
||||
this.observeSubmission(journal, clientMessageId)
|
||||
}
|
||||
}
|
||||
const turn = readAgentJournalTurn(body)
|
||||
if (turn?.userItemId) {
|
||||
const user = journal.canonicalItemId(turn.userItemId)
|
||||
const keys = this.turns.get(user) ?? new Set<string>()
|
||||
keys.add(key)
|
||||
this.turns.set(user, keys)
|
||||
for (const clientMessageId of this.noticesByUser.get(user) ?? []) {
|
||||
this.observeSubmission(journal, clientMessageId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private observeSubmission(journal: AgentSessionJournal, clientMessageId: string): void {
|
||||
const submission = journal.submission(clientMessageId)
|
||||
this.recovery.submission(submission)
|
||||
const rendered = journal.item(
|
||||
journal.canonicalItemId(agentJournalSubmissionKey(clientMessageId))
|
||||
)
|
||||
if (rendered) {
|
||||
this.recovery.item(journal, rendered)
|
||||
}
|
||||
if (
|
||||
submission?.dispatchState === 'rejected' &&
|
||||
readWholeAgentSessionFailureFact(submission.rejection)?.kind === 'notSignedIn'
|
||||
) {
|
||||
this.signedOutFences.add(submission.fence)
|
||||
}
|
||||
this.submissionKeys.set(
|
||||
journal.canonicalItemId(agentJournalSubmissionKey(clientMessageId)),
|
||||
clientMessageId
|
||||
)
|
||||
const body = journal.itemBody(agentJournalSubmissionKey(clientMessageId))
|
||||
const source = body?.kind === 'message' ? body.from?.orchestration : undefined
|
||||
if (source?.message === 'mail-notice' && !this.notices.has(clientMessageId)) {
|
||||
this.notices.set(clientMessageId, {
|
||||
clientMessageId,
|
||||
fence: identityFence(journal, clientMessageId),
|
||||
mailbox: source.mailbox,
|
||||
messages: source.messages.map((message) => message.messageId)
|
||||
})
|
||||
}
|
||||
const notice = this.notices.get(clientMessageId)
|
||||
if (!notice || !submission) {
|
||||
return
|
||||
}
|
||||
const user = journal.canonicalItemId(agentJournalSubmissionKey(clientMessageId))
|
||||
const clients = this.noticesByUser.get(user) ?? new Set<string>()
|
||||
clients.add(clientMessageId)
|
||||
this.noticesByUser.set(user, clients)
|
||||
for (const message of notice.messages) {
|
||||
if (!this.resolved.has(message)) {
|
||||
this.pending.add(message)
|
||||
}
|
||||
}
|
||||
const terminal = [...(this.turns.get(user) ?? [])].some((key) => {
|
||||
const turn = readAgentJournalTurn(journal.itemBody(key) ?? undefined)
|
||||
// Ending this exact turn disposes its account ownership, without claiming unknown/failed output succeeded.
|
||||
return turn !== null && turn.state !== 'running'
|
||||
})
|
||||
if (
|
||||
terminal ||
|
||||
submission.dispatchState === 'rejected' ||
|
||||
(submission.dispatchState === 'unknown' && submission.recovered === true)
|
||||
) {
|
||||
for (const message of notice.messages) {
|
||||
this.resolved.add(message)
|
||||
this.pending.delete(message)
|
||||
}
|
||||
clients.delete(clientMessageId)
|
||||
this.notices.delete(clientMessageId)
|
||||
}
|
||||
}
|
||||
|
||||
/** Ended generations keep main's handed-over/no-reply disposition; unhanded input still owns a future response. */
|
||||
private disposeEndedExecution(journal: AgentSessionJournal, fence: number): void {
|
||||
for (const notice of this.notices.values()) {
|
||||
const submission = journal.submission(notice.clientMessageId)
|
||||
if (submission && submission.fence !== fence && !isQueuedAgentJournalSubmission(submission)) {
|
||||
this.disposeNotice(notice.clientMessageId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private disposeNotice(clientMessageId: string): void {
|
||||
const notice = this.notices.get(clientMessageId)
|
||||
for (const message of notice?.messages ?? []) {
|
||||
this.resolved.add(message)
|
||||
this.pending.delete(message)
|
||||
}
|
||||
this.notices.delete(clientMessageId)
|
||||
}
|
||||
|
||||
signedOut(fence: number): boolean {
|
||||
return this.signedOutFences.has(fence)
|
||||
}
|
||||
|
||||
private result() {
|
||||
return {
|
||||
pending: this.queued.pendingWith(this.pending, this.resolved),
|
||||
disposed: this.resolved
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function identityFence(journal: AgentSessionJournal, clientMessageId: string): number {
|
||||
return journal.submission(clientMessageId)?.fence ?? 0
|
||||
}
|
||||
|
||||
/** Provider history was rewritten: a tombstone outside Stop/resume marks, or an outcome sequence that deleted an item. */
|
||||
function rewritesHistory(row: JournalReadRow): boolean {
|
||||
if (row.kind === 'outcome') {
|
||||
return row.deleted.itemIds.length > 0
|
||||
}
|
||||
return (
|
||||
(row.kind === 'tombstone' && !isJournalStopOrResumeRow(row)) ||
|
||||
(row.kind === 'lifecycle-batch' && row.mutations.some((item) => item.kind === 'tombstone'))
|
||||
)
|
||||
}
|
||||
+3
-79
@@ -1,7 +1,6 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture'
|
||||
import { acquiredAgentSessionAccount } from '../../../shared/agent-session-acquired-account'
|
||||
import {
|
||||
agentSessionAccountHome,
|
||||
@@ -14,11 +13,9 @@ import {
|
||||
type ClaudeProfileRouterSettings
|
||||
} from '../../claude-accounts/claude-profile-router'
|
||||
import type { ClaudeProfileSetupReport } from '../../claude-accounts/claude-profile-setup'
|
||||
import { prepareClaudeReceivingAccount } from '../../claude/claude-receiving-account'
|
||||
import { prepareClaudeLaunchAccount } from '../../claude/claude-launch-account'
|
||||
import { CLAUDE_STRUCTURED_AGENT } from '../../claude/structured/claude-structured-agent-definition'
|
||||
import { resolveStructuredClaudeAccountHomePath } from '../../runtime/structured-agent-account-home'
|
||||
import { createReceivingAccountFixture } from './structured-agent-session-receiving-account.test-support'
|
||||
import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { agentSessionFailureFact } from '../../../shared/agent-session/failures/agent-session-failure'
|
||||
import { agentSessionFailureWords } from '../../../shared/agent-session/failures/agent-session-failure-words'
|
||||
@@ -34,7 +31,6 @@ import {
|
||||
type RestTestRig
|
||||
} from './structured-agent-session-rest-test-rig'
|
||||
import { hostTestAttachParams } from './structured-agent-session-host-test-data'
|
||||
import { retireOutgrownStructuredAgentSessionChild } from './structured-agent-session-outgrown-child'
|
||||
|
||||
const accountHome = (path: string): LegacyAgentSessionAccountHome => ({
|
||||
variable: 'CODEX_HOME',
|
||||
@@ -131,7 +127,7 @@ describe('a send while the selected account folder is not set up yet', () => {
|
||||
launchAccountHome: async (_record, purpose) =>
|
||||
agentSessionAccountHome(
|
||||
CLAUDE_STRUCTURED_AGENT,
|
||||
resolveStructuredClaudeAccountHomePath({
|
||||
await resolveStructuredClaudeAccountHomePath({
|
||||
launchEnv: {},
|
||||
wslDistro: null,
|
||||
...(purpose === 'identity' ? { purpose } : {}),
|
||||
@@ -145,7 +141,7 @@ describe('a send while the selected account folder is not set up yet', () => {
|
||||
}
|
||||
rig.adapter.acquire.mockImplementation(async (input) => {
|
||||
// The real router prepares the selected account, joining or failing its setup, as a launch does.
|
||||
const recipe = await prepareClaudeReceivingAccount(router, {}, home('a'), input.accountRecipe)
|
||||
const recipe = await prepareClaudeLaunchAccount(router, {}, home('a'))
|
||||
const acquired = await base(input)
|
||||
if (!acquired.link) {
|
||||
throw new Error('the rig acquisition always links a provider handle')
|
||||
@@ -296,75 +292,3 @@ describe('a send after the agent said it is not signed in', () => {
|
||||
expect(rig.adapter.acquire).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('retireOutgrownStructuredAgentSessionChild', () => {
|
||||
const idle: Parameters<typeof retireOutgrownStructuredAgentSessionChild>[2]['work'] = {
|
||||
currentWork: () => ({ activeTurnId: () => null, hasActionablePrompt: () => false }),
|
||||
childWork: () => [],
|
||||
childWorkOpen: () => false,
|
||||
hasOpenDispatch: () => false,
|
||||
providerHoldsDispatch: () => false
|
||||
}
|
||||
it('keeps healthy acquired Claude A for canonical native result mail without provider children', async () => {
|
||||
const fixture = await createReceivingAccountFixture()
|
||||
try {
|
||||
await fixture.turn('completed-lead', 'completed')
|
||||
const next = await fixture.submit({
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'You have 1 orchestration message. Run `orca-dev orchestration check --run run_01227aad9fcf`.'
|
||||
}
|
||||
],
|
||||
from: {
|
||||
kind: 'agent',
|
||||
senders: [
|
||||
{
|
||||
party: {
|
||||
address: 'structworker_e7f53907-0cde-40b9-81c5-d18eb66c07a4',
|
||||
terminalHandle: 'structworker_e7f53907-0cde-40b9-81c5-d18eb66c07a4',
|
||||
orcaSessionId: testOrcaSessionId('d93bb955-2f5f-4206-93e9-cbbc9460d7e3')
|
||||
},
|
||||
name: 'QA30955 wake-home child'
|
||||
}
|
||||
],
|
||||
orchestration: {
|
||||
message: 'mail-notice',
|
||||
mailbox: 'run:run_01227aad9fcf',
|
||||
dispatchId: null,
|
||||
messages: [
|
||||
{
|
||||
messageId: 'msg_1df05968e9bb',
|
||||
runId: 'run_01227aad9fcf',
|
||||
from: 'structworker_e7f53907-0cde-40b9-81c5-d18eb66c07a4'
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
})
|
||||
const child = fixture.session.child
|
||||
const stopAgent = vi.fn(async () => undefined)
|
||||
await retireOutgrownStructuredAgentSessionChild(fixture.root, fixture.session, {
|
||||
next,
|
||||
work: idle,
|
||||
launchAccountHome: async () =>
|
||||
(
|
||||
await structuredAgentSessionReceivingAccount(
|
||||
fixture.deps,
|
||||
fixture.record,
|
||||
fixture.session,
|
||||
next
|
||||
)
|
||||
).home,
|
||||
stopAgent,
|
||||
logger: { warn: vi.fn(), error: vi.fn() }
|
||||
})
|
||||
expect(stopAgent).not.toHaveBeenCalled()
|
||||
expect(fixture.session.child).toBe(child)
|
||||
} finally {
|
||||
await fixture.dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
import type { AgentSessionJournal } from '../agent-session-journal/journal-store'
|
||||
import type { JournalRow } from '../agent-session-journal/journal-row-schema'
|
||||
import type { QueuedMessageRow } from '../agent-session-journal/queued-message-table'
|
||||
|
||||
/** Pointer delivery transfers ownership to a card before any submitted turn exists. */
|
||||
export class StructuredQueuedNativeResponses {
|
||||
private readonly messages = new Map<string, readonly string[]>()
|
||||
|
||||
reset(journal: AgentSessionJournal): void {
|
||||
this.messages.clear()
|
||||
for (const card of journal.queuedMessages.list()) {
|
||||
this.observe(card)
|
||||
}
|
||||
}
|
||||
|
||||
changed(journal: AgentSessionJournal, row: JournalRow): void {
|
||||
const id =
|
||||
row.kind === 'queue'
|
||||
? row.messageId
|
||||
: row.kind === 'submission'
|
||||
? row.queuedMessageId
|
||||
: row.kind === 'dispatch'
|
||||
? journal.submission(row.clientMessageId)?.queuedMessageId
|
||||
: undefined
|
||||
if (id) {
|
||||
this.changedCard(journal, id)
|
||||
}
|
||||
}
|
||||
|
||||
/** The card's current value decides: a present card is re-read, a gone one forgotten. */
|
||||
changedCard(journal: AgentSessionJournal, id: string): void {
|
||||
const card = journal.queuedMessages.get(id)
|
||||
if (card) {
|
||||
this.observe(card)
|
||||
} else {
|
||||
this.messages.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
private observe(card: QueuedMessageRow): void {
|
||||
const source = card.body.from?.orchestration
|
||||
if (
|
||||
(card.state === 'waiting' || card.state === 'returned') &&
|
||||
source?.message === 'mail-notice'
|
||||
) {
|
||||
this.messages.set(
|
||||
card.messageId,
|
||||
source.messages.map((message) => message.messageId)
|
||||
)
|
||||
} else {
|
||||
this.messages.delete(card.messageId)
|
||||
}
|
||||
}
|
||||
|
||||
*pendingWith(pending: ReadonlySet<string>, disposed: ReadonlySet<string>): Iterable<string> {
|
||||
yield* pending
|
||||
for (const messages of this.messages.values()) {
|
||||
for (const message of messages) {
|
||||
if (!disposed.has(message)) {
|
||||
yield message
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
import {
|
||||
agentSessionLeaseFixture,
|
||||
agentSessionRecordFixture
|
||||
} from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture'
|
||||
import { agentSessionConversationView } from '../../../shared/agent-session-conversation-view'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record'
|
||||
import type { StructuredAgentSessionConversationOpenDeps } from './structured-agent-session-conversation-open'
|
||||
import type { AgentSessionJournal } from '../agent-session-journal/journal-store'
|
||||
import {
|
||||
closeTestJournalHostDatabases,
|
||||
openTestJournalHostDatabase
|
||||
} from '../agent-session-journal/journal-host-database-test-support'
|
||||
import { publishJournalSessionEpoch } from '../agent-session-journal/journal-row-table'
|
||||
import { restoreStructuredAgentSessionRead } from './structured-agent-session-read-restore'
|
||||
import { recordingStructuredAgentSessionLogger } from './structured-agent-session-logger-test-support'
|
||||
import { codexProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
|
||||
|
||||
const SESSION_ID = 'codex_read_restore_fixture'
|
||||
const WORKSPACE_ID = 'repo-1::/tmp/workspace'
|
||||
|
||||
const RECORD: AgentSessionRecord = {
|
||||
...agentSessionRecordFixture(
|
||||
agentSessionLeaseFixture({ sessionId: SESSION_ID, runtimeFence: 1 })
|
||||
),
|
||||
sessionId: SESSION_ID,
|
||||
location: {
|
||||
executionHostId: 'local',
|
||||
wslDistro: null,
|
||||
workspaceId: WORKSPACE_ID,
|
||||
workspaceKind: 'git-worktree'
|
||||
},
|
||||
provider: 'codex',
|
||||
accountHome: { variable: 'CODEX_HOME', path: '/tmp/codex-home' },
|
||||
providerHandleChain: [
|
||||
{
|
||||
linkId: 'link-1',
|
||||
handle: codexProviderHandle('thread-1'),
|
||||
origin: 'created',
|
||||
mintedAtFence: 1,
|
||||
observedAt: 1
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const store: StructuredAgentSessionConversationOpenDeps['store'] = {
|
||||
getConversation: (sessionId: string) =>
|
||||
sessionId === SESSION_ID ? agentSessionConversationView(RECORD) : null,
|
||||
replacedRuntime: () => undefined
|
||||
}
|
||||
|
||||
let journalRoot: string
|
||||
const openDeps = () => ({
|
||||
store,
|
||||
journalDatabase: openTestJournalHostDatabase(journalRoot),
|
||||
logger: recordingStructuredAgentSessionLogger().logger
|
||||
})
|
||||
const opened: AgentSessionJournal[] = []
|
||||
|
||||
beforeEach(async () => {
|
||||
journalRoot = await mkdtemp(join(tmpdir(), 'orca-read-restore-'))
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.allSettled(opened.splice(0).map((journal) => journal.close()))
|
||||
closeTestJournalHostDatabases()
|
||||
await rm(journalRoot, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('read restore', () => {
|
||||
it('publishes a session with a journal, starting no agent', async () => {
|
||||
const deps = openDeps()
|
||||
const restored = await restoreStructuredAgentSessionRead(deps, SESSION_ID)
|
||||
expect(restored).toBeNull()
|
||||
publishJournalSessionEpoch(
|
||||
deps.journalDatabase.db,
|
||||
{ sessionId: SESSION_ID, workspaceId: WORKSPACE_ID },
|
||||
'epoch-1'
|
||||
)
|
||||
|
||||
const published = await restoreStructuredAgentSessionRead(deps, SESSION_ID)
|
||||
|
||||
expect(published).not.toBeNull()
|
||||
opened.push(published!.session.journal)
|
||||
expect(published!.session.child).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,21 +0,0 @@
|
||||
import { readJournalSessionEpoch } from '../agent-session-journal/journal-row-table'
|
||||
import {
|
||||
openStructuredAgentSessionConversationJournal,
|
||||
type OpenedStructuredAgentSessionConversation,
|
||||
type StructuredAgentSessionConversationOpenDeps
|
||||
} from './structured-agent-session-conversation-open'
|
||||
|
||||
/** Open only existing journals without founding empty chats; recovery may still write the crash boundary. */
|
||||
export async function restoreStructuredAgentSessionRead(
|
||||
deps: StructuredAgentSessionConversationOpenDeps,
|
||||
sessionId: string
|
||||
): Promise<OpenedStructuredAgentSessionConversation | null> {
|
||||
const record = deps.store.getConversation(sessionId)
|
||||
if (!record) {
|
||||
return null
|
||||
}
|
||||
if (readJournalSessionEpoch(deps.journalDatabase.db, sessionId) === null) {
|
||||
return null
|
||||
}
|
||||
return openStructuredAgentSessionConversationJournal(deps, record)
|
||||
}
|
||||
-325
@@ -1,325 +0,0 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import * as conversationView from '../../../shared/agent-session-conversation-view'
|
||||
import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture'
|
||||
import { conversationRecordReader } from '../../runtime/orchestration/structured-session-lineage'
|
||||
import { structuredSessionMailReach } from '../../runtime/orchestration/structured-session-mail-address'
|
||||
import { dispatchReportMailbox } from '../../runtime/orchestration/dispatch-report-mailbox'
|
||||
import { structuredMailNotice } from '../../runtime/orchestration/structured-mail-source'
|
||||
import { observeReceivingSql } from './structured-agent-session-receiving-sql.test-support'
|
||||
import {
|
||||
agentSessionRecordFixture,
|
||||
agentSessionLeaseFixture
|
||||
} from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture'
|
||||
import {
|
||||
openTestAgentSessionRecordStore,
|
||||
seedTestAgentSessionRecordStore
|
||||
} from '../../runtime/agent-session/records/agent-session-record-store-test-harness'
|
||||
import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support'
|
||||
import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import {
|
||||
createReceivingAccountFixture,
|
||||
RECEIVING_A,
|
||||
SELECTED_B
|
||||
} from './structured-agent-session-receiving-account.test-support'
|
||||
import { StructuredNativeResponses } from './structured-agent-session-native-responses'
|
||||
import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account'
|
||||
const ordinary: AgentJournalMessageItem = {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'ordinary' }]
|
||||
}
|
||||
it.each([10, 100])(
|
||||
'indexes %i native results once and reads only changed journal rows thereafter',
|
||||
async (n) => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const started = performance.now()
|
||||
const messages = Array.from({ length: n }, () => f.finish(f.start()))
|
||||
for (const message of messages) {
|
||||
const next = await f.submit(f.body(message))
|
||||
await f.turn(next.clientMessageId, 'completed')
|
||||
}
|
||||
const visits = vi.spyOn(f.journal, 'visitItemsWithLinkage')
|
||||
const submissions = vi.spyOn(f.journal, 'submissions')
|
||||
const rows = vi.spyOn(f.journal, 'readSince')
|
||||
const keys = vi.spyOn(f.journal, 'canonicalItemId')
|
||||
const projection = new StructuredNativeResponses()
|
||||
expect(projection.read(f.journal).disposed.size).toBe(n)
|
||||
expect(visits).toHaveBeenCalledTimes(1)
|
||||
expect(submissions).toHaveBeenCalledTimes(1)
|
||||
keys.mockClear()
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
projection.read(f.journal)
|
||||
}
|
||||
expect(keys).not.toHaveBeenCalled()
|
||||
expect(rows).not.toHaveBeenCalled()
|
||||
const next = await f.submit(ordinary, 'client')
|
||||
keys.mockClear()
|
||||
projection.read(f.journal)
|
||||
expect(keys.mock.calls.length).toBeLessThanOrEqual(8)
|
||||
expect(rows).toHaveBeenCalledTimes(1)
|
||||
expect(rows.mock.results[0]?.value).toMatchObject({ ok: true })
|
||||
expect(visits).toHaveBeenCalledTimes(1)
|
||||
expect(submissions).toHaveBeenCalledTimes(1)
|
||||
expect(next.clientMessageId).toBeTruthy()
|
||||
for (let i = 1; i <= n; i += 1) {
|
||||
await f.journal.appendTombstone(
|
||||
{ provider: 'claude', sessionId: 'parent-provider', uuid: `turn-receiving-${i}` },
|
||||
{ fence: 2 }
|
||||
)
|
||||
}
|
||||
projection.read(f.journal)
|
||||
expect(visits).toHaveBeenCalledTimes(2)
|
||||
expect(submissions).toHaveBeenCalledTimes(2)
|
||||
expect(rows).toHaveBeenCalledTimes(2)
|
||||
process.stdout.write(
|
||||
`receiving-account journal corpus=${n} initialVisits=1 initialSubmissionLists=1 unchangedReads=${n} incrementalReads=1 destructiveBatchRebuilds=1 elapsedMs=${(performance.now() - started).toFixed(3)}\n`
|
||||
)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it.each([10, 100])(
|
||||
'bounds real native mailbox enumeration at %i results despite unrelated history',
|
||||
async (n) => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const began = performance.now()
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const next = await f.submit(f.body(f.finish(f.start())))
|
||||
await f.turn(next.clientMessageId, 'completed')
|
||||
}
|
||||
for (let i = 0; i < n * 10; i += 1) {
|
||||
f.db.createTask({ spec: 'unrelated corpus', runId: f.run.id })
|
||||
}
|
||||
const observed = observeReceivingSql(f.db)
|
||||
const selected = await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)
|
||||
expect(selected.home).toEqual(SELECTED_B)
|
||||
// Scoped reach + current mailbox discovery + canonical report routing are constant preparations.
|
||||
expect(observed.measurements.prepares).toBeLessThanOrEqual(20)
|
||||
expect(observed.measurements.allRows).toBeLessThanOrEqual(n + 4)
|
||||
expect(observed.measurements.plans.length).toBeGreaterThan(0)
|
||||
expect(
|
||||
observed.measurements.plans.filter((detail) =>
|
||||
/\bSCAN (?:run|child|task|parent|messages|dispatch_contexts|agent_session_records)\b/.test(
|
||||
detail
|
||||
)
|
||||
)
|
||||
).toEqual([])
|
||||
observed.stop()
|
||||
process.stdout.write(
|
||||
`receiving-account native results=${n} unrelatedTasks=${n * 10} statements=${observed.measurements.prepares} enumerated=${observed.measurements.allRows} elapsedMs=${(performance.now() - began).toFixed(3)}\n`
|
||||
)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it.each([10, 100])(
|
||||
'reads %i historical clear links through the real record index, independent of other chats',
|
||||
async (n) => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const began = performance.now()
|
||||
const predecessors = Array.from({ length: n }, (_, i) => ({
|
||||
...agentSessionRecordFixture(
|
||||
agentSessionLeaseFixture({ sessionId: `clear-source-${i}`, runtimeFence: 2 })
|
||||
),
|
||||
conversationCommand: {
|
||||
command: 'clear' as const,
|
||||
state: 'completed' as const,
|
||||
phase: 'committed' as const,
|
||||
runtimeFence: 2,
|
||||
callerKey: 'legacy-client',
|
||||
operationId: '1800000000000-00000000000000000000000000000003',
|
||||
replacementSessionId: i === n - 1 ? f.root : `clear-source-${i + 1}`
|
||||
}
|
||||
}))
|
||||
const unrelated = Array.from({ length: n * 10 }, (_, i) =>
|
||||
agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: `unrelated-chat-${i}` }))
|
||||
)
|
||||
await seedTestAgentSessionRecordStore(f.rig.root, {
|
||||
records: [f.record, ...predecessors, ...unrelated]
|
||||
})
|
||||
const store = await openTestAgentSessionRecordStore(f.rig.root)
|
||||
const db = openTestJournalHostDatabase(f.rig.root).db
|
||||
const prepare = db.prepare.bind(db)
|
||||
let reads = 0
|
||||
let enumerated = 0
|
||||
const spy = vi.spyOn(db, 'prepare').mockImplementation((sql) => {
|
||||
const statement = prepare(sql)
|
||||
const all = statement.all.bind(statement)
|
||||
vi.spyOn(statement, 'all').mockImplementation((...args) => {
|
||||
reads += 1
|
||||
const rows = all(...args)
|
||||
enumerated += rows.length
|
||||
const plan = prepare(`EXPLAIN QUERY PLAN ${sql}`).all(...args)
|
||||
expect(
|
||||
plan.some(
|
||||
(row) =>
|
||||
typeof row.detail === 'string' &&
|
||||
row.detail.includes('idx_agent_session_clear_successor')
|
||||
)
|
||||
).toBe(true)
|
||||
return rows
|
||||
})
|
||||
return statement
|
||||
})
|
||||
const lineage = store.lineageRecords(f.record)
|
||||
expect(lineage.map((record) => record.sessionId)).toEqual([
|
||||
...predecessors.map((record) => record.sessionId),
|
||||
f.root
|
||||
])
|
||||
expect(spy).toHaveBeenCalledTimes(1)
|
||||
expect(reads).toBe(n + 1)
|
||||
expect(enumerated).toBe(n)
|
||||
spy.mockRestore()
|
||||
process.stdout.write(
|
||||
`receiving-account clearLinks=${n} unrelatedChats=${n * 10} indexPrepares=1 lookups=${reads} enumerated=${enumerated} elapsedMs=${(performance.now() - began).toFixed(3)}\n`
|
||||
)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it.each([
|
||||
{ l: 10, u: 100 },
|
||||
{ l: 100, u: 100 },
|
||||
{ l: 10, u: 1000 },
|
||||
{ l: 100, u: 1000 }
|
||||
])(
|
||||
'bounds canonical receiving projections for lineage $l with $u unrelated chats',
|
||||
async ({ l, u }) => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const ids = Array.from({ length: l - 1 }, () => testOrcaSessionId(randomUUID()))
|
||||
const predecessors = ids.map((sessionId, i) => ({
|
||||
...agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId, runtimeFence: 2 })),
|
||||
conversationCommand: {
|
||||
command: 'clear' as const,
|
||||
state: 'completed' as const,
|
||||
phase: 'committed' as const,
|
||||
runtimeFence: 2,
|
||||
callerKey: 'legacy-client',
|
||||
operationId: '1800000000000-00000000000000000000000000000003',
|
||||
replacementSessionId: ids[i + 1] ?? f.root
|
||||
}
|
||||
}))
|
||||
const unrelated = Array.from({ length: u }, () =>
|
||||
agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: randomUUID() }))
|
||||
)
|
||||
await seedTestAgentSessionRecordStore(f.rig.root, {
|
||||
records: [f.record, ...predecessors, ...unrelated]
|
||||
})
|
||||
const store = await openTestAgentSessionRecordStore(f.rig.root)
|
||||
const record = store.requireWritableRecord(f.root)
|
||||
expect(store.lineageRecords(record).map((item) => item.sessionId)).toEqual([...ids, f.root])
|
||||
const root = ids[0]
|
||||
if (!root) {
|
||||
throw new Error('clear lineage requires a predecessor')
|
||||
}
|
||||
const original = store.getConversation(root)
|
||||
if (!original) {
|
||||
throw new Error('canonical lineage root missing')
|
||||
}
|
||||
const reader = conversationRecordReader(store)
|
||||
expect(structuredSessionMailReach(reader, original, f.db, reader)).toMatchObject({
|
||||
kind: 'reachable',
|
||||
session: { sessionId: f.root }
|
||||
})
|
||||
const run = f.db.createRun({
|
||||
objective: 'clear-lineage native work',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: root
|
||||
})
|
||||
const child = f.db.createStartingWorkerDispatch({
|
||||
taskSpec: 'report to the current clear successor',
|
||||
taskRunId: run.id,
|
||||
taskCreatedByRunGeneration: run.consumer_generation,
|
||||
creator: { kind: 'session', orcaSessionId: root },
|
||||
maxDepth: 9,
|
||||
startOptions: {}
|
||||
})
|
||||
expect(dispatchReportMailbox(f.db, child.dispatch)).toBe(`run:${run.id}`)
|
||||
const all = vi.spyOn(store, 'listRecords').mockImplementation(() => {
|
||||
throw new Error('global raw history scan')
|
||||
})
|
||||
const conversations = vi.spyOn(store, 'listConversations').mockImplementation(() => {
|
||||
throw new Error('global conversation scan')
|
||||
})
|
||||
const projection = vi.spyOn(conversationView, 'agentSessionConversationView')
|
||||
const decide = async (expected: typeof RECEIVING_A) => {
|
||||
projection.mockClear()
|
||||
const observed = observeReceivingSql(f.db)
|
||||
try {
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount({ ...f.deps, store }, record, f.session))
|
||||
.home
|
||||
).toEqual(expected)
|
||||
// Array.map supplies index/array; direct getConversation projections take one argument.
|
||||
const mapped = projection.mock.calls.filter((args) => args.length > 1).length
|
||||
expect(mapped).toBeGreaterThan(0)
|
||||
expect(mapped).toBeLessThanOrEqual(3 * l)
|
||||
expect(observed.measurements.prepares).toBeLessThanOrEqual(20)
|
||||
expect(observed.measurements.allRows).toBeLessThanOrEqual(8)
|
||||
expect(observed.measurements.plans.length).toBeGreaterThan(0)
|
||||
expect(
|
||||
observed.measurements.plans.filter((detail) =>
|
||||
/\bSCAN (?:run|child|task|parent|messages|dispatch_contexts|agent_session_records)\b/.test(
|
||||
detail
|
||||
)
|
||||
)
|
||||
).toEqual([])
|
||||
expect(all).not.toHaveBeenCalled()
|
||||
expect(conversations).not.toHaveBeenCalled()
|
||||
process.stdout.write(
|
||||
`receiving-projection lineage=${l} unrelated=${u} mapped=${mapped} bound=${3 * l} sql=${observed.measurements.prepares} rows=${observed.measurements.allRows} home=${expected.path}\n`
|
||||
)
|
||||
} finally {
|
||||
observed.stop()
|
||||
}
|
||||
}
|
||||
await decide(RECEIVING_A)
|
||||
const message = f.db.commitWorkerDoneMessageMutation(() => {
|
||||
f.db.completeDispatch(child.dispatch.id)
|
||||
return f.db.insertMessage({
|
||||
from: 'structworker_e7f53907-0cde-40b9-81c5-d18eb66c07a4',
|
||||
to: dispatchReportMailbox(f.db, child.dispatch),
|
||||
runId: run.id,
|
||||
type: 'worker_done',
|
||||
subject: 'completed',
|
||||
payload: JSON.stringify({
|
||||
dispatchId: child.dispatch.id,
|
||||
taskId: child.task.id,
|
||||
outcome: 'succeeded'
|
||||
}),
|
||||
deliveryContract: 'current_delivery'
|
||||
})
|
||||
})
|
||||
await decide(RECEIVING_A)
|
||||
const next = await f.submit(
|
||||
structuredMailNotice({
|
||||
db: f.db,
|
||||
mailboxHandle: `run:${run.id}`,
|
||||
dispatchId: null,
|
||||
batch: { messages: [message], heldDeliveryId: undefined },
|
||||
cliCommand: 'orca-dev',
|
||||
senderSnapshot: () => ({ name: null, agent: null })
|
||||
})
|
||||
)
|
||||
await decide(RECEIVING_A)
|
||||
await f.turn(next.clientMessageId, 'completed')
|
||||
await decide(SELECTED_B)
|
||||
expect(f.db.getMessageById(message.id)?.read).toBe(0)
|
||||
} finally {
|
||||
vi.restoreAllMocks()
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
-108
@@ -1,108 +0,0 @@
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { agentSessionSendBodyFingerprint } from '../../../shared/agent-session/requests/structured-agent-session-send-mutation'
|
||||
import { StructuredNativeResponses } from './structured-agent-session-native-responses'
|
||||
import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account'
|
||||
import {
|
||||
createReceivingAccountFixture,
|
||||
RECEIVING_A,
|
||||
SELECTED_B
|
||||
} from './structured-agent-session-receiving-account.test-support'
|
||||
|
||||
it('retains queued pointer ownership across epoch replacement, then disposes only its actual response', async () => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const message = f.finish(f.start())
|
||||
const body = f.body(message)
|
||||
const target = () => structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)
|
||||
await f.journal.queuedMessages.insert({ messageId: 'native-pointer-card', body })
|
||||
f.db.markAsDelivered([message.id], `run:${f.run.id}`)
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
await f.journal.replaceEpochItems('handle_forked', 2, [])
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
await f.journal.appendSubmission(
|
||||
{
|
||||
clientMessageId: 'queued-native-response',
|
||||
payloadFingerprint: agentSessionSendBodyFingerprint(f.root, body),
|
||||
body,
|
||||
origin: 'host',
|
||||
fence: 2,
|
||||
handoverRecorded: true
|
||||
},
|
||||
{ messageId: 'native-pointer-card', expect: 'waiting' }
|
||||
)
|
||||
await f.journal.resolveDispatch({
|
||||
clientMessageId: 'queued-native-response',
|
||||
fence: 2,
|
||||
state: 'pending',
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE
|
||||
})
|
||||
await f.turn('queued-native-response', 'running')
|
||||
f.db.markAsRead([message.id])
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
await f.turn('queued-native-response', 'completed')
|
||||
expect((await target()).home).toEqual(SELECTED_B)
|
||||
// Provider history replacement removes the old turn, not the result's delivery stamp.
|
||||
await f.journal.replaceEpochItems('handle_forked', 2, [])
|
||||
expect((await target()).home).toEqual(SELECTED_B)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('withdrawal ends queued notice ownership even when the result remains unread', async () => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const message = f.finish(f.start())
|
||||
await f.journal.queuedMessages.insert({ messageId: 'withdrawn-pointer', body: f.body(message) })
|
||||
f.db.markAsDelivered([message.id], `run:${f.run.id}`)
|
||||
const target = () => structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
await f.journal.queuedMessages.withdraw(['withdrawn-pointer'])
|
||||
expect((await target()).home).toEqual(SELECTED_B)
|
||||
await f.journal.replaceEpochItems('handle_forked', 2, [])
|
||||
expect((await target()).home).toEqual(SELECTED_B)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it.each([10, 100])(
|
||||
'bounds queued native ownership updates at %i cards to the changed card',
|
||||
async (n) => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const started = performance.now()
|
||||
const ids: string[] = []
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const message = f.finish(f.start())
|
||||
const id = `pointer-${i}`
|
||||
ids.push(id)
|
||||
await f.journal.queuedMessages.insert({ messageId: id, body: f.body(message) })
|
||||
f.db.markAsDelivered([message.id], `run:${f.run.id}`)
|
||||
}
|
||||
const list = vi.spyOn(f.journal.queuedMessages, 'list')
|
||||
const get = vi.spyOn(f.journal.queuedMessages, 'get')
|
||||
const projection = new StructuredNativeResponses()
|
||||
expect([...projection.read(f.journal).pending]).toHaveLength(n)
|
||||
expect(list).toHaveBeenCalledTimes(1)
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
expect([...projection.read(f.journal).pending]).toHaveLength(n)
|
||||
}
|
||||
expect(list).toHaveBeenCalledTimes(1)
|
||||
expect(get).not.toHaveBeenCalled()
|
||||
await f.journal.queuedMessages.withdraw([ids[0]])
|
||||
// Count the receiving projection, excluding the existing mutation owner's own lookups.
|
||||
list.mockClear()
|
||||
get.mockClear()
|
||||
expect([...projection.read(f.journal).pending]).toHaveLength(n - 1)
|
||||
expect(list).not.toHaveBeenCalled()
|
||||
expect(get).toHaveBeenCalledTimes(1)
|
||||
process.stdout.write(
|
||||
`receiving-account queue corpus=${n} initialLists=1 unchangedReads=${n} changedCardGets=1 changedCardLists=0 elapsedMs=${(performance.now() - started).toFixed(3)}\n`
|
||||
)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
-218
@@ -1,218 +0,0 @@
|
||||
import { createRestTestRig } from './structured-agent-session-rest-test-rig'
|
||||
import { hostTestAttachParams } from './structured-agent-session-host-test-data'
|
||||
import {
|
||||
agentSessionRecordFixture,
|
||||
agentSessionLeaseFixture
|
||||
} from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture'
|
||||
import { withAcquiredAgentSessionAccount } from '../../../shared/agent-session-acquired-account'
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalMessageItem,
|
||||
type AgentJournalTurnLifecycle
|
||||
} from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import {
|
||||
agentJournalSubmissionKey,
|
||||
agentJournalItemKey
|
||||
} from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { isOrcaSessionId } from '../../../shared/orca-session-address'
|
||||
import { StructuredAgentSessionCurrentWork } from './structured-agent-session-current-work'
|
||||
import { AgentSessionJournal } from '../agent-session-journal/journal-store'
|
||||
import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support'
|
||||
import {
|
||||
seedTestAgentSessionRecordStore,
|
||||
openTestAgentSessionRecordStore
|
||||
} from '../../runtime/agent-session/records/agent-session-record-store-test-harness'
|
||||
import { OrchestrationDb } from '../../runtime/orchestration/db'
|
||||
import { structuredNativeWorkReaders } from '../../runtime/structured-native-work-readers'
|
||||
import { structuredMailNotice } from '../../runtime/orchestration/structured-mail-source'
|
||||
import type { StructuredAgentSessionHostSession } from './structured-agent-session-host-types'
|
||||
|
||||
export const RECEIVING_A = { variable: 'CLAUDE_CONFIG_DIR', path: '/qa/claude-profiles/qa-a/home' }
|
||||
export const SELECTED_B = { variable: 'CLAUDE_CONFIG_DIR', path: '/qa/claude-profiles/qa-b/home' }
|
||||
export async function createReceivingAccountFixture() {
|
||||
const rig = await createRestTestRig()
|
||||
const record = withAcquiredAgentSessionAccount(
|
||||
agentSessionRecordFixture(
|
||||
agentSessionLeaseFixture({
|
||||
sessionId: '6e1b4ae5-2354-4ca5-999e-647deeb23894',
|
||||
runtimeFence: 2
|
||||
})
|
||||
),
|
||||
{
|
||||
generation: 'generation-2',
|
||||
recipe: { route: 'system', home: RECEIVING_A.path, configDir: RECEIVING_A.path }
|
||||
}
|
||||
)
|
||||
const root = record.sessionId
|
||||
if (!isOrcaSessionId(root)) {
|
||||
throw new Error('fixture requires a canonical session id')
|
||||
}
|
||||
await seedTestAgentSessionRecordStore(rig.root, { records: [record] })
|
||||
const store = await openTestAgentSessionRecordStore(rig.root)
|
||||
const journal = new AgentSessionJournal({
|
||||
database: openTestJournalHostDatabase(rig.root),
|
||||
identity: {
|
||||
sessionId: root,
|
||||
workspaceId: 'workspace-1',
|
||||
hostId: 'local',
|
||||
agent: 'claude',
|
||||
providerHandle: null
|
||||
}
|
||||
})
|
||||
await journal.open()
|
||||
const session: StructuredAgentSessionHostSession = {
|
||||
journal,
|
||||
params: hostTestAttachParams(null, {
|
||||
provider: 'claude',
|
||||
agent: 'claude',
|
||||
accountHome: RECEIVING_A
|
||||
}),
|
||||
child: { phase: 'ready', fence: 2, generation: 'generation-2', accountHome: RECEIVING_A }
|
||||
}
|
||||
const db = new OrchestrationDb(':memory:')
|
||||
const run = db.createRun({
|
||||
objective: 'native parent',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: root
|
||||
})
|
||||
const deps = {
|
||||
...rig.host.deps,
|
||||
store,
|
||||
launchAccountHome: async () => SELECTED_B,
|
||||
...structuredNativeWorkReaders(() => db)
|
||||
}
|
||||
let sends = 0
|
||||
const submit = async (
|
||||
body: AgentJournalMessageItem,
|
||||
origin: 'client' | 'host' = 'host',
|
||||
legacy = false
|
||||
) => {
|
||||
const clientMessageId = `receiving-${++sends}`
|
||||
await journal.appendSubmission({
|
||||
clientMessageId,
|
||||
payloadFingerprint: clientMessageId,
|
||||
...(legacy ? {} : { handoverRecorded: true }),
|
||||
body,
|
||||
origin,
|
||||
fence: 2
|
||||
})
|
||||
const submission = journal.submission(clientMessageId)
|
||||
if (!submission) {
|
||||
throw new Error('submission was not committed')
|
||||
}
|
||||
return submission
|
||||
}
|
||||
const turn = async (
|
||||
clientMessageId: string,
|
||||
state: AgentJournalTurnLifecycle['state'],
|
||||
legacy = false
|
||||
) => {
|
||||
const identity = {
|
||||
provider: 'claude' as const,
|
||||
sessionId: 'parent-provider',
|
||||
uuid: `turn-${clientMessageId}`
|
||||
}
|
||||
let userItemId = agentJournalSubmissionKey(clientMessageId)
|
||||
const submitted = journal.submission(clientMessageId)
|
||||
if (submitted) {
|
||||
const echo = {
|
||||
provider: 'claude' as const,
|
||||
sessionId: 'parent-provider',
|
||||
uuid: `echo-${clientMessageId}`
|
||||
}
|
||||
const body = journal.itemBody(userItemId)
|
||||
if (!body) {
|
||||
throw new Error('provider echo requires its actual submitted input')
|
||||
}
|
||||
const turnScope = new StructuredAgentSessionCurrentWork(journal, 2).turnScope()
|
||||
if (submitted.handoverRecorded && submitted.handedOverAt === undefined) {
|
||||
await journal.resolveDispatch({ clientMessageId, fence: 2, state: 'pending', turnScope })
|
||||
}
|
||||
await journal.resolveDispatch({
|
||||
clientMessageId,
|
||||
fence: 2,
|
||||
state: 'accepted',
|
||||
providerIdentity: echo
|
||||
})
|
||||
await journal.appendItem(echo, body, { fence: 2, turnScope })
|
||||
if (legacy) {
|
||||
userItemId = agentJournalItemKey(echo)
|
||||
}
|
||||
}
|
||||
const lifecycle: AgentJournalTurnLifecycle = {
|
||||
turnId: `turn-${clientMessageId}`,
|
||||
state,
|
||||
outcome: state === 'completed' ? 'success' : undefined,
|
||||
userItemId,
|
||||
...(state === 'running' ? {} : { completedAt: 100 })
|
||||
}
|
||||
await journal.appendItem(
|
||||
identity,
|
||||
legacy
|
||||
? { kind: 'status', text: 'Done', turnLifecycle: lifecycle }
|
||||
: { kind: 'turn', ...lifecycle },
|
||||
{ fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
return agentJournalItemKey(identity)
|
||||
}
|
||||
const start = () =>
|
||||
db.createStartingWorkerDispatch({
|
||||
taskSpec: 'real native child work',
|
||||
taskRunId: run.id,
|
||||
taskCreatedByRunGeneration: run.consumer_generation,
|
||||
startOptions: {},
|
||||
creator: { kind: 'session', orcaSessionId: root },
|
||||
maxDepth: 9
|
||||
})
|
||||
const finish = (
|
||||
child: ReturnType<typeof start>,
|
||||
contract: 'legacy_direct' | 'current_delivery' = 'current_delivery'
|
||||
) =>
|
||||
db.commitWorkerDoneMessageMutation(() => {
|
||||
db.completeDispatch(child.dispatch.id)
|
||||
return db.insertMessage({
|
||||
from: 'structworker_e7f53907-0cde-40b9-81c5-d18eb66c07a4',
|
||||
to: `run:${run.id}`,
|
||||
runId: run.id,
|
||||
type: 'worker_done',
|
||||
subject: 'child completed',
|
||||
payload: JSON.stringify({
|
||||
dispatchId: child.dispatch.id,
|
||||
taskId: child.task.id,
|
||||
outcome: 'succeeded'
|
||||
}),
|
||||
deliveryContract: contract
|
||||
})
|
||||
})
|
||||
const body = (message: ReturnType<typeof finish>) =>
|
||||
structuredMailNotice({
|
||||
db,
|
||||
mailboxHandle: `run:${run.id}`,
|
||||
dispatchId: null,
|
||||
batch: { messages: [message], heldDeliveryId: undefined },
|
||||
cliCommand: 'orca-dev',
|
||||
senderSnapshot: () => ({ name: null, agent: null })
|
||||
})
|
||||
return {
|
||||
rig,
|
||||
record,
|
||||
store,
|
||||
session,
|
||||
deps,
|
||||
journal,
|
||||
db,
|
||||
run,
|
||||
root,
|
||||
submit,
|
||||
turn,
|
||||
start,
|
||||
finish,
|
||||
body,
|
||||
dispose: async () => {
|
||||
await journal.close()
|
||||
db.close()
|
||||
await rig.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
-285
@@ -1,285 +0,0 @@
|
||||
import {
|
||||
AGENT_JOURNAL_THREAD_SCOPE,
|
||||
type AgentJournalMessageItem
|
||||
} from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
createReceivingAccountFixture,
|
||||
RECEIVING_A,
|
||||
SELECTED_B
|
||||
} from './structured-agent-session-receiving-account.test-support'
|
||||
import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account'
|
||||
import { agentSessionFailureFact } from '../../../shared/agent-session/failures/agent-session-failure'
|
||||
import { agentSessionFailureWords } from '../../../shared/agent-session/failures/agent-session-failure-words'
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
|
||||
const ordinary: AgentJournalMessageItem = {
|
||||
kind: 'message',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'next ordinary input' }]
|
||||
}
|
||||
|
||||
describe('receiving account through native work and exact parent disposition', () => {
|
||||
it.each(['current_delivery', 'legacy_direct'] as const)(
|
||||
'retains A from creation through %s response, then eligible ordinary follows B',
|
||||
async (contract) => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const target = async () =>
|
||||
structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)
|
||||
const child = f.start()
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
const message = f.finish(child, contract)
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
const next = await f.submit(f.body(message), 'host', contract === 'legacy_direct')
|
||||
f.db.markAsDelivered([message.id], `run:${f.run.id}`)
|
||||
await f.turn(next.clientMessageId, 'running', contract === 'legacy_direct')
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
f.db.markAsRead([message.id])
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
await f.turn('unrelated-parent-request', 'completed')
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
await f.turn(next.clientMessageId, 'completed', contract === 'legacy_direct')
|
||||
expect((await target()).home).toEqual(SELECTED_B)
|
||||
const picked = await f.submit(ordinary, 'client')
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, picked)).recipe
|
||||
).toBeUndefined()
|
||||
// Repeated unread notice replays cannot recreate account ownership after the exact response.
|
||||
f.db.markAsUndelivered([message.id])
|
||||
expect((await target()).home).toEqual(SELECTED_B)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('retires owed ownership when a rewind retires the Orca send that carried the notice', async () => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const target = () => structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)
|
||||
const receipt = { write: () => undefined, committed: () => undefined }
|
||||
await f.journal.context.clear(
|
||||
{ operationId: 'clear-1', afterFence: 1, clearedAt: 1 },
|
||||
receipt
|
||||
)
|
||||
const floor = f.journal.cursor()
|
||||
const message = f.finish(f.start())
|
||||
const next = await f.submit(f.body(message))
|
||||
f.db.markAsDelivered([message.id], `run:${f.run.id}`)
|
||||
await f.turn(next.clientMessageId, 'running')
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
await f.journal.context.rewind(floor, 2, [], () => receipt)
|
||||
expect(f.journal.submission(next.clientMessageId)).toBeUndefined()
|
||||
expect((await target()).home).toEqual(SELECTED_B)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['interrupted', 'unverifiable'] as const)(
|
||||
'keeps existing %s disposition without a success-only hold',
|
||||
async (state) => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const message = f.finish(f.start())
|
||||
const next = await f.submit(f.body(message))
|
||||
const target = () => structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)
|
||||
expect((await target()).home).toEqual(RECEIVING_A)
|
||||
await f.turn(next.clientMessageId, state)
|
||||
expect((await target()).home).toEqual(SELECTED_B)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('retains known recipe after true absence; unknown historical absence uses selection, without inventing A', async () => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const next = await f.submit(f.body(f.finish(f.start())))
|
||||
await f.store.reconcileOnRestart({
|
||||
sessionId: f.root,
|
||||
probe: async () => ({ outcome: 'exit-observed' }),
|
||||
now: 40_000
|
||||
})
|
||||
f.session.child = null
|
||||
const released = f.store.getRecord(f.root)
|
||||
if (!released) {
|
||||
throw new Error('record missing after actual release')
|
||||
}
|
||||
const known = await structuredAgentSessionReceivingAccount(f.deps, released, f.session, next)
|
||||
expect(known.home).toEqual(RECEIVING_A)
|
||||
expect(known.recipe).toMatchObject({ route: 'system', home: RECEIVING_A.path })
|
||||
const { acquiredAccount: _observation, ...historical } = released
|
||||
// The store reader returns this historical record rather than a retained source observation.
|
||||
const lineageRecords = vi.spyOn(f.store, 'lineageRecords').mockReturnValue([historical])
|
||||
expect(
|
||||
await structuredAgentSessionReceivingAccount(f.deps, historical, f.session, next)
|
||||
).toEqual({ home: SELECTED_B })
|
||||
lineageRecords.mockRestore()
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('fences a previous consumer through the real Run rebind owner', async () => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
f.start()
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)).home
|
||||
).toEqual(RECEIVING_A)
|
||||
const next = f.db.createRun({
|
||||
objective: 'new coordinator consumer',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: f.root
|
||||
})
|
||||
// Creation keeps the earlier consumer; run-use is the real rebind owner.
|
||||
f.db.bindRun({
|
||||
runId: next.id,
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: f.root
|
||||
})
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)).home
|
||||
).toEqual(SELECTED_B)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('signed-out native mail uses existing selected-route recovery, including reacquisition', async () => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const next = await f.submit(f.body(f.finish(f.start())))
|
||||
await f.journal.appendItem(
|
||||
{ provider: 'orca', clientMessageId: 'signed-out' },
|
||||
{
|
||||
kind: 'status',
|
||||
...agentSessionFailureWords(agentSessionFailureFact('notSignedIn'), { surface: 'row' })
|
||||
},
|
||||
{ fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
expect(
|
||||
await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, next)
|
||||
).toEqual({ home: SELECTED_B })
|
||||
f.session.child = null
|
||||
expect(
|
||||
await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, next)
|
||||
).toEqual({ home: SELECTED_B })
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('allows explicit latest usage-cut recovery without automatically rerouting native mail', async () => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
f.start()
|
||||
const turnId = await f.turn('limited', 'completed')
|
||||
await f.journal.appendItem(
|
||||
{ provider: 'claude', sessionId: 'parent-provider', uuid: 'turn-limited' },
|
||||
{
|
||||
kind: 'turn',
|
||||
turnId: 'turn-limited',
|
||||
state: 'completed',
|
||||
outcome: 'failure',
|
||||
userItemId: agentJournalSubmissionKey('limited')
|
||||
},
|
||||
{ fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
await f.journal.appendItem(
|
||||
{ provider: 'orca', clientMessageId: 'usage' },
|
||||
{
|
||||
kind: 'status',
|
||||
...agentSessionFailureWords(agentSessionFailureFact('usageLimitReached'), {
|
||||
surface: 'row'
|
||||
})
|
||||
},
|
||||
{ fence: 2, turnScope: { kind: 'turn', turnItemId: turnId } }
|
||||
)
|
||||
const next = await f.submit(ordinary, 'client')
|
||||
expect(
|
||||
await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, next)
|
||||
).toEqual({ home: SELECTED_B })
|
||||
await f.turn(next.clientMessageId, 'completed')
|
||||
const afterRecovery = await f.submit(ordinary, 'client')
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, afterRecovery))
|
||||
.home
|
||||
).toEqual(RECEIVING_A)
|
||||
const automatic = await f.submit(f.body(f.finish(f.start())))
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, automatic)).home
|
||||
).toEqual(RECEIVING_A)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
it('ends pre-notice ownership when the actual created worker is stopped', async () => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const child = f.start()
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)).home
|
||||
).toEqual(RECEIVING_A)
|
||||
f.db.reconcileFederatedWorkerStart({
|
||||
dispatchId: child.dispatch.id,
|
||||
state: 'ready',
|
||||
stage: 'ready'
|
||||
})
|
||||
expect(f.db.beginWorkerStop(child.dispatch.id, 'test-runtime').disposition).toBe('stopping')
|
||||
f.db.settleWorkerStop(child.dispatch.id)
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)).home
|
||||
).toEqual(SELECTED_B)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
it("does not add an account hold to main's accepted-but-unanswered ended generation", async () => {
|
||||
const f = await createReceivingAccountFixture()
|
||||
try {
|
||||
const message = f.finish(f.start())
|
||||
const next = await f.submit(f.body(message), 'host', true)
|
||||
await f.journal.resolveDispatch({
|
||||
clientMessageId: next.clientMessageId,
|
||||
fence: 2,
|
||||
state: 'accepted',
|
||||
providerIdentity: {
|
||||
provider: 'claude',
|
||||
sessionId: 'parent-provider',
|
||||
uuid: 'unanswered-echo'
|
||||
}
|
||||
})
|
||||
f.db.markAsDelivered([message.id], `run:${f.run.id}`)
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)).home
|
||||
).toEqual(RECEIVING_A)
|
||||
await f.store.reconcileOnRestart({
|
||||
sessionId: f.root,
|
||||
probe: async () => ({ outcome: 'exit-observed' }),
|
||||
now: 40_000
|
||||
})
|
||||
f.session.child = null
|
||||
const released = f.store.getRecord(f.root)
|
||||
if (!released) {
|
||||
throw new Error('record missing after execution ended')
|
||||
}
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, released, f.session)).home
|
||||
).toEqual(SELECTED_B)
|
||||
expect(f.journal.submission(next.clientMessageId)?.dispatchState).toBe('accepted')
|
||||
// A distinct later result still has known receiving A; this does not erase the actual recipe.
|
||||
f.finish(f.start())
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, released, f.session)).home
|
||||
).toEqual(RECEIVING_A)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,85 +0,0 @@
|
||||
import {
|
||||
acquiredAgentSessionAccount,
|
||||
type ClaudeAccountRecipe
|
||||
} from '../../../shared/agent-session-acquired-account'
|
||||
import { agentSessionConversationView } from '../../../shared/agent-session-conversation-view'
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { AgentJournalSubmission } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import type { AgentSessionAccountHome } from '../../../shared/agent-session/lifecycle/agent-session-account-home'
|
||||
import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record'
|
||||
import type {
|
||||
StructuredAgentSessionHostDeps,
|
||||
StructuredAgentSessionHostSession
|
||||
} from './structured-agent-session-host-types'
|
||||
import type { NativeResponseEvidence } from '../../runtime/orchestration/structured-parent-account-work'
|
||||
import { StructuredNativeResponses } from './structured-agent-session-native-responses'
|
||||
|
||||
const responses = new WeakMap<
|
||||
StructuredAgentSessionHostSession['journal'],
|
||||
StructuredNativeResponses
|
||||
>()
|
||||
|
||||
/** Account construction authority is independent of whether an existing child may be retired. */
|
||||
export async function structuredAgentSessionReceivingAccount(
|
||||
deps: StructuredAgentSessionHostDeps,
|
||||
record: AgentSessionRecord,
|
||||
session: StructuredAgentSessionHostSession | undefined,
|
||||
next?: AgentJournalSubmission,
|
||||
purpose?: 'read' | 'identity'
|
||||
): Promise<{ home: AgentSessionAccountHome | null; recipe?: ClaudeAccountRecipe }> {
|
||||
const selected = () => deps.launchAccountHome?.(record, purpose) ?? Promise.resolve(null)
|
||||
if (record.provider !== 'claude' || !deps.launchAccountHome) {
|
||||
return { home: await selected() }
|
||||
}
|
||||
let index = session && responses.get(session.journal)
|
||||
if (session && !index) {
|
||||
index = new StructuredNativeResponses()
|
||||
responses.set(session.journal, index)
|
||||
}
|
||||
const evidence: NativeResponseEvidence =
|
||||
session && index
|
||||
? index.read(session.journal, record.lease.runtimeFence)
|
||||
: { pending: [], disposed: new Set() }
|
||||
const lineage = deps.store.lineageRecords(record)
|
||||
const recorded = acquiredAgentSessionAccount(record, deps.store.hostId)
|
||||
// Historical clear links identify native work; they cannot prove a successor's acquired account.
|
||||
const observation =
|
||||
recorded &&
|
||||
(!session?.child ||
|
||||
(recorded.fence === session.child.fence && recorded.generation === session.child.generation))
|
||||
? recorded
|
||||
: null
|
||||
const fence = session?.child?.fence ?? observation?.fence
|
||||
if (fence !== undefined && index?.signedOut(fence)) {
|
||||
return { home: await selected() }
|
||||
}
|
||||
const body =
|
||||
next && session
|
||||
? session.journal.itemBody(agentJournalSubmissionKey(next.clientMessageId))
|
||||
: null
|
||||
const mail = body?.kind === 'message' && body.from?.orchestration?.message === 'mail-notice'
|
||||
if (
|
||||
!mail &&
|
||||
session &&
|
||||
next?.origin === 'client' &&
|
||||
index?.recovery.allows(session.journal, next)
|
||||
) {
|
||||
return { home: await selected() }
|
||||
}
|
||||
const native =
|
||||
deps.parentAccountWork?.(record, lineage[0].sessionId, evidence, {
|
||||
getRecord: deps.store.getConversation,
|
||||
listRecords: () => lineage.map(agentSessionConversationView),
|
||||
getVisibleSessionTabIndex: deps.store.getVisibleSessionTabIndex
|
||||
}) ?? false
|
||||
if (mail || native) {
|
||||
const home =
|
||||
session?.child?.accountHome ??
|
||||
(observation ? { variable: 'CLAUDE_CONFIG_DIR', path: observation.recipe.home } : null)
|
||||
if (home) {
|
||||
return { home, ...(observation ? { recipe: observation.recipe } : {}) }
|
||||
}
|
||||
}
|
||||
// No successful observation exists for a gone historical process: use the selected route truthfully.
|
||||
return { home: await selected() }
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { z } from 'zod'
|
||||
import { createClaudeJournalTranslator } from '../../claude/structured/journal/claude-structured-journal-translation'
|
||||
import {
|
||||
createReceivingCallerFixture,
|
||||
HOME_A,
|
||||
HOME_B,
|
||||
PARENT
|
||||
} from './structured-agent-session-receiving-callers.test-support'
|
||||
|
||||
const entry = z.looseObject({ kind: z.string() })
|
||||
const capturedFrame = z.object({ at: z.number(), frame: z.record(z.string(), z.unknown()) })
|
||||
|
||||
describe('recorded Claude authentication failure reaches receiving recovery', () => {
|
||||
it('uses the recorded typed failure through the production translator and current acquired fence', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
await f.coldNative()
|
||||
f.selectB()
|
||||
await f.ensure()
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A)
|
||||
const sink = f.sinks.get(PARENT)
|
||||
if (!sink) {
|
||||
throw new Error('successful actual parent acquisition missing')
|
||||
}
|
||||
const translator = createClaudeJournalTranslator({ account: () => 'system', sink })
|
||||
try {
|
||||
// Shipping recorded CLI2.1.280 authentication_failed frames; context/fence comes from this actual host acquisition.
|
||||
const capture = await readFile(
|
||||
new URL(
|
||||
'../../claude/__fixtures__/claude-lifecycle-capture-auth-failed.jsonl',
|
||||
import.meta.url
|
||||
),
|
||||
'utf8'
|
||||
)
|
||||
for (const line of capture.trim().split('\n')) {
|
||||
const value: unknown = JSON.parse(line)
|
||||
if (entry.parse(value).kind !== 'frame') {
|
||||
continue
|
||||
}
|
||||
const { at, frame } = capturedFrame.parse(value)
|
||||
translator.handle({ type: 'message', sessionId: PARENT, observedAt: at, message: frame })
|
||||
}
|
||||
await f.rig.host.flushStreamedEvents(PARENT)
|
||||
const snapshot = await f.rig.host.journalSnapshot(PARENT)
|
||||
expect(
|
||||
snapshot.items.some(
|
||||
(item) => item.body.kind === 'status' && item.body.failure?.kind === 'notSignedIn'
|
||||
)
|
||||
).toBe(true)
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_B)
|
||||
} finally {
|
||||
translator.dispose()
|
||||
}
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
-165
@@ -1,165 +0,0 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { join } from 'node:path'
|
||||
import { expect, it } from 'vitest'
|
||||
import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture'
|
||||
import { OrchestrationDb } from '../../runtime/orchestration/db'
|
||||
import {
|
||||
createReceivingCallerFixture,
|
||||
HOME_A,
|
||||
PARENT,
|
||||
WORKER
|
||||
} from './structured-agent-session-receiving-callers.test-support'
|
||||
import { observeReceivingSql } from './structured-agent-session-receiving-sql.test-support'
|
||||
|
||||
it.each([
|
||||
{ n: 10, u: 100 },
|
||||
{ n: 100, u: 100 },
|
||||
{ n: 10, u: 1000 }
|
||||
])(
|
||||
'bounds real receiving/report work with D/P=$n and independently varied U=$u',
|
||||
async ({ n, u }) => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
const db = f.runtime.getOrchestrationDb()
|
||||
const run = db.createRun({
|
||||
objective: 'relevant Run',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: PARENT
|
||||
})
|
||||
const workers: Awaited<ReturnType<typeof f.createWorker>>[] = []
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
workers.push(await f.createWorker(testOrcaSessionId(randomUUID())))
|
||||
}
|
||||
const other = db.createRun({
|
||||
objective: 'unrelated',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null
|
||||
})
|
||||
for (let i = 0; i < u; i += 1) {
|
||||
db.createStartingWorkerDispatch({
|
||||
taskSpec: 'unrelated work',
|
||||
taskRunId: other.id,
|
||||
creator: { kind: 'system' },
|
||||
maxDepth: 9,
|
||||
startOptions: {}
|
||||
})
|
||||
}
|
||||
// Reopen a real populated database with the old branch's index shape; keep cold cost separate.
|
||||
db.db.exec(
|
||||
'DROP INDEX idx_dispatch_creator_mailbox_work; DROP INDEX idx_runs_current_coordinator_handle; DROP INDEX idx_messages_native_direct_work'
|
||||
)
|
||||
const coldAt = performance.now()
|
||||
const reopened = new OrchestrationDb(join(f.rig.root, 'orchestration.db'))
|
||||
const coldMs = performance.now() - coldAt
|
||||
expect(
|
||||
reopened.db
|
||||
.prepare(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_dispatch_creator_mailbox_work'"
|
||||
)
|
||||
.get()
|
||||
).toBeDefined()
|
||||
expect(reopened.db.prepare('SELECT count(*) AS n FROM dispatch_contexts').get()?.n).toBe(
|
||||
n + u
|
||||
)
|
||||
reopened.close()
|
||||
f.selectB()
|
||||
const active = observeReceivingSql(db)
|
||||
const activeAt = performance.now()
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A)
|
||||
const activeMs = performance.now() - activeAt
|
||||
active.stop()
|
||||
expect(active.measurements.executions).toBeLessThanOrEqual(40 + 5 * n)
|
||||
expect(active.measurements.rows).toBeLessThanOrEqual(12 + 4 * n)
|
||||
let reportExecutions = 0
|
||||
let reportRows = 0
|
||||
let reportMs = 0
|
||||
for (const worker of workers) {
|
||||
const observed = observeReceivingSql(db)
|
||||
const at = performance.now()
|
||||
await f.report(worker)
|
||||
reportMs += performance.now() - at
|
||||
observed.stop()
|
||||
expect(db.getWorkerDispatch(worker.dispatch.id)?.state).toBe('succeeded')
|
||||
expect(observed.measurements.executions).toBeLessThanOrEqual(300 + 25 * n)
|
||||
expect(observed.measurements.rows).toBeLessThanOrEqual(200 + 20 * n)
|
||||
reportExecutions += observed.measurements.executions
|
||||
reportRows += observed.measurements.rows
|
||||
}
|
||||
expect(db.getUndeliveredUnreadMessages(`run:${run.id}`)).toHaveLength(n)
|
||||
const pending = observeReceivingSql(db)
|
||||
const pendingAt = performance.now()
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A)
|
||||
const pendingMs = performance.now() - pendingAt
|
||||
pending.stop()
|
||||
expect(pending.measurements.executions).toBeLessThanOrEqual(40 + 5 * n)
|
||||
expect(pending.measurements.rows).toBeLessThanOrEqual(12 + 4 * n)
|
||||
const plans = [...active.measurements.plans, ...pending.measurements.plans]
|
||||
expect(plans.some((plan) => plan.includes('idx_dispatch_run_status'))).toBe(true)
|
||||
expect(
|
||||
plans.filter((plan) => /\bSCAN (?:runs|dispatch_contexts|messages|tasks)\b/.test(plan))
|
||||
).toEqual([])
|
||||
process.stdout.write(
|
||||
`receiving-callers D=${n} P=${n} M=1 U=${u} coldIndexedRows=${n + u} coldOpenMs=${coldMs.toFixed(3)} active=${JSON.stringify(active.measurements)} activeMs=${activeMs.toFixed(3)} pending=${JSON.stringify(pending.measurements)} pendingMs=${pendingMs.toFixed(3)} reportExecutions=${reportExecutions} reportRows=${reportRows} reportMs=${reportMs.toFixed(3)}\n`
|
||||
)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it.each([10, 100])(
|
||||
'bounds two current mailbox roles at %i real nested candidates per role',
|
||||
async (n) => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
const db = f.runtime.getOrchestrationDb()
|
||||
db.createRun({
|
||||
objective: 'original parent',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: PARENT
|
||||
})
|
||||
const worker = await f.createWorker(WORKER)
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
await f.createWorker(testOrcaSessionId(randomUUID()), WORKER)
|
||||
}
|
||||
const own = db.createRun({
|
||||
objective: 'worker also coordinates',
|
||||
coordinatorHandle: worker.handle,
|
||||
coordinatorPaneKey: worker.paneKey,
|
||||
coordinatorOrcaSessionId: WORKER
|
||||
})
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
await f.createWorker(testOrcaSessionId(randomUUID()), WORKER)
|
||||
}
|
||||
expect(f.runtime.mailTarget(`run:${own.id}`)?.sessionId).toBe(WORKER)
|
||||
expect(f.runtime.mailTarget(`dispatch:${worker.dispatch.id}`)?.sessionId).toBe(WORKER)
|
||||
f.selectB()
|
||||
const observed = observeReceivingSql(db)
|
||||
const began = performance.now()
|
||||
expect(await f.rig.host.prospectiveAccountHome(WORKER)).toEqual(HOME_A)
|
||||
const elapsedMs = performance.now() - began
|
||||
observed.stop()
|
||||
expect(observed.measurements.executions).toBeLessThanOrEqual(60 + 10 * n)
|
||||
expect(observed.measurements.rows).toBeLessThanOrEqual(30 + 8 * n)
|
||||
expect(
|
||||
observed.measurements.plans.some((plan) =>
|
||||
plan.includes('idx_dispatch_creator_mailbox_work')
|
||||
)
|
||||
).toBe(true)
|
||||
expect(
|
||||
observed.measurements.plans.filter((plan) =>
|
||||
/\bSCAN (?:runs|dispatch_contexts|messages|tasks)\b/.test(plan)
|
||||
)
|
||||
).toEqual([])
|
||||
process.stdout.write(
|
||||
`receiving-callers M=2 D=${n * 2} P=0 U=0 ${JSON.stringify(observed.measurements)} elapsedMs=${elapsedMs.toFixed(3)}\n`
|
||||
)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
+38
-34
@@ -1,12 +1,10 @@
|
||||
import {
|
||||
receivingPersistedFixtures,
|
||||
receivingRuntimeStore
|
||||
} from './structured-agent-session-receiving-persisted.test-support'
|
||||
import { join } from 'node:path'
|
||||
import { expect, vi } from 'vitest'
|
||||
import { Store } from '../../persistence/loading-store/store'
|
||||
import { ProfileStateSqliteAuthority } from '../../persistence/profile-state/profile-state-sqlite-authority'
|
||||
import { getAppEnvironment, setAppEnvironment } from '../../../shared/app-environment'
|
||||
import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture'
|
||||
import { claudeProviderHandle } from '../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
|
||||
import type { ClaudeAccountRecipe } from '../../../shared/agent-session-acquired-account'
|
||||
import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session/lifecycle/agent-session-mutation-envelope'
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
@@ -24,7 +22,7 @@ import {
|
||||
structuredWorkerIdentities,
|
||||
structuredWorkerProcessIncarnation
|
||||
} from '../../runtime/structured-worker-identity'
|
||||
import { structuredNativeWorkReaders } from '../../runtime/structured-native-work-readers'
|
||||
import { structuredWorkerOwesWork } from '../../runtime/structured-worker-custody'
|
||||
import { createRestTestRig, REST_TEST_CALLER } from './structured-agent-session-rest-test-rig'
|
||||
import {
|
||||
hostTestAttachParams,
|
||||
@@ -32,24 +30,36 @@ import {
|
||||
hostTestOperationId
|
||||
} from './structured-agent-session-host-test-data'
|
||||
import { setStructuredAgentSessionHost } from './structured-agent-session-registry'
|
||||
import { createClaudeAccountRouting } from './structured-agent-session-claude-account-routing.test-support'
|
||||
import type { StructuredAgentSessionEventSink } from './structured-agent-session-event-sink'
|
||||
|
||||
export const PARENT = testOrcaSessionId('cfe50e96-3a95-4353-9cdc-7a652779c6e8')
|
||||
export const WORKER = testOrcaSessionId('4c1b8d7a-975c-4984-a2e4-8149fdd4177a')
|
||||
export const HELPER = testOrcaSessionId('8e2ab9f7-0ad7-43f0-9241-539b1e4c5bc7')
|
||||
export const HOME_A = { variable: 'CLAUDE_CONFIG_DIR', path: '/qa/claude/a' }
|
||||
export const HOME_B = { variable: 'CLAUDE_CONFIG_DIR', path: '/qa/claude/b' }
|
||||
|
||||
/** Script only external adapter IO; reservation, proof, journals, RPC and native transactions are real. */
|
||||
export async function createReceivingCallerFixture(options: { reportsRecipe?: boolean } = {}) {
|
||||
/** The registered attach path reads launch defaults from the runtime's profile store. */
|
||||
function receivingRuntimeStore(root: string) {
|
||||
return new Store({
|
||||
dataFile: join(root, 'runtime-state.json'),
|
||||
profileStateAuthority: new ProfileStateSqliteAuthority(
|
||||
join(root, 'runtime-profile.db'),
|
||||
'receiving'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/** Script only external adapter IO (the Claude process and its transcripts); the account router,
|
||||
* Claude launch resolution, reservation, proof, journals, RPC and native transactions are real. */
|
||||
export async function createReceivingCallerFixture() {
|
||||
const previousEnvironment = getAppEnvironment()
|
||||
let selected = HOME_A
|
||||
let runtime: ReceivingRuntime | undefined
|
||||
const readers = structuredNativeWorkReaders(
|
||||
() => runtime?.getOrchestrationDbIfAvailable() ?? null,
|
||||
() => runtime?.getExistingOrchestrationDb() ?? null
|
||||
)
|
||||
const rig = await createRestTestRig({ ...readers, launchAccountHome: async () => selected })
|
||||
const routing = createClaudeAccountRouting()
|
||||
const rig = await createRestTestRig({
|
||||
// Production wiring: an assigned worker's own open Dispatch keeps its process.
|
||||
hasOpenDispatch: (record) =>
|
||||
structuredWorkerOwesWork(runtime?.getOrchestrationDbIfAvailable() ?? null, record),
|
||||
launchAccountHome: routing.launchAccountHome
|
||||
})
|
||||
const accounts = routing.install(rig.root, () => rig.store)
|
||||
setAppEnvironment({
|
||||
...previousEnvironment,
|
||||
getPath: (name) => (name === 'userData' ? rig.root : previousEnvironment.getPath(name))
|
||||
@@ -65,18 +75,14 @@ export async function createReceivingCallerFixture(options: { reportsRecipe?: bo
|
||||
const sinks = new Map<string, StructuredAgentSessionEventSink>()
|
||||
let generation = 0
|
||||
rig.adapter.acquire.mockImplementation(async (input) => {
|
||||
const recipe: ClaudeAccountRecipe = input.accountRecipe ?? {
|
||||
route: 'system',
|
||||
home: selected.path,
|
||||
configDir: selected.path
|
||||
}
|
||||
// Production launch resolution picks the account, as the Claude adapter's acquisition does.
|
||||
const launched = await accounts.launch(input)
|
||||
if (input.events) {
|
||||
sinks.set(input.identity.sessionId, input.events)
|
||||
}
|
||||
return {
|
||||
acquisitionGeneration: `caller-generation-${++generation}`,
|
||||
accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: recipe.home },
|
||||
...(options.reportsRecipe === false ? {} : { accountRecipe: recipe }),
|
||||
...launched,
|
||||
process: {
|
||||
hostId: 'local',
|
||||
pid: 4242,
|
||||
@@ -85,7 +91,8 @@ export async function createReceivingCallerFixture(options: { reportsRecipe?: bo
|
||||
},
|
||||
link: {
|
||||
linkId: `caller-link-${generation}`,
|
||||
handle: claudeProviderHandle(`provider-${input.identity.sessionId}`, null),
|
||||
// A chat that has answered has a leaf, which a resume elsewhere is checked against.
|
||||
handle: claudeProviderHandle(`provider-${input.identity.sessionId}`, 'leaf-1'),
|
||||
origin: rig.store.getRecord(input.identity.sessionId)?.providerHandleChain.length
|
||||
? 'resumed'
|
||||
: 'created',
|
||||
@@ -113,7 +120,7 @@ export async function createReceivingCallerFixture(options: { reportsRecipe?: bo
|
||||
},
|
||||
provider: 'claude',
|
||||
agent: 'claude',
|
||||
accountHome: HOME_A,
|
||||
accountHome: accounts.homeA,
|
||||
providerHandle: { kind: 'claude', sessionId: `provider-${id}`, leafUuid: null }
|
||||
})
|
||||
const ensure = async (id = PARENT) => {
|
||||
@@ -189,7 +196,7 @@ export async function createReceivingCallerFixture(options: { reportsRecipe?: bo
|
||||
)
|
||||
await rig.host.flushStreamedEvents(PARENT)
|
||||
}
|
||||
const createWorker = async (id: typeof WORKER | typeof HELPER, creator = PARENT) => {
|
||||
const createWorker = async (id: typeof WORKER, creator = PARENT) => {
|
||||
const from = caller(creator)
|
||||
const taskSpec = `work for ${id}`
|
||||
const { bindRun, helperCreator } = resolveWorkerStartRun(service, {
|
||||
@@ -269,16 +276,12 @@ export async function createReceivingCallerFixture(options: { reportsRecipe?: bo
|
||||
report,
|
||||
sinks,
|
||||
nudges,
|
||||
selectB: () => {
|
||||
selected = HOME_B
|
||||
},
|
||||
...receivingPersistedFixtures({ rig, params }),
|
||||
...accounts,
|
||||
selectB: () => accounts.select('b'),
|
||||
found: async () => {
|
||||
await ensure()
|
||||
await rig.store.setSessionTabVisibility(PARENT, true)
|
||||
if (options.reportsRecipe !== false) {
|
||||
expect(rig.store.requireWritableRecord(PARENT).acquiredAccount).toBeDefined()
|
||||
}
|
||||
expect(rig.store.requireWritableRecord(PARENT).acquiredAccount).toBeDefined()
|
||||
},
|
||||
dispose: async (
|
||||
stopHost = () => rig.host.flushAllStreamedEvents(),
|
||||
@@ -286,6 +289,7 @@ export async function createReceivingCallerFixture(options: { reportsRecipe?: bo
|
||||
) => {
|
||||
service.stopOrchestrationFederationRelay()
|
||||
setStructuredAgentSessionHost(null)
|
||||
accounts.uninstall()
|
||||
structuredWorkerIdentities.clear()
|
||||
await stopHost()
|
||||
service.getOrchestrationDbIfAvailable()?.close()
|
||||
|
||||
+1
-50
@@ -6,7 +6,6 @@ import { REST_TEST_CALLER } from './structured-agent-session-rest-test-rig'
|
||||
import { hostTestMessage, hostTestOperationId } from './structured-agent-session-host-test-data'
|
||||
import {
|
||||
createReceivingCallerFixture,
|
||||
HOME_B,
|
||||
PARENT
|
||||
} from './structured-agent-session-receiving-callers.test-support'
|
||||
|
||||
@@ -16,7 +15,7 @@ it('finishes an owned ordinary open but direct cancellation publishes no child',
|
||||
const release = Promise.withResolvers<void>()
|
||||
try {
|
||||
await f.found()
|
||||
await f.coldNative()
|
||||
await f.rig.host.close(PARENT, 'evict')
|
||||
f.selectB()
|
||||
const original = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))
|
||||
const open = AgentSessionJournal.prototype.open
|
||||
@@ -51,54 +50,6 @@ it('finishes an owned ordinary open but direct cancellation publishes no child',
|
||||
}
|
||||
})
|
||||
|
||||
it('a real Stop remains responsive while a background start awaits the selected resolver', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
const release = Promise.withResolvers<void>()
|
||||
try {
|
||||
await f.found()
|
||||
await f.rig.host.close(PARENT, 'evict')
|
||||
const original = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))
|
||||
const resolution = vi
|
||||
.spyOn(f.rig.host.deps, 'launchAccountHome')
|
||||
.mockImplementation(async () => {
|
||||
await release.promise
|
||||
return HOME_B
|
||||
})
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
f.rig.adapter.dispatch.mockClear()
|
||||
const id = await f.accept('cancel this background start')
|
||||
await vi.waitFor(() => expect(resolution).toHaveBeenCalled())
|
||||
const stopped = await f.rig.host.cancel(REST_TEST_CALLER, {
|
||||
envelope: {
|
||||
sessionId: PARENT,
|
||||
clientOperationId: hostTestOperationId(),
|
||||
expectedRuntimeFence: f.rig.store.requireWritableRecord(PARENT).lease.runtimeFence,
|
||||
payloadFingerprint: computeAgentSessionPayloadFingerprint({
|
||||
method: 'agentSession.cancel',
|
||||
sessionId: PARENT,
|
||||
fields: {}
|
||||
})
|
||||
}
|
||||
})
|
||||
expect(stopped).toMatchObject({ ok: true, value: { cancelled: true } })
|
||||
release.resolve()
|
||||
await vi.waitFor(() =>
|
||||
expect(f.rig.host.collaboratorsForTests().runtimeState.startFlights.has(PARENT)).toBe(false)
|
||||
)
|
||||
expect(f.rig.adapter.acquire).not.toHaveBeenCalled()
|
||||
expect(f.rig.adapter.dispatch).not.toHaveBeenCalled()
|
||||
expect(
|
||||
f.rig.host.collaboratorsForTests().sessions.get(PARENT)?.journal.submission(id)
|
||||
).toMatchObject({ rejection: { kind: 'cancelled' } })
|
||||
expect(acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe).toEqual(
|
||||
original?.recipe
|
||||
)
|
||||
} finally {
|
||||
release.resolve()
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('ensure and ordinary send share the journal refusal; retry retains history without a failed spawn', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
|
||||
+13
-205
@@ -1,42 +1,29 @@
|
||||
import { eraseRpcMethods, isStreamingMethod } from '../../runtime/rpc/core'
|
||||
import { STRUCTURED_AGENT_SESSION_OPTIONS_READ_METHODS } from '../../runtime/rpc/methods/structured-agent-session-options-read'
|
||||
import {
|
||||
type AgentModelCatalogSuccess,
|
||||
AgentModelCatalogStore
|
||||
} from '../agent-model-catalog/agent-model-catalog-store'
|
||||
import type { AgentModelCatalogProbe } from '../agent-model-catalog/agent-model-catalog-discovery'
|
||||
import { rm } from 'node:fs/promises'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session/lifecycle/agent-session-mutation-envelope'
|
||||
import { REST_TEST_CALLER } from './structured-agent-session-rest-test-rig'
|
||||
import { hostTestOperationId } from './structured-agent-session-host-test-data'
|
||||
import {
|
||||
catalogMutationDeadline as settled,
|
||||
disposeCatalogMutationHost
|
||||
} from './structured-agent-session-catalog-mutation.test-support'
|
||||
import { catalogMutationDeadline as settled } from './structured-agent-session-catalog-mutation.test-support'
|
||||
import { createAgentModelCatalogService } from '../agent-model-catalog/agent-model-catalog-service'
|
||||
import {
|
||||
agentModelCatalogFingerprint,
|
||||
agentModelCatalogScopeFingerprint
|
||||
} from '../agent-model-catalog/agent-model-catalog-fingerprint'
|
||||
import { structuredAgentModelCatalogAccountReads } from '../../runtime/structured-agent-model-catalog-wiring'
|
||||
import { readJournalSessionEpoch } from '../agent-session-journal/journal-row-table'
|
||||
import { setStructuredAgentSessionHost } from './structured-agent-session-registry'
|
||||
import {
|
||||
createReceivingCallerFixture,
|
||||
HOME_A,
|
||||
HOME_B,
|
||||
PARENT
|
||||
} from './structured-agent-session-receiving-callers.test-support'
|
||||
|
||||
function catalog(
|
||||
f: Awaited<ReturnType<typeof createReceivingCallerFixture>>,
|
||||
_countSavedScope = false
|
||||
) {
|
||||
function catalog(f: Awaited<ReturnType<typeof createReceivingCallerFixture>>) {
|
||||
const store = new AgentModelCatalogStore()
|
||||
for (const [home, id] of [
|
||||
[HOME_A, 'claude-sonnet-5'],
|
||||
[HOME_B, 'claude-opus-5-5[1m]']
|
||||
[f.homeA, 'claude-sonnet-5'],
|
||||
[f.homeB, 'claude-opus-5-5[1m]']
|
||||
] as const) {
|
||||
store.recordSuccess(
|
||||
agentModelCatalogScopeFingerprint(
|
||||
@@ -67,7 +54,7 @@ function catalog(
|
||||
getRecord: (id) => f.rig.store.getRecord(id) ?? undefined,
|
||||
recordWorkspacePath: async () => f.rig.root,
|
||||
drivesRecord: () => true,
|
||||
resolveAccountHome: async () => HOME_B,
|
||||
resolveAccountHome: async () => f.homeB,
|
||||
...structuredAgentModelCatalogAccountReads(() => f.rig.host),
|
||||
probes: { claude: Object.assign(probe, { resolve }) },
|
||||
agentReadsProjectModelConfig: () => false
|
||||
@@ -75,195 +62,16 @@ function catalog(
|
||||
f.rig.host.deps.modelCatalog = service
|
||||
const demands = vi.spyOn(service, 'demand')
|
||||
const read = () => f.rig.host.readModelCatalog({ agent: 'claude', sessionId: PARENT })
|
||||
const completed = async (viaRpc = false) => {
|
||||
if (viaRpc) {
|
||||
const method = eraseRpcMethods(STRUCTURED_AGENT_SESSION_OPTIONS_READ_METHODS).find(
|
||||
(entry) => entry.name === 'agentSession.modelCatalog'
|
||||
)
|
||||
if (!method?.params || isStreamingMethod(method)) {
|
||||
throw new Error('named catalog RPC is not installed')
|
||||
}
|
||||
await method.handler(method.params.parse({ agent: 'claude', sessionId: PARENT }), {
|
||||
runtime: f.runtime
|
||||
})
|
||||
} else {
|
||||
await read()
|
||||
}
|
||||
const claim = demands.mock.results.at(-1)?.value
|
||||
if (claim) {
|
||||
await settled(claim, 'named catalog demand completion')
|
||||
}
|
||||
const request = demands.mock.calls.at(-1)?.[0]
|
||||
return request ? service.snapshot(request) : { origin: 'unknown' as const }
|
||||
}
|
||||
return {
|
||||
service,
|
||||
store,
|
||||
probe,
|
||||
resolve,
|
||||
demands,
|
||||
read,
|
||||
ids: async (viaRpc = false) => {
|
||||
const result = await completed(viaRpc)
|
||||
expect(result.origin).not.toBe('unknown')
|
||||
if (result.origin === 'unknown') {
|
||||
throw new Error('catalog unexpectedly unknown')
|
||||
}
|
||||
return result.models.map((model) => model.id)
|
||||
}
|
||||
read
|
||||
}
|
||||
}
|
||||
|
||||
describe('catalog consumes the constructed host receiving account', () => {
|
||||
it('reads A before exact native disposition and B afterward, without the global registry', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
let service: ReturnType<typeof createAgentModelCatalogService> | undefined
|
||||
try {
|
||||
await f.found()
|
||||
const { started } = await f.coldNative()
|
||||
f.selectB()
|
||||
setStructuredAgentSessionHost(null)
|
||||
const c = catalog(f)
|
||||
service = c.service
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
const all = vi.spyOn(f.rig.store, 'listRecords').mockImplementation(() => {
|
||||
throw new Error('global history scan')
|
||||
})
|
||||
expect(await c.ids()).toEqual(['claude-sonnet-5'])
|
||||
expect((await f.rig.host.readOptions(PARENT)).current.model).toBe('claude-sonnet-5')
|
||||
expect(f.rig.host.hasSession(PARENT)).toBe(true)
|
||||
const session = f.rig.host.collaboratorsForTests().sessions.get(PARENT)
|
||||
if (!session) {
|
||||
throw new Error('existing journal was not adopted')
|
||||
}
|
||||
const visits = vi.spyOn(session.journal, 'visitItemsWithLinkage')
|
||||
await c.read()
|
||||
expect(visits).not.toHaveBeenCalled()
|
||||
const db = f.runtime.getOrchestrationDb()
|
||||
db.failWorkerStart(started.dispatch.id, 'agent_readiness', 'never constructed a worker')
|
||||
expect(await c.ids()).toEqual(['claude-opus-5-5[1m]'])
|
||||
expect((await f.rig.host.readOptions(PARENT)).current.model).toBe('claude-opus-5-5[1m]')
|
||||
expect(c.probe).not.toHaveBeenCalled()
|
||||
expect(f.rig.adapter.acquire).not.toHaveBeenCalled()
|
||||
all.mockRestore()
|
||||
} finally {
|
||||
service?.stop()
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('a proven absent journal still reads A from actual success and pre-notice work without founding one', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
let service: ReturnType<typeof createAgentModelCatalogService> | undefined
|
||||
try {
|
||||
await f.proveWithoutJournal()
|
||||
await f.coldNative()
|
||||
f.selectB()
|
||||
const c = catalog(f)
|
||||
service = c.service
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
expect(await c.ids()).toEqual(['claude-sonnet-5'])
|
||||
expect(readJournalSessionEpoch(f.rig.host.deps.journalDatabase.db, PARENT)).toBeNull()
|
||||
expect(f.rig.host.hasSession(PARENT)).toBe(false)
|
||||
expect(c.probe).not.toHaveBeenCalled()
|
||||
expect(f.rig.adapter.acquire).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
service?.stop()
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('real prospective read failure answers unknown instead of using B cached facts', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
let service: ReturnType<typeof createAgentModelCatalogService> | undefined
|
||||
try {
|
||||
await f.found()
|
||||
await f.coldNative()
|
||||
f.selectB()
|
||||
const c = catalog(f)
|
||||
service = c.service
|
||||
const db = f.runtime.getOrchestrationDb()
|
||||
const prepare = db.db.prepare.bind(db.db)
|
||||
vi.spyOn(db.db, 'prepare').mockImplementation((sql) => {
|
||||
if (sql.includes('SELECT id FROM runs WHERE coordinator_orca_session_id')) {
|
||||
throw new Error('native read unavailable')
|
||||
}
|
||||
return prepare(sql)
|
||||
})
|
||||
expect(await c.read()).toEqual({ origin: 'unknown' })
|
||||
expect(c.probe).not.toHaveBeenCalled()
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toBeUndefined()
|
||||
} finally {
|
||||
service?.stop()
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
// Real journal/native DB setup, two 2s mutations and bounded host cleanup share this budget.
|
||||
it('owned permission settlement reads actual A until exact native disposition, then eligible B', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
let service: ReturnType<typeof createAgentModelCatalogService> | undefined
|
||||
try {
|
||||
await f.found()
|
||||
const { started } = await f.coldNative()
|
||||
f.selectB()
|
||||
setStructuredAgentSessionHost(null)
|
||||
const c = catalog(f)
|
||||
service = c.service
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
const all = vi.spyOn(f.rig.store, 'listRecords').mockImplementation(() => {
|
||||
throw new Error('global history scan')
|
||||
})
|
||||
const pick = async () => {
|
||||
const key = 'permissionMode'
|
||||
const value = 'own'
|
||||
expect(
|
||||
await settled(
|
||||
f.rig.host.setOption(REST_TEST_CALLER, {
|
||||
key,
|
||||
value,
|
||||
envelope: {
|
||||
sessionId: PARENT,
|
||||
clientOperationId: hostTestOperationId(),
|
||||
expectedRuntimeFence: f.rig.store.requireWritableRecord(PARENT).lease.runtimeFence,
|
||||
payloadFingerprint: computeAgentSessionPayloadFingerprint({
|
||||
method: 'agentSession.setOption',
|
||||
sessionId: PARENT,
|
||||
fields: { key, value }
|
||||
})
|
||||
}
|
||||
}),
|
||||
'receiving-account permission mutation'
|
||||
)
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: { key, value, options: { permissionMode: 'own' } }
|
||||
})
|
||||
expect(f.rig.store.requireWritableRecord(PARENT).permissionMode).toBe('own')
|
||||
return undefined
|
||||
}
|
||||
await pick()
|
||||
expect(await c.ids()).toEqual(['claude-sonnet-5'])
|
||||
f.runtime
|
||||
.getOrchestrationDb()
|
||||
.failWorkerStart(started.dispatch.id, 'agent_readiness', 'never constructed a worker')
|
||||
await pick()
|
||||
expect(await c.ids()).toEqual(['claude-opus-5-5[1m]'])
|
||||
expect(c.probe).not.toHaveBeenCalled()
|
||||
expect(f.rig.adapter.acquire).not.toHaveBeenCalled()
|
||||
expect(f.rig.adapter.dispatch).not.toHaveBeenCalled()
|
||||
expect(f.rig.adapter.readOptions).not.toHaveBeenCalled()
|
||||
expect(all).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
service?.stop()
|
||||
await f.dispose(
|
||||
() => disposeCatalogMutationHost(f.rig),
|
||||
() => rm(f.rig.root, { recursive: true, force: true })
|
||||
)
|
||||
}
|
||||
}, 10_000)
|
||||
})
|
||||
|
||||
// These operations run the real host owner and catalog claim; only external provider IO is scripted.
|
||||
it('keeps newer public intent while discovery waits and reports a failed listing without holding Stop', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
@@ -273,7 +81,7 @@ it('keeps newer public intent while discovery waits and reports a failed listing
|
||||
await f.found()
|
||||
await f.rig.host.close(PARENT, 'evict')
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
const c = catalog(f, true)
|
||||
const c = catalog(f)
|
||||
service = c.service
|
||||
c.store.expireAgent('claude')
|
||||
c.probe.mockImplementationOnce(() => listing.promise)
|
||||
@@ -330,7 +138,7 @@ it('keeps newer public intent while discovery waits and reports a failed listing
|
||||
expect(
|
||||
c.store.failureDetail(
|
||||
agentModelCatalogScopeFingerprint(
|
||||
agentModelCatalogFingerprint({ agent: 'claude', accountHome: HOME_B, wslDistro: null }),
|
||||
agentModelCatalogFingerprint({ agent: 'claude', accountHome: f.homeB, wslDistro: null }),
|
||||
f.rig.root
|
||||
)
|
||||
)
|
||||
@@ -369,12 +177,12 @@ it.each(['deadline', 'retirement', 'stop', 'workspace'] as const)(
|
||||
async (end) => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
let service: ReturnType<typeof createAgentModelCatalogService> | undefined
|
||||
const home = Promise.withResolvers<typeof HOME_B>()
|
||||
const home = Promise.withResolvers<typeof f.homeB>()
|
||||
try {
|
||||
await f.found()
|
||||
await f.rig.host.close(PARENT, 'evict')
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
const c = catalog(f, true)
|
||||
const c = catalog(f)
|
||||
service = c.service
|
||||
const selected = vi.spyOn(f.rig.host.deps, 'launchAccountHome').mockReturnValue(home.promise)
|
||||
let workspaceIdentity = 'original'
|
||||
@@ -408,14 +216,14 @@ it.each(['deadline', 'retirement', 'stop', 'workspace'] as const)(
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
expect(await settled(pending, 'original scope deadline')).toEqual({ origin: 'unknown' })
|
||||
}
|
||||
home.resolve(HOME_B)
|
||||
home.resolve(f.homeB)
|
||||
expect(await settled(pending, 'retired scope completion')).toEqual({ origin: 'unknown' })
|
||||
expect(c.demands).not.toHaveBeenCalled()
|
||||
expect(c.resolve).not.toHaveBeenCalled()
|
||||
expect(c.probe).not.toHaveBeenCalled()
|
||||
expect(f.rig.adapter.acquire).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
home.resolve(HOME_B)
|
||||
home.resolve(f.homeB)
|
||||
service?.stop()
|
||||
vi.useRealTimers()
|
||||
await f.dispose()
|
||||
|
||||
-156
@@ -1,156 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { acquiredAgentSessionAccount } from '../../../shared/agent-session-acquired-account'
|
||||
import { readJournalSessionEpoch } from '../agent-session-journal/journal-row-table'
|
||||
import {
|
||||
createReceivingCallerFixture,
|
||||
HOME_A,
|
||||
HOME_B,
|
||||
PARENT
|
||||
} from './structured-agent-session-receiving-callers.test-support'
|
||||
|
||||
describe('registered ensure constructs from cold conversation-owned evidence', () => {
|
||||
it('opens existing native state and journal before reservation, then proves the actual A recipe', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
const original = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))
|
||||
expect(original?.recipe.home).toBe(HOME_A.path)
|
||||
await f.coldNative()
|
||||
expect(f.runtime.getOrchestrationDbIfAvailable()).toBeNull()
|
||||
f.selectB()
|
||||
const adopts = vi.spyOn(f.rig.host.collaboratorsForTests().sessions, 'set')
|
||||
const acquire = f.rig.adapter.acquire
|
||||
acquire.mockClear()
|
||||
expect(await f.ensure()).toMatchObject({ ok: true })
|
||||
expect(acquire).toHaveBeenCalledTimes(1)
|
||||
expect(acquire.mock.calls[0]?.[0].accountRecipe).toEqual(original?.recipe)
|
||||
expect(
|
||||
acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe
|
||||
).toEqual(original?.recipe)
|
||||
expect(f.runtime.getOrchestrationDbIfAvailable()).not.toBeNull()
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(HOME_A)
|
||||
expect(adopts).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('a last-success receipt alone does not pin an eligible ordinary acquisition', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
await f.rig.host.close(PARENT, 'evict')
|
||||
f.selectB()
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
expect(await f.ensure()).toMatchObject({ ok: true })
|
||||
expect(f.rig.adapter.acquire.mock.calls[0]?.[0].accountRecipe).toBeUndefined()
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(HOME_B)
|
||||
expect(
|
||||
acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe.home
|
||||
).toBe(HOME_B.path)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it.each([true, false])(
|
||||
'absent journal keeps native evidence, reportsRecipe=%s',
|
||||
async (reportsRecipe) => {
|
||||
const f = await createReceivingCallerFixture({ reportsRecipe })
|
||||
try {
|
||||
await f.proveWithoutJournal()
|
||||
expect(readJournalSessionEpoch(f.rig.host.deps.journalDatabase.db, PARENT)).toBeNull()
|
||||
await f.coldNative()
|
||||
f.selectB()
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
expect(await f.ensure()).toMatchObject({ ok: true })
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(reportsRecipe ? HOME_A : HOME_B)
|
||||
expect(f.rig.adapter.acquire.mock.calls[0]?.[0].accountRecipe?.home).toBe(
|
||||
reportsRecipe ? HOME_A.path : undefined
|
||||
)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('an actually unreadable native DB fails the operation without constructing or overwriting A', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
await f.coldNative()
|
||||
f.selectB()
|
||||
const record = f.rig.store.requireWritableRecord(PARENT)
|
||||
const db = f.runtime.getExistingOrchestrationDb()
|
||||
if (!db) {
|
||||
throw new Error('persisted database missing')
|
||||
}
|
||||
const prepare = db.db.prepare.bind(db.db)
|
||||
const read = vi.spyOn(db.db, 'prepare').mockImplementation((sql) => {
|
||||
if (sql.includes('SELECT id FROM runs WHERE coordinator_orca_session_id')) {
|
||||
throw new Error('fixture native read unavailable')
|
||||
}
|
||||
return prepare(sql)
|
||||
})
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
expect(await f.ensure()).toEqual({
|
||||
ok: false,
|
||||
refusal: {
|
||||
code: 'agent_session_operation_invalid',
|
||||
details: { ownerVerdict: 'exited' },
|
||||
ownerVerdict: 'exited',
|
||||
message: "Claude couldn't restart. Send your message to try again."
|
||||
}
|
||||
})
|
||||
read.mockRestore()
|
||||
expect(f.rig.adapter.acquire).not.toHaveBeenCalled()
|
||||
const after = f.rig.store.requireWritableRecord(PARENT)
|
||||
expect(after.lease.claimStatus).toBe('released')
|
||||
expect(acquiredAgentSessionAccount(after)?.recipe).toEqual(
|
||||
acquiredAgentSessionAccount(record)?.recipe
|
||||
)
|
||||
expect(await f.ensure()).toMatchObject({ ok: true })
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(HOME_A)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('direct cancellation during selected resolution starts nothing and preserves last success', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
await f.rig.host.close(PARENT, 'evict')
|
||||
const receipt = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))
|
||||
let release: (() => void) | undefined
|
||||
const waiting = new Promise<void>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
const resolveAccount = vi
|
||||
.spyOn(f.rig.host.deps, 'launchAccountHome')
|
||||
.mockImplementation(async () => {
|
||||
await waiting
|
||||
return HOME_B
|
||||
})
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
const result = f.ensure().then(
|
||||
(value) => ({ value }),
|
||||
(error: unknown) => ({ error })
|
||||
)
|
||||
await vi.waitFor(() => expect(resolveAccount).toHaveBeenCalled())
|
||||
f.rig.host
|
||||
.collaboratorsForTests()
|
||||
.runtimeState.acquireAborts.abort(PARENT, 'stopped while starting')
|
||||
release?.()
|
||||
await result
|
||||
expect(f.rig.adapter.acquire).not.toHaveBeenCalled()
|
||||
expect(
|
||||
acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe
|
||||
).toEqual(receipt?.recipe)
|
||||
expect(f.rig.store.requireWritableRecord(PARENT).lease.claimStatus).toBe('released')
|
||||
expect(readJournalSessionEpoch(f.rig.host.deps.journalDatabase.db, PARENT)).not.toBeNull()
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
-142
@@ -1,142 +0,0 @@
|
||||
import { agentJournalSubmissionKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { dispatchReportMailbox } from '../../runtime/orchestration/dispatch-report-mailbox'
|
||||
import { OrchestrationStructuredMailboxPointerDelivery } from '../../runtime/orchestration/structured-mailbox-pointer-delivery'
|
||||
import { createStructuredMailboxPointerHost } from '../../runtime/orchestration/structured-mailbox-pointer-host'
|
||||
import { HOST_TEST_NOW } from './structured-agent-session-host-test-data'
|
||||
import {
|
||||
createReceivingCallerFixture,
|
||||
HELPER,
|
||||
HOME_A,
|
||||
HOME_B,
|
||||
PARENT,
|
||||
WORKER
|
||||
} from './structured-agent-session-receiving-callers.test-support'
|
||||
|
||||
/** Production report transaction -> pointer park/wake -> host start/handover/settlement. */
|
||||
describe('nested receiving work follows its current consumer', () => {
|
||||
it('keeps A after creator Stop, accepts its helper result, then ordinary input acquires B', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(HOST_TEST_NOW)
|
||||
const f = await createReceivingCallerFixture()
|
||||
let unsubscribe: (() => void) | undefined
|
||||
try {
|
||||
await f.found()
|
||||
const db = f.runtime.getOrchestrationDb()
|
||||
const run = db.createRun({
|
||||
objective: 'nested production iteration',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: PARENT
|
||||
})
|
||||
const worker = await f.createWorker(WORKER)
|
||||
const helper = await f.createWorker(HELPER, WORKER)
|
||||
expect(helper.task.id).not.toBe(worker.task.id)
|
||||
expect(dispatchReportMailbox(db, helper.dispatch)).toBe(`dispatch:${worker.dispatch.id}`)
|
||||
const stopped = await f.call('orchestration.workerStop', { dispatch: worker.dispatch.id })
|
||||
expect(stopped).toMatchObject({ state: 'stopped', processAction: 'closed_agent_terminal' })
|
||||
expect(db.getDispatchContextById(helper.dispatch.id)?.status).toBe('dispatched')
|
||||
expect(dispatchReportMailbox(db, helper.dispatch)).toBe(`run:${run.id}`)
|
||||
await f.rig.host.close(PARENT, 'evict')
|
||||
f.selectB()
|
||||
f.rig.adapter.acquire.mockClear()
|
||||
const ordinary = await f.send('continue while the helper works')
|
||||
await f.turn(ordinary, 'running')
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(HOME_A)
|
||||
expect(f.rig.adapter.acquire.mock.calls[0]?.[0].accountRecipe?.home).toBe(HOME_A.path)
|
||||
|
||||
const nudges = f.nudges
|
||||
await f.call(
|
||||
'orchestration.send',
|
||||
{
|
||||
from: helper.handle,
|
||||
to: `run:${run.id}`,
|
||||
type: 'status',
|
||||
subject: 'finishing helper work'
|
||||
},
|
||||
f.caller(HELPER)
|
||||
)
|
||||
const batch = db.getOrCreateMailboxDelivery({
|
||||
runId: run.id,
|
||||
mailboxHandle: `run:${run.id}`,
|
||||
consumerGeneration: run.consumer_generation
|
||||
})
|
||||
if (!batch) {
|
||||
throw new Error('real status not accepted into the current Run')
|
||||
}
|
||||
expect(batch.messages.map((message) => message.to_handle)).toEqual([`run:${run.id}`])
|
||||
expect(batch.messages.map((message) => message.type)).toEqual(['status'])
|
||||
await f.report(helper)
|
||||
expect(nudges).toHaveBeenCalledWith(`run:${run.id}`, 'worker_done')
|
||||
expect(db.getWorkerDispatch(helper.dispatch.id)?.state).toBe('succeeded')
|
||||
const retained = vi.fn()
|
||||
const pointer = new OrchestrationStructuredMailboxPointerDelivery({
|
||||
getDb: () => db,
|
||||
getMessageWaiters: () => undefined,
|
||||
resolveStructuredTarget: (handle) => f.runtime.mailTarget(handle),
|
||||
getCliCommand: () => 'orca-dev',
|
||||
senderSnapshot: () => ({ name: null, agent: null }),
|
||||
host: createStructuredMailboxPointerHost(),
|
||||
onRetain: retained
|
||||
})
|
||||
unsubscribe = await f.rig.host.subscribe({
|
||||
id: 'real-pointer-wake',
|
||||
sessionId: PARENT,
|
||||
emit: () => pointer.onJournalActivity(PARENT)
|
||||
})
|
||||
const dispatches = f.rig.adapter.dispatch.mock.calls.length
|
||||
expect(pointer.deliverForHandle(`run:${run.id}`)).toBe(true)
|
||||
await vi.waitFor(() =>
|
||||
expect(retained).toHaveBeenCalledWith(expect.objectContaining({ reason: 'turn-unsettled' }))
|
||||
)
|
||||
expect(f.rig.adapter.dispatch).toHaveBeenCalledTimes(dispatches)
|
||||
await f.turn(ordinary, 'completed')
|
||||
await vi.waitFor(() => expect(f.rig.adapter.dispatch.mock.calls.length).toBe(dispatches + 1))
|
||||
const journal = f.rig.host.collaboratorsForTests().sessions.get(PARENT)?.journal
|
||||
if (!journal) {
|
||||
throw new Error('actual opened parent journal missing')
|
||||
}
|
||||
const notice = journal.submissions().find((submission) => {
|
||||
const body = journal.itemBody(agentJournalSubmissionKey(submission.clientMessageId))
|
||||
return body?.kind === 'message' && body.from?.orchestration?.message === 'mail-notice'
|
||||
})
|
||||
if (!notice) {
|
||||
throw new Error('production pointer did not submit its canonical notice')
|
||||
}
|
||||
await f.turn(notice.clientMessageId, 'running')
|
||||
db.acknowledgeMailboxDelivery({
|
||||
runId: run.id,
|
||||
mailboxHandle: `run:${run.id}`,
|
||||
consumerGeneration: run.consumer_generation,
|
||||
deliveryId: batch.delivery.id
|
||||
})
|
||||
const resultBatch = db.getOrCreateMailboxDelivery({
|
||||
runId: run.id,
|
||||
mailboxHandle: `run:${run.id}`,
|
||||
consumerGeneration: run.consumer_generation
|
||||
})
|
||||
if (!resultBatch) {
|
||||
throw new Error('real report not accepted into the current Run')
|
||||
}
|
||||
expect(resultBatch.messages.map((message) => message.to_handle)).toEqual([`run:${run.id}`])
|
||||
expect(resultBatch.messages.map((message) => message.type)).toEqual(['worker_done'])
|
||||
db.acknowledgeMailboxDelivery({
|
||||
runId: run.id,
|
||||
mailboxHandle: `run:${run.id}`,
|
||||
consumerGeneration: run.consumer_generation,
|
||||
deliveryId: resultBatch.delivery.id
|
||||
})
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A)
|
||||
await f.turn('unrelated-newer', 'completed')
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A)
|
||||
await f.turn(notice.clientMessageId, 'completed')
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_B)
|
||||
const next = await f.send('next eligible ordinary input')
|
||||
expect(f.rig.host.childAccountHome(PARENT)).toEqual(HOME_B)
|
||||
expect(f.rig.adapter.acquire).toHaveBeenCalledTimes(2)
|
||||
await f.turn(next, 'completed')
|
||||
} finally {
|
||||
unsubscribe?.()
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
import { join } from 'node:path'
|
||||
import { Store } from '../../persistence/loading-store/store'
|
||||
import { ProfileStateSqliteAuthority } from '../../persistence/profile-state/profile-state-sqlite-authority'
|
||||
import { expect } from 'vitest'
|
||||
import { OrchestrationDb } from '../../runtime/orchestration/db'
|
||||
import { REST_TEST_CALLER, type RestTestRig } from './structured-agent-session-rest-test-rig'
|
||||
import { hostTestOperationId } from './structured-agent-session-host-test-data'
|
||||
import type { AgentSessionAttachParams } from './structured-agent-session-attach'
|
||||
import { HOME_A, PARENT } from './structured-agent-session-receiving-callers.test-support'
|
||||
|
||||
/** The registered attach path reads launch defaults from the runtime's profile store. */
|
||||
export function receivingRuntimeStore(root: string) {
|
||||
return new Store({
|
||||
dataFile: join(root, 'runtime-state.json'),
|
||||
profileStateAuthority: new ProfileStateSqliteAuthority(
|
||||
join(root, 'runtime-profile.db'),
|
||||
'receiving'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/** Build persisted success/pre-notice state with the real store and database owners. */
|
||||
export function receivingPersistedFixtures({
|
||||
rig,
|
||||
params
|
||||
}: {
|
||||
rig: RestTestRig
|
||||
params: () => AgentSessionAttachParams
|
||||
}) {
|
||||
return {
|
||||
proveWithoutJournal: async () => {
|
||||
const input = params()
|
||||
await rig.store.reserveOwner({
|
||||
sessionId: PARENT,
|
||||
location: input.location,
|
||||
provider: 'claude',
|
||||
accountHome: HOME_A,
|
||||
expectedFence: null,
|
||||
spawnToken: 'pre-journal-spawn',
|
||||
claimKeyId: 'key-1',
|
||||
handoffOperationId: null,
|
||||
probe: { outcome: 'reservation-unused' },
|
||||
now: rig.clock.now,
|
||||
operation: {
|
||||
callerKey: REST_TEST_CALLER.callerKey,
|
||||
operationId: hostTestOperationId(),
|
||||
fingerprint: 'pre-journal-success'
|
||||
}
|
||||
})
|
||||
const record = rig.store.requireWritableRecord(PARENT)
|
||||
const acquired = await rig.adapter.acquire({
|
||||
identity: {
|
||||
sessionId: PARENT,
|
||||
workspaceId: input.location.workspaceId,
|
||||
hostId: 'local',
|
||||
agent: 'claude',
|
||||
providerHandle: null
|
||||
},
|
||||
fence: record.lease.runtimeFence,
|
||||
spawnToken: 'pre-journal-spawn'
|
||||
})
|
||||
await rig.store.commitProcessIdentity({
|
||||
sessionId: PARENT,
|
||||
fence: record.lease.runtimeFence,
|
||||
process: acquired.process,
|
||||
now: rig.clock.now
|
||||
})
|
||||
await rig.store.proveOwner({
|
||||
sessionId: PARENT,
|
||||
fence: record.lease.runtimeFence,
|
||||
...(acquired.link ? { link: acquired.link } : {}),
|
||||
now: rig.clock.now,
|
||||
...(acquired.accountRecipe
|
||||
? {
|
||||
accountAcquisition: {
|
||||
generation: acquired.acquisitionGeneration,
|
||||
recipe: acquired.accountRecipe
|
||||
}
|
||||
}
|
||||
: {})
|
||||
})
|
||||
await rig.store.evictProvenDeadOwner({
|
||||
sessionId: PARENT,
|
||||
expectedFence: record.lease.runtimeFence,
|
||||
probe: { outcome: 'exit-observed' },
|
||||
now: rig.clock.now
|
||||
})
|
||||
expect(rig.store.requireWritableRecord(PARENT).lease).toMatchObject({
|
||||
claimStatus: 'released',
|
||||
ownerProcess: null,
|
||||
deathEvidence: { kind: 'exit-observed' }
|
||||
})
|
||||
await rig.store.setSessionTabVisibility(PARENT, true)
|
||||
},
|
||||
coldNative: async () => {
|
||||
await rig.host.close(PARENT, 'evict')
|
||||
expect(rig.host.hasSession(PARENT)).toBe(false)
|
||||
const db = new OrchestrationDb(join(rig.root, 'orchestration.db'))
|
||||
const run = db.createRun({
|
||||
objective: 'parent native work',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: PARENT
|
||||
})
|
||||
const started = db.createStartingWorkerDispatch({
|
||||
taskSpec: 'pre-notice',
|
||||
taskRunId: run.id,
|
||||
creator: { kind: 'session', orcaSessionId: PARENT },
|
||||
maxDepth: 9,
|
||||
startOptions: {}
|
||||
})
|
||||
db.close()
|
||||
return { run, started }
|
||||
}
|
||||
}
|
||||
}
|
||||
-146
@@ -1,146 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture'
|
||||
import { dispatchReportMailbox } from '../../runtime/orchestration/dispatch-report-mailbox'
|
||||
import {
|
||||
createReceivingCallerFixture,
|
||||
HELPER,
|
||||
HOME_A,
|
||||
HOME_B,
|
||||
PARENT,
|
||||
WORKER
|
||||
} from './structured-agent-session-receiving-callers.test-support'
|
||||
|
||||
const NEXT = testOrcaSessionId('d2e4056e-2cf2-4e9f-958a-173f72acb592')
|
||||
|
||||
describe('receiving ownership uses current canonical mailbox and consumer', () => {
|
||||
it('hands actual unread helper mail from a stopped creator to its Run, then fences the old Run consumer', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
await f.ensure(NEXT)
|
||||
await f.rig.store.setSessionTabVisibility(NEXT, true)
|
||||
const db = f.runtime.getOrchestrationDb()
|
||||
const run = db.createRun({
|
||||
objective: 'handback and takeover',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: PARENT
|
||||
})
|
||||
const worker = await f.createWorker(WORKER)
|
||||
const helper = await f.createWorker(HELPER, WORKER)
|
||||
f.selectB()
|
||||
expect(await f.rig.host.prospectiveAccountHome(WORKER)).toEqual(HOME_A)
|
||||
await f.report(helper)
|
||||
const message = db.getUndeliveredUnreadMessages(`dispatch:${worker.dispatch.id}`)[0]
|
||||
if (!message) {
|
||||
throw new Error('canonical report was not sent to its live creator')
|
||||
}
|
||||
expect(message.to_handle).toBe(dispatchReportMailbox(db, helper.dispatch))
|
||||
expect(f.runtime.mailTarget(message.to_handle)?.sessionId).toBe(WORKER)
|
||||
expect(
|
||||
await f.call('orchestration.workerStop', { dispatch: worker.dispatch.id })
|
||||
).toMatchObject({ state: 'stopped' })
|
||||
expect(db.getMessageById(message.id)?.to_handle).toBe(`run:${run.id}`)
|
||||
expect(f.runtime.mailTarget(`run:${run.id}`)?.sessionId).toBe(PARENT)
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A)
|
||||
const old = db.getOrCreateMailboxDelivery({
|
||||
runId: run.id,
|
||||
mailboxHandle: `run:${run.id}`,
|
||||
consumerGeneration: run.consumer_generation
|
||||
})
|
||||
if (!old) {
|
||||
throw new Error('old current consumer could not check real handback mail')
|
||||
}
|
||||
const rebound = db.bindRun({
|
||||
runId: run.id,
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: NEXT
|
||||
})
|
||||
if (!rebound) {
|
||||
throw new Error('supported Run takeover failed')
|
||||
}
|
||||
expect(rebound.consumer_generation).toBeGreaterThan(run.consumer_generation)
|
||||
expect(f.runtime.mailTarget(`run:${run.id}`)?.sessionId).toBe(NEXT)
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_B)
|
||||
expect(await f.rig.host.prospectiveAccountHome(NEXT)).toEqual(HOME_A)
|
||||
expect(() =>
|
||||
db.acknowledgeMailboxDelivery({
|
||||
runId: run.id,
|
||||
mailboxHandle: `run:${run.id}`,
|
||||
consumerGeneration: run.consumer_generation,
|
||||
deliveryId: old.delivery.id
|
||||
})
|
||||
).toThrow()
|
||||
const current = db.getOrCreateMailboxDelivery({
|
||||
runId: run.id,
|
||||
mailboxHandle: `run:${run.id}`,
|
||||
consumerGeneration: rebound.consumer_generation
|
||||
})
|
||||
expect(current?.messages.map((row) => row.id)).toContain(message.id)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['settled', 'missing', 'wrong-run', 'null'] as const)(
|
||||
'accepts the actual report with a %s creator shape and old Task generation',
|
||||
async (shape) => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
const db = f.runtime.getOrchestrationDb()
|
||||
const run = db.createRun({
|
||||
objective: 'old canonical creator shapes',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: PARENT
|
||||
})
|
||||
const worker = await f.createWorker(WORKER)
|
||||
const helper = await f.createWorker(HELPER, WORKER)
|
||||
await f.call('orchestration.workerStop', { dispatch: worker.dispatch.id })
|
||||
if (shape !== 'settled') {
|
||||
let creator: string | null = null
|
||||
if (shape === 'missing') {
|
||||
creator = 'dispatch_old_missing'
|
||||
}
|
||||
if (shape === 'wrong-run') {
|
||||
const other = db.createRun({
|
||||
objective: 'different Run',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null
|
||||
})
|
||||
creator = db.createStartingWorkerDispatch({
|
||||
taskSpec: 'other active creator',
|
||||
taskRunId: other.id,
|
||||
creator: { kind: 'system' },
|
||||
maxDepth: 9,
|
||||
startOptions: {}
|
||||
}).dispatch.id
|
||||
}
|
||||
// Persisted older/imported row shapes; report admission and Task lifetime remain production-owned.
|
||||
db.db
|
||||
.prepare('UPDATE dispatch_contexts SET creator_dispatch_id = ? WHERE id = ?')
|
||||
.run(creator, helper.dispatch.id)
|
||||
}
|
||||
db.db
|
||||
.prepare('UPDATE tasks SET created_by_run_generation = ? WHERE id = ?')
|
||||
.run(run.consumer_generation - 1, helper.task.id)
|
||||
const row = db.getDispatchContextById(helper.dispatch.id)
|
||||
if (!row) {
|
||||
throw new Error('real helper missing')
|
||||
}
|
||||
expect(dispatchReportMailbox(db, row)).toBe(`run:${run.id}`)
|
||||
f.selectB()
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A)
|
||||
await f.report(helper)
|
||||
expect(db.getWorkerDispatch(helper.dispatch.id)?.state).toBe('succeeded')
|
||||
const message = db.getUndeliveredUnreadMessages(`run:${run.id}`)[0]
|
||||
expect(message?.to_handle).toBe(`run:${run.id}`)
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
-127
@@ -1,127 +0,0 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION } from '../../../shared/protocol-version'
|
||||
import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture'
|
||||
import { acquiredAgentSessionAccount } from '../../../shared/agent-session-acquired-account'
|
||||
import { hostTestOperationId } from './structured-agent-session-host-test-data'
|
||||
import {
|
||||
createReceivingCallerFixture,
|
||||
HOME_A,
|
||||
HOME_B,
|
||||
PARENT
|
||||
} from './structured-agent-session-receiving-callers.test-support'
|
||||
|
||||
const SUCCESSOR = testOrcaSessionId('2842b48e-8a73-443a-99fb-810bf7eb09ce')
|
||||
|
||||
it('routes an imported committed clear lineage to its current visible receiver, using its own successful receipt', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
await f.ensure(SUCCESSOR)
|
||||
await f.rig.store.setSessionTabVisibility(SUCCESSOR, true)
|
||||
const db = f.runtime.getOrchestrationDb()
|
||||
const run = db.createRun({
|
||||
objective: 'lineage receiving work',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: PARENT
|
||||
})
|
||||
db.createStartingWorkerDispatch({
|
||||
taskSpec: 'still owed to this conversation',
|
||||
taskRunId: run.id,
|
||||
creator: { kind: 'session', orcaSessionId: PARENT },
|
||||
maxDepth: 9,
|
||||
startOptions: {}
|
||||
})
|
||||
await f.rig.host.close(PARENT, 'evict')
|
||||
// Stored older clear shape, written through the real record owner; no caller admission is changed.
|
||||
await f.rig.store.transitionHandoff(PARENT, (record) => ({
|
||||
...record,
|
||||
conversationCommand: {
|
||||
command: 'clear',
|
||||
state: 'completed',
|
||||
phase: 'committed',
|
||||
runtimeFence: record.lease.runtimeFence,
|
||||
callerKey: 'older-clear-client',
|
||||
operationId: hostTestOperationId(),
|
||||
replacementSessionId: SUCCESSOR
|
||||
}
|
||||
}))
|
||||
await f.rig.store.setSessionTabVisibility(PARENT, false)
|
||||
f.selectB()
|
||||
expect(f.runtime.mailTarget(`run:${run.id}`)?.sessionId).toBe(SUCCESSOR)
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_B)
|
||||
expect(await f.rig.host.prospectiveAccountHome(SUCCESSOR)).toEqual(HOME_A)
|
||||
const parent = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))
|
||||
const successor = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(SUCCESSOR))
|
||||
expect(successor?.generation).not.toBe(parent?.generation)
|
||||
await f.rig.host.close(SUCCESSOR, 'evict')
|
||||
await f.rig.store.setSessionTabVisibility(SUCCESSOR, false)
|
||||
expect(f.runtime.mailTarget(`run:${run.id}`)).toBeNull()
|
||||
expect(await f.rig.host.prospectiveAccountHome(SUCCESSOR)).toEqual(HOME_B)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('a real root-remote relay import transfers pre-notice work into the home current mailbox', async () => {
|
||||
const f = await createReceivingCallerFixture()
|
||||
try {
|
||||
await f.found()
|
||||
const db = f.runtime.getOrchestrationDb()
|
||||
const run = db.createRun({
|
||||
objective: 'remote root result',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: PARENT
|
||||
})
|
||||
f.runtime.stopOrchestrationFederationRelay()
|
||||
const worker = db.createStartingWorkerDispatch({
|
||||
taskSpec: 'remote work',
|
||||
taskRunId: run.id,
|
||||
creator: { kind: 'session', orcaSessionId: PARENT },
|
||||
maxDepth: 9,
|
||||
startOptions: {},
|
||||
federation: {
|
||||
environmentId: 'remote-environment',
|
||||
environmentName: 'paired worker',
|
||||
peerFingerprint: 'fixture-peer',
|
||||
protocolVersion: ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION
|
||||
}
|
||||
})
|
||||
f.selectB()
|
||||
expect(f.runtime.mailTarget(`run:${run.id}`)?.sessionId).toBe(PARENT)
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A)
|
||||
const imported = db.importFederatedRelayItem({
|
||||
dispatchId: worker.dispatch.id,
|
||||
sequence: 1,
|
||||
message: {
|
||||
id: 'relay_root_result',
|
||||
runId: run.id,
|
||||
from: `dispatch:${worker.dispatch.id}`,
|
||||
to: `run:${run.id}`,
|
||||
subject: 'complete',
|
||||
body: 'real relay input',
|
||||
type: 'worker_done',
|
||||
priority: 'normal',
|
||||
payload: JSON.stringify({
|
||||
taskId: worker.task.id,
|
||||
dispatchId: worker.dispatch.id,
|
||||
outcome: 'succeeded'
|
||||
})
|
||||
},
|
||||
lifecycle: {
|
||||
kind: 'worker_report',
|
||||
taskId: worker.task.id,
|
||||
outcome: 'succeeded',
|
||||
result: 'complete'
|
||||
}
|
||||
})
|
||||
expect(imported.lifecycle).toMatchObject({ action: 'settled', outcome: 'succeeded' })
|
||||
expect(db.getMessageById(imported.message.id)?.to_handle).toBe(`run:${run.id}`)
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A)
|
||||
db.markAsRead([imported.message.id])
|
||||
expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_B)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
import { vi } from 'vitest'
|
||||
import type { SqliteBindings } from '../../sqlite/sqlite-statement'
|
||||
import type { OrchestrationDb } from '../../runtime/orchestration/db'
|
||||
|
||||
/** Count actual SQL calls/results and their plans; EXPLAIN itself is excluded. */
|
||||
export function observeReceivingSql(db: OrchestrationDb) {
|
||||
const prepare = db.db.prepare.bind(db.db)
|
||||
const instrumented = new WeakSet<object>()
|
||||
const restores: (() => void)[] = []
|
||||
const plans: string[] = []
|
||||
const measurements = { prepares: 0, executions: 0, rows: 0, allRows: 0, plans }
|
||||
const explain = (sql: string, args: SqliteBindings) => {
|
||||
if (!/^\s*(SELECT|WITH)\b/i.test(sql)) {
|
||||
return
|
||||
}
|
||||
for (const row of prepare(`EXPLAIN QUERY PLAN ${sql}`).all(...args)) {
|
||||
if (typeof row.detail === 'string') {
|
||||
measurements.plans.push(row.detail)
|
||||
}
|
||||
}
|
||||
}
|
||||
const spy = vi.spyOn(db.db, 'prepare').mockImplementation((sql) => {
|
||||
measurements.prepares += 1
|
||||
const statement = prepare(sql)
|
||||
if (instrumented.has(statement)) {
|
||||
return statement
|
||||
}
|
||||
instrumented.add(statement)
|
||||
const all = statement.all.bind(statement)
|
||||
const get = statement.get.bind(statement)
|
||||
const run = statement.run.bind(statement)
|
||||
const allSpy = vi.spyOn(statement, 'all').mockImplementation((...args) => {
|
||||
measurements.executions += 1
|
||||
explain(sql, args)
|
||||
const rows = all(...args)
|
||||
measurements.rows += rows.length
|
||||
measurements.allRows += rows.length
|
||||
return rows
|
||||
})
|
||||
const getSpy = vi.spyOn(statement, 'get').mockImplementation((...args) => {
|
||||
measurements.executions += 1
|
||||
explain(sql, args)
|
||||
const row = get(...args)
|
||||
measurements.rows += row === undefined ? 0 : 1
|
||||
return row
|
||||
})
|
||||
const runSpy = vi.spyOn(statement, 'run').mockImplementation((...args) => {
|
||||
measurements.executions += 1
|
||||
return run(...args)
|
||||
})
|
||||
restores.push(
|
||||
() => allSpy.mockRestore(),
|
||||
() => getSpy.mockRestore(),
|
||||
() => runSpy.mockRestore()
|
||||
)
|
||||
return statement
|
||||
})
|
||||
return {
|
||||
measurements,
|
||||
stop: () => {
|
||||
spy.mockRestore()
|
||||
for (const restore of restores.toReversed()) {
|
||||
restore()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-2
@@ -1,4 +1,3 @@
|
||||
import type { ClaudeAccountRecipe } from '../../../shared/agent-session-acquired-account'
|
||||
// Adapter-reachable contract must remain free of host and Node-only process dependencies.
|
||||
|
||||
import type { AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-identity'
|
||||
@@ -31,7 +30,6 @@ export type StructuredAgentSessionStartupAttempt = {
|
||||
/** Saved launch intent, never catalog guesses. */
|
||||
readonly options?: Readonly<Record<string, string>>
|
||||
readonly permissionMode?: AgentChatPermissionChoice
|
||||
readonly accountRecipe?: ClaudeAccountRecipe
|
||||
/** Provider events may begin before spawn returns. */
|
||||
readonly events?: StructuredAgentSessionEventSink
|
||||
/** Attempt-scoped background evidence; adapters use registration reporting when absent. */
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { ClaudeAccountRecipe } from '../../../shared/agent-session-acquired-account'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { SubmissionRejectionFact } from '../../../shared/agent-session/failures/agent-session-failure'
|
||||
import {
|
||||
@@ -23,7 +22,6 @@ export function mintStructuredAgentSessionStartupAttempt(input: {
|
||||
identity: AgentSessionJournalIdentity
|
||||
spawnToken: string
|
||||
permissionMode?: AgentChatPermissionChoice
|
||||
accountRecipe?: ClaudeAccountRecipe
|
||||
events?: StructuredAgentSessionEventSink
|
||||
signal?: AbortSignal
|
||||
startupOptions?: Readonly<Record<string, string>>
|
||||
@@ -44,7 +42,6 @@ export function mintStructuredAgentSessionStartupAttempt(input: {
|
||||
},
|
||||
...(options ? { options } : {}),
|
||||
...(input.permissionMode ? { permissionMode: input.permissionMode } : {}),
|
||||
...(input.accountRecipe ? { accountRecipe: input.accountRecipe } : {}),
|
||||
...(input.events ? { events: input.events } : {}),
|
||||
...(input.signal ? { signal: input.signal } : {})
|
||||
}
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
import {
|
||||
providerContextBoundaryForClear,
|
||||
type AgentSessionConversationClear
|
||||
} from './agent-session/records/agent-session-conversation-command-record'
|
||||
import { structuredAgentSessionReceivingAccount } from '../native-chat/agent-session-wire/structured-agent-session-receiving-account'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
acquiredAgentSessionAccount,
|
||||
@@ -10,36 +5,55 @@ import {
|
||||
} from '../../shared/agent-session-acquired-account'
|
||||
import { agentSessionConversationView } from '../../shared/agent-session-conversation-view'
|
||||
import {
|
||||
createReceivingAccountFixture,
|
||||
RECEIVING_A,
|
||||
SELECTED_B
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-receiving-account.test-support'
|
||||
import { openTestAgentSessionRecordStore } from './agent-session/records/agent-session-record-store-test-harness'
|
||||
agentSessionLeaseFixture,
|
||||
agentSessionRecordFixture
|
||||
} from '../../shared/agent-session/lifecycle/agent-session-record.test-fixture'
|
||||
import { createRestTestRig } from '../native-chat/agent-session-wire/structured-agent-session-rest-test-rig'
|
||||
import {
|
||||
openTestAgentSessionRecordStore,
|
||||
seedTestAgentSessionRecordStore
|
||||
} from './agent-session/records/agent-session-record-store-test-harness'
|
||||
import {
|
||||
proveAgentSessionOwner,
|
||||
withLease
|
||||
} from './agent-session/ownership/agent-session-lease-transitions'
|
||||
import { prepareClaudeReceivingAccount } from '../claude/claude-receiving-account'
|
||||
|
||||
const RECEIVING_A = '/qa/claude-profiles/qa-a/home'
|
||||
|
||||
async function releasedFixture() {
|
||||
const f = await createReceivingAccountFixture()
|
||||
await f.store.reconcileOnRestart({
|
||||
sessionId: f.root,
|
||||
const rig = await createRestTestRig()
|
||||
const record = withAcquiredAgentSessionAccount(
|
||||
agentSessionRecordFixture(
|
||||
agentSessionLeaseFixture({
|
||||
sessionId: '6e1b4ae5-2354-4ca5-999e-647deeb23894',
|
||||
runtimeFence: 2
|
||||
})
|
||||
),
|
||||
{
|
||||
generation: 'generation-2',
|
||||
recipe: { route: 'system', home: RECEIVING_A, configDir: RECEIVING_A }
|
||||
}
|
||||
)
|
||||
const root = record.sessionId
|
||||
await seedTestAgentSessionRecordStore(rig.root, { records: [record] })
|
||||
const store = await openTestAgentSessionRecordStore(rig.root)
|
||||
await store.reconcileOnRestart({
|
||||
sessionId: root,
|
||||
probe: async () => ({ outcome: 'exit-observed' }),
|
||||
now: 40_000
|
||||
})
|
||||
const record = f.store.getRecord(f.root)
|
||||
if (!record) {
|
||||
const released = store.getRecord(root)
|
||||
if (!released) {
|
||||
throw new Error('record missing after reconciliation')
|
||||
}
|
||||
return { ...f, released: record }
|
||||
return { rig, store, root, released, dispose: () => rig.dispose() }
|
||||
}
|
||||
|
||||
describe('actual acquired account receipt in the fenced record owner', () => {
|
||||
it('reloads the last success across a proven release and reservation, then co-writes the next success', async () => {
|
||||
const f = await releasedFixture()
|
||||
try {
|
||||
expect(acquiredAgentSessionAccount(f.released, 'local')?.recipe.home).toBe(RECEIVING_A.path)
|
||||
expect(acquiredAgentSessionAccount(f.released, 'local')?.recipe.home).toBe(RECEIVING_A)
|
||||
expect(acquiredAgentSessionAccount(f.released, 'another-host')).toBeNull()
|
||||
expect(acquiredAgentSessionAccount({ ...f.released, sessionId: 'another-chat' })).toBeNull()
|
||||
const reserved = await f.store.reserveOwner({
|
||||
@@ -64,7 +78,7 @@ describe('actual acquired account receipt in the fenced record owner', () => {
|
||||
if (!current) {
|
||||
throw new Error('reservation missing')
|
||||
}
|
||||
expect(acquiredAgentSessionAccount(current)?.recipe.home).toBe(RECEIVING_A.path)
|
||||
expect(acquiredAgentSessionAccount(current)?.recipe.home).toBe(RECEIVING_A)
|
||||
await f.store.commitProcessIdentity({
|
||||
sessionId: f.root,
|
||||
fence: current.lease.runtimeFence,
|
||||
@@ -94,11 +108,6 @@ describe('actual acquired account receipt in the fenced record owner', () => {
|
||||
expect(acquiredAgentSessionAccount(reloaded)?.recipe).toEqual(recipe)
|
||||
expect(acquiredAgentSessionAccount(reloaded)?.fence).toBe(current.lease.runtimeFence)
|
||||
expect(agentSessionConversationView(reloaded)).not.toHaveProperty('acquiredAccount')
|
||||
const env = { CLAUDE_CONFIG_DIR: '/selected/b', PATH: '/usr/bin' }
|
||||
expect(await prepareClaudeReceivingAccount(undefined, env, '/founding/c', recipe)).toEqual(
|
||||
recipe
|
||||
)
|
||||
expect(env).toEqual({ CLAUDE_CONFIG_DIR: '/custom/receiving', PATH: '/usr/bin' })
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
@@ -129,7 +138,7 @@ describe('actual acquired account receipt in the fenced record owner', () => {
|
||||
ownerFence: reserved.lease.runtimeFence
|
||||
}
|
||||
})
|
||||
expect(acquiredAgentSessionAccount(failed)?.recipe.home).toBe(RECEIVING_A.path)
|
||||
expect(acquiredAgentSessionAccount(failed)?.recipe.home).toBe(RECEIVING_A)
|
||||
const process = { hostId: 'local', pid: 4242, processStartTimeMs: 50_000, spawnToken: 'next' }
|
||||
const proving = withLease(reserved, { ...reserved.lease, ownerProcess: process })
|
||||
// Older proof preserves unknown extension bytes but does not observe the successful new construction.
|
||||
@@ -160,52 +169,4 @@ describe('actual acquired account receipt in the fenced record owner', () => {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
it('clears exact response ownership with the existing fenced record/journal receipt, retaining created work', async () => {
|
||||
const f = await releasedFixture()
|
||||
try {
|
||||
const message = f.finish(f.start())
|
||||
const next = await f.submit(f.body(message))
|
||||
f.session.child = null
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, f.released, f.session, next)).home
|
||||
).toEqual(RECEIVING_A)
|
||||
const clear: AgentSessionConversationClear = {
|
||||
sessionId: f.root,
|
||||
fence: f.released.lease.runtimeFence,
|
||||
now: 40_001,
|
||||
command: {
|
||||
command: 'clear',
|
||||
phase: 'committed',
|
||||
state: 'completed',
|
||||
runtimeFence: f.released.lease.runtimeFence,
|
||||
callerKey: 'client',
|
||||
operationId: '1800000000000-00000000000000000000000000000002'
|
||||
}
|
||||
}
|
||||
const operation = {
|
||||
callerKey: clear.command.callerKey,
|
||||
operationId: clear.command.operationId
|
||||
}
|
||||
await f.store.admitOperation({ ...operation, fingerprint: 'clear', now: 40_001 })
|
||||
await f.journal.context.clear(
|
||||
providerContextBoundaryForClear(clear),
|
||||
f.store.conversationReceipts.clear(() => clear, operation)
|
||||
)
|
||||
const current = f.store.getRecord(f.root)
|
||||
if (!current) {
|
||||
throw new Error('record missing after clear')
|
||||
}
|
||||
expect(current.providerHandleChain).toEqual([])
|
||||
expect(acquiredAgentSessionAccount(current)?.recipe.home).toBe(RECEIVING_A.path)
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, current, f.session)).home
|
||||
).toEqual(SELECTED_B)
|
||||
f.start()
|
||||
expect(
|
||||
(await structuredAgentSessionReceivingAccount(f.deps, current, f.session)).home
|
||||
).toEqual(RECEIVING_A)
|
||||
} finally {
|
||||
await f.dispose()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import type Database from '../sqlite/sync-database'
|
||||
import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record'
|
||||
|
||||
/** Indexed reverse links cover historical clear successors without scanning every conversation. */
|
||||
export function agentSessionRecordLineage(
|
||||
db: Database.Database,
|
||||
record: AgentSessionRecord,
|
||||
getRecord: (id: string) => AgentSessionRecord | null
|
||||
): AgentSessionRecord[] {
|
||||
const records = [record]
|
||||
const seen = new Set([record.sessionId])
|
||||
const prior = db.prepare(`SELECT session_id FROM agent_session_records
|
||||
WHERE CASE WHEN json_valid(record_json) THEN json_extract(record_json, '$.conversationCommand.replacementSessionId') END = ?`)
|
||||
for (let current = record; ;) {
|
||||
const rows = prior.all(current.sessionId)
|
||||
if (
|
||||
rows.length !== 1 ||
|
||||
typeof rows[0].session_id !== 'string' ||
|
||||
seen.has(rows[0].session_id)
|
||||
) {
|
||||
return records.toReversed()
|
||||
}
|
||||
const earlier = getRecord(rows[0].session_id)
|
||||
if (
|
||||
earlier?.conversationCommand?.command !== 'clear' ||
|
||||
earlier.conversationCommand.phase !== 'committed'
|
||||
) {
|
||||
return records.toReversed()
|
||||
}
|
||||
seen.add(earlier.sessionId)
|
||||
records.push(earlier)
|
||||
current = earlier
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import { agentSessionRecordLineage } from '../../agent-session-record-lineage'
|
||||
import type Database from '../../../sqlite/sync-database'
|
||||
import { createAgentSessionOwnerProof } from '../../agent-session-owner-proof'
|
||||
import { backfillAgentSessionPermissionModes } from '../ownership/agent-session-permission-backfill'
|
||||
import { createAgentSessionConversationReceipts } from '../agent-session-conversation-receipts'
|
||||
@@ -91,8 +89,7 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs {
|
||||
|
||||
private constructor(
|
||||
transactions: AgentSessionStoreTransactions,
|
||||
readonly hostId: string,
|
||||
private readonly database: Database.Database
|
||||
readonly hostId: string
|
||||
) {
|
||||
super(transactions)
|
||||
this.founding = createAgentSessionFoundingStore(transactions, this.firstRecordListeners)
|
||||
@@ -112,7 +109,7 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs {
|
||||
args.hostId,
|
||||
args.legacySessionTabIds
|
||||
)
|
||||
return new AgentSessionRecordStore(transactions, args.hostId, args.journalDatabase.db)
|
||||
return new AgentSessionRecordStore(transactions, args.hostId)
|
||||
}
|
||||
|
||||
private get state(): AgentSessionStoreState {
|
||||
@@ -130,9 +127,6 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs {
|
||||
getRecord = (sessionId: string): AgentSessionRecord | null =>
|
||||
this.state.records.get(sessionId) ?? null
|
||||
|
||||
lineageRecords = (record: AgentSessionRecord) =>
|
||||
agentSessionRecordLineage(this.database, record, this.getRecord)
|
||||
|
||||
getConversation = (sessionId: string) => getAgentSessionConversation(this.state, sessionId)
|
||||
listConversations = () => listAgentSessionConversations(this.state)
|
||||
selectWritableRecord = (sessionId: string) =>
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
import { structuredWorkerAddressable } from '../structured-worker-custody'
|
||||
import { isOrcaSessionId } from '../../../shared/orca-session-address'
|
||||
import type { AgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-record'
|
||||
import type { OrchestrationDb } from './db'
|
||||
import { currentRunCoordinatorOrcaSessionId } from './db/runs/run-coordinator-orca-session'
|
||||
import { dispatchReportMailbox } from './dispatch-report-mailbox'
|
||||
import {
|
||||
addressableSessionParty,
|
||||
structuredSessionMailReach
|
||||
} from './structured-session-mail-address'
|
||||
import type { AgentSessionRecordReader } from './structured-session-lineage'
|
||||
|
||||
export type NativeResponseEvidence = { pending: Iterable<string>; disposed: ReadonlySet<string> }
|
||||
|
||||
/** Current canonical recipients own future reports; original creator provenance does not. */
|
||||
export function structuredParentAccountWork(
|
||||
db: OrchestrationDb | null,
|
||||
record: AgentSessionRecord,
|
||||
root: string,
|
||||
response: NativeResponseEvidence,
|
||||
reader: AgentSessionRecordReader
|
||||
): boolean {
|
||||
if (!db || !isOrcaSessionId(root)) {
|
||||
return false
|
||||
}
|
||||
const original = reader.getRecord(root)
|
||||
const reach = original && structuredSessionMailReach(reader, original, db, reader)
|
||||
if (!reach || reach.kind !== 'reachable' || reach.session.sessionId !== record.sessionId) {
|
||||
return false
|
||||
}
|
||||
const party = addressableSessionParty(root, db, reader)
|
||||
if (!party) {
|
||||
return false
|
||||
}
|
||||
if (
|
||||
party.terminalHandle &&
|
||||
!structuredWorkerAddressable(
|
||||
db,
|
||||
{
|
||||
sessionId: reach.session.sessionId,
|
||||
record: reach.session,
|
||||
lineage: reader.listRecords().map((item) => item.sessionId)
|
||||
},
|
||||
db.getWorkerTerminalResourceByHandle(party.terminalHandle),
|
||||
{
|
||||
getPersistedVisibleSessionTabIndex: () =>
|
||||
reader.getVisibleSessionTabIndex?.() ?? { present: false, sessionIds: [] }
|
||||
}
|
||||
)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
const mailboxes = new Map<string, { runId: string; mailbox: string }>()
|
||||
const runs = new Set<string>()
|
||||
const dispatches = new Set<string>()
|
||||
const add = (runId: string, mailbox: string) => {
|
||||
mailboxes.set(`${runId}\0${mailbox}`, { runId, mailbox })
|
||||
}
|
||||
const runCandidates = db.db
|
||||
.prepare(`SELECT id FROM runs WHERE coordinator_orca_session_id = ?
|
||||
UNION SELECT id FROM runs WHERE coordinator_handle = ?`)
|
||||
.all(root, party.terminalHandle)
|
||||
for (const run of party.paneKey ? db.runsBoundToPane(party.paneKey) : []) {
|
||||
runCandidates.push({ id: run.id })
|
||||
}
|
||||
for (const candidate of runCandidates) {
|
||||
if (typeof candidate.id !== 'string') {
|
||||
continue
|
||||
}
|
||||
const run = db.getRunRaw(candidate.id)
|
||||
if (
|
||||
run &&
|
||||
(run.coordinator_handle !== null
|
||||
? run.coordinator_handle === party.terminalHandle
|
||||
: currentRunCoordinatorOrcaSessionId(run) === root)
|
||||
) {
|
||||
runs.add(run.id)
|
||||
add(run.id, `run:${run.id}`)
|
||||
}
|
||||
}
|
||||
const assigned = db.db
|
||||
.prepare(`SELECT id FROM dispatch_contexts
|
||||
WHERE assignee_orca_session_id = ? AND status IN ('pending', 'dispatched')
|
||||
UNION SELECT id FROM dispatch_contexts WHERE assignee_handle = ? AND status IN ('pending', 'dispatched')`)
|
||||
.all(root, party.address)
|
||||
for (const candidate of assigned) {
|
||||
if (typeof candidate.id !== 'string') {
|
||||
continue
|
||||
}
|
||||
const dispatch = db.getDispatchContextById(candidate.id)
|
||||
if (dispatch?.assignee_handle === party.address) {
|
||||
dispatches.add(dispatch.id)
|
||||
add(dispatch.run_id, `dispatch:${dispatch.id}`)
|
||||
}
|
||||
}
|
||||
const candidates = new Set<string>()
|
||||
const byRun = db.db.prepare(
|
||||
`SELECT id FROM dispatch_contexts WHERE run_id = ? AND status IN ('pending', 'dispatched')`
|
||||
)
|
||||
const byCreator = db.db.prepare(
|
||||
`SELECT id FROM dispatch_contexts WHERE creator_dispatch_id = ? AND status IN ('pending', 'dispatched')`
|
||||
)
|
||||
for (const rows of [
|
||||
...Array.from(runs, (id) => byRun.all(id)),
|
||||
...Array.from(dispatches, (id) => byCreator.all(id))
|
||||
]) {
|
||||
for (const row of rows) {
|
||||
if (typeof row.id === 'string') {
|
||||
candidates.add(row.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const id of candidates) {
|
||||
const dispatch = db.getDispatchContextById(id)
|
||||
if (dispatch && mailboxes.has(`${dispatch.run_id}\0${dispatchReportMailbox(db, dispatch)}`)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
const unread = db.db.prepare(`SELECT id FROM messages WHERE run_id = ? AND to_handle = ?
|
||||
AND type = 'worker_done' AND read = 0 AND delivered_at IS NULL AND delivery_contract <> 'audit_only'`)
|
||||
const direct = db.db.prepare(`SELECT id FROM messages WHERE to_handle = ?
|
||||
AND type = 'worker_done' AND read = 0 AND delivered_at IS NULL AND delivery_contract <> 'audit_only'`)
|
||||
const exact = db.db
|
||||
.prepare(`SELECT run_id, to_handle FROM messages WHERE id = ? AND type = 'worker_done'
|
||||
AND delivery_contract <> 'audit_only'`)
|
||||
for (const { runId, mailbox } of mailboxes.values()) {
|
||||
if (
|
||||
unread
|
||||
.all(runId, mailbox)
|
||||
.some((message) => typeof message.id === 'string' && !response.disposed.has(message.id))
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if (
|
||||
direct
|
||||
.all(party.address)
|
||||
.some((message) => typeof message.id === 'string' && !response.disposed.has(message.id))
|
||||
) {
|
||||
return true
|
||||
}
|
||||
// Acknowledgement does not dispose a response already accepted by the current recipient.
|
||||
for (const id of response.pending) {
|
||||
const message = exact.get(id)
|
||||
if (
|
||||
message &&
|
||||
(message.to_handle === party.address ||
|
||||
mailboxes.has(`${String(message.run_id)}\0${String(message.to_handle)}`))
|
||||
) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as fs from 'node:fs'
|
||||
import * as fsp from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { performance } from 'node:perf_hooks'
|
||||
@@ -21,6 +22,10 @@ vi.mock('node:fs', async (original) => {
|
||||
readdirSync: vi.fn(actual.readdirSync)
|
||||
}
|
||||
})
|
||||
vi.mock('node:fs/promises', async (original) => {
|
||||
const actual = await original<typeof fsp>()
|
||||
return { ...actual, stat: vi.fn(actual.stat), readFile: vi.fn(actual.readFile) }
|
||||
})
|
||||
vi.mock('../../orca-profiles/profile-storage-paths', async () => {
|
||||
const { tmpdir } = await import('node:os')
|
||||
return { getProfileUserDataPath: () => tmpdir() }
|
||||
@@ -37,7 +42,12 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
it.each([25, 250])('bounds desired-home reads with %i managed accounts', async (accounts) => {
|
||||
for (const signedIn of [true, false]) {
|
||||
for (const [signedIn, concurrent] of [
|
||||
[true, false],
|
||||
[false, false],
|
||||
[true, true],
|
||||
[false, true]
|
||||
]) {
|
||||
for (const deliveries of [10, 100]) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'orca-account-read-perf-'))
|
||||
roots.push(root)
|
||||
@@ -98,7 +108,45 @@ it.each([25, 250])('bounds desired-home reads with %i managed accounts', async (
|
||||
structuredAgentLaunchEnv: () => ({})
|
||||
}
|
||||
)
|
||||
const reads = vi.spyOn(router, 'routedHome')
|
||||
const reads = vi.spyOn(router, 'selectedProfile')
|
||||
for (const spy of [
|
||||
fs.statSync,
|
||||
fs.lstatSync,
|
||||
fs.existsSync,
|
||||
fs.readFileSync,
|
||||
fs.readdirSync,
|
||||
fsp.stat,
|
||||
fsp.readFile
|
||||
]) {
|
||||
vi.mocked(spy).mockClear()
|
||||
}
|
||||
accountVisits = 0
|
||||
selectionReads = 0
|
||||
const record = agentSessionRecordFixture()
|
||||
const deliver = () => runtime.resolveStructuredAgentLaunchAccountHome(record)
|
||||
const answers: (AgentSessionAccountHome | null)[] = []
|
||||
const started = performance.now()
|
||||
if (concurrent) {
|
||||
// Many chats reading at once on a cold cache, before any read has finished.
|
||||
answers.push(...(await Promise.all(Array.from({ length: deliveries }, deliver))))
|
||||
} else {
|
||||
for (let delivery = 0; delivery < deliveries; delivery += 1) {
|
||||
answers.push(await deliver())
|
||||
}
|
||||
}
|
||||
const elapsedMs = performance.now() - started
|
||||
expect(answers).toEqual(
|
||||
Array.from({ length: deliveries }, () => ({
|
||||
variable: 'CLAUDE_CONFIG_DIR',
|
||||
path: signedIn ? selectedHome : systemHome
|
||||
}))
|
||||
)
|
||||
const stats = vi.mocked(fsp.stat).mock.calls.length
|
||||
const stateReads = vi.mocked(fsp.readFile).mock.calls.length
|
||||
expect(reads).toHaveBeenCalledTimes(deliveries)
|
||||
expect(selectionReads).toBe(deliveries)
|
||||
expect(accountVisits).toBe(signedIn ? 0 : accounts * deliveries)
|
||||
// Chat reads run on main once per options read and send: nothing here may block it.
|
||||
for (const spy of [
|
||||
fs.statSync,
|
||||
fs.lstatSync,
|
||||
@@ -106,41 +154,25 @@ it.each([25, 250])('bounds desired-home reads with %i managed accounts', async (
|
||||
fs.readFileSync,
|
||||
fs.readdirSync
|
||||
]) {
|
||||
vi.mocked(spy).mockClear()
|
||||
expect(spy).not.toHaveBeenCalled()
|
||||
}
|
||||
accountVisits = 0
|
||||
selectionReads = 0
|
||||
const record = agentSessionRecordFixture()
|
||||
let answer: AgentSessionAccountHome | null = null
|
||||
const started = performance.now()
|
||||
for (let delivery = 0; delivery < deliveries; delivery += 1) {
|
||||
answer = await runtime.resolveStructuredAgentLaunchAccountHome(record)
|
||||
// Cold first read (shared by concurrent readers), then metadata-validated login cache.
|
||||
expect(stateReads).toBe(1)
|
||||
expect(vi.mocked(fsp.readFile).mock.calls[0][0]).toBe(stateFile)
|
||||
if (concurrent) {
|
||||
// Claude rewrote the file: one more read for the new revision, however many readers.
|
||||
fs.writeFileSync(stateFile, `${state} `)
|
||||
await Promise.all(Array.from({ length: deliveries }, deliver))
|
||||
expect(vi.mocked(fsp.readFile).mock.calls.length).toBe(2)
|
||||
}
|
||||
const elapsedMs = performance.now() - started
|
||||
expect(answer).toEqual({
|
||||
variable: 'CLAUDE_CONFIG_DIR',
|
||||
path: signedIn ? selectedHome : systemHome
|
||||
})
|
||||
const stats = vi.mocked(fs.statSync).mock.calls.length
|
||||
const directoryStats = vi.mocked(fs.lstatSync).mock.calls.length
|
||||
const stateReads = vi.mocked(fs.readFileSync).mock.calls.length
|
||||
expect(reads).toHaveBeenCalledTimes(deliveries)
|
||||
expect(selectionReads).toBe(deliveries)
|
||||
expect(accountVisits).toBe(signedIn ? 0 : accounts * deliveries)
|
||||
expect(stats).toBe(signedIn ? deliveries : 2 * deliveries)
|
||||
expect(directoryStats).toBe(signedIn ? deliveries : 0)
|
||||
expect(vi.mocked(fs.existsSync).mock.calls.length).toBeLessThanOrEqual(2 * deliveries)
|
||||
expect(stateReads).toBe(1) // Cold first read, then metadata-validated login cache.
|
||||
expect(vi.mocked(fs.readFileSync).mock.calls[0][0]).toBe(stateFile)
|
||||
expect(fs.readdirSync).not.toHaveBeenCalled()
|
||||
console.info('account-home-perf', {
|
||||
accounts,
|
||||
deliveries,
|
||||
signedIn,
|
||||
concurrent,
|
||||
selectionReads,
|
||||
accountVisits,
|
||||
stats,
|
||||
directoryStats,
|
||||
stateReads,
|
||||
stateBytes: Buffer.byteLength(state),
|
||||
elapsedMs
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { AgentSessionAccountKind } from '../../shared/agent-session/agent-s
|
||||
import type { GlobalSettings } from '../../shared/global-settings-types'
|
||||
import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path'
|
||||
import { getClaudeProfileRouter } from '../claude-accounts/claude-profile-installed-router'
|
||||
import { claudeRoutedHomeAsync } from '../claude-accounts/claude-profile-routed-home'
|
||||
import { normalizeCodexRuntimeSelection } from '../codex-accounts/runtime-selection'
|
||||
import { resolveOrcaManagedCodexHomePath, getSystemCodexHomePath } from '../codex/codex-home-paths'
|
||||
import { resolveAbsoluteDirOverride } from '../../shared/absolute-dir-override'
|
||||
@@ -20,13 +21,14 @@ export type StructuredClaudeAccountHomeDeps = {
|
||||
) => string | null | undefined
|
||||
}
|
||||
|
||||
export function resolveStructuredClaudeAccountHomePath(
|
||||
export async function resolveStructuredClaudeAccountHomePath(
|
||||
deps: StructuredClaudeAccountHomeDeps
|
||||
): string {
|
||||
): Promise<string> {
|
||||
// Why only an account: System default keeps the launch-env and configured homes below.
|
||||
const accountHome = deps.wslDistro
|
||||
? null
|
||||
: getClaudeProfileRouter()?.routedHome(deps.purpose === 'identity' ? 'identity' : 'checked')
|
||||
const router = deps.wslDistro ? undefined : getClaudeProfileRouter()
|
||||
const accountHome = router
|
||||
? await claudeRoutedHomeAsync(router, deps.purpose === 'identity' ? 'identity' : 'checked')
|
||||
: null
|
||||
if (accountHome) {
|
||||
return accountHome
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { ClaudeAccountRecipe } from '../../shared/agent-session-acquired-account'
|
||||
// Build agent launch resolvers with production composition over test doubles so tests exercise the shared path.
|
||||
|
||||
import type { AgentSessionRecordStore } from './agent-session/records/agent-session-record-store'
|
||||
@@ -108,7 +107,6 @@ function withTestSpawnToken<L>(
|
||||
identity: AgentSessionJournalIdentity
|
||||
spawnToken?: string | null
|
||||
permissionMode?: AgentChatPermissionChoice
|
||||
accountRecipe?: ClaudeAccountRecipe
|
||||
}) => {
|
||||
const spawnToken = input.spawnToken === undefined ? defaultToken : input.spawnToken
|
||||
return spawnToken === null
|
||||
@@ -116,7 +114,6 @@ function withTestSpawnToken<L>(
|
||||
: resolve({
|
||||
identity: input.identity,
|
||||
spawnToken,
|
||||
...(input.accountRecipe ? { accountRecipe: input.accountRecipe } : {}),
|
||||
...(input.permissionMode ? { permissionMode: input.permissionMode } : {})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { ClaudeAccountRecipe } from '../../shared/agent-session-acquired-account'
|
||||
// Compose shared admission, cwd, environment, visuals and child sealing; agent parts add only agent-specific inputs and never set cwd/sealed env.
|
||||
|
||||
import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-identity'
|
||||
@@ -54,7 +53,6 @@ export type StructuredAgentLaunchBasis = {
|
||||
refreshAfterMissingProgram?: (askedAt: number) => Promise<void>
|
||||
/** The permission mode the host decided this start runs with; absent asks. */
|
||||
permissionMode?: AgentChatPermissionChoice
|
||||
accountRecipe?: ClaudeAccountRecipe
|
||||
}
|
||||
|
||||
export type StructuredLaunchRequest = {
|
||||
@@ -62,7 +60,6 @@ export type StructuredLaunchRequest = {
|
||||
/** The reservation's token, which the seal hands the child. */
|
||||
spawnToken: string
|
||||
permissionMode?: AgentChatPermissionChoice
|
||||
accountRecipe?: ClaudeAccountRecipe
|
||||
}
|
||||
|
||||
/** What the composition sets on a launch; an agent's part never does. */
|
||||
@@ -141,8 +138,7 @@ async function composedPart<L>(
|
||||
sources: StructuredAgentLaunchSources,
|
||||
part: StructuredAgentLaunchPartResolver<L>,
|
||||
identity: AgentSessionJournalIdentity,
|
||||
permissionMode?: AgentChatPermissionChoice,
|
||||
accountRecipe?: ClaudeAccountRecipe
|
||||
permissionMode?: AgentChatPermissionChoice
|
||||
): Promise<StructuredAgentLaunchPart<L> & { cwd: string }> {
|
||||
const record = admittedRecord(definition, sources.store, identity.sessionId)
|
||||
const launchEnv = once(() => sources.resolveAgentLaunchEnv?.(definition.agent) ?? {})
|
||||
@@ -168,7 +164,6 @@ async function composedPart<L>(
|
||||
}
|
||||
}
|
||||
: {}),
|
||||
...(accountRecipe ? { accountRecipe } : {}),
|
||||
...(permissionMode ? { permissionMode } : {})
|
||||
}
|
||||
const composed = await part(basis, identity)
|
||||
@@ -180,14 +175,13 @@ export function composeStructuredLaunch<L>(
|
||||
sources: StructuredAgentLaunchSources,
|
||||
part: StructuredAgentLaunchPartResolver<L>
|
||||
): StructuredAgentLaunchResolver<L> {
|
||||
return async ({ identity, spawnToken, permissionMode, accountRecipe }) => {
|
||||
return async ({ identity, spawnToken, permissionMode }) => {
|
||||
const { launch, cwd, env, inheritedEnvToDelete, cliRuntimeCommand } = await composedPart(
|
||||
definition,
|
||||
sources,
|
||||
part,
|
||||
identity,
|
||||
permissionMode,
|
||||
accountRecipe
|
||||
permissionMode
|
||||
)
|
||||
admittedRecord(definition, sources.store, identity.sessionId)
|
||||
const child = sealStructuredSessionChild({
|
||||
|
||||
@@ -139,7 +139,7 @@ export const STRUCTURED_AGENT_RUNTIME_CATALOG: readonly StructuredAgentRuntimeCa
|
||||
resolveAccountHome: async ({ launchEnv, location, purpose }, services) =>
|
||||
agentSessionAccountHome(
|
||||
CLAUDE_STRUCTURED_AGENT,
|
||||
resolveStructuredClaudeAccountHomePath({
|
||||
await resolveStructuredClaudeAccountHomePath({
|
||||
launchEnv,
|
||||
wslDistro: location?.wslDistro ?? null,
|
||||
...(purpose === 'identity' ? { purpose } : {}),
|
||||
|
||||
@@ -89,7 +89,6 @@ export async function installOnJournal(
|
||||
...(deps.startupLimits ? { startupLimits: deps.startupLimits } : {}),
|
||||
...(deps.onSessionTabHidden ? { onSessionTabHidden: deps.onSessionTabHidden } : {}),
|
||||
...(deps.launchAccountHome ? { launchAccountHome: deps.launchAccountHome } : {}),
|
||||
...(deps.parentAccountWork ? { parentAccountWork: deps.parentAccountWork } : {}),
|
||||
...(deps.assertNoTerminalWriter ? { assertNoTerminalWriter: deps.assertNoTerminalWriter } : {}),
|
||||
...(await modelCatalogHostDeps({
|
||||
host: () => host,
|
||||
|
||||
@@ -82,5 +82,4 @@ export type StructuredAgentSessionRuntimeDeps = StructuredAgentSessionTransportO
|
||||
resolveAgentAccountHome?: RuntimeAgentAccountHomeResolver
|
||||
/** See `StructuredAgentSessionHostDeps.launchAccountHome`. */
|
||||
launchAccountHome?: StructuredAgentSessionHostDeps['launchAccountHome']
|
||||
parentAccountWork?: StructuredAgentSessionHostDeps['parentAccountWork']
|
||||
} & Pick<StructuredAgentSessionHostDeps, 'onRequestFailure' | 'statusSink'>
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import type { StructuredAgentSessionHostDeps } from '../native-chat/agent-session-wire/structured-agent-session-host-types'
|
||||
import type { OrchestrationDb } from './orchestration/db'
|
||||
import { structuredParentAccountWork } from './orchestration/structured-parent-account-work'
|
||||
import { structuredWorkerOwesWork } from './structured-worker-custody'
|
||||
|
||||
/** Both are re-read; assigned process custody remains separate from receiving-account ownership. */
|
||||
export function structuredNativeWorkReaders(
|
||||
read: () => OrchestrationDb | null,
|
||||
readReceiving: () => OrchestrationDb | null = read
|
||||
): Pick<StructuredAgentSessionHostDeps, 'hasOpenDispatch' | 'parentAccountWork'> {
|
||||
return {
|
||||
hasOpenDispatch: (record) => structuredWorkerOwesWork(read(), record),
|
||||
parentAccountWork: (record, root, response, reader) =>
|
||||
structuredParentAccountWork(readReceiving(), record, root, response, reader)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { structuredNativeWorkReaders } from '../structured-native-work-readers'
|
||||
import { getRepoHostIdentityForParts } from '../../../shared/repo-host-identity'
|
||||
import { createRepoRowExecutionHostLookup } from '../../../shared/worktree-execution-host-resolution'
|
||||
import { resolveWorktreeHostRouting } from '../worktree-launch-host-repo'
|
||||
@@ -44,7 +43,10 @@ import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-path
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host'
|
||||
import { chatWorkerTurnStopReporter } from '../orchestration/chat-worker-turn-stops'
|
||||
import { buildWorktreeListingPage } from '../worktree-listing-host-scope'
|
||||
import { structuredWorkerOpenTaskTitle } from '../structured-worker-custody'
|
||||
import {
|
||||
structuredWorkerOpenTaskTitle,
|
||||
structuredWorkerOwesWork
|
||||
} from '../structured-worker-custody'
|
||||
import { preModeChatGetsFullAccess } from '../../../shared/agent-chat-permission-mode'
|
||||
import { isTuiAgent } from '../../../shared/tui-agent-config'
|
||||
import { nativeChatShellEnvironmentPolicy } from '../../../shared/native-chat/native-chat-shell-environment'
|
||||
@@ -306,10 +308,9 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends OrcaRuntimeWithWorktr
|
||||
now: () => Date.now()
|
||||
}),
|
||||
onTurnAttention: chatWorkerTurnStopReporter(this.workerTurnStopReportDeps),
|
||||
...structuredNativeWorkReaders(
|
||||
() => this.getOrchestrationDbIfAvailable?.() ?? null,
|
||||
() => this.getExistingOrchestrationDb()
|
||||
)
|
||||
// Re-read dispatch ownership each sweep; absence of a database cannot keep the worker alive.
|
||||
hasOpenDispatch: (record) =>
|
||||
structuredWorkerOwesWork(this.getOrchestrationDbIfAvailable?.() ?? null, record)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user