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";
20import * as Schema from "effect/Schema";
21import * as SqlClient from "effect/unstable/sql/SqlClient";
22import * as Statement from "effect/unstable/sql/Statement";
23
24import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
25import * as ProjectionStore from "./ProjectionStore.ts";
26import { isAutoSettlementCandidate, resolveAutoSettlementAt } from "./ThreadSettlementService.ts";
27
28const SqlLayer = ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistenceMemory));
29const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
30const old = DateTime.subtract(now, { days: 10 });
31const providerInstanceId = ProviderInstanceId.make("codex");
32const modelSelection = { instanceId: providerInstanceId, model: "test-model" };
33const encodeNumbers = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.Number)));
34
35const createThread = Effect.fn(function* (
36 name: string,
37 overrides: Partial<OrchestrationV2AppThread> = {},
38) {
39 const store = yield* ProjectionStore.ProjectionStoreV2;
40 const threadId = ThreadId.make(`thread:settlement:${name}`);
41 const thread: OrchestrationV2AppThread = {
42 createdBy: "user",
43 creationSource: "web",
44 id: threadId,
45 projectId: ProjectId.make("project:settlement"),
46 title: name,
47 providerInstanceId,
48 modelSelection,
49 runtimeMode: "full-access",
50 interactionMode: "default",
51 branch: "feature",
52 worktreePath: null,
53 activeProviderThreadId: null,
54 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
55 forkedFrom: null,
56 createdAt: old,
57 updatedAt: old,
58 archivedAt: null,
59 settledOverride: null,
60 settledAt: null,
61 lastVisitedAt: null,
62 deletedAt: null,
63 ...overrides,
64 };
65 yield* store.apply({
66 id: EventId.make(`event:${threadId}`),
67 type: "thread.created",
68 threadId,
69 occurredAt: old,
70 payload: thread,
71 });
72 return threadId;
73});
74
75const createRun = Effect.fn(function* (
76 threadId: ThreadId,
77 status: OrchestrationV2Run["status"] = "completed",
78 ordinal = 1,
79) {
80 const store = yield* ProjectionStore.ProjectionStoreV2;
81 const runId = RunId.make(`run:${threadId}:${ordinal}`);
82 yield* store.apply({
83 id: EventId.make(`event:${runId}`),
84 type: "run.created",
85 threadId,
86 occurredAt: old,
87 payload: {
88 id: runId,
89 threadId,
90 ordinal,
91 providerInstanceId,
92 modelSelection,
93 providerThreadId: null,
94 userMessageId: MessageId.make(`message:${runId}`),
95 rootNodeId: null,
96 activeAttemptId: null,
97 status,
98 requestedAt: old,
99 startedAt: status === "queued" ? null : old,
100 completedAt: ["completed", "rolled_back", "failed"].includes(status) ? old : null,
101 checkpointId: null,
102 contextHandoffId: null,
103 },
104 });
105 return runId;
106});
107
108const createItem = Effect.fn(function* (
109 threadId: ThreadId,
110 runId: RunId,
111 status: "idle" | "running" | "completed",
112 persistent = false,
113) {
114 const store = yield* ProjectionStore.ProjectionStoreV2;
115 yield* store.apply({
116 id: EventId.make(`event:item:${runId}`),
117 type: "turn-item.updated",
118 threadId,
119 occurredAt: old,
120 payload: {
121 id: TurnItemId.make(`item:${runId}`),
122 threadId,
123 runId,
124 nodeId: null,
125 providerThreadId: null,
126 providerTurnId: null,
127 nativeItemRef: null,
128 parentItemId: null,
129 ordinal: 1,
130 type: "dynamic_tool",
131 status,
132 title: null,
133 startedAt: old,
134 completedAt: status === "completed" ? old : null,
135 updatedAt: old,
136 toolName: "background",
137 input: persistent ? { persistent: true } : null,
138 output: null,
139 },
140 });
141});
142
143for (const [name, testLayer] of [
144 ["sql", SqlLayer],
145 ["memory", ProjectionStore.layerMemory],
146] as const) {
147 it.effect(
148 `${name}: discovers settlement work with the same activity and background semantics as the shell`,
149 () =>
150 Effect.gen(function* () {
151 const store = yield* ProjectionStore.ProjectionStoreV2;
152 const idle = yield* createThread("idle");
153 const completed = yield* createThread("completed");
154 yield* createRun(completed);
155 for (const [name, overrides] of [
156 ["archived", { archivedAt: old }],
157 ["deleted", { deletedAt: old }],
158 ["settled", { settledOverride: "settled" }],
159 ["unsettled", { settledOverride: "active" }],
160 ["pinned", { pinnedAt: old }],
161 ["auto-settle-disabled", { autoSettleDisabledAt: old }],
162 ] satisfies ReadonlyArray<readonly [string, Partial<OrchestrationV2AppThread>]>) {
163 yield* createRun(yield* createThread(name, overrides));
164 }
165 for (const status of ["preparing", "starting", "running", "waiting"] as const) {
166 yield* createRun(yield* createThread(status), status);
167 }
168 const queued = yield* createThread("queued");
169 yield* createRun(queued, "queued");
170 const blocked = yield* createThread("blocked");
171 yield* store.apply({
172 id: EventId.make("event:settlement:request"),
173 type: "runtime-request.updated",
174 threadId: blocked,
175 occurredAt: old,
176 payload: {
177 id: RuntimeRequestId.make("request:settlement"),
178 nodeId: NodeId.make("node:settlement"),
179 providerTurnId: null,
180 nativeRequestRef: null,
181 kind: "user_input",
182 status: "pending",
183 responseCapability: { type: "not_resumable", reason: "Process stopped" },
184 createdAt: old,
185 resolvedAt: null,
186 },
187 });
188 const recent = yield* createThread("recent-message");
189 yield* createRun(recent);
190 yield* store.apply({
191 id: EventId.make("event:settlement:message"),
192 type: "message.updated",
193 threadId: recent,
194 occurredAt: now,
195 payload: {
196 createdBy: "user",
197 creationSource: "web",
198 id: MessageId.make("message:settlement:recent"),
199 threadId: recent,
200 runId: null,
201 nodeId: null,
202 role: "user",
203 text: "Next turn",
204 attachments: [],
205 streaming: false,
206 createdAt: now,
207 updatedAt: now,
208 },
209 });
210 yield* createRun(
211 yield* createThread("snoozed", {
212 snoozedUntil: DateTime.add(now, { days: 1 }),
213 snoozedAt: now,
214 }),
215 );
216 const woke = yield* createThread("woke", {
217 snoozedUntil: DateTime.add(now, { days: 1 }),
218 snoozedAt: DateTime.subtract(old, { days: 1 }),
219 });
220 yield* createRun(woke);
221 const background = yield* createThread("idle-background");
222 yield* createItem(background, yield* createRun(background), "idle");
223 const persistent = yield* createThread("persistent-monitor");
224 yield* createItem(persistent, yield* createRun(persistent), "running", true);
225 const rolledBack = yield* createThread("rolled-back-background");
226 yield* createItem(rolledBack, yield* createRun(rolledBack, "rolled_back"), "running");
227 yield* createRun(rolledBack, "completed", 2);
228 const roster = yield* createThread("provider-roster");
229 yield* createRun(roster);
230 yield* store.apply({
231 id: EventId.make("event:settlement:roster"),
232 type: "provider-thread.updated",
233 threadId: roster,
234 occurredAt: old,
235 payload: {
236 id: ProviderThreadId.make("provider-thread:settlement"),
237 appThreadId: roster,
238 ownerNodeId: null,
239 driver: ProviderDriverKind.make("codex"),
240 providerInstanceId,
241 providerSessionId: null,
242 nativeThreadRef: null,
243 nativeConversationHeadRef: null,
244 status: "idle",
245 firstRunOrdinal: null,
246 lastRunOrdinal: null,
247 handoffIds: [],
248 forkedFrom: null,
249 createdAt: old,
250 updatedAt: old,
251 pendingBackgroundTasks: [{ taskId: "running-task", kind: "command" }],
252 },
253 });
254 const candidates = yield* store.getSettlementCandidates();
255 const shell = yield* store.getShellSnapshot({ location: "active" });
256 const eligible = candidates.filter((thread) =>
257 isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)),
258 );
259 assert.deepEqual(
260 new Set(eligible.map((thread) => thread.id)),
261 new Set([idle, completed, queued, woke, background, persistent, rolledBack]),
262 );
263 assert.deepEqual(
264 new Set(eligible.map((thread) => thread.id)),
265 new Set(
266 shell.threads
267 .filter((thread) => isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)))
268 .map((thread) => thread.id),
269 ),
270 );
271 for (const candidate of candidates) {
272 const expected = shell.threads.find((thread) => thread.id === candidate.id)!;
273 assert.deepEqual(candidate.pendingBackgroundTasks, expected.pendingBackgroundTasks);
274 const settings = {
275 pullRequest: null,
276 nowMs: DateTime.toEpochMillis(now),
277 autoSettleAfterDays: 7,
278 autoSettleOnMerge: false,
279 };
280 assert.deepEqual(
281 resolveAutoSettlementAt({ ...settings, thread: candidate }),
282 resolveAutoSettlementAt({ ...settings, thread: expected }),
283 );
284 }
285 assert.equal(
286 DateTime.formatIso((yield* store.getThread(completed)).createdAt),
287 DateTime.formatIso(old),
288 );
289 assert.equal(
290 (yield* store.getThread(ThreadId.make("missing")).pipe(Effect.flip))._tag,
291 "ProjectionStoreThreadNotFoundError",
292 );
293 }).pipe(Effect.provide(testLayer)),
294 );
295}
296
297const pullRequestLink = (number: number) => ({
298 host: "github.com",
299 repository: "owner/repository",
300 number,
301 url: `https://github.com/owner/repository/pull/${number}`,
302 source: "manual" as const,
303 linkedAt: DateTime.formatIso(old),
304 snapshot: null,
305 stack: null,
306});
307
308for (const [name, testLayer] of [
309 ["sql", SqlLayer],
310 ["memory", ProjectionStore.layerMemory],
311] as const) {
312 it.effect(`${name}: lists only active threads with pull request links, oldest first`, () =>
313 Effect.gen(function* () {
314 const store = yield* ProjectionStore.ProjectionStoreV2;
315 yield* createThread("no-links");
316 yield* createThread("empty-links", { pullRequests: [] });
317 yield* createThread("archived-link", {
318 archivedAt: old,
319 pullRequests: [pullRequestLink(1)],
320 });
321 const settled = yield* createThread("settled-link", {
322 settledOverride: "settled",
323 settledAt: old,
324 updatedAt: DateTime.subtract(now, { days: 12 }),
325 pullRequests: [pullRequestLink(2)],
326 });
327 const open = yield* createThread("open-link", {
328 pullRequests: [pullRequestLink(3), pullRequestLink(4)],
329 });
330
331 const threads = yield* store.getThreadsWithPullRequests();
332 assert.deepEqual(
333 threads.map((thread) => [thread.id, thread.settledOverride, thread.pullRequests?.length]),
334 [
335 [settled, "settled", 1],
336 [open, null, 2],
337 ],
338 );
339 }).pipe(Effect.provide(testLayer)),
340 );
341}
342
343for (const [name, testLayer] of [
344 ["sql", SqlLayer],
345 ["memory", ProjectionStore.layerMemory],
346] as const) {
347 it.effect(`${name}: an unsettled-only shell read skips settled threads`, () =>
348 Effect.gen(function* () {
349 const store = yield* ProjectionStore.ProjectionStoreV2;
350 const open = yield* createThread("unsettled-open");
351 const reopened = yield* createThread("unsettled-reopened", { settledOverride: "active" });
352 yield* createThread("unsettled-manual", { settledOverride: "settled", settledAt: old });
353 yield* createThread("unsettled-auto", { settledAt: old });
354 yield* createThread("unsettled-archived", { archivedAt: old });
355
356 const shell = yield* store.getShellSnapshot({ location: "active", unsettledOnly: true });
357 assert.deepEqual(
358 new Set(shell.threads.map((thread) => thread.id)),
359 new Set([open, reopened]),
360 );
361 assert.equal(shell.archivedThreads.length, 0);
362 const all = yield* store.getShellSnapshot({ location: "active" });
363 assert.equal(all.threads.length, 4);
364 }).pipe(Effect.provide(testLayer)),
365 );
366}
367
368it.effect(
369 "reads settlement candidates and thread metadata without loading historical or archived payloads",
370 () =>
371 Effect.gen(function* () {
372 const store = yield* ProjectionStore.ProjectionStoreV2;
373 const sql = yield* SqlClient.SqlClient;
374 const source = yield* createThread("historical-source", { archivedAt: old });
375 const sourceRun = yield* createRun(source);
376 const threadId = yield* createThread("fork", {
377 forkedFrom: { type: "run", threadId: source, runId: sourceRun },
378 });
379 const runId = yield* createRun(threadId);
380 yield* createItem(threadId, runId, "completed");
381 yield* sql`UPDATE orchestration_v2_projection_turn_items SET payload_json = '{broken' WHERE thread_id = ${threadId}`;
382 yield* sql`UPDATE orchestration_v2_projection_runs SET payload_json = '{broken' WHERE thread_id = ${source}`;
383 yield* sql`INSERT INTO orchestration_v2_projection_turn_items
384 SELECT 'history:' || value, i.thread_id, i.run_id, i.node_id, i.provider_thread_id, i.provider_turn_id,
385 i.parent_item_id, i.ordinal + value, i.type, i.status, i.updated_at, i.payload_json
386 FROM orchestration_v2_projection_turn_items i, json_each(${encodeNumbers(Array.from({ length: 2000 }, (_, i) => i + 1))})
387 WHERE i.thread_id = ${threadId}`;
388 const queries: Array<readonly [string, ReadonlyArray<unknown>]> = [];
389 const record: Statement.Transformer = (statement) =>
390 Effect.sync(() => {
391 queries.push(statement.compile());
392 return statement;
393 });
394 const candidates = yield* store
395 .getSettlementCandidates()
396 .pipe(Effect.provideService(Statement.CurrentTransformer, record));
397 assert.deepEqual(
398 candidates.map((thread) => thread.id),
399 [threadId],
400 );
401 assert.isTrue(queries.every(([query]) => !query.includes("COUNT(")));
402 const pendingQuery = queries.find(([query]) =>
403 query.includes("FROM orchestration_v2_projection_turn_items"),
404 );
405 assert.isDefined(pendingQuery);
406 const metadata = yield* store.getThread(threadId);
407 assert.equal(metadata.id, threadId);
408 assert.equal((yield* store.getThreadProjection(threadId).pipe(Effect.exit))._tag, "Failure");
409 const plan = yield* sql.unsafe<{ readonly detail: string }>(
410 `EXPLAIN QUERY PLAN ${pendingQuery![0]}`,
411 pendingQuery![1],
412 );
413 assert.isTrue(plan.some((row) => row.detail.includes("turn_items_shell_pending_idx")));
414 const countsPlan = yield* sql<{ readonly detail: string }>`EXPLAIN QUERY PLAN
415 SELECT thread_id, run_id, COUNT(*) FROM orchestration_v2_projection_turn_items
416 WHERE thread_id = ${threadId} AND run_id IS NOT NULL GROUP BY thread_id, run_id`;
417 assert.isTrue(
418 countsPlan.some((row) =>
419 row.detail.includes(
420 "COVERING INDEX orchestration_v2_projection_turn_items_thread_run_idx",
421 ),
422 ),
423 );
424 assert.isFalse(countsPlan.some((row) => row.detail.includes("TEMP B-TREE")));
425 const messagePlan = yield* sql<{ readonly detail: string }>`EXPLAIN QUERY PLAN
426 SELECT updated_at FROM orchestration_v2_projection_messages
427 WHERE thread_id = ${threadId} AND role = 'user' ORDER BY updated_at DESC, message_id DESC LIMIT 1`;
428 assert.isTrue(messagePlan.some((row) => row.detail.includes("messages_latest_user_idx")));
429 assert.isFalse(messagePlan.some((row) => row.detail.includes("TEMP B-TREE")));
430 }).pipe(Effect.provide(SqlLayer)),
431);
432
433it.effect("shell failure lookups stay on the thread's own turn items", () =>
434 Effect.gen(function* () {
435 const store = yield* ProjectionStore.ProjectionStoreV2;
436 const sql = yield* SqlClient.SqlClient;
437 const failed = yield* createThread("failed-latest");
438 yield* createRun(failed, "failed");
439 const queries: Array<readonly [string, ReadonlyArray<unknown>]> = [];
440 const record: Statement.Transformer = (statement) =>
441 Effect.sync(() => {
442 queries.push(statement.compile());
443 return statement;
444 });
445 const shell = yield* store
446 .getShellSnapshot()
447 .pipe(Effect.provideService(Statement.CurrentTransformer, record));
448 assert.deepEqual(
449 shell.threads.map((thread) => thread.id),
450 [failed],
451 );
452 const shellQuery = queries.find(([query]) =>
453 query.includes("AS blocking_failure_payload_json"),
454 );
455 assert.isDefined(shellQuery);
456 const plan = yield* sql.unsafe<{ readonly detail: string }>(
457 `EXPLAIN QUERY PLAN ${shellQuery![0]}`,
458 shellQuery![1],
459 );
460 // A failed run's root node is often null, and every runless item shares that
461 // node_id, so a node_ordinal lookup walks the whole history once per thread.
462 const itemLookups = plan.filter((row) => row.detail.startsWith("SEARCH item "));
463 assert.lengthOf(itemLookups, 2);
464 assert.isTrue(itemLookups.every((row) => row.detail.includes("turn_items_thread_run_idx")));
465 }).pipe(Effect.provide(SqlLayer)),
466);