Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

24.4 KB
Raw Blame
// Việc Edit video dùng chung cho REST (server), MCP và CLI: hồ sơ edits/<id>/job.json, tiến độ, hàng chờ, dọn đĩa.
// Mỗi lúc chỉ 1 edit chạy trên cả máy (khoá file edits/.edit.lock tạo độc quyền "wx", có pid; khoá của tiến trình
// đã chết được gỡ dưới một khoá phụ cũng "wx" nên hai tiến trình không thể cùng gỡ/cùng giữ).
import fs from 'node:fs';
import path from 'node:path';
import { EDITS, editDir, newEditId, editVideo, reviseEdit, manualEdit, STEPS, baseSig, cleanSig, CLEAN, manualStartStep } from './pipeline.mjs';
import { parseManual, manualView, applyPatch } from './manual.mjs';
import { isMusicName } from './studio-media.mjs';
import { LAYER } from './captions-hf.mjs';
import { listStyles, loadStyle, parseNames, STYLES_DIR } from './planner.mjs';
import { setupStatus } from './env.mjs';
import { resolveEditStyle } from '../packs/registry.mjs';
import { probeSource } from './ingest.mjs';
import { redact } from '../server/logs.mjs';
import { withFrame, frameOf } from './edl.mjs';
import { normRatio } from '../engine/ratio.mjs';

