Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion apps/server/src/delivery/BoardConversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ interface Activity {
}

const STEER_MESSAGE_PREFIX = "message:board-steer:";
const HANDOFF_NOTICE_PREFIX = "message:board-handoff:";

/** The message a queued steer is delivered as: one per steer, on every attempt. */
export const steerMessageId = (task: BoardTask, steerId: number) =>
Expand Down Expand Up @@ -97,7 +98,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),
Expand Down Expand Up @@ -135,6 +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 run?: { readonly id: string } | null | undefined;
readonly hold?:
| { readonly stage: string; readonly deadline: string; readonly handoff: "handed" | null }
| null
| undefined;
}

const Detail = Schema.Struct({
Expand Down Expand Up @@ -344,6 +353,31 @@ export const make = Effect.gen(function* () {
}
});

const noticeHandoff = Effect.fn("BoardConversation.noticeHandoff")(function* (
task: BoardTask,
threadId: ThreadId,
run: string,
deadline: string,
) {
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:${entry}`),
threadId,
messageId,
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",
creationSource: "server",
})
.pipe(Effect.ignore);
});

const sync = Effect.fn("BoardConversation.sync")(
function* (input: {
readonly cards: ReadonlyArray<ConversationCard>;
Expand Down Expand Up @@ -372,6 +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.hold?.stage === "qa" && card.hold.handoff === null && card.run?.id)
yield* noticeHandoff(task, threadId, card.run.id, card.hold.deadline);
}
},
(effect) =>
Expand Down
31 changes: 31 additions & 0 deletions apps/server/src/delivery/BoardTaskThreads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -816,6 +819,34 @@ 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 QA entry when its hand-off is awaited", () => {
const engine = board();
const task = engine.addTask({ id: "task-7", run: { id: "run-1" } });
const store = threadStore();
return Effect.gen(function* () {
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-")));
});

const ownSeqs = (engine: ScratchEngine) =>
engine
.activityOf("task-7")
Expand Down
36 changes: 22 additions & 14 deletions apps/server/src/delivery/BoardTaskThreads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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({
Expand All @@ -59,6 +59,16 @@ 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 }))),
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;

Expand Down Expand Up @@ -252,19 +262,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 }));
});

Expand Down Expand Up @@ -306,7 +309,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;
Expand Down
31 changes: 16 additions & 15 deletions apps/server/src/delivery/DeliveryService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,10 @@ 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|handoffs(?:\/qa\/(?:delivered|fallback))?))$/;
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}`);

Expand Down Expand Up @@ -174,8 +176,7 @@ export class DeliveryService extends Context.Service<
input: DeliveryActInput,
) => Effect.Effect<DeliveryResponse, DeliveryError>;
/**
* 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";
Expand Down Expand Up @@ -268,6 +269,7 @@ const make = Effect.fn("DeliveryService.make")(function* (
const lineups = new Map<string, DeliveryOrchestrationConfig | null>();
const rememberedLineups = new Map<string, DeliveryRememberedLineup>();
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
Expand Down Expand Up @@ -1574,8 +1576,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"
Expand Down Expand Up @@ -1604,16 +1605,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,
Expand Down
17 changes: 7 additions & 10 deletions apps/server/src/delivery/NativeBuildExecution.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
DELIVERY_HARNESS_BY_DRIVER,
DeliveryNativeBuildStepInput,
DeliveryNativeBuildStepResult,
NodeId,
Expand All @@ -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),
Expand Down Expand Up @@ -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.",
);
Expand Down
Loading
Loading