generate-large-task-fixture.mjs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. #!/usr/bin/env node
  2. import { createHash, randomUUID } from "node:crypto";
  3. import { existsSync, mkdirSync, writeFileSync } from "node:fs";
  4. import { homedir } from "node:os";
  5. import { dirname, join, resolve } from "node:path";
  6. import { DatabaseSync } from "node:sqlite";
  7. import { spawnSync } from "node:child_process";
  8. const args = parseArgs(process.argv.slice(2));
  9. const zcodeRoot = join(homedir(), ".zcode");
  10. const cliDbPath = join(zcodeRoot, "cli", "db", "db.sqlite");
  11. const taskIndexPath = join(zcodeRoot, "v2", "tasks-index.sqlite");
  12. if (args.help) {
  13. printHelp();
  14. process.exit(0);
  15. }
  16. if (args.verify) {
  17. verifyTask(String(args.verify));
  18. process.exit(0);
  19. }
  20. if (args.delete) {
  21. deleteTask(String(args.delete));
  22. process.exit(0);
  23. }
  24. const workspacePath = resolve(String(args.workspace ?? process.cwd()));
  25. const turnCount = Number(args.turns ?? 3000);
  26. if (!Number.isInteger(turnCount) || turnCount <= 0) {
  27. throw new Error(`Invalid --turns value: ${args.turns}`);
  28. }
  29. const result = generateTask({
  30. workspacePath,
  31. turnCount,
  32. title: String(args.title ?? "Performance Fixture Large Mixed Task"),
  33. backup: args.backup !== false,
  34. });
  35. console.log(JSON.stringify(result, null, 2));
  36. function parseArgs(argv) {
  37. const out = { backup: true };
  38. for (let i = 0; i < argv.length; i += 1) {
  39. const arg = argv[i];
  40. if (arg === "--help" || arg === "-h") out.help = true;
  41. else if (arg === "--workspace") out.workspace = argv[++i];
  42. else if (arg === "--turns") out.turns = argv[++i];
  43. else if (arg === "--title") out.title = argv[++i];
  44. else if (arg === "--verify") out.verify = argv[++i];
  45. else if (arg === "--delete") out.delete = argv[++i];
  46. else if (arg === "--no-backup") out.backup = false;
  47. else throw new Error(`Unknown argument: ${arg}`);
  48. }
  49. return out;
  50. }
  51. function printHelp() {
  52. console.log(`Usage:
  53. generate:
  54. node generate-large-task-fixture.mjs --workspace "$PWD" --turns 3000
  55. verify:
  56. node generate-large-task-fixture.mjs --verify <sessionId>
  57. delete:
  58. node generate-large-task-fixture.mjs --delete <sessionId>
  59. `);
  60. }
  61. function generateTask({ workspacePath, turnCount, title, backup }) {
  62. assertDatabases();
  63. const backupDir = backup ? backupDatabases() : null;
  64. const now = Date.now();
  65. const stamp = new Date(now).toISOString().replace(/[-:.TZ]/g, "").slice(0, 14);
  66. const sessionId = `sess_perf_large_${stamp}_${randomUUID().slice(0, 8)}`;
  67. const traceId = `trace_perf_large_${stamp}`;
  68. const workspaceKey = workspacePath;
  69. const workspaceHash = hash12(workspaceKey);
  70. const providerId = "693f9c23-72a5-4f1f-bf4a-4b958add6472";
  71. const modelId = "deepseek-v4-flash";
  72. const model = `${providerId}/${modelId}`;
  73. const baseTime = now - 1000 * 60 * 60 * 24;
  74. const manifestPath = join(zcodeRoot, "perf-task-manifests", `${sessionId}.json`);
  75. let partCount = 0;
  76. const cli = openDb(cliDbPath);
  77. const idx = openDb(taskIndexPath);
  78. try {
  79. execTx(cli, () => {
  80. insertSession(cli, { sessionId, workspacePath, workspaceHash, traceId, title, baseTime, now, turnCount });
  81. const insertMsg = cli.prepare("insert into message (id, session_id, time_created, time_updated, data) values (?, ?, ?, ?, ?)");
  82. const insertPart = cli.prepare("insert into part (id, message_id, session_id, time_created, time_updated, data) values (?, ?, ?, ?, ?, ?)");
  83. const insertTodo = cli.prepare("insert into todo (session_id, content, status, priority, position, time_created, time_updated) values (?, ?, ?, ?, ?, ?, ?)");
  84. const insertEntry = cli.prepare("insert into session_entry (id, session_id, type, time_created, time_updated, data) values (?, ?, ?, ?, ?, ?)");
  85. const insertUsage = cli.prepare(`insert into model_usage (id, logical_request_id, attempt_index, session_id, turn_id, trace_id, span_id, assistant_message_id, parent_user_message_id, query_source, provider_id, model_id, variant, agent, mode, task_type, status, started_at, first_token_at, completed_at, duration_ms, time_to_first_token_ms, finish_reason, tool_call_count, input_tokens, output_tokens, reasoning_tokens, cache_creation_input_tokens, cache_read_input_tokens, provider_total_tokens, computed_total_tokens, retry_count, retryable, cancelled_by_user, context_exceeded, error_type, error_code, error_message, raw_usage_json, provider_metadata_json) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, null, 'zcode-agent', ?, 'interactive', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, 0, null, null, null, ?, ?)`);
  86. const insertTurnUsage = cli.prepare(`insert into turn_usage (session_id, turn_id, trace_id, user_message_id, status, started_at, first_model_start_at, first_token_at, completed_at, duration_ms, time_to_first_token_ms, model_request_count, model_retry_count, tool_call_count, tool_error_count, input_tokens, output_tokens, reasoning_tokens, cache_creation_input_tokens, cache_read_input_tokens, computed_total_tokens, retryable, cancelled_by_user, context_exceeded, error_type, error_code) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, 0, null, null)`);
  87. for (let n = 0; n < turnCount; n += 1) {
  88. const counts = insertTurn({ insertMsg, insertPart, insertUsage, insertTurnUsage, sessionId, traceId, workspacePath, providerId, modelId, baseTime, n });
  89. partCount += counts.partCount;
  90. }
  91. for (let i = 0; i < 60; i += 1) {
  92. insertTodo.run(sessionId, `Synthetic large task todo ${i}: validate ${["scroll", "search", "tool rendering", "permission", "diff", "mobile replayable"][i % 6]}`, i % 5 === 0 ? "completed" : i % 3 === 0 ? "in_progress" : "pending", ["high", "medium", "low"][i % 3], i, baseTime + i, now);
  93. }
  94. insertEntry.run(`${sessionId}:fixture_note`, sessionId, "perf_fixture/manifest", baseTime, now, json({ sessionId, turnCount, generatedAt: now, workspacePath }));
  95. cli.prepare("insert into session_target (session_id, target_id, objective, summary_title, status, token_budget, tokens_used, time_used_seconds, time_created, time_updated) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(sessionId, `target_${sessionId}`, "Generate a very large synthetic task for UI and persistence performance testing.", title, "complete", 10000000, 52000000, 7200, baseTime, now);
  96. });
  97. execTx(idx, () => {
  98. const searchable = repeatLine(`Performance Fixture Large Mixed Task ${sessionId}: toolcall thinking content diff permission ask user question patch compaction subagent retry todo usage`, 1800).slice(0, 200000);
  99. const meta = { taskId: sessionId, traceId, title, workspacePath, createdAt: baseTime, updatedAt: now, mode: "build", model, provider: "glm", status: "completed", changeSummary: { additions: 42000, deletions: 17000, files: 1300 } };
  100. idx.prepare("delete from tasks where workspace_key = ? and task_id = ?").run(workspaceKey, sessionId);
  101. idx.prepare(`insert into tasks (workspace_key, workspace_path, workspace_identity, task_id, title, task_status, provider, mode, model, migration_source, forked_from_task_id, created_at, updated_at, unread_at, pinned, archived, deleted, title_overridden, searchable_text, meta_json) values (?, ?, null, ?, ?, ?, ?, ?, ?, null, null, ?, ?, null, 1, 0, 0, 1, ?, ?)`).run(workspaceKey, workspacePath, sessionId, title, "completed", "glm", "build", model, baseTime, now, searchable, json(meta));
  102. });
  103. } finally {
  104. cli.close();
  105. idx.close();
  106. }
  107. const manifest = { sessionId, traceId, title, workspacePath, workspaceKey, workspaceHash, cliDbPath, taskIndexPath, manifestPath, generatedAt: new Date(now).toISOString(), turnCount, messageCount: turnCount * 2, partCount, todoCount: 60, modelUsageCount: turnCount, backupDir };
  108. mkdirSync(dirname(manifestPath), { recursive: true });
  109. writeFileSync(manifestPath, `${json(manifest)}\n`);
  110. return manifest;
  111. }
  112. function insertSession(db, input) {
  113. // 本地会话按目录归属;把目录哈希写成显式身份会使冷恢复报 session-lineage-invalid。
  114. db.prepare(`insert into session (id, project_id, workspace_id, parent_id, trace_id, task_type, slug, directory, path, title, title_source, title_message_id, version, share_url, summary_additions, summary_deletions, summary_files, summary_diffs, revert, permission, time_created, time_updated, time_title_updated, time_compacting, time_archived) values (?, ?, ?, null, ?, 'interactive', ?, ?, ?, ?, 'custom', null, 'perf-fixture', null, ?, ?, ?, ?, null, ?, ?, ?, ?, null, null)`).run(input.sessionId, `perf-${input.workspaceHash}`, null, input.traceId, slug(input.title), input.workspacePath, input.workspacePath, input.title, 42000, 17000, 1300, json([{ path: "synthetic/perf.ts", additions: 42000, deletions: 17000 }]), json({ defaultMode: "ask" }), input.baseTime, input.baseTime + input.turnCount * 1000, input.baseTime);
  115. }
  116. function insertTurn(params) {
  117. const { insertMsg, insertPart, insertUsage, insertTurnUsage, sessionId, traceId, workspacePath, providerId, modelId, baseTime, n } = params;
  118. const userId = msgId("msg_user", n, sessionId);
  119. const assistantId = msgId("msg_assistant", n, sessionId);
  120. const t = baseTime + n * 1000;
  121. let partCount = 0;
  122. insertMsg.run(userId, sessionId, t, t, json(userMessage({ n, t, workspacePath, providerId, modelId })));
  123. const userText = n % 17 === 0 ? repeatLine(`User large markdown prompt turn ${n}: includes requirements, code fences, tables, screenshot references, and constraints.`, 28) : `Synthetic user prompt turn ${n}: ${["create feature", "fix bug", "review diff", "answer question", "approve permission", "decline option", "upload attachment", "remote follow-up"][n % 8]}.`;
  124. insertPart.run(`${userId}:part_text`, userId, sessionId, t, t, json(textPart(userText, t, { metadata: { fixture: true } })));
  125. partCount += 1;
  126. if (n % 20 === 0) {
  127. insertPart.run(`${userId}:part_file`, userId, sessionId, t + 1, t + 1, json({ type: "file", mime: "text/plain", filename: `fixture-${n}.txt`, url: `data:text/plain;base64,${Buffer.from(repeatLine(`attachment ${n}`, 20)).toString("base64")}`, metadata: { fixture: true } }));
  128. partCount += 1;
  129. }
  130. const completed = t + 700;
  131. insertMsg.run(assistantId, sessionId, t + 10, completed, json(assistantMessage({ n, parentId: userId, t: t + 10, completed, workspacePath, providerId, modelId })));
  132. for (const [suffix, createdAt, value] of assistantParts({ n, sessionId, assistantId, workspacePath, t, completed })) {
  133. insertPart.run(`${assistantId}:${suffix}`, assistantId, sessionId, createdAt, createdAt, json(value));
  134. partCount += 1;
  135. }
  136. insertUsageRows({ insertUsage, insertTurnUsage, sessionId, traceId, providerId, modelId, n, t, completed, userId, assistantId });
  137. return { partCount };
  138. }
  139. function assistantParts({ n, sessionId, workspacePath, t, completed }) {
  140. const tools = ["Read", "Grep", "Glob", "Bash", "Edit", "Write", "TodoWrite", "AskUserQuestion", "Agent", "WebSearch", "WebFetch"];
  141. const stepSnapshot = json({ fixture: true, turn: n });
  142. const items = [
  143. ["step_start", t + 11, { type: "step-start", snapshot: stepSnapshot }],
  144. ["text_intro", t + 20, textPart(repeatLine(`Assistant content turn ${n}: summary, explanation, code review notes, and i18n text.`, 10 + (n % 10)), t + 20, { metadata: { fixture: true } })],
  145. ["tool_a", t + 40, toolPart({ n, tool: tools[n % tools.length], status: n % 97 === 0 ? "error" : "completed", start: t + 40, workspacePath })],
  146. ["tool_b", t + 45, toolPart({ n, tool: tools[(n * 7) % tools.length], status: n % 89 === 0 ? "pending" : n % 83 === 0 ? "running" : "completed", start: t + 45, workspacePath })],
  147. ["step_finish", completed, { type: "step-finish", reason: "stop", cost: 0, tokens: tokenUsage(n), snapshot: stepSnapshot }],
  148. ];
  149. if (n % 3 === 0) items.splice(1, 0, ["reasoning", t + 12, reasoningPart(n, t + 12)]);
  150. if (n % 5 === 0) items.push(["patch", t + 55, patchPart(n, sessionId)]);
  151. if (n % 37 === 0) items.push(["compaction", t + 58, compactionPart(n, t + 58)]);
  152. if (n % 41 === 0) items.push(["subtask", t + 60, { type: "subtask", agent: "explore", command: "analyze", description: `Synthetic subagent task ${n}`, prompt: repeatLine(`Subagent prompt ${n}`, 5) }]);
  153. if (n % 53 === 0) items.push(["agent", t + 61, { type: "agent", name: `synthetic-agent-${n}` }]);
  154. if (n % 67 === 0) items.push(["retry", t + 62, { type: "retry", attempt: 2, error: { name: "SyntheticRetryableError", data: { message: `retry fixture ${n}` } } }]);
  155. return items;
  156. }
  157. function insertUsageRows({ insertUsage, insertTurnUsage, sessionId, traceId, providerId, modelId, n, t, completed, userId, assistantId }) {
  158. const inputTokens = 15000 + (n % 1400);
  159. const outputTokens = 1200 + (n % 700);
  160. const reasoningTokens = n % 3 === 0 ? 240 + (n % 200) : 0;
  161. const total = inputTokens + outputTokens + reasoningTokens;
  162. insertUsage.run(`usage_${sessionId}_${n}`, `logical_${sessionId}_${n}`, 0, sessionId, `turn_${n}`, traceId, `span_${n}`, assistantId, userId, n % 11 === 0 ? "sidecar" : "main", providerId, modelId, n % 7 === 0 ? "plan" : "build", n % 97 === 0 ? "error" : "completed", t + 10, t + 30, completed, completed - (t + 10), 20, n % 13 === 0 ? "tool-calls" : "stop", 2 + (n % 4), inputTokens, outputTokens, reasoningTokens, n % 11 === 0 ? 256 : 0, n % 5 === 0 ? 4096 : 512, total, total, n % 19 === 0 ? 1 : 0, json({ inputTokens, outputTokens, reasoningTokens }), json({ fixture: true, turn: n }));
  163. insertTurnUsage.run(sessionId, `turn_${n}`, traceId, userId, n % 97 === 0 ? "error" : "completed", t, t + 10, t + 30, completed, completed - t, 30, 1, n % 19 === 0 ? 1 : 0, 2 + (n % 4), n % 97 === 0 ? 1 : 0, inputTokens, outputTokens, reasoningTokens, n % 11 === 0 ? 256 : 0, n % 5 === 0 ? 4096 : 512, total);
  164. }
  165. function userMessage({ n, t, workspacePath, providerId, modelId }) {
  166. return { role: "user", time: { created: t }, agent: "zcode-agent", model: { providerID: providerId, modelID: modelId }, contextSnapshot: { envInfo: { cwd: workspacePath, platform: process.platform, shell: process.env.SHELL ?? "zsh", nodeVersion: process.version, isGitRepository: true, gitStatus: n % 2 === 0 ? "clean" : "modified synthetic fixture files" } }, tools: { Read: true, Write: true, Edit: true, Bash: true, Glob: true, Grep: true, WebFetch: true, WebSearch: true, TodoRead: true, TodoWrite: true, AskUserQuestion: true, Agent: true, Skill: true }, metadata: { fixture: true, clientMode: n % 10 === 0 ? "web-remote-replayable" : "desktop-continuous" } };
  167. }
  168. function assistantMessage({ n, parentId, t, completed, workspacePath, providerId, modelId }) {
  169. return { role: "assistant", time: { created: t, completed }, parentID: parentId, modelID: modelId, providerID: providerId, mode: n % 7 === 0 ? "plan" : "build", agent: "zcode-agent", path: { cwd: workspacePath, root: workspacePath }, cost: 0, tokens: tokenUsage(n), finish: n % 13 === 0 ? "tool-calls" : "stop" };
  170. }
  171. function toolPart({ n, tool, status, start, workspacePath }) {
  172. const input = toolInput(tool, n, workspacePath);
  173. if (status === "pending") return { type: "tool", callID: toolCallId(n, tool), tool, state: { status, input, raw: json(input) }, time: { start, end: start + 100 } };
  174. if (status === "running") return { type: "tool", callID: toolCallId(n, tool), tool, state: { status, input, title: tool, time: { start }, metadata: { fixture: true, progress: n % 100 } }, time: { start, end: start + 100 } };
  175. if (status === "error") return { type: "tool", callID: toolCallId(n, tool), tool, state: { status, input, error: `SyntheticToolError: Synthetic tool error at turn ${n} (PERF_FIXTURE)`, time: { start, end: start + 100 }, metadata: { fixture: true } }, time: { start, end: start + 100 } };
  176. const output = tool === "Bash" || tool === "Grep" || tool === "Glob" ? repeatLine(`${tool} output turn ${n}`, 18 + (n % 18)) : tool === "AskUserQuestion" ? json({ question: input.question, selected: "Proceed", freeform: `Synthetic user answer ${n}` }) : tool === "Edit" || tool === "Write" ? diffText(n, 1 + (n % 3), 4 + (n % 5)) : repeatLine(`${tool} structured result turn ${n}`, 10 + (n % 12));
  177. return { type: "tool", callID: toolCallId(n, tool), tool, state: { status: "completed", input, output, title: tool, time: { start, end: start + 100 }, metadata: { fixture: true, permission: tool === "Bash" ? "approved" : undefined, serialization: { truncated: false, originalBytes: output.length, returnedBytes: output.length } } }, time: { start, end: start + 100 } };
  178. }
  179. function toolInput(tool, n, workspacePath) {
  180. const values = {
  181. Read: { file_path: `${workspacePath}/packages/ui/src/App.tsx`, offset: n % 50, limit: 80 },
  182. Grep: { pattern: `perf-fixture-${n % 37}`, path: workspacePath, output_mode: "content" },
  183. Glob: { pattern: "**/*.{ts,tsx,md}", path: workspacePath },
  184. Bash: { command: `printf 'synthetic turn ${n}'; sleep 0`, description: "Synthetic perf command" },
  185. Edit: { file_path: `${workspacePath}/tmp/perf-${n}.txt`, old_string: "before", new_string: "after" },
  186. Write: { file_path: `${workspacePath}/tmp/perf-${n}.txt`, content: repeatLine(`written content ${n}`, 10) },
  187. TodoWrite: { todos: [{ content: `Synthetic todo ${n}`, status: "in_progress", priority: "medium" }] },
  188. AskUserQuestion: { question: `Synthetic decision question for turn ${n}?`, options: ["Proceed", "Skip", "Change scope"] },
  189. Agent: { prompt: `Explore synthetic subtask ${n}`, agent_type: n % 2 === 0 ? "explore" : "main" },
  190. WebSearch: { query: `synthetic zcode performance fixture ${n}` },
  191. WebFetch: { url: "https://example.com", prompt: `summarize fixture ${n}` },
  192. };
  193. return values[tool] ?? { turn: n };
  194. }
  195. function verifyTask(sessionId) {
  196. assertSafeFixtureId(sessionId);
  197. const idx = openDb(taskIndexPath);
  198. const cli = openDb(cliDbPath);
  199. try {
  200. const task = idx.prepare("select task_id,title,workspace_path,provider,mode,task_status,pinned,archived,deleted,length(searchable_text) searchable_len,length(meta_json) meta_len from tasks where task_id = ?").get(sessionId);
  201. const counts = {
  202. session: cli.prepare("select count(*) count from session where id = ?").get(sessionId).count,
  203. messages: cli.prepare("select count(*) count from message where session_id = ?").get(sessionId).count,
  204. parts: cli.prepare("select count(*) count from part where session_id = ?").get(sessionId).count,
  205. todos: cli.prepare("select count(*) count from todo where session_id = ?").get(sessionId).count,
  206. modelUsage: cli.prepare("select count(*) count from model_usage where session_id = ?").get(sessionId).count,
  207. turnUsage: cli.prepare("select count(*) count from turn_usage where session_id = ?").get(sessionId).count,
  208. };
  209. const types = cli.prepare("select json_extract(data,'$.type') type, count(*) count from part where session_id = ? group by type order by count desc").all(sessionId);
  210. const shapeCheck = validateFixtureProtocolShapes(cli, sessionId);
  211. console.log(JSON.stringify({ task, counts, types, shapeCheck }, null, 2));
  212. if (shapeCheck.errors.length > 0) {
  213. throw new Error(`Fixture protocol shape check failed: ${shapeCheck.errors.slice(0, 5).join("; ")}`);
  214. }
  215. } finally {
  216. idx.close();
  217. cli.close();
  218. }
  219. }
  220. function validateFixtureProtocolShapes(db, sessionId) {
  221. const errors = [];
  222. const messageRows = db.prepare("select id,data from message where session_id = ? order by time_created asc").all(sessionId);
  223. const partRows = db.prepare("select id,data from part where session_id = ? order by time_created asc").all(sessionId);
  224. const syntheticSources = new Set(["background_task", "fork", "goal-continuation", "rewind", "subagent", "todo_reminder"]);
  225. const internalPartTypes = new Set(["agent", "compaction", "file", "patch", "reasoning", "retry", "snapshot", "step-finish", "step-start", "subtask", "text", "tool"]);
  226. for (const row of messageRows) {
  227. const data = parseJson(row.data, `message ${row.id}`, errors);
  228. if (!data) continue;
  229. if (data.role === "user" && data.source !== undefined && !syntheticSources.has(data.source)) {
  230. errors.push(`${row.id}: invalid user source ${data.source}`);
  231. }
  232. if (data.role === "assistant" && !data.tokens?.cache) {
  233. errors.push(`${row.id}: assistant tokens.cache is missing`);
  234. }
  235. }
  236. for (const row of partRows) {
  237. const data = parseJson(row.data, `part ${row.id}`, errors);
  238. if (!data) continue;
  239. // 这里覆盖 UI 打开时的协议校验失败点,避免 SQLite 写入成功但会话恢复失败。
  240. if (!internalPartTypes.has(data.type)) {
  241. errors.push(`${row.id}: unsupported internal part type ${String(data.type)}`);
  242. }
  243. if ((data.type === "step-start" || data.type === "step-finish") && data.snapshot !== undefined && typeof data.snapshot !== "string") {
  244. errors.push(`${row.id}: ${data.type}.snapshot must be a string`);
  245. }
  246. if (data.type === "step-finish" && !data.tokens?.cache) {
  247. errors.push(`${row.id}: step-finish tokens.cache is missing`);
  248. }
  249. if (data.type === "tool" && data.state?.status === "error" && typeof data.state.error !== "string") {
  250. errors.push(`${row.id}: tool error state.error must be a string`);
  251. }
  252. if (data.type === "patch" && !data.files?.every((file) => typeof file === "string")) {
  253. errors.push(`${row.id}: patch files must be string paths`);
  254. }
  255. if (data.type === "subagent") {
  256. errors.push(`${row.id}: raw session DB must use internal subtask; mapper emits protocol subagent`);
  257. }
  258. }
  259. return { checkedMessages: messageRows.length, checkedParts: partRows.length, errors };
  260. }
  261. function parseJson(value, label, errors) {
  262. try {
  263. return JSON.parse(value);
  264. } catch (error) {
  265. errors.push(`${label}: invalid JSON ${error.message}`);
  266. return null;
  267. }
  268. }
  269. function deleteTask(sessionId) {
  270. assertSafeFixtureId(sessionId);
  271. const backupDir = backupDatabases();
  272. const idx = openDb(taskIndexPath);
  273. const cli = openDb(cliDbPath);
  274. try {
  275. execTx(idx, () => idx.prepare("delete from tasks where task_id = ?").run(sessionId));
  276. execTx(cli, () => cli.prepare("delete from session where id = ?").run(sessionId));
  277. } finally {
  278. idx.close();
  279. cli.close();
  280. }
  281. console.log(JSON.stringify({ deleted: sessionId, backupDir }, null, 2));
  282. }
  283. function assertDatabases() {
  284. for (const path of [cliDbPath, taskIndexPath]) {
  285. if (!existsSync(path)) throw new Error(`Missing SQLite database: ${path}`);
  286. }
  287. }
  288. function backupDatabases() {
  289. const stamp = new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14);
  290. const backupDir = join(zcodeRoot, "perf-task-backups", stamp);
  291. mkdirSync(backupDir, { recursive: true });
  292. sqliteBackup(taskIndexPath, join(backupDir, "tasks-index.sqlite"));
  293. sqliteBackup(cliDbPath, join(backupDir, "cli-db.sqlite"));
  294. return backupDir;
  295. }
  296. function sqliteBackup(source, target) {
  297. const result = spawnSync("sqlite3", [source, `.backup '${target.replaceAll("'", "''")}'`], { encoding: "utf8" });
  298. if (result.status !== 0) throw new Error(`sqlite3 backup failed for ${source}: ${result.stderr || result.stdout}`);
  299. }
  300. function openDb(path) {
  301. const db = new DatabaseSync(path);
  302. db.exec("PRAGMA foreign_keys = ON");
  303. db.exec("PRAGMA journal_mode = WAL");
  304. return db;
  305. }
  306. function execTx(db, fn) {
  307. db.exec("BEGIN IMMEDIATE");
  308. try {
  309. const result = fn();
  310. db.exec("COMMIT");
  311. return result;
  312. } catch (error) {
  313. try {
  314. db.exec("ROLLBACK");
  315. } catch {}
  316. throw error;
  317. }
  318. }
  319. function assertSafeFixtureId(sessionId) {
  320. if (!/^sess_perf_large_[0-9]{14}_[a-f0-9]{8}$/.test(sessionId)) {
  321. throw new Error(`Refusing non-fixture session id: ${sessionId}`);
  322. }
  323. }
  324. function json(value) {
  325. return JSON.stringify(value);
  326. }
  327. function hash12(value) {
  328. return createHash("sha256").update(value).digest("hex").slice(0, 12);
  329. }
  330. function msgId(prefix, n, sessionId) {
  331. return `${prefix}_${String(n).padStart(5, "0")}_${sessionId}`;
  332. }
  333. function toolCallId(n, tool) {
  334. return `call_perf_${String(n).padStart(5, "0")}_${tool}_${randomUUID().slice(0, 8)}`;
  335. }
  336. function textPart(text, start, extra = {}) {
  337. return { type: "text", text, time: { start, end: start }, ...extra };
  338. }
  339. function reasoningPart(n, start) {
  340. return { type: "reasoning", text: repeatLine(`Reasoning turn ${n}: analyzing state, tool outputs, permission boundaries, UI rendering, mobile replayable recovery, and diff summaries.`, 8 + (n % 8)), metadata: { anthropic: { signature: randomUUID() }, fixture: true }, time: { start, end: start + 50 } };
  341. }
  342. function patchPart(n, sessionId) {
  343. return { type: "patch", hash: createHash("sha256").update(`patch-${sessionId}-${n}`).digest("hex"), files: [`src/perf-${n}.ts`, `docs/perf-${n}.md`] };
  344. }
  345. function tokenUsage(n) {
  346. const input = 15000 + (n % 1400);
  347. const output = 1200 + (n % 700);
  348. const reasoning = n % 3 === 0 ? 240 + (n % 200) : 0;
  349. return { total: input + output + reasoning, input, output, reasoning, cache: { read: n % 5 === 0 ? 4096 : 512, write: n % 11 === 0 ? 256 : 0 } };
  350. }
  351. function compactionPart(n, start) {
  352. return { type: "compaction", reason: "manual", auto: n % 2 === 0, phase: "completed", attempt: 1, maxAttempts: 1, preCompactTokenCount: 180000 + n, postCompactTokenCount: 42000 + n, truePostCompactTokenCount: 43000 + n, operationId: `compact_${n}`, boundaryId: `boundary_${n}`, timelineStatus: "completed", time: { start, end: start + 80 } };
  353. }
  354. function repeatLine(seed, count) {
  355. const lines = [];
  356. for (let i = 0; i < count; i += 1) {
  357. lines.push(`${seed} line ${String(i).padStart(4, "0")}: ${"x".repeat(72)} ${i % 7 === 0 ? "包含中文内容与 i18n 文本,用于验证渲染和搜索。" : "mixed english content for scroll/search/layout."}`);
  358. }
  359. return lines.join("\n");
  360. }
  361. function diffText(turn, files = 3, hunks = 8) {
  362. const out = [];
  363. for (let f = 0; f < files; f += 1) {
  364. out.push(`diff --git a/src/perf-${turn}-${f}.ts b/src/perf-${turn}-${f}.ts`);
  365. out.push(`index ${String(turn).padStart(6, "0")}..${String(turn + f + 1).padStart(6, "0")} 100644`);
  366. out.push(`--- a/src/perf-${turn}-${f}.ts`);
  367. out.push(`+++ b/src/perf-${turn}-${f}.ts`);
  368. for (let h = 0; h < hunks; h += 1) {
  369. out.push(`@@ -${h * 9 + 1},7 +${h * 9 + 1},9 @@\n-const oldValue${h} = ${turn + h};\n+const newValue${h} = ${turn + h + 1};\n+// synthetic perf fixture change ${turn}/${f}/${h}\n export function perfCase${h}() {\n return newValue${h};\n }`);
  370. }
  371. }
  372. return out.join("\n");
  373. }
  374. function slug(value) {
  375. return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
  376. }