export { STEPS, EDITS, newEditId, editDir };
export const ID_RE = /^[\w-]{1,80}$/;
const LOCK = path.join(EDITS, '.edit.lock');
const BREAKER = path.join(EDITS, '.edit.lock.break');
const readJson = (f, d = null) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return d; } };
export const pidAlive = (pid) => { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
const jobFile = (id) => path.join(editDir(id), 'job.json');

/** Tên file MP4 mới nhất (out.mp4 hoặc out-r<n>.mp4 sau mỗi lần sửa), null nếu chưa có. */
export function currentOut(id) {
  const st = readJson(path.join(editDir(id), 'state.json'), {});
  for (const f of [st.out, 'out.mp4']) if (f && /^out(-r\d{1,4})?\.mp4$/.test(f) && fs.existsSync(path.join(editDir(id), f))) return f;
  return null;
}

function writeJob(id, patch) {
  const cur = readJson(jobFile(id), {});
  const next = { ...cur, ...patch, id, updatedAt: new Date().toISOString() };
  fs.mkdirSync(editDir(id), { recursive: true });
  const tmp = jobFile(id) + `.${process.pid}.tmp`;
  fs.writeFileSync(tmp, JSON.stringify(next, null, 1));
  fs.renameSync(tmp, jobFile(id));
  return next;
}

/**
 * Job "queued"/"running" mà tiến trình giữ nó đã chết (CLI/MCP bị tắt, máy khởi động lại) → tự chuyển sang
 * error (dựng lần đầu) hoặc done + reviseError (sửa, bản cũ vẫn còn), kèm lý do. Gọi ở mọi lần đọc.
 */
function reapIfDead(job) {
  if (!job || !['queued', 'running'].includes(job.status) || pidAlive(job.pid)) return job;
  const why = `bị ngắt giữa chừng (tiến trình ${job.pid || '?'} đã tắt lúc "${job.step || 'chờ lượt'}")`;
  if (['revise', 'manual'].includes(job.action) && currentOut(job.id)) return writeJob(job.id, { status: 'done', reviseError: why + ' — bấm Render lại' });
  return writeJob(job.id, { status: 'error', error: why + ' — bấm Dựng lại' });
}

export function readEditJob(id) {
  if (!ID_RE.test(String(id))) return null;
  return reapIfDead(readJson(jobFile(id)));
}

/** Ảnh minh hoạ dọc của từng kiểu (khung từ bản demo), server phục vụ ở /edit-styles/thumbs/<id>.webp. */
export const STYLE_THUMBS = path.join(STYLES_DIR, 'thumbs');

/** Kiểu edit có sẵn (cho UI/MCP): tên + tóm tắt VI/EN, ảnh minh hoạ (nếu có), màu nhấn, độ dài mặc định. */
export function editStyles() {
  return listStyles().map((id) => {
    const s = loadStyle(id);
    const builtin = (s.source || 'builtin') === 'builtin';
    // ảnh của cách dựng trong gói: packs/http.mjs phục vụ ở /pack-thumbs/<packId>/edit-style-<slug>.webp
    const r = builtin ? null : resolveEditStyle(id);
    const thumb = builtin ? (fs.existsSync(path.join(STYLE_THUMBS, `${id}.webp`)) ? `/edit-styles/thumbs/${id}.webp` : null)
      : r?.thumbFile ? `/pack-thumbs/${r.packId}/edit-style-${r.slug}.webp` : null;
    return {
      id, source: s.source || 'builtin', ...(r ? { packId: r.packId, restricted: true } : {}), order: builtin ? (s.order ?? 99) : 200 + (Number(s.order) || 0), name: s.name, nameEn: s.nameEn || s.name,
      summary: s.summary || s.guide.split('\n').find((l) => l.trim() && !l.startsWith('#')) || '', summaryEn: s.summaryEn || '',
      thumb, accent: s.graphics?.accent || s.look?.hi || null, target: s.target ?? null,
    };
  }).sort((a, b) => a.order - b.order);
}

/** Đã cài đủ chưa (python, gói, model whisper, model mặt/người, font). UI hiện hướng dẫn cài nếu chưa. */
export function editReady() {
  const st = setupStatus();
  return {
    ready: st.ready, missing: st.missing, setup: 'node edit/setup.mjs',
    note: st.ready ? '' : `Chưa cài đủ phần Edit video (thiếu: ${st.missing.join(', ')}). Cần Python 3.10–3.12, ~6 GB gồm whisper large-v3. Chạy trong thư mục LumReels: node edit/setup.mjs`,
  };
}

/** ffprobe ngay khi tạo: video phải có hình + độ dài > 0; nhạc phải có tiếng. Lỗi → throw (chưa chạy whisper/LLM). */
export async function checkMedia(video, music) {
  let info;
  try { info = await probeSource(video); } catch (e) { throw new Error(`không đọc được video (${path.basename(video)}): ${e.message}`); }
  if (!Number.isFinite(info.duration) || info.duration < 1) throw new Error('video quá ngắn hoặc hỏng (dưới 1 giây)');
  if (!info.hasAudio) throw new Error('video không có tiếng: cần tiếng nói để cắt và làm phụ đề');
  if (info.duration > 30 * 60) throw new Error(`video dài ${Math.round(info.duration / 60)} phút; tối đa 30 phút`);
  if (music) await checkMusic(music);
  return info;
}

/** File nhạc phải có luồng tiếng đọc được (ffprobe). Lỗi → throw. */
export async function checkMusic(music) {
  const { run } = await import('../engine/lib.mjs');
  const r = await run('ffprobe', ['-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=codec_type:format=duration', '-of', 'json', music]);
  let j = null; try { j = JSON.parse(r.out); } catch { /* bỏ qua */ }
  if (!j?.streams?.length) throw new Error(`file nhạc ${path.basename(music)} không có tiếng hoặc hỏng`);
}

/**
 * Tạo hồ sơ edit (chưa chạy). input: {id?, video, style, ratio? (9:16 · 16:9 · 4:3 · 3:4), music?, musicName?, content?, names?, draft?, llm?, sourceName?}
 * Kiểm kiểu edit, file và ffprobe trước khi ghi job.json.
 */
export async function createEdit(input) {
  const id = input.id || newEditId();
  if (!ID_RE.test(id)) throw new Error('id không hợp lệ');
  const video = path.resolve(String(input.video || ''));
  if (!input.video || !fs.existsSync(video) || !fs.statSync(video).isFile()) throw new Error(`không thấy video ${input.video || ''}`);
  const style = String(input.style || 'sach-gon');
  if (!listStyles().includes(style)) throw new Error(`không có kiểu edit "${style}" (có: ${listStyles().join(', ')})`);
  const music = input.music ? path.resolve(String(input.music)) : null;
  if (music && (!fs.existsSync(music) || !fs.statSync(music).isFile())) throw new Error(`không thấy file nhạc ${input.music}`);
  let ratio;
  try { ratio = normRatio(input.ratio); } catch (e) { throw Object.assign(e, { code: 400 }); }
  const info = await checkMedia(video, music);
  const content = String(input.content || '').slice(0, 2000);
  const target = parseTarget(input.target);
  if (target && target >= info.duration) throw Object.assign(new Error(`--target ${target} s không ngắn hơn video (${Math.round(info.duration)} s)`), { code: 400 });
  return writeJob(id, {
    status: 'queued', action: 'edit', step: null, stepIndex: -1, stepTotal: STEPS.length, pct: 0, note: '',
    source: video, sourceName: input.sourceName || path.basename(video), sourceSeconds: +info.duration.toFixed(2),
    style, ratio, music, musicName: input.musicName || (music ? path.basename(music) : null),
    content, names: parseNames(input.names), draft: !!input.draft, llm: input.llm === 'off' ? 'off' : 'on', target, noMusic: !music && !!input.noMusic,
    ...(input.keepAll ? { keepAll: true, reel: input.reel || null, script: String(input.script || '').slice(0, 4000), musicGainDb: Number.isFinite(input.musicGainDb) ? input.musicGainDb : null } : {}),
    createdAt: new Date().toISOString(), error: null, out: null, pid: process.pid,
  });
}

/** --target (giây của short muốn ra): rỗng → null; số nguyên 15–180, sai → throw 400. */
export function parseTarget(v) {
  if (v === undefined || v === null || v === '' || v === false) return null;
  const n = Number(v);
  if (!Number.isFinite(n) || n < 15 || n > 180) throw Object.assign(new Error('target phải là số giây 15–180 (vd 45)'), { code: 400 });
  return Math.round(n);
}

// ---- khoá toàn máy ------------------------------------------------------------------------------------------------
function tryCreate(file, data) {
  try { fs.writeFileSync(file, data, { flag: 'wx' }); return true; } catch (e) { if (e.code === 'EEXIST') return false; throw e; }
}
/** Gỡ khoá của tiến trình đã chết, dưới khoá phụ "wx" (chỉ 1 tiến trình được gỡ, và chỉ gỡ đúng khoá đã thấy là chết). */
function breakStaleLock(seen) {
  if (!tryCreate(BREAKER, JSON.stringify({ pid: process.pid, at: Date.now() }))) {
    const b = readJson(BREAKER);
    if (!b || (!pidAlive(b.pid) && Date.now() - (b.at || 0) > 5000)) { try { fs.unlinkSync(BREAKER); } catch { /* người khác vừa gỡ */ } }
    return;
  }
  try {
    const again = readJson(LOCK);
    if (again && again.pid === seen.pid && again.at === seen.at && !pidAlive(again.pid)) fs.unlinkSync(LOCK);
  } catch { /* đã bị gỡ */ } finally { try { fs.unlinkSync(BREAKER); } catch { /* bỏ qua */ } }
}
export async function withLock(id, fn) {
  fs.mkdirSync(EDITS, { recursive: true });
  const me = { pid: process.pid, id, at: Date.now() };
  while (!tryCreate(LOCK, JSON.stringify(me))) {
    const cur = readJson(LOCK);
    if (cur && !pidAlive(cur.pid)) breakStaleLock(cur);
    else await new Promise((r) => setTimeout(r, 2000));
  }
  try { return await fn(); } finally {
    try { const cur = readJson(LOCK); if (cur?.pid === me.pid && cur?.at === me.at) fs.unlinkSync(LOCK); } catch { /* bỏ qua */ }
  }
}
/** Edit đang chiếm khoá (nếu có). */
export function editLockHolder() { const cur = readJson(LOCK); return cur && pidAlive(cur.pid) ? cur : null; }

const onProgress = (id) => (p) => writeJob(id, { step: p.step, stepIndex: p.index, stepTotal: p.total, pct: p.pct, note: p.note || '' });

// ---- dọn đĩa ---------------------------------------------------------------------------------------------------------
/**
 * Xong 1 lượt (dù được hay lỗi): xoá file trung gian lớn, chỉ giữ nguồn, edl, out*, phụ đề (index.html), log và
 * các JSON nhỏ (phân tích, chép lời, mặt) để sửa bằng lời không phải phân tích lại. Proxy dựng lại từ nguồn khi cần.
 * Giữ cho chỉnh tay: video nền (base.mp4), lớp chữ trong suốt, bản trộn tiếng (audio/mix.wav) — chỉnh nhạc thì
 * chỉ trộn lại tiếng, chỉnh chữ thì chỉ render lại lớp chữ, không phải cắt lại nền.
 */
export function cleanupEdit(id) {
  const dir = editDir(id);
  let freed = 0;
  const rm = (rel) => {
    const f = path.join(dir, rel);
    try {
      const st = fs.statSync(f);
      freed += st.isDirectory() ? dirBytes(f) : st.size;
      fs.rmSync(f, { recursive: true, force: true });
    } catch { /* không có */ }
  };
  for (const f of ['proxy.mov', 'base.words.json', 'base.face.json', path.join('captions', 'lib'), 'gfx-scene', 'qc.jpg', 'proxy.mov.part', 'preview-clean.v.mp4', 'preview-clean.part.mp4']) rm(f);
  for (const f of ['captions.webm', 'captions.mov', 'captions-png']) if (f !== LAYER.file) rm(f); // lớp chữ định dạng khác
  try { for (const f of fs.readdirSync(path.join(dir, 'audio'))) if (f !== 'mix.wav') rm(path.join('audio', f)); } catch { /* chưa có */ }
  try { for (const f of fs.readdirSync(dir)) if (/\.part\.mp4$|\.tmp$/.test(f)) rm(f); } catch { /* bỏ qua */ }
  return freed;
}
function dirBytes(d) {
  let n = 0;
  for (const e of fs.readdirSync(d, { withFileTypes: true })) {
    const f = path.join(d, e.name);
    n += e.isDirectory() ? dirBytes(f) : fs.statSync(f).size;
  }
  return n;
}

/** Xoá hẳn 1 edit (thư mục edits/<id>). Đang chạy → throw. */
export function deleteEdit(id) {
  if (!ID_RE.test(String(id))) throw new Error('id không hợp lệ');
  const job = readEditJob(id);
  if (!job) throw new Error('không thấy edit ' + id);
  if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi xoá'), { code: 409 });
  const dir = editDir(id);
  if (path.dirname(dir) !== EDITS) throw new Error('đường dẫn lạ');
  fs.rmSync(dir, { recursive: true, force: true });
  return true;
}

// ---- chạy ------------------------------------------------------------------------------------------------------------
/** Chạy dựng lần đầu (chờ khoá). log: hàm in dòng (mặc định im lặng). */
export async function runEditJob(id, { log = () => {} } = {}) {
  const job = readEditJob(id);
  if (!job) throw new Error('không thấy edit ' + id);
  writeJob(id, { status: 'queued', action: 'edit', error: null, pid: process.pid });
  return withLock(id, async () => {
    writeJob(id, { status: 'running', startedAt: new Date().toISOString(), pid: process.pid });
    let r;
    try {
      r = await editVideo(job.source, {
        id, style: job.style, ratio: job.ratio || '9:16', music: job.music, noMusic: !!job.noMusic, keepAll: !!job.keepAll, script: job.script, musicGainDb: job.musicGainDb, reel: job.reel, content: job.content, names: job.names, draft: job.draft, llm: job.llm, target: job.target, log, progress: onProgress(id),
      });
    } catch (e) { r = { ok: false, id, error: e.message }; }
    const freed = cleanupEdit(id);
    writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, error: null, freedBytes: freed } : { status: 'error', error: r.error, freedBytes: freed });
    return r;
  });
}

