Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OrchestrationMilestones.test.ts

300 lines11.2 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EnvironmentId,
5 EventId,
6 GuestMessageId,
7 GuestShareId,
8 MessageId,
9 type OrchestrationV2AppThread,
10 type OrchestrationV2DomainEvent,
11 type OrchestrationV2Run,
12 ProjectId,
13 ProviderDriverKind,
14 ProviderInstanceId,
15 RuntimeRequestId,
16 ThreadId,
17 type ThreadGuestMessage,
18} from "@t3tools/contracts";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
23​
24import * as SqlitePersistence from "../persistence/Sqlite.ts";
25import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
26import * as EffectOutbox from "../orchestration-v2/EffectOutbox.ts";
27import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
28import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
29import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
30import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
31import * as MilestoneHub from "./MilestoneHub.ts";
32import * as OrchestrationMilestones from "./OrchestrationMilestones.ts";
33​
34const instanceId = ProviderInstanceId.make("codex");
35const modelSelection = { instanceId, model: "gpt-5.1-codex" };
36const adapter = {
37 instanceId,
38 driver: ProviderDriverKind.make("codex"),
39 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
40 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
41 openSession: () => Effect.die("No provider process needed for milestones"),
42} as ProviderAdapter.ProviderAdapterV2["Service"];
43const layerDatabase = SqlitePersistence.layerMemory;
44const layerTest = OrchestrationMilestones.layer.pipe(
45 Layer.provideMerge(MilestoneHub.layer),
46 Layer.provideMerge(
47 Layer.mergeAll(
48 layerDatabase,
49 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
50 EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
51 ProviderReplayHarness.layerWithRegistry(
52 { name: "milestones" },
53 ProviderAdapterRegistry.layerFromAdapters([adapter]),
54 { databaseLayer: layerDatabase, runEffectWorker: false },
55 ),
56 ),
57 ),
58);
59​
60it.effect("tells each thread transition once, with its lineage", () =>
61 Effect.gen(function* () {
62 const orchestrator = yield* Orchestrator.OrchestratorV2;
63 const projections = yield* ProjectionStore.ProjectionStoreV2;
64 const feeder = yield* OrchestrationMilestones.OrchestrationMilestones;
65 const hub = yield* MilestoneHub.MilestoneHub;
66 const parentThreadId = ThreadId.make("thread:milestone-parent");
67 yield* orchestrator.dispatch({
68 type: "thread.create",
69 commandId: CommandId.make("create-milestone-parent"),
70 threadId: parentThreadId,
71 projectId: ProjectId.make("project:milestones"),
72 title: "Parent",
73 modelSelection,
74 runtimeMode: "full-access",
75 interactionMode: "default",
76 branch: null,
77 worktreePath: null,
78 createdBy: "user",
79 creationSource: "web",
80 });
81 yield* orchestrator.dispatch({
82 type: "message.dispatch",
83 commandId: CommandId.make("start-milestone-parent"),
84 threadId: parentThreadId,
85 messageId: MessageId.make("message:milestone-parent"),
86 text: "Delegate the research",
87 attachments: [],
88 dispatchMode: { type: "start_immediately" },
89 createdBy: "user",
90 creationSource: "web",
91 });
92 const parentRun = (yield* projections.getThreadProjection(parentThreadId)).runs[0]!;
93 yield* orchestrator.dispatch({
94 type: "delegated_task.request",
95 commandId: CommandId.make("delegate-milestone-task"),
96 parentThreadId,
97 parentRunId: parentRun.id,
98 parentNodeId: parentRun.rootNodeId!,
99 task: "Research the sources",
100 completionWake: "settled_only",
101 modelSelection,
102 runtimeMode: "full-access",
103 interactionMode: "default",
104 createdBy: "agent",
105 creationSource: "mcp",
106 });
107 const childThreadId = (yield* projections.getThreadProjection(parentThreadId)).subagents[0]!
108 .childThreadId!;
109 const childRun = (yield* projections.getThreadRecords(childThreadId, ["runs"])).runs[0]!;
110 // A workflow run's agent step, which a filter on its run picks out.
111 const stepThreadId = ThreadId.make("thread:milestone-workflow-step");
112 yield* orchestrator.dispatch({
113 type: "thread.create",
114 commandId: CommandId.make("create-milestone-step"),
115 threadId: stepThreadId,
116 projectId: ProjectId.make("project:milestones"),
117 title: "Triage",
118 modelSelection,
119 runtimeMode: "full-access",
120 interactionMode: "default",
121 branch: null,
122 worktreePath: null,
123 createdBy: "system",
124 creationSource: "server",
125 workflowRun: {
126 environmentId: EnvironmentId.make("environment:milestones"),
127 runId: "workflow-run:milestones",
128 workflow: "review",
129 step: "triage",
130 },
131 });
132 yield* orchestrator.dispatch({
133 type: "message.dispatch",
134 commandId: CommandId.make("start-milestone-step"),
135 threadId: stepThreadId,
136 messageId: MessageId.make("message:milestone-step"),
137 text: "Triage the issue",
138 attachments: [],
139 dispatchMode: { type: "start_immediately" },
140 createdBy: "system",
141 creationSource: "server",
142 });
143 const stepRun = (yield* projections.getThreadRecords(stepThreadId, ["runs"])).runs[0]!;
144 const parent = yield* projections.getThread(parentThreadId);
145 const now = yield* DateTime.now;
146 const base = (id: string, threadId: ThreadId) => ({
147 id: EventId.make(id),
148 threadId,
149 occurredAt: now,
150 });
151 const ended = (id: string, run: OrchestrationV2Run, status: OrchestrationV2Run["status"]) =>
152 ({
153 ...base(id, run.threadId),
154 type: "run.updated",
155 runId: run.id,
156 payload: { ...run, status, startedAt: now, completedAt: now },
157 }) satisfies OrchestrationV2DomainEvent;
158 const request = (id: string, status: "pending" | "resolved") =>
159 ({
160 ...base(id, parentThreadId),
161 type: "runtime-request.updated",
162 payload: {
163 id: RuntimeRequestId.make("request:milestone"),
164 nodeId: parentRun.rootNodeId!,
165 providerTurnId: null,
166 nativeRequestRef: null,
167 kind: "command",
168 status,
169 responseCapability: { type: "message" },
170 createdAt: now,
171 resolvedAt: status === "pending" ? null : now,
172 },
173 }) satisfies OrchestrationV2DomainEvent;
174 const shareId = GuestShareId.make("share:milestone");
175 const guestMessage = (id: string, status: ThreadGuestMessage["status"]) => ({
176 id: GuestMessageId.make(id),
177 text: "Can you also check the docs?",
178 status,
179 submittedAt: DateTime.formatIso(now),
180 });
181 const shared = (
182 id: string,
183 messages: ReadonlyArray<ThreadGuestMessage> | null,
184 ): OrchestrationV2DomainEvent => {
185 const payload: OrchestrationV2AppThread = {
186 ...parent,
187 guestShare:
188 messages === null
189 ? null
190 : {
191 id: shareId,
192 host: "tunnel.example",
193 createdAt: DateTime.formatIso(now),
194 expiresAt: DateTime.formatIso(now),
195 guestName: "Sam",
196 messages,
197 },
198 };
199 return { ...base(id, parentThreadId), type: "thread.guest-share-updated", payload };
200 };
201 const wake = {
202 ...base("event:wake", parentThreadId),
203 type: "message.updated",
204 payload: {
205 id: MessageId.make("message:pr-wake"),
206 threadId: parentThreadId,
207 runId: null,
208 nodeId: null,
209 role: "user",
210 text: "Checks finished on #7.",
211 attachments: [],
212 streaming: false,
213 createdAt: now,
214 updatedAt: now,
215 createdBy: "system",
216 creationSource: "server",
217 notification: {
218 source: {
219 kind: "monitor",
220 pullRequest: {
221 host: "github.com",
222 repository: "me/app",
223 number: 7,
224 watchStartedAt: DateTime.formatIso(now),
225 headSha: "abc",
226 watchEnded: true,
227 },
228 },
229 outcome: "completed",
230 summary: "#7: checks passed",
231 },
232 },
233 } satisfies OrchestrationV2DomainEvent;
234​
235 for (const event of [
236 ended("event:parent-done", parentRun, "completed"),
237 // A later update of a settled run is not a second settlement.
238 ended("event:parent-done-again", parentRun, "completed"),
239 ended("event:child-failed", childRun, "failed"),
240 request("event:asked", "pending"),
241 request("event:answered", "resolved"),
242 shared("event:guest-asked", [guestMessage("guest:one", "pending")]),
243 shared("event:guest-sent", [guestMessage("guest:one", "sent")]),
244 shared("event:guest-asked-again", [
245 guestMessage("guest:one", "sent"),
246 guestMessage("guest:two", "pending"),
247 ]),
248 shared("event:guest-closed", null),
249 wake,
250 wake,
251 ended("event:step-done", stepRun, "completed"),
252 ]) {
253 yield* feeder.handle(event);
254 }
255​
256 const { events } = yield* hub.recent({ filter: { includeSubagentChildren: true } });
257 assert.deepStrictEqual(
258 events.map((event) => [
259 event.id,
260 event.threadId,
261 event.parentThreadId,
262 event.isSubagentChild,
263 ]),
264 [
265 [`thread.run_settled:${parentRun.id}`, parentThreadId, null, false],
266 [`thread.run_settled:${childRun.id}`, childThreadId, parentThreadId, true],
267 ["thread.needs_input:request:milestone", parentThreadId, null, false],
268 ["thread.input_resolved:request:milestone", parentThreadId, null, false],
269 ["thread.guest_request:guest:one", parentThreadId, null, false],
270 ["thread.guest_request_resolved:guest:one", parentThreadId, null, false],
271 ["thread.guest_request:guest:two", parentThreadId, null, false],
272 ["thread.guest_request_resolved:guest:two", parentThreadId, null, false],
273 ["pr.watch_wake:message:pr-wake", parentThreadId, null, false],
274 [`thread.run_settled:${stepRun.id}`, stepThreadId, null, false],
275 ],
276 );
277 assert.deepStrictEqual(
278 (yield* hub.recent({ filter: { workflowRunIds: ["workflow-run:milestones"] } })).events.map(
279 (event) => event.threadId,
280 ),
281 [stepThreadId],
282 );
283 const [, child, asked, answered, , sent, , closed, woke] = events;
284 assert.deepInclude(child, { outcome: "failed", projectId: parent.projectId });
285 assert.deepInclude(asked, { kind: "approval" });
286 assert.deepInclude(answered, { resolution: "resolved", actor: { type: "user" } });
287 assert.deepInclude(sent, { resolution: "sent" });
288 assert.deepInclude(closed, { resolution: "closed" });
289 assert.deepInclude(woke, {
290 pullRequests: [{ host: "github.com", repository: "me/app", number: 7 }],
291 watchEnded: true,
292 summary: "#7: checks passed",
293 });
294 // A subscriber that did not ask for children never hears of the child's run.
295 assert.notInclude(
296 (yield* hub.recent()).events.map((event) => event.threadId),
297 childThreadId,
298 );
299 }).pipe(Effect.provide(layerTest)),
300);