case-read-state-hash-resume.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. import { createHash } from "node:crypto";
  2. import { access, readFile, stat, utimes, writeFile } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { FAKE_MODEL } from "./constants.mjs";
  6. import {
  7. assertCondition,
  8. assertProviderCapture,
  9. buildCaseResult,
  10. buildRuntimeConfig,
  11. createApp,
  12. fakeProviderConfig,
  13. makeCaseDirs,
  14. writeProviderConfig,
  15. } from "./case-utils.mjs";
  16. import { writeJsonFile } from "./artifacts.mjs";
  17. import { prepareWorkspace } from "./workspace.mjs";
  18. import {
  19. chatCompletion,
  20. startScriptedProvider,
  21. stopScriptedProvider,
  22. writeScriptedCaptureFile,
  23. } from "./scripted-provider.mjs";
  24. // 规格:docs/design/v2/tool/17-read-file-state-resume.md「快照不存正文」。
  25. // 真实 CLI、真实 SQLite:快照只存 contentSha256;冷恢复后只 touch 放行、内容变化报 stale;
  26. // 升级前带正文、没有 contentSha256 的旧快照照旧恢复。
  27. const CASE_NAME = "read-state-hash-resume";
  28. const COMPLETION_MARKER = "READ_STATE_HASH_RESUME_E2E_DONE";
  29. const UNEXPECTED_MARKER = "READ_STATE_HASH_RESUME_E2E_UNEXPECTED_EXTRA_REQUEST";
  30. const TARGET_FILE = "target.txt";
  31. const BIG_FILE = "big.txt";
  32. const LEGACY_FILE = "legacy.txt";
  33. const TARGET_INITIAL = "alpha\nbeta\n";
  34. const TARGET_AFTER_EDIT = "gamma\nbeta\n";
  35. const TARGET_AFTER_RESUME_EDIT = "delta\nbeta\n";
  36. // 与上一行同样字节数:大小不变,只有正文哈希能发现变化。
  37. const TARGET_EXTERNAL = "delta\nBETA\n";
  38. const LEGACY_INITIAL = "one\n";
  39. const LEGACY_AFTER_EDIT = "two\n";
  40. const LEGACY_AFTER_RESUME_EDIT = "three\n";
  41. const BIG_HEADER = "HEADER\n";
  42. const BIG_HEADER_EDITED = "HEADER EDITED\n";
  43. const BIG_LINE_COUNT = 400;
  44. // Edit 一个约 21 KB 的文件后,这一条 tool part 的大小上限(升级前它包含整份文件,必然超过)。
  45. const BIG_EDIT_PART_MAX_BYTES = 8 * 1024;
  46. const TOUCH_STEP_MS = 10_000;
  47. const EDIT_SUCCESS = "has been updated successfully";
  48. const STALE_ERROR = "File has been modified since read";
  49. const NOT_READ_ERROR = "File has not been read yet";
  50. export const readStateHashResumeCase = {
  51. name: CASE_NAME,
  52. requiresApiKey: false,
  53. async run(input) {
  54. const events = [];
  55. const failures = [];
  56. const paths = await makeCaseDirs({ ...input, caseName: CASE_NAME });
  57. const sessionDbPath = join(paths.storageDir, "db", "db.sqlite");
  58. const files = {
  59. big: join(paths.workspace, BIG_FILE),
  60. legacy: join(paths.workspace, LEGACY_FILE),
  61. target: join(paths.workspace, TARGET_FILE),
  62. };
  63. const bigContent = buildBigContent();
  64. const steps = buildSteps({ bigContent, files });
  65. let provider;
  66. let app;
  67. try {
  68. await prepareWorkspace({ fixtureDir: input.fixtureDir, workspace: paths.workspace });
  69. await writeFile(files.target, TARGET_INITIAL);
  70. await writeFile(files.legacy, LEGACY_INITIAL);
  71. provider = await startScriptedProvider({
  72. handler: createStepHandler({ failures, steps }),
  73. name: CASE_NAME,
  74. });
  75. await writeProviderConfig(
  76. paths.configPath,
  77. fakeProviderConfig({
  78. baseURL: provider.baseURL,
  79. model: FAKE_MODEL,
  80. storageDir: paths.storageDir,
  81. }),
  82. );
  83. const runtimeConfig = buildRuntimeConfig({
  84. compact: { contextWindow: 1_000_000, microcompact: { enabled: false } },
  85. maxTurns: 12,
  86. workspace: paths.workspace,
  87. });
  88. const appInput = {
  89. configPath: paths.configPath,
  90. modules: input.modules,
  91. runtimeConfig,
  92. sessionDbPath,
  93. storageDir: paths.storageDir,
  94. };
  95. const onEvent = async (event) => events.push(event);
  96. // 第一段:Read/Edit target,Write/Edit 大文件,Read/Edit legacy。
  97. app = await createApp(appInput);
  98. const sessionId = app.sessionId;
  99. const first = await app.submitPrompt("Run read-state hash phase 1.", { onEvent });
  100. await app.close?.();
  101. app = undefined;
  102. assertPhase({ failures, phase: 1, response: first.response });
  103. await assertFileContent(files.target, TARGET_AFTER_EDIT);
  104. await assertFileContent(files.big, bigContent.replace(BIG_HEADER, BIG_HEADER_EDITED));
  105. await assertFileContent(files.legacy, LEGACY_AFTER_EDIT);
  106. await access(sessionDbPath);
  107. const phase1 = readToolParts(sessionDbPath, sessionId);
  108. assertHashSnapshot(phase1, "call_hash_read_target", "Read", TARGET_INITIAL);
  109. assertHashSnapshot(phase1, "call_hash_edit_target", "Edit", TARGET_AFTER_EDIT);
  110. assertHashSnapshot(phase1, "call_hash_write_big", "Write", bigContent);
  111. const bigEdit = assertHashSnapshot(
  112. phase1,
  113. "call_hash_edit_big",
  114. "Edit",
  115. bigContent.replace(BIG_HEADER, BIG_HEADER_EDITED),
  116. );
  117. assertCondition(
  118. bigEdit.bytes < BIG_EDIT_PART_MAX_BYTES,
  119. "Edit on a large file must not persist the whole file in its tool part",
  120. { partBytes: bigEdit.bytes, fileBytes: Buffer.byteLength(bigContent, "utf8") },
  121. );
  122. // 模拟升级前写下的数据:legacy 的 Edit 快照去掉 contentSha256、改回带正文。
  123. rewriteAsLegacySnapshot(
  124. sessionDbPath,
  125. phase1.get("call_hash_edit_legacy"),
  126. LEGACY_AFTER_EDIT,
  127. );
  128. // 第二段:只 touch,冷恢复后 Edit 两个文件都应放行。
  129. await touch(files.target);
  130. await touch(files.legacy);
  131. app = await createApp({ ...appInput, resume: true, sessionId });
  132. await app.resume?.();
  133. assertCondition(app.sessionId === sessionId, "phase 2 must resume the original session");
  134. const second = await app.submitPrompt("Run read-state hash phase 2.", { onEvent });
  135. await app.close?.();
  136. app = undefined;
  137. assertPhase({ failures, phase: 2, response: second.response });
  138. await assertFileContent(files.target, TARGET_AFTER_RESUME_EDIT);
  139. await assertFileContent(files.legacy, LEGACY_AFTER_RESUME_EDIT);
  140. assertHashSnapshot(
  141. readToolParts(sessionDbPath, sessionId),
  142. "call_hash_resume_edit_target",
  143. "Edit",
  144. TARGET_AFTER_RESUME_EDIT,
  145. );
  146. // 第三段:外部改了内容(大小不变),冷恢复后 Edit 必须报 stale 且不改文件。
  147. await writeFile(files.target, TARGET_EXTERNAL);
  148. await touch(files.target);
  149. app = await createApp({ ...appInput, resume: true, sessionId });
  150. await app.resume?.();
  151. const third = await app.submitPrompt("Run read-state hash phase 3.", { onEvent });
  152. await app.close?.();
  153. app = undefined;
  154. assertPhase({ failures, phase: 3, response: third.response });
  155. await assertFileContent(files.target, TARGET_EXTERNAL);
  156. assertCondition(steps.length === 0, "all scripted steps must be consumed", {
  157. remaining: steps.map((step) => step.id),
  158. });
  159. assertProviderCapture(provider.records);
  160. await writeScriptedCaptureFile(provider, paths.capturePath);
  161. await writeJsonFile(paths.eventsPath, events);
  162. const resultPayload = buildCaseResult({
  163. capturedProviderRequestCount: provider.records.length,
  164. caseName: CASE_NAME,
  165. capturePath: paths.capturePath,
  166. events,
  167. eventsPath: paths.eventsPath,
  168. response: third.response,
  169. resultPath: paths.resultPath,
  170. traceId: third.traceId,
  171. });
  172. await writeJsonFile(paths.resultPath, resultPayload);
  173. return resultPayload;
  174. } catch (error) {
  175. await writeScriptedCaptureFile(provider, paths.capturePath);
  176. await writeJsonFile(paths.eventsPath, events);
  177. throw error;
  178. } finally {
  179. await app?.close?.();
  180. await stopScriptedProvider(provider);
  181. }
  182. },
  183. };
  184. /** 每个 step 是一次 provider 请求的回复;check 检查上一条 tool result。 */
  185. function buildSteps({ bigContent, files }) {
  186. const succeeded = { includes: EDIT_SUCCESS };
  187. return [
  188. {
  189. id: "phase1-read-target",
  190. phase: 1,
  191. call: ["call_hash_read_target", "Read", { file_path: files.target }],
  192. },
  193. {
  194. id: "phase1-edit-target",
  195. phase: 1,
  196. check: { includes: "alpha" },
  197. call: [
  198. "call_hash_edit_target",
  199. "Edit",
  200. { file_path: files.target, old_string: "alpha", new_string: "gamma" },
  201. ],
  202. },
  203. {
  204. id: "phase1-write-big",
  205. phase: 1,
  206. check: succeeded,
  207. call: ["call_hash_write_big", "Write", { file_path: files.big, content: bigContent }],
  208. },
  209. {
  210. id: "phase1-edit-big",
  211. phase: 1,
  212. check: { includes: "File created successfully" },
  213. call: [
  214. "call_hash_edit_big",
  215. "Edit",
  216. { file_path: files.big, old_string: BIG_HEADER, new_string: BIG_HEADER_EDITED },
  217. ],
  218. },
  219. {
  220. id: "phase1-read-legacy",
  221. phase: 1,
  222. check: succeeded,
  223. call: ["call_hash_read_legacy", "Read", { file_path: files.legacy }],
  224. },
  225. {
  226. id: "phase1-edit-legacy",
  227. phase: 1,
  228. check: { includes: "one" },
  229. call: [
  230. "call_hash_edit_legacy",
  231. "Edit",
  232. { file_path: files.legacy, old_string: "one", new_string: "two" },
  233. ],
  234. },
  235. { id: "phase1-done", phase: 1, check: succeeded },
  236. {
  237. id: "phase2-edit-target",
  238. phase: 2,
  239. call: [
  240. "call_hash_resume_edit_target",
  241. "Edit",
  242. { file_path: files.target, old_string: "gamma", new_string: "delta" },
  243. ],
  244. },
  245. {
  246. id: "phase2-edit-legacy",
  247. phase: 2,
  248. check: succeeded,
  249. call: [
  250. "call_hash_resume_edit_legacy",
  251. "Edit",
  252. { file_path: files.legacy, old_string: "two", new_string: "three" },
  253. ],
  254. },
  255. { id: "phase2-done", phase: 2, check: succeeded },
  256. {
  257. id: "phase3-edit-target",
  258. phase: 3,
  259. call: [
  260. "call_hash_stale_edit_target",
  261. "Edit",
  262. { file_path: files.target, old_string: "delta", new_string: "epsilon" },
  263. ],
  264. },
  265. { id: "phase3-done", phase: 3, check: { includes: STALE_ERROR, allowStale: true } },
  266. ];
  267. }
  268. function createStepHandler({ failures, steps }) {
  269. // 断言失败不抛:provider 返回 500 会触发重试,掩盖真正的失败点。记下来,由每段收尾统一检查。
  270. return async ({ body }) => {
  271. const step = steps.shift();
  272. if (!step) {
  273. failures.push({ reason: "unexpected extra provider request" });
  274. return { body: chatCompletion({ content: UNEXPECTED_MARKER, model: body?.model }) };
  275. }
  276. const previous = lastToolResult(body);
  277. if (step.check?.includes && !previous.includes(step.check.includes)) {
  278. failures.push({ step: step.id, reason: `missing "${step.check.includes}"`, previous });
  279. }
  280. for (const forbidden of step.check?.allowStale
  281. ? [NOT_READ_ERROR]
  282. : [NOT_READ_ERROR, STALE_ERROR]) {
  283. if (step.check && previous.includes(forbidden)) {
  284. failures.push({ step: step.id, reason: `unexpected "${forbidden}"`, previous });
  285. }
  286. }
  287. if (!step.call) {
  288. return {
  289. body: chatCompletion({ content: `${COMPLETION_MARKER}:${step.phase}`, model: body?.model }),
  290. };
  291. }
  292. const [id, name, args] = step.call;
  293. return {
  294. body: chatCompletion({
  295. model: body?.model,
  296. toolCalls: [{ id, type: "function", function: { name, arguments: JSON.stringify(args) } }],
  297. }),
  298. };
  299. };
  300. }
  301. function lastToolResult(body) {
  302. const messages = Array.isArray(body?.messages) ? body.messages : [];
  303. const tool = messages.filter((message) => message?.role === "tool").at(-1);
  304. if (!tool) return "";
  305. return typeof tool.content === "string" ? tool.content : JSON.stringify(tool.content ?? "");
  306. }
  307. function assertPhase({ failures, phase, response }) {
  308. assertCondition(failures.length === 0, `phase ${phase} tool results must match the script`, {
  309. failures: failures.map((failure) => ({
  310. ...failure,
  311. previous: failure.previous?.slice(0, 600),
  312. })),
  313. });
  314. assertCondition(
  315. response.includes(`${COMPLETION_MARKER}:${phase}`),
  316. `phase ${phase} must finish`,
  317. {
  318. response,
  319. },
  320. );
  321. }
  322. /** 只读本会话的 tool part,按 provider 的 tool call id 索引。 */
  323. function readToolParts(dbPath, sessionId) {
  324. const db = new DatabaseSync(dbPath, { readOnly: true });
  325. try {
  326. const rows = db
  327. .prepare(
  328. "select id, data, length(cast(data as blob)) as bytes from part where session_id = ?",
  329. )
  330. .all(sessionId);
  331. const parts = new Map();
  332. for (const row of rows) {
  333. const data = JSON.parse(row.data);
  334. if (data.type === "tool") parts.set(data.callID, { bytes: row.bytes, data, id: row.id });
  335. }
  336. return parts;
  337. } finally {
  338. db.close();
  339. }
  340. }
  341. function assertHashSnapshot(parts, callID, tool, expectedContent) {
  342. const part = parts.get(callID);
  343. const snapshot = part?.data.state?.metadata?.readFileState;
  344. assertCondition(
  345. part?.data.state?.status === "completed",
  346. `${callID} must be a completed tool part`,
  347. {
  348. callIDs: [...parts.keys()],
  349. },
  350. );
  351. assertCondition(
  352. snapshot?.tool === tool &&
  353. snapshot.contentSha256 === sha256(expectedContent) &&
  354. !("content" in snapshot),
  355. `${callID} must persist a hash-only read-state snapshot`,
  356. { snapshot: snapshot && { ...snapshot, content: snapshot.content?.slice(0, 80) } },
  357. );
  358. return part;
  359. }
  360. function rewriteAsLegacySnapshot(dbPath, part, content) {
  361. assertCondition(Boolean(part), "legacy Edit part must exist before rewriting it");
  362. const { contentSha256: _hash, ...rest } = part.data.state.metadata.readFileState;
  363. part.data.state.metadata.readFileState = { ...rest, content };
  364. const db = new DatabaseSync(dbPath);
  365. try {
  366. db.prepare("update part set data = ? where id = ?").run(JSON.stringify(part.data), part.id);
  367. } finally {
  368. db.close();
  369. }
  370. }
  371. async function touch(path) {
  372. const info = await stat(path);
  373. const mtime = new Date(info.mtimeMs + TOUCH_STEP_MS);
  374. await utimes(path, mtime, mtime);
  375. }
  376. async function assertFileContent(path, expected) {
  377. const actual = await readFile(path, "utf8");
  378. assertCondition(actual === expected, `unexpected content in ${path}`, {
  379. actual: actual.slice(0, 200),
  380. expected: expected.slice(0, 200),
  381. });
  382. }
  383. function buildBigContent() {
  384. const lines = [BIG_HEADER];
  385. for (let index = 1; index <= BIG_LINE_COUNT; index += 1) {
  386. lines.push(`line ${index} read-state hash resume payload ${"x".repeat(16)}\n`);
  387. }
  388. return lines.join("");
  389. }
  390. // 与 hashReadFileStateContent 相同:sha256 按 UTF-16LE(JS 字符串码元)计算。
  391. function sha256(text) {
  392. return createHash("sha256").update(text, "utf16le").digest("hex");
  393. }