Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6import * as NodeSqlite from "node:sqlite";
7
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { assert, it } from "@effect/vitest";
10import { ThreadId } from "@t3tools/contracts";
11import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as SqlClient from "effect/sql/SqlClient";
15
16import * as ServerConfig from "../config.ts";
17import * as SqlitePersistence from "./Sqlite.ts";
18import { runMigrations } from "./Migrations.ts";
19import { initializeV2Database } from "./initializeV2Database.ts";
20import * as EventStore from "../orchestration-v2/EventStore.ts";
21import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
22import * as EventSink from "../orchestration-v2/EventSink.ts";
23import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
24
25it.effect(
26 "snapshots V1, imports transcripts lazily, and preserves both databases across switches",
27 () => {
28 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v1-v2-"));
29 const sourcePath = NodePath.join(directory, "state.sqlite");
30 const destinationPath = NodePath.join(directory, "statev2.sqlite");
31 const threadId = ThreadId.make("legacy-thread");
32 const seed = Effect.gen(function* () {
33 const sql = yield* SqlClient.SqlClient;
34 yield* runMigrations({ toMigrationInclusive: 52 });
35 yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at)
36 VALUES ('project', 'Project', '/tmp/project', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')`;
37 yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, created_at, updated_at)
38 VALUES (${threadId}, 'project', 'V1 thread', '{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', 'default', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')`;
39 for (let index = 0; index < 6; index++) {
40 yield* sql`INSERT INTO projection_thread_messages (message_id, thread_id, role, text, is_streaming, created_at, updated_at)
41 VALUES (${`message-${index}`}, ${threadId}, ${index % 2 ? "assistant" : "user"}, ${`Text ${index}`}, 0, ${`2026-01-0${index + 1}T00:00:00.000Z`}, ${`2026-01-0${index + 1}T00:00:00.000Z`})`;
42 }
43 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: sourcePath })));
44
45 return Effect.gen(function* () {
46 yield* seed;
47 const original = NodeFS.readFileSync(sourcePath);
48 const config = yield* ServerConfig.ServerConfig;
49 const layerDatabase = SqlitePersistence.layerConfig.pipe(
50 Layer.provide(ServerConfig.layer({ ...config, dbPath: destinationPath })),
51 );
52 const layerStores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(
53 Layer.provideMerge(layerDatabase),
54 );
55 const layerSink = EventSink.layer.pipe(Layer.provide(layerStores));
56 const layerImporter = LegacyV1ThreadImporter.layer.pipe(
57 Layer.provideMerge(Layer.mergeAll(layerStores, layerSink)),
58 );
59 yield* Effect.gen(function* () {
60 const sql = yield* SqlClient.SqlClient;
61 const legacy = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
62 yield* legacy.reconcileShells;
63 const projections = yield* ProjectionStore.ProjectionStoreV2;
64 const shell = yield* projections.getThreadProjection(threadId);
65 assert.equal(shell.thread.id, threadId);
66 assert.deepEqual(
67 shell.messages.map((message) => message.text),
68 ["Text 4", "Text 5"],
69 );
70 const pending =
71 yield* sql`SELECT transcript_imported_at FROM orchestration_v2_legacy_imports`;
72 assert.equal(pending[0]?.transcript_imported_at, null);
73 yield* legacy.ensureTranscript(threadId);
74 const transcript = yield* projections.getThreadProjection(threadId);
75 assert.deepEqual(
76 transcript.messages.map((message) => message.text),
77 ["Text 0", "Text 1", "Text 2", "Text 3", "Text 4", "Text 5"],
78 );
79 const imported =
80 yield* sql`SELECT imported_message_count, transcript_imported_at FROM orchestration_v2_legacy_imports`;
81 assert.equal(imported[0]?.imported_message_count, 6);
82 assert.isNotNull(imported[0]?.transcript_imported_at);
83 yield* sql`CREATE TABLE v2_work (text TEXT)`;
84 yield* sql`INSERT INTO v2_work VALUES ('Keep V2 work')`;
85 }).pipe(Effect.provide(layerImporter));
86 assert.deepEqual(NodeFS.readFileSync(sourcePath), original);
87 const v1 = new NodeSqlite.DatabaseSync(sourcePath);
88 try {
89 assert.equal(
90 v1.prepare("SELECT MAX(migration_id) AS id FROM effect_sql_migrations").get()?.id,
91 52,
92 );
93 assert.equal(
94 v1
95 .prepare(
96 "SELECT count(*) AS count FROM sqlite_master WHERE name = 'orchestration_v2_legacy_imports'",
97 )
98 .get()?.count,
99 0,
100 );
101 v1.exec("UPDATE projection_threads SET title = 'Continued in V1'");
102 } finally {
103 v1.close();
104 }
105 yield* Effect.gen(function* () {
106 const sql = yield* SqlClient.SqlClient;
107 assert.equal((yield* sql`SELECT text FROM v2_work`)[0]?.text, "Keep V2 work");
108 assert.equal((yield* sql`SELECT title FROM projection_threads`)[0]?.title, "V1 thread");
109 }).pipe(Effect.provide(layerDatabase));
110 }).pipe(
111 Effect.provide(
112 ServerConfig.layerTest(directory, directory).pipe(Layer.provideMerge(NodeServices.layer)),
113 ),
114 Effect.ensuring(
115 Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true })),
116 ),
117 );
118 },
119);
120
121it.effect("includes committed WAL data and does not publish a failed snapshot", () => {
122 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-snapshot-"));
123 const sourcePath = NodePath.join(directory, "state.sqlite");
124 const destinationPath = NodePath.join(directory, "statev2.sqlite");
125 return Effect.gen(function* () {
126 NodeFS.writeFileSync(sourcePath, "invalid SQLite");
127 assert.isTrue((yield* Effect.result(initializeV2Database(destinationPath)))._tag === "Failure");
128 assert.isFalse(NodeFS.existsSync(destinationPath));
129 NodeFS.unlinkSync(sourcePath);
130 const source = new NodeSqlite.DatabaseSync(sourcePath);
131 try {
132 source.exec(
133 "PRAGMA journal_mode=WAL; CREATE TABLE messages(text TEXT); INSERT INTO messages VALUES ('committed'); BEGIN; INSERT INTO messages VALUES ('uncommitted');",
134 );
135 yield* initializeV2Database(destinationPath);
136 const copy = new NodeSqlite.DatabaseSync(destinationPath, { readOnly: true });
137 try {
138 assert.deepEqual(
139 copy
140 .prepare("SELECT text FROM messages")
141 .all()
142 .map((row) => row.text),
143 ["committed"],
144 );
145 } finally {
146 copy.close();
147 }
148 source.exec("ROLLBACK");
149 } finally {
150 source.close();
151 }
152 }).pipe(
153 Effect.provide(NodeServices.layer),
154 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true }))),
155 );
156});
157
158it.effect("starts fresh without V1 and never imports over existing V2 state", () => {
159 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-fresh-"));
160 const destinationPath = NodePath.join(directory, "userdata", "statev2.sqlite");
161 return Effect.gen(function* () {
162 const config = yield* ServerConfig.ServerConfig;
163 const layerDatabase = SqlitePersistence.layerConfig.pipe(
164 Layer.provide(ServerConfig.layer({ ...config, dbPath: destinationPath })),
165 );
166 yield* Effect.gen(function* () {
167 const sql = yield* SqlClient.SqlClient;
168 yield* sql`CREATE TABLE v2_work (text TEXT)`;
169 yield* sql`INSERT INTO v2_work VALUES ('fresh V2 work')`;
170 }).pipe(Effect.provide(layerDatabase));
171 const sourcePath = NodePath.join(NodePath.dirname(destinationPath), "state.sqlite");
172 assert.isFalse(NodeFS.existsSync(sourcePath));
173 NodeFS.writeFileSync(sourcePath, "This source must never be opened once V2 exists");
174 yield* initializeV2Database(destinationPath);
175 yield* Effect.gen(function* () {
176 const sql = yield* SqlClient.SqlClient;
177 assert.equal((yield* sql`SELECT text FROM v2_work`)[0]?.text, "fresh V2 work");
178 }).pipe(Effect.provide(layerDatabase));
179 }).pipe(
180 Effect.provide(
181 ServerConfig.layerTest(directory, directory).pipe(Layer.provideMerge(NodeServices.layer)),
182 ),
183 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true }))),
184 );
185});
186
187it.effect("removes copies left by a killed start, but not one that is still running", () => {
188 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-abandoned-"));
189 const killed = NodeChildProcess.spawnSync(process.execPath, ["-e", ""]).pid;
190 const running = `.v2-import-${process.pid}-Kq81Zx`;
191 const unrelated = ".v2-import-not-a-copy";
192 return Effect.gen(function* () {
193 for (const name of [`.v2-import-${killed}-Wm3nPa`, ".v2-import-Q3xZ9a", running]) {
194 NodeFS.mkdirSync(NodePath.join(directory, name));
195 NodeFS.writeFileSync(NodePath.join(directory, name, "snapshot.sqlite"), "partial copy");
196 }
197 NodeFS.mkdirSync(NodePath.join(directory, unrelated));
198 const destinationPath = NodePath.join(directory, "statev2.sqlite");
199 NodeFS.writeFileSync(destinationPath, "existing V2 database");
200 yield* initializeV2Database(destinationPath);
201 assert.deepEqual(
202 NodeFS.readdirSync(directory).sort(),
203 [running, unrelated, "statev2.sqlite"].sort(),
204 );
205 assert.equal(NodeFS.readFileSync(destinationPath, "utf8"), "existing V2 database");
206 }).pipe(
207 Effect.provide(NodeServices.layer),
208 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(directory, { recursive: true, force: true }))),
209 );
210});