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 ["auto-settle-disabled", { autoSettleDisabledAt: old }],
166 ] satisfies ReadonlyArray<readonly [string, Partial<OrchestrationV2AppThread>]>) {
167 yield* createRun(yield* createThread(name, overrides));
168 }
169 for (const status of ["preparing", "starting", "running", "waiting"] as const) {
170 yield* createRun(yield* createThread(status), status);
171 }
172 const queued = yield* createThread("queued");
173 yield* createRun(queued, "queued");
174 const blocked = yield* createThread("blocked");
175 yield* store.apply({
176 id: EventId.make("event:settlement:request"),
177 type: "runtime-request.updated",
178 threadId: blocked,
179 occurredAt: old,
180 payload: {
181 id: RuntimeRequestId.make("request:settlement"),
182 nodeId: NodeId.make("node:settlement"),
183 providerTurnId: null,
184 nativeRequestRef: null,
185 kind: "user_input",
186 status: "pending",
187 responseCapability: { type: "not_resumable", reason: "Process stopped" },
188 createdAt: old,
189 resolvedAt: null,
190 },
191 });
192 const recent = yield* createThread("recent-message");
193 yield* createRun(recent);
194 yield* store.apply({
195 id: EventId.make("event:settlement:message"),
196 type: "message.updated",
197 threadId: recent,
198 occurredAt: now,
199 payload: {
200 createdBy: "user",
201 creationSource: "web",
202 id: MessageId.make("message:settlement:recent"),
203 threadId: recent,
204 runId: null,
205 nodeId: null,
206 role: "user",
207 text: "Next turn",
208 attachments: [],
209 streaming: false,
210 createdAt: now,
211 updatedAt: now,
212 },
213 });
214 yield* createRun(
215 yield* createThread("snoozed", {
216 snoozedUntil: DateTime.add(now, { days: 1 }),
217 snoozedAt: now,
218 }),
219 );
220 const woke = yield* createThread("woke", {
221 snoozedUntil: DateTime.add(now, { days: 1 }),
222 snoozedAt: DateTime.subtract(old, { days: 1 }),
223 });
224 yield* createRun(woke);
225 const background = yield* createThread("idle-background");
226 yield* createItem(background, yield* createRun(background), "idle");
227 const persistent = yield* createThread("persistent-monitor");
228 yield* createItem(persistent, yield* createRun(persistent), "running", true);
229 const rolledBack = yield* createThread("rolled-back-background");
230 yield* createItem(rolledBack, yield* createRun(rolledBack, "rolled_back"), "running");
231 yield* createRun(rolledBack, "completed", 2);
232 const roster = yield* createThread("provider-roster");
233 yield* createRun(roster);
234 yield* store.apply({
235 id: EventId.make("event:settlement:roster"),
236 type: "provider-thread.updated",
237 threadId: roster,
238 occurredAt: old,
239 payload: {
240 id: ProviderThreadId.make("provider-thread:settlement"),
241 appThreadId: roster,
242 ownerNodeId: null,
243 driver: ProviderDriverKind.make("codex"),
244 providerInstanceId,
245 providerSessionId: null,
246 nativeThreadRef: null,
247 nativeConversationHeadRef: null,
248 status: "idle",
249 firstRunOrdinal: null,
250 lastRunOrdinal: null,
251 handoffIds: [],
252 forkedFrom: null,
253 createdAt: old,
254 updatedAt: old,
255 pendingBackgroundTasks: [{ taskId: "running-task" }],
256 },
257 });
258 const candidates = yield* store.getSettlementCandidates();
259 const shell = yield* store.getShellSnapshot({ location: "active" });
260 const eligible = candidates.filter((thread) =>
261 isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)),
262 );
263 assert.deepEqual(
264 new Set(eligible.map((thread) => thread.id)),
265 new Set([idle, completed, queued, woke, background, persistent, rolledBack]),
266 );
267 assert.deepEqual(
268 new Set(eligible.map((thread) => thread.id)),
269 new Set(
270 shell.threads
271 .filter((thread) => isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)))
272 .map((thread) => thread.id),
273 ),
274 );
275 for (const candidate of candidates) {
276 const expected = shell.threads.find((thread) => thread.id === candidate.id)!;
277 assert.deepEqual(candidate.pendingBackgroundTasks, expected.pendingBackgroundTasks);
278 const settings = {
279 pullRequest: null,
280 nowMs: DateTime.toEpochMillis(now),
281 autoSettleAfterDays: 7,
282 autoSettleOnMerge: false,
283 };
284 assert.deepEqual(
285 resolveAutoSettlementAt({ ...settings, thread: candidate }),
286 resolveAutoSettlementAt({ ...settings, thread: expected }),
287 );
288 }
289 assert.equal(
290 DateTime.formatIso((yield* store.getThread(completed)).createdAt),
291 DateTime.formatIso(old),
292 );
293 assert.equal(
294 (yield* store.getThread(ThreadId.make("missing")).pipe(Effect.flip))._tag,
295 "ProjectionStoreThreadNotFoundError",
296 );
297 }).pipe(Effect.provide(testLayer)),
298 );
299}
300
301it.effect(
302 "reads settlement candidates and thread metadata without loading historical or archived payloads",
303 () =>
304 Effect.gen(function* () {
305 const store = yield* ProjectionStoreV2;
306 const sql = yield* SqlClient.SqlClient;
307 const source = yield* createThread("historical-source", { archivedAt: old });
308 const sourceRun = yield* createRun(source);
309 const threadId = yield* createThread("fork", {
310 forkedFrom: { type: "run", threadId: source, runId: sourceRun },
311 });
312 const runId = yield* createRun(threadId);
313 yield* createItem(threadId, runId, "completed");
314 yield* sql`UPDATE orchestration_v2_projection_turn_items SET payload_json = '{broken' WHERE thread_id = ${threadId}`;
315 yield* sql`UPDATE orchestration_v2_projection_runs SET payload_json = '{broken' WHERE thread_id = ${source}`;
316 yield* sql`INSERT INTO orchestration_v2_projection_turn_items
317 SELECT 'history:' || value, i.thread_id, i.run_id, i.node_id, i.provider_thread_id, i.provider_turn_id,
318 i.parent_item_id, i.ordinal + value, i.type, i.status, i.updated_at, i.payload_json
319 FROM orchestration_v2_projection_turn_items i, json_each(${encodeNumbers(Array.from({ length: 2000 }, (_, i) => i + 1))})
320 WHERE i.thread_id = ${threadId}`;
321 const queries: Array<readonly [string, ReadonlyArray<unknown>]> = [];
322 const record: Statement.Transformer = (statement) =>
323 Effect.sync(() => {
324 queries.push(statement.compile());
325 return statement;
326 });
327 const candidates = yield* store
328 .getSettlementCandidates()
329 .pipe(Effect.provideService(Statement.CurrentTransformer, record));
330 assert.deepEqual(
331 candidates.map((thread) => thread.id),
332 [threadId],
333 );
334 assert.isTrue(queries.every(([query]) => !query.includes("COUNT(")));
335 const pendingQuery = queries.find(([query]) =>
336 query.includes("FROM orchestration_v2_projection_turn_items"),
337 );
338 assert.isDefined(pendingQuery);
339 const metadata = yield* store.getThread(threadId);
340 assert.equal(metadata.id, threadId);
341 assert.equal((yield* store.getThreadProjection(threadId).pipe(Effect.exit))._tag, "Failure");
342 const plan = yield* sql.unsafe<{ readonly detail: string }>(
343 `EXPLAIN QUERY PLAN ${pendingQuery![0]}`,
344 pendingQuery![1],
345 );
346 assert.isTrue(plan.some((row) => row.detail.includes("turn_items_shell_pending_idx")));
347 const countsPlan = yield* sql<{ readonly detail: string }>`EXPLAIN QUERY PLAN
348 SELECT thread_id, run_id, COUNT(*) FROM orchestration_v2_projection_turn_items
349 WHERE thread_id = ${threadId} AND run_id IS NOT NULL GROUP BY thread_id, run_id`;
350 assert.isTrue(
351 countsPlan.some((row) =>
352 row.detail.includes(
353 "COVERING INDEX orchestration_v2_projection_turn_items_thread_run_idx",
354 ),
355 ),
356 );
357 assert.isFalse(countsPlan.some((row) => row.detail.includes("TEMP B-TREE")));
358 const messagePlan = yield* sql<{ readonly detail: string }>`EXPLAIN QUERY PLAN
359 SELECT updated_at FROM orchestration_v2_projection_messages
360 WHERE thread_id = ${threadId} AND role = 'user' ORDER BY updated_at DESC, message_id DESC LIMIT 1`;
361 assert.isTrue(messagePlan.some((row) => row.detail.includes("messages_latest_user_idx")));
362 assert.isFalse(messagePlan.some((row) => row.detail.includes("TEMP B-TREE")));
363 }).pipe(Effect.provide(SqlLayer)),
364);