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
refactor([issue-3015]): guard the registry at load, share one import scanner, pin the client mirror
[._.]/ Adam Eivyefd4874a881d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cbfc41a578..102f561f2b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -13,7 +13,8 @@## Internal-- **[issue-3015] Per-track animation registry — frame-count/fps bounds stop being walk-shaped** — the authoring range (`6–16` frames, `4–24` fps) was global and defined once in `server/services/sprites/walkBounds.js`, so it described *every* animation as if it were a walk cycle; a 3-frame ambient loop or a 4-frame scanner action sits below walk's floor of 6 and was literally unrepresentable. A new sharp-free leaf, `server/services/sprites/animationTracks.js`, holds one row per known track (`{ id, label, directional, min/max/defaultFrameCount, min/max/defaultFps, contractFrameCountField, contractFpsField }`), with `walk` as its only row carrying today's exact values. `walkBounds.js` keeps every historical export as a thin re-read of that row, so `walkPostprocess`, `atlas`, `walk`, `server/lib/validation.js`, and the client mirror need no changes. `resolveAnimationTarget` / `targetDrift` / `withTrackTarget` now range-check against the *named track's* row (and read the app rung through the field names that row declares, instead of hard-coded `walkFrameCount`), and the Zod ranges are built by `spriteTrackFrameCountSchema(track)` / `spriteTrackFpsSchema(track)` factories with a `spriteAnimationTrackSchema` that rejects an unknown id by name. An absent track resolves to `walk` — which is what keeps every existing call site identical — while an *unrecognized* one throws rather than silently validating against walk's range. #2985's invariant is preserved: an unrecognized sibling track key still round-trips untouched on write, even though writing to an unknown track is now refused. Pure refactor — walk behaves identically end to end; no second track is added here.+- **[issue-3015] Per-track animation registry — frame-count/fps bounds stop being walk-shaped** — the authoring range (`6–16` frames, `4–24` fps) was global and defined once in `server/services/sprites/walkBounds.js`, so it described *every* animation as if it were a walk cycle; a 3-frame ambient loop or a 4-frame scanner action sits below walk's floor of 6 and was literally unrepresentable. A new sharp-free leaf, `server/services/sprites/animationTracks.js`, holds one row per known track (`{ id, label, directional, min/max/defaultFrameCount, min/max/defaultFps, contractFrameCountField, contractFpsField }`), with `walk` as its only row carrying today's exact values. `walkBounds.js` keeps every historical export as a thin re-read of that row, so `walkPostprocess`, `atlas`, `walk`, `server/lib/validation.js`, and the client mirror need no changes. `resolveAnimationTarget` / `targetDrift` / `withTrackTarget` now range-check against the *named track's* row (and read the app rung through the field names that row declares, instead of hard-coded `walkFrameCount`), and the Zod ranges are built by `spriteTrackFrameCountSchema(track)` / `spriteTrackFpsSchema(track)` factories. An absent track resolves to `walk` — which is what keeps every existing call site identical — while an *unrecognized* one throws rather than silently validating against walk's range. The registry validates its own rows at module load (the `navManifest.js` / `catalogTypes.js` idiom), so a half-declared track blocks boot with a message naming the field instead of surfacing later as a `NaN` frame count. #2985's invariant is preserved: an unrecognized sibling track key still round-trips untouched on write, even though writing to an unknown track is now refused. Pure refactor — walk behaves identically end to end; no second track is added here.+- **New `server/lib/staticImportGraph.js` — one static-import scanner for the structural test guards** — `agentImportCycles.test.js` (the agent-lifecycle acyclicity guard) and the new sprite guard each had their own copy of the ES-module import regex pair and graph walk, which is how a structural guard rots: a fix to one parser silently under-reports in the other. Both now call `staticImportSpecifiers` / `staticImportClosure`. The sprite guard also asserts the property that actually matters — `server/lib/validation.js`'s whole import closure reaches no native image dependency — rather than only the three leaf modules, with a positive control pinning that the walk genuinely traverses. A companion parity test pins the client's mirrored walk bounds (`spriteTrimmer.js`, `PublishWorkflow.jsx`) against the registry row, so the first real per-track bounds change can't silently desync the pickers from the server's range.- **[issue-3001] Approving and compiling a walk direction now agree on what "valid packaged frames" means** — the check that a direction's per-frame images are all present was written twice: the cheap gate that runs when you *approve* a direction only checked the files existed (and, for an imported character, could silently drop a frame whose path it couldn't re-anchor — understating the count in its own error), while the stricter gate that runs when you *compile* the atlas also verified each frame's checksum and gait-phase order. So a direction could pass approval and then fail compile for a frame reason the approve step was meant to catch. Both now call one shared `verifyPackagedFrames` helper: approve runs its existence-only prefix (resolving imported frame paths the same drift-tolerant way the clip and strip checks beside it already do, and counting an un-re-anchorable path as a failure instead of dropping it), and compile runs the same resolution plus the checksum/order checks — reading each frame's bytes exactly once. The approve gate is now a strict prefix of the compile gate, so the two can no longer disagree.- **Shared `ui/FilePickerButton` + two hygiene guards for file pickers** — 28 call sites across the client hand-rolled the same hidden-`<input type="file">` idiom; they now share `client/src/components/ui/FilePickerButton.jsx` (sr-only-but-focusable input + native `<label for>` activation, extra props spread onto the label so a drop zone can pass `onDrop`/`onDragOver` and a forwarded ref, and an async-aware value clear that waits for the handler to settle before emptying `input.files`). Because the failure only reproduces in WebKit-as-installed-PWA — invisible to lint, CI, and local testing — `a11yConventions.test.js` gains two cases mirroring the existing `crypto.randomUUID` lint precedent: no `type="file"` input may carry `hidden`/`aria-hidden`/`tabIndex={-1}`, and no `.current.click()` may appear in a tracked `.jsx`.- **`server/lib/uploadLimits.js` is the single source of truth for upload size caps** — `express.json`'s limit lived as a bare `'55mb'` literal in `server/index.js` while four routes each re-derived their own byte cap against it, two of them landing on unreachable values (100MB, 50MB). The limit and the base64-derived file cap now live in one module (mirroring the `lib/ports.js` pattern), consumed by `index.js` and every upload route; `uploadLimits.test.js` asserts the derivation actually fits, that no route re-hardcodes a cap, and that the client mirror in `utils/fileUpload.js` agrees.diff --git a/server/lib/README.md b/server/lib/README.mdindex 7e5631b201..5774f7c2d2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -284,6 +284,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. || `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). || `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. |+| `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath. Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `agentImportCycles.test.js` (acyclicity) and `sprites/animationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). || `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. || `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). || `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. |diff --git a/server/lib/index.js b/server/lib/index.jsindex e937b5e0f5..653cd06761 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -255,6 +255,7 @@ export * from './openapiSpec.js';export * from './shellQuote.js';export * from './sidecarProcess.js';export * from './singleFlight.js';+export * from './staticImportGraph.js';export * from './streamBackpressure.js';export * from './sseUtils.js';export * from './uploadLimits.js';diff --git a/server/lib/staticImportGraph.js b/server/lib/staticImportGraph.jsnew file mode 100644index 0000000000..6d29d8fffd--- /dev/null+++ b/server/lib/staticImportGraph.js@@ -0,0 +1,85 @@+/**+ * Static ES-module import scanning — one parser for every import-graph guard.+ *+ * Several suites assert structural properties of the module graph rather than+ * runtime behavior: `agentImportCycles.test.js` proves the agent-lifecycle+ * cluster is acyclic, and `sprites/animationTracks.test.js` proves the+ * request-validation graph never reaches the native image dependencies+ * (sharp/ffmpeg). Both need the same thing — "which modules does this file+ * statically import?" — and both had their own copy of the regex pair and the+ * `exec` drain loop, which is exactly how a guard rots: a fix to one parser+ * (multi-line import lists, `export * from`, a new specifier shape) lands in+ * one copy while the other keeps silently under-reporting.+ *+ * **Static imports only.** `await import('./x.js')` is deferred to call time,+ * so it can neither produce a load-time cycle nor drag a native dependency into+ * a module's initialization graph — matching on it would report false+ * positives. The line-anchored patterns also mean a specifier mentioned inside+ * a comment is not matched, because a comment line never starts with+ * `import`/`export`.+ */++import { readFileSync, existsSync } from 'fs';+import { dirname, resolve } from 'path';++// `import … from 'x'` / `export … from 'x'` (line-anchored, non-greedy up to+// the `from`), and bare `import 'x'` side-effect imports.+const STATIC_FROM = /^\s*(?:import|export)\b[^;]*?from\s*['"]([^'"]+)['"]/gm;+const STATIC_BARE = /^\s*import\s*['"]([^'"]+)['"]/gm;++/**+ * Every module specifier `file` statically imports, in source order, verbatim+ * (relative specifiers keep their `./` / `../` prefix; bare package specifiers+ * come through as written). Duplicates are preserved — callers that want a set+ * build one.+ */+export function staticImportSpecifiers(file) {+ const src = readFileSync(file, 'utf-8');+ const out = [];+ for (const re of [STATIC_FROM, STATIC_BARE]) {+ re.lastIndex = 0;+ let match;+ while ((match = re.exec(src)) !== null) out.push(match[1]);+ }+ return out;+}++/**+ * Walk the static import graph from `entry`, following relative specifiers that+ * resolve to a file on disk.+ *+ * @returns {{files: Set<string>, packages: Set<string>}} `files` — absolute+ * paths of every module reachable from `entry` (including `entry` itself);+ * `packages` — every BARE specifier hit anywhere in that closure, which is+ * what a "this graph must not reach <dependency>" guard asserts against.+ *+ * A relative specifier that does not resolve to an existing path (an+ * extensionless import, a directory index) is skipped rather than throwing —+ * these guards assert a negative ("nothing here reaches sharp"), so a resolver+ * gap must not be able to make the walk *look* clean. Pair every such guard+ * with a positive control that pins a known-reaching entry point.+ */+export function staticImportClosure(entry) {+ const files = new Set();+ const packages = new Set();+ const walk = (file) => {+ if (files.has(file)) return;+ files.add(file);+ for (const spec of staticImportSpecifiers(file)) {+ if (!spec.startsWith('.')) { packages.add(spec); continue; }+ const next = resolve(dirname(file), spec);+ if (existsSync(next)) walk(next);+ }+ };+ walk(entry);+ return { files, packages };+}++/**+ * True when `specifier` names `pkg` or a subpath of it (`sharp` matches both+ * `sharp` and `sharp/lib/x`), so a dependency guard can't be sidestepped by+ * importing a deep path.+ */+export function specifierMatchesPackage(specifier, pkg) {+ return specifier === pkg || specifier.startsWith(`${pkg}/`);+}diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 8f5f1dfc88..aab8be4c90 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -5,9 +5,7 @@ import { WORK_TRACKERS } from './workTracker.js';import { SPRITE_ID_PATTERN, SPRITE_RECORD_KINDS } from '../services/sprites/recordsLogic.js';import { ANCHOR_DIRECTIONS, SPRITE_DIRECTIONS, TURNAROUND_ID } from '../services/sprites/prompts.js';import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';-import {- WALK_TRACK, ANIMATION_TRACK_IDS, isAnimationTrack, getAnimationTrack,-} from '../services/sprites/animationTracks.js';+import { WALK_TRACK, getAnimationTrack } from '../services/sprites/animationTracks.js';import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total@@ -957,23 +955,22 @@ export const videoDownloadSchema = z.object({});// Animation-track-aware bounds (#3015). Frame-count / fps ranges are per track,-// not global, so the schema factories below take a track id and build the range-// from that track's registry row. `walk` is the default, which is what keeps-// every pre-#3015 call site behaving identically. An unrecognized id throws out-// of `getAnimationTrack` at schema-construction time (a wiring bug, caught at-// boot) rather than degrading to walk's range; a track id arriving in a REQUEST-// is validated by `spriteAnimationTrackSchema`, which rejects it with a message-// naming the known tracks.-export const spriteAnimationTrackSchema = z.string().refine(isAnimationTrack, {- message: `unknown animation track — expected one of: ${ANIMATION_TRACK_IDS.join(', ')}`,-});--export function spriteTrackFrameCountSchema(track = WALK_TRACK) {+// not global, so the factories below take a track id and build the range from+// that track's registry row. An absent id is the default (walk) track, which is+// what keeps every pre-#3015 schema identical; an unrecognized one throws out of+// `getAnimationTrack` at schema-CONSTRUCTION time, so a mis-keyed track is a+// boot failure naming the known tracks rather than a range that silently+// validates a scanner action against walk's 6–16.+//+// There is deliberately no exported `track` field schema yet: no request shape+// carries a track id until the first second track lands, and an exported-but-+// unwired validator is false confidence.+export function spriteTrackFrameCountSchema(track) {const row = getAnimationTrack(track);return z.number().int().min(row.minFrameCount).max(row.maxFrameCount);}-export function spriteTrackFpsSchema(track = WALK_TRACK) {+export function spriteTrackFpsSchema(track) {const row = getAnimationTrack(track);return z.number().int().min(row.minFps).max(row.maxFps);}@@ -1026,10 +1023,10 @@ const spriteRepoRelativePath = z.string().min(1).max(1024)// have no animation-fps concept, so PortOS's fps is preview-only and never// part of the contract.export const spriteRuntimeContractSchema = z.object({- // Field name and range both come from the walk registry row (#3015) — the- // row names the contract field it occupies, so a second track declaring its- // own contract field can't drift from what resolveAnimationTarget reads.- [getAnimationTrack(WALK_TRACK).contractFrameCountField]: spriteTrackFrameCountSchema(WALK_TRACK),+ // Range from the walk registry row (#3015). The KEY stays a literal so+ // `grep walkFrameCount` still finds the schema that validates it — the row's+ // `contractFrameCountField` is asserted to agree in animationTargets.test.js.+ walkFrameCount: spriteTrackFrameCountSchema(WALK_TRACK),cellSize: z.number().int().min(16).max(1024).nullable().optional(),columnCount: z.number().int().min(1).max(256).nullable().optional(),});diff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex 099a46d460..8e65c0365e 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -38,7 +38,6 @@ import {databaseSwitchSchema,databaseBackendSchema,databaseExportSchema,- spriteAnimationTrackSchema,spriteTrackFrameCountSchema,spriteTrackFpsSchema,spriteRuntimeContractSchema,@@ -1435,14 +1434,6 @@ describe('ad-hoc route schemas (#2521)', () => {});describe('animation-track-aware sprite bounds (#3015)', () => {- it('accepts a known track id and rejects an unknown one by name', () => {- expect(spriteAnimationTrackSchema.safeParse('walk').success).toBe(true);- const bad = spriteAnimationTrackSchema.safeParse('scanner');- expect(bad.success).toBe(false);- expect(JSON.stringify(bad.error.issues)).toMatch(/unknown animation track/);- expect(JSON.stringify(bad.error.issues)).toMatch(/walk/);- });-it('builds the walk range from the registry row, unchanged from pre-#3015', () => {const frames = spriteTrackFrameCountSchema('walk');expect(frames.safeParse(6).success).toBe(true);diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.jsindex 99c498544b..98dbde729c 100644--- a/server/services/agentImportCycles.test.js+++ b/server/services/agentImportCycles.test.js@@ -19,6 +19,7 @@ import { describe, it, expect } from 'vitest';import { readdirSync, readFileSync } from 'fs';import { fileURLToPath } from 'url';import { dirname, join } from 'path';+import { staticImportSpecifiers } from '../lib/staticImportGraph.js';const SERVICES_DIR = dirname(fileURLToPath(import.meta.url));@@ -40,26 +41,22 @@ const CLUSTER = ['agentRunnerOutputBatchers.js',];-// Matches `import … from './x.js'`, `export … from './x.js'`, and bare-// `import './x.js'` at the start of a line. Deliberately does NOT match-// `await import('./x.js')` (dynamic) or the same string inside a comment,-// because a comment never starts with `import`/`export`.-const STATIC_FROM = /^\s*(?:import|export)\b[^;]*?from\s*['"]\.\/([\w.\-/]+\.js)['"]/gm;-const STATIC_BARE = /^\s*import\s*['"]\.\/([\w.\-/]+\.js)['"]/gm;-+// The static-import scan itself lives in `server/lib/staticImportGraph.js` so+// this guard and the sprites sharp-free guard share ONE parser — two copies is+// how a structural guard rots (a fix to one silently under-reports in the+// other). It matches static `import`/`export … from` and bare side-effect+// imports only, never `await import()` (deferred to call time, so it can't+// produce a load-time cycle) and never a specifier inside a comment.function buildStaticGraph() {const files = readdirSync(SERVICES_DIR).filter(f => f.endsWith('.js') && !f.includes('.test.'));const known = new Set(files);const graph = new Map();for (const file of files) {- const src = readFileSync(join(SERVICES_DIR, file), 'utf-8');const deps = new Set();- for (const re of [STATIC_FROM, STATIC_BARE]) {- re.lastIndex = 0;- let match;- while ((match = re.exec(src)) !== null) {- if (known.has(match[1])) deps.add(match[1]);- }+ for (const spec of staticImportSpecifiers(join(SERVICES_DIR, file))) {+ // Same-directory siblings only — this guard is scoped to the services dir.+ const sibling = spec.startsWith('./') ? spec.slice(2) : null;+ if (sibling && known.has(sibling)) deps.add(sibling);}graph.set(file, [...deps]);}diff --git a/server/services/sprites/animationTargets.js b/server/services/sprites/animationTargets.jsindex 2acd428c05..37f2d5cfbc 100644--- a/server/services/sprites/animationTargets.js+++ b/server/services/sprites/animationTargets.js@@ -37,13 +37,11 @@ import {// here; the registry owns the value now, so the two can never disagree.export { WALK_TRACK };-const intInRange = (v, min, max) => (Number.isInteger(v) && v >= min && v <= max ? v : null);-// Range readers bound to ONE track's row. Out-of-range values read as `null`+// Range readers against one track's row. Out-of-range values read as `null`// (absent) rather than being clamped — see resolveAnimationTarget's contract.-const trackReaders = (row) => ({- readFrameCount: (v) => intInRange(v, row.minFrameCount, row.maxFrameCount),- readFps: (v) => intInRange(v, row.minFps, row.maxFps),-});+const intInRange = (v, min, max) => (Number.isInteger(v) && v >= min && v <= max ? v : null);+const readFrameCount = (row, v) => intInRange(v, row.minFrameCount, row.maxFrameCount);+const readFps = (row, v) => intInRange(v, row.minFps, row.maxFps);/*** Resolve one track's pinned target from the precedence chain, newest authority@@ -68,9 +66,8 @@ const trackReaders = (row) => ({** `track` selects which persisted entry to read AND which registry row supplies* the bounds, the defaults, and the `runtimeContract` field names — all three- * were walk-specific before #3015. An absent track resolves to `walk`- * (preserving every existing call site); an UNRECOGNIZED one throws rather than- * silently validating against walk's range.+ * were walk-specific before #3015. Absent/unrecognized handling is+ * `getAnimationTrack`'s (absent ⇒ the default track, unrecognized ⇒ throws).** @param {object} input* @param {string} [input.track] Track id from `animationTracks.js` (default 'walk').@@ -82,28 +79,26 @@ const trackReaders = (row) => ({* frameCountLocked: boolean, fpsLocked: boolean}}*/export function resolveAnimationTarget({- track = WALK_TRACK,+ track,runtimeContract = null,animationTargets = null,packagedCycles = [],} = {}) {- // Throws on an unrecognized track — an explicit error beats silently- // range-checking a scanner action against the walk's 6–16.+ // Absent → the default track; unrecognized → throws (see getAnimationTrack).const row = getAnimationTrack(track);- const { readFrameCount, readFps } = trackReaders(row);// The bound app's declared expectation for its own atlas (#2982) — a stronger// authority than any per-render pick. Read defensively: that field lands// independently of this module, so an absent contract just falls through.- const appCount = readFrameCount(runtimeContract?.[row.contractFrameCountField]);- const appFps = readFps(runtimeContract?.[row.contractFpsField]);+ const appCount = readFrameCount(row, runtimeContract?.[row.contractFrameCountField]);+ const appFps = row.contractFpsField ? readFps(row, runtimeContract?.[row.contractFpsField]) : null;const pinned = animationTargets?.[row.id] || null;- const setCount = readFrameCount(pinned?.frameCount);- const setFps = readFps(pinned?.fps);+ const setCount = readFrameCount(row, pinned?.frameCount);+ const setFps = readFps(row, pinned?.fps);- const derivedCount = firstDefined(packagedCycles, (c) => readFrameCount(c?.frameCount));- const derivedFps = firstDefined(packagedCycles, (c) => readFps(c?.fps));+ const derivedCount = firstDefined(packagedCycles, (c) => readFrameCount(row, c?.frameCount));+ const derivedFps = firstDefined(packagedCycles, (c) => readFps(row, c?.fps));let source = 'default';if (derivedCount !== null || derivedFps !== null) source = 'derived';@@ -137,10 +132,9 @@ function firstDefined(list, read) {* later PortOS) may have written a `scanner` / ambient entry this build knows* nothing about, and a naive `{ walk: … }` overwrite would silently drop it.*- * The track being WRITTEN must be one this build knows (#3015) — an unrecognized- * write target is a bug, not a forward-compat case, and would persist a row- * nothing can range-check. Sibling keys are untouched either way: preserving- * what a newer peer wrote and writing a bogus key are different things.+ * The track being WRITTEN must be one this build knows (#3015) — preserving what+ * a newer peer wrote and minting a bogus key are different things, so an+ * unrecognized write target throws while sibling keys are untouched either way.*/export function withTrackTarget(animationTargets, track, { frameCount, fps, source }) {const row = getAnimationTrack(track);@@ -161,10 +155,10 @@ export function withTrackTarget(animationTargets, track, { frameCount, fps, sour* to the default track when the caller passed a bare `{ frameCount, fps }`.*/export function targetDrift(target, packagedCycles = []) {- const { readFrameCount, readFps } = trackReaders(getAnimationTrack(target?.track));+ const row = getAnimationTrack(target?.track);return (packagedCycles || []).flatMap((cycle) => {- const frameCount = readFrameCount(cycle?.frameCount);- const fps = readFps(cycle?.fps);+ const frameCount = readFrameCount(row, cycle?.frameCount);+ const fps = readFps(row, cycle?.fps);if (frameCount === null && fps === null) return [];const countDrifts = frameCount !== null && frameCount !== target.frameCount;const fpsDrifts = fps !== null && fps !== target.fps;diff --git a/server/services/sprites/animationTracks.js b/server/services/sprites/animationTracks.jsindex edf7220aaf..bed5403b93 100644--- a/server/services/sprites/animationTracks.js+++ b/server/services/sprites/animationTracks.js@@ -44,7 +44,8 @@ export const WALK_TRACK = 'walk';* - `contractFrameCountField` / `contractFpsField` — the field names this track* occupies in an app's `publishBinding.runtimeContract` (#2982). Named here so* the app rung of the precedence chain is track-driven rather than hard-coded- * to `walkFrameCount`.+ * to `walkFrameCount`. `contractFpsField` may be `null` for a track whose+ * speed an app has no say in.*/export const ANIMATION_TRACKS = Object.freeze({[WALK_TRACK]: Object.freeze({@@ -58,6 +59,11 @@ export const ANIMATION_TRACKS = Object.freeze({maxFps: 24,defaultFps: 10,contractFrameCountField: 'walkFrameCount',+ // `spriteRuntimeContractSchema` deliberately declares no fps key (a+ // distance-driven consumer has no animation-fps concept), so today this is+ // reachable only by a legacy/hand-built contract object — kept, not+ // nulled, because dropping it would change resolution behavior for those.+ // A second track copying this row should decide its own answer.contractFpsField: 'walkFps',}),});@@ -65,6 +71,35 @@ export const ANIMATION_TRACKS = Object.freeze({/** Known track ids, in registry order. */export const ANIMATION_TRACK_IDS = Object.freeze(Object.keys(ANIMATION_TRACKS));+// Fail fast at module load, the way navManifest.js and catalogTypes.js guard+// their registries: a row missing a bound would otherwise boot clean and+// surface much later as `NaN` out of a Math.min, or as `z.number().min(+// undefined)` throwing at the first sprite render. A bad row should block boot+// with a message naming the field, not corrupt a render hours later.+for (const id of ANIMATION_TRACK_IDS) {+ const row = ANIMATION_TRACKS[id];+ if (row.id !== id) throw new Error(`animationTracks: row '${id}' declares mismatched id '${row.id}'`);+ if (typeof row.label !== 'string' || !row.label) throw new Error(`animationTracks: track '${id}' needs a label`);+ if (typeof row.directional !== 'boolean') throw new Error(`animationTracks: track '${id}' needs a boolean 'directional'`);+ for (const field of ['minFrameCount', 'maxFrameCount', 'defaultFrameCount', 'minFps', 'maxFps', 'defaultFps']) {+ if (!Number.isInteger(row[field])) throw new Error(`animationTracks: track '${id}' needs an integer '${field}'`);+ }+ if (typeof row.contractFrameCountField !== 'string' || !row.contractFrameCountField) {+ throw new Error(`animationTracks: track '${id}' needs a contractFrameCountField`);+ }+ if (row.contractFpsField !== null && (typeof row.contractFpsField !== 'string' || !row.contractFpsField)) {+ throw new Error(`animationTracks: track '${id}' needs a contractFpsField (or null)`);+ }+ for (const [min, def, max] of [+ ['minFrameCount', 'defaultFrameCount', 'maxFrameCount'],+ ['minFps', 'defaultFps', 'maxFps'],+ ]) {+ if (!(row[min] <= row[def] && row[def] <= row[max])) {+ throw new Error(`animationTracks: track '${id}' needs ${min} <= ${def} <= ${max}`);+ }+ }+}+/** True when `id` names a track this build knows. */export function isAnimationTrack(id) {return typeof id === 'string' && Object.prototype.hasOwnProperty.call(ANIMATION_TRACKS, id);@@ -85,18 +120,23 @@ export function getAnimationTrack(id) {return ANIMATION_TRACKS[key];}+// Round-then-clamp, with unusable input (NaN, non-numeric) falling back to the+// knob's default rather than to a bound — the two knobs differ only in which+// three row fields they read.+const clampInto = (n, min, max, fallback) => {+ const v = Math.round(Number(n));+ if (!Number.isFinite(v)) return fallback;+ return Math.max(min, Math.min(max, v));+};+/** Clamp a requested frame count into `track`'s authoring range. */export function clampTrackFrameCount(n, track) {const row = getAnimationTrack(track);- const v = Math.round(Number(n));- if (!Number.isFinite(v)) return row.defaultFrameCount;- return Math.max(row.minFrameCount, Math.min(row.maxFrameCount, v));+ return clampInto(n, row.minFrameCount, row.maxFrameCount, row.defaultFrameCount);}/** Clamp a requested playback fps into `track`'s authoring range. */export function clampTrackFps(n, track) {const row = getAnimationTrack(track);- const v = Math.round(Number(n));- if (!Number.isFinite(v)) return row.defaultFps;- return Math.max(row.minFps, Math.min(row.maxFps, v));+ return clampInto(n, row.minFps, row.maxFps, row.defaultFps);}diff --git a/server/services/sprites/animationTracks.test.js b/server/services/sprites/animationTracks.test.jsindex dd2ed09d3c..e39eb4e090 100644--- a/server/services/sprites/animationTracks.test.js+++ b/server/services/sprites/animationTracks.test.js@@ -9,15 +9,25 @@*/import { describe, it, expect } from 'vitest';-import { readFileSync, existsSync } from 'fs';+import { readFileSync } from 'fs';import { fileURLToPath } from 'url';-import { dirname, join, resolve } from 'path';+import { dirname, join } from 'path';import {WALK_TRACK, ANIMATION_TRACKS, ANIMATION_TRACK_IDS,isAnimationTrack, getAnimationTrack, clampTrackFrameCount, clampTrackFps,} from './animationTracks.js';+import {+ staticImportSpecifiers, staticImportClosure, specifierMatchesPackage,+} from '../../lib/staticImportGraph.js';+import {+ WALK_DEFAULT_FRAME_COUNT as CLIENT_DEFAULT_FRAME_COUNT,+ WALK_DEFAULT_FPS as CLIENT_DEFAULT_FPS,+ WALK_FRAME_COUNT_OPTIONS as CLIENT_FRAME_COUNT_OPTIONS,+ walkFpsOptionsFor as clientWalkFpsOptionsFor,+} from '../../../client/src/lib/spriteTrimmer.js';const SPRITES_DIR = dirname(fileURLToPath(import.meta.url));+const SERVER_DIR = dirname(dirname(SPRITES_DIR));describe('the registry rows', () => {it('reproduces the walk track\'s historical bounds and defaults exactly', () => {@@ -37,9 +47,9 @@ describe('the registry rows', () => {});it('describes every declared track completely', () => {- // A row missing a bound would fall through as `undefined` into a Math.min- // (→ NaN) or a Zod .min() (→ throw at boot); assert the shape up front so- // adding a track can't half-land.+ // Mirrors the module-load guard in animationTracks.js (which is what+ // actually blocks boot on a bad row) so a shape violation reads as a named+ // assertion here rather than only as an import-time throw somewhere else.for (const id of ANIMATION_TRACK_IDS) {const row = ANIMATION_TRACKS[id];expect(row.id, `${id}.id must match its registry key`).toBe(id);@@ -146,71 +156,84 @@ describe('walkBounds re-reads the walk row (no call-site churn)', () => {});});-// Matches `import … from './x.js'` / `export … from './x.js'` / bare-// `import './x.js'` at the start of a line — the same static-only scan-// agentImportCycles.test.js uses. Deliberately does NOT match `await import()`-// (deferred to call time) or the string inside a comment.-const STATIC_FROM = /^\s*(?:import|export)\b[^;]*?from\s*['"]([^'"]+)['"]/gm;-const STATIC_BARE = /^\s*import\s*['"]([^'"]+)['"]/gm;--function staticSpecifiers(file) {- const src = readFileSync(file, 'utf-8');- const out = [];- for (const re of [STATIC_FROM, STATIC_BARE]) {- re.lastIndex = 0;- let match;- while ((match = re.exec(src)) !== null) out.push(match[1]);- }- return out;-}--/** Every module statically reachable from `entry`, plus the bare packages hit. */-function importClosure(entry) {- const seen = new Set();- const packages = new Set();- const walk = (file) => {- if (seen.has(file)) return;- seen.add(file);- for (const spec of staticSpecifiers(file)) {- if (!spec.startsWith('.')) { packages.add(spec); continue; }- const next = resolve(dirname(file), spec);- if (existsSync(next)) walk(next);- }- };- walk(entry);- return { files: seen, packages };-}-describe('sharp-free leaf property', () => {- // server/lib/validation.js builds its sprite frame-count/fps ranges from this- // registry. If the registry (or anything it reaches) ever imports sharp, the- // native image graph lands in the request-validation graph — the exact- // regression walkBounds.js was split out to prevent, now one level deeper.+ // The property that actually matters is on `server/lib/validation.js`: it+ // builds its sprite frame-count/fps ranges from this registry, and the whole+ // reason walkBounds.js was split out (and now animationTracks.js beneath it)+ // is to keep the native image graph out of REQUEST VALIDATION. Asserting only+ // the three leaves would pass while someone routed sharp into validation.js+ // through any of its ~90 other closure members, so validation.js is the first+ // entry point here, not an afterthought.const NATIVE = ['sharp', 'canvas', 'fluent-ffmpeg', '@ffmpeg-installer/ffmpeg'];it.each([- ['animationTracks.js'],- ['walkBounds.js'],- ['animationTargets.js'],- ])('%s reaches no native image/video dependency', (file) => {- const { packages } = importClosure(join(SPRITES_DIR, file));- const offending = [...packages].filter((p) => NATIVE.some((n) => p === n || p.startsWith(`${n}/`)));- expect(offending, `${file} must not reach ${offending.join(', ')}`).toEqual([]);+ ['the request-validation graph', join(SERVER_DIR, 'lib', 'validation.js')],+ ['animationTracks.js', join(SPRITES_DIR, 'animationTracks.js')],+ ['walkBounds.js', join(SPRITES_DIR, 'walkBounds.js')],+ ['animationTargets.js', join(SPRITES_DIR, 'animationTargets.js')],+ ])('%s reaches no native image/video dependency', (_label, entry) => {+ const { packages } = staticImportClosure(entry);+ const offending = [...packages].filter((p) => NATIVE.some((n) => specifierMatchesPackage(p, n)));+ expect(offending, `must not reach ${offending.join(', ')}`).toEqual([]);});it('keeps animationTracks.js a true leaf — it imports nothing at all', () => {- expect(staticSpecifiers(join(SPRITES_DIR, 'animationTracks.js'))).toEqual([]);+ expect(staticImportSpecifiers(join(SPRITES_DIR, 'animationTracks.js'))).toEqual([]);});it('actually walks the graph (positive control — the guard is not vacuous)', () => {- // Two ways this assertion could pass for the wrong reason: the closure- // never follows relative imports, or it never records bare packages. Pin- // both against a module that genuinely reaches sharp.- const walkBounds = importClosure(join(SPRITES_DIR, 'walkBounds.js'));+ // Three ways the assertions above could pass for the wrong reason: the walk+ // never follows relative imports, it never records bare packages, or an+ // unresolvable specifier silently truncates it. Pin the first two against a+ // module that genuinely reaches sharp.+ const walkBounds = staticImportClosure(join(SPRITES_DIR, 'walkBounds.js'));expect([...walkBounds.files]).toContain(join(SPRITES_DIR, 'animationTracks.js'));- const packer = importClosure(join(SPRITES_DIR, 'walkPostprocess.js'));+ const packer = staticImportClosure(join(SPRITES_DIR, 'walkPostprocess.js'));expect([...packer.packages], 'walkPostprocess is the native-graph module this split exists to fence off').toContain('sharp');++ // …and that validation.js's closure is genuinely large, so a resolver gap+ // can't make its clean result meaningless.+ expect(staticImportClosure(join(SERVER_DIR, 'lib', 'validation.js')).files.size).toBeGreaterThan(20);+ });+});++describe('client mirror parity', () => {+ // `client/src/lib/spriteTrimmer.js` restates walk's bounds as literals so the+ // pickers can seed their option lists without importing a server module. The+ // registry is now the source of truth for a SET of ranges, so the first real+ // per-track bounds change — the entire motivation for #3015 — would silently+ // desync the picker from the server's Zod range and surface as a 400 with no+ // field-level explanation. Same guard shape as catalogTypes.parity.test.js.+ const walk = getAnimationTrack(WALK_TRACK);++ it('mirrors the walk defaults', () => {+ expect(CLIENT_DEFAULT_FRAME_COUNT).toBe(walk.defaultFrameCount);+ expect(CLIENT_DEFAULT_FPS).toBe(walk.defaultFps);+ });++ it('seeds the frame-count picker from the walk row\'s full range', () => {+ expect(CLIENT_FRAME_COUNT_OPTIONS[0]).toBe(walk.minFrameCount);+ expect(CLIENT_FRAME_COUNT_OPTIONS.at(-1)).toBe(walk.maxFrameCount);+ });++ it('seeds the fps picker within the walk row\'s range', () => {+ // The list is even-stepped, so it need not END on the max — but it must+ // start at the floor and never offer a value the server would reject.+ const options = clientWalkFpsOptionsFor(walk.defaultFps);+ expect(options[0]).toBe(walk.minFps);+ expect(Math.max(...options)).toBeLessThanOrEqual(walk.maxFps);+ });++ it('keeps the publish form\'s hard-coded frame-count bounds in step', () => {+ // PublishWorkflow.jsx is a React component (not importable under the server+ // runner), so its two mirrored literals are asserted as source text.+ const src = readFileSync(+ join(SERVER_DIR, '..', 'client', 'src', 'components', 'sprites', 'PublishWorkflow.jsx'),+ 'utf-8',+ );+ expect(src).toContain(`const WALK_MIN_FRAME_COUNT = ${walk.minFrameCount};`);+ expect(src).toContain(`const WALK_MAX_FRAME_COUNT = ${walk.maxFrameCount};`);});});diff --git a/server/services/sprites/atlasLayout.js b/server/services/sprites/atlasLayout.jsindex e01d467b85..d25add01ab 100644--- a/server/services/sprites/atlasLayout.js+++ b/server/services/sprites/atlasLayout.js@@ -35,9 +35,13 @@import { basename } from 'path';import { ATLAS_IDLE_COLUMN, ATLAS_SCANNER_COLUMN } from './walkBounds.js';// The track id the sidecar names its walk span with — read from the registry-// (#3015) so the layout descriptor and `animationTargets.walk` can never key the-// same track differently. animationTracks imports nothing, so this keeps the-// module dependency-free.+// (#3015) rather than restated as a local literal, so the descriptor and+// `animationTargets.walk` agree on how the walk span is spelled. Note the two+// namespaces are NOT otherwise unified: `deriveTracks` still mints track names+// straight from column labels (`idle`, `scanner`), which are not registry ids,+// and `walkColumnsOf` still defines walk as "everything that isn't idle or+// scanner". Reconciling those is the second track's job, not this import's.+// animationTracks imports nothing, so this keeps the module dependency-free.import { WALK_TRACK } from './animationTracks.js';// Bump only on a breaking shape change. Adding a field (or a new track) is