json-migration.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. import { describe, test, expect, beforeEach, afterEach } from "bun:test"
  2. import { Database } from "bun:sqlite"
  3. import { drizzle } from "drizzle-orm/bun-sqlite"
  4. import { migrate } from "drizzle-orm/bun-sqlite/migrator"
  5. import path from "path"
  6. import fs from "fs/promises"
  7. import { readFileSync, readdirSync } from "fs"
  8. import { JsonMigration } from "../../src/storage/json-migration"
  9. import { Global } from "../../src/global"
  10. import { ProjectTable } from "../../src/project/project.sql"
  11. import { SessionTable, MessageTable, PartTable, TodoTable, PermissionTable } from "../../src/session/session.sql"
  12. import { SessionShareTable } from "../../src/share/share.sql"
  13. // Test fixtures
  14. const fixtures = {
  15. project: {
  16. id: "proj_test123abc",
  17. name: "Test Project",
  18. worktree: "/test/path",
  19. vcs: "git" as const,
  20. sandboxes: [],
  21. },
  22. session: {
  23. id: "ses_test456def",
  24. projectID: "proj_test123abc",
  25. slug: "test-session",
  26. directory: "/test/path",
  27. title: "Test Session",
  28. version: "1.0.0",
  29. time: { created: 1700000000000, updated: 1700000001000 },
  30. },
  31. message: {
  32. id: "msg_test789ghi",
  33. sessionID: "ses_test456def",
  34. role: "user" as const,
  35. agent: "default",
  36. model: { providerID: "openai", modelID: "gpt-4" },
  37. time: { created: 1700000000000 },
  38. },
  39. part: {
  40. id: "prt_testabc123",
  41. messageID: "msg_test789ghi",
  42. sessionID: "ses_test456def",
  43. type: "text" as const,
  44. text: "Hello, world!",
  45. },
  46. }
  47. // Helper to create test storage directory structure
  48. async function setupStorageDir() {
  49. const storageDir = path.join(Global.Path.data, "storage")
  50. await fs.rm(storageDir, { recursive: true, force: true })
  51. await fs.mkdir(path.join(storageDir, "project"), { recursive: true })
  52. await fs.mkdir(path.join(storageDir, "session", "proj_test123abc"), { recursive: true })
  53. await fs.mkdir(path.join(storageDir, "message", "ses_test456def"), { recursive: true })
  54. await fs.mkdir(path.join(storageDir, "part", "msg_test789ghi"), { recursive: true })
  55. await fs.mkdir(path.join(storageDir, "session_diff"), { recursive: true })
  56. await fs.mkdir(path.join(storageDir, "todo"), { recursive: true })
  57. await fs.mkdir(path.join(storageDir, "permission"), { recursive: true })
  58. await fs.mkdir(path.join(storageDir, "session_share"), { recursive: true })
  59. // Create legacy marker to indicate JSON storage exists
  60. await Bun.write(path.join(storageDir, "migration"), "1")
  61. return storageDir
  62. }
  63. async function writeProject(storageDir: string, project: Record<string, unknown>) {
  64. await Bun.write(path.join(storageDir, "project", `${project.id}.json`), JSON.stringify(project))
  65. }
  66. async function writeSession(storageDir: string, projectID: string, session: Record<string, unknown>) {
  67. await Bun.write(path.join(storageDir, "session", projectID, `${session.id}.json`), JSON.stringify(session))
  68. }
  69. // Helper to create in-memory test database with schema
  70. function createTestDb() {
  71. const sqlite = new Database(":memory:")
  72. sqlite.exec("PRAGMA foreign_keys = ON")
  73. // Apply schema migrations using drizzle migrate
  74. const dir = path.join(import.meta.dirname, "../../migration")
  75. const entries = readdirSync(dir, { withFileTypes: true })
  76. const migrations = entries
  77. .filter((entry) => entry.isDirectory())
  78. .map((entry) => ({
  79. sql: readFileSync(path.join(dir, entry.name, "migration.sql"), "utf-8"),
  80. timestamp: Number(entry.name.split("_")[0]),
  81. }))
  82. .sort((a, b) => a.timestamp - b.timestamp)
  83. migrate(drizzle({ client: sqlite }), migrations)
  84. return sqlite
  85. }
  86. describe("JSON to SQLite migration", () => {
  87. let storageDir: string
  88. let sqlite: Database
  89. beforeEach(async () => {
  90. storageDir = await setupStorageDir()
  91. sqlite = createTestDb()
  92. })
  93. afterEach(async () => {
  94. sqlite.close()
  95. await fs.rm(storageDir, { recursive: true, force: true })
  96. })
  97. test("migrates project", async () => {
  98. await writeProject(storageDir, {
  99. id: "proj_test123abc",
  100. worktree: "/test/path",
  101. vcs: "git",
  102. name: "Test Project",
  103. time: { created: 1700000000000, updated: 1700000001000 },
  104. sandboxes: ["/test/sandbox"],
  105. })
  106. const stats = await JsonMigration.run(sqlite)
  107. expect(stats?.projects).toBe(1)
  108. const db = drizzle({ client: sqlite })
  109. const projects = db.select().from(ProjectTable).all()
  110. expect(projects.length).toBe(1)
  111. expect(projects[0].id).toBe("proj_test123abc")
  112. expect(projects[0].worktree).toBe("/test/path")
  113. expect(projects[0].name).toBe("Test Project")
  114. expect(projects[0].sandboxes).toEqual(["/test/sandbox"])
  115. })
  116. test("migrates project with commands", async () => {
  117. await writeProject(storageDir, {
  118. id: "proj_with_commands",
  119. worktree: "/test/path",
  120. vcs: "git",
  121. name: "Project With Commands",
  122. time: { created: 1700000000000, updated: 1700000001000 },
  123. sandboxes: ["/test/sandbox"],
  124. commands: { start: "npm run dev" },
  125. })
  126. const stats = await JsonMigration.run(sqlite)
  127. expect(stats?.projects).toBe(1)
  128. const db = drizzle({ client: sqlite })
  129. const projects = db.select().from(ProjectTable).all()
  130. expect(projects.length).toBe(1)
  131. expect(projects[0].id).toBe("proj_with_commands")
  132. expect(projects[0].commands).toEqual({ start: "npm run dev" })
  133. })
  134. test("migrates project without commands field", async () => {
  135. await writeProject(storageDir, {
  136. id: "proj_no_commands",
  137. worktree: "/test/path",
  138. vcs: "git",
  139. name: "Project Without Commands",
  140. time: { created: 1700000000000, updated: 1700000001000 },
  141. sandboxes: [],
  142. })
  143. const stats = await JsonMigration.run(sqlite)
  144. expect(stats?.projects).toBe(1)
  145. const db = drizzle({ client: sqlite })
  146. const projects = db.select().from(ProjectTable).all()
  147. expect(projects.length).toBe(1)
  148. expect(projects[0].id).toBe("proj_no_commands")
  149. expect(projects[0].commands).toBeNull()
  150. })
  151. test("migrates session with individual columns", async () => {
  152. await writeProject(storageDir, {
  153. id: "proj_test123abc",
  154. worktree: "/test/path",
  155. time: { created: Date.now(), updated: Date.now() },
  156. sandboxes: [],
  157. })
  158. await writeSession(storageDir, "proj_test123abc", {
  159. id: "ses_test456def",
  160. projectID: "proj_test123abc",
  161. slug: "test-session",
  162. directory: "/test/dir",
  163. title: "Test Session Title",
  164. version: "1.0.0",
  165. time: { created: 1700000000000, updated: 1700000001000 },
  166. summary: { additions: 10, deletions: 5, files: 3 },
  167. share: { url: "https://example.com/share" },
  168. })
  169. await JsonMigration.run(sqlite)
  170. const db = drizzle({ client: sqlite })
  171. const sessions = db.select().from(SessionTable).all()
  172. expect(sessions.length).toBe(1)
  173. expect(sessions[0].id).toBe("ses_test456def")
  174. expect(sessions[0].project_id).toBe("proj_test123abc")
  175. expect(sessions[0].slug).toBe("test-session")
  176. expect(sessions[0].title).toBe("Test Session Title")
  177. expect(sessions[0].summary_additions).toBe(10)
  178. expect(sessions[0].summary_deletions).toBe(5)
  179. expect(sessions[0].share_url).toBe("https://example.com/share")
  180. })
  181. test("migrates messages and parts", async () => {
  182. await writeProject(storageDir, {
  183. id: "proj_test123abc",
  184. worktree: "/",
  185. time: { created: Date.now(), updated: Date.now() },
  186. sandboxes: [],
  187. })
  188. await writeSession(storageDir, "proj_test123abc", { ...fixtures.session })
  189. await Bun.write(
  190. path.join(storageDir, "message", "ses_test456def", "msg_test789ghi.json"),
  191. JSON.stringify({ ...fixtures.message }),
  192. )
  193. await Bun.write(
  194. path.join(storageDir, "part", "msg_test789ghi", "prt_testabc123.json"),
  195. JSON.stringify({ ...fixtures.part }),
  196. )
  197. const stats = await JsonMigration.run(sqlite)
  198. expect(stats?.messages).toBe(1)
  199. expect(stats?.parts).toBe(1)
  200. const db = drizzle({ client: sqlite })
  201. const messages = db.select().from(MessageTable).all()
  202. expect(messages.length).toBe(1)
  203. expect(messages[0].id).toBe("msg_test789ghi")
  204. const parts = db.select().from(PartTable).all()
  205. expect(parts.length).toBe(1)
  206. expect(parts[0].id).toBe("prt_testabc123")
  207. })
  208. test("migrates legacy parts without ids in body", async () => {
  209. await writeProject(storageDir, {
  210. id: "proj_test123abc",
  211. worktree: "/",
  212. time: { created: Date.now(), updated: Date.now() },
  213. sandboxes: [],
  214. })
  215. await writeSession(storageDir, "proj_test123abc", { ...fixtures.session })
  216. await Bun.write(
  217. path.join(storageDir, "message", "ses_test456def", "msg_test789ghi.json"),
  218. JSON.stringify({
  219. role: "user",
  220. agent: "default",
  221. model: { providerID: "openai", modelID: "gpt-4" },
  222. time: { created: 1700000000000 },
  223. }),
  224. )
  225. await Bun.write(
  226. path.join(storageDir, "part", "msg_test789ghi", "prt_testabc123.json"),
  227. JSON.stringify({
  228. type: "text",
  229. text: "Hello, world!",
  230. }),
  231. )
  232. const stats = await JsonMigration.run(sqlite)
  233. expect(stats?.messages).toBe(1)
  234. expect(stats?.parts).toBe(1)
  235. const db = drizzle({ client: sqlite })
  236. const messages = db.select().from(MessageTable).all()
  237. expect(messages.length).toBe(1)
  238. expect(messages[0].id).toBe("msg_test789ghi")
  239. expect(messages[0].session_id).toBe("ses_test456def")
  240. expect(messages[0].data).not.toHaveProperty("id")
  241. expect(messages[0].data).not.toHaveProperty("sessionID")
  242. const parts = db.select().from(PartTable).all()
  243. expect(parts.length).toBe(1)
  244. expect(parts[0].id).toBe("prt_testabc123")
  245. expect(parts[0].message_id).toBe("msg_test789ghi")
  246. expect(parts[0].session_id).toBe("ses_test456def")
  247. expect(parts[0].data).not.toHaveProperty("id")
  248. expect(parts[0].data).not.toHaveProperty("messageID")
  249. expect(parts[0].data).not.toHaveProperty("sessionID")
  250. })
  251. test("skips orphaned sessions (no parent project)", async () => {
  252. await Bun.write(
  253. path.join(storageDir, "session", "proj_test123abc", "ses_orphan.json"),
  254. JSON.stringify({
  255. id: "ses_orphan",
  256. projectID: "proj_nonexistent",
  257. slug: "orphan",
  258. directory: "/",
  259. title: "Orphan",
  260. version: "1.0.0",
  261. time: { created: Date.now(), updated: Date.now() },
  262. }),
  263. )
  264. const stats = await JsonMigration.run(sqlite)
  265. expect(stats?.sessions).toBe(0)
  266. })
  267. test("is idempotent (running twice doesn't duplicate)", async () => {
  268. await writeProject(storageDir, {
  269. id: "proj_test123abc",
  270. worktree: "/",
  271. time: { created: Date.now(), updated: Date.now() },
  272. sandboxes: [],
  273. })
  274. await JsonMigration.run(sqlite)
  275. await JsonMigration.run(sqlite)
  276. const db = drizzle({ client: sqlite })
  277. const projects = db.select().from(ProjectTable).all()
  278. expect(projects.length).toBe(1) // Still only 1 due to onConflictDoNothing
  279. })
  280. test("migrates todos", async () => {
  281. await writeProject(storageDir, {
  282. id: "proj_test123abc",
  283. worktree: "/",
  284. time: { created: Date.now(), updated: Date.now() },
  285. sandboxes: [],
  286. })
  287. await writeSession(storageDir, "proj_test123abc", { ...fixtures.session })
  288. // Create todo file (named by sessionID, contains array of todos)
  289. await Bun.write(
  290. path.join(storageDir, "todo", "ses_test456def.json"),
  291. JSON.stringify([
  292. {
  293. id: "todo_1",
  294. content: "First todo",
  295. status: "pending",
  296. priority: "high",
  297. },
  298. {
  299. id: "todo_2",
  300. content: "Second todo",
  301. status: "completed",
  302. priority: "medium",
  303. },
  304. ]),
  305. )
  306. const stats = await JsonMigration.run(sqlite)
  307. expect(stats?.todos).toBe(2)
  308. const db = drizzle({ client: sqlite })
  309. const todos = db.select().from(TodoTable).orderBy(TodoTable.position).all()
  310. expect(todos.length).toBe(2)
  311. expect(todos[0].content).toBe("First todo")
  312. expect(todos[0].status).toBe("pending")
  313. expect(todos[0].priority).toBe("high")
  314. expect(todos[0].position).toBe(0)
  315. expect(todos[1].content).toBe("Second todo")
  316. expect(todos[1].position).toBe(1)
  317. })
  318. test("todos are ordered by position", async () => {
  319. await writeProject(storageDir, {
  320. id: "proj_test123abc",
  321. worktree: "/",
  322. time: { created: Date.now(), updated: Date.now() },
  323. sandboxes: [],
  324. })
  325. await writeSession(storageDir, "proj_test123abc", { ...fixtures.session })
  326. await Bun.write(
  327. path.join(storageDir, "todo", "ses_test456def.json"),
  328. JSON.stringify([
  329. { content: "Third", status: "pending", priority: "low" },
  330. { content: "First", status: "pending", priority: "high" },
  331. { content: "Second", status: "in_progress", priority: "medium" },
  332. ]),
  333. )
  334. await JsonMigration.run(sqlite)
  335. const db = drizzle({ client: sqlite })
  336. const todos = db.select().from(TodoTable).orderBy(TodoTable.position).all()
  337. expect(todos.length).toBe(3)
  338. expect(todos[0].content).toBe("Third")
  339. expect(todos[0].position).toBe(0)
  340. expect(todos[1].content).toBe("First")
  341. expect(todos[1].position).toBe(1)
  342. expect(todos[2].content).toBe("Second")
  343. expect(todos[2].position).toBe(2)
  344. })
  345. test("migrates permissions", async () => {
  346. await writeProject(storageDir, {
  347. id: "proj_test123abc",
  348. worktree: "/",
  349. time: { created: Date.now(), updated: Date.now() },
  350. sandboxes: [],
  351. })
  352. // Create permission file (named by projectID, contains array of rules)
  353. const permissionData = [
  354. { permission: "file.read", pattern: "/test/file1.ts", action: "allow" as const },
  355. { permission: "file.write", pattern: "/test/file2.ts", action: "ask" as const },
  356. { permission: "command.run", pattern: "npm install", action: "deny" as const },
  357. ]
  358. await Bun.write(path.join(storageDir, "permission", "proj_test123abc.json"), JSON.stringify(permissionData))
  359. const stats = await JsonMigration.run(sqlite)
  360. expect(stats?.permissions).toBe(1)
  361. const db = drizzle({ client: sqlite })
  362. const permissions = db.select().from(PermissionTable).all()
  363. expect(permissions.length).toBe(1)
  364. expect(permissions[0].project_id).toBe("proj_test123abc")
  365. expect(permissions[0].data).toEqual(permissionData)
  366. })
  367. test("migrates session shares", async () => {
  368. await writeProject(storageDir, {
  369. id: "proj_test123abc",
  370. worktree: "/",
  371. time: { created: Date.now(), updated: Date.now() },
  372. sandboxes: [],
  373. })
  374. await writeSession(storageDir, "proj_test123abc", { ...fixtures.session })
  375. // Create session share file (named by sessionID)
  376. await Bun.write(
  377. path.join(storageDir, "session_share", "ses_test456def.json"),
  378. JSON.stringify({
  379. id: "share_123",
  380. secret: "supersecretkey",
  381. url: "https://share.example.com/ses_test456def",
  382. }),
  383. )
  384. const stats = await JsonMigration.run(sqlite)
  385. expect(stats?.shares).toBe(1)
  386. const db = drizzle({ client: sqlite })
  387. const shares = db.select().from(SessionShareTable).all()
  388. expect(shares.length).toBe(1)
  389. expect(shares[0].session_id).toBe("ses_test456def")
  390. expect(shares[0].id).toBe("share_123")
  391. expect(shares[0].secret).toBe("supersecretkey")
  392. expect(shares[0].url).toBe("https://share.example.com/ses_test456def")
  393. })
  394. test("returns empty stats when storage directory does not exist", async () => {
  395. await fs.rm(storageDir, { recursive: true, force: true })
  396. const stats = await JsonMigration.run(sqlite)
  397. expect(stats.projects).toBe(0)
  398. expect(stats.sessions).toBe(0)
  399. expect(stats.messages).toBe(0)
  400. expect(stats.parts).toBe(0)
  401. expect(stats.todos).toBe(0)
  402. expect(stats.permissions).toBe(0)
  403. expect(stats.shares).toBe(0)
  404. expect(stats.errors).toEqual([])
  405. })
  406. test("continues when a JSON file is unreadable and records an error", async () => {
  407. await writeProject(storageDir, {
  408. id: "proj_test123abc",
  409. worktree: "/",
  410. time: { created: Date.now(), updated: Date.now() },
  411. sandboxes: [],
  412. })
  413. await Bun.write(path.join(storageDir, "project", "broken.json"), "{ invalid json")
  414. const stats = await JsonMigration.run(sqlite)
  415. expect(stats.projects).toBe(1)
  416. expect(stats.errors.some((x) => x.includes("failed to read") && x.includes("broken.json"))).toBe(true)
  417. const db = drizzle({ client: sqlite })
  418. const projects = db.select().from(ProjectTable).all()
  419. expect(projects.length).toBe(1)
  420. expect(projects[0].id).toBe("proj_test123abc")
  421. })
  422. test("skips invalid todo entries while preserving source positions", async () => {
  423. await writeProject(storageDir, {
  424. id: "proj_test123abc",
  425. worktree: "/",
  426. time: { created: Date.now(), updated: Date.now() },
  427. sandboxes: [],
  428. })
  429. await writeSession(storageDir, "proj_test123abc", { ...fixtures.session })
  430. await Bun.write(
  431. path.join(storageDir, "todo", "ses_test456def.json"),
  432. JSON.stringify([
  433. { content: "keep-0", status: "pending", priority: "high" },
  434. { content: "drop-1", priority: "low" },
  435. { content: "keep-2", status: "completed", priority: "medium" },
  436. ]),
  437. )
  438. const stats = await JsonMigration.run(sqlite)
  439. expect(stats.todos).toBe(2)
  440. const db = drizzle({ client: sqlite })
  441. const todos = db.select().from(TodoTable).orderBy(TodoTable.position).all()
  442. expect(todos.length).toBe(2)
  443. expect(todos[0].content).toBe("keep-0")
  444. expect(todos[0].position).toBe(0)
  445. expect(todos[1].content).toBe("keep-2")
  446. expect(todos[1].position).toBe(2)
  447. })
  448. test("skips orphaned todos, permissions, and shares", async () => {
  449. await writeProject(storageDir, {
  450. id: "proj_test123abc",
  451. worktree: "/",
  452. time: { created: Date.now(), updated: Date.now() },
  453. sandboxes: [],
  454. })
  455. await writeSession(storageDir, "proj_test123abc", { ...fixtures.session })
  456. await Bun.write(
  457. path.join(storageDir, "todo", "ses_test456def.json"),
  458. JSON.stringify([{ content: "valid", status: "pending", priority: "high" }]),
  459. )
  460. await Bun.write(
  461. path.join(storageDir, "todo", "ses_missing.json"),
  462. JSON.stringify([{ content: "orphan", status: "pending", priority: "high" }]),
  463. )
  464. await Bun.write(
  465. path.join(storageDir, "permission", "proj_test123abc.json"),
  466. JSON.stringify([{ permission: "file.read" }]),
  467. )
  468. await Bun.write(
  469. path.join(storageDir, "permission", "proj_missing.json"),
  470. JSON.stringify([{ permission: "file.write" }]),
  471. )
  472. await Bun.write(
  473. path.join(storageDir, "session_share", "ses_test456def.json"),
  474. JSON.stringify({ id: "share_ok", secret: "secret", url: "https://ok.example.com" }),
  475. )
  476. await Bun.write(
  477. path.join(storageDir, "session_share", "ses_missing.json"),
  478. JSON.stringify({ id: "share_missing", secret: "secret", url: "https://missing.example.com" }),
  479. )
  480. const stats = await JsonMigration.run(sqlite)
  481. expect(stats.todos).toBe(1)
  482. expect(stats.permissions).toBe(1)
  483. expect(stats.shares).toBe(1)
  484. const db = drizzle({ client: sqlite })
  485. expect(db.select().from(TodoTable).all().length).toBe(1)
  486. expect(db.select().from(PermissionTable).all().length).toBe(1)
  487. expect(db.select().from(SessionShareTable).all().length).toBe(1)
  488. })
  489. test("handles mixed corruption and partial validity in one migration run", async () => {
  490. await writeProject(storageDir, {
  491. id: "proj_test123abc",
  492. worktree: "/ok",
  493. time: { created: 1700000000000, updated: 1700000001000 },
  494. sandboxes: [],
  495. })
  496. await Bun.write(
  497. path.join(storageDir, "project", "proj_missing_id.json"),
  498. JSON.stringify({ worktree: "/bad", sandboxes: [] }),
  499. )
  500. await Bun.write(path.join(storageDir, "project", "proj_broken.json"), "{ nope")
  501. await writeSession(storageDir, "proj_test123abc", {
  502. id: "ses_test456def",
  503. projectID: "proj_test123abc",
  504. slug: "ok",
  505. directory: "/ok",
  506. title: "Ok",
  507. version: "1",
  508. time: { created: 1700000000000, updated: 1700000001000 },
  509. })
  510. await Bun.write(
  511. path.join(storageDir, "session", "proj_test123abc", "ses_missing_project.json"),
  512. JSON.stringify({
  513. id: "ses_missing_project",
  514. slug: "bad",
  515. directory: "/bad",
  516. title: "Bad",
  517. version: "1",
  518. }),
  519. )
  520. await Bun.write(
  521. path.join(storageDir, "session", "proj_test123abc", "ses_orphan.json"),
  522. JSON.stringify({
  523. id: "ses_orphan",
  524. projectID: "proj_missing",
  525. slug: "orphan",
  526. directory: "/bad",
  527. title: "Orphan",
  528. version: "1",
  529. }),
  530. )
  531. await Bun.write(
  532. path.join(storageDir, "message", "ses_test456def", "msg_ok.json"),
  533. JSON.stringify({ role: "user", time: { created: 1700000000000 } }),
  534. )
  535. await Bun.write(path.join(storageDir, "message", "ses_test456def", "msg_broken.json"), "{ nope")
  536. await Bun.write(
  537. path.join(storageDir, "message", "ses_missing", "msg_orphan.json"),
  538. JSON.stringify({ role: "user", time: { created: 1700000000000 } }),
  539. )
  540. await Bun.write(
  541. path.join(storageDir, "part", "msg_ok", "part_ok.json"),
  542. JSON.stringify({ type: "text", text: "ok" }),
  543. )
  544. await Bun.write(
  545. path.join(storageDir, "part", "msg_missing", "part_missing_message.json"),
  546. JSON.stringify({ type: "text", text: "bad" }),
  547. )
  548. await Bun.write(path.join(storageDir, "part", "msg_ok", "part_broken.json"), "{ nope")
  549. await Bun.write(
  550. path.join(storageDir, "todo", "ses_test456def.json"),
  551. JSON.stringify([
  552. { content: "ok", status: "pending", priority: "high" },
  553. { content: "skip", status: "pending" },
  554. ]),
  555. )
  556. await Bun.write(
  557. path.join(storageDir, "todo", "ses_missing.json"),
  558. JSON.stringify([{ content: "orphan", status: "pending", priority: "high" }]),
  559. )
  560. await Bun.write(path.join(storageDir, "todo", "ses_broken.json"), "{ nope")
  561. await Bun.write(
  562. path.join(storageDir, "permission", "proj_test123abc.json"),
  563. JSON.stringify([{ permission: "file.read" }]),
  564. )
  565. await Bun.write(
  566. path.join(storageDir, "permission", "proj_missing.json"),
  567. JSON.stringify([{ permission: "file.write" }]),
  568. )
  569. await Bun.write(path.join(storageDir, "permission", "proj_broken.json"), "{ nope")
  570. await Bun.write(
  571. path.join(storageDir, "session_share", "ses_test456def.json"),
  572. JSON.stringify({ id: "share_ok", secret: "secret", url: "https://ok.example.com" }),
  573. )
  574. await Bun.write(
  575. path.join(storageDir, "session_share", "ses_missing.json"),
  576. JSON.stringify({ id: "share_orphan", secret: "secret", url: "https://missing.example.com" }),
  577. )
  578. await Bun.write(path.join(storageDir, "session_share", "ses_broken.json"), "{ nope")
  579. const stats = await JsonMigration.run(sqlite)
  580. expect(stats.projects).toBe(1)
  581. expect(stats.sessions).toBe(1)
  582. expect(stats.messages).toBe(1)
  583. expect(stats.parts).toBe(1)
  584. expect(stats.todos).toBe(1)
  585. expect(stats.permissions).toBe(1)
  586. expect(stats.shares).toBe(1)
  587. expect(stats.errors.length).toBeGreaterThanOrEqual(6)
  588. const db = drizzle({ client: sqlite })
  589. expect(db.select().from(ProjectTable).all().length).toBe(1)
  590. expect(db.select().from(SessionTable).all().length).toBe(1)
  591. expect(db.select().from(MessageTable).all().length).toBe(1)
  592. expect(db.select().from(PartTable).all().length).toBe(1)
  593. expect(db.select().from(TodoTable).all().length).toBe(1)
  594. expect(db.select().from(PermissionTable).all().length).toBe(1)
  595. expect(db.select().from(SessionShareTable).all().length).toBe(1)
  596. })
  597. })