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 * as ProjectionThreadPullRequests from "../ProjectionThreadPullRequests.ts";
19import { ProjectionProjectRepository } from "../Services/ProjectionProjects.ts";
20import { ProjectionThreadRepository } from "../Services/ProjectionThreads.ts";
21import {
22 ProjectionThreadPullRequestRepository,
23 type ProjectionThreadPullRequest,
24} from "../ProjectionThreadPullRequests.ts";
25import { ProjectionThreadProposedPlanRepositoryLive } from "./ProjectionThreadProposedPlans.ts";
26import { ProjectionThreadProposedPlanRepository } from "../Services/ProjectionThreadProposedPlans.ts";
27
28const projectionRepositoriesLayer = it.layer(
29 Layer.mergeAll(
30 ProjectionProjectRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
31 ProjectionThreadRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
32 ProjectionThreadPullRequests.layer.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
33 ProjectionThreadProposedPlanRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
34 SqlitePersistenceMemory,
35 ),
36);
37
38projectionRepositoriesLayer("Projection repositories", (it) => {
39 it.effect("selects the latest-turn plan before checking implementation status", () =>
40 Effect.gen(function* () {
41 const plans = yield* ProjectionThreadProposedPlanRepository;
42 const threadId = ThreadId.make("thread-plan-status");
43 const latestTurnId = TurnId.make("turn-plan-status-current");
44 const firstPlan = {
45 planId: "plan-status-first",
46 threadId,
47 turnId: latestTurnId,
48 planMarkdown: "# First plan",
49 implementedAt: null,
50 implementationThreadId: null,
51 createdAt: "2026-03-24T00:00:01.000Z",
52 updatedAt: "2026-03-24T00:00:01.000Z",
53 };
54 yield* plans.upsert(firstPlan);
55 yield* plans.upsert({
56 ...firstPlan,
57 planId: "plan-status-implemented",
58 implementedAt: "2026-03-24T00:00:02.000Z",
59 createdAt: "2026-03-24T00:00:02.000Z",
60 updatedAt: "2026-03-24T00:00:02.000Z",
61 });
62 yield* plans.upsert({
63 ...firstPlan,
64 planId: "plan-status-other-turn",
65 turnId: TurnId.make("turn-plan-status-old"),
66 updatedAt: "2026-03-24T00:00:10.000Z",
67 });
68
69 assert.isFalse(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
70 assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }));
71
72 yield* plans.upsert({ ...firstPlan, updatedAt: "2026-03-24T00:00:03.000Z" });
73 assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
74 }),
75 );
76
77 it.effect("falls back within the thread when the latest turn has no plan", () =>
78 Effect.gen(function* () {
79 const plans = yield* ProjectionThreadProposedPlanRepository;
80 const threadId = ThreadId.make("thread-plan-fallback");
81 const latestTurnId = TurnId.make("turn-plan-fallback-missing");
82 assert.isFalse(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
83 assert.isFalse(yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }));
84
85 const firstPlan = {
86 planId: "plan-fallback-without-turn",
87 threadId,
88 turnId: null,
89 planMarkdown: "# Old plan",
90 implementedAt: "2026-03-24T00:00:01.000Z",
91 implementationThreadId: null,
92 createdAt: "2026-03-24T00:00:01.000Z",
93 updatedAt: "2026-03-24T00:00:01.000Z",
94 };
95 yield* plans.upsert(firstPlan);
96 yield* plans.upsert({
97 ...firstPlan,
98 planId: "plan-fallback-with-turn",
99 turnId: TurnId.make("turn-plan-fallback-old"),
100 implementedAt: null,
101 updatedAt: "2026-03-24T00:00:02.000Z",
102 });
103 yield* plans.upsert({
104 ...firstPlan,
105 planId: "plan-fallback-other-thread",
106 threadId: ThreadId.make("thread-plan-fallback-other"),
107 turnId: latestTurnId,
108 updatedAt: "2026-03-24T00:00:03.000Z",
109 });
110
111 assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
112 assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }));
113 }),
114 );
115
116 it.effect("preserves locale ordering and stable ties when selecting plan status", () =>
117 Effect.gen(function* () {
118 const plans = yield* ProjectionThreadProposedPlanRepository;
119 const timestamp = "2026-03-24T00:00:00.000Z";
120 const cases = [
121 {
122 name: "mixed-case-ids",
123 expected: "plan-A".localeCompare("plan-a") > 0,
124 rows: [
125 {
126 planId: "plan-a",
127 implementedAt: timestamp,
128 createdAt: timestamp,
129 updatedAt: timestamp,
130 },
131 { planId: "plan-A", implementedAt: null, createdAt: timestamp, updatedAt: timestamp },
132 ],
133 },
134 {
135 name: "equivalent-ids",
136 expected: true,
137 rows: [
138 {
139 planId: "plan-\u00e9",
140 implementedAt: timestamp,
141 createdAt: timestamp,
142 updatedAt: timestamp,
143 },
144 {
145 planId: "plan-e\u0301",
146 implementedAt: null,
147 createdAt: "2026-03-24T00:00:01.000Z",
148 updatedAt: timestamp,
149 },
150 ],
151 },
152 {
153 name: "timestamp-formats",
154 expected: "2026-03-24T00:00:00+00:00".localeCompare("2026-03-24T00:00:00-01:00") > 0,
155 rows: [
156 {
157 planId: "plan-minus",
158 implementedAt: timestamp,
159 createdAt: timestamp,
160 updatedAt: "2026-03-24T00:00:00-01:00",
161 },
162 {
163 planId: "plan-plus",
164 implementedAt: null,
165 createdAt: timestamp,
166 updatedAt: "2026-03-24T00:00:00+00:00",
167 },
168 ],
169 },
170 ];
171 for (const testCase of cases) {
172 const threadId = ThreadId.make(`thread-plan-order-${testCase.name}`);
173 const latestTurnId = TurnId.make(`turn-plan-order-${testCase.name}`);
174 for (const plan of testCase.rows) {
175 yield* plans.upsert({
176 ...plan,
177 planId: `${testCase.name}-${plan.planId}`,
178 threadId,
179 turnId: latestTurnId,
180 planMarkdown: "# Plan",
181 implementationThreadId: null,
182 });
183 }
184 assert.strictEqual(
185 yield* plans.hasActionableByThreadId({ threadId, latestTurnId }),
186 testCase.expected,
187 testCase.name,
188 );
189 assert.strictEqual(
190 yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }),
191 testCase.expected,
192 testCase.name,
193 );
194 }
195 }),
196 );
197
198 it.effect("returns only current-turn status metadata when old plans have large bodies", () =>
199 Effect.gen(function* () {
200 const plans = yield* ProjectionThreadProposedPlanRepository;
201 const sql = yield* SqlClient.SqlClient;
202 const threadId = ThreadId.make("thread-plan-metadata");
203 const latestTurnId = TurnId.make("turn-plan-metadata-current");
204 const updatedAt = "2026-03-24T00:00:00.000Z";
205 yield* sql`
206 WITH RECURSIVE history(n) AS (
207 SELECT 1 UNION ALL SELECT n + 1 FROM history WHERE n < 256
208 )
209 INSERT INTO projection_thread_proposed_plans (
210 plan_id, thread_id, turn_id, plan_markdown, implemented_at,
211 implementation_thread_id, created_at, updated_at
212 )
213 SELECT 'plan-metadata-old-' || n, ${threadId}, 'turn-plan-metadata-old',
214 ${"# Old plan\n".repeat(1024)}, ${updatedAt}, NULL, ${updatedAt}, ${updatedAt}
215 FROM history
216 `;
217 yield* plans.upsert({
218 planId: "plan-metadata-current",
219 threadId,
220 turnId: latestTurnId,
221 planMarkdown: "# Current plan",
222 implementedAt: null,
223 implementationThreadId: null,
224 createdAt: updatedAt,
225 updatedAt,
226 });
227 const statements: Array<Statement.Statement<unknown>> = [];
228 const actionable = yield* plans.hasActionableByThreadId({ threadId, latestTurnId }).pipe(
229 Effect.provideService(Statement.CurrentTransformer, (statement) => {
230 statements.push(statement);
231 return Effect.succeed(statement);
232 }),
233 );
234 assert.isTrue(actionable);
235 assert.strictEqual(statements.length, 1);
236 const statement = statements[0];
237 if (statement === undefined) return yield* Effect.die("Expected a plan status query.");
238 assert.deepEqual(yield* statement, [
239 { planId: "plan-metadata-current", implementedAt: null, updatedAt },
240 ]);
241 }),
242 );
243
244 it.effect("reads only the requested plan in its thread", () =>
245 Effect.gen(function* () {
246 const plans = yield* ProjectionThreadProposedPlanRepository;
247 const sql = yield* SqlClient.SqlClient;
248 const threadId = ThreadId.make("plan-query-thread");
249 const planId = OrchestrationProposedPlanId.make("plan-query-target");
250 yield* plans.upsert({
251 planId,
252 threadId,
253 turnId: null,
254 planMarkdown: "Keep this plan",
255 implementedAt: "2026-03-01T00:01:00.000Z",
256 implementationThreadId: ThreadId.make("implementation-thread"),
257 createdAt: "2026-03-01T00:00:00.000Z",
258 updatedAt: "2026-03-01T00:01:00.000Z",
259 });
260 // An unrelated old row must not be loaded or decoded by the exact lookup.
261 yield* sql`
262 INSERT INTO projection_thread_proposed_plans (
263 plan_id, thread_id, turn_id, plan_markdown, implemented_at,
264 implementation_thread_id, created_at, updated_at
265 ) VALUES (
266 'unrelated-plan', ${threadId}, NULL, '', NULL, NULL,
267 '2026-03-01T00:00:00.000Z', '2026-03-01T00:00:00.000Z'
268 )
269 `;
270 const plan = Option.getOrThrow(yield* plans.getByPlanId({ threadId, planId }));
271 assert.equal(plan.planMarkdown, "Keep this plan");
272 assert.equal(plan.implementedAt, "2026-03-01T00:01:00.000Z");
273 assert.isTrue(
274 Option.isNone(
275 yield* plans.getByPlanId({
276 threadId: ThreadId.make("another-thread"),
277 planId,
278 }),
279 ),
280 );
281 }),
282 );
283
284 it.effect("stores SQL NULL for missing project model options", () =>
285 Effect.gen(function* () {
286 const projects = yield* ProjectionProjectRepository;
287 const sql = yield* SqlClient.SqlClient;
288
289 yield* projects.upsert({
290 projectId: ProjectId.make("project-null-options"),
291 title: "Null options project",
292 workspaceRoot: "/tmp/project-null-options",
293 defaultModelSelection: {
294 instanceId: ProviderInstanceId.make("codex"),
295 model: "gpt-5.4",
296 },
297 defaultThreadEnvMode: null,
298 autoPull: false,
299 scripts: [],
300 createdAt: "2026-03-24T00:00:00.000Z",
301 updatedAt: "2026-03-24T00:00:00.000Z",
302 deletedAt: null,
303 });
304
305 const rows = yield* sql<{
306 readonly defaultModelSelection: string | null;
307 }>`
308 SELECT default_model_selection_json AS "defaultModelSelection"
309 FROM projection_projects
310 WHERE project_id = 'project-null-options'
311 `;
312 const row = rows[0];
313 if (!row) {
314 return yield* Effect.die("Expected projection_projects row to exist.");
315 }
316
317 assert.strictEqual(
318 row.defaultModelSelection,
319 // @effect-diagnostics-next-line preferSchemaOverJson:off
320 JSON.stringify({
321 instanceId: ProviderInstanceId.make("codex"),
322 model: "gpt-5.4",
323 }),
324 );
325
326 const persisted = yield* projects.getById({
327 projectId: ProjectId.make("project-null-options"),
328 });
329 assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
330 instanceId: ProviderInstanceId.make("codex"),
331 model: "gpt-5.4",
332 });
333 }),
334 );
335
336 it.effect("stores JSON for thread model options", () =>
337 Effect.gen(function* () {
338 const threads = yield* ProjectionThreadRepository;
339 const sql = yield* SqlClient.SqlClient;
340
341 yield* threads.upsert({
342 threadId: ThreadId.make("thread-null-options"),
343 projectId: ProjectId.make("project-null-options"),
344 title: "Null options thread",
345 modelSelection: {
346 instanceId: ProviderInstanceId.make("claudeAgent"),
347 model: "claude-opus-4-6",
348 },
349 runtimeMode: "full-access",
350 interactionMode: "default",
351 branch: null,
352 worktreePath: null,
353 latestTurnId: null,
354 createdAt: "2026-03-24T00:00:00.000Z",
355 updatedAt: "2026-03-24T00:00:00.000Z",
356 archivedAt: null,
357 settledOverride: null,
358 settledAt: null,
359 unsettledAt: null,
360 snoozedUntil: null,
361 snoozedAt: null,
362 pinnedAt: null,
363 latestUserMessageAt: null,
364 pendingApprovalCount: 0,
365 pendingUserInputCount: 0,
366 hasActionableProposedPlan: 0,
367 deletedAt: null,
368 });
369
370 const rows = yield* sql<{
371 readonly modelSelection: string | null;
372 }>`
373 SELECT model_selection_json AS "modelSelection"
374 FROM projection_threads
375 WHERE thread_id = 'thread-null-options'
376 `;
377 const row = rows[0];
378 if (!row) {
379 return yield* Effect.die("Expected projection_threads row to exist.");
380 }
381
382 assert.strictEqual(
383 row.modelSelection,
384 // @effect-diagnostics-next-line preferSchemaOverJson:off
385 JSON.stringify({
386 instanceId: ProviderInstanceId.make("claudeAgent"),
387 model: "claude-opus-4-6",
388 }),
389 );
390
391 const persisted = yield* threads.getById({
392 threadId: ThreadId.make("thread-null-options"),
393 });
394 assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
395 instanceId: ProviderInstanceId.make("claudeAgent"),
396 model: "claude-opus-4-6",
397 });
398 }),
399 );
400
401 it.effect("round-trips non-null settlement values through the thread row", () =>
402 Effect.gen(function* () {
403 const threads = yield* ProjectionThreadRepository;
404
405 yield* threads.upsert({
406 threadId: ThreadId.make("thread-settled"),
407 projectId: ProjectId.make("project-1"),
408 title: "Settled thread",
409 modelSelection: {
410 instanceId: ProviderInstanceId.make("codex"),
411 model: "gpt-5.4",
412 },
413 runtimeMode: "full-access",
414 interactionMode: "default",
415 branch: null,
416 worktreePath: null,
417 latestTurnId: null,
418 createdAt: "2026-03-24T00:00:00.000Z",
419 updatedAt: "2026-03-25T00:00:00.000Z",
420 archivedAt: null,
421 settledOverride: "settled",
422 settledAt: "2026-03-25T00:00:00.000Z",
423 unsettledAt: null,
424 snoozedUntil: "2026-03-26T09:00:00.000Z",
425 snoozedAt: "2026-03-25T00:00:00.000Z",
426 pinnedAt: "2026-03-25T00:00:00.000Z",
427 latestUserMessageAt: null,
428 pendingApprovalCount: 0,
429 pendingUserInputCount: 0,
430 hasActionableProposedPlan: 0,
431 deletedAt: null,
432 });
433
434 const persisted = yield* threads.getById({
435 threadId: ThreadId.make("thread-settled"),
436 });
437 const row = Option.getOrNull(persisted);
438 if (!row) {
439 return yield* Effect.die("Expected settled projection_threads row to exist.");
440 }
441 assert.strictEqual(row.settledOverride, "settled");
442 assert.strictEqual(row.settledAt, "2026-03-25T00:00:00.000Z");
443 assert.strictEqual(row.snoozedUntil, "2026-03-26T09:00:00.000Z");
444 assert.strictEqual(row.snoozedAt, "2026-03-25T00:00:00.000Z");
445 assert.strictEqual(row.pinnedAt, "2026-03-25T00:00:00.000Z");
446
447 // Un-settle to the keep-active pin and wake the snooze; confirm the
448 // flips persist.
449 yield* threads.upsert({
450 ...row,
451 settledOverride: "active",
452 settledAt: null,
453 unsettledAt: "2026-03-26T00:00:00.000Z",
454 snoozedUntil: null,
455 snoozedAt: null,
456 pinnedAt: null,
457 });
458 const repersisted = yield* threads.getById({
459 threadId: ThreadId.make("thread-settled"),
460 });
461 const updated = Option.getOrNull(repersisted);
462 assert.strictEqual(updated?.settledOverride, "active");
463 assert.strictEqual(updated?.settledAt, null);
464 assert.strictEqual(updated?.unsettledAt, "2026-03-26T00:00:00.000Z");
465 assert.strictEqual(updated?.snoozedUntil, null);
466 assert.strictEqual(updated?.snoozedAt, null);
467 assert.strictEqual(updated?.pinnedAt, null);
468 }),
469 );
470
471 it.effect("round-trips manual and branch pull requests through the thread row", () =>
472 Effect.gen(function* () {
473 const threads = yield* ProjectionThreadRepository;
474 const linkedPullRequest = {
475 projectId: ProjectId.make("project-linked-pr"),
476 repository: "pingdotgg/t3code",
477 number: 42,
478 url: "https://github.com/pingdotgg/t3code/pull/42",
479 };
480 const branchPullRequest = {
481 ...linkedPullRequest,
482 number: 43,
483 url: "https://github.com/pingdotgg/t3code/pull/43",
484 };
485
486 yield* threads.upsert({
487 threadId: ThreadId.make("thread-linked-pr"),
488 projectId: ProjectId.make("project-linked-pr"),
489 title: "Linked pull request",
490 modelSelection: {
491 instanceId: ProviderInstanceId.make("codex"),
492 model: "gpt-5.4",
493 },
494 runtimeMode: "full-access",
495 interactionMode: "default",
496 branch: null,
497 worktreePath: null,
498 linkedPullRequest,
499 branchPullRequest,
500 latestTurnId: null,
501 createdAt: "2026-03-24T00:00:00.000Z",
502 updatedAt: "2026-03-24T00:00:00.000Z",
503 archivedAt: null,
504 settledOverride: null,
505 settledAt: null,
506 unsettledAt: null,
507 snoozedUntil: null,
508 snoozedAt: null,
509 pinnedAt: null,
510 latestUserMessageAt: null,
511 pendingApprovalCount: 0,
512 pendingUserInputCount: 0,
513 hasActionableProposedPlan: 0,
514 deletedAt: null,
515 });
516
517 const persisted = yield* threads.getById({ threadId: ThreadId.make("thread-linked-pr") });
518 assert.deepStrictEqual(Option.getOrNull(persisted)?.linkedPullRequest, linkedPullRequest);
519 assert.deepStrictEqual(Option.getOrNull(persisted)?.branchPullRequest, branchPullRequest);
520
521 const listed = yield* threads.listByProjectId({ projectId: linkedPullRequest.projectId });
522 assert.deepStrictEqual(listed[0]?.branchPullRequest, branchPullRequest);
523
524 const row = Option.getOrNull(persisted);
525 if (row === null) return yield* Effect.die("Expected linked thread row to exist.");
526 yield* threads.upsert({ ...row, linkedPullRequest: null });
527
528 const cleared = yield* threads.getById({ threadId: ThreadId.make("thread-linked-pr") });
529 assert.strictEqual(Option.getOrNull(cleared)?.linkedPullRequest, null);
530 assert.deepStrictEqual(Option.getOrNull(cleared)?.branchPullRequest, branchPullRequest);
531
532 yield* threads.upsert({ ...row, branchPullRequest: null });
533 const branchCleared = yield* threads.getById({ threadId: row.threadId });
534 assert.strictEqual(Option.getOrNull(branchCleared)?.branchPullRequest, null);
535 assert.deepStrictEqual(Option.getOrNull(branchCleared)?.linkedPullRequest, linkedPullRequest);
536 }),
537 );
538
539 it.effect("uses one Azure identity for repository writes, lookups, and deletion", () =>
540 Effect.gen(function* () {
541 const pullRequests = yield* ProjectionThreadPullRequestRepository;
542 const threadId = ThreadId.make("azure-alias-link");
543 const row: ProjectionThreadPullRequest = {
544 threadId,
545 host: "org.visualstudio.com",
546 repository: "project/_git/web",
547 number: 7,
548 url: "https://org.visualstudio.com/project/_git/web/pullrequest/7",
549 source: "manual",
550 linkedAt: "2026-09-09T00:00:00.000Z",
551 snapshot: null,
552 stack: null,
553 };
554 yield* pullRequests.upsert(row);
555 yield* pullRequests.upsert({
556 ...row,
557 host: "dev.azure.com",
558 repository: "org/project/_git/web",
559 });
560 const found = yield* pullRequests.listByPullRequest({
561 host: "ssh.dev.azure.com",
562 repository: "v3/org/project/web",
563 number: 7,
564 });
565 assert.deepStrictEqual(found, [
566 { ...row, host: "dev.azure.com", repository: "org/project/_git/web" },
567 ]);
568 assert.deepStrictEqual(
569 yield* pullRequests.listByPullRequest({
570 host: "dev.azure.com",
571 repository: "other/project/_git/web",
572 number: 7,
573 }),
574 [],
575 );
576 yield* pullRequests.delete({
577 threadId,
578 host: "vs-ssh.visualstudio.com",
579 repository: "v3/org/project/web",
580 number: 7,
581 });
582 assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId }), []);
583 }),
584 );
585
586 it.effect("round-trips pull request links with JSON snapshot and stack columns", () =>
587 Effect.gen(function* () {
588 const pullRequests = yield* ProjectionThreadPullRequestRepository;
589 const sql = yield* SqlClient.SqlClient;
590 const threadId = ThreadId.make("thread-pr-links");
591 const otherThreadId = ThreadId.make("thread-pr-links-other");
592
593 const unsynced: ProjectionThreadPullRequest = {
594 threadId,
595 host: "github.com",
596 repository: "pingdotgg/t3code",
597 number: 42,
598 url: "https://github.com/pingdotgg/t3code/pull/42",
599 source: "manual",
600 linkedAt: "2026-03-24T00:00:00.000Z",
601 snapshot: null,
602 stack: null,
603 };
604 const synced: ProjectionThreadPullRequest = {
605 threadId,
606 host: "github.com",
607 repository: "pingdotgg/t3code",
608 number: 7,
609 url: "https://github.com/pingdotgg/t3code/pull/7",
610 source: "stack",
611 linkedAt: "2026-03-23T00:00:00.000Z",
612 snapshot: {
613 state: "open",
614 title: "Add links",
615 headBranch: "feat/links",
616 baseBranch: "main",
617 isDraft: false,
618 updatedAt: "2026-03-23T01:00:00.000Z",
619 syncedAt: "2026-03-23T02:00:00.000Z",
620 },
621 stack: {
622 kind: "native",
623 id: "stack-1",
624 number: 1,
625 url: "https://github.com/pingdotgg/t3code/stack/1",
626 base: "main",
627 layers: [
628 { number: 7, headBranch: "feat/links", state: "open" },
629 { number: 42, headBranch: "feat/links-ui", state: "open" },
630 ],
631 },
632 };
633 const sharedOnOtherThread: ProjectionThreadPullRequest = {
634 ...unsynced,
635 threadId: otherThreadId,
636 source: "agent",
637 linkedAt: "2026-03-25T00:00:00.000Z",
638 };
639
640 yield* pullRequests.upsert(unsynced);
641 yield* pullRequests.upsert(synced);
642 yield* pullRequests.upsert(sharedOnOtherThread);
643
644 const rawRows = yield* sql<{
645 readonly number: number;
646 readonly snapshotJson: string | null;
647 readonly stackJson: string | null;
648 }>`
649 SELECT number, snapshot_json AS "snapshotJson", stack_json AS "stackJson"
650 FROM projection_thread_pull_requests
651 WHERE thread_id = ${threadId}
652 ORDER BY number ASC
653 `;
654 assert.strictEqual(rawRows[0]?.number, 7);
655 // @effect-diagnostics-next-line preferSchemaOverJson:off
656 assert.deepStrictEqual(JSON.parse(rawRows[0]?.snapshotJson ?? "null"), synced.snapshot);
657 // @effect-diagnostics-next-line preferSchemaOverJson:off
658 assert.deepStrictEqual(JSON.parse(rawRows[0]?.stackJson ?? "null"), synced.stack);
659 assert.strictEqual(rawRows[1]?.snapshotJson, null);
660 assert.strictEqual(rawRows[1]?.stackJson, null);
661
662 // Ordered by linked_at, then number.
663 assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId }), [synced, unsynced]);
664
665 // One pull request across threads, ordered by linked_at.
666 assert.deepStrictEqual(
667 yield* pullRequests.listByPullRequest({
668 host: "github.com",
669 repository: "pingdotgg/t3code",
670 number: 42,
671 }),
672 [unsynced, sharedOnOtherThread],
673 );
674
675 // Upsert on the composite key replaces snapshot and stack in place.
676 const resynced = { ...unsynced, snapshot: synced.snapshot, stack: null } as const;
677 yield* pullRequests.upsert(resynced);
678 assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId }), [synced, resynced]);
679
680 yield* pullRequests.delete({
681 threadId,
682 host: "github.com",
683 repository: "pingdotgg/t3code",
684 number: 7,
685 });
686 assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId }), [resynced]);
687
688 yield* pullRequests.deleteByThreadIdAndSource({ threadId, source: "manual" });
689 assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId }), []);
690 assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId: otherThreadId }), [
691 sharedOnOtherThread,
692 ]);
693
694 yield* pullRequests.deleteByThreadId({ threadId: otherThreadId });
695 assert.deepStrictEqual(yield* pullRequests.listByThreadId({ threadId: otherThreadId }), []);
696 }),
697 );
698});