diff --git a/skill-guides/orchestration.md b/skill-guides/orchestration.md index ebcf3630fe4..eebead5caba 100644 --- a/skill-guides/orchestration.md +++ b/skill-guides/orchestration.md @@ -104,12 +104,14 @@ precedence over the idle rule. Do not reuse the settled lifecycle IDs. ## Canonical supervised loop -Confirm the runtime, bind one Run, and start the full independent wave before -waiting. `worker-start --spec` creates the Task and its attempt in one call: +Confirm the runtime and start the full independent wave before waiting. +`worker-start --spec` creates the Task and its attempt in one call; with no Run +bound, it also creates one bound to you (an older Orca refuses instead; then +`run-create` first). Its receipt's `run` names the Run it created or joined; if +that is an earlier goal's Run, `run-create` first: ```text ORCA status --json -ORCA orchestration run-create --objective "" --json ORCA orchestration worker-start --spec "" --worktree current --agent codex --json ORCA orchestration worker-start --spec "" --worktree current --agent claude --json ORCA orchestration check --wait --types "worker_done,escalation,question" --timeout-ms 900000 --json @@ -125,8 +127,9 @@ If `worker-start` exits non-zero, do not relaunch. Read the receipt's `failedStage` and `residualResources`, then load `references/recovery-and-cleanup.md`. -Use `task-create` plus `worker-start --task ` for planned fan-out with -dependencies or a retry of a known Task. Use dependencies only for real ordering +Use `run-create --objective ""`, then `task-create` plus +`worker-start --task `, for planned fan-out with dependencies or a +retry of a known Task. Use dependencies only for real ordering and prefer parallel waves over chains deeper than three or four steps; nested workers obey the depth limit, and a new Run does not reset the caller's depth. A dispatched worker starts its own helpers with `worker-start --spec` on the Run diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index bfeb0d4946d..5fc3b4517ec 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -2439,12 +2439,14 @@ const ORCHESTRATION_MARKDOWN = [ "", "## Canonical supervised loop", "", - "Confirm the runtime, bind one Run, and start the full independent wave before", - "waiting. `worker-start --spec` creates the Task and its attempt in one call:", + "Confirm the runtime and start the full independent wave before waiting.", + "`worker-start --spec` creates the Task and its attempt in one call; with no Run", + "bound, it also creates one bound to you (an older Orca refuses instead; then", + "`run-create` first). Its receipt's `run` names the Run it created or joined; if", + "that is an earlier goal's Run, `run-create` first:", "", "```text", "ORCA status --json", - "ORCA orchestration run-create --objective \"\" --json", "ORCA orchestration worker-start --spec \"\" --worktree current --agent codex --json", "ORCA orchestration worker-start --spec \"\" --worktree current --agent claude --json", "ORCA orchestration check --wait --types \"worker_done,escalation,question\" --timeout-ms 900000 --json", @@ -2460,8 +2462,9 @@ const ORCHESTRATION_MARKDOWN = [ "`failedStage` and `residualResources`, then load", "`references/recovery-and-cleanup.md`.", "", - "Use `task-create` plus `worker-start --task ` for planned fan-out with", - "dependencies or a retry of a known Task. Use dependencies only for real ordering", + "Use `run-create --objective \"\"`, then `task-create` plus", + "`worker-start --task `, for planned fan-out with dependencies or a", + "retry of a known Task. Use dependencies only for real ordering", "and prefer parallel waves over chains deeper than three or four steps; nested", "workers obey the depth limit, and a new Run does not reset the caller's depth.", "A dispatched worker starts its own helpers with `worker-start --spec` on the Run", diff --git a/src/cli/handlers/orchestration/worker-output.ts b/src/cli/handlers/orchestration/worker-output.ts index 7de970fabe6..55a95c624c3 100644 --- a/src/cli/handlers/orchestration/worker-output.ts +++ b/src/cli/handlers/orchestration/worker-output.ts @@ -9,6 +9,7 @@ export type LegacyWorkerReadResult = { export type WorkerStartReceipt = { mode?: { detail: string } + run?: { id: string; objective: string; created: boolean } taskId: string dispatchId: string state: string @@ -22,6 +23,11 @@ export type WorkerStartReceipt = { export function formatWorkerStart(value: WorkerStartReceipt): string { const lines = [`Worker ${value.dispatchId} [${value.state}] for ${value.taskId}`] + if (value.run) { + lines.push( + `${value.run.created ? 'Created and bound Run' : 'In Run'} ${value.run.id}: ${value.run.objective}` + ) + } // Show the mode that actually ran so a fallback from the user's default is visible. if (value.mode) { lines.push(value.mode.detail) diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts index 99265c751e9..d395e4f326f 100644 --- a/src/cli/specs/orchestration-worker-specs.ts +++ b/src/cli/specs/orchestration-worker-specs.ts @@ -33,6 +33,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ ], identityFlagRoles: { from: 'caller', terminal: 'target' }, notes: [ + 'With --spec and no bound Run, a coordinator gets a new Run bound to it, named after the Task title; the receipt names the Run it created or joined.', 'Current and existing worktrees never rerun setup; a fresh agent terminal is created unless --terminal is explicit.', 'When reusing --terminal, pass --worktree for that terminal; current means the coordinator worktree.', "Reusing a settled worker's terminal with --terminal before its autoReleaseAt cancels that automatic release; after it, the start is refused while the release runs.", diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts index 5ed5e68b7a4..cb148302260 100644 --- a/src/cli/specs/orchestration.ts +++ b/src/cli/specs/orchestration.ts @@ -10,7 +10,7 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ allowedFlags: [...GLOBAL_FLAGS, 'objective', 'from', 'retry-request'], identityFlagRoles: { from: 'caller' }, notes: [ - 'A Run is a namespace and home inbox. It never schedules or places workers.', + 'A Run is a namespace and home inbox. It never schedules or places workers. worker-start --spec creates one when none is bound; use run-create for Task graphs or a new goal.', '--retry-request is only for exact recovery after an unknown mutation result.' ] }, diff --git a/src/main/runtime/rpc/methods/orchestration/runs/runs.ts b/src/main/runtime/rpc/methods/orchestration/runs/runs.ts index c2d5bd4d23d..3d15cbfbb8f 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/runs.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/runs.ts @@ -5,6 +5,7 @@ import { assertCallerHandleMatchesEvidence, resolveOrchestrationCaller } from '. import { exposeRun } from './run-receipt' import type { OrcaRuntimeService } from '../../../../orca-runtime' import type { OrchestrationCallerIdentity } from '../../../../orchestration/orchestration-caller-identity' +import type { RunRow } from '../../../../orchestration/types' import { currentDispatchAssigneeRun } from '../messaging/recipient-routing' import { RunCreateParams, @@ -26,6 +27,29 @@ function cancelBoundDispatchWaiters( } } +/** Create a Run and bind it to the caller, as `run-create` does; one-step `worker-start` reuses it. */ +export function createBoundRun( + runtime: OrcaRuntimeService, + caller: OrchestrationCallerIdentity, + from: string, + objective: string +): RunRow { + const db = runtime.getOrchestrationDb() + const priorRun = db.getCurrentRunForCoordinator(caller) + const run = db.createRun({ + objective, + coordinatorHandle: caller.terminalHandle, + coordinatorPaneKey: caller.paneKey, + coordinatorOrcaSessionId: caller.orcaSessionId + }) + runtime.cancelMessageWaiters(from) + cancelBoundDispatchWaiters(runtime, caller, run.id) + if (priorRun) { + runtime.cancelMessageWaiters(`run:${priorRun.id}`) + } + return run +} + export const ORCHESTRATION_RUN_METHODS = [ defineMethod({ name: 'orchestration.runCreate', @@ -38,20 +62,7 @@ export const ORCHESTRATION_RUN_METHODS = [ callerSession: orchestrationCaller, requireStablePane: true }) - const db = runtime.getOrchestrationDb() - const priorRun = db.getCurrentRunForCoordinator(caller) - const run = db.createRun({ - objective: params.objective, - coordinatorHandle: caller.terminalHandle, - coordinatorPaneKey: caller.paneKey, - coordinatorOrcaSessionId: caller.orcaSessionId - }) - runtime.cancelMessageWaiters(params.from) - cancelBoundDispatchWaiters(runtime, caller, run.id) - if (priorRun) { - runtime.cancelMessageWaiters(`run:${priorRun.id}`) - } - return { run: exposeRun(run) } + return { run: exposeRun(createBoundRun(runtime, caller, params.from, params.objective)) } } }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts index c63cee713d4..f6386d45705 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts @@ -165,6 +165,41 @@ describe('orchestration RPC methods', () => { ) }) + it('creates and binds a Run for an unbound coordinator, then names it on reuse', async () => { + setup(false) + mockCurrentWorkerStart() + const start = () => + call('orchestration.workerStart', { + spec: 'Audit the parser\nCheck every branch.', + from: 'term_coord', + agent: 'codex' + }) + + const first = await start() + const bound = db.getCurrentRunForCoordinator({ + terminalHandle: 'term_coord', + paneKey: coordinatorPaneKey, + orcaSessionId: null + }) + const run = { id: bound?.id, objective: 'Audit the parser' } + expect(first).toMatchObject({ state: 'ready', run: { ...run, created: true } }) + expect(await start()).toMatchObject({ run: { ...run, created: false } }) + }) + + it('creates no Run when an unbound coordinator names an existing Task', async () => { + setup(false) + mockCurrentWorkerStart() + + await expect( + call('orchestration.workerStart', { + task: 'task_missing', + from: 'term_coord', + agent: 'codex' + }) + ).rejects.toMatchObject({ code: 'consumer_fenced' }) + expect(db.listRuns().runs.filter((run) => run.legacy === 0)).toEqual([]) + }) + it('applies and reports opaque per-invocation model preferences', async () => { setup() mockCurrentWorkerStart() diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts index 8c925a46c52..be74617d343 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-authority.ts @@ -7,8 +7,10 @@ import type { import type { DispatchContextRow, RunRow, TaskRow } from '../../../../orchestration/types' import type { OrcaRuntimeService } from '../../../../orca-runtime' import { resolveDispatchCreator } from '../runs/dispatch-creator' +import { createBoundRun } from '../runs/runs' +import { ROOT_DISPATCH_DEPTH } from '../../../../../../shared/nested-worker-depth' -/** Coordinators start workers in their Run; active workers start helpers as themselves so reports return to their Dispatch without moving its mailbox. */ +/** Coordinators start workers in their Run, creating one when none is bound; active workers start helpers as themselves so reports return to their Dispatch without moving its mailbox. */ export function resolveWorkerStartRun( runtime: OrcaRuntimeService, args: { @@ -16,8 +18,10 @@ export function resolveWorkerStartRun( from: string callerSession: OrchestrationSessionCaller | undefined runId: string | undefined + /** Objective for a Run this start may create; absent when it names an existing Task. */ + objective: string | undefined } -): { run: RunRow; helperCreator?: DispatchContextRow } { +): { run: RunRow; runCreated: boolean; helperCreator?: DispatchContextRow } { const db = runtime.getOrchestrationDb() const coordinated = args.coordinator ? db.getCurrentRunForCoordinator(args.coordinator) @@ -26,25 +30,36 @@ export function resolveWorkerStartRun( if (args.runId && args.runId !== coordinated.id) { throw fenced(`This caller coordinates Run ${coordinated.id}, not ${args.runId}.`) } - return { run: coordinated } + return { run: coordinated, runCreated: false } } // Use the same active delegated Dispatch for authority and creator/reporting identity; remote Dispatches have no local row. - const creatorId = db.resolveCreatorDispatchId( - resolveDispatchCreator(runtime, args.from, args.callerSession) - ) + const dispatchCreator = resolveDispatchCreator(runtime, args.from, args.callerSession) + const creatorId = db.resolveCreatorDispatchId(dispatchCreator) const creator = creatorId ? db.getDispatchContextById(creatorId) : undefined const run = creator ? db.getRun(creator.run_id) : undefined - if (!creator || !run || run.legacy === 1) { - throw fenced( - 'worker-start needs the coordinator bound to the Run, or a worker on an active Dispatch in it.' - ) + if (creator && run && run.legacy !== 1) { + if (args.runId && args.runId !== run.id) { + throw fenced( + `This worker's Dispatch ${creator.id} is in Run ${run.id}; it starts helpers only there.` + ) + } + return { run, runCreated: false, helperCreator: creator } } - if (args.runId && args.runId !== run.id) { - throw fenced( - `This worker's Dispatch ${creator.id} is in Run ${run.id}; it starts helpers only there.` - ) + // Only a root caller gets a new Run, so a worker can never reset its depth this way. + if ( + args.coordinator && + args.objective && + !args.runId && + db.resolveCreatorDepth(dispatchCreator) === ROOT_DISPATCH_DEPTH + ) { + return { + run: createBoundRun(runtime, args.coordinator, args.from, args.objective), + runCreated: true + } } - return { run, helperCreator: creator } + throw fenced( + 'worker-start needs the coordinator bound to the Run, or a worker on an active Dispatch in it.' + ) } /** Workers may launch fresh local helpers or retry their own helper's latest Attempt, never coordinator Tasks or another party's pane. */ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts index eb5ef4aca8f..38937b74f01 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts @@ -13,6 +13,7 @@ import { isWorkerStartTimeoutWithinTimerLimit, resolveWorkerStartReadinessTimeoutMs } from '../../../../../../shared/orchestration-timing-budgets' +import { buildOrchestrationTaskDisplayMetadata } from '../../../../../../shared/orchestration-task-display' import { assertWorkerStartTaskSpecWithinPromptBudget } from './worker-start-prompt-budget' import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../../shared/orca-session-address' import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as SESSION_CODES } from '../../../../../../shared/orchestration-session-caller-codes' @@ -32,34 +33,6 @@ export const ORCHESTRATION_WORKER_START_METHODS = [ '--timeout-ms is too large for worker-start transport grace; the derived timeout must fit within the timer limit.' ) } - const readinessTimeoutMs = resolveWorkerStartReadinessTimeoutMs(params.timeoutMs) - const db = runtime.getOrchestrationDb() - const coordinator = resolveOrchestrationCaller(runtime, { - callerTerminalHandle: params.from, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) - const { run, helperCreator } = resolveWorkerStartRun(runtime, { - coordinator, - from: params.from, - callerSession: orchestrationCaller, - runId: params.run - }) - const existingTask = params.task ? db.getTask(params.task) : undefined - if (params.task && (!existingTask || existingTask.run_id !== run.id)) { - throw new OrchestrationError( - 'task_not_found', - `Task ${params.task} was not found in Run ${run.id}.` - ) - } - if (helperCreator) { - assertHelperStartScope(db, helperCreator, { task: existingTask, params }) - } - await assertWorkerStartTaskSpecWithinPromptBudget(params.spec ?? existingTask!.spec) - const mode = decideWorkerStartMode({ - params, - settings: readWorkerStartModeSettings(runtime) - }) if (params.on && params.terminal?.startsWith(ORCA_SESSION_ADDRESS_PREFIX)) { // Refused here, before any remote call: an Orca session ID names a chat only on its own host. throw new OrchestrationError( @@ -68,6 +41,62 @@ export const ORCHESTRATION_WORKER_START_METHODS = [ { effectsApplied: false } ) } + const readinessTimeoutMs = resolveWorkerStartReadinessTimeoutMs(params.timeoutMs) + const db = runtime.getOrchestrationDb() + const coordinator = resolveOrchestrationCaller(runtime, { + callerTerminalHandle: params.from, + callerEvidence: orchestrationCompatibilityEvidence, + callerSession: orchestrationCaller + }) + if (params.spec) { + // Before the Run resolves, so a refused spec cannot leave a new Run bound. + await assertWorkerStartTaskSpecWithinPromptBudget(params.spec) + } + const { run, runCreated, helperCreator } = resolveWorkerStartRun(runtime, { + coordinator, + from: params.from, + callerSession: orchestrationCaller, + runId: params.run, + // The Run takes the title its first Task gets. + objective: params.spec + ? buildOrchestrationTaskDisplayMetadata({ + spec: params.spec, + taskTitle: params.taskTitle + }).taskTitle + : undefined + }) + // Name the Run in every receipt so a reused, stale binding is visible. + const withRun = (receipt: unknown): unknown => + receipt && typeof receipt === 'object' + ? { + ...receipt, + run: { + id: run.id, + objective: run.objective, + created: runCreated + } + } + : receipt + const existingTask = params.task ? db.getTask(params.task) : undefined + if (params.task && (!existingTask || existingTask.run_id !== run.id)) { + throw new OrchestrationError( + 'task_not_found', + `Task ${params.task} was not found in Run ${run.id}.` + ) + } + if (helperCreator) { + assertHelperStartScope(db, helperCreator, { + task: existingTask, + params + }) + } + if (existingTask) { + await assertWorkerStartTaskSpecWithinPromptBudget(existingTask.spec) + } + const mode = decideWorkerStartMode({ + params, + settings: readWorkerStartModeSettings(runtime) + }) if (params.on) { // Remote workers are terminal-only; carry the mode receipt to explain structured-preference fallback. const receipt = await startFederatedWorker({ @@ -79,20 +108,22 @@ export const ORCHESTRATION_WORKER_START_METHODS = [ orchestrationMutation, callerSession: orchestrationCaller }) - return receipt && typeof receipt === 'object' ? { ...receipt, mode } : receipt + return withRun(receipt && typeof receipt === 'object' ? { ...receipt, mode } : receipt) } - return startLocalWorker({ - params: { ...params, timeoutMs: readinessTimeoutMs }, - runtime, - db, - run, - coordinator, - callerSession: orchestrationCaller, - existingTask, - orchestrationMutation, - mode, - helperCreator - }) + return withRun( + await startLocalWorker({ + params: { ...params, timeoutMs: readinessTimeoutMs }, + runtime, + db, + run, + coordinator, + callerSession: orchestrationCaller, + existingTask, + orchestrationMutation, + mode, + helperCreator + }) + ) } }) ]