From b151ad4c540026bfa49ee889d0f5253b76e32fcf Mon Sep 17 00:00:00 2001 From: "melodic-automation-lanes[bot]" <337595936+melodic-automation-lanes[bot]@users.noreply.github.com> Date: Sun, 18 Oct 2026 06:01:09 +0000 Subject: [PATCH 1/6] fix(knowledge): clean up video-digest temp dirs when a watch is interrupted by a signal Co-Authored-By: Claude Sonnet 5.5 --- ...eo-digest-watch-signal-cleanup-6920a1c4.md | 7 ++ .../extraction/watch/run-watch-signal.test.js | 83 +++++++++++++++++++ .../extraction/watch/run-watch.js | 21 ++++- 3 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 .changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md create mode 100644 plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js diff --git a/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md b/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md new file mode 100644 index 00000000000..464cf2deddc --- /dev/null +++ b/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md @@ -0,0 +1,7 @@ +--- +bump: patch +--- + +### Fixed + +- `video-digest` `run-watch.js` now removes its temp video, frame and sheet directories when SIGINT or SIGTERM interrupts a watch before `watch.json` records them, then exits `130` or `143`. Cleanup runs once, and the handlers are removed when the run ends. diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js new file mode 100644 index 00000000000..3803df039f8 --- /dev/null +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js @@ -0,0 +1,83 @@ +/** + * A watch killed by SIGINT or SIGTERM during acquisition removes the temp dirs it + * made and exits with the conventional signal code. A real child run is used: a + * fake `yt-dlp` on PATH blocks the acquisition so the signal lands mid-download. + * POSIX only (the fake yt-dlp is a shell script). + */ + +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +const RUN_WATCH = fileURLToPath(new URL("./run-watch.js", import.meta.url)); +const URL_UNDER_TEST = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"; +const TEMP_PREFIXES = ["video-extraction-", "video-frames-", "video-sheets-"]; + +/** @type {string} */ +let sandbox; +/** @type {string} */ +let fakeTmp; +/** @type {string} */ +let started; + +async function watchTempDirs() { + const names = await fs.readdir(fakeTmp); + return names.filter((name) => TEMP_PREFIXES.some((prefix) => name.startsWith(prefix))); +} + +async function waitFor(predicate, timeoutMs = 20_000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (await predicate()) return; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + throw new Error("timed out waiting for the child to reach acquisition"); +} + +describe.skipIf(process.platform === "win32")("run-watch interrupted by a signal", () => { + beforeEach(async () => { + sandbox = await fs.mkdtemp(path.join(os.tmpdir(), "watch-signal-")); + fakeTmp = path.join(sandbox, "tmp"); + const bin = path.join(sandbox, "bin"); + started = path.join(sandbox, "yt-dlp-started"); + await fs.mkdir(fakeTmp); + await fs.mkdir(bin); + await fs.writeFile( + path.join(bin, "yt-dlp"), + `#!/bin/sh\ntouch "${started}"\nexec sleep 60\n`, + { mode: 0o755 }, + ); + }); + + afterEach(async () => { + await fs.rm(sandbox, { recursive: true, force: true }); + }); + + it.each([ + ["SIGTERM", 143], + ["SIGINT", 130], + ])("%s removes the temp dirs and exits %i", async (signal, exitCode) => { + const child = spawn(process.execPath, [RUN_WATCH, URL_UNDER_TEST], { + env: { + ...process.env, + PATH: `${path.join(sandbox, "bin")}${path.delimiter}${process.env.PATH}`, + TMPDIR: fakeTmp, + VIDEO_DIGEST_WORK_ROOT: path.join(sandbox, "work"), + }, + stdio: "ignore", + }); + const exited = new Promise((resolve) => child.on("exit", (code, sig) => resolve({ code, sig }))); + + await waitFor(() => existsSync(started)); + expect(await watchTempDirs()).toHaveLength(3); + + child.kill(signal); + expect(await exited).toEqual({ code: exitCode, sig: null }); + expect(await watchTempDirs()).toEqual([]); + }); +}); diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js index d9b5cac3151..168378c78ca 100755 --- a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js @@ -139,13 +139,32 @@ export async function runWatchCli(argv) { // failure removes the ones this run made. Once recorded, --recover needs them. /** @type {TempDirs} */ const temp = { dirs: {}, recorded: false }; + // The signal handlers and the finally block share one cleanup, so it runs once. + let cleanup = null; + const cleanUpOnce = () => { + cleanup ??= temp.recorded + ? Promise.resolve() + : removeRecordedTempSessionDirs(temp.dirs, "watch"); + return cleanup; + }; + const signalHandlers = Object.entries(SIGNAL_EXIT_CODES).map(([signal, code]) => { + const handler = () => { + cleanUpOnce().finally(() => process.exit(code)); + }; + process.on(signal, handler); + return /** @type {const} */ ([signal, handler]); + }); try { return await watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFrameGapSec, temp }); } finally { - if (!temp.recorded) await removeRecordedTempSessionDirs(temp.dirs, "watch"); + for (const [signal, handler] of signalHandlers) process.off(signal, handler); + await cleanUpOnce(); } } +/** Conventional exit code (128 + signal number) for each signal the watch cleans up on. */ +const SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 }; + /** * @typedef {Object} TempDirs * @property {{ workDir?: string, framesDir?: string, contactSheetsDir?: string }} dirs - created by this run From ab375f692b28bc26d6aacd5ba1b314d3988ca378 Mon Sep 17 00:00:00 2001 From: "melodic-automation-lanes[bot]" <337595936+melodic-automation-lanes[bot]@users.noreply.github.com> Date: Mon, 19 Oct 2026 02:21:18 +0000 Subject: [PATCH 2/6] fix(knowledge): end video-digest children and stop temp-dir creation before signal cleanup On SIGINT/SIGTERM, kill the tracked yt-dlp/ffmpeg children, flag the run interrupted so watchUrl creates and records nothing further, and remove the temp dirs only after watchUrl settles. The signal test's fake yt-dlp now writes into the work dir. Co-Authored-By: Claude Sonnet 5.5 --- .../extraction/watch/run-watch-signal.test.js | 7 +- .../extraction/watch/run-watch.js | 79 ++++++++++++++++++- 2 files changed, 82 insertions(+), 4 deletions(-) diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js index 3803df039f8..55cc40d403b 100644 --- a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js @@ -49,7 +49,9 @@ describe.skipIf(process.platform === "win32")("run-watch interrupted by a signal await fs.mkdir(bin); await fs.writeFile( path.join(bin, "yt-dlp"), - `#!/bin/sh\ntouch "${started}"\nexec sleep 60\n`, + // Keeps writing into the work dir, as a real download would, so a signal that + // leaves it running races the cleanup and recreates files after the rm. + `#!/bin/sh\ntouch "${started}"\nwhile :; do\n for d in "$TMPDIR"/video-extraction-*; do\n [ -d "$d" ] && echo x >> "$d/partial.part"\n done\n sleep 0.05\ndone\n`, { mode: 0o755 }, ); }); @@ -79,5 +81,8 @@ describe.skipIf(process.platform === "win32")("run-watch interrupted by a signal child.kill(signal); expect(await exited).toEqual({ code: exitCode, sig: null }); expect(await watchTempDirs()).toEqual([]); + // A surviving fake yt-dlp would recreate the work dir's file within one tick. + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(await watchTempDirs()).toEqual([]); }); }); diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js index 168378c78ca..07359a98bd0 100755 --- a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js @@ -22,7 +22,9 @@ * Vision absorption, research, and synthesis run in the skill session (not this script). */ +import childProcess from "node:child_process"; import fs from "node:fs/promises"; +import { syncBuiltinESMExports } from "node:module"; import os from "node:os"; import path from "node:path"; @@ -138,7 +140,8 @@ export async function runWatchCli(argv) { // Until watch.json records the temp dirs, nothing else points at them, so a // failure removes the ones this run made. Once recorded, --recover needs them. /** @type {TempDirs} */ - const temp = { dirs: {}, recorded: false }; + const temp = { dirs: {}, recorded: false, interrupted: false }; + const children = trackChildren(temp); // The signal handlers and the finally block share one cleanup, so it runs once. let cleanup = null; const cleanUpOnce = () => { @@ -147,17 +150,32 @@ export async function runWatchCli(argv) { : removeRecordedTempSessionDirs(temp.dirs, "watch"); return cleanup; }; + /** @type {Promise | null} */ + let running = null; const signalHandlers = Object.entries(SIGNAL_EXIT_CODES).map(([signal, code]) => { const handler = () => { - cleanUpOnce().finally(() => process.exit(code)); + // Stop the work first: end the yt-dlp/ffmpeg children and flag the run so + // watchUrl creates and records nothing more. The dirs go only once watchUrl + // has settled, so nothing is still writing into them or creating them. + children.interrupt(); + const settled = Promise.race([ + Promise.resolve(running).catch(() => {}), + new Promise((resolve) => setTimeout(resolve, INTERRUPT_SETTLE_MS).unref()), + ]); + settled.then(cleanUpOnce).finally(() => process.exit(code)); }; process.on(signal, handler); return /** @type {const} */ ([signal, handler]); }); try { - return await watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFrameGapSec, temp }); + running = watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFrameGapSec, temp }); + return await running; + } catch (error) { + if (error instanceof InterruptedError) return 1; + throw error; } finally { for (const [signal, handler] of signalHandlers) process.off(signal, handler); + children.stop(); await cleanUpOnce(); } } @@ -165,10 +183,54 @@ export async function runWatchCli(argv) { /** Conventional exit code (128 + signal number) for each signal the watch cleans up on. */ const SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 }; +/** Longest the signal handler waits for watchUrl to wind down before removing the dirs anyway. */ +const INTERRUPT_SETTLE_MS = 10_000; + +class InterruptedError extends Error { + constructor() { + super("watch interrupted"); + this.name = "InterruptedError"; + } +} + +/** + * Track every child the run spawns (yt-dlp, ffmpeg, ...) so a signal can end them. + * The shared spawn helper keeps no handle on its children, so `spawn` is wrapped + * for the life of the run; once interrupted, a child spawned late is ended at once. + * + * @param {TempDirs} temp + */ +function trackChildren(temp) { + const originalSpawn = childProcess.spawn; + /** @type {Set} */ + const live = new Set(); + childProcess.spawn = /** @type {typeof childProcess.spawn} */ ( + function trackedSpawn(...args) { + const child = originalSpawn.apply(this, args); + live.add(child); + child.once("close", () => live.delete(child)); + if (temp.interrupted) child.kill("SIGKILL"); + return child; + } + ); + syncBuiltinESMExports(); + return { + interrupt() { + temp.interrupted = true; + for (const child of live) child.kill("SIGKILL"); + }, + stop() { + childProcess.spawn = originalSpawn; + syncBuiltinESMExports(); + }, + }; +} + /** * @typedef {Object} TempDirs * @property {{ workDir?: string, framesDir?: string, contactSheetsDir?: string }} dirs - created by this run * @property {boolean} recorded - true once watch.json holds them as tempSession + * @property {boolean} interrupted - set by a signal; watchUrl then creates and records nothing more */ /** @@ -183,13 +245,20 @@ const SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 }; * }} options */ async function watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFrameGapSec, temp }) { + const throwIfInterrupted = () => { + if (temp.interrupted) throw new InterruptedError(); + }; + throwIfInterrupted(); // Temp dirs retained for vision reads in the same session; regen via run-watch when missing. const workDir = await fs.mkdtemp(path.join(os.tmpdir(), "video-extraction-")); temp.dirs.workDir = workDir; + throwIfInterrupted(); const framesDir = await fs.mkdtemp(path.join(os.tmpdir(), "video-frames-")); temp.dirs.framesDir = framesDir; + throwIfInterrupted(); const sheetsDir = await fs.mkdtemp(path.join(os.tmpdir(), "video-sheets-")); temp.dirs.contactSheetsDir = sheetsDir; + throwIfInterrupted(); /** @type {import('../adapters/adapter-contract.js').AcquireOutcome} */ let acquisition; @@ -203,6 +272,7 @@ async function watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFr } throw error; } + throwIfInterrupted(); if (!acquisition.success || !acquisition.data) { writeStderr(acquisition.error ?? "Acquisition failed"); return 1; @@ -294,6 +364,7 @@ async function watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFr next = markPhaseComplete(next, "research", { skipped: true }); } + throwIfInterrupted(); await writeWatchState(sliceDir, next); temp.recorded = true; const continuationPrompt = await writeContinuationPrompt(sliceDir, next); @@ -360,8 +431,10 @@ async function watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFr // detectRecoverableBootstrap can discover (it requires the file to exist). state.status = "watching"; writeStderr("watch: watching start"); + throwIfInterrupted(); await writeWatchState(sliceDir, state); temp.recorded = true; + throwIfInterrupted(); const watching = await orchestrateWatching({ videoPath: primary.mediaPath, From 181b1f67caca6d58d815b02b8939db7f2a6f8129 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:39:25 -0400 Subject: [PATCH 3/6] fix(knowledge): stop a watch interrupted during frame extraction and type its exit code A signal during orchestrateWatching killed ffmpeg, which yields a degraded result rather than a rejection, so the run went on to write the watching manifest and README from killed work. It now stops right after orchestrateWatching. The in-flight promise is typed Promise, which clears the tsc error on process.exitCode. Co-Authored-By: Claude Opus 5.5 --- .../watch/run-watch-signal-watching.test.js | 110 ++++++++++++++++++ .../extraction/watch/run-watch.js | 4 +- 2 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal-watching.test.js diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal-watching.test.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal-watching.test.js new file mode 100644 index 00000000000..751661e3952 --- /dev/null +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal-watching.test.js @@ -0,0 +1,110 @@ +/** + * A signal that lands while frame extraction runs stops the watch before it writes + * anything from the killed work: no watching manifest, and the run reports failure. + * The signal handler is invoked in-process, with process.exit stubbed. + */ + +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { createAcquisitionEnvelope } from "../adapters/adapter-contract.js"; +import { acquireMedia } from "../adapters/registry.js"; +import { orchestrateWatching } from "../watching/orchestrate-watching.js"; +import { writeWatchingManifest } from "../watching/write-watching-manifest.js"; +import { runWatchCli } from "./run-watch.js"; + +vi.mock("@melodic/video-digestion/shared/terminal", () => ({ + writeStderr: () => {}, + writeStdout: () => {}, +})); + +vi.mock("../adapters/registry.js", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, acquireMedia: vi.fn() }; +}); + +vi.mock("../transcript/asr-transcribe.js", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, detectAsrCapability: vi.fn(async () => ({ available: false })) }; +}); + +vi.mock("../watching/orchestrate-watching.js", () => ({ orchestrateWatching: vi.fn() })); + +vi.mock("../watching/write-watching-manifest.js", () => ({ + writeWatchingManifest: vi.fn(async () => ({ + selectionPath: "selection.json", + coveragePlanPath: "coverage-plan.json", + frameCount: 0, + contactSheetCount: 0, + })), +})); + +const URL = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"; +const ENV_KEYS = ["TMPDIR", "TEMP", "TMP"]; + +/** @type {string} */ +let sandbox; +/** @type {Record} */ +let savedEnv; + +describe("run-watch interrupted during frame extraction", () => { + beforeEach(async () => { + sandbox = await fs.mkdtemp(path.join(os.tmpdir(), "watch-signal-watching-")); + const fakeTmp = path.join(sandbox, "tmp"); + await fs.mkdir(fakeTmp); + savedEnv = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]])); + for (const key of ENV_KEYS) process.env[key] = fakeTmp; + process.env.YOUTUBE_WORK_ROOT = path.join(sandbox, "work"); + vi.mocked(acquireMedia).mockReset(); + vi.mocked(orchestrateWatching).mockReset(); + vi.mocked(writeWatchingManifest).mockClear(); + vi.spyOn(process, "exit").mockImplementation(/** @type {any} */ (() => undefined)); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + delete process.env.YOUTUBE_WORK_ROOT; + await fs.rm(sandbox, { recursive: true, force: true }); + }); + + it("writes no watching manifest and returns 1 when SIGTERM lands mid-extraction", async () => { + vi.mocked(acquireMedia).mockImplementation(async (_url, { workDir }) => { + const mediaPath = path.join(workDir, "dQw4w9WgXcQ.mp4"); + const metadataPath = path.join(workDir, "dQw4w9WgXcQ.info.json"); + await fs.writeFile(mediaPath, "binary"); + await fs.writeFile(metadataPath, "{}"); + return { + success: true, + data: createAcquisitionEnvelope({ + entries: [{ mediaPath, captionPaths: [], metadataPath, caption: null }], + metadata: { id: "dQw4w9WgXcQ", title: "Fixture Talk", description: "", chapters: [], comments: [] }, + workDir, + }), + }; + }); + vi.mocked(orchestrateWatching).mockImplementation(async () => { + const handler = /** @type {() => void} */ (process.listeners("SIGTERM").at(-1)); + handler(); + // A killed ffmpeg leaves a degraded result rather than a rejection. + return /** @type {any} */ ({ + selectedFrames: [], + targetMinFrames: 0, + highVolume: false, + candidateCount: 0, + probedDurationSec: null, + densificationWindows: [], + }); + }); + + expect(await runWatchCli(["node", "run-watch.js", URL])).toBe(1); + expect(vi.mocked(orchestrateWatching)).toHaveBeenCalledOnce(); + expect(vi.mocked(writeWatchingManifest)).not.toHaveBeenCalled(); + }); +}); diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js index c76f2975d5c..a49f3ebd47a 100755 --- a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js @@ -151,7 +151,7 @@ export async function runWatchCli(argv) { : removeRecordedTempSessionDirs(temp.dirs, "watch"); return cleanup; }; - /** @type {Promise | null} */ + /** @type {Promise | null} */ let running = null; const signalHandlers = Object.entries(SIGNAL_EXIT_CODES).map(([signal, code]) => { const handler = () => { @@ -451,6 +451,8 @@ async function watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFr cues, maxFrameGapSec, }); + // A killed ffmpeg yields a degraded result, not a rejection: write nothing from it. + throwIfInterrupted(); state.status = "vision"; state.frameSelection = { From 6eafaad7c803ff071b8c95825cb0795b07d14417 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:17:19 -0400 Subject: [PATCH 4/6] fix(knowledge): kill each watch child's process group on interrupt The signal handler SIGKILLed only the tracked direct children, so an ffmpeg that yt-dlp started could outlive it and write into the work dir after cleanup. On POSIX the tracked spawn now starts each child detached, as its own process group, and the interrupt kills the whole group. Windows keeps the direct-child kill; the gap is stated in the trackChildren comment. Co-Authored-By: Claude Opus 5.5 --- ...eo-digest-watch-signal-cleanup-6920a1c4.md | 2 +- .../extraction/watch/run-watch-signal.test.js | 45 +++++++++++++++++++ .../extraction/watch/run-watch.js | 28 ++++++++++-- 3 files changed, 70 insertions(+), 5 deletions(-) diff --git a/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md b/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md index 464cf2deddc..65e89fc20cd 100644 --- a/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md +++ b/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md @@ -4,4 +4,4 @@ bump: patch ### Fixed -- `video-digest` `run-watch.js` now removes its temp video, frame and sheet directories when SIGINT or SIGTERM interrupts a watch before `watch.json` records them, then exits `130` or `143`. Cleanup runs once, and the handlers are removed when the run ends. +- `video-digest` `run-watch.js` now removes its temp video, frame and sheet directories when SIGINT or SIGTERM interrupts a watch before `watch.json` records them, then exits `130` or `143`. On POSIX the interrupt kills each child's whole process group, so a yt-dlp ffmpeg grandchild ends too; on Windows only direct children are killed. Cleanup runs once, and the handlers are removed when the run ends. diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js index 55cc40d403b..d9da7983135 100644 --- a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js @@ -85,4 +85,49 @@ describe.skipIf(process.platform === "win32")("run-watch interrupted by a signal await new Promise((resolve) => setTimeout(resolve, 300)); expect(await watchTempDirs()).toEqual([]); }); + + it("SIGTERM also ends a grandchild the yt-dlp child started", async () => { + const grandPid = path.join(sandbox, "grandchild.pid"); + // A real yt-dlp runs ffmpeg as its own child; this one leaves a writer looping + // in the background, which outlives a SIGKILL sent to yt-dlp alone. + await fs.writeFile( + path.join(sandbox, "bin", "yt-dlp"), + `#!/bin/sh\n( while :; do\n for d in "$TMPDIR"/video-extraction-*; do\n [ -d "$d" ] && echo x >> "$d/merge.part"\n done\n sleep 0.05\ndone ) &\necho $! > "${grandPid}"\ntouch "${started}"\nwait\n`, + { mode: 0o755 }, + ); + const child = spawn(process.execPath, [RUN_WATCH, URL_UNDER_TEST], { + env: { + ...process.env, + PATH: `${path.join(sandbox, "bin")}${path.delimiter}${process.env.PATH}`, + TMPDIR: fakeTmp, + VIDEO_DIGEST_WORK_ROOT: path.join(sandbox, "work"), + }, + stdio: "ignore", + }); + const exited = new Promise((resolve) => child.on("exit", (code, sig) => resolve({ code, sig }))); + + await waitFor(() => existsSync(started)); + const pid = Number(await fs.readFile(grandPid, "utf8")); + child.kill("SIGTERM"); + expect(await exited).toEqual({ code: 143, sig: null }); + + const alive = () => { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + }; + try { + await waitFor(() => !alive(), 2_000).catch(() => {}); + expect(alive()).toBe(false); + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(await watchTempDirs()).toEqual([]); + } finally { + if (alive()) process.kill(pid, "SIGKILL"); + } + // A surviving grandchild holds yt-dlp's pipes open, so the run waits out its + // settle window before exiting; the timeout leaves room for that failure. + }, 30_000); }); diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js index 5868a573cb0..ed2e12367c9 100755 --- a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js @@ -198,19 +198,39 @@ class InterruptedError extends Error { * Track every child the run spawns (yt-dlp, ffmpeg, ...) so a signal can end them. * The shared spawn helper keeps no handle on its children, so `spawn` is wrapped * for the life of the run; once interrupted, a child spawned late is ended at once. + * On POSIX each child leads its own process group and the whole group is killed, + * so yt-dlp's ffmpeg goes with it. On Windows only the direct child is killed, and + * a grandchild can outlive the interrupt. * * @param {TempDirs} temp */ function trackChildren(temp) { const originalSpawn = childProcess.spawn; + const groups = process.platform !== "win32"; /** @type {Set} */ const live = new Set(); + /** @param {import('node:child_process').ChildProcess} child */ + const kill = (child) => { + if (groups && child.pid) { + try { + process.kill(-child.pid, "SIGKILL"); + return; + } catch { + // The group is already gone; fall through to the direct kill. + } + } + child.kill("SIGKILL"); + }; childProcess.spawn = /** @type {typeof childProcess.spawn} */ ( - function trackedSpawn(...args) { - const child = originalSpawn.apply(this, args); + function trackedSpawn(command, ...rest) { + if (groups) { + const at = rest[0] == null || Array.isArray(rest[0]) ? 1 : 0; + rest[at] = { ...rest[at], detached: true }; + } + const child = originalSpawn.call(this, command, ...rest); live.add(child); child.once("close", () => live.delete(child)); - if (temp.interrupted) child.kill("SIGKILL"); + if (temp.interrupted) kill(child); return child; } ); @@ -218,7 +238,7 @@ function trackChildren(temp) { return { interrupt() { temp.interrupted = true; - for (const child of live) child.kill("SIGKILL"); + for (const child of live) kill(child); }, stop() { childProcess.spawn = originalSpawn; From e9636da3b71d8ae4aa11a8b1f9b1168c18b45512 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:19:28 -0400 Subject: [PATCH 5/6] fix(knowledge): end the watch child groups on SIGHUP too The children now run in their own process groups, so a closed terminal no longer reaches yt-dlp or ffmpeg. SIGHUP joins SIGINT and SIGTERM on the same interrupt handler and exits 129 (128 + signal). Co-Authored-By: Claude Opus 5.5 --- ...fix-video-digest-watch-signal-cleanup-6920a1c4.md | 2 +- .../extraction/watch/run-watch-signal.test.js | 12 +++++++----- .../video-digest/extraction/watch/run-watch.js | 2 +- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md b/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md index 65e89fc20cd..26c0768bcb6 100644 --- a/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md +++ b/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md @@ -4,4 +4,4 @@ bump: patch ### Fixed -- `video-digest` `run-watch.js` now removes its temp video, frame and sheet directories when SIGINT or SIGTERM interrupts a watch before `watch.json` records them, then exits `130` or `143`. On POSIX the interrupt kills each child's whole process group, so a yt-dlp ffmpeg grandchild ends too; on Windows only direct children are killed. Cleanup runs once, and the handlers are removed when the run ends. +- `video-digest` `run-watch.js` now removes its temp video, frame and sheet directories when SIGHUP, SIGINT or SIGTERM interrupts a watch before `watch.json` records them, then exits `129`, `130` or `143`. On POSIX the interrupt kills each child's whole process group, so a yt-dlp ffmpeg grandchild ends too; on Windows only direct children are killed. Cleanup runs once, and the handlers are removed when the run ends. diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js index d9da7983135..1950802d648 100644 --- a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js @@ -1,5 +1,5 @@ /** - * A watch killed by SIGINT or SIGTERM during acquisition removes the temp dirs it + * A watch killed by SIGHUP, SIGINT or SIGTERM during acquisition removes the temp dirs it * made and exits with the conventional signal code. A real child run is used: a * fake `yt-dlp` on PATH blocks the acquisition so the signal lands mid-download. * POSIX only (the fake yt-dlp is a shell script). @@ -86,7 +86,10 @@ describe.skipIf(process.platform === "win32")("run-watch interrupted by a signal expect(await watchTempDirs()).toEqual([]); }); - it("SIGTERM also ends a grandchild the yt-dlp child started", async () => { + it.each([ + ["SIGTERM", 143], + ["SIGHUP", 129], + ])("%s also ends a grandchild the yt-dlp child started", async (signal, exitCode) => { const grandPid = path.join(sandbox, "grandchild.pid"); // A real yt-dlp runs ffmpeg as its own child; this one leaves a writer looping // in the background, which outlives a SIGKILL sent to yt-dlp alone. @@ -108,9 +111,6 @@ describe.skipIf(process.platform === "win32")("run-watch interrupted by a signal await waitFor(() => existsSync(started)); const pid = Number(await fs.readFile(grandPid, "utf8")); - child.kill("SIGTERM"); - expect(await exited).toEqual({ code: 143, sig: null }); - const alive = () => { try { process.kill(pid, 0); @@ -120,6 +120,8 @@ describe.skipIf(process.platform === "win32")("run-watch interrupted by a signal } }; try { + child.kill(signal); + expect(await exited).toEqual({ code: exitCode, sig: null }); await waitFor(() => !alive(), 2_000).catch(() => {}); expect(alive()).toBe(false); await new Promise((resolve) => setTimeout(resolve, 300)); diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js index ed2e12367c9..db72e1eeb97 100755 --- a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js @@ -182,7 +182,7 @@ export async function runWatchCli(argv) { } /** Conventional exit code (128 + signal number) for each signal the watch cleans up on. */ -const SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 }; +const SIGNAL_EXIT_CODES = { SIGHUP: 129, SIGINT: 130, SIGTERM: 143 }; /** Longest the signal handler waits for watchUrl to wind down before removing the dirs anyway. */ const INTERRUPT_SETTLE_MS = 10_000; From 16743efe71e4a7374ad1ec80e1d2f4d8c75b3ff4 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Tue, 20 Oct 2026 05:19:50 -0400 Subject: [PATCH 6/6] fix(knowledge): type the shared cleanup promise for TypeScript 7 TypeScript 7 no longer widens a null-initialized local, so `let cleanup = null` failed tsc (TS2322) once this branch met main's TS7 bump (#8495) in the merge queue. The local now carries its JSDoc type. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WyWcv2NwzrPQ4dChfwFjM7 --- .../knowledge/skills/video-digest/extraction/watch/run-watch.js | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js index 98a20fc2c18..a0f11a9be69 100755 --- a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js @@ -144,6 +144,7 @@ export async function runWatchCli(argv) { const temp = { dirs: {}, recorded: false, interrupted: false }; const children = trackChildren(temp); // The signal handlers and the finally block share one cleanup, so it runs once. + /** @type {Promise | null} */ let cleanup = null; const cleanUpOnce = () => { cleanup ??= temp.recorded