post-compact-file-restore.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { ReadTextOutput } from "@zcode/contracts";
  3. import type { RuntimeMessageEntry } from "../src/agent/message-history.js";
  4. import {
  5. buildPostCompactFileRestore,
  6. replaceReadFileStateAfterCompact,
  7. type PostCompactFileRead,
  8. } from "../src/runtime/helpers/compact-post-reminders.js";
  9. import { READ_FILE_UNCHANGED_STUB } from "../src/tool/handlers/read-text.js";
  10. import { createReadFileStatePathKey } from "../src/tool/read-file-state.js";
  11. import type { ReadFileStateEntry, ReadFileStateMap } from "../src/tool/types.js";
  12. const root = "/tmp/zcode-post-compact-file-restore";
  13. describe("post-compact file restore", () => {
  14. it("re-reads Read, Write and Edit records and skips other writers and excluded paths", async () => {
  15. const files = {
  16. read: `${root}/src/read.ts`,
  17. written: `${root}/src/written.ts`,
  18. edited: `${root}/src/edited.ts`,
  19. bashBackfill: `${root}/src/bash.ts`,
  20. seeded: `${root}/memory/MEMORY.md`,
  21. draft: `${root}/.zcode/workflows/draft.js`,
  22. plan: `${root}/.zcode/plans/plan-session.md`,
  23. instructions: `${root}/AGENTS.md`,
  24. codexMemory: "/Users/dev/.codex/memories/note.md",
  25. superpowersPlan: `${root}/docs/superpowers/plans/plan.md`,
  26. git: `${root}/.git/config`,
  27. };
  28. const readFileState = createState([
  29. entry(files.read, { mtimeMs: 9, sourceTool: "Read" }),
  30. entry(files.written, { mtimeMs: 8, sourceTool: "Write" }),
  31. entry(files.edited, { mtimeMs: 7, sourceTool: "Edit" }),
  32. entry(files.bashBackfill, { mtimeMs: 20 }),
  33. entry(files.seeded, { mtimeMs: 20, seededFromContext: true }),
  34. entry(files.draft, { mtimeMs: 20, sourceTool: "CreateWorkflow" }),
  35. entry(files.plan, { mtimeMs: 20, sourceTool: "Read" }),
  36. entry(files.instructions, { mtimeMs: 20, sourceTool: "Read" }),
  37. entry(files.codexMemory, { mtimeMs: 20, sourceTool: "Read" }),
  38. entry(files.superpowersPlan, { mtimeMs: 20, sourceTool: "Read" }),
  39. entry(files.git, { mtimeMs: 20, sourceTool: "Read" }),
  40. ]);
  41. const readFiles = vi.fn(perFile(async (filePath) => textRead(filePath, `disk ${filePath}`)));
  42. const restore = await buildPostCompactFileRestore({
  43. excludedPaths: [files.plan, files.instructions],
  44. readFiles,
  45. readFileState,
  46. });
  47. // 一次拿到全部候选,读权限规则只需加载一次。
  48. expect(readFiles.mock.calls.map(([paths]) => paths)).toEqual([
  49. [files.read, files.written, files.edited],
  50. ]);
  51. // 补回的是磁盘上的当前内容,不是读取状态里缓存的视图。
  52. expect(restore.entries.map(attachmentText)).toEqual([
  53. restoredText(files.read, `1\tdisk ${files.read}`),
  54. restoredText(files.written, `1\tdisk ${files.written}`),
  55. restoredText(files.edited, `1\tdisk ${files.edited}`),
  56. ]);
  57. expect(restore.entries.every(isFileRestoreAttachment)).toBe(true);
  58. expect(restore.readFileStateEntries.map((restored) => restored.path)).toEqual([
  59. files.read,
  60. files.written,
  61. files.edited,
  62. ]);
  63. expect(readFileState.size).toBe(11);
  64. });
  65. it("reads range records as the whole current file and records full views", async () => {
  66. const file = `${root}/src/range.ts`;
  67. const readFileState = createState([
  68. entry(file, { content: "two", limit: 1, offset: 2, sourceTool: "Read" }),
  69. ]);
  70. const restore = await buildPostCompactFileRestore({
  71. readFiles: perFile(async (filePath) => textRead(filePath, "one\ntwo\nthree")),
  72. readFileState,
  73. });
  74. expect(restore.entries.map(attachmentText)).toEqual([
  75. restoredText(file, "1\tone\n2\ttwo\n3\tthree"),
  76. ]);
  77. expect(restore.readFileStateEntries).toEqual([
  78. expect.objectContaining({
  79. content: "one\ntwo\nthree",
  80. isPartialView: false,
  81. path: file,
  82. sourceTool: "Read",
  83. }),
  84. ]);
  85. });
  86. it("uses the Read tool result text for the restored body", async () => {
  87. const file = `${root}/src/empty.ts`;
  88. const restore = await buildPostCompactFileRestore({
  89. readFiles: perFile(async (filePath) =>
  90. textRead(filePath, "", { numLines: 0, startLine: 1, totalLines: 0 }),
  91. ),
  92. readFileState: createState([entry(file, { sourceTool: "Read" })]),
  93. });
  94. expect(restore.entries.map(attachmentText)).toEqual([
  95. restoredText(
  96. file,
  97. "<system-reminder>Warning: the file exists but the contents are empty.</system-reminder>",
  98. ),
  99. ]);
  100. });
  101. it("skips files Read in the preserved segment unless that Read returned file_unchanged", async () => {
  102. const preservedFile = `${root}/src/preserved.ts`;
  103. const unchangedFile = `${root}/src/unchanged.ts`;
  104. const preservedEntries: RuntimeMessageEntry[] = [
  105. {
  106. message: {
  107. role: "assistant",
  108. content: "",
  109. toolCalls: [
  110. { id: "read-preserved", input: { file_path: preservedFile }, name: "Read" },
  111. { id: "read-unchanged", input: { file_path: unchangedFile }, name: "Read" },
  112. ],
  113. },
  114. },
  115. {
  116. message: {
  117. role: "tool",
  118. content: "1\texport const preserved = 1;",
  119. toolCallId: "read-preserved",
  120. toolName: "Read",
  121. },
  122. },
  123. {
  124. message: {
  125. role: "tool",
  126. content: READ_FILE_UNCHANGED_STUB,
  127. toolCallId: "read-unchanged",
  128. toolName: "Read",
  129. },
  130. },
  131. ];
  132. const readFiles = vi.fn(perFile(async (filePath) => textRead(filePath, "current")));
  133. await buildPostCompactFileRestore({
  134. preservedEntries,
  135. readFiles,
  136. readFileState: createState([
  137. entry(preservedFile, { mtimeMs: 2, sourceTool: "Read" }),
  138. entry(unchangedFile, { mtimeMs: 1, sourceTool: "Read" }),
  139. ]),
  140. });
  141. expect(readFiles.mock.calls.map(([paths]) => paths)).toEqual([[unchangedFile]]);
  142. });
  143. it("selects the five newest records before reading and lets skipped files keep their slot", async () => {
  144. const live = (name: string, mtimeMs: number, readAtMs: number) =>
  145. entry(`${root}/src/${name}.ts`, { mtimeMs, readAt: new Date(readAtMs), sourceTool: "Read" });
  146. const readFileState = createState([
  147. live("oldest", 1, 900),
  148. live("missing", 60, 10),
  149. live("newest", 70, 10),
  150. // 冷恢复出的记录按读取时间排序,不看 mtimeMs。
  151. entry(`${root}/src/resumed.ts`, {
  152. mtimeMs: 1,
  153. readAt: new Date(65),
  154. restoredFromSession: true,
  155. sourceTool: "Read",
  156. }),
  157. // 缺 mtimeMs 时用读取时间。
  158. entry(`${root}/src/no-mtime.ts`, { readAt: new Date(50), sourceTool: "Edit" }),
  159. live("fifth", 40, 10),
  160. live("sixth", 30, 10),
  161. ]);
  162. const readFiles = vi.fn(
  163. perFile(
  164. async (filePath): Promise<PostCompactFileRead> =>
  165. filePath.endsWith("missing.ts") ? { type: "skipped" } : textRead(filePath, filePath),
  166. ),
  167. );
  168. const restore = await buildPostCompactFileRestore({ readFiles, readFileState });
  169. expect(readFiles.mock.calls.map(([paths]) => paths)).toEqual([
  170. [
  171. `${root}/src/newest.ts`,
  172. `${root}/src/resumed.ts`,
  173. `${root}/src/missing.ts`,
  174. `${root}/src/no-mtime.ts`,
  175. `${root}/src/fifth.ts`,
  176. ],
  177. ]);
  178. expect(restore.readFileStateEntries.map((restored) => restored.path)).toEqual([
  179. `${root}/src/newest.ts`,
  180. `${root}/src/resumed.ts`,
  181. `${root}/src/no-mtime.ts`,
  182. `${root}/src/fifth.ts`,
  183. ]);
  184. });
  185. it("references files over the per-file token cap and records them as partial views", async () => {
  186. const capped = `${root}/src/capped.ts`;
  187. const truncated = `${root}/src/truncated.ts`;
  188. const tooLarge = `${root}/src/too-large.ts`;
  189. const restore = await buildPostCompactFileRestore({
  190. maxFileTokens: 10,
  191. readFiles: perFile(async (filePath): Promise<PostCompactFileRead> => {
  192. if (filePath === capped) return textRead(filePath, "x".repeat(31));
  193. if (filePath === truncated) {
  194. return textRead(filePath, "short", { truncated: true, truncatedByTokenCap: true });
  195. }
  196. return { type: "too_large" };
  197. }),
  198. readFileState: createState([
  199. entry(capped, { mtimeMs: 3, sourceTool: "Read" }),
  200. entry(truncated, { mtimeMs: 2, sourceTool: "Read" }),
  201. entry(tooLarge, { mtimeMs: 1, sourceTool: "Read" }),
  202. ]),
  203. });
  204. expect(restore.entries.map(attachmentText)).toEqual([
  205. referenceText(capped),
  206. referenceText(truncated),
  207. referenceText(tooLarge),
  208. ]);
  209. expect(
  210. restore.readFileStateEntries.map((restored) => [restored.path, restored.isPartialView]),
  211. ).toEqual([
  212. [capped, true],
  213. [truncated, true],
  214. ]);
  215. });
  216. it("drops files that exceed the total token budget without a note or a record", async () => {
  217. const first = `${root}/src/first.ts`;
  218. const dropped = `${root}/src/dropped.ts`;
  219. const small = `${root}/src/small.ts`;
  220. // 每个文件约 150 token(正文 100 token 加上调用说明),小文件约 50 token。
  221. const contents: Record<string, string> = {
  222. [first]: "a".repeat(300),
  223. [dropped]: "b".repeat(300),
  224. [small]: "c",
  225. };
  226. const restore = await buildPostCompactFileRestore({
  227. maxFileTokens: 150,
  228. maxTotalTokens: 250,
  229. readFiles: perFile(async (filePath) => textRead(filePath, contents[filePath] ?? "")),
  230. readFileState: createState([
  231. entry(first, { mtimeMs: 3, sourceTool: "Read" }),
  232. entry(dropped, { mtimeMs: 2, sourceTool: "Read" }),
  233. entry(small, { mtimeMs: 1, sourceTool: "Read" }),
  234. ]),
  235. });
  236. const text = restore.entries.map(attachmentText).join("\n");
  237. expect(text).toContain(first);
  238. expect(text).not.toContain(dropped);
  239. expect(text).toContain(small);
  240. expect(restore.readFileStateEntries.map((restored) => restored.path)).toEqual([first, small]);
  241. });
  242. it("propagates reader failures", async () => {
  243. const file = `${root}/src/aborted.ts`;
  244. await expect(
  245. buildPostCompactFileRestore({
  246. readFiles: async () => {
  247. throw new Error("read aborted");
  248. },
  249. readFileState: createState([entry(file, { sourceTool: "Read" })]),
  250. }),
  251. ).rejects.toThrow("read aborted");
  252. });
  253. });
  254. describe("post-compact file restore paths and read state", () => {
  255. // 修复原因:保留段里 Read 的 file_path 曾不解析就比较,模型用相对路径读过的文件匹配不上,会再补回一份。
  256. it("resolves preserved Read paths against the working directory before excluding them", async () => {
  257. const preservedFile = `${root}/src/relative.ts`;
  258. const readFiles = vi.fn(perFile(async (filePath) => textRead(filePath, "current")));
  259. await buildPostCompactFileRestore({
  260. preservedEntries: [
  261. {
  262. message: {
  263. role: "assistant",
  264. content: "",
  265. toolCalls: [
  266. { id: "read-relative", input: { file_path: "src/relative.ts" }, name: "Read" },
  267. ],
  268. },
  269. },
  270. ],
  271. readFiles,
  272. readFileState: createState([entry(preservedFile, { sourceTool: "Read" })]),
  273. workingDirectory: root,
  274. });
  275. expect(readFiles).not.toHaveBeenCalled();
  276. });
  277. // 修复原因:补回记录曾按选择顺序(新到旧)写入,和"Map 遍历顺序即写入顺序"的约定相反。
  278. it("replaces the shared map in place and writes the newest restored file last", () => {
  279. const readFileState = createState([entry(`${root}/src/before.ts`, { sourceTool: "Read" })]);
  280. const shared = readFileState;
  281. const newest = entry(`${root}/src/newest.ts`, { sourceTool: "Read" });
  282. const oldest = entry(`${root}/src/oldest.ts`, { sourceTool: "Read" });
  283. replaceReadFileStateAfterCompact(readFileState, [newest, oldest]);
  284. expect(readFileState).toBe(shared);
  285. expect([...readFileState.values()]).toEqual([oldest, newest]);
  286. });
  287. });
  288. function perFile(
  289. read: (filePath: string) => Promise<PostCompactFileRead>,
  290. ): (filePaths: readonly string[]) => Promise<PostCompactFileRead[]> {
  291. return (filePaths) => Promise.all(filePaths.map(read));
  292. }
  293. function createState(entries: ReadFileStateEntry[]): ReadFileStateMap {
  294. const state: ReadFileStateMap = new Map();
  295. for (const item of entries) state.set(createReadFileStatePathKey(item.path), item);
  296. return state;
  297. }
  298. function entry(path: string, overrides: Partial<ReadFileStateEntry> = {}): ReadFileStateEntry {
  299. return {
  300. content: `cached ${path}`,
  301. isPartialView: false,
  302. path,
  303. readAt: new Date(1),
  304. ...overrides,
  305. };
  306. }
  307. function textRead(
  308. filePath: string,
  309. content: string,
  310. overrides: Partial<ReadTextOutput> = {},
  311. ): PostCompactFileRead {
  312. const lineCount = content.split("\n").length;
  313. const output: ReadTextOutput = {
  314. content,
  315. filePath,
  316. numLines: lineCount,
  317. startLine: 1,
  318. totalLines: lineCount,
  319. type: "text",
  320. ...overrides,
  321. };
  322. return {
  323. output,
  324. readFileStateEntry: {
  325. content,
  326. isPartialView: output.truncatedByTokenCap === true,
  327. mtimeMs: 1,
  328. path: filePath,
  329. readAt: new Date(2),
  330. revisionId: `rev:${filePath}`,
  331. sizeBytes: Buffer.byteLength(content, "utf8"),
  332. sourceTool: "Read",
  333. },
  334. type: "text",
  335. };
  336. }
  337. function restoredText(filePath: string, body: string): string {
  338. return [
  339. `Called the Read tool with the following input: ${JSON.stringify({ file_path: filePath })}`,
  340. "Result of calling the Read tool:",
  341. body,
  342. ].join("\n");
  343. }
  344. function referenceText(filePath: string): string {
  345. return `Note: ${filePath} was read before the last conversation was summarized, but the contents are too large to include. Use Read tool if you need to access it.`;
  346. }
  347. function attachmentText(entry: RuntimeMessageEntry): string {
  348. return "message" in entry ? String(entry.message.content) : entry.content;
  349. }
  350. function isFileRestoreAttachment(entry: RuntimeMessageEntry): boolean {
  351. return !("message" in entry) && entry.metadata.source === "resume_referenced_session_context";
  352. }