From 27dac66a3d1aa5ba834320165f4011c64403b6f0 Mon Sep 17 00:00:00 2001 From: Tanner Polley <42780259+tannerpolley@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:22:35 -0700 Subject: [PATCH 1/2] refactor(server): one completion decision for both cohort owners Issue closeout moves from ForkDelegatedCompletion into IssueCommentEffects. The "result still owed work" decision behind task_status, wait and the parent wake now has one owner (ForkDelegatedCompletion.taskResultPending). Finalize reuses delegatedCompletionPlanEvents instead of an inline copy. Fix: a late, unobserved result read of a thread-owned (run-less managed) task acknowledged it and dropped it from the queued wake. It now follows upstream's late-read rule for both owners. Narrows reads: run-less admission reads only the parent thread row, reuseManagedChild reads only the current owner's task, and the closed-child pending check reads only this task. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/issues/IssueCommentEffects.ts | 94 ++- .../DelegatedCompletionDelivery.fork.test.ts | 541 +++++++++++++----- .../ForkDelegatedCompletion.ts | 106 +--- .../src/orchestration-v2/IssueWorkCommands.ts | 4 +- .../src/orchestration-v2/Orchestrator.ts | 79 ++- ...unchService.repositoryHandoff.fork.test.ts | 3 +- 6 files changed, 544 insertions(+), 283 deletions(-) diff --git a/apps/server/src/issues/IssueCommentEffects.ts b/apps/server/src/issues/IssueCommentEffects.ts index bd986f183dca8..567ff34e5f03c 100644 --- a/apps/server/src/issues/IssueCommentEffects.ts +++ b/apps/server/src/issues/IssueCommentEffects.ts @@ -8,10 +8,12 @@ import { type IssueWorkStatus, type OrchestrationV2StoredEvent, type OrchestrationV2AppThread, + type OrchestrationV2Run, type RunId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import type * as SqlClient from "effect/sql/SqlClient"; @@ -20,8 +22,14 @@ import { type PendingOrchestrationEffectV2, type EffectOutboxV2Shape, } from "../orchestration-v2/EffectOutbox.ts"; -import type { ProjectionStoreV2Shape } from "../orchestration-v2/ProjectionStore.ts"; -import { delegatedTaskProgress } from "@t3tools/provider-core/server/subagentProjection"; +import type { + ProjectionRecords, + ProjectionStoreV2Shape, +} from "../orchestration-v2/ProjectionStore.ts"; +import { + delegatedTaskProgress, + subagentResultForRun, +} from "@t3tools/provider-core/server/subagentProjection"; import { deriveIssueWorkStatus } from "./IssueWorkStatus.ts"; import { readIssueWorkCommentState } from "./IssueWorkProjection.ts"; @@ -30,7 +38,7 @@ const decodeCommentEffect = Schema.decodeEffect( Schema.fromJsonString(OrchestrationEffectRequestV2), ); -export function issueCloseoutEffect(input: { +function issueCloseoutEffect(input: { readonly issue: ThreadLinkedIssue; readonly thread: Pick; readonly runId: RunId; @@ -68,6 +76,86 @@ export function issueCloseoutEffect(input: { }; } +type CloseoutChild = ProjectionRecords< + "runs" | "messages" | "subagents" | "providerThreads" | "providerTurns" | "attempts" +>; + +/** Posts a linked child's finished result once, when its repository root opts in. */ +export function makeIssueCloseout(hooks: { + readonly projectionStore: ProjectionStoreV2Shape; + readonly enqueue: ( + effects: ReadonlyArray, + ) => Effect.Effect; + readonly childAwaitsRecoveryContinuation: ( + thread: OrchestrationV2AppThread, + runs: ReadonlyArray, + resultRun: OrchestrationV2Run, + settledContinuationOf?: RunId, + ) => Effect.Effect; +}) { + const { projectionStore } = hooks; + const publish = Effect.fn("Orchestrator.publishIssueCloseout")(function* ( + child: CloseoutChild, + resultRun: OrchestrationV2Run, + ) { + const issue = child.thread.linkedIssue; + if (issue === undefined) return; + const root = yield* projectionStore + .getThread(child.thread.lineage.rootThreadId) + .pipe(Effect.option); + if (Option.isNone(root) || root.value.repositoryOrchestration?.publishCloseoutComments !== true) + return; + const result = yield* projectionStore.getThreadRecords( + child.thread.id, + ["messages", "turnItems"], + { + messageRoles: ["assistant"], + messageRunIds: [resultRun.id], + turnItemRunId: resultRun.id, + turnItemTypes: ["assistant_message", "error"], + }, + ); + yield* hooks.enqueue([ + issueCloseoutEffect({ + issue, + thread: child.thread, + runId: resultRun.id, + status: deriveIssueWorkStatus({ + shell: yield* projectionStore.getThreadShell(child.thread.id), + paused: false, + waitingOnSubIssues: false, + resultAvailable: true, + }), + completedAt: yield* DateTime.now, + result: subagentResultForRun( + { ...child, messages: result.messages, turnItems: result.turnItems }, + resultRun, + ).text, + }), + ]); + }); + const publishUntagged = Effect.fnUntraced(function* ( + child: CloseoutChild, + progress: ReturnType, + settledContinuationOf?: RunId, + ) { + const { resultRun } = progress; + if ( + progress.state === "result_available" && + resultRun !== undefined && + resultRun.delegatedTaskId === undefined && + !(yield* hooks.childAwaitsRecoveryContinuation( + child.thread, + child.runs, + resultRun, + settledContinuationOf, + )) + ) + yield* publish(child, resultRun); + }); + return { publish, publishUntagged }; +} + function statusCommentEffect(input: { readonly issue: ThreadLinkedIssue; readonly threadId: ThreadId; diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.fork.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.fork.test.ts index 81fe5ac235ddd..8f840769b166b 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.fork.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.fork.test.ts @@ -28,6 +28,7 @@ import * as ProjectionMaintenance from "./ProjectionMaintenance.ts"; import * as ProjectionReplay from "./testkit/ProjectionReplay.ts"; import * as EventSink from "./EventSink.ts"; import * as Orchestrator from "./Orchestrator.ts"; +import { completionCohort } from "./ForkDelegatedCompletion.ts"; import * as ProviderRuntimeRecoveryService from "./ProviderRuntimeRecoveryService.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as CheckpointCaptureService from "./CheckpointCaptureService.ts"; @@ -56,79 +57,221 @@ import { wakeChildQuestion, } from "./DelegatedCompletionDelivery.testHarness.ts"; +// Run-less managed admissions keep their cohort on the parent thread; ordinary delegation keeps it on the run. +const cohortOwners = ["run", "thread"] as const; +type CohortOwner = (typeof cohortOwners)[number]; + +const seedOwnedParent = Effect.fn("seedOwnedParent")(function* ( + owner: CohortOwner, + name: string, + input: { + readonly deliveryState: "delivered" | "claimed"; + readonly withDelivery: boolean; + readonly parentRunEnded: boolean; + readonly disposition?: "open" | "stopped"; + }, +) { + const engine = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const key = `${owner}-owned-${name}`; + const threadId = ThreadId.make(`thread:${key}`); + const runId = RunId.make(`run:${key}`); + const taskId = NodeId.make(`task:${key}`); + yield* seedParentWithTerminalTask({ + threadId, + projectId: ProjectId.make(`project:${key}`), + runId, + rootNodeId: NodeId.make(`root:${key}`), + taskId, + deliveryState: input.deliveryState, + completionWake: "always", + ...(input.withDelivery ? { deliveryTaskIds: [taskId] } : {}), + now, + }); + const seeded = yield* engine.getThreadProjection(threadId); + const run = seeded.runs[0]!; + const parentRunId = owner === "run" ? runId : null; + const cohort = { ...run.delegatedCompletion!, disposition: input.disposition ?? "open" }; + yield* sink.write({ + commandId: reconcileCommandId(`${key}-owner`), + events: [ + ...(owner === "thread" + ? [ + { + id: EventId.make(`${key}-thread-cohort`), + type: "thread.metadata-updated" as const, + threadId, + occurredAt: now, + payload: { ...seeded.thread, delegatedCompletion: cohort }, + }, + ] + : []), + { + id: EventId.make(`${key}-parent-run`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { + ...run, + ...(input.parentRunEnded + ? { + status: input.disposition === "stopped" ? "interrupted" : "completed", + completedAt: now, + } + : {}), + delegatedCompletion: + owner === "run" ? cohort : { disposition: "open", nextGeneration: 1, delivery: null }, + }, + }, + { + id: EventId.make(`${key}-task-owner`), + type: "subagent.updated", + threadId, + occurredAt: now, + payload: { ...seeded.subagents[0]!, runId: parentRunId }, + }, + ], + }); + return { + key, + threadId, + runId, + taskId, + parentRunId, + now, + thread: seeded.thread, + run, + task: seeded.subagents[0]!, + messageId: MessageId.make(`message:delegated-delivery:${threadId}`), + cohortOf: (projection: Parameters[0]) => + completionCohort(projection, parentRunId), + }; +}); + +/** Events for a worker of `parent` whose run ended with `text`, committed before any listener saw them. */ +const finishedWorkerEvents = ( + parent: Effect.Success>, + name: string, + text: string, +) => { + const childThreadId = ThreadId.make(`thread:${parent.key}-${name}`); + const childRunId = RunId.make(`run:${parent.key}-${name}`); + const task = { + ...parent.task, + id: NodeId.make(`task:${parent.key}-${name}`), + runId: parent.parentRunId, + childThreadId, + status: "running" as const, + result: null, + completedAt: null, + completionDelivery: { state: "pending" as const, observedByRunId: null }, + }; + const { now } = parent; + return { + task, + events: [ + { + id: EventId.make(`${parent.key}-${name}-created`), + type: "thread.created" as const, + threadId: childThreadId, + occurredAt: now, + payload: { + ...parent.thread, + id: childThreadId, + activeProviderThreadId: null, + lineage: { + parentThreadId: parent.threadId, + rootThreadId: parent.threadId, + relationshipToParent: "subagent" as const, + }, + forkedFrom: { type: "node" as const, nodeId: task.id }, + }, + }, + { + id: EventId.make(`${parent.key}-${name}-task`), + type: "subagent.updated" as const, + threadId: parent.threadId, + occurredAt: now, + payload: task, + }, + { + id: EventId.make(`${parent.key}-${name}-result`), + type: "message.updated" as const, + threadId: childThreadId, + runId: childRunId, + occurredAt: now, + payload: { + id: MessageId.make(`message:${parent.key}-${name}-result`), + threadId: childThreadId, + runId: childRunId, + nodeId: null, + role: "assistant" as const, + text, + attachments: [], + streaming: false, + createdBy: "agent" as const, + creationSource: "server" as const, + createdAt: now, + updatedAt: now, + }, + }, + { + id: EventId.make(`${parent.key}-${name}-ended`), + type: "run.updated" as const, + threadId: childThreadId, + occurredAt: now, + payload: { + ...parent.run, + id: childRunId, + threadId: childThreadId, + userMessageId: MessageId.make(`message:${parent.key}-${name}`), + providerThreadId: null, + rootNodeId: null, + delegatedTaskId: task.id, + delegatedCompletion: { disposition: "open" as const, nextGeneration: 1, delivery: null }, + status: "completed" as const, + completedAt: now, + }, + }, + ], + }; +}; + it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( - "thread-owned completion recovery", + "completion recovery for both cohort owners", (it) => { - it.effect( - "restart recovery adds a second worker to a queued thread-owned delivery and settles both", - () => + it.effect.each(cohortOwners)( + "restart recovery adds a second worker to a queued %s-owned delivery and settles both", + (owner) => Effect.gen(function* () { const engine = yield* Orchestrator.OrchestratorV2; const sink = yield* EventSink.EventSinkV2; const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; - const now = yield* DateTime.now; - const threadId = ThreadId.make("thread:thread-owned-recovery"); - const runId = RunId.make("run:thread-owned-recovery"); - const taskId = NodeId.make("task:thread-owned-recovery"); - const messageId = MessageId.make(`message:delegated-delivery:${threadId}`); - yield* seedParentWithTerminalTask({ - threadId, - projectId: ProjectId.make("project:thread-owned-recovery"), - runId, - rootNodeId: NodeId.make("root:thread-owned-recovery"), - taskId, + // The result and reservation committed, but no continuation was dispatched before shutdown. + const parent = yield* seedOwnedParent(owner, "recovery", { deliveryState: "claimed", - completionWake: "always", - deliveryTaskIds: [taskId], - now, + withDelivery: true, + parentRunEnded: true, }); - const parent = yield* engine.getThreadProjection(threadId); - const run = parent.runs[0]!; - const task = parent.subagents[0]!; - // The result and reservation committed, but no continuation was dispatched before shutdown. + const { threadId, taskId, messageId, parentRunId, now } = parent; yield* sink.write({ - commandId: reconcileCommandId("thread-owned-reservation"), + commandId: reconcileCommandId(`${parent.key}-busy`), events: [ { - id: EventId.make("thread-owned-cohort"), - type: "thread.metadata-updated", - threadId, - occurredAt: now, - payload: { ...parent.thread, delegatedCompletion: run.delegatedCompletion }, - }, - { - id: EventId.make("thread-owned-idle-parent"), + id: EventId.make(`${parent.key}-busy-parent`), type: "run.updated", threadId, occurredAt: now, payload: { - ...run, - status: "completed", - completedAt: now, - delegatedCompletion: { ...run.delegatedCompletion!, delivery: null }, - }, - }, - { - id: EventId.make("thread-owned-busy-parent"), - type: "run.updated", - threadId, - occurredAt: now, - payload: { - ...run, - id: RunId.make("run:thread-owned-busy-parent"), + ...parent.run, + id: RunId.make(`run:${parent.key}-busy-parent`), ordinal: 2, - userMessageId: MessageId.make("message:thread-owned-busy-parent"), + userMessageId: MessageId.make(`message:${parent.key}-busy-parent`), rootNodeId: null, delegatedCompletion: { disposition: "open", nextGeneration: 1, delivery: null }, }, }, - { - id: EventId.make("thread-owned-task"), - type: "subagent.updated", - threadId, - occurredAt: now, - payload: { ...task, runId: null }, - }, ], }); const offer = vi.spyOn(requests, "offer"); @@ -136,19 +279,19 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( yield* engine.recoverDelegatedTasks; assert.equal(offer.mock.calls.length, 1); assert.deepEqual(offer.mock.calls[0]![0].delegatedCompletion, { - parentRunId: null, + parentRunId, generation: 1, messageId, }); yield* engine.dispatch({ type: "message.dispatch", - commandId: CommandId.make("thread-owned-delivery"), + commandId: CommandId.make(`${parent.key}-delivery`), threadId, messageId, text: "Issue worker finished.", attachments: [], dispatchMode: { type: "queue_after_active" }, - delegatedCompletion: { parentRunId: null, generation: 1, taskIds: [taskId] }, + delegatedCompletion: { parentRunId, generation: 1, taskIds: [taskId] }, createdBy: "agent", creationSource: "server", }); @@ -157,103 +300,33 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( (candidate) => candidate.userMessageId === messageId, )!; assert.equal(deliveryRun.status, "queued"); - const childThreadId = ThreadId.make("thread:thread-owned-second-worker"); - const childRunId = RunId.make("run:thread-owned-second-worker"); - const secondTask = { - ...task, - id: NodeId.make("task:thread-owned-second-worker"), - runId: null, - childThreadId, - status: "running" as const, - result: null, - completedAt: null, - completionDelivery: { state: "pending" as const, observedByRunId: null }, - }; + // A sibling finished while the server was down: its result is published at restart. + const second = finishedWorkerEvents( + parent, + "second-worker", + "Second issue worker result.", + ); yield* sink.write({ - commandId: reconcileCommandId("thread-owned-second-worker-finished"), - events: [ - { - id: EventId.make("thread-owned-second-worker-created"), - type: "thread.created", - threadId: childThreadId, - occurredAt: now, - payload: { - ...parent.thread, - id: childThreadId, - activeProviderThreadId: null, - lineage: { - parentThreadId: threadId, - rootThreadId: threadId, - relationshipToParent: "subagent", - }, - forkedFrom: { type: "node", nodeId: secondTask.id }, - }, - }, - { - id: EventId.make("thread-owned-second-worker-task"), - type: "subagent.updated", - threadId, - occurredAt: now, - payload: secondTask, - }, - { - id: EventId.make("thread-owned-second-worker-result"), - type: "message.updated", - threadId: childThreadId, - runId: childRunId, - occurredAt: now, - payload: { - id: MessageId.make("message:thread-owned-second-worker-result"), - threadId: childThreadId, - runId: childRunId, - nodeId: null, - role: "assistant", - text: "Second issue worker result.", - attachments: [], - streaming: false, - createdBy: "agent", - creationSource: "server", - createdAt: now, - updatedAt: now, - }, - }, - { - id: EventId.make("thread-owned-second-worker-ended"), - type: "run.updated", - threadId: childThreadId, - occurredAt: now, - payload: { - ...run, - id: childRunId, - threadId: childThreadId, - userMessageId: MessageId.make("message:thread-owned-second-worker"), - providerThreadId: null, - rootNodeId: null, - delegatedTaskId: secondTask.id, - delegatedCompletion: { disposition: "open", nextGeneration: 1, delivery: null }, - status: "completed", - completedAt: now, - }, - }, - ], + commandId: reconcileCommandId(`${parent.key}-second-worker-finished`), + events: second.events, }); yield* engine.recoverDelegatedTasks; const coalesced = yield* engine.getThreadProjection(threadId); - assert.deepEqual(coalesced.thread.delegatedCompletion?.delivery, { + assert.deepEqual(parent.cohortOf(coalesced)?.delivery, { generation: 1, messageId, - taskIds: [taskId, secondTask.id], + taskIds: [taskId, second.task.id], }); const message = coalesced.messages.find((candidate) => candidate.id === messageId)!; - assert.deepEqual(message.delegatedCompletion?.taskIds, [taskId, secondTask.id]); + assert.deepEqual(message.delegatedCompletion?.taskIds, [taskId, second.task.id]); assert.include(message.text, "child finished"); assert.include(message.text, "Second issue worker result."); // This delivery also ended before startup's terminal-run listener was attached. yield* sink.write({ - commandId: reconcileCommandId("thread-owned-delivery-ended"), + commandId: reconcileCommandId(`${parent.key}-delivery-ended`), events: [ { - id: EventId.make("thread-owned-delivery-ended"), + id: EventId.make(`${parent.key}-delivery-ended`), type: "run.updated", threadId, occurredAt: now, @@ -262,9 +335,11 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( ], }); yield* engine.recoverDelegatedTasks; + // A further restart finds nothing left to deliver. + yield* engine.recoverDelegatedTasks; const settled = yield* engine.getThreadProjection(threadId); - assert.isNull(settled.thread.delegatedCompletion?.delivery); - for (const id of [taskId, secondTask.id]) { + assert.isNull(parent.cohortOf(settled)?.delivery); + for (const id of [taskId, second.task.id]) { assert.equal( settled.subagents.find((candidate) => candidate.id === id)?.completionDelivery ?.state, @@ -279,12 +354,196 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( settled.messages.filter((candidate) => candidate.delegatedCompletion !== undefined), 1, ); + assert.equal(offer.mock.calls.length, 1); }).pipe(Effect.ensuring(Effect.sync(() => offer.mockRestore()))); }), ); + + it.effect.each( + cohortOwners.flatMap((owner) => + (["observed", "late"] as const).map((read) => ({ owner, read })), + ), + )( + "a $read result read of a $owner-owned task settles its queued wake only when seen", + ({ owner, read }) => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const parent = yield* seedOwnedParent(owner, `read-${read}`, { + deliveryState: "claimed", + withDelivery: true, + parentRunEnded: false, + }); + const { threadId, taskId, messageId, parentRunId } = parent; + yield* engine.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${parent.key}-delivery`), + threadId, + messageId, + text: "Issue worker finished.", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + delegatedCompletion: { parentRunId, generation: 1, taskIds: [taskId] }, + createdBy: "agent", + creationSource: "server", + }); + const wakeRunId = (yield* engine.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.userMessageId === messageId, + )!.id; + // A late wait ends after its turn did, so no run saw the result it returned. + yield* engine.dispatch({ + type: "delegated_task.completion-delivery.acknowledge", + commandId: CommandId.make(`${parent.key}-acknowledge`), + parentThreadId: threadId, + taskId, + observedByRunId: read === "observed" ? parent.runId : null, + }); + const after = yield* engine.getThreadProjection(threadId); + const task = after.subagents.find((candidate) => candidate.id === taskId)!; + const wakeRun = after.runs.find((candidate) => candidate.id === wakeRunId)!; + if (read === "observed") { + assert.equal(task.completionDelivery?.state, "acknowledged"); + assert.isNull(parent.cohortOf(after)?.delivery); + assert.equal(wakeRun.status, "cancelled"); + } else { + assert.equal(task.completionDelivery?.state, "claimed"); + assert.deepEqual(parent.cohortOf(after)?.delivery?.taskIds, [taskId]); + assert.equal(wakeRun.status, "queued"); + } + }), + ); + + it.effect.each( + cohortOwners.flatMap((owner) => + (["archived", "deleted", "stopped"] as const).map((closure) => ({ owner, closure })), + ), + )("a $owner-owned worker that finishes after its parent was $closure", ({ owner, closure }) => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; + // A thread cohort marked stopped is the pre-#418 format: the whole mailbox stopped. + const parent = yield* seedOwnedParent(owner, `closed-${closure}`, { + deliveryState: "delivered", + withDelivery: false, + parentRunEnded: true, + disposition: closure === "stopped" ? "stopped" : "open", + }); + const worker = finishedWorkerEvents(parent, "worker", "Worker result."); + const closed = yield* engine.getThreadProjection(parent.threadId); + yield* sink.write({ + commandId: reconcileCommandId(`${parent.key}-worker-finished`), + events: [ + ...worker.events, + ...(closure === "stopped" + ? [] + : [ + { + id: EventId.make(`${parent.key}-closed`), + type: "thread.metadata-updated" as const, + threadId: parent.threadId, + occurredAt: parent.now, + payload: { + ...closed.thread, + ...(closure === "archived" + ? { archivedAt: parent.now } + : { deletedAt: parent.now }), + }, + }, + ]), + ], + }); + const offer = vi.spyOn(requests, "offer"); + yield* Effect.gen(function* () { + yield* engine.recoverDelegatedTasks; + const after = yield* projections.getThreadRecords(parent.threadId, ["runs", "subagents"]); + const task = after.subagents.find((candidate) => candidate.id === worker.task.id)!; + assert.equal(task.result, "Worker result."); + if (owner === "thread" && closure === "stopped") { + assert.equal(task.completionDelivery?.state, "claimed"); + assert.deepEqual(parent.cohortOf(after)?.delivery?.taskIds, [worker.task.id]); + // A re-offer names the same message and generation, so it dispatches no second wake. + const delivery = parent.cohortOf(after)!.delivery!; + assert.isAbove(offer.mock.calls.length, 0); + for (const [request] of offer.mock.calls) { + assert.deepEqual(request.delegatedCompletion, { + parentRunId: null, + generation: delivery.generation, + messageId: delivery.messageId, + }); + } + } else { + assert.equal(task.completionDelivery?.state, "disposed"); + assert.isTrue(parent.cohortOf(after)?.delivery == null); + assert.equal(offer.mock.calls.length, 0); + } + }).pipe(Effect.ensuring(Effect.sync(() => offer.mockRestore()))); + }), + ); }, ); +it.layer(layerTest)("workspace preparation failure for both cohort owners", (it) => { + it.effect.each(cohortOwners)( + "a %s-owned worker whose workspace preparation fails wakes its parent with the failure", + (owner) => + Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const parent = yield* seedOwnedParent(owner, "preparation-failed", { + deliveryState: "delivered", + withDelivery: false, + parentRunEnded: true, + }); + const worker = finishedWorkerEvents(parent, "worker", "unused"); + const [created, taskEvent] = worker.events; + const childThreadId = created.threadId; + yield* sink.write({ events: [created, taskEvent] }); + yield* engine.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${parent.key}-worker-start`), + threadId: childThreadId, + senderThreadId: parent.threadId, + messageId: MessageId.make(`message:${parent.key}-worker-start`), + text: "Implement the issue.", + attachments: [], + dispatchMode: { type: "defer_start" }, + createdBy: "agent", + creationSource: "server", + }); + const preparing = (yield* engine.getThreadProjection(childThreadId)).runs[0]!; + assert.equal(preparing.status, "preparing"); + const { sequence } = yield* engine.dispatch({ + type: "prepared-run.fail", + commandId: CommandId.make(`${parent.key}-worker-preparation-failed`), + threadId: childThreadId, + runId: preparing.id, + failure: { + class: "validation_error", + message: "Worktree setup failed: branch already exists", + code: null, + retryable: false, + }, + }); + yield* sink.stream({ afterSequence: sequence - 1, eventType: "subagent.updated" }).pipe( + Stream.filter( + (stored) => + stored.event.type === "subagent.updated" && + stored.event.payload.id === worker.task.id && + stored.event.payload.status === "failed", + ), + Stream.take(1), + Stream.runDrain, + ); + const after = yield* engine.getThreadProjection(parent.threadId); + const task = after.subagents.find((candidate) => candidate.id === worker.task.id)!; + assert.include(task.result, "Worktree setup failed: branch already exists"); + assert.equal(task.completionDelivery?.state, "claimed"); + assert.deepEqual(parent.cohortOf(after)?.delivery?.taskIds, [worker.task.id]); + }), + ); +}); + it.layer(layerTest)("child question wake", (it) => { it.effect("wakes the parent with the full question once", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ForkDelegatedCompletion.ts b/apps/server/src/orchestration-v2/ForkDelegatedCompletion.ts index 11076f4c54b61..883c9e91ca74c 100644 --- a/apps/server/src/orchestration-v2/ForkDelegatedCompletion.ts +++ b/apps/server/src/orchestration-v2/ForkDelegatedCompletion.ts @@ -14,18 +14,11 @@ import type { RunId, ThreadId, } from "@t3tools/contracts"; -import { - delegatedTaskProgress, - subagentResultForRun, -} from "@t3tools/provider-core/server/subagentProjection"; +import { delegatedTaskProgress } from "@t3tools/provider-core/server/subagentProjection"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; -import { deriveIssueWorkStatus } from "../issues/IssueWorkStatus.ts"; -import { issueCloseoutEffect } from "../issues/IssueCommentEffects.ts"; import { runOutcome } from "./RestartBackgroundNote.ts"; import type { ProjectionStoreV2, ProjectionRecords } from "./ProjectionStore.ts"; -import type { PendingOrchestrationEffectV2 } from "./EffectOutbox.ts"; import type { usageLimitSwitchMessageId, usageLimitSwitchResultRun, @@ -40,15 +33,10 @@ type CompletionOptions = { readonly resultRun?: OrchestrationV2Run; }; type Progress = ReturnType; -interface ForkDelegatedCompletionHooks { +interface ForkDelegatedCompletionHooks { readonly usageLimitSwitchMessageId: typeof usageLimitSwitchMessageId; readonly usageLimitSwitchResultRun: typeof usageLimitSwitchResultRun; readonly projectionStore: ProjectionStoreV2["Service"]; - readonly writeSystemEvents: ( - events: ReadonlyArray>, - effects?: ReadonlyArray, - options?: { readonly updateDelegatedCompletionOnly?: boolean }, - ) => Effect.Effect; readonly childAwaitsRecoveryContinuation: ( thread: OrchestrationV2AppThread, runs: ReadonlyArray, @@ -95,16 +83,15 @@ export const completionCohortEvent = ( }; // The orchestrator retains the upstream completion pipeline, reads, locks, and commits. -export function makeForkDelegatedCompletion({ +export function makeForkDelegatedCompletion({ projectionStore, - writeSystemEvents, childAwaitsRecoveryContinuation, delegatedTaskTerminalStatus, isTerminalDelegatedTaskStatus, isBlockingRun, usageLimitSwitchMessageId, usageLimitSwitchResultRun, -}: ForkDelegatedCompletionHooks) { +}: ForkDelegatedCompletionHooks) { function delegatedTaskResultRun( projection: Pick, taskId: NodeId, @@ -139,76 +126,6 @@ export function makeForkDelegatedCompletion({ ); } - const publishIssueCloseout = Effect.fn("Orchestrator.publishIssueCloseout")(function* ( - childControls: ProjectionRecords< - "runs" | "messages" | "subagents" | "providerThreads" | "providerTurns" | "attempts" - >, - childRun: OrchestrationV2Run, - ) { - const issue = childControls.thread.linkedIssue; - if (issue === undefined) return; - const root = yield* projectionStore - .getThread(childControls.thread.lineage.rootThreadId) - .pipe(Effect.option); - if (Option.isNone(root) || root.value.repositoryOrchestration?.publishCloseoutComments !== true) - return; - const childResult = yield* projectionStore.getThreadRecords( - childControls.thread.id, - ["messages", "turnItems"], - { - messageRoles: ["assistant"], - messageRunIds: [childRun.id], - turnItemRunId: childRun.id, - turnItemTypes: ["assistant_message", "error"], - }, - ); - yield* writeSystemEvents( - [], - [ - issueCloseoutEffect({ - issue, - thread: childControls.thread, - runId: childRun.id, - status: deriveIssueWorkStatus({ - shell: yield* projectionStore.getThreadShell(childControls.thread.id), - paused: false, - waitingOnSubIssues: false, - resultAvailable: true, - }), - completedAt: yield* DateTime.now, - result: subagentResultForRun( - { - ...childControls, - messages: childResult.messages, - turnItems: childResult.turnItems, - }, - childRun, - ).text, - }), - ], - ); - }); - - // These hooks run inside the existing completion or recovery operation. - const publishUntaggedIssueCloseout = Effect.fnUntraced(function* ( - childControls: ChildControls, - progress: Progress, - options?: CompletionOptions, - ) { - if ( - progress.state === "result_available" && - progress.resultRun !== undefined && - progress.resultRun.delegatedTaskId === undefined && - !(yield* childAwaitsRecoveryContinuation( - childControls.thread, - childControls.runs, - progress.resultRun, - options?.settledContinuationOf, - )) - ) { - yield* publishIssueCloseout(childControls, progress.resultRun); - } - }); const closedChildResult = Effect.fnUntraced(function* ( childControls: ChildControls, options: CompletionOptions, @@ -223,6 +140,7 @@ export function makeForkDelegatedCompletion({ : recordedRun; return { closed, childRun }; }); + // The one "is this result still owed work" decision behind task_status, wait and the parent wake. const taskResultPending = Effect.fnUntraced(function* ( childThreadId: ThreadId, taskId: NodeId | undefined, @@ -237,7 +155,9 @@ export function makeForkDelegatedCompletion({ ) { const parentThreadId = child.thread.lineage.parentThreadId; if (parentThreadId === null) return true; - const parent = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"]); + const parent = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], { + subagentIds: [taskId], + }); return !parent.subagents.some( (task) => task.id === taskId && @@ -254,6 +174,14 @@ export function makeForkDelegatedCompletion({ return true; return yield* childAwaitsRecoveryContinuation(child.thread, child.runs, run); } + const shell = yield* projectionStore.getThreadShell(childThreadId); + const progress = delegatedTaskProgress({ + ...child, + pendingBackgroundTasks: shell?.pendingBackgroundTasks ?? [], + }); + if (progress.state !== "result_available") return true; + if (progress.resultRun === undefined) return false; + return yield* childAwaitsRecoveryContinuation(child.thread, child.runs, progress.resultRun); }); const recoverDeletedChildren = Effect.fnUntraced(function* ( tasks: ReadonlyArray, @@ -295,8 +223,6 @@ export function makeForkDelegatedCompletion({ const hasPublishedResult = (task: OrchestrationV2Subagent) => task.result !== null; return { delegatedTaskResultRun, - publishIssueCloseout, - publishUntaggedIssueCloseout, closedChildResult, taskResultPending, recoverDeletedChildren, diff --git a/apps/server/src/orchestration-v2/IssueWorkCommands.ts b/apps/server/src/orchestration-v2/IssueWorkCommands.ts index c0a431fbb0d1f..187b0d0fcdb8d 100644 --- a/apps/server/src/orchestration-v2/IssueWorkCommands.ts +++ b/apps/server/src/orchestration-v2/IssueWorkCommands.ts @@ -433,7 +433,9 @@ export function makeIssueWorkCommands({ parent === null || parent === undefined ? undefined : (yield* projectionStore - .getThreadRecords(parent, ["subagents"]) + .getThreadRecords(parent, ["subagents"], { + subagentChildThreadIds: [currentOwner], + }) .pipe(mapDispatchError(command))).subagents.findLast( (task) => task.childThreadId === currentOwner, ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 327de90008830..e3aaf6b1811dc 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -241,6 +241,7 @@ import { completionCohort, completionCohortEvent, } from "./ForkDelegatedCompletion.ts"; +import { makeIssueCloseout } from "../issues/IssueCommentEffects.ts"; const isIssueQueueRefreshRequired = Schema.is(IssueQueueRefreshRequired); @@ -3590,7 +3591,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runIds: task.runId === null ? [] : [task.runId], }); // A late wait can arrive after finalization held the result for its still-live spawning run. - if (isUnobservedAcknowledgement(command) && task.runId !== null) { + if (isUnobservedAcknowledgement(command)) { if ( !isTerminalDelegatedTaskStatus(task.status) || task.completionDelivery?.state !== "pending" @@ -9834,13 +9835,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio effects: Ref.Ref>, command: OrchestrationV2ServerCommand, ) { - // A run-less delegation (fork) has no run to scope the read to. + // A run-less (managed) delegation reads no parent run, so the thread row is all it uses. const parentProjection = yield* ( request.parentRunId === null || request.parentNodeId === null - ? projectionStore.getThreadRecords( - request.parentThreadId, - ["runs", "nodes", "providerThreads", "providerTurns", "attempts"], - { omitSettledLeafNodes: true }, + ? projectionStore.getThreadRecords(request.parentThreadId, []).pipe( + Effect.map( + ({ + thread, + }): ProjectionRecords< + "runs" | "nodes" | "providerThreads" | "providerTurns" | "attempts" + > => ({ + thread, + runs: [], + nodes: [], + providerThreads: [], + providerTurns: [], + attempts: [], + }), + ), ) : projectionStore.getRunProviderRecords( request.parentThreadId, @@ -15047,7 +15059,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const now = yield* DateTime.now; const settledRun = { ...childRun, status: outcome }; const result = subagentResultForRun(childProjection, settledRun); - yield* forkDelegatedCompletion.publishIssueCloseout(childControls, settledRun); + yield* issueCloseout.publish(childControls, settledRun); const parentNode = parentTask.nodes.find((candidate) => candidate.id === task.id); const parentTurnItem = parentTask.turnItems.find( (candidate) => candidate.type === "subagent" && candidate.subagentId === task.id, @@ -15112,29 +15124,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: completionPlan.task, }, - ...(completionPlan.cohort === undefined - ? [] - : [ - completionCohortEvent(parentProjection.thread, parentRun, completionPlan.cohort, now), - ]), - ...(completionPlan.message === undefined - ? [] - : [ - { - type: "message.updated" as const, - threadId: parentThreadId, - ...(completionPlan.message.runId === null - ? {} - : { runId: completionPlan.message.runId }), - ...(completionPlan.message.nodeId === null - ? {} - : { nodeId: completionPlan.message.nodeId }), - providerInstanceId: - parentRun?.providerInstanceId ?? parentProjection.thread.providerInstanceId, - occurredAt: now, - payload: completionPlan.message, - }, - ]), + ...delegatedCompletionPlanEvents( + parentProjection.thread, + completionPlan, + parentProjection.thread.providerInstanceId, + now, + ), ...(parentNode === undefined ? [] : [ @@ -15220,7 +15215,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...childControls, pendingBackgroundTasks: childShell?.pendingBackgroundTasks ?? [], }); - yield* forkDelegatedCompletion.publishUntaggedIssueCloseout(childControls, progress, options); + yield* issueCloseout.publishUntagged(childControls, progress, options?.settledContinuationOf); // Each task of this child names it, so the parent's other tasks stay unread. const parent = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], { subagentChildThreadIds: [childThreadId], @@ -15645,7 +15640,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }; const forkDelegatedCompletion = makeForkDelegatedCompletion({ projectionStore, - writeSystemEvents, childAwaitsRecoveryContinuation, delegatedTaskTerminalStatus, isTerminalDelegatedTaskStatus, @@ -15654,6 +15648,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio usageLimitSwitchResultRun, }); const { delegatedTaskResultRun } = forkDelegatedCompletion; + const issueCloseout = makeIssueCloseout({ + projectionStore, + enqueue: (effects) => writeSystemEvents([], effects), + childAwaitsRecoveryContinuation, + }); const appOwnedUserInput = makeAppOwnedUserInputCommands({ ...forkCommandHooks, @@ -16930,21 +16929,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"], { messageRoles: ["user"] }, ); - const pending = yield* forkDelegatedCompletion.taskResultPending( - childThreadId, - taskId, - child, - ); - if (pending !== undefined) return pending; - const childShell = yield* projectionStore.getThreadShell(childThreadId); - const progress = delegatedTaskProgress({ - ...child, - pendingBackgroundTasks: childShell?.pendingBackgroundTasks ?? [], - }); - - if (progress.state !== "result_available") return true; - if (progress.resultRun === undefined) return false; - return yield* childAwaitsRecoveryContinuation(child.thread, child.runs, progress.resultRun); + return yield* forkDelegatedCompletion.taskResultPending(childThreadId, taskId, child); }, (effect, childThreadId, _taskId?) => effect.pipe( diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.repositoryHandoff.fork.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.repositoryHandoff.fork.test.ts index eab0305064e7d..fcf41df4cc6af 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.repositoryHandoff.fork.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.repositoryHandoff.fork.test.ts @@ -769,10 +769,11 @@ describe("fresh-thread repository handoff", () => { taskId: notifiedRoot.subagents[0]!.id, observedByRunId: null, }); + // No root run saw that read, so the result stays in the root's wake. assert.deepEqual( (yield* threads.getThreadRecords(rootId, [])).thread.delegatedCompletion!.delivery! .taskIds, - [], + [notifiedRoot.subagents[0]!.id], ); yield* (yield* EffectWorker.OrchestrationEffectWorkerV2).drain(); }).pipe( From 22f5cdf947398c6909417aed0028a15c93ec9ade Mon Sep 17 00:00:00 2001 From: Tanner Polley <42780259+tannerpolley@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:28:50 -0700 Subject: [PATCH 2/2] test(server): type the preparation-failure worker setup Co-Authored-By: Claude Opus 5.5 --- .../DelegatedCompletionDelivery.fork.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.fork.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.fork.test.ts index 8f840769b166b..7f7c21bf15842 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.fork.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.fork.test.ts @@ -496,9 +496,9 @@ it.layer(layerTest)("workspace preparation failure for both cohort owners", (it) parentRunEnded: true, }); const worker = finishedWorkerEvents(parent, "worker", "unused"); - const [created, taskEvent] = worker.events; - const childThreadId = created.threadId; - yield* sink.write({ events: [created, taskEvent] }); + const childThreadId = worker.task.childThreadId; + // The worker's thread and task exist; its run has not started. + yield* sink.write({ events: worker.events.slice(0, 2) }); yield* engine.dispatch({ type: "message.dispatch", commandId: CommandId.make(`${parent.key}-worker-start`),