diff --git a/packages/cli/src/commands/beats.ts b/packages/cli/src/commands/beats.ts
index 925796dd57..50f6d2b96c 100644
--- a/packages/cli/src/commands/beats.ts
+++ b/packages/cli/src/commands/beats.ts
@@ -1,6 +1,7 @@
import { failCommand } from "../utils/commandResult.js";
import { defineCommand } from "../utils/defineCommand.js";
-import { existsSync, readFileSync, mkdirSync, statSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, mkdirSync, statSync } from "node:fs";
+import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { join, dirname, resolve } from "node:path";
import {
analyzeMusicFromSignal,
@@ -170,7 +171,7 @@ export default defineCommand({
if (!isSafePath(project.dir, outPath))
fail(`Beat file path resolves outside the project: ${rel}`);
mkdirSync(dirname(outPath), { recursive: true });
- writeFileSync(outPath, serializeBeats(result.beatTimes, result.beatStrengths, rel));
+ replaceFileAtomically(outPath, serializeBeats(result.beatTimes, result.beatStrengths, rel));
report(`beats/${rel}.json`, result, Boolean(args.json));
},
});
diff --git a/packages/cli/src/commands/measure/extract.ts b/packages/cli/src/commands/measure/extract.ts
index 055fe2d345..ee736755ab 100644
--- a/packages/cli/src/commands/measure/extract.ts
+++ b/packages/cli/src/commands/measure/extract.ts
@@ -1,10 +1,11 @@
// Pixels from the original, as project media: a still at one moment or a clip over a window, cropped to a region,
// frame-exact, recorded in the media ledger as cut from the original. A rebuild reuses footage, photos and people
// this way instead of drawing or generating them.
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { createStagingDir } from "@hyperframes/core/atomic-file";
import { makeOutputFolder } from "../../utils/outputFolder.js";
import { tmpdir } from "node:os";
-import { dirname, join, relative, resolve } from "node:path";
+import { basename, dirname, join, relative, resolve } from "node:path";
import { defineCommand } from "../../utils/defineCommand.js";
import type { Example } from "../_examples.js";
import { jsonArg, num, roiArg, runMeasure, videoAndRoi, videoArg } from "../../measure/command.js";
@@ -18,6 +19,17 @@ import {
type VideoInfo,
} from "../../measure/media.js";
+function encodeOnto(out: string, encode: (staged: string) => void): void {
+ const staging = createStagingDir(dirname(out), ".hf-extract-");
+ try {
+ const staged = join(staging, basename(out));
+ encode(staged);
+ renameSync(staged, out);
+ } finally {
+ rmSync(staging, { recursive: true, force: true });
+ }
+}
+
export const examples: Example[] = [
[
"A photo from the original at 3.2 s, cropped to its box",
@@ -76,7 +88,9 @@ export async function cutStill(info: VideoInfo, at: number, roi: Roi, out: strin
try {
const full = join(work, "frame.png");
writeFileSync(full, png);
- runFfmpeg(["-y", "-i", full, "-vf", crop(roi), "-frames:v", "1", out]);
+ encodeOnto(out, (staged) =>
+ runFfmpeg(["-y", "-i", full, "-vf", crop(roi), "-frames:v", "1", staged]),
+ );
} finally {
rmSync(work, { recursive: true, force: true });
}
@@ -100,25 +114,36 @@ export function cutClip(
const sound = Boolean(opts.audio && info.audio);
// Frames picked by index, as diff and the event map count them: a seek keeps whichever frame is showing at the
// seek time, which at some rates is the one before k0.
- runFfmpeg([
- ...["-y", "-i", info.path],
- ...[
- "-vf",
- `trim=start_frame=${k0}:end_frame=${k1},setpts=PTS-STARTPTS,${crop(roi)},format=yuv420p`,
- ],
- ...["-r", info.fpsText, "-c:v", "libx264", "-crf", String(opts.crf ?? 14), "-preset", "medium"],
- ...(sound
- ? [
- "-af",
- `atrim=start=${a}:end=${k1 / info.fps},asetpts=PTS-STARTPTS`,
- "-c:a",
- "aac",
- "-b:a",
- "192k",
- ]
- : ["-an"]),
- ...["-movflags", "+faststart", out],
- ]);
+ encodeOnto(out, (staged) =>
+ runFfmpeg([
+ ...["-y", "-i", info.path],
+ ...[
+ "-vf",
+ `trim=start_frame=${k0}:end_frame=${k1},setpts=PTS-STARTPTS,${crop(roi)},format=yuv420p`,
+ ],
+ ...[
+ "-r",
+ info.fpsText,
+ "-c:v",
+ "libx264",
+ "-crf",
+ String(opts.crf ?? 14),
+ "-preset",
+ "medium",
+ ],
+ ...(sound
+ ? [
+ "-af",
+ `atrim=start=${a}:end=${k1 / info.fps},asetpts=PTS-STARTPTS`,
+ "-c:a",
+ "aac",
+ "-b:a",
+ "192k",
+ ]
+ : ["-an"]),
+ ...["-movflags", "+faststart", staged],
+ ]),
+ );
return {
window: [round(a, 3), round(k1 / info.fps, 3)],
frames: n,
@@ -138,7 +163,20 @@ export function cutSound(info: VideoInfo, from: number, to: number, out: string)
: /\.mp3$/i.test(out)
? ["-c:a", "libmp3lame", "-q:a", "2"]
: ["-c:a", "aac", "-b:a", "256k"];
- runFfmpeg(["-y", "-ss", String(a), "-i", info.path, "-t", String(b - a), "-vn", ...codec, out]);
+ encodeOnto(out, (staged) =>
+ runFfmpeg([
+ "-y",
+ "-ss",
+ String(a),
+ "-i",
+ info.path,
+ "-t",
+ String(b - a),
+ "-vn",
+ ...codec,
+ staged,
+ ]),
+ );
return { window: [round(a, 3), round(b, 3)], duration: round(b - a, 3) };
}
diff --git a/packages/cli/src/commands/media-treatment.ts b/packages/cli/src/commands/media-treatment.ts
index 9b7dcd621f..1c6d498165 100644
--- a/packages/cli/src/commands/media-treatment.ts
+++ b/packages/cli/src/commands/media-treatment.ts
@@ -1,4 +1,5 @@
-import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
+import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { relative, resolve } from "node:path";
import {
HF_COLOR_GRADING_ATTR,
@@ -734,7 +735,7 @@ async function prepareMutation(args: MediaTreatmentCommandArgs) {
const lintResult = await lintHyperframeHtml(result.html);
const findings = lintResult.findings.filter(({ code }) => code.startsWith("color_grading_"));
const lint = { ok: findings.every(({ severity }) => severity !== "error"), findings };
- if (result.changed && !dryRun) writeFileSync(filePath, result.html);
+ if (result.changed && !dryRun) replaceFileAtomically(filePath, result.html);
const action: "clear" | "apply" = result.targets.every(({ value }) => value === null)
? "clear"
diff --git a/packages/cli/src/commands/motionShot.ts b/packages/cli/src/commands/motionShot.ts
index 7107969ca8..c6ae302d85 100644
--- a/packages/cli/src/commands/motionShot.ts
+++ b/packages/cli/src/commands/motionShot.ts
@@ -12,7 +12,8 @@ import { launchWithPageNetwork } from "../browser/pageNetwork.js";
// exactly what it's editing. All geometry + SVG live in ./motionShotLayout.ts
// (pure, tested); this file only drives the browser and SAMPLES.
-import { statSync, writeFileSync } from "node:fs";
+import { statSync } from "node:fs";
+import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { makeOutputFolder } from "../utils/outputFolder.js";
import { dirname, resolve } from "node:path";
import { pageNavigationTimeoutMs } from "../utils/renderArgs.js";
@@ -676,7 +677,7 @@ async function captureGhostOnionSkin(
)) as string;
const b64 = String(dataUrl).replace(/^data:image\/png;base64,/, "");
if (!b64) throw new Error("ghost composite returned no data");
- writeFileSync(outPath, Buffer.from(b64, "base64"));
+ replaceFileAtomically(outPath, Buffer.from(b64, "base64"));
return outPath;
}
@@ -734,7 +735,7 @@ async function captureRenderedSvgStrip(
await new Promise((resolveWait) => setTimeout(resolveWait, 60));
const output = await page.screenshot({ type: "png" });
if (!output) throw new Error("screenshot returned no data");
- writeFileSync(outPath, output as Uint8Array);
+ replaceFileAtomically(outPath, output as Uint8Array);
return outPath;
}
@@ -777,7 +778,7 @@ async function captureMarkerOnionSkin(
const buf = await page.screenshot({ type: "png" });
if (!buf) throw new Error("screenshot returned no data");
- writeFileSync(outPath, buf as Uint8Array);
+ replaceFileAtomically(outPath, buf as Uint8Array);
return outPath;
}
diff --git a/packages/cli/src/commands/normalize-audio.command.test.ts b/packages/cli/src/commands/normalize-audio.command.test.ts
index 2e5e69d31a..8501940ee0 100644
--- a/packages/cli/src/commands/normalize-audio.command.test.ts
+++ b/packages/cli/src/commands/normalize-audio.command.test.ts
@@ -1,4 +1,12 @@
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import {
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCommand } from "citty";
@@ -71,6 +79,40 @@ describe("absolute normalize-audio command", () => {
});
});
+// fails without the fix: the rewrite went through a link at its pid-named temp file, onto a file outside.
+describe("normalize-audio --write never writes through a link at its temp name", () => {
+ it("leaves the link's target alone and writes the composition in the project", async () => {
+ const root = mkdtempSync(join(tmpdir(), "hf-normalize-link-test-"));
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ try {
+ const dir = join(root, "project");
+ mkdirSync(dir);
+ const outside = join(root, "outside.txt");
+ writeFileSync(outside, "keep me");
+ const path = join(dir, "index.html");
+ writeFileSync(
+ path,
+ ``,
+ );
+ writeFileSync(join(dir, "voice.wav"), "audio bytes");
+ symlinkSync(outside, `${path}.hf-normalize-${process.pid}.tmp`);
+ measureAudio.mockResolvedValue({ integratedLufs: -20, truePeakDbfs: -12.3 });
+
+ await runCommand(normalizeAudioCommand, {
+ rawArgs: [dir, "--target", "voice", "--json", "--write"],
+ });
+
+ expect(readFileSync(outside, "utf8")).toBe("keep me");
+ expect(readFileSync(path, "utf8")).toMatch(/data-volume="(?!0")/);
+ expect(lstatSync(path).isSymbolicLink()).toBe(false);
+ } finally {
+ log.mockRestore();
+ measureAudio.mockReset();
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
+
describe("normalize-audio on a clip inside a mounted scene", () => {
it("measures it and writes the gain into the scene file", async () => {
const dir = mkdtempSync(join(tmpdir(), "hf-normalize-scene-test-"));
diff --git a/packages/cli/src/commands/normalize-audio.ts b/packages/cli/src/commands/normalize-audio.ts
index 20a9bf384e..73e437b78f 100644
--- a/packages/cli/src/commands/normalize-audio.ts
+++ b/packages/cli/src/commands/normalize-audio.ts
@@ -1,4 +1,5 @@
-import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
+import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { relative, resolve } from "node:path";
import {
absoluteLoudnessPlan,
@@ -122,12 +123,6 @@ async function measuredPlan(
);
}
-function writeAtomically(path: string, contents: string): void {
- const temporary = `${path}.hf-normalize-${process.pid}.tmp`;
- writeFileSync(temporary, contents);
- renameSync(temporary, path);
-}
-
function parsedTolerance(raw: string): number {
const tolerance = Number(raw);
if (!Number.isFinite(tolerance) || tolerance < 0) {
@@ -195,7 +190,7 @@ async function normalizeAudio(options: NormalizeAudioOptions): Promise 0 && heldAtLimit(plan, tolerance);
const wrote = options.write && !withinTolerance && !heldByLimit;
if (wrote) {
- writeAtomically(
+ replaceFileAtomically(
filePath,
updateAudioVolume(readFileSync(filePath, "utf8"), targetTag.id, plan.volume),
);
diff --git a/packages/cli/src/commands/snapshot.ts b/packages/cli/src/commands/snapshot.ts
index 94d7c36fce..a5d7f785c0 100644
--- a/packages/cli/src/commands/snapshot.ts
+++ b/packages/cli/src/commands/snapshot.ts
@@ -54,10 +54,9 @@ import {
mkdirSync,
rmSync,
statSync,
- writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
-import { createStagingDir } from "@hyperframes/core/atomic-file";
+import { createStagingDir, replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { sumOf } from "../measure/media.js";
import { resolve, join, relative, isAbsolute, basename, posix } from "node:path";
import {
@@ -2166,7 +2165,7 @@ export default defineCommand({
}
const descPath = join(snapshotDir, "descriptions.md");
- writeFileSync(descPath, descriptions.join("\n"));
+ replaceFileAtomically(descPath, descriptions.join("\n"));
describedPath = descPath;
log(` ${c.dim("descriptions.md")} (Gemini frame analysis)`);
}
diff --git a/packages/cli/src/commands/upgrade.project.test.ts b/packages/cli/src/commands/upgrade.project.test.ts
index d55101f249..976fe91dc8 100644
--- a/packages/cli/src/commands/upgrade.project.test.ts
+++ b/packages/cli/src/commands/upgrade.project.test.ts
@@ -1,5 +1,13 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import {
+ chmodSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -91,6 +99,19 @@ describe("upgradeProjectPins", () => {
expect(readFileSync(publish, "utf8")).toContain("hyperframes@0.7.55");
});
+ // fails without the fix: the rewritten wrapper came back 0644, so `./render.sh` no longer ran.
+ it.skipIf(process.platform === "win32")("keeps an executable wrapper executable", async () => {
+ const d = project({});
+ const wrapper = join(d, "render.sh");
+ writeFileSync(wrapper, "npx --yes hyperframes@0.7.48 render\n");
+ chmodSync(wrapper, 0o755);
+
+ await upgradeProjectPins(d, { json: false, check: false });
+
+ expect(readFileSync(wrapper, "utf8")).toContain("hyperframes@0.7.55");
+ expect(statSync(wrapper).mode & 0o777).toBe(0o755);
+ });
+
it.skipIf(process.platform === "win32")(
"leaves the target of a package.json.tmp link untouched",
async () => {
diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.ts
index 245112fb64..52190e9369 100644
--- a/packages/cli/src/commands/upgrade.ts
+++ b/packages/cli/src/commands/upgrade.ts
@@ -4,7 +4,15 @@ import { defineCommand } from "../utils/defineCommand.js";
import type { Example } from "./_examples.js";
import * as clack from "../ui/prompts.js";
import { execFileSync } from "node:child_process";
-import { existsSync, readFileSync, writeFileSync, readdirSync } from "node:fs";
+import {
+ closeSync,
+ constants,
+ existsSync,
+ fstatSync,
+ openSync,
+ readdirSync,
+ readFileSync,
+} from "node:fs";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { join, resolve } from "node:path";
import { c } from "../ui/colors.js";
@@ -273,6 +281,15 @@ export function resolveProjectArgs(
return { dir: project, check: opts.check, json: opts.json };
}
+function readWrapper(path: string): { mode: number; text: string } {
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
+ try {
+ return { mode: fstatSync(fd).mode & 0o7777, text: readFileSync(fd, "utf-8") };
+ } finally {
+ closeSync(fd);
+ }
+}
+
export async function upgradeProjectPins(
dir: string,
opts: { json: boolean; check: boolean },
@@ -292,7 +309,8 @@ export async function upgradeProjectPins(
.filter((entry) => entry.isFile() && entry.name.endsWith(".sh"))
.map((entry) => {
const path = resolve(dir, entry.name);
- return { path, rewrite: rewritePinnedHyperframesText(readFileSync(path, "utf-8"), latest) };
+ const { mode, text } = readWrapper(path);
+ return { path, mode, rewrite: rewritePinnedHyperframesText(text, latest) };
});
if (rewrite.changed && !opts.check) {
raw.scripts = rewrite.scripts;
@@ -300,7 +318,8 @@ export async function upgradeProjectPins(
}
if (!opts.check) {
for (const wrapper of wrapperRewrites) {
- if (wrapper.rewrite.changed) writeFileSync(wrapper.path, wrapper.rewrite.text, "utf-8");
+ if (wrapper.rewrite.changed)
+ replaceFileAtomically(wrapper.path, wrapper.rewrite.text, wrapper.mode);
}
}
const from = new Set(rewrite.fromVersions);
diff --git a/packages/cli/src/media-use/lib/lut-preset-provider.mjs b/packages/cli/src/media-use/lib/lut-preset-provider.mjs
index 9b318fa935..8bdadca1a7 100644
--- a/packages/cli/src/media-use/lib/lut-preset-provider.mjs
+++ b/packages/cli/src/media-use/lib/lut-preset-provider.mjs
@@ -1,6 +1,6 @@
-import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync } from "node:fs";
import { dirname, join } from "node:path";
-import { withReservedFile, withReservedFileSync } from "./manifest.mjs";
+import { withReservedFile, withReservedFileSync, writeTempBeside } from "./manifest.mjs";
import { freezeUrl } from "./freeze.mjs";
import { tokenOverlap } from "./match.mjs";
import { buildCube } from "./cube-build.mjs";
@@ -245,13 +245,13 @@ export async function freezeLibraryLut(match, { projectDir, type, localOnly = fa
if (match.params) {
return withReservedFileSync(projectDir, type, ".cube", ({ id, localPath, fullPath }) => {
- const tmpPath = `${fullPath}.tmp`;
+ let tmpPath = null;
try {
const cube = buildCube(match.params);
assertValidCubeText(cube, `invalid library LUT ${match.id}`);
- // Write + validate at .tmp, then atomic rename — same no-orphan guarantee
+ // Write + validate at a temp file, then atomic rename — same no-orphan guarantee
// as the url path above.
- writeFileSync(tmpPath, cube);
+ tmpPath = writeTempBeside(fullPath, cube);
assertValidCubeFile(tmpPath, `invalid frozen LUT ${localPath}`);
renameSync(tmpPath, fullPath);
return libraryRecord(match, {
@@ -261,7 +261,7 @@ export async function freezeLibraryLut(match, { projectDir, type, localOnly = fa
via: match.url ? "params-fallback" : "params",
});
} finally {
- rmSync(tmpPath, { force: true });
+ if (tmpPath) rmSync(tmpPath, { force: true });
}
});
}
diff --git a/packages/cli/src/media-use/lib/manifest.mjs b/packages/cli/src/media-use/lib/manifest.mjs
index 7e8916375b..f656d7414b 100644
--- a/packages/cli/src/media-use/lib/manifest.mjs
+++ b/packages/cli/src/media-use/lib/manifest.mjs
@@ -9,7 +9,6 @@ import {
writeSync,
rmSync,
renameSync,
- statSync,
lstatSync,
realpathSync,
constants,
@@ -89,6 +88,22 @@ export function ownMediaDir(projectDir) {
return dir;
}
+/** The project's own folder for `type` under `.media`, made if missing; throws when any folder on the way is a link. */
+export function ownTypeDir(projectDir, type) {
+ let dir = ownMediaDir(projectDir);
+ // Each folder is looked at before it is made, so nothing is ever made through a link.
+ for (const part of typeSubdir(type).split("/")) {
+ dir = join(dir, part);
+ if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) {
+ throw new Error(
+ `${dir} is a link; media is written only into real folders, so nothing was written there`,
+ );
+ }
+ mkdirSync(dir, { recursive: true });
+ }
+ return dir;
+}
+
/** Throws when `path` is a link. */
export function refuseLink(path) {
if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) {
@@ -96,18 +111,29 @@ export function refuseLink(path) {
}
}
-/** Replaces the file at `path` with `content` by writing a temp file beside it and renaming it over, so a link there is replaced, never followed. */
-export function replaceFile(path, content) {
+/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */
+export function writeTempBeside(path, content) {
// Same shape as core atomicTempPath, which Studio's project history skips.
const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`;
try {
writeFileSync(temp, content, { flag: "wx" });
- renameRidingWindowsHolds(temp, path);
} catch (error) {
// EEXIST: the random name belongs to another writer, so it is left alone.
if (error?.code !== "EEXIST") rmSync(temp, { force: true });
throw error;
}
+ return temp;
+}
+
+/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */
+export function replaceFile(path, content) {
+ const temp = writeTempBeside(path, content);
+ try {
+ renameRidingWindowsHolds(temp, path);
+ } catch (error) {
+ rmSync(temp, { force: true });
+ throw error;
+ }
}
// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file.
@@ -127,9 +153,7 @@ function renameRidingWindowsHolds(from, to) {
}
export function appendRecord(projectDir, record) {
- ownMediaDir(projectDir);
- const typeDir = typeDirPath(projectDir, record.type);
- mkdirSync(typeDir, { recursive: true });
+ ownTypeDir(projectDir, record.type);
const p = manifestPath(projectDir);
refuseLink(p);
@@ -246,13 +270,12 @@ function withLock(dir, fn) {
break;
} catch (err) {
if (err.code !== "EEXIST") throw err;
- try {
- if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
- rmSync(lock, { force: true }); // steal a stale lock from a dead holder
- continue;
- }
- } catch {
- continue; // lock vanished between check and stat — retry the acquire
+ const held = lstatSync(lock, { throwIfNoEntry: false });
+ if (!held) continue; // released between the open and the look: retry the acquire
+ if (!held.isFile()) throw new Error(`${lock} is not a lock file; remove it and try again`);
+ if (Date.now() - held.mtimeMs > LOCK_STALE_MS) {
+ rmSync(lock, { force: true }); // steal a stale lock from a dead holder
+ continue;
}
if (Date.now() - start > LOCK_TIMEOUT_MS) {
throw new Error("media-use: timed out acquiring .media/.lock");
@@ -269,8 +292,7 @@ function withLock(dir, fn) {
/** Runs `fn` holding the project's `.media/.lock`, so concurrent resolves take turns on what it guards. */
export function withMediaLock(projectDir, fn) {
- mkdirSync(mediaDir(projectDir), { recursive: true });
- return withLock(mediaDir(projectDir), fn);
+ return withLock(ownMediaDir(projectDir), fn);
}
// Atomically allocate the next free id for `type` AND reserve it on disk, so a
@@ -280,7 +302,7 @@ export function withMediaLock(projectDir, fn) {
// O_EXCL-create an empty marker under core's atomic temp name, which Studio's
// project history skips. Returns { id, localPath, markerPath }.
export function allocateId(projectDir, type, ext) {
- mkdirSync(typeDirPath(projectDir, type), { recursive: true });
+ ownTypeDir(projectDir, type);
return withMediaLock(projectDir, () => {
const id = nextFreeId(projectDir, type);
const localPath = `.media/${typeSubdir(type)}/${id}${ext}`;
diff --git a/packages/cli/src/media-use/lib/manifest.test.mjs b/packages/cli/src/media-use/lib/manifest.test.mjs
index 18b0c18c05..29308f1b0f 100644
--- a/packages/cli/src/media-use/lib/manifest.test.mjs
+++ b/packages/cli/src/media-use/lib/manifest.test.mjs
@@ -7,6 +7,7 @@ import {
mkdirSync,
existsSync,
readdirSync,
+ symlinkSync,
} from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
@@ -23,6 +24,7 @@ import {
mediaDir,
typeDirPath,
typeSubdir,
+ withMediaLock,
} from "./manifest.mjs";
import { regenerateIndex, generateIndexContent } from "./index-gen.mjs";
import {
@@ -376,6 +378,43 @@ function runTests() {
// --- run ---
+ // fails without the fix: a .media/.lock that is a folder or a dead link spun forever at full CPU.
+ test("the media lock refuses a lock that is a folder or a link, at once", () => {
+ for (const plant of [
+ (lock) => mkdirSync(lock),
+ (lock) => symlinkSync(join(lock, "..", "gone"), lock),
+ ]) {
+ const project = mkdtempSync(join(tmpdir(), "mu-lock-"));
+ try {
+ mkdirSync(join(project, ".media"));
+ plant(join(project, ".media", ".lock"));
+ const started = Date.now();
+ assert.throws(() => withMediaLock(project, () => "ran"), /not a lock file/);
+ assert.ok(Date.now() - started < 5000);
+ } finally {
+ rmSync(project, { recursive: true, force: true });
+ }
+ }
+ });
+
+ // fails without the fix: a linked .media/audio folder took reserved files and records outside the project.
+ test("a media type folder that is a link is refused before anything is made through it", () => {
+ const project = mkdtempSync(join(tmpdir(), "mu-typedir-"));
+ const outside = mkdtempSync(join(tmpdir(), "mu-outside-"));
+ try {
+ mkdirSync(join(project, ".media"));
+ symlinkSync(outside, join(project, ".media", "audio"));
+ assert.throws(
+ () => allocateId(project, "sfx", ".mp3"),
+ /is a link; media is written only into real folders/,
+ );
+ assert.deepEqual(readdirSync(outside), []);
+ } finally {
+ rmSync(project, { recursive: true, force: true });
+ rmSync(outside, { recursive: true, force: true });
+ }
+ });
+
let passed = 0;
let failed = 0;
for (const { name, fn } of tests) {
diff --git a/packages/cli/src/media-use/lib/openverse.mjs b/packages/cli/src/media-use/lib/openverse.mjs
index 87f80aa74d..f4e5cc2198 100644
--- a/packages/cli/src/media-use/lib/openverse.mjs
+++ b/packages/cli/src/media-use/lib/openverse.mjs
@@ -2,7 +2,17 @@
// Anonymous use is rate limited (20 requests a minute, 200 a day); callers fall
// back to the bundled library when it is unavailable.
-import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { randomBytes } from "node:crypto";
+import {
+ closeSync,
+ constants,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
import { dirname } from "node:path";
const OPENVERSE_AUDIO_URL = "https://api.openverse.org/v1/audio/";
@@ -117,18 +127,37 @@ export function writeSfxCredit(creditsPath, file, sound) {
// The sound may come from a saved record, not this run's pick: clean it again here.
const sourceUrl = httpsUrl(sound.sourceUrl, SOURCE_HOSTS);
const source = sourceUrl ? ` Source: ${sourceUrl}` : "";
- const line = `- \`${file}\`: ${oneLine(sound.credit)}${source}`;
+ const name = oneLine(file);
+ const line = `- \`${name}\`: ${oneLine(sound.credit)}${source}`;
let prior = "";
+ let fd;
try {
- prior = readFileSync(creditsPath, "utf8");
+ fd = openSync(creditsPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
} catch (error) {
+ if (error.code === "ELOOP")
+ throw new Error(`${creditsPath} is a link; nothing was written through it`);
if (error.code !== "ENOENT") throw error;
}
+ if (fd !== undefined) {
+ try {
+ prior = readFileSync(fd, "utf8");
+ } finally {
+ closeSync(fd);
+ }
+ }
const kept = prior
.split("\n")
- .filter((l) => l.startsWith("- ") && !l.startsWith(`- \`${file}\`:`));
+ .filter((l) => l.startsWith("- ") && !l.startsWith(`- \`${name}\`:`));
const header =
"# Sound effect credits\n\nThese sounds are licensed CC BY: credit them wherever the video is published.\n\n";
mkdirSync(dirname(creditsPath), { recursive: true });
- writeFileSync(creditsPath, `${header}${[...kept, line].join("\n")}\n`);
+ // The audio skill ships this file alone, so it cannot use manifest.mjs's replaceFile.
+ const temp = `${creditsPath}.hf${randomBytes(3).toString("hex")}.tmp`;
+ writeFileSync(temp, `${header}${[...kept, line].join("\n")}\n`, { flag: "wx" });
+ try {
+ renameSync(temp, creditsPath);
+ } catch (error) {
+ rmSync(temp, { force: true });
+ throw error;
+ }
}
diff --git a/packages/cli/src/media-use/lib/openverse.test.mjs b/packages/cli/src/media-use/lib/openverse.test.mjs
index 29a1340d6c..382222ae73 100644
--- a/packages/cli/src/media-use/lib/openverse.test.mjs
+++ b/packages/cli/src/media-use/lib/openverse.test.mjs
@@ -1,5 +1,13 @@
import { strict as assert } from "node:assert";
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import {
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
@@ -217,3 +225,38 @@ test("earlier credit lines survive a new credit", () => {
rmSync(dir, { recursive: true, force: true });
}
});
+
+// fails without the fix: a linked CREDITS.md had its target overwritten with the project's text.
+test("credits are never written through a link at the credits file", () => {
+ const dir = mkdtempSync(join(tmpdir(), "openverse-credits-link-"));
+ try {
+ const outside = join(dir, "outside.txt");
+ writeFileSync(outside, "keep me\n- secret line\n");
+ const path = join(dir, "project", ".media", "audio", "sfx", "CREDITS.md");
+ mkdirSync(join(dir, "project", ".media", "audio", "sfx"), { recursive: true });
+ symlinkSync(outside, path);
+ const by = { license: "by", credit: '"Pop" by Ana', sourceUrl: "https://freesound.org/s/1" };
+ assert.throws(() => writeSfxCredit(path, "assets/sfx/pop.mp3", by), /link/);
+ assert.equal(readFileSync(outside, "utf8"), "keep me\n- secret line\n");
+ assert.ok(lstatSync(path).isSymbolicLink());
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// fails without the fix: a record path with a newline added lines of its own to the credits file.
+test("a file name with a line break or backtick stays one credit line", () => {
+ const dir = mkdtempSync(join(tmpdir(), "openverse-credits-line-"));
+ try {
+ const path = join(dir, "CREDITS.md");
+ const by = { license: "by", credit: '"Pop" by Ana', sourceUrl: "https://freesound.org/s/1" };
+ writeSfxCredit(path, "a.mp3`\n- injected line", by);
+ const lines = readFileSync(path, "utf8")
+ .split("\n")
+ .filter((l) => l.startsWith("- "));
+ assert.equal(lines.length, 1);
+ assert.doesNotMatch(lines[0], /\n|`a\.mp3`.*`/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/packages/cli/src/media-use/resolve.mjs b/packages/cli/src/media-use/resolve.mjs
index 2918aa23f5..887a74c138 100644
--- a/packages/cli/src/media-use/resolve.mjs
+++ b/packages/cli/src/media-use/resolve.mjs
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import { spawnSync } from "node:child_process";
-import { existsSync, statSync, writeFileSync, renameSync, rmSync, realpathSync } from "node:fs";
+import { existsSync, statSync, renameSync, rmSync, realpathSync } from "node:fs";
import { resolve, join, extname, basename, relative, isAbsolute, sep } from "node:path";
import { parseArgs } from "node:util";
import {
@@ -12,8 +12,9 @@ import {
findByPrompt,
findByEntity,
nextId,
- typeDirPath,
+ ownTypeDir,
withMediaLock,
+ writeTempBeside,
withReservedFile,
withReservedFileSync,
} from "./lib/manifest.mjs";
@@ -653,16 +654,16 @@ function freezeGeneratedLut(
},
) {
return withReservedFileSync(projectDir, type, ".cube", ({ id, localPath, fullPath }) => {
- const tmpPath = `${fullPath}.tmp`;
+ let tmpPath = null;
try {
- // Write + validate at .tmp, then atomic rename, so a crash between write and
+ // Write + validate at a temp file, then atomic rename, so a crash between write and
// validate can't leave an invalid .cube at the final path.
- writeFileSync(tmpPath, buildCube(params));
+ tmpPath = writeTempBeside(fullPath, buildCube(params));
const check = validateCubeFile(tmpPath);
if (!check.ok) throw new Error(check.error);
renameSync(tmpPath, fullPath);
} catch (err) {
- rmSync(tmpPath, { force: true });
+ if (tmpPath) rmSync(tmpPath, { force: true });
throw new Error(`${validationErrorPrefix}: ${err.message}`);
}
return {
@@ -1351,7 +1352,7 @@ async function result(record, source, match = recordedMatch(record)) {
// Under the media lock: two resolves at once each read, then rewrite, the whole credits file.
if (provider === OPENVERSE_SFX_PROVIDER)
withMediaLock(projectDir, () =>
- writeSfxCredit(join(typeDirPath(projectDir, "sfx"), "CREDITS.md"), record.path, {
+ writeSfxCredit(join(ownTypeDir(projectDir, "sfx"), "CREDITS.md"), record.path, {
license,
credit,
sourceUrl,
diff --git a/skills-manifest.json b/skills-manifest.json
index 9e213168e5..36dd66ad55 100644
--- a/skills-manifest.json
+++ b/skills-manifest.json
@@ -18,7 +18,7 @@
"files": 13
},
"media-use": {
- "hash": "cebaf2c0fa1d49ca",
+ "hash": "e31a0f67f111ee82",
"files": 131
},
"remotion-to-hyperframes": {
diff --git a/skills/media-use/audio/scripts/lib/openverse.mjs b/skills/media-use/audio/scripts/lib/openverse.mjs
index 87f80aa74d..f4e5cc2198 100644
--- a/skills/media-use/audio/scripts/lib/openverse.mjs
+++ b/skills/media-use/audio/scripts/lib/openverse.mjs
@@ -2,7 +2,17 @@
// Anonymous use is rate limited (20 requests a minute, 200 a day); callers fall
// back to the bundled library when it is unavailable.
-import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { randomBytes } from "node:crypto";
+import {
+ closeSync,
+ constants,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
import { dirname } from "node:path";
const OPENVERSE_AUDIO_URL = "https://api.openverse.org/v1/audio/";
@@ -117,18 +127,37 @@ export function writeSfxCredit(creditsPath, file, sound) {
// The sound may come from a saved record, not this run's pick: clean it again here.
const sourceUrl = httpsUrl(sound.sourceUrl, SOURCE_HOSTS);
const source = sourceUrl ? ` Source: ${sourceUrl}` : "";
- const line = `- \`${file}\`: ${oneLine(sound.credit)}${source}`;
+ const name = oneLine(file);
+ const line = `- \`${name}\`: ${oneLine(sound.credit)}${source}`;
let prior = "";
+ let fd;
try {
- prior = readFileSync(creditsPath, "utf8");
+ fd = openSync(creditsPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
} catch (error) {
+ if (error.code === "ELOOP")
+ throw new Error(`${creditsPath} is a link; nothing was written through it`);
if (error.code !== "ENOENT") throw error;
}
+ if (fd !== undefined) {
+ try {
+ prior = readFileSync(fd, "utf8");
+ } finally {
+ closeSync(fd);
+ }
+ }
const kept = prior
.split("\n")
- .filter((l) => l.startsWith("- ") && !l.startsWith(`- \`${file}\`:`));
+ .filter((l) => l.startsWith("- ") && !l.startsWith(`- \`${name}\`:`));
const header =
"# Sound effect credits\n\nThese sounds are licensed CC BY: credit them wherever the video is published.\n\n";
mkdirSync(dirname(creditsPath), { recursive: true });
- writeFileSync(creditsPath, `${header}${[...kept, line].join("\n")}\n`);
+ // The audio skill ships this file alone, so it cannot use manifest.mjs's replaceFile.
+ const temp = `${creditsPath}.hf${randomBytes(3).toString("hex")}.tmp`;
+ writeFileSync(temp, `${header}${[...kept, line].join("\n")}\n`, { flag: "wx" });
+ try {
+ renameSync(temp, creditsPath);
+ } catch (error) {
+ rmSync(temp, { force: true });
+ throw error;
+ }
}
diff --git a/skills/media-use/scripts/lib/manifest.mjs b/skills/media-use/scripts/lib/manifest.mjs
index 7e8916375b..f656d7414b 100644
--- a/skills/media-use/scripts/lib/manifest.mjs
+++ b/skills/media-use/scripts/lib/manifest.mjs
@@ -9,7 +9,6 @@ import {
writeSync,
rmSync,
renameSync,
- statSync,
lstatSync,
realpathSync,
constants,
@@ -89,6 +88,22 @@ export function ownMediaDir(projectDir) {
return dir;
}
+/** The project's own folder for `type` under `.media`, made if missing; throws when any folder on the way is a link. */
+export function ownTypeDir(projectDir, type) {
+ let dir = ownMediaDir(projectDir);
+ // Each folder is looked at before it is made, so nothing is ever made through a link.
+ for (const part of typeSubdir(type).split("/")) {
+ dir = join(dir, part);
+ if (lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink()) {
+ throw new Error(
+ `${dir} is a link; media is written only into real folders, so nothing was written there`,
+ );
+ }
+ mkdirSync(dir, { recursive: true });
+ }
+ return dir;
+}
+
/** Throws when `path` is a link. */
export function refuseLink(path) {
if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) {
@@ -96,18 +111,29 @@ export function refuseLink(path) {
}
}
-/** Replaces the file at `path` with `content` by writing a temp file beside it and renaming it over, so a link there is replaced, never followed. */
-export function replaceFile(path, content) {
+/** A new temp file beside `path` holding `content`, with a random name, created exclusively. */
+export function writeTempBeside(path, content) {
// Same shape as core atomicTempPath, which Studio's project history skips.
const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`;
try {
writeFileSync(temp, content, { flag: "wx" });
- renameRidingWindowsHolds(temp, path);
} catch (error) {
// EEXIST: the random name belongs to another writer, so it is left alone.
if (error?.code !== "EEXIST") rmSync(temp, { force: true });
throw error;
}
+ return temp;
+}
+
+/** Writes `content` to a temp file beside `path`, then renames it over: a link at `path` is replaced, not followed. */
+export function replaceFile(path, content) {
+ const temp = writeTempBeside(path, content);
+ try {
+ renameRidingWindowsHolds(temp, path);
+ } catch (error) {
+ rmSync(temp, { force: true });
+ throw error;
+ }
}
// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file.
@@ -127,9 +153,7 @@ function renameRidingWindowsHolds(from, to) {
}
export function appendRecord(projectDir, record) {
- ownMediaDir(projectDir);
- const typeDir = typeDirPath(projectDir, record.type);
- mkdirSync(typeDir, { recursive: true });
+ ownTypeDir(projectDir, record.type);
const p = manifestPath(projectDir);
refuseLink(p);
@@ -246,13 +270,12 @@ function withLock(dir, fn) {
break;
} catch (err) {
if (err.code !== "EEXIST") throw err;
- try {
- if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) {
- rmSync(lock, { force: true }); // steal a stale lock from a dead holder
- continue;
- }
- } catch {
- continue; // lock vanished between check and stat — retry the acquire
+ const held = lstatSync(lock, { throwIfNoEntry: false });
+ if (!held) continue; // released between the open and the look: retry the acquire
+ if (!held.isFile()) throw new Error(`${lock} is not a lock file; remove it and try again`);
+ if (Date.now() - held.mtimeMs > LOCK_STALE_MS) {
+ rmSync(lock, { force: true }); // steal a stale lock from a dead holder
+ continue;
}
if (Date.now() - start > LOCK_TIMEOUT_MS) {
throw new Error("media-use: timed out acquiring .media/.lock");
@@ -269,8 +292,7 @@ function withLock(dir, fn) {
/** Runs `fn` holding the project's `.media/.lock`, so concurrent resolves take turns on what it guards. */
export function withMediaLock(projectDir, fn) {
- mkdirSync(mediaDir(projectDir), { recursive: true });
- return withLock(mediaDir(projectDir), fn);
+ return withLock(ownMediaDir(projectDir), fn);
}
// Atomically allocate the next free id for `type` AND reserve it on disk, so a
@@ -280,7 +302,7 @@ export function withMediaLock(projectDir, fn) {
// O_EXCL-create an empty marker under core's atomic temp name, which Studio's
// project history skips. Returns { id, localPath, markerPath }.
export function allocateId(projectDir, type, ext) {
- mkdirSync(typeDirPath(projectDir, type), { recursive: true });
+ ownTypeDir(projectDir, type);
return withMediaLock(projectDir, () => {
const id = nextFreeId(projectDir, type);
const localPath = `.media/${typeSubdir(type)}/${id}${ext}`;
diff --git a/skills/media-use/scripts/transcribe.mjs b/skills/media-use/scripts/transcribe.mjs
index a7fe760bec..216d8da5ec 100644
--- a/skills/media-use/scripts/transcribe.mjs
+++ b/skills/media-use/scripts/transcribe.mjs
@@ -2,15 +2,8 @@
import "./lib/windows-exe-search.mjs";
import { execFileSync } from "node:child_process";
-import {
- existsSync,
- readFileSync,
- writeFileSync,
- copyFileSync,
- renameSync,
- mkdtempSync,
- rmSync,
-} from "node:fs";
+import { existsSync, readFileSync, writeFileSync, renameSync, mkdtempSync, rmSync } from "node:fs";
+import { randomBytes } from "node:crypto";
import { homedir, tmpdir } from "node:os";
import { basename, extname, join, resolve } from "node:path";
import { parseArgs, stripVTControlCharacters } from "node:util";
@@ -95,10 +88,16 @@ function resolveParakeet() {
// Write via a sibling temp + atomic rename so a SIGKILL mid-write can't leave a
// truncated transcript at outPath (downstream reads it as valid JSON).
+// The temp name is random and created exclusively, so a link beside the target is never written through.
function atomicWrite(target, data) {
- const tmp = `${target}.tmp-${process.pid}`;
- writeFileSync(tmp, data);
- renameSync(tmp, target);
+ const tmp = `${target}.hf${randomBytes(3).toString("hex")}.tmp`;
+ writeFileSync(tmp, data, { flag: "wx" });
+ try {
+ renameSync(tmp, target);
+ } catch (error) {
+ rmSync(tmp, { force: true });
+ throw error;
+ }
}
function report(engine, wordCount) {
@@ -175,9 +174,7 @@ function runCli(cliEngine) {
const produced = join(workDir, "transcript.json");
if (!existsSync(produced))
throw new Error("hyperframes transcribe produced no transcript.json");
- const tmp = `${outPath}.tmp-${process.pid}`;
- copyFileSync(produced, tmp);
- renameSync(tmp, outPath); // atomic publish
+ atomicWrite(outPath, readFileSync(produced));
let words;
try {
const t = JSON.parse(readFileSync(outPath, "utf8"));
diff --git a/skills/media-use/scripts/transcribe.test.mjs b/skills/media-use/scripts/transcribe.test.mjs
index e6ba27ae3f..3a60c318d4 100644
--- a/skills/media-use/scripts/transcribe.test.mjs
+++ b/skills/media-use/scripts/transcribe.test.mjs
@@ -213,3 +213,46 @@ test(
}
},
);
+
+// fails without the fix: the transcript went through a link at `.tmp-`, onto a file outside.
+test(
+ "the transcript is never written through a link beside it",
+ { skip: process.platform === "win32" },
+ () => {
+ const root = mkdtempSync(join(tmpdir(), "media-use-transcribe-link-"));
+ try {
+ const outside = join(root, "outside.txt");
+ writeFileSync(outside, "keep me");
+ const out = join(root, "in.transcribe.json");
+ const cli = join(root, "cli.mjs");
+ // The stand-in runs as this script's child, so its parent pid is the one the temp name would use.
+ writeFileSync(
+ cli,
+ `import { symlinkSync, writeFileSync } from "node:fs";\nconst a = process.argv.slice(2);\n` +
+ `symlinkSync(${JSON.stringify(outside)}, ${JSON.stringify(out)} + ".tmp-" + process.ppid);\n` +
+ `writeFileSync(a[a.indexOf("--dir") + 1] + "/transcript.json", '[{"text":"a","start":0,"end":1}]');\n` +
+ `console.log('{"ok":true,"engine":"whisper"}');\n`,
+ );
+ writeFileSync(join(root, "in.wav"), "");
+ const script = fileURLToPath(new URL("./transcribe.mjs", import.meta.url));
+ const env = { ...process.env, HYPERFRAMES_CLI_ENTRY: cli, HOME: root };
+ delete env.HYPERFRAMES_PARAKEET;
+ execFileSync(
+ process.execPath,
+ [script, "--input", join(root, "in.wav"), "--engine", "whisper", "--json"],
+ {
+ encoding: "utf8",
+ env: {
+ ...env,
+ HYPERFRAMES_MEDIA_HOME: join(root, "home"),
+ HYPERFRAMES_NO_TELEMETRY: "1",
+ },
+ },
+ );
+ assert.equal(readFileSync(outside, "utf8"), "keep me");
+ assert.match(readFileSync(out, "utf8"), /"text"/);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/skills/media-use/scripts/transcript-cut.mjs b/skills/media-use/scripts/transcript-cut.mjs
index 4efb47f1cd..0342be7c9b 100644
--- a/skills/media-use/scripts/transcript-cut.mjs
+++ b/skills/media-use/scripts/transcript-cut.mjs
@@ -90,6 +90,8 @@ function run() {
const outPath = resolve(args.out);
mkdirSync(dirname(outPath), { recursive: true });
const tmpDir = mkdtempSync(join(tmpdir(), "media-use-cut-"));
+ // The encode lands in a new private folder beside --out, so nothing already next to it is written through.
+ let outDir = null;
const keptSeconds = sumDurations(segments);
const totalSeconds = probeDuration(inputPath);
@@ -122,9 +124,10 @@ function run() {
listPath,
parts.map((part) => `file '${escapeConcatPath(part)}'`).join("\n") + "\n",
);
- // Encode to a sibling temp (same extension so ffmpeg picks the right muxer),
+ // Encode to a temp beside --out (same extension so ffmpeg picks the right muxer),
// then atomic-rename so a SIGKILL mid-encode can't leave a truncated outPath.
- const tmpOut = `${outPath}.part${extname(outPath) || ".mp4"}`;
+ outDir = mkdtempSync(join(dirname(outPath), ".media-use-cut-"));
+ const tmpOut = join(outDir, `out${extname(outPath) || ".mp4"}`);
// --copy already produced final-codec segments, so concat can stream-copy.
// Otherwise the PCM intermediates are encoded here, once, for the whole file.
const concatCodecs = args.copy
@@ -142,6 +145,7 @@ function run() {
renameSync(tmpOut, outPath);
} finally {
rmSync(tmpDir, { recursive: true, force: true });
+ if (outDir) rmSync(outDir, { recursive: true, force: true });
}
// Stream copy can only cut on keyframes; on sparse-keyframe footage the snap
diff --git a/skills/media-use/scripts/transcript-cut.test.mjs b/skills/media-use/scripts/transcript-cut.test.mjs
index 95852adb82..56bc779e50 100644
--- a/skills/media-use/scripts/transcript-cut.test.mjs
+++ b/skills/media-use/scripts/transcript-cut.test.mjs
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { lstatSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
@@ -339,3 +339,41 @@ test("a kept range starting on a 30 fps frame keeps that frame", { skip: !HAS_FF
);
assert.equal(frames, 88, `expected 88 frames, got ${frames}`);
});
+
+// fails without the fix: ffmpeg encoded through a link at `.part`, onto a file outside.
+test("the cut is never encoded through a link beside --out", { skip: !HAS_FFMPEG }, (t) => {
+ const { dir, cleanup } = fixture();
+ t.after(cleanup);
+ const source = join(dir, "source.wav");
+ execFileSync("ffmpeg", [
+ "-y",
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "sine=duration=1",
+ source,
+ ]);
+ const transcriptPath = join(dir, "transcript.json");
+ writeFileSync(transcriptPath, JSON.stringify({ words: [{ text: "tone", start: 0, end: 1 }] }));
+ const outside = join(dir, "outside.txt");
+ writeFileSync(outside, "keep me");
+ const output = join(dir, "out.wav");
+ symlinkSync(outside, `${output}.part.wav`);
+ const result = run([
+ "--input",
+ source,
+ "--transcript",
+ transcriptPath,
+ "--keep",
+ "0.1-0.6",
+ "--out",
+ output,
+ "--json",
+ ]);
+ assert.equal(result.status, 0, result.stderr || result.stdout);
+ assert.equal(readFileSync(outside, "utf8"), "keep me");
+ assert.ok(lstatSync(output).isFile());
+});