Skip to content

Write HTML. Render video. Built for agents.

135 KB
Raw Blame
// fallow-ignore-file code-duplication
// executeGsapMutationRecast and executeGsapMutationAcorn are intentionally
// parallel — two writers, same switch-case interface. Structural duplication
// is load-bearing (both paths must remain testable in isolation).
import type { Hono } from "hono";
import { encodeUrlPath, decodedUrlPath, decodeCssEscapes } from "@hyperframes/parsers/asset-paths";
import {
  scanHtmlOpeningTags,
  decodeAuthoredAttribute,
  HTML_ATTRIBUTE_ENTITIES,
} from "@hyperframes/parsers";
import { bodyLimit } from "hono/body-limit";
import {
  closeSync,
  existsSync,
  lstatSync,
  openSync,
  readFileSync,
  readlinkSync,
  unlinkSync,
  rmSync,
  statSync,
  fstatSync,
  renameSync,
  readdirSync,
  realpathSync,
  type Dirent,
} from "node:fs";
import { resolve, dirname, join, sep } from "node:path";
import type { StudioApiAdapter } from "../types.js";
import { isAudioFile } from "../helpers/mime.js";
import { lengthIsTimeline } from "../helpers/compositionInputs.js";
import { createFileAtomically, replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { generateWaveformCache } from "../helpers/waveform.js";
import { validateUploadedMediaBuffer } from "../helpers/mediaValidation.js";
import {
  folderGone,
  isInHiddenOrVendorDir,
  isPrivateProjectFile,
  isSafePath,
  mkdirWithinProject,
  pinWithinProject,
  resolveWithinProject,
  walkDir,
} from "../helpers/safePath.js";
import { backupPathForResponse, snapshotBeforeWrite } from "../helpers/backupJournal.js";
import { projectDirMissing } from "../helpers/projectDirMissing.js";
import {
  createWriteToken,
  fileContentVersion,
  recordFileWriteReceipt,
} from "../helpers/fileVersion.js";
import { applyFileMutations, FileChangedError } from "../helpers/applyFileMutations.js";
import {
  findUnsafeDomPatchValues,
  findUnsafeMutationValues,
  type UnsafeMutationValue,
} from "../helpers/finiteMutation.js";
import type { GsapAnimation } from "@hyperframes/parsers";
import { classifyPropertyGroup } from "@hyperframes/parsers/gsap-constants";
import { findTimelineScript, parseGsapScriptAcorn } from "@hyperframes/parsers/gsap-parser-acorn";
import { unrollComputedTimeline } from "@hyperframes/parsers";
import {
  updateAnimationInScript,
  addAnimationToScript,
  removeAnimationFromScript,
  addKeyframeToScript,
  removeKeyframeFromScript,
  moveKeyframeInScript,
  resizeKeyframedTweenInScript,
  updateKeyframeInScript,
  convertToKeyframesFromScript,
  removeAllKeyframesFromScript,
  materializeKeyframesFromScript,
  unrollDynamicAnimations,
  setArcPathInScript,
  updateArcSegmentInScript,
  updateMotionPathPointInScript,
  addMotionPathPointInScript,
  removeMotionPathPointInScript,
  addMotionPathToScript,
  removeArcPathFromScript,
  addAnimationWithKeyframesToScript,
  replaceTweenWithKeyframesInScript,
  splitAnimationsInScript,
  splitIntoPropertyGroupsFromScript,
  retimeClipTweensInScript,
  type ClipTweenRetime,
  dedupePositionWritesInScript,
  syncPositionHoldsBeforeKeyframes,
  trimTrailingKeyframeSpans,
  clipQueryRoot,
} from "@hyperframes/parsers/gsap-writer-acorn";
import {
  removeElementFromHtml,
  removeElementsFromHtml,
  patchElementInHtml,
  probeElementInSource,
  probeElementsInSource,
  splitElementInHtml,
  relinkSplitHalvesInHtml,
  wrapElementsInHtml,
  unwrapElementsFromHtml,
  isHTMLElement,
  type PatchOperation,
  type ElementRebase,
} from "../helpers/sourceMutation.js";
import { ensureStudioFontFaceCss, isStudioFontFaceCss } from "../helpers/studioFontFace.js";
import { parseHTML } from "linkedom";
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
import {
  CompositionInsertionError,
  insertCompositionIntoSource,
} from "../helpers/compositionInsertion.js";
import { resolveGsapWriter } from "./gsapMutationCapabilities.js";
import { decodeWellFormedEscapes, requestSubPath } from "../helpers/requestSubPath.js";
import {
  hasCompositionOutsideTemplates,
  insertBeforeCloseTag,
} from "@hyperframes/core/compiler/html-document";

// ── Server cutover flag ─────────────────────────────────────────────────────

/**
 * Writer selection is deliberately independent from the Studio SDK cutover.
 * Recast remains the default until the capability report has no parity blockers.
 */
/**
 * Lazy-load gsapParser for write ops (recast-backed) — the default server writer.
 * The read path uses the browser-safe acorn parser; this loader is only needed
 * for the recast write path (the default until the migration gate graduates).
 */
async function loadGsapParser() {
  return import("@hyperframes/parsers/gsap-parser-recast");
}

// ── Shared helpers ──────────────────────────────────────────────────────────

/**
 * Resolve the project and file path from the request, validating safety.
 * Returns null (and sends an error response) if anything is invalid.
 */
interface RouteContext {
  req: {
    param: (name: string) => string;
    url: string;
    query: (name: string) => string | undefined;
    header: (name: string) => string | undefined;
  };
  header: (name: string, value: string) => void;
  json: (data: unknown, status?: number) => Response;
}

interface ResolvedGsapFile {
  project: { dir: string };
  filePath: string;
  absPath: string;
}

/**
 * True only for a symlink that itself lives inside the project, whose target
 * (once resolved against the link's own directory) also names a location
 * inside the project, and does not exist anywhere — not for one that exists
 * (that stays a real containment failure) and not for a plain missing path
 * (the ordinary case `resolveWithinProject` already covers).
 *
 * Both containment checks matter, not just the second: a request can name a
 * path lexically *outside* the project (reached via `..`) that happens to be
 * a dangling symlink out there, or a real in-project symlink that points
 * *outside* the project at a target that may or may not exist. Labeling
 * either of those "not found" would leak, to anyone who can hit the route,
 * whether an out-of-project path exists — the containment check exists
 * precisely so that answer never depends on what's outside the project.
 * `isSafePath` fails closed on a dangling in-project symlink by design (a
 * write through it could later resolve outside the project once something
 * creates the target) — this does not loosen that; it only tells the caller
 * *why* the containment check refused, so the response can say "not found"
 * instead of a path-traversal-shaped "forbidden" for a case that scans as
 * broken plumbing, not an attack.
 */
function isDanglingSymlinkInProject(projectDir: string, lexicalPath: string): boolean {
  if (!isSafePath(projectDir, dirname(lexicalPath))) return false;
  let stats;
  try {
    stats = lstatSync(lexicalPath);
  } catch {
    return false;
  }
  if (!stats.isSymbolicLink()) return false;
  const target = resolve(dirname(lexicalPath), readlinkSync(lexicalPath));
  if (!isSafePath(projectDir, target)) return false;
  try {
    statSync(lexicalPath);
    return false;
  } catch {
    return true;
  }
}

/** Resolve project + safe absolute path for any project-scoped route. */
async function resolveProjectPath(
  c: RouteContext,
  adapter: StudioApiAdapter,
  route: string,
  opts?: { mustExist?: boolean; pin?: boolean },
) {
  const id = c.req.param("id");
  const project = await adapter.resolveProject(id);
  if (!project) {
    return { error: c.json({ error: "not found" }, 404) } as const;
  }

  // The CLI host's `resolveProject` is static (`id === projectId ? project : null`),
  // so it keeps answering with this project even after its folder is renamed
  // or deleted out from under a running `preview` — mount-time validation
  // (`/api/projects/:id`) still passes, so nothing upstream catches this.
  // Every subsequent read then failed closed inside `isSafePath` (its
  // `realpathSync(base)` throws when the base itself is gone) and reported as
  // `403 forbidden` — indistinguishable from a real path-traversal attempt.
  // Checked here, once, so every route built on this shares the fix.
  if (folderGone(project.dir)) {
    return { error: projectDirMissing(c) } as const;
  }

  const filePath = requestSubPath(c.req.url, `projects/:id/${route}`);
  if (filePath.includes("\0")) {
    return { error: c.json({ error: "forbidden", why: "nul" }, 403) } as const;
  }

  // An edit pins its target; create-only writes use `wx`, and a delete or rename acts on a link itself.
  const absPath = (opts?.pin ? pinWithinProject : resolveWithinProject)(project.dir, filePath);
  if (!absPath) {
    if (isDanglingSymlinkInProject(project.dir, resolve(project.dir, filePath))) {
      return { error: c.json({ error: "not found", why: "dangling_symlink" }, 404) } as const;
    }
    return { error: c.json({ error: "forbidden", why: "outside_project" }, 403) } as const;
  }

  if (opts?.mustExist && !existsSync(absPath)) {
    return { error: c.json({ error: "not found" }, 404) } as const;
  }

  return { project, filePath, absPath } as const;
}

function resolveProjectFile(
  c: RouteContext,
  adapter: StudioApiAdapter,
  opts?: { mustExist?: boolean; pin?: boolean },
) {
  return resolveProjectPath(c, adapter, "files", opts);
}

function resolveFileMutationContext(c: RouteContext, adapter: StudioApiAdapter, operation: string) {
  return resolveProjectPath(c, adapter, `file-mutations/${operation}`, { pin: true });
}

type MutationTarget = {
  id?: string | null;
  hfId?: string;
  selector?: string;
  selectorIndex?: number;
};

interface ElementPatchRequest {
  target: MutationTarget;
  operations: PatchOperation[];
}

interface ElementPatchBatchRequest {
  sourceFile: string;
  patches: ElementPatchRequest[];
}

interface ElementPatchBatchFileResult {
  sourceFile: string;
  changed: boolean;
  matched: boolean[];
  before: string;
  after: string;
  backupPath?: string | null;
}

interface AtomicCutTarget {
  target: MutationTarget;
  originalId?: string;
  splitTime: number;
  elementStart: number;
  elementDuration: number;
  playbackStart?: number;
  playbackRate?: number;
  track?: number;
}

interface AtomicCutFileRequest {
  path: string;
  expectedVersion: string;
  targets: AtomicCutTarget[];
}

function isOptionalInteger(value: unknown): value is number | undefined {
  return value === undefined || Number.isInteger(value);
}

function isAtomicCutTarget(value: unknown): value is AtomicCutTarget {
  if (!value || typeof value !== "object") return false;
  const target = value as Partial<AtomicCutTarget>;
  return (
    !!target.target &&
    typeof target.target === "object" &&
    Number.isFinite(target.splitTime) &&
    Number.isFinite(target.elementStart) &&
    Number.isFinite(target.elementDuration) &&
    Number(target.elementDuration) > 0 &&
    isOptionalInteger(target.track)
  );
}

function isAtomicCutFileRequest(value: unknown): value is AtomicCutFileRequest {
  if (!value || typeof value !== "object") return false;
  const file = value as Partial<AtomicCutFileRequest>;
  return (
    typeof file.path === "string" &&
    file.path.length > 0 &&
    typeof file.expectedVersion === "string" &&
    Array.isArray(file.targets) &&
    file.targets.length > 0 &&
    file.targets.every(isAtomicCutTarget)
  );
}

let atomicCutTail: Promise<unknown> = Promise.resolve();

/** Serialize cut actions so a rapid second gesture observes the first one's bytes. */
function serializeAtomicCut<T>(task: () => Promise<T>): Promise<T> {
  const next = atomicCutTail.then(task, task);
  atomicCutTail = next.then(
    () => undefined,
    () => undefined,
  );
  return next;
}

function isElementPatchRequest(value: unknown): value is ElementPatchRequest {
  if (typeof value !== "object" || value === null) return false;
  if (!("target" in value) || typeof value.target !== "object" || value.target === null) {
    return false;
  }
  return "operations" in value && Array.isArray(value.operations) && value.operations.length > 0;
}

function isElementPatchBatchRequest(value: unknown): value is ElementPatchBatchRequest {
  return (
    typeof value === "object" &&
    value !== null &&
    "sourceFile" in value &&
    typeof value.sourceFile === "string" &&
    value.sourceFile.length > 0 &&
    "patches" in value &&
    Array.isArray(value.patches) &&
    value.patches.length > 0 &&
    value.patches.every(isElementPatchRequest)
  );
}

function findUnsafeElementPatchBatchValues(
  batches: readonly ElementPatchBatchRequest[],
): UnsafeMutationValue[] {
  return batches.flatMap((batch) =>
    batch.patches.flatMap((patch) => findUnsafeDomPatchValues(patch)),
  );
}

function foldElementPatches(
  originalContent: string,
  patches: ElementPatchRequest[],
): { content: string; matched: boolean[] } {
  let content = originalContent;
  const matched: boolean[] = [];
  for (const patch of patches) {
    const result = patchElementInHtml(content, patch.target, patch.operations);
    content = result.html;
    matched.push(result.matched);
  }
  return { content, matched };
}

const PATCH_CONFLICT_ATTEMPTS = 3;

const ID_ATTRIBUTE = /[\s"'/]id\s*=\s*(?=(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))/gi;

/** Every id in the project's HTML files: sub-compositions share one preview document. */
function projectHtmlIds(projectDir: string): Set<string> {
  const ids = new Set<string>();
  for (const rel of walkDir(projectDir)) {
    if (!rel.endsWith(".html") || isInHiddenOrVendorDir(rel)) continue;
    let html: string;
    try {
      html = readFileSync(join(projectDir, rel), "utf-8");
    } catch {
      continue;
    }
    for (const m of html.matchAll(ID_ATTRIBUTE)) ids.add(m[1] ?? m[2] ?? m[3] ?? "");
  }
  return ids;
}

type ElementPatchCommitResult =
  | { error: "duplicate" | "forbidden" | "not-found" | "conflict"; sourceFile: string }
  | { durable: boolean; files: ElementPatchBatchFileResult[] };

/**
 * The single commit owner for element patch batches. All files are resolved,
 * read, and folded before the first write; any unmatched target refuses the
 * whole request, and a write from elsewhere mid-fold refolds before it answers 409.
 * Studio Server is single-process; within it the final snapshots/writes are
 * synchronous, so another route cannot interleave once the commit begins. A
 * multi-process deployment needs a shared per-project file lock instead.
 */
export function commitElementPatchBatches(
  projectDir: string,
  batches: ElementPatchBatchRequest[],
  writeFile: (path: string, content: string, encoding: "utf-8") => void = (path, content) =>
    replaceFileAtomically(path, content, statSync(path).mode),
  requestToken?: string,
): ElementPatchCommitResult {
  for (let attempt = 1; ; attempt += 1) {
    try {
      return foldAndCommitElementPatchBatches(projectDir, batches, writeFile, requestToken);
    } catch (error) {
      if (!(error instanceof FileChangedError)) throw error;
      if (attempt === PATCH_CONFLICT_ATTEMPTS)
        return { error: "conflict", sourceFile: error.sourceFile };
    }
  }
}

function foldAndCommitElementPatchBatches(
  projectDir: string,
  batches: ElementPatchBatchRequest[],
  writeFile: (path: string, content: string, encoding: "utf-8") => void,
  requestToken: string | undefined,
): ElementPatchCommitResult {
  const resolvedPaths = new Set<string>();
  const prepared: Array<{
    sourceFile: string;
    absPath: string;
    before: string;
    matched: boolean[];
    after: string;
  }> = [];

  for (const batch of batches) {
    const absPath = pinWithinProject(projectDir, batch.sourceFile);
    if (!absPath) return { error: "forbidden", sourceFile: batch.sourceFile };
    if (resolvedPaths.has(absPath)) return { error: "duplicate", sourceFile: batch.sourceFile };
    resolvedPaths.add(absPath);

    let before: string;
    try {
      before = readFileSync(absPath, "utf-8");
    } catch {
      return { error: "not-found", sourceFile: batch.sourceFile };
    }
    const folded = foldElementPatches(before, batch.patches);
    prepared.push({
      sourceFile: batch.sourceFile,
      absPath,
      before,
      matched: folded.matched,
      after: folded.content,
    });
  }

  const durable = prepared.every((file) => file.matched.every(Boolean));
  if (!durable) {
    return {
      durable: false,
      files: prepared.map((file) => ({
        sourceFile: file.sourceFile,
        changed: false,
        matched: file.matched,
        before: file.before,
        after: file.before,
      })),
    };
  }

  const applied = applyFileMutations(
    projectDir,
    prepared.map(({ sourceFile, absPath, before, after }) => ({
      sourceFile,
      absPath,
      before,
      after,
    })),
    requestToken,
    writeFile,
  );
  const files: ElementPatchBatchFileResult[] = applied.map((file, index) => ({
    sourceFile: file.sourceFile,
    changed: file.changed,
    matched: prepared[index]?.matched ?? [],
    before: file.before,
    after: file.after,
    backupPath: file.backupPath ?? undefined,
  }));
  return { durable: true, files };
}

function commitElementPatchBatchesWithReceipts(
  c: RouteContext,
  projectDir: string,
  batches: ElementPatchBatchRequest[],
): ReturnType<typeof commitElementPatchBatches> {
  return commitElementPatchBatches(
    projectDir,
    batches,
    undefined,
    c.req.header("X-Hyperframes-Write-Token"),
  );
}

/**
 * Record the receipt that claims a mutation result.
 *
 * The file watcher broadcasts every write, including the ones Studio itself just
 * asked for. The receipt is what lets the client tell its own echo from an agent
 * or an editor writing the file behind its back: without one, the client treats
 * its own edit as an external change and does a full preview reload, which blanks
 * the stage for a few hundred milliseconds right after the user typed. Every
 * mutation route records through here so no route can forget.
 */
function writeFileWithReceipt(
  c: RouteContext,
  filePath: string,
  absPath: string,
  html: string,
): { version: string; writeToken: string } {
  const overwrote = readFileSync(absPath);
  replaceFileAtomically(absPath, html, statSync(absPath).mode);
  // The synchronous write cannot yield before its receipt is recorded; keep this block await-free.
  const version = fileContentVersion(html);
  const writeToken = createWriteToken(c.req.header("X-Hyperframes-Write-Token"));
  recordFileWriteReceipt(absPath, { path: filePath, version, writeToken, overwrote });
  return { version, writeToken };
}

function writeMutationResult(
  c: RouteContext,
  projectDir: string,
  filePath: string,
  absPath: string,
  html: string,
  original: string,
): { backupPath: string | null; version: string } | Response {
  const backup = snapshotBeforeWrite(projectDir, absPath);
  if (backup.error) return c.json({ error: `backup failed: ${backup.error}` }, 500);
  if (readFileSync(absPath, "utf-8") !== original) {
    return c.json({ error: "file changed", conflict: true, path: filePath }, 409);
  }
  const { version } = writeFileWithReceipt(c, filePath, absPath, html);
  return { backupPath: backupPathForResponse(projectDir, backup.backupPath), version };
}

/** Write `next` to `absPath` only if it differs from `original`, returning a standardized change response. */
function writeIfChanged(
  c: RouteContext,
  projectDir: string,
  filePath: string,
  absPath: string,
  original: string,
  next: string,
): Response {
  if (next === original) {
    return c.json({ ok: true, changed: false, content: original, path: filePath });
  }
  const mutationResult = writeMutationResult(c, projectDir, filePath, absPath, next, original);
  if (mutationResult instanceof Response) return mutationResult;
  const { backupPath } = mutationResult;
  return c.json({
    ok: true,
    changed: true,
    content: next,
    path: filePath,
    backupPath,
  });
}

function rejectUnsafeMutationValues(
  c: RouteContext,
  unsafeFields: UnsafeMutationValue[],
): Response {
  return c.json(
    {
      error: "mutation contains unsafe values",
      fields: unsafeFields.map((field) => field.path),
      unsafeValues: unsafeFields,
    },
    400,
  );
}

function elementPatchBatchCommitErrorResponse(
  c: RouteContext,
  error: Extract<ElementPatchCommitResult, { error: unknown }>["error"],
  sourceFile: string,
): Response {
  if (error === "conflict")
    return c.json({ error: "file changed", conflict: true, sourceFile }, 409);
  if (error === "not-found") return c.json({ error, sourceFile }, 404);
  if (error === "forbidden") return c.json({ error, sourceFile }, 403);
  return c.json({ error: "duplicate source file", sourceFile }, 400);
}

/**
 * Parse the request body and validate that `target` is present.
 * Returns `{ error }` if missing, or `{ target, body }` for the full parsed body.
 */
async function parseMutationBody<T extends { target?: MutationTarget }>(
  c: RouteContext & { req: { json(): Promise<unknown> } },
): Promise<{ error: Response } | { target: MutationTarget; body: T }> {
  const body = (await (c.req as { json(): Promise<unknown> }).json().catch(() => null)) as T | null;
  if (!body?.target) {
    return { error: c.json({ error: "target required" }, 400) };
  }
  return { target: body.target, body };
}

/** Ensure the parent directory of a path exists, never recreating a project folder that is gone. */
function ensureDir(projectDir: string, filePath: string) {
  mkdirWithinProject(projectDir, dirname(filePath));
}

/**
 * Generate a copy name: foo.html → foo (copy).html → foo (copy 2).html
 */
function generateCopyPath(projectDir: string, originalPath: string): string {
  const ext = originalPath.includes(".") ? "." + originalPath.split(".").pop() : "";
  const base = ext ? originalPath.slice(0, -ext.length) : originalPath;

  // If already a copy, increment the number
  const copyMatch = base.match(/ \(copy(?: (\d+))?\)$/);
  const cleanBase = copyMatch ? base.slice(0, -copyMatch[0].length) : base;
  let num = copyMatch ? (copyMatch[1] ? parseInt(copyMatch[1]) + 1 : 2) : 1;

  let candidate = num === 1 ? `${cleanBase} (copy)${ext}` : `${cleanBase} (copy ${num})${ext}`;
  while (existsSync(resolve(projectDir, candidate))) {
    num++;
    candidate = `${cleanBase} (copy ${num})${ext}`;
  }

  return candidate;
}

/**
 * Walk a directory recursively and return all file paths matching a filter.
 */
function walkFiles(dir: string, filter: (name: string) => boolean): string[] {
  const results: string[] = [];
  for (const entry of readableEntries(dir)) {
    const full = join(dir, entry.name);
    if (entry.isDirectory()) {
      if (
        entry.name === "node_modules" ||
        entry.name === ".thumbnails" ||
        entry.name === "renders" ||
        entry.name === ".transcode-cache"
      )
        continue;
      results.push(...walkFiles(full, filter));
    } else if (filter(entry.name)) {
      results.push(full);
    }
  }
  return results;
}

const SKIPPED_ENTRY = new Set(["EACCES", "EPERM", "ENOENT"]);

function skippable(error: unknown): boolean {
  return error instanceof Error && SKIPPED_ENTRY.has((error as NodeJS.ErrnoException).code ?? "");
}

function readableEntries(dir: string): Dirent[] {
  try {
    return readdirSync(dir, { withFileTypes: true });
  } catch (error) {
    if (skippable(error)) return [];
    throw error;
  }
}

function readableText(file: string): string | null {
  try {
    return readFileSync(file, "utf-8");
  } catch (error) {
    if (skippable(error)) return null;
    throw error;
  }
}

const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

const SEPARATOR = String.raw`\\{0,2}[\\/]`;
const REFERENCE_START = String.raw`(?<![\w./\\+-])`;
const FILE_END = String.raw`(?![\w-]|\.\w)`;

const ENTITY_SPELLINGS = HTML_ATTRIBUTE_ENTITIES;

function referenceSpellings(char: string): string {
  const spellings = [escapeRegExp(char)];
  const encoded = encodeUrlPath(char);
  if (encoded !== char)
    spellings.push(encoded.replace(/[A-F]/g, (hex) => `[${hex}${hex.toLowerCase()}]`));
  if (ENTITY_SPELLINGS[char]) spellings.push(...ENTITY_SPELLINGS[char]);
  if (["'", '"', "`", "$", " ", "(", ")"].includes(char)) {
    spellings.push(escapeRegExp(`&#92;${char}`), escapeRegExp(`&#92;${escapeHtmlReference(char)}`));
  }
  const scriptSpelling = escapeQuotedReference(char, '"');
  if (scriptSpelling !== char) spellings.push(escapeRegExp(scriptSpelling));
  if (["'", "`", "$", " ", "(", ")"].includes(char)) spellings.push(escapeRegExp(`\\${char}`));
  if (/[\t\n\f\r =<>`]/.test(char)) spellings.push(`&#${char.codePointAt(0)!};`);
  if (char.charCodeAt(0) < 0x20 || char.charCodeAt(0) === 0x7f) {
    spellings.push(escapeRegExp(`\\${char.charCodeAt(0).toString(16)} `));
  }
  return spellings.length === 1 ? spellings[0]! : `(?:${spellings.join("|")})`;
}

type ReferenceSyntax = "html" | "script" | "css" | "plain";
interface ReferenceContext {
  syntax: ReferenceSyntax;
  url: boolean;
  htmlAttribute: boolean;
  encodeAll: boolean;
  quote: string;
}

function escapeHtmlReference(path: string): string {
  return path.replace(/[&"']/g, (char) => ENTITY_SPELLINGS[char]![0]!);
}

function escapeQuotedReference(path: string, quote: string): string {
  const escaped = JSON.stringify(path).slice(1, -1);
  return quote === '"'
    ? escaped
    : escaped.replace(new RegExp(escapeRegExp(quote), "g"), `\\${quote}`);
}

function escapeRawUrlPath(path: string): string {
  const encodeSpaces = path.startsWith(" ") || path.endsWith(" ");
  return path.replace(/[\s\S]/g, (char) => {
    if (char.charCodeAt(0) < 0x20 || ":?%#\\".includes(char) || (encodeSpaces && char === " ")) {
      return encodeUrlPath(char);
    }
    return char;
  });
}

function spellLike(
  reference: string,
  path: string,
  oldPath: string,
  context: ReferenceContext,
): string {
  const { syntax, quote, url, encodeAll } = context;
  if (url && (encodeAll || (reference !== oldPath && /%[0-9A-Fa-f]{2}/.test(reference))))
    return encodeUrlPath(path);
  switch (syntax) {
    case "html": {
      const escaped = escapeHtmlReference(url ? escapeRawUrlPath(path) : path);
      return ["'", '"'].includes(quote)
        ? escaped
        : escaped.replace(/[\t\n\f\r =<>`]/g, (char) => `&#${char.codePointAt(0)!};`);
    }
    case "script": {
      if (!["'", '"', "`"].includes(quote)) return path;
      const escaped = escapeQuotedReference(path, quote);
      return quote === "`" ? escaped.replace(/\$\{/g, "\\${") : escaped;
    }
    case "css":
      return url ? encodeUrlPath(path) : path;
    case "plain":
      return path;
  }
}

function referenceSyntax(file: string): ReferenceSyntax {
  if (/\.html$/i.test(file)) return "html";
  if (/\.css$/i.test(file)) return "css";
  if (/\.(?:[cm]?js|jsx|tsx?|json)$/i.test(file)) return "script";
  return "plain";
}

function decodeQuotedReference(text: string, syntax: ReferenceSyntax): string {
  if (syntax === "css") return decodeCssEscapes(text);
  if (syntax === "script") {
    const controls: Record<string, string> = { b: "\b", f: "\f", n: "\n", r: "\r", t: "\t" };
    return text.replace(
      /\\(?:u([0-9a-fA-F]{4})|([bfnrt"'`$\\/]))/g,
      (_escaped, hex: string | undefined, char: string | undefined) => {
        if (hex !== undefined) return String.fromCharCode(Number.parseInt(hex, 16));
        return controls[char!] ?? char!;
      },
    );
  }
  return text;
}

function referencePattern(oldPath: string, isDirectory: boolean): RegExp {
  const name = oldPath
    .split("/")
    .map((segment) => Array.from(segment, referenceSpellings).join(""))
    .join(SEPARATOR);
  const end = isDirectory ? `(?=${SEPARATOR})` : FILE_END;
  return new RegExp(
    String.raw`${REFERENCE_START}(?<lead>(?:\.{1,2}${SEPARATOR}|${SEPARATOR}){0,4})${name}${end}`,
    "g",
  );
}

function rewriteEntityAttributes(text: string, rewrite: (text: string) => string): string {
  const parts: string[] = [];
  let cursor = 0;
  for (const tag of scanHtmlOpeningTags(text)) {
    for (const attr of tag.attributes) {
      if (attr.kind !== "value") continue;
      const decoded = decodeAuthoredAttribute(attr.value);
      if (decoded === attr.value) continue;
      let value = escapeHtmlReference(decoded);
      if (!attr.quote)
        value = value.replace(/[\t\n\f\r =<>`]/g, (char) => `&#${char.codePointAt(0)!};`);
      const source = `<x ${attr.name}=${attr.quote}${value}${attr.quote}>`;
      const updated = rewrite(source);
      if (updated === source) continue;
      const replacement = scanHtmlOpeningTags(updated)[0]!.attributes[0]!;
      if (replacement.kind !== "value") throw new Error("Reference rewrite removed its attribute");
      parts.push(text.slice(cursor, attr.valueStart), replacement.value);
      cursor = attr.valueEnd;
    }
  }
  parts.push(text.slice(cursor));
  return parts.join("");
}

// A match inside the longer path of a file or folder that exists (`a.png&b.png`, `other assets/`) is that path's.
// Existing paths are indexed by the text after the old path, then the text before it, so a match costs a few lookups.
export function referenceRewriter(
  oldPath: string,
  newPath: string,
  isDirectory: boolean,
  existing: readonly string[] = [],
): (text: string, syntax?: ReferenceSyntax) => string {
  const oldIdentity = sep === "\\" ? oldPath.replace(/\\/g, "/") : oldPath;
  const pattern = referencePattern(oldPath, isDirectory);
  const around = new Map<string, Map<number, Set<string>>>();
  const afterLengths = new Set<number>();
  let window = 0;
  for (const path of existing) {
    if (path.length <= oldPath.length) continue;
    for (const start of occurrences(path, oldPath)) {
      const [before, after] = [path.slice(0, start), path.slice(start + oldPath.length)];
      const befores = around.get(after) ?? around.set(after, new Map()).get(after)!;
      (befores.get(before.length) ?? befores.set(before.length, new Set()).get(before.length)!).add(
        before,
      );
      afterLengths.add(after.length);
      window = Math.max(window, path.length * 9);
    }
  }
  const normalized = (text: string, context: ReferenceContext, full = false) => {
    let value = text;
    if (context.syntax === "html" || context.htmlAttribute) {
      value = decodeAuthoredAttribute(value);
    }
    value = decodeQuotedReference(value, context.syntax);
    if (context.url) {
      value = value.replace(/\\/g, "/");
      value = full ? decodedUrlPath(value) : decodeWellFormedEscapes(value);
    }
    return sep === "\\" ? value.replace(/\\/g, "/") : value;
  };
  return function rewriteText(text, syntax = "html", normalizeEntities = true) {
    if (syntax === "html" && normalizeEntities) {
      text = rewriteEntityAttributes(text, (source) => rewriteText(source, "html", false));
    }
    pattern.lastIndex = 0;
    if (!pattern.test(text)) return text;
    pattern.lastIndex = 0;
    const tags = syntax === "html" ? scanHtmlOpeningTags(text) : [];
    const inlineRegions = tags
      .filter(
        (tag) => tag.closed && ["script", "style"].includes(tag.name) && tag.rawTextEnd !== null,
      )
      .map((tag) => ({
        start: tag.end,
        end: tag.rawTextEnd!,
        syntax: tag.name === "style" ? ("css" as const) : ("script" as const),
      }));
    const attributes = tags.flatMap((tag) =>
      tag.attributes.flatMap((attr) => (attr.kind === "value" ? [attr] : [])),
    );
    const cssContexts =
      syntax === "css"
        ? [{ start: 0, end: text.length, htmlAttribute: false }]
        : [
            ...inlineRegions
              .filter((region) => region.syntax === "css")
              .map((region) => ({ ...region, htmlAttribute: false })),
            ...attributes
              .filter((attr) => attr.name === "style")
              .map((attr) => ({ ...attr, htmlAttribute: true })),
          ];
    const cssFields = (pattern: RegExp) =>
      cssContexts.flatMap((context) =>
        [...text.slice(context.start, context.end).matchAll(pattern)].map((match) => {
          const prefix = /^(?:url\(\s*|@import\s+)/i.exec(match[0])![0];
          const rest = match[0].slice(prefix.length);
          const delimiter = context.htmlAttribute
            ? /^(?:["']|&quot;|&#39;|&apos;)/.exec(rest)?.[0]
            : /^["']/.exec(rest)?.[0];
          const start = context.start + match.index! + prefix.length + (delimiter?.length ?? 0);
          return {
            start,
            end: context.start + match.index! + match[0].length,
            syntax: "css" as const,
            htmlAttribute: context.htmlAttribute,
            encodeAll: true,
          };
        }),
      );
    const urlRegions = [
      ...attributes
        .filter((attr) => ["src", "href", "poster", "xlink:href"].includes(attr.name))
        .map((attr) => ({
          start: attr.valueStart + (/^[\t\n\f\r ]*/.exec(attr.value)?.[0].length ?? 0),
          end: attr.valueEnd,
          syntax: "html" as const,
          htmlAttribute: true,
          encodeAll: false,
        })),
      ...attributes
        .filter((attr) => attr.name === "srcset")
        .flatMap((attr) =>
          [...attr.value.matchAll(/(^|,)[\t\n\f\r ]*([^,\t\n\f\r ]+)/g)].map((match) => ({
            start: attr.valueStart + match.index! + match[0].length - match[2]!.length,
            end: attr.valueStart + match.index! + match[0].length,
            syntax: "html" as const,
            htmlAttribute: true,
            encodeAll: true,
          })),
        ),
      ...cssFields(
        /\burl\((?:\s*"(?:\\.|[^"\\])*"\s*|\s*'(?:\\.|[^'\\])*'\s*|(?:\\.|[^)\\])*)\)/gi,
      ),
      ...cssFields(/@import\s+(?:"[^"]*"|'[^']*')/gi),
    ].sort((a, b) => a.start - b.start);
    let urlIndex = 0;
    let regionIndex = 0;
    return text.replace(pattern, (...args) => {
      const [match, offset] = [args[0] as string, args.at(-3) as number];
      const { lead } = args.at(-1) as { lead: string };
      while (inlineRegions[regionIndex] && inlineRegions[regionIndex]!.end <= offset) regionIndex++;
      const region = inlineRegions[regionIndex];
      const matchSyntax = region && offset >= region.start ? region.syntax : syntax;
      while (urlRegions[urlIndex] && urlRegions[urlIndex]!.end <= offset) urlIndex++;
      const urlRegion = urlRegions[urlIndex];
      const url = matchSyntax !== "script" && !!urlRegion && offset >= urlRegion.start;
      const context: ReferenceContext = {
        syntax: url ? urlRegion!.syntax : matchSyntax,
        url,
        htmlAttribute: url && urlRegion!.htmlAttribute,
        encodeAll: url && urlRegion!.encodeAll,
        quote: text[offset - 1] ?? "",
      };
      if (url && offset !== urlRegion!.start) return match;
      const reference = match.slice(lead.length);
      if (normalized(reference, context, true) !== oldIdentity) return match;
      if (
        isDirectory &&
        !normalized(
          text.slice(offset + match.length, offset + match.length + 4),
          context,
        ).startsWith("/")
      )
        return match;
      const at = offset + lead.length;
      const head = normalized(text.slice(Math.max(0, at - window), at), context);
      const tail = normalized(
        text.slice(offset + match.length, offset + match.length + window),
        context,
        context.url,
      );
      const inLonger = [...afterLengths].some((after) => {
        const befores = tail.length >= after && around.get(tail.slice(0, after));
        return (
          befores &&
          [...befores].some(
            ([length, set]) => head.length >= length && set.has(head.slice(head.length - length)),
          )
        );
      });
      if (inLonger) return match;
      return `${lead}${spellLike(reference, newPath, oldPath, context)}`;
    });
  };
}

function occurrences(text: string, part: string): number[] {
  const at: number[] = [];
  for (let i = text.indexOf(part); i >= 0; i = text.indexOf(part, i + 1)) at.push(i);
  return at;
}

function projectPaths(
  root: string,
  dir = root,
  prefix = "",
  ancestors: ReadonlySet<string> = new Set(),
): string[] {
  return readableEntries(dir).flatMap((entry) => {
    const [path, full] = [`${prefix}${entry.name}`, join(dir, entry.name)];
    const real = entry.name === "node_modules" ? null : directoryReal(entry, full);
    if (real === null || ancestors.has(real) || !isSafePath(root, full)) return [path];
    return [path, ...projectPaths(root, full, `${path}/`, new Set([...ancestors, real]))];
  });
}

// A directory's real path, through a link, or null for anything else: aliases are paths too.
function directoryReal(entry: Dirent, full: string): string | null {
  try {
    return entry.isDirectory() || (entry.isSymbolicLink() && statSync(full).isDirectory())
      ? realpathSync(full)
      : null;
  } catch {
    return null;
  }
}

/**
 * After a rename, update all references to the old path in project files.
 * Scans HTML, CSS, JS, and JSON files for the old path and replaces it where it names that path.
 */
function updateReferences(
  projectDir: string,
  oldPath: string,
  newPath: string,
  isDirectory: boolean,
): number {
  const textFiles = walkFiles(projectDir, (name) =>
    /\.(html|css|js|jsx|ts|tsx|json|mjs|cjs|md|mdx)$/i.test(name),
  );

  const rewrite = referenceRewriter(oldPath, newPath, isDirectory, projectPaths(projectDir));
  let updatedCount = 0;
  for (const file of textFiles) {
    if (!isSafePath(projectDir, file) || isPrivateProjectFile(projectDir, file)) continue;
    const content = readableText(file);
    if (content === null) continue;

    const updated = rewrite(content, referenceSyntax(file));
    if (updated !== content) {
      replaceFileAtomically(file, updated, statSync(file).mode);
      updatedCount++;
    }
  }
  return updatedCount;
}

// ── GSAP script extraction ──────────────────────────────────────────────────

/**
 * Mint the HTML's ids (so a tween saved on a served id writes that id too), parse it with
 * linkedom, locate the inline `<script>` holding GSAP timeline code, and return its text and
 * a function that replaces that script block and serialises back to HTML.
 */
function extractGsapScriptBlock(html: string): {
  scriptText: string;
  document: Document;
  root: ParentNode;
  replaceScript: (newText: string) => string;
} | null {
  const { document } = parseHTML(ensureHfIds(html));
  const scripts = [
    ...document.querySelectorAll("script:not([src])"),
    ...Array.from(document.querySelectorAll("template")).flatMap((tmpl) =>
      Array.from(tmpl.querySelectorAll("script:not([src])")),
    ),
  ];
  const script = findTimelineScript(scripts);
  if (!script) return null;
  return {
    scriptText: script.textContent || "",
    document,
    root: clipQueryRoot(script),
    replaceScript(newText: string): string {
      script.textContent = newText;
      return document.toString();
    },
  };
}

/**
 * Remove every GSAP animation that targets `selector` from an HTML string's
 * inline script. Used after unwrapping a group so its leftover `gsap.set("#id")`
 * (the wrapper is gone) doesn't throw "target not found" on every preview run.
 */
function stripGsapAnimationsForSelector(html: string, selector: string): string {
  const block = extractGsapScriptBlock(html);
  if (!block) return html;
  const parsed = parseGsapScriptAcorn(block.scriptText);
  const matching = parsed.animations.filter((a) => a.targetSelector === selector);
  if (matching.length === 0) return html;
  let script = block.scriptText;
  // Reverse so earlier removals don't shift the spans of later ones.
  for (const anim of [...matching].reverse()) {
    script = removeAnimationFromScript(script, anim.id);
  }
  return block.replaceScript(script);
}

/**
 * Bake a group's STATIC GSAP transform into each member BEFORE the group is
 * stripped on ungroup. Moving a group is stored as `gsap.set("#group-1",{x,y,…})`;
 * without distributing it to the members they snap back to their creation-time
 * positions. Translation (x/y/z) is an exact per-axis add; rotation/scale are
 * composed about the group's centre (the pivot) so off-centre members don't drift.
 * Animated group transforms (keyframes/tweens) are NOT baked — left to be stripped.
 */
function bakeGroupTransformIntoMembers(
  html: string,
  groupId: string,
  members: Array<{ id: string; cx: number; cy: number }>,
  groupCenter: { cx: number; cy: number },
): string {
  const block = extractGsapScriptBlock(html);
  if (!block) return html;
  const parsed = parseGsapScriptAcorn(block.scriptText);
  const groupSel = `#${groupId}`;
  const groupSets = parsed.animations.filter(
    (a) => a.targetSelector === groupSel && a.method === "set",
  );
  if (groupSets.length === 0) return html;
  // Merge the group's sets (later per-prop wins) → its effective static transform.
  const gt: Record<string, number> = {};
  for (const s of groupSets) {
    for (const [k, v] of Object.entries(s.properties)) if (typeof v === "number") gt[k] = v;
  }
  const gx = gt.x ?? 0;
  const gy = gt.y ?? 0;
  const gz = gt.z ?? 0;
  const grot = gt.rotation ?? 0;
  const gscale = gt.scale ?? 1;
  // Identity across ALL axes (incl. the extras baked below) — else a group whose
  // only transform is e.g. scaleX would skip the bake and silently drop it.
  const isScaleAxis = (k: string) => k === "scale" || k === "scaleX" || k === "scaleY";
  const groupIsIdentity = Object.entries(gt).every(([k, v]) =>
    isScaleAxis(k) ? v === 1 : v === 0,
  );
  if (groupIsIdentity) return html;

  const rad = (grot * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  const round3 = (n: number) => Math.round(n * 1000) / 1000;

  let script = block.scriptText;
  for (const m of members) {
    const memberSel = `#${m.id}`;
    const sets = parsed.animations.filter(
      (a) => a.targetSelector === memberSel && a.method === "set",
    );
    // Effective member transform (merge its sets — last per-prop wins).
    const mProps: Record<string, number | string> = {};
    for (const s of sets) Object.assign(mProps, s.properties);
    const mx = typeof mProps.x === "number" ? mProps.x : 0;
    const my = typeof mProps.y === "number" ? mProps.y : 0;
    // Compose the group transform onto the member's centre, then back to an offset.
    const dx = m.cx + mx - groupCenter.cx;
    const dy = m.cy + my - groupCenter.cy;
    const visX = groupCenter.cx + gscale * (cos * dx - sin * dy) + gx;
    const visY = groupCenter.cy + gscale * (sin * dx + cos * dy) + gy;
    const newProps: Record<string, number | string> = {
      ...mProps,
      x: round3(visX - m.cx),
      y: round3(visY - m.cy),
    };
    if (gz !== 0) newProps.z = (typeof mProps.z === "number" ? mProps.z : 0) + gz;
    if (grot !== 0) {
      newProps.rotation = round3(
        (typeof mProps.rotation === "number" ? mProps.rotation : 0) + grot,
      );
    }
    if (gscale !== 1) {
      newProps.scale = round3((typeof mProps.scale === "number" ? mProps.scale : 1) * gscale);
    }
    // Bake any REMAINING group transform axis so nothing is silently dropped on
    // ungroup. The pivot-composed axes (x/y/z/rotation/scale) are handled above;
    // these extras (scaleX/Y, rotationX/Y/Z, skewX/Y, transformPerspective) compose
    // about the member's own origin — exact for a member at the group centre, a
    // close approximation otherwise (groups rarely carry these).
    const pivoted = new Set(["x", "y", "z", "rotation", "scale"]);
    for (const [k, v] of Object.entries(gt)) {
      if (pivoted.has(k) || typeof v !== "number") continue;
      if (k === "scaleX" || k === "scaleY") {
        if (v !== 1) newProps[k] = round3((typeof mProps[k] === "number" ? mProps[k] : 1) * v);
      } else if (k === "transformPerspective") {
        // Adopt the group's lens only if the member has none of its own — never
        // silently overwrite a member's existing perspective.
        if (typeof mProps[k] !== "number") newProps[k] = v;
      } else if (v !== 0) {
        newProps[k] = round3((typeof mProps[k] === "number" ? mProps[k] : 0) + v);
      }
    }

    // Strip ALL the member's existing sets and write ONE fresh gsap.set at position
    // 0. The baked transform is the member's static base — writing it to an arbitrary
    // "last" set could land it at a non-zero timeline position, or leave stale earlier
    // sets that override it. Reverse-remove so spans don't shift, then add fresh.
    for (const s of [...sets].reverse()) {
      script = removeAnimationFromScript(script, s.id);
    }
    script = addAnimationToScript(script, {
      targetSelector: memberSel,
      method: "set",
      position: 0,
      properties: newProps,
      global: true,
    }).script;
  }
  return block.replaceScript(script);
}

function stripStudioEditsFromTarget(document: Document, selector: string): number {
  if (!selector) return 0;
  let stripped = 0;
  try {
    for (const el of document.querySelectorAll(selector)) {
      if (!isHTMLElement(el)) continue;
      const htmlEl = el;
      let touched = false;
      // Manual path offset (--hf-studio-offset / translate) — a GSAP position tween
      // now owns position, so the stale offset channel must go.
      if (el.getAttribute("data-hf-studio-path-offset")) {
        const originalTranslate = el.getAttribute("data-hf-studio-original-inline-translate");
        htmlEl.style.removeProperty("--hf-studio-offset-x");
        htmlEl.style.removeProperty("--hf-studio-offset-y");
        if (originalTranslate) {
          htmlEl.style.setProperty("translate", originalTranslate);
        } else {
          htmlEl.style.removeProperty("translate");
        }
        el.removeAttribute("data-hf-studio-path-offset");
        el.removeAttribute("data-hf-studio-original-translate");
        el.removeAttribute("data-hf-studio-original-inline-translate");
        touched = true;
      }
      // Manual rotation (--hf-studio-rotation / rotate) — likewise, a GSAP rotation
      // set/tween now owns rotation, so clear the legacy CSS-var channel.
      if (el.getAttribute("data-hf-studio-rotation")) {
        const originalRotate = el.getAttribute("data-hf-studio-original-inline-rotate");
        const originalOrigin = el.getAttribute("data-hf-studio-original-rotation-transform-origin");
        htmlEl.style.removeProperty("--hf-studio-rotation");
        if (originalRotate) {
          htmlEl.style.setProperty("rotate", originalRotate);
        } else {
          htmlEl.style.removeProperty("rotate");
        }
        if (originalOrigin) {
          htmlEl.style.setProperty("transform-origin", originalOrigin);
        } else {
          htmlEl.style.removeProperty("transform-origin");
        }
        el.removeAttribute("data-hf-studio-rotation");
        el.removeAttribute("data-hf-studio-rotation-draft");
        el.removeAttribute("data-hf-studio-original-rotate");
        el.removeAttribute("data-hf-studio-original-inline-rotate");
        el.removeAttribute("data-hf-studio-original-rotation-transform-origin");
        touched = true;
      }
      if (touched) stripped++;
    }
  } catch {
    // Invalid selector — skip silently.
  }
  return stripped;
}

// A studio path-offset (--hf-studio-offset / data-hf-studio-path-offset) and a GSAP
// position tween both drive translate — keeping both stacks the offsets (a gesture or
// drag recorded over a stale offset plays shoved off-position). When a committed tween
// writes a position property, the tween owns position, so the stale offset must go.
function keyframesWritePosition(
  keyframes: Array<{ properties: Record<string, number | string> }>,
): boolean {
  return keyframes.some((kf) =>
    Object.keys(kf.properties).some((k) => classifyPropertyGroup(k) === "position"),
  );
}

// A studio rotation edit (--hf-studio-rotation / data-hf-studio-rotation) and a GSAP
// rotation tween both drive rotate — keeping both stacks them. When a committed keyframe
// set writes a rotation property, the tween owns rotation, so the stale CSS-var channel
// must go (the position twin of this is `keyframesWritePosition`).
function keyframesWriteRotation(
  keyframes: Array<{ properties: Record<string, number | string> }>,
): boolean {
  return keyframes.some((kf) =>
    Object.keys(kf.properties).some((k) => classifyPropertyGroup(k) === "rotation"),
  );
}

function lastKeyframeOpacity(kfs: GsapAnimation["keyframes"]): number | string | undefined {
  if (!kfs) return undefined;
  for (let i = kfs.keyframes.length - 1; i >= 0; i--) {
    if ("opacity" in kfs.keyframes[i]!.properties) return kfs.keyframes[i]!.properties.opacity;
  }
  return undefined;
}

function resolveFinalOpacity(anim: GsapAnimation): number | null {
  if (anim.method === "from") return null;
  const raw = anim.keyframes ? lastKeyframeOpacity(anim.keyframes) : anim.properties.opacity;
  if (raw == null) return null;
  if (typeof raw === "string" && /^[+\-*]=/.test(raw)) return null;
  const num = Number(raw);
  return Number.isFinite(num) && num !== 0 ? num : null;
}

function bakeVisibilityOnDelete(document: Document, anim: GsapAnimation): void {
  const opacity = resolveFinalOpacity(anim);
  if (opacity === null) return;
  try {
    for (const el of document.querySelectorAll(anim.targetSelector)) {
      if (isHTMLElement(el)) el.style.setProperty("opacity", String(opacity));
    }
  } catch {
    // Invalid selector — skip silently.
  }
}

// ── GSAP mutation types ─────────────────────────────────────────────────────

export type GsapMutationRequest =
  | {
      type: "update-property";
      animationId: string;
      property: string;
      value: number | string;
    }
  | {
      // Merge MULTIPLE properties into an animation in ONE call. A per-property
      // loop on a `set` can shift its group-derived id mid-way (e.g. adding `scale`
      // to a rotation set), 404-ing the next update; this lands them all at once.
      type: "update-properties";
      animationId: string;
      properties: Record<string, number | string>;
    }
  | {
      type: "update-from-property";
      animationId: string;
      property: string;
      value: number | string;
    }
  | {
      type: "update-meta";
      animationId: string;
      updates: {
        duration?: number;
        ease?: string;
        easeEach?: string;
        position?: number;
        resetKeyframeEases?: boolean;
      };
    }
  | {
      type: "add";
      targetSelector: string;
      method: "to" | "from" | "set" | "fromTo";
      position: number;
      duration?: number;
      ease?: string;
      properties: Record<string, number | string>;
      fromProperties?: Record<string, number | string>;
      /** Emit a base `gsap.set` (off-timeline, no keyframe marker) instead of `tl.set`. */
      global?: boolean;
    }
  | { type: "delete"; animationId: string; stripStudioEdits?: boolean }
  | {
      type: "add-property";
      animationId: string;
      property: string;
      defaultValue: number | string;
    }
  | {
      type: "add-from-property";
      animationId: string;
      property: string;
      defaultValue: number | string;
    }
  | { type: "remove-property"; animationId: string; property: string }
  | { type: "remove-from-property"; animationId: string; property: string }
  | {
      type: "add-keyframe";
      animationId: string;
      percentage: number;
      properties: Record<string, number | string>;
      ease?: string;
      backfillDefaults?: Record<string, number | string>;
    }
  | { type: "remove-keyframe"; animationId: string; percentage: number }
  | {
      type: "move-keyframe";
      animationId: string;
      fromPercentage: number;
      toPercentage: number;
    }
  | {
      // Boundary drag-to-retime: grow/shift a keyframed tween's window and re-key
      // its existing keyframes in place (preserves _auto / per-keyframe ease /
      // easeEach / outer ease, unlike the array-rebuild replace-with-keyframes).
      type: "resize-keyframed-tween";
      animationId: string;
      position: number;
      duration: number;
      pctRemap: Array<{ from: number; to: number }>;
    }
  | {
      type: "update-keyframe";
      animationId: string;
      percentage: number;
      properties: Record<string, number | string>;
      ease?: string;
    }
  | {
      type: "convert-to-keyframes";
      animationId: string;
      resolvedFromValues?: Record<string, number | string>;
      /** Duration (s) to give a converted static `set`, which has none. */
      duration?: number;
    }
  | { type: "remove-all-keyframes"; animationId: string }
  | {
      type: "materialize-keyframes";
      animationId: string;
      keyframes: Array<{
        percentage: number;
        properties: Record<string, number | string>;
        ease?: string;
      }>;
      easeEach?: string;
      resolvedSelector?: string;
      allElements?: Array<{
        selector: string;
        keyframes: Array<{ percentage: number; properties: Record<string, number | string> }>;
        easeEach?: string;
      }>;
    }
  | {
      type: "set-arc-path";
      animationId: string;
      enabled: boolean;
      autoRotate?: boolean | number;
      segments?: Array<{
        curviness: number;
        cp1?: { x: number; y: number };
        cp2?: { x: number; y: number };
      }>;
    }
  | {
      type: "update-arc-segment";
      animationId: string;
      segmentIndex: number;
      curviness?: number;
      cp1?: { x: number; y: number };
      cp2?: { x: number; y: number };
    }
  | {
      type: "update-motion-path-point";
      animationId: string;
      pointIndex: number;
      x: number;
      y: number;
    }
  | { type: "add-motion-path-point"; animationId: string; index: number; x: number; y: number }
  | { type: "remove-motion-path-point"; animationId: string; index: number }
  | {
      type: "add-motion-path";
      targetSelector: string;
      position: number;
      duration: number;
      x: number;
      y: number;
      ease?: string;
    }
  | { type: "remove-arc-path"; animationId: string }
  | {
      type: "add-with-keyframes";
      targetSelector: string;
      position: number;
      duration: number;
      keyframes: Array<{
        percentage: number;
        properties: Record<string, number | string>;
        ease?: string;
        auto?: boolean;
      }>;
      ease?: string;
      easeEach?: string;
    }
  | {
      type: "replace-with-keyframes";
      animationId: string;
      targetSelector: string;
      position: number;
      duration: number;
      keyframes: Array<{
        percentage: number;
        properties: Record<string, number | string>;
        ease?: string;
        auto?: boolean;
      }>;
      ease?: string;
      easeEach?: string;
    }
  | {
      type: "split-animations";
      originalId: string;
      newId: string;
      splitTime: number;
      elementStart: number;
      elementDuration: number;
    }
  | {
      type: "split-into-property-groups";
      animationId: string;
    }
  | {
      type: "delete-all-for-selector";
      targetSelector: string;
    }
  | {
      // Enforce "exactly one position write per element": keep `keepAnimationId`
      // (the write the commit is editing) and strip every other pure-position
      // write for the selector. Self-heals files that already have duplicates.
      type: "consolidate-position-writes";
      targetSelector: string;
      keepAnimationId?: string;
    }
  | {
      // Rewrite all top-level helper/loop constructs into literal tweens so
      // computed keyframes become directly editable (visual no-op).
      type: "unroll-timeline";
    }
  | {
      type: "shift-positions";
      targetSelector: string;
      delta: number;
    }
  | {
      // Batched shift: fold shiftPositionsInScript over N selectors in one write.
      // Lets a multi-clip timeline move (ripple / insert) shift every affected
      // clip's tweens atomically instead of one racing server round-trip per clip.
      type: "shift-positions-batch";
      shifts: Array<{ targetSelector: string; delta: number }>;
    }
  | {
      type: "scale-positions";
      targetSelector: string;
      oldStart: number;
      oldDuration: number;
      newStart: number;
      newDuration: number;
    };

// ── GSAP mutation executor ──────────────────────────────────────────────────

type GsapMutationResult = string | { script: string; skippedSelectors: string[] };

function replaceInPlaceUnlessSetOrUnknown(
  scriptText: string,
  body: Extract<GsapMutationRequest, { type: "replace-with-keyframes" }>,
): string {
  const edit = { ...body, easeEach: resolveReplacementEaseEach(scriptText, body) };
  const inPlace = replaceTweenWithKeyframesInScript(scriptText, body.animationId, edit);
  if (inPlace !== null) return inPlace;
  const script = removeAnimationFromScript(scriptText, body.animationId);
  return addAnimationWithKeyframesToScript(
    script,
    body.targetSelector,
    body.position,
    body.duration,
    body.keyframes,
    body.ease,
    edit.easeEach,
  ).script;
}

function resolveReplacementEaseEach(
  scriptText: string,
  request: { animationId: string; easeEach?: string },
): string | undefined {
  if (request.easeEach !== undefined) return request.easeEach;
  const original = parseGsapScriptAcorn(scriptText).animations.find(
    (animation) => animation.id === request.animationId,
  );
  if (!original?.arcPath?.enabled) return undefined;
  return original?.keyframes?.easeEach ?? original?.ease;
}

// Mutations that can change a position tween's first keyframe (value/existence/timing)
// and therefore require the pre-keyframe hold-`set`s to be re-synced afterwards.
// `syncPositionHoldsBeforeKeyframes` rebuilds all `hf-hold` sets from scratch: it acts
// on every tween whose 0% keyframe carries a position prop and
// whose start is > 0. So any mutation that creates such a tween, retargets it, or moves
// its start across the t=0 boundary must trigger a re-sync.
const HOLD_SYNC_MUTATION_TYPES = new Set<string>([
  "add-keyframe",
  "update-keyframe",
  "remove-keyframe",
  "move-keyframe",
  "resize-keyframed-tween",
  "remove-all-keyframes",
  "add-with-keyframes",
  "replace-with-keyframes",
  "convert-to-keyframes",
  "materialize-keyframes",
  "update-motion-path-point",
  "add-motion-path-point",
  "remove-motion-path-point",
  // Authors a fresh motionPath tween whose parsed first keyframe is (0,0); if it lands
  // at position > 0 the element snaps home at t=0 without a pre-tween hold-`set`.
  "add-motion-path",
  // Can move a tween's `position` (start) across the t=0 boundary, which flips whether a
  // keyframed position tween needs a hold (started at 0 → moved later, or vice versa).
  "update-meta",
  // Time-shift / time-scale tweens, which can move a keyframed position tween's start
  // across t=0, flipping hold need; stale holds are not repositioned by these ops.
  "shift-positions",
  "shift-positions-batch",
  "scale-positions",
  // Retargets keyframed position tweens to a cloned element's selector; the old hold is
  // keyed to the prior selector, so holds must be rebuilt for the new target.
  "split-animations",
  "delete",
  "delete-all-for-selector",
]);

async function executeGsapMutation(
  body: GsapMutationRequest,
  block: NonNullable<ReturnType<typeof extractGsapScriptBlock>>,
  respond: (data: unknown, status?: number) => Response,
  writer: "recast" | "acorn",
): Promise<GsapMutationResult | Response> {
  // Keep writer selection explicit at the route boundary so a batch cannot
  // switch implementations between operations.
  if (writer === "recast") {
    return executeGsapMutationRecast(body, block, respond);
  }
  return executeGsapMutationAcorn(body, block, respond);
}

function validateGsapMutationRequest(
  c: RouteContext,
  body: GsapMutationRequest | null,
): Response | null {
  if (!body || typeof body !== "object" || !("type" in body) || !body.type) {
    return c.json({ error: "mutation type required" }, 400);
  }
  if (containsRawGsapExpression(body)) {
    return c.json({ error: "raw JavaScript expressions are not accepted" }, 400);
  }
  const unsafeFields = findUnsafeMutationValues(body);
  if (unsafeFields.length > 0) return rejectUnsafeMutationValues(c, unsafeFields);
  if (
    body.type === "shift-positions-batch" &&
    (!("shifts" in body) || !Array.isArray(body.shifts))
  ) {
    return c.json({ error: "shift-positions-batch requires a `shifts` array" }, 400);
  }
  return null;
}

function containsRawGsapExpression(value: unknown): boolean {
  if (typeof value === "string") return value.startsWith("__raw:");
  if (Array.isArray(value)) return value.some(containsRawGsapExpression);
  if (!value || typeof value !== "object") return false;
  return Object.values(value).some(containsRawGsapExpression);
}

async function prepareGsapMutationScript(
  c: RouteContext,
  res: ResolvedGsapFile,
  firstMutation: GsapMutationRequest,
): Promise<
  | Response
  | {
      html: string;
      beforeHtml: string;
      block: NonNullable<ReturnType<typeof extractGsapScriptBlock>>;
    }
> {
  const beforeHtml = readFileSync(res.absPath, "utf-8");
  let html = beforeHtml;
  let block = extractGsapScriptBlock(html);
  if (!block && (firstMutation.type === "add" || firstMutation.type === "add-with-keyframes")) {
    const compId = html.match(/data-composition-id="([^"]+)"/)?.[1] ?? "main";
    const { GSAP_CDN } = await import("@hyperframes/core");
    const bootstrap = [
      `<script src="${GSAP_CDN}"></script>`,
      "<script>",
      "window.__timelines = window.__timelines || {};",
      "const tl = gsap.timeline({ paused: true });",
      `window.__timelines["${compId}"] = tl;`,
      "</script>",
    ].join("\n");
    const [first, second] = hasCompositionOutsideTemplates(html)
      ? (["body", "template"] as const)
      : (["template", "body"] as const);
    html =
      insertBeforeCloseTag(html, first, `${bootstrap}\n`) ??
      insertBeforeCloseTag(html, second, `${bootstrap}\n`) ??
      `${html}\n${bootstrap}`;
    block = extractGsapScriptBlock(html);
  }
  if (
    !block &&
    (firstMutation.type === "shift-positions" ||
      firstMutation.type === "scale-positions" ||
      firstMutation.type === "shift-positions-batch")
  ) {
    return c.json({
      ok: true,
      changed: false,
      mutated: false,
      parsed: { animations: [], timelineVar: "tl", preamble: "", postamble: "" },
      before: html,
      after: html,
      scriptText: "",
      path: res.filePath,
      backupPath: null,
    });
  }
  if (!block) return c.json({ error: "no GSAP script found in file" }, 400);
  return { html, beforeHtml, block };
}

type RetimeSlot = ClipTweenRetime | "no-op";

function retimeRuns(mutations: readonly GsapMutationRequest[]): Map<number, RetimeSlot[]> {
  const runs = new Map<number, RetimeSlot[]>();
  let start = -1;
  mutations.forEach((mutation, index) => {
    const retime = clipRetimeOf(mutation);
    if (!retime) return void (start = -1);
    if (start < 0) runs.set((start = index), []);
    runs.get(start)!.push(retime);
  });
  return runs;
}

// The one owner of the clip-retime no-op rules; a no-op keeps its slot so flags line up.
function clipRetimeOf(mutation: GsapMutationRequest): RetimeSlot | null {
  if (mutation.type === "shift-positions") {
    const { targetSelector, delta } = mutation;
    return targetSelector && Number.isFinite(delta) && delta !== 0
      ? { kind: "shift", targetSelector, delta }
      : "no-op";
  }
  if (mutation.type !== "scale-positions") return null;
  const { targetSelector, oldStart, oldDuration, newStart, newDuration } = mutation;
  const finite = [oldStart, oldDuration, newStart, newDuration].every(Number.isFinite);
  if (!targetSelector || !finite || oldDuration <= 0 || newDuration <= 0) return "no-op";
  if (oldStart === newStart && oldDuration === newDuration) return "no-op";
  return { kind: "scale", targetSelector, oldStart, oldDuration, newStart, newDuration };
}

function retimeRun(script: string, run: readonly RetimeSlot[], root: ParentNode | undefined) {
  const live = run.filter((slot): slot is ClipTweenRetime => slot !== "no-op");
  const retimed = retimeClipTweensInScript(script, live, root);
  const synced = syncPositionHoldsBeforeKeyframes(retimed.script, script);
  let next = 0;
  const changed = run.map((slot) => slot !== "no-op" && retimed.changed[next++]!);
  if (synced !== retimed.script) changed[changed.length - 1] = true;
  return { script: synced, changed: synced === script ? changed.map(() => false) : changed };
}

async function applyGsapMutations(
  c: RouteContext,
  res: ResolvedGsapFile,
  mutations: GsapMutationRequest[],
): Promise<Response> {
  const firstMutation = mutations[0];
  if (!firstMutation) return c.json({ error: "mutations array required" }, 400);
  const prepared = await prepareGsapMutationScript(c, res, firstMutation);
  if (prepared instanceof Response) return prepared;
  const { html, beforeHtml, block } = prepared;
  let lengthIsAuthored: boolean | undefined;

  const initialScript = block.scriptText;
  const skippedSelectors = new Set<string>();
  const respond = (data: unknown, status?: number) =>
    status ? c.json(data, status) : c.json(data);
  let writer: "recast" | "acorn";
  try {
    writer = resolveGsapWriter({
      HYPERFRAMES_GSAP_WRITER: process.env["HYPERFRAMES_GSAP_WRITER"],
    });
  } catch (error) {
    return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
  }

  const mutationChanges: boolean[] = [];
  const retimes = writer === "acorn" ? retimeRuns(mutations) : new Map<number, RetimeSlot[]>();
  for (let index = 0; index < mutations.length; index++) {
    const run = retimes.get(index);
    if (run) {
      const retimed = retimeRun(block.scriptText, run, block.root);
      mutationChanges.push(...retimed.changed);
      block.scriptText = retimed.script;
      index += run.length - 1;
      continue;
    }
    const mutation = mutations[index]!;
    const previousScript = block.scriptText;
    const result = await executeGsapMutation(mutation, block, respond, writer);
    if (result instanceof Response) return result;
    let newScript = typeof result === "string" ? result : result.script;
    if (typeof result !== "string") {
      for (const selector of result.skippedSelectors) skippedSelectors.add(selector);
    }
    if (HOLD_SYNC_MUTATION_TYPES.has(mutation.type)) {
      lengthIsAuthored ??= !lengthIsTimeline(res.project.dir, res.filePath);
      if (lengthIsAuthored) newScript = trimTrailingKeyframeSpans(previousScript, newScript);
      newScript =
        writer === "acorn"
          ? syncPositionHoldsBeforeKeyframes(newScript, previousScript)
          : (await loadGsapParser()).syncPositionHoldsBeforeKeyframes(newScript, previousScript);
    }
    mutationChanges.push(newScript !== previousScript);
    block.scriptText = newScript;
  }

  const changed = block.scriptText !== initialScript;
  const newHtml = changed ? block.replaceScript(block.scriptText) : html;
  let backupPath: string | null = null;
  // Parsing can await lazy imports. Revalidate before EVERY successful response,
  // including semantic no-ops: a stale no-op response would otherwise claim
  // the old bytes and let the client keep a preview that missed a successor.
  if (readFileSync(res.absPath, "utf-8") !== beforeHtml) {
    return c.json({ error: "file changed during GSAP mutation", conflict: true }, 409);
  }
  if (changed) {
    const mutationResult = writeMutationResult(
      c,
      res.project.dir,
      res.filePath,
      res.absPath,
      newHtml,
      beforeHtml,
    );
    if (mutationResult instanceof Response) return mutationResult;
    backupPath = mutationResult.backupPath;
  }

  const responsePayload: Record<string, unknown> = {
    ok: true,
    changed,
    mutated: changed,
    mutationChanges,
    parsed: parseGsapScriptAcorn(block.scriptText),
    before: beforeHtml,
    after: newHtml,
    scriptText: block.scriptText,
    path: res.filePath,
    version: fileContentVersion(newHtml),
    backupPath,
  };
  if (skippedSelectors.size > 0) responsePayload.skippedSelectors = [...skippedSelectors];
  c.header("ETag", responsePayload.version as string);
  return c.json(responsePayload);
}

function executeGsapMutationAcorn(
  body: GsapMutationRequest,
  block: NonNullable<ReturnType<typeof extractGsapScriptBlock>>,
  respond: (data: unknown, status?: number) => Response,
): GsapMutationResult | Response {
  function requireAnimation(
    scriptText: string,
    animationId: string,
  ): { anim: GsapAnimation } | { err: Response } {
    const parsed = parseGsapScriptAcorn(scriptText);
    const anim = parsed.animations.find((a) => a.id === animationId);
    if (!anim) return { err: respond({ error: "animation not found" }, 404) };
    return { anim };
  }

  function requireFromToAnimation(
    scriptText: string,
    animationId: string,
  ): { anim: GsapAnimation } | { err: Response } {
    const result = requireAnimation(scriptText, animationId);
    if ("err" in result) return result;
    if (result.anim.method !== "fromTo")
      return { err: respond({ error: "animation is not a fromTo" }, 400) };
    return result;
  }

  switch (body.type) {
    case "update-property":
    case "add-property": {
      const r = requireAnimation(block.scriptText, body.animationId);
      if ("err" in r) return r.err;
      const val = body.type === "update-property" ? body.value : body.defaultValue;
      return updateAnimationInScript(block.scriptText, body.animationId, {
        properties: { ...r.anim.properties, [body.property]: val },
      });
    }
    case "update-properties": {
      const r = requireAnimation(block.scriptText, body.animationId);
      if ("err" in r) return r.err;
      return updateAnimationInScript(block.scriptText, body.animationId, {
        properties: { ...r.anim.properties, ...body.properties },
      });
    }
    case "update-from-property":
    case "add-from-property": {
      const r = requireFromToAnimation(block.scriptText, body.animationId);
      if ("err" in r) return r.err;
      const val = body.type === "update-from-property" ? body.value : body.defaultValue;
      return updateAnimationInScript(block.scriptText, body.animationId, {
        fromProperties: { ...(r.anim.fromProperties ?? {}), [body.property]: val },
      });
    }
    case "update-meta": {
      return updateAnimationInScript(block.scriptText, body.animationId, body.updates);
    }
    case "add": {
      if (body.fromProperties && body.method !== "fromTo") {
        return respond({ error: "fromProperties is only valid for method=fromTo" }, 400);
      }
      if (
        Object.keys(body.properties).some((key) => {
          const group = classifyPropertyGroup(key);
          return group === "position" || group === "rotation";
        })
      ) {
        stripStudioEditsFromTarget(block.document, body.targetSelector);
      }
      const result = addAnimationToScript(block.scriptText, {
        targetSelector: body.targetSelector,
        method: body.method,
        position: body.position,
        duration: body.duration,
        ease: body.ease,
        properties: body.properties,
        fromProperties: body.fromProperties,
        ...(body.global ? { global: true } : {}),
      });
      return result.script;
    }
    case "delete": {
      const delTarget = requireAnimation(block.scriptText, body.animationId);
      if (!("err" in delTarget) && body.stripStudioEdits) {
        stripStudioEditsFromTarget(block.document, delTarget.anim.targetSelector);
        bakeVisibilityOnDelete(block.document, delTarget.anim);
      }
      return removeAnimationFromScript(block.scriptText, body.animationId);
    }
    case "delete-all-for-selector": {
      const parsed = parseGsapScriptAcorn(block.scriptText);
      const matching = parsed.animations.filter((a) => a.targetSelector === body.targetSelector);
      if (matching.length === 0) return block.scriptText;
      stripStudioEditsFromTarget(block.document, body.targetSelector);
      let script = block.scriptText;
      for (const anim of matching.reverse()) {
        script = removeAnimationFromScript(script, anim.id);
      }
      return script;
    }
    case "consolidate-position-writes": {
      if (!body.targetSelector) return block.scriptText;
      return dedupePositionWritesInScript(
        block.scriptText,
        body.targetSelector,
        body.keepAnimationId,
      );
    }
    case "remove-property": {
      const r = requireAnimation(block.scriptText, body.animationId);
      if ("err" in r) return r.err;
      const filtered = { ...r.anim.properties };
      delete filtered[body.property];
      return updateAnimationInScript(block.scriptText, body.animationId, {
        properties: filtered,
      });
    }
    case "remove-from-property": {
      const r = requireFromToAnimation(block.scriptText, body.animationId);
      if ("err" in r) return r.err;
      const filtered = { ...(r.anim.fromProperties ?? {}) };
      delete filtered[body.property];
      return updateAnimationInScript(block.scriptText, body.animationId, {
        fromProperties: filtered,
      });
    }
    case "add-keyframe": {
      return addKeyframeToScript(
        block.scriptText,
        body.animationId,
        body.percentage,
        body.properties,
        body.ease,
        body.backfillDefaults,
      );
    }
    case "remove-keyframe": {
      return removeKeyframeFromScript(block.scriptText, body.animationId, body.percentage);
    }
    case "move-keyframe": {
      return moveKeyframeInScript(
        block.scriptText,
        body.animationId,
        body.fromPercentage,
        body.toPercentage,
      );
    }
    case "resize-keyframed-tween": {
      return resizeKeyframedTweenInScript(
        block.scriptText,
        body.animationId,
        body.position,
        body.duration,
        body.pctRemap,
      );
    }
    case "update-keyframe": {
      return updateKeyframeInScript(
        block.scriptText,
        body.animationId,
        body.percentage,
        body.properties,
        body.ease,
      );
    }
    case "convert-to-keyframes": {
      return convertToKeyframesFromScript(
        block.scriptText,
        body.animationId,
        body.resolvedFromValues,
        body.duration,
      );
    }
    case "remove-all-keyframes": {
      const preCollapse = requireAnimation(block.scriptText, body.animationId);
      if (!("err" in preCollapse)) {
        bakeVisibilityOnDelete(block.document, preCollapse.anim);
      }
      return removeAllKeyframesFromScript(block.scriptText, body.animationId);
    }
    case "materialize-keyframes": {
      if (body.allElements && body.allElements.length > 0) {
        return unrollDynamicAnimations(block.scriptText, body.animationId, body.allElements);
      }
      return materializeKeyframesFromScript(
        block.scriptText,
        body.animationId,
        body.keyframes,
        body.easeEach,
        body.resolvedSelector,
      );
    }
    case "set-arc-path": {
      return setArcPathInScript(block.scriptText, body.animationId, {
        enabled: body.enabled,
        autoRotate: body.autoRotate ?? false,
        segments: body.segments ?? [],
      });
    }
    case "update-arc-segment": {
      return updateArcSegmentInScript(block.scriptText, body.animationId, body.segmentIndex, {
        ...(body.curviness !== undefined ? { curviness: body.curviness } : {}),
        ...(body.cp1 ? { cp1: body.cp1 } : {}),
        ...(body.cp2 ? { cp2: body.cp2 } : {}),
      });
    }
    case "update-motion-path-point": {
      return updateMotionPathPointInScript(block.scriptText, body.animationId, body.pointIndex, {
        x: body.x,
        y: body.y,
      });
    }
    case "add-motion-path-point": {
      return addMotionPathPointInScript(block.scriptText, body.animationId, body.index, {
        x: body.x,
        y: body.y,
      });
    }
    case "remove-motion-path-point": {
      return removeMotionPathPointInScript(block.scriptText, body.animationId, body.index);
    }
    case "add-motion-path": {
      return addMotionPathToScript(
        block.scriptText,
        body.targetSelector,
        body.position,
        body.duration,
        { x: body.x, y: body.y },
        body.ease,
      ).script;
    }
    case "remove-arc-path": {
      return removeArcPathFromScript(block.scriptText, body.animationId);
    }
    case "add-with-keyframes": {
      if (keyframesWritePosition(body.keyframes) || keyframesWriteRotation(body.keyframes)) {
        stripStudioEditsFromTarget(block.document, body.targetSelector);
      }
      const result = addAnimationWithKeyframesToScript(
        block.scriptText,
        body.targetSelector,
        body.position,
        body.duration,
        body.keyframes,
        body.ease,
        body.easeEach,
      );
      return result.script;
    }
    case "replace-with-keyframes": {
      if (keyframesWritePosition(body.keyframes) || keyframesWriteRotation(body.keyframes)) {
        stripStudioEditsFromTarget(block.document, body.targetSelector);
      }
      return replaceInPlaceUnlessSetOrUnknown(block.scriptText, body);
    }
    case "split-animations": {
      if (
        typeof body.originalId !== "string" ||
        !body.originalId ||
        typeof body.newId !== "string" ||
        !body.newId ||
        typeof body.splitTime !== "number" ||
        !Number.isFinite(body.splitTime) ||
        typeof body.elementStart !== "number" ||
        !Number.isFinite(body.elementStart) ||
        typeof body.elementDuration !== "number" ||
        !Number.isFinite(body.elementDuration) ||
        body.elementDuration <= 0
      ) {
        return respond(
          {
            error:
              "split-animations requires originalId, newId (non-empty strings), splitTime, elementStart (finite numbers), and elementDuration (positive number)",
          },
          400,
        );
      }
      return splitAnimationsInScript(block.scriptText, {
        originalId: body.originalId,
        newId: body.newId,
        splitTime: body.splitTime,
        elementStart: body.elementStart,
        elementDuration: body.elementDuration,
      });
    }
    case "split-into-property-groups": {
      const result = splitIntoPropertyGroupsFromScript(block.scriptText, body.animationId);
      return result.script;
    }
    case "unroll-timeline": {
      return unrollComputedTimeline(block.scriptText);
    }
    case "shift-positions-batch": {
      const shifts = body.shifts
        .filter((s) => s.targetSelector && Number.isFinite(s.delta) && s.delta !== 0)
        .map((s) => ({ kind: "shift" as const, targetSelector: s.targetSelector, delta: s.delta }));
      return retimeClipTweensInScript(block.scriptText, shifts, block.root).script;
    }
    case "shift-positions":
    case "scale-positions": {
      const retime = clipRetimeOf(body);
      return retime && retime !== "no-op"
        ? retimeClipTweensInScript(block.scriptText, [retime], block.root).script
        : block.scriptText;
    }
    default:
      return respond({ error: `unknown mutation type: ${(body as { type: string }).type}` }, 400);
  }
}

async function executeGsapMutationRecast(
  body: GsapMutationRequest,
  block: NonNullable<ReturnType<typeof extractGsapScriptBlock>>,
  respond: (data: unknown, status?: number) => Response,
): Promise<GsapMutationResult | Response> {
  const parser = await loadGsapParser();
  const {
    updateAnimationInScript,
    addAnimationToScript,
    removeAnimationFromScript,
    addKeyframeToScript,
    removeKeyframeFromScript,
    moveKeyframeInScript,
    resizeKeyframedTweenInScript,
    updateKeyframeInScript,
    convertToKeyframesInScript,
    removeAllKeyframesFromScript,
    materializeKeyframesInScript,
    unrollDynamicAnimations,
    setArcPathInScript,
    updateArcSegmentInScript,
    updateMotionPathPointInScript,
    addMotionPathPointInScript,
    removeMotionPathPointInScript,
    addMotionPathToScript,
    removeArcPathFromScript,
    addAnimationWithKeyframesToScript,
    splitAnimationsInScript,
    splitIntoPropertyGroups,
    dedupePositionWritesInScript,
  } = parser;

  function requireAnimation(
    scriptText: string,
    animationId: string,
  ): { anim: GsapAnimation } | { err: Response } {
    const parsed = parseGsapScriptAcorn(scriptText);
    const anim = parsed.animations.find((a) => a.id === animationId);
    if (!anim) return { err: respond({ error: "animation not found" }, 404) };
    return { anim };
  }

  function requireFromToAnimation(
    scriptText: string,
    animationId: string,
  ): { anim: GsapAnimation } | { err: Response } {
    const result = requireAnimation(scriptText, animationId);
    if ("err" in result) return result;
    if (result.anim.method !== "fromTo")
      return { err: respond({ error: "animation is not a fromTo" }, 400) };
    return result;
  }

  switch (body.type) {
    case "update-property":
    case "add-property": {
      const r = requireAnimation(block.scriptText, body.animationId);
      if ("err" in r) return r.err;
      const val = body.type === "update-property" ? body.value : body.defaultValue;
      return updateAnimationInScript(block.scriptText, body.animationId, {
        properties: { ...r.anim.properties, [body.property]: val },
      });
    }
    case "update-properties": {
      const r = requireAnimation(block.scriptText, body.animationId);
      if ("err" in r) return r.err;
      return updateAnimationInScript(block.scriptText, body.animationId, {
        properties: { ...r.anim.properties, ...body.properties },
      });
    }
    case "update-from-property":
    case "add-from-property": {
      const r = requireFromToAnimation(block.scriptText, body.animationId);
      if ("err" in r) return r.err;
      const val = body.type === "update-from-property" ? body.value : body.defaultValue;
      return updateAnimationInScript(block.scriptText, body.animationId, {
        fromProperties: { ...(r.anim.fromProperties ?? {}), [body.property]: val },
      });
    }
    case "update-meta": {
      return updateAnimationInScript(block.scriptText, body.animationId, body.updates);
    }
    case "add": {
      if (body.fromProperties && body.method !== "fromTo") {
        return respond({ error: "fromProperties is only valid for method=fromTo" }, 400);
      }
      // A new position/rotation animation owns that channel — strip the matching
      // legacy studio CSS var (--hf-studio-offset / --hf-studio-rotation) so it can't
      // double with the tween, matching add-with-keyframes/replace-with-keyframes.
      if (
        Object.keys(body.properties).some((k) => {
          const group = classifyPropertyGroup(k);
          return group === "position" || group === "rotation";
        })
      ) {
        stripStudioEditsFromTarget(block.document, body.targetSelector);
      }
      const result = addAnimationToScript(block.scriptText, {
        targetSelector: body.targetSelector,
        method: body.method,
        position: body.position,
        duration: body.duration,
        ease: body.ease,
        properties: body.properties,
        fromProperties: body.fromProperties,
        ...(body.global ? { global: true } : {}),
      });
      return result.script;
    }
    case "delete": {
      const delTarget = requireAnimation(block.scriptText, body.animationId);
      if (!("err" in delTarget) && body.stripStudioEdits) {
        stripStudioEditsFromTarget(block.document, delTarget.anim.targetSelector);
        bakeVisibilityOnDelete(block.document, delTarget.anim);
      }
      return removeAnimationFromScript(block.scriptText, body.animationId);
    }
    case "delete-all-for-selector": {
      const parsed = parseGsapScriptAcorn(block.scriptText);
      const matching = parsed.animations.filter((a) => a.targetSelector === body.targetSelector);
      if (matching.length === 0) return block.scriptText;
      stripStudioEditsFromTarget(block.document, body.targetSelector);
      let script = block.scriptText;
      for (const anim of matching.reverse()) {
        script = removeAnimationFromScript(script, anim.id);
      }
      return script;
    }
    case "consolidate-position-writes": {
      if (!body.targetSelector) return block.scriptText;
      return dedupePositionWritesInScript(
        block.scriptText,
        body.targetSelector,
        body.keepAnimationId,
      );
    }
    case "remove-property": {
      const r = requireAnimation(block.scriptText, body.animationId);
      if ("err" in r) return r.err;
      const filtered = { ...r.anim.properties };
      delete filtered[body.property];
      return updateAnimationInScript(block.scriptText, body.animationId, {
        properties: filtered,
      });
    }
    case "remove-from-property": {
      const r = requireFromToAnimation(block.scriptText, body.animationId);
      if ("err" in r) return r.err;
      const filtered = { ...(r.anim.fromProperties ?? {}) };
      delete filtered[body.property];
      return updateAnimationInScript(block.scriptText, body.animationId, {
        fromProperties: filtered,
      });
    }
    case "add-keyframe": {
      return addKeyframeToScript(
        block.scriptText,
        body.animationId,
        body.percentage,
        body.properties,
        body.ease,
        body.backfillDefaults,
      );
    }
    case "remove-keyframe": {
      return removeKeyframeFromScript(block.scriptText, body.animationId, body.percentage);
    }
    case "move-keyframe": {
      return moveKeyframeInScript(
        block.scriptText,
        body.animationId,
        body.fromPercentage,
        body.toPercentage,
      );
    }
    case "resize-keyframed-tween": {
      return resizeKeyframedTweenInScript(
        block.scriptText,
        body.animationId,
        body.position,
        body.duration,
        body.pctRemap,
      );
    }
    case "update-keyframe": {
      return updateKeyframeInScript(
        block.scriptText,
        body.animationId,
        body.percentage,
        body.properties,
        body.ease,
      );
    }
    case "convert-to-keyframes": {
      return convertToKeyframesInScript(
        block.scriptText,
        body.animationId,
        body.resolvedFromValues,
        body.duration,
      );
    }
    case "remove-all-keyframes": {
      const preCollapse = requireAnimation(block.scriptText, body.animationId);
      if (!("err" in preCollapse)) {
        bakeVisibilityOnDelete(block.document, preCollapse.anim);
      }
      return removeAllKeyframesFromScript(block.scriptText, body.animationId);
    }
    case "materialize-keyframes": {
      if (body.allElements && body.allElements.length > 0) {
        return unrollDynamicAnimations(block.scriptText, body.animationId, body.allElements);
      }
      return materializeKeyframesInScript(
        block.scriptText,
        body.animationId,
        body.keyframes,
        body.easeEach,
        body.resolvedSelector,
      );
    }
    case "set-arc-path": {
      return setArcPathInScript(block.scriptText, body.animationId, {
        enabled: body.enabled,
        autoRotate: body.autoRotate ?? false,
        segments: body.segments ?? [],
      });
    }
    case "update-arc-segment": {
      return updateArcSegmentInScript(block.scriptText, body.animationId, body.segmentIndex, {
        ...(body.curviness !== undefined ? { curviness: body.curviness } : {}),
        ...(body.cp1 ? { cp1: body.cp1 } : {}),
        ...(body.cp2 ? { cp2: body.cp2 } : {}),
      });
    }
    case "update-motion-path-point": {
      return updateMotionPathPointInScript(block.scriptText, body.animationId, body.pointIndex, {
        x: body.x,
        y: body.y,
      });
    }
    case "add-motion-path-point": {
      return addMotionPathPointInScript(block.scriptText, body.animationId, body.index, {
        x: body.x,
        y: body.y,
      });
    }
    case "remove-motion-path-point": {
      return removeMotionPathPointInScript(block.scriptText, body.animationId, body.index);
    }
    case "add-motion-path": {
      const result = addMotionPathToScript(
        block.scriptText,
        body.targetSelector,
        body.position,
        body.duration,
        { x: body.x, y: body.y },
        body.ease,
      );
      return result.script;
    }
    case "remove-arc-path": {
      return removeArcPathFromScript(block.scriptText, body.animationId);
    }
    case "add-with-keyframes": {
      if (keyframesWritePosition(body.keyframes) || keyframesWriteRotation(body.keyframes)) {
        stripStudioEditsFromTarget(block.document, body.targetSelector);
      }
      const result = addAnimationWithKeyframesToScript(
        block.scriptText,
        body.targetSelector,
        body.position,
        body.duration,
        body.keyframes,
        body.ease,
        body.easeEach,
      );
      return result.script;
    }
    case "replace-with-keyframes": {
      if (keyframesWritePosition(body.keyframes) || keyframesWriteRotation(body.keyframes)) {
        stripStudioEditsFromTarget(block.document, body.targetSelector);
      }
      return replaceInPlaceUnlessSetOrUnknown(block.scriptText, body);
    }
    case "split-animations": {
      if (
        typeof body.originalId !== "string" ||
        !body.originalId ||
        typeof body.newId !== "string" ||
        !body.newId ||
        typeof body.splitTime !== "number" ||
        !Number.isFinite(body.splitTime) ||
        typeof body.elementStart !== "number" ||
        !Number.isFinite(body.elementStart) ||
        typeof body.elementDuration !== "number" ||
        !Number.isFinite(body.elementDuration) ||
        body.elementDuration <= 0
      ) {
        return respond(
          {
            error:
              "split-animations requires originalId, newId (non-empty strings), splitTime, elementStart (finite numbers), and elementDuration (positive number)",
          },
          400,
        );
      }
      return splitAnimationsInScript(block.scriptText, {
        originalId: body.originalId,
        newId: body.newId,
        splitTime: body.splitTime,
        elementStart: body.elementStart,
        elementDuration: body.elementDuration,
      });
    }
    case "split-into-property-groups": {
      const result = splitIntoPropertyGroups(block.scriptText, body.animationId);
      return result.script;
    }
    case "unroll-timeline": {
      return unrollComputedTimeline(block.scriptText);
    }
    case "shift-positions": {
      const { targetSelector, delta } = body;
      if (!targetSelector || !Number.isFinite(delta) || delta === 0) return block.scriptText;
      const { shiftPositionsInScript } = parser;
      return shiftPositionsInScript(block.scriptText, targetSelector, delta, block.root);
    }
    case "shift-positions-batch": {
      const { shiftPositionsInScript } = parser;
      let script = block.scriptText;
      for (const s of body.shifts) {
        if (!s.targetSelector || !Number.isFinite(s.delta) || s.delta === 0) continue;
        script = shiftPositionsInScript(script, s.targetSelector, s.delta, block.root);
      }
      return script;
    }
    case "scale-positions": {
      const { targetSelector, oldStart, oldDuration, newStart, newDuration } = body;
      if (
        !targetSelector ||
        !Number.isFinite(oldStart) ||
        !Number.isFinite(oldDuration) ||
        !Number.isFinite(newStart) ||
        !Number.isFinite(newDuration) ||
        oldDuration <= 0 ||
        newDuration <= 0
      )
        return block.scriptText;
      if (oldStart === newStart && oldDuration === newDuration) return block.scriptText;
      const { scalePositionsInScript } = parser;
      return scalePositionsInScript(
        block.scriptText,
        targetSelector,
        oldStart,
        oldDuration,
        newStart,
        newDuration,
        block.root,
      );
    }
    default:
      return respond({ error: `unknown mutation type: ${(body as { type: string }).type}` }, 400);
  }
}

interface FoldedAtomicCutFile {
  path: string;
  absPath: string;
  before: string;
  after: string;
  splitCount: number;
  skippedSelectors: string[];
}

/** Fold every split and optional GSAP retarget for one file without touching disk. */
async function foldAtomicCutFile(
  c: RouteContext,
  file: AtomicCutFileRequest,
  absPath: string,
  before: string,
  writer: "recast" | "acorn",
): Promise<FoldedAtomicCutFile | Response> {
  let after = before;
  let splitCount = 0;
  const skippedSelectors = new Set<string>();
  const rightHalfIds: string[] = [];
  const respond = (data: unknown, status?: number) =>
    status ? c.json(data, status) : c.json(data);

  const orderedTargets = file.targets
    .map((cut, index) => ({ cut, index }))
    .sort((left, right) => {
      const locatorKey = (entry: AtomicCutTarget): string | null =>
        !entry.target.id && !entry.target.hfId && entry.target.selector
          ? entry.target.selector
          : null;
      const leftKey = locatorKey(left.cut);
      const rightKey = locatorKey(right.cut);
      if (leftKey && rightKey) {
        return (
          leftKey.localeCompare(rightKey) ||
          (right.cut.target.selectorIndex ?? 0) - (left.cut.target.selectorIndex ?? 0)
        );
      }
      if (leftKey) return -1;
      if (rightKey) return 1;
      return left.index - right.index;
    })
    .map(({ cut }) => cut);
  for (const cut of orderedTargets) {
    const baseId = cut.originalId || cut.target.id || "clip";
    const split = splitElementInHtml(after, cut.target, cut.splitTime, `${baseId}-split`, {
      start: cut.elementStart,
      duration: cut.elementDuration,
      playbackStart: cut.playbackStart,
      playbackRate: cut.playbackRate,
      track: cut.track,
    });
    if (!split.matched || !split.newId) {
      return c.json(
        { error: `Cut target was not found or was outside its authored bounds in ${file.path}` },
        400,
      );
    }
    after = split.html;
    splitCount++;
    rightHalfIds.push(split.newId);

    if (!cut.originalId) continue;
    const block = extractGsapScriptBlock(after);
    if (!block) continue;
    const result = await executeGsapMutation(
      {
        type: "split-animations",
        originalId: cut.originalId,
        newId: split.newId,
        splitTime: cut.splitTime,
        elementStart: cut.elementStart,
        elementDuration: cut.elementDuration,
      },
      block,
      respond,
      writer,
    );
    if (result instanceof Response) return result;
    let script = typeof result === "string" ? result : result.script;
    if (typeof result !== "string") {
      for (const selector of result.skippedSelectors) skippedSelectors.add(selector);
    }
    if (script !== block.scriptText) {
      script =
        writer === "acorn"
          ? syncPositionHoldsBeforeKeyframes(script, block.scriptText)
          : (await loadGsapParser()).syncPositionHoldsBeforeKeyframes(script, block.scriptText);
      after = block.replaceScript(script);
    }
  }

  after = relinkSplitHalvesInHtml(after, rightHalfIds);
  return {
    path: file.path,
    absPath,
    before,
    after,
    splitCount,
    skippedSelectors: [...skippedSelectors],
  };
}

// ── Upload file processing ──────────────────────────────────────────────────

export const MAX_UPLOAD_BYTES = 500 * 1024 * 1024;

async function processUploadedFiles(
  formData: FormData,
  targetDir: string,
  projectDir: string,
): Promise<{
  uploaded: string[];
  skipped: string[];
  invalid: Array<{ name: string; reason: string }>;
  unchecked: Array<{ name: string; reason: string }>;
}> {
  const uploaded: string[] = [];
  const skipped: string[] = [];
  const invalid: Array<{ name: string; reason: string }> = [];
  const unchecked: Array<{ name: string; reason: string }> = [];

  // @types/node v25 narrows the ambient `FormData.entries()` to
  // `[string, string]` in workspaces where another dep declares an
  // `onmessage` global (it trips the worker branch of v25's conditional
  // File type). At runtime the value is still `File | string` — cast the
  // iterator so the rest of this block keeps type-checking on every
  // bun-install layout (hoisted on Windows surfaces this; isolated on
  // Linux happens to keep v24 in scope).
  type FileLike = {
    readonly name: string;
    readonly size: number;
    arrayBuffer(): Promise<ArrayBuffer>;
  };
  const entries = formData.entries() as unknown as Iterable<[string, FileLike | string]>;

  // Derive the subdirectory prefix from targetDir relative to projectDir
  const subDir = targetDir === projectDir ? "" : targetDir.slice(projectDir.length + 1);

  for (const [, value] of entries) {
    if (typeof value === "string") continue;

    // Strip path separators — browsers may include directory components
    const name = value.name.split("/").pop()?.split("\\").pop() ?? "";
    if (!name || name.includes("\0") || name.includes("..")) continue;

    // Reject individual files that exceed the size limit
    if (value.size > MAX_UPLOAD_BYTES) {
      skipped.push(name);
      continue;
    }

    const destPath = resolve(targetDir, name);
    if (!isSafePath(projectDir, destPath)) continue;

    // Don't overwrite — append (2), (3), etc.
    let finalPath = destPath;
    let finalName = name;
    // Handle dotfiles correctly: .gitignore → ext="", base=".gitignore"
    const dotIdx = name.indexOf(".", name.startsWith(".") ? 1 : 0);
    const ext = dotIdx > 0 ? name.slice(dotIdx) : "";
    const base = dotIdx > 0 ? name.slice(0, dotIdx) : name;
    const MAX_COPY_INDEX = 10000;
    let n = 1;
    if (existsSync(finalPath)) {
      n = 2;
      while (n < MAX_COPY_INDEX && existsSync(resolve(targetDir, `${base} (${n})${ext}`))) n++;
      if (n >= MAX_COPY_INDEX) {
        skipped.push(name);
        continue;
      }
      finalName = `${base} (${n})${ext}`;
      finalPath = resolve(targetDir, finalName);
    }

    // The collision suffix chooses a different path; validate that destination
    // too, including dangling symlinks that existsSync treats as absent.
    if (!isSafePath(projectDir, finalPath) || isPrivateProjectFile(projectDir, finalPath)) continue;

    const buffer = Buffer.from(await value.arrayBuffer());
    const validation = validateUploadedMediaBuffer(finalName, buffer);
    if (!validation.ok) {
      invalid.push({ name: finalName, reason: validation.reason });
      continue;
    }

    // Reading the upload yields: another request can claim the selected name.
    // Only exclusive creation authorizes a write; retry collisions without
    // following a newly planted link or overwriting another upload.
    let written = false;
    while (n < MAX_COPY_INDEX && isSafePath(projectDir, finalPath)) {
      try {
        createFileAtomically(finalPath, buffer);
        written = true;
        break;
      } catch (error) {
        if (!(error instanceof Error) || !("code" in error) || error.code !== "EEXIST") {
          throw error;
        }
        n++;
        finalName = `${base} (${n})${ext}`;
        finalPath = resolve(targetDir, finalName);
      }
    }
    if (!written) {
      if (n >= MAX_COPY_INDEX) skipped.push(name);
      continue;
    }
    const relativePath = subDir ? join(subDir, finalName) : finalName;
    uploaded.push(relativePath);
    if (validation.unchecked) unchecked.push({ name: finalName, reason: validation.unchecked });
    if (isAudioFile(finalName)) {
      generateWaveformCache(projectDir, relativePath).catch(() => {});
    }
  }

  return { uploaded, skipped, invalid, unchecked };
}

// ── Route registration ──────────────────────────────────────────────────────

const MAX_TEXT_READ_BYTES = 32 * 1024 * 1024;
const GIT_BINARY_SNIFF_BYTES = 8000;

export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
  // ── Read ──

  api.get("/projects/:id/files/*", async (c) => {
    const res = await resolveProjectFile(c, adapter);
    if ("error" in res) return res.error;

    // Opened once and checked/read through the same descriptor, not the path,
    // so a directory-for-file swap (or anything else) between the check below
    // and the read can't land a stale answer — both act on the identical inode.
    let fd: number;
    try {
      fd = openSync(res.absPath, "r");
    } catch {
      if (c.req.query("optional") === "1") {
        // `missing: true` separates the absent-file shim from a genuinely
        // 0-byte file — both answer `content: ""`, and the caller could not
        // tell them apart. That ambiguity hid the largest remaining class of
        // SDK-session failures: a composition the file tree lists but this
        // read answers empty for is either a placeholder nobody has written
        // yet, or a path that does not resolve here at all, and those need
        // different fixes. Additive, so an older client ignores it.
        return c.json({ filename: res.filePath, content: "", missing: true });
      }
      return c.json({ error: "not found" }, 404);
    }
    try {
      // A listing built from `walkDir` can show a path that has since been
      // replaced by a directory (a rename, or an agent overwriting a file
      // with a folder of the same name) — opening it succeeds (POSIX allows
      // O_RDONLY on a directory), and reading it would throw `EISDIR`, which
      // Hono answers as a plain-text 500. The caller already handles a 404
      // with `why`; this reports the same shape instead of an opaque server
      // error for something that is not one.
      const stat = fstatSync(fd);
      if (!stat.isFile()) {
        return c.json({ error: "not found", why: "not_a_file" }, 404);
      }
      if (stat.size > MAX_TEXT_READ_BYTES) {
        return c.json({ error: "too large to read as text", why: "too_large" }, 413);
      }

      const content = readFileSync(fd);
      const version = fileContentVersion(content);
      c.header("ETag", version);
      if (content.subarray(0, GIT_BINARY_SNIFF_BYTES).includes(0)) {
        return c.json({ error: "not a text file", why: "binary", version }, 415);
      }
      // `missing: false` on the read path too, so its PRESENCE is what tells a
      // caller this server distinguishes the two empty answers at all. Without
      // it here, a real 0-byte file from a new server looks exactly like either
      // case from an old one, and the split above buys nothing.
      return c.json({
        filename: res.filePath,
        content: content.toString("utf-8"),
        version,
        missing: false,
      });
    } finally {
      closeSync(fd);
    }
  });

  // ── Write (overwrite) ──

  api.put("/projects/:id/files/*", async (c) => {
    const res = await resolveProjectFile(c, adapter, { pin: true });
    if ("error" in res) return res.error;

    const body = Buffer.from(await c.req.arrayBuffer());
    const expectedVersion = c.req.header("If-Match")?.trim() ?? null;
    const createOnly = c.req.header("If-None-Match")?.trim() === "*";
    if (expectedVersion === null && !createOnly) {
      let currentContent: Buffer | null = null;
      try {
        currentContent = readFileSync(res.absPath);
      } catch (error) {
        if (!error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") {
          throw error;
        }
      }
      return c.json(
        {
          error: "precondition required",
          path: res.filePath,
          currentVersion: currentContent === null ? null : fileContentVersion(currentContent),
          currentContent: currentContent?.toString("utf-8") ?? null,
        },
        428,
      );
    }

    let backup: ReturnType<typeof snapshotBeforeWrite> = { backupPath: null };
    let overwrote: Buffer | undefined;
    if (createOnly) {
      ensureDir(res.project.dir, res.absPath);
      try {
        createFileAtomically(res.absPath, body);
      } catch (error) {
        if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST") {
          throw error;
        }
        const currentContent = readFileSync(res.absPath);
        return c.json(
          {
            error: "file conflict",
            path: res.filePath,
            currentVersion: fileContentVersion(currentContent),
            currentContent: currentContent.toString("utf-8"),
          },
          409,
        );
      }
    } else {
      let fd: number | null;
      try {
        fd = openSync(res.absPath, "r+");
      } catch (error) {
        if (!error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") {
          throw error;
        }
        return c.json(
          {
            error: "file conflict",
            path: res.filePath,
            currentVersion: null,
            currentContent: null,
          },
          409,
        );
      }
      try {
        const currentContent = readFileSync(fd);
        overwrote = currentContent;
        const currentVersion = fileContentVersion(currentContent);
        if (expectedVersion !== currentVersion) {
          return c.json(
            {
              error: "file conflict",
              path: res.filePath,
              currentVersion,
              currentContent: currentContent.toString("utf-8"),
            },
            409,
          );
        }
        backup = snapshotBeforeWrite(res.project.dir, res.absPath);
        if (backup.error) return c.json({ error: `backup failed: ${backup.error}` }, 500);
        const mode = fstatSync(fd).mode;
        closeSync(fd);
        fd = null;
        replaceFileAtomically(res.absPath, body, mode);
      } finally {
        if (fd !== null) closeSync(fd);
      }
    }
    const version = fileContentVersion(body);
    const writeToken = createWriteToken(c.req.header("X-Hyperframes-Write-Token"));
    recordFileWriteReceipt(res.absPath, { path: res.filePath, version, writeToken, overwrote });
    c.header("ETag", version);

    return c.json({
      ok: true,
      path: res.filePath,
      version,
      writeToken,
      backupPath: backupPathForResponse(res.project.dir, backup.backupPath),
    });
  });

  // ── Create (fail if exists) ──

  api.post("/projects/:id/files/*", async (c) => {
    const res = await resolveProjectFile(c, adapter);
    if ("error" in res) return res.error;

    ensureDir(res.project.dir, res.absPath);
    const body = Buffer.from(await c.req.arrayBuffer());
    try {
      createFileAtomically(res.absPath, body);
    } catch (error) {
      if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST") {
        throw error;
      }
      return c.json({ error: "already exists" }, 409);
    }

    return c.json({ ok: true, path: res.filePath }, 201);
  });

  // ── Delete ──

  api.delete("/projects/:id/files/*", async (c) => {
    const res = await resolveProjectFile(c, adapter, { mustExist: true });
    if ("error" in res) return res.error;

    const stat = statSync(res.absPath);
    const backup = snapshotBeforeWrite(res.project.dir, res.absPath);
    if (backup.error) return c.json({ error: `backup failed: ${backup.error}` }, 500);
    if (stat.isDirectory()) {
      rmSync(res.absPath, { recursive: true });
    } else {
      unlinkSync(res.absPath);
    }

    return c.json({
      ok: true,
      backupPath: backupPathForResponse(res.project.dir, backup.backupPath),
    });
  });

  api.post("/projects/:id/file-mutations/insert-composition/*", async (c) => {
    const ctx = await resolveFileMutationContext(c, adapter, "insert-composition");
    if ("error" in ctx) return ctx.error;

    const body = (await c.req.json().catch(() => null)) as {
      sourcePath?: unknown;
      start?: unknown;
      track?: unknown;
      expectedVersion?: unknown;
    } | null;
    if (
      !body ||
      typeof body.sourcePath !== "string" ||
      typeof body.start !== "number" ||
      !Number.isFinite(body.start) ||
      body.start < 0 ||
      typeof body.track !== "number" ||
      !Number.isFinite(body.track) ||
      typeof body.expectedVersion !== "string"
    ) {
      return c.json({ error: "sourcePath, finite placement, and expectedVersion required" }, 400);
    }

    let before: string;
    try {
      before = readFileSync(ctx.absPath, "utf-8");
    } catch (error) {
      if (!error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") {
        throw error;
      }
      return c.json({ error: "not found" }, 404);
    }
    const currentVersion = fileContentVersion(before);
    if (body.expectedVersion !== currentVersion) {
      return c.json({ error: "file conflict", currentVersion, currentContent: before }, 409);
    }

    let insertion: ReturnType<typeof insertCompositionIntoSource>;
    try {
      insertion = insertCompositionIntoSource({
        projectDir: ctx.project.dir,
        targetPath: ctx.filePath,
        sourcePath: body.sourcePath,
        parentSource: before,
        start: body.start,
        desiredTrack: body.track,
      });
    } catch (error) {
      if (error instanceof CompositionInsertionError) {
        return c.json({ error: error.message }, error.status);
      }
      throw error;
    }

    const backup = snapshotBeforeWrite(ctx.project.dir, ctx.absPath);
    if (backup.error) return c.json({ error: `backup failed: ${backup.error}` }, 500);
    const current = readFileSync(ctx.absPath, "utf-8");
    if (current !== before) {
      const currentVersion = fileContentVersion(current);
      return c.json({ error: "file conflict", currentVersion, currentContent: current }, 409);
    }
    const { version, writeToken } = writeFileWithReceipt(
      c,
      ctx.filePath,
      ctx.absPath,
      insertion.html,
    );
    c.header("ETag", version);
    return c.json({
      ok: true,
      path: ctx.filePath,
      hostId: insertion.hostId,
      track: insertion.track,
      duration: insertion.duration,
      before,
      after: insertion.html,
      version,
      writeToken,
      backupPath: backupPathForResponse(ctx.project.dir, backup.backupPath),
    });
  });

  api.post("/projects/:id/file-mutations/remove-element/*", async (c) => {
    const ctx = await resolveFileMutationContext(c, adapter, "remove-element");
    if ("error" in ctx) return ctx.error;

    if (!existsSync(ctx.absPath)) {
      return c.json({ error: "not found" }, 404);
    }

    const parsed = await parseMutationBody<{ target?: MutationTarget }>(c);
    if ("error" in parsed) return parsed.error;

    const originalContent = readFileSync(ctx.absPath, "utf-8");
    return writeIfChanged(
      c,
      ctx.project.dir,
      ctx.filePath,
      ctx.absPath,
      originalContent,
      removeElementFromHtml(originalContent, parsed.target),
    );
  });

  // Removing a marquee selection one element at a time meant one request and
  // one rewrite of the whole file per element. A canvas selection runs to
  // hundreds of members, so a single Delete press became hundreds of serial
  // round trips: the file ended up correct, but only after long enough that the
  // key looked like it had done nothing at all.
  api.post("/projects/:id/file-mutations/remove-elements/*", async (c) => {
    const ctx = await resolveFileMutationContext(c, adapter, "remove-elements");
    if ("error" in ctx) return ctx.error;

    if (!existsSync(ctx.absPath)) {
      return c.json({ error: "not found" }, 404);
    }

    const body = (await c.req.json().catch(() => null)) as { targets?: MutationTarget[] } | null;
    const targets = body?.targets;
    if (!Array.isArray(targets) || targets.length === 0) {
      return c.json({ error: "targets required" }, 400);
    }

    const originalContent = readFileSync(ctx.absPath, "utf-8");
    // The response says whether the file changed, not how many of the targets landed, so a
    // caller can tell a no-op from a write, but not a partial pass from a complete one.
    return writeIfChanged(
      c,
      ctx.project.dir,
      ctx.filePath,
      ctx.absPath,
      originalContent,
      removeElementsFromHtml(originalContent, targets),
    );
  });

  api.post("/projects/:id/file-mutations/split-batch", async (c) => {
    const body = (await c.req.json().catch(() => null)) as {
      files?: unknown;
      transactionToken?: unknown;
    } | null;
    if (
      !Array.isArray(body?.files) ||
      body.files.length === 0 ||
      !body.files.every(isAtomicCutFileRequest)
    ) {
      return c.json({ error: "files with path, expectedVersion, and cut targets required" }, 400);
    }
    const files = body.files as AtomicCutFileRequest[];
    const project = await adapter.resolveProject(c.req.param("id"));
    if (!project) return c.json({ error: "not found" }, 404);
    let writer: "recast" | "acorn";
    try {
      writer = resolveGsapWriter({
        HYPERFRAMES_GSAP_WRITER: process.env["HYPERFRAMES_GSAP_WRITER"],
      });
    } catch (error) {
      return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
    }

    return serializeAtomicCut(async () => {
      const seen = new Set<string>();
      const prepared: FoldedAtomicCutFile[] = [];
      for (const file of files) {
        const absPath = pinWithinProject(project.dir, file.path);
        if (!absPath) return c.json({ error: `forbidden path: ${file.path}` }, 403);
        if (seen.has(absPath)) return c.json({ error: `duplicate path: ${file.path}` }, 400);
        seen.add(absPath);

        let before: string;
        try {
          before = readFileSync(absPath, "utf-8");
        } catch {
          return c.json({ error: `not found: ${file.path}` }, 404);
        }
        const currentVersion = fileContentVersion(before);
        if (currentVersion !== file.expectedVersion) {
          return c.json(
            {
              error: `file conflict: ${file.path}`,
              path: file.path,
              currentVersion,
              currentContent: before,
            },
            409,
          );
        }
        let folded: FoldedAtomicCutFile | Response;
        try {
          folded = await foldAtomicCutFile(c, file, absPath, before, writer);
        } catch (error) {
          const message = error instanceof Error ? error.message : "Cut transform failed";
          return c.json({ error: message }, 400);
        }
        if (folded instanceof Response) return folded;
        prepared.push(folded);
      }

      // Lazy GSAP parsing above can yield; revalidate every base before the first write.
      for (const file of prepared) {
        const current = readFileSync(file.absPath, "utf-8");
        if (current !== file.before) {
          return c.json(
            {
              error: `file conflict: ${file.path}`,
              path: file.path,
              currentVersion: fileContentVersion(current),
              currentContent: current,
            },
            409,
          );
        }
      }

      const backups = new Map<string, string | null>();
      for (const file of prepared) {
        const backup = snapshotBeforeWrite(project.dir, file.absPath);
        if (backup.error) {
          return c.json(
            { error: `Failed to create backup for ${file.path}: ${backup.error}` },
            500,
          );
        }
        backups.set(file.path, backupPathForResponse(project.dir, backup.backupPath));
      }

      const writeToken = createWriteToken(
        typeof body.transactionToken === "string"
          ? body.transactionToken
          : c.req.header("X-Hyperframes-Write-Token"),
      );
      const written: FoldedAtomicCutFile[] = [];
      try {
        for (const file of prepared) {
          replaceFileAtomically(file.absPath, file.after, statSync(file.absPath).mode);
          written.push(file);
          recordFileWriteReceipt(file.absPath, {
            path: file.path,
            version: fileContentVersion(file.after),
            writeToken,
            overwrote: file.before,
          });
        }
      } catch (error) {
        const conflicts: string[] = [];
        for (const file of written.reverse()) {
          try {
            const current = readFileSync(file.absPath, "utf-8");
            if (current !== file.after) {
              conflicts.push(file.path);
              continue;
            }
            replaceFileAtomically(file.absPath, file.before, statSync(file.absPath).mode);
            recordFileWriteReceipt(file.absPath, {
              path: file.path,
              version: fileContentVersion(file.before),
              writeToken,
            });
          } catch {
            conflicts.push(file.path);
          }
        }
        return c.json(
          {
            error: error instanceof Error ? error.message : "Cut write failed",
            outcome: conflicts.length ? "aborted-with-conflicts" : "aborted-restored",
            conflicts,
          },
          conflicts.length ? 409 : 500,
        );
      }

      const result = prepared.map((file) => ({
        path: file.path,
        before: file.before,
        after: file.after,
        version: fileContentVersion(file.after),
        writeToken,
        backupPath: backups.get(file.path) ?? null,
        splitCount: file.splitCount,
        skippedSelectors: file.skippedSelectors,
      }));
      return c.json({ ok: true, outcome: "committed", files: result });
    });
  });

  api.post("/projects/:id/file-mutations/split-element/*", async (c) => {
    const ctx = await resolveFileMutationContext(c, adapter, "split-element");
    if ("error" in ctx) return ctx.error;

    const parsed = await parseMutationBody<{
      target?: { id?: string; selector?: string; selectorIndex?: number };
      splitTime?: number;
      newId?: string;
      elementStart?: number;
      elementDuration?: number;
    }>(c);
    if ("error" in parsed) return parsed.error;
    if (typeof parsed.body.splitTime !== "number" || !parsed.body.newId) {
      return c.json({ error: "target, splitTime, and newId required" }, 400);
    }
    const fallbackTiming =
      typeof parsed.body.elementStart === "number" &&
      typeof parsed.body.elementDuration === "number"
        ? { start: parsed.body.elementStart, duration: parsed.body.elementDuration }
        : undefined;

    let originalContent: string;
    try {
      originalContent = readFileSync(ctx.absPath, "utf-8");
    } catch {
      return c.json({ error: "not found" }, 404);
    }
    const result = splitElementInHtml(
      originalContent,
      parsed.target,
      parsed.body.splitTime,
      parsed.body.newId,
      fallbackTiming,
    );
    if (!result.matched) {
      const version = fileContentVersion(originalContent);
      c.header("ETag", version);
      return c.json({
        ok: false,
        changed: false,
        content: originalContent,
        path: ctx.filePath,
        version,
      });
    }
    const mutationResult = writeMutationResult(
      c,
      ctx.project.dir,
      ctx.filePath,
      ctx.absPath,
      result.html,
      originalContent,
    );
    if (mutationResult instanceof Response) return mutationResult;
    const { version, backupPath } = mutationResult;
    c.header("ETag", version);
    return c.json({
      ok: true,
      changed: true,
      content: result.html,
      newId: result.newId,
      path: ctx.filePath,
      version,
      backupPath,
    });
  });

  api.post("/projects/:id/file-mutations/patch-element/*", async (c) => {
    const ctx = await resolveFileMutationContext(c, adapter, "patch-element");
    if ("error" in ctx) return ctx.error;

    const parsed = await parseMutationBody<{
      target?: MutationTarget;
      operations?: PatchOperation[];
      fontFaceCss?: unknown;
    }>(c);
    if ("error" in parsed) return parsed.error;
    if (!Array.isArray(parsed.body.operations) || parsed.body.operations.length === 0) {
      return c.json({ error: "target and operations required" }, 400);
    }
    const { fontFaceCss } = parsed.body;
    if (fontFaceCss !== undefined && !isStudioFontFaceCss(fontFaceCss)) {
      return c.json({ error: "fontFaceCss must be one @font-face rule" }, 400);
    }
    const unsafeFields = findUnsafeDomPatchValues(parsed.body);
    if (unsafeFields.length > 0) {
      return rejectUnsafeMutationValues(c, unsafeFields);
    }

    for (let attempt = 1; ; attempt += 1) {
      let originalContent: string;
      try {
        originalContent = readFileSync(ctx.absPath, "utf-8");
      } catch {
        return c.json({ error: "not found" }, 404);
      }
      const takenIds = parsed.body.operations.some((op) => op.type === "ensure-id")
        ? projectHtmlIds(ctx.project.dir)
        : undefined;
      const element = patchElementInHtml(
        originalContent,
        parsed.target,
        parsed.body.operations,
        takenIds,
      );
      const { matched } = element;
      const patched =
        matched && isStudioFontFaceCss(fontFaceCss)
          ? ensureStudioFontFaceCss(element.html, fontFaceCss)
          : element.html;
      if (patched === originalContent) {
        const version = fileContentVersion(originalContent);
        c.header("ETag", version);
        return c.json({
          ok: true,
          changed: false,
          matched,
          elementId: element.elementId,
          content: originalContent,
          path: ctx.filePath,
          version,
        });
      }
      const mutationResult = writeMutationResult(
        c,
        ctx.project.dir,
        ctx.filePath,
        ctx.absPath,
        patched,
        originalContent,
      );
      if (mutationResult instanceof Response) {
        if (mutationResult.status === 409 && attempt < PATCH_CONFLICT_ATTEMPTS) continue;
        return mutationResult;
      }
      const { backupPath, version } = mutationResult;
      c.header("ETag", version);
      return c.json({
        ok: true,
        changed: true,
        matched,
        elementId: element.elementId,
        content: patched,
        path: ctx.filePath,
        version,
        backupPath,
      });
    }
  });

  api.post("/projects/:id/file-mutations/patch-element-batches", async (c) => {
    const project = await adapter.resolveProject(c.req.param("id"));
    if (!project) return c.json({ error: "not found" }, 404);

    const body: unknown = await c.req.json().catch(() => null);
    if (
      typeof body !== "object" ||
      body === null ||
      !("batches" in body) ||
      !Array.isArray(body.batches) ||
      body.batches.length === 0 ||
      !body.batches.every(isElementPatchBatchRequest)
    ) {
      return c.json({ error: "batches with sourceFile and patches required" }, 400);
    }
    const unsafeFields = findUnsafeElementPatchBatchValues(body.batches);
    if (unsafeFields.length > 0) return rejectUnsafeMutationValues(c, unsafeFields);

    const result = commitElementPatchBatchesWithReceipts(c, project.dir, body.batches);
    if ("error" in result) {
      return elementPatchBatchCommitErrorResponse(c, result.error, result.sourceFile);
    }
    return c.json(result);
  });

  api.post("/projects/:id/file-mutations/patch-elements-batch/*", async (c) => {
    const ctx = await resolveFileMutationContext(c, adapter, "patch-elements-batch");
    if ("error" in ctx) return ctx.error;

    const body = (await c.req.json().catch(() => null)) as {
      patches?: ElementPatchRequest[];
    } | null;
    if (
      !body ||
      !Array.isArray(body.patches) ||
      body.patches.length === 0 ||
      !body.patches.every(isElementPatchRequest)
    ) {
      return c.json({ error: "patches with target and operations required" }, 400);
    }
    const batch = { sourceFile: ctx.filePath, patches: body.patches };
    const unsafeFields = findUnsafeElementPatchBatchValues([batch]);
    if (unsafeFields.length > 0) {
      return rejectUnsafeMutationValues(c, unsafeFields);
    }

    const result = commitElementPatchBatchesWithReceipts(c, ctx.project.dir, [batch]);
    if ("error" in result) {
      return elementPatchBatchCommitErrorResponse(c, result.error, result.sourceFile);
    }
    const file = result.files[0];
    if (!file) return c.json({ error: "empty element patch result" }, 500);
    return c.json({
      ok: true,
      changed: file.changed,
      matched: file.matched,
      content: file.after,
      path: file.sourceFile,
      backupPath: file.backupPath,
    });
  });

  api.post("/projects/:id/file-mutations/wrap-elements/*", async (c) => {
    const ctx = await resolveFileMutationContext(c, adapter, "wrap-elements");
    if ("error" in ctx) return ctx.error;

    const body = (await c.req.json().catch(() => null)) as {
      targets?: MutationTarget[];
      groupId?: string;
      bbox?: { left?: number; top?: number; width?: number; height?: number };
      rebases?: ElementRebase[];
    } | null;
    if (!Array.isArray(body?.targets) || body.targets.length === 0 || !body.groupId) {
      return c.json({ error: "targets and groupId required" }, 400);
    }
    // left/top/width/height are interpolated into inline style strings; reject
    // anything non-numeric so a crafted value can't inject extra declarations.
    const bbox = body.bbox ?? {};
    const bboxNums = [bbox.left, bbox.top, bbox.width, bbox.height];
    const rebases = body.rebases ?? [];
    const allNumeric =
      bboxNums.every((n) => typeof n === "number" && Number.isFinite(n)) &&
      rebases.every(
        (r) =>
          typeof r?.left === "number" &&
          Number.isFinite(r.left) &&
          typeof r?.top === "number" &&
          Number.isFinite(r.top) &&
          isOptionalInteger(r?.track),
      );
    if (!allNumeric) {
      return c.json({ error: "bbox and rebase coordinates must be finite numbers" }, 400);
    }

    let originalContent: string;
    try {
      originalContent = readFileSync(ctx.absPath, "utf-8");
    } catch {
      return c.json({ error: "not found" }, 404);
    }
    const result = wrapElementsInHtml(
      originalContent,
      body.targets,
      body.groupId,
      { left: bbox.left!, top: bbox.top!, width: bbox.width!, height: bbox.height! },
      rebases,
    );
    if (!result.matched) {
      return c.json(
        {
          ok: false,
          changed: false,
          content: originalContent,
          path: ctx.filePath,
          error: result.error,
        },
        result.error === "grouped elements must share a single parent" ? 422 : 400,
      );
    }
    const mutationResult = writeMutationResult(
      c,
      ctx.project.dir,
      ctx.filePath,
      ctx.absPath,
      result.html,
      originalContent,
    );
    if (mutationResult instanceof Response) return mutationResult;
    const { backupPath } = mutationResult;
    return c.json({
      ok: true,
      changed: true,
      groupId: result.groupId,
      content: result.html,
      path: ctx.filePath,
      backupPath,
    });
  });

  api.post("/projects/:id/file-mutations/unwrap-elements/*", async (c) => {
    const ctx = await resolveFileMutationContext(c, adapter, "unwrap-elements");
    if ("error" in ctx) return ctx.error;

    const parsed = await parseMutationBody<{
      target?: MutationTarget;
      childTracks?: Array<{ target?: MutationTarget; track?: number }>;
    }>(c);
    if ("error" in parsed) return parsed.error;

    const rawChildTracks = parsed.body.childTracks ?? [];
    if (!rawChildTracks.every((entry) => isOptionalInteger(entry?.track))) {
      return c.json({ error: "childTracks track must be a finite integer" }, 400);
    }
    const childTracks = rawChildTracks
      .filter((entry): entry is { target: MutationTarget; track?: number } =>
        Boolean(entry?.target),
      )
      .map((entry) => ({ target: entry.target, track: entry.track }));

    let originalContent: string;
    try {
      originalContent = readFileSync(ctx.absPath, "utf-8");
    } catch {
      return c.json({ error: "not found" }, 404);
    }
    const result = unwrapElementsFromHtml(originalContent, parsed.target, childTracks);
    if (!result.unwrapped) {
      return c.json({ ok: false, changed: false, content: originalContent, path: ctx.filePath });
    }
    // BAKE the group's static transform into the members FIRST, so the group's
    // accumulated moves are preserved (otherwise members snap back to their
    // creation-time positions), THEN strip the group's GSAP — a leftover
    // `gsap.set("#group-1")` throws "target not found" every preview run.
    let cleaned = result.html;
    if (result.unwrappedGroupId && result.members && result.groupCenter) {
      cleaned = bakeGroupTransformIntoMembers(
        cleaned,
        result.unwrappedGroupId,
        result.members,
        result.groupCenter,
      );
    }
    if (result.unwrappedGroupId) {
      cleaned = stripGsapAnimationsForSelector(cleaned, `#${result.unwrappedGroupId}`);
    }
    return writeIfChanged(c, ctx.project.dir, ctx.filePath, ctx.absPath, originalContent, cleaned);
  });

  api.post("/projects/:id/file-mutations/probe-element/*", async (c) => {
    const ctx = await resolveFileMutationContext(c, adapter, "probe-element");
    if ("error" in ctx) return ctx.error;

    const parsed = await parseMutationBody<{ target?: MutationTarget }>(c);
    if ("error" in parsed) return parsed.error;

    let content: string;
    try {
      content = readFileSync(ctx.absPath, "utf-8");
    } catch {
      return c.json({ exists: false });
    }

    const exists = probeElementInSource(content, parsed.target);
    return c.json({ exists });
  });

  api.post("/projects/:id/file-mutations/probe-elements/*", async (c) => {
    const ctx = await resolveFileMutationContext(c, adapter, "probe-elements");
    if ("error" in ctx) return ctx.error;

    const body = (await c.req.json().catch(() => null)) as { targets?: MutationTarget[] } | null;
    if (!Array.isArray(body?.targets)) return c.json({ error: "targets required" }, 400);

    let content: string;
    try {
      content = readFileSync(ctx.absPath, "utf-8");
    } catch {
      return c.json({ exists: body.targets.map(() => false) });
    }
    return c.json({ exists: probeElementsInSource(content, body.targets) });
  });

  // ── Rename / Move ──

  api.patch("/projects/:id/files/*", async (c) => {
    const res = await resolveProjectFile(c, adapter, { mustExist: true });
    if ("error" in res) return res.error;

    const body: unknown = await c.req.json();
    const newPath =
      body !== null && typeof body === "object" && "newPath" in body ? body.newPath : undefined;
    if (
      typeof newPath !== "string" ||
      !newPath ||
      newPath.includes("\0") ||
      /[\uD800-\uDFFF]/u.test(newPath)
    ) {
      return c.json({ error: "newPath required" }, 400);
    }

    const newAbs = resolveWithinProject(res.project.dir, newPath);
    if (!newAbs) {
      return c.json({ error: "forbidden" }, 403);
    }
    if (existsSync(newAbs)) {
      return c.json({ error: "already exists" }, 409);
    }

    const isDirectory = statSync(res.absPath, { throwIfNoEntry: false })?.isDirectory() ?? false;
    ensureDir(res.project.dir, newAbs);
    renameSync(res.absPath, newAbs);

    // Update references to the old path across all project files
    const updatedFiles = updateReferences(res.project.dir, res.filePath, newPath, isDirectory);

    return c.json({ ok: true, path: newPath, updatedReferences: updatedFiles });
  });

  // ── Duplicate ──

  api.post("/projects/:id/duplicate-file", async (c) => {
    const project = await adapter.resolveProject(c.req.param("id"));
    if (!project) return c.json({ error: "not found" }, 404);

    const body = (await c.req.json()) as { path: string };
    if (!body.path || body.path.includes("\0")) {
      return c.json({ error: "path required" }, 400);
    }

    const srcAbs = resolveWithinProject(project.dir, body.path);
    if (!srcAbs || !existsSync(srcAbs)) {
      return c.json({ error: "not found" }, 404);
    }

    const copyPath = generateCopyPath(project.dir, body.path);
    const destAbs = resolveWithinProject(project.dir, copyPath);
    if (!destAbs) {
      return c.json({ error: "forbidden" }, 403);
    }

    ensureDir(project.dir, destAbs);
    try {
      createFileAtomically(destAbs, readFileSync(srcAbs));
    } catch (error) {
      if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST") {
        throw error;
      }
      return c.json({ error: "already exists" }, 409);
    }

    return c.json({ ok: true, path: copyPath }, 201);
  });

  // ── Upload (binary assets via multipart form) ──

  api.post(
    "/projects/:id/upload",
    bodyLimit({
      maxSize: MAX_UPLOAD_BYTES,
      onError: (c) => c.json({ error: "payload too large" }, 413),
    }),
    async (c) => {
      const project = await adapter.resolveProject(c.req.param("id"));
      if (!project) return c.json({ error: "not found" }, 404);
      if (folderGone(project.dir)) return projectDirMissing(c);

      // Optional subdirectory within the project (e.g. "assets/audio")
      const subDir = c.req.query("dir") ?? "";
      const targetDir = subDir ? resolveWithinProject(project.dir, subDir) : project.dir;
      if (!targetDir) return c.json({ error: "forbidden" }, 403);

      const formData = await c.req.formData();
      mkdirWithinProject(project.dir, targetDir);
      const result = await processUploadedFiles(formData, targetDir, project.dir);
      if (folderGone(project.dir)) return projectDirMissing(c);

      return c.json(
        {
          ok: true,
          files: result.uploaded,
          skipped: result.skipped,
          invalid: result.invalid,
          unchecked: result.unchecked,
        },
        201,
      );
    },
  );

  // ── GSAP Animations (parse) ──

  api.get("/projects/:id/gsap-animations/*", async (c) => {
    const res = await resolveProjectPath(c, adapter, "gsap-animations", {
      mustExist: true,
    });
    if ("error" in res) return res.error;

    // The parse is a pure function of the file and the parser, so a client that revalidates on
    // every read gets a 304 for every unchanged file; bump the `v1` salt when the parser changes.
    const html = readFileSync(res.absPath, "utf-8");
    const etag = `${fileContentVersion(html).slice(0, -1)}:gsap-animations:v1"`;
    const headers = { ETag: etag, "Cache-Control": "no-cache" };
    if (c.req.header("If-None-Match") === etag) return new Response(null, { status: 304, headers });

    const block = extractGsapScriptBlock(html);
    if (!block) {
      return c.json(
        { animations: [], timelineVar: "tl", preamble: "", postamble: "" },
        200,
        headers,
      );
    }

    return c.json(parseGsapScriptAcorn(block.scriptText), 200, headers);
  });

  // ── GSAP Mutations ──

  api.get("/projects/:id/gsap-mutation-capabilities", async (c) => {
    const project = await adapter.resolveProject(c.req.param("id"));
    if (!project) return c.json({ error: "not found" }, 404);
    return c.json({ atomicOwnershipPairs: true });
  });

  api.post("/projects/:id/gsap-mutations/*", async (c) => {
    const res = await resolveProjectPath(c, adapter, "gsap-mutations", {
      mustExist: true,
      pin: true,
    });
    if ("error" in res) return res.error;

    const body = (await c.req.json().catch(() => null)) as GsapMutationRequest | null;
    if (!body) return c.json({ error: "mutation type required" }, 400);
    const error = validateGsapMutationRequest(c, body);
    if (error) return error;
    return applyGsapMutations(c, res, [body]);
  });

  api.post("/projects/:id/gsap-mutations-batch/*", async (c) => {
    const res = await resolveProjectPath(c, adapter, "gsap-mutations-batch", {
      mustExist: true,
      pin: true,
    });
    if ("error" in res) return res.error;

    const body = (await c.req.json().catch(() => null)) as {
      mutations?: GsapMutationRequest[];
    } | null;
    if (!body || !Array.isArray(body.mutations) || body.mutations.length === 0) {
      return c.json({ error: "mutations array required" }, 400);
    }
    for (const mutation of body.mutations) {
      const error = validateGsapMutationRequest(c, mutation);
      if (error) return error;
    }
    return applyGsapMutations(c, res, body.mutations);
  });

  // A failed multi-step GSAP transaction may restore only the exact bytes its
  // mutation wrote. Keep compare + write in this synchronous server section so
  // another request cannot land between a client-side check and the restore.
  api.post("/projects/:id/gsap-mutation-rollback/*", async (c) => {
    const res = await resolveProjectPath(c, adapter, "gsap-mutation-rollback", {
      mustExist: true,
      pin: true,
    });
    if ("error" in res) return res.error;

    const body = (await c.req.json().catch(() => null)) as {
      expected?: unknown;
      restore?: unknown;
    } | null;
    if (!body || typeof body.expected !== "string" || typeof body.restore !== "string") {
      return c.json({ error: "expected and restore contents required" }, 400);
    }

    const current = readFileSync(res.absPath, "utf-8");
    if (current !== body.expected) {
      return c.json({ ok: true, restored: false, conflict: true });
    }
    replaceFileAtomically(res.absPath, body.restore, statSync(res.absPath).mode);
    return c.json({ ok: true, restored: true, conflict: false });
  });
}