@clipy/cli 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,7 @@ import { spawn } from "node:child_process";
11
11
  import { existsSync, mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";
12
12
  import { tmpdir } from "node:os";
13
13
  import { join } from "node:path";
14
+ import { BASELINE_DOWNLOAD_ARGS, DEFAULT_FORMAT, MAX_ATTEMPTS, PROGRESSIVE_FALLBACK, RETRY_BACKOFF_MS, TOKEN_FREE_CLIENT_ARGS, classifyFailure, isRetriable, retryNotice, sleep, } from "./retry.js";
14
15
  /** A 720p video-only rendition of a long talk still runs to hundreds of MB;
15
16
  * past this we are no longer "borrowing" the file. */
16
17
  const MAX_BYTES = 1_500_000_000;
@@ -65,6 +66,138 @@ function dirBytes(dir) {
65
66
  }
66
67
  return total;
67
68
  }
69
+ /** Leftovers from a failed attempt would be mistaken for a finished download. */
70
+ function clearDir(dir) {
71
+ for (const entry of readdirSync(dir))
72
+ rmSync(join(dir, entry), { recursive: true, force: true });
73
+ }
74
+ function attemptDownload(dir, input, plan) {
75
+ return new Promise((resolveRun, reject) => {
76
+ const child = spawn(input.ytDlpBin, [
77
+ "--ignore-config",
78
+ "--no-playlist",
79
+ "--no-part",
80
+ "--no-progress",
81
+ ...BASELINE_DOWNLOAD_ARGS,
82
+ ...plan.extraArgs,
83
+ "--max-filesize",
84
+ `${Math.floor(MAX_BYTES / 1_000_000)}M`,
85
+ "-f",
86
+ plan.format,
87
+ "-o",
88
+ join(dir, "source.%(ext)s"),
89
+ input.url,
90
+ ], { stdio: ["ignore", "ignore", "pipe"] });
91
+ let stderr = "";
92
+ let aborted = null;
93
+ child.stderr.on("data", (d) => {
94
+ if (stderr.length < 16_384)
95
+ stderr += d.toString("utf8");
96
+ });
97
+ // --max-filesize only knows sizes the server declared up front, so watch
98
+ // the bytes actually landing too.
99
+ const poll = setInterval(() => {
100
+ try {
101
+ if (dirBytes(dir) > MAX_BYTES) {
102
+ aborted = `the download passed the ${Math.round(MAX_BYTES / 1_000_000_000)}GB ceiling`;
103
+ child.kill("SIGKILL");
104
+ }
105
+ }
106
+ catch {
107
+ // Directory already gone; the close handler will sort it out.
108
+ }
109
+ }, SIZE_POLL_MS);
110
+ const timer = setTimeout(() => {
111
+ aborted = "the download timed out";
112
+ child.kill("SIGKILL");
113
+ }, DOWNLOAD_TIMEOUT_MS);
114
+ const done = () => {
115
+ clearInterval(poll);
116
+ clearTimeout(timer);
117
+ };
118
+ child.on("error", (e) => {
119
+ done();
120
+ reject(e);
121
+ });
122
+ child.on("close", (code) => {
123
+ done();
124
+ if (aborted) {
125
+ resolveRun({ ok: false, abort: aborted });
126
+ return;
127
+ }
128
+ if (code !== 0) {
129
+ resolveRun({ ok: false, stderr: stderr.trim() || `exit ${code}` });
130
+ return;
131
+ }
132
+ resolveRun({ ok: true });
133
+ });
134
+ });
135
+ }
136
+ /**
137
+ * Three attempts on yt-dlp's own defaults, then two escalations.
138
+ *
139
+ * The 403 this exists for is not a verdict about the video — the identical
140
+ * command succeeds a minute later, because the media URL YouTube signed has
141
+ * expired and only a fresh extraction mints a new one. Re-running the binary IS
142
+ * the re-extraction, which is why the outer loop earns its keep even though
143
+ * BASELINE_DOWNLOAD_ARGS already makes yt-dlp retry internally.
144
+ *
145
+ * The escalation ladder and the reasoning behind each rung are documented in
146
+ * docs/research/2026-07-29-ytdlp-403-fallbacks.md §3.
147
+ */
148
+ async function downloadWithRetries(dir, input) {
149
+ const base = { format: DEFAULT_FORMAT, extraArgs: [] };
150
+ let last = "";
151
+ const escalations = [
152
+ {
153
+ plan: { format: DEFAULT_FORMAT, extraArgs: TOKEN_FREE_CLIENT_ARGS },
154
+ notice: "Still blocked — trying YouTube's token-free player clients (tv, android_vr, web_embedded)…",
155
+ success: "A different player client worked — continuing with frame extraction.",
156
+ },
157
+ {
158
+ plan: PROGRESSIVE_FALLBACK,
159
+ notice: "Still blocked — falling back to a pre-muxed progressive format (lower resolution, but it downloads in one piece)…",
160
+ success: "The progressive format worked — continuing with frame extraction.",
161
+ },
162
+ ];
163
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
164
+ if (attempt > 1)
165
+ clearDir(dir);
166
+ const result = await attemptDownload(dir, input, base);
167
+ if (result.ok)
168
+ return;
169
+ if ("abort" in result)
170
+ throw new VideoUnavailableError(`${result.abort}, so frames were skipped.`);
171
+ last = result.stderr;
172
+ const kind = classifyFailure(last);
173
+ if (!isRetriable(kind)) {
174
+ throw new VideoUnavailableError(`yt-dlp could not download the video for frame extraction: ${lastLine(last)}`);
175
+ }
176
+ if (attempt === MAX_ATTEMPTS)
177
+ break;
178
+ input.notify(retryNotice(last, kind, attempt + 1, MAX_ATTEMPTS));
179
+ await sleep(RETRY_BACKOFF_MS[attempt - 1] ?? 5_000);
180
+ }
181
+ for (const step of escalations) {
182
+ input.notify(step.notice);
183
+ clearDir(dir);
184
+ const result = await attemptDownload(dir, input, step.plan);
185
+ if (result.ok) {
186
+ input.notify(step.success);
187
+ return;
188
+ }
189
+ if ("abort" in result)
190
+ throw new VideoUnavailableError(`${result.abort}, so frames were skipped.`);
191
+ last = result.stderr;
192
+ // A fatal answer from a different client is the video's real answer.
193
+ if (!isRetriable(classifyFailure(last)))
194
+ break;
195
+ }
196
+ throw new VideoUnavailableError(`yt-dlp could not download the video for frame extraction: ${lastLine(last)}`);
197
+ }
198
+ function lastLine(stderr) {
199
+ return stderr.split("\n").filter(Boolean).pop() ?? "unknown error";
200
+ }
68
201
  /**
69
202
  * Downloads a bounded rendition of a YouTube video into a temp directory.
70
203
  * Throws VideoUnavailableError when the source is out of bounds — callers treat
@@ -83,64 +216,7 @@ export async function borrowYoutubeVideo(input) {
83
216
  };
84
217
  try {
85
218
  input.notify("Downloading a low-resolution (≤720p) copy of the video for frame extraction — it is deleted the moment the frames are cut…");
86
- await new Promise((resolveRun, reject) => {
87
- const child = spawn(input.ytDlpBin, [
88
- "--ignore-config",
89
- "--no-playlist",
90
- "--no-part",
91
- "--no-progress",
92
- "--max-filesize",
93
- `${Math.floor(MAX_BYTES / 1_000_000)}M`,
94
- "-f",
95
- "bv*[height<=720]/b[height<=720]",
96
- "-o",
97
- join(dir, "source.%(ext)s"),
98
- input.url,
99
- ], { stdio: ["ignore", "ignore", "pipe"] });
100
- let stderr = "";
101
- let aborted = null;
102
- child.stderr.on("data", (d) => {
103
- if (stderr.length < 16_384)
104
- stderr += d.toString("utf8");
105
- });
106
- // --max-filesize only knows sizes the server declared up front, so watch
107
- // the bytes actually landing too.
108
- const poll = setInterval(() => {
109
- try {
110
- if (dirBytes(dir) > MAX_BYTES) {
111
- aborted = `the download passed the ${Math.round(MAX_BYTES / 1_000_000_000)}GB ceiling`;
112
- child.kill("SIGKILL");
113
- }
114
- }
115
- catch {
116
- // Directory already gone; the close handler will sort it out.
117
- }
118
- }, SIZE_POLL_MS);
119
- const timer = setTimeout(() => {
120
- aborted = "the download timed out";
121
- child.kill("SIGKILL");
122
- }, DOWNLOAD_TIMEOUT_MS);
123
- const done = () => {
124
- clearInterval(poll);
125
- clearTimeout(timer);
126
- };
127
- child.on("error", (e) => {
128
- done();
129
- reject(e);
130
- });
131
- child.on("close", (code) => {
132
- done();
133
- if (aborted) {
134
- reject(new VideoUnavailableError(`${aborted}, so frames were skipped.`));
135
- return;
136
- }
137
- if (code !== 0) {
138
- reject(new VideoUnavailableError(`yt-dlp could not download the video for frame extraction: ${stderr.trim().split("\n").pop() ?? `exit ${code}`}`));
139
- return;
140
- }
141
- resolveRun();
142
- });
143
- });
219
+ await downloadWithRetries(dir, input);
144
220
  const file = readdirSync(dir).find((f) => f.startsWith("source."));
145
221
  if (!file || !existsSync(join(dir, file)) || statSync(join(dir, file)).size === 0) {
146
222
  throw new VideoUnavailableError("the download produced no usable video file, so frames were skipped.");
@@ -0,0 +1,68 @@
1
+ /**
2
+ * YouTube URL → video id, tolerantly.
3
+ *
4
+ * The motivating failure: zsh users copy a URL and escape it, so the CLI is
5
+ * handed `https://www.youtube.com/watch\?v\=77FB-LS0Bjk` with literal
6
+ * backslashes. Passed through verbatim, yt-dlp does not error on that — it
7
+ * resolves it to a placeholder video ("Press Subscribe to continue", 0:00) and
8
+ * the user gets a bundle for a video they never asked for. So nothing raw ever
9
+ * reaches yt-dlp: we extract the id and rebuild the canonical URL ourselves.
10
+ */
11
+ /** YouTube ids are exactly 11 chars of base64url. */
12
+ const VIDEO_ID = /^[A-Za-z0-9_-]{11}$/;
13
+ /** Shell escaping and stray whitespace are noise, never meaning, in a URL. */
14
+ function deEscape(raw) {
15
+ return raw.trim().replace(/\\/g, "").replace(/\s+/g, "");
16
+ }
17
+ const YOUTUBE_HOSTS = new Set([
18
+ "youtube.com",
19
+ "www.youtube.com",
20
+ "m.youtube.com",
21
+ "music.youtube.com",
22
+ "youtube-nocookie.com",
23
+ "www.youtube-nocookie.com",
24
+ "youtu.be",
25
+ "www.youtu.be",
26
+ ]);
27
+ /** The path forms that carry the id as their first segment. */
28
+ const PATH_PREFIXES = ["shorts", "live", "embed", "v"];
29
+ export function isYoutubeHost(host) {
30
+ return YOUTUBE_HOSTS.has(host.toLowerCase());
31
+ }
32
+ /**
33
+ * Returns the 11-char video id, or null if this is not a recognisable
34
+ * single-video YouTube URL (a channel, a playlist-only link, or garbage).
35
+ */
36
+ export function parseYoutubeId(raw) {
37
+ const cleaned = deEscape(raw);
38
+ let url = null;
39
+ try {
40
+ url = new URL(cleaned);
41
+ }
42
+ catch {
43
+ url = null;
44
+ }
45
+ if (url && isYoutubeHost(url.hostname)) {
46
+ const v = url.searchParams.get("v");
47
+ if (v && VIDEO_ID.test(v))
48
+ return v;
49
+ const segments = url.pathname.split("/").filter(Boolean);
50
+ if (url.hostname.toLowerCase().endsWith("youtu.be")) {
51
+ if (segments[0] && VIDEO_ID.test(segments[0]))
52
+ return segments[0];
53
+ }
54
+ if (segments.length >= 2 && PATH_PREFIXES.includes(segments[0].toLowerCase())) {
55
+ if (VIDEO_ID.test(segments[1]))
56
+ return segments[1];
57
+ }
58
+ }
59
+ // Last resort for input too mangled to parse as a URL at all (a lost scheme,
60
+ // a doubled query separator). Anchored on the YouTube-specific markers so a
61
+ // random 11-char word in an unrelated string can never match.
62
+ const loose = /(?:youtube(?:-nocookie)?\.com\/(?:watch\?(?:[^#]*&)?v=|shorts\/|live\/|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/.exec(cleaned);
63
+ return loose ? loose[1] : null;
64
+ }
65
+ /** The one URL shape every yt-dlp call and every manifest uses. */
66
+ export function canonicalYoutubeUrl(videoId) {
67
+ return `https://www.youtube.com/watch?v=${videoId}`;
68
+ }
@@ -7,13 +7,23 @@
7
7
  * we run or fan a single URL out into a channel.
8
8
  */
9
9
  import { spawn } from "node:child_process";
10
- import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
10
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync } from "node:fs";
11
11
  import { homedir, tmpdir } from "node:os";
12
12
  import { join } from "node:path";
13
13
  import { Readable } from "node:stream";
14
+ import { MAX_ATTEMPTS, RETRY_BACKOFF_MS, classifyFailure, isRetriable, retryNotice, sleep } from "./retry.js";
14
15
  import { pipeline } from "node:stream/promises";
15
16
  import { createWriteStream } from "node:fs";
16
- const RELEASE_BASE = "https://github.com/yt-dlp/yt-dlp/releases/latest/download";
17
+ /**
18
+ * NIGHTLY, not stable. yt-dlp's own README calls stable "often stale and prone
19
+ * to external breakage" and names nightly "the recommended channel for regular
20
+ * users" — and YouTube-side breakage in 2026 has repeatedly been fixed the same
21
+ * week it appeared. A stable pin means shipping known-broken extraction for
22
+ * weeks. See docs/research/2026-07-29-ytdlp-403-fallbacks.md §4.
23
+ */
24
+ const RELEASE_BASE = "https://github.com/yt-dlp/yt-dlp-nightly-builds/releases/latest/download";
25
+ /** Past this, our managed copy is refreshed before it is used. */
26
+ const MAX_BINARY_AGE_MS = 7 * 24 * 60 * 60 * 1000;
17
27
  const STDERR_CAP = 16_384;
18
28
  export function clipyBinDir() {
19
29
  return join(homedir(), ".clipy", "bin");
@@ -116,12 +126,54 @@ async function install(notify) {
116
126
  return target;
117
127
  }
118
128
  let cached = null;
129
+ /**
130
+ * Refreshes OUR copy if it has gone stale.
131
+ *
132
+ * Deliberately never touches a yt-dlp the user installed themselves: `-U` on a
133
+ * Homebrew or pipx binary either fails or fights the package manager, and
134
+ * either way it is not ours to modify. Failure here is always swallowed — a
135
+ * stale binary might still work, and an unreachable GitHub must not block an
136
+ * import that would otherwise succeed.
137
+ */
138
+ async function refreshManagedBinary(bin, notify) {
139
+ if (bin !== managedPath())
140
+ return;
141
+ let age;
142
+ try {
143
+ age = Date.now() - statSync(bin).mtimeMs;
144
+ }
145
+ catch {
146
+ return;
147
+ }
148
+ if (age < MAX_BINARY_AGE_MS)
149
+ return;
150
+ notify(`Your yt-dlp copy is ${Math.floor(age / (24 * 60 * 60 * 1000))} days old — updating it (YouTube breaks extraction often; this is Clipy's own copy, not a system install)…`);
151
+ try {
152
+ const res = await run(bin, ["-U"], 120_000);
153
+ notify(res.code === 0
154
+ ? "yt-dlp is up to date."
155
+ : "yt-dlp could not update itself — continuing with the copy you have.");
156
+ }
157
+ catch {
158
+ notify("yt-dlp could not update itself — continuing with the copy you have.");
159
+ }
160
+ // Stamp it either way: a failed check should not be retried on every import.
161
+ try {
162
+ const now = new Date();
163
+ utimesSync(bin, now, now);
164
+ }
165
+ catch {
166
+ // Best effort.
167
+ }
168
+ }
119
169
  export async function resolveYtDlp(notify) {
120
170
  if (cached)
121
171
  return cached;
122
172
  const managed = managedPath();
123
- if (existsSync(managed))
173
+ if (existsSync(managed)) {
174
+ await refreshManagedBinary(managed, notify);
124
175
  return (cached = managed);
176
+ }
125
177
  const found = onPath();
126
178
  if (found)
127
179
  return (cached = found);
@@ -159,6 +211,20 @@ export async function fetchVideoMeta(bin, url) {
159
211
  autoCaptionLangs: langKeys(info.automatic_captions),
160
212
  };
161
213
  }
214
+ /** yt-dlp marks a video's own caption track with an -orig suffix. */
215
+ function baseLang(track) {
216
+ return track.replace(/-orig$/i, "");
217
+ }
218
+ /**
219
+ * The language the video was actually spoken in, if we can tell. The -orig
220
+ * track name is the strongest signal (YouTube adds it precisely to distinguish
221
+ * the source track from its ~200 auto-translations); the metadata `language`
222
+ * field is the fallback.
223
+ */
224
+ function originalLanguage(meta) {
225
+ const tagged = [...meta.subtitleLangs, ...meta.autoCaptionLangs].find((l) => /-orig$/i.test(l));
226
+ return tagged ?? meta.language;
227
+ }
162
228
  /**
163
229
  * Picks one caption track and downloads only that track. Creator captions beat
164
230
  * auto-captions; an exact language match beats a regional variant (en-US for
@@ -175,45 +241,126 @@ function pickLang(available, want) {
175
241
  available.find((l) => l.toLowerCase().startsWith(`${base}-`)) ??
176
242
  null);
177
243
  }
178
- export async function fetchCaptions(bin, url, meta, langPref) {
244
+ /**
245
+ * Which caption track to try, in order. Exported for tests: the ranking is the
246
+ * whole feature, and it is worth asserting without a network round trip.
247
+ *
248
+ * An explicit --language is obeyed and nothing else is attempted — silently
249
+ * importing a different language than the one asked for would be worse than
250
+ * failing. Otherwise: creator captions beat machine ones, and within the
251
+ * machine ones the video's ORIGINAL language beats a translation of it,
252
+ * because YouTube's auto-translations are a translation OF a transcription and
253
+ * degrade twice over.
254
+ */
255
+ export function planCaptionAttempts(meta, explicitLanguage) {
179
256
  const attempts = [];
180
- const creator = pickLang(meta.subtitleLangs, langPref);
181
- if (creator)
182
- attempts.push({ source: "creator_captions", lang: creator, flag: "--write-subs" });
183
- const auto = pickLang(meta.autoCaptionLangs, langPref);
184
- if (auto)
185
- attempts.push({ source: "auto_captions", lang: auto, flag: "--write-auto-subs" });
257
+ const seen = new Set();
258
+ const orig = originalLanguage(meta);
259
+ const add = (track, kind) => {
260
+ if (!track || seen.has(`${kind}:${track}`))
261
+ return;
262
+ seen.add(`${kind}:${track}`);
263
+ const language = baseLang(track);
264
+ const translated = kind === "auto" && !!orig && baseLang(orig).toLowerCase() !== language.toLowerCase();
265
+ attempts.push({
266
+ track,
267
+ language,
268
+ source: kind === "creator"
269
+ ? "creator_captions"
270
+ : translated
271
+ ? "auto_captions_translated"
272
+ : "auto_captions",
273
+ ...(translated ? { translatedFrom: baseLang(orig) } : {}),
274
+ flag: kind === "creator" ? "--write-subs" : "--write-auto-subs",
275
+ });
276
+ };
277
+ if (explicitLanguage) {
278
+ add(pickLang(meta.subtitleLangs, explicitLanguage), "creator");
279
+ add(pickLang(meta.autoCaptionLangs, explicitLanguage), "auto");
280
+ return attempts;
281
+ }
282
+ // 2. Any creator track, the original language for preference.
283
+ add(orig ? pickLang(meta.subtitleLangs, orig) : null, "creator");
284
+ add(meta.subtitleLangs[0], "creator");
285
+ // 3-5. Auto: original language, then English, then whatever exists.
286
+ add(orig ? pickLang(meta.autoCaptionLangs, orig) : null, "auto");
287
+ add(pickLang(meta.autoCaptionLangs, "en"), "auto");
288
+ add(meta.autoCaptionLangs[0], "auto");
289
+ return attempts;
290
+ }
291
+ /** One human-readable phrase for a track's provenance. */
292
+ export function describeCaptions(c) {
293
+ if (c.source === "creator_captions")
294
+ return `${c.language}, creator-provided`;
295
+ if (c.source === "auto_captions_translated") {
296
+ return `${c.language}, auto-translated from ${c.translatedFrom}`;
297
+ }
298
+ return `${c.language}, auto-generated — video's original language`;
299
+ }
300
+ export async function fetchCaptions(bin, url, meta, opts = {}) {
301
+ const attempts = planCaptionAttempts(meta, opts.language);
302
+ // A track can be listed and still refuse to download — YouTube rate-limits
303
+ // (HTTP 429) under exactly the retry patterns an import produces. Reporting
304
+ // that as "this video has no captions" sends the user to fix the wrong thing.
305
+ let lastFailure = null;
186
306
  for (const attempt of attempts) {
187
- for (const format of ["json3", "vtt"]) {
188
- const dir = mkdtempSync(join(tmpdir(), "clipy-subs-"));
189
- try {
190
- const res = await run(bin, [
191
- "--ignore-config",
192
- "--no-playlist",
193
- "--skip-download",
194
- attempt.flag,
195
- "--sub-langs",
196
- attempt.lang,
197
- "--sub-format",
198
- format,
199
- "-o",
200
- join(dir, "track.%(ext)s"),
201
- url,
202
- ], 180_000);
203
- if (res.code !== 0)
204
- continue;
205
- const file = readdirSync(dir).find((f) => f.endsWith(`.${format}`));
206
- if (!file)
207
- continue;
208
- const text = readFileSync(join(dir, file), "utf8");
209
- if (!text.trim())
210
- continue;
211
- return { format, text, source: attempt.source, language: attempt.lang };
212
- }
213
- finally {
214
- rmSync(dir, { recursive: true, force: true });
307
+ opts.notify?.(`Downloading captions (${describeCaptions(attempt)})…`);
308
+ // Retrying the PREFERRED track before dropping to the next language is what
309
+ // keeps re-runs idempotent: a transient 403/429 on the original-language
310
+ // track must not silently promote a machine translation, because that would
311
+ // change the transcript under a bundle fingerprint that has not changed and
312
+ // the server would reject the re-upload as a content conflict.
313
+ for (let tryN = 1; tryN <= MAX_ATTEMPTS; tryN += 1) {
314
+ let stderr = "";
315
+ for (const format of ["json3", "vtt"]) {
316
+ const dir = mkdtempSync(join(tmpdir(), "clipy-subs-"));
317
+ try {
318
+ const res = await run(bin, [
319
+ "--ignore-config",
320
+ "--no-playlist",
321
+ "--skip-download",
322
+ attempt.flag,
323
+ "--sub-langs",
324
+ attempt.track,
325
+ "--sub-format",
326
+ format,
327
+ "-o",
328
+ join(dir, "track.%(ext)s"),
329
+ url,
330
+ ], 180_000);
331
+ if (res.code !== 0) {
332
+ stderr = res.stderr.trim();
333
+ const line = stderr.split("\n").filter(Boolean).pop();
334
+ if (line)
335
+ lastFailure = `${attempt.track}: ${line}`;
336
+ continue;
337
+ }
338
+ const file = readdirSync(dir).find((f) => f.endsWith(`.${format}`));
339
+ if (!file)
340
+ continue;
341
+ const text = readFileSync(join(dir, file), "utf8");
342
+ if (!text.trim())
343
+ continue;
344
+ return {
345
+ format,
346
+ text,
347
+ source: attempt.source,
348
+ language: attempt.language,
349
+ ...(attempt.translatedFrom ? { translatedFrom: attempt.translatedFrom } : {}),
350
+ };
351
+ }
352
+ finally {
353
+ rmSync(dir, { recursive: true, force: true });
354
+ }
215
355
  }
356
+ const kind = classifyFailure(stderr);
357
+ if (!stderr || !isRetriable(kind) || tryN === MAX_ATTEMPTS)
358
+ break;
359
+ opts.notify?.(retryNotice(stderr, kind, tryN + 1, MAX_ATTEMPTS));
360
+ await sleep(RETRY_BACKOFF_MS[tryN - 1] ?? 5_000);
216
361
  }
217
362
  }
363
+ if (lastFailure)
364
+ opts.onFailure?.(lastFailure);
218
365
  return null;
219
366
  }
@@ -40,6 +40,15 @@ function mdInline(raw) {
40
40
  .replace(/\s{2,}/g, ' ')
41
41
  .trim();
42
42
  }
43
+ /**
44
+ * For text going INSIDE a code span, where mdInline is exactly wrong: it strips
45
+ * `_`, `*` and `[]`, which silently corrupts an error code or a shell command
46
+ * the reader is meant to copy. A code span only has to survive its own fence,
47
+ * so backticks and newlines are the only things that need removing.
48
+ */
49
+ function mdCode(raw) {
50
+ return raw.replace(/[\r\n]+/g, ' ').replace(/`/g, '').trim();
51
+ }
43
52
  export function buildManifest(input) {
44
53
  return {
45
54
  bundleVersion: 1,
@@ -59,6 +68,7 @@ export function buildManifest(input) {
59
68
  ? { serverClassification: input.serverClassification }
60
69
  : {}),
61
70
  ...(input.frames && input.frames.length ? { frames: input.frames } : {}),
71
+ ...(input.completeness ? { completeness: input.completeness } : {}),
62
72
  createdAt: input.createdAt ?? new Date().toISOString(),
63
73
  };
64
74
  }
@@ -72,6 +82,7 @@ const GAP_REASON_TEXT = {
72
82
  const TRANSCRIPT_SOURCE_TEXT = {
73
83
  creator_captions: 'creator-provided captions',
74
84
  auto_captions: 'provider auto-generated captions',
85
+ auto_captions_translated: 'provider auto-generated captions, machine-translated from another language',
75
86
  user_file: 'a caption file supplied by the user',
76
87
  local_stt: 'local speech-to-text on the user’s machine',
77
88
  };
@@ -82,6 +93,34 @@ export function renderArecMarkdown(manifest, transcript, opts = {}) {
82
93
  lines.push('');
83
94
  lines.push(`# ${mdInline(manifest.title) || 'Untitled recording'}`);
84
95
  lines.push('');
96
+ // Directly under the title, before anything a reader might act on: a bundle
97
+ // that is missing evidence must say so where nobody can miss it, and a bundle
98
+ // that is transcript-only ON PURPOSE must say THAT — otherwise the two are
99
+ // indistinguishable on disk and an agent re-runs a finished import, or trusts
100
+ // an unfinished one.
101
+ const completeness = manifest.completeness;
102
+ if (completeness && completeness.status === 'incomplete') {
103
+ lines.push('## Incomplete');
104
+ lines.push('');
105
+ lines.push(`**This bundle is missing visual evidence.** ${completeness.missingFrames
106
+ ? `${completeness.missingFrames} frame${completeness.missingFrames === 1 ? '' : 's'} the classifier asked for ${completeness.missingFrames === 1 ? 'was' : 'were'} not captured`
107
+ : 'Frames the classifier asked for were not captured'}${completeness.reasonCode ? ` (\`${mdCode(completeness.reasonCode)}\`)` : ''}.`);
108
+ lines.push('');
109
+ if (completeness.reason) {
110
+ lines.push(`- Why: ${mdInline(completeness.reason)}`);
111
+ }
112
+ lines.push('- Still complete and usable: the transcript, the metadata, and the server classification below. Read them normally.');
113
+ if (completeness.rerunCommand) {
114
+ lines.push(`- To complete this bundle, re-run exactly: \`${mdCode(completeness.rerunCommand)}\``);
115
+ lines.push(' Imports are idempotent — this fills in what is missing rather than creating a second document.');
116
+ }
117
+ lines.push('');
118
+ }
119
+ else if (manifest.serverClassification &&
120
+ !manifest.serverClassification.needsVisual) {
121
+ lines.push('> This bundle is transcript-only BY DESIGN: the classifier judged the words sufficient on their own, so no frames were planned. Nothing is missing — do not re-run this import to "complete" it.');
122
+ lines.push('');
123
+ }
85
124
  lines.push('## Metadata');
86
125
  lines.push('');
87
126
  // A local import has no URL to link back to, so the file's own name plus a