Open History to see the last commit
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.each([
140 ["sql", layerSql],
141 ["memory", ProjectionStore.layerMemory],
142] as const)(
143 "%s: discovers settlement work with the same activity and background semantics as the shell",
144 ([, testLayer]) =>
145 Effect.gen(function* () {
146 const store = yield* ProjectionStore.ProjectionStoreV2;
147 const idle = yield* createThread("idle");
148 const completed = yield* createThread("completed");
149 yield* createRun(completed);
150 for (const [name, overrides] of [
151 ["archived", { archivedAt: old }],
152 ["deleted", { deletedAt: old }],
153 ["settled", { settledOverride: "settled" }],
154 ["unsettled", { settledOverride: "active" }],
155 ["pinned", { pinnedAt: old }],
156 ["auto-settle-disabled", { autoSettleDisabledAt: old }],
157 ] satisfies ReadonlyArray<readonly [string, Partial<OrchestrationV2AppThread>]>) {
158 yield* createRun(yield* createThread(name, overrides));
159 }
160 for (const status of ["preparing", "starting", "running", "waiting"] as const) {
161 yield* createRun(yield* createThread(status), status);
162 }
163 const queued = yield* createThread("queued");
164 yield* createRun(queued, "queued");
165 const blocked = yield* createThread("blocked");
166 yield* store.apply({
167 id: EventId.make("event:settlement:request"),
168 type: "runtime-request.updated",
169 threadId: blocked,
170 occurredAt: old,
171 payload: {
172 id: RuntimeRequestId.make("request:settlement"),
173 nodeId: NodeId.make("node:settlement"),
174 providerTurnId: null,
175 nativeRequestRef: null,
176 kind: "user_input",
177 status: "pending",
178 responseCapability: { type: "not_resumable", reason: "Process stopped" },
179 createdAt: old,
180 resolvedAt: null,
181 },
182 });
183 const recent = yield* createThread("recent-message");
184 yield* createRun(recent);
185 yield* store.apply({
186 id: EventId.make("event:settlement:message"),
187 type: "message.updated",
188 threadId: recent,
189 occurredAt: now,
190 payload: {
191 createdBy: "user",
192 creationSource: "web",
193 id: MessageId.make("message:settlement:recent"),
194 threadId: recent,
195 runId: null,
196 nodeId: null,
197 role: "user",
198 text: "Next turn",
199 attachments: [],
200 streaming: false,
201 createdAt: now,
202 updatedAt: now,
203 },
204 });
205 yield* createRun(
206 yield* createThread("snoozed", {
207 snoozedUntil: DateTime.add(now, { days: 1 }),
208 snoozedAt: now,
209 }),
210 );
211 const woke = yield* createThread("woke", {
212 snoozedUntil: DateTime.add(now, { days: 1 }),
213 snoozedAt: DateTime.subtract(old, { days: 1 }),
214 });
215 yield* createRun(woke, "failed");
216 const background = yield* createThread("idle-background");
217 yield* createItem(background, yield* createRun(background), "idle");
218 const persistent = yield* createThread("persistent-monitor");
219 yield* createItem(persistent, yield* createRun(persistent), "running", true);
220 const rolledBack = yield* createThread("rolled-back-background");
221 yield* createItem(rolledBack, yield* createRun(rolledBack, "rolled_back"), "running");
222 yield* createRun(rolledBack, "completed", 2);
223 const roster = yield* createThread("provider-roster");
224 yield* createRun(roster);
225 yield* store.apply({
226 id: EventId.make("event:settlement:roster"),
227 type: "provider-thread.updated",
228 threadId: roster,
229 occurredAt: old,
230 payload: {
231 id: ProviderThreadId.make("provider-thread:settlement"),
232 appThreadId: roster,
233 ownerNodeId: null,
234 driver: ProviderDriverKind.make("codex"),
235 providerInstanceId,
236 providerSessionId: null,
237 nativeThreadRef: null,
238 nativeConversationHeadRef: null,
239 status: "idle",
240 firstRunOrdinal: null,
241 lastRunOrdinal: null,
242 handoffIds: [],
243 forkedFrom: null,
244 createdAt: old,
245 updatedAt: old,
246 pendingBackgroundTasks: [{ taskId: "running-task", kind: "subagent" }],
247 },
248 });
249 const candidates = yield* store.getSettlementCandidates();
250 const shell = yield* store.getShellSnapshot({ location: "active" });
251 const eligible = candidates.filter((thread) =>
252 isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)),
253 );
254 assert.deepEqual(
255 new Set(eligible.map((thread) => thread.id)),
256 new Set([idle, completed, queued, woke, background, persistent, rolledBack]),
257 );
258 assert.deepEqual(
259 new Set(eligible.map((thread) => thread.id)),
260 new Set(
261 shell.threads
262 .filter((thread) => isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)))
263 .map((thread) => thread.id),
264 ),
265 );
266 for (const candidate of candidates) {
267 const expected = shell.threads.find((thread) => thread.id === candidate.id)!;
268 assert.deepEqual(candidate.pendingBackgroundTasks, expected.pendingBackgroundTasks);
269 const settings = {
270 pullRequest: null,
271 nowMs: DateTime.toEpochMillis(now),
272 autoSettleAfterDays: 7,
273 autoSettleOnMerge: false,
274 };
275 assert.deepEqual(
276 resolveAutoSettlementAt({ ...settings, thread: candidate }),
277 resolveAutoSettlementAt({
278 ...settings,
279 thread: {
280 ...expected,
281 latestUserAuthoredMessageAt: candidate.latestUserAuthoredMessageAt,
282 },
283 }),
284 );
285 }
286 assert.equal(
287 DateTime.formatIso((yield* store.getThread(completed)).createdAt),
288 DateTime.formatIso(old),
289 );
290 assert.equal(
291 (yield* store.getThread(ThreadId.make("missing")).pipe(Effect.flip))._tag,
292 "ProjectionStoreThreadNotFoundError",
293 );
294 }).pipe(Effect.provide(testLayer)),
295);
296
297it.effect.each([
298 ["sql", layerSql],
299 ["memory", ProjectionStore.layerMemory],
300] as const)("%s: the user-authored message time ignores agent notifications", ([, testLayer]) =>
301 Effect.gen(function* () {
302 const store = yield* ProjectionStore.ProjectionStoreV2;
303 const threadId = yield* createThread("agent-woken");
304 yield* createRun(threadId);
305 const message = (
306 id: string,
307 createdBy: "user" | "agent",
308 creationSource: "web" | "provider",
309 at: DateTime.Utc,
310 ) =>
311 store.apply({
312 id: EventId.make(`event:settlement:${id}`),
313 type: "message.updated",
314 threadId,
315 occurredAt: at,
316 payload: {
317 createdBy,
318 creationSource,
319 id: MessageId.make(`message:settlement:${id}`),
320 threadId,
321 runId: null,
322 nodeId: null,
323 role: "user",
324 text: id,
325 attachments: [],
326 streaming: false,
327 createdAt: at,
328 updatedAt: at,
329 },
330 });
331 const written = DateTime.subtract(now, { hours: 2 });
332 yield* message("written", "user", "web", written);
333 yield* message("notification", "agent", "provider", now);
334
335 const [candidate] = yield* store.getSettlementCandidates(threadId);
336 assert.isDefined(candidate);
337 assert.equal(DateTime.formatIso(candidate.latestUserMessageAt!), DateTime.formatIso(now));
338 assert.equal(
339 DateTime.formatIso(candidate.latestUserAuthoredMessageAt!),
340 DateTime.formatIso(written),
341 );
342 const shellThread = (yield* store.getShellSnapshot()).threads.find(
343 (thread) => thread.id === threadId,
344 );
345 assert.equal(
346 DateTime.formatIso(shellThread!.latestUserAuthoredMessageAt!),
347 DateTime.formatIso(written),
348 );
349 }).pipe(Effect.provide(testLayer)),
350);
351
352const pullRequestLink = (number: number) => ({
353 host: "github.com",
354 repository: "owner/repository",
355 number,
356 url: `https://github.com/owner/repository/pull/${number}`,
357 source: "manual" as const,
358 linkedAt: DateTime.formatIso(old),
359 snapshot: null,
360 stack: null,
361});
362
363it.effect.each([
364 ["sql", layerSql],
365 ["memory", ProjectionStore.layerMemory],
366] as const)(
367 "%s: lists only active threads with pull request links, oldest first",
368 ([, testLayer]) =>
369 Effect.gen(function* () {
370 const store = yield* ProjectionStore.ProjectionStoreV2;
371 yield* createThread("no-links");
372 yield* createThread("empty-links", { pullRequests: [] });
373 yield* createThread("archived-link", {
374 archivedAt: old,
375 pullRequests: [pullRequestLink(1)],
376 });
377 const settled = yield* createThread("settled-link", {
378 settledOverride: "settled",
379 settledAt: old,
380 updatedAt: DateTime.subtract(now, { days: 12 }),
381 pullRequests: [pullRequestLink(2)],
382 });
383 const open = yield* createThread("open-link", {
384 pullRequests: [pullRequestLink(3), pullRequestLink(4)],
385 });
386
387 const threads = yield* store.getThreadsWithPullRequests();
388 assert.deepEqual(
389 threads.map((thread) => [thread.id, thread.settledOverride, thread.pullRequests?.length]),
390 [
391 [settled, "settled", 1],
392 [open, null, 2],
393 ],
394 );
395 assert.deepEqual(
396 (yield* store.getThreadsWithPullRequests(open)).map((thread) => thread.id),
397 [open],
398 );
399 }).pipe(Effect.provide(testLayer)),
400);
401
402it.effect.each([
403 ["sql", layerSql],
404 ["memory", ProjectionStore.layerMemory],
405] as const)("%s: an unsettled-only shell read skips settled threads", ([, testLayer]) =>
406 Effect.gen(function* () {
407 const store = yield* ProjectionStore.ProjectionStoreV2;
408 const open = yield* createThread("unsettled-open");
409 const reopened = yield* createThread("unsettled-reopened", { settledOverride: "active" });
410 yield* createThread("unsettled-manual", { settledOverride: "settled", settledAt: old });
411 yield* createThread("unsettled-auto", { settledAt: old });
412 yield* createThread("unsettled-archived", { archivedAt: old });
413
414 const shell = yield* store.getShellSnapshot({ location: "active", unsettledOnly: true });
415 assert.deepEqual(new Set(shell.threads.map((thread) => thread.id)), new Set([open, reopened]));
416 assert.equal(shell.archivedThreads.length, 0);
417 const all = yield* store.getShellSnapshot({ location: "active" });
418 assert.equal(all.threads.length, 4);
419 }).pipe(Effect.provide(testLayer)),
420);