Skip to content
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
2f5930b
fix(orchestration): refuse run-use by a worker on the Run it works for
brennanb2025 Oct 15, 2026
110fb8f
fix(orchestration): tell a worker naming its own Run where its mail is
brennanb2025 Oct 15, 2026
f32d591
feat(orchestration): refuse run-use over a live coordinator without -…
brennanb2025 Oct 15, 2026
0d918d4
fix(orchestration): stop pointing workers at run-use
brennanb2025 Oct 15, 2026
51899d8
fix(orchestration): stop routing mail to addresses that grabbed a Run…
brennanb2025 Oct 15, 2026
7e73137
fix(cli): keep the orchestration spec file within its line limit
brennanb2025 Oct 15, 2026
e00c287
fix(orchestration): read remembered coordinator Run ids without a typ…
brennanb2025 Oct 15, 2026
a9a9dbb
fix(orchestration): compare seat-grab times at whole seconds
brennanb2025 Oct 15, 2026
0ee076e
fix(orchestration): a worker coordinates only Runs it created
brennanb2025 Oct 15, 2026
da2e196
fix(orchestration): say what happens to mail on takeover and stop nam…
brennanb2025 Oct 15, 2026
2a68fbb
refactor(orchestration): throw one non-null refusal from the live gate
brennanb2025 Oct 15, 2026
2b3b672
refactor(runtime): host the coordinator presence probe beside the hoo…
brennanb2025 Oct 15, 2026
dc1730a
fix(orchestration): use findLast for the worktree name
brennanb2025 Oct 15, 2026
cf73598
refactor(runtime): move the coordinator presence probe beside the pty…
brennanb2025 Oct 15, 2026
6c1eb61
fix(orchestration): keep workers out of their own Run seat
brennanb2025 Oct 15, 2026
a118df0
fix(orchestration): clarify worker Run handoffs in skill
brennanb2025 Oct 15, 2026
69818e2
test: align explicit Run gate refusal wording
brennanb2025 Oct 16, 2026
5bab97a
Merge remote-tracking branch 'origin/main' into brennanb2025/worker-c…
brennanb2025 Oct 16, 2026
7cef60c
Move coordinator presence beside terminal presence checks
brennanb2025 Oct 16, 2026
e066e0d
Merge remote-tracking branch 'origin/main' into brennanb2025/worker-c…
brennanb2025 Oct 16, 2026
61ffe2d
Walk complete worker creator lineage when binding Runs
brennanb2025 Oct 16, 2026
5688a64
Merge origin/main into brennanb2025/worker-cannot-bind-parent-run
brennanb2025 Oct 22, 2026
ff924f6
Restore main documentation after merge hook formatting
brennanb2025 Oct 22, 2026
0a85815
Merge origin/main into worker run binding fix
brennanb2025 Oct 23, 2026
e2e2ddf
perf(orchestration): check run bindings without terminal snapshots
brennanb2025 Oct 23, 2026
3787d57
test(orchestration): narrow SQLite instrumentation before access
brennanb2025 Oct 23, 2026
f5eccb8
test(orchestration): import the explicit RPC methods module
brennanb2025 Oct 23, 2026
ab1c437
test: cover orchestration restart and continued Run handoff
brennanb2025 Oct 23, 2026
dbadf5e
test: place orchestration CLI integration in CLI project
brennanb2025 Oct 23, 2026
d3c6c99
test(cli): use explicit module extensions in restart handoff test
brennanb2025 Oct 23, 2026
a865bf9
test(orchestration): isolate source CLI integration in subprocesses
brennanb2025 Oct 23, 2026
b2fbefe
refactor(orchestration): leave the live-coordinator takeover rule to …
brennanb2025 Oct 25, 2026
b9662bc
test(orchestration): cover delegated worker legacy takeover refusal
brennanb2025 Oct 26, 2026
6754bd2
Merge origin/main into orchestration worker binding fix
brennanb2025 Oct 26, 2026
fc7b415
test(orchestration): explain source CLI integration timeout
brennanb2025 Oct 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions skill-guides/orchestration.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,14 @@ ORCA orchestration worker-start --spec "<worker B task>" --worktree current --ag
ORCA orchestration check --wait --types "worker_done,escalation,question" --timeout-ms 900000 --json
```

After a restart, resume your own Run with `run-use --id <run_id>`. It is refused
while another coordinator of that Run is still running; replace it with
`--takeover` only when the user asks. A worker cannot bind the Run it works for
or an ancestor. When its coordinator directs a handoff, a replacement worker
may resume a separate Run with plain `run-use` after the prior coordinator is
no longer provably live. A worker cannot use either takeover flag to replace
another coordinator; an already-bound no-op remains allowed.

If `worker-start` exits non-zero, do not relaunch. Read the receipt's
`failedStage` and `residualResources`, then load
`references/recovery-and-cleanup.md`.
Expand Down
7 changes: 6 additions & 1 deletion skill-guides/orchestration/references/worker-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,12 @@ run — and once more immediately before `worker_done`, so a redirect or a
cancellation lands before the Task settles. `check` names its caller with
`--terminal`, never `--from`. Stop checking after `worker_done`.

If `check` returns `consumer_fenced`, this process no longer owns its Dispatch:
Do not use `run-use` to check your Dispatch's mail or bind the Run you work for.
You may resume a separate Run when your coordinator directs a handoff, but you
cannot use either takeover flag. Plain `check` returns your Dispatch's mail
unless you are coordinating a Run; report to your coordinator with `send`.

If a plain `check` (no `--run`) returns `consumer_fenced`, this process no longer owns its Dispatch:
the Attempt was re-attached to another worker or settled without you. Stop, do
not send `worker_done`, and do not retry the check. An empty `check` never means
you were replaced; `consumer_fenced` is the only way you learn that.
Expand Down
6 changes: 3 additions & 3 deletions src/cli/bundled-skill-guides.ts

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions src/cli/handlers/orchestration/run-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export const ORCHESTRATION_RUN_HANDLERS: Record<string, CommandHandler> = {
}>(client, flags, 'orchestration.runUse', {
id: getRequiredStringFlag(flags, 'id'),
from,
...(flags.has('takeover') ? { takeover: true } : {}),
...(flags.has('takeover-legacy') ? { takeoverLegacy: true } : {})
})
printResult(result, json, (r) => `Using Run ${r.run.id}: ${r.run.objective}`)
Expand Down
2 changes: 1 addition & 1 deletion src/cli/root-help-text-primary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [
'',
'Orchestration:',
' orchestration run-create Create and bind a lightweight orchestration Run',
' orchestration run-use Bind this coordinator to an existing Run',
' orchestration run-use Resume coordinating a Run (workers never use this)',
" orchestration run-current Show this coordinator's bound Run",
' orchestration run-list List lightweight orchestration Runs',
' orchestration run-show Show one lightweight orchestration Run',
Expand Down
8 changes: 4 additions & 4 deletions src/cli/specs/orchestration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
},
{
path: ['orchestration', 'run-use'],
summary: 'Bind this coordinator to an existing Run',
summary: 'Resume coordinating a Run',
usage:
'orca orchestration run-use --id <run_id> [--from <handle>] [--takeover-legacy] [--retry-request <id>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'id', 'from', 'takeover-legacy', 'retry-request'],
'orca orchestration run-use --id <run_id> [--from <handle>] [--takeover] [--takeover-legacy] [--retry-request <id>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'id', 'from', 'takeover', 'takeover-legacy', 'retry-request'],
identityFlagRoles: { from: 'caller' },
notes: [
'--takeover-legacy must run in the live coordinator agent terminal it binds; it preserves existing worker assignments.'
'Refused while another coordinator of the Run is still open; --takeover replaces it, and its unacknowledged mail is replayed to you. A worker cannot bind its own or ancestor Run or use either takeover flag. --takeover-legacy must run in the live coordinator agent terminal it binds; it preserves existing worker assignments.'
]
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,8 @@ describe('orchestration notification mailbox consistency', () => {
.map(([sql]) => sql)
.find((sql) => sql.includes('FROM run_coordinator_handles AS coordinator'))
expect(routingSql).toContain('INDEXED BY idx_messages_undelivered_direct_run')
expect(routingSql).not.toContain('NOT EXISTS')
// An anti-join per coordinator row is fine; one per candidate message would scan the backlog.
expect(routingSql).not.toMatch(/NOT EXISTS \([^)]*candidate\./)
expect(db.getMessageById(owned.id)?.to_handle).toBe(`run:${ownedRun.id}`)
expect(db.getUnreadDirectMessageTypes(detachedHandle)).toEqual(['status'])
db.close()
Expand Down
2 changes: 1 addition & 1 deletion src/main/runtime/orchestration/db/dispatch-depth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function recordedCreatorIdentity(creator: DispatchCreator): {
* terminal. Nothing was delegated, so it is not a nesting parent. Rows written before v37 record
* no creator and keep counting, which is the pre-v37 answer and fails closed.
*/
function isSelfCreatedDispatch(row: DispatchContextRow): boolean {
export function isSelfCreatedDispatch(row: DispatchContextRow): boolean {
if (row.creator_pane_key && row.assignee_pane_key) {
return isEquivalentPaneKey(row.creator_pane_key, row.assignee_pane_key)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { DispatchContextRow, MessageType } from '../../types'
import { DISPATCH_PANE_KEY_MATCH_SUFFIX_SQL, paneKeyMatchSuffix } from '../pane-key-match'
import type { OrchestrationDb } from '../orchestration-db'
import { DISPATCH_CONTEXT_COLUMN_LIST } from '../row-column-lists'
import { workerSeatGrabSql } from '../runs/run-coordinator-mail-routing'
import {
ORCHESTRATION_DELIVERY_BATCH_LIMIT,
type ForeignDirectMailboxRoutingPage
Expand Down Expand Up @@ -58,6 +59,7 @@ export function routeForeignDirectMessagesToOwnedMailboxes(
ON candidate.run_id = coordinator.run_id
AND candidate.to_handle = coordinator.terminal_handle
WHERE coordinator.terminal_handle = ?${runExclusion}
AND NOT ${workerSeatGrabSql('coordinator')}
AND candidate.read = 0 AND candidate.delivered_at IS NULL
AND candidate.delivery_contract = 'current_delivery'`,
`SELECT candidate.id, candidate.run_id, candidate.type, candidate.sequence
Expand Down
73 changes: 72 additions & 1 deletion src/main/runtime/orchestration/db/runs/run-binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import { LEGACY_CONTRACT_VERSION } from '../contract-constants'
import { isEquivalentPaneKey } from '../pane-key-match'
import type { OrchestrationDb } from '../orchestration-db'
import type { OrcaSessionId } from '../../../../../shared/orca-session-address'
import { findCallerWorkerDispatches, workerRunBindingRefusal } from './worker-run-binding'
import {
mailboxAddressOf,
runBoundToCoordinator,
runCoordinatorKey
runCoordinatorKey,
type OrchestrationCoordinatorKey
} from '../../orchestration-caller-identity'

export function bindRun(
Expand All @@ -19,6 +21,13 @@ export function bindRun(
/** The coordinator's bare Orca session id when it is a structured session; see orca-session-address. */
coordinatorOrcaSessionId?: OrcaSessionId | null
takeoverLegacy?: boolean
/** The user asked to replace a coordinator that is still open. */
takeover?: boolean
/**
* What the RPC layer saw just before this call: the Run's coordinator then, and how a user
* recognizes it when it was proven open. A binding that moved since is refused, never bound blindly.
*/
probed?: { coordinator: OrchestrationCoordinatorKey; liveLabel: string | null }
legacyCoordinatorAuthority?: {
runId: string
principalId: string | null
Expand All @@ -41,6 +50,17 @@ export function bindRun(
return undefined
}
const sameBinding = runBoundToCoordinator(run, coordinator)
const explicitTakeover = params.takeover === true || params.takeoverLegacy === true
// Why: before the legacy gate, so a worker never sees its --takeover-legacy recovery command.
const workerRefusal = sameBinding
? null
: workerRunBindingRefusal(this, coordinator, params.runId, {
takeover: explicitTakeover,
bind: true
})
if (workerRefusal) {
throw workerRefusal
}
const adoption = this.getLegacyAdoption()
const adoptedRun = adoption?.adopted_run_id === params.runId
const legacyAuthority = params.legacyCoordinatorAuthority
Expand Down Expand Up @@ -112,6 +132,13 @@ export function bindRun(
// Why: only LIVE legacy work needs the flag — settled work has no competing authority left, and
// fencing it would strand the recovered graph behind an attestation the caller may not have.
if (activeLegacyAssignment && !sameBinding && !provenLegacyBinding && !params.takeoverLegacy) {
if (findCallerWorkerDispatches(this, coordinator).length > 0) {
throw new OrchestrationError(
'consumer_fenced',
`Run ${params.runId} still has active legacy work and this caller cannot bind it. Nothing changed.`,
{ effectsApplied: false }
)
}
throw new OrchestrationError(
'consumer_fenced',
'This adopted Run still has live legacy work. Its attested coordinator may rebind it, or a current coordinator may explicitly use run-use --takeover-legacy.',
Expand All @@ -121,6 +148,23 @@ export function bindRun(
}
)
}
const probed = params.probed
if (probed && !sameBinding && !provenLegacyBinding && !explicitTakeover) {
if (!sameCoordinatorKey(runCoordinatorKey(run), probed.coordinator)) {
throw new OrchestrationError(
'run_binding_changed',
`Run ${params.runId}'s coordinator changed while this command ran. Nothing changed; run the same command again.`,
{ effectsApplied: false, retryable: true }
)
}
if (probed.liveLabel !== null) {
throw runCoordinatorLiveError(
params.runId,
probed.liveLabel,
findCallerWorkerDispatches(this, coordinator).length > 0
)
}
}
this.unbindOtherRunsForCoordinator(coordinator, params.runId)
// The mailbox address of the coordinator being replaced and of the one binding now.
for (const address of new Set([
Expand Down Expand Up @@ -186,6 +230,33 @@ export function bindRun(
return this.getRun(params.runId)
}

function sameCoordinatorKey(
a: OrchestrationCoordinatorKey,
b: OrchestrationCoordinatorKey
): boolean {
return (
a.terminalHandle === b.terminalHandle &&
a.paneKey === b.paneKey &&
a.orcaSessionId === b.orcaSessionId
)
}

// No recoveryCommand on purpose: agents run those mechanically, and the flag must carry user intent.
function runCoordinatorLiveError(
runId: string,
label: string,
worker: boolean
): OrchestrationError {
const takeoverAdvice = worker
? ''
: ` Take it over only if the user asks: orca orchestration run-use --id ${runId} --takeover replaces it, and its unacknowledged mail is replayed to you.`
return new OrchestrationError(
'run_coordinator_live',
`Run ${runId} is coordinated by ${label}, which is still open. Nothing changed. Closing it clears this.${takeoverAdvice}`,
{ effectsApplied: false, runId, coordinator: label }
)
}

export type RunBindingMethods = {
bindRun: typeof bindRun
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,48 @@
import type Database from '../../../../sqlite/sync-database'
import type { OrchestrationDb } from '../orchestration-db'
import { currentRunCoordinatorSessionAddressSql } from './run-coordinator-orca-session'
import { orcaSessionAddressSql } from '../orca-session-address-sql'

/** Mail to an active Dispatch assignee's address in the same Run is that worker's, not coordinator mail. */
export function activeDispatchOwnsAddressSql(runIdSql: string, addressSql: string): string {
return `EXISTS (
SELECT 1 FROM dispatch_contexts
WHERE dispatch_contexts.run_id = ${runIdSql}
AND dispatch_contexts.assignee_handle = ${addressSql}
AND (dispatch_contexts.assignee_handle = ${addressSql}
OR ${orcaSessionAddressSql('dispatch_contexts.assignee_orca_session_id')} = ${addressSql})
AND dispatch_contexts.status IN ('pending', 'dispatched')
)`
}

/**
* A remembered address first bound while it worked an unsettled, delegated Dispatch in the same Run
* was a worker grabbing the seat, not a spelling of the coordinator, so it never routes as one.
* Derived from the rows, so addresses older builds remembered stop mattering without editing them.
* julianday() because completed_at is stored in two text formats; whole seconds and a strict >
* because first_bound_at has no milliseconds, so a bind in the second a Dispatch settled is not a grab.
*/
export function workerSeatGrabSql(aliasRow: string): string {
return `EXISTS (
SELECT 1 FROM dispatch_contexts AS grab
WHERE grab.run_id = ${aliasRow}.run_id
AND (grab.assignee_handle = ${aliasRow}.terminal_handle
OR ${orcaSessionAddressSql('grab.assignee_orca_session_id')} = ${aliasRow}.terminal_handle)
AND NOT (grab.creator_handle IS NOT NULL AND grab.creator_handle = grab.assignee_handle)
AND julianday(grab.created_at) <= julianday(${aliasRow}.first_bound_at)
AND (grab.status IN ('pending', 'dispatched')
OR julianday(datetime(grab.completed_at)) > julianday(${aliasRow}.first_bound_at))
)`
}

/** Whether `addressSql` is a coordinator address of the Run `runIdSql`, seat grabs excluded. */
function coordinatorAliasSql(runIdSql: string, addressSql: string): string {
return `EXISTS (
SELECT 1 FROM run_coordinator_handles AS alias
WHERE alias.run_id = ${runIdSql} AND alias.terminal_handle = ${addressSql}
AND NOT ${workerSeatGrabSql('alias')}
)`
}

export function rememberRunCoordinatorHandle(
this: OrchestrationDb,
runId: string,
Expand Down Expand Up @@ -93,10 +124,7 @@ export function createCoordinatorMailRoutingTrigger(this: OrchestrationDb): void
SELECT 1 FROM runs
WHERE runs.id = NEW.run_id AND runs.legacy = 0
)
AND EXISTS (
SELECT 1 FROM run_coordinator_handles
WHERE run_id = NEW.run_id AND terminal_handle = NEW.to_handle
)
AND ${coordinatorAliasSql('NEW.run_id', 'NEW.to_handle')}
AND NOT ${activeDispatchOwnsAddressSql('NEW.run_id', 'NEW.to_handle')}
BEGIN
UPDATE messages SET to_handle = 'run:' || NEW.run_id WHERE sequence = NEW.sequence;
Expand All @@ -119,7 +147,12 @@ export function routeAllUnreadDirectMessagesToRunMailbox(
`UPDATE messages SET to_handle = ?
WHERE run_id = ? AND to_handle = ? AND read = 0
AND delivery_contract = 'current_delivery'
AND NOT ${activeDispatchOwnsAddressSql('messages.run_id', 'messages.to_handle')}`
AND NOT ${activeDispatchOwnsAddressSql('messages.run_id', 'messages.to_handle')}
AND NOT EXISTS (
SELECT 1 FROM run_coordinator_handles AS alias
WHERE alias.run_id = messages.run_id AND alias.terminal_handle = messages.to_handle
AND ${workerSeatGrabSql('alias')}
)`
)
.run(`run:${runId}`, runId, directHandle)
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/runtime/orchestration/db/runs/run-delivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export function requireCurrentConsumer(
if (!run || run.legacy === 1 || run.consumer_generation !== consumerGeneration) {
throw new OrchestrationError(
'consumer_fenced',
'This mailbox consumer has been replaced. Rebind with orchestration run-use.'
`Another session now coordinates Run ${runId}; stop reading this mailbox.`
)
}
return run
Expand Down
26 changes: 15 additions & 11 deletions src/main/runtime/orchestration/db/runs/run-lookup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { encodeRunListCursor, decodeRunListCursor } from '../run-list-cursor'
import type { RunListPage } from '../run-list-page'
import type { OrchestrationDb } from '../orchestration-db'
import { RUN_COLUMN_LIST } from '../row-column-lists'
import { workerSeatGrabSql } from './run-coordinator-mail-routing'

export type LegacyAdoptedMailboxOwner = {
runId: string
Expand Down Expand Up @@ -57,17 +58,20 @@ export function getRunMailboxOwnerIdsForHandle(
terminalHandle: string,
legacyAdoptedMailboxOwner?: LegacyAdoptedMailboxOwner | null
): string[] {
const runIds = (
this.db
.prepare(
`SELECT coordinator.run_id
FROM run_coordinator_handles AS coordinator
JOIN runs ON runs.id = coordinator.run_id AND runs.legacy = 0
WHERE coordinator.terminal_handle = ?
ORDER BY coordinator.run_id`
)
.all(terminalHandle) as { run_id: string }[]
).map((row) => row.run_id)
const runIds = this.db
.prepare(
`SELECT coordinator.run_id
FROM run_coordinator_handles AS coordinator
JOIN runs ON runs.id = coordinator.run_id AND runs.legacy = 0
WHERE coordinator.terminal_handle = ? AND NOT ${workerSeatGrabSql('coordinator')}
ORDER BY coordinator.run_id`
)
.all(terminalHandle)
.flatMap((row) =>
typeof row === 'object' && row !== null && 'run_id' in row && typeof row.run_id === 'string'
? [row.run_id]
: []
)
const adoptedOwner =
legacyAdoptedMailboxOwner === undefined
? this.getLegacyAdoptedRunMailboxOwner()
Expand Down
Loading
Loading