From 1f68d4d9446f6115b7c607b6bd8d1a68f9ada4f7 Mon Sep 17 00:00:00 2001 From: trvon Date: Thu, 19 Nov 2026 17:17:42 -0700 Subject: [PATCH] feat(orchestration): record the workflow phase a swarm was started from Phased work is a workflow whose states each run a swarm, but nothing tied a swarm to its phase, so progress views showed two unrelated controllers. A batch created while its session holds a live claim on exactly one active workflow now records that workflow, execution and state, and the create result names it. The link is display metadata. No claim, an expired claim, a paused workflow or several claims leave the batch unlinked, and the link is never consulted for dispatch, admission or transitions. --- AGENTS.md | 2 +- docs/REFERENCE.md | 2 +- src/orchestration-reducer.ts | 10 ++++- src/tools/subagent-orchestration-tools.ts | 21 ++++++++- src/types.ts | 10 +++++ test/orchestration-reducer.test.ts | 16 +++++++ test/orchestration-tools.test.ts | 54 +++++++++++++++++++++++ 7 files changed, 111 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7001c47..22bc335 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -61,7 +61,7 @@ A workflow is one dynamic `LoopEntry` with a version-1 named-state definition. An orchestration is one finite, session-file-backed `LoopEntry` batch. -- It accepts explicit independent work only; it never discovers TaskStore work or workflow executions. +- It accepts explicit independent work only; it never discovers TaskStore work or workflow executions as work to run. A batch started while its session holds exactly one live workflow claim records that phase (`phase`: workflow, execution, state) for display grouping only; the link never affects dispatch, admission, or transitions. - Creation requires a compatible provider (`@tintinweb/pi-subagents` protocol v2, or npm `pi-subagents` RPC v1) and rejects memory/project/custom/off storage. Worker access goes through `SubagentProvider` (`src/runtime/subagent-provider.ts`); the orchestration tools register only once a provider answers, and never unregister. The selected provider is kept for the runtime's lifetime. Provider differences (default agent type, turn limits, usage evidence) are declared on the adapter, never special-cased in the reducer. - Every dispatch is persisted before spawn and fenced by controller revision, owner runtime/generation, work ID, dispatch ID, attempt, and upstream agent ID. - `spawning`, `queued`, and `running` consume local capacity; pi-subagents retains its global queue. diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index fb0d023..656c153 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -133,7 +133,7 @@ Uncertain dispatches do not change the window; they already block all dispatch. Lifecycle callbacks CAS loop revision, owner runtime/generation, work ID, dispatch ID, attempt, and agent ID. Normal terminal evidence is bounded and persisted with `provider_owned` completion status; pi-loop does not call `subagents:rpc:consume`, so the provider retains its native completion surface. Protocol-v2 stop replies and `stopped`/`aborted` lifecycle statuses acknowledge cancellation, not quiescence. They become non-retryable, non-consumable `uncertain` dispatches before stop RPCs run. A late spawn reply may attach its exact cleanup identity without restoring execution. Proved failures retry only within `maxAttempts`; a spawn timeout is ambiguous without upstream status/list or idempotent dispatch keys, so it becomes `uncertain` and is never retried automatically. -Completion bursts refill capacity without a pi-loop parent wake. When every terminal dispatch is provider-owned, pi-loop pauses the controller and acknowledges its aggregate wake internally so only the provider's native completion path runs. Uncertain dispatches and failures without a provider-owned terminal result retain the durable hidden wake until `pi.sendMessage` succeeds, unless cancelled or retired by expiry; a crash before acknowledgement may duplicate that delivery. Completed/attention controllers pause for `OrchestrationGet` inspection and explicit deletion. Presentation labels controller status as `active`, `needs attention`, `complete`, or `cancelled` while preserving reducer vocabulary in persisted state. Progress separates local `reserved` capacity from pending work and last-reported dispatch observations (`starting`, `queued`, `reported running`); none proves current worker liveness. An active controller shows the reservation count against its current capacity as `N/W in flight` (the aimd window, or the fixed concurrency); a controller that is no longer dispatching shows `N reserved`. "Swarm" is the user-facing keyword for this surface: the tool description and its prompt guidelines route a swarm, fan-out, or parallel subagents over a finite list of independent items here; send one delegation, a chain whose steps need earlier results, or foreground work to the provider's own tool; forbid sending the same items through both; name `WorkflowCreate` and `TaskCreate` for other shapes; and explain `verify`. A listing row for a work item ends with the evidence held for it: `verify ok` or `verify failed (exit N)`, the reported duration, and the reported token total; a field is omitted when nothing was reported. The progress panel lists up to five work items under each orchestration. When an aimd batch is larger than its unverified ceiling, the create result says the window is capped and that declaring `verify` on every item lifts it. When a fixed batch of several items is held to one worker, the create result says it is serial and that omitting `concurrency` lifts that. The status line and progress panel count an orchestration only while it is `active` or `needs attention`; a `complete` or `cancelled` batch leaves both at once and stays stored for `OrchestrationGet`, `LoopList` and `/loop` until deleted or expired. Provider-native `SubagentWorkflow` UI and execution remain a separate provider-owned surface. +Completion bursts refill capacity without a pi-loop parent wake. When every terminal dispatch is provider-owned, pi-loop pauses the controller and acknowledges its aggregate wake internally so only the provider's native completion path runs. Uncertain dispatches and failures without a provider-owned terminal result retain the durable hidden wake until `pi.sendMessage` succeeds, unless cancelled or retired by expiry; a crash before acknowledgement may duplicate that delivery. Completed/attention controllers pause for `OrchestrationGet` inspection and explicit deletion. Presentation labels controller status as `active`, `needs attention`, `complete`, or `cancelled` while preserving reducer vocabulary in persisted state. Progress separates local `reserved` capacity from pending work and last-reported dispatch observations (`starting`, `queued`, `reported running`); none proves current worker liveness. An active controller shows the reservation count against its current capacity as `N/W in flight` (the aimd window, or the fixed concurrency); a controller that is no longer dispatching shows `N reserved`. "Swarm" is the user-facing keyword for this surface: the tool description and its prompt guidelines route a swarm, fan-out, or parallel subagents over a finite list of independent items here; send one delegation, a chain whose steps need earlier results, or foreground work to the provider's own tool; forbid sending the same items through both; name `WorkflowCreate` and `TaskCreate` for other shapes; and explain `verify`. A batch created while its session holds a live claim on exactly one active workflow records that workflow, execution and state as its `phase`, and the create result names it. With no claim, an expired claim, a paused workflow, or more than one claim, the batch is unlinked. The link groups the batch under that phase in progress views and has no effect on dispatch, workflow admission, or transitions. A listing row for a work item ends with the evidence held for it: `verify ok` or `verify failed (exit N)`, the reported duration, and the reported token total; a field is omitted when nothing was reported. The progress panel lists up to five work items under each orchestration. When an aimd batch is larger than its unverified ceiling, the create result says the window is capped and that declaring `verify` on every item lifts it. When a fixed batch of several items is held to one worker, the create result says it is serial and that omitting `concurrency` lifts that. The status line and progress panel count an orchestration only while it is `active` or `needs attention`; a `complete` or `cancelled` batch leaves both at once and stays stored for `OrchestrationGet`, `LoopList` and `/loop` until deleted or expired. Provider-native `SubagentWorkflow` UI and execution remain a separate provider-owned surface. Session shutdown/switch invalidates lifecycle callbacks, persists unresolved work as uncertain, and best-effort requests cancellation before store rebinding. Any unresolved dispatch history prevents controller deletion under the Store lock; cancelled batches stay paused and inspectable. Late completion events do not clear this safety latch. Protocol v2 provides no safe automatic clearance or deletion route. Legacy `stopped`/`interrupted` records normalize to non-consumable uncertainty; previously launched retries or consumed evidence cannot be undone, and missing historical stop provenance cannot be reconstructed. A new runtime cannot adopt an unexpired foreign owner lease; after expiry it marks active dispatches uncertain rather than risking duplicates. Project scope, dynamic work addition, dependency graphs, cross-session election, and exact-once dispatch are not implemented. diff --git a/src/orchestration-reducer.ts b/src/orchestration-reducer.ts index 63f12f9..a5e01e8 100644 --- a/src/orchestration-reducer.ts +++ b/src/orchestration-reducer.ts @@ -3,6 +3,7 @@ import type { OrchestrationActor, OrchestrationDefinitionInput, OrchestrationDispatch, + OrchestrationPhaseLink, OrchestrationState, OrchestrationUsage, OrchestrationVerification, @@ -34,6 +35,10 @@ const DISPATCH_STATUSES = new Set(["spawning", "queued", "running", "verifying", const CONSUME_STATUSES = new Set(["not_applicable", "provider_owned", "pending", "consumed", "unavailable"]); const WAKE_REASONS = new Set(["completed", "failed", "uncertain", "recovery"]); +function isPhaseLink(value: unknown): value is OrchestrationPhaseLink { + return isRecord(value) && [value.workflowId, value.executionId, value.state].every((field) => typeof field === "string" && field.length > 0); +} + function isOrchestrationLabel(value: unknown): value is string { return typeof value === "string" && value.trim().length > 0 && value.length <= MAX_ORCHESTRATION_LABEL_CHARS; } @@ -54,8 +59,9 @@ export function validateOrchestrationDefinition(input: OrchestrationDefinitionIn if (input.work.some((item) => item.label !== undefined && !isOrchestrationLabel(item.label))) return "invalid label"; if (input.work.some((item) => item.verify !== undefined && (!item.verify.trim() || item.verify.length > MAX_ORCHESTRATION_VERIFY_CHARS))) return "invalid verify command"; if (input.initialWindow !== undefined && !isWindowSeed(input.initialWindow)) return "invalid initialWindow"; + if (input.phase !== undefined && !isPhaseLink(input.phase)) return "invalid phase link"; // The limit bounds what the caller sent; a seed injected by OrchestrationCreate does not count. - const { initialWindow: _seed, ...callerInput } = input; + const { initialWindow: _seed, phase: _phase, ...callerInput } = input; if (Buffer.byteLength(JSON.stringify(callerInput), "utf8") > MAX_ORCHESTRATION_INPUT_BYTES) return "serialized input exceeds limit"; return undefined; } @@ -137,6 +143,7 @@ export function validatePersistedOrchestration(value: unknown): OrchestrationSta } if (value.status === "completed" && !allWorkCompleted) throw new Error("Malformed orchestration state: incomplete completed batch"); if (!Number.isInteger(value.nextWakeSequence) || Number(value.nextWakeSequence) < 0 || !Number.isFinite(value.createdAt) || !Number.isFinite(value.updatedAt)) throw new Error("Malformed orchestration state: invalid sequence or timestamp"); + if (value.phase !== undefined && !isPhaseLink(value.phase)) throw new Error("Malformed orchestration state: invalid phase link"); if (value.window !== undefined && !validateAckWindow(value.window, Number(value.concurrency))) throw new Error("Malformed orchestration state: invalid window"); if (value.pendingWake !== undefined && (!isRecord(value.pendingWake) || !Number.isInteger(value.pendingWake.sequence) || Number(value.pendingWake.sequence) < 1 || Number(value.pendingWake.sequence) > Number(value.nextWakeSequence) || !WAKE_REASONS.has(String(value.pendingWake.reason)) || !Number.isFinite(value.pendingWake.createdAt))) { throw new Error("Malformed orchestration state: invalid pending wake"); @@ -455,6 +462,7 @@ export function createOrchestrationState( })), nextWakeSequence: 0, ...(input.pacing === "aimd" ? { window: createAckWindow(concurrency, seed) } : {}), + ...(input.phase ? { phase: { workflowId: input.phase.workflowId, executionId: input.phase.executionId, state: input.phase.state } } : {}), createdAt: at, updatedAt: at, }; diff --git a/src/tools/subagent-orchestration-tools.ts b/src/tools/subagent-orchestration-tools.ts index c5e2a3b..3982458 100644 --- a/src/tools/subagent-orchestration-tools.ts +++ b/src/tools/subagent-orchestration-tools.ts @@ -3,7 +3,7 @@ import { Type } from "typebox"; import { learnWindowSeed, MAX_ORCHESTRATION_LABEL_CHARS, MAX_ORCHESTRATION_VERIFY_CHARS } from "../orchestration-reducer.js"; import type { LoopScope } from "../runtime/scope.js"; import type { LoopStore } from "../store.js"; -import type { OrchestrationActor, OrchestrationDefinitionInput, OrchestrationPacing } from "../types.js"; +import type { LoopEntry, OrchestrationActor, OrchestrationDefinitionInput, OrchestrationPacing, OrchestrationPhaseLink } from "../types.js"; import { orchestrationControllerText, orchestrationDisplayDetails, orchestrationProgressLabel, orchestrationWorkText } from "../ui/orchestration-presentation.js"; import { renderToolCall, renderToolResult, toolArg } from "../ui/tool-renderer.js"; import { textResult } from "./tool-result.js"; @@ -92,6 +92,22 @@ function resolvePacing(params: CreateParams, defaultPacing: OrchestrationPacing) return { ...params, pacing: params.concurrency !== undefined ? "fixed" : defaultPacing }; } +/** + * The workflow phase this session is working in, when that is unambiguous: exactly one active + * workflow whose current execution this runtime holds under a live lease. The link only groups + * the batch under that phase for display, so anything less certain is left unlinked. + */ +function claimedPhase(entries: readonly LoopEntry[], actor: { sessionId: string; runtimeId: string }, now: number): OrchestrationPhaseLink | undefined { + const held = entries.filter((entry) => { + const lease = entry.workflow?.activeExecution?.lease; + return entry.status === "active" && lease !== undefined && lease.expiresAt > now + && lease.ownerSessionId === actor.sessionId && lease.ownerRuntimeId === actor.runtimeId; + }); + const [only] = held; + if (held.length !== 1 || !only?.workflow?.activeExecution) return undefined; + return { workflowId: only.id, executionId: only.workflow.activeExecution.id, state: only.workflow.currentState }; +} + /** A label is a display name: tidy it instead of rejecting the batch over it. */ function labelFrom(raw: string | undefined): { label?: string } { const label = typeof raw === "string" ? raw.replace(/[\u0000-\u001f\u007f-\u009f\s]+/g, " ").trim().slice(0, MAX_ORCHESTRATION_LABEL_CHARS).trim() : ""; @@ -188,6 +204,8 @@ export function registerSubagentOrchestrationTools(options: OrchestrationToolsOp const seed = definition.pacing === "aimd" ? learnWindowSeed(store.list().flatMap((candidate) => candidate.orchestration ? [{ id: candidate.id, state: candidate.orchestration }] : []), definition.model, Date.now()) : undefined; + const phase = claimedPhase(store.list(), actor, Date.now()); + if (phase) definition.phase = phase; if (seed) definition.initialWindow = seed.ssthresh === undefined ? { cwnd: seed.cwnd } : { cwnd: seed.cwnd, ssthresh: seed.ssthresh }; let entry: ReturnType; try { @@ -219,6 +237,7 @@ export function registerSubagentOrchestrationTools(options: OrchestrationToolsOp `${definition.work.length} work items · ${pacingLabel}`, ...unverifiedCap, ...serial, + ...(stored.phase ? [`Phase: workflow #${stored.phase.workflowId} · ${stored.phase.state}`] : []), "Dispatch begins after the parent turn becomes idle. Use OrchestrationGet to inspect durable results.", ].join("\n"); return textResult(message, { diff --git a/src/types.ts b/src/types.ts index 56e7267..6e976a8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -154,10 +154,19 @@ export interface OrchestrationState { pendingWake?: OrchestrationPendingWake; /** Present only for `pacing: "aimd"`; `concurrency` remains the hard ceiling. */ window?: AckWindow; + /** Display link to the workflow phase this batch was started from; never consulted for dispatch or admission. */ + phase?: OrchestrationPhaseLink; createdAt: number; updatedAt: number; } +/** Names one visit to a workflow state: a state re-entered on rework is a different execution. */ +export interface OrchestrationPhaseLink { + workflowId: string; + executionId: string; + state: string; +} + export interface OrchestrationDefinitionInput { goal: string; work: Array<{ prompt: string; label?: string; agentType?: string; verify?: string }>; @@ -166,6 +175,7 @@ export interface OrchestrationDefinitionInput { maxAttempts?: number; model?: string; maxTurns?: number; + phase?: OrchestrationPhaseLink; /** aimd only: start from a window an earlier batch in this session learned. */ initialWindow?: WindowSeed; } diff --git a/test/orchestration-reducer.test.ts b/test/orchestration-reducer.test.ts index e076782..0532256 100644 --- a/test/orchestration-reducer.test.ts +++ b/test/orchestration-reducer.test.ts @@ -71,6 +71,22 @@ describe("subagent orchestration reducer", () => { } }); + it("K3: a phase link is stored as given, round-trips, is optional, and changes nothing else", () => { + const phase = { workflowId: "4", executionId: "exec-9", state: "audit" }; + const linked = create(2, { phase }); + expect(linked.phase).toEqual(phase); + expect(validatePersistedOrchestration(JSON.parse(JSON.stringify(linked))).phase).toEqual(phase); + // The link is display metadata: the batch is otherwise the one an unlinked caller would get. + const { phase: _phase, ...rest } = linked; + expect(rest).toEqual(create(2)); + expect("phase" in create(2)).toBe(false); + for (const bad of [{ workflowId: "4" }, { workflowId: "", executionId: "e", state: "s" }, { workflowId: 4, executionId: "e", state: "s" }, "audit"]) { + const snapshot = JSON.parse(JSON.stringify(create(1))); + snapshot.phase = bad; + expect(() => validatePersistedOrchestration(snapshot)).toThrow("invalid phase link"); + } + }); + it("rejects malformed nested persisted evidence before wake rendering", () => { const malformedResult = dispatch(create(1), "1", "dispatch-1", 110).state as any; malformedResult.work[0].dispatches[0].result = { unsafe: true }; diff --git a/test/orchestration-tools.test.ts b/test/orchestration-tools.test.ts index ea02e3e..56357db 100644 --- a/test/orchestration-tools.test.ts +++ b/test/orchestration-tools.test.ts @@ -161,6 +161,60 @@ describe("subagent orchestration tools", () => { expect(await h.text("OrchestrationGet", { id: "1", workId: "4" })).not.toContain("Label:"); }); + describe("workflow phase link", () => { + const me = { sessionId: "session-a", runtimeId: "runtime-a" }; + const definition = { + version: 1 as const, + initialState: "audit", + states: { audit: { prompt: "Audit.", task: { subject: "Audit", description: "Audit it" }, on: { done: "done" } }, done: { prompt: "Done.", terminal: "completed" as const } }, + }; + const claim = (actor = me) => h.store.create({ type: "dynamic" }, "Audit the thing", { recurring: true, workflow: definition, actor }); + const swarm = () => h.text("OrchestrationCreate", { goal: "Fan out", work: [{ prompt: "A" }, { prompt: "B" }] }); + const lastPhase = () => h.store.list().filter((entry) => entry.orchestration).at(-1)?.orchestration?.phase; + + it("K1: a swarm started while this session holds one workflow's claim is tied to that phase", async () => { + const workflow = claim(); + const out = await swarm(); + expect(lastPhase()).toEqual({ workflowId: workflow.id, executionId: workflow.workflow!.activeExecution!.id, state: "audit" }); + expect(out).toContain(`Phase: workflow #${workflow.id} · audit`); + // The workflow itself is untouched by the link. + expect(h.store.get(workflow.id)).toEqual(workflow); + }); + + it("K2 (controls): no claim, another session's claim, an expired claim, a paused workflow or two claims leave the swarm unlinked", async () => { + expect(await swarm()).not.toContain("Phase:"); + expect(lastPhase()).toBeUndefined(); + + const other = claim({ sessionId: "session-b", runtimeId: "runtime-b" }); + await swarm(); + expect(lastPhase()).toBeUndefined(); + h.store.delete(other.id); + + vi.useFakeTimers(); + try { + claim(); + vi.advanceTimersByTime(31 * 60_000); + await swarm(); + expect(lastPhase()).toBeUndefined(); + } finally { + vi.useRealTimers(); + } + }); + + it("K2b (controls): a paused workflow or two live claims leave the swarm unlinked", async () => { + const paused = claim(); + h.store.pause(paused.id, "administrative", "hold"); + await swarm(); + expect(lastPhase()).toBeUndefined(); + h.store.delete(paused.id); + + claim(); + claim(); + expect(await swarm()).not.toContain("Phase:"); + expect(lastPhase()).toBeUndefined(); + }); + }); + describe("default pacing", () => { it("paces a batch with aimd when neither pacing nor concurrency is given", async () => { h = setup();