/**
 * Sửa bằng lời rồi render lại. Kiểm đầu vào NGAY (throw đồng bộ: REST trả 4xx), rồi trả Promise chạy nền.
 * Lỗi lúc chạy thì bản cũ vẫn giữ (status về done, ghi reviseError).
 */
export function reviseEditJob(id, instruction, { log = () => {} } = {}) {
  const job = readEditJob(id);
  if (!job) throw Object.assign(new Error('không thấy edit ' + id), { code: 404 });
  if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi sửa'), { code: 409 });
  if (!fs.existsSync(path.join(editDir(id), 'state.json'))) throw Object.assign(new Error('edit này chưa dựng xong lần đầu'), { code: 409 });
  const text = String(instruction || '').trim();
  if (!text) throw Object.assign(new Error('thiếu lời sửa'), { code: 400 });
  if (text.length > 1000) throw Object.assign(new Error('lời sửa quá dài (tối đa 1000 ký tự)'), { code: 413 });
  writeJob(id, { status: 'queued', action: 'revise', instruction: text, reviseError: null, pid: process.pid });
  return withLock(id, async () => {
    writeJob(id, { status: 'running', startedAt: new Date().toISOString(), stepIndex: 2, pid: process.pid });
    let r;
    try { r = await reviseEdit(id, text, { log, progress: onProgress(id) }); } catch (e) { r = { ok: false, id, error: e.message }; }
    const freed = cleanupEdit(id);
    const hasOut = !!currentOut(id);
    writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, reviseError: null, freedBytes: freed }
      : { status: hasOut ? 'done' : 'error', reviseError: r.error, error: hasOut ? null : r.error, freedBytes: freed });
    return r;
  });
}

