shadow-replay.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // 影子重放对账(交付 / 测试基建)。
  2. // 用途:把本机真实 CLI 库(默认 ~/.zcode/cli/db/db.sqlite)的历史会话全量喂给
  3. // 冷恢复管线(transcript 合成 → ProductProjection),输出守恒对账报告——
  4. // 每阶段上线门槛 = 全量重放无崩溃、无静默丢弃、失败清单审查完毕。
  5. //
  6. // 对源库只读:默认把 db(含 -wal/-shm)复制到临时目录再打开——store 打开时会跑
  7. // 迁移(0015/0016 等),不能直接落在用户真实库上(迁移应由 CLI 正常启动路径应用)。
  8. // 运行前先构建:pnpm -C apps/zcode-cli build(脚本从各包 dist 导入)。
  9. //
  10. // 用法:
  11. // node scripts/shadow-replay.mjs [--db <path>] [--limit <n>] [--session <id>] [--verbose] [--no-copy]
  12. import { parseArgs } from "node:util";
  13. import { homedir, tmpdir } from "node:os";
  14. import { join, dirname, basename } from "node:path";
  15. import { copyFileSync, existsSync, mkdtempSync } from "node:fs";
  16. import { fileURLToPath, pathToFileURL } from "node:url";
  17. const here = dirname(fileURLToPath(import.meta.url));
  18. const pkg = (relative) =>
  19. import(pathToFileURL(join(here, "..", "packages", relative)).href);
  20. const { values: args } = parseArgs({
  21. options: {
  22. db: { type: "string" },
  23. limit: { type: "string" },
  24. session: { type: "string" },
  25. verbose: { type: "boolean", default: false },
  26. "no-copy": { type: "boolean", default: false },
  27. },
  28. });
  29. const [{ createSqliteSessionStore }, hydration, projectionModule, contracts] =
  30. await Promise.all([
  31. pkg("adapters/dist/storage/index.js"),
  32. pkg("bootstrap/dist/zcode-protocol-v4/transcript-hydration.js"),
  33. pkg("bootstrap/dist/zcode-protocol-v4/product-projection.js"),
  34. pkg("contracts/dist/index.js"),
  35. ]);
  36. const {
  37. synthesizeEventsFromMessages,
  38. goalVerificationEntriesFromSessionEntries,
  39. } = hydration;
  40. const { ProductProjection } = projectionModule;
  41. const { SESSION_ENTRY_TARGET_COMPLETION_VERIFICATION } = contracts;
  42. const sourceDbPath = args.db ?? join(homedir(), ".zcode", "cli", "db", "db.sqlite");
  43. const limit = args.limit ? Number(args.limit) : Infinity;
  44. let dbPath = sourceDbPath;
  45. if (!args["no-copy"]) {
  46. const tempDir = mkdtempSync(join(tmpdir(), "zcode-shadow-replay-"));
  47. dbPath = join(tempDir, basename(sourceDbPath));
  48. copyFileSync(sourceDbPath, dbPath);
  49. for (const suffix of ["-wal", "-shm"]) {
  50. if (existsSync(sourceDbPath + suffix)) {
  51. copyFileSync(sourceDbPath + suffix, dbPath + suffix);
  52. }
  53. }
  54. }
  55. const store = createSqliteSessionStore({ dbPath });
  56. const sessions = args.session
  57. ? [{ id: args.session }]
  58. : await store.listSessions({ includeArchived: true, limit: 100000 });
  59. const totals = {
  60. sessions: 0,
  61. crashed: 0,
  62. assistantTextMissing: 0,
  63. userInputMismatch: 0,
  64. goalVerifyMissing: 0,
  65. modelChangeMissing: 0,
  66. entityTargetMismatch: 0,
  67. actionAddressabilityMismatch: 0,
  68. clean: 0,
  69. };
  70. const offenders = [];
  71. for (const session of sessions) {
  72. if (totals.sessions >= limit) break;
  73. totals.sessions += 1;
  74. const sessionId = String(session.id);
  75. const report = {
  76. sessionId,
  77. problems: [],
  78. };
  79. try {
  80. const messages = await store.messages({ sessionID: session.id });
  81. if (messages.length === 0) continue;
  82. const entries = store.sessionEntries
  83. ? await store.sessionEntries({
  84. sessionID: session.id,
  85. type: SESSION_ENTRY_TARGET_COMPLETION_VERIFICATION,
  86. })
  87. : [];
  88. const goalVerificationEntries = goalVerificationEntriesFromSessionEntries(entries);
  89. const events = synthesizeEventsFromMessages(messages, {
  90. sessionId,
  91. goalVerificationEntries,
  92. });
  93. const projection = new ProductProjection(sessionId, "shadow-replay");
  94. for (const event of events) projection.applyEvent(event);
  95. const rows = projection.getSnapshot().rows.window;
  96. // ── 守恒对账 ──
  97. // assistant 守恒:每条可见 assistant text 必须出现在 rows(多重集覆盖)。
  98. const expectedTexts = [];
  99. for (const message of messages) {
  100. if (message.info.role !== "assistant") continue;
  101. for (const part of message.parts) {
  102. if (part.type === "text" && part.ignored !== true && part.text.length > 0) {
  103. expectedTexts.push(part.text);
  104. }
  105. }
  106. }
  107. const actualTexts = rows
  108. .filter((row) => row.kind === "assistantText")
  109. .map((row) => row.text);
  110. const remaining = [...actualTexts];
  111. let missingTexts = 0;
  112. for (const text of expectedTexts) {
  113. const index = remaining.indexOf(text);
  114. if (index < 0) missingTexts += 1;
  115. else remaining.splice(index, 1);
  116. }
  117. if (missingTexts > 0) {
  118. totals.assistantTextMissing += 1;
  119. report.problems.push(`assistant text 缺失 ${missingTexts}/${expectedTexts.length}`);
  120. }
  121. // goal verify 守恒:part ∪ entry 的 lifecycle key 数 vs goalVerify marker 行数。
  122. const goalKeys = new Set();
  123. for (const message of messages) {
  124. for (const part of message.parts) {
  125. if (part.type === "timeline" && part.timelineType === "goal_verification") {
  126. goalKeys.add(
  127. part.goalIteration !== undefined
  128. ? `${part.targetId}_${part.goalIteration}`
  129. : part.verificationId,
  130. );
  131. }
  132. }
  133. }
  134. for (const entry of goalVerificationEntries) {
  135. const payload = entry.payload;
  136. goalKeys.add(
  137. payload.goalIteration !== undefined
  138. ? `${payload.targetId}_${payload.goalIteration}`
  139. : payload.verificationId,
  140. );
  141. }
  142. const goalMarkers = rows.filter(
  143. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  144. ).length;
  145. if (goalMarkers < goalKeys.size) {
  146. totals.goalVerifyMissing += 1;
  147. report.problems.push(`goalVerify marker ${goalMarkers}/${goalKeys.size}`);
  148. }
  149. // 可见 user 输入守恒:userInput 行数不得少于真实 user 文本消息数的下限估计
  150. //(synthetic/model-only 不计;guide steer 内联也是可见行,计入两侧)。
  151. // 已知误报:legacy 数据里 goal-continuation reminder / fork notice 以裸文本
  152. // 持久化(无 synthetic/source/metadata 标记),分类器按文本前缀正确隐藏,
  153. // 本启发式会把它们计成可见——flag 需人工核对(全量重放中 21 个
  154. // flag 全为此类误报,真实守恒失败为 0)。
  155. const expectedUsers = messages.filter(
  156. (message) =>
  157. message.info.role === "user" &&
  158. message.info.synthetic !== true &&
  159. message.info.visibility !== "model-only" &&
  160. // compact 续接摘要(info.summary / semantics.kind=compact_summary)是
  161. // providerContextOnly:分类器裁决不可见,不计入可见 user 下限。
  162. message.info.summary === undefined &&
  163. !message.info.semantics?.kind?.startsWith?.("compact") &&
  164. message.info.source === undefined &&
  165. message.parts.some(
  166. (part) => part.type === "text" && part.ignored !== true && part.text.length > 0,
  167. ),
  168. ).length;
  169. const actualUsers = rows.filter((row) => row.kind === "userInput").length;
  170. if (actualUsers < expectedUsers) {
  171. totals.userInputMismatch += 1;
  172. report.problems.push(`userInput 行 ${actualUsers}/${expectedUsers}`);
  173. }
  174. // 可寻址性守恒:shadow replay 不能只证明“文本还在”。每条 transcript row 的
  175. // entity/productTurn/message target,以及每个已发布 action,都必须由同一次 cold
  176. // materialization 的 resolver 精确命中;否则 UI 会显示按钮但命令必然 stale/reject。
  177. let entityTargetProblems = 0;
  178. let actionProblems = 0;
  179. const actionByFlag = [
  180. ["canEdit", "editUserQuery"],
  181. ["canRetry", "retryTurn"],
  182. ["canFork", "forkAssistant"],
  183. ["canRewindFiles", "fileRewindPreview"],
  184. ];
  185. for (const row of rows) {
  186. const entityId = projection.getEntityIdForRow(row.rowId);
  187. const messageId = projection.getMessageIdForRow(row.rowId);
  188. if (
  189. (row.kind === "userInput" || row.kind === "assistantText") &&
  190. (!entityId || !messageId || !row.turnId)
  191. ) {
  192. entityTargetProblems += 1;
  193. }
  194. for (const [flag, action] of actionByFlag) {
  195. if (row.actions?.[flag] !== true) continue;
  196. if (!entityId) {
  197. actionProblems += 1;
  198. continue;
  199. }
  200. const resolution = projection.resolveRowActionTarget(
  201. { rowId: row.rowId, entityId },
  202. action,
  203. );
  204. if (!resolution.ok || resolution.row.turnId !== row.turnId) {
  205. actionProblems += 1;
  206. continue;
  207. }
  208. if (
  209. (action === "editUserQuery" ||
  210. action === "retryTurn" ||
  211. action === "forkAssistant") &&
  212. (!messageId ||
  213. ("messageId" in resolution && resolution.messageId !== messageId) ||
  214. ("editTarget" in resolution &&
  215. resolution.editTarget.productTurnId !== row.turnId))
  216. ) {
  217. actionProblems += 1;
  218. }
  219. }
  220. }
  221. if (entityTargetProblems > 0) {
  222. totals.entityTargetMismatch += 1;
  223. report.problems.push(`entity/target 不可寻址 ${entityTargetProblems}`);
  224. }
  225. if (actionProblems > 0) {
  226. totals.actionAddressabilityMismatch += 1;
  227. report.problems.push(`row.actions resolver 不等价 ${actionProblems}`);
  228. }
  229. if (report.problems.length === 0) totals.clean += 1;
  230. } catch (error) {
  231. totals.crashed += 1;
  232. report.problems.push(`重放崩溃: ${error?.message ?? error}`);
  233. }
  234. if (report.problems.length > 0) {
  235. offenders.push(report);
  236. if (args.verbose) {
  237. console.log(`✗ ${sessionId}: ${report.problems.join("; ")}`);
  238. }
  239. }
  240. }
  241. store.close();
  242. console.log("\n── 影子重放对账报告 ──");
  243. console.log(`源 DB: ${sourceDbPath}${dbPath === sourceDbPath ? "" : "(已复制到临时副本重放)"}`);
  244. console.log(`会话: ${totals.sessions}(干净 ${totals.clean})`);
  245. console.log(`重放崩溃: ${totals.crashed}`);
  246. console.log(`assistant text 缺失: ${totals.assistantTextMissing}`);
  247. console.log(`userInput 行不足: ${totals.userInputMismatch}`);
  248. console.log(`goalVerify marker 缺失: ${totals.goalVerifyMissing}`);
  249. console.log(`entity/target 不可寻址: ${totals.entityTargetMismatch}`);
  250. console.log(`row.actions resolver 不等价: ${totals.actionAddressabilityMismatch}`);
  251. if (offenders.length > 0 && !args.verbose) {
  252. console.log(`\n问题会话(前 20,--verbose 看全量):`);
  253. for (const report of offenders.slice(0, 20)) {
  254. console.log(` ${report.sessionId}: ${report.problems.join("; ")}`);
  255. }
  256. }
  257. process.exitCode =
  258. totals.crashed > 0 ||
  259. totals.entityTargetMismatch > 0 ||
  260. totals.actionAddressabilityMismatch > 0
  261. ? 1
  262. : 0;