The best way to control Claude Code, Codex and more from any computer or phone

main
ts 219 lines 8.9 KB
Raw
1 import { assert, describe, it } from "@effect/vitest";
2 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import * as Effect from "effect/Effect";
5 import * as Exit from "effect/Exit";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Path from "effect/Path";
8 import * as SqlClient from "effect/sql/SqlClient";
9
10 import { migrationManifest, runMigrations } from "./Migrations.ts";
11
12 const v2Migrations = migrationManifest.filter(([id]) => id >= 55);
13 const newerMigrationId = Math.max(...migrationManifest.map(([id]) => id)) + 1;
14
15 const history = Effect.gen(function* () {
16 const sql = yield* SqlClient.SqlClient;
17 const rows = yield* sql<{ readonly migration_id: number; readonly name: string }>`
18 SELECT migration_id, name FROM effect_sql_migrations ORDER BY migration_id
19 `;
20 return rows.map((row) => [row.migration_id, row.name] as const);
21 });
22
23 const v2TableCount = Effect.gen(function* () {
24 const sql = yield* SqlClient.SqlClient;
25 const rows = yield* sql`
26 SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'orchestration_v2_%'
27 `;
28 return rows.length;
29 });
30
31 describe("runMigrations", () => {
32 it.effect("refuses to start when another migration took a V2 id", () =>
33 Effect.gen(function* () {
34 const sql = yield* SqlClient.SqlClient;
35 yield* runMigrations({ toMigrationInclusive: 54 });
36 yield* sql`
37 INSERT INTO effect_sql_migrations (migration_id, name) VALUES (55, 'FutureMainMigration')
38 `;
39 const before = yield* history;
40
41 assert.deepStrictEqual(yield* runMigrations({ toMigrationInclusive: 54 }), []);
42 const exit = yield* Effect.exit(runMigrations());
43
44 assert.isTrue(Exit.isFailure(exit));
45 assert.include(String(exit), "55_OrchestrationV2 (recorded: FutureMainMigration)");
46 assert.deepStrictEqual(yield* history, before);
47 assert.strictEqual(yield* v2TableCount, 0);
48 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
49 );
50
51 it.effect("refuses to start when a later id would skip V2 migrations", () =>
52 Effect.gen(function* () {
53 const sql = yield* SqlClient.SqlClient;
54 yield* runMigrations({ toMigrationInclusive: 54 });
55 yield* sql`
56 INSERT INTO effect_sql_migrations (migration_id, name)
57 VALUES (${newerMigrationId}, 'FutureMainMigration')
58 `;
59 const before = yield* history;
60
61 const exit = yield* Effect.exit(runMigrations());
62
63 assert.isTrue(Exit.isFailure(exit));
64 for (const [id, name] of v2Migrations) {
65 assert.include(String(exit), `${id}_${name} (recorded: nothing)`);
66 }
67 assert.deepStrictEqual(yield* history, before);
68 assert.strictEqual(yield* v2TableCount, 0);
69 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
70 );
71
72 it.effect("upgrades a database at exactly 54, then rechecks it without a write lock", () =>
73 Effect.gen(function* () {
74 const sql = yield* SqlClient.SqlClient;
75 yield* runMigrations({ toMigrationInclusive: 54 });
76 assert.deepStrictEqual(yield* runMigrations(), v2Migrations);
77 assert.deepStrictEqual(yield* history, migrationManifest);
78 assert.isAbove(yield* v2TableCount, 0);
79
80 // query_only rejects BEGIN IMMEDIATE, which CLI startup would otherwise take on the live database.
81 yield* sql`PRAGMA query_only = ON`;
82 assert.deepStrictEqual(yield* runMigrations(), []);
83 assert.deepStrictEqual(yield* history, migrationManifest);
84 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
85 );
86
87 it.effect("drops the unused correlation index and keeps correlation values", () =>
88 Effect.gen(function* () {
89 const sql = yield* SqlClient.SqlClient;
90 yield* runMigrations({ toMigrationInclusive: 54 });
91 yield* sql`
92 INSERT INTO orchestration_events (
93 event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
94 command_id, causation_event_id, correlation_id, actor_kind, payload_json, metadata_json
95 )
96 VALUES (
97 'event-1', 'thread', 'thread-1', 0, 'thread.created', '2026-01-01T00:00:00.000Z',
98 'command-1', NULL, 'correlation-1', 'client', '{}', '{}'
99 )
100 `;
101
102 yield* runMigrations();
103
104 const indexes = yield* sql<{ readonly name: string }>`
105 SELECT name FROM sqlite_master
106 WHERE type = 'index' AND tbl_name = 'orchestration_events' AND sql IS NOT NULL
107 `;
108 const indexNames = indexes.map((row) => row.name);
109 assert.notInclude(indexNames, "idx_orch_events_correlation_id");
110 for (const kept of [
111 "idx_orch_events_stream_version",
112 "idx_orch_events_stream_sequence",
113 "idx_orch_events_command_id",
114 "idx_orchestration_events_agent_stream_sequence",
115 ]) {
116 assert.include(indexNames, kept);
117 }
118 const events = yield* sql<{ readonly correlation_id: string | null }>`
119 SELECT correlation_id FROM orchestration_events WHERE event_id = 'event-1'
120 `;
121 assert.deepStrictEqual(events, [{ correlation_id: "correlation-1" }]);
122 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
123 );
124
125 it.effect.each([30, 54])("still starts with a site-local migration at id %s", (id) =>
126 Effect.gen(function* () {
127 const sql = yield* SqlClient.SqlClient;
128 yield* runMigrations({ toMigrationInclusive: 54 });
129 yield* sql`
130 UPDATE effect_sql_migrations SET name = 'SiteLocalMigration' WHERE migration_id = ${id}
131 `;
132
133 assert.deepStrictEqual(yield* runMigrations(), v2Migrations);
134 assert.isAbove(yield* v2TableCount, 0);
135 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
136 );
137
138 it.effect("only checks V2 migrations within the requested limit", () =>
139 Effect.gen(function* () {
140 const sql = yield* SqlClient.SqlClient;
141 yield* runMigrations({ toMigrationInclusive: 55 });
142 yield* sql`
143 INSERT INTO effect_sql_migrations (migration_id, name)
144 VALUES (56, 'SiteLocalMigration'), (${newerMigrationId}, 'NewerV2Migration')
145 `;
146 const before = yield* history;
147
148 assert.deepStrictEqual(yield* runMigrations({ toMigrationInclusive: 55 }), []);
149 const exit = yield* Effect.exit(runMigrations({ toMigrationInclusive: 56 }));
150 assert.isTrue(Exit.isFailure(exit));
151 assert.include(
152 String(exit),
153 "56_RemoveRedundantProjectionIndexes (recorded: SiteLocalMigration)",
154 );
155 assert.notInclude(String(exit), "57_ScheduledTaskWebhooks");
156 assert.deepStrictEqual(yield* history, before);
157 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
158 );
159
160 it.effect("keeps the migrations that finished before a later one failed", () =>
161 Effect.gen(function* () {
162 const sql = yield* SqlClient.SqlClient;
163 yield* runMigrations({ toMigrationInclusive: 81 });
164 yield* sql`CREATE TABLE orchestration_v2_projection_turn_item_counts (thread_id TEXT)`;
165
166 const exit = yield* Effect.exit(runMigrations());
167
168 assert.isTrue(Exit.isFailure(exit));
169 assert.deepStrictEqual(
170 yield* history,
171 migrationManifest.filter(([id]) => id <= 84),
172 );
173 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
174 );
175
176 it.effect("reapplies peer link migrations whose ledger rows are missing", () =>
177 Effect.gen(function* () {
178 const sql = yield* SqlClient.SqlClient;
179 yield* runMigrations({ toMigrationInclusive: 72 });
180 yield* sql`DELETE FROM effect_sql_migrations WHERE migration_id BETWEEN 70 AND 72`;
181
182 assert.deepStrictEqual(
183 yield* runMigrations(),
184 migrationManifest.filter(([id]) => id >= 70),
185 );
186 assert.deepStrictEqual(yield* history, migrationManifest);
187 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
188 );
189
190 it.effect("still starts after a newer build recorded a later V2 migration", () =>
191 Effect.gen(function* () {
192 const sql = yield* SqlClient.SqlClient;
193 yield* runMigrations();
194 yield* sql`
195 INSERT INTO effect_sql_migrations (migration_id, name)
196 VALUES (${newerMigrationId}, 'NewerV2Migration')
197 `;
198
199 assert.deepStrictEqual(yield* runMigrations(), []);
200 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
201 );
202 });
203
204 // The npm launcher reads the highest migration id from these file names.
205 it.effect("registers every migration file", () =>
206 Effect.gen(function* () {
207 const fs = yield* FileSystem.FileSystem;
208 const path = yield* Path.Path;
209 const dir = path.join(import.meta.dirname, "Migrations");
210 const files = (yield* fs.readDirectory(dir)).flatMap((name) => {
211 const match = /^(\d+)_(\w+)\.ts$/.exec(name);
212 return match ? [[Number(match[1]), match[2]] as const] : [];
213 });
214 assert.deepStrictEqual(
215 files.toSorted(([a], [b]) => a - b),
216 migrationManifest,
217 );
218 }).pipe(Effect.provide(NodeServices.layer)),
219 );