storage.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import { existsSync, readFileSync, writeFileSync } from "node:fs";
  2. import { join } from "node:path";
  3. import { describe, expect, it } from "vitest";
  4. import { NodeExecutionEnv } from "../../src/harness/env/nodejs.ts";
  5. import { JsonlSessionStorage, loadJsonlSessionMetadata } from "../../src/harness/session/jsonl-storage.ts";
  6. import { InMemorySessionStorage } from "../../src/harness/session/memory-storage.ts";
  7. import { type MessageEntry, ok, type SessionMetadata } from "../../src/harness/types.ts";
  8. import { createAssistantMessage, createTempDir, createUserMessage } from "./session-test-utils.ts";
  9. describe("InMemorySessionStorage", () => {
  10. it("returns configured session metadata", async () => {
  11. const metadata: SessionMetadata = { id: "session-1", createdAt: "2026-01-01T00:00:00.000Z" };
  12. const storage = new InMemorySessionStorage({ metadata });
  13. expect(await storage.getMetadata()).toEqual(metadata);
  14. });
  15. it("copies initial entries and persists leaf changes", async () => {
  16. const entry: MessageEntry = {
  17. type: "message",
  18. id: "entry-1",
  19. parentId: null,
  20. timestamp: "2026-01-01T00:00:00.000Z",
  21. message: createUserMessage("one"),
  22. };
  23. const initialEntries = [entry];
  24. const storage = new InMemorySessionStorage({ entries: initialEntries });
  25. initialEntries.push({ ...entry, id: "entry-2" });
  26. expect((await storage.getEntries()).map((storedEntry) => storedEntry.id)).toEqual(["entry-1"]);
  27. expect(await storage.getLeafId()).toBe("entry-1");
  28. await storage.setLeafId(null);
  29. expect(await storage.getLeafId()).toBeNull();
  30. expect((await storage.getEntries()).at(-1)).toMatchObject({ type: "leaf", targetId: null });
  31. });
  32. it("rejects invalid leaf ids", async () => {
  33. const storage = new InMemorySessionStorage();
  34. await expect(storage.setLeafId("missing")).rejects.toThrow("Entry missing not found");
  35. });
  36. it("finds entries by type", async () => {
  37. const entry: MessageEntry = {
  38. type: "message",
  39. id: "entry-1",
  40. parentId: null,
  41. timestamp: "2026-01-01T00:00:00.000Z",
  42. message: createUserMessage("one"),
  43. };
  44. const storage = new InMemorySessionStorage({ entries: [entry] });
  45. expect((await storage.findEntries("message")).map((found) => found.id)).toEqual(["entry-1"]);
  46. expect(await storage.findEntries("session_info")).toEqual([]);
  47. });
  48. it("maintains label lookup", async () => {
  49. const entry: MessageEntry = {
  50. type: "message",
  51. id: "entry-1",
  52. parentId: null,
  53. timestamp: "2026-01-01T00:00:00.000Z",
  54. message: createUserMessage("one"),
  55. };
  56. const storage = new InMemorySessionStorage({ entries: [entry] });
  57. expect(await storage.getLabel("entry-1")).toBeUndefined();
  58. await storage.appendEntry({
  59. type: "label",
  60. id: "label-1",
  61. parentId: "entry-1",
  62. timestamp: "2026-01-01T00:00:01.000Z",
  63. targetId: "entry-1",
  64. label: "checkpoint",
  65. });
  66. expect(await storage.getLabel("entry-1")).toBe("checkpoint");
  67. await storage.appendEntry({
  68. type: "label",
  69. id: "label-2",
  70. parentId: "label-1",
  71. timestamp: "2026-01-01T00:00:02.000Z",
  72. targetId: "entry-1",
  73. label: undefined,
  74. });
  75. expect(await storage.getLabel("entry-1")).toBeUndefined();
  76. });
  77. it("walks paths to root", async () => {
  78. const root: MessageEntry = {
  79. type: "message",
  80. id: "root",
  81. parentId: null,
  82. timestamp: "2026-01-01T00:00:00.000Z",
  83. message: createUserMessage("root"),
  84. };
  85. const child: MessageEntry = {
  86. ...root,
  87. id: "child",
  88. parentId: "root",
  89. message: createAssistantMessage("child"),
  90. };
  91. const storage = new InMemorySessionStorage({ entries: [root, child] });
  92. expect((await storage.getPathToRoot("child")).map((entry) => entry.id)).toEqual(["root", "child"]);
  93. expect(await storage.getPathToRoot(null)).toEqual([]);
  94. });
  95. });
  96. describe("JsonlSessionStorage", () => {
  97. it("throws for missing files when opening", async () => {
  98. const dir = createTempDir();
  99. const env = new NodeExecutionEnv({ cwd: dir });
  100. const filePath = join(dir, "session.jsonl");
  101. await expect(JsonlSessionStorage.open(env, filePath)).rejects.toMatchObject({ code: "not_found" });
  102. });
  103. it("writes the header on create", async () => {
  104. const dir = createTempDir();
  105. const env = new NodeExecutionEnv({ cwd: dir });
  106. const filePath = join(dir, "session.jsonl");
  107. const storage = await JsonlSessionStorage.create(env, filePath, { cwd: dir, sessionId: "session-1" });
  108. expect(existsSync(filePath)).toBe(true);
  109. expect(readFileSync(filePath, "utf8").trim().split("\n")).toHaveLength(1);
  110. expect(await storage.getLeafId()).toBeNull();
  111. expect(await storage.getEntries()).toEqual([]);
  112. await storage.appendEntry({
  113. type: "message",
  114. id: "user-1",
  115. parentId: null,
  116. timestamp: "2026-01-01T00:00:00.000Z",
  117. message: createUserMessage("one"),
  118. });
  119. const lines = readFileSync(filePath, "utf8").trim().split("\n");
  120. expect(JSON.parse(lines[0]!).type).toBe("session");
  121. expect(JSON.parse(lines[1]!).id).toBe("user-1");
  122. expect(lines).toHaveLength(2);
  123. });
  124. it("throws for malformed session headers", async () => {
  125. const dir = createTempDir();
  126. const env = new NodeExecutionEnv({ cwd: dir });
  127. const filePath = join(dir, "session.jsonl");
  128. writeFileSync(filePath, "not json\n");
  129. await expect(JsonlSessionStorage.open(env, filePath)).rejects.toThrow("first line is not a valid session header");
  130. });
  131. it("throws for malformed entry lines", async () => {
  132. const dir = createTempDir();
  133. const env = new NodeExecutionEnv({ cwd: dir });
  134. const filePath = join(dir, "session.jsonl");
  135. const header = {
  136. type: "session",
  137. version: 3,
  138. id: "session-1",
  139. timestamp: "2026-01-01T00:00:00.000Z",
  140. cwd: dir,
  141. };
  142. const entry: MessageEntry = {
  143. type: "message",
  144. id: "entry-1",
  145. parentId: null,
  146. timestamp: "2026-01-01T00:00:00.000Z",
  147. message: createUserMessage("one"),
  148. };
  149. writeFileSync(filePath, `${JSON.stringify(header)}\nnot json\n${JSON.stringify(entry)}\n`);
  150. await expect(JsonlSessionStorage.open(env, filePath)).rejects.toMatchObject({ code: "invalid_entry" });
  151. });
  152. it("creates and reads session metadata from the header", async () => {
  153. const dir = createTempDir();
  154. const env = new NodeExecutionEnv({ cwd: dir });
  155. const filePath = join(dir, "session.jsonl");
  156. const storage = await JsonlSessionStorage.create(env, filePath, {
  157. cwd: dir,
  158. sessionId: "session-1",
  159. parentSessionPath: "/tmp/parent.jsonl",
  160. });
  161. const metadata = await storage.getMetadata();
  162. expect(metadata).toMatchObject({
  163. id: "session-1",
  164. cwd: dir,
  165. path: filePath,
  166. parentSessionPath: "/tmp/parent.jsonl",
  167. });
  168. await storage.appendEntry({
  169. type: "message",
  170. id: "user-1",
  171. parentId: null,
  172. timestamp: "2026-01-01T00:00:00.000Z",
  173. message: createUserMessage("one"),
  174. });
  175. expect(await loadJsonlSessionMetadata(env, filePath)).toEqual(metadata);
  176. });
  177. it("loads existing entries and reconstructs leaf", async () => {
  178. const dir = createTempDir();
  179. const env = new NodeExecutionEnv({ cwd: dir });
  180. const filePath = join(dir, "session.jsonl");
  181. const storage = await JsonlSessionStorage.create(env, filePath, { cwd: dir, sessionId: "session-1" });
  182. const root: MessageEntry = {
  183. type: "message",
  184. id: "root",
  185. parentId: null,
  186. timestamp: "2026-01-01T00:00:00.000Z",
  187. message: createUserMessage("root"),
  188. };
  189. const child: MessageEntry = {
  190. ...root,
  191. id: "child",
  192. parentId: "root",
  193. message: createAssistantMessage("child"),
  194. };
  195. await storage.appendEntry(root);
  196. await storage.appendEntry(child);
  197. const loaded = await JsonlSessionStorage.open(env, filePath);
  198. expect(await loaded.getLeafId()).toBe("child");
  199. expect((await loaded.getEntries()).map((entry) => entry.id)).toEqual(["root", "child"]);
  200. await loaded.setLeafId("root");
  201. const reloaded = await JsonlSessionStorage.open(env, filePath);
  202. expect(await reloaded.getLeafId()).toBe("root");
  203. expect((await reloaded.getEntries()).at(-1)).toMatchObject({ type: "leaf", targetId: "root" });
  204. expect((await loaded.getPathToRoot("child")).map((entry) => entry.id)).toEqual(["root", "child"]);
  205. });
  206. it("finds entries by type", async () => {
  207. const dir = createTempDir();
  208. const env = new NodeExecutionEnv({ cwd: dir });
  209. const filePath = join(dir, "session.jsonl");
  210. const storage = await JsonlSessionStorage.create(env, filePath, { cwd: dir, sessionId: "session-1" });
  211. await storage.appendEntry({
  212. type: "message",
  213. id: "entry-1",
  214. parentId: null,
  215. timestamp: "2026-01-01T00:00:00.000Z",
  216. message: createUserMessage("one"),
  217. });
  218. expect((await storage.findEntries("message")).map((found) => found.id)).toEqual(["entry-1"]);
  219. expect(await storage.findEntries("session_info")).toEqual([]);
  220. });
  221. it("maintains label lookup", async () => {
  222. const dir = createTempDir();
  223. const env = new NodeExecutionEnv({ cwd: dir });
  224. const filePath = join(dir, "session.jsonl");
  225. const storage = await JsonlSessionStorage.create(env, filePath, { cwd: dir, sessionId: "session-1" });
  226. await storage.appendEntry({
  227. type: "message",
  228. id: "entry-1",
  229. parentId: null,
  230. timestamp: "2026-01-01T00:00:00.000Z",
  231. message: createUserMessage("one"),
  232. });
  233. expect(await storage.getLabel("entry-1")).toBeUndefined();
  234. await storage.appendEntry({
  235. type: "label",
  236. id: "label-1",
  237. parentId: "entry-1",
  238. timestamp: "2026-01-01T00:00:01.000Z",
  239. targetId: "entry-1",
  240. label: "checkpoint",
  241. });
  242. expect(await storage.getLabel("entry-1")).toBe("checkpoint");
  243. await storage.appendEntry({
  244. type: "label",
  245. id: "label-2",
  246. parentId: "label-1",
  247. timestamp: "2026-01-01T00:00:02.000Z",
  248. targetId: "entry-1",
  249. label: undefined,
  250. });
  251. expect(await storage.getLabel("entry-1")).toBeUndefined();
  252. const loaded = await JsonlSessionStorage.open(env, filePath);
  253. expect(await loaded.getLabel("entry-1")).toBeUndefined();
  254. });
  255. it("reads session metadata through the line-reading filesystem operation", async () => {
  256. const dir = createTempDir();
  257. const filePath = join(dir, "session.jsonl");
  258. const header = {
  259. type: "session",
  260. version: 3,
  261. id: "session-1",
  262. timestamp: "2026-01-01T00:00:00.000Z",
  263. cwd: dir,
  264. };
  265. const metadata = await loadJsonlSessionMetadata(
  266. {
  267. readTextLines: async () => ok([JSON.stringify(header)]),
  268. readTextFile: async () => {
  269. throw new Error("readTextFile should not be called for metadata");
  270. },
  271. writeFile: async () => ok(undefined),
  272. appendFile: async () => ok(undefined),
  273. },
  274. filePath,
  275. );
  276. expect(metadata).toEqual({
  277. id: "session-1",
  278. createdAt: "2026-01-01T00:00:00.000Z",
  279. cwd: dir,
  280. path: filePath,
  281. parentSessionPath: undefined,
  282. });
  283. });
  284. });