database-migration.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. import { describe, expect, test } from "bun:test"
  2. import { $ } from "bun"
  3. import { fileURLToPath } from "url"
  4. import path from "path"
  5. import { SqliteClient } from "@effect/sql-sqlite-bun"
  6. import { EffectDrizzleSqlite } from "@opencode-ai/effect-drizzle-sqlite"
  7. import { Effect, Layer } from "effect"
  8. import { eq, inArray, sql } from "drizzle-orm"
  9. import { DatabaseMigration } from "@opencode-ai/core/database/migration"
  10. import { migrations } from "@opencode-ai/core/database/migration.gen"
  11. import sessionUsageMigration from "@opencode-ai/core/database/migration/20260510033149_session_usage"
  12. import normalizeStoragePathsMigration from "@opencode-ai/core/database/migration/20260601010001_normalize_storage_paths"
  13. import sessionMessageProjectionOrderMigration from "@opencode-ai/core/database/migration/20260603040000_session_message_projection_order"
  14. import eventSourcedSessionInputMigration from "@opencode-ai/core/database/migration/20260604172448_event_sourced_session_input"
  15. import contextEpochAgentMigration from "@opencode-ai/core/database/migration/20260605042240_add_context_epoch_agent"
  16. import simplifyIntegrationCredentialsMigration from "@opencode-ai/core/database/migration/20260611192811_lush_chimera"
  17. import simplifySessionInputMigration from "@opencode-ai/core/database/migration/20260622202450_simplify_session_input"
  18. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  19. import { LayerNode } from "@opencode-ai/core/effect/layer-node"
  20. import { EventV2 } from "@opencode-ai/core/event"
  21. import { ProjectV2 } from "@opencode-ai/core/project"
  22. import { ProjectTable } from "@opencode-ai/core/project/sql"
  23. import { AbsolutePath } from "@opencode-ai/core/schema"
  24. import { SessionSchema } from "@opencode-ai/core/session/schema"
  25. import { SessionTable } from "@opencode-ai/core/session/sql"
  26. import sessionMetadataMigration from "@opencode-ai/core/database/migration/20260511173437_session-metadata"
  27. import type { SqlClient as SqlClientService } from "effect/unstable/sql/SqlClient"
  28. import { Database } from "@opencode-ai/core/database/database"
  29. import { SessionProjector } from "@opencode-ai/core/session/projector"
  30. import { SessionV1 } from "@opencode-ai/core/v1/session"
  31. import { tmpdir } from "./fixture/tmpdir"
  32. const run = <A, E>(effect: Effect.Effect<A, E, SqlClientService>) =>
  33. Effect.runPromise(
  34. effect.pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:", disableWAL: true })), Effect.scoped),
  35. )
  36. const makeDb = EffectDrizzleSqlite.makeWithDefaults()
  37. describe("DatabaseMigration", () => {
  38. test("serializes concurrent embedded initialization for one database path", async () => {
  39. await using tmp = await tmpdir()
  40. const filename = path.join(tmp.path, "embedded.sqlite")
  41. const layers = [Database.layerFromPath(filename), Database.layerFromPath(filename)]
  42. await Effect.runPromise(
  43. Effect.all(
  44. layers.map((layer) => Effect.scoped(Layer.build(layer))),
  45. { concurrency: "unbounded" },
  46. ),
  47. )
  48. })
  49. if (process.platform === "linux") {
  50. test("declared schema has no ungenerated migrations", async () => {
  51. const result = await $`bun ${fileURLToPath(new URL("../script/migration.ts", import.meta.url))} --check`
  52. .quiet()
  53. .nothrow()
  54. expect(result.exitCode, result.stderr.toString()).toBe(0)
  55. expect(result.stdout.toString()).toContain("No schema changes, nothing to migrate")
  56. }, 30_000)
  57. }
  58. test("applies tracked migrations to an empty database", async () => {
  59. await run(
  60. Effect.gen(function* () {
  61. const db = yield* makeDb
  62. yield* DatabaseMigration.apply(db)
  63. expect(yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session'`)).toEqual({
  64. name: "session",
  65. })
  66. expect(
  67. yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_input'`),
  68. ).toEqual({ name: "session_input" })
  69. expect(
  70. yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_context_epoch'`),
  71. ).toEqual({ name: "session_context_epoch" })
  72. expect(
  73. yield* db.get(
  74. sql`SELECT name FROM pragma_table_info('session_context_epoch') WHERE name IN ('agent', 'replacement_seq', 'revision')`,
  75. ),
  76. ).toBeUndefined()
  77. expect(yield* db.get(sql`SELECT count(*) as count FROM migration`)).toEqual({ count: migrations.length })
  78. expect(
  79. yield* db.all(
  80. sql`SELECT name FROM sqlite_master WHERE type = 'index' AND name IN ('event_aggregate_seq_idx', 'event_aggregate_type_seq_idx', 'session_input_session_pending_seq_idx', 'session_input_session_pending_delivery_seq_idx', 'session_input_session_admitted_seq_idx', 'session_input_session_promoted_seq_idx', 'session_message_session_idx', 'session_message_session_type_idx', 'session_message_session_seq_idx', 'session_message_session_type_seq_idx', 'session_message_session_time_created_id_idx') ORDER BY name`,
  81. ),
  82. ).toEqual([
  83. { name: "event_aggregate_seq_idx" },
  84. { name: "event_aggregate_type_seq_idx" },
  85. { name: "session_input_session_admitted_seq_idx" },
  86. { name: "session_input_session_pending_delivery_seq_idx" },
  87. { name: "session_input_session_promoted_seq_idx" },
  88. { name: "session_message_session_seq_idx" },
  89. { name: "session_message_session_time_created_id_idx" },
  90. { name: "session_message_session_type_seq_idx" },
  91. ])
  92. }),
  93. )
  94. })
  95. test("rejects a non-empty database without a session table", async () => {
  96. await expect(
  97. run(
  98. Effect.gen(function* () {
  99. const db = yield* makeDb
  100. yield* db.run(sql`CREATE TABLE unrelated (id text PRIMARY KEY)`)
  101. yield* DatabaseMigration.apply(db)
  102. }),
  103. ),
  104. ).rejects.toThrow("Database is not empty and has no session table")
  105. })
  106. test("backfills existing Context Epoch rows to the build agent", async () => {
  107. await run(
  108. Effect.gen(function* () {
  109. const db = yield* makeDb
  110. yield* db.run(
  111. sql`CREATE TABLE session_context_epoch (session_id text PRIMARY KEY, baseline text NOT NULL, snapshot text NOT NULL, baseline_seq integer NOT NULL, replacement_seq integer, revision integer DEFAULT 0 NOT NULL)`,
  112. )
  113. yield* db.run(
  114. sql`INSERT INTO session_context_epoch (session_id, baseline, snapshot, baseline_seq) VALUES ('ses_existing', 'baseline', '{}', 0)`,
  115. )
  116. yield* DatabaseMigration.applyOnly(db, [contextEpochAgentMigration])
  117. expect(yield* db.get(sql`SELECT agent FROM session_context_epoch WHERE session_id = 'ses_existing'`)).toEqual({
  118. agent: "build",
  119. })
  120. }),
  121. )
  122. })
  123. test("keeps legacy credential fields nullable", async () => {
  124. await run(
  125. Effect.gen(function* () {
  126. const db = yield* makeDb
  127. yield* db.run(
  128. sql`CREATE TABLE credential (id text PRIMARY KEY, connector_id text NOT NULL, method_id text NOT NULL, label text NOT NULL, value text NOT NULL, active integer DEFAULT false NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL)`,
  129. )
  130. yield* db.run(
  131. sql`CREATE UNIQUE INDEX credential_connector_active_idx ON credential (connector_id) WHERE active = 1`,
  132. )
  133. yield* DatabaseMigration.applyOnly(db, [simplifyIntegrationCredentialsMigration])
  134. yield* db.run(
  135. sql`INSERT INTO credential (id, connector_id, method_id, label, value, active, time_created, time_updated) VALUES ('legacy', 'openai', 'oauth', 'Legacy', '{}', 1, 1, 1)`,
  136. )
  137. yield* db.run(
  138. sql`INSERT INTO credential (id, integration_id, label, value, time_created, time_updated) VALUES ('current', 'anthropic', 'Current', '{}', 2, 2)`,
  139. )
  140. expect(yield* db.get(sql`SELECT connector_id, method_id, active FROM credential WHERE id = 'current'`)).toEqual(
  141. { connector_id: null, method_id: null, active: null },
  142. )
  143. }),
  144. )
  145. })
  146. test("resets beta history and rebuilds event-sourced Session input storage", async () => {
  147. await run(
  148. Effect.gen(function* () {
  149. const db = yield* makeDb
  150. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, workspace_id text)`)
  151. yield* db.run(sql`CREATE TABLE workspace (id text PRIMARY KEY)`)
  152. yield* db.run(sql`CREATE TABLE message (id text PRIMARY KEY)`)
  153. yield* db.run(sql`CREATE TABLE part (id text PRIMARY KEY)`)
  154. yield* db.run(sql`CREATE TABLE event_sequence (aggregate_id text PRIMARY KEY, seq integer NOT NULL)`)
  155. yield* db.run(
  156. sql`CREATE TABLE event (id text PRIMARY KEY, aggregate_id text NOT NULL, seq integer NOT NULL, type text NOT NULL, data text NOT NULL)`,
  157. )
  158. yield* db.run(sql`CREATE INDEX event_aggregate_seq_idx ON event (aggregate_id, seq)`)
  159. yield* db.run(sql`CREATE INDEX event_aggregate_type_seq_idx ON event (aggregate_id, type, seq)`)
  160. yield* db.run(
  161. sql`CREATE TABLE session_message (id text PRIMARY KEY, session_id text NOT NULL, type text NOT NULL, seq integer NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  162. )
  163. yield* db.run(sql`CREATE INDEX session_message_session_seq_idx ON session_message (session_id, seq)`)
  164. yield* db.run(
  165. sql`CREATE TABLE session_input (seq integer PRIMARY KEY AUTOINCREMENT, id text NOT NULL UNIQUE, session_id text NOT NULL, prompt text NOT NULL, delivery text NOT NULL, promoted_seq integer, time_created integer NOT NULL)`,
  166. )
  167. yield* db.run(
  168. sql`CREATE INDEX session_input_session_pending_delivery_seq_idx ON session_input (session_id, promoted_seq, delivery, seq)`,
  169. )
  170. yield* db.run(sql`INSERT INTO session (id, workspace_id) VALUES ('session', 'wrk_old')`)
  171. yield* db.run(sql`INSERT INTO workspace (id) VALUES ('wrk_old')`)
  172. yield* db.run(sql`INSERT INTO message (id) VALUES ('message')`)
  173. yield* db.run(sql`INSERT INTO part (id) VALUES ('part')`)
  174. yield* db.run(sql`INSERT INTO event_sequence (aggregate_id, seq) VALUES ('session', 0)`)
  175. yield* db.run(
  176. sql`INSERT INTO event (id, aggregate_id, seq, type, data) VALUES ('evt_old', 'session', 0, 'old.1', '{}')`,
  177. )
  178. yield* db.run(
  179. sql`INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES ('msg_old', 'session', 'user', 0, 1, 1, '{}')`,
  180. )
  181. yield* db.run(
  182. sql`INSERT INTO session_input (id, session_id, prompt, delivery, time_created) VALUES ('msg_pending', 'session', '{}', 'steer', 1)`,
  183. )
  184. yield* DatabaseMigration.applyOnly(db, [eventSourcedSessionInputMigration])
  185. expect(yield* db.all(sql`SELECT id, workspace_id FROM session`)).toEqual([
  186. { id: "session", workspace_id: null },
  187. ])
  188. expect(yield* db.all(sql`SELECT id FROM workspace`)).toEqual([])
  189. expect(yield* db.all(sql`SELECT id FROM message`)).toEqual([{ id: "message" }])
  190. expect(yield* db.all(sql`SELECT id FROM part`)).toEqual([{ id: "part" }])
  191. expect(yield* db.all(sql`SELECT id FROM event`)).toEqual([])
  192. expect(yield* db.all(sql`SELECT aggregate_id FROM event_sequence`)).toEqual([])
  193. expect(yield* db.all(sql`SELECT id FROM session_message`)).toEqual([])
  194. expect(yield* db.all(sql`SELECT id FROM session_input`)).toEqual([])
  195. expect(
  196. (yield* db.all<{ name: string }>(sql`PRAGMA table_info(session_input)`)).map((column) => column.name),
  197. ).toEqual(["id", "session_id", "prompt", "delivery", "admitted_seq", "promoted_seq", "time_created"])
  198. expect(
  199. (yield* db.all<{ name: string; unique: number }>(sql`PRAGMA index_list(session_message)`)).find(
  200. (index) => index.name === "session_message_session_seq_idx",
  201. ),
  202. ).toMatchObject({ unique: 1 })
  203. expect(
  204. (yield* db.all<{ name: string; unique: number }>(sql`PRAGMA index_list(event)`)).find(
  205. (index) => index.name === "event_aggregate_seq_idx",
  206. ),
  207. ).toMatchObject({ unique: 1 })
  208. expect(
  209. (yield* db.all<{ name: string; unique: number }>(sql`PRAGMA index_list(session_input)`)).filter((index) =>
  210. ["session_input_session_admitted_seq_idx", "session_input_session_promoted_seq_idx"].includes(index.name),
  211. ),
  212. ).toEqual([
  213. expect.objectContaining({ name: "session_input_session_promoted_seq_idx", unique: 1 }),
  214. expect.objectContaining({ name: "session_input_session_admitted_seq_idx", unique: 1 }),
  215. ])
  216. }),
  217. )
  218. })
  219. test("preserves canonical V1 state and restarts its event stream", async () => {
  220. await run(
  221. Effect.gen(function* () {
  222. const db = yield* makeDb
  223. yield* db.run(sql`PRAGMA foreign_keys = ON`)
  224. yield* DatabaseMigration.apply(db)
  225. yield* db.run(
  226. sql`INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES ('global', '/project', 1, 1, '[]')`,
  227. )
  228. yield* db.run(
  229. sql`INSERT INTO workspace (id, type, project_id, time_used) VALUES ('workspace', 'local', 'global', 1)`,
  230. )
  231. yield* db.run(
  232. sql`INSERT INTO session (id, project_id, workspace_id, slug, directory, title, version, time_created, time_updated) VALUES ('session', 'global', 'workspace', 'session', '/project', 'Before', 'test', 1, 1)`,
  233. )
  234. yield* db.run(
  235. sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES ('message', 'session', 1, 1, '{}')`,
  236. )
  237. yield* db.run(
  238. sql`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES ('part', 'message', 'session', 1, 1, '{}')`,
  239. )
  240. yield* db.run(sql`INSERT INTO event_sequence (aggregate_id, seq) VALUES ('session', 9)`)
  241. yield* db.run(
  242. sql`INSERT INTO event (id, aggregate_id, seq, type, data) VALUES ('event', 'session', 9, 'session.updated.1', '{}')`,
  243. )
  244. yield* db.run(
  245. sql`INSERT INTO session_input (id, session_id, prompt, delivery, admitted_seq, time_created) VALUES ('input', 'session', '{}', 'steer', 9, 1)`,
  246. )
  247. yield* db.run(
  248. sql`INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES ('projected', 'session', 'user', 9, 1, 1, '{}')`,
  249. )
  250. yield* db.run(
  251. sql`INSERT INTO session_context_epoch (session_id, baseline, snapshot, baseline_seq) VALUES ('session', 'baseline', '{}', 9)`,
  252. )
  253. yield* db.run(sql`DELETE FROM migration WHERE id = ${simplifySessionInputMigration.id}`)
  254. yield* DatabaseMigration.applyOnly(db, [simplifySessionInputMigration])
  255. const database = Layer.succeed(Database.Service, { db })
  256. yield* EventV2.Service.use((service) =>
  257. service.publish(SessionV1.Event.Updated, {
  258. sessionID: SessionSchema.ID.make("session"),
  259. info: {
  260. id: SessionSchema.ID.make("session"),
  261. slug: "session",
  262. projectID: ProjectV2.ID.global,
  263. directory: "/project",
  264. title: "After",
  265. version: "test",
  266. time: { created: 1, updated: 2 },
  267. },
  268. }),
  269. ).pipe(
  270. Effect.provide(
  271. AppNodeBuilder.build(LayerNode.group([EventV2.node, SessionProjector.node]), [[Database.node, database]]),
  272. ),
  273. )
  274. expect(
  275. yield* db.get(sql`
  276. SELECT
  277. (SELECT title FROM session WHERE id = 'session') AS title,
  278. (SELECT workspace_id FROM session WHERE id = 'session') AS workspaceID,
  279. (SELECT COUNT(*) FROM message WHERE id = 'message') AS messages,
  280. (SELECT COUNT(*) FROM part WHERE id = 'part') AS parts,
  281. (SELECT COUNT(*) FROM workspace) AS workspaces,
  282. (SELECT COUNT(*) FROM session_input) AS sessionInputs,
  283. (SELECT COUNT(*) FROM session_message) AS sessionMessages,
  284. (SELECT COUNT(*) FROM session_context_epoch) AS contextEpochs,
  285. (SELECT seq FROM event_sequence WHERE aggregate_id = 'session') AS seq,
  286. (SELECT type FROM event WHERE aggregate_id = 'session') AS eventType
  287. `),
  288. ).toEqual({
  289. title: "After",
  290. workspaceID: null,
  291. messages: 1,
  292. parts: 1,
  293. workspaces: 0,
  294. sessionInputs: 0,
  295. sessionMessages: 0,
  296. contextEpochs: 0,
  297. seq: 0,
  298. eventType: "session.updated.1",
  299. })
  300. }),
  301. )
  302. })
  303. test("resets incompatible projected Session messages before adding sequence order", async () => {
  304. await run(
  305. Effect.gen(function* () {
  306. const db = yield* makeDb
  307. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY)`)
  308. yield* db.run(
  309. sql`CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  310. )
  311. yield* db.run(
  312. sql`CREATE TABLE part (id text PRIMARY KEY, message_id text NOT NULL, session_id text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  313. )
  314. yield* db.run(sql`CREATE TABLE event (id text PRIMARY KEY, seq integer NOT NULL)`)
  315. yield* db.run(
  316. sql`CREATE TABLE session_message (id text PRIMARY KEY, session_id text NOT NULL, type text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  317. )
  318. yield* db.run(
  319. sql`CREATE INDEX session_message_session_time_created_id_idx ON session_message (session_id, time_created, id)`,
  320. )
  321. yield* db.run(
  322. sql`CREATE INDEX session_message_session_type_time_created_id_idx ON session_message (session_id, type, time_created, id)`,
  323. )
  324. yield* db.run(sql`INSERT INTO session (id) VALUES ('session')`)
  325. yield* db.run(
  326. sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES ('legacy_message', 'session', 1, 1, '{"role":"user"}')`,
  327. )
  328. yield* db.run(
  329. sql`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES ('legacy_part', 'legacy_message', 'session', 1, 1, '{"type":"text","text":"hello"}')`,
  330. )
  331. yield* db.run(
  332. sql`INSERT INTO session_message (id, session_id, type, time_created, time_updated, data) VALUES ('stale_projection', 'session', 'user', 1, 1, '{}')`,
  333. )
  334. yield* DatabaseMigration.applyOnly(db, [sessionMessageProjectionOrderMigration])
  335. expect(yield* db.all(sql`SELECT id, session_id, data FROM message`)).toEqual([
  336. { id: "legacy_message", session_id: "session", data: '{"role":"user"}' },
  337. ])
  338. expect(yield* db.all(sql`SELECT id, message_id, session_id, data FROM part`)).toEqual([
  339. {
  340. id: "legacy_part",
  341. message_id: "legacy_message",
  342. session_id: "session",
  343. data: '{"type":"text","text":"hello"}',
  344. },
  345. ])
  346. expect(yield* db.all(sql`SELECT id FROM session_message`)).toEqual([])
  347. yield* db.run(
  348. sql`INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES ('fresh_projection', 'session', 'user', 7, 2, 2, '{}')`,
  349. )
  350. expect(yield* db.get(sql`SELECT id, seq FROM session_message`)).toEqual({ id: "fresh_projection", seq: 7 })
  351. }),
  352. )
  353. })
  354. test("runs session usage backfill in order with schema changes", async () => {
  355. await run(
  356. Effect.gen(function* () {
  357. const db = yield* makeDb
  358. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, time_updated integer NOT NULL)`)
  359. yield* db.run(sql`CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, data text NOT NULL)`)
  360. yield* db.run(sql`INSERT INTO session (id, time_updated) VALUES ('session_1', 1)`)
  361. yield* db.run(
  362. sql`INSERT INTO message (id, session_id, data) VALUES ('message_1', 'session_1', '{"role":"assistant","cost":1.25,"tokens":{"input":2,"output":3,"reasoning":4,"cache":{"read":5,"write":6}}}')`,
  363. )
  364. yield* DatabaseMigration.applyOnly(db, [sessionUsageMigration])
  365. expect(
  366. yield* db.get(
  367. sql`SELECT cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = 'session_1'`,
  368. ),
  369. ).toEqual({
  370. cost: 1.25,
  371. tokens_input: 2,
  372. tokens_output: 3,
  373. tokens_reasoning: 4,
  374. tokens_cache_read: 5,
  375. tokens_cache_write: 6,
  376. })
  377. }),
  378. )
  379. })
  380. test("normalizes Windows storage paths and leaves POSIX paths untouched", async () => {
  381. await run(
  382. Effect.gen(function* () {
  383. const db = yield* makeDb
  384. yield* db.run(sql`CREATE TABLE project (id text PRIMARY KEY, worktree text NOT NULL, sandboxes text NOT NULL)`)
  385. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, directory text NOT NULL, path text)`)
  386. // Windows-shaped rows (drive + backslash) must be normalized.
  387. yield* db.run(
  388. sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"win"}, ${"C:\\Repo\\Thing"}, ${JSON.stringify([
  389. "C:\\Repo\\Thing\\sandbox",
  390. ])})`,
  391. )
  392. yield* db.run(
  393. sql`INSERT INTO session (id, directory, path) VALUES (${"win"}, ${"C:\\Repo\\Thing\\packages\\api"}, ${"packages\\api"})`,
  394. )
  395. // UNC worktrees and their sandboxes must normalize too (not just drive paths).
  396. yield* db.run(
  397. sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"unc"}, ${"\\\\server\\share"}, ${JSON.stringify([
  398. "\\\\server\\share\\sandbox",
  399. ])})`,
  400. )
  401. // The "/" worktree sentinel and POSIX paths (including a pathological
  402. // backslash in a POSIX filename) must survive byte-for-byte.
  403. yield* db.run(sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"global"}, ${"/"}, ${"[]"})`)
  404. yield* db.run(
  405. sql`INSERT INTO session (id, directory, path) VALUES (${"posix"}, ${"/home/me/we\\ird"}, ${"src\\weird"})`,
  406. )
  407. yield* DatabaseMigration.applyOnly(db, [normalizeStoragePathsMigration])
  408. expect(yield* db.get(sql`SELECT worktree, sandboxes FROM project WHERE id = 'win'`)).toEqual({
  409. worktree: "C:/Repo/Thing",
  410. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  411. })
  412. expect(yield* db.get(sql`SELECT directory, path FROM session WHERE id = 'win'`)).toEqual({
  413. directory: "C:/Repo/Thing/packages/api",
  414. path: "packages/api",
  415. })
  416. expect(yield* db.get(sql`SELECT worktree, sandboxes FROM project WHERE id = 'unc'`)).toEqual({
  417. worktree: "//server/share",
  418. sandboxes: JSON.stringify(["//server/share/sandbox"]),
  419. })
  420. expect(yield* db.get(sql`SELECT worktree FROM project WHERE id = 'global'`)).toEqual({ worktree: "/" })
  421. expect(yield* db.get(sql`SELECT directory, path FROM session WHERE id = 'posix'`)).toEqual({
  422. directory: "/home/me/we\\ird",
  423. path: "src\\weird",
  424. })
  425. }),
  426. )
  427. })
  428. test("maps native Windows paths through database columns", async () => {
  429. if (process.platform !== "win32") return
  430. await run(
  431. Effect.gen(function* () {
  432. const db = yield* makeDb
  433. yield* DatabaseMigration.apply(db)
  434. const projectID = ProjectV2.ID.make("codec_project")
  435. const worktree = AbsolutePath.make("C:\\Repo\\Thing")
  436. const sandbox = AbsolutePath.make("C:\\Repo\\Thing\\sandbox")
  437. const directory = "C:\\Repo\\Thing\\packages\\api"
  438. const sessionID = SessionSchema.ID.make("ses_codec")
  439. expect(() =>
  440. Effect.runSync(
  441. db
  442. .insert(ProjectTable)
  443. .values({
  444. id: ProjectV2.ID.make("invalid_path"),
  445. worktree: AbsolutePath.make("not-absolute"),
  446. sandboxes: [],
  447. time_created: 1,
  448. time_updated: 1,
  449. })
  450. .run(),
  451. ),
  452. ).toThrow()
  453. yield* db
  454. .insert(ProjectTable)
  455. .values({
  456. id: projectID,
  457. worktree,
  458. sandboxes: [sandbox],
  459. time_created: 1,
  460. time_updated: 1,
  461. })
  462. .run()
  463. yield* db
  464. .insert(SessionTable)
  465. .values({
  466. id: sessionID,
  467. project_id: projectID,
  468. slug: "codec",
  469. directory,
  470. path: "packages\\api",
  471. title: "Codec",
  472. version: "test",
  473. time_created: 1,
  474. time_updated: 1,
  475. })
  476. .run()
  477. expect(
  478. yield* db.get<{ worktree: string; sandboxes: string }>(
  479. sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`,
  480. ),
  481. ).toEqual({
  482. worktree: "C:/Repo/Thing",
  483. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  484. })
  485. expect(
  486. yield* db.get<{ directory: string; path: string }>(
  487. sql`SELECT directory, path FROM session WHERE id = ${sessionID}`,
  488. ),
  489. ).toEqual({
  490. directory: "C:/Repo/Thing/packages/api",
  491. path: "packages/api",
  492. })
  493. const project = yield* db.select().from(ProjectTable).where(eq(ProjectTable.worktree, worktree)).get()
  494. const session = yield* db.select().from(SessionTable).where(eq(SessionTable.directory, directory)).get()
  495. expect(project?.worktree).toBe(worktree)
  496. expect(project?.sandboxes).toEqual([sandbox])
  497. expect(session?.directory).toBe(directory)
  498. expect(session?.path).toBe("packages/api")
  499. expect((yield* db.select().from(SessionTable).where(eq(SessionTable.path, "packages\\api")).get())?.id).toBe(
  500. sessionID,
  501. )
  502. const moved = AbsolutePath.make("D:\\Moved\\Thing")
  503. const updated = yield* db
  504. .update(ProjectTable)
  505. .set({ worktree: moved, sandboxes: [moved] })
  506. .where(eq(ProjectTable.id, projectID))
  507. .returning()
  508. .get()
  509. expect(updated?.worktree).toBe(moved)
  510. expect(updated?.sandboxes).toEqual([moved])
  511. expect(
  512. yield* db.get<{ worktree: string; sandboxes: string }>(
  513. sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`,
  514. ),
  515. ).toEqual({ worktree: "D:/Moved/Thing", sandboxes: JSON.stringify(["D:/Moved/Thing"]) })
  516. expect(
  517. (yield* db
  518. .select()
  519. .from(ProjectTable)
  520. .where(inArray(ProjectTable.worktree, [moved]))
  521. .get())?.id,
  522. ).toBe(projectID)
  523. yield* db.run(sql`UPDATE project SET worktree = ${"not-absolute"} WHERE id = ${projectID}`)
  524. expect(() =>
  525. Effect.runSync(db.select().from(ProjectTable).where(eq(ProjectTable.id, projectID)).get()),
  526. ).toThrow()
  527. }),
  528. )
  529. })
  530. test("imports existing drizzle migration state", async () => {
  531. await run(
  532. Effect.gen(function* () {
  533. const db = yield* makeDb
  534. yield* db.run(
  535. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  536. )
  537. yield* db.run(sql`
  538. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  539. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  540. `)
  541. yield* DatabaseMigration.applyOnly(db, [])
  542. expect(yield* db.get(sql`SELECT id FROM migration`)).toEqual({ id: "20260127222353_familiar_lady_ursula" })
  543. }),
  544. )
  545. })
  546. test("does not replay a migrated session metadata column", async () => {
  547. await run(
  548. Effect.gen(function* () {
  549. const db = yield* makeDb
  550. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  551. yield* db.run(
  552. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  553. )
  554. yield* db.run(sql`
  555. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  556. VALUES ('hash', 1, '20260511173437_session-metadata', ${new Date().toISOString()})
  557. `)
  558. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  559. expect(yield* db.all(sql`SELECT id FROM migration`)).toEqual([{ id: "20260511173437_session-metadata" }])
  560. }),
  561. )
  562. })
  563. test("accepts the temporary replacement session metadata migration id", async () => {
  564. await run(
  565. Effect.gen(function* () {
  566. const db = yield* makeDb
  567. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  568. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  569. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('20260530232709_lovely_romulus', 1)`)
  570. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  571. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([
  572. { id: "20260511173437_session-metadata" },
  573. { id: "20260530232709_lovely_romulus" },
  574. ])
  575. }),
  576. )
  577. })
  578. test("skips drizzle import when migration table already has state", async () => {
  579. await run(
  580. Effect.gen(function* () {
  581. const db = yield* makeDb
  582. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  583. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('existing', 1)`)
  584. yield* db.run(
  585. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  586. )
  587. yield* db.run(sql`
  588. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  589. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  590. `)
  591. yield* DatabaseMigration.applyOnly(db, [])
  592. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([{ id: "existing" }])
  593. }),
  594. )
  595. })
  596. })