From 7bff69cad1cd2b23ef3f5298da7d15f8b28d7594 Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Mon, 23 Nov 2026 16:56:21 +0000 Subject: [PATCH 01/10] feat(server): QA seats file receipts and T3 attests the seats it spawns Co-Authored-By: Claude Opus 5.5 --- apps/server/src/delivery/DeliveryService.ts | 30 +- apps/server/src/delivery/SeatHandoffs.test.ts | 277 ++++++++++++++++++ apps/server/src/delivery/SeatHandoffs.ts | 251 ++++++++++++++++ .../src/delivery/boardThreadMarker.test.ts | 4 + .../src/mcp/toolkits/orchestrator/handlers.ts | 8 + .../src/mcp/toolkits/orchestrator/tools.ts | 16 + packages/contracts/src/delivery.ts | 66 +++++ 7 files changed, 637 insertions(+), 15 deletions(-) create mode 100644 apps/server/src/delivery/SeatHandoffs.test.ts create mode 100644 apps/server/src/delivery/SeatHandoffs.ts diff --git a/apps/server/src/delivery/DeliveryService.ts b/apps/server/src/delivery/DeliveryService.ts index 54844b132a75e..f017a6a75d944 100644 --- a/apps/server/src/delivery/DeliveryService.ts +++ b/apps/server/src/delivery/DeliveryService.ts @@ -133,8 +133,9 @@ const BOARD_THREAD_CLAIM = /^\/api\/orchestration\/tasks\/[\w-]+\/(claim|ack|rel // The conversation's mirror and the steer handshake (spec 6a, slice 5). const BOARD_THREAD_CONVERSATION = /^\/api\/tasks\/[\w-]+\/(activity|steers\/\d+\/(delivered|failed))$/; +const BOARD_SEAT_POST = /^\/api\/(?:tasks\/[\w-]+\/qa-receipts|runs\/[\w-]+\/seat-attestations)$/; const BOARD_THREAD_POST = new RegExp( - `${BOARD_THREAD_CLAIM.source}|${BOARD_THREAD_CONVERSATION.source}`, + `${BOARD_THREAD_CLAIM.source}|${BOARD_THREAD_CONVERSATION.source}|${BOARD_SEAT_POST.source}`, ); const BOARD_THREAD_WRITE = new RegExp(`${BOARD_THREAD_LINK.source}|${BOARD_THREAD_POST.source}`); @@ -174,8 +175,7 @@ export class DeliveryService extends Context.Service< input: DeliveryActInput, ) => Effect.Effect; /** - * The server's own writes for a board task's conversation: the `boardThread` link (PUT and - * DELETE) and the task claim with its heartbeat. No client reaches these: `act` refuses them. + * Server-owned board conversation and seat writes. The generic `act` relay refuses them. */ readonly boardThreadAct: (input: { readonly method: "PUT" | "DELETE" | "POST"; @@ -268,6 +268,7 @@ const make = Effect.fn("DeliveryService.make")(function* ( const lineups = new Map(); const rememberedLineups = new Map(); const writeLock = yield* Semaphore.make(1); + const boardSeatWrites = yield* Semaphore.make(1); // Only a file that is not there means that no thread is bound. A file that // is there and cannot be read or understood holds bindings this service @@ -1574,8 +1575,7 @@ const make = Effect.fn("DeliveryService.make")(function* ( ? Effect.fail( new DeliveryError({ reason: "refused", - detail: - "A board task's conversation is claimed and linked by the server, when the engine says the task started.", + detail: "Board conversation and seat records can only be written by the server.", }), ) : new URL(input.path, "http://delivery.invalid").pathname === "/api/delivery/requests" @@ -1604,16 +1604,16 @@ const make = Effect.fn("DeliveryService.make")(function* ( }), ), ), - boardThreadAct: Effect.fn("DeliveryService.boardThreadAct")((input) => - (input.method === "POST" ? BOARD_THREAD_POST : BOARD_THREAD_LINK).test(input.path) - ? request(input.method, input.path, input.body) - : Effect.fail( - new DeliveryError({ - reason: "invalid", - detail: "Invalid board thread mutation path.", - }), - ), - ), + boardThreadAct: Effect.fn("DeliveryService.boardThreadAct")(function* (input) { + if (!(input.method === "POST" ? BOARD_THREAD_POST : BOARD_THREAD_LINK).test(input.path)) + return yield* new DeliveryError({ + reason: "invalid", + detail: "Invalid board thread mutation path.", + }); + const write = request(input.method, input.path, input.body); + // The engine's approval throttle expects one seat write at a time. + return yield* BOARD_SEAT_POST.test(input.path) ? boardSeatWrites.withPermit(write) : write; + }), nativeIntakeAct: Effect.fn("DeliveryService.nativeIntakeAct")((input) => /^\/api\/native-intakes\/intake-[a-f0-9]{64}\/(claim|attach|complete|abandon|cancel)$/.test( input.path, diff --git a/apps/server/src/delivery/SeatHandoffs.test.ts b/apps/server/src/delivery/SeatHandoffs.test.ts new file mode 100644 index 0000000000000..6e41c6d385c78 --- /dev/null +++ b/apps/server/src/delivery/SeatHandoffs.test.ts @@ -0,0 +1,277 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ServerConfig from "../config.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import type { McpInvocationScope } from "../mcp/McpInvocationContext.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { BOARD_THREAD_KEY_VARIABLE } from "./BoardTaskThreads.ts"; +import { scratchEngine, scratchEngineHttp } from "./boardThreadEngine.testkit.ts"; +import { boardTaskOf, boardTaskThreadMarker } from "./boardThreadMarker.ts"; +import * as DeliveryService from "./DeliveryService.ts"; +import * as SeatHandoffs from "./SeatHandoffs.ts"; + +const ENVIRONMENT = EnvironmentId.make("local-test-environment"); +const PARENT = ThreadId.make("thread:board-parent"); +const QA = ThreadId.make("thread:qa"); +const BUILDER = ThreadId.make("thread:builder"); +const TASK_PATH = "/api/tasks/task-17"; +const RUN = "run-24"; +const ATTESTATION_PATH = `/api/runs/${RUN}/seat-attestations`; +const RECEIPT_PATH = `${TASK_PATH}/qa-receipts`; +const ACCEPTANCE = "The preview renders the report."; +const KEY = "scratch-key"; +const INPUT = { acceptanceIndex: 0, verdict: "pass", evidence: ["report.png"] } as const; + +const scopeFor = (threadId: ThreadId): McpInvocationScope => ({ + environmentId: ENVIRONMENT, + thread: { + threadId, + providerSessionId: "session", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 0, + requestNamespace: "test", +}); + +function harness( + options: { + readonly key?: boolean; + readonly receiptRefusal?: { + readonly status: number; + readonly code: string; + readonly field?: string; + }; + } = {}, +) { + const engine = scratchEngine(); + const task = boardTaskOf("board", "task-17")!; + let acceptance = [ACCEPTANCE]; + const layer = SeatHandoffs.layer.pipe( + Layer.provideMerge(DeliveryService.layer(deriveProviderInstanceConfigMap)), + Layer.provide( + scratchEngineHttp({ + ...engine, + handle(method, path, body) { + if (method === "GET" && path === TASK_PATH) { + engine.requests.push({ method, path, body }); + return { + status: 200, + body: { + acceptance, + council: { + run: RUN, + seats: [ + { seat: "validation", threadId: QA, actualModel: "qa-model" }, + { seat: "builder", threadId: BUILDER, actualModel: "build-model" }, + ], + }, + roster: [ + { seat: "validation", inGate: true }, + { seat: "builder", inGate: false, stages: ["build"] }, + ], + }, + }; + } + if (method === "POST" && path === ATTESTATION_PATH) { + engine.requests.push({ method, path, body }); + return { + status: 200, + body: { + attestation: { + run: RUN, + seat: "validation", + threadId: QA, + environmentId: ENVIRONMENT, + model: "qa-model", + harness: "codex", + }, + }, + }; + } + if (method === "POST" && path === RECEIPT_PATH) { + engine.requests.push({ method, path, body }); + if (options.receiptRefusal) { + const { status, ...details } = options.receiptRefusal; + acceptance = ["The preview works offline.", "The report can be exported."]; + return { status, body: { error: "Unrelated engine prose.", ...details } }; + } + return { + status: 200, + body: { qaReceipt: { id: 21, modelSource: "attested", independenceChecked: true } }, + }; + } + return engine.handle(method, path, body); + }, + }), + ), + Layer.provideMerge( + Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(ENVIRONMENT), + }), + ), + Layer.provide( + Layer.succeed(ThreadManagementService.ThreadManagementService, { + getThreadShell: (threadId: ThreadId) => + Effect.succeed( + threadId === PARENT + ? { lineage: { engineIntake: boardTaskThreadMarker(task) } } + : { lineage: { parentThreadId: PARENT } }, + ), + } as unknown as ThreadManagementService.ThreadManagementService["Service"]), + ), + Layer.provide( + ServerSettings.layerTest({ + delivery: { enabled: true, engineUrl: "http://127.0.0.1:4320" }, + }), + ), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "seat-handoffs-" })), + Layer.provide(NodeServices.layer), + Layer.provideMerge( + Layer.succeed( + HostProcess.Environment, + options.key === false + ? {} + : { + [BOARD_THREAD_KEY_VARIABLE]: KEY, + }, + ), + ), + ); + return { layer, requests: engine.requests }; +} + +it.effect("attests a seat with the launched model, harness and server identity", () => { + const { layer, requests } = harness(); + return Effect.gen(function* () { + const handoffs = yield* SeatHandoffs.SeatHandoffs; + yield* handoffs.attestSeat(RUN, "validation", QA, "qa-model", "codex"); + assert.deepEqual(requests, [ + { + method: "POST", + path: ATTESTATION_PATH, + body: { + seat: "validation", + environmentId: ENVIRONMENT, + threadId: QA, + model: "qa-model", + harness: "codex", + setBy: ENVIRONMENT, + key: KEY, + }, + }, + ]); + }).pipe(Effect.provide(layer)); +}); + +it.effect("files a receipt from the current attested seat and hashes the acceptance text", () => { + const { layer, requests } = harness(); + return Effect.gen(function* () { + const handoffs = yield* SeatHandoffs.SeatHandoffs; + const input = { + ...INPUT, + run: "other-run", + seat: "other-seat", + seatThread: { environmentId: "other-env", threadId: "other-thread" }, + acceptance: { index: 9, hash: "forged" }, + }; + const { qaReceipt } = yield* handoffs.fileQaReceipt(scopeFor(QA), input); + assert.deepEqual(requests.at(-1), { + method: "POST", + path: RECEIPT_PATH, + body: { + run: RUN, + seat: "validation", + seatThread: { environmentId: ENVIRONMENT, threadId: QA }, + acceptance: { index: 0, hash: "87b61f888e1f0da4" }, + verdict: "pass", + evidence: ["report.png"], + filedBy: ENVIRONMENT, + key: KEY, + }, + }); + assert.deepEqual(qaReceipt, { id: 21, modelSource: "attested", independenceChecked: true }); + }).pipe(Effect.provide(layer)); +}); + +it.effect("refuses callers without an attested QA seat on the current run", () => { + const { layer, requests } = harness(); + return Effect.gen(function* () { + const handoffs = yield* SeatHandoffs.SeatHandoffs; + for (const threadId of [PARENT, ThreadId.make("thread:unattested"), BUILDER]) { + const failure = yield* Effect.flip(handoffs.fileQaReceipt(scopeFor(threadId), INPUT)); + assert.equal(failure.code, "invalid_request"); + assert.match(failure.message, /attested QA seat/); + } + assert.isFalse(requests.some((request) => request.method === "POST")); + }).pipe(Effect.provide(layer)); +}); + +it.effect("maps an independence refusal by code and tells the QA seat to stop", () => { + const { layer, requests } = harness({ + receiptRefusal: { status: 409, code: "independence" }, + }); + return Effect.gen(function* () { + const handoffs = yield* SeatHandoffs.SeatHandoffs; + const failure = yield* Effect.flip(handoffs.fileQaReceipt(scopeFor(QA), INPUT)); + assert.match(failure.message, /builder's model.*Do not retry.*different model/); + assert.lengthOf( + requests.filter((request) => request.method === "POST"), + 1, + ); + }).pipe(Effect.provide(layer)); +}); + +it.effect("reads and returns the updated numbered checklist after hash drift", () => { + const { layer, requests } = harness({ + receiptRefusal: { status: 400, code: "invalid-field", field: "acceptance.hash" }, + }); + return Effect.gen(function* () { + const handoffs = yield* SeatHandoffs.SeatHandoffs; + const failure = yield* Effect.flip(handoffs.fileQaReceipt(scopeFor(QA), INPUT)); + assert.include( + failure.message, + "1. The preview works offline.\n2. The report can be exported.", + ); + assert.deepEqual( + requests.map(({ method, path }) => [method, path]), + [ + ["GET", TASK_PATH], + ["POST", RECEIPT_PATH], + ["GET", TASK_PATH], + ], + ); + }).pipe(Effect.provide(layer)); +}); + +it.effect("refuses both operations without a host key before contacting the engine", () => { + const { layer, requests } = harness({ key: false }); + return Effect.gen(function* () { + const handoffs = yield* SeatHandoffs.SeatHandoffs; + const receipt = yield* Effect.flip(handoffs.fileQaReceipt(scopeFor(QA), INPUT)); + const attestation = yield* Effect.flip(handoffs.attestSeat(RUN, "validation", QA, "qa-model")); + assert.match(receipt.message, /no board approval key/); + assert.match(attestation.message, /no board approval key/); + assert.isEmpty(requests); + }).pipe(Effect.provide(layer)); +}); + +it.effect("keeps seat attestations and receipts out of the generic delivery relay", () => { + const { layer, requests } = harness(); + return Effect.gen(function* () { + const delivery = yield* DeliveryService.DeliveryService; + for (const path of [ATTESTATION_PATH, RECEIPT_PATH]) { + const error = yield* Effect.flip(delivery.act({ path, body: { key: KEY } })); + assert.equal(error.reason, "refused"); + } + assert.isEmpty(requests); + }).pipe(Effect.provide(layer)); +}); diff --git a/apps/server/src/delivery/SeatHandoffs.ts b/apps/server/src/delivery/SeatHandoffs.ts new file mode 100644 index 0000000000000..6ecc2283e773d --- /dev/null +++ b/apps/server/src/delivery/SeatHandoffs.ts @@ -0,0 +1,251 @@ +import { + type DeliveryError, + DeliveryQaReceiptInput, + DeliveryQaReceiptResult, + DeliverySeatAttestation, + DeliverySeatHandoff, + OrchestratorMcpFailure, + type ThreadId, +} from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Hex from "effect/encoding/Hex"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import { type McpInvocationScope, requireThreadScope } from "../mcp/McpInvocationContext.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import { BOARD_THREAD_KEY_VARIABLE } from "./BoardTaskThreads.ts"; +import { boardTaskOfMarker } from "./boardThreadMarker.ts"; +import * as DeliveryService from "./DeliveryService.ts"; + +const TaskDetail = Schema.Struct({ + acceptance: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), + council: Schema.optional( + Schema.NullOr( + Schema.Struct({ + run: Schema.String, + seats: Schema.Array( + Schema.Struct({ + seat: Schema.String, + threadId: Schema.optional(Schema.NullOr(Schema.String)), + actualModel: Schema.optional(Schema.NullOr(Schema.String)), + }), + ), + }), + ), + ), + roster: Schema.optional( + Schema.NullOr( + Schema.Array( + Schema.Struct({ + seat: Schema.String, + inGate: Schema.optional(Schema.Boolean), + stages: Schema.optional(Schema.Array(Schema.String)), + }), + ), + ), + ), + handoffs: Schema.optional(Schema.NullOr(Schema.Array(DeliverySeatHandoff))), +}); +const decodeTaskDetail = Schema.decodeUnknownEffect(TaskDetail); +const decodeAttestation = Schema.decodeUnknownEffect( + Schema.Struct({ attestation: DeliverySeatAttestation }), +); +const decodeReceipt = Schema.decodeUnknownEffect(DeliveryQaReceiptResult); +const decodeRefusal = Schema.decodeUnknownOption( + Schema.Struct({ code: Schema.optional(Schema.String), field: Schema.optional(Schema.String) }), +); + +const refusalOf = (error: DeliveryError) => Option.getOrUndefined(decodeRefusal(error.body)); +const invalidRequest = (message: string) => + new OrchestratorMcpFailure({ code: "invalid_request", message }); +const missingKey = () => invalidRequest("This server has no board approval key configured."); +const notQaSeat = () => + invalidRequest("File QA receipts from an attested QA seat thread for the task's current run."); + +const engineFailure = (error: DeliveryError, operation: string) => { + switch (refusalOf(error)?.code) { + case "independence": + return invalidRequest( + "This seat runs the builder's model. Do not retry. The lead needs a QA seat from a different model.", + ); + case "moved": + return invalidRequest("This task is worked on another machine. Continue there."); + case "refused": + return invalidRequest( + "This server has no valid board approval key. Ask the server operator.", + ); + case "not-found": + return new OrchestratorMcpFailure({ + code: "task_not_found", + message: + "The engine could not find the task or run. Ask the lead to check the current run.", + }); + case "invalid-field": + return invalidRequest(`The engine rejected a field while trying to ${operation}.`); + default: + return new OrchestratorMcpFailure({ + code: "orchestration_error", + message: `Could not ${operation} through the delivery engine.`, + }); + } +}; + +const checklistChanged = (items: ReadonlyArray) => + invalidRequest( + items.length === 0 + ? "The current checklist has no acceptance items." + : `Check the current acceptance items before filing again. Use a zero-based acceptanceIndex (item 1 is index 0).\n${items.map((item, index) => `${index + 1}. ${item}`).join("\n")}`, + ); + +export class SeatHandoffs extends Context.Service< + SeatHandoffs, + { + readonly attestSeat: ( + run: string, + seat: string, + threadId: ThreadId, + model: string, + harness?: string, + ) => Effect.Effect< + typeof DeliverySeatAttestation.Type, + OrchestratorMcpFailure, + ServerEnvironment.ServerEnvironmentIdentity + >; + readonly fileQaReceipt: ( + scope: McpInvocationScope, + input: typeof DeliveryQaReceiptInput.Type, + ) => Effect.Effect; + } +>()("t3/delivery/SeatHandoffs") {} + +const make = Effect.gen(function* () { + const delivery = yield* DeliveryService.DeliveryService; + const threads = yield* ThreadManagementService.ThreadManagementService; + const hostEnvironment = yield* HostProcess.Environment; + + const readTask = Effect.fn("SeatHandoffs.readTask")(function* (path: string) { + const response = yield* delivery + .read({ path }) + .pipe(Effect.mapError((error) => engineFailure(error, "read the board task"))); + return yield* decodeTaskDetail(response.body).pipe( + Effect.mapError(() => invalidRequest("The engine returned an incompatible board task.")), + ); + }); + + return SeatHandoffs.of({ + attestSeat: Effect.fn("SeatHandoffs.attestSeat")( + function* (run, seat, threadId, model, harness) { + const key = hostEnvironment[BOARD_THREAD_KEY_VARIABLE]; + if (!key) return yield* missingKey(); + const identity = yield* ServerEnvironment.ServerEnvironmentIdentity; + const environmentId = yield* identity.getEnvironmentId; + const response = yield* delivery + .boardThreadAct({ + method: "POST", + path: `/api/runs/${run}/seat-attestations`, + body: { seat, environmentId, threadId, model, harness, setBy: environmentId, key }, + }) + .pipe(Effect.mapError((error) => engineFailure(error, "attest the seat"))); + const { attestation } = yield* decodeAttestation(response.body).pipe( + Effect.mapError(() => invalidRequest("The engine did not return a seat attestation.")), + ); + return attestation; + }, + ), + fileQaReceipt: Effect.fn("SeatHandoffs.fileQaReceipt")(function* (scope, input) { + const caller = yield* requireThreadScope(scope, "Filing a QA receipt"); + const environmentId = caller.environmentId; + const key = hostEnvironment[BOARD_THREAD_KEY_VARIABLE]; + if (!key) return yield* missingKey(); + + const findThread = (threadId: ThreadId) => + threads.getThreadShell(threadId).pipe( + Effect.mapError( + () => + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "Could not read the QA thread's lineage.", + }), + ), + ); + const thread = yield* findThread(caller.thread.threadId); + const parentId = thread?.lineage.parentThreadId; + if (!parentId) return yield* notQaSeat(); + const parent = yield* findThread(parentId); + const task = boardTaskOfMarker(parent?.lineage.engineIntake); + if (!task) return yield* notQaSeat(); + + const path = `/api/tasks/${task.id}`; + const detail = yield* readTask(path); + const council = detail.council; + const seat = council?.seats.find((entry) => entry.threadId === caller.thread.threadId); + if (!council?.run || !seat?.seat || !seat.actualModel || !seat.threadId) + return yield* notQaSeat(); + + const roster = detail.roster ?? []; + const duty = roster.find((entry) => entry.seat === seat.seat); + const inQa = roster.some((entry) => entry.inGate) + ? duty?.inGate + : duty?.stages?.includes("qa"); + const handoff = detail.handoffs?.find( + (entry) => + entry.run === council.run && + entry.stage === "qa" && + entry.seat === seat.seat && + entry.seatThread?.threadId === seat.threadId, + ); + const seatEnvironment = handoff?.seatThread?.environmentId ?? environmentId; + if ((!inQa && !handoff) || seatEnvironment !== environmentId) return yield* notQaSeat(); + + const items = detail.acceptance ?? []; + const item = items[input.acceptanceIndex]; + if (item === undefined) return yield* checklistChanged(items); + const digest = yield* Effect.tryPromise({ + try: () => crypto.subtle.digest("SHA-256", new TextEncoder().encode(item)), + catch: () => + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "Could not hash the acceptance item.", + }), + }); + const hash = Hex.encode(new Uint8Array(digest).subarray(0, 8)); + const filed = yield* delivery + .boardThreadAct({ + method: "POST", + path: `${path}/qa-receipts`, + body: { + run: council.run, + seat: seat.seat, + seatThread: { environmentId: seatEnvironment, threadId: seat.threadId }, + acceptance: { index: input.acceptanceIndex, hash }, + verdict: input.verdict, + evidence: input.evidence, + filedBy: environmentId, + key, + }, + }) + .pipe(Effect.result); + if (filed._tag === "Failure") { + const refusal = refusalOf(filed.failure); + if ( + refusal?.code === "invalid-field" && + (refusal.field === "acceptance.hash" || refusal.field === "acceptance.index") + ) { + const latest = yield* readTask(path); + return yield* checklistChanged(latest.acceptance ?? []); + } + return yield* engineFailure(filed.failure, "file the QA receipt"); + } + return yield* decodeReceipt(filed.success.body).pipe( + Effect.mapError(() => invalidRequest("The engine did not return a QA receipt.")), + ); + }), + }); +}); + +export const layer = Layer.effect(SeatHandoffs, make); diff --git a/apps/server/src/delivery/boardThreadMarker.test.ts b/apps/server/src/delivery/boardThreadMarker.test.ts index bf80180241297..b84a54d86cf2a 100644 --- a/apps/server/src/delivery/boardThreadMarker.test.ts +++ b/apps/server/src/delivery/boardThreadMarker.test.ts @@ -89,6 +89,10 @@ const BOARD_TASK_READS = [ file: "apps/server/src/delivery/BoardTaskThreads.ts", line: "const stamped = boardTaskOfMarker(created.thread.lineage.engineIntake);", }, + { + file: "apps/server/src/delivery/SeatHandoffs.ts", + line: "const task = boardTaskOfMarker(parent?.lineage.engineIntake);", + }, ]; it("only the engine intake and the named board task readers read the marker's value", () => { diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index 903c10b2fed54..5f54d585f317a 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -12,6 +12,7 @@ import * as McpToolAccess from "../../McpToolAccess.ts"; import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts"; import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts"; import * as NativeBuildExecution from "../../../delivery/NativeBuildExecution.ts"; +import * as SeatHandoffs from "../../../delivery/SeatHandoffs.ts"; const handlers = { delivery_read: McpToolAccess.reads(({ environmentId, ...input }) => @@ -28,6 +29,13 @@ const handlers = { return yield* service.step(scope, input); }).pipe(Effect.provide(NativeBuildExecution.layer)), ), + delivery_qa_receipt: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const scope = yield* McpInvocationContext.McpInvocationContext; + const service = yield* SeatHandoffs.SeatHandoffs; + return yield* service.fileQaReceipt(scope, input); + }).pipe(Effect.provide(SeatHandoffs.layer)), + ), orchestrator_capabilities: McpToolAccess.reads((input) => Effect.gen(function* () { const scope = yield* McpInvocationContext.McpInvocationContext; diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 2c35e9a01ca3b..d2e86becce70c 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -4,6 +4,8 @@ import { DeliveryDiscoverySnapshot, DeliveryNativeBuildStepInput, DeliveryNativeBuildStepResult, + DeliveryQaReceiptInput, + DeliveryQaReceiptResult, OrchestratorMcpCapabilitiesInput, OrchestratorMcpCapabilitiesResult, OrchestrationV2StopWorkflowInput, @@ -402,9 +404,23 @@ const NativeBuildStepTool = Tool.make("delivery_native_build_step", { .annotate(Tool.Destructive, true) .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWhileDeliveryOff); +const QaReceiptTool = Tool.make("delivery_qa_receipt", { + description: + "File a verdict and evidence refs for one acceptance item from the current run's attested QA seat thread. Use a zero-based index. The server resolves the task, seat, and checklist hash.", + parameters: DeliveryQaReceiptInput, + success: DeliveryQaReceiptResult, + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [...dependencies, DeliveryService], +}) + .annotate(Tool.Title, "File a QA receipt") + .annotate(Tool.Destructive, true) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWhileDeliveryOff); + export const OrchestratorToolkit = Toolkit.make( DeliveryReadTool, NativeBuildStepTool, + QaReceiptTool, OrchestratorCapabilitiesTool, DelegateTaskTool, TaskStatusTool, diff --git a/packages/contracts/src/delivery.ts b/packages/contracts/src/delivery.ts index 060dfc9d8d456..eb09a18d4bc8d 100644 --- a/packages/contracts/src/delivery.ts +++ b/packages/contracts/src/delivery.ts @@ -156,6 +156,72 @@ export const DeliveryNativeBuildStepResult = Schema.Struct({ next: Schema.optional(Schema.String), }); +const DeliverySeatThread = Schema.Struct({ + environmentId: Schema.optional(Schema.NullOr(Schema.String)), + threadId: Schema.optional(Schema.NullOr(Schema.String)), +}); +const DeliveryQaVerdict = Schema.Literals(["pass", "fail", "blocked"]); +const DeliveryAcceptanceIndex = Schema.Number.check( + Schema.isInt(), + Schema.isGreaterThanOrEqualTo(0), +); +const DeliveryEvidenceRef = Schema.String.check(Schema.isPattern(/^[^\s\p{C}]{1,1024}$/u)); + +export const DeliveryQaReceipt = Schema.Struct({ + id: Schema.optional(Schema.NullOr(Schema.Number)), + task: Schema.optional(Schema.NullOr(Schema.String)), + run: Schema.optional(Schema.NullOr(Schema.String)), + seat: Schema.optional(Schema.NullOr(Schema.String)), + seatThread: Schema.optional(Schema.NullOr(DeliverySeatThread)), + acceptance: Schema.optional( + Schema.NullOr( + Schema.Struct({ + index: Schema.optional(Schema.NullOr(DeliveryAcceptanceIndex)), + hash: Schema.optional(Schema.NullOr(Schema.String)), + }), + ), + ), + verdict: Schema.optional(Schema.NullOr(DeliveryQaVerdict)), + evidence: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), + model: Schema.optional(Schema.NullOr(Schema.String)), + modelSource: Schema.optional(Schema.NullOr(Schema.Literals(["attested", "picked", "requested"]))), + independenceChecked: Schema.optional(Schema.NullOr(Schema.Boolean)), + filedBy: Schema.optional(Schema.NullOr(Schema.String)), + filedAt: Schema.optional(Schema.NullOr(Schema.String)), +}); + +export const DeliverySeatHandoff = Schema.Struct({ + id: Schema.optional(Schema.NullOr(Schema.Number)), + run: Schema.optional(Schema.NullOr(Schema.String)), + stage: Schema.optional(Schema.NullOr(Schema.Literals(["build", "review", "qa"]))), + seat: Schema.optional(Schema.NullOr(Schema.String)), + seatThread: Schema.optional(Schema.NullOr(DeliverySeatThread)), + state: Schema.optional(Schema.NullOr(Schema.Literals(["handed", "delivered", "fallen-back"]))), + reason: Schema.optional(Schema.NullOr(Schema.String)), + setBy: Schema.optional(Schema.NullOr(Schema.String)), + setAt: Schema.optional(Schema.NullOr(Schema.String)), +}); + +export const DeliverySeatAttestation = Schema.Struct({ + ...DeliverySeatThread.fields, + run: Schema.optional(Schema.NullOr(Schema.String)), + seat: Schema.optional(Schema.NullOr(Schema.String)), + model: Schema.optional(Schema.NullOr(Schema.String)), + harness: Schema.optional(Schema.NullOr(Schema.String)), + setBy: Schema.optional(Schema.NullOr(Schema.String)), + setAt: Schema.optional(Schema.NullOr(Schema.String)), +}); + +export const DeliveryQaReceiptInput = Schema.Struct({ + acceptanceIndex: DeliveryAcceptanceIndex.annotate({ description: "Zero-based checklist index." }), + verdict: DeliveryQaVerdict, + evidence: Schema.Array(DeliveryEvidenceRef), +}); +export const DeliveryQaReceiptResult = Schema.Struct({ + qaReceipt: DeliveryQaReceipt, + unchanged: Schema.optional(Schema.NullOr(Schema.Boolean)), +}); + /** * What a thread was started with. Pinned at bind time: a thread keeps its * team, role and configuration revision even when the team is edited later. From 132b6abedd7ad0a2c52fdd7f93b0b7ca86c0d220 Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Mon, 23 Nov 2026 17:25:03 +0000 Subject: [PATCH 02/10] feat(server): the board lead hands QA to a seat conversation and settles it Co-Authored-By: Claude Opus 5.5 --- apps/server/src/delivery/BoardTaskThreads.ts | 19 +- apps/server/src/delivery/DeliveryService.ts | 3 +- .../src/delivery/NativeBuildExecution.ts | 17 +- apps/server/src/delivery/SeatHandoffs.test.ts | 371 +++++++++++++++- apps/server/src/delivery/SeatHandoffs.ts | 405 ++++++++++++++++-- .../src/delivery/boardThreadMarker.test.ts | 4 + apps/server/src/delivery/seatProvider.ts | 27 ++ apps/server/src/mcp/McpHttpServer.ts | 7 +- .../src/mcp/toolkits/orchestrator/handlers.ts | 9 +- .../src/mcp/toolkits/orchestrator/tools.ts | 19 +- packages/contracts/src/delivery.ts | 10 + 11 files changed, 810 insertions(+), 81 deletions(-) create mode 100644 apps/server/src/delivery/seatProvider.ts diff --git a/apps/server/src/delivery/BoardTaskThreads.ts b/apps/server/src/delivery/BoardTaskThreads.ts index 4ad7b6f52887c..99d2f4d69d1b9 100644 --- a/apps/server/src/delivery/BoardTaskThreads.ts +++ b/apps/server/src/delivery/BoardTaskThreads.ts @@ -2,7 +2,6 @@ // facts only: its lanes say what started and which thread each task holds, its teams say who // leads. This never starts a task, and no client asks it to make a thread. import { - DELIVERY_HARNESS_BY_DRIVER, CommandId, type DeliveryError, ModelSelection, @@ -37,6 +36,7 @@ import { type BoardTask, } from "./boardThreadMarker.ts"; import * as DeliveryService from "./DeliveryService.ts"; +import { resolveSeatProvider } from "./seatProvider.ts"; /** The engine's `boardThread` (spec 6a). The field names are the engine's and are not renamed. */ const BoardThread = Schema.Struct({ @@ -252,19 +252,12 @@ export const make = Effect.gen(function* () { team?.seats.find((seat) => seat.seat === "lead"); if (lead === undefined) return "no-lead" as const; if (!lead.model) return "no-lead-model" as const; - const candidates = (yield* instances.listInstances).filter( - (instance) => - instance.enabled && DELIVERY_HARNESS_BY_DRIVER[instance.driverKind] === lead.harness, + const instance = resolveSeatProvider( + (yield* instances.listInstances).filter((instance) => instance.enabled), + lead.harness, + (instance) => instance.instanceId, ); - // Two instances of one harness are two accounts: the engine names a harness, not an account, - // so only the driver's own default instance or a sole instance is the one it means. - const instance = - candidates.find( - (candidate) => String(candidate.instanceId) === String(candidate.driverKind), - ) ?? (candidates.length === 1 ? candidates[0] : undefined); - if (instance === undefined) { - return candidates.length === 0 ? ("no-provider" as const) : ("ambiguous-provider" as const); - } + if (typeof instance === "string") return instance; return yield* local(decodeSelection({ instanceId: instance.instanceId, model: lead.model })); }); diff --git a/apps/server/src/delivery/DeliveryService.ts b/apps/server/src/delivery/DeliveryService.ts index f017a6a75d944..54440fa88aa50 100644 --- a/apps/server/src/delivery/DeliveryService.ts +++ b/apps/server/src/delivery/DeliveryService.ts @@ -133,7 +133,8 @@ const BOARD_THREAD_CLAIM = /^\/api\/orchestration\/tasks\/[\w-]+\/(claim|ack|rel // The conversation's mirror and the steer handshake (spec 6a, slice 5). const BOARD_THREAD_CONVERSATION = /^\/api\/tasks\/[\w-]+\/(activity|steers\/\d+\/(delivered|failed))$/; -const BOARD_SEAT_POST = /^\/api\/(?:tasks\/[\w-]+\/qa-receipts|runs\/[\w-]+\/seat-attestations)$/; +const BOARD_SEAT_POST = + /^\/api\/(?:tasks\/[\w-]+\/qa-receipts|runs\/[\w-]+\/(?:seat-attestations|handoffs(?:\/qa\/(?:delivered|fallback))?))$/; const BOARD_THREAD_POST = new RegExp( `${BOARD_THREAD_CLAIM.source}|${BOARD_THREAD_CONVERSATION.source}|${BOARD_SEAT_POST.source}`, ); diff --git a/apps/server/src/delivery/NativeBuildExecution.ts b/apps/server/src/delivery/NativeBuildExecution.ts index 506d428196ae7..111565d6aa12b 100644 --- a/apps/server/src/delivery/NativeBuildExecution.ts +++ b/apps/server/src/delivery/NativeBuildExecution.ts @@ -1,5 +1,4 @@ import { - DELIVERY_HARNESS_BY_DRIVER, DeliveryNativeBuildStepInput, DeliveryNativeBuildStepResult, NodeId, @@ -15,6 +14,7 @@ import * as Schema from "effect/Schema"; import type { McpInvocationScope } from "../mcp/McpInvocationContext.ts"; import { OrchestratorMcpService } from "../mcp/OrchestratorMcpService.ts"; import { DeliveryService, sameFolder } from "./DeliveryService.ts"; +import { resolveSeatProvider } from "./seatProvider.ts"; const NativeBuild = Schema.Struct({ version: Schema.Literal(1), @@ -107,16 +107,13 @@ export const make = Effect.gen(function* () { const nativeScope = { ...scope, requestNamespace: `delivery-native:${owner}:${build.id}` }; if (!build.native) { const capabilities = yield* orchestrator.capabilities(scope); - const candidates = capabilities.providers.filter( - (provider) => - provider.canRunChildTask && - DELIVERY_HARNESS_BY_DRIVER[provider.driverKind] === build.harness, + const provider = resolveSeatProvider( + capabilities.providers.filter((provider) => provider.canRunChildTask), + build.harness, + (provider) => provider.providerInstanceId, + scope.thread.providerInstanceId, ); - const provider = - candidates.find( - (provider) => provider.providerInstanceId === scope.thread?.providerInstanceId, - ) ?? (candidates.length === 1 ? candidates[0] : undefined); - if (!provider) + if (typeof provider === "string") return yield* refused( "The engine harness does not identify one enabled native provider instance.", ); diff --git a/apps/server/src/delivery/SeatHandoffs.test.ts b/apps/server/src/delivery/SeatHandoffs.test.ts index 6e41c6d385c78..ca409d96d7566 100644 --- a/apps/server/src/delivery/SeatHandoffs.test.ts +++ b/apps/server/src/delivery/SeatHandoffs.test.ts @@ -1,5 +1,14 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import { + type DeliveryQaReceipt, + type DeliverySeatHandoff, + EnvironmentId, + NodeId, + type OrchestratorMcpDelegateTaskInput, + type OrchestratorMcpTerminalDelegatedTaskStatus, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; @@ -8,6 +17,7 @@ import * as Layer from "effect/Layer"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import type { McpInvocationScope } from "../mcp/McpInvocationContext.ts"; +import * as OrchestratorMcpService from "../mcp/OrchestratorMcpService.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -24,6 +34,7 @@ const BUILDER = ThreadId.make("thread:builder"); const TASK_PATH = "/api/tasks/task-17"; const RUN = "run-24"; const ATTESTATION_PATH = `/api/runs/${RUN}/seat-attestations`; +const HANDOFF_PATH = `/api/runs/${RUN}/handoffs`; const RECEIPT_PATH = `${TASK_PATH}/qa-receipts`; const ACCEPTANCE = "The preview renders the report."; const KEY = "scratch-key"; @@ -45,6 +56,10 @@ const scopeFor = (threadId: ThreadId): McpInvocationScope => ({ function harness( options: { readonly key?: boolean; + readonly checklist?: string[]; + readonly seatThread?: { readonly environmentId: string; readonly threadId: string } | null; + readonly boardThread?: { readonly environmentId: string; readonly threadId: string }; + readonly handoffResponse?: "lost" | "conflict" | "independence"; readonly receiptRefusal?: { readonly status: number; readonly code: string; @@ -54,7 +69,16 @@ function harness( ) { const engine = scratchEngine(); const task = boardTaskOf("board", "task-17")!; - let acceptance = [ACCEPTANCE]; + let acceptance = options.checklist ?? [ACCEPTANCE]; + let handoff: typeof DeliverySeatHandoff.Type | undefined; + let handoffResponse = options.handoffResponse; + let attestedThread: string = QA; + let qaReceipts: ReadonlyArray = []; + let terminal: OrchestratorMcpTerminalDelegatedTaskStatus | null = null; + const admissions = new Map(); + const launches: Array<{ namespace: string; input: OrchestratorMcpDelegateTaskInput }> = []; + const cancels: Array = []; + const statusReads: NodeId[] = []; const layer = SeatHandoffs.layer.pipe( Layer.provideMerge(DeliveryService.layer(deriveProviderInstanceConfigMap)), Layer.provide( @@ -66,37 +90,104 @@ function harness( return { status: 200, body: { + title: "Verify report preview", + body: "A report should appear in the preview pane.", + boardThread: options.boardThread ?? { + environmentId: ENVIRONMENT, + threadId: PARENT, + }, acceptance, + handoffs: handoff ? [handoff] : [], + qaReceipts, council: { run: RUN, + candidate: "a".repeat(40), + base: "b".repeat(40), seats: [ - { seat: "validation", threadId: QA, actualModel: "qa-model" }, + { seat: "unavailable", harness: "dsh", requestedModel: "unavailable-model" }, + { + seat: "validation", + threadId: options.seatThread ? "old-thread-field" : attestedThread, + seatThread: options.seatThread, + actualModel: "qa-model", + harness: "dsh", + requestedModel: "original-model", + currentModel: { model: "picked-model", harness: "codex", source: "picked" }, + }, { seat: "builder", threadId: BUILDER, actualModel: "build-model" }, + { seat: "backup", harness: "codex", requestedModel: "backup-model" }, ], }, roster: [ + { seat: "unavailable", inGate: true }, { seat: "validation", inGate: true }, { seat: "builder", inGate: false, stages: ["build"] }, + { seat: "backup", inGate: true }, ], }, }; } if (method === "POST" && path === ATTESTATION_PATH) { engine.requests.push({ method, path, body }); + const input = body as { + seat: string; + threadId: string; + model: string; + harness?: string; + }; + attestedThread = input.threadId; return { status: 200, body: { attestation: { run: RUN, - seat: "validation", - threadId: QA, + seat: input.seat, + threadId: input.threadId, environmentId: ENVIRONMENT, - model: "qa-model", - harness: "codex", + model: input.model, + harness: input.harness, }, }, }; } + if (method === "POST" && path === HANDOFF_PATH) { + engine.requests.push({ method, path, body }); + if (handoffResponse === "lost") { + handoffResponse = undefined; + return { status: 503, body: { error: "Engine unavailable." } }; + } + if (handoffResponse === "independence") { + handoffResponse = undefined; + return { status: 409, body: { code: "independence", error: "Engine refusal." } }; + } + handoff = { + id: (handoff?.id ?? 0) + 1, + run: RUN, + stage: "qa", + seat: (body as { seat: string }).seat, + seatThread: { environmentId: ENVIRONMENT, threadId: attestedThread }, + state: "handed", + }; + if (handoffResponse === "conflict") { + handoffResponse = undefined; + return { + status: 409, + body: { code: "conflict", error: "Already handed.", current: handoff }, + }; + } + return { status: 200, body: { run: RUN, handoff } }; + } + if (method === "POST" && handoff && path.startsWith(`${HANDOFF_PATH}/qa/`)) { + engine.requests.push({ method, path, body }); + const delivered = path.endsWith("/delivered"); + handoff = { + ...handoff, + id: handoff.id! + 1, + state: delivered ? "delivered" : "fallen-back", + reason: delivered ? null : (body as { reason: string }).reason, + }; + return { status: 200, body: { run: RUN, handoff } }; + } if (method === "POST" && path === RECEIPT_PATH) { engine.requests.push({ method, path, body }); if (options.receiptRefusal) { @@ -120,14 +211,62 @@ function harness( ), Layer.provide( Layer.succeed(ThreadManagementService.ThreadManagementService, { - getThreadShell: (threadId: ThreadId) => - Effect.succeed( + getThreadShell: (threadId: ThreadId) => { + const child = [...admissions.values()].find( + ({ childThreadId }) => childThreadId === threadId, + ); + return Effect.succeed( threadId === PARENT ? { lineage: { engineIntake: boardTaskThreadMarker(task) } } - : { lineage: { parentThreadId: PARENT } }, - ), + : { + lineage: { parentThreadId: PARENT }, + forkedFrom: child ? { type: "node", nodeId: child.taskId } : null, + }, + ); + }, } as unknown as ThreadManagementService.ThreadManagementService["Service"]), ), + Layer.provide( + Layer.succeed(OrchestratorMcpService.OrchestratorMcpService, { + capabilities: () => + Effect.succeed({ + providers: [ + { driverKind: "deepseek", providerInstanceId: "deepseek", canRunChildTask: false }, + { driverKind: "codex", providerInstanceId: "other-codex", canRunChildTask: true }, + { driverKind: "codex", providerInstanceId: "codex", canRunChildTask: true }, + ], + }), + delegateTask: (scope: McpInvocationScope, input: OrchestratorMcpDelegateTaskInput) => { + launches.push({ namespace: scope.requestNamespace, input }); + const request = `${scope.requestNamespace}:${input.clientRequestId}`; + const existing = admissions.get(request); + const child = existing ?? { + taskId: NodeId.make(`node:qa:${admissions.size}`), + childThreadId: ThreadId.make(`thread:qa:${admissions.size}`), + }; + admissions.set(request, child); + return Effect.succeed({ + ...child, + providerInstanceId: input.target?.providerInstanceId, + model: "launched-model", + }); + }, + cancelTask: (_scope: McpInvocationScope, input: { readonly taskId: NodeId }) => { + cancels.push(input.taskId); + return Effect.succeed({}); + }, + taskStatus: (_scope: McpInvocationScope, taskId: NodeId) => { + statusReads.push(taskId); + return Effect.succeed({ + childThreadId: [...admissions.values()].find((entry) => entry.taskId === taskId) + ?.childThreadId, + workState: terminal === null ? "working" : "result_available", + hasPendingChildRuns: false, + latestTerminalStatus: terminal, + }); + }, + } as unknown as OrchestratorMcpService.OrchestratorMcpService["Service"]), + ), Layer.provide( ServerSettings.layerTest({ delivery: { enabled: true, engineUrl: "http://127.0.0.1:4320" }, @@ -146,7 +285,18 @@ function harness( ), ), ); - return { layer, requests: engine.requests }; + return { + layer, + requests: engine.requests, + admissions, + launches, + statusReads, + cancels, + finish(status: OrchestratorMcpTerminalDelegatedTaskStatus, receipts: typeof qaReceipts = []) { + terminal = status; + qaReceipts = receipts; + }, + }; } it.effect("attests a seat with the launched model, harness and server identity", () => { @@ -172,8 +322,14 @@ it.effect("attests a seat with the launched model, harness and server identity", }).pipe(Effect.provide(layer)); }); -it.effect("files a receipt from the current attested seat and hashes the acceptance text", () => { - const { layer, requests } = harness(); +it.effect.each([ + { label: "infers an omitted seat thread", seatThread: undefined }, + { + label: "uses the engine's seat thread in preference to the legacy thread id", + seatThread: { environmentId: ENVIRONMENT, threadId: QA }, + }, +])("files a receipt and $label", ({ seatThread }) => { + const { layer, requests } = harness(seatThread ? { seatThread } : {}); return Effect.gen(function* () { const handoffs = yield* SeatHandoffs.SeatHandoffs; const input = { @@ -202,6 +358,183 @@ it.effect("files a receipt from the current attested seat and hashes the accepta }).pipe(Effect.provide(layer)); }); +it.effect("rejects a child caller and a lead whose task is held by another thread", () => { + const { layer, requests, launches } = harness({ + boardThread: { environmentId: ENVIRONMENT, threadId: "different-lead" }, + }); + return Effect.gen(function* () { + const service = yield* SeatHandoffs.SeatHandoffs; + for (const caller of [QA, PARENT]) { + const failure = yield* Effect.flip(service.handQa(scopeFor(caller), {})); + assert.equal(failure.code, "invalid_request"); + assert.match(failure.message, /lead thread/); + } + assert.isEmpty(launches); + assert.deepEqual( + requests.map(({ method }) => method), + ["GET"], + ); + }).pipe(Effect.provide(layer)); +}); + +it.effect("hands QA to the first launchable gate seat and attests the model T3 launched", () => { + const { layer, launches, requests } = harness(); + return Effect.gen(function* () { + const service = yield* SeatHandoffs.SeatHandoffs; + const result = yield* service.handQa(scopeFor(PARENT), {}); + assert.equal(result.state, "working"); + assert.match(result.next ?? "", /end your turn.*do not poll/); + assert.equal(result.handoff.seat, "validation"); + assert.lengthOf(launches, 1); + const launch = launches[0]!.input; + assert.equal(launch.isolation, "worktree"); + assert.equal(launch.mode, "async"); + assert.deepEqual(launch.target, { + providerInstanceId: ProviderInstanceId.make("codex"), + model: "picked-model", + options: [], + }); + for (const text of [ + "Verify report preview", + "A report should appear in the preview pane.", + `0. ${ACCEPTANCE}`, + "a".repeat(40), + "b".repeat(40), + "exactly one delivery_qa_receipt", + "Do not edit code.", + ]) + assert.include(launch.task, text); + assert.deepEqual( + requests.filter(({ method }) => method === "POST"), + [ + { + method: "POST", + path: ATTESTATION_PATH, + body: { + seat: "validation", + environmentId: ENVIRONMENT, + threadId: "thread:qa:0", + model: "launched-model", + harness: "codex", + setBy: ENVIRONMENT, + key: KEY, + }, + }, + { + method: "POST", + path: HANDOFF_PATH, + body: { stage: "qa", seat: "validation", setBy: ENVIRONMENT, key: KEY }, + }, + ], + ); + }).pipe(Effect.provide(layer)); +}); + +it.effect( + "recovers the same filing across sessions and launches a new child after settlement", + () => { + const { layer, launches, admissions, statusReads, finish } = harness({ + handoffResponse: "lost", + }); + const lead = scopeFor(PARENT); + return Effect.gen(function* () { + const service = yield* SeatHandoffs.SeatHandoffs; + yield* Effect.flip(service.handQa(lead, {})); + const newSession = { ...lead, requestNamespace: "another-session" }; + const recovered = yield* service.handQa(newSession, {}); + assert.equal(recovered.state, "working"); + assert.equal(admissions.size, 1); + assert.deepEqual( + launches.map(({ namespace }) => namespace), + [`delivery-handoff:${RUN}:qa:0`, `delivery-handoff:${RUN}:qa:0`], + ); + assert.deepEqual(yield* service.handQa(newSession, {}), recovered); + assert.deepEqual(statusReads, ["node:qa:0"]); + assert.lengthOf(launches, 2); + + finish("interrupted"); + assert.equal((yield* service.handQa(newSession, {})).handoff.reason, "seat-failed"); + const refiled = yield* service.handQa(newSession, {}); + assert.equal(refiled.handoff.seatThread?.threadId, "thread:qa:1"); + assert.equal(admissions.size, 2); + }).pipe(Effect.provide(layer)); + }, +); + +it.effect("recovers the current record carried by an engine conflict", () => { + const { layer, statusReads, launches } = harness({ handoffResponse: "conflict" }); + return Effect.gen(function* () { + const service = yield* SeatHandoffs.SeatHandoffs; + const result = yield* service.handQa(scopeFor(PARENT), { seat: "backup" }); + assert.equal(result.state, "working"); + assert.equal(result.handoff.seat, "backup"); + assert.deepEqual(statusReads, ["node:qa:0"]); + assert.equal(launches[0]?.input.target?.model, "backup-model"); + }).pipe(Effect.provide(layer)); +}); + +it.effect("maps the engine's independence refusal and names the other gate seats", () => { + const { layer, cancels } = harness({ handoffResponse: "independence" }); + return Effect.gen(function* () { + const service = yield* SeatHandoffs.SeatHandoffs; + const failure = yield* Effect.flip(service.handQa(scopeFor(PARENT), {})); + assert.equal(failure.code, "invalid_request"); + // The refused seat is stopped before it can file receipts. + assert.deepEqual(cancels, ["node:qa:0"]); + assert.equal( + failure.message, + "That QA seat shares the builder's model family; pick another seat (seat: unavailable, backup)", + ); + assert.equal( + (yield* service.handQa(scopeFor(PARENT), { seat: "backup" })).handoff.seat, + "backup", + ); + }).pipe(Effect.provide(layer)); +}); + +const currentReceipt = { + run: RUN, + seat: "validation", + acceptance: { index: 0 }, + verdict: "fail", +} as const; +const secondReceipt = { ...currentReceipt, acceptance: { index: 1 }, verdict: "blocked" } as const; +it.effect.each([ + { terminal: "completed", receipts: [currentReceipt, secondReceipt], reason: null }, + { + terminal: "completed", + receipts: [ + currentReceipt, + { ...secondReceipt, run: "old-run" }, + { ...secondReceipt, seat: "backup" }, + ], + reason: "no-receipts", + }, + { terminal: "failed", receipts: [currentReceipt], reason: "seat-failed" }, + { terminal: "cancelled", receipts: [], reason: "seat-failed" }, +] as const)( + "settles a $terminal QA child with reason $reason", + ({ terminal, receipts, reason }) => { + const { layer, finish, requests } = harness({ + checklist: [ACCEPTANCE, "The report can be exported."], + }); + return Effect.gen(function* () { + const service = yield* SeatHandoffs.SeatHandoffs; + const lead = scopeFor(PARENT); + yield* service.handQa(lead, {}); + finish(terminal, receipts); + const result = yield* service.handQa(lead, {}); + assert.equal(result.state, reason ? "fallen-back" : "delivered"); + assert.equal(result.handoff.reason, reason); + assert.deepEqual(requests.at(-1), { + method: "POST", + path: `${HANDOFF_PATH}/qa/${reason ? "fallback" : "delivered"}`, + body: { ...(reason ? { reason } : {}), setBy: ENVIRONMENT, key: KEY }, + }); + }).pipe(Effect.provide(layer)); + }, +); + it.effect("refuses callers without an attested QA seat on the current run", () => { const { layer, requests } = harness(); return Effect.gen(function* () { @@ -209,7 +542,7 @@ it.effect("refuses callers without an attested QA seat on the current run", () = for (const threadId of [PARENT, ThreadId.make("thread:unattested"), BUILDER]) { const failure = yield* Effect.flip(handoffs.fileQaReceipt(scopeFor(threadId), INPUT)); assert.equal(failure.code, "invalid_request"); - assert.match(failure.message, /attested QA seat/); + assert.match(failure.message, /attested/); } assert.isFalse(requests.some((request) => request.method === "POST")); }).pipe(Effect.provide(layer)); @@ -268,7 +601,13 @@ it.effect("keeps seat attestations and receipts out of the generic delivery rela const { layer, requests } = harness(); return Effect.gen(function* () { const delivery = yield* DeliveryService.DeliveryService; - for (const path of [ATTESTATION_PATH, RECEIPT_PATH]) { + for (const path of [ + ATTESTATION_PATH, + RECEIPT_PATH, + HANDOFF_PATH, + `${HANDOFF_PATH}/qa/delivered`, + `${HANDOFF_PATH}/qa/fallback`, + ]) { const error = yield* Effect.flip(delivery.act({ path, body: { key: KEY } })); assert.equal(error.reason, "refused"); } diff --git a/apps/server/src/delivery/SeatHandoffs.ts b/apps/server/src/delivery/SeatHandoffs.ts index 6ecc2283e773d..b4209cc4cb174 100644 --- a/apps/server/src/delivery/SeatHandoffs.ts +++ b/apps/server/src/delivery/SeatHandoffs.ts @@ -1,11 +1,16 @@ import { + DELIVERY_HARNESS_BY_DRIVER, type DeliveryError, DeliveryQaReceiptInput, DeliveryQaReceiptResult, + DeliveryQaReceipt, DeliverySeatAttestation, DeliverySeatHandoff, + DeliverySeatHandoffInput, + DeliverySeatHandoffResult, + type EnvironmentId, OrchestratorMcpFailure, - type ThreadId, + ThreadId, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; @@ -14,25 +19,45 @@ import * as Hex from "effect/encoding/Hex"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; -import { type McpInvocationScope, requireThreadScope } from "../mcp/McpInvocationContext.ts"; +import { + type McpInvocationScope, + type McpThreadInvocationScope, + requireThreadScope, +} from "../mcp/McpInvocationContext.ts"; +import * as OrchestratorMcpService from "../mcp/OrchestratorMcpService.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import { BOARD_THREAD_KEY_VARIABLE } from "./BoardTaskThreads.ts"; import { boardTaskOfMarker } from "./boardThreadMarker.ts"; import * as DeliveryService from "./DeliveryService.ts"; +import { resolveSeatProvider } from "./seatProvider.ts"; +const SeatThread = Schema.Struct({ environmentId: Schema.String, threadId: Schema.String }); +const optionalString = Schema.optional(Schema.NullOr(Schema.String)); const TaskDetail = Schema.Struct({ + title: optionalString, + body: optionalString, + boardThread: Schema.optional(Schema.NullOr(SeatThread)), acceptance: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), council: Schema.optional( Schema.NullOr( Schema.Struct({ run: Schema.String, + candidate: optionalString, + base: optionalString, seats: Schema.Array( Schema.Struct({ seat: Schema.String, - threadId: Schema.optional(Schema.NullOr(Schema.String)), - actualModel: Schema.optional(Schema.NullOr(Schema.String)), + threadId: optionalString, + seatThread: Schema.optional(Schema.NullOr(SeatThread)), + actualModel: optionalString, + requestedModel: optionalString, + harness: optionalString, + currentModel: Schema.optional( + Schema.NullOr(Schema.Struct({ model: optionalString, harness: optionalString })), + ), }), ), }), @@ -50,14 +75,29 @@ const TaskDetail = Schema.Struct({ ), ), handoffs: Schema.optional(Schema.NullOr(Schema.Array(DeliverySeatHandoff))), + qaReceipts: Schema.optional(Schema.NullOr(Schema.Array(DeliveryQaReceipt))), }); +type TaskDetail = typeof TaskDetail.Type; const decodeTaskDetail = Schema.decodeUnknownEffect(TaskDetail); const decodeAttestation = Schema.decodeUnknownEffect( Schema.Struct({ attestation: DeliverySeatAttestation }), ); const decodeReceipt = Schema.decodeUnknownEffect(DeliveryQaReceiptResult); +const decodeHandoff = Schema.decodeUnknownEffect(Schema.Struct({ handoff: DeliverySeatHandoff })); +const readHandoff = Effect.fn("SeatHandoffs.readHandoff")(function* (body: unknown, run: string) { + const { handoff } = yield* decodeHandoff(body).pipe( + Effect.mapError(() => invalidRequest("The engine did not return a QA hand-off.")), + ); + if (handoff.run !== run || handoff.stage !== "qa" || !handoff.state) + return yield* invalidRequest("The engine did not return this run's QA hand-off."); + return handoff; +}); const decodeRefusal = Schema.decodeUnknownOption( - Schema.Struct({ code: Schema.optional(Schema.String), field: Schema.optional(Schema.String) }), + Schema.Struct({ + code: Schema.optional(Schema.String), + field: Schema.optional(Schema.String), + current: Schema.optional(Schema.Unknown), + }), ); const refusalOf = (error: DeliveryError) => Option.getOrUndefined(decodeRefusal(error.body)); @@ -66,6 +106,22 @@ const invalidRequest = (message: string) => const missingKey = () => invalidRequest("This server has no board approval key configured."); const notQaSeat = () => invalidRequest("File QA receipts from an attested QA seat thread for the task's current run."); +const notLead = () => invalidRequest("Only this board task's lead thread can hand off QA."); +const working = (handoff: typeof DeliverySeatHandoff.Type) => ({ + handoff, + state: "working" as const, + next: "Completion wakes this thread, so end your turn and call delivery_seat_handoff again after the notification; do not poll.", +}); + +const qaGateSeats = (detail: TaskDetail) => { + const roster = detail.roster ?? []; + return roster.some((entry) => entry.inGate) + ? roster.filter((entry) => entry.inGate) + : roster.filter((entry) => entry.stages?.includes("qa")); +}; + +const currentQaHandoff = (detail: TaskDetail, run: string) => + detail.handoffs?.find((entry) => entry.run === run && entry.stage === "qa"); const engineFailure = (error: DeliveryError, operation: string) => { switch (refusalOf(error)?.code) { @@ -120,13 +176,19 @@ export class SeatHandoffs extends Context.Service< scope: McpInvocationScope, input: typeof DeliveryQaReceiptInput.Type, ) => Effect.Effect; + readonly handQa: ( + scope: McpInvocationScope, + input: Pick, + ) => Effect.Effect; } >()("t3/delivery/SeatHandoffs") {} const make = Effect.gen(function* () { const delivery = yield* DeliveryService.DeliveryService; const threads = yield* ThreadManagementService.ThreadManagementService; + const orchestrator = yield* OrchestratorMcpService.OrchestratorMcpService; const hostEnvironment = yield* HostProcess.Environment; + const handoffLock = yield* Semaphore.make(1); const readTask = Effect.fn("SeatHandoffs.readTask")(function* (path: string) { const response = yield* delivery @@ -137,25 +199,292 @@ const make = Effect.gen(function* () { ); }); + const attestSeatAs = Effect.fn("SeatHandoffs.attestSeatAs")(function* ( + environmentId: EnvironmentId, + run: string, + seat: string, + threadId: ThreadId, + model: string, + harness?: string, + ) { + const key = hostEnvironment[BOARD_THREAD_KEY_VARIABLE]; + if (!key) return yield* missingKey(); + const response = yield* delivery + .boardThreadAct({ + method: "POST", + path: `/api/runs/${run}/seat-attestations`, + body: { seat, environmentId, threadId, model, harness, setBy: environmentId, key }, + }) + .pipe(Effect.mapError((error) => engineFailure(error, "attest the seat"))); + const { attestation } = yield* decodeAttestation(response.body).pipe( + Effect.mapError(() => invalidRequest("The engine did not return a seat attestation.")), + ); + return attestation; + }); + + const findThread = Effect.fn("SeatHandoffs.findThread")((threadId: ThreadId) => + threads.getThreadShell(threadId).pipe( + Effect.mapError( + () => + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "Could not read the thread's lineage.", + }), + ), + ), + ); + + const launchQaSeat = Effect.fn("SeatHandoffs.launchQaSeat")(function* ( + detail: TaskDetail, + council: NonNullable, + caller: McpThreadInvocationScope, + filing: number, + namedSeat: string | undefined, + ) { + if (!detail.title || !council.candidate || !council.base) + return yield* invalidRequest( + "The board task needs a title, candidate commit and base to hand off QA.", + ); + const gates = qaGateSeats(detail).flatMap( + ({ seat }) => council.seats.find((entry) => entry.seat === seat) ?? [], + ); + const capabilities = yield* orchestrator.capabilities(caller); + const providers = capabilities.providers.filter((provider) => provider.canRunChildTask); + const nativeScope = { + ...caller, + requestNamespace: `delivery-handoff:${council.run}:qa:${filing}`, + }; + const prompt = [ + `Task: ${detail.title}`, + detail.body ?? "", + "Acceptance items (zero-based indexes):", + ...(detail.acceptance ?? []).map((item, index) => `${index}. ${item}`), + `Candidate commit: ${council.candidate}`, + `Base commit: ${council.base}`, + "Check out the candidate commit in your worktree and test it. Do not edit code. File receipts only after testing.", + "File exactly one delivery_qa_receipt for each acceptance item with its zero-based index, a pass, fail or blocked verdict, and evidence refs. Then end your turn.", + ].join("\n"); + for (const seat of gates) { + if (namedSeat !== undefined && seat.seat !== namedSeat) continue; + const { model, harness } = seat.currentModel ?? { + model: seat.requestedModel, + harness: seat.harness, + }; + if (!model || !harness) continue; + const provider = resolveSeatProvider(providers, harness, (entry) => entry.providerInstanceId); + if (typeof provider === "string") continue; + + const delegated = yield* orchestrator + .delegateTask(nativeScope, { + task: prompt, + clientRequestId: seat.seat, + isolation: "worktree", + mode: "async", + target: { providerInstanceId: provider.providerInstanceId, model, options: [] }, + }) + .pipe(Effect.result); + if (delegated._tag === "Failure") { + if ( + namedSeat === undefined && + (delegated.failure.code === "model_unavailable" || + delegated.failure.code === "provider_unavailable") + ) + continue; + return yield* delegated.failure; + } + const child = delegated.success; + const launchedProvider = capabilities.providers.find( + (entry) => entry.providerInstanceId === child.providerInstanceId, + ); + const launchedHarness = + launchedProvider && DELIVERY_HARNESS_BY_DRIVER[launchedProvider.driverKind]; + if (!child.childThreadId || !child.model || !launchedHarness) + return yield* invalidRequest( + "T3 did not return the launched QA thread, model and harness. Retry to recover the delegation.", + ); + return { + name: seat.seat, + threadId: child.childThreadId, + model: child.model, + harness: launchedHarness, + taskId: child.taskId, + scope: nativeScope, + otherSeats: gates.filter((entry) => entry !== seat).map((entry) => entry.seat), + }; + } + return yield* invalidRequest( + namedSeat === undefined + ? "No QA gate seat has a launchable model and provider." + : "The named seat is not a QA gate seat with a launchable model and provider.", + ); + }); + return SeatHandoffs.of({ attestSeat: Effect.fn("SeatHandoffs.attestSeat")( function* (run, seat, threadId, model, harness) { + const identity = yield* ServerEnvironment.ServerEnvironmentIdentity; + return yield* attestSeatAs( + yield* identity.getEnvironmentId, + run, + seat, + threadId, + model, + harness, + ); + }, + ), + handQa: Effect.fn("SeatHandoffs.handQa")( + function* (scope, input) { + const caller = yield* requireThreadScope(scope, "Handing off QA"); + const { + environmentId, + thread: { threadId }, + } = caller; + const lead = yield* findThread(threadId); + const task = boardTaskOfMarker(lead?.lineage.engineIntake); + if (!task) return yield* notLead(); const key = hostEnvironment[BOARD_THREAD_KEY_VARIABLE]; if (!key) return yield* missingKey(); - const identity = yield* ServerEnvironment.ServerEnvironmentIdentity; - const environmentId = yield* identity.getEnvironmentId; - const response = yield* delivery - .boardThreadAct({ + + const path = `/api/tasks/${task.id}`; + const isLead = (detail: TaskDetail) => + detail.boardThread?.environmentId === environmentId && + detail.boardThread.threadId === threadId; + const detail = yield* readTask(path); + if (!isLead(detail)) return yield* notLead(); + const council = detail.council; + if (!council?.run) return yield* invalidRequest("The board task has no current run."); + const { run } = council; + const endpoint = `/api/runs/${encodeURIComponent(run)}/handoffs`; + const post = (action: string, body: Record) => + delivery.boardThreadAct({ method: "POST", - path: `/api/runs/${run}/seat-attestations`, - body: { seat, environmentId, threadId, model, harness, setBy: environmentId, key }, - }) - .pipe(Effect.mapError((error) => engineFailure(error, "attest the seat"))); - const { attestation } = yield* decodeAttestation(response.body).pipe( - Effect.mapError(() => invalidRequest("The engine did not return a seat attestation.")), + path: endpoint + action, + body: { ...body, setBy: environmentId, key }, + }); + let current = currentQaHandoff(detail, run); + if (current?.state !== "handed") { + if (current && current.id == null) + return yield* invalidRequest("The engine's previous QA hand-off has no filing id."); + // The engine serves the latest filing only. Its id distinguishes a new filing from a retry. + const filing = current?.id == null ? 0 : current.id + 1; + const seat = yield* launchQaSeat(detail, council, caller, filing, input.seat); + yield* attestSeatAs( + environmentId, + run, + seat.name, + seat.threadId, + seat.model, + seat.harness, + ); + const handed = yield* post("", { stage: "qa", seat: seat.name }).pipe(Effect.result); + if (handed._tag === "Success") { + const handoff = yield* readHandoff(handed.success.body, run); + if ( + handoff.state !== "handed" || + handoff.seat !== seat.name || + handoff.seatThread?.environmentId !== environmentId || + handoff.seatThread.threadId !== seat.threadId + ) + return yield* invalidRequest("The engine did not hand QA to the launched seat."); + return working(handoff); + } + const refusal = refusalOf(handed.failure); + const held = + handed.failure.status === 409 && refusal?.code === "conflict" + ? yield* readHandoff({ handoff: refusal.current }, run) + : undefined; + // A seat the engine did not take must not go on to file receipts. + if (held?.seatThread?.threadId !== seat.threadId) + yield* orchestrator + .cancelTask(seat.scope, { + taskId: seat.taskId, + clientRequestId: "handoff-refused", + reason: "The delivery engine refused this QA hand-off.", + }) + .pipe(Effect.ignore); + if (handed.failure.status === 409 && refusal?.code === "independence") + return yield* invalidRequest( + `That QA seat shares the builder's model family; pick another seat (seat: ${seat.otherSeats.join(", ") || "none"})`, + ); + if (held === undefined) return yield* engineFailure(handed.failure, "hand off QA"); + current = held; + if (current.state === "delivered" || current.state === "fallen-back") + return { state: current.state, handoff: current }; + } + + if (current.seatThread?.environmentId !== environmentId || !current.seatThread.threadId) + return yield* invalidRequest("This run's QA hand-off belongs to another environment."); + const childId = ThreadId.make(current.seatThread.threadId); + const child = yield* findThread(childId); + // T3 links the delegated child to the lead's task node when it creates the thread. + if (child?.lineage.parentThreadId !== threadId || child.forkedFrom?.type !== "node") + return yield* invalidRequest( + "This run's QA hand-off has no delegated child of this lead.", + ); + const status = yield* orchestrator.taskStatus(caller, child.forkedFrom.nodeId); + if (status.childThreadId !== childId) + return yield* invalidRequest("The delegated task does not match the handed QA thread."); + if ( + status.workState !== "result_available" || + status.hasPendingChildRuns || + !status.latestTerminalStatus + ) + return working(current); + + const latest = yield* readTask(path); + if (!isLead(latest)) return yield* notLead(); + const handoff = currentQaHandoff(latest, run); + if ( + latest.council?.run !== run || + !handoff || + handoff.seatThread?.threadId !== childId || + handoff.seatThread.environmentId !== environmentId + ) + return yield* invalidRequest( + "The run or its QA hand-off changed. Read the current board task.", + ); + if (handoff.state === "delivered" || handoff.state === "fallen-back") + return { state: handoff.state, handoff }; + if (handoff.state !== "handed" || handoff.id !== current.id) + return yield* invalidRequest("The QA hand-off changed. Read the current board task."); + + const received = new Set( + latest.qaReceipts + ?.filter((receipt) => receipt.run === run && receipt.seat === handoff.seat) + .map((receipt) => receipt.acceptance?.index), ); - return attestation; + const reason = + status.latestTerminalStatus !== "completed" + ? "seat-failed" + : (latest.acceptance ?? []).every((_, index) => received.has(index)) + ? undefined + : "no-receipts"; + const settled = yield* post( + reason ? "/qa/fallback" : "/qa/delivered", + reason ? { reason } : {}, + ).pipe(Effect.result); + let body: unknown; + if (settled._tag === "Success") { + body = settled.success.body; + } else { + const refusal = refusalOf(settled.failure); + if (settled.failure.status !== 409 || refusal?.code !== "conflict") + return yield* engineFailure(settled.failure, "settle the QA hand-off"); + body = { handoff: refusal.current }; + } + const recorded = yield* readHandoff(body, run); + if ( + recorded.seatThread?.environmentId !== environmentId || + recorded.seatThread.threadId !== childId || + (recorded.state !== "delivered" && recorded.state !== "fallen-back") + ) + return yield* invalidRequest( + "The engine did not return this seat's settled QA hand-off.", + ); + return { state: recorded.state, handoff: recorded }; }, + (effect) => handoffLock.withPermit(effect), ), fileQaReceipt: Effect.fn("SeatHandoffs.fileQaReceipt")(function* (scope, input) { const caller = yield* requireThreadScope(scope, "Filing a QA receipt"); @@ -163,16 +492,6 @@ const make = Effect.gen(function* () { const key = hostEnvironment[BOARD_THREAD_KEY_VARIABLE]; if (!key) return yield* missingKey(); - const findThread = (threadId: ThreadId) => - threads.getThreadShell(threadId).pipe( - Effect.mapError( - () => - new OrchestratorMcpFailure({ - code: "orchestration_error", - message: "Could not read the QA thread's lineage.", - }), - ), - ); const thread = yield* findThread(caller.thread.threadId); const parentId = thread?.lineage.parentThreadId; if (!parentId) return yield* notQaSeat(); @@ -183,24 +502,34 @@ const make = Effect.gen(function* () { const path = `/api/tasks/${task.id}`; const detail = yield* readTask(path); const council = detail.council; - const seat = council?.seats.find((entry) => entry.threadId === caller.thread.threadId); - if (!council?.run || !seat?.seat || !seat.actualModel || !seat.threadId) - return yield* notQaSeat(); + const seat = council?.seats.find( + (entry) => + (entry.seatThread === undefined ? entry.threadId : entry.seatThread?.threadId) === + caller.thread.threadId, + ); + // A seat starts before the lead's attestation lands, so an early filing is asked to retry. + if (!council?.run || !seat?.seat || !seat.actualModel) + return yield* invalidRequest( + "This QA seat is not attested for the task's current run yet. Finish testing, then file again; if it still fails, end your turn and report it.", + ); - const roster = detail.roster ?? []; - const duty = roster.find((entry) => entry.seat === seat.seat); - const inQa = roster.some((entry) => entry.inGate) - ? duty?.inGate - : duty?.stages?.includes("qa"); + const inQa = qaGateSeats(detail).some((entry) => entry.seat === seat.seat); const handoff = detail.handoffs?.find( (entry) => entry.run === council.run && entry.stage === "qa" && entry.seat === seat.seat && - entry.seatThread?.threadId === seat.threadId, + entry.seatThread?.threadId === caller.thread.threadId, ); - const seatEnvironment = handoff?.seatThread?.environmentId ?? environmentId; - if ((!inQa && !handoff) || seatEnvironment !== environmentId) return yield* notQaSeat(); + const seatThread = + seat.seatThread === undefined + ? { + environmentId: handoff?.seatThread?.environmentId ?? environmentId, + threadId: caller.thread.threadId, + } + : seat.seatThread; + if ((!inQa && !handoff) || seatThread?.environmentId !== environmentId) + return yield* notQaSeat(); const items = detail.acceptance ?? []; const item = items[input.acceptanceIndex]; @@ -221,7 +550,7 @@ const make = Effect.gen(function* () { body: { run: council.run, seat: seat.seat, - seatThread: { environmentId: seatEnvironment, threadId: seat.threadId }, + seatThread, acceptance: { index: input.acceptanceIndex, hash }, verdict: input.verdict, evidence: input.evidence, diff --git a/apps/server/src/delivery/boardThreadMarker.test.ts b/apps/server/src/delivery/boardThreadMarker.test.ts index b84a54d86cf2a..8d7ecc3b8987e 100644 --- a/apps/server/src/delivery/boardThreadMarker.test.ts +++ b/apps/server/src/delivery/boardThreadMarker.test.ts @@ -93,6 +93,10 @@ const BOARD_TASK_READS = [ file: "apps/server/src/delivery/SeatHandoffs.ts", line: "const task = boardTaskOfMarker(parent?.lineage.engineIntake);", }, + { + file: "apps/server/src/delivery/SeatHandoffs.ts", + line: "const task = boardTaskOfMarker(lead?.lineage.engineIntake);", + }, ]; it("only the engine intake and the named board task readers read the marker's value", () => { diff --git a/apps/server/src/delivery/seatProvider.ts b/apps/server/src/delivery/seatProvider.ts new file mode 100644 index 0000000000000..7324940ff1586 --- /dev/null +++ b/apps/server/src/delivery/seatProvider.ts @@ -0,0 +1,27 @@ +import { + defaultInstanceIdForDriver, + DELIVERY_HARNESS_BY_DRIVER, + type ProviderDriverKind, + type ProviderInstanceId, +} from "@t3tools/contracts"; + +export function resolveSeatProvider( + providers: ReadonlyArray, + harness: string, + instanceIdOf: (provider: T) => ProviderInstanceId, + preferredInstanceId?: ProviderInstanceId, +): T | "no-provider" | "ambiguous-provider" { + const candidates = providers.filter( + (provider) => DELIVERY_HARNESS_BY_DRIVER[provider.driverKind] === harness, + ); + if (candidates.length === 0) return "no-provider"; + if (candidates.length === 1) return candidates[0]!; + // A harness names a driver, not an account. + return ( + candidates.find( + (candidate) => + instanceIdOf(candidate) === + (preferredInstanceId ?? defaultInstanceIdForDriver(candidate.driverKind)), + ) ?? "ambiguous-provider" + ); +} diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index a51f0808eec4a..7539521699d1f 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -79,6 +79,7 @@ import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts"; import * as McpSessionRegistry from "./McpSessionRegistry.ts"; import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts"; import * as OrchestratorHandlers from "./toolkits/orchestrator/handlers.ts"; +import * as SeatHandoffs from "../delivery/SeatHandoffs.ts"; import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts"; import * as PreviewHandlers from "./toolkits/preview/handlers.ts"; import { @@ -1348,7 +1349,11 @@ export const layerPreviewToolkit = Layer.mergeAll( export const layerOrchestratorToolkit = toolkitRegistration( OrchestratorToolkit, OrchestratorHandlers.layer, -).pipe(Layer.provide(OrchestratorMcpService.layer), Layer.provide(ThreadMetadataMcpService.layer)); +).pipe( + Layer.provide(SeatHandoffs.layer), + Layer.provide(OrchestratorMcpService.layer), + Layer.provide(ThreadMetadataMcpService.layer), +); export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer); const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer); diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index 5f54d585f317a..22204d280051e 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -34,7 +34,14 @@ const handlers = { const scope = yield* McpInvocationContext.McpInvocationContext; const service = yield* SeatHandoffs.SeatHandoffs; return yield* service.fileQaReceipt(scope, input); - }).pipe(Effect.provide(SeatHandoffs.layer)), + }), + ), + delivery_seat_handoff: McpToolAccess.actsAsCaller(({ seat }) => + Effect.gen(function* () { + const scope = yield* McpInvocationContext.McpInvocationContext; + const service = yield* SeatHandoffs.SeatHandoffs; + return yield* service.handQa(scope, { seat }); + }), ), orchestrator_capabilities: McpToolAccess.reads((input) => Effect.gen(function* () { diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index d2e86becce70c..7733b28dcaedb 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -6,6 +6,8 @@ import { DeliveryNativeBuildStepResult, DeliveryQaReceiptInput, DeliveryQaReceiptResult, + DeliverySeatHandoffInput, + DeliverySeatHandoffResult, OrchestratorMcpCapabilitiesInput, OrchestratorMcpCapabilitiesResult, OrchestrationV2StopWorkflowInput, @@ -58,6 +60,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts"; import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts"; import { DeliveryService } from "../../../delivery/DeliveryService.ts"; +import { SeatHandoffs } from "../../../delivery/SeatHandoffs.ts"; const dependencies = [ McpInvocationContext.McpInvocationContext, @@ -411,16 +414,30 @@ const QaReceiptTool = Tool.make("delivery_qa_receipt", { success: DeliveryQaReceiptResult, failure: OrchestratorMcpFailure, failureMode: "return", - dependencies: [...dependencies, DeliveryService], + dependencies: [...dependencies, SeatHandoffs], }) .annotate(Tool.Title, "File a QA receipt") .annotate(Tool.Destructive, true) .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWhileDeliveryOff); +const SeatHandoffTool = Tool.make("delivery_seat_handoff", { + description: + "From a board task's lead thread, hand QA to a gate seat in its own worktree. Call again after the child completion wake to settle the hand-off.", + parameters: DeliverySeatHandoffInput, + success: DeliverySeatHandoffResult, + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [...dependencies, SeatHandoffs], +}) + .annotate(Tool.Title, "Hand off QA to a team seat") + .annotate(Tool.Destructive, true) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWhileDeliveryOff); + export const OrchestratorToolkit = Toolkit.make( DeliveryReadTool, NativeBuildStepTool, QaReceiptTool, + SeatHandoffTool, OrchestratorCapabilitiesTool, DelegateTaskTool, TaskStatusTool, diff --git a/packages/contracts/src/delivery.ts b/packages/contracts/src/delivery.ts index eb09a18d4bc8d..4d615815f1e9a 100644 --- a/packages/contracts/src/delivery.ts +++ b/packages/contracts/src/delivery.ts @@ -212,6 +212,16 @@ export const DeliverySeatAttestation = Schema.Struct({ setAt: Schema.optional(Schema.NullOr(Schema.String)), }); +export const DeliverySeatHandoffInput = Schema.Struct({ + stage: Schema.Literal("qa"), + seat: Schema.optional(TrimmedNonEmptyString), +}); +export const DeliverySeatHandoffResult = Schema.Struct({ + handoff: DeliverySeatHandoff, + state: Schema.Literals(["working", "delivered", "fallen-back"]), + next: Schema.optional(Schema.String), +}); + export const DeliveryQaReceiptInput = Schema.Struct({ acceptanceIndex: DeliveryAcceptanceIndex.annotate({ description: "Zero-based checklist index." }), verdict: DeliveryQaVerdict, From 9d34e743eae303517ea8da35f2956fd747a8d650 Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Mon, 23 Nov 2026 17:27:00 +0000 Subject: [PATCH 03/10] feat(server): board tasks opt into the QA hold and the lead is told once when QA waits Co-Authored-By: Claude Opus 5.5 --- apps/server/src/delivery/BoardConversation.ts | 37 ++++++++++++++++++- .../src/delivery/BoardTaskThreads.test.ts | 20 +++++++++- apps/server/src/delivery/BoardTaskThreads.ts | 11 +++++- .../src/delivery/boardThreadEngine.testkit.ts | 3 ++ 4 files changed, 68 insertions(+), 3 deletions(-) diff --git a/apps/server/src/delivery/BoardConversation.ts b/apps/server/src/delivery/BoardConversation.ts index d89da3e459efe..e0126c8829337 100644 --- a/apps/server/src/delivery/BoardConversation.ts +++ b/apps/server/src/delivery/BoardConversation.ts @@ -42,6 +42,11 @@ interface Activity { } const STEER_MESSAGE_PREFIX = "message:board-steer:"; +const HANDOFF_NOTICE_PREFIX = "message:board-handoff:"; + +/** The one notice per run and stage that the lead's hand-off is awaited. */ +export const handoffNoticeMessageId = (task: BoardTask, run: string, stage: string) => + MessageId.make(`${HANDOFF_NOTICE_PREFIX}${task.board}:${task.id}:${run}:${stage}`); /** The message a queued steer is delivered as: one per steer, on every attempt. */ export const steerMessageId = (task: BoardTask, steerId: number) => @@ -97,7 +102,10 @@ function scanActivity( } if (message.role !== "user" || state.messages.has(message.id)) continue; state.messages.add(message.id); - const steer = message.id.startsWith(STEER_MESSAGE_PREFIX) || message.createdBy === "user"; + const steer = + message.id.startsWith(STEER_MESSAGE_PREFIX) || + message.id.startsWith(HANDOFF_NOTICE_PREFIX) || + message.createdBy === "user"; found.push({ seq: stored.sequence, at: DateTime.formatIso(event.occurredAt), @@ -135,6 +143,7 @@ export interface ConversationCard { /** Absent on an engine before slice 5, which takes no ingest. */ readonly conversation?: unknown; readonly steers?: { readonly pending: number } | null | undefined; + readonly handoffHold?: { readonly run: string; readonly stage: string } | null | undefined; } const Detail = Schema.Struct({ @@ -332,6 +341,30 @@ export const make = Effect.gen(function* () { } }); + /** Tells the lead once that the engine holds QA for its hand-off; the lead does the handing. */ + const noticeHandoff = Effect.fn("BoardConversation.noticeHandoff")(function* ( + task: BoardTask, + threadId: ThreadId, + run: string, + ) { + const messageId = handoffNoticeMessageId(task, run, "qa"); + const present = yield* projections.getMessagesById(threadId, [messageId]).pipe(Effect.result); + if (present._tag === "Failure" || present.success.has(messageId)) return; + yield* threads + .dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${boardTaskThreadMarker(task)}:handoff:${run}:qa`), + threadId, + messageId, + text: `Run ${run} reached QA and the engine is holding it for your hand-off. Call delivery_seat_handoff with stage "qa".`, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "system", + creationSource: "server", + }) + .pipe(Effect.ignore); + }); + const sync = Effect.fn("BoardConversation.sync")( function* (input: { readonly cards: ReadonlyArray; @@ -360,6 +393,8 @@ export const make = Effect.gen(function* () { yield* mirror(card, threadId, context, detail); if (steering && (card.steers?.pending ?? 0) > 0) yield* steer(task, threadId, context, detail); + if (steering && card.handoffHold?.stage === "qa") + yield* noticeHandoff(task, threadId, card.handoffHold.run); } }, (effect) => diff --git a/apps/server/src/delivery/BoardTaskThreads.test.ts b/apps/server/src/delivery/BoardTaskThreads.test.ts index 627c59b6e2c29..d4d36aaf25306 100644 --- a/apps/server/src/delivery/BoardTaskThreads.test.ts +++ b/apps/server/src/delivery/BoardTaskThreads.test.ts @@ -26,7 +26,7 @@ import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry. import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as BoardConversation from "./BoardConversation.ts"; -import { steerMessageId } from "./BoardConversation.ts"; +import { handoffNoticeMessageId, steerMessageId } from "./BoardConversation.ts"; import * as BoardTaskThreads from "./BoardTaskThreads.ts"; import { scratchEngine, @@ -347,6 +347,9 @@ it.effect("gives a started task one thread, led as the engine's team says, and l assert.deepInclude(put?.body, { expect: null }); // The claim names the conversation that holds the task, and the next pass is its heartbeat. assert.equal(engine.leaseOf("task-7")?.origin, `thread:${ENVIRONMENT}/${THREAD}`); + // The claim opts the task into the engine holding QA for the lead's hand-off. + const claim = engine.requests.find((request) => request.path.endsWith("/claim")); + assert.deepInclude(claim?.body, { handoffs: ["qa"] }); engine.advance(100_000); yield* threads.reconcile(); engine.advance(100_000); @@ -816,6 +819,21 @@ it.effect("mirrors each conversation event once, across a restart and a replaced }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-mirror-"))); }); +it.effect("tells the lead once per run that QA is held for its hand-off", () => { + const engine = board(); + engine.addTask({ id: "task-7", handoffHold: { run: "run-1", stage: "qa" } }); + const store = threadStore(); + return Effect.gen(function* () { + yield* (yield* service(store)).reconcile(); + yield* (yield* service(store)).reconcile(); + const notices = steerSends(store).filter( + (command) => command.messageId === handoffNoticeMessageId(TASK, "run-1", "qa"), + ); + assert.equal(notices.length, 1); + assert.match(String(notices[0]?.text), /delivery_seat_handoff/); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-handoff-notice-"))); +}); + it.effect("delivers a queued steer at the next turn boundary, once, and confirms it", () => { const engine = board(); engine.addTask({ id: "task-7" }); diff --git a/apps/server/src/delivery/BoardTaskThreads.ts b/apps/server/src/delivery/BoardTaskThreads.ts index 99d2f4d69d1b9..a5ea46ca4b484 100644 --- a/apps/server/src/delivery/BoardTaskThreads.ts +++ b/apps/server/src/delivery/BoardTaskThreads.ts @@ -59,6 +59,10 @@ const Card = Schema.Struct({ // Slice 5's mirror and steer counts; absent on an engine before it. conversation: Schema.optional(Schema.NullOr(Schema.Unknown)), steers: Schema.optional(Schema.NullOr(Schema.Struct({ pending: Schema.Number }))), + // A stage the engine holds for a hand-off that has none yet; the engine field is provisional. + handoffHold: Schema.optional( + Schema.NullOr(Schema.Struct({ run: Schema.String, stage: Schema.String })), + ), }); type Card = typeof Card.Type; @@ -299,7 +303,12 @@ export const make = Effect.gen(function* () { .boardThreadAct({ method: "POST", path: `${path}/claim`, - body: { origin: `thread:${environmentId}/${threadId}`, by: environmentId }, + // The opt-in asks the engine to hold its QA stage for the lead's hand-off. + body: { + origin: `thread:${environmentId}/${threadId}`, + by: environmentId, + handoffs: ["qa"], + }, }) .pipe(Effect.result); if (claimed._tag !== "Success") return; diff --git a/apps/server/src/delivery/boardThreadEngine.testkit.ts b/apps/server/src/delivery/boardThreadEngine.testkit.ts index db30ecb53c1d3..f2ce4daaa6303 100644 --- a/apps/server/src/delivery/boardThreadEngine.testkit.ts +++ b/apps/server/src/delivery/boardThreadEngine.testkit.ts @@ -26,6 +26,8 @@ export interface ScratchTask { state: string; submitted: boolean; held: boolean; + /** A stage the engine holds for the lead's hand-off, with none filed yet. */ + handoffHold?: { readonly run: string; readonly stage: string } | null; } interface Lease { @@ -116,6 +118,7 @@ export function scratchEngine( state: task.state, submitted: task.submitted ? "2026-11-22T09:00:00.000Z" : null, held: task.held, + ...(task.handoffHold === undefined ? {} : { handoffHold: task.handoffHold }), ...(options.servesLink === false ? {} : { boardThread: links.get(task.id) ?? null }), ...(conversing ? { conversation: mirrorOf(task.id), steers: steerCounts(task.id) } : {}), }); From 65e98de80ae912de5c60530c437fa49e809c6b56 Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Mon, 23 Nov 2026 17:34:02 +0000 Subject: [PATCH 04/10] test(server): record the MCP tool list budget for the two seat tools Co-Authored-By: Claude Opus 5.5 --- apps/server/src/provider/agentContextBudget.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 9bd3bb20144e8..6e8fb62ceec52 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 62636 + "mcpToolListJsonBytes": 63536 } From aa2bd385162cdfae509c66be2ae958d02f4138a5 Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Mon, 23 Nov 2026 17:35:32 +0000 Subject: [PATCH 05/10] fix(server): shorten the seat tools' model-facing text Co-Authored-By: Claude Opus 5.5 --- apps/server/src/delivery/SeatHandoffs.ts | 4 +++- apps/server/src/mcp/toolkits/orchestrator/tools.ts | 6 +++--- apps/server/src/provider/agentContextBudget.json | 2 +- packages/contracts/src/delivery.ts | 8 ++++---- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/apps/server/src/delivery/SeatHandoffs.ts b/apps/server/src/delivery/SeatHandoffs.ts index b4209cc4cb174..8a191a324b3bc 100644 --- a/apps/server/src/delivery/SeatHandoffs.ts +++ b/apps/server/src/delivery/SeatHandoffs.ts @@ -142,7 +142,9 @@ const engineFailure = (error: DeliveryError, operation: string) => { "The engine could not find the task or run. Ask the lead to check the current run.", }); case "invalid-field": - return invalidRequest(`The engine rejected a field while trying to ${operation}.`); + return invalidRequest( + `The engine rejected ${refusalOf(error)?.field ?? "a field"} while trying to ${operation}.`, + ); default: return new OrchestratorMcpFailure({ code: "orchestration_error", diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 7733b28dcaedb..b2fcd25237b56 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -396,7 +396,7 @@ const DeliveryReadTool = Tool.make("delivery_read", { const NativeBuildStepTool = Tool.make("delivery_native_build_step", { description: - "Step an opted-in build from its exact engine worktree. Retries reuse one native child; the server reads its result. Step after completion or engine cancellation. Read-only flows stay legacy. No caller-supplied results.", + "Step an opted-in build from its exact engine worktree. Retries reuse one native child; the server reads its result. Step after completion or engine cancellation.", parameters: DeliveryNativeBuildStepInput, success: DeliveryNativeBuildStepResult, failure: OrchestratorMcpFailure, @@ -409,7 +409,7 @@ const NativeBuildStepTool = Tool.make("delivery_native_build_step", { const QaReceiptTool = Tool.make("delivery_qa_receipt", { description: - "File a verdict and evidence refs for one acceptance item from the current run's attested QA seat thread. Use a zero-based index. The server resolves the task, seat, and checklist hash.", + "From a QA seat thread, file one acceptance item's verdict and evidence refs. The server fills in task, seat and hash.", parameters: DeliveryQaReceiptInput, success: DeliveryQaReceiptResult, failure: OrchestratorMcpFailure, @@ -422,7 +422,7 @@ const QaReceiptTool = Tool.make("delivery_qa_receipt", { const SeatHandoffTool = Tool.make("delivery_seat_handoff", { description: - "From a board task's lead thread, hand QA to a gate seat in its own worktree. Call again after the child completion wake to settle the hand-off.", + "From a board lead thread, hand QA to a gate seat. Call again after its completion wake to settle.", parameters: DeliverySeatHandoffInput, success: DeliverySeatHandoffResult, failure: OrchestratorMcpFailure, diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 6e8fb62ceec52..4433ac7e8b8d3 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 63536 + "mcpToolListJsonBytes": 63350 } diff --git a/packages/contracts/src/delivery.ts b/packages/contracts/src/delivery.ts index 4d615815f1e9a..d15af0b6eb10a 100644 --- a/packages/contracts/src/delivery.ts +++ b/packages/contracts/src/delivery.ts @@ -165,7 +165,6 @@ const DeliveryAcceptanceIndex = Schema.Number.check( Schema.isInt(), Schema.isGreaterThanOrEqualTo(0), ); -const DeliveryEvidenceRef = Schema.String.check(Schema.isPattern(/^[^\s\p{C}]{1,1024}$/u)); export const DeliveryQaReceipt = Schema.Struct({ id: Schema.optional(Schema.NullOr(Schema.Number)), @@ -214,7 +213,7 @@ export const DeliverySeatAttestation = Schema.Struct({ export const DeliverySeatHandoffInput = Schema.Struct({ stage: Schema.Literal("qa"), - seat: Schema.optional(TrimmedNonEmptyString), + seat: Schema.optional(Schema.String), }); export const DeliverySeatHandoffResult = Schema.Struct({ handoff: DeliverySeatHandoff, @@ -223,9 +222,10 @@ export const DeliverySeatHandoffResult = Schema.Struct({ }); export const DeliveryQaReceiptInput = Schema.Struct({ - acceptanceIndex: DeliveryAcceptanceIndex.annotate({ description: "Zero-based checklist index." }), + acceptanceIndex: DeliveryAcceptanceIndex.annotate({ description: "Zero-based." }), verdict: DeliveryQaVerdict, - evidence: Schema.Array(DeliveryEvidenceRef), + // The engine validates each ref and refuses a bad one by field. + evidence: Schema.Array(Schema.String), }); export const DeliveryQaReceiptResult = Schema.Struct({ qaReceipt: DeliveryQaReceipt, From 418a42079ab1b8229affbb8c7acc82aca8b3cdf4 Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Mon, 23 Nov 2026 17:40:32 +0000 Subject: [PATCH 06/10] fix(server): a lost engine answer never stops or re-files a QA seat Kimi QA findings: a hand-off the engine took is recovered instead of cancelled when its answer is lost, a settled hand-off is returned on retry unless the lead asks again, and the independence refusal names only seats that can be launched. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/delivery/SeatHandoffs.test.ts | 45 +++++++++++++++++-- apps/server/src/delivery/SeatHandoffs.ts | 43 ++++++++++++++---- packages/contracts/src/delivery.ts | 1 + 3 files changed, 78 insertions(+), 11 deletions(-) diff --git a/apps/server/src/delivery/SeatHandoffs.test.ts b/apps/server/src/delivery/SeatHandoffs.test.ts index ca409d96d7566..fd29eef41d2ad 100644 --- a/apps/server/src/delivery/SeatHandoffs.test.ts +++ b/apps/server/src/delivery/SeatHandoffs.test.ts @@ -59,7 +59,8 @@ function harness( readonly checklist?: string[]; readonly seatThread?: { readonly environmentId: string; readonly threadId: string } | null; readonly boardThread?: { readonly environmentId: string; readonly threadId: string }; - readonly handoffResponse?: "lost" | "conflict" | "independence"; + readonly handoffResponse?: "lost" | "committed-lost" | "conflict" | "independence"; + readonly settleResponse?: "committed-lost"; readonly receiptRefusal?: { readonly status: number; readonly code: string; @@ -78,6 +79,7 @@ function harness( const admissions = new Map(); const launches: Array<{ namespace: string; input: OrchestratorMcpDelegateTaskInput }> = []; const cancels: Array = []; + let settleLost = false; const statusReads: NodeId[] = []; const layer = SeatHandoffs.layer.pipe( Layer.provideMerge(DeliveryService.layer(deriveProviderInstanceConfigMap)), @@ -168,6 +170,10 @@ function harness( seatThread: { environmentId: ENVIRONMENT, threadId: attestedThread }, state: "handed", }; + if (handoffResponse === "committed-lost") { + handoffResponse = undefined; + return { status: 503, body: { error: "Engine unavailable." } }; + } if (handoffResponse === "conflict") { handoffResponse = undefined; return { @@ -186,6 +192,10 @@ function harness( state: delivered ? "delivered" : "fallen-back", reason: delivered ? null : (body as { reason: string }).reason, }; + if (options.settleResponse === "committed-lost" && !settleLost) { + settleLost = true; + return { status: 503, body: { error: "Engine unavailable." } }; + } return { status: 200, body: { run: RUN, handoff } }; } if (method === "POST" && path === RECEIPT_PATH) { @@ -454,13 +464,42 @@ it.effect( finish("interrupted"); assert.equal((yield* service.handQa(newSession, {})).handoff.reason, "seat-failed"); - const refiled = yield* service.handQa(newSession, {}); + // A settled hand-off is returned on retry; only `again` files QA anew. + assert.equal((yield* service.handQa(newSession, {})).handoff.reason, "seat-failed"); + assert.equal(admissions.size, 1); + const refiled = yield* service.handQa(newSession, { again: true }); assert.equal(refiled.handoff.seatThread?.threadId, "thread:qa:1"); assert.equal(admissions.size, 2); }).pipe(Effect.provide(layer)); }, ); +it.effect("keeps a seat whose hand-off the engine took when the answer is lost", () => { + const { layer, cancels, launches } = harness({ handoffResponse: "committed-lost" }); + return Effect.gen(function* () { + const service = yield* SeatHandoffs.SeatHandoffs; + const result = yield* service.handQa(scopeFor(PARENT), {}); + assert.equal(result.state, "working"); + assert.deepEqual(cancels, []); + assert.lengthOf(launches, 1); + }).pipe(Effect.provide(layer)); +}); + +it.effect("returns a settled hand-off whose answer was lost instead of filing QA again", () => { + const { layer, finish, launches } = harness({ settleResponse: "committed-lost" }); + return Effect.gen(function* () { + const service = yield* SeatHandoffs.SeatHandoffs; + const lead = scopeFor(PARENT); + yield* service.handQa(lead, {}); + finish("failed", []); + yield* Effect.flip(service.handQa(lead, {})); + const retried = yield* service.handQa(lead, {}); + assert.equal(retried.state, "fallen-back"); + assert.equal(retried.handoff.reason, "seat-failed"); + assert.lengthOf(launches, 1); + }).pipe(Effect.provide(layer)); +}); + it.effect("recovers the current record carried by an engine conflict", () => { const { layer, statusReads, launches } = harness({ handoffResponse: "conflict" }); return Effect.gen(function* () { @@ -483,7 +522,7 @@ it.effect("maps the engine's independence refusal and names the other gate seats assert.deepEqual(cancels, ["node:qa:0"]); assert.equal( failure.message, - "That QA seat shares the builder's model family; pick another seat (seat: unavailable, backup)", + "That QA seat shares the builder's model family; pick another seat (seat: backup)", ); assert.equal( (yield* service.handQa(scopeFor(PARENT), { seat: "backup" })).handoff.seat, diff --git a/apps/server/src/delivery/SeatHandoffs.ts b/apps/server/src/delivery/SeatHandoffs.ts index 8a191a324b3bc..9e8041a4f90bd 100644 --- a/apps/server/src/delivery/SeatHandoffs.ts +++ b/apps/server/src/delivery/SeatHandoffs.ts @@ -266,15 +266,17 @@ const make = Effect.gen(function* () { "Check out the candidate commit in your worktree and test it. Do not edit code. File receipts only after testing.", "File exactly one delivery_qa_receipt for each acceptance item with its zero-based index, a pass, fail or blocked verdict, and evidence refs. Then end your turn.", ].join("\n"); - for (const seat of gates) { - if (namedSeat !== undefined && seat.seat !== namedSeat) continue; + const launchable = gates.flatMap((seat) => { const { model, harness } = seat.currentModel ?? { model: seat.requestedModel, harness: seat.harness, }; - if (!model || !harness) continue; + if (!model || !harness) return []; const provider = resolveSeatProvider(providers, harness, (entry) => entry.providerInstanceId); - if (typeof provider === "string") continue; + return typeof provider === "string" ? [] : [{ seat, model, provider }]; + }); + for (const { seat, model, provider } of launchable) { + if (namedSeat !== undefined && seat.seat !== namedSeat) continue; const delegated = yield* orchestrator .delegateTask(nativeScope, { @@ -311,7 +313,9 @@ const make = Effect.gen(function* () { harness: launchedHarness, taskId: child.taskId, scope: nativeScope, - otherSeats: gates.filter((entry) => entry !== seat).map((entry) => entry.seat), + otherSeats: launchable + .filter((entry) => entry.seat !== seat) + .map((entry) => entry.seat.seat), }; } return yield* invalidRequest( @@ -365,6 +369,13 @@ const make = Effect.gen(function* () { body: { ...body, setBy: environmentId, key }, }); let current = currentQaHandoff(detail, run); + // A settled hand-off is returned as it stands, so a retry after a lost settle answer + // never files QA again; only an explicit `again` does. + if (current && current.state !== "handed" && !input.again) + return { + state: current.state === "delivered" ? "delivered" : "fallen-back", + handoff: current, + }; if (current?.state !== "handed") { if (current && current.id == null) return yield* invalidRequest("The engine's previous QA hand-off has no filing id."); @@ -392,11 +403,25 @@ const make = Effect.gen(function* () { return working(handoff); } const refusal = refusalOf(handed.failure); + if (refusal?.code === undefined) { + // The answer is unknown: the engine may have taken the hand-off. Read what it holds, + // and never stop a seat it may have. + const latest = yield* readTask(path).pipe(Effect.option); + const recovered = Option.isSome(latest) + ? currentQaHandoff(latest.value, run) + : undefined; + if (recovered?.state === "handed" && recovered.seatThread?.threadId === seat.threadId) + return working(recovered); + return yield* new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "The engine's answer was lost. Call delivery_seat_handoff again to recover.", + }); + } const held = - handed.failure.status === 409 && refusal?.code === "conflict" + handed.failure.status === 409 && refusal.code === "conflict" ? yield* readHandoff({ handoff: refusal.current }, run) : undefined; - // A seat the engine did not take must not go on to file receipts. + // A seat the engine refused must not go on to file receipts. if (held?.seatThread?.threadId !== seat.threadId) yield* orchestrator .cancelTask(seat.scope, { @@ -407,7 +432,9 @@ const make = Effect.gen(function* () { .pipe(Effect.ignore); if (handed.failure.status === 409 && refusal?.code === "independence") return yield* invalidRequest( - `That QA seat shares the builder's model family; pick another seat (seat: ${seat.otherSeats.join(", ") || "none"})`, + seat.otherSeats.length > 0 + ? `That QA seat shares the builder's model family; pick another seat (seat: ${seat.otherSeats.join(", ")})` + : "That QA seat shares the builder's model family, and no other QA gate seat can be launched.", ); if (held === undefined) return yield* engineFailure(handed.failure, "hand off QA"); current = held; diff --git a/packages/contracts/src/delivery.ts b/packages/contracts/src/delivery.ts index d15af0b6eb10a..3f38a648c3ccb 100644 --- a/packages/contracts/src/delivery.ts +++ b/packages/contracts/src/delivery.ts @@ -214,6 +214,7 @@ export const DeliverySeatAttestation = Schema.Struct({ export const DeliverySeatHandoffInput = Schema.Struct({ stage: Schema.Literal("qa"), seat: Schema.optional(Schema.String), + again: Schema.optional(Schema.Boolean).annotate({ description: "Hand off a settled QA again." }), }); export const DeliverySeatHandoffResult = Schema.Struct({ handoff: DeliverySeatHandoff, From 3b23dbf18b95299b8c4c30f4dec55ceafcb63aba Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Mon, 23 Nov 2026 17:45:49 +0000 Subject: [PATCH 07/10] test(server): record the measured MCP tool list budget Co-Authored-By: Claude Opus 5.5 --- apps/server/src/provider/agentContextBudget.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 4433ac7e8b8d3..6a6562f3ecb97 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 63350 + "mcpToolListJsonBytes": 63387 } From dd73971578ed148bc7f7036b7f81052bf07c6a21 Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Mon, 23 Nov 2026 17:50:09 +0000 Subject: [PATCH 08/10] fix(server): type the QA hand-off retry input and its settled state Co-Authored-By: Claude Opus 5.5 --- apps/server/src/delivery/SeatHandoffs.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/server/src/delivery/SeatHandoffs.ts b/apps/server/src/delivery/SeatHandoffs.ts index 9e8041a4f90bd..cffd76014bbf6 100644 --- a/apps/server/src/delivery/SeatHandoffs.ts +++ b/apps/server/src/delivery/SeatHandoffs.ts @@ -180,7 +180,7 @@ export class SeatHandoffs extends Context.Service< ) => Effect.Effect; readonly handQa: ( scope: McpInvocationScope, - input: Pick, + input: Pick, ) => Effect.Effect; } >()("t3/delivery/SeatHandoffs") {} @@ -373,7 +373,8 @@ const make = Effect.gen(function* () { // never files QA again; only an explicit `again` does. if (current && current.state !== "handed" && !input.again) return { - state: current.state === "delivered" ? "delivered" : "fallen-back", + state: + current.state === "delivered" ? ("delivered" as const) : ("fallen-back" as const), handoff: current, }; if (current?.state !== "handed") { From 48444c816ca55da37e2157af4e22beb08c25bc7b Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Mon, 23 Nov 2026 20:12:12 +0000 Subject: [PATCH 09/10] fix(server): evals provide the seat hand-off service, and the hand-off tool passes its whole input Co-Authored-By: Claude Opus 5.5 --- apps/server/src/delivery/SeatHandoffs.ts | 8 ++++++++ apps/server/src/mcp/toolkits/orchestrator/handlers.ts | 4 ++-- evals/mcp-tool-use/run.test.ts | 10 +++++++++- evals/mcp-tool-use/run.ts | 2 ++ 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/apps/server/src/delivery/SeatHandoffs.ts b/apps/server/src/delivery/SeatHandoffs.ts index cffd76014bbf6..9ec5af944154d 100644 --- a/apps/server/src/delivery/SeatHandoffs.ts +++ b/apps/server/src/delivery/SeatHandoffs.ts @@ -608,3 +608,11 @@ const make = Effect.gen(function* () { }); export const layer = Layer.effect(SeatHandoffs, make); + +const turnedOff = () => Effect.fail(invalidRequest("Delivery is turned off.")); + +/** Inert service, for suites that only need the tool surface to resolve. */ +export const layerTest = Layer.succeed( + SeatHandoffs, + SeatHandoffs.of({ attestSeat: turnedOff, fileQaReceipt: turnedOff, handQa: turnedOff }), +); diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index 22204d280051e..f4790409c89b8 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -36,11 +36,11 @@ const handlers = { return yield* service.fileQaReceipt(scope, input); }), ), - delivery_seat_handoff: McpToolAccess.actsAsCaller(({ seat }) => + delivery_seat_handoff: McpToolAccess.actsAsCaller((input) => Effect.gen(function* () { const scope = yield* McpInvocationContext.McpInvocationContext; const service = yield* SeatHandoffs.SeatHandoffs; - return yield* service.handQa(scope, { seat }); + return yield* service.handQa(scope, input); }), ), orchestrator_capabilities: McpToolAccess.reads((input) => diff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.ts index 1f25528af7a7c..c533dd0a8d92b 100644 --- a/evals/mcp-tool-use/run.test.ts +++ b/evals/mcp-tool-use/run.test.ts @@ -45,6 +45,7 @@ import { } from "./run.ts"; import { briefRoute, gradeDevice, shellInvocations } from "./device-grading.ts"; import * as DeliveryService from "../../apps/server/src/delivery/DeliveryService.ts"; +import * as SeatHandoffs from "../../apps/server/src/delivery/SeatHandoffs.ts"; import { taskPrompt } from "../../apps/server/src/mcp/delegatedTaskModes.ts"; it("grades Codex shell and subagent calls with the shared rules", () => { @@ -1853,7 +1854,14 @@ it.effect("seeds T3's error for a prior background wait whose IDs match nothing" } }).pipe( Effect.scoped, - Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, DeliveryService.layerTest)), + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + DeliveryService.layerTest, + SeatHandoffs.layerTest, + ), + ), ), ); diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index 26e0c8ce08a31..b988ac9adb43c 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -40,6 +40,7 @@ import * as McpSchema from "effect/ai/McpSchema"; import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; import * as DeliveryService from "../../apps/server/src/delivery/DeliveryService.ts"; +import * as SeatHandoffs from "../../apps/server/src/delivery/SeatHandoffs.ts"; import { teamDiscussionContext } from "../../apps/server/src/delivery/teamDiscussionContext.ts"; import { deliveryTurnContext } from "../../apps/server/src/delivery/deliveryDiscovery.ts"; import { taskPrompt } from "../../apps/server/src/mcp/delegatedTaskModes.ts"; @@ -3562,6 +3563,7 @@ if (import.meta.main) { PlatformNodeCrypto.layer, FetchHttpClient.layer, DeliveryService.layerTest, + SeatHandoffs.layerTest, ), ), NodeRuntime.runMain, From dd61a216284ce110957484ed26d4703649d23e01 Mon Sep 17 00:00:00 2001 From: Tevin2119 <48298711+Tevin2119@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:24:26 +0000 Subject: [PATCH 10/10] fix(server): follow the engine's hand-off hold contract Read QA holds from the engine card and notify the lead for each entry. Settle by filing ID and recover from the engine's receipt and stale-filing refusals. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/delivery/BoardConversation.ts | 23 ++--- .../src/delivery/BoardTaskThreads.test.ts | 33 +++++-- apps/server/src/delivery/BoardTaskThreads.ts | 12 ++- apps/server/src/delivery/SeatHandoffs.test.ts | 92 ++++++++++++++----- apps/server/src/delivery/SeatHandoffs.ts | 28 +++++- .../src/delivery/boardThreadEngine.testkit.ts | 11 ++- packages/contracts/src/delivery.ts | 1 + 7 files changed, 148 insertions(+), 52 deletions(-) diff --git a/apps/server/src/delivery/BoardConversation.ts b/apps/server/src/delivery/BoardConversation.ts index a47155e0efe96..a1f9d35edd78f 100644 --- a/apps/server/src/delivery/BoardConversation.ts +++ b/apps/server/src/delivery/BoardConversation.ts @@ -44,10 +44,6 @@ interface Activity { const STEER_MESSAGE_PREFIX = "message:board-steer:"; const HANDOFF_NOTICE_PREFIX = "message:board-handoff:"; -/** The one notice per run and stage that the lead's hand-off is awaited. */ -export const handoffNoticeMessageId = (task: BoardTask, run: string, stage: string) => - MessageId.make(`${HANDOFF_NOTICE_PREFIX}${task.board}:${task.id}:${run}:${stage}`); - /** The message a queued steer is delivered as: one per steer, on every attempt. */ export const steerMessageId = (task: BoardTask, steerId: number) => MessageId.make(`${STEER_MESSAGE_PREFIX}${task.board}:${task.id}:${steerId}`); @@ -143,7 +139,11 @@ export interface ConversationCard { /** Absent on an engine before slice 5, which takes no ingest. */ readonly conversation?: unknown; readonly steers?: { readonly pending: number } | null | undefined; - readonly handoffHold?: { readonly run: string; readonly stage: string } | null | undefined; + readonly run?: { readonly id: string } | null | undefined; + readonly hold?: + | { readonly stage: string; readonly deadline: string; readonly handoff: "handed" | null } + | null + | undefined; } const Detail = Schema.Struct({ @@ -353,22 +353,23 @@ export const make = Effect.gen(function* () { } }); - /** Tells the lead once that the engine holds QA for its hand-off; the lead does the handing. */ const noticeHandoff = Effect.fn("BoardConversation.noticeHandoff")(function* ( task: BoardTask, threadId: ThreadId, run: string, + deadline: string, ) { - const messageId = handoffNoticeMessageId(task, run, "qa"); + const entry = `${run}:qa:${deadline}`; + const messageId = MessageId.make(`${HANDOFF_NOTICE_PREFIX}${task.board}:${task.id}:${entry}`); const present = yield* projections.getMessagesById(threadId, [messageId]).pipe(Effect.result); if (present._tag === "Failure" || present.success.has(messageId)) return; yield* threads .dispatch({ type: "message.dispatch", - commandId: CommandId.make(`${boardTaskThreadMarker(task)}:handoff:${run}:qa`), + commandId: CommandId.make(`${boardTaskThreadMarker(task)}:handoff:${entry}`), threadId, messageId, - text: `Run ${run} reached QA and the engine is holding it for your hand-off. Call delivery_seat_handoff with stage "qa".`, + text: `Run ${run} reached QA and the engine is holding it for your hand-off until ${deadline}. Call delivery_seat_handoff with stage "qa".`, attachments: [], dispatchMode: { type: "queue_after_active" }, createdBy: "system", @@ -405,8 +406,8 @@ export const make = Effect.gen(function* () { yield* mirror(card, threadId, context, detail); if (steering && (card.steers?.pending ?? 0) > 0) yield* steer(task, threadId, context, detail); - if (steering && card.handoffHold?.stage === "qa") - yield* noticeHandoff(task, threadId, card.handoffHold.run); + if (steering && card.hold?.stage === "qa" && card.hold.handoff === null && card.run?.id) + yield* noticeHandoff(task, threadId, card.run.id, card.hold.deadline); } }, (effect) => diff --git a/apps/server/src/delivery/BoardTaskThreads.test.ts b/apps/server/src/delivery/BoardTaskThreads.test.ts index 39b4640287f45..5dbe673c2c99b 100644 --- a/apps/server/src/delivery/BoardTaskThreads.test.ts +++ b/apps/server/src/delivery/BoardTaskThreads.test.ts @@ -26,7 +26,7 @@ import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry. import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as BoardConversation from "./BoardConversation.ts"; -import { handoffNoticeMessageId, steerMessageId } from "./BoardConversation.ts"; +import { steerMessageId } from "./BoardConversation.ts"; import * as BoardTaskThreads from "./BoardTaskThreads.ts"; import { scratchEngine, @@ -819,18 +819,31 @@ it.effect("mirrors each conversation event once, across a restart and a replaced }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-mirror-"))); }); -it.effect("tells the lead once per run that QA is held for its hand-off", () => { +it.effect("tells the lead once per QA entry when its hand-off is awaited", () => { const engine = board(); - engine.addTask({ id: "task-7", handoffHold: { run: "run-1", stage: "qa" } }); + const task = engine.addTask({ id: "task-7", run: { id: "run-1" } }); const store = threadStore(); return Effect.gen(function* () { - yield* (yield* service(store)).reconcile(); - yield* (yield* service(store)).reconcile(); - const notices = steerSends(store).filter( - (command) => command.messageId === handoffNoticeMessageId(TASK, "run-1", "qa"), - ); - assert.equal(notices.length, 1); - assert.match(String(notices[0]?.text), /delivery_seat_handoff/); + const threads = yield* service(store); + const firstDeadline = "2026-11-22T10:30:00.000Z"; + const reworkDeadline = "2026-11-22T11:00:00.000Z"; + for (const { hold, noticeCount } of [ + { hold: null, noticeCount: 0 }, + { hold: { stage: "qa", deadline: firstDeadline, handoff: "handed" }, noticeCount: 0 }, + { hold: { stage: "qa", deadline: firstDeadline, handoff: null }, noticeCount: 1 }, + { hold: { stage: "qa", deadline: reworkDeadline, handoff: null }, noticeCount: 2 }, + ] as const) { + task.hold = hold; + yield* threads.reconcile(); + yield* threads.reconcile(); + assert.lengthOf(steerSends(store), noticeCount); + } + const [first, rework] = steerSends(store); + assert.include(first?.text, firstDeadline); + assert.include(rework?.text, reworkDeadline); + assert.match(String(first?.text), /delivery_seat_handoff/); + assert.notEqual(first?.messageId, rework?.messageId); + assert.notEqual(first?.commandId, rework?.commandId); }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-handoff-notice-"))); }); diff --git a/apps/server/src/delivery/BoardTaskThreads.ts b/apps/server/src/delivery/BoardTaskThreads.ts index a5ea46ca4b484..d86132ea2c24f 100644 --- a/apps/server/src/delivery/BoardTaskThreads.ts +++ b/apps/server/src/delivery/BoardTaskThreads.ts @@ -59,9 +59,15 @@ const Card = Schema.Struct({ // Slice 5's mirror and steer counts; absent on an engine before it. conversation: Schema.optional(Schema.NullOr(Schema.Unknown)), steers: Schema.optional(Schema.NullOr(Schema.Struct({ pending: Schema.Number }))), - // A stage the engine holds for a hand-off that has none yet; the engine field is provisional. - handoffHold: Schema.optional( - Schema.NullOr(Schema.Struct({ run: Schema.String, stage: Schema.String })), + run: Schema.optional(Schema.NullOr(Schema.Struct({ id: Schema.String }))), + hold: Schema.optional( + Schema.NullOr( + Schema.Struct({ + stage: Schema.String, + deadline: Schema.String, + handoff: Schema.NullOr(Schema.Literal("handed")), + }), + ), ), }); type Card = typeof Card.Type; diff --git a/apps/server/src/delivery/SeatHandoffs.test.ts b/apps/server/src/delivery/SeatHandoffs.test.ts index fd29eef41d2ad..1677342bae62f 100644 --- a/apps/server/src/delivery/SeatHandoffs.test.ts +++ b/apps/server/src/delivery/SeatHandoffs.test.ts @@ -60,7 +60,7 @@ function harness( readonly seatThread?: { readonly environmentId: string; readonly threadId: string } | null; readonly boardThread?: { readonly environmentId: string; readonly threadId: string }; readonly handoffResponse?: "lost" | "committed-lost" | "conflict" | "independence"; - readonly settleResponse?: "committed-lost"; + readonly settleResponse?: "committed-lost" | "no-receipt" | "stale-filing"; readonly receiptRefusal?: { readonly status: number; readonly code: string; @@ -162,8 +162,10 @@ function harness( handoffResponse = undefined; return { status: 409, body: { code: "independence", error: "Engine refusal." } }; } + const id = (handoff?.id ?? 0) + 1; handoff = { - id: (handoff?.id ?? 0) + 1, + id, + filing: id, run: RUN, stage: "qa", seat: (body as { seat: string }).seat, @@ -186,6 +188,16 @@ function harness( if (method === "POST" && handoff && path.startsWith(`${HANDOFF_PATH}/qa/`)) { engine.requests.push({ method, path, body }); const delivered = path.endsWith("/delivered"); + if (options.settleResponse === "no-receipt" && delivered) + return { status: 409, body: { code: "no-receipt", error: "Engine refusal." } }; + if (options.settleResponse === "stale-filing") { + const id = handoff.id! + 2; + handoff = { ...handoff, id, filing: id }; + return { + status: 409, + body: { code: "stale-filing", error: "Engine refusal.", current: handoff }, + }; + } handoff = { ...handoff, id: handoff.id! + 1, @@ -395,6 +407,7 @@ it.effect("hands QA to the first launchable gate seat and attests the model T3 l assert.equal(result.state, "working"); assert.match(result.next ?? "", /end your turn.*do not poll/); assert.equal(result.handoff.seat, "validation"); + assert.equal(result.handoff.filing, 1); assert.lengthOf(launches, 1); const launch = launches[0]!.input; assert.equal(launch.isolation, "worktree"); @@ -540,6 +553,12 @@ const currentReceipt = { const secondReceipt = { ...currentReceipt, acceptance: { index: 1 }, verdict: "blocked" } as const; it.effect.each([ { terminal: "completed", receipts: [currentReceipt, secondReceipt], reason: null }, + { + terminal: "completed", + receipts: [currentReceipt, secondReceipt], + reason: "no-receipts", + settleResponse: "no-receipt", + }, { terminal: "completed", receipts: [ @@ -551,28 +570,57 @@ it.effect.each([ }, { terminal: "failed", receipts: [currentReceipt], reason: "seat-failed" }, { terminal: "cancelled", receipts: [], reason: "seat-failed" }, -] as const)( - "settles a $terminal QA child with reason $reason", - ({ terminal, receipts, reason }) => { - const { layer, finish, requests } = harness({ - checklist: [ACCEPTANCE, "The report can be exported."], - }); - return Effect.gen(function* () { - const service = yield* SeatHandoffs.SeatHandoffs; - const lead = scopeFor(PARENT); - yield* service.handQa(lead, {}); - finish(terminal, receipts); - const result = yield* service.handQa(lead, {}); - assert.equal(result.state, reason ? "fallen-back" : "delivered"); - assert.equal(result.handoff.reason, reason); - assert.deepEqual(requests.at(-1), { +] as const)("settles a $terminal QA child with reason $reason", (scenario) => { + const { terminal, receipts, reason } = scenario; + const settleResponse = "settleResponse" in scenario ? scenario.settleResponse : undefined; + const { layer, finish, requests } = harness({ + checklist: [ACCEPTANCE, "The report can be exported."], + ...(settleResponse ? { settleResponse } : {}), + }); + return Effect.gen(function* () { + const service = yield* SeatHandoffs.SeatHandoffs; + const lead = scopeFor(PARENT); + yield* service.handQa(lead, {}); + finish(terminal, receipts); + const result = yield* service.handQa(lead, {}); + assert.equal(result.state, reason ? "fallen-back" : "delivered"); + assert.equal(result.handoff.reason, reason); + const settleRequests = requests.filter(({ path }) => path.startsWith(`${HANDOFF_PATH}/qa/`)); + assert.lengthOf(settleRequests, settleResponse ? 2 : 1); + if (settleResponse) + assert.deepEqual(settleRequests[0], { method: "POST", - path: `${HANDOFF_PATH}/qa/${reason ? "fallback" : "delivered"}`, - body: { ...(reason ? { reason } : {}), setBy: ENVIRONMENT, key: KEY }, + path: `${HANDOFF_PATH}/qa/delivered`, + body: { filing: 1, setBy: ENVIRONMENT, key: KEY }, }); - }).pipe(Effect.provide(layer)); - }, -); + assert.deepEqual(settleRequests.at(-1), { + method: "POST", + path: `${HANDOFF_PATH}/qa/${reason ? "fallback" : "delivered"}`, + body: { filing: 1, ...(reason ? { reason } : {}), setBy: ENVIRONMENT, key: KEY }, + }); + }).pipe(Effect.provide(layer)); +}); + +it.effect("reads the current QA hand-off after a stale filing refusal", () => { + const { layer, finish, requests } = harness({ settleResponse: "stale-filing" }); + return Effect.gen(function* () { + const service = yield* SeatHandoffs.SeatHandoffs; + const lead = scopeFor(PARENT); + yield* service.handQa(lead, {}); + finish("completed", [currentReceipt]); + const result = yield* service.handQa(lead, {}); + assert.equal(result.state, "working"); + assert.equal(result.handoff.filing, 3); + assert.deepEqual(requests.slice(-2), [ + { + method: "POST", + path: `${HANDOFF_PATH}/qa/delivered`, + body: { filing: 1, setBy: ENVIRONMENT, key: KEY }, + }, + { method: "GET", path: TASK_PATH, body: undefined }, + ]); + }).pipe(Effect.provide(layer)); +}); it.effect("refuses callers without an attested QA seat on the current run", () => { const { layer, requests } = harness(); diff --git a/apps/server/src/delivery/SeatHandoffs.ts b/apps/server/src/delivery/SeatHandoffs.ts index 9ec5af944154d..cd2396a452e27 100644 --- a/apps/server/src/delivery/SeatHandoffs.ts +++ b/apps/server/src/delivery/SeatHandoffs.ts @@ -362,7 +362,7 @@ const make = Effect.gen(function* () { if (!council?.run) return yield* invalidRequest("The board task has no current run."); const { run } = council; const endpoint = `/api/runs/${encodeURIComponent(run)}/handoffs`; - const post = (action: string, body: Record) => + const post = (action: string, body: Record) => delivery.boardThreadAct({ method: "POST", path: endpoint + action, @@ -490,15 +490,37 @@ const make = Effect.gen(function* () { : (latest.acceptance ?? []).every((_, index) => received.has(index)) ? undefined : "no-receipts"; - const settled = yield* post( + const filing = current.filing == null ? {} : { filing: current.filing }; + let settled = yield* post( reason ? "/qa/fallback" : "/qa/delivered", - reason ? { reason } : {}, + reason ? { ...filing, reason } : filing, ).pipe(Effect.result); + if ( + reason === undefined && + settled._tag === "Failure" && + settled.failure.status === 409 && + refusalOf(settled.failure)?.code === "no-receipt" + ) + settled = yield* post("/qa/fallback", { ...filing, reason: "no-receipts" }).pipe( + Effect.result, + ); let body: unknown; if (settled._tag === "Success") { body = settled.success.body; } else { const refusal = refusalOf(settled.failure); + if (settled.failure.status === 409 && refusal?.code === "stale-filing") { + const refreshed = yield* readTask(path); + if (!isLead(refreshed)) return yield* notLead(); + const latestHandoff = currentQaHandoff(refreshed, run); + if (refreshed.council?.run !== run || !latestHandoff?.state) + return yield* invalidRequest( + "The run or its QA hand-off changed. Read the current board task.", + ); + return latestHandoff.state === "handed" + ? working(latestHandoff) + : { state: latestHandoff.state, handoff: latestHandoff }; + } if (settled.failure.status !== 409 || refusal?.code !== "conflict") return yield* engineFailure(settled.failure, "settle the QA hand-off"); body = { handoff: refusal.current }; diff --git a/apps/server/src/delivery/boardThreadEngine.testkit.ts b/apps/server/src/delivery/boardThreadEngine.testkit.ts index 9b2cff7e1c3d9..85847a58ba1e8 100644 --- a/apps/server/src/delivery/boardThreadEngine.testkit.ts +++ b/apps/server/src/delivery/boardThreadEngine.testkit.ts @@ -26,8 +26,12 @@ export interface ScratchTask { state: string; submitted: boolean; held: boolean; - /** A stage the engine holds for the lead's hand-off, with none filed yet. */ - handoffHold?: { readonly run: string; readonly stage: string } | null; + run?: { readonly id: string } | null; + hold?: { + readonly stage: string; + readonly deadline: string; + readonly handoff: "handed" | null; + } | null; } interface Lease { @@ -125,7 +129,8 @@ export function scratchEngine( state: task.state, submitted: task.submitted ? "2026-11-22T09:00:00.000Z" : null, held: task.held, - ...(task.handoffHold === undefined ? {} : { handoffHold: task.handoffHold }), + run: task.run ?? null, + hold: task.hold ?? null, ...(options.servesLink === false ? {} : { boardThread: links.get(task.id) ?? null }), ...(conversing ? { conversation: mirrorOf(task.id), steers: steerCounts(task.id) } : {}), }); diff --git a/packages/contracts/src/delivery.ts b/packages/contracts/src/delivery.ts index 3f38a648c3ccb..4e227deab4523 100644 --- a/packages/contracts/src/delivery.ts +++ b/packages/contracts/src/delivery.ts @@ -191,6 +191,7 @@ export const DeliveryQaReceipt = Schema.Struct({ export const DeliverySeatHandoff = Schema.Struct({ id: Schema.optional(Schema.NullOr(Schema.Number)), + filing: Schema.optional(Schema.NullOr(Schema.Number)), run: Schema.optional(Schema.NullOr(Schema.String)), stage: Schema.optional(Schema.NullOr(Schema.Literals(["build", "review", "qa"]))), seat: Schema.optional(Schema.NullOr(Schema.String)),