snapshot.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. export * as Snapshot from "./snapshot"
  2. import path from "path"
  3. import { Context, Effect, Layer, Schema } from "effect"
  4. import { Config } from "./config"
  5. import { File } from "./file"
  6. import { FSUtil } from "./fs-util"
  7. import { Git } from "./git"
  8. import { Global } from "./global"
  9. import { Location } from "./location"
  10. import { AbsolutePath, RelativePath } from "./schema"
  11. import { Hash } from "./util/hash"
  12. export const ID = Schema.String.pipe(Schema.brand("Snapshot.ID"))
  13. export type ID = typeof ID.Type
  14. export class Error extends Schema.TaggedErrorClass<Error>()("Snapshot.Error", {
  15. operation: Schema.Literals(["capture", "files", "diff", "preview", "restore"]),
  16. message: Schema.String,
  17. cause: Schema.optional(Schema.Defect()),
  18. }) {}
  19. export interface CompareInput {
  20. readonly from: ID
  21. readonly to: ID
  22. }
  23. export interface DiffInput extends CompareInput {
  24. readonly context?: number
  25. readonly paths?: readonly RelativePath[]
  26. }
  27. export interface RestoreInput {
  28. /** Paths are relative to the project root. */
  29. readonly files: ReadonlyMap<RelativePath, ID>
  30. }
  31. export interface PreviewInput extends RestoreInput {
  32. readonly context?: number
  33. }
  34. export interface Interface {
  35. /**
  36. * Capture the current Location-scoped filesystem state as a content-addressed
  37. * tree. Returns `undefined` when snapshots are disabled, unsupported, or the
  38. * best-effort capture fails.
  39. */
  40. readonly capture: () => Effect.Effect<ID | undefined>
  41. /**
  42. * List project-relative paths changed between two captured trees without
  43. * loading file contents or generating patches.
  44. */
  45. readonly files: (input: CompareInput) => Effect.Effect<readonly RelativePath[], Error>
  46. /**
  47. * Generate structured per-file diffs between two captured trees. `context`
  48. * controls unchanged lines around each unified diff hunk.
  49. */
  50. readonly diff: (input: DiffInput) => Effect.Effect<readonly File.Diff[], Error>
  51. /**
  52. * Preview the filesystem result of a selective restore without modifying the
  53. * worktree. Each project-relative path maps to the tree it would be restored
  54. * from.
  55. */
  56. readonly preview: (input: PreviewInput) => Effect.Effect<readonly File.Diff[], Error>
  57. /**
  58. * Restore selected project-relative paths from their associated trees. A path
  59. * absent from its selected tree is removed; paths outside the map are untouched.
  60. */
  61. readonly restore: (input: RestoreInput) => Effect.Effect<void, Error>
  62. /**
  63. * Replace the snapshot index with a captured tree and check out all its entries.
  64. * Files absent from the tree remain untouched. Prefer selective `restore` when
  65. * only known paths should change.
  66. */
  67. readonly checkout: (snapshot: ID) => Effect.Effect<void, Error>
  68. }
  69. export class Service extends Context.Service<Service, Interface>()("@opencode/v2/Snapshot") {}
  70. export const layer = Layer.effect(
  71. Service,
  72. Effect.gen(function* () {
  73. const config = yield* Config.Service
  74. const fs = yield* FSUtil.Service
  75. const git = yield* Git.Service
  76. const global = yield* Global.Service
  77. const location = yield* Location.Service
  78. const source = yield* git.repo.discover(location.project.directory)
  79. const worktree = source
  80. ? AbsolutePath.make(yield* fs.realPath(source.worktree).pipe(Effect.orDie))
  81. : location.project.directory
  82. const gitDirectory = AbsolutePath.make(path.join(global.data, "snapshot", location.project.id, Hash.fast(worktree)))
  83. const scope = Effect.fnUntraced(function* () {
  84. const relative = path.relative(worktree, location.directory)
  85. if (relative.startsWith("..") || path.isAbsolute(relative))
  86. return yield* new Error({ operation: "capture", message: "Location is outside the project" })
  87. return RelativePath.make(relative.replaceAll("\\", "/") || ".")
  88. })
  89. const repository = Effect.fnUntraced(function* () {
  90. if (!source) return yield* new Error({ operation: "capture", message: "Project is not a Git repository" })
  91. if (yield* fs.existsSafe(path.join(gitDirectory, "HEAD")))
  92. return new Git.Repository({
  93. worktree,
  94. gitDirectory,
  95. commonDirectory: gitDirectory,
  96. })
  97. return yield* git.repo
  98. .create({
  99. worktree,
  100. gitDirectory,
  101. seed: source,
  102. })
  103. .pipe(Effect.mapError((cause) => failure("capture", cause)))
  104. })
  105. const enabled = Effect.fnUntraced(function* () {
  106. if (location.vcs?.type !== "git") return false
  107. return Config.latest(yield* config.entries(), "snapshots") !== false
  108. })
  109. const capture = Effect.fn("Snapshot.capture")(function* () {
  110. if (!(yield* enabled())) return undefined
  111. return yield* Effect.gen(function* () {
  112. const repo = yield* repository()
  113. return ID.make(
  114. yield* git.tree.capture({
  115. repository: repo,
  116. scopes: [yield* scope()],
  117. ignores: source,
  118. maximumUntrackedFileBytes: 2 * 1024 * 1024,
  119. }),
  120. )
  121. }).pipe(
  122. Effect.catch((cause) => Effect.logWarning("failed to capture snapshot", { cause }).pipe(Effect.as(undefined))),
  123. )
  124. })
  125. const compare = Effect.fnUntraced(function* (operation: "files" | "diff", input: CompareInput) {
  126. const repo = yield* repository().pipe(Effect.mapError((cause) => failure(operation, cause)))
  127. return { repository: repo, from: Git.TreeID.make(input.from), to: Git.TreeID.make(input.to) }
  128. })
  129. const files = Effect.fn("Snapshot.files")(function* (input: CompareInput) {
  130. const comparison = yield* compare("files", input)
  131. const files = yield* git.tree.files(comparison).pipe(Effect.mapError((cause) => failure("files", cause)))
  132. if (!source) return files
  133. const ignored = yield* git.index
  134. .ignored({ repository: source, paths: files })
  135. .pipe(Effect.mapError((cause) => failure("files", cause)))
  136. return files.filter((file) => !ignored.has(file))
  137. })
  138. const diff = Effect.fn("Snapshot.diff")(function* (input: DiffInput) {
  139. const comparison = yield* compare("diff", input)
  140. const files = yield* git.tree.files(comparison).pipe(Effect.mapError((cause) => failure("diff", cause)))
  141. const ignored = source
  142. ? yield* git.index
  143. .ignored({ repository: source, paths: files })
  144. .pipe(Effect.mapError((cause) => failure("diff", cause)))
  145. : new Set<RelativePath>()
  146. return yield* git.tree
  147. .diff({
  148. ...comparison,
  149. context: input.context,
  150. paths: (input.paths ?? files).filter((file) => !ignored.has(file)),
  151. })
  152. .pipe(Effect.mapError((cause) => failure("diff", cause)))
  153. })
  154. const plan = Effect.fnUntraced(function* (operation: "preview" | "restore", input: RestoreInput) {
  155. const files = new Map<RelativePath, Git.TreeID>()
  156. for (const [file, snapshot] of input.files) {
  157. const absolute = path.resolve(worktree, file)
  158. if (!FSUtil.contains(worktree, absolute))
  159. return yield* new Error({ operation, message: `Path escapes the project: ${file}` })
  160. files.set(file, Git.TreeID.make(snapshot))
  161. }
  162. return files
  163. })
  164. const preview = Effect.fn("Snapshot.preview")(function* (input: PreviewInput) {
  165. if (!(yield* enabled())) return yield* new Error({ operation: "preview", message: "Snapshots are disabled" })
  166. const repo = yield* repository().pipe(Effect.mapError((cause) => failure("preview", cause)))
  167. const files = yield* plan("preview", input)
  168. const current = yield* git.tree
  169. .capture({
  170. repository: repo,
  171. scopes: Array.from(files.keys()),
  172. ignores: source,
  173. maximumUntrackedFileBytes: 2 * 1024 * 1024,
  174. })
  175. .pipe(Effect.mapError((cause) => failure("preview", cause)))
  176. return yield* git.tree
  177. .preview({
  178. repository: repo,
  179. current,
  180. files,
  181. context: input.context,
  182. })
  183. .pipe(Effect.mapError((cause) => failure("preview", cause)))
  184. })
  185. const restore = Effect.fn("Snapshot.restore")(function* (input: RestoreInput) {
  186. if (!(yield* enabled())) return yield* new Error({ operation: "restore", message: "Snapshots are disabled" })
  187. const repo = yield* repository().pipe(Effect.mapError((cause) => failure("restore", cause)))
  188. yield* git.tree
  189. .restore({ repository: repo, files: yield* plan("restore", input) })
  190. .pipe(Effect.mapError((cause) => failure("restore", cause)))
  191. })
  192. const checkout = Effect.fn("Snapshot.checkout")(function* (snapshot: ID) {
  193. const repo = yield* repository().pipe(Effect.mapError((cause) => failure("restore", cause)))
  194. yield* git.tree
  195. .checkout({ repository: repo, tree: Git.TreeID.make(snapshot) })
  196. .pipe(Effect.mapError((cause) => failure("restore", cause)))
  197. })
  198. return Service.of({ capture, files, diff, preview, restore, checkout })
  199. }),
  200. )
  201. export const locationLayer = layer.pipe(Layer.provideMerge(Config.locationLayer))
  202. export const noopLayer = Layer.succeed(
  203. Service,
  204. Service.of({
  205. capture: () => Effect.succeed(undefined),
  206. files: () => Effect.succeed([]),
  207. diff: () => Effect.succeed([]),
  208. preview: () => Effect.succeed([]),
  209. restore: () => Effect.void,
  210. checkout: () => Effect.void,
  211. }),
  212. )
  213. function failure(operation: Error["operation"], cause: unknown) {
  214. if (cause instanceof Error && cause.operation === operation) return cause
  215. return new Error({
  216. operation,
  217. message: cause instanceof globalThis.Error ? cause.message : String(cause),
  218. cause,
  219. })
  220. }
  221. /** Legacy persisted session diff shape. */
  222. export type LegacyFileDiff = {
  223. file?: string
  224. patch?: string
  225. additions: number
  226. deletions: number
  227. status?: "added" | "deleted" | "modified"
  228. }