scan-legacy-sessions.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. #!/usr/bin/env node
  2. import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
  3. import { basename, join } from "node:path";
  4. import { homedir } from "node:os";
  5. const originalEmitWarning = process.emitWarning;
  6. process.emitWarning = function filterSqliteExperimentalWarning(warning, ...args) {
  7. // 只读扫描依赖 node:sqlite 访问本地 DB;过滤该实验提示,避免污染给用户选择用的表格。
  8. if (String(warning).includes("SQLite is an experimental feature")) return;
  9. return originalEmitWarning.call(process, warning, ...args);
  10. };
  11. const { DatabaseSync } = await import("node:sqlite");
  12. process.emitWarning = originalEmitWarning;
  13. const defaultLegacyDir = join(homedir(), ".zcode", "v2", "sessions");
  14. const defaultTaskIndexPath = join(homedir(), ".zcode", "v2", "tasks-index.sqlite");
  15. const defaultCliDbPath = join(homedir(), ".zcode", "cli", "db", "db.sqlite");
  16. function printUsage() {
  17. console.log(`Usage:
  18. scan-legacy-sessions.mjs summary [--json]
  19. scan-legacy-sessions.mjs agents [--json]
  20. scan-legacy-sessions.mjs workspaces --agent <provider> [--json]
  21. scan-legacy-sessions.mjs conversations --agent <provider> --workspace <path> [--query <text>] [--limit <n>] [--json]
  22. Options:
  23. --legacy-dir <path> Legacy snapshot root. Default: ${defaultLegacyDir}
  24. --task-index <path> Task index sqlite path. Default: ${defaultTaskIndexPath}
  25. --cli-db <path> New ZCode session sqlite path. Default: ${defaultCliDbPath}
  26. --agent <provider> Filter by provider, such as glm, claude, codex, opencode.
  27. --workspace <path> Filter by exact workspace path.
  28. --query <text> Filter conversations by title, ids, or visible message text.
  29. --conversation <id> Filter by restored task id, legacy task id, or ACP session id.
  30. --limit <n> Conversation row limit. Default: 30.
  31. --json Print JSON instead of Markdown tables.
  32. `);
  33. }
  34. function parseArgs(argv) {
  35. const args = {
  36. command: argv[0] ?? "summary",
  37. legacyDir: defaultLegacyDir,
  38. taskIndexPath: defaultTaskIndexPath,
  39. cliDbPath: defaultCliDbPath,
  40. json: false,
  41. limit: 30,
  42. };
  43. for (let index = 1; index < argv.length; index += 1) {
  44. const item = argv[index];
  45. if (item === "--json") {
  46. args.json = true;
  47. continue;
  48. }
  49. if (item === "--help" || item === "-h") {
  50. args.help = true;
  51. continue;
  52. }
  53. const next = argv[index + 1];
  54. if (!next) {
  55. throw new Error(`Missing value for ${item}`);
  56. }
  57. index += 1;
  58. if (item === "--legacy-dir") args.legacyDir = next;
  59. else if (item === "--task-index") args.taskIndexPath = next;
  60. else if (item === "--cli-db") args.cliDbPath = next;
  61. else if (item === "--agent") args.agent = next;
  62. else if (item === "--workspace") args.workspace = next;
  63. else if (item === "--query") args.query = next;
  64. else if (item === "--conversation") args.conversation = next;
  65. else if (item === "--limit") args.limit = Number.parseInt(next, 10);
  66. else throw new Error(`Unknown option: ${item}`);
  67. }
  68. if (!Number.isFinite(args.limit) || args.limit <= 0) args.limit = 30;
  69. return args;
  70. }
  71. function collectJsonFiles(root) {
  72. if (!existsSync(root)) return [];
  73. const files = [];
  74. for (const workspaceDir of readdirSync(root)) {
  75. const dirPath = join(root, workspaceDir);
  76. if (!statSync(dirPath).isDirectory()) continue;
  77. for (const fileName of readdirSync(dirPath)) {
  78. if (!fileName.endsWith(".json") || fileName.endsWith(".deleted.json")) continue;
  79. files.push(join(dirPath, fileName));
  80. }
  81. }
  82. return files;
  83. }
  84. function readSnapshot(filePath) {
  85. try {
  86. const raw = JSON.parse(readFileSync(filePath, "utf8"));
  87. const meta = raw.meta && typeof raw.meta === "object" ? raw.meta : {};
  88. const messages = Array.isArray(raw.messages) ? raw.messages : [];
  89. const legacyTaskId = String(meta.taskId || basename(filePath, ".json"));
  90. const acpSessionId = typeof meta.acpSessionId === "string" ? meta.acpSessionId : "";
  91. const restoredTaskId = acpSessionId || legacyTaskId;
  92. const workspacePath = typeof meta.workspacePath === "string" ? meta.workspacePath : "";
  93. const provider = typeof meta.provider === "string" ? meta.provider : "unknown";
  94. const firstUser = messages.find((message) => message?.role === "user");
  95. const title =
  96. typeof meta.title === "string" && meta.title.trim()
  97. ? meta.title.trim()
  98. : summarizeText(firstUser?.content) || "Untitled session";
  99. const createdAt = finiteNumber(meta.createdAt) ?? firstTimestamp(messages) ?? 0;
  100. const updatedAt = finiteNumber(meta.updatedAt) ?? lastTimestamp(messages) ?? createdAt;
  101. const visibleText = messages.map((message) => String(message?.content ?? "")).join("\n");
  102. return {
  103. filePath,
  104. workspaceHash: basename(join(filePath, "..")),
  105. legacyTaskId,
  106. acpSessionId,
  107. restoredTaskId,
  108. workspacePath,
  109. workspaceIdentity:
  110. typeof meta.workspaceIdentity === "string" ? meta.workspaceIdentity : undefined,
  111. provider,
  112. model: typeof meta.model === "string" ? meta.model : undefined,
  113. title,
  114. createdAt,
  115. updatedAt,
  116. messageCount: messages.length,
  117. userMessageCount: messages.filter((message) => message?.role === "user").length,
  118. assistantMessageCount: messages.filter((message) => message?.role === "assistant").length,
  119. visibleText,
  120. };
  121. } catch (error) {
  122. return {
  123. filePath,
  124. error: error instanceof Error ? error.message : String(error),
  125. };
  126. }
  127. }
  128. function finiteNumber(value) {
  129. return typeof value === "number" && Number.isFinite(value) ? value : undefined;
  130. }
  131. function firstTimestamp(messages) {
  132. for (const message of messages) {
  133. const timestamp = finiteNumber(message?.timestamp);
  134. if (timestamp !== undefined) return timestamp;
  135. }
  136. return undefined;
  137. }
  138. function lastTimestamp(messages) {
  139. for (let index = messages.length - 1; index >= 0; index -= 1) {
  140. const timestamp = finiteNumber(messages[index]?.timestamp);
  141. if (timestamp !== undefined) return timestamp;
  142. }
  143. return undefined;
  144. }
  145. function summarizeText(value) {
  146. const text = typeof value === "string" ? value.trim().replace(/\s+/g, " ") : "";
  147. return text.length > 80 ? `${text.slice(0, 77)}...` : text;
  148. }
  149. function openDatabase(path) {
  150. if (!existsSync(path)) return null;
  151. if (statSync(path).size === 0) return null;
  152. try {
  153. return new DatabaseSync(path, { readOnly: true });
  154. } catch {
  155. return null;
  156. }
  157. }
  158. function attachStoreStatus(candidates, taskIndexPath, cliDbPath) {
  159. const taskIndexDb = openDatabase(taskIndexPath);
  160. const cliDb = openDatabase(cliDbPath);
  161. const taskByRestored = prepareOrNull(
  162. taskIndexDb,
  163. "select count(*) as count from tasks where workspace_path = ? and task_id = ?",
  164. );
  165. const taskByLegacy = prepareOrNull(
  166. taskIndexDb,
  167. "select count(*) as count from tasks where workspace_path = ? and task_id = ?",
  168. );
  169. const cliBySession = prepareOrNull(cliDb, "select count(*) as count from session where id = ?");
  170. for (const candidate of candidates) {
  171. if (candidate.error) continue;
  172. const taskIndexRestored = countResult(
  173. taskByRestored?.get(candidate.workspacePath, candidate.restoredTaskId),
  174. );
  175. const taskIndexLegacy = countResult(
  176. taskByLegacy?.get(candidate.workspacePath, candidate.legacyTaskId),
  177. );
  178. const cliSession = countResult(cliBySession?.get(candidate.restoredTaskId));
  179. candidate.store = {
  180. cliDb: cliSession > 0 ? "present" : "missing",
  181. taskIndex:
  182. taskIndexRestored > 0 ? "present" : taskIndexLegacy > 0 ? "legacy-task-id" : "missing",
  183. };
  184. candidate.restoreState = restoreState(candidate.store);
  185. }
  186. taskIndexDb?.close();
  187. cliDb?.close();
  188. }
  189. function prepareOrNull(db, sql) {
  190. if (!db) return null;
  191. try {
  192. return db.prepare(sql);
  193. } catch {
  194. // 目的地 DB 可能刚被备份/清空;扫描阶段只把缺表视为 missing,不能创建或修复。
  195. return null;
  196. }
  197. }
  198. function countResult(row) {
  199. return typeof row?.count === "number" ? row.count : 0;
  200. }
  201. function restoreState(store) {
  202. const cliPresent = store.cliDb === "present";
  203. const taskPresent = store.taskIndex === "present";
  204. if (cliPresent && taskPresent) return "ready";
  205. if (!cliPresent && taskPresent) return "needs-cli-db";
  206. if (cliPresent && !taskPresent) return "needs-task-index";
  207. return "needs-full-import";
  208. }
  209. function filterCandidates(candidates, args) {
  210. const query = args.query?.toLowerCase();
  211. const conversation = args.conversation?.toLowerCase();
  212. return candidates.filter((candidate) => {
  213. if (candidate.error) return false;
  214. if (args.agent && args.agent !== "all" && candidate.provider !== args.agent) return false;
  215. if (args.workspace && candidate.workspacePath !== args.workspace) return false;
  216. if (
  217. conversation &&
  218. ![candidate.restoredTaskId, candidate.legacyTaskId, candidate.acpSessionId]
  219. .filter(Boolean)
  220. .some((value) => value.toLowerCase() === conversation)
  221. ) {
  222. return false;
  223. }
  224. if (!query) return true;
  225. const haystack = [
  226. candidate.provider,
  227. candidate.workspacePath,
  228. candidate.title,
  229. candidate.restoredTaskId,
  230. candidate.legacyTaskId,
  231. candidate.acpSessionId,
  232. candidate.visibleText,
  233. ]
  234. .join("\n")
  235. .toLowerCase();
  236. return haystack.includes(query);
  237. });
  238. }
  239. function groupBy(items, keyFn) {
  240. const map = new Map();
  241. for (const item of items) {
  242. const key = keyFn(item);
  243. const existing = map.get(key) ?? [];
  244. existing.push(item);
  245. map.set(key, existing);
  246. }
  247. return map;
  248. }
  249. function summarizeGroups(candidates, keyFn) {
  250. return [...groupBy(candidates, keyFn).entries()]
  251. .map(([key, items]) => ({
  252. key,
  253. count: items.length,
  254. workspaces: new Set(items.map((item) => item.workspacePath)).size,
  255. ready: items.filter((item) => item.restoreState === "ready").length,
  256. needsCliDb: items.filter((item) => item.restoreState === "needs-cli-db").length,
  257. needsTaskIndex: items.filter((item) => item.restoreState === "needs-task-index").length,
  258. needsFullImport: items.filter((item) => item.restoreState === "needs-full-import").length,
  259. latestUpdatedAt: Math.max(...items.map((item) => item.updatedAt || 0)),
  260. }))
  261. .sort((a, b) => b.count - a.count || a.key.localeCompare(b.key));
  262. }
  263. function escapeCell(value) {
  264. return String(value ?? "")
  265. .replace(/\|/g, "\\|")
  266. .replace(/\n/g, " ")
  267. .trim();
  268. }
  269. function markdownTable(headers, rows) {
  270. const header = `| ${headers.map(escapeCell).join(" | ")} |`;
  271. const divider = `| ${headers.map(() => "---").join(" | ")} |`;
  272. const body = rows.map((row) => `| ${row.map(escapeCell).join(" | ")} |`);
  273. return [header, divider, ...body].join("\n");
  274. }
  275. function formatTime(ms) {
  276. if (!ms) return "";
  277. return new Date(ms).toISOString().replace("T", " ").replace(".000Z", "Z");
  278. }
  279. function printAgents(candidates, json) {
  280. const rows = summarizeGroups(candidates, (item) => item.provider);
  281. if (json) return printJson(rows);
  282. console.log(
  283. markdownTable(
  284. ["agent", "conversations", "workspaces", "ready", "needs-cli-db", "needs-task-index", "needs-full-import"],
  285. rows.map((row) => [
  286. row.key,
  287. row.count,
  288. row.workspaces,
  289. row.ready,
  290. row.needsCliDb,
  291. row.needsTaskIndex,
  292. row.needsFullImport,
  293. ]),
  294. ),
  295. );
  296. }
  297. function printWorkspaces(candidates, json) {
  298. const rows = summarizeGroups(candidates, (item) => item.workspacePath);
  299. if (json) return printJson(rows);
  300. console.log(
  301. markdownTable(
  302. ["workspace", "conversations", "ready", "needs-cli-db", "needs-task-index", "needs-full-import", "latest"],
  303. rows.map((row) => [
  304. row.key,
  305. row.count,
  306. row.ready,
  307. row.needsCliDb,
  308. row.needsTaskIndex,
  309. row.needsFullImport,
  310. formatTime(row.latestUpdatedAt),
  311. ]),
  312. ),
  313. );
  314. }
  315. function printConversations(candidates, args) {
  316. const rows = [...candidates]
  317. .sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0))
  318. .slice(0, args.limit);
  319. if (args.json) return printJson(rows.map(stripVisibleText));
  320. console.log(
  321. markdownTable(
  322. ["#", "state", "agent", "title", "messages", "updated", "restoredTaskId", "legacyTaskId"],
  323. rows.map((row, index) => [
  324. index + 1,
  325. row.restoreState,
  326. row.provider,
  327. row.title,
  328. row.messageCount,
  329. formatTime(row.updatedAt),
  330. row.restoredTaskId,
  331. row.legacyTaskId,
  332. ]),
  333. ),
  334. );
  335. }
  336. function printSummary(candidates, invalid, json) {
  337. const payload = {
  338. total: candidates.length,
  339. invalid: invalid.length,
  340. byAgent: summarizeGroups(candidates, (item) => item.provider),
  341. byState: summarizeGroups(candidates, (item) => item.restoreState),
  342. };
  343. if (json) return printJson(payload);
  344. console.log(`Total legacy conversations: ${payload.total}`);
  345. if (payload.invalid > 0) console.log(`Invalid snapshots: ${payload.invalid}`);
  346. console.log("\nBy agent:");
  347. printAgents(candidates, false);
  348. console.log("\nBy restore state:");
  349. console.log(
  350. markdownTable(
  351. ["state", "conversations", "workspaces"],
  352. payload.byState.map((row) => [row.key, row.count, row.workspaces]),
  353. ),
  354. );
  355. }
  356. function stripVisibleText(candidate) {
  357. const { visibleText, ...rest } = candidate;
  358. return rest;
  359. }
  360. function printJson(value) {
  361. console.log(JSON.stringify(value, null, 2));
  362. }
  363. function main() {
  364. const args = parseArgs(process.argv.slice(2));
  365. if (args.help) {
  366. printUsage();
  367. return;
  368. }
  369. const raw = collectJsonFiles(args.legacyDir).map(readSnapshot);
  370. const invalid = raw.filter((candidate) => candidate.error);
  371. const valid = raw.filter((candidate) => !candidate.error);
  372. attachStoreStatus(valid, args.taskIndexPath, args.cliDbPath);
  373. const filtered = filterCandidates(valid, args);
  374. if (args.command === "summary") printSummary(filtered, invalid, args.json);
  375. else if (args.command === "agents") printAgents(filtered, args.json);
  376. else if (args.command === "workspaces") printWorkspaces(filtered, args.json);
  377. else if (args.command === "conversations") printConversations(filtered, args);
  378. else {
  379. throw new Error(`Unknown command: ${args.command}`);
  380. }
  381. }
  382. try {
  383. main();
  384. } catch (error) {
  385. console.error(error instanceof Error ? error.message : String(error));
  386. printUsage();
  387. process.exitCode = 1;
  388. }