Open History to see the last commit
1import {
2 ProjectId,
3 ThreadId,
4 TurnId,
5 ProviderInstanceId,
6 OrchestrationProposedPlanId,
7} from "@t3tools/contracts";
8import { assert, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as SqlClient from "effect/unstable/sql/SqlClient";
13import * as Statement from "effect/unstable/sql/Statement";
14
15import { SqlitePersistenceMemory } from "./Sqlite.ts";
16import { ProjectionProjectRepositoryLive } from "./ProjectionProjects.ts";
17import { ProjectionThreadRepositoryLive } from "./ProjectionThreads.ts";
18import { ProjectionThreadProposedPlanRepositoryLive } from "./ProjectionThreadProposedPlans.ts";
19import { ProjectionProjectRepository } from "../Services/ProjectionProjects.ts";
20import { ProjectionThreadRepository } from "../Services/ProjectionThreads.ts";
21import { ProjectionThreadProposedPlanRepository } from "../Services/ProjectionThreadProposedPlans.ts";
22
23const projectionRepositoriesLayer = it.layer(
24 Layer.mergeAll(
25 ProjectionProjectRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
26 ProjectionThreadRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
27 ProjectionThreadProposedPlanRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
28 SqlitePersistenceMemory,
29 ),
30);
31
32projectionRepositoriesLayer("Projection repositories", (it) => {
33 it.effect("selects the latest-turn plan before checking implementation status", () =>
34 Effect.gen(function* () {
35 const plans = yield* ProjectionThreadProposedPlanRepository;
36 const threadId = ThreadId.make("thread-plan-status");
37 const latestTurnId = TurnId.make("turn-plan-status-current");
38 const firstPlan = {
39 planId: "plan-status-first",
40 threadId,
41 turnId: latestTurnId,
42 planMarkdown: "# First plan",
43 implementedAt: null,
44 implementationThreadId: null,
45 createdAt: "2026-03-24T00:00:01.000Z",
46 updatedAt: "2026-03-24T00:00:01.000Z",
47 };
48 yield* plans.upsert(firstPlan);
49 yield* plans.upsert({
50 ...firstPlan,
51 planId: "plan-status-implemented",
52 implementedAt: "2026-03-24T00:00:02.000Z",
53 createdAt: "2026-03-24T00:00:02.000Z",
54 updatedAt: "2026-03-24T00:00:02.000Z",
55 });
56 yield* plans.upsert({
57 ...firstPlan,
58 planId: "plan-status-other-turn",
59 turnId: TurnId.make("turn-plan-status-old"),
60 updatedAt: "2026-03-24T00:00:10.000Z",
61 });
62
63 assert.isFalse(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
64 assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }));
65
66 yield* plans.upsert({ ...firstPlan, updatedAt: "2026-03-24T00:00:03.000Z" });
67 assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
68 }),
69 );
70
71 it.effect("falls back within the thread when the latest turn has no plan", () =>
72 Effect.gen(function* () {
73 const plans = yield* ProjectionThreadProposedPlanRepository;
74 const threadId = ThreadId.make("thread-plan-fallback");
75 const latestTurnId = TurnId.make("turn-plan-fallback-missing");
76 assert.isFalse(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
77 assert.isFalse(yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }));
78
79 const firstPlan = {
80 planId: "plan-fallback-without-turn",
81 threadId,
82 turnId: null,
83 planMarkdown: "# Old plan",
84 implementedAt: "2026-03-24T00:00:01.000Z",
85 implementationThreadId: null,
86 createdAt: "2026-03-24T00:00:01.000Z",
87 updatedAt: "2026-03-24T00:00:01.000Z",
88 };
89 yield* plans.upsert(firstPlan);
90 yield* plans.upsert({
91 ...firstPlan,
92 planId: "plan-fallback-with-turn",
93 turnId: TurnId.make("turn-plan-fallback-old"),
94 implementedAt: null,
95 updatedAt: "2026-03-24T00:00:02.000Z",
96 });
97 yield* plans.upsert({
98 ...firstPlan,
99 planId: "plan-fallback-other-thread",
100 threadId: ThreadId.make("thread-plan-fallback-other"),
101 turnId: latestTurnId,
102 updatedAt: "2026-03-24T00:00:03.000Z",
103 });
104
105 assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
106 assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }));
107 }),
108 );
109
110 it.effect("preserves locale ordering and stable ties when selecting plan status", () =>
111 Effect.gen(function* () {
112 const plans = yield* ProjectionThreadProposedPlanRepository;
113 const timestamp = "2026-03-24T00:00:00.000Z";
114 const cases = [
115 {
116 name: "mixed-case-ids",
117 expected: "plan-A".localeCompare("plan-a") > 0,
118 rows: [
119 {
120 planId: "plan-a",
121 implementedAt: timestamp,
122 createdAt: timestamp,
123 updatedAt: timestamp,
124 },
125 { planId: "plan-A", implementedAt: null, createdAt: timestamp, updatedAt: timestamp },
126 ],
127 },
128 {
129 name: "equivalent-ids",
130 expected: true,
131 rows: [
132 {
133 planId: "plan-\u00e9",
134 implementedAt: timestamp,
135 createdAt: timestamp,
136 updatedAt: timestamp,
137 },
138 {
139 planId: "plan-e\u0301",
140 implementedAt: null,
141 createdAt: "2026-03-24T00:00:01.000Z",
142 updatedAt: timestamp,
143 },
144 ],
145 },
146 {
147 name: "timestamp-formats",
148 expected: "2026-03-24T00:00:00+00:00".localeCompare("2026-03-24T00:00:00-01:00") > 0,
149 rows: [
150 {
151 planId: "plan-minus",
152 implementedAt: timestamp,
153 createdAt: timestamp,
154 updatedAt: "2026-03-24T00:00:00-01:00",
155 },
156 {
157 planId: "plan-plus",
158 implementedAt: null,
159 createdAt: timestamp,
160 updatedAt: "2026-03-24T00:00:00+00:00",
161 },
162 ],
163 },
164 ];
165 for (const testCase of cases) {
166 const threadId = ThreadId.make(`thread-plan-order-${testCase.name}`);
167 const latestTurnId = TurnId.make(`turn-plan-order-${testCase.name}`);
168 for (const plan of testCase.rows) {
169 yield* plans.upsert({
170 ...plan,
171 planId: `${testCase.name}-${plan.planId}`,
172 threadId,
173 turnId: latestTurnId,
174 planMarkdown: "# Plan",
175 implementationThreadId: null,
176 });
177 }
178 assert.strictEqual(
179 yield* plans.hasActionableByThreadId({ threadId, latestTurnId }),
180 testCase.expected,
181 testCase.name,
182 );
183 assert.strictEqual(
184 yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }),
185 testCase.expected,
186 testCase.name,
187 );
188 }
189 }),
190 );
191
192 it.effect("returns only current-turn status metadata when old plans have large bodies", () =>
193 Effect.gen(function* () {
194 const plans = yield* ProjectionThreadProposedPlanRepository;
195 const sql = yield* SqlClient.SqlClient;
196 const threadId = ThreadId.make("thread-plan-metadata");
197 const latestTurnId = TurnId.make("turn-plan-metadata-current");
198 const updatedAt = "2026-03-24T00:00:00.000Z";
199 yield* sql`
200 WITH RECURSIVE history(n) AS (
201 SELECT 1 UNION ALL SELECT n + 1 FROM history WHERE n < 256
202 )
203 INSERT INTO projection_thread_proposed_plans (
204 plan_id, thread_id, turn_id, plan_markdown, implemented_at,
205 implementation_thread_id, created_at, updated_at
206 )
207 SELECT 'plan-metadata-old-' || n, ${threadId}, 'turn-plan-metadata-old',
208 ${"# Old plan\n".repeat(1024)}, ${updatedAt}, NULL, ${updatedAt}, ${updatedAt}
209 FROM history
210 `;
211 yield* plans.upsert({
212 planId: "plan-metadata-current",
213 threadId,
214 turnId: latestTurnId,
215 planMarkdown: "# Current plan",
216 implementedAt: null,
217 implementationThreadId: null,
218 createdAt: updatedAt,
219 updatedAt,
220 });
221 const statements: Array<Statement.Statement<unknown>> = [];
222 const actionable = yield* plans.hasActionableByThreadId({ threadId, latestTurnId }).pipe(
223 Effect.provideService(Statement.CurrentTransformer, (statement) => {
224 statements.push(statement);
225 return Effect.succeed(statement);
226 }),
227 );
228 assert.isTrue(actionable);
229 assert.strictEqual(statements.length, 1);
230 const statement = statements[0];
231 if (statement === undefined) return yield* Effect.die("Expected a plan status query.");
232 assert.deepEqual(yield* statement, [
233 { planId: "plan-metadata-current", implementedAt: null, updatedAt },
234 ]);
235 }),
236 );
237
238 it.effect("reads only the requested plan in its thread", () =>
239 Effect.gen(function* () {
240 const plans = yield* ProjectionThreadProposedPlanRepository;
241 const sql = yield* SqlClient.SqlClient;
242 const threadId = ThreadId.make("plan-query-thread");
243 const planId = OrchestrationProposedPlanId.make("plan-query-target");
244 yield* plans.upsert({
245 planId,
246 threadId,
247 turnId: null,
248 planMarkdown: "Keep this plan",
249 implementedAt: "2026-03-01T00:01:00.000Z",
250 implementationThreadId: ThreadId.make("implementation-thread"),
251 createdAt: "2026-03-01T00:00:00.000Z",
252 updatedAt: "2026-03-01T00:01:00.000Z",
253 });
254 // An unrelated old row must not be loaded or decoded by the exact lookup.
255 yield* sql`
256 INSERT INTO projection_thread_proposed_plans (
257 plan_id, thread_id, turn_id, plan_markdown, implemented_at,
258 implementation_thread_id, created_at, updated_at
259 ) VALUES (
260 'unrelated-plan', ${threadId}, NULL, '', NULL, NULL,
261 '2026-03-01T00:00:00.000Z', '2026-03-01T00:00:00.000Z'
262 )
263 `;
264 const plan = Option.getOrThrow(yield* plans.getByPlanId({ threadId, planId }));
265 assert.equal(plan.planMarkdown, "Keep this plan");
266 assert.equal(plan.implementedAt, "2026-03-01T00:01:00.000Z");
267 assert.isTrue(
268 Option.isNone(
269 yield* plans.getByPlanId({
270 threadId: ThreadId.make("another-thread"),
271 planId,
272 }),
273 ),
274 );
275 }),
276 );
277
278 it.effect("stores SQL NULL for missing project model options", () =>
279 Effect.gen(function* () {
280 const projects = yield* ProjectionProjectRepository;
281 const sql = yield* SqlClient.SqlClient;
282
283 yield* projects.upsert({
284 projectId: ProjectId.make("project-null-options"),
285 title: "Null options project",
286 workspaceRoot: "/tmp/project-null-options",
287 defaultModelSelection: {
288 instanceId: ProviderInstanceId.make("codex"),
289 model: "gpt-5.4",
290 },
291 defaultThreadEnvMode: null,
292 autoPull: false,
293 scripts: [],
294 createdAt: "2026-03-24T00:00:00.000Z",
295 updatedAt: "2026-03-24T00:00:00.000Z",
296 deletedAt: null,
297 });
298
299 const rows = yield* sql<{
300 readonly defaultModelSelection: string | null;
301 }>`
302 SELECT default_model_selection_json AS "defaultModelSelection"
303 FROM projection_projects
304 WHERE project_id = 'project-null-options'
305 `;
306 const row = rows[0];
307 if (!row) {
308 return yield* Effect.die("Expected projection_projects row to exist.");
309 }
310
311 assert.strictEqual(
312 row.defaultModelSelection,
313 // @effect-diagnostics-next-line preferSchemaOverJson:off
314 JSON.stringify({
315 instanceId: ProviderInstanceId.make("codex"),
316 model: "gpt-5.4",
317 }),
318 );
319
320 const persisted = yield* projects.getById({
321 projectId: ProjectId.make("project-null-options"),
322 });
323 assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
324 instanceId: ProviderInstanceId.make("codex"),
325 model: "gpt-5.4",
326 });
327 }),
328 );
329
330 it.effect("stores JSON for thread model options", () =>
331 Effect.gen(function* () {
332 const threads = yield* ProjectionThreadRepository;
333 const sql = yield* SqlClient.SqlClient;
334
335 yield* threads.upsert({
336 threadId: ThreadId.make("thread-null-options"),
337 projectId: ProjectId.make("project-null-options"),
338 title: "Null options thread",
339 modelSelection: {
340 instanceId: ProviderInstanceId.make("claudeAgent"),
341 model: "claude-opus-4-6",
342 },
343 runtimeMode: "full-access",
344 interactionMode: "default",
345 branch: null,
346 worktreePath: null,
347 latestTurnId: null,
348 createdAt: "2026-03-24T00:00:00.000Z",
349 updatedAt: "2026-03-24T00:00:00.000Z",
350 archivedAt: null,
351 settledOverride: null,
352 settledAt: null,
353 unsettledAt: null,
354 snoozedUntil: null,
355 snoozedAt: null,
356 pinnedAt: null,
357 latestUserMessageAt: null,
358 pendingApprovalCount: 0,
359 pendingUserInputCount: 0,
360 hasActionableProposedPlan: 0,
361 deletedAt: null,
362 });
363
364 const rows = yield* sql<{
365 readonly modelSelection: string | null;
366 }>`
367 SELECT model_selection_json AS "modelSelection"
368 FROM projection_threads
369 WHERE thread_id = 'thread-null-options'
370 `;
371 const row = rows[0];
372 if (!row) {
373 return yield* Effect.die("Expected projection_threads row to exist.");
374 }
375
376 assert.strictEqual(
377 row.modelSelection,
378 // @effect-diagnostics-next-line preferSchemaOverJson:off
379 JSON.stringify({
380 instanceId: ProviderInstanceId.make("claudeAgent"),
381 model: "claude-opus-4-6",
382 }),
383 );
384
385 const persisted = yield* threads.getById({
386 threadId: ThreadId.make("thread-null-options"),
387 });
388 assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
389 instanceId: ProviderInstanceId.make("claudeAgent"),
390 model: "claude-opus-4-6",
391 });
392 }),
393 );
394
395 it.effect("round-trips non-null settlement values through the thread row", () =>
396 Effect.gen(function* () {
397 const threads = yield* ProjectionThreadRepository;
398
399 yield* threads.upsert({
400 threadId: ThreadId.make("thread-settled"),
401 projectId: ProjectId.make("project-1"),
402 title: "Settled thread",
403 modelSelection: {
404 instanceId: ProviderInstanceId.make("codex"),
405 model: "gpt-5.4",
406 },
407 runtimeMode: "full-access",
408 interactionMode: "default",
409 branch: null,
410 worktreePath: null,
411 latestTurnId: null,
412 createdAt: "2026-03-24T00:00:00.000Z",
413 updatedAt: "2026-03-25T00:00:00.000Z",
414 archivedAt: null,
415 settledOverride: "settled",
416 settledAt: "2026-03-25T00:00:00.000Z",
417 unsettledAt: null,
418 snoozedUntil: "2026-03-26T09:00:00.000Z",
419 snoozedAt: "2026-03-25T00:00:00.000Z",
420 pinnedAt: "2026-03-25T00:00:00.000Z",
421 latestUserMessageAt: null,
422 pendingApprovalCount: 0,
423 pendingUserInputCount: 0,
424 hasActionableProposedPlan: 0,
425 deletedAt: null,
426 });
427
428 const persisted = yield* threads.getById({
429 threadId: ThreadId.make("thread-settled"),
430 });
431 const row = Option.getOrNull(persisted);
432 if (!row) {
433 return yield* Effect.die("Expected settled projection_threads row to exist.");
434 }
435 assert.strictEqual(row.settledOverride, "settled");
436 assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
437 assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
438 assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
439 assert.strictEqual(row.pinnedAt, "2026-03-25T00:00:00.000Z");
440
441 // Un-settle to the keep-active pin and wake the snooze; confirm the
442 // flips persist.
443 yield* threads.upsert({
444 ...row,
445 settledOverride: "active",
446 settledAt: null,
447 unsettledAt: "2026-03-26T00:00:00.000Z",
448 snoozedUntil: null,
449 snoozedAt: null,
450 pinnedAt: null,
451 });
452 const repersisted = yield* threads.getById({
453 threadId: ThreadId.make("thread-settled"),
454 });
455 const updated = Option.getOrNull(repersisted);
456 assert.strictEqual(updated?.settledOverride, "active");
457 assert.strictEqual(updated?.settledAt, null);
458 assert.strictEqual(updated?.unsettledAt, "2026-03-26T00:00:00.000Z");
459 assert.strictEqual(updated?.snoozedUntil, null);
460 assert.strictEqual(updated?.snoozedAt, null);
461 assert.strictEqual(updated?.pinnedAt, null);
462 }),
463 );
464
465 it.effect("round-trips manual and branch pull requests through the thread row", () =>
466 Effect.gen(function* () {
467 const threads = yield* ProjectionThreadRepository;
468 const linkedPullRequest = {
469 projectId: ProjectId.make("project-linked-pr"),
470 repository: "pingdotgg/t3code",
471 number: 42,
472 url: "https://github.com/pingdotgg/t3code/pull/42",
473 };
474 const branchPullRequest = {
475 ...linkedPullRequest,
476 number: 43,
477 url: "https://github.com/pingdotgg/t3code/pull/43",
478 };
479
480 yield* threads.upsert({
481 threadId: ThreadId.make("thread-linked-pr"),
482 projectId: ProjectId.make("project-linked-pr"),
483 title: "Linked pull request",
484 modelSelection: {
485 instanceId: ProviderInstanceId.make("codex"),
486 model: "gpt-5.4",
487 },
488 runtimeMode: "full-access",
489 interactionMode: "default",
490 branch: null,
491 worktreePath: null,
492 linkedPullRequest,
493 branchPullRequest,
494 latestTurnId: null,
495 createdAt: "2026-03-24T00:00:00.000Z",
496 updatedAt: "2026-03-24T00:00:00.000Z",
497 archivedAt: null,
498 settledOverride: null,
499 settledAt: null,
500 unsettledAt: null,
501 snoozedUntil: null,
502 snoozedAt: null,
503 pinnedAt: null,
504 latestUserMessageAt: null,
505 pendingApprovalCount: 0,
506 pendingUserInputCount: 0,
507 hasActionableProposedPlan: 0,
508 deletedAt: null,
509 });
510
511 const persisted = yield* threads.getById({ threadId: ThreadId.make("thread-linked-pr") });
512 assert.deepStrictEqual(Option.getOrNull(persisted)?.linkedPullRequest, linkedPullRequest);
513 assert.deepStrictEqual(Option.getOrNull(persisted)?.branchPullRequest, branchPullRequest);
514
515 const listed = yield* threads.listByProjectId({ projectId: linkedPullRequest.projectId });
516 assert.deepStrictEqual(listed[0]?.branchPullRequest, branchPullRequest);
517
518 const row = Option.getOrNull(persisted);
519 if (row === null) return yield* Effect.die("Expected linked thread row to exist.");
520 yield* threads.upsert({ ...row, linkedPullRequest: null });
521
522 const cleared = yield* threads.getById({ threadId: ThreadId.make("thread-linked-pr") });
523 assert.strictEqual(Option.getOrNull(cleared)?.linkedPullRequest, null);
524 assert.deepStrictEqual(Option.getOrNull(cleared)?.branchPullRequest, branchPullRequest);
525
526 yield* threads.upsert({ ...row, branchPullRequest: null });
527 const branchCleared = yield* threads.getById({ threadId: row.threadId });
528 assert.strictEqual(Option.getOrNull(branchCleared)?.branchPullRequest, null);
529 assert.deepStrictEqual(Option.getOrNull(branchCleared)?.linkedPullRequest, linkedPullRequest);
530 }),
531 );
532});