Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address local review: bound the anchor window, gate usability on signal not exposure (#4666)
[._.]/ Adam Eivy4bb74dc19b52
diff --git a/server/lib/README.md b/server/lib/README.mdindex cc66a34eb2..789f469e7b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -213,7 +213,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. || `execGit.js` | `execGit(args, cwd, options)` utility imported by `git.js` + worktree manager. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). || `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. |-| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. `quality` (focus − exposure) is what `USABLE_QUALITY_FLOOR` tests — NOT `score`, or the free recency bonus on the last candidate could lift a black frame over the floor. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or nothing clears the floor, so the caller degrades rather than failing a render). `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |+| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or nothing clears the floor, so the caller degrades rather than failing a render). `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. || `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. || `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). || `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` — the run-window commit probe: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. |diff --git a/server/lib/frameQuality.js b/server/lib/frameQuality.jsindex 1c0c344bcd..83b483a0dc 100644--- a/server/lib/frameQuality.js+++ b/server/lib/frameQuality.js@@ -23,18 +23,24 @@* cut as possible. Without it the scorer drifts toward the calm* middle of the window and continuity loosens.*- * `quality` (focus − exposure) is what the usability floor tests, NOT `score`- * — otherwise the free recency bonus on the last candidate could lift a black- * frame over the floor.+ * Usability is a SEPARATE question from ranking. `usable` gates on raw gradient+ * variance alone, so only a mathematically degenerate frame (a solid fill, a+ * fully faded one) is rejected outright and a dark-but-real low-key tail still+ * qualifies. Exposure shapes the RANKING, not the gate.*/import sharp from 'sharp';-// Tail window the candidates are decoded from, and how densely. ~12 frames-// across the final 1.75s: dense enough that a blur burst doesn't cover every-// candidate, sparse enough that the decode stays well under a second.-export const TAIL_WINDOW_SECONDS = 1.75;-export const CANDIDATE_FPS = 7;+// Tail window the candidates are decoded from, and how densely.+//+// The window is deliberately capped at the reach of the single `-sseof -1.0`+// seek this replaces. Focus tends to be HIGHEST at the oldest candidate (motion,+// and therefore blur, accumulates toward the cut), so a wider window would let+// the scorer routinely anchor further from the cut than the old behavior did —+// widening the backward jump at every chain seam instead of tightening it. The+// recency bonus biases toward the cut but cannot bound the window on its own.+export const TAIL_WINDOW_SECONDS = 1.0;+export const CANDIDATE_FPS = 12;export const MAX_CANDIDATES = 12;// Gradient variance that maps to a focus of 1.0. Real sharp frames land in the@@ -42,9 +48,21 @@ export const MAX_CANDIDATES = 12;export const FOCUS_SCALE = 20000;export const EXPOSURE_WEIGHT = 0.6;export const RECENCY_WEIGHT = 0.15;-// Below this, the whole tail is unusable (black, or uniformly featureless) and-// the caller should degrade rather than anchor on it.-export const USABLE_QUALITY_FLOOR = 0.05;++// Gradient variance below which a frame carries no signal at all — a solid+// fill, a fully faded frame, or a decode that produced nothing.+//+// This, NOT the composite score, is what `usable` gates on. Gating on a+// score that includes the exposure penalty would reject a legitimately dark,+// low-key tail (mean luma 0.12 alone costs ~0.46 of quality) and silently+// revert every night scene to the unscored end seek. Same property+// `imageFrameStats.js` commits to: reject only the mathematically degenerate+// case, never dark-but-real content. Exposure still does its job in the+// RANKING, where a fade-to-black loses to its neighbours.+//+// 0.25 is (0.5 levels)^2 — half of one 8-bit level, below the smallest+// difference an encoder can represent, mirroring `SOLID_FILL_STDEV_EPSILON`.+export const MIN_SIGNAL_VARIANCE = 0.25;const clamp01 = (n) => (n < 0 ? 0 : (n > 1 ? 1 : n));@@ -110,13 +128,14 @@ export function scoreFrame(frame, { recency = 1 } = {}) {const r = clamp01(Number.isFinite(recency) ? recency : 0);const quality = focus - EXPOSURE_WEIGHT * exposurePenalty;return {+ variance,focus,luma,exposurePenalty,recency: r,quality,score: quality + RECENCY_WEIGHT * r,- usable: quality >= USABLE_QUALITY_FLOOR,+ usable: variance >= MIN_SIGNAL_VARIANCE,};}@@ -126,11 +145,20 @@ export function scoreFrame(frame, { recency = 1 } = {}) {* candidate, and must never abort a render the user already paid GPU time for.*/export async function decodeGreyscaleFrame(path, { sharpImpl = sharp } = {}) {- const decoded = await sharpImpl(path).greyscale().raw()+ // `removeAlpha()` before `greyscale()` matters: greyscale PRESERVES alpha, so+ // an RGBA source decodes to 2 interleaved channels. The buffer would still be+ // ≥ width×height bytes, so the shape check below would pass while+ // gradientVariance read alpha samples as neighbouring pixels and meanLuma+ // averaged only the first half of the image.+ const decoded = await sharpImpl(path).removeAlpha().greyscale().raw().toBuffer({ resolveWithObject: true }).catch(() => null);if (!decoded?.info) return null;- const { width, height } = decoded.info;+ const { width, height, channels } = decoded.info;+ // Belt and braces for a sharp stand-in (or a future format) that lands more+ // than one channel here anyway — interleaved data must never reach the+ // scorer, and a null simply drops this candidate.+ if (channels != null && channels !== 1) return null;const frame = { width, height, data: decoded.data };return isFrame(frame) ? frame : null;}diff --git a/server/lib/frameQuality.test.js b/server/lib/frameQuality.test.jsindex 60999a8017..9e26629fdc 100644--- a/server/lib/frameQuality.test.js+++ b/server/lib/frameQuality.test.js@@ -1,7 +1,7 @@import { describe, it, expect, vi } from 'vitest';import {gradientVariance, meanLuma, scoreFrame, pickBestFrame, decodeGreyscaleFrame,- RECENCY_WEIGHT, USABLE_QUALITY_FLOOR,+ RECENCY_WEIGHT, MIN_SIGNAL_VARIANCE,} from './frameQuality.js';// Deterministic synthetic frames — a real clip's tail can't be checked into@@ -78,23 +78,34 @@ describe('scoreFrame', () => {expect(sharp.usable).toBe(true);});- it('rejects a fade-to-black frame even with the full recency bonus', () => {- const black = scoreFrame(BLACK, { recency: 1 });- expect(black.exposurePenalty).toBe(1);- expect(black.quality).toBeLessThan(USABLE_QUALITY_FLOOR);- expect(black.usable).toBe(false);+it.each([+ ['a faded-to-black frame', BLACK],+ ['a blown highlight', WHITE],+ ['a well-exposed but featureless frame', FLAT_GREY],+ ])('rejects %s even with the full recency bonus', (_label, frame) => {+ const scored = scoreFrame(frame, { recency: 1 });+ expect(scored.variance).toBeLessThan(MIN_SIGNAL_VARIANCE);+ expect(scored.usable).toBe(false);});- it('rejects a blown highlight the same way it rejects black', () => {- expect(scoreFrame(WHITE, { recency: 1 }).usable).toBe(false);+ it('ranks a fade-to-black below a mid-grey frame of equal detail', () => {+ // Exposure is what demotes a fade — the gate above only catches the FLAT+ // case, so the ranking has to carry a dim-but-textured frame.+ const dimmed = { ...SHARP, data: SHARP.data.map((v) => Math.round(v * 0.1)) };+ expect(scoreFrame(dimmed, { recency: 1 }).score)+ .toBeLessThan(scoreFrame(SHARP, { recency: 1 }).score);});- it('rejects a well-exposed but featureless frame', () => {- // Perfect exposure alone must not qualify — a flat grey carries nothing- // for the next chunk to condition on.- const flat = scoreFrame(FLAT_GREY, { recency: 1 });- expect(flat.exposurePenalty).toBeLessThan(0.01);- expect(flat.usable).toBe(false);+ it('accepts a legitimately dark low-key frame', () => {+ // The regression this guards: gating usability on the composite score+ // rejected every night scene (mean luma 0.12 alone costs ~0.46 of quality)+ // and silently reverted them to the unscored end seek. Only mathematically+ // degenerate frames may be rejected — same contract as imageFrameStats.js.+ const lowKey = { ...SHARP, data: SHARP.data.map((v) => Math.round(v * 0.12)) };+ const scored = scoreFrame(lowKey, { recency: 0 });+ expect(scored.luma).toBeLessThan(0.2);+ expect(scored.quality).toBeLessThan(0);+ expect(scored.usable).toBe(true);});it('breaks a tie between identical frames in favour of the later one', () => {@@ -115,13 +126,19 @@ describe('scoreFrame', () => {// Minimal sharp stand-in: maps a path to a canned raw greyscale decode, or// throws for paths meant to model a partial/absent file.-const fakeSharp = (byPath) => (path) => ({+const fakeSharp = (byPath, { channels = 1, honorRemoveAlpha = true } = {}) => (path) => ({+ alphaRemoved: false,+ removeAlpha() { this.alphaRemoved = true; return this; },greyscale() { return this; },raw() { return this; },async toBuffer() {const frame = byPath[path];if (!frame) throw new Error(`ENOENT: ${path}`);- return { data: Buffer.from(frame.data), info: { width: frame.width, height: frame.height } };+ const reported = honorRemoveAlpha && this.alphaRemoved ? 1 : channels;+ return {+ data: Buffer.from(frame.data),+ info: { width: frame.width, height: frame.height, channels: reported },+ };},});@@ -130,6 +147,23 @@ describe('decodeGreyscaleFrame', () => {const sharpImpl = fakeSharp({});await expect(decodeGreyscaleFrame('/tmp/missing.png', { sharpImpl })).resolves.toBeNull();});++ it('strips alpha before greyscaling so the buffer is single-channel', async () => {+ // sharp's greyscale() PRESERVES alpha: an RGBA source would land 2+ // interleaved channels, and the scorer would read alpha samples as+ // neighbouring pixels. removeAlpha() is what collapses it to one.+ const sharpImpl = fakeSharp({ '/t/rgba.png': SHARP }, { channels: 2 });+ await expect(decodeGreyscaleFrame('/t/rgba.png', { sharpImpl })).resolves.toMatchObject({+ width: SHARP.width,+ });+ });++ it('drops a candidate that still decodes to more than one channel', async () => {+ // The shape check alone cannot catch this — an interleaved buffer is still+ // ≥ width×height bytes.+ const sharpImpl = fakeSharp({ '/t/rgba.png': SHARP }, { channels: 2, honorRemoveAlpha: false });+ await expect(decodeGreyscaleFrame('/t/rgba.png', { sharpImpl })).resolves.toBeNull();+ });});describe('pickBestFrame', () => {@@ -148,7 +182,7 @@ describe('pickBestFrame', () => {expect(best.recency).toBe(1);});- it('returns null when every candidate is unusable', async () => {+ it('returns null when every candidate is degenerate', async () => {const paths = ['/t/a.png', '/t/b.png'];const sharpImpl = fakeSharp({ '/t/a.png': BLACK, '/t/b.png': BLACK });await expect(pickBestFrame(paths, { sharpImpl })).resolves.toBeNull();diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 75944b6a53..7671237ddc 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -12,7 +12,7 @@import { execFile, spawn } from '../../lib/childProcess.js';import { existsSync, statSync } from 'fs';-import { unlink, writeFile, copyFile, rm } from 'fs/promises';+import { unlink, writeFile, copyFile, rm, rename } from 'fs/promises';import { join, basename } from 'path';import { tmpdir, totalmem } from 'os';import { randomUUID } from 'crypto';@@ -2611,7 +2611,7 @@ async function decodeTailCandidates(ffmpeg, videoPath, candidateDir) {const outPattern = join(candidateDir, 'cand-%03d.png');await new Promise((resolve) => {const proc = spawn(ffmpeg, [- '-sseof', `-${TAIL_WINDOW_SECONDS}`, '-i', videoPath,+ '-sseof', `-${TAIL_WINDOW_SECONDS.toFixed(2)}`, '-i', videoPath,'-vf', `fps=${CANDIDATE_FPS}`, '-vsync', 'vfr','-frames:v', String(MAX_CANDIDATES), '-y', outPattern,], safeChildProcessOptions({ stdio: 'ignore' }));@@ -2646,9 +2646,9 @@ async function decodeTailCandidates(ffmpeg, videoPath, candidateDir) {// and in a multi-chunk chain the next chunk inherits that blur as the scene's// actual content, compounding through every subsequent hop.//-// When no candidate clears the usability floor (a genuinely black or-// featureless tail), this falls back to the original single-seek behavior and-// says so: a degraded anchor still beats failing the chain.+// When no candidate carries any signal at all (a genuinely black or flat+// tail) or nothing decodes, this falls back to the original single-seek+// behavior and says so: a degraded anchor still beats failing the chain.export async function extractLastFrame(historyId) {// Keep this service safe for callers outside the route layer too. Shared// gallery uploads deliberately use `upload-<uuid8>` ids, while generated@@ -2749,9 +2749,17 @@ export async function extractLastFrame(historyId) {return null;}): null;+ // Copy through a temp name and rename into place. `copyFile` is not atomic,+ // and a truncated non-zero PNG at framePath would be served forever by the+ // size>0 cache hit above — the fallback's own guard only unlinks at exactly+ // zero bytes.const installed = best- ? await copyFile(best.path, framePath).then(() => true).catch((err) => {+ ? await copyFile(best.path, `${framePath}.tmp`)+ .then(() => rename(`${framePath}.tmp`, framePath))+ .then(() => true)+ .catch(async (err) => {console.log(`⚠️ Anchor install failed: ${err.message}`);+ await unlink(`${framePath}.tmp`).catch(() => {});return false;}): false;@@ -2761,9 +2769,12 @@ export async function extractLastFrame(historyId) {await rm(candidateDir, { recursive: true, force: true }).catch(() => {});if (installed) {- // Candidate i sits i/CANDIDATE_FPS into a window that starts- // TAIL_WINDOW_SECONDS before EOF, so this is its offset from the end.- const offset = TAIL_WINDOW_SECONDS - best.index / CANDIDATE_FPS;+ // Offset back from the NEWEST candidate, not from a nominal window start:+ // `-sseof` clamps to the file start on a clip shorter than the window, so+ // deriving this from TAIL_WINDOW_SECONDS would state an offset the frame+ // does not have. Measured against the candidates actually decoded, this is+ // exact in both cases.+ const offset = (candidates.length - 1 - best.index) / CANDIDATE_FPS;await writeSidecar(`-${offset.toFixed(2)}s`);console.log(`🎞️ Anchor frame ${best.index + 1}/${candidates.length} at -${offset.toFixed(2)}s (focus ${best.focus.toFixed(2)}): ${frameFilename}`);return { filename: frameFilename, path: `/data/images/${frameFilename}` };diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 0e1a07b8f7..23ca51380b 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -240,9 +240,16 @@ vi.mock('../../lib/hfCache.js', () => ({// cache MISS on a path that then exists after ffmpeg writes it — which is the// only way to reach extractLastFrame's extraction path at all, since a// stat-everything mock otherwise short-circuits on the cache hit.-const fsState = vi.hoisted(() => ({ missOnce: [] }));+const fsState = vi.hoisted(() => ({ missOnce: [], candidateCount: null }));vi.mock('fs', () => ({- existsSync: vi.fn(() => true),+ // `candidateCount` caps how many anchor candidates 'exist', so a test can+ // model ffmpeg writing fewer frames than the window asked for.+ existsSync: vi.fn((p) => {+ const s = String(p);+ if (fsState.candidateCount == null || !s.includes('anchorcand-')) return true;+ const n = s.match(/cand-(\d+)\.png$/);+ return n ? Number(n[1]) <= fsState.candidateCount : true;+ }),statSync: vi.fn((p) => {const i = fsState.missOnce.findIndex((frag) => String(p).includes(frag));if (i >= 0) { fsState.missOnce.splice(i, 1); return undefined; }@@ -349,6 +356,7 @@ beforeEach(async () => {afterEach(() => {settingsState.acceptedModelTerms = [];fsState.missOnce = [];+ fsState.candidateCount = null;anchorPick.best = null;vi.clearAllMocks();});@@ -392,33 +400,57 @@ describe('extractLastFrame — anchor selection', () => {score: 0.82,usable: true,};- const { copyFile, writeFile, rm } = await import('fs/promises');+ const { copyFile, rename, writeFile, rm } = await import('fs/promises');await expect(extractLastFrame(ID)).resolves.toEqual({filename: ANCHOR,path: `/data/images/${ANCHOR}`,});- // The winner is installed under the NEW cache name, not the legacy one.- expect(vi.mocked(copyFile)).toHaveBeenCalledWith(- anchorPick.best.path,- join(MOCK_PATHS.images, ANCHOR),- );+ // The winner is installed under the NEW cache name, not the legacy one —+ // and through a temp file, so a truncated copy can never be cached as a+ // non-zero PNG that the size>0 hit would then serve forever.+ const dest = join(MOCK_PATHS.images, ANCHOR);+ expect(vi.mocked(copyFile)).toHaveBeenCalledWith(anchorPick.best.path, `${dest}.tmp`);+ expect(vi.mocked(rename)).toHaveBeenCalledWith(`${dest}.tmp`, dest);// One decode pass over the tail window; the single-seek fallback must NOT// have run — that would mean the scored pick was thrown away.const spawns = await ffmpegSpawns();expect(spawns).toHaveLength(1);- expect(spawns[0]).toEqual(expect.arrayContaining(['-sseof', '-1.75', '-vf', 'fps=7']));+ expect(spawns[0]).toEqual(expect.arrayContaining(['-sseof', '-1.00', '-vf', 'fps=12']));expect(spawns[0]).not.toContain('-vframes');// Temp candidates are cleaned up rather than left in tmpdir.expect(vi.mocked(rm)).toHaveBeenCalledWith(join(tmpdir(), `anchorcand-${ID}`),{ recursive: true, force: true },);- // Sidecar names the offset the anchor actually came from — candidate 3 of- // a 7fps window that starts 1.75s before EOF sits 1.46s from the end.+ // Sidecar names the offset the anchor actually came from, measured back+ // from the NEWEST candidate rather than a nominal window start: 9 of the 12+ // decoded frames follow index 2, so at 12fps the pick sits 0.75s from the+ // end of the tail that was actually scanned.const sidecar = JSON.parse(vi.mocked(writeFile).mock.calls.at(-1)[1]);- expect(sidecar).toMatchObject({ filename: ANCHOR, extractedAt: '-1.46s' });+ expect(sidecar).toMatchObject({ filename: ANCHOR, extractedAt: '-0.75s' });+ });++ it('reads back exactly the candidate files it told ffmpeg to write', async () => {+ // The enumerator builds `cand-NNN.png` names by hand rather than reading the+ // directory, so nothing else checks that they match the pattern ffmpeg+ // actually received. A typo in the pattern or the padding would produce zero+ // candidates in production with every other test still green — derive the+ // expectation from the argv so the two sides can't drift apart.+ await seedHistory();+ fsState.missOnce = [ANCHOR];+ fsState.candidateCount = 3; // ffmpeg only managed three frames+ const { pickBestFrame } = await import('../../lib/frameQuality.js');++ await extractLastFrame(ID);++ const outPattern = (await ffmpegSpawns())[0].at(-1);+ expect(outPattern).toContain('%03d');+ const [scanned] = vi.mocked(pickBestFrame).mock.calls.at(-1);+ expect(scanned).toEqual([1, 2, 3].map((n) => outPattern.replace('%03d', String(n).padStart(3, '0'))));+ // Enumeration stops at the first gap instead of inventing a full window.+ expect(scanned).toHaveLength(3);});it('falls back to the end seek when no candidate is usable', async () => {@@ -901,8 +933,8 @@ describe('generateChainedVideo — continuation strategy (context window vs lastanchorPick.best = best;// One hop → one anchor cache check; miss it so extraction actually runs.fsState.missOnce = ['anchor-'];- const { copyFile } = await import('fs/promises');- vi.mocked(copyFile).mockClear();+ const { rename } = await import('fs/promises');+ vi.mocked(rename).mockClear();const { renders, innerJobIds } = await runChain({modelId: 'ltx23_unified',@@ -911,9 +943,9 @@ describe('generateChainedVideo — continuation strategy (context window vs last}, 2);expect(flagValue(renders[1], '--image')).toBeTruthy();- // A scored winner is installed under the new cache name; the fallback lets- // ffmpeg write that path directly, so there is no copy.- const installedAnchor = vi.mocked(copyFile).mock.calls+ // A scored winner is renamed into place under the new cache name; the+ // fallback lets ffmpeg write that path directly, so there is no install.+ const installedAnchor = vi.mocked(rename).mock.calls.some(([, dest]) => dest === join(MOCK_PATHS.images, `anchor-${innerJobIds[0]}.png`));expect(installedAnchor).toBe(!!best);});