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 {
26 ProjectionStoreV2,
27 layer as projectionStoreLayer,
28 layerMemory,
29} from "./ProjectionStore.ts";
30import { isAutoSettlementCandidate, resolveAutoSettlementAt } from "./ThreadSettlementService.ts";
31
32const SqlLayer = projectionStoreLayer.pipe(Layer.provideMerge(SqlitePersistenceMemory));
33const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
34const old = DateTime.subtract(now, { days: 10 });
35const providerInstanceId = ProviderInstanceId.make("codex");
36const modelSelection = { instanceId: providerInstanceId, model: "test-model" };
37const encodeNumbers = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.Number)));
38
39const createThread = Effect.fn(function* (
40 name: string,
41 overrides: Partial<OrchestrationV2AppThread> = {},
42) {
43 const store = yield* ProjectionStoreV2;
44 const threadId = ThreadId.make(`thread:settlement:${name}`);
45 const thread: OrchestrationV2AppThread = {
46 createdBy: "user",
47 creationSource: "web",
48 id: threadId,
49 projectId: ProjectId.make("project:settlement"),
50 title: name,
51 providerInstanceId,
52 modelSelection,
53 runtimeMode: "full-access",
54 interactionMode: "default",
55 branch: "feature",
56 worktreePath: null,
57 activeProviderThreadId: null,
58 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
59 forkedFrom: null,
60 createdAt: old,
61 updatedAt: old,
62 archivedAt: null,
63 settledOverride: null,
64 settledAt: null,
65 lastVisitedAt: null,
66 deletedAt: null,
67 ...overrides,
68 };
69 yield* store.apply({
70 id: EventId.make(`event:${threadId}`),
71 type: "thread.created",
72 threadId,
73 occurredAt: old,
74 payload: thread,
75 });
76 return threadId;
77});
78
79const createRun = Effect.fn(function* (
80 threadId: ThreadId,
81 status: OrchestrationV2Run["status"] = "completed",
82 ordinal = 1,
83) {
84 const store = yield* ProjectionStoreV2;
85 const runId = RunId.make(`run:${threadId}:${ordinal}`);
86 yield* store.apply({
87 id: EventId.make(`event:${runId}`),
88 type: "run.created",
89 threadId,
90 occurredAt: old,
91 payload: {
92 id: runId,
93 threadId,
94 ordinal,
95 providerInstanceId,
96 modelSelection,
97 providerThreadId: null,
98 userMessageId: MessageId.make(`message:${runId}`),
99 rootNodeId: null,
100 activeAttemptId: null,
101 status,
102 requestedAt: old,
103 startedAt: status === "queued" ? null : old,
104 completedAt: ["completed", "rolled_back", "failed"].includes(status) ? old : null,
105 checkpointId: null,
106 contextHandoffId: null,
107 },
108 });
109 return runId;
110});
111
112const createItem = Effect.fn(function* (
113 threadId: ThreadId,
114 runId: RunId,
115 status: "idle" | "running" | "completed",
116 persistent = false,
117) {
118 const store = yield* ProjectionStoreV2;
119 yield* store.apply({
120 id: EventId.make(`event:item:${runId}`),
121 type: "turn-item.updated",
122 threadId,
123 occurredAt: old,
124 payload: {
125 id: TurnItemId.make(`item:${runId}`),
126 threadId,
127 runId,
128 nodeId: null,
129 providerThreadId: null,
130 providerTurnId: null,
131 nativeItemRef: null,
132 parentItemId: null,
133 ordinal: 1,
134 type: "dynamic_tool",
135 status,
136 title: null,
137 startedAt: old,
138 completedAt: status === "completed" ? old : null,
139 updatedAt: old,
140 toolName: "background",
141 input: persistent ? { persistent: true } : null,
142 output: null,
143 },
144 });
145});
146
147for (const [name, testLayer] of [
148 ["sql", SqlLayer],
149 ["memory", layerMemory],
150] as const) {
151 it.effect(
152 `${name}: discovers settlement work with the same activity and background semantics as the shell`,
153 () =>
154 Effect.gen(function* () {
155 const store = yield* ProjectionStoreV2;
156 const idle = yield* createThread("idle");
157 const completed = yield* createThread("completed");
158 yield* createRun(completed);
159 for (const [name, overrides] of [
160 ["archived", { archivedAt: old }],
161 ["deleted", { deletedAt: old }],
162 ["settled", { settledOverride: "settled" }],
163 ["unsettled", { settledOverride: "active" }],
164 ["pinned", { pinnedAt: old }],
165 ] satisfies ReadonlyArray<readonly [string, Partial<OrchestrationV2AppThread>]>) {
166 yield* createRun(yield* createThread(name, overrides));
167 }
168 for (const status of ["preparing", "starting", "running", "waiting"] as const) {
169 yield* createRun(yield* createThread(status), status);
170 }
171 const queued = yield* createThread("queued");
172 yield* createRun(queued, "queued");
173 const blocked = yield* createThread("blocked");
174 yield* store.apply({
175 id: EventId.make("event:settlement:request"),
176 type: "runtime-request.updated",
177 threadId: blocked,
178 occurredAt: old,
179 payload: {
180 id: RuntimeRequestId.make("request:settlement"),
181 nodeId: NodeId.make("node:settlement"),
182 providerTurnId: null,
183 nativeRequestRef: null,
184 kind: "user_input",
185 status: "pending",
186 responseCapability: { type: "not_resumable", reason: "Process stopped" },
187 createdAt: old,
188 resolvedAt: null,
189 },
190 });
191 const recent = yield* createThread("recent-message");
192 yield* createRun(recent);
193 yield* store.apply({
194 id: EventId.make("event:settlement:message"),
195 type: "message.updated",
196 threadId: recent,
197 occurredAt: now,
198 payload: {
199 createdBy: "user",
200 creationSource: "web",
201 id: MessageId.make("message:settlement:recent"),
202 threadId: recent,
203 runId: null,
204 nodeId: null,
205 role: "user",
206 text: "Next turn",
207 attachments: [],
208 streaming: false,
209 createdAt: now,
210 updatedAt: now,
211 },
212 });
213 yield* createRun(
214 yield* createThread("snoozed", {
215 snoozedUntil: DateTime.add(now, { days: 1 }),
216 snoozedAt: now,
217 }),
218 );
219 const woke = yield* createThread("woke", {
220 snoozedUntil: DateTime.add(now, { days: 1 }),
221 snoozedAt: DateTime.subtract(old, { days: 1 }),
222 });
223 yield* createRun(woke);
224 const background = yield* createThread("idle-background");
225 yield* createItem(background, yield* createRun(background), "idle");
226 const persistent = yield* createThread("persistent-monitor");
227 yield* createItem(persistent, yield* createRun(persistent), "running", true);
228 const rolledBack = yield* createThread("rolled-back-background");
229 yield* createItem(rolledBack, yield* createRun(rolledBack, "rolled_back"), "running");
230 yield* createRun(rolledBack, "completed", 2);
231 const roster = yield* createThread("provider-roster");
232 yield* createRun(roster);
233 yield* store.apply({
234 id: EventId.make("event:settlement:roster"),
235 type: "provider-thread.updated",
236 threadId: roster,
237 occurredAt: old,
238 payload: {
239 id: ProviderThreadId.make("provider-thread:settlement"),
240 appThreadId: roster,
241 ownerNodeId: null,
242 driver: ProviderDriverKind.make("codex"),
243 providerInstanceId,
244 providerSessionId: null,
245 nativeThreadRef: null,
246 nativeConversationHeadRef: null,
247 status: "idle",
248 firstRunOrdinal: null,
249 lastRunOrdinal: null,
250 handoffIds: [],
251 forkedFrom: null,
252 createdAt: old,
253 updatedAt: old,
254 pendingBackgroundTasks: [{ taskId: "running-task" }],
255 },
256 });
257 const candidates = yield* store.getSettlementCandidates();
258 const shell = yield* store.getShellSnapshot({ location: "active" });
259 const eligible = candidates.filter((thread) =>
260 isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)),
261 );
262 assert.deepEqual(
263 new Set(eligible.map((thread) => thread.id)),
264 new Set([idle, completed, queued, woke, persistent, rolledBack]),
265 );
266 assert.deepEqual(
267 new Set(eligible.map((thread) => thread.id)),
268 new Set(
269 shell.threads
270 .filter((thread) => isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)))
271 .map((thread) => thread.id),
272 ),
273 );
274 for (const candidate of candidates) {
275 const expected = shell.threads.find((thread) => thread.id === candidate.id)!;
276 assert.deepEqual(candidate.pendingBackgroundTasks, expected.pendingBackgroundTasks);
277 const settings = {
278 pullRequest: null,
279 nowMs: DateTime.toEpochMillis(now),
280 autoSettleAfterDays: 7,
281 autoSettleOnMerge: false,
282 };
283 assert.deepEqual(
284 resolveAutoSettlementAt({ ...settings, thread: candidate }),
285 resolveAutoSettlementAt({ ...settings, thread: expected }),
286 );
287 }
288 assert.equal(
289 DateTime.formatIso((yield* store.getThread(completed)).createdAt),
290 DateTime.formatIso(old),
291 );
292 assert.equal(
293 (yield* store.getThread(ThreadId.make("missing")).pipe(Effect.flip))._tag,
294 "ProjectionStoreThreadNotFoundError",
295 );
296 }).pipe(Effect.provide(testLayer)),
297 );
298}
299
300it.effect(
301 "reads settlement candidates and thread metadata without loading historical or archived payloads",
302 () =>
303 Effect.gen(function* () {
304 const store = yield* ProjectionStoreV2;
305 const sql = yield* SqlClient.SqlClient;
306 const source = yield* createThread("historical-source", { archivedAt: old });
307 const sourceRun = yield* createRun(source);
308 const threadId = yield* createThread("fork", {
309 forkedFrom: { type: "run", threadId: source, runId: sourceRun },
310 });
311 const runId = yield* createRun(threadId);
312 yield* createItem(threadId, runId, "completed");
313 yield* sql`UPDATE orchestration_v2_projection_turn_items SET payload_json = '{broken' WHERE thread_id = ${threadId}`;
314 yield* sql`UPDATE orchestration_v2_projection_runs SET payload_json = '{broken' WHERE thread_id = ${source}`;
315 yield* sql`INSERT INTO orchestration_v2_projection_turn_items
316 SELECT 'history:' || value, i.thread_id, i.run_id, i.node_id, i.provider_thread_id, i.provider_turn_id,
317 i.parent_item_id, i.ordinal + value, i.type, i.status, i.updated_at, i.payload_json
318 FROM orchestration_v2_projection_turn_items i, json_each(${encodeNumbers(Array.from({ length: 2000 }, (_, i) => i + 1))})
319 WHERE i.thread_id = ${threadId}`;
320 const queries: Array<readonly [string, ReadonlyArray<unknown>]> = [];
321 const record: Statement.Transformer = (statement) =>
322 Effect.sync(() => {
323 queries.push(statement.compile());
324 return statement;
325 });
326 const candidates = yield* store
327 .getSettlementCandidates()
328 .pipe(Effect.provideService(Statement.CurrentTransformer, record));
329 assert.deepEqual(
330 candidates.map((thread) => thread.id),
331 [threadId],
332 );
333 assert.isTrue(queries.every(([query]) => !query.includes("COUNT(")));
334 const pendingQuery = queries.find(([query]) =>
335 query.includes("FROM orchestration_v2_projection_turn_items"),
336 );
337 assert.isDefined(pendingQuery);
338 const metadata = yield* store.getThread(threadId);
339 assert.equal(metadata.id, threadId);
340 assert.equal((yield* store.getThreadProjection(threadId).pipe(Effect.exit))._tag, "Failure");
341 const plan = yield* sql.unsafe<{ readonly detail: string }>(
342 `EXPLAIN QUERY PLAN ${pendingQuery![0]}`,
343 pendingQuery![1],
344 );
345 assert.isTrue(plan.some((row) => row.detail.includes("turn_items_shell_pending_idx")));
346 const countsPlan = yield* sql<{ readonly detail: string }>`EXPLAIN QUERY PLAN
347 SELECT thread_id, run_id, COUNT(*) FROM orchestration_v2_projection_turn_items
348 WHERE thread_id = ${threadId} AND run_id IS NOT NULL GROUP BY thread_id, run_id`;
349 assert.isTrue(
350 countsPlan.some((row) =>
351 row.detail.includes(
352 "COVERING INDEX orchestration_v2_projection_turn_items_thread_run_idx",
353 ),
354 ),
355 );
356 assert.isFalse(countsPlan.some((row) => row.detail.includes("TEMP B-TREE")));
357 const messagePlan = yield* sql<{ readonly detail: string }>`EXPLAIN QUERY PLAN
358 SELECT updated_at FROM orchestration_v2_projection_messages
359 WHERE thread_id = ${threadId} AND role = 'user' ORDER BY updated_at DESC, message_id DESC LIMIT 1`;
360 assert.isTrue(messagePlan.some((row) => row.detail.includes("messages_latest_user_idx")));
361 assert.isFalse(messagePlan.some((row) => row.detail.includes("TEMP B-TREE")));
362 }).pipe(Effect.provide(SqlLayer)),
363);