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 review (claude): verify source-frame provenance by bytes and key the panel per run
[._.]/ Adam Eivy561d53c05f9b
diff --git a/client/src/components/sprites/LoopTrimmer.jsx b/client/src/components/sprites/LoopTrimmer.jsxindex a5a05d38d3..384baaeded 100644--- a/client/src/components/sprites/LoopTrimmer.jsx+++ b/client/src/components/sprites/LoopTrimmer.jsx@@ -368,11 +368,21 @@ export default function LoopTrimmer({{/* Every frame the run's clip produced, plus the in-place re-derive(#2980). Run sources only: a saved trim has no run (and no clip)behind it, so there is nothing to enumerate or re-derive. */}- {/* `onSaved` is passed straight through: the parent already hands down a- stable callback, and the panel is memoized so it doesn't re-render on- every loop-preview tick. */}+ {/* `key` is load-bearing, not cosmetic: extraction is a multi-second POST,+ and switching the animation source mid-flight would otherwise resolve+ into the SAME instance — writing one run's frames and lock state into a+ panel now labelled another run. Remounting per run makes the stale+ response a no-op, covering the extract, refresh and load paths at once.+ `onSaved` is passed straight through (the parent hands down a stable+ callback, and the panel is memoized so it doesn't re-render on every+ loop-preview tick). */}{source?.kind === 'run' && source.runId && (- <WalkSourceFrames recordId={recordId} runId={source.runId} onSaved={onSaved} />+ <WalkSourceFrames+ key={source.runId}+ recordId={recordId}+ runId={source.runId}+ onSaved={onSaved}+ />)}{/* Save + result */}diff --git a/server/routes/sprites.js b/server/routes/sprites.jsindex 5582ada341..0dc7a84e89 100644--- a/server/routes/sprites.js+++ b/server/routes/sprites.js@@ -215,6 +215,13 @@ router.get('/:id/walk/runs/:runId/source-frames', asyncHandler(async (req, res)// so every imported run would otherwise spawn an ffmpeg decode (~96 PNGs) just// from rendering the trimmer — this keeps the work behind an explicit click. No// AI call; deterministic ffmpeg only.+//+// Deliberately NOT gated on an unfinalized set, unlike its neighbours: it writes+// only re-derivable intermediates into the run's own `raw/` directory and+// touches no packaged artifact, manifest or record — and inspecting a finalized+// direction's source frames is exactly how the user decides whether to unlock it+// at all. The immutability guards stay where they matter, on the ops that change+// what the atlas compiles.router.post('/:id/walk/runs/:runId/source-frames/extract', asyncHandler(async (req, res) => {const { runId } = validateRequest(spriteWalkSourceFramesParamsSchema, req.params);res.json(await getWalkSourceFrames(req.params.id, runId, { extract: true }));diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex c4db3092cc..d213978f1d 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -1146,9 +1146,11 @@ async function listRawFrameNames(recordId, rawRel) {* window's first raw frame. Without this translation the highlight would sit* `span.start` frames to the left of the frames it claims to cover.*- * Each field degrades to null independently rather than collapsing the whole- * block, so a manifest that records the window but no frames[] still reports the- * window length it selected.+ * `windowEndFrame` is EXCLUSIVE — it is the seam frame the packer scored the+ * window's endpoints against, not a member of the cycle. Only ever called for a+ * manifest whose packed frames were verified against disk (see+ * `manifestCycleProvenance`), so the per-field null degradation below covers a+ * malformed `cycleSelection`, not a missing `frames[]`.*/function cycleWindowOf(packaged) {const cycle = packaged?.cycleSelection;@@ -1176,30 +1178,49 @@ function cycleWindowOf(packaged) {* re-extracted by this install's ffmpeg (`fps=12`, first 8s). If those two* extractions disagree at all, the indices address different PNGs and the panel* would confidently mark the wrong frames as "the gait cycle" and "packed into- * the strip" — a false claim about provenance is worse than no claim. The- * manifest already records each packed frame's `sourcePath`, so verify the- * basenames are among the files on disk and report:+ * the strip" — a false claim about provenance is worse than no claim.*- * 'verified' the manifest's source frames are all present → markers are real+ * **Presence is not identity, which is why this hashes.** Both extractions name+ * their output `source-%04d.png`, so a source pipeline that sampled at 24fps+ * declares a `source-0010.png` that also exists here — holding a different+ * moment of the clip. A basename check would call that 'verified' and mark the+ * wrong frames, i.e. miss the exact hazard it exists for. The packer records+ * `sourceSha256` per frame (walkPostprocess.js), so compare one declared frame's+ * bytes; a manifest too old to carry hashes falls back to presence, which is+ * still better than nothing and never worse than not checking.+ *+ * 'verified' the declared source frames are the ones on disk → markers are real* 'stale' they are not → markers withheld, and the client says why* 'none' the run carries no packaged cycle to map (never packaged, or a* minimal manifest) → nothing to verify, nothing to withhold*/-function manifestCycleProvenance(packaged, names) {+async function manifestCycleProvenance(recordId, rawRel, packaged, names) {const packedFrames = Array.isArray(packaged?.frames) ? packaged.frames : [];const indices = packedFrames.map((frame) => frame?.sourceFrameIndex).filter((index) => Number.isInteger(index));- if (!indices.length) return { cycle: null, selectedSourceIndices: [], cycleProvenance: 'none' };+ const withheld = { cycle: null, selectedSourceIndices: [], cycleProvenance: 'stale' };+ if (!indices.length) return { ...withheld, cycleProvenance: 'none' };+ const declared = packedFrames.map((frame) => (typeof frame?.sourcePath === 'string'+ ? { name: frame.sourcePath.split('/').pop(), sha256: frame.sourceSha256 }+ : null));+ // Partial declaration is not partial evidence: two of twelve frames naming a+ // path that happens to exist says nothing about the other ten, so treat an+ // incompletely-declared manifest as unverifiable rather than verified. A+ // manifest that declares NOTHING (older/minimal packaging) is taken at its+ // word — there is nothing to compare, and withholding the markers would punish+ // a record for being terse rather than wrong.+ if (!declared.some(Boolean)) {+ return { cycle: cycleWindowOf(packaged), selectedSourceIndices: indices, cycleProvenance: 'verified' };+ }const onDisk = new Set(names);- const declared = packedFrames- .map((frame) => (typeof frame?.sourcePath === 'string' ? frame.sourcePath.split('/').pop() : null))- .filter(Boolean);- // A manifest that declares no sourcePath at all (older/minimal packaging) is- // taken at its word — there is nothing to compare, and withholding the markers- // would punish a record for being terse rather than wrong.- const matches = !declared.length || declared.every((name) => onDisk.has(name));- if (!matches) return { cycle: null, selectedSourceIndices: [], cycleProvenance: 'stale' };+ if (!declared.every((frame) => frame && onDisk.has(frame.name))) return withheld;+ // One hash settles it: the declared frames come from a single extraction, so+ // if one is byte-identical the numbering they share is the numbering on disk.+ const hashed = declared.find((frame) => typeof frame.sha256 === 'string' && frame.sha256);+ if (hashed && await sha256File(join(spriteDir(recordId), rawRel, hashed.name)) !== hashed.sha256) {+ return withheld;+ }return {cycle: cycleWindowOf(packaged),selectedSourceIndices: indices,@@ -1340,7 +1361,7 @@ export async function getWalkSourceFrames(recordId, runId, { extract = false } =// with different remedies — the second is one click from recoverable.reason: frames.length > 0 ? null : (clipRel ? 'raw-frames-cleaned' : 'no-source-video'),frames,- ...manifestCycleProvenance(packaged, names),+ ...(await manifestCycleProvenance(recordId, rawRel, packaged, names)),editable: !lockReason,lockReason,});diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex c67672aef2..981dce9612 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -1100,7 +1100,9 @@ describe('getWalkSourceFrames', () => {// degenerate span.start = 0 case, where `windowStart + 1` and// `frames[0].sourceFrameIndex` coincide and a translation that ignored the// packed frames entirely would still look correct.- async function stampCycleProvenance(id, runId, direction = 'east', { sourcePaths = true } = {}) {+ async function stampCycleProvenance(id, runId, direction = 'east', {+ sourcePaths = true, shas = true, partial = false,+ } = {}) {const manifestAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', `${id}-walk-${direction}-manifest.json`,);@@ -1108,11 +1110,15 @@ describe('getWalkSourceFrames', () => {manifest.cycleSelection = {windowStart: 2, windowLength: 4, endpointSeamScore: 1.25, medianMotionScore: 3.5,};- manifest.frames = [5, 7].map((index) => ({+ manifest.frames = [5, 7].map((index, i) => ({sourceFrameIndex: index,- ...(sourcePaths+ // `partial` declares a path on only the first frame — evidence about one+ // frame is not evidence about the rest.+ ...(sourcePaths && !(partial && i > 0)? { sourcePath: `runs/${runId}/generated/raw/${rawName(index)}` }: {}),+ // The bytes `seedRawFrames` writes, so a matching hash is the healthy case.+ ...(shas && !(partial && i > 0) ? { sourceSha256: sha256(Buffer.from(`raw-${index}`)) } : {}),}));await writeFile(manifestAbs, JSON.stringify(manifest));}@@ -1207,17 +1213,44 @@ describe('getWalkSourceFrames', () => {expect(out.selectedSourceIndices).toEqual([]);});- // A minimal manifest that declares no sourcePath has nothing to verify — take- // it at its word rather than punishing it for being terse.- it('trusts a manifest that declares no source paths', async () => {+ // The subtle case a filename check cannot catch: BOTH extractions name their+ // output source-%04d.png, so a source pipeline that sampled at a different fps+ // declares files that all "exist" here while holding different moments of the+ // clip. The bytes are what settle it.+ it('withholds the markers when the declared frames are present but not the same bytes', async () => {const id = await characterWithLockedAnchors(newId(), ['east']);const { runId } = await makeCandidateRun(id, 'east');- await seedRawFrames(join(TEST_ROOT, 'sprites', id, 'runs', runId), 4);- await stampCycleProvenance(id, runId, 'east', { sourcePaths: false });+ const runAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId);+ await seedRawFrames(runAbs, 8);+ await stampCycleProvenance(id, runId);+ // Same filename, different content — exactly a re-extraction at another fps.+ await writeFile(join(runAbs, 'generated', 'raw', rawName(5)), 'a-different-moment');const out = await getWalkSourceFrames(id, runId);- expect(out.cycleProvenance).toBe('verified');- expect(out.selectedSourceIndices).toEqual([5, 7]);+ expect(out.cycleProvenance).toBe('stale');+ expect(out.cycle).toBeNull();+ expect(out.selectedSourceIndices).toEqual([]);+ });++ // A minimal manifest that declares no sourcePath has nothing to verify — take+ // it at its word rather than punishing it for being terse. A PARTIALLY+ // declared one is different: evidence about one frame is not evidence about+ // the rest, so it stays unverified.+ it('trusts a manifest that declares no source paths, but not a partial one', async () => {+ const id = await characterWithLockedAnchors(newId(), ['east']);+ const bare = await makeCandidateRun(id, 'east');+ await seedRawFrames(join(TEST_ROOT, 'sprites', id, 'runs', bare.runId), 8);+ await stampCycleProvenance(id, bare.runId, 'east', { sourcePaths: false, shas: false });+ const bareOut = await getWalkSourceFrames(id, bare.runId);+ expect(bareOut.cycleProvenance).toBe('verified');+ expect(bareOut.selectedSourceIndices).toEqual([5, 7]);++ const half = await makeCandidateRun(id, 'east');+ await seedRawFrames(join(TEST_ROOT, 'sprites', id, 'runs', half.runId), 8);+ await stampCycleProvenance(id, half.runId, 'east', { partial: true });+ const halfOut = await getWalkSourceFrames(id, half.runId);+ expect(halfOut.cycleProvenance).toBe('stale');+ expect(halfOut.selectedSourceIndices).toEqual([]);});it('reports no-source-video rather than an empty-looking success', async () => {