/** Tên gốc của file nhạc tải lên cho chỉnh tay: edits/<id>/uploads.json {music-up-<n>.<ext>: tên gốc}. */
export function musicUploads(id) { return readJson(path.join(editDir(id), 'uploads.json'), {}); }
export function addMusicUpload(id, file, name) {
  const all = musicUploads(id); all[file] = String(name || file).slice(0, 120);
  fs.writeFileSync(path.join(editDir(id), 'uploads.json'), JSON.stringify(all, null, 1));
  return all;
}

/**
 * Những gì chỉnh tay được (bảng phụ đề, nhạc, giọng, sfx, zoom, đồ hoạ) của bản hiện tại. null nếu chưa dựng xong.
 * rev (số bản, 0 = bản gốc out.mp4): xem lại bản cũ, chỉ đọc (EDL lấy từ versions/edl-<rev+1>.json).
 * Kèm media cho Studio: video nền không chữ (base.mp4, khi chữ ký nền khớp EDL) để vẽ phụ đề xem trước, file nhạc, các bản.
 */
export function manualState(id, rev = null) {
  if (!ID_RE.test(String(id))) return null;
  const dir = editDir(id);
  const state = readJson(path.join(dir, 'state.json'));
  let edl = readJson(path.join(dir, 'edl.json'));
  if (!edl || !state) return null;
  const revs = state.revisions || [];
  const latest = revs.length;
  let n = latest;
  if (rev !== null && rev !== undefined && rev !== '') {
    n = Number(rev);
    if (!Number.isInteger(n) || n < 0 || n > latest) throw Object.assign(new Error(`không có bản r${rev} (có r0–r${latest})`), { code: 404 });
    if (n < latest) {
      edl = readJson(path.join(dir, 'versions', `edl-${n + 1}.json`));
      if (!edl) throw Object.assign(new Error(`bản r${n} không còn EDL`), { code: 404 });
    }
  }
  const lookNames = Object.fromEntries(editStyles().map((s) => [s.id, { name: s.name, nameEn: s.nameEn }]));
  const v = withFrame(edl, () => manualView(edl, state, { lookNames, uploads: musicUploads(id) })); // khung của bản đang xem
  const has = (f) => fs.existsSync(path.join(dir, f));
  const stamp = (f) => { try { return Math.round(fs.statSync(path.join(dir, f)).mtimeMs); } catch { return 0; } };
  const url = (f) => `/edits/${id}/${f}?v=${stamp(f)}`;
  const outOf = (k) => (k === 0 ? 'out.mp4' : revs[k - 1]?.out);
  const sig = readJson(path.join(dir, 'render.sig.json'), {});
  const baseOk = n === latest && has('base.mp4') && sig.base === baseSig(edl, state.draft);
  const cleanOk = n === latest && has(CLEAN) && sig.clean === cleanSig(edl);
  const mf = edl.music?.file && path.dirname(path.resolve(edl.music.file)) === path.resolve(dir) && isMusicName(path.basename(edl.music.file)) ? path.basename(edl.music.file) : null;
  v.rev = n; v.latest = latest; v.readOnly = n !== latest;
  const job = readEditJob(id);
  v.reel = job?.reel || null; v.keepAll = !!job?.keepAll;
  v.media = {
    out: outOf(n) && has(outOf(n)) ? url(outOf(n)) : null, outName: outOf(n) || null,
    base: baseOk ? url('base.mp4') : null, clean: cleanOk ? url(CLEAN) : null, music: mf && has(mf) ? url(mf) : null, musicFile: mf && has(mf) ? mf : null,
  };
  // khung mặt bản ra (lumedit faces, mỗi 0,25 s): tâm zoom xem trước bằng CSS (như lumedit Zooms: tâm đầu lúc zoom bắt đầu)
  const fo = readJson(path.join(dir, 'faces-out.json'));
  v.faces = fo && Array.isArray(fo.boxes) ? { step: fo.step || 0.25, boxes: fo.boxes.map(([tt, b]) => [+Number(tt).toFixed(2), Array.isArray(b) ? b.map((x) => Math.round(x)) : null]) } : null;
  v.versions = [{ n: 0, out: has('out.mp4') ? 'out.mp4' : null }, ...revs.map((r) => ({ n: r.n, out: r.out && has(r.out) ? r.out : null, manual: !!r.manual, instruction: r.instruction || '', at: r.at || null }))];
  return v;
}

