gitCheckpointRepo.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. import { copyFile, lstat, mkdir, mkdtemp, rm } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import type {
  4. GitCheckpointConflict,
  5. GitCheckpointDiff,
  6. GitCheckpointMeta,
  7. GitCheckpointRestoreResult,
  8. } from "@zcode/shared";
  9. import { getGitCheckpointIndexRootDir } from "../../paths.js";
  10. import { toWorkspaceRelativeGitPath } from "../config.js";
  11. import {
  12. createGitCommandProvider,
  13. type GitCommandProvider,
  14. } from "../providers/gitCommandProvider.js";
  15. import { createGitCliRepo, type GitCliRepo } from "./gitCliRepo.js";
  16. import {
  17. buildAffectedRepoPaths,
  18. buildCheckpointEnv,
  19. getCheckpointRefName,
  20. getWorkspacePathspec,
  21. mergeCheckpointDiff,
  22. normalizeAffectedRepoPath,
  23. parseLsTree,
  24. parseNameStatus,
  25. parseNumstat,
  26. removeFileIfExists,
  27. toAbsolutePath,
  28. } from "./gitCheckpointHelpers.js";
  29. import { ensureGitCommandSucceeded } from "./gitCliHelpers.js";
  30. interface GitCheckpointRepo {
  31. createCheckpoint(params: {
  32. workspacePath: string;
  33. checkpointId: string;
  34. }): Promise<GitCheckpointMeta>;
  35. diffCheckpoints(params: {
  36. workspacePath: string;
  37. from: GitCheckpointMeta;
  38. to: GitCheckpointMeta;
  39. }): Promise<GitCheckpointDiff>;
  40. restoreBetweenCheckpoints(params: {
  41. workspacePath: string;
  42. from: GitCheckpointMeta;
  43. to: GitCheckpointMeta;
  44. force?: boolean;
  45. }): Promise<GitCheckpointRestoreResult>;
  46. deleteCheckpoint(params: { workspacePath: string; checkpoint: GitCheckpointMeta }): Promise<void>;
  47. }
  48. async function pathExists(path: string): Promise<boolean> {
  49. try {
  50. await lstat(path);
  51. return true;
  52. } catch {
  53. return false;
  54. }
  55. }
  56. export function createGitCheckpointRepo(options?: {
  57. commandProvider?: GitCommandProvider;
  58. gitRepo?: Pick<GitCliRepo, "resolveRepository">;
  59. }): GitCheckpointRepo {
  60. const commandProvider = options?.commandProvider ?? createGitCommandProvider();
  61. const gitRepo = options?.gitRepo ?? createGitCliRepo({ commandProvider });
  62. async function ensureRepository(
  63. workspacePath: string,
  64. ): Promise<Awaited<ReturnType<typeof gitRepo.resolveRepository>>> {
  65. // 所有 checkpoint 操作都必须建立在“当前 workspace 对应一个真实 Git 仓库”这个前提上。
  66. // 这里统一做仓库解析和能力前置校验,避免各个方法各自判断后出现错误语义不一致。
  67. const resolution = await gitRepo.resolveRepository(workspacePath);
  68. if (!resolution.isGitAvailable) {
  69. throw new Error("Git binary is not available in the current environment.");
  70. }
  71. if (!resolution.isRepository) {
  72. throw new Error("Workspace is not inside a Git repository.");
  73. }
  74. return resolution;
  75. }
  76. async function computeCheckpointDiff(params: {
  77. workspacePath: string;
  78. from: GitCheckpointMeta;
  79. to: GitCheckpointMeta;
  80. }): Promise<GitCheckpointDiff> {
  81. // checkpoint 之间的 diff 只针对当前 workspace scope 计算,而不是整仓库。
  82. // 这样 monorepo 子目录打开时,后续 restore / 摘要 / 冲突检测都会天然收敛在当前工作区边界内。
  83. const resolution = await ensureRepository(params.workspacePath);
  84. const pathspec = getWorkspacePathspec(resolution.workspaceInRepoPath);
  85. const [nameStatusResult, numstatResult] = await Promise.all([
  86. commandProvider.run({
  87. cwd: resolution.repoRoot,
  88. args: [
  89. "diff",
  90. "--name-status",
  91. "--find-renames",
  92. "-z",
  93. params.from.commitOid,
  94. params.to.commitOid,
  95. "--",
  96. pathspec,
  97. ],
  98. }),
  99. commandProvider.run({
  100. cwd: resolution.repoRoot,
  101. args: [
  102. "diff",
  103. "--numstat",
  104. "--find-renames",
  105. "-z",
  106. params.from.commitOid,
  107. params.to.commitOid,
  108. "--",
  109. pathspec,
  110. ],
  111. }),
  112. ]);
  113. ensureGitCommandSucceeded("git diff --name-status checkpoint", nameStatusResult);
  114. ensureGitCommandSucceeded("git diff --numstat checkpoint", numstatResult);
  115. // name-status 决定“改了哪些文件、是什么类型的改动”,numstat 提供 added/removed 统计。
  116. // 两者拼起来,得到的是给上层使用的结构化 checkpoint diff,而不是原始 Git 文本输出。
  117. return mergeCheckpointDiff({
  118. repoRoot: resolution.repoRoot,
  119. workspaceInRepoPath: resolution.workspaceInRepoPath,
  120. fromCheckpointId: params.from.checkpointId,
  121. toCheckpointId: params.to.checkpointId,
  122. nameStatusEntries: parseNameStatus(nameStatusResult.stdout),
  123. numstat: parseNumstat(numstatResult.stdout),
  124. });
  125. }
  126. async function collectWorkspaceConflicts(params: {
  127. repoRoot: string;
  128. workspaceInRepoPath: string;
  129. from: GitCheckpointMeta;
  130. affectedRepoPaths: string[];
  131. }): Promise<GitCheckpointConflict[]> {
  132. if (params.affectedRepoPaths.length === 0) {
  133. return [];
  134. }
  135. // 冲突检测不是判断“整个工作区是否 dirty”,而是判断 restore 将触达的这些路径,
  136. // 当前磁盘状态是否仍然等于调用方声明的 fromCheckpoint。
  137. // 只有这样,底层能力才能在存在无关改动时依然安全工作,不会把整个仓库一刀切地判成不可恢复。
  138. const treeResult = await commandProvider.run({
  139. cwd: params.repoRoot,
  140. args: ["ls-tree", "-r", "-z", params.from.commitOid, "--", ...params.affectedRepoPaths],
  141. });
  142. ensureGitCommandSucceeded("git ls-tree checkpoint paths", treeResult);
  143. const treeEntries = parseLsTree(treeResult.stdout);
  144. const conflicts: GitCheckpointConflict[] = [];
  145. for (const repoRelativePath of params.affectedRepoPaths) {
  146. const absolutePath = toAbsolutePath(params.repoRoot, repoRelativePath);
  147. const expectedEntry = treeEntries.get(repoRelativePath);
  148. if (!expectedEntry) {
  149. // fromCheckpoint 里不存在该路径,说明按基线语义它本来就不该在磁盘上出现。
  150. // 如果现在却存在,就意味着用户或其它流程在 checkpoint 之后新增了该文件,属于覆盖风险。
  151. if (!(await pathExists(absolutePath))) {
  152. continue;
  153. }
  154. conflicts.push({
  155. path: absolutePath,
  156. repoRelativePath,
  157. workspaceRelativePath: toWorkspaceRelativeGitPath(
  158. repoRelativePath,
  159. params.workspaceInRepoPath,
  160. ),
  161. reason: "unexpected-file-in-worktree",
  162. });
  163. continue;
  164. }
  165. let stats: Awaited<ReturnType<typeof lstat>>;
  166. try {
  167. stats = await lstat(absolutePath);
  168. } catch {
  169. // fromCheckpoint 里要求该文件存在,但磁盘上已经没有了,恢复时如果直接写回,
  170. // 就会覆盖掉“文件为何消失”的真实用户操作,所以要先显式报告冲突。
  171. conflicts.push({
  172. path: absolutePath,
  173. repoRelativePath,
  174. workspaceRelativePath: toWorkspaceRelativeGitPath(
  175. repoRelativePath,
  176. params.workspaceInRepoPath,
  177. ),
  178. reason: "missing-in-worktree",
  179. });
  180. continue;
  181. }
  182. const expectsSymlink = expectedEntry.mode === "120000";
  183. if (stats.isDirectory() || (expectsSymlink && !stats.isSymbolicLink())) {
  184. // 当前实现只处理 Git 能稳定表达的文件状态;如果 checkpoint 期待的是文件/符号链接,
  185. // 现在磁盘却变成了目录或其它类型,直接 restore 很容易出现语义错位,因此按类型冲突处理。
  186. conflicts.push({
  187. path: absolutePath,
  188. repoRelativePath,
  189. workspaceRelativePath: toWorkspaceRelativeGitPath(
  190. repoRelativePath,
  191. params.workspaceInRepoPath,
  192. ),
  193. reason: "type-mismatch",
  194. });
  195. continue;
  196. }
  197. const hashResult = await commandProvider.run({
  198. cwd: params.repoRoot,
  199. args: ["hash-object", "--no-filters", absolutePath],
  200. });
  201. ensureGitCommandSucceeded("git hash-object checkpoint verify", hashResult);
  202. if (hashResult.stdout.trim() === expectedEntry.objectId) {
  203. continue;
  204. }
  205. // 这里不比较时间戳、大小等弱信号,而是直接比较 blob hash。
  206. // 只有内容完全一致,才视为“当前磁盘仍然停留在 fromCheckpoint 基线”。
  207. conflicts.push({
  208. path: absolutePath,
  209. repoRelativePath,
  210. workspaceRelativePath: toWorkspaceRelativeGitPath(
  211. repoRelativePath,
  212. params.workspaceInRepoPath,
  213. ),
  214. reason: "content-mismatch",
  215. });
  216. }
  217. const deduped = new Map<string, GitCheckpointConflict>();
  218. for (const conflict of conflicts) {
  219. deduped.set(conflict.repoRelativePath, conflict);
  220. }
  221. return [...deduped.values()];
  222. }
  223. return {
  224. /**
  225. * 创建一个不可变的 workspace 文件快照。
  226. *
  227. * 整体流程:
  228. * 1. 解析 workspace 对应的 Git 仓库与 scope
  229. * 2. 用临时 GIT_INDEX_FILE 收集当前 live worktree 状态
  230. * 3. 通过 write-tree / commit-tree 生成内部隐藏 commit
  231. * 4. 用 hidden ref 挂住这份 commit,防止被 Git GC 提前清掉
  232. * 5. 返回 manifest 需要的元信息
  233. *
  234. * 关键约束:
  235. * - 不污染用户真实 index
  236. * - 不产生用户可见分支或普通 commit
  237. * - scope 永远跟随当前 workspace,而不是整个 repo 无差别快照
  238. */
  239. async createCheckpoint(params) {
  240. const resolution = await ensureRepository(params.workspacePath);
  241. const refName = getCheckpointRefName(params.workspacePath, params.checkpointId);
  242. const tempIndexRootDir = getGitCheckpointIndexRootDir();
  243. await mkdir(tempIndexRootDir, { recursive: true });
  244. const tempIndexDir = await mkdtemp(resolve(tempIndexRootDir, "index-"));
  245. const tempIndexPath = resolve(tempIndexDir, "index");
  246. const env = buildCheckpointEnv(tempIndexPath);
  247. const pathspec = getWorkspacePathspec(resolution.workspaceInRepoPath);
  248. try {
  249. // 预热临时 index:优先复制用户真实 index,降级到 read-tree HEAD,最差回到空 index。
  250. // 背景:空 index 下 git add -A 会对 workspace 全量文件做 open/read/hash 并写入 object store,
  251. // 在 Windows + Defender 环境下单文件开销被放大到 5-15ms,大仓库轻易撞破 15s 超时。
  252. // 复用用户 index 的 stat cache 后,未改动文件走 stat-match 快速路径,直接跳过读取与写对象,
  253. // Mac/Linux 同样受益(大仓库 add 从数秒降到亚秒),且最终 tree 由 worktree 决定,语义完全等价。
  254. // 用 rev-parse --git-path index 解析真实 index 路径,兼容 worktree / submodule 场景。
  255. const indexPathResult = await commandProvider.run({
  256. cwd: resolution.repoRoot,
  257. args: ["rev-parse", "--git-path", "index"],
  258. });
  259. let primed = false;
  260. if (indexPathResult.exitCode === 0) {
  261. const indexRelPath = indexPathResult.stdout.trim();
  262. if (indexRelPath.length > 0) {
  263. const userIndexPath = resolve(resolution.repoRoot, indexRelPath);
  264. try {
  265. await copyFile(userIndexPath, tempIndexPath);
  266. primed = true;
  267. } catch {
  268. // 用户 index 不存在(刚 init 的空仓)或无权限,降级处理。
  269. }
  270. }
  271. }
  272. if (!primed) {
  273. // 没有可复制的 index 时,用 HEAD tree 填充临时 index,至少让已追踪文件走 hash-match 路径。
  274. // HEAD 不存在(全新仓库)时 read-tree 会失败,允许静默回落到空 index。
  275. const readTreeResult = await commandProvider.run({
  276. cwd: resolution.repoRoot,
  277. args: ["read-tree", "HEAD"],
  278. env,
  279. });
  280. if (readTreeResult.exitCode === 0) {
  281. primed = true;
  282. }
  283. }
  284. // 核心实现:用临时 GIT_INDEX_FILE 把当前 workspace 的 live 状态固化成隐藏 commit,
  285. // 这样既能复用 Git 的对象存储能力,又不会污染用户真实 index / staged 状态。
  286. const addResult = await commandProvider.run({
  287. cwd: resolution.repoRoot,
  288. args: ["add", "-A", "--", pathspec],
  289. env,
  290. });
  291. ensureGitCommandSucceeded("git add checkpoint", addResult);
  292. // 临时 index 已经收集了当前 workspace scope 的完整状态,下一步把它冻结成 tree object。
  293. const treeResult = await commandProvider.run({
  294. cwd: resolution.repoRoot,
  295. args: ["write-tree"],
  296. env,
  297. });
  298. ensureGitCommandSucceeded("git write-tree checkpoint", treeResult);
  299. // checkpoint 不需要进入用户 branch 历史,但 Git object 必须有一个稳定锚点。
  300. // 因此这里创建内部 commit,再由后续 hidden ref 指向它。
  301. const commitResult = await commandProvider.run({
  302. cwd: resolution.repoRoot,
  303. args: [
  304. "commit-tree",
  305. treeResult.stdout.trim(),
  306. "-m",
  307. `zcode checkpoint ${params.checkpointId}`,
  308. ],
  309. env,
  310. });
  311. ensureGitCommandSucceeded("git commit-tree checkpoint", commitResult);
  312. const commitOid = commitResult.stdout.trim();
  313. // hidden ref 是 checkpoint 的“长期引用”,它保证:
  314. // 1. Git 不会把这份对象当成垃圾直接回收
  315. // 2. 后续 diff / restore / delete 都能稳定按 refName 找回对应 commit
  316. const updateRefResult = await commandProvider.run({
  317. cwd: resolution.repoRoot,
  318. args: ["update-ref", refName, commitOid],
  319. });
  320. ensureGitCommandSucceeded("git update-ref checkpoint", updateRefResult);
  321. return {
  322. checkpointId: params.checkpointId,
  323. workspacePath: params.workspacePath,
  324. repoRoot: resolution.repoRoot,
  325. workspaceInRepoPath: resolution.workspaceInRepoPath,
  326. createdAt: Date.now(),
  327. refName,
  328. commitOid,
  329. scope: "workspace",
  330. };
  331. } finally {
  332. // 临时 index 只服务于本次 checkpoint 构建,结束后必须清掉,避免泄露到宿主环境。
  333. await rm(tempIndexDir, { recursive: true, force: true });
  334. }
  335. },
  336. /**
  337. * 比较两个 checkpoint 在当前 workspace scope 下的文件差异。
  338. *
  339. * 这个方法本身不感知 ZCode Agent/task/turn,只回答一个纯文件问题:
  340. * “从 fromCheckpoint 到 toCheckpoint,这个工作区范围内有哪些文件发生了什么变化?”
  341. *
  342. * 返回值会被 restore、后续摘要能力、甚至潜在的调试工具复用,所以这里保持纯读、无副作用。
  343. */
  344. async diffCheckpoints(params) {
  345. return await computeCheckpointDiff(params);
  346. },
  347. /**
  348. * 把当前 live workspace 从 fromCheckpoint 安全恢复到 toCheckpoint。
  349. *
  350. * 这是整个底座最核心的方法,它的语义不是“直接恢复到某个 checkpoint”,
  351. * 而是“三方比较”:
  352. * - 调用方声明:当前磁盘应当还停留在 fromCheckpoint
  353. * - 实际目标:希望把文件状态恢复到 toCheckpoint
  354. * - 当前现实:磁盘上可能已经被用户或其它流程继续改过
  355. *
  356. * 因此执行顺序是:
  357. * 1. 先算 from -> to 的受影响路径
  358. * 2. 再检查这些路径当前是否仍等于 fromCheckpoint
  359. * 3. 有冲突则返回,不直接覆盖
  360. * 4. 无冲突或 force=true 时,再把 toCheckpoint 的内容写回 worktree
  361. * 5. 最后再次校验,确保恢复后的真实磁盘已经等于 toCheckpoint
  362. */
  363. async restoreBetweenCheckpoints(params) {
  364. const resolution = await ensureRepository(params.workspacePath);
  365. const diff = await computeCheckpointDiff({
  366. workspacePath: params.workspacePath,
  367. from: params.from,
  368. to: params.to,
  369. });
  370. // diff 里既可能有当前路径,也可能有 rename 前的旧路径。
  371. // 这里统一折叠成最终受影响 path 集,后面的冲突检测和删除逻辑都按这份集合工作。
  372. const affectedRepoPaths = buildAffectedRepoPaths(diff.files).map((path) =>
  373. normalizeAffectedRepoPath(resolution.repoRoot, path),
  374. );
  375. if (affectedRepoPaths.length === 0) {
  376. return {
  377. success: true,
  378. restoredPaths: [],
  379. };
  380. }
  381. const conflicts = await collectWorkspaceConflicts({
  382. repoRoot: resolution.repoRoot,
  383. workspaceInRepoPath: resolution.workspaceInRepoPath,
  384. from: params.from,
  385. affectedRepoPaths,
  386. });
  387. if (conflicts.length > 0 && params.force !== true) {
  388. // 默认模式下,一旦发现相关路径已经偏离 fromCheckpoint,就拒绝写入。
  389. // 这样上层可以把冲突信息抛给用户,而不是底层偷偷覆盖掉他们的新修改。
  390. return {
  391. success: false,
  392. conflicts,
  393. };
  394. }
  395. const restoreRepoPaths = diff.files
  396. .filter((file) => file.kind !== "deleted")
  397. .map((file) => file.repoRelativePath);
  398. if (restoreRepoPaths.length > 0) {
  399. // restore 阶段只改 worktree,不改真实 index。这样回滚能力才是“文件状态恢复”,
  400. // 而不是偷偷改用户暂存区的破坏性操作。
  401. const restoreResult = await commandProvider.run({
  402. cwd: resolution.repoRoot,
  403. args: [
  404. "restore",
  405. `--source=${params.to.commitOid}`,
  406. "--worktree",
  407. "--",
  408. ...restoreRepoPaths,
  409. ],
  410. });
  411. ensureGitCommandSucceeded("git restore checkpoint", restoreResult);
  412. }
  413. const deleteAbsolutePaths = new Set<string>();
  414. for (const file of diff.files) {
  415. if (file.kind === "deleted") {
  416. // toCheckpoint 不再包含这些路径,restore 之后需要把 live worktree 里的残留实体删掉。
  417. deleteAbsolutePaths.add(file.path);
  418. continue;
  419. }
  420. if (file.kind === "renamed" && file.originalPath) {
  421. // rename 场景下,git restore 只会把新路径内容恢复出来;
  422. // 旧路径要由我们显式删除,避免“新旧文件并存”。
  423. deleteAbsolutePaths.add(file.originalPath);
  424. }
  425. }
  426. for (const path of deleteAbsolutePaths) {
  427. await removeFileIfExists(path);
  428. }
  429. const verifyConflicts = await collectWorkspaceConflicts({
  430. repoRoot: resolution.repoRoot,
  431. workspaceInRepoPath: resolution.workspaceInRepoPath,
  432. from: params.to,
  433. affectedRepoPaths,
  434. });
  435. if (verifyConflicts.length > 0) {
  436. // 这里理论上不应该再有偏差;如果还有,说明 restore 过程没有把磁盘真正带到目标状态,
  437. // 继续向上返回 success 只会把错误状态固化,因此直接抛错让调用方感知异常。
  438. throw new Error("Checkpoint restore verification failed.");
  439. }
  440. return {
  441. success: true,
  442. restoredPaths: diff.files.map((file) => file.path),
  443. };
  444. },
  445. /**
  446. * 删除一个 checkpoint 的 Git 引用。
  447. *
  448. * 这里只负责删除 hidden ref;manifest 的删除由上层 store/service 完成。
  449. * 这样 repo 层专注于 Git 对象引用管理,store 层专注于本地元数据文件管理,职责更清晰。
  450. */
  451. async deleteCheckpoint(params) {
  452. const resolution = await ensureRepository(params.workspacePath);
  453. const deleteRefResult = await commandProvider.run({
  454. cwd: resolution.repoRoot,
  455. args: ["update-ref", "-d", params.checkpoint.refName],
  456. });
  457. ensureGitCommandSucceeded("git update-ref -d checkpoint", deleteRefResult, [0, 1]);
  458. },
  459. };
  460. }
  461. export type { GitCheckpointRepo };