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
stop the requested phase count from hiding a shorter gait period
[._.]/ Adam Eivy1d5314ae959c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a55101bdba..d16681de49 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -189,3 +189,4 @@- **[issue-3043] Let a frozen imported walk set be unlocked for regeneration** — a character imported from the source pipeline whose walk set was finalized without its per-run source clips (the phase-1 import shape) had *no reachable action at all*: unlock and reopen both 409'd `LEGACY_IMPORTED_WALK_SET` (nothing to re-derive from), the cycle-target PUT 409'd `WALK_SET_FINAL` (set is frozen), and the workflow header rendered a dead `imported · no clips to re-derive` label with no button behind it — while the drift banner told the user to re-derive. The guard's premise was too narrow: it reasoned only about *re-derivation*, but a walk render is conditioned on the direction's **locked anchor**, so such a set can always be rebuilt from scratch — it just costs a new render per direction instead of a free local repack. `POST /walk/unlock` now accepts `{ acknowledgeNoClips }`, honored only where the server has proven every stranded direction has a locked anchor to regenerate from (an acknowledgement can never be the thing that strands a set — a stranded direction with an unlocked anchor still refuses, with the original error code). `getWalkState` stamps `walkSet.unlock = { blocked, stranded, acknowledgeable }` from the same resolver the gate itself uses, so the button a client offers and the 409 it might hit are computed from one reading of the set; the refusal that *can* be acknowledged past gets its own code (`LEGACY_IMPORTED_WALK_SET_REGENERABLE`) and names that path. The Walk Cycles header replaces the dead label with an **Unlock anyway** panel stating the cost as visible text rather than a tooltip (one new grok render per direction, every approval dropped, nothing deleted on disk), and the Loop Trimmer disables its `CycleTarget` while the set is frozen — it was enabled and 409'd on change — with the same two unlock offers below it. Two adjacent bugs surfaced while proving the escape is real and are fixed with it: `startWalkGenerationImpl` read `manifest.chromaKey` alone, but the importer stamps the key it used on the RECORD and copies a manifest carrying none — so every fully-locked source-pipeline import reported `MAIN_NOT_LOCKED` ("no frozen chroma key") and refused every Generate; the lookup now falls back manifest → record, the order reference.js already resolves it in at eight sites, The postprocess path carried the SAME missing rung (`run.chromaKey || manifest.chromaKey`) and died inside sharp with `Invalid hex color: undefined` on any reprocess of an imported run — a parser complaining about its argument, naming neither the field nor the record behind it. All three sites now share one `resolveChromaKey({ manifest, record, run })` (run → manifest → record), and a genuinely keyless record is refused by name before reaching the color parser. And the render path's anchor/chroma preconditions are now one shared `resolveWalkRenderability()`, so the gate that promises "every direction can be regenerated" and the render path that has to deliver it cannot drift — a predicate checking less than the render requires is exactly how an acknowledgement walks a user into the dead end it promises cannot happen.- **[issue-3049] Pin the walk aligner to the character's torso, not its bounding box** — a re-derived walk cycle slid visibly left and right as the legs scissored instead of walking in place; measured on a real packed 12-frame strip the torso travelled **29px** in a 384px cell. `alignFrames` crops each frame to its own alpha bbox and composites the crop at `dx`, and since #3021 `dx` was a single shared value — but `sourceRootXs[i]` is measured *relative to that frame's own crop*, so a constant `dx` pins `bbox.left` (the leading arm/leg extremity) and lets the body swing by the full spread of those offsets. The emitted manifest showed it exactly: `hipOffsets` spanning 26.2px against `translations` whose x was `122` for all twelve frames, and the strip itself had `bbox.left` at exactly 122 in every cell while the hip swung 179→205. #3021's premise was right (the old 42%–76% hip/leg band did migrate as the legs scissored) but freezing `dx` swapped it for a *worse* landmark: measured in absolute source coordinates over one 6s clip, the candidates rank torso 14px · hip 17px · head 24px · **bbox.left 44px** · legs 52px. So `rootX` now measures the **torso** band (30%–58%, above the knees — the visual mass a viewer tracks and the part genuinely stationary in a walk-in-place) and `dx` is per-frame again, computed from each frame's own crop offset so the shared landmark lands on the pivot every time; that cancels the crop variation *and* the residual drift grok leaves in a "walk in place" clip (~14px). `rootX` is shared with `atlas.js` for idle-frame registration, so both moved together. The #3021 guard had asserted the mechanism (`new Set(translations.map(([dx]) => dx)).size === 1`) rather than the behaviour, and its own fixed-torso/swinging-arm fixture passed while the body slid 30px — it now measures where the torso *lands* in the output frames and requires ≤1px spread, which pinning the crop cannot satisfy. Re-deriving a real direction: torso spread **29px → 1.0px**, with the hip band still swinging 8px and `bbox.left` varying 9px (limbs moving, body still).- **[issue-3050] Spread walk-cycle phases evenly when the gait period doesn't divide the frame count** — a re-derived walk could read as a limp rather than a smooth loop: the *timing* was uneven, not the seam (which is why `validation` never flagged it — the loop closed fine). `selectCycleIndices` resamples the detected window with `pyRound(i * cycleLength / frameCount)`, and `pyRound` is Python's round-half-to-even, so a `.5` tie breaks toward the even integer — meaning the tie's *direction* depends on the parity of the integer part and consecutive ties resolve opposite ways. A 15-frame gait over 12 phases landed its ties at 2.5→2 (down), 7.5→8 (up), 12.5→12 (down), putting double-steps at positions 2, 5 and 10 — spacings of 3 and 5, an arrhythmic hitch. The run manifest corroborated it: those three transitions carried ~28% more motion than the single-step median. Phase indices are now distributed with integer half-up (`floor((i * cycleLength + frameCount/2) / frameCount)`), which resolves every tie the same way, so the unavoidable stretch is spread evenly — 15→12 moves its double-steps to 1, 5 and 9 (gaps of 4 and 4). This is the one place that deliberately does not use `pyRound`: the pixel math keeps it for byte-compatibility with the source pipeline, while phase selection is a perceptual-quality question and only it has a tie problem. The legacy 12→8 default was affected too (strides `2,1,1,2,2,1,1` → `2,1,2,1,2,1,2`), as were 18→12 and any other ratio landing ties at regular intervals; 16→12, 13→12 and 12→12 were already even and are unchanged. The old golden-array test asserted the banker's-rounding output directly; it is replaced by a property assertion — at most two distinct stride lengths, differing by 1, with the longer ones evenly spaced — checked across five ratios so a future change to the resample has to preserve it for all of them.+- **[issue-3052] Stop the requested phase count from hiding a shorter gait period** — a walk read as janky leg movement (the legs visibly jump mid-loop) even though the endpoint seam scored well and validation passed. `selectCycleIndices` searched only windows of at least `frameCount`, on the grounds that a shorter one cannot yield that many *distinct* source frames — but that floor also made any gait whose real period is shorter **invisible to the detector**. On a real clip the gait ran 11 frames against 12 requested phases, so the search could only offer a 15-frame window: **1.36 gait cycles**, which replays a third of a stride. It scored well because a front-facing walk is near-symmetric, so 15 frames lands on the *mirrored* pose and an image-distance metric reads that as the same one — `endpointSeamScore` 0.53 while the legs were plainly wrong. The detector now probes for the true period without the output-count floor and prefers it when it is only mildly shorter (`MIN_PERIOD_RATIO = 0.8`), holding one frame to reach the requested count: a far smaller artifact than replaying part of a stride, and bounded so a much shorter period still falls back to the longer window. `cycleSelection.heldFrames` records how many phases repeat, and `validateFrames` takes it so an intentional hold is not confused with the "packer picked the same frame twice" failure that guard exists for. Across one character's seven directions the probe found better (lower-seam) windows on five — south 15→11 (0.531→0.476), south-east 12→11 (1.082→**0.438**), north-east 12→11 (0.985→**0.600**). **Rejected on evidence:** re-extracting at `WALK_FPS * frameCount / period` so the period lands exactly on the count was built and measured, and is wrong twice over — ffmpeg's `fps` filter picks the nearest source frame, so any rate that is not `sourceFps / k` samples unevenly (13.09fps from a 24fps source gives source-frame steps `[2,2,2,1,2,2,2,2,2,1,2,2]`, widening the adjacent-motion range from 2.2× to 11×), and extracting denser gains nothing because the clip is 12fps content encoded at 24fps with every frame duplicated (adjacent scores at 24fps alternate `1.29, 0.21, 2.65, 0.10…`). `WALK_FPS = 12` is already the native content rate, so an 11-frame period genuinely cannot yield 12 distinct phases.diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex e434f7b5b1..b02d93ef38 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -334,21 +334,34 @@ export function imageDistance(a, b) {}/**- * Find the best walk-cycle window by endpoint-seam continuity vs motion, and- * resample it onto the 8 gait phases. `signatures` is one entry per recovered- * source frame.+ * The shortest gait period a probe will consider. Below this a "cycle" is more+ * likely to be a half-stride or an artifact of AI frame boiling than a real one.*/-export function selectCycleIndices(signatures, frameCount = WALK_FRAME_COUNT) {+export const GAIT_MIN_PERIOD = 6;++/**+ * How much shorter than the requested phase count a TRUE gait period may be and+ * still be preferred over a longer, non-periodic window (#3052). At 0.8, an+ * 11-frame gait can serve 12 phases by holding one frame; a 6-frame gait cannot,+ * because half the loop would be held frames and a longer window is the better+ * compromise there.+ */+const MIN_PERIOD_RATIO = 0.8;++/**+ * The best-scoring periodic window, by endpoint-seam continuity vs motion.+ *+ * `minLength` is what separates the two callers, and it is the whole point of+ * splitting this out (#3052): the gait's real period is a property of the CLIP+ * and has nothing to do with how many phases the user asked for.+ */+export function findCycleWindow(signatures, frameCount, minLength) {const n = signatures.length;- if (n < frameCount + 1) {- throw new Error(`Need at least ${frameCount + 1} extracted frames, got ${n}`);- }let best = null; // [score, start, cycleLength, seam, motion]- // The window must be at least `frameCount` long to yield that many distinct- // source frames (we never upsample). Widen the ceiling with frameCount so a- // larger requested count can still find a long-enough gait window.+ // Widen the ceiling with frameCount so a larger requested count can still find+ // a long-enough gait window.const maxLen = Math.min(Math.max(18, frameCount + 6), n - 1);- for (let cycleLength = frameCount; cycleLength <= maxLen; cycleLength++) {+ for (let cycleLength = minLength; cycleLength <= maxLen; cycleLength++) {for (let start = 0; start < n - cycleLength; start++) {const seam = imageDistance(signatures[start], signatures[start + cycleLength]);const motionSamples = [];@@ -364,6 +377,36 @@ export function selectCycleIndices(signatures, frameCount = WALK_FRAME_COUNT) {}if (!best) throw new Error('No detectable moving walk cycle in the source video');const [, start, cycleLength, seam, motion] = best;+ return { start, cycleLength, seam, motion };+}++/**+ * Find the best walk-cycle window and resample it onto `frameCount` gait phases.+ * `signatures` is one entry per recovered source frame.+ */+export function selectCycleIndices(signatures, frameCount = WALK_FRAME_COUNT) {+ const n = signatures.length;+ if (n < frameCount + 1) {+ throw new Error(`Need at least ${frameCount + 1} extracted frames, got ${n}`);+ }+ // A window of at least `frameCount` gives one distinct source frame per phase.+ let chosen = findCycleWindow(signatures, frameCount, frameCount);+ // …but that floor also HIDES any gait whose real period is shorter, and forces+ // a longer window that is not a whole number of cycles (#3052). A real clip's+ // gait ran 11 frames while 12 phases were requested, so the search could only+ // offer a 15-frame window — 1.36 cycles. Its endpoints still matched (a+ // front-facing walk is near-symmetric, so the mirrored pose reads as the same+ // one), which is why the seam score looked fine while the legs visibly jumped+ // mid-loop. Probing without the floor finds the true period; holding one frame+ // to reach the requested count is a far smaller artifact than replaying a third+ // of a stride. The ratio guard keeps this to MILD upsampling — a much shorter+ // period would be mostly held frames, and a longer window wins there.+ const shortFloor = Math.max(GAIT_MIN_PERIOD, Math.ceil(frameCount * MIN_PERIOD_RATIO));+ if (shortFloor < frameCount) {+ const probe = findCycleWindow(signatures, frameCount, shortFloor);+ if (probe.cycleLength < frameCount) chosen = probe;+ }+ const { start, cycleLength, seam, motion } = chosen;// Even phase distribution, in integer arithmetic (#3050).//// This is the ONE place that deliberately does not use `pyRound`. Banker's@@ -386,7 +429,14 @@ export function selectCycleIndices(signatures, frameCount = WALK_FRAME_COUNT) {{ length: frameCount },(_, i) => start + Math.floor((i * cycleLength + half) / frameCount),);- if (new Set(indices).size !== frameCount) {+ // Every source frame of the window must be used. When the window is at least+ // `frameCount` long that means all-distinct as before; when it is shorter (the+ // mild-upsample path above) the phases hold `frameCount - cycleLength` frames,+ // and the check becomes "no frame of the gait was SKIPPED" — which is the+ // property that actually matters, and which the old all-distinct rule enforced+ // only incidentally.+ const distinct = new Set(indices).size;+ if (distinct !== Math.min(frameCount, cycleLength)) {throw new Error(`Cycle window too short to resample ${frameCount} distinct phases`);}return {@@ -396,6 +446,10 @@ export function selectCycleIndices(signatures, frameCount = WALK_FRAME_COUNT) {windowLength: cycleLength,endpointSeamScore: pyRoundTo(seam, 4),medianMotionScore: pyRoundTo(motion, 4),+ // How many phases repeat a source frame because the gait is shorter than+ // 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),},};}@@ -619,15 +673,24 @@ function keyDominantPixels(frame, split) {}/**- * Validate the packed candidate: 8 distinct frames, tolerable loop seam,+ * Validate the packed candidate: enough distinct frames, tolerable loop seam,* no visible key residue.+ *+ * `heldFrames` is how many phases deliberately repeat a source frame because the+ * clip's gait is shorter than the requested count (#3052) — an intentional hold,+ * not the "packer picked the same frame twice" failure this guard exists for. It+ * defaults to 0, so every caller that packs a full-length window keeps the strict+ * all-distinct rule.*/-export async function validateFrames(frames, split, frameCount = WALK_FRAME_COUNT) {+export async function validateFrames(frames, split, frameCount = WALK_FRAME_COUNT, heldFrames = 0) {if (frames.length !== frameCount) {throw new Error(`Expected ${frameCount} frames, got ${frames.length}`);}const hashes = frames.map((f) => sha256Buffer(f.data));- if (new Set(hashes).size !== frames.length) throw new Error('Duplicate frames in the packed cycle');+ const distinct = new Set(hashes).size;+ if (distinct !== frames.length - heldFrames) {+ throw new Error(`Duplicate frames in the packed cycle (${distinct} distinct of ${frames.length}, expected ${frames.length - heldFrames})`);+ }const signatures = await Promise.all(frames.map(signatureOf));const adjacent = signatures.map((sig, i) => pyRoundTo(imageDistance(sig, signatures[(i + 1) % frames.length]), 4));const seam = adjacent[adjacent.length - 1];@@ -785,7 +848,7 @@ export async function runWalkPostprocess({const { frames: aligned, alignment } = await alignFrames(selected);const despilled = aligned.map((f) => despillKeyFrame(f, split));- const validation = await validateFrames(despilled, split, targetFrames);+ const validation = await validateFrames(despilled, split, targetFrames, cycle.heldFrames || 0);const framesDir = join(generatedAbs, 'frames');await ensureDir(framesDir);diff --git a/server/services/sprites/walkPostprocess.test.js b/server/services/sprites/walkPostprocess.test.jsindex 878e9b2a3f..4b347149b6 100644--- a/server/services/sprites/walkPostprocess.test.js+++ b/server/services/sprites/walkPostprocess.test.js@@ -213,6 +213,38 @@ describe('selectCycleIndices', () => {}});+ /**+ * #3052 — a gait SHORTER than the requested count must still win. The window+ * floor used to be `frameCount`, which hid an 11-frame period behind a+ * 15-frame window: 1.36 cycles, whose endpoints matched anyway (a front-facing+ * walk is near-symmetric, so the mirrored pose reads as the same one) while the+ * legs visibly jumped mid-loop.+ */+ it('prefers a true short period over a longer non-periodic window', () => {+ // Period 11, sampled 30 frames long. 12 phases are requested, so the old+ // floor could only offer >=12 — i.e. never the real cycle.+ // A sawtooth, NOT a triangle: a symmetric wave repeats its values within the+ // period, which makes several window lengths look equally seamless.+ const signatures = Array.from({ length: 30 }, (_, i) => constSig((i % 11) * 5));+ const { indices, cycle } = selectCycleIndices(signatures, 12);+ expect(cycle.windowLength).toBe(11);+ expect(cycle.heldFrames).toBe(1);+ // Exactly one phase repeats, and no frame of the gait is skipped.+ expect(new Set(indices).size).toBe(11);+ const strides = indices.slice(1).map((v, i) => v - indices[i]);+ expect(strides.filter((s) => s === 0)).toHaveLength(1);+ expect(strides.every((s) => s === 0 || s === 1)).toBe(true);+ });++ it('does not upsample a period far below the requested count', () => {+ // Period 6 against 12 phases would be half held frames — the ratio guard+ // keeps the longer window instead.+ const signatures = Array.from({ length: 30 }, (_, i) => constSig((i % 6) * 10));+ const { cycle } = selectCycleIndices(signatures, 12);+ expect(cycle.windowLength).toBeGreaterThanOrEqual(12);+ expect(cycle.heldFrames).toBe(0);+ });+it('rejects a static clip and too-few frames', () => {expect(() => selectCycleIndices(Array.from({ length: 20 }, () => constSig(7)))).toThrow(/no detectable moving walk cycle/i);