Record created threads and subagent progress

- Add parent-thread records for spawned child threads
- Persist Claude subagent progress as reasoning items
- Tighten projection verification around readable thread projections
This commit is contained in:
Julius Marminge authored and maria-rcks committed 2026-08-03 11:45:05 -04:00
1 parent 82ffe9862c
commit efdf72ec8c
26 files changed
+1081 -266

No files matched your search

+38 -1
View File
@@ -445,8 +445,10 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null {
return item.summary ?? `${item.strategy} handoff to ${item.toProviderInstanceId}`;
case "fork":
return `Forked to thread ${item.targetThreadId}.`;
case "thread_created":
return `Created thread ${item.targetThreadId} with ${item.targetProviderInstanceId} (${item.targetModel}).`;
case "subagent":
return item.result ?? item.prompt;
return item.result ?? item.progress ?? item.prompt;
case "dynamic_tool":
return jsonText({ toolName: item.toolName, input: item.input, output: item.output });
}
@@ -863,6 +865,18 @@ const make = Effect.gen(function* () {
Effect.gen(function* () {
yield* requireCapability(scope);
const parent = yield* loadProjection(scope.threadId);
const parentRun = latestActiveRun(parent);
if (
parentRun === undefined ||
parentRun.rootNodeId === null ||
parentRun.providerInstanceId !== scope.providerInstanceId
) {
return yield* failure(
"parent_not_active",
"Thread creation requires an active run owned by this MCP provider session.",
);
}
const parentNodeId = parentRun.rootNodeId;
const providers = yield* loadProviders;
const key = yield* requestKey(input.clientRequestId);
const created = yield* Effect.forEach(
@@ -955,6 +969,29 @@ const make = Effect.gen(function* () {
}
const projection = yield* loadProjection(threadId);
const run = projection.runs.at(-1);
yield* threadManagement
.dispatch({
type: "thread.created.record",
commandId: stableCommandId({
scope,
requestKey: key,
operation: "record-created-thread",
index,
}),
parentThreadId: scope.threadId,
parentRunId: parentRun.id,
parentNodeId,
targetThreadId: threadId,
targetRunId: run?.id ?? null,
})
.pipe(
Effect.mapError((error) =>
failure(
"orchestration_error",
`Unable to record thread ${index + 1} in the parent timeline: ${errorMessage(error)}`,
),
),
);
return {
threadId,
runId: run?.id ?? null,
@@ -730,6 +730,35 @@ describe("orchestrator MCP toolkit", () => {
.filter((message) => message.role === "user")
.map((message) => message.text),
).toEqual([createdThreadPrompt]);
const createdThreadItems = (yield* orchestrator.getThreadProjection(
parentThreadId,
)).visibleTurnItems
.map((row) => row.item)
.filter((item) => item.type === "thread_created");
expect(
createdThreadItems.map((item) => ({
targetThreadId: item.targetThreadId,
targetRunId: item.targetRunId,
title: item.title,
providerInstanceId: item.targetProviderInstanceId,
model: item.targetModel,
})),
).toEqual([
{
targetThreadId: emptyThread.threadId,
targetRunId: null,
title: emptyThread.title,
providerInstanceId: codexInstanceId,
model: codexModel,
},
{
targetThreadId: promptedThread.threadId,
targetRunId: promptedThread.runId,
title: promptedThread.title,
providerInstanceId: claudeInstanceId,
model: claudeModel,
},
]);
const repeatedCreateCall = yield* invoke("create_threads", createInput);
const repeatedCreated = yield* decodeCreateThreadsResult(
@@ -738,6 +767,15 @@ describe("orchestrator MCP toolkit", () => {
expect(repeatedCreated.threads.map((thread) => thread.threadId)).toEqual(
created.threads.map((thread) => thread.threadId),
);
expect(
(yield* orchestrator.getThreadProjection(parentThreadId)).visibleTurnItems.filter(
(row) => {
if (row.item.type !== "thread_created") return false;
const targetThreadId = row.item.targetThreadId;
return created.threads.some((thread) => thread.threadId === targetThreadId);
},
),
).toHaveLength(2);
const promptedReadCall = yield* invoke("t3_thread_read", {
threadId: promptedThread.threadId,
@@ -814,6 +852,22 @@ describe("orchestrator MCP toolkit", () => {
const activeThread = yield* decodeCreatedThread(
activeThreadCall.structuredContent,
).pipe(Effect.orDie);
const activeThreadItem = (yield* orchestrator.getThreadProjection(
parentThreadId,
)).visibleTurnItems
.map((row) => row.item)
.find(
(item) =>
item.type === "thread_created" && item.targetThreadId === activeThread.threadId,
);
expect(activeThreadItem).toMatchObject({
type: "thread_created",
title: "Managed active thread",
targetThreadId: activeThread.threadId,
targetRunId: activeThread.runId,
targetProviderInstanceId: codexInstanceId,
targetModel: codexModel,
});
const activeProjection = yield* waitForProjection(
orchestrator,
activeThread.threadId,
@@ -1769,6 +1769,8 @@ interface ActiveClaudeSubagent {
readonly turnItemId: OrchestrationV2TurnItem["id"];
readonly turnItemOrdinal: number;
nextChildItemOrdinal: number;
progressItemOrdinal: number | null;
progressStartedAt: DateTime.Utc | null;
resultItemOrdinal: number | null;
}
@@ -2038,6 +2040,7 @@ export function makeClaudeAdapterV2(
readonly toolUseId?: string;
readonly prompt?: string;
readonly title?: string;
readonly progress?: string;
readonly result?: string;
readonly status: Extract<
OrchestrationV2ExecutionNode["status"],
@@ -2052,6 +2055,8 @@ export function makeClaudeAdapterV2(
if (existingSubagent === undefined && input.status !== "running") {
return;
}
const lifecycleChanged =
existingSubagent === undefined || existingSubagent.task.status !== input.status;
const now = yield* DateTime.now;
const nativeItemId = `task:${input.taskId}`;
@@ -2105,6 +2110,7 @@ export function makeClaudeAdapterV2(
status: input.status,
...(input.prompt === undefined ? {} : { prompt: input.prompt }),
...(input.title === undefined ? {} : { title: input.title }),
...(input.progress === undefined ? {} : { progress: input.progress }),
...(input.result === undefined ? {} : { result: input.result }),
completedAt: input.status === "running" ? null : now,
updatedAt: now,
@@ -2121,6 +2127,8 @@ export function makeClaudeAdapterV2(
}),
turnItemOrdinal,
nextChildItemOrdinal: existingSubagent?.nextChildItemOrdinal ?? 100,
progressItemOrdinal: existingSubagent?.progressItemOrdinal ?? null,
progressStartedAt: existingSubagent?.progressStartedAt ?? null,
resultItemOrdinal: existingSubagent?.resultItemOrdinal ?? null,
} satisfies ActiveClaudeSubagent;
input.context.subagentsByTaskId.set(input.taskId, subagent);
@@ -2153,52 +2161,54 @@ export function makeClaudeAdapterV2(
});
}
yield* emitProviderEvent({
type: "node.updated",
driver: CLAUDE_PROVIDER,
node: {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
parentNodeId: input.context.input.rootNodeId,
rootNodeId: input.context.input.rootNodeId,
kind: "subagent",
status: input.status,
countsForRun: false,
providerThreadId: input.context.input.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: {
driver: CLAUDE_PROVIDER,
nativeId: input.taskId,
strength: "strong",
if (lifecycleChanged) {
yield* emitProviderEvent({
type: "node.updated",
driver: CLAUDE_PROVIDER,
node: {
id: nodeId,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
parentNodeId: input.context.input.rootNodeId,
rootNodeId: input.context.input.rootNodeId,
kind: "subagent",
status: input.status,
countsForRun: false,
providerThreadId: input.context.input.providerThread.id,
providerTurnId: input.context.providerTurnId,
nativeItemRef: {
driver: CLAUDE_PROVIDER,
nativeId: input.taskId,
strength: "strong",
},
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: task.startedAt,
completedAt: input.status === "running" ? null : now,
},
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: task.startedAt,
completedAt: input.status === "running" ? null : now,
},
});
yield* emitProviderEvent({
type: "node.updated",
driver: CLAUDE_PROVIDER,
node: {
id: childRootNodeId,
threadId: childThreadId,
runId: null,
parentNodeId: null,
rootNodeId: childRootNodeId,
kind: "root_turn",
status: input.status,
countsForRun: false,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: task.nativeTaskRef,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: task.startedAt,
completedAt: input.status === "running" ? null : now,
},
});
});
yield* emitProviderEvent({
type: "node.updated",
driver: CLAUDE_PROVIDER,
node: {
id: childRootNodeId,
threadId: childThreadId,
runId: null,
parentNodeId: null,
rootNodeId: childRootNodeId,
kind: "root_turn",
status: input.status,
countsForRun: false,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: task.nativeTaskRef,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: task.startedAt,
completedAt: input.status === "running" ? null : now,
},
});
}
if (existingSubagent === undefined) {
const promptNativeItemId = `${nativeItemId}:prompt`;
const promptArtifacts = makeSubagentConversationArtifacts({
@@ -2265,10 +2275,55 @@ export function makeClaudeAdapterV2(
providerInstanceId: task.providerInstanceId,
childThreadId: task.childThreadId,
prompt: task.prompt,
...(task.progress === undefined ? {} : { progress: task.progress }),
result: task.result,
},
});
const progress = task.progress?.trim();
if (
progress !== undefined &&
progress.length > 0 &&
(input.progress !== undefined || (lifecycleChanged && input.status !== "running"))
) {
const progressNativeItemId = `${nativeItemId}:progress`;
const progressItemOrdinal =
subagent.progressItemOrdinal ?? ++subagent.nextChildItemOrdinal;
const progressStartedAt = subagent.progressStartedAt ?? now;
subagent.progressItemOrdinal = progressItemOrdinal;
subagent.progressStartedAt = progressStartedAt;
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CLAUDE_PROVIDER,
turnItem: {
id: idAllocator.derive.turnItemFromProviderItem({
driver: CLAUDE_PROVIDER,
nativeItemId: progressNativeItemId,
}),
threadId: childThreadId,
runId: null,
nodeId: childRootNodeId,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: {
driver: CLAUDE_PROVIDER,
nativeId: progressNativeItemId,
strength: "strong",
},
parentItemId: null,
ordinal: progressItemOrdinal,
status: input.status,
title: "Subagent progress",
startedAt: progressStartedAt,
completedAt: input.status === "running" ? null : now,
updatedAt: now,
type: "reasoning",
text: progress,
streaming: input.status === "running",
},
});
}
if (
input.result !== undefined &&
input.result.trim().length > 0 &&
@@ -2670,6 +2725,19 @@ export function makeClaudeAdapterV2(
});
}
if (message.type === "system" && message.subtype === "task_progress") {
const progress = message.description.trim();
if (progress.length > 0) {
yield* updateClaudeSubagentNode({
context,
taskId: message.task_id,
...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }),
progress,
status: "running",
});
}
}
if (message.type === "system" && message.subtype === "task_notification") {
yield* updateClaudeSubagentNode({
context,
@@ -4,6 +4,7 @@ import {
CheckpointRef,
CheckpointScopeId,
CommandId,
ContextTransferId,
EventId,
MessageId,
type ModelSelection,
@@ -258,6 +259,177 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
}),
);
it.effect("verifies and rebuilds projections with cross-thread subagent relations", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const projectionStore = yield* ProjectionStoreV2;
const maintenance = yield* ProjectionMaintenanceV2;
const now = yield* DateTime.now;
const parentThreadId = ThreadId.make("thread:foundation-cross-thread:parent");
const childThreadId = ThreadId.make("thread:foundation-cross-thread:child");
const childProviderThreadId = ProviderThreadId.make(
"provider-thread:foundation-cross-thread:child",
);
const subagentId = NodeId.make("subagent:foundation-cross-thread");
const spawnTransferId = ContextTransferId.make("transfer:foundation-cross-thread:spawn");
const resultTransferId = ContextTransferId.make("transfer:foundation-cross-thread:result");
const parentThread = makeThread(parentThreadId, now);
const childThread = {
...makeThread(childThreadId, now),
createdBy: "agent" as const,
creationSource: "provider" as const,
lineage: {
parentThreadId,
relationshipToParent: "subagent" as const,
rootThreadId: parentThreadId,
},
};
yield* eventSink.write({
events: [
threadCreatedEvent({
id: "event:foundation-cross-thread:parent",
thread: parentThread,
now,
}),
threadCreatedEvent({
id: "event:foundation-cross-thread:child",
thread: childThread,
now,
}),
{
id: EventId.make("event:foundation-cross-thread:subagent"),
type: "subagent.updated",
threadId: parentThreadId,
nodeId: subagentId,
providerInstanceId,
occurredAt: now,
payload: {
id: subagentId,
threadId: parentThreadId,
runId: null,
parentNodeId: NodeId.make("node:foundation-cross-thread:parent"),
origin: "app_owned",
createdBy: "agent",
driver: providerDriver,
providerInstanceId,
providerThreadId: childProviderThreadId,
childThreadId,
nativeTaskRef: null,
prompt: "Inspect the child flow",
title: "Cross-thread child",
model: modelSelection.model,
status: "completed",
result: "done",
startedAt: now,
completedAt: now,
updatedAt: now,
},
},
{
id: EventId.make("event:foundation-cross-thread:spawn-transfer"),
type: "context-transfer.created",
threadId: childThreadId,
providerInstanceId,
occurredAt: now,
payload: {
id: spawnTransferId,
type: "subagent_spawn",
sourceThreadId: parentThreadId,
targetThreadId: childThreadId,
sourcePoint: { threadId: parentThreadId },
basePoint: null,
sourceProviderInstanceId: providerInstanceId,
targetProviderInstanceId: providerInstanceId,
targetRunId: null,
status: "consumed",
resolution: null,
createdBy: "agent",
error: null,
createdAt: now,
updatedAt: now,
consumedAt: now,
},
},
{
id: EventId.make("event:foundation-cross-thread:provider-thread"),
type: "provider-thread.updated",
threadId: parentThreadId,
driver: providerDriver,
providerInstanceId,
occurredAt: now,
payload: {
id: childProviderThreadId,
driver: providerDriver,
providerInstanceId,
providerSessionId: null,
appThreadId: childThreadId,
ownerNodeId: null,
nativeThreadRef: null,
nativeConversationHeadRef: null,
status: "idle",
firstRunOrdinal: 1,
lastRunOrdinal: 1,
handoffIds: [],
forkedFrom: null,
createdAt: now,
updatedAt: now,
},
},
{
id: EventId.make("event:foundation-cross-thread:result-transfer"),
type: "context-transfer.created",
threadId: parentThreadId,
providerInstanceId,
occurredAt: now,
payload: {
id: resultTransferId,
type: "subagent_result",
sourceThreadId: childThreadId,
targetThreadId: parentThreadId,
sourcePoint: { threadId: childThreadId },
basePoint: null,
sourceProviderInstanceId: providerInstanceId,
targetProviderInstanceId: providerInstanceId,
targetRunId: null,
status: "consumed",
resolution: null,
createdBy: "system",
error: null,
createdAt: now,
updatedAt: now,
consumedAt: now,
},
},
],
});
const assertCrossThreadProjection = Effect.gen(function* () {
const parent = yield* projectionStore.getThreadProjection(parentThreadId);
const child = yield* projectionStore.getThreadProjection(childThreadId);
const expectedTransferIds = [spawnTransferId, resultTransferId].toSorted();
assert.deepEqual(
parent.contextTransfers.map((transfer) => transfer.id).toSorted(),
expectedTransferIds,
);
assert.deepEqual(
child.contextTransfers.map((transfer) => transfer.id).toSorted(),
expectedTransferIds,
);
assert.deepEqual(
parent.providerThreads.map((providerThread) => providerThread.id),
[childProviderThreadId],
);
assert.equal(child.thread.activeProviderThreadId, childProviderThreadId);
});
yield* assertCrossThreadProjection;
assert.isTrue((yield* maintenance.verify).valid);
assert.isTrue((yield* maintenance.rebuild).valid);
yield* assertCrossThreadProjection;
}),
);
it.effect(
"rolls back events, projections, receipts, and effects after a projection failure",
() =>
@@ -1138,12 +1310,13 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
assert.equal((yield* maintenance.verify).valid, true);
yield* sql`
DELETE FROM orchestration_v2_projection_turn_items
UPDATE orchestration_v2_projection_turn_items
SET payload_json = '{}'
WHERE turn_item_id = ${items[75]!.id}
`;
const broken = yield* maintenance.verify;
assert.isFalse(broken.valid);
assert.deepEqual(broken.differingThreadIds, [threadId]);
assert.deepEqual(broken.unreadableThreadIds, [threadId]);
const rebuilt = yield* maintenance.rebuild;
assert.isTrue(rebuilt.valid);
@@ -134,6 +134,7 @@ export interface IdAllocatorV2DeriveShape {
readonly delegatedTaskThread: (input: { readonly commandId: CommandId }) => ThreadId;
readonly delegatedTaskMessage: (input: { readonly commandId: CommandId }) => MessageId;
readonly delegatedTaskTurnItem: (input: { readonly commandId: CommandId }) => TurnItemId;
readonly createdThreadTurnItem: (input: { readonly commandId: CommandId }) => TurnItemId;
readonly threadFromProviderThread: (input: {
readonly driver: ProviderDriverKind;
readonly nativeThreadId: string;
@@ -357,6 +358,8 @@ export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed(
MessageId.make(joinId("message", "delegated-task", input.commandId)),
delegatedTaskTurnItem: (input) =>
TurnItemId.make(joinId("turn-item", "delegated-task", input.commandId)),
createdThreadTurnItem: (input) =>
TurnItemId.make(joinId("turn-item", "created-thread", input.commandId)),
threadFromProviderThread: (input) =>
ThreadId.make(
joinId("thread", "provider", input.driver, "native-thread", input.nativeThreadId),
@@ -193,6 +193,7 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId {
case "provider.switch":
return command.threadId;
case "delegated_task.request":
case "thread.created.record":
return command.parentThreadId;
case "thread.fork":
case "thread.merge_back":
@@ -3691,6 +3692,108 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
);
const dispatchCreatedThreadRecord = Effect.fn("orchestrationV2.dispatch.createdThreadRecord")(
function* (
command: Extract<OrchestrationV2Command, { readonly type: "thread.created.record" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
) {
const parentProjection = yield* projectionStore
.getThreadProjection(command.parentThreadId)
.pipe(
Effect.mapError(
(cause) =>
new OrchestratorProjectionError({
threadId: command.parentThreadId,
cause,
}),
),
);
const targetProjection = yield* projectionStore
.getThreadProjection(command.targetThreadId)
.pipe(
Effect.mapError(
(cause) =>
new OrchestratorProjectionError({
threadId: command.targetThreadId,
cause,
}),
),
);
const parentRun = parentProjection.runs.find(
(candidate) => candidate.id === command.parentRunId,
);
const parentNode = parentProjection.nodes.find(
(candidate) => candidate.id === command.parentNodeId,
);
if (
parentRun === undefined ||
parentNode === undefined ||
parentNode.runId !== command.parentRunId ||
parentRun.rootNodeId !== command.parentNodeId
) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Parent node ${command.parentNodeId} is not the root of run ${command.parentRunId}.`,
});
}
if (parentProjection.thread.projectId !== targetProjection.thread.projectId) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Target thread ${command.targetThreadId} belongs to another project.`,
});
}
if (
command.targetRunId !== null &&
!targetProjection.runs.some((candidate) => candidate.id === command.targetRunId)
) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Target run ${command.targetRunId} does not belong to thread ${command.targetThreadId}.`,
});
}
const now = yield* DateTime.now;
const parentProviderTurn = providerTurnForRun(parentProjection, parentRun);
const turnItem: OrchestrationV2TurnItem = {
id: idAllocator.derive.createdThreadTurnItem({ commandId: command.commandId }),
threadId: command.parentThreadId,
runId: command.parentRunId,
nodeId: command.parentNodeId,
providerThreadId: parentRun.providerThreadId,
providerTurnId: parentProviderTurn?.id ?? null,
nativeItemRef: null,
parentItemId: null,
ordinal: nextTurnItemOrdinal(parentProjection),
status: "completed",
title: targetProjection.thread.title,
startedAt: now,
completedAt: now,
updatedAt: now,
type: "thread_created",
targetThreadId: command.targetThreadId,
targetRunId: command.targetRunId,
targetProviderInstanceId: targetProjection.thread.modelSelection.instanceId,
targetModel: targetProjection.thread.modelSelection.model,
};
yield* emit(
events,
command,
)({
type: "turn-item.updated",
threadId: command.parentThreadId,
runId: command.parentRunId,
nodeId: command.parentNodeId,
providerInstanceId: parentRun.providerInstanceId,
occurredAt: now,
payload: turnItem,
});
},
);
const dispatchRuntimeRequestRespond = (
command: Extract<OrchestrationV2Command, { readonly type: "runtime-request.respond" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
@@ -4920,6 +5023,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
case "delegated_task.request":
yield* dispatchDelegatedTaskRequest(command, events, effects);
break;
case "thread.created.record":
yield* dispatchCreatedThreadRecord(command, events);
break;
default:
return yield* dispatchUnsupported(command);
}
@@ -1,8 +1,4 @@
import {
type OrchestrationV2StoredEvent,
type OrchestrationV2ThreadProjection,
ThreadId,
} from "@t3tools/contracts";
import { type OrchestrationV2StoredEvent, ThreadId } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -13,8 +9,6 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
import { EventStoreV2 } from "./EventStore.ts";
import {
applyToProjectionReplayState,
makeProjectionReplayState,
ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
ProjectionStoreV2,
} from "./ProjectionStore.ts";
@@ -24,7 +18,7 @@ export interface ProjectionVerificationV2 {
readonly schemaVersion: number;
readonly expectedSequence: number;
readonly projectionSequence: number;
readonly differingThreadIds: ReadonlyArray<ThreadId>;
readonly unreadableThreadIds: ReadonlyArray<ThreadId>;
readonly missingThreadIds: ReadonlyArray<ThreadId>;
readonly unexpectedThreadIds: ReadonlyArray<ThreadId>;
}
@@ -52,45 +46,6 @@ type ProjectionMetadataRow = {
readonly last_sequence: number;
};
function sortedProjection(projection: OrchestrationV2ThreadProjection): unknown {
const sortById = <A extends { readonly id: string }>(values: ReadonlyArray<A>) =>
values.toSorted((left, right) => left.id.localeCompare(right.id));
return {
...projection,
runs: sortById(projection.runs),
attempts: sortById(projection.attempts),
nodes: sortById(projection.nodes),
subagents: sortById(projection.subagents),
providerSessions: sortById(projection.providerSessions),
providerThreads: sortById(projection.providerThreads),
providerTurns: sortById(projection.providerTurns),
runtimeRequests: sortById(projection.runtimeRequests),
messages: sortById(projection.messages),
plans: sortById(projection.plans),
turnItems: sortById(projection.turnItems),
checkpointScopes: sortById(projection.checkpointScopes),
checkpoints: sortById(projection.checkpoints),
contextHandoffs: sortById(projection.contextHandoffs),
contextTransfers: sortById(projection.contextTransfers),
// This is a derived lineage view. Its source entities are compared above.
visibleTurnItems: [],
};
}
function stableStringify(value: unknown): string {
if (Array.isArray(value)) {
return `[${value.map(stableStringify).join(",")}]`;
}
if (typeof value === "object" && value !== null) {
const record = value as Record<string, unknown>;
return `{${Object.keys(record)
.toSorted()
.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
.join(",")}}`;
}
return JSON.stringify(value);
}
export const layer: Layer.Layer<
ProjectionMaintenanceV2,
never,
@@ -120,50 +75,49 @@ export const layer: Layer.Layer<
return events;
});
const expectedProjections = (events: ReadonlyArray<OrchestrationV2StoredEvent>) => {
const state = makeProjectionReplayState();
for (const stored of events) {
applyToProjectionReplayState(state, stored.event);
}
return state.projections;
};
/**
* EventSink commits the event, its projection updates, and projection metadata in one SQL
* transaction. Startup verification therefore checks that transaction boundary and that every
* stored projection can be decoded. It intentionally does not replay domain events through a
* second projector: doing so creates another implementation of projection semantics that must
* evolve in lockstep with ProjectionStore.
*/
const verify = Effect.gen(function* () {
const events = yield* readAllEvents;
const expected = expectedProjections(events);
const expectedThreadRows = yield* sql<{ readonly thread_id: string }>`
SELECT DISTINCT stream_id AS thread_id
FROM orchestration_events
WHERE application_event_version = 2
AND aggregate_kind = 'thread'
AND event_type = 'thread.created'
ORDER BY stream_id ASC
`;
const projectionRows = yield* sql<{ readonly thread_id: string }>`
SELECT thread_id
FROM orchestration_v2_projection_threads
ORDER BY thread_id ASC
`;
const actualIds = projectionRows.map((row) => ThreadId.make(row.thread_id));
const expectedIds = [...expected.keys()].toSorted((left, right) => left.localeCompare(right));
const expectedIds = expectedThreadRows.map((row) => ThreadId.make(row.thread_id));
const actualSet = new Set(actualIds);
const expectedSet = new Set(expectedIds);
const missingThreadIds = expectedIds.filter((threadId) => !actualSet.has(threadId));
const unexpectedThreadIds = actualIds.filter((threadId) => !expectedSet.has(threadId));
const differingThreadIds: Array<ThreadId> = [];
for (const threadId of expectedIds) {
if (!actualSet.has(threadId)) {
continue;
}
const actual = yield* projectionStore.getThreadProjection(threadId);
const expectedProjection = expected.get(threadId);
if (
expectedProjection === undefined ||
stableStringify(sortedProjection(actual)) !==
stableStringify(sortedProjection(expectedProjection))
) {
differingThreadIds.push(threadId);
}
}
const unreadableThreadIds = (yield* Effect.forEach(
actualIds,
(threadId) =>
projectionStore.getThreadProjection(threadId).pipe(
Effect.as<ThreadId | null>(null),
Effect.orElseSucceed((): ThreadId | null => threadId),
),
{ concurrency: 8 },
)).filter((threadId): threadId is ThreadId => threadId !== null);
const metadata = yield* sql<ProjectionMetadataRow>`
SELECT schema_version, last_sequence
FROM orchestration_v2_projection_metadata
WHERE projection_name = 'thread-projections'
LIMIT 1
`;
const expectedSequence = events.at(-1)?.sequence ?? 0;
const expectedSequence = yield* eventStore.latestSequence();
const schemaVersion = metadata[0]?.schema_version ?? 0;
const projectionSequence = metadata[0]?.last_sequence ?? 0;
return {
@@ -172,11 +126,11 @@ export const layer: Layer.Layer<
projectionSequence === expectedSequence &&
missingThreadIds.length === 0 &&
unexpectedThreadIds.length === 0 &&
differingThreadIds.length === 0,
unreadableThreadIds.length === 0,
schemaVersion,
expectedSequence,
projectionSequence,
differingThreadIds,
unreadableThreadIds,
missingThreadIds,
unexpectedThreadIds,
} satisfies ProjectionVerificationV2;
@@ -118,6 +118,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
case "provider.switch":
return [command.threadId];
case "delegated_task.request":
case "thread.created.record":
return [command.parentThreadId];
case "thread.fork":
case "thread.merge_back":
@@ -67,10 +67,14 @@ export function assertClaudeSubagentOutput(
),
);
for (const subagent of projection.subagents) {
const expectedProgress = subagent.prompt.includes("package.json")
? "Summarizing package.json"
: "Reading tsconfig.json";
assert.equal(subagent.origin, "provider_native");
assert.equal(subagent.createdBy, "agent");
assert.equal(subagent.driver, "claudeAgent");
assert.equal(subagent.status, "completed");
assert.equal(subagent.progress, expectedProgress);
assert.isNull(subagent.providerThreadId);
assert.isNotNull(subagent.childThreadId);
assert.isNotNull(subagent.nativeTaskRef);
@@ -88,7 +92,12 @@ export function assertClaudeSubagentOutput(
assert.lengthOf(childProjection.providerThreads, 0);
assert.lengthOf(childProjection.providerTurns, 0);
assertExecutionNodeKinds(childProjection, ["root_turn", "tool_call"]);
assertTurnItemTypes(childProjection, ["user_message", "dynamic_tool", "assistant_message"]);
assertTurnItemTypes(childProjection, [
"user_message",
"reasoning",
"dynamic_tool",
"assistant_message",
]);
assertUserMessagesInclude(childProjection, [subagent.prompt]);
assert.isTrue(
childProjection.turnItems.some(
@@ -99,5 +108,28 @@ export function assertClaudeSubagentOutput(
),
`child thread ${subagent.childThreadId} must contain the subagent response`,
);
const progressItems = childProjection.turnItems.filter((item) => item.type === "reasoning");
assert.lengthOf(
progressItems,
1,
`child thread ${subagent.childThreadId} must coalesce progress into one item`,
);
const progressItem = progressItems[0];
if (progressItem === undefined) {
throw new Error(`Missing progress item for subagent ${subagent.id}`);
}
assert.equal(progressItem.text, expectedProgress);
assert.equal(progressItem.status, "completed");
assert.isFalse(progressItem.streaming);
assert.isNotNull(progressItem.completedAt);
const parentItem = projection.turnItems.find(
(item) => item.type === "subagent" && item.subagentId === subagent.id,
);
assert.isDefined(parentItem);
if (parentItem?.type !== "subagent") {
throw new Error(`Missing parent lifecycle item for subagent ${subagent.id}`);
}
assert.equal(parentItem.progress, expectedProgress);
}
}
@@ -19,6 +19,7 @@
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_019MHopVQzAkpKERfKvRB1cj","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01P6KQcUPy8t2bCbFjv8K4Jz","name":"Read","input":{"file_path":"/private/var/folders/b3/b51_pdxj7dl0t981zpqkxxhr0000gn/T/t3-orchestrator-v2-claude-agent-sdk-record-subagent-jAoxxI/tsconfig.json"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":1140,"cache_read_input_tokens":7492,"cache_creation":{"ephemeral_5m_input_tokens":1140,"ephemeral_1h_input_tokens":0},"output_tokens":73,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"a5d6d0ed-bc30-43fb-9295-f338fedbf020"}}
{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01P6KQcUPy8t2bCbFjv8K4Jz","type":"tool_result","content":"1\t{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}"}]},"parent_tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"6814c55d-46df-4aeb-b594-f8819f353925","timestamp":"2026-05-27T00:24:46.995Z"}}
{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01EV8j88CPEmhoWF3iuvaFSC","type":"tool_result","content":"1\t{\"name\":\"claude-read-only-fixture\",\"private\":true,\"scripts\":{\"typecheck\":\"tsc --noEmit\"}}"}]},"parent_tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"cd552b77-8f0a-4984-b2e1-8eeea3e63148","timestamp":"2026-05-27T00:24:46.875Z"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_progress","task_id":"a35c9b7d354c20172","tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","description":"Summarizing package.json","usage":{"total_tokens":9250,"tool_uses":1,"duration_ms":3090},"last_tool_name":"Read","uuid":"9de3f10b-1955-4be3-a046-0e064e2d0e0d","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_notification","task_id":"a3d3213ffad1bd057","tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","status":"completed","output_file":"","summary":"Read tsconfig.json","usage":{"total_tokens":10750,"tool_uses":1,"duration_ms":5183},"uuid":"71cc121b-cc9f-42ad-aaea-40730ef81125","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","type":"tool_result","content":[{"type":"text","text":"Here are the full contents of `tsconfig.json`:\n\n```json\n{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}\n```\n\nIt is a minimal TypeScript configuration with three compiler options set:\n- `module`: `ESNext` — uses ES module syntax\n- `strict`: `true` — enables all strict type-checking options\n- `target`: `ES2022` — compiles down to ES2022 JavaScript"},{"type":"text","text":"agentId: a3d3213ffad1bd057 (use SendMessage with to: 'a3d3213ffad1bd057' to continue this agent)\n<usage>total_tokens: 10783\ntool_uses: 1\nduration_ms: 5186</usage>"}]}]},"parent_tool_use_id":null,"session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"526e0d3c-7688-4b39-8b54-4aa438b93f07","timestamp":"2026-05-27T00:24:50.087Z","tool_use_result":{"status":"completed","prompt":"Read the file `tsconfig.json` in the current working directory and return its full contents.","agentId":"a3d3213ffad1bd057","agentType":"general-purpose","content":[{"type":"text","text":"Here are the full contents of `tsconfig.json`:\n\n```json\n{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}\n```\n\nIt is a minimal TypeScript configuration with three compiler options set:\n- `module`: `ESNext` — uses ES module syntax\n- `strict`: `true` — enables all strict type-checking options\n- `target`: `ES2022` — compiles down to ES2022 JavaScript"}],"totalDurationMs":5186,"totalTokens":10783,"totalToolUseCount":1,"usage":{"input_tokens":1,"cache_creation_input_tokens":2043,"cache_read_input_tokens":8632,"output_tokens":107,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":2043},"inference_geo":"","iterations":[{"input_tokens":1,"output_tokens":107,"cache_read_input_tokens":8632,"cache_creation_input_tokens":2043,"cache_creation":{"ephemeral_5m_input_tokens":2043,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"toolStats":{"readCount":1,"searchCount":0,"bashCount":0,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0}}}}
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_notification","task_id":"a35c9b7d354c20172","tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","status":"completed","output_file":"","summary":"Read package.json","usage":{"total_tokens":10755,"tool_uses":1,"duration_ms":6211},"uuid":"5fd5a6f9-6045-4b50-99d9-a0bbe8991047","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
+11 -8
View File
@@ -394,14 +394,17 @@ export const make = Effect.gen(function* () {
Effect.tap((verification) =>
verification.valid
? Effect.void
: Effect.logWarning("V2 orchestration projections are stale; rebuilding", {
expectedSequence: verification.expectedSequence,
projectionSequence: verification.projectionSequence,
schemaVersion: verification.schemaVersion,
missingThreadCount: verification.missingThreadIds.length,
unexpectedThreadCount: verification.unexpectedThreadIds.length,
differingThreadCount: verification.differingThreadIds.length,
}),
: Effect.logWarning(
"V2 orchestration projection metadata or structure is invalid; rebuilding",
{
expectedSequence: verification.expectedSequence,
projectionSequence: verification.projectionSequence,
schemaVersion: verification.schemaVersion,
missingThreadCount: verification.missingThreadIds.length,
unexpectedThreadCount: verification.unexpectedThreadIds.length,
unreadableThreadCount: verification.unreadableThreadIds.length,
},
),
),
),
),
+2 -1
View File
@@ -885,7 +885,8 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
"orchestration_v2.thread_id":
command.type === "thread.fork" || command.type === "thread.merge_back"
? command.targetThreadId
: command.type === "delegated_task.request"
: command.type === "delegated_task.request" ||
command.type === "thread.created.record"
? command.parentThreadId
: command.threadId,
...(command.type === "thread.fork" || command.type === "thread.merge_back"