read-file-state-hydrator.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. import { describe, expect, it } from "vitest";
  2. import { join } from "node:path";
  3. import {
  4. createMessageId,
  5. createPartId,
  6. createSessionId,
  7. type MessageWithParts,
  8. type ToolPart,
  9. } from "@zcode/contracts";
  10. import { hydrateReadFileStateFromSession } from "../src/agent/read-file-state-hydrator.js";
  11. import { READ_FILE_UNCHANGED_STUB } from "../src/tool/handlers/read-text.js";
  12. import { createReadFileStatePathKey } from "../src/tool/read-file-state.js";
  13. import type { ReadFileStateEntry, ReadFileStateMap } from "../src/tool/types.js";
  14. const workspaceRoot = "/tmp/zcode-read-state-hydrator";
  15. describe("read file state hydrator", () => {
  16. it("restores full Read state from structured completed metadata", async () => {
  17. const sessionID = createSessionId("hydrate-read-state-full");
  18. const file = join(workspaceRoot, "src", "index.ts");
  19. const readFileState: ReadFileStateMap = new Map();
  20. const result = await hydrateReadFileStateFromSession({
  21. messages: [
  22. assistantToolMessage(sessionID, "assistant-full-read", 10, [
  23. completedToolPart(sessionID, "assistant-full-read", "tool-read", "Read", {
  24. input: { file_path: "src/index.ts" },
  25. output: "1\texport const answer = 42;\n2\t",
  26. metadata: readStateMetadata(file, "export const answer = 42;\n"),
  27. }),
  28. ]),
  29. ],
  30. markRestoredFromSession: true,
  31. readFileState,
  32. workingDirectory: workspaceRoot,
  33. workspaceRoot,
  34. });
  35. expect(result.restoredCount).toBe(1);
  36. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  37. content: "export const answer = 42;\n",
  38. isPartialView: false,
  39. limit: undefined,
  40. mtimeMs: 1,
  41. offset: undefined,
  42. path: file,
  43. restoredFromSession: true,
  44. revisionId: `rev:${file}:${Buffer.byteLength("export const answer = 42;\n", "utf8")}:1`,
  45. });
  46. });
  47. // 修复原因:旧数据里 file_unchanged 的 Read 也存了快照(当时最新记录的副本)。按它重放会把
  48. // 读取时间改成这次调用的时间;之前那次真实读取不在 active history 里时,还会恢复出模型看不到原文的视图。
  49. it("skips stored file_unchanged Read snapshots and keeps the earlier real Read", async () => {
  50. const sessionID = createSessionId("hydrate-read-state-skip-unchanged");
  51. const file = join(workspaceRoot, "src", "unchanged.ts");
  52. const unchangedOnly = join(workspaceRoot, "src", "unchanged-only.ts");
  53. const readFileState: ReadFileStateMap = new Map();
  54. const result = await hydrateReadFileStateFromSession({
  55. messages: [
  56. assistantToolMessage(sessionID, "assistant-real-read", 10, [
  57. completedToolPart(sessionID, "assistant-real-read", "tool-real-read", "Read", {
  58. input: { file_path: file },
  59. output: "1\tsame",
  60. metadata: readStateMetadata(file, "same", { readAtMs: 2 }),
  61. }),
  62. ]),
  63. assistantToolMessage(sessionID, "assistant-unchanged-read", 20, [
  64. completedToolPart(sessionID, "assistant-unchanged-read", "tool-unchanged", "Read", {
  65. input: { file_path: file },
  66. output: READ_FILE_UNCHANGED_STUB,
  67. metadata: readStateMetadata(file, "same", { readAtMs: 30 }),
  68. }),
  69. completedToolPart(sessionID, "assistant-unchanged-read", "tool-unchanged-only", "Read", {
  70. input: { file_path: unchangedOnly },
  71. output: READ_FILE_UNCHANGED_STUB,
  72. metadata: readStateMetadata(unchangedOnly, "summarized", { readAtMs: 31 }),
  73. }),
  74. ]),
  75. ],
  76. readFileState,
  77. workingDirectory: workspaceRoot,
  78. workspaceRoot,
  79. });
  80. expect(result.restoredCount).toBe(1);
  81. expect([...readFileState.values()]).toEqual([
  82. expect.objectContaining({ content: "same", path: file, readAt: new Date(2) }),
  83. ]);
  84. });
  85. it.each([0, 1])(
  86. "restores explicit offset %i Read without limit as a full Read",
  87. async (offset) => {
  88. const sessionID = createSessionId(`hydrate-read-state-full-offset-${offset}`);
  89. const file = join(workspaceRoot, "src", `offset-${offset}.ts`);
  90. const readFileState: ReadFileStateMap = new Map();
  91. const result = await hydrateReadFileStateFromSession({
  92. messages: [
  93. assistantToolMessage(sessionID, `assistant-full-offset-${offset}`, 10, [
  94. completedToolPart(sessionID, `assistant-full-offset-${offset}`, "tool-read", "Read", {
  95. input: { file_path: file, offset },
  96. output: "1\talpha\n2\tbeta\n",
  97. metadata: readStateMetadata(file, "alpha\nbeta\n", { offset }),
  98. }),
  99. ]),
  100. ],
  101. readFileState,
  102. workingDirectory: workspaceRoot,
  103. workspaceRoot,
  104. });
  105. expect(result.restoredCount).toBe(1);
  106. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  107. content: "alpha\nbeta\n",
  108. isPartialView: false,
  109. limit: undefined,
  110. offset: undefined,
  111. path: file,
  112. });
  113. },
  114. );
  115. it("skips string-only Read output when completed metadata is missing", async () => {
  116. const sessionID = createSessionId("hydrate-read-state-legacy-output");
  117. const file = join(workspaceRoot, "src", "legacy.ts");
  118. const readFileState: ReadFileStateMap = new Map();
  119. const result = await hydrateReadFileStateFromSession({
  120. messages: [
  121. assistantToolMessage(sessionID, "assistant-legacy-read", 10, [
  122. completedToolPart(sessionID, "assistant-legacy-read", "tool-read-legacy", "Read", {
  123. input: { file_path: file },
  124. output:
  125. "1\talpha\n2\tbeta\n\n<system-reminder>\nWhenever you read a file, you should consider whether it would be considered malware.\n</system-reminder>\n",
  126. }),
  127. ]),
  128. ],
  129. readFileState,
  130. workingDirectory: workspaceRoot,
  131. workspaceRoot,
  132. });
  133. expect(result.restoredCount).toBe(0);
  134. expect(readFileState.size).toBe(0);
  135. });
  136. it("skips Read metadata without complete freshness fields", async () => {
  137. const sessionID = createSessionId("hydrate-read-state-incomplete-metadata");
  138. const file = join(workspaceRoot, "src", "incomplete.ts");
  139. const readFileState: ReadFileStateMap = new Map();
  140. const result = await hydrateReadFileStateFromSession({
  141. messages: [
  142. assistantToolMessage(sessionID, "assistant-incomplete-read", 10, [
  143. completedToolPart(
  144. sessionID,
  145. "assistant-incomplete-read",
  146. "tool-read-incomplete",
  147. "Read",
  148. {
  149. input: { file_path: file },
  150. output: "1\tincomplete\n2\t",
  151. metadata: {
  152. readFileState: {
  153. content: "incomplete\n",
  154. isPartialView: false,
  155. path: file,
  156. readAtMs: 2,
  157. schemaVersion: 1,
  158. sizeBytes: Buffer.byteLength("incomplete\n", "utf8"),
  159. tool: "Read",
  160. },
  161. schemaVersion: 1,
  162. },
  163. },
  164. ),
  165. ]),
  166. ],
  167. readFileState,
  168. workingDirectory: workspaceRoot,
  169. workspaceRoot,
  170. });
  171. expect(result.restoredCount).toBe(0);
  172. expect(readFileState.size).toBe(0);
  173. });
  174. it("restores historical range Reads with their offset and limit", async () => {
  175. const sessionID = createSessionId("hydrate-read-state-range");
  176. const file = join(workspaceRoot, "src", "range.ts");
  177. const readFileState: ReadFileStateMap = new Map();
  178. const result = await hydrateReadFileStateFromSession({
  179. messages: [
  180. assistantToolMessage(sessionID, "assistant-range-read", 10, [
  181. completedToolPart(sessionID, "assistant-range-read", "tool-read-range", "Read", {
  182. input: { file_path: file, offset: 2, limit: 1 },
  183. output: "2\tline two",
  184. metadata: readStateMetadata(file, "line two", { offset: 2, limit: 1 }),
  185. }),
  186. ]),
  187. ],
  188. readFileState,
  189. workingDirectory: workspaceRoot,
  190. workspaceRoot,
  191. });
  192. // range Read 和 same-runtime 一样是有效的读取记录。
  193. expect(result.restoredCount).toBe(1);
  194. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  195. content: "line two",
  196. isPartialView: false,
  197. limit: 1,
  198. offset: 2,
  199. path: file,
  200. });
  201. });
  202. it("keeps only the latest Read per file, including a later range Read", async () => {
  203. const sessionID = createSessionId("hydrate-read-state-full-then-range");
  204. const file = join(workspaceRoot, "src", "full-then-range.ts");
  205. const readFileState: ReadFileStateMap = new Map();
  206. const result = await hydrateReadFileStateFromSession({
  207. messages: [
  208. assistantToolMessage(sessionID, "assistant-full-read-before-range", 10, [
  209. completedToolPart(
  210. sessionID,
  211. "assistant-full-read-before-range",
  212. "tool-read-full",
  213. "Read",
  214. {
  215. input: { file_path: file },
  216. output: "1\tline one\n2\tline two\n3\t",
  217. metadata: readStateMetadata(file, "line one\nline two\n"),
  218. },
  219. ),
  220. ]),
  221. assistantToolMessage(sessionID, "assistant-range-read-after-full", 20, [
  222. completedToolPart(
  223. sessionID,
  224. "assistant-range-read-after-full",
  225. "tool-read-range-after-full",
  226. "Read",
  227. {
  228. input: { file_path: file, offset: 2, limit: 1 },
  229. output: "2\tline two",
  230. metadata: readStateMetadata(file, "line two", { offset: 2, limit: 1 }),
  231. },
  232. ),
  233. ]),
  234. ],
  235. readFileState,
  236. workingDirectory: workspaceRoot,
  237. workspaceRoot,
  238. });
  239. // 冷恢复与 same-runtime 相同:最近一次是 range 视图,之后的完整 Read 会返回正文。
  240. expect(result.restoredCount).toBe(2);
  241. expect(readFileState.size).toBe(1);
  242. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  243. content: "line two",
  244. limit: 1,
  245. offset: 2,
  246. path: file,
  247. });
  248. });
  249. it("restores a Read from its metadata even when the stored tool input is not an object", async () => {
  250. const sessionID = createSessionId("hydrate-read-state-odd-input");
  251. const file = join(workspaceRoot, "src", "odd-input.ts");
  252. const readFileState: ReadFileStateMap = new Map();
  253. const part = completedToolPart(sessionID, "assistant-odd-input", "tool-read-odd", "Read", {
  254. input: {},
  255. output: "1\tvalue\n2\t",
  256. metadata: readStateMetadata(file, "value\n"),
  257. });
  258. // 恢复只读 metadata;input 不参与,形态异常也不能挡住恢复。
  259. (part.state as { input: unknown }).input = "not-an-object";
  260. const result = await hydrateReadFileStateFromSession({
  261. messages: [assistantToolMessage(sessionID, "assistant-odd-input", 10, [part])],
  262. readFileState,
  263. workingDirectory: workspaceRoot,
  264. workspaceRoot,
  265. });
  266. expect(result.restoredCount).toBe(1);
  267. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  268. content: "value\n",
  269. });
  270. });
  271. it("orders Reads across assistant messages by history, not by readAtMs", async () => {
  272. const sessionID = createSessionId("hydrate-read-state-history-over-clock");
  273. const file = join(workspaceRoot, "src", "history-over-clock.ts");
  274. const readFileState: ReadFileStateMap = new Map();
  275. await hydrateReadFileStateFromSession({
  276. messages: [
  277. assistantToolMessage(sessionID, "assistant-full-read-late-clock", 10, [
  278. completedToolPart(sessionID, "assistant-full-read-late-clock", "tool-read-full", "Read", {
  279. input: { file_path: file },
  280. output: "1\tline one\n2\tline two\n3\t",
  281. metadata: readStateMetadata(file, "line one\nline two\n", { readAtMs: 100 }),
  282. }),
  283. ]),
  284. assistantToolMessage(sessionID, "assistant-range-read-early-clock", 20, [
  285. completedToolPart(
  286. sessionID,
  287. "assistant-range-read-early-clock",
  288. "tool-read-range",
  289. "Read",
  290. {
  291. input: { file_path: file, offset: 2, limit: 1 },
  292. output: "2\tline two",
  293. metadata: readStateMetadata(file, "line two", { offset: 2, limit: 1, readAtMs: 50 }),
  294. },
  295. ),
  296. ]),
  297. ],
  298. readFileState,
  299. workingDirectory: workspaceRoot,
  300. workspaceRoot,
  301. });
  302. // 不同批次之间历史顺序就是 live 的更新顺序;系统时钟回拨不能改变它。
  303. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  304. limit: 1,
  305. offset: 2,
  306. });
  307. });
  308. // 修复原因:part 在工具开始前按声明顺序落盘,完成时原地更新、位置不变,part 顺序不是写入顺序。
  309. // 并行时范围 Read 先写、完整 Read 后写,live 最后是完整视图;按 part 顺序重放会选成范围视图。
  310. it.each([
  311. ["by snapshotIndex when the full Read writes last", { full: 1, range: 0 }, "full"],
  312. ["by snapshotIndex when the range Read writes last", { full: 0, range: 1 }, "range"],
  313. ["in part order for legacy snapshots without snapshotIndex", {}, "range"],
  314. ["in part order when only some snapshots carry snapshotIndex", { full: 1 }, "range"],
  315. ] as const)(
  316. "replays Reads within one assistant message %s",
  317. async (_label, snapshotIndex: { full?: number; range?: number }, expectedView) => {
  318. const sessionID = createSessionId("hydrate-read-state-snapshot-order");
  319. const file = join(workspaceRoot, "src", "snapshot-order.ts");
  320. const readFileState: ReadFileStateMap = new Map();
  321. await hydrateReadFileStateFromSession({
  322. messages: [
  323. assistantToolMessage(sessionID, "assistant-parallel-reads", 10, [
  324. completedToolPart(sessionID, "assistant-parallel-reads", "tool-read-full", "Read", {
  325. input: { file_path: file },
  326. output: "1\tline one\n2\tline two\n3\t",
  327. metadata: readStateMetadata(file, "line one\nline two\n", {
  328. snapshotIndex: snapshotIndex.full,
  329. }),
  330. }),
  331. completedToolPart(sessionID, "assistant-parallel-reads", "tool-read-range", "Read", {
  332. input: { file_path: file, offset: 2, limit: 1 },
  333. output: "2\tline two",
  334. metadata: readStateMetadata(file, "line two", {
  335. offset: 2,
  336. limit: 1,
  337. snapshotIndex: snapshotIndex.range,
  338. }),
  339. }),
  340. ]),
  341. ],
  342. readFileState,
  343. workingDirectory: workspaceRoot,
  344. workspaceRoot,
  345. });
  346. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject(
  347. expectedView === "full"
  348. ? { content: "line one\nline two\n", limit: undefined }
  349. : { content: "line two", limit: 1, offset: 2 },
  350. );
  351. },
  352. );
  353. it("restores a later token-truncated full Read as partial state over an earlier full Read", async () => {
  354. const sessionID = createSessionId("hydrate-read-state-full-then-partial");
  355. const file = join(workspaceRoot, "src", "full-then-partial.ts");
  356. const readFileState: ReadFileStateMap = new Map();
  357. const result = await hydrateReadFileStateFromSession({
  358. messages: [
  359. assistantToolMessage(sessionID, "assistant-full-read-before-partial", 10, [
  360. completedToolPart(
  361. sessionID,
  362. "assistant-full-read-before-partial",
  363. "tool-read-full-before-partial",
  364. "Read",
  365. {
  366. input: { file_path: file },
  367. output: "1\tline one\n2\tline two\n3\t",
  368. metadata: readStateMetadata(file, "line one\nline two\n"),
  369. },
  370. ),
  371. ]),
  372. assistantToolMessage(sessionID, "assistant-partial-full-read-after-full", 20, [
  373. completedToolPart(
  374. sessionID,
  375. "assistant-partial-full-read-after-full",
  376. "tool-read-partial-after-full",
  377. "Read",
  378. {
  379. input: { file_path: file },
  380. output: "1\tline one\n<system-reminder>partial view</system-reminder>",
  381. metadata: readStateMetadata(file, "line one\n", { isPartialView: true }),
  382. },
  383. ),
  384. ]),
  385. ],
  386. readFileState,
  387. workingDirectory: workspaceRoot,
  388. workspaceRoot,
  389. });
  390. expect(result.restoredCount).toBe(2);
  391. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  392. content: "line one\n",
  393. isPartialView: true,
  394. limit: undefined,
  395. offset: undefined,
  396. path: file,
  397. });
  398. });
  399. it("restores Write state from structured metadata", async () => {
  400. const sessionID = createSessionId("hydrate-read-state-write-completed-time");
  401. const file = join(workspaceRoot, "src", "write-completed-time.ts");
  402. const readFileState: ReadFileStateMap = new Map();
  403. await hydrateReadFileStateFromSession({
  404. messages: [
  405. assistantToolMessage(sessionID, "assistant-write-completed-time", 10, [
  406. completedToolPart(
  407. sessionID,
  408. "assistant-write-completed-time",
  409. "tool-write-completed-time",
  410. "Write",
  411. {
  412. input: { file_path: file, content: "written\n" },
  413. output: "The file has been updated successfully.",
  414. metadata: readStateMetadata(file, "written\n", { tool: "Write" }),
  415. time: { start: 100, end: 200 },
  416. },
  417. ),
  418. ]),
  419. ],
  420. readFileState,
  421. workingDirectory: workspaceRoot,
  422. workspaceRoot,
  423. });
  424. expect(readFileState.get(createReadFileStatePathKey(file))).toMatchObject({
  425. content: "written\n",
  426. mtimeMs: 1,
  427. path: file,
  428. readAt: new Date(2),
  429. revisionId: `rev:${file}:${Buffer.byteLength("written\n", "utf8")}:1`,
  430. });
  431. });
  432. it("skips legacy Write and Edit parts without structured read state metadata", async () => {
  433. const sessionID = createSessionId("hydrate-read-state-write-edit-legacy-skip");
  434. const writeFile = join(workspaceRoot, "legacy-written.ts");
  435. const editFile = join(workspaceRoot, "legacy-edited.ts");
  436. const readFileState: ReadFileStateMap = new Map();
  437. const result = await hydrateReadFileStateFromSession({
  438. messages: [
  439. assistantToolMessage(sessionID, "assistant-write-edit-legacy", 10, [
  440. completedToolPart(
  441. sessionID,
  442. "assistant-write-edit-legacy",
  443. "tool-write-legacy",
  444. "Write",
  445. {
  446. input: { file_path: writeFile, content: "written content\n" },
  447. output: "The file has been updated successfully.",
  448. },
  449. ),
  450. completedToolPart(sessionID, "assistant-write-edit-legacy", "tool-edit-legacy", "Edit", {
  451. input: { file_path: editFile, old_string: "old", new_string: "edited" },
  452. output: "The file has been updated successfully.",
  453. }),
  454. ]),
  455. ],
  456. readFileState,
  457. workingDirectory: workspaceRoot,
  458. workspaceRoot,
  459. });
  460. expect(result.restoredCount).toBe(0);
  461. expect(readFileState.size).toBe(0);
  462. });
  463. it("restores Write and Edit states from structured metadata without reading current disk", async () => {
  464. const sessionID = createSessionId("hydrate-read-state-write-edit");
  465. const writeFile = join(workspaceRoot, "written.ts");
  466. const editFile = join(workspaceRoot, "edited.ts");
  467. const readFileState: ReadFileStateMap = new Map();
  468. const result = await hydrateReadFileStateFromSession({
  469. messages: [
  470. assistantToolMessage(sessionID, "assistant-write-edit", 10, [
  471. completedToolPart(sessionID, "assistant-write-edit", "tool-write", "Write", {
  472. input: { file_path: writeFile, content: "written content\n" },
  473. metadata: readStateMetadata(writeFile, "written content\n", { tool: "Write" }),
  474. output: "The file has been updated successfully.",
  475. }),
  476. completedToolPart(sessionID, "assistant-write-edit", "tool-edit", "Edit", {
  477. input: { file_path: editFile, old_string: "old", new_string: "edited" },
  478. metadata: readStateMetadata(editFile, "edited from metadata\n", { tool: "Edit" }),
  479. output: "The file has been updated successfully.",
  480. }),
  481. ]),
  482. ],
  483. readFileState,
  484. workingDirectory: workspaceRoot,
  485. workspaceRoot,
  486. });
  487. expect(result.restoredCount).toBe(2);
  488. expect(readFileState.get(createReadFileStatePathKey(writeFile))).toMatchObject({
  489. content: "written content\n",
  490. isPartialView: false,
  491. path: writeFile,
  492. });
  493. expect(readFileState.get(createReadFileStatePathKey(editFile))).toMatchObject({
  494. content: "edited from metadata\n",
  495. isPartialView: false,
  496. path: editFile,
  497. });
  498. });
  499. it("keeps the context seed on rewind and clears it on resume", async () => {
  500. const sessionID = createSessionId("hydrate-read-state-context-seed");
  501. const memoryIndex = join(workspaceRoot, "memory", "MEMORY.md");
  502. const rewoundFile = join(workspaceRoot, "rewound.ts");
  503. const seed = {
  504. path: memoryIndex,
  505. content: "- [Note](note.md)\n",
  506. isPartialView: false,
  507. readAt: new Date(1),
  508. seededFromContext: true as const,
  509. mtimeMs: 1,
  510. sizeBytes: 18,
  511. };
  512. const seeded = (): ReadFileStateMap =>
  513. new Map<string, ReadFileStateEntry>([
  514. [createReadFileStatePathKey(memoryIndex), seed],
  515. [
  516. createReadFileStatePathKey(rewoundFile),
  517. { path: rewoundFile, content: "x", isPartialView: false, readAt: new Date(2) },
  518. ],
  519. ]);
  520. const messages = [
  521. assistantToolMessage(sessionID, "assistant-kept", 10, [
  522. completedToolPart(sessionID, "assistant-kept", "tool-kept", "Read", {
  523. input: { file_path: join(workspaceRoot, "kept.ts") },
  524. output: "1\tkept",
  525. metadata: readStateMetadata(join(workspaceRoot, "kept.ts"), "kept"),
  526. }),
  527. ]),
  528. ];
  529. // 修复原因:rewind 重建时清空整张表,会话开始由 context 写入的 MEMORY.md 记录也被清掉,
  530. // 之后 Write MEMORY.md 报未读。rewind 只按 active history 重建工具记录,保留这条。
  531. const afterRewind = seeded();
  532. await hydrateReadFileStateFromSession({
  533. messages,
  534. readFileState: afterRewind,
  535. retainContextSeeds: true,
  536. workingDirectory: workspaceRoot,
  537. workspaceRoot,
  538. });
  539. expect(afterRewind.get(createReadFileStatePathKey(memoryIndex))).toBe(seed);
  540. expect(afterRewind.has(createReadFileStatePathKey(rewoundFile))).toBe(false);
  541. // 修复原因:rewind 重建的记录曾被标成冷恢复,compaction 改按读取时间选文件;同进程重建应和 live 一样按 mtime。
  542. expect(afterRewind.get(createReadFileStatePathKey(join(workspaceRoot, "kept.ts")))).toEqual(
  543. expect.not.objectContaining({ restoredFromSession: true }),
  544. );
  545. // resume 全部清空,由 context 初始化重新写入。
  546. const afterResume = seeded();
  547. await hydrateReadFileStateFromSession({
  548. messages,
  549. readFileState: afterResume,
  550. workingDirectory: workspaceRoot,
  551. workspaceRoot,
  552. });
  553. expect(afterResume.has(createReadFileStatePathKey(memoryIndex))).toBe(false);
  554. });
  555. it("only restores tool state from messages after the active compaction boundary", async () => {
  556. const sessionID = createSessionId("hydrate-read-state-compact");
  557. const oldFile = join(workspaceRoot, "old.ts");
  558. const newFile = join(workspaceRoot, "new.ts");
  559. const readFileState: ReadFileStateMap = new Map();
  560. await hydrateReadFileStateFromSession({
  561. messages: [
  562. assistantToolMessage(sessionID, "assistant-before-compact", 10, [
  563. completedToolPart(sessionID, "assistant-before-compact", "tool-old", "Read", {
  564. input: { file_path: oldFile },
  565. output: "1\told\n2\t",
  566. metadata: readStateMetadata(oldFile, "old\n"),
  567. }),
  568. ]),
  569. compactionMessage(sessionID, "compact-boundary", 20),
  570. assistantToolMessage(sessionID, "assistant-after-compact", 30, [
  571. completedToolPart(sessionID, "assistant-after-compact", "tool-new", "Read", {
  572. input: { file_path: newFile },
  573. output: "1\tnew\n2\t",
  574. metadata: readStateMetadata(newFile, "new\n"),
  575. }),
  576. ]),
  577. ],
  578. readFileState,
  579. workingDirectory: workspaceRoot,
  580. workspaceRoot,
  581. });
  582. expect(readFileState.has(createReadFileStatePathKey(oldFile))).toBe(false);
  583. expect(readFileState.has(createReadFileStatePathKey(newFile))).toBe(true);
  584. });
  585. });
  586. function completedToolPart(
  587. sessionID: ReturnType<typeof createSessionId>,
  588. messageIDText: string,
  589. callID: string,
  590. tool: string,
  591. state: {
  592. input: Record<string, unknown>;
  593. metadata?: Record<string, unknown>;
  594. output: string;
  595. time?: {
  596. end: number;
  597. start: number;
  598. };
  599. },
  600. ): ToolPart {
  601. const messageID = createMessageId(messageIDText);
  602. return {
  603. callID,
  604. id: createPartId(`${callID}-part`),
  605. messageID,
  606. sessionID,
  607. state: {
  608. input: state.input,
  609. metadata: state.metadata ?? { schemaVersion: 1 },
  610. output: state.output,
  611. status: "completed",
  612. title: tool,
  613. time: state.time ?? { start: 1, end: 2 },
  614. },
  615. tool,
  616. type: "tool",
  617. };
  618. }
  619. function assistantToolMessage(
  620. sessionID: ReturnType<typeof createSessionId>,
  621. messageIDText: string,
  622. created: number,
  623. parts: ToolPart[],
  624. ): MessageWithParts {
  625. const messageID = createMessageId(messageIDText);
  626. return {
  627. info: {
  628. agent: "zcode-agent",
  629. cost: 0,
  630. id: messageID,
  631. mode: "build",
  632. modelID: "model-test",
  633. parentID: createMessageId(`${messageIDText}-user`),
  634. path: { cwd: workspaceRoot, root: workspaceRoot },
  635. providerID: "provider-test",
  636. role: "assistant",
  637. sessionID,
  638. time: { created },
  639. tokens: emptyTokens(),
  640. },
  641. parts,
  642. };
  643. }
  644. function compactionMessage(
  645. sessionID: ReturnType<typeof createSessionId>,
  646. messageIDText: string,
  647. created: number,
  648. ): MessageWithParts {
  649. const messageID = createMessageId(messageIDText);
  650. return {
  651. info: {
  652. agent: "zcode-agent",
  653. id: messageID,
  654. model: { modelID: "model-test", providerID: "provider-test" },
  655. role: "user",
  656. sessionID,
  657. time: { created },
  658. },
  659. parts: [
  660. {
  661. id: createPartId(`${messageIDText}-part`),
  662. messageID,
  663. sessionID,
  664. type: "compaction",
  665. } as MessageWithParts["parts"][number],
  666. ],
  667. };
  668. }
  669. function readStateMetadata(
  670. filePath: string,
  671. content: string,
  672. options: {
  673. isPartialView?: boolean;
  674. limit?: number;
  675. offset?: number;
  676. readAtMs?: number;
  677. snapshotIndex?: number;
  678. tool?: "Read" | "Write" | "Edit";
  679. } = {},
  680. ): Record<string, unknown> {
  681. const sizeBytes = Buffer.byteLength(content, "utf8");
  682. return {
  683. readFileState: {
  684. content,
  685. isPartialView: options.isPartialView ?? false,
  686. ...(options.limit === undefined ? {} : { limit: options.limit }),
  687. mtimeMs: 1,
  688. ...(options.offset === undefined ? {} : { offset: options.offset }),
  689. path: filePath,
  690. readAtMs: options.readAtMs ?? 2,
  691. revisionId: `rev:${filePath}:${sizeBytes}:1`,
  692. schemaVersion: 1,
  693. sizeBytes,
  694. ...(options.snapshotIndex === undefined ? {} : { snapshotIndex: options.snapshotIndex }),
  695. tool: options.tool ?? "Read",
  696. },
  697. schemaVersion: 1,
  698. };
  699. }
  700. function emptyTokens() {
  701. return {
  702. cache: {
  703. read: 0,
  704. write: 0,
  705. },
  706. input: 0,
  707. output: 0,
  708. reasoning: 0,
  709. };
  710. }