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

ProjectionSettlement.test.ts

406 lines13.6 KB

1import { assert, it } from "@effect/vitest";
2import {
3 EventId,
4 MessageId,
5 NodeId,
6 type OrchestrationV2AppThread,
7 type OrchestrationV2Run,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 ProviderThreadId,
12 RunId,
13 RuntimeRequestId,
14 ThreadId,
15 TurnItemId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20​
21import * as SqlitePersistence from "../persistence/Sqlite.ts";
22import * as ProjectionStore from "./ProjectionStore.ts";
23import { isAutoSettlementCandidate, resolveAutoSettlementAt } from "./ThreadSettlementService.ts";
24​
25const layerSql = ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory));
26const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
27const old = DateTime.subtract(now, { days: 10 });
28const providerInstanceId = ProviderInstanceId.make("codex");
29const modelSelection = { instanceId: providerInstanceId, model: "test-model" };
30​
31const createThread = Effect.fn(function* (
32 name: string,
33 overrides: Partial<OrchestrationV2AppThread> = {},
34) {
35 const store = yield* ProjectionStore.ProjectionStoreV2;
36 const threadId = ThreadId.make(`thread:settlement:${name}`);
37 const thread: OrchestrationV2AppThread = {
38 createdBy: "user",
39 creationSource: "web",
40 id: threadId,
41 projectId: ProjectId.make("project:settlement"),
42 title: name,
43 providerInstanceId,
44 modelSelection,
45 runtimeMode: "full-access",
46 interactionMode: "default",
47 branch: "feature",
48 worktreePath: null,
49 activeProviderThreadId: null,
50 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
51 forkedFrom: null,
52 createdAt: old,
53 updatedAt: old,
54 archivedAt: null,
55 settledOverride: null,
56 settledAt: null,
57 lastVisitedAt: null,
58 deletedAt: null,
59 ...overrides,
60 };
61 yield* store.apply({
62 id: EventId.make(`event:${threadId}`),
63 type: "thread.created",
64 threadId,
65 occurredAt: old,
66 payload: thread,
67 });
68 return threadId;
69});
70​
71const createRun = Effect.fn(function* (
72 threadId: ThreadId,
73 status: OrchestrationV2Run["status"] = "completed",
74 ordinal = 1,
75) {
76 const store = yield* ProjectionStore.ProjectionStoreV2;
77 const runId = RunId.make(`run:${threadId}:${ordinal}`);
78 yield* store.apply({
79 id: EventId.make(`event:${runId}`),
80 type: "run.created",
81 threadId,
82 occurredAt: old,
83 payload: {
84 id: runId,
85 threadId,
86 ordinal,
87 providerInstanceId,
88 modelSelection,
89 providerThreadId: null,
90 userMessageId: MessageId.make(`message:${runId}`),
91 rootNodeId: null,
92 activeAttemptId: null,
93 status,
94 requestedAt: old,
95 startedAt: status === "queued" ? null : old,
96 completedAt: ["completed", "rolled_back", "failed"].includes(status) ? old : null,
97 checkpointId: null,
98 contextHandoffId: null,
99 },
100 });
101 return runId;
102});
103​
104const createItem = Effect.fn(function* (
105 threadId: ThreadId,
106 runId: RunId,
107 status: "idle" | "running" | "completed",
108 persistent = false,
109) {
110 const store = yield* ProjectionStore.ProjectionStoreV2;
111 yield* store.apply({
112 id: EventId.make(`event:item:${runId}`),
113 type: "turn-item.updated",
114 threadId,
115 occurredAt: old,
116 payload: {
117 id: TurnItemId.make(`item:${runId}`),
118 threadId,
119 runId,
120 nodeId: null,
121 providerThreadId: null,
122 providerTurnId: null,
123 nativeItemRef: null,
124 parentItemId: null,
125 ordinal: 1,
126 type: "dynamic_tool",
127 status,
128 title: null,
129 startedAt: old,
130 completedAt: status === "completed" ? old : null,
131 updatedAt: old,
132 toolName: "background",
133 input: persistent ? { persistent: true } : null,
134 output: null,
135 },
136 });
137});
138​
139it.effect(
140 "sql: discovers settlement work with the same activity and background semantics as the shell",
141 () =>
142 Effect.gen(function* () {
143 const store = yield* ProjectionStore.ProjectionStoreV2;
144 const idle = yield* createThread("idle");
145 const completed = yield* createThread("completed");
146 yield* createRun(completed);
147 for (const [name, overrides] of [
148 ["archived", { archivedAt: old }],
149 ["deleted", { deletedAt: old }],
150 ["settled", { settledOverride: "settled" }],
151 ["unsettled", { settledOverride: "active" }],
152 ["pinned", { pinnedAt: old }],
153 ["auto-settle-disabled", { autoSettleDisabledAt: old }],
154 ] satisfies ReadonlyArray<readonly [string, Partial<OrchestrationV2AppThread>]>) {
155 yield* createRun(yield* createThread(name, overrides));
156 }
157 for (const status of ["preparing", "starting", "running", "waiting"] as const) {
158 yield* createRun(yield* createThread(status), status);
159 }
160 const queued = yield* createThread("queued");
161 yield* createRun(queued, "queued");
162 const blocked = yield* createThread("blocked");
163 yield* store.apply({
164 id: EventId.make("event:settlement:request"),
165 type: "runtime-request.updated",
166 threadId: blocked,
167 occurredAt: old,
168 payload: {
169 id: RuntimeRequestId.make("request:settlement"),
170 nodeId: NodeId.make("node:settlement"),
171 providerTurnId: null,
172 nativeRequestRef: null,
173 kind: "user_input",
174 status: "pending",
175 responseCapability: { type: "not_resumable", reason: "Process stopped" },
176 createdAt: old,
177 resolvedAt: null,
178 },
179 });
180 const recent = yield* createThread("recent-message");
181 yield* createRun(recent);
182 yield* store.apply({
183 id: EventId.make("event:settlement:message"),
184 type: "message.updated",
185 threadId: recent,
186 occurredAt: now,
187 payload: {
188 createdBy: "user",
189 creationSource: "web",
190 id: MessageId.make("message:settlement:recent"),
191 threadId: recent,
192 runId: null,
193 nodeId: null,
194 role: "user",
195 text: "Next turn",
196 attachments: [],
197 streaming: false,
198 createdAt: now,
199 updatedAt: now,
200 },
201 });
202 yield* createRun(
203 yield* createThread("snoozed", {
204 snoozedUntil: DateTime.add(now, { days: 1 }),
205 snoozedAt: now,
206 }),
207 );
208 const woke = yield* createThread("woke", {
209 snoozedUntil: DateTime.add(now, { days: 1 }),
210 snoozedAt: DateTime.subtract(old, { days: 1 }),
211 });
212 yield* createRun(woke, "failed");
213 const background = yield* createThread("idle-background");
214 yield* createItem(background, yield* createRun(background), "idle");
215 const persistent = yield* createThread("persistent-monitor");
216 yield* createItem(persistent, yield* createRun(persistent), "running", true);
217 const rolledBack = yield* createThread("rolled-back-background");
218 yield* createItem(rolledBack, yield* createRun(rolledBack, "rolled_back"), "running");
219 yield* createRun(rolledBack, "completed", 2);
220 const roster = yield* createThread("provider-roster");
221 yield* createRun(roster);
222 yield* store.apply({
223 id: EventId.make("event:settlement:roster"),
224 type: "provider-thread.updated",
225 threadId: roster,
226 occurredAt: old,
227 payload: {
228 id: ProviderThreadId.make("provider-thread:settlement"),
229 appThreadId: roster,
230 ownerNodeId: null,
231 driver: ProviderDriverKind.make("codex"),
232 providerInstanceId,
233 providerSessionId: null,
234 nativeThreadRef: null,
235 nativeConversationHeadRef: null,
236 status: "idle",
237 firstRunOrdinal: null,
238 lastRunOrdinal: null,
239 handoffIds: [],
240 forkedFrom: null,
241 createdAt: old,
242 updatedAt: old,
243 pendingBackgroundTasks: [{ taskId: "running-task", kind: "subagent" }],
244 },
245 });
246 const candidates = yield* store.getSettlementCandidates();
247 const shell = yield* store.getShellSnapshot({ location: "active" });
248 const eligible = candidates.filter((thread) =>
249 isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)),
250 );
251 assert.deepEqual(
252 new Set(eligible.map((thread) => thread.id)),
253 new Set([idle, completed, queued, woke, background, persistent, rolledBack]),
254 );
255 assert.deepEqual(
256 new Set(eligible.map((thread) => thread.id)),
257 new Set(
258 shell.threads
259 .filter((thread) => isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)))
260 .map((thread) => thread.id),
261 ),
262 );
263 for (const candidate of candidates) {
264 const expected = shell.threads.find((thread) => thread.id === candidate.id)!;
265 assert.deepEqual(candidate.pendingBackgroundTasks, expected.pendingBackgroundTasks);
266 const settings = {
267 pullRequest: null,
268 nowMs: DateTime.toEpochMillis(now),
269 autoSettleAfterDays: 7,
270 autoSettleOnMerge: false,
271 };
272 assert.deepEqual(
273 resolveAutoSettlementAt({ ...settings, thread: candidate }),
274 resolveAutoSettlementAt({
275 ...settings,
276 thread: {
277 ...expected,
278 latestUserAuthoredMessageAt: candidate.latestUserAuthoredMessageAt,
279 },
280 }),
281 );
282 }
283 assert.equal(
284 DateTime.formatIso((yield* store.getThread(completed)).createdAt),
285 DateTime.formatIso(old),
286 );
287 assert.equal(
288 (yield* store.getThread(ThreadId.make("missing")).pipe(Effect.flip))._tag,
289 "ProjectionStoreThreadNotFoundError",
290 );
291 }).pipe(Effect.provide(layerSql)),
292);
293​
294it.effect("sql: the user-authored message time ignores agent notifications", () =>
295 Effect.gen(function* () {
296 const store = yield* ProjectionStore.ProjectionStoreV2;
297 const threadId = yield* createThread("agent-woken");
298 yield* createRun(threadId);
299 const message = (
300 id: string,
301 createdBy: "user" | "agent",
302 creationSource: "web" | "provider",
303 at: DateTime.Utc,
304 ) =>
305 store.apply({
306 id: EventId.make(`event:settlement:${id}`),
307 type: "message.updated",
308 threadId,
309 occurredAt: at,
310 payload: {
311 createdBy,
312 creationSource,
313 id: MessageId.make(`message:settlement:${id}`),
314 threadId,
315 runId: null,
316 nodeId: null,
317 role: "user",
318 text: id,
319 attachments: [],
320 streaming: false,
321 createdAt: at,
322 updatedAt: at,
323 },
324 });
325 const written = DateTime.subtract(now, { hours: 2 });
326 yield* message("written", "user", "web", written);
327 yield* message("notification", "agent", "provider", now);
328​
329 const [candidate] = yield* store.getSettlementCandidates(threadId);
330 assert.isDefined(candidate);
331 assert.equal(DateTime.formatIso(candidate.latestUserMessageAt!), DateTime.formatIso(now));
332 assert.equal(
333 DateTime.formatIso(candidate.latestUserAuthoredMessageAt!),
334 DateTime.formatIso(written),
335 );
336 const shellThread = (yield* store.getShellSnapshot()).threads.find(
337 (thread) => thread.id === threadId,
338 );
339 assert.equal(
340 DateTime.formatIso(shellThread!.latestUserAuthoredMessageAt!),
341 DateTime.formatIso(written),
342 );
343 }).pipe(Effect.provide(layerSql)),
344);
345​
346const pullRequestLink = (number: number) => ({
347 host: "github.com",
348 repository: "owner/repository",
349 number,
350 url: `https://github.com/owner/repository/pull/${number}`,
351 source: "manual" as const,
352 linkedAt: DateTime.formatIso(old),
353 snapshot: null,
354 stack: null,
355});
356​
357it.effect("sql: lists only active threads with pull request links, oldest first", () =>
358 Effect.gen(function* () {
359 const store = yield* ProjectionStore.ProjectionStoreV2;
360 yield* createThread("no-links");
361 yield* createThread("empty-links", { pullRequests: [] });
362 yield* createThread("archived-link", {
363 archivedAt: old,
364 pullRequests: [pullRequestLink(1)],
365 });
366 const settled = yield* createThread("settled-link", {
367 settledOverride: "settled",
368 settledAt: old,
369 updatedAt: DateTime.subtract(now, { days: 12 }),
370 pullRequests: [pullRequestLink(2)],
371 });
372 const open = yield* createThread("open-link", {
373 pullRequests: [pullRequestLink(3), pullRequestLink(4)],
374 });
375​
376 const threads = yield* store.getThreadsWithPullRequests();
377 assert.deepEqual(
378 threads.map((thread) => [thread.id, thread.settledOverride, thread.pullRequests?.length]),
379 [
380 [settled, "settled", 1],
381 [open, null, 2],
382 ],
383 );
384 assert.deepEqual(
385 (yield* store.getThreadsWithPullRequests(open)).map((thread) => thread.id),
386 [open],
387 );
388 }).pipe(Effect.provide(layerSql)),
389);
390​
391it.effect("sql: an unsettled-only shell read skips settled threads", () =>
392 Effect.gen(function* () {
393 const store = yield* ProjectionStore.ProjectionStoreV2;
394 const open = yield* createThread("unsettled-open");
395 const reopened = yield* createThread("unsettled-reopened", { settledOverride: "active" });
396 yield* createThread("unsettled-manual", { settledOverride: "settled", settledAt: old });
397 yield* createThread("unsettled-auto", { settledAt: old });
398 yield* createThread("unsettled-archived", { archivedAt: old });
399​
400 const shell = yield* store.getShellSnapshot({ location: "active", unsettledOnly: true });
401 assert.deepEqual(new Set(shell.threads.map((thread) => thread.id)), new Set([open, reopened]));
402 assert.equal(shell.archivedThreads.length, 0);
403 const all = yield* store.getShellSnapshot({ location: "active" });
404 assert.equal(all.threads.length, 4);
405 }).pipe(Effect.provide(layerSql)),
406);