fix(orchestration): preserve active workers across updates (#11271)

* fix(orchestration): preserve active workers across updates

* test(ssh): model absent legacy adoption

* test(orchestration): align compatibility contracts

* fix(windows): escape updater PowerShell booleans

* fix(windows): restore stock uninstall process check

* fix(orchestration): keep recovery off renderer startup barrier

* fix(orchestration): harden legacy recovery migration

* fix(orchestration): close recovery review gaps

* fix(orchestration): complete legacy worker cutover recovery

* fix(orchestration): preserve legacy workers across updates

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-07-29 11:31:35 -07:00
committed by GitHub
co-authored by OrcaWin
parent 4543bb6826
commit 363e478909
150 changed files with 19865 additions and 792 deletions
@@ -265,7 +265,7 @@ describe('orchestration federation control mail', () => {
})
await expect(waiting).resolves.toMatchObject({
ok: true,
result: { count: 0, timedOut: true }
result: { count: 0 }
})
})
@@ -224,6 +224,7 @@ describe('orchestration federation', () => {
])
)
expect(workerDb.listTasks()).toHaveLength(0)
expect(vi.mocked(workerRuntime.createManagedWorktree).mock.calls[0]?.[0].activate).toBe(false)
expect(workerRuntime.sendTerminalAgentPrompt).toHaveBeenCalledWith(
'term_windows_worker',
expect.stringContaining(`Your task ID is: ${task.id}`)
@@ -103,8 +103,12 @@ export const ORCHESTRATION_GATE_METHODS: RpcMethod[] = [
defineMethod({
name: 'orchestration.gateCreate',
params: GateCreateParams,
handler: (params, { runtime }) => {
handler: (params, { runtime, legacyCoordinatorRunId }) => {
const db = runtime.getOrchestrationDb()
const task = db.getTask(params.task)
if (legacyCoordinatorRunId && task?.run_id !== legacyCoordinatorRunId) {
throw new Error(`Task not found: ${params.task}`)
}
let options: string[] | undefined
if (params.options) {
try {
@@ -129,8 +133,12 @@ export const ORCHESTRATION_GATE_METHODS: RpcMethod[] = [
defineMethod({
name: 'orchestration.gateResolve',
params: GateResolveParams,
handler: (params, { runtime }) => {
handler: (params, { runtime, legacyCoordinatorRunId }) => {
const db = runtime.getOrchestrationDb()
const existing = db.getGate(params.id)
if (legacyCoordinatorRunId && existing?.run_id !== legacyCoordinatorRunId) {
throw new Error(`Gate not found: ${params.id}`)
}
const gate = db.resolveGate(params.id, params.resolution)
if (!gate) {
throw new Error(`Gate not found: ${params.id}`)
@@ -1,6 +1,6 @@
import { z } from 'zod'
import { defineMethod, type RpcMethod } from '../core'
import { OptionalString, requiredString } from '../schemas'
import { OptionalBoolean, OptionalString, requiredString } from '../schemas'
import type { OrcaRuntimeService } from '../../orca-runtime'
import { OrchestrationError } from '../../orchestration/orchestration-error'
@@ -11,7 +11,8 @@ const RunCreateParams = z.object({
const RunUseParams = z.object({
id: requiredString('Missing --id'),
from: requiredString('Missing coordinator terminal')
from: requiredString('Missing coordinator terminal'),
takeoverLegacy: OptionalBoolean
})
const RunCurrentParams = z.object({ from: requiredString('Missing coordinator terminal') })
@@ -51,14 +52,33 @@ export const ORCHESTRATION_RUN_METHODS: RpcMethod[] = [
defineMethod({
name: 'orchestration.runUse',
params: RunUseParams,
handler: (params, { runtime }) => {
handler: (
params,
{
runtime,
legacyCoordinatorAuthority,
orchestrationCompatibilityCallerAuthority: callerAuthority
}
) => {
const paneKey = requireCallerPane(runtime, params.from)
if (
params.takeoverLegacy &&
(callerAuthority?.terminalHandle !== params.from || callerAuthority.paneKey !== paneKey)
) {
throw new OrchestrationError(
'legacy_read_only',
'Legacy takeover must be invoked by the live coordinator agent terminal it will bind. No effects were applied.',
{ effectsApplied: false }
)
}
const db = runtime.getOrchestrationDb()
const priorRun = db.getCurrentRunForPane(paneKey)
const run = db.bindRun({
runId: params.id,
coordinatorHandle: params.from,
coordinatorPaneKey: paneKey
coordinatorPaneKey: paneKey,
takeoverLegacy: params.takeoverLegacy,
legacyCoordinatorAuthority
})
if (!run) {
throw new OrchestrationError(
@@ -36,6 +36,21 @@ export type WorkerSetupReceipt = {
| 'not_applicable'
}
export function requireWorkerAuthority(runtime: OrcaRuntimeService, terminalHandle: string) {
const authority = runtime.getOrchestrationDispatchAuthority(terminalHandle)
const paneKey = authority?.paneKey ?? runtime.getTerminalPaneKey(terminalHandle)
const processIncarnation =
authority?.processIncarnation ?? runtime.getTerminalProcessIncarnation(terminalHandle)
if (!paneKey || !processIncarnation) {
throw new Error('stable_pane_required')
}
return {
paneKey,
processIncarnation,
...(authority?.launchTokenHash ? { launchTokenHash: authority.launchTokenHash } : {})
}
}
export async function createExistingWorktreeWorkerTerminal(args: {
runtime: OrcaRuntimeService
worktreeId: string
@@ -10,6 +10,7 @@ import {
createExistingWorktreeWorkerTerminal,
createWorkerWorktree,
monitorWorkerSetup,
requireWorkerAuthority,
type WorkerEffect,
type WorkerSetupReceipt
} from './orchestration-worker-topology'
@@ -235,16 +236,11 @@ export const ORCHESTRATION_WORKER_START_METHODS: RpcMethod[] = [
: `Agent did not become ready (${wait.status}).`
)
}
const paneKey = runtime.getTerminalPaneKey(terminalHandle)
const processIncarnation = runtime.getTerminalProcessIncarnation(terminalHandle)
if (!paneKey || !processIncarnation) {
throw new Error('stable_pane_required')
}
const terminalAuthority = requireWorkerAuthority(runtime, terminalHandle)
const capability = db.prepareStartingWorkerAuthority({
dispatchId: started.dispatch.id,
handle: terminalHandle,
paneKey,
processIncarnation,
...terminalAuthority,
worktreeId: resolvedWorktree.id,
effects,
setupState: setupReceipt.state
@@ -1918,6 +1918,30 @@ describe('orchestration RPC methods', () => {
expect(db.getDispatchContextById(result.dispatch.id)?.assignee_pane_key).toBe('tab_w:leaf_w')
})
it('commits the target process launch token on a manual dispatch', async () => {
setup()
vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockReturnValue({
runtimeId: runtime.getRuntimeId(),
terminalHandle: 'term_a',
ptyId: 'pty_a',
worktreeId: 'repo::worktree',
paneKey: 'tab_w:leaf_w',
processIncarnation: 'runtime_test:term_a:1',
launchTokenHash: 'launch-token-hash',
hostScope: { kind: 'local', hostId: 'local' }
})
const task = db.createTask({ spec: 'work' })
const result = (await call('orchestration.dispatch', {
task: task.id,
to: 'term_a'
})) as { dispatch: { id: string } }
expect(db.getDispatchContextById(result.dispatch.id)?.launch_token_hash).toBe(
'launch-token-hash'
)
})
it('rejects dispatch for a pending task', async () => {
setup()
const parent = db.createTask({ spec: 'parent' })
@@ -2162,6 +2186,32 @@ describe('orchestration RPC methods', () => {
)
})
it('commits the launched worker token with its durable authority', async () => {
setup()
mockCurrentWorkerStart()
vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockReturnValue({
runtimeId: runtime.getRuntimeId(),
terminalHandle: 'term_worker',
ptyId: 'pty_worker',
worktreeId: 'repo::worktree',
paneKey: 'tab_worker:leaf_worker',
processIncarnation: 'runtime_test:term_worker:1',
launchTokenHash: 'worker-launch-token-hash',
hostScope: { kind: 'local', hostId: 'local' }
})
const task = db.createTask({ spec: 'persist worker identity' })
const result = (await call('orchestration.workerStart', {
task: task.id,
from: 'term_coord',
agent: 'codex'
})) as { dispatchId: string }
expect(db.getDispatchContextById(result.dispatchId)?.launch_token_hash).toBe(
'worker-launch-token-hash'
)
})
it('surfaces a worker terminal reveal failure without discarding the live worker', async () => {
setup()
mockCurrentWorkerStart()
+167 -21
View File
@@ -2,7 +2,12 @@
import { z } from 'zod'
import { defineMethod, type RpcMethod } from '../core'
import { OptionalFiniteNumber, OptionalString, OptionalBoolean, requiredString } from '../schemas'
import type { MessageType, MessagePriority, TaskStatus } from '../../orchestration/db'
import {
LEGACY_CONTRACT_VERSION,
type MessageType,
type MessagePriority,
type TaskStatus
} from '../../orchestration/db'
import { MESSAGE_TYPES } from '../../orchestration/types'
import { buildDispatchPreamble } from '../../orchestration/preamble'
import { formatMessageBanner } from '../../orchestration/formatter'
@@ -51,6 +56,10 @@ function parseRemoteWorkerPayload(payload: string | undefined): Record<string, u
}
}
function isWorkerReportOutcome(value: unknown): value is 'succeeded' | 'failed' {
return value === 'succeeded' || value === 'failed'
}
const SendParams = z
.object({
to: OptionalString,
@@ -107,6 +116,9 @@ const CheckParams = z
// Why: one-release RPC compatibility only; the public CLI uses --format because no terminal input is injected.
inject: OptionalBoolean,
ack: OptionalString,
compatibilityAck: OptionalString,
compatibilityQuestionAck: OptionalString,
compatibilityCliCommand: z.enum(['orca', 'orca-ide', 'orca-dev']).optional(),
run: OptionalString,
wait: OptionalBoolean,
timeoutMs: OptionalFiniteNumber
@@ -205,7 +217,9 @@ const AskParams = z
options: OptionalString,
timeoutMs: OptionalFiniteNumber,
from: OptionalString,
run: OptionalString
run: OptionalString,
compatibilityCliCommand: z.enum(['orca', 'orca-ide', 'orca-dev']).optional(),
compatibilityWindowsCommand: z.enum(['orca', 'orca-ide']).optional()
})
.superRefine((params, ctx) => {
if ((params.question ? 1 : 0) + (params.resume ? 1 : 0) !== 1) {
@@ -241,6 +255,7 @@ function resolveRunScope(
callerTerminalHandle?: string
callerPaneKey?: string
requireCurrentConsumer: boolean
legacyCoordinatorRunId?: string
}
): RunRow {
const db = runtime.getOrchestrationDb()
@@ -252,6 +267,9 @@ function resolveRunScope(
if (!params.requireCurrentConsumer && explicit) {
return explicit
}
if (explicit && params.legacyCoordinatorRunId === explicit.id) {
return explicit
}
if (!params.callerTerminalHandle) {
throw new OrchestrationError(
'run_required',
@@ -366,6 +384,49 @@ function resolveMessageRun(
return { run, dispatchId: dispatch?.id ?? dispatchId }
}
function legacyWorkerDeliveryContract(
runtime: OrcaRuntimeService,
runId: string | undefined,
recipient: string
): 'legacy_direct' | undefined {
if (!runId) {
return undefined
}
if (!recipient.startsWith('dispatch:')) {
return runtime
.getOrchestrationDb()
.resolveLegacyWorkerCandidate({ runId, terminalHandle: recipient })
? 'legacy_direct'
: undefined
}
const dispatch = runtime
.getOrchestrationDb()
.getDispatchContextById(recipient.slice('dispatch:'.length))
return dispatch?.run_id === runId &&
dispatch.contract_version === LEGACY_CONTRACT_VERSION &&
(dispatch.status === 'pending' || dispatch.status === 'dispatched')
? 'legacy_direct'
: undefined
}
function interruptedAcknowledgedCheck(
runId: string,
acknowledged: string,
reason: 'consumer_fenced' | 'outcome_unknown' | 'waiter_exists'
): Record<string, unknown> {
return {
runId,
deliveryId: null,
messages: [],
count: 0,
acknowledged,
timedOut: false,
cancelled: false,
connectionLost: false,
waitInterrupted: reason
}
}
function rejectFederatedExplicitTarget(params: { to?: string; run?: string }): void {
if (params.to || params.run) {
throw new OrchestrationError(
@@ -382,7 +443,10 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
defineMethod({
name: 'orchestration.send',
params: SendParams,
handler: async (params, { runtime, orchestrationCapability }) => {
handler: async (
params,
{ runtime, orchestrationCapability, legacyCoordinatorRunId, revalidateLegacyCoordinator }
) => {
const db = runtime.getOrchestrationDb()
const from = params.from ?? 'unknown'
// Why: caller-supplied pane fields are only compatibility metadata; lifecycle authority uses the runtime-observed pane plus capability.
@@ -463,6 +527,15 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
runId: params.run,
payload: params.payload
})
if (
params.type === 'worker_done' &&
!isWorkerReportOutcome(parseRemoteWorkerPayload(params.payload).outcome)
) {
throw new OrchestrationError(
'invalid_argument',
'worker_done requires outcome=succeeded|failed for a current Dispatch.'
)
}
if (params.to?.startsWith('task:')) {
throw new OrchestrationError(
'invalid_argument',
@@ -514,6 +587,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
'Coordinator-to-worker control mail cannot report worker lifecycle.'
)
}
revalidateLegacyCoordinator?.()
const relay = db.enqueueFederationRelay({
dispatchId,
direction: 'to_worker',
@@ -540,6 +614,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
}
}
// Point-to-point — existing single-recipient behavior
revalidateLegacyCoordinator?.()
const msg = db.insertMessage({
from,
to,
@@ -550,7 +625,12 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
threadId: params.threadId,
payload: params.payload,
senderPaneKey,
runId: routing.run?.id
runId: routing.run?.id,
deliveryContract: legacyWorkerDeliveryContract(
runtime,
routing.run?.id ?? legacyCoordinatorRunId,
to
)
})
const dispatch = routing.dispatchId
? db.getDispatchContextById(routing.dispatchId)
@@ -607,6 +687,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
throw new Error(`No recipients resolved for group address: ${to}`)
}
revalidateLegacyCoordinator?.()
const threadId = params.threadId ?? `thread_${Date.now()}`
const messages = handles.map((handle) =>
db.insertMessage({
@@ -619,7 +700,12 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
threadId,
payload: params.payload,
senderPaneKey,
runId: routing.run?.id
runId: routing.run?.id,
deliveryContract: legacyWorkerDeliveryContract(
runtime,
routing.run?.id ?? legacyCoordinatorRunId,
handle
)
})
)
for (const message of messages) {
@@ -633,7 +719,16 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
defineMethod({
name: 'orchestration.check',
params: CheckParams,
handler: async (params, { runtime, signal }) => {
handler: async (
params,
{
runtime,
signal,
legacyCoordinatorRunId,
revalidateLegacyCoordinator,
recordMutationReceipt
}
) => {
const db = runtime.getOrchestrationDb()
const handle = params.terminal ?? 'unknown'
const typeFilter = parseMessageTypes(params.types)
@@ -646,7 +741,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
runId: params.run,
callerTerminalHandle: handle,
callerPaneKey: paneKey ?? undefined,
requireCurrentConsumer: true
requireCurrentConsumer: true,
legacyCoordinatorRunId
})
const generation = run.consumer_generation
const address = `run:${run.id}`
@@ -659,6 +755,11 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
deliveryId: params.ack
})
: undefined
if (acknowledged) {
recordMutationReceipt?.(
interruptedAcknowledgedCheck(run.id, acknowledged.delivery.id, 'outcome_unknown')
)
}
if (params.peek || params.all || params.unread === false) {
const history = db.getRunMailboxHistory(run.id, 100, typeFilter)
const messages =
@@ -722,14 +823,28 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
signal,
exclusive: true
})
try {
revalidateLegacyCoordinator?.()
} catch (error) {
if (!acknowledged) {
throw error
}
return interruptedAcknowledgedCheck(run.id, acknowledged.delivery.id, 'consumer_fenced')
}
const latestRun = db.getRun(run.id)
if (!latestRun || latestRun.consumer_generation !== generation) {
if (acknowledged) {
return interruptedAcknowledgedCheck(run.id, acknowledged.delivery.id, 'consumer_fenced')
}
throw new OrchestrationError(
'consumer_fenced',
'This mailbox consumer was replaced while waiting.'
)
}
if (waitResult === 'waiter_exists') {
if (acknowledged) {
return interruptedAcknowledgedCheck(run.id, acknowledged.delivery.id, 'waiter_exists')
}
throw new OrchestrationError(
'waiter_exists',
`Run ${run.id} already has an active actionable waiter.`
@@ -911,13 +1026,28 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
defineMethod({
name: 'orchestration.reply',
params: ReplyParams,
handler: async (params, { runtime }) => {
handler: async (params, { runtime, legacyCoordinatorRunId }) => {
const db = runtime.getOrchestrationDb()
const original = db.getMessageById(params.id)
if (!original) {
throw new Error(`Message not found: ${params.id}`)
}
if (original.run_id === ORCHESTRATION_LEGACY_RUN_ID) {
if (
legacyCoordinatorRunId &&
(original.run_id !== legacyCoordinatorRunId ||
(params.run !== undefined && params.run !== legacyCoordinatorRunId))
) {
throw new OrchestrationError(
'request_mismatch',
`Message ${params.id} does not belong to this adopted Run.`,
{ effectsApplied: false }
)
}
if (
original.run_id === ORCHESTRATION_LEGACY_RUN_ID ||
original.delivery_contract === 'legacy_direct' ||
original.delivery_contract === 'audit_only'
) {
throw new OrchestrationError(
'legacy_read_only',
'Legacy orchestration messages are inspect-only; no reply was applied.',
@@ -930,7 +1060,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
const run = resolveRunScope(runtime, {
runId: params.run ?? question.run_id,
callerTerminalHandle: params.from,
requireCurrentConsumer: true
requireCurrentConsumer: true,
legacyCoordinatorRunId
})
const answered = db.answerQuestion({
messageId: question.message_id,
@@ -993,7 +1124,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
defineMethod({
name: 'orchestration.taskCreate',
params: TaskCreateParams,
handler: (params, { runtime }) => {
handler: (params, { runtime, legacyCoordinatorRunId }) => {
const db = runtime.getOrchestrationDb()
let deps: string[] | undefined
if (params.deps) {
@@ -1017,7 +1148,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
runId: resolveRunScope(runtime, {
runId: params.run,
callerTerminalHandle: params.callerTerminalHandle,
requireCurrentConsumer: true
requireCurrentConsumer: true,
legacyCoordinatorRunId
}).id
})
return { task }
@@ -1027,7 +1159,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
defineMethod({
name: 'orchestration.taskList',
params: TaskListParams,
handler: (params, { runtime }) => {
handler: (params, { runtime, legacyCoordinatorRunId }) => {
const db = runtime.getOrchestrationDb()
const explicitRun = params.run ? db.getRun(params.run) : undefined
const run =
@@ -1036,7 +1168,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
: resolveRunScope(runtime, {
runId: params.run,
callerTerminalHandle: params.callerTerminalHandle,
requireCurrentConsumer: params.run === undefined
requireCurrentConsumer: params.run === undefined,
legacyCoordinatorRunId
})
// Why: listTasksWithDispatch adds assignee_handle + dispatch_id (NULL for non-dispatched), so legacy-shape consumers are unaffected.
const joined = db.listTasksWithDispatch({
@@ -1063,12 +1196,13 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
defineMethod({
name: 'orchestration.taskUpdate',
params: TaskUpdateParams,
handler: (params, { runtime }) => {
handler: (params, { runtime, legacyCoordinatorRunId }) => {
const db = runtime.getOrchestrationDb()
const run = resolveRunScope(runtime, {
runId: params.run,
callerTerminalHandle: params.callerTerminalHandle,
requireCurrentConsumer: true
requireCurrentConsumer: true,
legacyCoordinatorRunId
})
const existing = db.getTask(params.id)
if (!existing || existing.run_id !== run.id) {
@@ -1088,7 +1222,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
defineMethod({
name: 'orchestration.dispatch',
params: DispatchParams,
handler: async (params, { runtime }) => {
handler: async (params, { runtime, legacyCoordinatorRunId, revalidateLegacyCoordinator }) => {
const db = runtime.getOrchestrationDb()
const task = db.getTask(params.task)
if (!task) {
@@ -1097,7 +1231,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
const run = resolveRunScope(runtime, {
runId: params.run,
callerTerminalHandle: params.from,
requireCurrentConsumer: true
requireCurrentConsumer: true,
legacyCoordinatorRunId
})
if (task.run_id !== run.id) {
throw new OrchestrationError(
@@ -1143,8 +1278,13 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
}
}
const assigneePaneKey = runtime.getTerminalPaneKey(to) ?? undefined
const processIncarnation = runtime.getTerminalProcessIncarnation(to) ?? undefined
const dispatchAuthority = runtime.getOrchestrationDispatchAuthority(to)
const assigneePaneKey =
dispatchAuthority?.paneKey ?? runtime.getTerminalPaneKey(to) ?? undefined
const processIncarnation =
dispatchAuthority?.processIncarnation ??
runtime.getTerminalProcessIncarnation(to) ??
undefined
if (params.inject && (!assigneePaneKey || !processIncarnation)) {
throw new OrchestrationError(
'stable_pane_required',
@@ -1152,7 +1292,13 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
)
}
const ctx = db.createDispatchContext(params.task, to, assigneePaneKey)
revalidateLegacyCoordinator?.()
const ctx = db.createDispatchContext(
params.task,
to,
assigneePaneKey,
dispatchAuthority?.launchTokenHash ?? undefined
)
const dispatchCapability = params.inject
? db.mintDispatchCapability({
dispatchId: ctx.id,