diff-rewind-files.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import { createHash } from 'node:crypto';
  2. import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
  3. import path from 'node:path';
  4. import { logger } from '../common/logger.js';
  5. import type {
  6. LocalTurnDiffRewindFilePlan,
  7. LocalTurnDiffSnapshotEntry,
  8. } from '../persistence/ports.js';
  9. export type LocalTurnDiffRewindPreflightErrorCode =
  10. | 'partial-turn'
  11. | 'not-undoable'
  12. | 'unsafe-path'
  13. | 'snapshot-incomplete'
  14. | 'chain-conflict'
  15. | 'workspace-conflict'
  16. | 'request-conflict';
  17. export class LocalTurnDiffRewindPreflightError extends Error {
  18. constructor(
  19. readonly code: LocalTurnDiffRewindPreflightErrorCode,
  20. message: string,
  21. ) {
  22. super(message);
  23. this.name = 'LocalTurnDiffRewindPreflightError';
  24. }
  25. }
  26. export type FileApplyResult =
  27. | { readonly status: 'applied'; readonly turnIds: readonly string[] }
  28. | {
  29. readonly status: 'skipped';
  30. readonly reason:
  31. | 'workspace-file-missing'
  32. | 'workspace-file-unexpected'
  33. | 'workspace-content-changed'
  34. | 'workspace-read-failed'
  35. | 'workspace-write-failed';
  36. readonly errorCode?: string;
  37. };
  38. export async function applyFileIfSafe(file: LocalTurnDiffRewindFilePlan): Promise<FileApplyResult> {
  39. let current: LocalTurnDiffSnapshotEntry;
  40. try {
  41. current = await snapshotFile(file);
  42. } catch (error) {
  43. return skippedFile('workspace-read-failed', error);
  44. }
  45. const conflict = workspaceConflictReason(current, file.expected);
  46. if (conflict) return { status: 'skipped', reason: conflict };
  47. try {
  48. await writeTarget(file);
  49. return { status: 'applied', turnIds: file.turnIds ?? [] };
  50. } catch (error) {
  51. return skippedFile('workspace-write-failed', error);
  52. }
  53. }
  54. export async function fileMatches(file: LocalTurnDiffRewindFilePlan): Promise<boolean> {
  55. try {
  56. return sameSnapshot(await snapshotFile(file), file.expected);
  57. } catch {
  58. return false;
  59. }
  60. }
  61. export function logSkippedFile(
  62. input: { readonly operationId: string; readonly sessionId: string },
  63. file: LocalTurnDiffRewindFilePlan,
  64. result: Extract<FileApplyResult, { readonly status: 'skipped' }>,
  65. ): void {
  66. logFileSkip({
  67. operationId: input.operationId,
  68. sessionId: input.sessionId,
  69. file: file.file,
  70. turnIds: file.turnIds ?? [],
  71. reason: result.reason,
  72. ...(result.errorCode ? { errorCode: result.errorCode } : {}),
  73. });
  74. }
  75. export function logFileSkip(fields: {
  76. readonly operationId: string;
  77. readonly sessionId: string;
  78. readonly file: string;
  79. readonly turnIds: readonly string[];
  80. readonly reason: string;
  81. readonly errorCode?: string;
  82. }): void {
  83. try {
  84. logger.warn(fields, 'Turn diff rewind file skipped');
  85. } catch {
  86. // Engineering logging is best-effort and cannot affect Rewind.
  87. }
  88. }
  89. export function planKey(plan: Pick<LocalTurnDiffRewindFilePlan, 'workspaceDir' | 'file'>): string {
  90. return `${path.resolve(plan.workspaceDir)}\0${plan.file}`;
  91. }
  92. export function requireSafeRelativePath(file: string): string {
  93. const portable = file.replaceAll('\\', '/');
  94. const segments = portable.split('/');
  95. if (
  96. !portable ||
  97. portable.includes('\0') ||
  98. path.isAbsolute(file) ||
  99. path.win32.isAbsolute(file) ||
  100. segments.some((segment) => !segment || segment === '.' || segment === '..')
  101. ) {
  102. preflightError('unsafe-path', `Unsafe Turn diff path: ${file}`);
  103. }
  104. return segments.join('/');
  105. }
  106. export function assertSnapshotComplete(
  107. snapshot: LocalTurnDiffSnapshotEntry,
  108. file: string,
  109. requireContent: boolean,
  110. ): void {
  111. if (snapshot.file !== file || snapshot.binary || snapshot.oversized) {
  112. preflightError('snapshot-incomplete', `Turn diff snapshot is incomplete: ${file}`);
  113. }
  114. if (
  115. snapshot.exists &&
  116. snapshot.content === undefined &&
  117. (requireContent || snapshot.hash === undefined)
  118. ) {
  119. preflightError('snapshot-incomplete', `Turn diff snapshot content is missing: ${file}`);
  120. }
  121. }
  122. export function sameSnapshot(
  123. left: LocalTurnDiffSnapshotEntry,
  124. right: LocalTurnDiffSnapshotEntry,
  125. ): boolean {
  126. if (left.exists !== right.exists) return false;
  127. if (!left.exists) return true;
  128. return snapshotDigest(left) === snapshotDigest(right);
  129. }
  130. function workspaceConflictReason(
  131. current: LocalTurnDiffSnapshotEntry,
  132. expected: LocalTurnDiffSnapshotEntry,
  133. ): Extract<FileApplyResult, { readonly status: 'skipped' }>['reason'] | undefined {
  134. if (current.exists !== expected.exists) {
  135. return current.exists ? 'workspace-file-unexpected' : 'workspace-file-missing';
  136. }
  137. if (!current.exists) return undefined;
  138. return snapshotDigest(current) === snapshotDigest(expected)
  139. ? undefined
  140. : 'workspace-content-changed';
  141. }
  142. function skippedFile(
  143. reason: Extract<FileApplyResult, { readonly status: 'skipped' }>['reason'],
  144. error: unknown,
  145. ): FileApplyResult {
  146. const errorCode = readErrorCode(error);
  147. return { status: 'skipped', reason, ...(errorCode ? { errorCode } : {}) };
  148. }
  149. async function writeTarget(file: LocalTurnDiffRewindFilePlan): Promise<void> {
  150. const target = resolvePlanPath(file);
  151. if (!file.target.exists) {
  152. await rm(target, { force: true });
  153. return;
  154. }
  155. if (file.target.content === undefined) {
  156. preflightError('snapshot-incomplete', `Turn diff target content is missing: ${file.file}`);
  157. }
  158. await mkdir(path.dirname(target), { recursive: true });
  159. await writeFile(target, file.target.content, 'utf8');
  160. }
  161. async function snapshotFile(
  162. plan: LocalTurnDiffRewindFilePlan,
  163. ): Promise<LocalTurnDiffSnapshotEntry> {
  164. const target = resolvePlanPath(plan);
  165. try {
  166. const content = await readFile(target);
  167. return {
  168. file: plan.file,
  169. exists: true,
  170. hash: createHash('sha256').update(content).digest('hex'),
  171. sizeBytes: content.byteLength,
  172. content: content.toString('utf8'),
  173. };
  174. } catch (error) {
  175. if (isMissing(error)) return { file: plan.file, exists: false };
  176. throw error;
  177. }
  178. }
  179. function resolvePlanPath(plan: LocalTurnDiffRewindFilePlan): string {
  180. const file = requireSafeRelativePath(plan.file);
  181. const root = path.resolve(plan.workspaceDir);
  182. const absolute = path.resolve(root, file);
  183. const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
  184. if (!absolute.startsWith(prefix)) preflightError('unsafe-path', `Unsafe Turn diff path: ${file}`);
  185. return absolute;
  186. }
  187. function snapshotDigest(snapshot: LocalTurnDiffSnapshotEntry): string | undefined {
  188. return (
  189. snapshot.hash ??
  190. (snapshot.content === undefined
  191. ? undefined
  192. : createHash('sha256').update(snapshot.content).digest('hex'))
  193. );
  194. }
  195. function preflightError(code: LocalTurnDiffRewindPreflightErrorCode, message: string): never {
  196. throw new LocalTurnDiffRewindPreflightError(code, message);
  197. }
  198. function isMissing(error: unknown): boolean {
  199. return isRecord(error) && error.code === 'ENOENT';
  200. }
  201. function readErrorCode(error: unknown): string | undefined {
  202. const code = isRecord(error) ? error.code : undefined;
  203. return typeof code === 'string' ? code : undefined;
  204. }
  205. function isRecord(value: unknown): value is Record<string, unknown> {
  206. return typeof value === 'object' && value !== null;
  207. }