analyzer.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { describe, expect, it } from "vitest";
  6. import { inspectTrace, listTraces } from "../server/analyzer.js";
  7. describe("debug analyzer", () => {
  8. it("merges JSONL events and logs into trace summaries", async () => {
  9. const fixture = await createFixture();
  10. const response = await listTraces({
  11. eventPath: fixture.eventPath,
  12. logDir: fixture.logDir,
  13. dbPath: join(fixture.root, "missing.sqlite"),
  14. });
  15. expect(response.traces).toHaveLength(1);
  16. expect(response.traces[0]).toMatchObject({
  17. traceId: "trace-debug",
  18. firstUserMessage: "inspect this trace",
  19. eventCount: 3,
  20. logCount: 1,
  21. cacheReadTokens: 64,
  22. cacheWriteTokens: 12,
  23. });
  24. expect(response.sources.find((source) => source.kind === "eventlog")?.recordCount).toBe(3);
  25. });
  26. it("derives context sections and cache prefix status from observed events", async () => {
  27. const fixture = await createFixture();
  28. const detail = await inspectTrace("trace-debug", {
  29. eventPath: fixture.eventPath,
  30. logDir: fixture.logDir,
  31. dbPath: join(fixture.root, "missing.sqlite"),
  32. });
  33. expect(detail.timeline.map((item) => item.kind)).toContain("model_request");
  34. expect(detail.timeline[0]?.kind).toBe("turn_complete");
  35. const fullSnapshot = detail.contextSnapshots.find(
  36. (snapshot) => snapshot.observationLevel === "full",
  37. );
  38. expect(fullSnapshot?.sections.map((section) => section.source)).toEqual(
  39. expect.arrayContaining(["system_prompt", "skills", "tools"]),
  40. );
  41. expect(detail.cacheReports[0]?.segments.map((segment) => segment.status)).toEqual([
  42. "hit",
  43. "miss",
  44. ]);
  45. expect(detail.developerRequests.map((request) => request.eventName)).toContain(
  46. "prompt_cache_report",
  47. );
  48. });
  49. it("builds overlapping execution spans for Gantt views", async () => {
  50. const root = await mkdtemp(join(tmpdir(), "zcode-debug-spans-"));
  51. const logDir = join(root, "logs");
  52. await mkdir(logDir);
  53. const eventPath = join(root, "events.jsonl");
  54. await writeFile(join(logDir, "zcode.jsonl"), "", "utf8");
  55. const events = [
  56. {
  57. id: "evt-turn-start",
  58. type: "turn_started",
  59. timestamp: "2026-05-04T01:00:00.000Z",
  60. traceId: "trace-spans",
  61. sessionId: "session-spans",
  62. turnId: "turn-1",
  63. },
  64. {
  65. id: "evt-model-start",
  66. type: "model_request",
  67. timestamp: "2026-05-04T01:00:00.100Z",
  68. traceId: "trace-spans",
  69. sessionId: "session-spans",
  70. turnId: "turn-1",
  71. payload: { model: "gpt-test" },
  72. },
  73. {
  74. id: "evt-tool-read-start",
  75. type: "tool_call_started",
  76. timestamp: "2026-05-04T01:00:00.500Z",
  77. traceId: "trace-spans",
  78. sessionId: "session-spans",
  79. turnId: "turn-1",
  80. payload: { toolCallId: "tool-read", toolName: "Read" },
  81. },
  82. {
  83. id: "evt-tool-bash-start",
  84. type: "tool_call_started",
  85. timestamp: "2026-05-04T01:00:00.600Z",
  86. traceId: "trace-spans",
  87. sessionId: "session-spans",
  88. turnId: "turn-1",
  89. payload: { toolCallId: "tool-bash", toolName: "Bash" },
  90. },
  91. {
  92. id: "evt-tool-read-end",
  93. type: "tool_call_result",
  94. timestamp: "2026-05-04T01:00:01.500Z",
  95. traceId: "trace-spans",
  96. sessionId: "session-spans",
  97. turnId: "turn-1",
  98. payload: { toolCallId: "tool-read", toolName: "Read" },
  99. },
  100. {
  101. id: "evt-tool-bash-end",
  102. type: "tool_call_result",
  103. timestamp: "2026-05-04T01:00:01.700Z",
  104. traceId: "trace-spans",
  105. sessionId: "session-spans",
  106. turnId: "turn-1",
  107. payload: { toolCallId: "tool-bash", toolName: "Bash" },
  108. },
  109. {
  110. id: "evt-tool-open-start",
  111. type: "tool_call_started",
  112. timestamp: "2026-05-04T01:00:01.800Z",
  113. traceId: "trace-spans",
  114. sessionId: "session-spans",
  115. turnId: "turn-1",
  116. payload: { toolCallId: "tool-open", toolName: "Open" },
  117. },
  118. {
  119. id: "evt-model-end",
  120. type: "model_complete",
  121. timestamp: "2026-05-04T01:00:02.000Z",
  122. traceId: "trace-spans",
  123. sessionId: "session-spans",
  124. turnId: "turn-1",
  125. },
  126. {
  127. id: "evt-turn-end",
  128. type: "turn_complete",
  129. timestamp: "2026-05-04T01:00:02.200Z",
  130. traceId: "trace-spans",
  131. sessionId: "session-spans",
  132. turnId: "turn-1",
  133. payload: { resultType: "success" },
  134. },
  135. ];
  136. await writeFile(
  137. eventPath,
  138. `${events.map((event) => JSON.stringify(event)).join("\n")}\n`,
  139. "utf8",
  140. );
  141. const detail = await inspectTrace("trace-spans", {
  142. eventPath,
  143. logDir,
  144. dbPath: join(root, "missing.sqlite"),
  145. });
  146. const lanes = detail.spans.map((span) => span.lane);
  147. expect(lanes).toEqual(expect.arrayContaining(["turn", "model", "tool"]));
  148. const readSpan = detail.spans.find((span) => span.toolCallId === "tool-read");
  149. const bashSpan = detail.spans.find((span) => span.toolCallId === "tool-bash");
  150. expect(readSpan).toMatchObject({
  151. lane: "tool",
  152. label: "Read",
  153. startAt: "2026-05-04T01:00:00.500Z",
  154. endAt: "2026-05-04T01:00:01.500Z",
  155. status: "ok",
  156. });
  157. expect(bashSpan).toMatchObject({
  158. lane: "tool",
  159. label: "Bash",
  160. startAt: "2026-05-04T01:00:00.600Z",
  161. endAt: "2026-05-04T01:00:01.700Z",
  162. status: "ok",
  163. });
  164. const openSpan = detail.spans.find((span) => span.toolCallId === "tool-open");
  165. expect(openSpan).toMatchObject({
  166. lane: "tool",
  167. label: "Open",
  168. status: "unknown",
  169. });
  170. expect(openSpan?.endAt).toBeUndefined();
  171. });
  172. it("uses debug context-built logs as full context snapshots when section content is present", async () => {
  173. const root = await mkdtemp(join(tmpdir(), "zcode-debug-context-log-"));
  174. const logDir = join(root, "logs");
  175. await mkdir(logDir);
  176. await writeFile(
  177. join(logDir, "zcode.jsonl"),
  178. `${[
  179. {
  180. timestamp: "2026-05-04T01:00:00.100Z",
  181. level: "debug",
  182. event: "context.built",
  183. message: "Context built",
  184. traceId: "trace-log-context",
  185. sessionId: "session-log-context",
  186. turnId: "turn-log-context",
  187. status: "completed",
  188. context: {
  189. totalChars: 54,
  190. totalTokens: 14,
  191. sections: [
  192. {
  193. name: "Skills",
  194. source: "skills",
  195. chars: 32,
  196. tokens: 8,
  197. preview: "## Skills - debug",
  198. content: "## Skills\n- debug: inspect things",
  199. },
  200. {
  201. name: "Tools",
  202. source: "tools",
  203. chars: 22,
  204. tokens: 6,
  205. preview: "## Tools",
  206. content: "## Tools\n- Read",
  207. },
  208. ],
  209. },
  210. },
  211. {
  212. timestamp: "2026-05-04T01:00:00.200Z",
  213. level: "debug",
  214. event: "context_usage_snapshot",
  215. message: "Context usage snapshot",
  216. traceId: "trace-log-context",
  217. sessionId: "session-log-context",
  218. turnId: "turn-log-context",
  219. status: "completed",
  220. context: {
  221. tokenMethod: "estimated",
  222. confidence: "low",
  223. tokenizer: "zcode.estimateTokens.v1",
  224. totalChars: 140,
  225. totalTokens: 35,
  226. categories: [
  227. {
  228. name: "Meta user context",
  229. source: "meta_user_context",
  230. chars: 20,
  231. tokens: 5,
  232. tokenMethod: "estimated",
  233. confidence: "medium",
  234. tokenizer: "zcode.estimateTokens.v1",
  235. },
  236. {
  237. name: "Skills",
  238. source: "skills",
  239. chars: 32,
  240. tokens: 8,
  241. tokenMethod: "estimated",
  242. confidence: "medium",
  243. tokenizer: "zcode.estimateTokens.v1",
  244. },
  245. {
  246. name: "MCP tool schemas",
  247. source: "mcp_tool_schemas",
  248. chars: 88,
  249. tokens: 22,
  250. tokenMethod: "estimated",
  251. confidence: "low",
  252. tokenizer: "zcode.estimateTokens.v1",
  253. },
  254. ],
  255. mcpTools: [
  256. {
  257. name: "mcp__github__search_issues",
  258. source: "mcp_tool",
  259. serverName: "github",
  260. chars: 88,
  261. tokens: 22,
  262. tokenMethod: "estimated",
  263. confidence: "low",
  264. tokenizer: "zcode.estimateTokens.v1",
  265. },
  266. ],
  267. warnings: ["当前 token 来自本地估算。"],
  268. },
  269. },
  270. ]
  271. .map((entry) => JSON.stringify(entry))
  272. .join("\n")}\n`,
  273. "utf8",
  274. );
  275. const detail = await inspectTrace("trace-log-context", {
  276. logDir,
  277. dbPath: join(root, "missing.sqlite"),
  278. });
  279. expect(detail.contextSnapshots).toHaveLength(1);
  280. expect(detail.contextSnapshots[0]).toMatchObject({
  281. observationLevel: "full",
  282. sessionId: "session-log-context",
  283. turnId: "turn-log-context",
  284. warnings: [],
  285. });
  286. expect(detail.contextSnapshots[0]?.sections.map((section) => section.source)).toEqual([
  287. "skills",
  288. "tools",
  289. ]);
  290. expect(detail.contextSnapshots[0]?.sections[0]?.content).toContain("debug: inspect things");
  291. expect(detail.contextUsageSnapshots[0]).toMatchObject({
  292. tokenMethod: "estimated",
  293. confidence: "low",
  294. totalTokens: 35,
  295. });
  296. expect(detail.contextUsageSnapshots[0]?.categories.map((category) => category.source)).toEqual([
  297. "meta_user_context",
  298. "skills",
  299. "mcp_tool_schemas",
  300. ]);
  301. expect(detail.contextUsageSnapshots[0]?.mcpTools[0]).toMatchObject({
  302. name: "mcp__github__search_issues",
  303. serverName: "github",
  304. tokenMethod: "estimated",
  305. confidence: "low",
  306. });
  307. expect(detail.developerRequests.map((request) => request.eventName)).not.toContain(
  308. "context_snapshot",
  309. );
  310. });
  311. it("keeps timeline summaries and payloads untruncated", async () => {
  312. const root = await mkdtemp(join(tmpdir(), "zcode-debug-full-timeline-"));
  313. const logDir = join(root, "logs");
  314. await mkdir(logDir);
  315. const eventPath = join(root, "events.jsonl");
  316. const dbPath = join(root, "db.sqlite");
  317. const eventText = ["event-start", "e".repeat(260), "event-tail"].join("\n");
  318. const logText = ["log-start", "l".repeat(4_200), "log-tail"].join("\n");
  319. const dbText = ["db-start", "d".repeat(260), "db-tail"].join("\n");
  320. const partText = ["part-start", "p".repeat(260), "part-tail"].join("\n");
  321. await writeFile(
  322. eventPath,
  323. `${JSON.stringify({
  324. id: "evt-full-user",
  325. type: "user_message",
  326. timestamp: "2026-05-04T01:00:00.000Z",
  327. traceId: "trace-full-timeline",
  328. sessionId: "session-full-timeline",
  329. payload: { content: eventText },
  330. })}\n`,
  331. "utf8",
  332. );
  333. await writeFile(
  334. join(logDir, "zcode.jsonl"),
  335. `${JSON.stringify({
  336. timestamp: "2026-05-04T01:00:00.100Z",
  337. level: "debug",
  338. event: "debug.long",
  339. message: "Full log payload",
  340. traceId: "trace-full-timeline",
  341. sessionId: "session-full-timeline",
  342. context: { detail: logText },
  343. })}\n`,
  344. "utf8",
  345. );
  346. const db = new DatabaseSync(dbPath);
  347. try {
  348. db.exec(`
  349. create table session (
  350. id text primary key,
  351. project_id text not null,
  352. title text not null,
  353. directory text not null,
  354. time_created integer not null,
  355. time_updated integer not null
  356. );
  357. create table message (
  358. id text primary key,
  359. session_id text not null,
  360. time_created integer not null,
  361. time_updated integer not null,
  362. data text not null
  363. );
  364. create table part (
  365. id text primary key,
  366. message_id text not null,
  367. session_id text not null,
  368. time_created integer not null,
  369. time_updated integer not null,
  370. data text not null
  371. );
  372. `);
  373. db.prepare(
  374. "insert into session (id, project_id, title, directory, time_created, time_updated) values (?, ?, ?, ?, ?, ?)",
  375. ).run("session-full-timeline", "project-full", "Full", "/work/full", 1000, 1000);
  376. db.prepare(
  377. "insert into message (id, session_id, time_created, time_updated, data) values (?, ?, ?, ?, ?)",
  378. ).run(
  379. "message-full",
  380. "session-full-timeline",
  381. 1100,
  382. 1100,
  383. JSON.stringify({ role: "user", content: dbText }),
  384. );
  385. db.prepare(
  386. "insert into part (id, message_id, session_id, time_created, time_updated, data) values (?, ?, ?, ?, ?, ?)",
  387. ).run(
  388. "part-full",
  389. "message-full",
  390. "session-full-timeline",
  391. 1200,
  392. 1200,
  393. JSON.stringify({ type: "text", text: partText }),
  394. );
  395. } finally {
  396. db.close();
  397. }
  398. const detail = await inspectTrace("trace-full-timeline", {
  399. eventPath,
  400. logDir,
  401. dbPath,
  402. });
  403. const eventItem = detail.timeline.find((item) => item.id === "event:evt-full-user");
  404. const logItem = detail.timeline.find((item) => item.kind === "debug.long");
  405. const dbMessage = detail.timeline.find((item) => item.id === "sqlite:message:message-full");
  406. const dbPart = detail.timeline.find((item) => item.id === "sqlite:part:part-full");
  407. expect(eventItem?.summary).toContain("event-tail");
  408. expect(eventItem?.summary).not.toContain("...");
  409. expect((eventItem?.payload as { content?: string } | undefined)?.content).toBe(eventText);
  410. expect((logItem?.payload as { detail?: string } | undefined)?.detail).toBe(logText);
  411. expect(dbMessage?.summary).toContain("db-tail");
  412. expect(dbMessage?.summary).not.toContain("...");
  413. expect(dbPart?.summary).toContain("part-tail");
  414. expect(dbPart?.summary).not.toContain("...");
  415. });
  416. it("surfaces JSONL parse warnings without failing the whole source", async () => {
  417. const fixture = await createFixture({ includeBadLine: true });
  418. const response = await listTraces({
  419. eventPath: fixture.eventPath,
  420. logDir: fixture.logDir,
  421. dbPath: join(fixture.root, "missing.sqlite"),
  422. });
  423. expect(response.sources.find((source) => source.kind === "eventlog")?.warning).toContain(
  424. "不是合法 JSON",
  425. );
  426. expect(response.traces[0]?.traceId).toBe("trace-debug");
  427. });
  428. it("lists projects, filters traces by project, and defaults trace list to 10 items", async () => {
  429. const fixture = await createProjectFixture();
  430. const all = await listTraces({
  431. eventPath: fixture.eventPath,
  432. logDir: fixture.logDir,
  433. dbPath: fixture.dbPath,
  434. });
  435. expect(all.projects.map((project) => project.projectId)).toEqual([
  436. "project-new",
  437. "project-old",
  438. ]);
  439. expect(all.traces).toHaveLength(10);
  440. const filtered = await listTraces({
  441. eventPath: fixture.eventPath,
  442. logDir: fixture.logDir,
  443. dbPath: fixture.dbPath,
  444. projectId: "project-old",
  445. });
  446. expect(filtered.traces.map((trace) => trace.traceId)).toEqual(["trace-old"]);
  447. expect(filtered.traces[0]?.firstUserMessage).toBe("old project part prompt");
  448. const detail = await inspectTrace("trace-old", {
  449. eventPath: fixture.eventPath,
  450. logDir: fixture.logDir,
  451. dbPath: fixture.dbPath,
  452. });
  453. expect(detail.cacheReports[0]).toMatchObject({
  454. inputTokens: 100,
  455. cacheReadTokens: 20,
  456. cacheWriteTokens: 5,
  457. hitRate: 0.2,
  458. });
  459. expect(detail.cacheReports[0]?.segments).toEqual([]);
  460. expect(detail.cacheReports[0]?.limitations[0]).toBe(
  461. "SQLite 里有聚合缓存 token,但没有逐文本 cache report。",
  462. );
  463. expect(detail.contextUsageSnapshots[0]).toMatchObject({
  464. totalTokens: 100,
  465. tokenMethod: "provider_usage",
  466. confidence: "low",
  467. });
  468. expect(detail.contextUsageSnapshots[0]?.categories[0]).toMatchObject({
  469. name: "模型输入(SQLite 聚合)",
  470. source: "other",
  471. tokens: 100,
  472. });
  473. expect(detail.contextUsageSnapshots[0]?.warnings[0]).toContain("无法拆分");
  474. });
  475. });
  476. async function createFixture(options: { includeBadLine?: boolean } = {}) {
  477. const root = await mkdtemp(join(tmpdir(), "zcode-debug-"));
  478. const logDir = join(root, "logs");
  479. await mkdir(logDir);
  480. const eventPath = join(root, "events.jsonl");
  481. const logPath = join(logDir, "zcode.jsonl");
  482. const systemPrompt = [
  483. "You are ZCode.",
  484. "",
  485. "## Skills",
  486. "- debug: inspect things",
  487. "",
  488. "## Available Tools",
  489. "### Read",
  490. "Read files",
  491. "",
  492. "# User Instructions",
  493. "Keep work observable.",
  494. ].join("\n");
  495. const events = [
  496. {
  497. id: "evt-1",
  498. type: "model_request",
  499. timestamp: "2026-05-04T01:00:00.000Z",
  500. traceId: "trace-debug",
  501. sessionId: "session-debug",
  502. turnId: "turn-1",
  503. payload: {
  504. model: "gpt-test",
  505. messages: [
  506. { role: "system", content: systemPrompt },
  507. { role: "user", content: "inspect this trace" },
  508. ],
  509. },
  510. },
  511. {
  512. id: "evt-2",
  513. type: "model_complete",
  514. timestamp: "2026-05-04T01:00:01.000Z",
  515. traceId: "trace-debug",
  516. sessionId: "session-debug",
  517. turnId: "turn-1",
  518. payload: {
  519. usage: {
  520. inputTokens: 128,
  521. outputTokens: 32,
  522. totalTokens: 160,
  523. cacheReadTokens: 64,
  524. cacheWriteTokens: 12,
  525. },
  526. },
  527. },
  528. {
  529. id: "evt-3",
  530. type: "turn_complete",
  531. timestamp: "2026-05-04T01:00:02.000Z",
  532. traceId: "trace-debug",
  533. sessionId: "session-debug",
  534. turnId: "turn-1",
  535. payload: {
  536. resultType: "success",
  537. cacheStats: {
  538. totalMessages: 2,
  539. cachedMessages: 1,
  540. lastCacheHit: true,
  541. },
  542. },
  543. },
  544. ];
  545. const eventLines = events.map((event) => JSON.stringify(event));
  546. if (options.includeBadLine) eventLines.splice(1, 0, "{bad json");
  547. await writeFile(eventPath, `${eventLines.join("\n")}\n`, "utf8");
  548. await writeFile(
  549. logPath,
  550. `${JSON.stringify({
  551. timestamp: "2026-05-04T01:00:00.100Z",
  552. level: "debug",
  553. message: "Context built",
  554. traceId: "trace-debug",
  555. sessionId: "session-debug",
  556. context: {
  557. totalChars: 40,
  558. totalTokens: 10,
  559. sections: [{ name: "Skills", chars: 24, tokens: 6 }],
  560. },
  561. })}\n`,
  562. "utf8",
  563. );
  564. return { root, logDir, eventPath };
  565. }
  566. async function createProjectFixture() {
  567. const root = await mkdtemp(join(tmpdir(), "zcode-debug-project-"));
  568. const logDir = join(root, "logs");
  569. await mkdir(logDir);
  570. const eventPath = join(root, "events.jsonl");
  571. const dbPath = join(root, "db.sqlite");
  572. const events = Array.from({ length: 12 }, (_, index) => ({
  573. id: `evt-new-${index}`,
  574. type: "turn_complete",
  575. timestamp: `2026-05-04T02:${String(index).padStart(2, "0")}:00.000Z`,
  576. traceId: `trace-new-${index}`,
  577. sessionId: "session-new",
  578. payload: { resultType: "success" },
  579. }));
  580. events.push({
  581. id: "evt-old",
  582. type: "turn_complete",
  583. timestamp: "2026-05-04T01:00:00.000Z",
  584. traceId: "trace-old",
  585. sessionId: "session-old",
  586. payload: { resultType: "success" },
  587. });
  588. await writeFile(
  589. eventPath,
  590. `${events.map((event) => JSON.stringify(event)).join("\n")}\n`,
  591. "utf8",
  592. );
  593. await writeFile(join(logDir, "zcode.jsonl"), "", "utf8");
  594. const db = new DatabaseSync(dbPath);
  595. try {
  596. db.exec(`
  597. create table session (
  598. id text primary key,
  599. project_id text not null,
  600. title text not null,
  601. directory text not null,
  602. time_created integer not null,
  603. time_updated integer not null
  604. );
  605. `);
  606. const insert = db.prepare(
  607. "insert into session (id, project_id, title, directory, time_created, time_updated) values (?, ?, ?, ?, ?, ?)",
  608. );
  609. insert.run("session-old", "project-old", "Old", "/work/old", 1000, 1000);
  610. insert.run("session-new", "project-new", "New", "/work/new", 2000, 2000);
  611. db.exec(`
  612. create table message (
  613. id text primary key,
  614. session_id text not null,
  615. time_created integer not null,
  616. time_updated integer not null,
  617. data text not null
  618. );
  619. create table part (
  620. id text primary key,
  621. message_id text not null,
  622. session_id text not null,
  623. time_created integer not null,
  624. time_updated integer not null,
  625. data text not null
  626. );
  627. `);
  628. const insertMessage = db.prepare(
  629. "insert into message (id, session_id, time_created, time_updated, data) values (?, ?, ?, ?, ?)",
  630. );
  631. insertMessage.run(
  632. "message-old-user",
  633. "session-old",
  634. 1100,
  635. 1100,
  636. JSON.stringify({ role: "user" }),
  637. );
  638. insertMessage.run(
  639. "message-new-user",
  640. "session-new",
  641. 2100,
  642. 2100,
  643. JSON.stringify({ role: "user", content: "new project first prompt" }),
  644. );
  645. const insertPart = db.prepare(
  646. "insert into part (id, message_id, session_id, time_created, time_updated, data) values (?, ?, ?, ?, ?, ?)",
  647. );
  648. insertPart.run(
  649. "part-old-user-text",
  650. "message-old-user",
  651. "session-old",
  652. 1100,
  653. 1100,
  654. JSON.stringify({ type: "text", text: "old project part prompt" }),
  655. );
  656. insertPart.run(
  657. "part-old-step-finish",
  658. "message-old-assistant",
  659. "session-old",
  660. 1200,
  661. 1200,
  662. JSON.stringify({
  663. type: "step-finish",
  664. tokens: {
  665. input: 100,
  666. output: 25,
  667. total: 125,
  668. cache: { read: 20, write: 5 },
  669. },
  670. }),
  671. );
  672. } finally {
  673. db.close();
  674. }
  675. return { root, logDir, eventPath, dbPath };
  676. }