Skip to content

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

feat: cross-check walk cycle period against motion periodicity (#4693) (#4713)

[._.]/ Adam Eivy2df39fddedba
diff --git a/client/src/components/sprites/WalkSourceFrames.jsx b/client/src/components/sprites/WalkSourceFrames.jsx
index 20275fd886..e2c16c77ef 100644
--- a/client/src/components/sprites/WalkSourceFrames.jsx
+++ b/client/src/components/sprites/WalkSourceFrames.jsx
@@ -279,6 +279,11 @@ function WalkSourceFrames({ recordId, runId, onSaved = () => {} }) {
strip's columns.
</>
)}
+ {data.cycle?.periodAgreement === 'disagree' && data.cycle?.periodEstimate != null && (
+ <>
+ {' '}The loop may not be a whole stride (motion periodicity suggests {data.cycle.periodEstimate} frames vs selected {data.cycle.windowLength}).
+ </>
+ )}
{data.cycleProvenance === 'stale' && (
<>
{' '}These frames were re-extracted here and don&apos;t match the ones the packed
diff --git a/client/src/components/sprites/WalkSourceFrames.test.jsx b/client/src/components/sprites/WalkSourceFrames.test.jsx
index 26f04f2f63..88cd717aff 100644
--- a/client/src/components/sprites/WalkSourceFrames.test.jsx
+++ b/client/src/components/sprites/WalkSourceFrames.test.jsx
@@ -104,6 +104,29 @@ describe('WalkSourceFrames', () => {
expect(screen.getByText(/Frames 3–6 are the/)).toBeTruthy();
});
+ it('displays an advisory when cycle window disagrees with motion periodicity', async () => {
+ await renderPanel(payload({
+ cycle: {
+ windowStart: 1, windowLength: 15, windowStartFrame: 3, windowEndFrame: 18,
+ periodEstimate: 11, periodAgreement: 'disagree',
+ },
+ }));
+ expandGrid();
+ expect(screen.getByText(/The loop may not be a whole stride/)).toBeTruthy();
+ expect(screen.getByText(/motion periodicity suggests 11 frames vs selected 15/)).toBeTruthy();
+ });
+
+ it('omits the advisory when period agreement is ok or unavailable', async () => {
+ await renderPanel(payload({
+ cycle: {
+ windowStart: 1, windowLength: 8, windowStartFrame: 3, windowEndFrame: 11,
+ periodEstimate: 8, periodAgreement: 'ok',
+ },
+ }));
+ expandGrid();
+ expect(screen.queryByText(/The loop may not be a whole stride/)).toBeNull();
+ });
+
// Geometry is deliberately omitted so the server adopts the pinned target: a
// panel one refetch behind must not 409 on a value the user never chose.
it('re-derives the SELECTED run by id alone, letting the server adopt the target', async () => {
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index ea0b18c345..23fc0c820a 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -1333,6 +1333,8 @@ function cycleWindowOf(packaged) {
windowStartFrame,
windowEndFrame: windowStartFrame !== null && windowLength !== null
? windowStartFrame + windowLength : null,
+ periodEstimate: Number.isInteger(cycle.periodEstimate) ? cycle.periodEstimate : null,
+ periodAgreement: typeof cycle.periodAgreement === 'string' ? cycle.periodAgreement : null,
};
}
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index 499eabd81d..341061448b 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -1486,6 +1486,7 @@ describe('getWalkSourceFrames', () => {
const manifest = JSON.parse(await readFile(manifestAbs, 'utf8'));
manifest.cycleSelection = {
windowStart: 2, windowLength: 4, endpointSeamScore: 1.25, medianMotionScore: 3.5,
+ periodEstimate: 4, periodAgreement: 'ok',
};
manifest.frames = [5, 7].map((index, i) => ({
sourceFrameIndex: index,
@@ -1523,6 +1524,7 @@ describe('getWalkSourceFrames', () => {
// (which would be 3, four frames to the left of the frames it covers).
expect(out.cycle).toMatchObject({
windowStart: 2, windowLength: 4, windowStartFrame: 5, windowEndFrame: 9,
+ periodEstimate: 4, periodAgreement: 'ok',
});
expect(out.cycleProvenance).toBe('verified');
// Older records predate run.frameCount/run.fps — the packed preview is the
diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.js
index 40d82b909e..51a651d216 100644
--- a/server/services/sprites/walkPostprocess.js
+++ b/server/services/sprites/walkPostprocess.js
@@ -342,6 +342,113 @@ export const GAIT_MIN_PERIOD = 6;
*/
const MIN_PERIOD_RATIO = 0.8;
+/**
+ * Estimate the dominant period of frame-to-frame motion via normalized autocorrelation.
+ * Returns { lag, strength } or null if motion is flat, too short, or lacks clear periodicity.
+ */
+export function estimateMotionPeriod(signatures) {
+ if (!Array.isArray(signatures) || signatures.length < 9) return null;
+ const motionSeries = [];
+ for (let i = 0; i < signatures.length - 1; i++) {
+ motionSeries.push(imageDistance(signatures[i], signatures[i + 1]));
+ }
+ const L = motionSeries.length;
+
+ let sum = 0;
+ for (let i = 0; i < L; i++) sum += motionSeries[i];
+ const mean = sum / L;
+
+ let varSum = 0;
+ for (let i = 0; i < L; i++) {
+ const diff = motionSeries[i] - mean;
+ varSum += diff * diff;
+ }
+ const variance = varSum / L;
+ // If variance is negligible or motion is virtually static, periodicity is unavailable.
+ if (variance < 1e-4) return null;
+
+ const minLag = 3;
+ // Search lags up to half the series length so each lag is supported by at least 2 full cycles
+ const maxLag = Math.min(24, Math.floor(L / 2));
+ if (maxLag < minLag) return null;
+ const maxComputedLag = Math.min(maxLag + 1, L - 2);
+
+ const correlations = [];
+ for (let lag = minLag - 1; lag <= maxComputedLag; lag++) {
+ if (lag < 1) continue;
+ let cov = 0;
+ for (let i = 0; i < L - lag; i++) {
+ cov += (motionSeries[i] - mean) * (motionSeries[i + lag] - mean);
+ }
+ const r = Math.max(-1, Math.min(1, cov / ((L - lag) * variance)));
+ correlations[lag] = r;
+ }
+
+ // Find strictly interior local peaks in autocorrelation that exceed the minimum strength threshold.
+ const MIN_AUTOCORR_STRENGTH = 0.25;
+ let bestPeak = null;
+ for (let lag = minLag; lag <= maxLag; lag++) {
+ const r = correlations[lag];
+ if (r < MIN_AUTOCORR_STRENGTH) continue;
+ const prev = correlations[lag - 1];
+ const next = correlations[lag + 1];
+ if (prev != null && next != null && r > prev && r >= next) {
+ if (!bestPeak || r > bestPeak.strength) {
+ bestPeak = { lag, strength: pyRoundTo(r, 4) };
+ }
+ }
+ }
+
+ if (!bestPeak) return null;
+
+ // In a symmetric walk, frame-to-frame motion peaks at the half-stride (e.g. lag 4
+ // for an 8-frame gait). If 2 * lag shows stronger full-pose agreement between
+ // signatures, elevate to the full stride period so integer-multiple checks don't
+ // confuse a 1.5-stride window (3 * half-stride) with a whole cycle.
+ const doubleLag = bestPeak.lag * 2;
+ if (doubleLag <= maxComputedLag && (correlations[doubleLag] ?? 0) > MIN_AUTOCORR_STRENGTH) {
+ let d1Sum = 0;
+ let d1Count = 0;
+ for (let i = 0; i < signatures.length - bestPeak.lag; i++) {
+ d1Sum += imageDistance(signatures[i], signatures[i + bestPeak.lag]);
+ d1Count++;
+ }
+ let d2Sum = 0;
+ let d2Count = 0;
+ for (let i = 0; i < signatures.length - doubleLag; i++) {
+ d2Sum += imageDistance(signatures[i], signatures[i + doubleLag]);
+ d2Count++;
+ }
+ const d1 = d1Count > 0 ? d1Sum / d1Count : Infinity;
+ const d2 = d2Count > 0 ? d2Sum / d2Count : Infinity;
+ if (d2 < d1 * 0.85) {
+ bestPeak = { lag: doubleLag, strength: pyRoundTo(correlations[doubleLag], 4) };
+ }
+ }
+
+ return bestPeak;
+}
+
+/**
+ * Does the chosen cycle window match the estimated single-stride motion period?
+ *
+ * Accepts single-stride agreement (nearestK === 1) within either ±1 frame
+ * (integer sampling / quantization jitter) or < 12% relative drift. Multi-stride (k >= 2)
+ * and sub-stride (k < 1) windows are rejected as disagreeing so the advisory
+ * alerts the reviewer when a double-speed or fractional stride was packed.
+ */
+export function isPeriodAgreement(cycleLength, lag) {
+ if (!Number.isFinite(cycleLength) || !Number.isFinite(lag) || cycleLength <= 0 || lag <= 0) {
+ return false;
+ }
+ const ratio = cycleLength / lag;
+ const nearestK = Math.round(ratio);
+ if (nearestK === 1) {
+ if (Math.abs(cycleLength - lag) <= 1 || Math.abs(ratio - 1) < 0.12) return true;
+ }
+ return false;
+}
+
/**
* The best-scoring periodic window, by endpoint-seam continuity vs motion.
*
@@ -369,7 +476,24 @@ export function findCycleWindow(signatures, frameCount, minLength) {
if (!best || candLess(cand, best)) best = cand;
}
}
- if (!best) throw new Error('No detectable moving walk cycle in the source video');
+ if (!best) {
+ let maxAdjacentMotion = 0;
+ for (let i = 0; i < n - 1; i++) {
+ const d = imageDistance(signatures[i], signatures[i + 1]);
+ if (d > maxAdjacentMotion) maxAdjacentMotion = d;
+ }
+ if (maxAdjacentMotion < 0.01) {
+ throw new Error('No detectable moving walk cycle in the source video (no motion detected)');
+ }
+ if (maxAdjacentMotion < MIN_CYCLE_MOTION) {
+ throw new Error('No detectable moving walk cycle in the source video (motion too faint to score as a gait cycle)');
+ }
+ const period = estimateMotionPeriod(signatures);
+ if (!period) {
+ throw new Error('No detectable moving walk cycle in the source video (motion has no detectable periodicity)');
+ }
+ throw new Error(`No detectable moving walk cycle in the source video (motion is periodic at ~${period.lag} frames, but no window scored as a clean gait cycle)`);
+ }
const [, start, cycleLength, seam, motion] = best;
return { start, cycleLength, seam, motion };
}
@@ -404,6 +528,13 @@ export function selectCycleIndices(signatures, frameCount = WALK_FRAME_COUNT) {
// period would be mostly held frames, and a longer window wins there.
const shortFloor = Math.min(frameCount, Math.max(GAIT_MIN_PERIOD, Math.ceil(frameCount * MIN_PERIOD_RATIO)));
const { start, cycleLength, seam, motion } = findCycleWindow(signatures, frameCount, shortFloor);
+
+ const motionPeriod = estimateMotionPeriod(signatures);
+ let periodAgreement = 'unavailable';
+ if (motionPeriod && Number.isInteger(motionPeriod.lag)) {
+ periodAgreement = isPeriodAgreement(cycleLength, motionPeriod.lag) ? 'ok' : 'disagree';
+ }
+
// Even phase distribution, in integer arithmetic (#3050).
//
// This is the ONE place that deliberately does not use `pyRound`. Banker's
@@ -447,6 +578,8 @@ export function selectCycleIndices(signatures, frameCount = WALK_FRAME_COUNT) {
// the requested count. 0 for every window at or above `frameCount`, so an
// existing manifest's shape is unchanged in the common case.
heldFrames: Math.max(0, frameCount - cycleLength),
+ periodEstimate: motionPeriod ? motionPeriod.lag : null,
+ periodAgreement,
},
};
}
@@ -489,6 +622,8 @@ export function selectAmbientLoopIndices(signatures, frameCount) {
windowLength,
endpointSeamScore: pyRoundTo(seam, 4),
heldFrames: 0,
+ periodEstimate: null,
+ periodAgreement: 'unavailable',
},
};
}
diff --git a/server/services/sprites/walkPostprocess.test.js b/server/services/sprites/walkPostprocess.test.js
index 5ec17119e0..2eb97a64bd 100644
--- a/server/services/sprites/walkPostprocess.test.js
+++ b/server/services/sprites/walkPostprocess.test.js
@@ -13,7 +13,8 @@ import sharp from 'sharp';
import {
pyRound, pyRoundTo, median, sampleBorderKey, validateMeasuredKey,
isUsableMeasuredKey, longestUsableSpan,
- recoverAlphaFrame, despillKeyFrame, imageDistance, selectCycleIndices, selectAmbientLoopIndices,
+ recoverAlphaFrame, despillKeyFrame, imageDistance, estimateMotionPeriod, isPeriodAgreement,
+ selectCycleIndices, selectAmbientLoopIndices,
alphaBbox, rootX, robustBottomRow, alignFrames, packStrip, validateFrames, buildContrastSheet,
rootBandForManifest, ROOT_BAND_TORSO, ROOT_BAND_HIP, ALIGN_OP_TORSO_X,
decodeTransparentSpriteSource, prepareWalkAnchorChromaInput,
@@ -268,19 +269,99 @@ describe('selectCycleIndices', () => {
expect(cycle.heldFrames).toBe(0);
});
- it('rejects a static clip and too-few frames', () => {
+ it('rejects a static clip and too-few frames with descriptive failure messages', () => {
expect(() => selectCycleIndices(Array.from({ length: 20 }, () => constSig(7))))
- .toThrow(/no detectable moving walk cycle/i);
+ .toThrow(/no detectable moving walk cycle.*no motion detected/i);
+ // Transient blip without periodicity
+ const faintSigs = Array.from({ length: 20 }, (_, i) => constSig(i === 2 ? 10 : 0));
+ expect(() => selectCycleIndices(faintSigs))
+ .toThrow(/no detectable moving walk cycle.*motion has no detectable periodicity/i);
+ // Periodic motion that is too faint for MIN_CYCLE_MOTION (0.75)
+ const faintStepPattern = [0, 500, 1500, 3000, 4500, 3000, 1500, 500]; // period 8
+ const faintPeriodicSigs = Array.from({ length: 24 }, (_, i) => {
+ const b = Buffer.alloc(SIG_LEN, 0);
+ b.fill(1, 0, faintStepPattern[i % 8]);
+ return b;
+ });
+ expect(() => selectCycleIndices(faintPeriodicSigs))
+ .toThrow(/no detectable moving walk cycle.*motion too faint/i);
expect(() => selectCycleIndices(Array.from({ length: 8 }, () => constSig(0))))
.toThrow(/at least 9/);
});
+ it('cross-checks period agreement between chosen window and motion periodicity', () => {
+ // Clean 8-frame loop (variable motion period 8) -> ok
+ const cleanPattern = [0, 5, 18, 35, 55, 45, 25, 10];
+ const cleanSigs = Array.from({ length: 25 }, (_, i) => constSig(cleanPattern[i % 8]));
+ const cleanRes = selectCycleIndices(cleanSigs, 8);
+ expect(cleanRes.cycle.periodAgreement).toBe('ok');
+ expect(cleanRes.cycle.periodEstimate).toBe(8);
+
+ // Period 11 motion pattern -> ok when 11 chosen
+ const pattern11 = [0, 4, 12, 28, 45, 60, 50, 35, 20, 10, 3];
+ const period11Sigs = Array.from({ length: 30 }, (_, i) => constSig(pattern11[i % 11]));
+ const agreedRes = selectCycleIndices(period11Sigs, 12);
+ expect(agreedRes.cycle.windowLength).toBe(11);
+ expect(agreedRes.cycle.periodEstimate).toBe(11);
+ expect(agreedRes.cycle.periodAgreement).toBe('ok');
+
+ // Production disagree path: 2 strides (12 frames) selected for a 6-frame period:
+ const period6Sigs = Array.from({ length: 30 }, (_, i) => constSig((i % 6) * 10));
+ const disagreeRes = selectCycleIndices(period6Sigs, 12);
+ expect(disagreeRes.cycle.windowLength).toBeGreaterThanOrEqual(12);
+ expect(disagreeRes.cycle.periodEstimate).toBe(6);
+ expect(disagreeRes.cycle.periodAgreement).toBe('disagree');
+ });
+
it('imageDistance is the mean absolute channel difference', () => {
expect(imageDistance(constSig(10), constSig(10))).toBe(0);
expect(imageDistance(constSig(0), constSig(30))).toBe(30);
});
});
+describe('estimateMotionPeriod', () => {
+ const SIG_LEN = 48 * 48 * 3;
+ const constSig = (v) => Buffer.alloc(SIG_LEN, v);
+
+ it('estimates dominant lag on a clean periodic motion series', () => {
+ const pattern = [0, 4, 12, 28, 45, 60, 50, 35, 20, 10]; // period 10
+ const signatures = Array.from({ length: 30 }, (_, i) => constSig(pattern[i % 10]));
+ const est = estimateMotionPeriod(signatures);
+ expect(est).not.toBeNull();
+ expect(est.lag).toBe(10);
+ expect(est.strength).toBeGreaterThan(0.8);
+ });
+
+ it('elevates half-stride motion lag to full stride period on symmetric gait', () => {
+ // 8-frame symmetric gait: motion peaks at half-stride (lag 4), but pose distance
+ // at lag 8 is 0 while at lag 4 is non-zero (mirrored leg/arm positions).
+ // Signatures alternate fill extent between 1000 and 2000 bytes across the halves.
+ const posePattern = [0, 5, 15, 30, 0, 5, 15, 30];
+ const signatures = Array.from({ length: 32 }, (_, i) => {
+ const half = Math.floor((i % 8) / 4);
+ const buf = Buffer.alloc(SIG_LEN, 0);
+ buf.fill(posePattern[i % 8], 0, half === 0 ? 1000 : 2000);
+ return buf;
+ });
+ const est = estimateMotionPeriod(signatures);
+ expect(est).not.toBeNull();
+ expect(est.lag).toBe(8); // Full stride, not half-stride 4
+
+ // 12-frame window (1.5 strides) must disagree with 8-frame full period
+ expect(isPeriodAgreement(12, est.lag)).toBe(false);
+ // 8-frame window agrees
+ expect(isPeriodAgreement(8, est.lag)).toBe(true);
+ });
+
+ it('returns null for motionless or flat motion series (unavailable)', () => {
+ const staticSigs = Array.from({ length: 20 }, () => constSig(5));
+ expect(estimateMotionPeriod(staticSigs)).toBeNull();
+
+ const shortSigs = [constSig(0), constSig(10)];
+ expect(estimateMotionPeriod(shortSigs)).toBeNull();
+ });
+});
+
describe('selectAmbientLoopIndices', () => {
const SIG_LEN = 48 * 48 * 3;
const constSig = (v) => Buffer.alloc(SIG_LEN, v);