/**
 * Chỉnh tay rồi dựng lại phần cần thiết. Kiểm đầu vào NGAY (schema chặt; throw đồng bộ → REST 4xx), rồi chạy nền.
 * Lỗi lúc chạy thì bản cũ vẫn giữ (status về done, ghi reviseError).
 */
export function manualEditJob(id, body, { log = () => {} } = {}) {
  const job = readEditJob(id);
  if (!job) throw Object.assign(new Error('không thấy edit ' + id), { code: 404 });
  if (['queued', 'running'].includes(job.status)) throw Object.assign(new Error('edit này đang chạy, chờ xong rồi chỉnh'), { code: 409 });
  if (!fs.existsSync(path.join(editDir(id), 'state.json')) || !currentOut(id)) throw Object.assign(new Error('edit này chưa dựng xong lần đầu'), { code: 409 });
  const patch = parseManual(body);
  // thử áp lên EDL hiện tại ngay (zoom/đồ hoạ không có, dòng đè nhau, bản nháp, không đổi gì…) → 4xx đồng bộ, không xếp hàng
  const dir = editDir(id);
  const st = readJson(path.join(dir, 'state.json'), {});
  let style = null; try { style = loadStyle(st.style); } catch { /* kiểu đã xoá */ }
  const cur = readJson(path.join(dir, 'edl.json'));
  const ap = withFrame(patch.ratio || cur, () => applyPatch(cur, st, patch, { dir, style, uploads: musicUploads(id) }));
  const from = manualStartStep(dir, ap.edl, st.draft);
  writeJob(id, { status: 'queued', action: 'manual', instruction: null, reviseError: null, pid: process.pid, stepFrom: from, stepIndex: from, step: STEPS[from], pct: 0 });
  return withLock(id, async () => {
    writeJob(id, { status: 'running', startedAt: new Date().toISOString(), stepIndex: from, step: STEPS[from], pct: 0, pid: process.pid });
    let r;
    try { r = await manualEdit(id, patch, { log, progress: onProgress(id), uploads: musicUploads(id) }); } catch (e) { r = { ok: false, id, error: e.message }; }
    const freed = cleanupEdit(id);
    const hasOut = !!currentOut(id);
    writeJob(id, r.ok ? { status: 'done', out: r.out, pct: 100, reviseError: null, freedBytes: freed }
      : { status: hasOut ? 'done' : 'error', reviseError: r.error, error: hasOut ? null : r.error, freedBytes: freed });
    return r;
  });
}

