The Open Framework for Building Agents
Add phase to eve hero (#580)
Matias Gonzalezb8a119168615
diff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/hooks.ts b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/hooks.tsindex 7e65508a3..881611b9d 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/hooks.ts+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/hooks.ts@@ -1,23 +1,24 @@+import { useSyncedRef } from "phase/react";import { useEffect, useState } from "react";-// Owns browser theme and reduced-motion subscriptions for the Eve hero.+// Owns browser theme subscriptions for the Eve hero.// INVARIANT: resolution order matches the old index.tsx hooks exactly.// Imported only by index.tsx.-export function getCurrentTheme(): "light" | "dark" {+export function getCurrentTheme(prefersDarkTheme: boolean): "light" | "dark" {if (typeof document === "undefined") return "light";const root = document.documentElement;if (root.classList.contains("dark") || root.dataset.theme === "dark") return "dark";if (root.classList.contains("light") || root.dataset.theme === "light") return "light";- return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";+ return prefersDarkTheme ? "dark" : "light";}-export function useResolvedTheme() {+export function useResolvedTheme(prefersDarkTheme: boolean) {const [theme, setTheme] = useState<"light" | "dark">("light");+ const prefersDarkThemeRef = useSyncedRef(prefersDarkTheme);useEffect(() => {- const syncTheme = () => setTheme(getCurrentTheme());- const media = window.matchMedia("(prefers-color-scheme: dark)");+ const syncTheme = () => setTheme(getCurrentTheme(prefersDarkThemeRef.current));const observer = new MutationObserver(syncTheme);syncTheme();@@ -25,29 +26,15 @@ export function useResolvedTheme() {attributes: true,attributeFilter: ["class", "data-theme"],});- media.addEventListener("change", syncTheme);-return () => {observer.disconnect();- media.removeEventListener("change", syncTheme);};}, []);- return theme;-}--export function usePrefersReducedMotion() {- const [prefersReducedMotion, setPrefersReducedMotion] = useState<boolean | null>(null);-useEffect(() => {- const media = window.matchMedia("(prefers-reduced-motion: reduce)");- const syncPreference = () => setPrefersReducedMotion(media.matches);+ setTheme(getCurrentTheme(prefersDarkTheme));+ }, [prefersDarkTheme]);- syncPreference();- media.addEventListener("change", syncPreference);-- return () => media.removeEventListener("change", syncPreference);- }, []);-- return prefersReducedMotion;+ return theme;}+diff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/index.tsx b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/index.tsxindex 411c8c495..adad49309 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/index.tsx+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/index.tsx@@ -1,24 +1,39 @@"use client";import { App, Device, type VGPUAdapter } from "@vgpu/core";+import { createDevicePixelRatio, prefersReducedMotion as prefersReducedMotionSync } from "phase";+import {+ useLoop,+ useMediaQuery,+ usePrefersReducedMotion,+ useSize,+ useStableCallback,+ useSyncedRef,+} from "phase/react";import { useEffect, useRef, useState, type CSSProperties } from "react";+import { preload } from "react-dom";import { meshAspect } from "./mesh";import {FallbackImage,FALLBACK_CONTAINER_ASPECT_RATIO,getFallbackImageProps,} from "./fallback-image";-import { usePrefersReducedMotion, useResolvedTheme } from "./hooks";-import { DEFAULT_LOGO_ASPECT, getLogicalRenderSize, resizeCanvas } from "./runtime/canvas-sizing";-import { loadMesh } from "./runtime/load-mesh";+import { useResolvedTheme } from "./hooks";+import {+ DEFAULT_LOGO_ASPECT,+ getLogicalRenderSize,+ resizeCanvas,+ type CanvasLayout,+} from "./runtime/canvas-sizing";+import { loadMesh, MODEL_URL } from "./runtime/load-mesh";import {destroyTransitionDebugGui,setupTransitionDebugGui,type EveTransitionDebugGui,type EveTransitionDebugState,} from "./runtime/debug-gui";-import { createDrawLoop } from "./runtime/frame-loop";-import { createPointerController } from "./runtime/pointer-input";+import { createDrawLoop, type DrawLoop } from "./runtime/frame-loop";+import { createPointerController, syncPointerInteractionMode } from "./runtime/pointer-input";import type { HeroRuntimeState } from "./runtime/state";import {BLOOM_RADIUS,@@ -58,12 +73,27 @@ const DEFAULT_CONTROLS: RenderControls = {};export const AGENTS_ENV_YAW_LERP_SPEED = 3;const LOGO_MODE_TRANSITION_DURATION_SECONDS = 0.45;-const IMPRINT_GLYPH_SCALE = 1.35;+const IMPRINT_GLYPH_SCALE = 1.27;+const IS_PRODUCTION = process.env.NODE_ENV === "production";+const INITIAL_CANVAS_LAYOUT: CanvasLayout = { width: 1, height: 1 };+export function EveLogoShader({ audience = "humans" }: { audience?: InstallAudience }) {- const theme = useResolvedTheme();+ preload(MODEL_URL, { as: "fetch", crossOrigin: "anonymous" });+ const prefersDarkTheme = useMediaQuery("(prefers-color-scheme: dark)");+ const theme = useResolvedTheme(prefersDarkTheme);const prefersReducedMotion = usePrefersReducedMotion();+ const coarsePointer = useMediaQuery("(pointer: coarse)");+ const containerRef = useRef<HTMLDivElement>(null);+ const { size: containerSize } = useSize({ ref: containerRef });const canvasRef = useRef<HTMLCanvasElement>(null);const controlsRef = useRef<RenderControls>({ ...DEFAULT_CONTROLS });+ const canvasLayoutRef = useRef<CanvasLayout>(INITIAL_CANVAS_LAYOUT);+ const devicePixelRatioRef = useRef(1);+ const coarsePointerRef = useSyncedRef(coarsePointer);+ const stateRef = useRef<HeroRuntimeState | null>(null);+ const drawLoopRef = useRef<DrawLoop | null>(null);+ const loopPhaseRef = useRef("idle");+ const invalidatePointerCanvasRectRef = useRef(() => {});const [logoAspect, setLogoAspect] = useState(DEFAULT_LOGO_ASPECT);const [revealed, setRevealed] = useState(false);const [showLightFallback, setShowLightFallback] = useState(false);@@ -72,6 +102,47 @@ export function EveLogoShader({ audience = "humans" }: { audience?: InstallAudieconst agentsSelected = audience === "agents";targetAgentsEnvYawMixRef.current = agentsSelected ? 1 : 0;targetLogoModeProgressRef.current = agentsSelected ? 1 : 0;+ const handleCanvasRevealed = useStableCallback(() => {+ if (!stateRef.current?.cancelled) setRevealed(true);+ });+ const handleFallback = useStableCallback(() => {+ setRevealed(false);+ setShowLightFallback(true);+ });+ const fatalErrorRef = useRef<(() => void) | null>(null);+ const handleFatalError = useStableCallback(() => {+ fatalErrorRef.current?.();+ });++ const { phase: loopPhase } = useLoop({+ ref: containerRef,+ reducedMotion: "pause",+ intersectionOptions: { threshold: 0 },+ onTick: (frame) => {+ drawLoopRef.current?.step(frame.time);+ },+ });++ useEffect(() => {+ loopPhaseRef.current = loopPhase;+ const canvas = canvasRef.current;+ if (!IS_PRODUCTION && canvas) {+ canvas.dataset.heroPhase = loopPhase === "running" ? "active" : String(loopPhase);+ }+ if (loopPhase === "running") drawLoopRef.current?.start();+ else drawLoopRef.current?.stop();+ }, [loopPhase]);++ useEffect(() => {+ if (!containerSize) return;+ canvasLayoutRef.current = containerSize;+ invalidatePointerCanvasRectRef.current();+ }, [containerSize]);++ useEffect(() => {+ const state = stateRef.current;+ if (state) syncPointerInteractionMode(state, coarsePointer);+ }, [coarsePointer]);useEffect(() => {const state: HeroRuntimeState = {@@ -102,30 +173,63 @@ export function EveLogoShader({ audience = "humans" }: { audience?: InstallAudielastBrushMoveTime: Number.NEGATIVE_INFINITY,lastPointerClientX: undefined,lastPointerClientY: undefined,- isCoarsePointer: window.matchMedia("(pointer: coarse)").matches,+ isCoarsePointer: coarsePointerRef.current,};+ stateRef.current = state;const canvas = canvasRef.current;resetCanvasVisibility(canvas);setRevealed(false);- if (prefersReducedMotion !== false) {+ const dprWatcher = createDevicePixelRatio({+ onChange: (dpr) => {+ devicePixelRatioRef.current = dpr;+ invalidatePointerCanvasRectRef.current();+ },+ });+ devicePixelRatioRef.current = dprWatcher.dpr;++ const pointerController = createPointerController({+ state,+ controlsRef,+ canvasRef,+ coarsePointerRef,+ canvasLayoutRef,+ devicePixelRatioRef,+ });+ invalidatePointerCanvasRectRef.current = pointerController.invalidateCanvasRect;++ const cleanupSetup = () => {+ state.cancelled = true;+ pointerController.detach();+ dprWatcher.stop();+ invalidatePointerCanvasRectRef.current = () => {};+ state.cleanup = undefined;+ stateRef.current = null;+ drawLoopRef.current = null;+ fatalErrorRef.current = null;+ resetCanvasVisibility(canvasRef.current);+ };++ const resolvedPrefersReducedMotion = prefersReducedMotion || prefersReducedMotionSync();+ if (resolvedPrefersReducedMotion) {// No WebGPU animation will run (reduced motion or the preference hasn't// resolved yet), so the canvas stays hidden. Show the static light// fallback to mirror the dark fallback, which is always visible until// the animation reveals. Otherwise light-theme users would see a blank hero.setShowLightFallback(true);- return;+ return cleanupSetup;}setShowLightFallback(false);- const pointerController = createPointerController({ state, controlsRef, canvasRef });+ let disposeRuntime: (() => void) | undefined;async function start() {const renderTheme = theme;const canvas = canvasRef.current;+ const container = containerRef.current;const context = canvas?.getContext("webgpu");- if (!canvas || !context || !navigator.gpu) {+ if (!canvas || !container || !context || !navigator.gpu) {setShowLightFallback(true);return;}@@ -135,7 +239,7 @@ export function EveLogoShader({ audience = "humans" }: { audience?: InstallAudiestate.activeMesh = mesh;setLogoAspect(meshAspect(mesh));await nextFrame();- resizeCanvas(canvas);+ resizeCanvas(canvas, canvasLayoutRef, devicePixelRatioRef);const app = await App.create({ adapter: new BrowserAdapter() });if (state.cancelled) {@@ -154,7 +258,7 @@ export function EveLogoShader({ audience = "humans" }: { audience?: InstallAudieconst transitionDebug: EveTransitionDebugState = {overrideEnabled: false,progress: modeTransitionProgressRef.current,- gridScaleMultiplier: DEFAULT_IMPRINT_GRID_SCALE_MULTIPLIER,+ gridScaleMultiplier: 1.31,glyphScale: IMPRINT_GLYPH_SCALE,durationSeconds: LOGO_MODE_TRANSITION_DURATION_SECONDS,paintDecayPerFrame120: DEFAULT_PAINT_DECAY_PER_FRAME_120,@@ -179,6 +283,8 @@ export function EveLogoShader({ audience = "humans" }: { audience?: InstallAudieconst dispose = () => {if (disposed) return;disposed = true;+ drawLoopRef.current = null;+ fatalErrorRef.current = null;drawLoopDispose?.();resetCanvasVisibility(canvas);if (!state.cancelled) setRevealed(false);@@ -186,11 +292,13 @@ export function EveLogoShader({ audience = "humans" }: { audience?: InstallAudietransitionDebugGui = undefined;renderer.dispose();app.device.destroy();+ disposeRuntime = undefined;};+ disposeRuntime = dispose;app.device.gpu.lost- .then(() => {- if (state.cancelled) return;+ .then((info) => {+ if (state.cancelled || disposed || info?.reason === "destroyed") return;setRevealed(false);setShowLightFallback(true);state.cancelled = true;@@ -211,17 +319,16 @@ export function EveLogoShader({ audience = "humans" }: { audience?: InstallAudietargetLogoModeProgressRef,targetAgentsEnvYawMixRef,defaultMaterial: DEFAULT_CONTROLS.material,- onCanvasRevealed: () => {- if (!state.cancelled) setRevealed(true);- },- onFallback: () => {- setRevealed(false);- setShowLightFallback(true);- },- onFatalError: dispose,+ canvasLayoutRef,+ devicePixelRatioRef,+ onCanvasRevealed: handleCanvasRevealed,+ onFallback: handleFallback,+ onFatalError: handleFatalError,});drawLoopDispose = drawLoop.dispose;- drawLoop.draw();+ drawLoopRef.current = drawLoop;+ fatalErrorRef.current = dispose;+ if (loopPhaseRef.current === "running") drawLoop.start();return dispose;}@@ -237,12 +344,10 @@ export function EveLogoShader({ audience = "humans" }: { audience?: InstallAudiereturn () => {state.cancelled = true;- cancelAnimationFrame(state.animationFrame);- pointerController.detach();- state.cleanup?.();- resetCanvasVisibility(canvasRef.current);+ cleanupSetup();+ disposeRuntime?.();};- }, [theme, prefersReducedMotion]);+ }, [theme, prefersReducedMotion, handleCanvasRevealed, handleFallback, handleFatalError]);const logicalSize = getLogicalRenderSize(logoAspect);const paddedWidth = logicalSize.width + BLOOM_RADIUS * 2;@@ -251,6 +356,7 @@ export function EveLogoShader({ audience = "humans" }: { audience?: InstallAudiereturn (<div+ ref={containerRef}aria-hidden="true"className="pointer-events-none relative z-0 mb-8 aspect-[var(--eve-logo-mobile-aspect-ratio)] w-full md:absolute md:left-1/2 md:top-1/2 md:mb-0 md:h-[6.5em] md:w-auto md:max-w-none md:-translate-x-1/2 md:translate-y-[calc(-50%-0.42em)] md:aspect-[var(--eve-logo-desktop-aspect-ratio)]"style={diff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render.ts b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render.tsindex aba918e00..089ef3b38 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render.ts+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render.ts@@ -26,5 +26,7 @@ export {DEFAULT_PAINT_DIFFUSION_RATE,DEFAULT_PAINT_DT,imprintCellSizeForDevicePixelRatio,+ imprintCellSizeForLogicalHeight,+ imprintGridSizeForLogicalSize,} from "./render/constants";export type { Bounds, EnvLightConfig, EveMaterial, ImprintRenderOptions, MeshData, PaintPointerMapping, PaintPointerMappingInput, PaintPointerRect, PaintRenderOptions, PaintSeed, PaintStroke, RenderControls, StudioCubemap } from "./render/types";diff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/constants.ts b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/constants.tsindex 027305d7c..0a1ae18b2 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/constants.ts+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/constants.ts@@ -43,6 +43,7 @@ export const EVE_THICKNESS_SCALE_MULTIPLIER = 1.3;export const PREVIEW_BACK_ALBEDO = 0;export const PREVIEW_BACK_DEPTH = 1;export const DEFAULT_IMPRINT_CELL_SIZE = 16;+export const REFERENCE_IMPRINT_LOGICAL_HEIGHT = 348;export const DEFAULT_IMPRINT_DEVICE_PIXEL_RATIO = 2;export const DEFAULT_IMPRINT_GRID_SCALE_MULTIPLIER = 0.71;export const DEFAULT_IMPRINT_GLYPH_SCALE = 1.35;@@ -68,6 +69,27 @@ function safeDevicePixelRatioOrDefault(devicePixelRatio: number | undefined) {return Math.max(0.001, ratio);}+export function imprintCellSizeForLogicalHeight(logicalHeight: number) {+ const safeLogicalHeight = typeof logicalHeight === "number" && Number.isFinite(logicalHeight)+ ? logicalHeight+ : REFERENCE_IMPRINT_LOGICAL_HEIGHT;++ return DEFAULT_IMPRINT_CELL_SIZE * (Math.max(1, safeLogicalHeight) / REFERENCE_IMPRINT_LOGICAL_HEIGHT);+}++export function imprintGridSizeForLogicalSize(+ logicalWidth: number,+ logicalHeight: number,+ gridScaleMultiplier = DEFAULT_IMPRINT_GRID_SCALE_MULTIPLIER,+) {+ const cellSize = imprintCellSizeForLogicalHeight(logicalHeight);+ const multiplierScale = Math.max(0.001, gridScaleMultiplier) / DEFAULT_IMPRINT_GRID_SCALE_MULTIPLIER;+ return {+ cols: Math.max(1, Math.ceil((logicalWidth / cellSize) * multiplierScale)),+ rows: Math.max(1, Math.ceil((logicalHeight / cellSize) * multiplierScale)),+ };+}+export function imprintCellSizeForDevicePixelRatio(devicePixelRatio = DEFAULT_IMPRINT_DEVICE_PIXEL_RATIO,) {diff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/paint-system.ts b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/paint-system.tsindex 5f54fb7b1..c655b68aa 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/paint-system.ts+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/paint-system.ts@@ -14,7 +14,7 @@ import {DEFAULT_PAINT_DIFFUSION_RATE,DEFAULT_PAINT_DT,PAINT_STROKE_MOVEMENT_EPSILON_CELLS,- imprintCellSizeForDevicePixelRatio,+ imprintGridSizeForLogicalSize,} from "./constants";import { mix } from "./math";import { paintMappingMetrics } from "./pointer-mapping";@@ -39,10 +39,8 @@ export function createPaintSystem(device: Device, resources: RendererResources,targets = undefined;};- const ensure = (logicalWidth: number, logicalHeight: number, devicePixelRatio?: number) => {- const cellSize = imprintCellSizeForDevicePixelRatio(devicePixelRatio);- const cols = Math.max(1, Math.ceil(logicalWidth / cellSize));- const rows = Math.max(1, Math.ceil(logicalHeight / cellSize));+ const ensure = (logicalWidth: number, logicalHeight: number, gridScaleMultiplier?: number) => {+ const { cols, rows } = imprintGridSizeForLogicalSize(logicalWidth, logicalHeight, gridScaleMultiplier);if (targets?.cols === cols && targets.rows === rows) return targets;dispose();const ping = createPaintTexture(device, "eve-5-paint-ping", cols, rows);diff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/pointer-mapping.ts b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/pointer-mapping.tsindex 41fcb1b00..f830176e9 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/pointer-mapping.ts+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/pointer-mapping.ts@@ -6,7 +6,7 @@ import type { Bounds, PaintPointerMapping, PaintPointerMappingInput, RenderContrimport {BLOOM_RADIUS,DEFAULT_IMPRINT_GRID_SCALE_MULTIPLIER,- imprintCellSizeForDevicePixelRatio,+ imprintCellSizeForLogicalHeight,} from "./constants";import { meshOrbitTargetFromBounds } from "./camera";import { degreesToRadians, dot } from "./math";@@ -62,7 +62,7 @@ export function paintMappingMetrics(logicalHeight: number,gridScaleMultiplier: number,paddingRadius: number,- devicePixelRatio?: number,+ _devicePixelRatio?: number,) {const padded = getPaddedRenderSize(logicalWidth, logicalHeight, paddingRadius);const fovRad = degreesToRadians(controls.fov);@@ -73,7 +73,7 @@ export function paintMappingMetrics(const basis = cameraBasis(eye, orbitTarget);const distToFrontPlane = Math.max(0.001, -dot(eye, basis.forward));const pxPerModelUnit = padded.height / (2 * distToFrontPlane * Math.tan(fovEff * 0.5));- const cellSize = imprintCellSizeForDevicePixelRatio(devicePixelRatio);+ const cellSize = imprintCellSizeForLogicalHeight(logicalHeight);const gridScale = (pxPerModelUnit / cellSize) * Math.max(0.001, gridScaleMultiplier);const normalizedBounds = normalizedMeshBounds(bounds);const originCell: [number, number] = [diff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/renderer.ts b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/renderer.tsindex 6698cdb7d..87b6ec509 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/renderer.ts+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/render/renderer.ts@@ -41,7 +41,7 @@ export function createEve5Renderer(const safeHeight = Math.max(1, Math.round(logicalHeight));const paddingRadius = options.paddingRadius ?? bloomRadiusForDevicePixelRatio(imprint.devicePixelRatio);const targets = bloomTargets.ensure(safeWidth, safeHeight, paddingRadius);- const currentPaintTargets = paintSystem.ensure(safeWidth, safeHeight, imprint.devicePixelRatio);+ const currentPaintTargets = paintSystem.ensure(safeWidth, safeHeight, imprint.gridScaleMultiplier);const backSurfaceDepthView = targets.backSurfaceDepth.createView();renderBackMaterial(diff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/canvas-sizing.ts b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/canvas-sizing.tsindex b3533d30f..c76078425 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/canvas-sizing.ts+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/canvas-sizing.ts@@ -1,3 +1,4 @@+import type { MutableRefObject } from "react";import { DEFAULT_IMPRINT_DEVICE_PIXEL_RATIO, bloomRadiusForDevicePixelRatio } from "../render";// Owns canvas and hero-logo sizing math for the browser renderer.@@ -8,6 +9,14 @@ export const DEFAULT_LOGO_ASPECT = 78 / 25;const LOGO_RENDER_HEIGHT = 500;const MAX_DEVICE_PIXEL_RATIO = DEFAULT_IMPRINT_DEVICE_PIXEL_RATIO;+export type CanvasLayout = {+ width: number;+ height: number;+};++export type CanvasLayoutRef = MutableRefObject<CanvasLayout>;+export type DevicePixelRatioRef = MutableRefObject<number>;+export function getLogicalRenderSize(aspect: number) {return {width: Math.max(1, Math.round(LOGO_RENDER_HEIGHT * aspect)),@@ -15,16 +24,20 @@ export function getLogicalRenderSize(aspect: number) {};}-export function getBrowserDevicePixelRatio() {- return Math.min(window.devicePixelRatio || 1, MAX_DEVICE_PIXEL_RATIO);+export function getBrowserDevicePixelRatio(devicePixelRatio: number) {+ return Math.min(devicePixelRatio || 1, MAX_DEVICE_PIXEL_RATIO);}-export function resizeCanvas(canvas: HTMLCanvasElement | null) {- const dpr = getBrowserDevicePixelRatio();+export function resizeCanvas(+ canvas: HTMLCanvasElement | null,+ canvasLayoutRef: CanvasLayoutRef,+ devicePixelRatioRef: DevicePixelRatioRef,+) {+ const dpr = getBrowserDevicePixelRatio(devicePixelRatioRef.current);if (!canvas) return dpr;- const rect = canvas.getBoundingClientRect();- const width = Math.max(1, Math.floor(rect.width * dpr));- const height = Math.max(1, Math.floor(rect.height * dpr));+ const { width: cssWidth, height: cssHeight } = canvasLayoutRef.current;+ const width = Math.max(1, Math.floor(cssWidth * dpr));+ const height = Math.max(1, Math.floor(cssHeight * dpr));if (canvas.width !== width || canvas.height !== height) {canvas.width = width;canvas.height = height;@@ -34,7 +47,7 @@ export function resizeCanvas(canvas: HTMLCanvasElement | null) {export function getCanvasLogicalSize(canvas: HTMLCanvasElement,- devicePixelRatio = getBrowserDevicePixelRatio(),+ devicePixelRatio: number,) {// The renderer pads the logical scene size by a DPR-scaled bloom radius on each side before// allocating its offscreen back/depth targets. The canvas itself is that padded physical renderdiff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/frame-loop.ts b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/frame-loop.tsindex e08dcf284..b5f1814ff 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/frame-loop.ts+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/frame-loop.ts@@ -1,13 +1,19 @@+import { clamp, clamp01, easeInOutCubic, lerp } from "phase/ease";import type { MutableRefObject } from "react";import { evePointerInteractionMode, mobileAutoEnvYaw } from "../mobile-motion";import type { ImprintRenderOptions, RenderControls } from "../render";-import { getCanvasLogicalSize, resizeCanvas } from "./canvas-sizing";+import {+ getCanvasLogicalSize,+ resizeCanvas,+ type CanvasLayoutRef,+ type DevicePixelRatioRef,+} from "./canvas-sizing";import type { EveTransitionDebugState } from "./debug-gui";import type { ControlsRef, HeroRuntimeState } from "./state";-// Owns the Eve hero rAF draw loop and canvas reveal sequencing.+// Owns the Eve hero draw step and canvas reveal sequencing.// INVARIANT: dataset markers, paint movement gating, and fallback-on-error behavior are preserved.-// Imported only by index.tsx's single effect.+// Imported only by index.tsx's single effect and driven by phase's useLoop.const ENV_YAW_LERP_SPEED = 3;export const AGENTS_ENV_YAW_LERP_SPEED = 3;@@ -16,6 +22,10 @@ const ASCII_MOUSE_LERP_SPEED = 6;const PAINT_MOVEMENT_GRACE_MS = 72;const CANVAS_FADE_FALLBACK_MS = 800;const CANVAS_REVEAL_RENDER_COUNT = 3;+const MAX_FRAME_DELTA_SECONDS = 0.05;+export const AGENTS_MAX_FRAME_DELTA_SECONDS = MAX_FRAME_DELTA_SECONDS;++const PROBE_DATASET_WRITE_INTERVAL_MS = 250;type Renderer = {render: (@@ -27,6 +37,40 @@ type Renderer = {) => void;};+const IS_PRODUCTION = process.env.NODE_ENV === "production";++type EveHeroFrameLoopProbe = {+ frames: number;+ running: boolean;+ lastFrameAt: number;+};++declare global {+ interface Window {+ __eveHeroFrameLoop?: EveHeroFrameLoopProbe;+ }+}++function getHeroFrameLoopProbe(): EveHeroFrameLoopProbe | undefined {+ if (IS_PRODUCTION) return undefined;+ if (typeof window === "undefined") return undefined;+ if (!window.__eveHeroFrameLoop) {+ window.__eveHeroFrameLoop = {+ frames: 0,+ running: false,+ lastFrameAt: 0,+ };+ }+ return window.__eveHeroFrameLoop;+}++export type DrawLoop = {+ start: () => void;+ stop: () => void;+ step: (frameTime?: number) => void;+ dispose: () => void;+};+export function createDrawLoop({state,canvas,@@ -38,6 +82,8 @@ export function createDrawLoop({targetLogoModeProgressRef,targetAgentsEnvYawMixRef,defaultMaterial,+ canvasLayoutRef,+ devicePixelRatioRef,onCanvasRevealed,onFallback,onFatalError,@@ -52,70 +98,88 @@ export function createDrawLoop({targetLogoModeProgressRef: MutableRefObject<number>;targetAgentsEnvYawMixRef: MutableRefObject<number>;defaultMaterial: RenderControls["material"];+ canvasLayoutRef: CanvasLayoutRef;+ devicePixelRatioRef: DevicePixelRatioRef;onCanvasRevealed: () => void;onFallback: () => void;onFatalError: () => void;}) {let successfulRenderCount = 0;let finishCanvasFade: (() => void) | undefined;+ let running = false;+ const frameLoopProbe = getHeroFrameLoopProbe();+ let lastProbeDatasetWrite = 0;++ const updateFrameLoopProbeDataset = (force = false) => {+ if (!frameLoopProbe) return;+ const now = performance.now();+ if (!force && now - lastProbeDatasetWrite < PROBE_DATASET_WRITE_INTERVAL_MS) return;+ lastProbeDatasetWrite = now;+ canvas.dataset.heroFrames = String(frameLoopProbe.frames);+ canvas.dataset.heroRunning = String(frameLoopProbe.running);+ canvas.dataset.heroLastFrameAt = String(Math.round(frameLoopProbe.lastFrameAt));+ };const draw = (frameTime = performance.now()) => {- if (state.cancelled) return;+ if (!running || state.cancelled) return;- const deltaSeconds = Math.max(0, (frameTime - state.previousFrameTime) / 1000);+ const deltaSeconds = Math.min(+ MAX_FRAME_DELTA_SECONDS,+ Math.max(0, (frameTime - state.previousFrameTime) / 1000),+ );state.previousFrameTime = frameTime;if (evePointerInteractionMode(state.isCoarsePointer).autoRotateEnvYaw) {state.targetMouseEnvYaw = mobileAutoEnvYaw((frameTime - state.autoRotateStartTime) / 1000);state.targetMouseEnvPitch = 0;state.targetBrushActive = false;}- state.mouseEnvYaw = safeLerp(+ state.mouseEnvYaw = lerp(state.mouseEnvYaw,state.targetMouseEnvYaw,- deltaSeconds * ENV_YAW_LERP_SPEED,+ clamp01(deltaSeconds * ENV_YAW_LERP_SPEED),);- state.mouseEnvPitch = safeLerp(+ state.mouseEnvPitch = lerp(state.mouseEnvPitch,state.targetMouseEnvPitch,- deltaSeconds * ENV_YAW_LERP_SPEED,+ clamp01(deltaSeconds * ENV_YAW_LERP_SPEED),);- state.asciiMouseX = safeLerp(+ state.asciiMouseX = lerp(state.asciiMouseX,state.targetAsciiMouseX,- deltaSeconds * ASCII_MOUSE_LERP_SPEED,+ clamp01(deltaSeconds * ASCII_MOUSE_LERP_SPEED),);- state.asciiMouseY = safeLerp(+ state.asciiMouseY = lerp(state.asciiMouseY,state.targetAsciiMouseY,- deltaSeconds * ASCII_MOUSE_LERP_SPEED,+ clamp01(deltaSeconds * ASCII_MOUSE_LERP_SPEED),);state.brushActive = state.targetBrushActive && state.hasBrushCell;const targetAgentsEnvYawMix = targetAgentsEnvYawMixRef.current;- state.agentsEnvYawMix = safeLerp(+ state.agentsEnvYawMix = lerp(state.agentsEnvYawMix,targetAgentsEnvYawMix,- deltaSeconds * AGENTS_ENV_YAW_LERP_SPEED,+ clamp01(deltaSeconds * AGENTS_ENV_YAW_LERP_SPEED),);controlsRef.current.envYaw = state.mouseEnvYaw + state.agentsEnvYawMix * AGENTS_ENV_YAW_OFFSET;controlsRef.current.envPitch = state.mouseEnvPitch;- const devicePixelRatio = resizeCanvas(canvas);+ const devicePixelRatio = resizeCanvas(canvas, canvasLayoutRef, devicePixelRatioRef);const { logicalWidth, logicalHeight } = getCanvasLogicalSize(canvas, devicePixelRatio);try {- const transitionDurationSeconds = clampRange(transitionDebug.durationSeconds, 0.05, 2);+ const transitionDurationSeconds = clamp(transitionDebug.durationSeconds, 0.05, 2);modeTransitionProgressRef.current = stepLogoModeProgress(modeTransitionProgressRef.current,targetLogoModeProgressRef.current,deltaSeconds,transitionDurationSeconds,);- const animatedMixProgress = easeLogoModeProgress(modeTransitionProgressRef.current);+ const animatedMixProgress = easeInOutCubic(clamp01(modeTransitionProgressRef.current));const mixProgress = transitionDebug.overrideEnabled- ? clampUnit(transitionDebug.progress)+ ? clamp01(transitionDebug.progress): animatedMixProgress;const timeSeconds = frameTime / 1000;- const gridScaleMultiplier = clampRange(transitionDebug.gridScaleMultiplier, 0.5, 2);+ const gridScaleMultiplier = clamp(transitionDebug.gridScaleMultiplier, 0.5, 2);state.paintGridScaleMultiplier = gridScaleMultiplier;controlsRef.current.material = transitionDebug.visualizePaintBuffer? "paint-debug"@@ -133,7 +197,7 @@ export function createDrawLoop({{progress: mixProgress,gridScaleMultiplier,- glyphScale: clampRange(transitionDebug.glyphScale, 0.5, 2.5),+ glyphScale: clamp(transitionDebug.glyphScale, 0.5, 2.5),time: timeSeconds,mouse: [state.asciiMouseX, state.asciiMouseY],devicePixelRatio,@@ -144,12 +208,12 @@ export function createDrawLoop({dt: deltaSeconds,brushCell: [state.brushCellX, state.brushCellY],brushPreviousCell,- brushRadius: clampRange(transitionDebug.brushRadius, 1, 8),- brushStrength: clampRange(transitionDebug.brushStrength, 4, 32),+ brushRadius: clamp(transitionDebug.brushRadius, 1, 8),+ brushStrength: clamp(transitionDebug.brushStrength, 4, 32),brushActive: brushCanWrite,- decayRate: clampRange(transitionDebug.paintDecayPerFrame120, 0.002, 0.08) * 120,- diffusionRate: clampRange(transitionDebug.diffusionAmount, 0, 24),- diffusionJitter: clampRange(transitionDebug.diffusionJitter, 0, 4),+ decayRate: clamp(transitionDebug.paintDecayPerFrame120, 0.002, 0.08) * 120,+ diffusionRate: clamp(transitionDebug.diffusionAmount, 0, 24),+ diffusionJitter: clamp(transitionDebug.diffusionJitter, 0, 4),},},);@@ -176,31 +240,47 @@ export function createDrawLoop({finishCanvasFade = onCanvasFullyOpaque(canvas, onCanvasRevealed);}- state.animationFrame = requestAnimationFrame(draw);+ if (frameLoopProbe) {+ frameLoopProbe.frames += 1;+ frameLoopProbe.lastFrameAt = frameTime;+ updateFrameLoopProbeDataset();+ }+ };++ const start = () => {+ if (running) return;+ running = true;+ if (frameLoopProbe) {+ frameLoopProbe.running = true;+ updateFrameLoopProbeDataset(true);+ }+ const frameTime = performance.now();+ state.previousFrameTime = frameTime;+ if (evePointerInteractionMode(state.isCoarsePointer).autoRotateEnvYaw) {+ state.autoRotateStartTime = frameTime;+ }+ };++ const stop = () => {+ running = false;+ state.animationFrame = 0;+ if (frameLoopProbe) {+ frameLoopProbe.running = false;+ updateFrameLoopProbeDataset(true);+ }};return {- draw,+ start,+ stop,+ step: draw,dispose() {- cancelAnimationFrame(state.animationFrame);+ stop();finishCanvasFade?.();},};}-function safeLerp(from: number, to: number, amount: number) {- const safeAmount = Math.max(0, Math.min(1, amount));- return from + (to - from) * safeAmount;-}--function clampUnit(value: number) {- return clampRange(value, 0, 1);-}--function clampRange(value: number, min: number, max: number) {- return Math.max(min, Math.min(max, value));-}-function stepLogoModeProgress(current: number,target: number,@@ -208,17 +288,12 @@ function stepLogoModeProgress(durationSeconds: number,) {const safeTarget = target >= 0.5 ? 1 : 0;- const safeDuration = clampRange(durationSeconds, 0.05, 2);+ const safeDuration = clamp(durationSeconds, 0.05, 2);const step = Math.max(0, deltaSeconds) / safeDuration;if (Math.abs(safeTarget - current) <= step) return safeTarget;return current + Math.sign(safeTarget - current) * step;}-function easeLogoModeProgress(progress: number) {- const t = Math.max(0, Math.min(1, progress));- return t * t * (3 - 2 * t);-}-function onCanvasFullyOpaque(canvas: HTMLCanvasElement, callback: () => void) {let done = false;let timeout = 0;diff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/load-mesh.ts b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/load-mesh.tsindex ae2210b9f..a07180efe 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/load-mesh.ts+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/load-mesh.ts@@ -1,13 +1,19 @@import { decodeGltfMesh } from "../mesh";// Owns browser glTF fetch/decode for the Eve logo mesh.-// INVARIANT: no-store fetch behavior is preserved for HMR/content updates.+// INVARIANT: dev no-store fetch behavior is preserved for HMR/content updates.// Imported only by index.tsx startup.export const MODEL_URL = "/eve-5/eve-logo.gltf";+const DEV_FETCH_OPTIONS = { cache: "no-store" } as const;++function meshFetchOptions() {+ return process.env.NODE_ENV === "production" ? undefined : DEV_FETCH_OPTIONS;+}+export async function loadMesh() {- const response = await fetch(MODEL_URL, { cache: "no-store" });+ const response = await fetch(MODEL_URL, meshFetchOptions());if (!response.ok) throw new Error(`Failed to load ${MODEL_URL}: ${response.status}`);return decodeGltfMesh(await response.json(), (uri) => loadGltfBuffer(uri, MODEL_URL));}@@ -17,7 +23,7 @@ async function loadGltfBuffer(uri: string, modelUrl: string) {return Uint8Array.from(atob(uri.split(",")[1]!), (char) => char.charCodeAt(0)).buffer;}const url = new URL(uri, window.location.origin + modelUrl);- const response = await fetch(url, { cache: "no-store" });+ const response = await fetch(url, meshFetchOptions());if (!response.ok)throw new Error(`Failed to load glTF buffer ${url.pathname}: ${response.status}`);return response.arrayBuffer();diff --git a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/pointer-input.ts b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/pointer-input.tsindex 25baf9d78..c6fac09d6 100644--- a/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/pointer-input.ts+++ b/apps/docs/app/[lang]/(home)/components/eve-logo-shader/runtime/pointer-input.ts@@ -1,7 +1,11 @@import type { RefObject } from "react";import { evePointerInteractionMode } from "../mobile-motion";import { bloomRadiusForDevicePixelRatio, mapClientPointToPaintCell } from "../render";-import { getBrowserDevicePixelRatio } from "./canvas-sizing";+import {+ getBrowserDevicePixelRatio,+ type CanvasLayoutRef,+ type DevicePixelRatioRef,+} from "./canvas-sizing";import type { ControlsRef, HeroRuntimeState } from "./state";// Owns browser pointer input for env yaw and paint brush updates.@@ -12,25 +16,59 @@ const MAX_ENV_YAW = 0.3;const MAX_ENV_PITCH = 0.2;const PAINT_POINTER_MOVE_EPSILON_PX = 0.5;+export function syncPointerInteractionMode(state: HeroRuntimeState, isCoarsePointer: boolean) {+ state.isCoarsePointer = isCoarsePointer;+ if (evePointerInteractionMode(state.isCoarsePointer).autoRotateEnvYaw) {+ state.targetBrushActive = false;+ state.targetMouseEnvPitch = 0;+ state.targetAsciiMouseX = 0;+ state.targetAsciiMouseY = 0;+ state.autoRotateStartTime = performance.now();+ }+}+export function createPointerController({state,controlsRef,canvasRef,+ coarsePointerRef,+ canvasLayoutRef,+ devicePixelRatioRef,}: {state: HeroRuntimeState;controlsRef: ControlsRef;canvasRef: RefObject<HTMLCanvasElement | null>;+ coarsePointerRef: RefObject<boolean>;+ canvasLayoutRef: CanvasLayoutRef;+ devicePixelRatioRef: DevicePixelRatioRef;}) {- const coarsePointerQuery = window.matchMedia("(pointer: coarse)");- const syncPointerInteractionMode = () => {- state.isCoarsePointer = coarsePointerQuery.matches;- if (evePointerInteractionMode(state.isCoarsePointer).autoRotateEnvYaw) {- state.targetBrushActive = false;- state.targetMouseEnvPitch = 0;- state.targetAsciiMouseX = 0;- state.targetAsciiMouseY = 0;- state.autoRotateStartTime = performance.now();+ let cachedCanvasRect: DOMRectReadOnly | undefined;+ let rectInvalidated = true;++ const getCanvasRect = () => {+ const canvas = canvasRef.current;+ if (!canvas) return undefined;+ const { width, height } = canvasLayoutRef.current;+ if (+ !cachedCanvasRect ||+ rectInvalidated ||+ cachedCanvasRect.width !== width ||+ cachedCanvasRect.height !== height+ ) {+ const rect = canvas.getBoundingClientRect();+ cachedCanvasRect = new DOMRectReadOnly(+ rect.left,+ rect.top,+ width || rect.width,+ height || rect.height,+ );+ rectInvalidated = false;}+ return cachedCanvasRect;+ };++ const invalidateCanvasRect = () => {+ rectInvalidated = true;};const updateEnvRotation = (clientX: number, clientY: number) => {@@ -68,14 +106,19 @@ export function createPointerController({deactivateBrush();return;}- const devicePixelRatio = getBrowserDevicePixelRatio();+ const rect = getCanvasRect();+ if (!rect) {+ deactivateBrush();+ return;+ }+ const devicePixelRatio = getBrowserDevicePixelRatio(devicePixelRatioRef.current);const paddingRadius = bloomRadiusForDevicePixelRatio(devicePixelRatio);const logicalWidth = Math.max(1, canvas.width - paddingRadius * 2);const logicalHeight = Math.max(1, canvas.height - paddingRadius * 2);const mapping = mapClientPointToPaintCell({clientX: event.clientX,clientY: event.clientY,- rect: canvas.getBoundingClientRect(),+ rect,canvasWidth: canvas.width,canvasHeight: canvas.height,logicalWidth,@@ -115,18 +158,21 @@ export function createPointerController({updatePaintBrush(event);};- syncPointerInteractionMode();- coarsePointerQuery.addEventListener("change", syncPointerInteractionMode);+ syncPointerInteractionMode(state, coarsePointerRef.current);window.addEventListener("pointermove", onPointerMove, { passive: true });+ window.addEventListener("scroll", invalidateCanvasRect, { passive: true });+ window.addEventListener("resize", invalidateCanvasRect, { passive: true });window.addEventListener("pointerout", deactivateBrush, { passive: true });window.addEventListener("blur", deactivateBrush);return {+ invalidateCanvasRect,detach() {window.removeEventListener("pointermove", onPointerMove);+ window.removeEventListener("scroll", invalidateCanvasRect);+ window.removeEventListener("resize", invalidateCanvasRect);window.removeEventListener("pointerout", deactivateBrush);window.removeEventListener("blur", deactivateBrush);- coarsePointerQuery.removeEventListener("change", syncPointerInteractionMode);},};}diff --git a/apps/docs/package.json b/apps/docs/package.jsonindex 05f456a3b..facaec3c4 100644--- a/apps/docs/package.json+++ b/apps/docs/package.json@@ -44,6 +44,7 @@"nanoid": "5.1.11","next": "catalog:","next-themes": "0.4.6",+ "phase": "catalog:","radix-ui": "1.4.3","react": "catalog:","react-dom": "catalog:",diff --git a/apps/docs/scripts/eve-render/paint-fixtures.ts b/apps/docs/scripts/eve-render/paint-fixtures.tsindex d3098b5e2..2ca633eac 100644--- a/apps/docs/scripts/eve-render/paint-fixtures.ts+++ b/apps/docs/scripts/eve-render/paint-fixtures.ts@@ -1,5 +1,5 @@import {- imprintCellSizeForDevicePixelRatio,+ imprintGridSizeForLogicalSize,type PaintRenderOptions,type PaintSeed,} from "../../app/[lang]/(home)/components/eve-logo-shader/render";@@ -20,9 +20,11 @@ export function paintRequested() {export function buildPaintSeed(config: RenderConfig): PaintSeed | undefined {if (!paintRequested()) return undefined;- const cellSize = imprintCellSizeForDevicePixelRatio(config.dpr);- const width = Math.max(1, Math.ceil(config.logicalWidth / cellSize));- const height = Math.max(1, Math.ceil(config.logicalHeight / cellSize));+ const { cols: width, rows: height } = imprintGridSizeForLogicalSize(+ config.logicalWidth,+ config.logicalHeight,+ config.imprintGridScaleMultiplier,+ );const values = new Float32Array(width * height);const pattern = process.env.EVE_LOGO_PAINT_PATTERN;if (pattern) {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e71a2aa66..143d6886a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -48,6 +48,9 @@ catalogs:next:specifier: 16.2.6version: 16.2.6+ phase:+ specifier: 0.0.1+ version: 0.0.1picocolors:specifier: 1.1.1version: 1.1.1@@ -209,6 +212,9 @@ importers:next-themes:specifier: 0.4.6+ phase:+ specifier: 'catalog:'+ version: 0.0.1([email protected])radix-ui:specifier: 1.4.3version: 1.4.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])@@ -10998,6 +11004,15 @@ packages:resolution: {integrity: sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==}+ resolution: {integrity: sha512-QTeTClFj700SPwdgfVckQ8uO/dquPO5MdxHpSLCOtKpJbLrpUrFnEVhoCuQKXMSWXNIMlnwPsKQ7fqfXCX6BJg==}+ engines: {node: 24.x}+ peerDependencies:+ react: '>=18'+ peerDependenciesMeta:+ react:+ optional: true+resolution: {integrity: sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==}@@ -24393,6 +24408,10 @@ snapshots:+ optionalDependencies:+ react: 19.2.6+diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 89521aecc..1a87503f7 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -11,6 +11,7 @@ allowBuilds:cbor-extract: trueesbuild: truenode-liblzma: false+ phase: falseprotobufjs: truesharp: truesimple-git-hooks: true@@ -33,6 +34,7 @@ catalog:"@vercel/sandbox": "2.3.0"ai: "^7.0.0"next: "16.2.6"+ phase: "0.0.1"picocolors: "1.1.1"react: "19.2.6"react-dom: "19.2.6"@@ -61,3 +63,4 @@ minimumReleaseAgeExclude:- typescript- vercel- workflowdiff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjsindex e45a875cf..8bdd7851d 100644--- a/scripts/guard-invariants.mjs+++ b/scripts/guard-invariants.mjs@@ -81,6 +81,7 @@* must go through the `src/internal/workflow/runtime.ts` facade and* `queue-namespace.ts`. The generated agent bootstrap installs the* agent-scoped namespace before queue-producing APIs can run.+ * rule 34 — `phase` stays a runtime-only dependency. No file under the Eve\n * logo renderer's GPU/runtime boundary (render/, shaders/, or the\n * offline render harness) may import the `phase` package. This keeps\n * the mechanical separation between the lifecycle layer and the GPU\n * renderer enforceable.** Baselines for rules with pre-existing violations live in* `guard-invariants-baseline.json`. Counts and allowlists in that file@@ -798,6 +799,54 @@ async function checkRule32ResearchFrontmatter() {return violations;}+// ---------- Rule 34: no `phase` imports under GPU/shader boundaries ----------++const PHASE_BOUNDARY_DIRS = [+ "apps/docs/app/[lang]/(home)/components/eve-logo-shader/render",+ "apps/docs/app/[lang]/(home)/components/eve-logo-shader/shaders",+ "apps/docs/scripts/eve-render",+];+const PHASE_IMPORT_RE =+ /(from\s+|import\s+)(?:type\s+)?['"]phase(?:\/[^'"]*)?['"]|require\(\s*['"]phase(?:\/[^'")]*)?['"]\s*\)|import\(\s*['"]phase(?:\/[^'")]*)?['"]\s*\)/;++/**+ * @returns {Promise<Violation[]>}+ */+async function checkRule34PhaseBoundary() {+ /** @type {Violation[]} */+ const violations = [];+ for (const relDir of PHASE_BOUNDARY_DIRS) {+ const absDir = join(REPO_ROOT, relDir);+ let stats;+ try {+ stats = await lstat(absDir);+ } catch (error) {+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {+ continue;+ }+ throw error;+ }+ if (!stats.isDirectory()) continue;+ for await (const entry of walkFiles(absDir)) {+ if (!entry.stat.isFile()) continue;+ const content = await readFile(entry.absPath, "utf8");+ const match = content.match(PHASE_IMPORT_RE);+ if (!match) continue;+ const before = content.slice(0, match.index ?? 0);+ const line = before.split(/\r?\n/).length;+ violations.push({+ rule: 34,+ file: entry.relPath,+ line,+ message:+ "imports the `phase` package inside the GPU/shader boundary. Phase must stay in the lifecycle/runtime layer — add lifecycle hooks above render/ and keep render/, shaders/, and scripts/eve-render/ free of `phase` imports.",+ });+ }+ }+ return violations;+}++/*** @returns {Promise<Set<string>>}*/@@ -1060,6 +1109,9 @@ async function main() {// Rule 33violations.push(...state.rule33);+ // Rule 34+ violations.push(...(await checkRule34PhaseBoundary()));+if (violations.length === 0) {process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");return;