/** Hồ sơ đầy đủ cho UI/MCP: trạng thái, tiến độ, link file, chữ LLM đã sửa, các lần sửa, log cuối. */
export function editView(id, { withLog = true, urlBase = `/edits/${id}` } = {}) {
  const job = readEditJob(id);
  if (!job) return null;
  const dir = editDir(id);
  const has = (f) => fs.existsSync(path.join(dir, f));
  const result = readJson(path.join(dir, 'result.json'), {});
  const state = readJson(path.join(dir, 'state.json'), {});
  const stamp = (f) => { try { return Math.round(fs.statSync(path.join(dir, f)).mtimeMs); } catch { return 0; } };
  const outName = currentOut(id);
  const v = {
    ...job,
    ratio: (() => { try { return frameOf(readJson(path.join(dir, 'edl.json')) || job.ratio || '9:16').ratio; } catch { return job.ratio || '9:16'; } })(),
    styleName: (() => { try { return loadStyle(job.style).name; } catch { return job.style; } })(),
    steps: STEPS,
    fixes: result.checks?.fixes || [],
    revisions: (state.revisions || []).map((r) => ({ ...r, url: r.out && /^out-r\d{1,4}\.mp4$/.test(r.out) && has(r.out) ? `${urlBase}/${r.out}?v=${stamp(r.out)}` : null })),
    originalUrl: has('out.mp4') ? `${urlBase}/out.mp4?v=${stamp('out.mp4')}` : null,
    checks: result.checks || null,
    timings: result.timings || null,
    warnings: result.warnings || [],
    links: {
      out: outName ? `${urlBase}/${outName}?v=${stamp(outName)}` : null,
      preview: has('preview.jpg') ? `${urlBase}/preview.jpg?v=${stamp('preview.jpg')}` : null,
      previewFinal: has('preview-final.jpg') ? `${urlBase}/preview-final.jpg?v=${stamp('preview-final.jpg')}` : null,
      edl: has('edl.json') ? `${urlBase}/edl.json` : null,
    },
    files: { dir, out: outName ? path.join(dir, outName) : null, edl: has('edl.json') ? path.join(dir, 'edl.json') : null },
  };
  if (v.error) v.error = redact(v.error);
  if (v.reviseError) v.reviseError = redact(v.reviseError);
  if (withLog) {
    try { v.log = fs.readFileSync(path.join(dir, 'log.txt'), 'utf8').trim().split(/\r?\n/).slice(-40); } catch { v.log = []; }
  }
  return v;
}

export function listEdits(limit = 50) {
  if (!fs.existsSync(EDITS)) return [];
  return fs.readdirSync(EDITS).filter((d) => ID_RE.test(d) && fs.existsSync(jobFile(d)))
    .sort().reverse().slice(0, limit).map((id) => editView(id, { withLog: false })).filter(Boolean);
}

/** Server khởi động: quét mọi edit để job của tiến trình đã chết được chuyển trạng thái (readEditJob tự làm). */
export function markStaleEdits() { listEdits(500); }