From 7882d0c315348f8fd98916c6be068c2291da8aa2 Mon Sep 17 00:00:00 2001 From: Vincent Naples Date: Tue, 6 Oct 2026 18:42:12 -0500 Subject: [PATCH 1/5] VN33: a Mesh File In inside a component is sized through its instance The mesh loader wrote a file's measured facts (vertices, triangles, parts, joints, clips, clipFrames, frameOrigin, bounds) onto the node it found with getGraph().nodes[nodeId]. An inner node's id is flattened (instance/inner), the document does not hold it, so the write never happened and the node compiled as the one-vertex stand-in: it drew nothing. The facts now land as that instance's overrides of the inner node (state.componentOverrides, keyed internalParameterPath), which flattening already applies over the definition. Each instance keeps its own size, two instances can load different files, and the shared definition is untouched. - setParameters gains an optional internalNodeId, on the precedent of setNodeChannelMask's: one op through the bus, so undo, audit and the revision check come with it. A non-instance and a nested path are refused by name (parameter.internal.notComponent / .nested). - "Already sized" reads the flattened node (definition plus overrides). - Ids are split and joined through domain/components/addressing.ts (enteredThrough, toInstance), per T1695b's gate. - One level only: an override key is /, so a mesh inside a nested component is refused as mesh.unsizable. mesh.component is retired. Tests: the literal bug on Dawn (the app's loader hook sizes two instances of one component loading different files, and each Geometry renders only its own instance's mesh); undo of the measure; the definition untouched; the nested refusal. Red-verified against the old lookup. Co-Authored-By: Claude Opus 5.5 --- src/app/use-mesh-sources.test.tsx | 125 +++++++++++++ src/app/use-mesh-sources.ts | 164 +++++++++++------- src/domain/commands/apply-patch.ts | 28 ++- src/domain/diagnostics/class-reasons.ts | 4 +- src/domain/diagnostics/classes.ts | 4 +- src/domain/types/patch.ts | 10 +- src/domain/types/schemas.ts | 5 +- src/editor/agent/describe-operation.ts | 3 +- .../headless/mesh-in-component.gpu.test.ts | 154 ++++++++++++++++ 9 files changed, 428 insertions(+), 69 deletions(-) create mode 100644 src/tests/headless/mesh-in-component.gpu.test.ts diff --git a/src/app/use-mesh-sources.test.tsx b/src/app/use-mesh-sources.test.tsx index 1098310ad..da81fa2a6 100644 --- a/src/app/use-mesh-sources.test.tsx +++ b/src/app/use-mesh-sources.test.tsx @@ -1,5 +1,6 @@ // @vitest-environment jsdom import { cleanup, renderHook, waitFor } from "@testing-library/react"; +import { useSyncExternalStore } from "react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { cubePrimitive, encodeFixtureGlb } from "@domain/mesh/glb.fixture.ts"; import { createFileReference } from "@domain/media/file-reference.ts"; @@ -126,3 +127,127 @@ describe("mesh file source bindings", () => { } finally { runtime.dispose(); } }); }); + +/* + * VN33 — the literal bug: a Mesh File In inside a component drew nothing. The loader found + * the node by `getGraph().nodes[nodeId]`, an inner node's id is flattened (`instance/inner`) + * and the document does not hold it, so the facts were never written and the node stayed + * the one-vertex stand-in. They are now that INSTANCE's overrides: each instance carries the + * size of the file it loads, and the shared definition is not touched. + */ +describe("VN33: a mesh inside a component", () => { + const one = encodeFixtureGlb({ nodes: [{ name: "a", mesh: [cubePrimitive()] }] }); + const two = encodeFixtureGlb({ nodes: [{ name: "a", mesh: [cubePrimitive()] }, { name: "b", translation: [3, 0, 0], mesh: [cubePrimitive()] }] }); + const factsOf = (bytes: Uint8Array) => { + const prepared = prepareMesh(bytes, ""); + if (prepared === null) throw new Error("fixture must contain a mesh"); + return prepared.facts; + }; + + async function fixture(nested = false) { + const runtime = createAppRuntime({ identityStorage: null }); + const { bus, invocation } = runtime; + const added = await bus.execute("graph.applyPatch", { baseRevision: 0, operations: [ + { op: "addNode", ref: "$mesh", type: "meshFileIn", position: { x: 0, y: 0 }, parameters: { file: "media/one.glb" } }, + { op: "addNode", ref: "$geo", type: "geometry", position: { x: 200, y: 0 } }, + { op: "connect", source: { nodeId: "$mesh", portId: "out" }, target: { nodeId: "$geo", portId: "points" } }, + ] }, invocation); + expect(added.status).toBe("applied"); + const meshId = added.output.createdIds["$mesh"]!; + let saved = await bus.execute("component.saveSelection", { nodeIds: [meshId], name: "Stage" }, invocation); + expect(saved.status).toBe("applied"); + if (nested) { + saved = await bus.execute("component.saveSelection", { nodeIds: [saved.output.instanceNodeId!], name: "Venue" }, invocation); + expect(saved.status).toBe("applied"); + } + const second = await bus.execute("component.instantiate", { componentId: saved.output.componentId! }, invocation); + expect(second.status).toBe("applied"); + return { runtime, meshId, componentId: saved.output.componentId!, first: saved.output.instanceNodeId!, second: second.output.nodeId! }; + } + + const serve = (files: Record) => + vi.stubGlobal("fetch", vi.fn(async (url: string) => new Response(new Uint8Array(files[url]!)))); + const useFlatGraph = (runtime: ReturnType) => + useSyncExternalStore(runtime.bus.store.subscribe, () => runtime.flattened.current().graph); + + it("sizes each instance for the file IT loads, through the bus, and leaves the definition alone", async () => { + const { runtime, meshId, componentId, first, second } = await fixture(); + try { + // The second instance loads another file: its own override, beside the size. + const routed = await runtime.bus.execute("graph.applyPatch", { baseRevision: runtime.bus.store.getRevision(), operations: [ + { op: "setParameters", nodeId: second, internalNodeId: meshId, parameters: { file: "media/two.glb" } }, + ] }, runtime.invocation); + expect(routed.status).toBe("applied"); + serve({ "media/one.glb": one, "media/two.glb": two }); + const definitionBefore = JSON.stringify(runtime.components.latest(componentId)); + // What is registered NOW: the effect re-runs after each write and releases what it fed. + const live = new Map(); + const registerMediaSource = vi.fn((id, source) => { + live.set(id, source.currentFrame()!.bytes as Uint8Array); + return () => live.delete(id); + }); + const backend = { registerMediaSource } as unknown as LoomBackend; + const stateOf = () => [first, second].map(id => JSON.stringify(runtime.bus.store.getGraph().nodes[id]!.state ?? {})); + const before = stateOf(); + + const hook = renderHook(() => useMeshSources(runtime, backend, useFlatGraph(runtime))); + const ids = [meshSourceIdsFor(`${first}/${meshId}`), meshSourceIdsFor(`${second}/${meshId}`)]; + await waitFor(() => expect([...live.keys()].sort()).toEqual([ids[0]!.points, ids[0]!.indices, ids[1]!.points, ids[1]!.indices].sort())); + expect(hook.result.current.diagnostics).toEqual([]); + // Each instance is fed ITS file's bytes. + expect(live.get(ids[0]!.points)).toEqual(prepareMesh(one, "")!.points); + expect(live.get(ids[1]!.points)).toEqual(prepareMesh(two, "")!.points); + + const flat = runtime.flattened.current().graph.nodes; + for (const [instance, facts] of [[first, factsOf(one)], [second, factsOf(two)]] as const) { + expect(flat[`${instance}/${meshId}`]!.parameters).toMatchObject({ vertices: facts.vertices, triangles: facts.triangles, parts: facts.parts, bounds: facts.bounds }); + } + expect(factsOf(two).vertices).not.toBe(factsOf(one).vertices); + // Nothing was written into the shared definition. + expect(JSON.stringify(runtime.components.latest(componentId))).toBe(definitionBefore); + hook.unmount(); + + // One measure is one undo step: two undos restore both instances exactly as they were. + const measured = stateOf(); + expect(measured.filter((state, index) => state !== before[index])).toHaveLength(2); + expect((await runtime.bus.execute("graph.undo", {}, runtime.invocation)).status).toBe("applied"); + expect(stateOf().filter((state, index) => state === before[index])).toHaveLength(1); + expect((await runtime.bus.execute("graph.undo", {}, runtime.invocation)).status).toBe("applied"); + expect(stateOf()).toEqual(before); + expect(runtime.flattened.current().graph.nodes[`${second}/${meshId}`]!.parameters["file"]).toBe("media/two.glb"); + } finally { runtime.dispose(); } + }); + + it("the op refuses a node that is not an instance, and a nested path, by name", async () => { + const { runtime, meshId, first } = await fixture(); + try { + const geo = Object.values(runtime.bus.store.getGraph().nodes).find(node => node.type === "geometry")!.id; + const send = (nodeId: string, internalNodeId: string) => runtime.bus.execute("graph.applyPatch", { baseRevision: runtime.bus.store.getRevision(), operations: [ + { op: "setParameters", nodeId, internalNodeId, parameters: { vertices: 8 } }, + ] }, runtime.invocation); + const plain = await send(geo, meshId); + expect(plain.status).toBe("rejected"); + expect(plain.diagnostics.map(d => d.code)).toEqual(["parameter.internal.notComponent"]); + const nested = await send(first, `${meshId}/${meshId}`); + expect(nested.status).toBe("rejected"); + expect(nested.diagnostics.map(d => d.code)).toEqual(["parameter.internal.nested"]); + } finally { runtime.dispose(); } + }); + + it("refuses a mesh inside a NESTED component by name, and feeds nothing", async () => { + const { runtime } = await fixture(true); + try { + serve({ "media/one.glb": one }); + const registerMediaSource = vi.fn(() => () => {}); + const backend = { registerMediaSource } as unknown as LoomBackend; + const revision = runtime.bus.store.getRevision(); + const hook = renderHook(() => useMeshSources(runtime, backend, useFlatGraph(runtime))); + await waitFor(() => expect(hook.result.current.diagnostics).toHaveLength(2)); + expect(hook.result.current.diagnostics.map(d => d.code)).toEqual(["mesh.unsizable", "mesh.unsizable"]); + expect(hook.result.current.diagnostics[0]!.message).toContain("nested component"); + expect(registerMediaSource).not.toHaveBeenCalled(); + expect(runtime.bus.store.getRevision()).toBe(revision); + hook.unmount(); + } finally { runtime.dispose(); } + }); +}); diff --git a/src/app/use-mesh-sources.ts b/src/app/use-mesh-sources.ts index 0e2e7edad..30964a064 100644 --- a/src/app/use-mesh-sources.ts +++ b/src/app/use-mesh-sources.ts @@ -1,6 +1,9 @@ import { useEffect, useRef, useState } from "react"; import type { RuntimeDiagnostic } from "@domain/types/diagnostics.ts"; -import type { GraphDocument } from "@domain/types/graph.ts"; +import type { GraphDocument, GraphNode } from "@domain/types/graph.ts"; +import type { ParameterValue } from "@domain/types/parameters.ts"; +import { isComponentInstance } from "@domain/components/instance.ts"; +import { enteredThrough } from "@domain/components/addressing.ts"; import type { NodeId } from "@domain/types/ids.ts"; import { GlbDecodeError, type MeshFrame } from "@domain/mesh/glb.ts"; import { storedStaticValue } from "@domain/parameters/slots.ts"; @@ -20,9 +23,10 @@ import type { AppRuntime } from "./app-runtime.ts"; * the file's size; the sources are already registered by then and the upload lands on the * first frame of the new plan. * - * A file that will not decode, a selection that matches nothing, or a mesh node inside a - * component (whose facts live on a node this document does not hold) registers nothing - * and says why here; the node keeps publishing its degenerate stand-in and draws nothing. + * A mesh node inside a component is sized through its instance (VN33, `factsTarget`). A + * file that will not decode, a selection that matches nothing, or a mesh inside a NESTED + * component registers nothing and says why here; the node keeps publishing its degenerate + * stand-in and draws nothing. * * HONEST LIMIT: the decode runs on the main thread. A 100 MB export takes on the order of * a second, once per file and selection; moving it to a worker is the follow-up if a @@ -83,6 +87,94 @@ function meshRequests(graph: GraphDocument): MeshRequest[] { return requests.sort((a, b) => (a.nodeId < b.nodeId ? -1 : a.nodeId > b.nodeId ? 1 : 0)); } +/** + * VN33 — WHERE a mesh node's measured facts are read and written. A node at the root holds + * them itself. A node inside a component is a flattened id (`instance/inner`) the document + * does not hold: its facts are that INSTANCE's overrides of `inner` (`setParameters` with + * `internalNodeId`), so each instance carries the size of the file IT loads and the shared + * definition is not touched. "Already sized" then reads the flattened node, the definition + * with the overrides applied, because that is what the compile sizes the node by. + * + * One level: an override key is `/`, so a node inside a NESTED instance + * (`a/b/inner`) is refused by name, and the mesh keeps drawing nothing there. + */ +function factsTarget( + root: GraphDocument, + flat: GraphDocument, + nodeId: NodeId, +): { readonly nodeId: NodeId; readonly internalNodeId?: string; readonly parameters: GraphNode["parameters"] } | { readonly refused: string } { + const own = root.nodes[nodeId]; + if (own !== undefined) return { nodeId, parameters: own.parameters }; + const entered = enteredThrough(nodeId); + const instance = entered === undefined ? undefined : root.nodes[entered.instance]; + const flattened = flat.nodes[nodeId]; + if (entered === undefined || instance === undefined || flattened === undefined || !isComponentInstance(instance)) { + return { refused: "the document holds no node or component instance by that id, so its facts have nowhere to go" }; + } + if (enteredThrough(entered.rest) !== undefined) { + return { refused: "it sits inside a nested component, and an instance's overrides reach its own internal nodes only; set its Vertices/Triangles on the nested component's node" }; + } + return { nodeId: instance.id, internalNodeId: entered.rest, parameters: flattened.parameters }; +} + +interface MeshMeasure { + /** True when the node is already sized for the file: its buffers may be fed. */ + readonly sized: boolean; + /** Why the node cannot be sized from here (VN33: a nested component). */ + readonly refused?: string; +} + +/** + * The loader's measure step. Answers whether the node is already sized for this file; + * otherwise writes the facts through the bus (the write changes `sized`, which re-runs the + * hook's effect) and answers false: registering now would offer the stand-in's one-vertex + * buffer a whole file's bytes. + */ +function measureMesh( + runtime: Pick, + nodeId: NodeId, + facts: PreparedMesh["facts"], +): MeshMeasure { + const bus = runtime.bus; + const target = factsTarget(bus.store.getGraph(), runtime.flattened.current().graph, nodeId); + if ("refused" in target) return { sized: false, refused: target.refused }; + const write = (parameters: Record): void => + void bus.execute( + "graph.applyPatch", + { + baseRevision: bus.store.getRevision(), + label: "Measure mesh", + operations: [{ op: "setParameters", nodeId: target.nodeId, parameters, ...(target.internalNodeId === undefined ? {} : { internalNodeId: target.internalNodeId }) }], + }, + runtime.invocation, + ); + const parameters = target.parameters; + // An unskinned node may never have stored Joints at all: absent reads as the empty table. + const joints = typeof parameters["joints"] === "string" ? parameters["joints"] : ""; + // T1410b: absent clip facts read as the no-clip file's ("" and 0). + const clips = typeof parameters["clips"] === "string" ? parameters["clips"] : ""; + const clipFrames = typeof parameters["clipFrames"] === "number" ? parameters["clipFrames"] : 0; + // T1581b: absent reads as the world frame's (empty). + const frameOrigin = typeof parameters["frameOrigin"] === "string" ? parameters["frameOrigin"] : ""; + if ( + parameters["vertices"] === facts.vertices && + parameters["triangles"] === facts.triangles && + parameters["parts"] === facts.parts && + joints === facts.joints && + clips === facts.clips && + clipFrames === facts.clipFrames && + frameOrigin === facts.frameOrigin + ) { + /* T1598b: Bounds sizes NOTHING, so it is not part of "sized for this file": a document + saved before it existed still feeds. It is written beside the facts, and on its own + when it is all that is missing. */ + if (parameters["bounds"] !== facts.bounds) write({ bounds: facts.bounds }); + return { sized: true }; + } + write({ vertices: facts.vertices, triangles: facts.triangles, parts: facts.parts, joints: facts.joints, clips: facts.clips, clipFrames: facts.clipFrames, frameOrigin: facts.frameOrigin, bounds: facts.bounds }); + return { sized: false }; +} + export function useMeshSources(runtime: AppRuntime, backend: LoomBackend | null, graph: GraphDocument): MeshWiring { const [diagnostics, setDiagnostics] = useState(NO_DIAGNOSTICS); const runtimeRef = useRef(runtime); @@ -125,64 +217,6 @@ export function useMeshSources(runtime: AppRuntime, backend: LoomBackend | null, return loading; }; - /** - * True when the node is already sized for this file. Otherwise writes the facts (the - * write changes `sized`, which re-runs this effect) and answers false: registering - * now would offer the stand-in's one-vertex buffer a whole file's bytes. - */ - const sizedFor = (nodeId: NodeId, facts: PreparedMesh["facts"]): boolean => { - const bus = runtimeRef.current.bus; - const stored = bus.store.getGraph().nodes[nodeId]; - if (stored === undefined) { - found.push({ - severity: "warning", - code: "mesh.component", - message: `Mesh "${nodeId}" sits inside a component; its Vertices/Triangles must be set on the component's own node (${facts.vertices} / ${facts.triangles}).`, - nodeId, - }); - return false; - } - const parameters = stored.parameters; - // An unskinned node may never have stored Joints at all: absent reads as the empty table. - const joints = typeof parameters["joints"] === "string" ? parameters["joints"] : ""; - // T1410b: absent clip facts read as the no-clip file's ("" and 0). - const clips = typeof parameters["clips"] === "string" ? parameters["clips"] : ""; - const clipFrames = typeof parameters["clipFrames"] === "number" ? parameters["clipFrames"] : 0; - // T1581b: absent reads as the world frame's (empty). - const frameOrigin = typeof parameters["frameOrigin"] === "string" ? parameters["frameOrigin"] : ""; - if ( - parameters["vertices"] === facts.vertices && - parameters["triangles"] === facts.triangles && - parameters["parts"] === facts.parts && - joints === facts.joints && - clips === facts.clips && - clipFrames === facts.clipFrames && - frameOrigin === facts.frameOrigin - ) { - /* T1598b: Bounds sizes NOTHING, so it is not part of "sized for this file": a - document saved before it existed, or a mesh inside a component, still feeds. - It is written beside the facts, and on its own when it is all that is missing. */ - if (parameters["bounds"] !== facts.bounds) { - void bus.execute( - "graph.applyPatch", - { baseRevision: bus.store.getRevision(), label: "Measure mesh", operations: [{ op: "setParameters", nodeId, parameters: { bounds: facts.bounds } }] }, - runtimeRef.current.invocation, - ); - } - return true; - } - void bus.execute( - "graph.applyPatch", - { - baseRevision: bus.store.getRevision(), - label: "Measure mesh", - operations: [{ op: "setParameters", nodeId, parameters: { vertices: facts.vertices, triangles: facts.triangles, parts: facts.parts, joints: facts.joints, clips: facts.clips, clipFrames: facts.clipFrames, frameOrigin: facts.frameOrigin, bounds: facts.bounds } }], - }, - runtimeRef.current.invocation, - ); - return false; - }; - void (async () => { for (const request of requests) { const preparedKey = `${request.file}|${request.select}|${request.clip}@${request.clipRate}|${request.lamps}|${request.frame}`; @@ -213,7 +247,11 @@ export function useMeshSources(runtime: AppRuntime, backend: LoomBackend | null, for (const warning of prepared.mesh.warnings) { found.push({ severity: "info", code: "mesh.note", message: `Mesh "${request.nodeId}": ${warning}`, nodeId: request.nodeId }); } - if (!sizedFor(request.nodeId, prepared.facts)) continue; + const measured = measureMesh(runtimeRef.current, request.nodeId, prepared.facts); + if (measured.refused !== undefined) { + found.push({ severity: "warning", code: "mesh.unsizable", message: `Mesh "${request.nodeId}": ${measured.refused} (${prepared.facts.vertices} / ${prepared.facts.triangles}).`, nodeId: request.nodeId }); + } + if (!measured.sized) continue; const ids = meshSourceIdsFor(request.nodeId); const points = prepared.points; const indices = prepared.indices; diff --git a/src/domain/commands/apply-patch.ts b/src/domain/commands/apply-patch.ts index 2a3ca512c..20808256a 100644 --- a/src/domain/commands/apply-patch.ts +++ b/src/domain/commands/apply-patch.ts @@ -5,7 +5,8 @@ import type { RuntimeDiagnostic } from "../types/diagnostics.ts"; import type { EdgeId, GroupId, NodeId, PortId } from "../types/ids.ts"; import { isDefaultChannelMask, MIN_NODE_SIZE } from "../types/graph.ts"; import { supportsChannelMask } from "../graph/channel-mask.ts"; -import { isComponentInstance } from "../components/instance.ts"; +import { COMPONENT_OVERRIDES_STATE_KEY, internalParameterPath, isComponentInstance, readComponentInstance } from "../components/instance.ts"; +import { enteredThrough } from "../components/addressing.ts"; import { INTERNAL_CHANNEL_MASKS_KEY, internalChannelMasks } from "../components/internal-channel-masks.ts"; import type { GraphDocument, GraphEdge, GraphNode } from "../types/graph.ts"; import type { StoredParameter } from "../types/parameters.ts"; @@ -693,6 +694,31 @@ function executeOperation( case "setParameters": { const node = requireNode(operation.nodeId); + if (operation.internalNodeId !== undefined) { + // VN33: the instance's own override of one internal node (see the op's type). The + // definition is not in this context, so the values are not schema-checked here: + // flattening writes each onto the internal node, and the compile's parameter checks + // read it there like any other stored value. + if (!isComponentInstance(node)) { + fail("parameter.internal.notComponent", `node "${node.id}" is not a component instance, so it has no internal node "${operation.internalNodeId}".`, { nodeId: node.id }); + } + const nested = enteredThrough(operation.internalNodeId); + if (nested !== undefined) { + fail("parameter.internal.nested", `"${operation.internalNodeId}" is inside a nested component of "${node.id}"; an instance's parameter overrides reach its own internal nodes only.`, { + nodeId: node.id, + suggestion: `Write the override on the nested instance "${nested.instance}" inside the component's definition.`, + }); + } + const overrides: Record = { ...readComponentInstance(node)?.overrides }; + for (const [key, value] of Object.entries(operation.parameters)) { + const path = internalParameterPath(operation.internalNodeId, key); + const existing = overrides[path]; + // §V108: the same rule as a node's own parameters, below. + overrides[path] = isParameterSlot(existing) && !isParameterSlot(value) ? withBinding(existing, { kind: "static", value: value as ParameterValue }) : value; + } + node.state = { ...node.state, [COMPONENT_OVERRIDES_STATE_KEY]: overrides }; + return; + } const definition = registry.get(node.type); if (definition === undefined) { fail( diff --git a/src/domain/diagnostics/class-reasons.ts b/src/domain/diagnostics/class-reasons.ts index ed7c793d4..c2a2d9218 100644 --- a/src/domain/diagnostics/class-reasons.ts +++ b/src/domain/diagnostics/class-reasons.ts @@ -319,11 +319,11 @@ export const DIAGNOSTIC_CLASS_REASONS: Readonly> = { "media.playback": "this session's device, helper or file", "media.screenCapture": "this session's device, helper or file", "media.unavailable": "this session's device, helper or file", - "mesh.component": "this session's device, helper or file", "mesh.decode": "this session's device, helper or file", "mesh.empty": "this session's device, helper or file", "mesh.note": "this session's device, helper or file", "mesh.read": "this session's device, helper or file", + "mesh.unsizable": "a mesh inside a nested component: this build sizes a mesh one component level down", "native.input": "this session's device, helper or file", "native.output": "this session's device, helper or file", "node.ambiguous": "the patch operation's input", @@ -452,6 +452,8 @@ export const DIAGNOSTIC_CLASS_REASONS: Readonly> = { "parameter.expression.syntax": "an expression that does not parse: a token, a function the grammar lacks, an argument count", "parameter.expression.type": "an expression on a parameter type that takes none", "parameter.expression.value": "arithmetic with no finite answer at this frame: the stored value stands in", + "parameter.internal.nested": "the patch operation's input", + "parameter.internal.notComponent": "the patch operation's input", "parameter.map.empty": "a map naming no attribute", "parameter.mode.payload": "a parameter command's input", "parameter.mode.retired": "a parameter command's input", diff --git a/src/domain/diagnostics/classes.ts b/src/domain/diagnostics/classes.ts index d803b34fa..db347ee95 100644 --- a/src/domain/diagnostics/classes.ts +++ b/src/domain/diagnostics/classes.ts @@ -370,11 +370,11 @@ export const DIAGNOSTIC_CLASSES: Readonly> = "media.playback": { class: "elsewhereHost" }, "media.screenCapture": { class: "elsewhereHost" }, "media.unavailable": { class: "elsewhereHost" }, - "mesh.component": { class: "elsewhereHost" }, "mesh.decode": { class: "elsewhereHost" }, "mesh.empty": { class: "elsewhereHost" }, "mesh.note": { class: "elsewhereHost" }, "mesh.read": { class: "elsewhereHost" }, + "mesh.unsizable": { class: "elsewhereBuild" }, "native.input": { class: "elsewhereHost" }, "native.output": { class: "elsewhereHost" }, "node.ambiguous": { class: "act" }, @@ -503,6 +503,8 @@ export const DIAGNOSTIC_CLASSES: Readonly> = "parameter.expression.syntax": { class: "never", local: true }, "parameter.expression.type": { class: "never", local: true }, "parameter.expression.value": { class: "degraded" }, + "parameter.internal.nested": { class: "act" }, + "parameter.internal.notComponent": { class: "act" }, "parameter.map.empty": { class: "never" }, "parameter.mode.payload": { class: "act" }, "parameter.mode.retired": { class: "act" }, diff --git a/src/domain/types/patch.ts b/src/domain/types/patch.ts index 492a335bc..c6bed0991 100644 --- a/src/domain/types/patch.ts +++ b/src/domain/types/patch.ts @@ -54,7 +54,15 @@ export type GraphPatchOperation = * order nobody asked for. */ | { op: "reorderEdges"; nodeId: NodeRef; portId: PortId; edgeIds: EdgeId[] } - | { op: "setParameters"; nodeId: NodeRef; parameters: Record } + /** + * VN33: with `internalNodeId`, `nodeId` is a component INSTANCE and the write lands in + * that instance's own overrides (`state.componentOverrides`, keyed + * `internalParameterPath(internalNodeId, key)`), which flattening applies over the + * definition. The shared definition is not touched, so two instances of one component + * carry their own values. One level only: an id inside a nested instance (`b/inner`) is + * refused by name, because an override key is `/` split at its first "/". + */ + | { op: "setParameters"; nodeId: NodeRef; parameters: Record; internalNodeId?: string } /** * §T1641b slice 2: delete stored keys the node's schema does NOT declare. * diff --git a/src/domain/types/schemas.ts b/src/domain/types/schemas.ts index 53ca1bb25..8bd9442f7 100644 --- a/src/domain/types/schemas.ts +++ b/src/domain/types/schemas.ts @@ -364,7 +364,10 @@ export const graphPatchOperationSchema = z.discriminatedUnion("op", [ edgeIds: z.array(z.string().min(1)), }) .strict(), - z.object({ op: z.literal("setParameters"), nodeId: refString, parameters: patchParameters }).strict(), + // VN33: the nested shape parses, so apply-patch can refuse it by name rather than as malformed. + z.object({ op: z.literal("setParameters"), nodeId: refString, parameters: patchParameters, + internalNodeId: z.string().regex(/^[^/]+(?:\/[^/]+)*$/).optional(), + }).strict(), z.object({ op: z.literal("removeParameters"), nodeId: refString, keys: z.array(z.string().min(1)).min(1) }).strict(), z.object({ op: z.literal("setShaderSource"), nodeId: refString, source: z.string() }).strict(), z.object({ op: z.literal("moveNodes"), positions: z.record(patchPoint) }).strict(), diff --git a/src/editor/agent/describe-operation.ts b/src/editor/agent/describe-operation.ts index b941d9ebb..db93fae94 100644 --- a/src/editor/agent/describe-operation.ts +++ b/src/editor/agent/describe-operation.ts @@ -1,4 +1,5 @@ import type { GraphPatchOperation } from "@domain/types/patch.ts"; +import { toInstance } from "@domain/components/addressing.ts"; /** * One patch operation, flattened for display (T60). @@ -41,7 +42,7 @@ export function describeOperation(operation: GraphPatchOperation): OperationRow case "setParameters": return { kind: operation.op, - targets: [operation.nodeId], + targets: [operation.internalNodeId === undefined ? operation.nodeId : toInstance([operation.nodeId], operation.internalNodeId)], detail: Object.keys(operation.parameters).sort().join(", "), }; case "removeParameters": diff --git a/src/tests/headless/mesh-in-component.gpu.test.ts b/src/tests/headless/mesh-in-component.gpu.test.ts new file mode 100644 index 000000000..3cb02d598 --- /dev/null +++ b/src/tests/headless/mesh-in-component.gpu.test.ts @@ -0,0 +1,154 @@ +// @vitest-environment jsdom +import { cleanup, renderHook, waitFor } from "@testing-library/react"; +import { useSyncExternalStore } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { createAppRuntime } from "../../app/app-runtime.ts"; +import { useMeshSources } from "../../app/use-mesh-sources.ts"; +import { cameraPayloadMatrix, transformPoint } from "../../domain/geometry/camera.ts"; +import { cubePrimitive, encodeFixtureGlb } from "../../domain/mesh/glb.fixture.ts"; +import type { GraphDocument, ProjectSettings } from "../../domain/types/graph.ts"; +import { meshSourceIdsFor } from "../../points/mesh.ts"; +import type { LoomBackend } from "../../runtime/backend/index.ts"; +import { nodeGpuHost, probeDawn } from "../../runtime/backend/vgpu/node-gpu-host.ts"; +import { renderHeadless } from "./render-harness.ts"; + +/** + * VN33 — A MESH FILE IN INSIDE A COMPONENT DREW NOTHING, through the real stack on Dawn. + * + * The loader (`useMeshSources`) measures the file and writes the facts that SIZE the node. + * It found the node with `getGraph().nodes[nodeId]`; an inner node's id is flattened + * (`instance/inner`), the document does not hold it, so the facts were never written and + * the node compiled as the one-vertex stand-in. The harness feeds a mesh by its flat id and + * refuses a node not sized for the file, so the unfixed loader fails here by name. + * + * Built through the app's own commands: a mesh saved as a component, instanced twice, the + * second instance loading another file. The loader's writes land as each instance's + * overrides, and the render of each instance's Geometry alone draws ITS file and nothing of + * the other's (§V321): file one is a cube above the axis, file two two cubes below it. + */ + +const SIZE = 64; +const SETTINGS: ProjectSettings = { + outputResolution: { width: SIZE, height: SIZE }, + workingFormat: "rgba8unorm", + randomSeed: 7, + previewLongEdge: 192, + previewFps: 20, + limits: { maxResolution: 4096, maxDispatch: 65535, maxBufferBytes: 268_435_456, memoryBudgetBytes: 1_073_741_824 }, +}; +const EYE = [0, 0, 6] as const; + +type Vec3 = readonly [number, number, number]; +const TOP: Vec3 = [0, 1.2, 0]; +const BOTTOM_LEFT: Vec3 = [-1.5, -1.2, 0]; +const BOTTOM_RIGHT: Vec3 = [1.5, -1.2, 0]; + +const ONE = encodeFixtureGlb({ nodes: [{ name: "top", translation: [...TOP], mesh: [cubePrimitive()] }] }); +const TWO = encodeFixtureGlb({ + nodes: [ + { name: "left", translation: [...BOTTOM_LEFT], mesh: [cubePrimitive()] }, + { name: "right", translation: [...BOTTOM_RIGHT], mesh: [cubePrimitive()] }, + ], +}); + +function texelOf(world: Vec3): number { + const matrix = cameraPayloadMatrix({ eye: EYE, lookAt: [0, 0, 0], fovDeg: 60, near: 0.1, far: 100, ortho: false, orthoHeight: 2 }, 1); + const clip = transformPoint(matrix, world); + const x = Math.floor(((clip[0] / clip[3]) * 0.5 + 0.5) * SIZE); + const y = Math.floor((0.5 - (clip[1] / clip[3]) * 0.5) * SIZE); + return (y * SIZE + x) * 4; +} +const lit = (bytes: Uint8Array, world: Vec3): boolean => { + const at = texelOf(world); + return (bytes[at] ?? 0) + (bytes[at + 1] ?? 0) + (bytes[at + 2] ?? 0) > 0; +}; + +afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); + +async function stage() { + const runtime = createAppRuntime({ identityStorage: null }); + const { bus, invocation } = runtime; + const added = await bus.execute("graph.applyPatch", { baseRevision: 0, operations: [ + { op: "addNode", ref: "$mesh", type: "meshFileIn", position: { x: 0, y: 0 }, label: "mesh_stage", parameters: { file: "media/one.glb" } }, + { op: "addNode", ref: "$a", type: "geometry", position: { x: 200, y: 0 }, label: "geometry_a", parameters: { mode: "surface" } }, + { op: "connect", source: { nodeId: "$mesh", portId: "out" }, target: { nodeId: "$a", portId: "points" } }, + ] }, invocation); + expect(added.status).toBe("applied"); + const meshId = added.output.createdIds["$mesh"]!; + const saved = await bus.execute("component.saveSelection", { nodeIds: [meshId], name: "Stage" }, invocation); + expect(saved.status).toBe("applied"); + const port = saved.output.exposedOutputs[0]!; + const placed = await bus.execute("component.instantiate", { componentId: saved.output.componentId! }, invocation); + expect(placed.status).toBe("applied"); + const first = saved.output.instanceNodeId!; + const second = placed.output.nodeId!; + const rest = await bus.execute("graph.applyPatch", { baseRevision: bus.store.getRevision(), operations: [ + { op: "addNode", ref: "$b", type: "geometry", position: { x: 200, y: 200 }, label: "geometry_b", parameters: { mode: "surface" } }, + { op: "connect", source: { nodeId: second, portId: port }, target: { nodeId: "$b", portId: "points" } }, + { op: "addNode", ref: "$cam", type: "camera", position: { x: 400, y: 0 }, label: "camera_lens", parameters: { eye: [...EYE], lookAt: [0, 0, 0] } }, + { op: "addNode", ref: "$shot", type: "render", position: { x: 600, y: 0 }, label: "render_shot", + parameters: { scenes: "geometry_a geometry_b", camera: "camera_lens", lights: "", background: [0, 0, 0, 1], ambientColor: [1, 1, 1, 1], ambientIntensity: 0.5 } }, + { op: "addNode", ref: "$out", type: "output", position: { x: 800, y: 0 }, label: "output_main" }, + { op: "connect", source: { nodeId: "$shot", portId: "out" }, target: { nodeId: "$out", portId: "input" } }, + // The second instance loads the other file: its own override, through the same op. + { op: "setParameters", nodeId: second, internalNodeId: meshId, parameters: { file: "media/two.glb" } }, + ] }, invocation); + expect(rest.diagnostics).toEqual([]); + expect(rest.status).toBe("applied"); + return { runtime, meshId, first, second, shot: rest.output.createdIds["$shot"]! }; +} + +describe("VN33: a Mesh File In inside a component draws, each instance its own file (Dawn)", () => { + it("the loader sizes both instances, and each Geometry draws its own instance's mesh", async () => { + const probe = await probeDawn(); + if (!probe.available) throw new Error(`Dawn unavailable: ${probe.error}`); + const { runtime, meshId, first, second, shot } = await stage(); + try { + const flatA = `${first}/${meshId}`; + const flatB = `${second}/${meshId}`; + + // THE LOADER: the app's hook, reading the files, writing the facts through the bus. + const files: Record = { "media/one.glb": ONE, "media/two.glb": TWO }; + vi.stubGlobal("fetch", vi.fn(async (url: string) => new Response(new Uint8Array(files[url]!)))); + const live = new Set(); + const registerMediaSource = vi.fn((id) => { live.add(id); return () => live.delete(id); }); + const backend = { registerMediaSource } as unknown as LoomBackend; + const hook = renderHook(() => + useMeshSources(runtime, backend, useSyncExternalStore(runtime.bus.store.subscribe, () => runtime.flattened.current().graph)), + ); + // The loader feeds a node only once it is sized for the file: both fed is both sized. + await waitFor(() => expect([...live].sort()).toEqual([ + meshSourceIdsFor(flatA).points, meshSourceIdsFor(flatA).indices, meshSourceIdsFor(flatB).points, meshSourceIdsFor(flatB).indices, + ].sort()), { timeout: 5000 }); + expect(hook.result.current.diagnostics).toEqual([]); + hook.unmount(); + + const document = runtime.bus.store.getGraph(); + const render = async (scenes: string): Promise => { + const graph: GraphDocument = { ...document, nodes: { ...document.nodes, [shot]: { + ...document.nodes[shot]!, parameters: { ...document.nodes[shot]!.parameters, scenes }, + } } }; + const result = await renderHeadless({ + host: nodeGpuHost(), + graph, + components: runtime.components.view(), + settings: SETTINGS, + frames: 2, + outputNodeId: shot, + outputPortId: "out", + meshes: { [flatA]: ONE, [flatB]: TWO }, + }); + expect(result.diagnostics.filter((d) => d.severity === "error")).toEqual([]); + const frame = result.frames[result.frames.length - 1]; + if (frame === undefined) throw new Error("no frame captured"); + return frame.bytes; + }; + + const a = await render("geometry_a"); + expect([lit(a, TOP), lit(a, BOTTOM_LEFT), lit(a, BOTTOM_RIGHT)]).toEqual([true, false, false]); + const b = await render("geometry_b"); + expect([lit(b, TOP), lit(b, BOTTOM_LEFT), lit(b, BOTTOM_RIGHT)]).toEqual([false, true, true]); + } finally { runtime.dispose(); } + }, 60_000); +}); From a5c775998a73ccbbc38b65dc5a1dea05173c45d2 Mon Sep 17 00:00:00 2001 From: Vincent Naples Date: Tue, 6 Oct 2026 20:10:14 -0500 Subject: [PATCH 2/5] =?UTF-8?q?VN35:=20path-aware=20names=20=E2=80=94=20a?= =?UTF-8?q?=20path=20names=20one=20copy=20of=20a=20component's=20node?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit COMP-model stage 1 (proposal 01 §4). B41 renumbers the names inside the second and later instances of a component, so an outer reference could reach in only by a bare name, and a bare name binds the first copy. Three instances of a Projector component could not be bound by one Render. - `op('instance/node')`, `../node`, and path-valued source references (every SOURCE_REFERENCE_PARAMETERS entry). Relative only. A segment is a node's name as written in its own graph. Parsing and the walk live in addressing.ts, the one joiner. - Resolved once, at flatten (path-references.ts): each path is rewritten to its target's unique flat label, so synthesis, the op() reader, liveness and channels are unchanged. A path that reaches nothing stays as written and is refused by name. - Bare names resolve as before. New warning compiler/reference-cross-scope when one reaches INTO an instance the referrer is not in, with the path to write and how many copies carry the name. Reading outward is silent. No shipped example raises it; stage-previz-8 raises 52. - §V128: a rename moves the head of a path written in its graph. B41's uniquing does not touch paths. - `/` is refused in labels at the exact doors (node.label.separator); the suggestion is TD's validName form (roleFromText). node.rename already converts it. Gate (Dawn, projector-paths.gpu.test.ts): one Projector component placed three times through the app's commands, each with its own aim and pure colour; the outer Render binds all three by path and each third of the stage is lit in its own colour only. Red-verified with the pass removed. The bare name, the old way, lights the left third alone and now warns. Co-Authored-By: Claude Opus 5.5 --- docs/path-names-2026-10-06.md | 127 ++++++++++++ src/compiler/diagnostics.ts | 6 + src/compiler/flatten.ts | 32 ++- src/compiler/path-references.test.ts | 170 ++++++++++++++++ src/compiler/path-references.ts | 183 ++++++++++++++++++ src/compiler/source-reference-edges.ts | 14 +- src/domain/commands/apply-patch.test.ts | 16 ++ src/domain/commands/apply-patch.ts | 26 ++- src/domain/components/addressing.test.ts | 51 +++++ src/domain/components/addressing.ts | 133 +++++++++++++ src/domain/diagnostics/class-reasons.ts | 2 + src/domain/diagnostics/classes.ts | 2 + src/domain/graph/names.test.ts | 33 ++++ src/domain/graph/names.ts | 66 +++++-- .../headless/projector-paths.gpu.test.ts | 151 +++++++++++++++ 15 files changed, 988 insertions(+), 24 deletions(-) create mode 100644 docs/path-names-2026-10-06.md create mode 100644 src/compiler/path-references.test.ts create mode 100644 src/compiler/path-references.ts create mode 100644 src/domain/components/addressing.test.ts create mode 100644 src/tests/headless/projector-paths.gpu.test.ts diff --git a/docs/path-names-2026-10-06.md b/docs/path-names-2026-10-06.md new file mode 100644 index 000000000..bf6e058bb --- /dev/null +++ b/docs/path-names-2026-10-06.md @@ -0,0 +1,127 @@ +# Path-aware names (COMP-model stage 1, VN35) + +Proposal: `docs/comp-model-2026-10-06/01-comps-as-folders.md` (laubsauger/loom#3) §2.2, §3.2, §4 stage 1, §6.4. Upstream T1701b rates these paths "low regret". + +## The bug, restated + +`withUniqueNames` (flatten.ts) makes every label globally unique on the flat graph and renumbers +collisions inside instances. That keeps references *inside* an instance pointing at that instance's +own nodes (B41, §V320/§V321). But an outer reference can only reach in by a bare name, and a bare +name binds whichever copy kept its spelling, which is the first one. Instance a Projector three times +and an outer Render naming `projector_beam` binds copy 1 three times, or binds copies 2 and 3 not at +all. No diagnostic is raised. + +## Decisions + +1. **A path segment is a node's NAME (its label), as written in the graph it lives in.** + - For a node inside an instance, that is the label in the *definition*, never the B41-renumbered + flat label. An author never sees the flat label. + - The flat id (`inst/inner`, built from ids) stays the machine address. `addressing.ts` owns it. + - A path is the human address, and it resolves to a flat id. + - An instance with no label has no path, the same rule as any unnamed node (§V127). + +2. **Syntax: relative only.** + - `a/b`: relative to the graph the referring node lives in. + - `../x`: one level up, to the graph that holds the referring node's instance. `..` may repeat. + - There is no absolute form. At the root a relative path already is the absolute one. + Inside a definition, `/a/b` would name a document the definition cannot know, and a + rename could not tell whether it was running at the root. + - A leading `/`, an empty segment, and a `..` after a name are malformed. + - There is no `.` segment. + - A token with no `/` is a bare name and keeps today's rules (see 4). + +3. **Mechanism: resolve once, at flatten, in the same walk as B41.** + - Flatten already knows every level's authored labels, every instance's label and its scope. + - After the walk, each path reference on the flat graph is rewritten to the target's + (unique) flat label. + - Every downstream reader stays unchanged: source-reference synthesis, the `op()` reader, + liveness, channels, and the dependency walk over the flat graph. + - A path that does not resolve is left as written and hits the existing refusals: + `sourceReference.missing` is an error that names the path, and a failed `op()` falls back + to §V108 with its reason. + - Parsing and resolving a path go in `addressing.ts` (`parseNodePath`, `resolveNodePath`), so + `flat-id-joiner.test.ts` stays green and there is still only one joiner. + - Covered: `op('…')` in expression bindings, and every `SOURCE_REFERENCE_PARAMETERS` entry + (Render scenes/camera/lights/projectors, Light casters, Geometry material, Feedback source, + the renderers' camera, Camera Blur, Window, Layer). + +4. **Bare names: resolution unchanged, plus a deprecation warning when one reaches INTO an instance.** + - New code `compiler/reference-cross-scope` (warning), registered in `classes.ts` and `class-reasons.ts`. + - It fires when a bare `op()` or source-reference name lands on a node that is neither in the + referrer's own graph nor in one of its ancestors' graphs. + - The message gives the path to write. When the name is carried by N instances, it also says + that only the first one binds, which is the silent mis-bind made visible. + - Reading OUTWARD stays silent: a component reading a root node by bare name is ordinary + lexical scope. + - Old files keep working exactly as they do now. Nothing changes until someone writes a path. + - Known pre-existing quirk, documented and not changed: with three nested levels, a bare name + that the middle level shadows resolves to the root node rather than the middle one, because + B41 rewrites only a level's own references. Under true lexical scoping it would bind the + middle node. Changing that changes how old files behave, so it is left for stage 2. + +5. **Rename (§V128).** + - Renaming node `x` rewrites, in the same patch: + - bare `x`, as today; + - paths whose first segment is `x`, in the same graph (`renamedPathHead`). + - Not rewritten: + - a path that reaches into a definition from outside, when a node inside the definition is + renamed (the definition is shared and does not know its users); + - `../x` written inside a definition. + - Both cases are exactly where bare names stand today. The dangling path is an error that names + the path. Stage 2 (folders) closes this. + - B41's internal renumbering will NOT rewrite paths. It keeps rewriting bare names only, so a + path is always read in authored-label space. + +6. **`/` in labels: converted at the naming door, refused at the exact doors.** This follows TD's + `tdu.validName`, which turns illegal characters into underscores, slashes included. + - `node.rename` already does what `validName` does: a name that does not conform goes through + `roleFromText`, which turns every run of characters other than letters, digits and `_` into + one `_`. So `rig/a` becomes `rig_a` there, as it did before. + - The doors that store a label exactly (`addNode` with a label, `setNodeLabel`, and so + `rename` with `exact: true`) store what they are given (§V324), so they refuse instead. The + code is `node.label.separator`, and the suggestion names the `validName` form. + - Only `/` is refused. Spaces and other characters still pass the exact doors, as they did, + because older documents and agent patches use them. + - No shipped document has a `/` in a label. A node already labelled `a/b` still loads, but it + is unaddressable by name until it is renamed. + +7. **`kind_role` (T1593b).** + - Each segment is a node name and conforms on its own: `projector_left/projector_beam`. + - A path is not a name. It has no kind and is never kind-prefixed. + - `node-names.test.ts` is unaffected. + +## Out of scope (rows that already exist or follow) + +- `parent()` in expressions (VN36). +- Nested override keys (VN33's codec). +- Paths in preset targets, panel boards, cue lists and Channel In. +- The inspector's authored-graph `op()` read reaching into an instance. A bare name does not reach + there today either, so this is not a regression. It's for stage 2 or a follow-up row. + +## Gate (the PR's claim), Dawn, through the app's commands + +- **Setup.** One `projector_beam` saved as component "Projector" and instanced three times. Each + instance gets its own aim and a pure R, G or B cookie through VN33's `internalNodeId` overrides. + The outer `render_stage` names + `projectors: "projector_left/projector_beam projector_mid/projector_beam projector_right/projector_beam"`. +- **Claim.** Each third of the stage is lit only by its own projector's colour, which is only + possible if three different projectors are bound. +- **Red-verify.** Against today's code the paths dangle (`sourceReference.missing`). The literal old + bug gets a test of its own: the bare `projector_beam` lights only the left third, and now also + raises `compiler/reference-cross-scope`. +- **Unit tests.** + - Path parse and resolve: relative, `..`, malformed, not found, through an unlabelled instance. + - The rename rewrite of path heads. + - The label refusal. + - The cross-scope warning firing for inward bare names and staying silent for outward ones. + +## Measured + +- **Shipped documents.** Every example and starter component, and every project under + `projects/`. + - Not one shipped example raises `compiler/reference-cross-scope`. + - `projects/stage-previz/stage-previz-8.loom.json` raises 52 warnings, one per node and name. + These are exactly the leaks proposal 01 §2.2 describes. Converting that file to paths is + its own change. +- **Cost.** The pass adds about 0.15 ms to a flatten of stage-previz-8 (0.53 to 0.68 ms on an + M-series Mac). Flatten runs once per document revision, not once per frame. diff --git a/src/compiler/diagnostics.ts b/src/compiler/diagnostics.ts index e94a7a21a..37334012f 100644 --- a/src/compiler/diagnostics.ts +++ b/src/compiler/diagnostics.ts @@ -54,6 +54,12 @@ export const CompilerDiagnosticCode = { sourceReferenceMissing: "compiler/source-reference-missing", /** T350: a source reference AND a wired input on the same loop — one truth. */ sourceReferenceAmbiguous: "compiler/source-reference-ambiguous", + /** + * VN35: a BARE name (`op()` or a source reference) that reaches into a component instance + * the referring node is not in. It binds, first-wins, as it always has; the path that + * names the intended copy is the fix (proposal 01 §2.2). + */ + referenceCrossScope: "compiler/reference-cross-scope", /** * T546: more than one renderer frames itself with this camera, so "what the renderer * sees" has no single answer and the preview shows the stock reference scene. INFO, not diff --git a/src/compiler/flatten.ts b/src/compiler/flatten.ts index bade78ac5..eabab9c86 100644 --- a/src/compiler/flatten.ts +++ b/src/compiler/flatten.ts @@ -49,6 +49,8 @@ import { CompilerDiagnosticCode, compilerDiagnostic } from "./diagnostics.ts"; import { resolveNodeParameters } from "./validate.ts"; import type { ActiveSink } from "./types.ts"; import { COMPONENT_ID_SEPARATOR, flattenedNodeId } from "../domain/components/internal-resolutions.ts"; +import type { NameScope } from "../domain/components/addressing.ts"; +import { resolvePathReferences } from "./path-references.ts"; import { applyInstance } from "../domain/components/apply-instance.ts"; import { isDefaultChannelMask } from "../domain/types/graph.ts"; export { COMPONENT_ID_SEPARATOR, flattenedNodeId } from "../domain/components/internal-resolutions.ts"; @@ -554,7 +556,7 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { // the rename works on a copy, never the definition. graph = structuredClone(level) as GraphDocument; for (const rename of renames) { - rewriteNodeNameReferences(graph, rename.oldName, rename.newName); + rewriteNodeNameReferences(graph, rename.oldName, rename.newName, { paths: false }); const node = graph.nodes[rename.nodeId]; if (node !== undefined) graph.nodes[rename.nodeId] = { ...node, label: rename.newName }; } @@ -563,6 +565,22 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { return graph; }; + /* + * VN35: every graph of the flattening as names see it, keyed by its prefix (the root is + * `""`), with the names AS WRITTEN — read off the level's own graph, before + * `withUniqueNames` renumbers them. `path-references.ts` resolves paths against these. + */ + const scopes = new Map }>(); + const scopeOf = new Map(); + const authoredOf = new Map(); + const nameNode = (prefix: string, authored: string | undefined, flatId: NodeId): void => { + scopeOf.set(flatId, prefix); + if (authored === undefined) return; + authoredOf.set(flatId, authored); + const names = scopes.get(prefix)?.names; + if (names !== undefined && !names.has(authored)) names.set(authored, { node: flatId }); + }; + const recordSource = (flatId: NodeId, path: ComponentPath, node: GraphNode, leaf: string): void => { sources.set(flatId, { nodeId: flatId, @@ -687,6 +705,7 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { const flattenLevel = (input: LevelInput): LevelResult => { const levelGraph = withUniqueNames(input.graph); + if (!scopes.has(input.prefix)) scopes.set(input.prefix, { parent: undefined, label: undefined, names: new Map() }); const scope = buildParentScope(input.chain); const grouped = overridesByNode(input.overrides); const origins = originsByNode(input.origins); @@ -704,6 +723,7 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { const node = levelGraph.nodes[nodeId]; if (node === undefined) continue; const flatId = flattenedNodeId(input.prefix, nodeId); + const authored = input.graph.nodes[nodeId]?.label; const instance = readComponentInstance(node); const componentDefinition = instance === null ? undefined : request.components.get(instance.componentId, instance.version); @@ -728,6 +748,7 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { if (instance === null) { addNode(resolved, flatId); + nameNode(input.prefix, authored, flatId); recordSource(flatId, input.path, node, node.label ?? nodeId); // T1497b: the published values this node carries, and where each came from. if (Object.keys(publishedFrom).length > 0) publishedOrigins.set(flatId, publishedFrom); @@ -747,6 +768,7 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { flatId, ); addNode(resolved, flatId); + nameNode(input.prefix, authored, flatId); recordSource(flatId, input.path, node, node.label ?? nodeId); continue; } @@ -768,6 +790,7 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { * bypass mutes, exactly as it does on a plain node. */ addNode(resolved, flatId); + nameNode(input.prefix, authored, flatId); recordSource(flatId, input.path, node, node.label ?? nodeId); continue; } @@ -812,6 +835,10 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { for (const path of applied.missing.channelMasks) diagnostics.push({ severity: "error", code: "component.channelMaskTargetMissing", nodeId: flatId, message: `Component channel mask override names missing internal node "${path}".` }); + // VN35: the instance is a graph of names; its own name, as written, is how a path enters it. + scopes.set(flatId, { parent: input.prefix, label: authored, names: new Map() }); + const enclosing = scopes.get(input.prefix)?.names; + if (authored !== undefined && enclosing !== undefined && !enclosing.has(authored)) enclosing.set(authored, { scope: flatId }); const child = flattenLevel({ graph: applied.graph, definition: componentDefinition, @@ -1008,6 +1035,9 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { target: { nodeId: boundary.id, portId: "preserved" } }; } + // VN35: paths name nodes the walk above has now placed; resolve them before anything reads a name. + diagnostics.push(...resolvePathReferences({ nodes, edges, scopes, scopeOf, authoredOf })); + const graph = flat({ revision: request.graph.revision, nodes, diff --git a/src/compiler/path-references.test.ts b/src/compiler/path-references.test.ts new file mode 100644 index 000000000..0157eb6f0 --- /dev/null +++ b/src/compiler/path-references.test.ts @@ -0,0 +1,170 @@ +import { describe, expect, it } from "vitest"; + +import { componentNodeType, createComponentSystem } from "../domain/components/index.ts"; +import type { GraphComponentDefinition } from "../domain/types/components.ts"; +import type { GraphDocument, GraphNode } from "../domain/types/graph.ts"; +import type { ComponentId } from "../domain/types/ids.ts"; +import type { ParameterSlot } from "../domain/types/parameters.ts"; +import { allNodeDefinitions } from "../nodes/definitions/index.ts"; +import { flattenComponents } from "./flatten.ts"; +import { synthesizeSourceReferenceEdges } from "./source-reference-edges.ts"; +import { CompilerDiagnosticCode } from "./diagnostics.ts"; +import { createCompilerTestRegistry, testNode } from "./test-support.ts"; + +/** + * VN35 — PATHS NAME ONE COPY OF A COMPONENT'S NODE (proposal 01 §2.2, §4 stage 1). + * + * B41 makes every label of the flattening unique by renumbering the copies inside the + * second and later instances, so a bare name from outside reaches the FIRST copy and no + * other. These tests follow what a reference actually binds: the edge the synthesis makes + * from it, whose source is the flattened id of the node it reached. + */ + +const base = createCompilerTestRegistry(allNodeDefinitions).view(); + +const expressionSlot = (source: string, retained: number): ParameterSlot => ({ + mode: "expression", + bindings: { static: { kind: "static", value: retained }, expression: { kind: "expression", source } }, +}); + +const graphOf = (nodes: GraphNode[]): GraphDocument => ({ + revision: 1, + nodes: Object.fromEntries(nodes.map((node) => [node.id, node])), + edges: {}, + groups: {}, +}); + +const instance = (id: string, componentId: ComponentId, label: string): GraphNode => + testNode(id, componentNodeType(componentId, 1), { label }); + +/** One projector, named `projector_beam` in its definition. */ +const projector: GraphComponentDefinition = { + componentId: "projector", + version: 1, + name: "Projector", + graph: graphOf([testNode("beam", "projector", { label: "projector_beam", parameters: { brightness: 1 } })]), + inputs: [], + outputs: [{ externalId: "out", label: "Out", nodeId: "beam", portId: "out" }], + parameters: [], +}; + +/** A rig holding a Projector instance and a Render naming it by a path, and the stage camera from outside. */ +const rig: GraphComponentDefinition = { + componentId: "rig", + version: 1, + name: "Rig", + graph: graphOf([ + instance("lamp", "projector", "projector_lamp"), + testNode("shot", "render", { + label: "render_rig", + parameters: { scenes: "", lights: "", camera: "../camera_stage", projectors: "projector_lamp/projector_beam" }, + }), + ]), + inputs: [], + outputs: [{ externalId: "out", label: "Out", nodeId: "shot", portId: "out" }], + parameters: [], +}; + +function flatten(definitions: GraphComponentDefinition[], nodes: GraphNode[]) { + const system = createComponentSystem(base, definitions); + const flattened = flattenComponents({ graph: graphOf(nodes), registry: system.nodes, components: system.components.view() }); + const synthesized = synthesizeSourceReferenceEdges(flattened.graph, system.nodes); + /** The flattened ids the names feeding a node's input bound, in list order. */ + const bound = (nodeId: string, input: string): string[] => + Object.values(synthesized.graph.edges) + .filter((edge) => edge.id.startsWith("ref:") && edge.target.nodeId === nodeId && edge.target.portId === input) + .sort((a, b) => (a.order ?? 0) - (b.order ?? 0)) + .map((edge) => edge.source.nodeId); + return { flattened, synthesized, bound }; +} + +const threeProjectors = (projectors: string): GraphNode[] => [ + instance("left", "projector", "projector_left"), + instance("mid", "projector", "projector_mid"), + instance("right", "projector", "projector_right"), + testNode("cam", "camera", { label: "camera_stage" }), + testNode("shot", "render", { label: "render_stage", parameters: { scenes: "", lights: "", camera: "camera_stage", projectors } }), +]; + +describe("a path names one copy of a component's node (VN35)", () => { + it("binds three projectors in three instances, one each, in list order", () => { + const { bound, synthesized } = flatten( + [projector], + threeProjectors("projector_left/projector_beam projector_mid/projector_beam projector_right/projector_beam"), + ); + expect(synthesized.diagnostics).toEqual([]); + expect(bound("shot", "projectors")).toEqual(["left/beam", "mid/beam", "right/beam"]); + }); + + it("the bare name, the old way, binds the first copy alone and now says so", () => { + const { bound, flattened } = flatten([projector], threeProjectors("projector_beam")); + // The bug, as it always was: three copies, one bind, and it is the first. + expect(bound("shot", "projectors")).toEqual(["left/beam"]); + const crossing = flattened.diagnostics.filter((d) => d.code === CompilerDiagnosticCode.referenceCrossScope); + expect(crossing).toHaveLength(1); + expect(crossing[0]).toMatchObject({ severity: "warning", nodeId: "shot" }); + expect(crossing[0]?.message).toContain("3 nodes in the document are named \"projector_beam\""); + expect(crossing[0]?.suggestion).toContain("\"projector_left/projector_beam\""); + }); + + it("resolves inside a component, and climbs out of it with ../, per instance", () => { + const { bound, synthesized, flattened } = flatten( + [projector, rig], + [ + instance("a", "rig", "rig_a"), + instance("b", "rig", "rig_b"), + testNode("cam", "camera", { label: "camera_stage" }), + ], + ); + expect(synthesized.diagnostics).toEqual([]); + expect(flattened.diagnostics.filter((d) => d.code === CompilerDiagnosticCode.referenceCrossScope)).toEqual([]); + // Each rig's Render binds its OWN projector — B41 renumbered the second copy's names, + // and the path is read in the names the definition wrote. + expect(bound("a/shot", "projectors")).toEqual(["a/lamp/beam"]); + expect(bound("b/shot", "projectors")).toEqual(["b/lamp/beam"]); + expect(bound("a/shot", "camera")).toEqual(["cam"]); + expect(bound("b/shot", "camera")).toEqual(["cam"]); + }); + + it("rewrites op('instance/node') to the copy it names", () => { + const { flattened } = flatten([projector], [ + ...threeProjectors(""), + testNode("reader", "constant", { + label: "constant_reader", + parameters: { value: expressionSlot("op('projector_right/projector_beam').par.brightness * 2", 0) }, + }), + ]); + const source = (flattened.graph.nodes["reader"]?.parameters["value"] as { bindings: { expression: { source: string } } }).bindings + .expression.source; + const label = flattened.graph.nodes["right/beam"]?.label; + expect(label).not.toBe("projector_beam"); // the third copy was renumbered + expect(source).toBe(`op('${label}').par.brightness * 2`); + }); + + it("leaves a path that reaches nothing as written, and the synthesis refuses it by name", () => { + for (const written of ["projector_left/nope", "camera_stage/projector_beam", "../camera_stage", "/projector_left/projector_beam", "projector_left"]) { + const { synthesized, flattened } = flatten([projector], threeProjectors(written)); + expect(flattened.graph.nodes["shot"]?.parameters["projectors"]).toBe(written); + const missing = synthesized.diagnostics.filter((d) => d.code === CompilerDiagnosticCode.sourceReferenceMissing); + expect(missing, written).toHaveLength(1); + if (written.includes("/")) expect(missing[0]?.message).toContain("a path that reaches no node"); + } + }); + + it("does not warn when a component reads OUTWARD by a bare name — that is lexical scope", () => { + const outward: GraphComponentDefinition = { + ...rig, + componentId: "outward", + graph: graphOf([ + instance("lamp", "projector", "projector_lamp"), + testNode("shot", "render", { + label: "render_rig", + parameters: { scenes: "", lights: "", camera: "camera_stage", projectors: "projector_lamp/projector_beam" }, + }), + ]), + }; + const { flattened, bound } = flatten([projector, outward], [instance("a", "outward", "rig_a"), testNode("cam", "camera", { label: "camera_stage" })]); + expect(bound("a/shot", "camera")).toEqual(["cam"]); + expect(flattened.diagnostics.filter((d) => d.code === CompilerDiagnosticCode.referenceCrossScope)).toEqual([]); + }); +}); diff --git a/src/compiler/path-references.ts b/src/compiler/path-references.ts new file mode 100644 index 000000000..b19b9db32 --- /dev/null +++ b/src/compiler/path-references.ts @@ -0,0 +1,183 @@ +import { + isNodePath, + isWithinScope, + parseNodePath, + pathBetween, + resolveNodePath, + type NameScopes, +} from "../domain/components/addressing.ts"; +import { liveSourceReferenceTokens, sourceReferencesOf } from "../domain/graph/source-references.ts"; +import { isParameterSlot } from "../domain/parameters/slots.ts"; +import type { RuntimeDiagnostic } from "../domain/types/diagnostics.ts"; +import type { GraphEdge, GraphNode } from "../domain/types/graph.ts"; +import type { NodeId } from "../domain/types/ids.ts"; +import { CompilerDiagnosticCode, compilerDiagnostic } from "./diagnostics.ts"; + +/** + * VN35 — PATHS RESOLVE HERE, ONCE, AND EVERY READER DOWNSTREAM READS A NAME. + * + * B41's uniquing leaves every label in the flattening unique across the whole document, so + * a bare name in it names one node. A path (`projector_left/projector_beam`) is resolved + * against the names the author wrote, graph by graph (`addressing.ts`), and the reference + * is rewritten to the label its target carries in the flattening. Source-reference + * synthesis, the `op()` reader, liveness and the channels then read a name as they always + * have, and none of them learns that paths exist. A path that does not resolve is left as + * written: the synthesis refuses it by name (§V369), and an `op()` falls back (§V108). + * + * Beside that, the deprecation half of stage 1: a BARE name that lands inside an instance + * the referring node is not in. That bind is the one B41 leaves first-wins, so of three + * copies only the first is ever reached, and nothing said so. Reading outward (a node in + * an instance naming a node of a graph it lies in) is lexical scope, and is not reported. + * + * Writes `nodes` in place: the flattener's own record, whose node objects it made. The + * parameter records and slots inside them are replaced, never edited, since they can be + * the definition's. + */ +export interface PathReferenceInput { + readonly nodes: Record; + readonly edges: Readonly>; + readonly scopes: NameScopes; + /** Each flattened node's graph (its scope key). */ + readonly scopeOf: ReadonlyMap; + /** Each flattened node's name as written in its own graph, before B41's uniquing. */ + readonly authoredOf: ReadonlyMap; +} + +interface Crossing { + /** The target's name in its own graph. */ + readonly authored: string; + /** The path the referring node should write, when every instance on the way is named. */ + readonly path: string | undefined; + /** How many nodes anywhere carry that written name. */ + readonly carried: number; + /** The name of the instance the target lies in. */ + readonly instance: string; +} + +const OP_REFERENCE = /op\(\s*(['"])([^'"]*)\1\s*\)/g; + +export function resolvePathReferences(input: PathReferenceInput): RuntimeDiagnostic[] { + const { nodes, scopes, scopeOf, authoredOf } = input; + const diagnostics: RuntimeDiagnostic[] = []; + let labels: Map | undefined; + let carriers: Map | undefined; + + /** The flattening's own label for what `written` names from `scope`, or undefined to leave it as written. */ + const resolved = (written: string, scope: string): string | undefined => { + if (!isNodePath(written)) return undefined; + const path = parseNodePath(written); + if (path === undefined) return undefined; + const target = resolveNodePath(path, scope, scopes); + return target.ok ? nodes[target.nodeId]?.label : undefined; + }; + + /** A bare name read from `scope` that reaches into an instance `scope` is not in. */ + const crossesInto = (written: string, scope: string): Crossing | undefined => { + if (isNodePath(written)) return undefined; + labels ??= flatLabels(nodes); + const target = labels.get(written); + const targetScope = target === undefined ? undefined : scopeOf.get(target); + if (target === undefined || targetScope === undefined || isWithinScope(scope, targetScope, scopes)) return undefined; + const authored = authoredOf.get(target) ?? written; + carriers ??= countCarriers(authoredOf); + return { + authored, + path: pathBetween(scope, targetScope, authored, scopes), + carried: carriers.get(authored) ?? 1, + instance: scopes.get(targetScope)?.label ?? targetScope, + }; + }; + + /** One warning per node and name, however many of its parameters write that name. */ + const warn = (nodeId: NodeId, written: string, crossing: Crossing, where: readonly string[]): void => { + const others = + crossing.carried > 1 + ? ` ${crossing.carried} nodes in the document are named "${crossing.authored}", and a bare name reaches only this one.` + : ""; + diagnostics.push( + compilerDiagnostic( + "warning", + CompilerDiagnosticCode.referenceCrossScope, + `Node "${nodeId}" names "${written}" (in ${where.join(", ")}), which lives inside the component instance "${crossing.instance}".${others}`, + { + nodeId, + suggestion: + crossing.path === undefined + ? "Name the instance, then write the reference as a path through it." + : `Write the path "${crossing.path}": a bare name reaching into an instance is kept for old files only.`, + }, + ), + ); + }; + + for (const nodeId of Object.keys(nodes).sort()) { + const node = nodes[nodeId]; + if (node === undefined) continue; + const scope = scopeOf.get(nodeId); + if (scope === undefined) continue; + let parameters: Record | undefined; + const crossings = new Map(); + const note = (written: string, where: string): void => { + const known = crossings.get(written); + if (known !== undefined) { + if (!known.where.includes(where)) known.where.push(where); + return; + } + const crossing = crossesInto(written, scope); + if (crossing !== undefined) crossings.set(written, { crossing, where: [where] }); + }; + const write = (key: string, value: GraphNode["parameters"][string]): void => { + parameters ??= { ...node.parameters }; + parameters[key] = value; + }; + + for (const spec of sourceReferencesOf(node.type)) { + const stored = node.parameters[spec.parameter]; + if (typeof stored !== "string") continue; + for (const token of liveSourceReferenceTokens(spec, node, input.edges)) { + note(token, spec.parameter); + } + if (!isNodePath(stored)) continue; + const rewritten = stored + .split(/([\s,]+)/) + .map((piece) => resolved(piece.trim(), scope) ?? piece) + .join(""); + if (rewritten !== stored) write(spec.parameter, rewritten); + } + + for (const key of Object.keys(node.parameters).sort()) { + const stored = node.parameters[key]; + if (stored === undefined || !isParameterSlot(stored)) continue; + const binding = stored.bindings.expression; + if (binding?.kind !== "expression") continue; + const source = binding.source.replace(OP_REFERENCE, (match, quote: string, written: string) => { + if (stored.mode === "expression") note(written, key); + const label = resolved(written, scope); + return label === undefined ? match : `op(${quote}${label}${quote})`; + }); + if (source !== binding.source) { + write(key, { ...stored, bindings: { ...stored.bindings, expression: { kind: "expression", source } } }); + } + } + + if (parameters !== undefined) nodes[nodeId] = { ...node, parameters }; + for (const [written, { crossing, where }] of crossings) warn(nodeId, written, crossing, where); + } + return diagnostics; +} + +/** The flattening's label index, first-wins in id order, as `nodeNames` builds it. */ +function flatLabels(nodes: Readonly>): Map { + const labels = new Map(); + for (const nodeId of Object.keys(nodes).sort()) { + const label = nodes[nodeId]?.label; + if (label !== undefined && !labels.has(label)) labels.set(label, nodeId); + } + return labels; +} + +function countCarriers(authoredOf: ReadonlyMap): Map { + const counts = new Map(); + for (const name of authoredOf.values()) counts.set(name, (counts.get(name) ?? 0) + 1); + return counts; +} diff --git a/src/compiler/source-reference-edges.ts b/src/compiler/source-reference-edges.ts index a18e84d48..b72a33029 100644 --- a/src/compiler/source-reference-edges.ts +++ b/src/compiler/source-reference-edges.ts @@ -1,3 +1,4 @@ +import { isNodePath } from "../domain/components/addressing.ts"; import { nodeNames } from "../domain/graph/names.ts"; import { liveSourceReferenceTokens, sourceReferencesOf } from "../domain/graph/source-references.ts"; import type { RuntimeDiagnostic } from "../domain/types/diagnostics.ts"; @@ -81,12 +82,21 @@ export function synthesizeSourceReferenceEdges( // §V369: a dangling name is an ERROR that names the name — never a quietly // smaller scene. An empty render because every name dangled is the failure // this refusal exists to make impossible. + // VN35: the flattening rewrote every path that resolves, so a path here reaches nothing. + const path = isNodePath(name); diagnostics.push( compilerDiagnostic( "error", CompilerDiagnosticCode.sourceReferenceMissing, - `Node "${nodeId}" (${node.type}) names ${spec.parameter} "${name}", which no node in the document is called.`, - { nodeId, suggestion: "Name an existing node, or rename the intended one to match." }, + path + ? `Node "${nodeId}" (${node.type}) names ${spec.parameter} "${name}", a path that reaches no node.` + : `Node "${nodeId}" (${node.type}) names ${spec.parameter} "${name}", which no node in the document is called.`, + { + nodeId, + suggestion: path + ? "A path walks node names from the referring node's own graph: instance/node into a component instance, ../node out of one." + : "Name an existing node, or rename the intended one to match.", + }, ), ); return; diff --git a/src/domain/commands/apply-patch.test.ts b/src/domain/commands/apply-patch.test.ts index c34d8e6c8..963873a56 100644 --- a/src/domain/commands/apply-patch.test.ts +++ b/src/domain/commands/apply-patch.test.ts @@ -1078,6 +1078,22 @@ describe("graph.applyPatch — op() reference cycles refused at write time (T331 }); }); +describe("graph.applyPatch — a name may not hold the path separator (VN35)", () => { + it("refuses '/' in an explicit label at both exact doors, and names the valid form", async () => { + const added = await apply([{ op: "addNode", ref: "$a", type: "test.solid", position: { x: 0, y: 0 }, label: "rig/solid" }]); + expect(added.status).toBe("rejected"); + expect(added.diagnostics[0]).toMatchObject({ code: "node.label.separator", suggestion: '"rig_solid" is a name.' }); + expect(nodeCount()).toBe(0); + + const created = await apply([addSolid("$a")]); + const nodeId = created.output.createdIds["$a"] as string; + const renamed = await apply([{ op: "setNodeLabel", nodeId, label: "solid/one" }]); + expect(renamed.status).toBe("rejected"); + expect(renamed.diagnostics[0]?.code).toBe("node.label.separator"); + expect(graph().nodes[nodeId]?.label).toBe("solid1"); + }); +}); + describe("graph.applyPatch — names as identifiers (T221/T222, §V128/§V129)", () => { it("auto-names created nodes uniquely, in patch order", async () => { const result = await apply([addSolid("$a"), addSolid("$b", 100)]); diff --git a/src/domain/commands/apply-patch.ts b/src/domain/commands/apply-patch.ts index 20808256a..9f5f8abf8 100644 --- a/src/domain/commands/apply-patch.ts +++ b/src/domain/commands/apply-patch.ts @@ -6,7 +6,7 @@ import type { EdgeId, GroupId, NodeId, PortId } from "../types/ids.ts"; import { isDefaultChannelMask, MIN_NODE_SIZE } from "../types/graph.ts"; import { supportsChannelMask } from "../graph/channel-mask.ts"; import { COMPONENT_OVERRIDES_STATE_KEY, internalParameterPath, isComponentInstance, readComponentInstance } from "../components/instance.ts"; -import { enteredThrough } from "../components/addressing.ts"; +import { enteredThrough, isNodePath } from "../components/addressing.ts"; import { INTERNAL_CHANNEL_MASKS_KEY, internalChannelMasks } from "../components/internal-channel-masks.ts"; import type { GraphDocument, GraphEdge, GraphNode } from "../types/graph.ts"; import type { StoredParameter } from "../types/parameters.ts"; @@ -27,7 +27,7 @@ import { rewriteNodeNameReferences, uniqueNodeName, } from "../graph/names.ts"; -import { kindOf } from "../graph/node-kinds.ts"; +import { kindOf, roleFromText } from "../graph/node-kinds.ts"; import { sourceReferenceForInput } from "../graph/source-references.ts"; import { defaultParameters, undeclaredKeys, validateParameters } from "../parameters/validate.ts"; import { bindCycleDiagnostics } from "../parameters/bind-cycles.ts"; @@ -358,6 +358,20 @@ function executeOperation( throw new PatchAbort(); }; + /* + * VN35: `/` separates the names of a path (`projector_left/projector_beam`), so a name may + * not hold one: `op('a/b')` would mean two things. Refused, not converted, at the doors that + * store a label exactly (§V324): a caller carrying a name has references written against it. + * The suggestion is TD's `tdu.validName` of the label, which is `roleFromText`. + */ + const refuseSeparator = (label: string, nodeId: NodeId): void => { + const valid = roleFromText(label); + fail("node.label.separator", `the name "${label}" holds "/", which separates the names in a path.`, { + nodeId, + ...(valid === "" ? {} : { suggestion: `"${valid}" is a name.` }), + }); + }; + const resolveNodeId = (ref: NodeRef): NodeId => { if (isTempId(ref)) { const resolved = run.createdIds[ref]; @@ -447,6 +461,10 @@ function executeOperation( fail("node.emptyLabel", `an explicit label may not be empty.`, { nodeId }); return; } + if (requested !== undefined && isNodePath(requested)) { + refuseSeparator(requested, nodeId); + return; + } if (requested !== undefined && nodeNames(draft).has(requested)) { fail("node.nameTaken", `the name "${requested}" is already in use.`, { nodeId }); return; @@ -967,6 +985,10 @@ function executeOperation( suggestion: "Pass null to clear the label and fall back to the definition title.", }); } + if (isNodePath(label)) { + refuseSeparator(label, node.id); + return; + } if (label.length > 120) { fail("node.label.tooLong", `label is ${label.length} characters; the limit is 120.`, { nodeId: node.id, diff --git a/src/domain/components/addressing.test.ts b/src/domain/components/addressing.test.ts new file mode 100644 index 000000000..316f69dc5 --- /dev/null +++ b/src/domain/components/addressing.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vitest"; + +import { formatNodePath, parseNodePath, pathBetween, renamedPathHead, resolveNodePath, type NameScopes } from "./addressing.ts"; + +/** + * VN35 — the path grammar and its walk, on a hand-built scope table: + * the root holds `camera_stage` and two rigs; `rig_a` holds a projector instance; the + * unnamed rig `u` holds a node no path can reach. + */ +const scopes: NameScopes = new Map([ + ["", { parent: undefined, label: undefined, names: new Map([["camera_stage", { node: "cam" }], ["rig_a", { scope: "a" }], ["rig_b", { scope: "b" }]]) }], + ["a", { parent: "", label: "rig_a", names: new Map([["projector_lamp", { scope: "a/lamp" }], ["render_rig", { node: "a/shot" }]]) }], + ["a/lamp", { parent: "a", label: "projector_lamp", names: new Map([["projector_beam", { node: "a/lamp/beam" }]]) }], + ["b", { parent: "", label: "rig_b", names: new Map([["render_rig", { node: "b/shot" }]]) }], + ["u", { parent: "", label: undefined, names: new Map([["hidden", { node: "u/hidden" }]]) }], +] as const); + +describe("node paths (VN35)", () => { + it("parses relative paths and refuses the malformed", () => { + expect(parseNodePath("rig_a/projector_lamp")).toEqual({ up: 0, names: ["rig_a", "projector_lamp"] }); + expect(parseNodePath("../../camera_stage")).toEqual({ up: 2, names: ["camera_stage"] }); + for (const malformed of ["/rig_a", "rig_a/", "rig_a//x", "..", "rig_a/../x", ""]) { + expect(parseNodePath(malformed), malformed).toBeUndefined(); + } + expect(formatNodePath({ up: 1, names: ["rig_b", "render_rig"] })).toBe("../rig_b/render_rig"); + }); + + it("walks down through instances and up out of them, and says where a walk stops", () => { + const walk = (text: string, from: string) => resolveNodePath(parseNodePath(text)!, from, scopes); + expect(walk("rig_a/projector_lamp/projector_beam", "")).toEqual({ ok: true, nodeId: "a/lamp/beam" }); + expect(walk("../../camera_stage", "a/lamp")).toEqual({ ok: true, nodeId: "cam" }); + expect(walk("../rig_b/render_rig", "a")).toEqual({ ok: true, nodeId: "b/shot" }); + expect(walk("../camera_stage", "")).toMatchObject({ ok: false, reason: "it climbs above the document's root" }); + expect(walk("rig_a/nope", "")).toMatchObject({ ok: false, reason: 'no node is named "nope" there' }); + expect(walk("rig_a/projector_lamp", "")).toMatchObject({ ok: false }); + expect(walk("camera_stage/x", "")).toMatchObject({ ok: false }); + }); + + it("writes the path between two graphs, and none through an unnamed instance", () => { + expect(pathBetween("", "a/lamp", "projector_beam", scopes)).toBe("rig_a/projector_lamp/projector_beam"); + expect(pathBetween("b", "a/lamp", "projector_beam", scopes)).toBe("../rig_a/projector_lamp/projector_beam"); + expect(pathBetween("", "u", "hidden", scopes)).toBeUndefined(); + }); + + it("renames only the head of a path that starts in the renamed node's graph", () => { + expect(renamedPathHead("rig_a/projector_lamp", "rig_a", "rig_left")).toBe("rig_left/projector_lamp"); + expect(renamedPathHead("rig_a", "rig_a", "rig_left")).toBeUndefined(); + expect(renamedPathHead("../rig_a/x", "rig_a", "rig_left")).toBeUndefined(); + expect(renamedPathHead("rig_b/rig_a", "rig_a", "rig_left")).toBeUndefined(); + }); +}); diff --git a/src/domain/components/addressing.ts b/src/domain/components/addressing.ts index 3e40769f1..f9e9cafc8 100644 --- a/src/domain/components/addressing.ts +++ b/src/domain/components/addressing.ts @@ -62,3 +62,136 @@ export function fromInstance(path: InstancePath, flatId: NodeId): NodeId | undef const rest = flatId.slice(prefix.length); return rest === "" || rest.includes(COMPONENT_ID_SEPARATOR) ? undefined : rest; } + +/** + * VN35 — A NODE REACHED BY NAME ACROSS INSTANCES (proposal 01 §4 stage 1). + * + * The flattened id above is the MACHINE's address of a node inside an instance, built from + * ids. A path is the AUTHOR's: the same walk spelled in node names, which is what an + * `op('…')` and a source reference hold. `projector_left/projector_beam` is the node named + * `projector_beam` inside the instance named `projector_left`, and `../camera_stage` is the + * node named `camera_stage` in the graph that holds the referring node's instance. + * + * - A segment is a node's NAME as written in the graph it lives in: an internal's label in + * its DEFINITION, never the label B41's uniquing gave its flattened copy, which no author + * sees. An unnamed instance has no path, as an unnamed node has no name (§V127). + * - Relative only. At the root a relative path is the absolute one, and inside a definition + * an absolute path would name a document the definition cannot know. A leading `/`, an + * empty segment, and a `..` after a name are malformed. + * - A name holding no separator is a bare name and is not a path: it keeps the rules it had. + */ +export const NODE_PATH_UP = ".."; + +export interface NodePath { + /** How many graphs to climb before the names apply. */ + readonly up: number; + /** The names to walk down, the node's own last. Never empty. */ + readonly names: readonly string[]; +} + +/** True when a reference is written as a path rather than as a bare name. */ +export function isNodePath(text: string): boolean { + return text.includes(COMPONENT_ID_SEPARATOR); +} + +/** The path a reference spells, or undefined when it is malformed. A bare name parses as a one-name path. */ +export function parseNodePath(text: string): NodePath | undefined { + const segments = text.split(COMPONENT_ID_SEPARATOR); + let up = 0; + while (segments[up] === NODE_PATH_UP) up += 1; + const names = segments.slice(up); + if (names.length === 0 || names.some((name) => name === "" || name === NODE_PATH_UP)) return undefined; + return { up, names }; +} + +export function formatNodePath(path: NodePath): string { + return [...Array(path.up).fill(NODE_PATH_UP), ...path.names].join(COMPONENT_ID_SEPARATOR); +} + +/** + * §V128 for a path: the reference with its FIRST name renamed, when that name is a node of + * the graph the reference is written in (a path that does not climb). Undefined when the + * rename does not touch it: a bare name (the caller's own clause), a path that climbs, or a + * path through another node. A name further down lives in a definition and is that + * definition's to rename. + */ +export function renamedPathHead(text: string, oldName: string, newName: string): string | undefined { + if (!isNodePath(text)) return undefined; + const path = parseNodePath(text); + if (path === undefined || path.up > 0 || path.names[0] !== oldName) return undefined; + return formatNodePath({ up: 0, names: [newName, ...path.names.slice(1)] }); +} + +/** + * One graph of the flattening, as names see it. The root's key is `""`; an inlined + * instance's is its flattened id, which is the prefix its own nodes carry. + */ +export interface NameScope { + /** The graph holding this one's instance; undefined at the root. */ + readonly parent: string | undefined; + /** The instance's own name in `parent`; undefined at the root and for an unnamed instance. */ + readonly label: string | undefined; + /** Each name in this graph: a flattened node, or an inlined instance's scope key. */ + readonly names: ReadonlyMap; +} +export type NameScopes = ReadonlyMap; + +export type PathResolution = + | { readonly ok: true; readonly nodeId: NodeId } + | { readonly ok: false; readonly reason: string }; + +/** Walks `path` from the graph `from`, name by name. Each refusal says where the walk stopped. */ +export function resolveNodePath(path: NodePath, from: string, scopes: NameScopes): PathResolution { + let at = scopes.get(from); + for (let climb = 0; climb < path.up; climb += 1) { + if (at?.parent === undefined) return { ok: false, reason: "it climbs above the document's root" }; + at = scopes.get(at.parent); + } + for (let index = 0; index < path.names.length; index += 1) { + const name = path.names[index] as string; + const entry = at?.names.get(name); + const last = index === path.names.length - 1; + if (entry === undefined) { + return { ok: false, reason: `no node is named "${name}" ${index === 0 && path.up === 0 ? "beside it" : "there"}` }; + } + if (last) { + if ("node" in entry) return { ok: true, nodeId: entry.node }; + return { ok: false, reason: `"${name}" is a component instance; name a node inside it` }; + } + if (!("scope" in entry)) return { ok: false, reason: `"${name}" is not a component instance, so nothing is inside it` }; + at = scopes.get(entry.scope); + } + return { ok: false, reason: "it names nothing" }; +} + +/** True when `scope` is `ancestor` or lies inside it. */ +export function isWithinScope(scope: string, ancestor: string, scopes: NameScopes): boolean { + for (let at: string | undefined = scope; at !== undefined; at = scopes.get(at)?.parent) { + if (at === ancestor) return true; + } + return false; +} + +/** + * The path a node in `from` writes to reach `name` in the graph `to`: climb to the graph + * both lie in, then name the instances down. Undefined when an instance on the way has no + * name, so no path can be written. + */ +export function pathBetween(from: string, to: string, name: string, scopes: NameScopes): string | undefined { + let up = 0; + let common = from; + while (!isWithinScope(to, common, scopes)) { + const parent = scopes.get(common)?.parent; + if (parent === undefined) return undefined; + common = parent; + up += 1; + } + const down: string[] = []; + for (let at = to; at !== common; ) { + const scope = scopes.get(at); + if (scope?.label === undefined || scope.parent === undefined) return undefined; + down.unshift(scope.label); + at = scope.parent; + } + return formatNodePath({ up, names: [...down, name] }); +} diff --git a/src/domain/diagnostics/class-reasons.ts b/src/domain/diagnostics/class-reasons.ts index c2a2d9218..7c904a177 100644 --- a/src/domain/diagnostics/class-reasons.ts +++ b/src/domain/diagnostics/class-reasons.ts @@ -94,6 +94,7 @@ export const DIAGNOSTIC_CLASS_REASONS: Readonly> = { "compiler/port-incompatible": "two port types with no conversion between them", "compiler/port-missing": "an edge on a port the type does not declare", "compiler/port-occupied": "a second wire into a single input is ignored", + "compiler/reference-cross-scope": "a bare name that reaches into an instance binds as stored; a path says which copy", "compiler/resolution-clamped": "scaled down to the limit in force", "compiler/resolution-custom": "the project resolution stands in for a custom policy", "compiler/resolution-input-missing": "the project resolution stands in for an unwired input's", @@ -344,6 +345,7 @@ export const DIAGNOSTIC_CLASS_REASONS: Readonly> = { "node.emptyLabel": "the patch operation's input", "node.format.invalid": "the patch operation's input", "node.label.empty": "the patch operation's input", + "node.label.separator": "the patch operation's input", "node.label.tooLong": "the patch operation's input", "node.materialWgsl.params": "a Params field named after one of the material's own keys", "node.materialWgsl.source": "material source that breaks the surface contract", diff --git a/src/domain/diagnostics/classes.ts b/src/domain/diagnostics/classes.ts index db347ee95..f0c437a85 100644 --- a/src/domain/diagnostics/classes.ts +++ b/src/domain/diagnostics/classes.ts @@ -145,6 +145,7 @@ export const DIAGNOSTIC_CLASSES: Readonly> = "compiler/port-incompatible": { class: "never" }, "compiler/port-missing": { class: "never" }, "compiler/port-occupied": { class: "never" }, + "compiler/reference-cross-scope": { class: "advice" }, "compiler/resolution-clamped": { class: "degraded" }, "compiler/resolution-custom": { class: "degraded" }, "compiler/resolution-input-missing": { class: "degraded" }, @@ -395,6 +396,7 @@ export const DIAGNOSTIC_CLASSES: Readonly> = "node.emptyLabel": { class: "act" }, "node.format.invalid": { class: "act" }, "node.label.empty": { class: "act" }, + "node.label.separator": { class: "act" }, "node.label.tooLong": { class: "act" }, "node.materialWgsl.params": { class: "never" }, "node.materialWgsl.source": { class: "never" }, diff --git a/src/domain/graph/names.test.ts b/src/domain/graph/names.test.ts index 5cdd30142..a6f76e410 100644 --- a/src/domain/graph/names.test.ts +++ b/src/domain/graph/names.test.ts @@ -258,3 +258,36 @@ describe("T1172 — the name index reflects a graph mutated between reads", () = expect(nodeByName(graph, "gain9")).toBe("a"); }); }); + +describe("a rename and a path (VN35, §V128)", () => { + const expression = (source: string) => ({ mode: "expression", bindings: { expression: { kind: "expression", source } } }); + const sourceOf = (graph: GraphDocument, id: string): string => + (graph.nodes[id]?.parameters["value"] as { bindings: { expression: { source: string } } }).bindings.expression.source; + + it("moves the FIRST name of a path written in the renamed node's graph, and only that", () => { + const graph = graphWith({ + rig: { label: "rig_a" }, + render: { + type: "render", + label: "render_stage", + parameters: { projectors: "rig_a/projector_beam rig_ab/projector_beam rig_b/rig_a", camera: "../rig_a" }, + }, + reader: { label: "constant_reader", parameters: { value: expression("op('rig_a/projector_beam').par.x + op('rig_a').par.y") as never } }, + }); + expect(countNodeNameReferences(graph, "rig_a")).toBe(2); + rewriteNodeNameReferences(graph, "rig_a", "rig_left"); + // The head moved; a name further down, a longer name sharing the prefix, and a path + // that climbs out (it names a node of ANOTHER graph) did not. + expect(graph.nodes["render"]?.parameters["projectors"]).toBe("rig_left/projector_beam rig_ab/projector_beam rig_b/rig_a"); + expect(graph.nodes["render"]?.parameters["camera"]).toBe("../rig_a"); + expect(sourceOf(graph, "reader")).toBe("op('rig_left/projector_beam').par.x + op('rig_left').par.y"); + }); + + it("leaves paths alone when asked to (B41's uniquing renames a copy, not what the author wrote)", () => { + const graph = graphWith({ + render: { type: "render", label: "render_stage", parameters: { projectors: "rig_a/projector_beam rig_a" } }, + }); + rewriteNodeNameReferences(graph, "rig_a", "rig_a1", { paths: false }); + expect(graph.nodes["render"]?.parameters["projectors"]).toBe("rig_a/projector_beam rig_a1"); + }); +}); diff --git a/src/domain/graph/names.ts b/src/domain/graph/names.ts index 8c5f4e5ef..e220e0671 100644 --- a/src/domain/graph/names.ts +++ b/src/domain/graph/names.ts @@ -10,6 +10,7 @@ import { CUE_LIST_NODE_TYPE, parseCueList, serializeCueList } from "../presets/c import type { StoredParameter } from "../types/parameters.ts"; import { parsePanelBoard, serializePanelBoard } from "../../nodes/definitions/controls.ts"; import { kindOfType, roleFromText, withKind } from "./node-kinds.ts"; +import { renamedPathHead } from "../components/addressing.ts"; /** * Node names as identifiers (T221/T222, §V127-§V129). @@ -84,9 +85,17 @@ export function resolveRename(graph: GraphDocument, requested: string, excludeNo } } -/** Matches `op('name')` / `op("name")`, the coming reference syntax, name captured. */ -const referencePattern = (name: string): RegExp => - new RegExp(String.raw`op\(\s*(['"])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\1\s*\)`, "g"); +/** Matches every `op('…')` / `op("…")`, quote and name captured. */ +const OP_REFERENCE = /op\(\s*(['"])([^'"]*)\1\s*\)/g; + +/** + * What a rename makes of one written reference: `name` itself, or (VN35) a path whose first + * name is `name` when `paths` is on. Undefined when the reference is not to the node. + */ +function renamedReference(written: string, name: string, rename: string, paths: boolean): string | undefined { + if (written === name) return rename; + return paths ? renamedPathHead(written, name, rename) : undefined; +} /** * §V128: rewrites every stored reference to `oldName` into one to `newName`, across the @@ -98,17 +107,29 @@ export function rewriteNodeNameReferences( graph: GraphDocument, oldName: string, newName: string, + options: RewriteOptions = {}, ): number { if (oldName === newName) return 0; + const paths = options.paths ?? true; let rewritten = 0; for (const nodeId of Object.keys(graph.nodes).sort()) { const node = graph.nodes[nodeId]; if (node === undefined) continue; - for (const clause of REFERENCE_CLAUSES) rewritten += clause(node, oldName, newName); + for (const clause of REFERENCE_CLAUSES) rewritten += clause(node, oldName, newName, paths); } return rewritten; } +export interface RewriteOptions { + /** + * VN35: also move a PATH whose first name is the renamed node (`old/inner` → `new/inner`). + * On for every rename an author makes. B41's uniquing in the flattener turns it off: it + * renames a COPY's labels so bare names stay inside their instance, while a path is read + * in the names the author wrote, which that renumbering does not change. + */ + readonly paths?: boolean; +} + /** * How many stored references name `name` — what a CLEAR of the label would strand. * @@ -124,7 +145,7 @@ export function countNodeNameReferences(graph: GraphDocument, name: string): num for (const nodeId of Object.keys(graph.nodes).sort()) { const node = graph.nodes[nodeId]; if (node === undefined) continue; - for (const clause of REFERENCE_CLAUSES) count += clause(node, name, null); + for (const clause of REFERENCE_CLAUSES) count += clause(node, name, null, true); } return count; } @@ -137,21 +158,25 @@ export function countNodeNameReferences(graph: GraphDocument, name: string): num * answering both questions — `rename === null` counts, a string rewrites — so the two * surfaces cannot drift apart again: they are the same walk. */ -type ReferenceClause = (node: GraphNode, name: string, rename: string | null) => number; +type ReferenceClause = (node: GraphNode, name: string, rename: string | null, paths: boolean) => number; -/** Kind 1: `op('name')` inside expression payloads (the original clause). */ -const expressionClause: ReferenceClause = (node, name, rename) => { - const pattern = referencePattern(name); +/** Kind 1: `op('name')` inside expression payloads (the original clause), and `op('name/inner')` (VN35). */ +const expressionClause: ReferenceClause = (node, name, rename, paths) => { let touched = 0; for (const key of Object.keys(node.parameters).sort()) { const stored = node.parameters[key]; if (stored === undefined || !isParameterSlot(stored)) continue; const binding = stored.bindings.expression; if (binding?.kind !== "expression") continue; - pattern.lastIndex = 0; - if (!pattern.test(binding.source)) continue; + let hit = false; + const source = binding.source.replace(OP_REFERENCE, (match, quote: string, written: string) => { + const moved = renamedReference(written, name, rename ?? name, paths); + if (moved === undefined) return match; + hit = true; + return `op(${quote}${moved}${quote})`; + }); + if (!hit) continue; if (rename !== null) { - const source = binding.source.replace(referencePattern(name), (_match, quote: string) => `op(${quote}${rename}${quote})`); node.parameters[key] = { ...stored, bindings: { ...stored.bindings, expression: { kind: "expression", source } }, @@ -191,22 +216,25 @@ const drivenChannelClause: ReferenceClause = (node, name, rename) => { * move, separators and order preserved — because list order is draw/light order and a * rename must not reshuffle the scene. */ -const sourceReferenceClause: ReferenceClause = (node, name, rename) => { +const sourceReferenceClause: ReferenceClause = (node, name, rename, paths) => { let touched = 0; for (const spec of sourceReferencesOf(node.type)) { const stored = node.parameters[spec.parameter]; if (typeof stored !== "string") continue; if (spec.list === true) { - if (!sourceReferenceTokens(spec, node.parameters).includes(name)) continue; + const tokens = sourceReferenceTokens(spec, node.parameters); + if (!tokens.some((token) => renamedReference(token, name, name, paths) !== undefined)) continue; if (rename !== null) { node.parameters[spec.parameter] = stored .split(/([\s,]+)/) - .map((piece) => (piece === name ? rename : piece)) + .map((piece) => renamedReference(piece, name, rename, paths) ?? piece) .join(""); } touched += 1; - } else if (stored.trim() === name) { - if (rename !== null) node.parameters[spec.parameter] = rename; + } else { + const moved = renamedReference(stored.trim(), name, rename ?? name, paths); + if (moved === undefined) continue; + if (rename !== null) node.parameters[spec.parameter] = moved; touched += 1; } } @@ -239,7 +267,7 @@ function renamedKey(record: Readonly>, name: string, rename * a node name, so the key never moves — but their slots are stored references like any * other, and an expression in one names root nodes. Kinds 1 and 2 run over them. */ -const presetBankClause: ReferenceClause = (node, name, rename) => { +const presetBankClause: ReferenceClause = (node, name, rename, paths) => { const instance = isComponentNodeType(node.type); // `parent` on an instance's records is the reserved word, never a root node's name. if ((!isPresetsNode(node) && !instance) || (instance && name === PAGE_TARGET)) return 0; @@ -251,7 +279,7 @@ const presetBankClause: ReferenceClause = (node, name, rename) => { const walked: Record> = {}; for (const [nodeName, record] of Object.entries(values)) { const standIn: GraphNode = { id: node.id, type: "", definitionVersion: 1, position: { x: 0, y: 0 }, parameters: { ...record } }; - hits += expressionClause(standIn, name, rename) + drivenChannelClause(standIn, name, rename); + hits += expressionClause(standIn, name, rename, paths) + drivenChannelClause(standIn, name, rename, paths); walked[nodeName] = standIn.parameters; } if (name in walked) hits += 1; diff --git a/src/tests/headless/projector-paths.gpu.test.ts b/src/tests/headless/projector-paths.gpu.test.ts new file mode 100644 index 000000000..b36f58a59 --- /dev/null +++ b/src/tests/headless/projector-paths.gpu.test.ts @@ -0,0 +1,151 @@ +import { describe, expect, it } from "vitest"; + +import { createAppRuntime } from "../../app/app-runtime.ts"; +import { cameraPayloadMatrix, transformPoint } from "../../domain/geometry/camera.ts"; +import type { GraphDocument, ProjectSettings } from "../../domain/types/graph.ts"; +import { nodeGpuHost, probeDawn } from "../../runtime/backend/vgpu/node-gpu-host.ts"; +import { renderHeadless } from "./render-harness.ts"; + +/** + * VN35 — ONE PROJECTOR COMPONENT, THREE INSTANCES, THREE DIFFERENT PROJECTORS BOUND, on Dawn. + * + * Proposal 01 §2.2: B41 renumbers the names inside the second and later instances, so the + * outer Render could reach a component's projector only by a bare name, and a bare name + * reaches the FIRST copy. A reusable projector component was impossible. A path names one + * copy: `projector_left/projector_beam`. + * + * Built through the app's own commands: one projector saved as the component "Projector", + * placed three times, each instance named, aimed at its own third of a flat stage and lit + * its own pure colour through its own overrides (VN33's `internalNodeId`). Pure 0/1 colours + * are fixed points of the display decode (§V56), so each beam is exactly one channel. + * + * The claim is read from pixels (§V147, the arithmetic of `projector-render.gpu.test.ts`): + * the centre of third k is lit at full strength in colour k ONLY, and the other two channels + * there are the ambient floor. That is possible only if all three projectors are bound, each + * once. Against the code before VN35 the paths name nothing and the compile refuses them; the + * bare name, written the old way, lights the left third alone. + */ + +const SIZE = 64; +const SETTINGS: ProjectSettings = { + outputResolution: { width: SIZE, height: SIZE }, + workingFormat: "rgba8unorm", + randomSeed: 7, + previewLongEdge: 192, + previewFps: 20, + limits: { maxResolution: 4096, maxDispatch: 65535, maxBufferBytes: 268_435_456, memoryBudgetBytes: 1_073_741_824 }, +}; + +/** Three thirds of the stage, and the beam that lands on each: red, green, blue. */ +const BEAMS = [ + { name: "projector_left", x: -0.66, color: [1, 0, 0, 1] }, + { name: "projector_mid", x: 0, color: [0, 1, 0, 1] }, + { name: "projector_right", x: 0.66, color: [0, 0, 1, 1] }, +] as const; + +/* Albedo 0.8 under white ambient 0.12; a beam on its own axis at its throw distance adds one + light's worth (|N·L| = 1, falloff 1). Throw ratio 6 from 4 out: half-width 1/3, so each + beam stays in its own third. */ +const FLOOR = Math.round(0.8 * 0.12 * 255); +const FULL = Math.round(0.8 * (0.12 + 1) * 255); + +const camera = cameraPayloadMatrix({ eye: [0, 0, 3], lookAt: [0, 0, 0], fovDeg: 55, near: 0.1, far: 100, ortho: false, orthoHeight: 2 }, 1); +function rgbAt(bytes: Uint8Array, x: number): [number, number, number] { + const clip = transformPoint(camera, [x, 0, 0]); + const px = Math.round(((clip[0] / clip[3]) * 0.5 + 0.5) * SIZE); + const py = Math.round((0.5 - (clip[1] / clip[3]) * 0.5) * SIZE); + const at = (py * SIZE + px) * 4; + return [bytes[at] ?? -1, bytes[at + 1] ?? -1, bytes[at + 2] ?? -1]; +} + +async function stage(): Promise<{ graph: GraphDocument; shot: string; components: ReturnType["components"]["view"]> }> { + const runtime = createAppRuntime({ identityStorage: null }); + const { bus, invocation } = runtime; + const added = await bus.execute("graph.applyPatch", { baseRevision: 0, operations: [ + { op: "addNode", ref: "$beam", type: "projector", position: { x: 0, y: 0 }, label: "projector_beam", + parameters: { throwRatio: 6, occlusion: false } }, + ] }, invocation); + expect(added.status).toBe("applied"); + const beam = added.output.createdIds["$beam"]!; + const saved = await bus.execute("component.saveSelection", { nodeIds: [beam], name: "Projector" }, invocation); + expect(saved.status).toBe("applied"); + const instances = [saved.output.instanceNodeId!]; + for (let copy = 1; copy < BEAMS.length; copy += 1) { + const placed = await bus.execute("component.instantiate", { componentId: saved.output.componentId! }, invocation); + expect(placed.status).toBe("applied"); + instances.push(placed.output.nodeId!); + } + for (const [index, spec] of BEAMS.entries()) { + const renamed = await bus.execute("node.rename", { nodeId: instances[index]!, label: spec.name }, invocation); + expect(renamed.status).toBe("applied"); + } + + const rest = await bus.execute("graph.applyPatch", { baseRevision: bus.store.getRevision(), operations: [ + ...BEAMS.map((spec, index) => ({ + op: "setParameters" as const, + nodeId: instances[index]!, + internalNodeId: beam, + parameters: { eye: [spec.x, 0, 4], lookAt: [spec.x, 0, 0], color: [...spec.color] }, + })), + { op: "addNode", ref: "$grid", type: "pointGrid", position: { x: 0, y: 300 }, label: "grid_stage", parameters: { cols: 8, rows: 8 } }, + { op: "addNode", ref: "$geo", type: "geometry", position: { x: 200, y: 300 }, label: "geometry_stage", parameters: { mode: "surface" } }, + { op: "connect", source: { nodeId: "$grid", portId: "out" }, target: { nodeId: "$geo", portId: "points" } }, + { op: "addNode", ref: "$cam", type: "camera", position: { x: 200, y: 450 }, label: "camera_stage", parameters: { eye: [0, 0, 3], lookAt: [0, 0, 0] } }, + { op: "addNode", ref: "$shot", type: "render", position: { x: 400, y: 300 }, label: "render_stage", parameters: { + scenes: "geometry_stage", camera: "camera_stage", lights: "", + projectors: BEAMS.map((spec) => `${spec.name}/projector_beam`).join(" "), + ambientColor: [1, 1, 1, 1], ambientIntensity: 0.12, + } }, + { op: "addNode", ref: "$out", type: "output", position: { x: 600, y: 300 }, label: "output_main" }, + { op: "connect", source: { nodeId: "$shot", portId: "out" }, target: { nodeId: "$out", portId: "input" } }, + ] }, invocation); + expect(rest.status).toBe("applied"); + return { graph: bus.store.getGraph(), shot: rest.output.createdIds["$shot"]!, components: runtime.components.view() }; +} + +async function render(staged: Awaited>, projectors?: string) { + const { graph, shot } = staged; + const node = graph.nodes[shot]!; + const result = await renderHeadless({ + host: nodeGpuHost(), + graph: projectors === undefined ? graph : { ...graph, nodes: { ...graph.nodes, [shot]: { ...node, parameters: { ...node.parameters, projectors } } } }, + components: staged.components, + settings: SETTINGS, + frames: 2, + outputNodeId: shot, + outputPortId: "out", + }); + const frame = result.frames[result.frames.length - 1]; + if (frame === undefined) throw new Error("no frame captured"); + return { bytes: frame.bytes, diagnostics: result.diagnostics }; +} + +describe("VN35: three instances of one Projector component, three projectors bound by path (Dawn)", () => { + it("each third of the stage is lit by its own instance's projector and no other", async () => { + const probe = await probeDawn(); + if (!probe.available) throw new Error(`Dawn unavailable: ${probe.error}`); + const staged = await stage(); + const { bytes, diagnostics } = await render(staged); + expect(diagnostics.filter((d) => d.severity === "error" || d.code === "compiler/reference-cross-scope")).toEqual([]); + expect(BEAMS.map((spec) => rgbAt(bytes, spec.x))).toEqual([ + [FULL, FLOOR, FLOOR], + [FLOOR, FULL, FLOOR], + [FLOOR, FLOOR, FULL], + ]); + }, 120_000); + + it("the bare name, the old way, binds the first copy only, and the compile now says so", async () => { + const probe = await probeDawn(); + if (!probe.available) throw new Error(`Dawn unavailable: ${probe.error}`); + const staged = await stage(); + const { bytes, diagnostics } = await render(staged, "projector_beam"); + expect(BEAMS.map((spec) => rgbAt(bytes, spec.x))).toEqual([ + [FULL, FLOOR, FLOOR], + [FLOOR, FLOOR, FLOOR], + [FLOOR, FLOOR, FLOOR], + ]); + expect(diagnostics.filter((d) => d.code === "compiler/reference-cross-scope").map((d) => d.suggestion)).toEqual([ + expect.stringContaining('"projector_left/projector_beam"'), + ]); + }, 120_000); +}); From f0a144904ec367067aa5060e3f4fd92265badc55 Mon Sep 17 00:00:00 2001 From: Vincent Naples Date: Tue, 6 Oct 2026 22:51:57 -0500 Subject: [PATCH 3/5] =?UTF-8?q?VN36:=20parent(n).par.key=20parses=20?= =?UTF-8?q?=E2=80=94=20the=20grammar=20half?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `parent()` / `parent(n)` followed by `.par.` with an optional component, refused at parse time in every other shape with the form to write. A bare `parent` stays a variable name. The AST node records its span, so a caller with the scope can rewrite the read in place (`parent-reads.ts`) without re-serialising or pattern-matching the expression. Nothing evaluates one yet: the evaluator refuses it as `reference.unreadable` ("not inside a component") rather than reading 0. The flattener's rewrite lands in the next commits. Co-Authored-By: Claude Opus 5.5 --- src/domain/expressions/evaluate.ts | 71 ++++++++++++++++++ src/domain/expressions/index.ts | 2 + src/domain/expressions/parent-reads.test.ts | 72 ++++++++++++++++++ src/domain/expressions/parent-reads.ts | 77 ++++++++++++++++++++ src/domain/graph/composed-parameter-reads.ts | 1 + src/domain/graph/parameter-dependencies.ts | 3 + 6 files changed, 226 insertions(+) create mode 100644 src/domain/expressions/parent-reads.test.ts create mode 100644 src/domain/expressions/parent-reads.ts diff --git a/src/domain/expressions/evaluate.ts b/src/domain/expressions/evaluate.ts index a842236d1..86e38b24b 100644 --- a/src/domain/expressions/evaluate.ts +++ b/src/domain/expressions/evaluate.ts @@ -38,6 +38,18 @@ export type ExpressionAst = * parameter resolver turns into the §V108 fallback rather than an error wall. */ | { kind: "opRef"; name: string; path: readonly string[] } + /** + * VN36 — `parent().par.gain`, `parent(2).par.tint.r`: a published parameter of the + * component `hops` levels out (§V81). `path` is always `["par", key]` or + * `["par", key, component]`; the parser refuses every other shape. `at`/`end` are its span + * in the TRIMMED source, a pure function of the text like the rest of the tree (the parse + * memo shares it), and they are what lets the flattener rewrite the read in place. + * + * Nothing evaluates one: the flattener rewrites it to an `op()` read of the instance it + * names (`parent-reads.ts`), and one that reaches the evaluator was never inside a + * component. + */ + | { kind: "parentRef"; hops: number; path: readonly string[]; at: number; end: number } /** A whitelisted function call (T370). Arity is checked at PARSE time; see `FUNCTIONS`. */ | { kind: "call"; name: string; args: readonly ExpressionAst[] } | { kind: "unary"; operator: "-" | "+"; operand: ExpressionAst } @@ -666,6 +678,7 @@ function parsePrimary(cursor: Cursor): ExpressionAst { const next = peek(cursor); if (next !== undefined && next.kind === "paren" && next.value === "(") { if (token.value === "op") return parseOpReference(cursor); + if (token.value === PARENT_FUNCTION) return parseParentReference(cursor, token.at); return parseCall(cursor, token.value); } return { kind: "variable", name: token.value }; @@ -852,6 +865,57 @@ function parseOpReference(cursor: Cursor): ExpressionAst { return { kind: "opRef", name: name.value, path }; } +/** VN36: the one name `parent(` is spelled with. A bare `parent` stays a variable name. */ +export const PARENT_FUNCTION = "parent"; + +/** + * `parent(n).par.key[.component]` — the cursor stands ON the opening paren (VN36, §V81). + * + * Stricter than `op()` on purpose. `op()` takes any member path and leaves the reader to + * refuse one it cannot read, because the target's type decides what it has. A component's + * page has parameters and nothing else (a component's channels are read through + * `op('').chan`), so every other shape is known wrong while the author is still + * typing, and is refused here with the form to write. + */ +function parseParentReference(cursor: Cursor, at: number): ExpressionAst { + cursor.index += 1; // consume "(" + let hops = 1; + const count = peek(cursor); + if (count !== undefined && count.kind === "number") { + if (!Number.isInteger(count.value) || count.value < 1) { + fail("syntax", `parent() counts components outward from 1: parent(1) is the one this node is in, not parent(${count.value})`); + } + hops = count.value; + cursor.index += 1; + } + const closing = peek(cursor); + if (closing === undefined || closing.kind !== "paren" || closing.value !== ")") { + fail("syntax", "parent() takes nothing, or how many components out as a whole number: parent(), parent(2)"); + } + cursor.index += 1; + + const path: string[] = []; + let end = closing.end; + for (;;) { + const dot = peek(cursor); + if (dot === undefined || dot.kind !== "dot") break; + cursor.index += 1; + const member = peek(cursor); + if (member === undefined || member.kind !== "identifier") fail("syntax", "expected a member name after \".\""); + cursor.index += 1; + path.push(member.value); + end = member.end; + } + const shape = "parent().par., or one component of it, as parent().par.color.r"; + if (path[0] !== "par") { + fail("syntax", path.length === 0 ? `parent() must read a parameter: ${shape}` : `parent() reads parameters only (.par), not .${path[0]}`, { + suggestion: `Write ${shape}. A component's channels are read as op('').chan..`, + }); + } + if (path.length < 2 || path.length > 3) fail("syntax", `name one parameter: ${shape}`); + return { kind: "parentRef", hops, path, at, end }; +} + /** * ═══════════════════════════════════════════════════════════════════════════════════ * THE PARSE MEMO (T1172) — KEYED BY THE SOURCE TEXT, SO IT CANNOT OUTLIVE AN EDIT @@ -972,6 +1036,13 @@ function evaluateNode( if (!read.ok) fail(`reference.${read.kind ?? "unreadable"}`, read.reason, { suggestion: read.suggestion }); return read.value; } + case "parentRef": + // VN36: the flattener rewrites every one inside a component to an `op()` read of the + // instance it names, so one that gets here is outside any. A number here would be one + // that looks like an answer. + fail("reference.unreadable", `parent() reads a published parameter of the component a node is in, and this expression is not inside one`, { + suggestion: "Use parent() in a node inside a component, or read the parameter with op('').par..", + }); case "call": { const spec = FUNCTIONS[ast.name]; // Unreachable through `parseExpression`, which refuses both cases. Reachable diff --git a/src/domain/expressions/index.ts b/src/domain/expressions/index.ts index a86012354..83bafab0c 100644 --- a/src/domain/expressions/index.ts +++ b/src/domain/expressions/index.ts @@ -8,6 +8,7 @@ export { functionSignature, nearestSpelling, parseExpression, + PARENT_FUNCTION, scopeFromFrame, type EvaluateResult, type ExpressionAst, @@ -21,3 +22,4 @@ export { type ReferenceFailureKind, type SpelledLike, } from "./evaluate.ts"; +export { formatParentRead, parentReadsOf, rewriteParentReads, type ParentRead } from "./parent-reads.ts"; diff --git a/src/domain/expressions/parent-reads.test.ts b/src/domain/expressions/parent-reads.test.ts new file mode 100644 index 000000000..160fbd686 --- /dev/null +++ b/src/domain/expressions/parent-reads.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from "vitest"; + +import { evaluateExpression, parseExpression } from "./evaluate.ts"; +import { formatParentRead, parentReadsOf, rewriteParentReads } from "./parent-reads.ts"; + +describe("VN36 — parent() in the grammar", () => { + it("parses parent() as one hop and parent(n) as n, reading .par.key and one component", () => { + expect(parseExpression("parent().par.gain")).toEqual({ + ok: true, + ast: { kind: "parentRef", hops: 1, path: ["par", "gain"], at: 0, end: 17 }, + }); + const two = parseExpression("parent(2).par.tint.r * 0.5"); + expect(two.ok && two.ast.kind === "binary" ? two.ast.left : null).toMatchObject({ kind: "parentRef", hops: 2, path: ["par", "tint", "r"] }); + }); + + it("keeps a bare `parent` a variable name; only `parent(` is the read", () => { + expect(evaluateExpression("parent * 2", { parent: 3 })).toEqual({ ok: true, value: 6 }); + }); + + it.each([ + ["parent()", "must read a parameter"], + ["parent().chan.value", "parameters only (.par)"], + ["parent().par", "name one parameter"], + ["parent().par.color.r.x", "name one parameter"], + ["parent(0).par.gain", "counts components outward from 1"], + ["parent(1.5).par.gain", "counts components outward from 1"], + ["parent('rig').par.gain", "takes nothing, or how many"], + ["parent(1, 2).par.gain", "takes nothing, or how many"], + ])("refuses %s as syntax, saying what to write", (source, reason) => { + const parsed = parseExpression(source); + expect(parsed.ok).toBe(false); + if (!parsed.ok) { + expect(parsed.kind).toBe("syntax"); + expect(parsed.reason).toContain(reason); + } + }); + + it("never evaluates to a number outside a component: it fails as unreadable, with the reason", () => { + const evaluated = evaluateExpression("parent().par.gain + 1", {}, () => ({ ok: true, value: 0 })); + expect(evaluated).toMatchObject({ ok: false, kind: "reference.unreadable" }); + if (!evaluated.ok) expect(evaluated.reason).toContain("not inside one"); + }); +}); + +describe("VN36 — parent() reads by span", () => { + it("finds every read, nested in calls and operators, with spans into the source as given", () => { + const source = " clamp(parent().par.gain, 0, parent(2).par.max) + op('parent().par.x').par.y"; + const reads = parentReadsOf(source); + expect(reads.map((read) => source.slice(read.at, read.end))).toEqual(["parent().par.gain", "parent(2).par.max"]); + expect(reads.map(({ hops, key, component }) => ({ hops, key, component }))).toEqual([ + { hops: 1, key: "gain", component: undefined }, + { hops: 2, key: "max", component: undefined }, + ]); + }); + + it("reads nothing from a source that does not parse", () => { + expect(parentReadsOf("parent().par.gain +")).toEqual([]); + }); + + it("rewrites in place, right to left, and leaves a read the caller declines as written", () => { + const source = "parent().par.gain * 2 + parent(2).par.gain"; + const rewritten = rewriteParentReads(source, (read) => (read.hops === 1 ? "op('rig1').par.gain" : undefined)); + expect(rewritten).toBe("op('rig1').par.gain * 2 + parent(2).par.gain"); + }); + + it("formats a read the way the grammar parses it", () => { + for (const read of [{ hops: 1, key: "gain", component: undefined }, { hops: 3, key: "tint", component: "g" }]) { + const [parsed] = parentReadsOf(formatParentRead(read)); + expect(parsed).toMatchObject(read); + } + }); +}); diff --git a/src/domain/expressions/parent-reads.ts b/src/domain/expressions/parent-reads.ts new file mode 100644 index 000000000..acec53e84 --- /dev/null +++ b/src/domain/expressions/parent-reads.ts @@ -0,0 +1,77 @@ +import { parseExpression, PARENT_FUNCTION, type ExpressionAst } from "./evaluate.ts"; + +/** + * VN36: `parent(n).par.key` in one expression source, read and rewritten by its SPAN. + * + * The grammar parses the read; this is how a caller that has the scope turns it into one it + * can evaluate without one. The flattener rewrites each read to an `op()` read of the + * instance it names (`compiler/parent-references.ts`), and `component.detach` rewrites it one + * level outward. Both splice the text at the span the parser recorded, so nothing here + * re-serialises an expression or matches it with a pattern: a `'parent()'` inside an `op()` + * name is a string, never a read. + */ +export interface ParentRead { + /** 1 = the component the node is in, 2 = the one around that, and so on. */ + readonly hops: number; + readonly key: string; + /** `parent().par.color.r` reads one component of a compound (§V113). */ + readonly component: string | undefined; + /** Its span in the source AS GIVEN (not trimmed). */ + readonly at: number; + readonly end: number; +} + +/** + * Every `parent()` read in `source`, in source order. Empty when there is none, and when the + * source does not parse: such a source reads nothing, and its own syntax error says so. + */ +export function parentReadsOf(source: string): ParentRead[] { + // Cheap refusal first: this runs over every expression slot of every flattening. + if (!source.includes(`${PARENT_FUNCTION}(`) && !source.includes(`${PARENT_FUNCTION} (`)) return []; + const parsed = parseExpression(source); + if (!parsed.ok) return []; + const offset = source.length - source.trimStart().length; + const reads: ParentRead[] = []; + const walk = (ast: ExpressionAst): void => { + switch (ast.kind) { + case "parentRef": + reads.push({ hops: ast.hops, key: ast.path[1] ?? "", component: ast.path[2], at: ast.at + offset, end: ast.end + offset }); + return; + case "unary": + walk(ast.operand); + return; + case "binary": + walk(ast.left); + walk(ast.right); + return; + case "call": + for (const arg of ast.args) walk(arg); + return; + case "opRef": + case "number": + case "variable": + return; + } + }; + walk(parsed.ast); + return reads.sort((a, b) => a.at - b.at); +} + +/** + * `source` with each `parent()` read replaced by what `replace` returns for it. A read + * `replace` returns `undefined` for is left as written. Spliced right to left, so every span + * still holds when it is reached. + */ +export function rewriteParentReads(source: string, replace: (read: ParentRead) => string | undefined): string { + let rewritten = source; + for (const read of parentReadsOf(source).reverse()) { + const replacement = replace(read); + if (replacement !== undefined) rewritten = rewritten.slice(0, read.at) + replacement + rewritten.slice(read.end); + } + return rewritten; +} + +/** How a read is written: `parent().par.gain`, `parent(2).par.tint.r`. */ +export function formatParentRead(read: Pick): string { + return `${PARENT_FUNCTION}(${read.hops === 1 ? "" : read.hops}).par.${read.key}${read.component === undefined ? "" : `.${read.component}`}`; +} diff --git a/src/domain/graph/composed-parameter-reads.ts b/src/domain/graph/composed-parameter-reads.ts index d10725b7c..372ef7d35 100644 --- a/src/domain/graph/composed-parameter-reads.ts +++ b/src/domain/graph/composed-parameter-reads.ts @@ -72,6 +72,7 @@ export function composedParameterReadDiagnostics( case "call": for (const arg of ast.args) walk(arg); return; + case "parentRef": case "number": case "variable": return; diff --git a/src/domain/graph/parameter-dependencies.ts b/src/domain/graph/parameter-dependencies.ts index 0a4d3058c..ab19a4fe8 100644 --- a/src/domain/graph/parameter-dependencies.ts +++ b/src/domain/graph/parameter-dependencies.ts @@ -125,6 +125,9 @@ export function opReferences(source: string): OpReference[] | null { case "call": for (const arg of ast.args) walk(arg); return; + // VN36: a `parent()` read is lexical scope, never an edge (§V81). The flattener + // rewrites it to an `op()` read, which this walk then sees on the flat graph. + case "parentRef": case "number": case "variable": return; From 34a282b004ef0cbe59faa6bd6caf10ed5c78f6d2 Mon Sep 17 00:00:00 2001 From: Vincent Naples Date: Tue, 6 Oct 2026 22:58:40 -0500 Subject: [PATCH 4/5] VN36: op('').par. reads a dissolved instance's page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Flattening deletes the instance node, so the compiler's reader, over the flat graph, found nothing called `rig1`. T1485b answered that for `.chan`. This answers it for `.par`: the flattening hands over each instance's page (`FlatteningReads.instancePages`, label → the instance as flattened plus its published schema), and a name no flat node carries is resolved there, through the same `targetOf` as any node. An animated knob is evaluated once per frame at its publisher, and the reader gets a number. This is the read `parent()` becomes (next commit). It is a stage-1 bridge: when a COMP is a real node (proposal 01 stages 2–3) the name index finds it and the map retires. `instancePages` is REQUIRED on `FlatteningReads` (T1551b's rule), so every reader site says it: the compile and per-frame compile (beside `resolution.instances`), the value graph, the OSC pump, parameter commands, the controls pane, the inspector (the root flattening's pages while inside an instance) and the test harnesses. Gate (integration, real flattener/value graph/compiler): page value read and followed; an animated page knob at two frames; a compound component; an unknown key refused with the nearest spelling; the per-frame values-only compile equal to the full compile and moving. Red-verified: reader lookup off fails all five; the per-frame compile's pages off fails the last. Co-Authored-By: Claude Opus 5.5 --- src/app/use-osc-bridge.ts | 2 +- src/app/use-value-graph.ts | 2 +- src/app/values-lane.test.ts | 2 +- src/compiler/compile.ts | 15 +- src/compiler/flatten.ts | 28 +++- src/compiler/frame-compile.ts | 16 +- src/compiler/generated-text.test.ts | 4 +- src/compiler/validate.ts | 10 +- src/domain/channels/graph-channels.ts | 4 +- src/domain/commands/parameter-commands.ts | 2 +- src/domain/parameters/index.ts | 1 + src/domain/parameters/node-references.ts | 49 +++++- src/domain/parameters/test-support.ts | 6 +- src/editor/controls/controls-pane.tsx | 2 +- src/editor/inspector/inspector.tsx | 9 +- src/tests/headless/cook-oracle.ts | 3 +- src/tests/headless/render-harness.ts | 6 +- .../instance-parameter-reference.test.ts | 147 ++++++++++++++++++ 18 files changed, 278 insertions(+), 30 deletions(-) create mode 100644 src/tests/integration/instance-parameter-reference.test.ts diff --git a/src/app/use-osc-bridge.ts b/src/app/use-osc-bridge.ts index eb9baf2c1..250927b1a 100644 --- a/src/app/use-osc-bridge.ts +++ b/src/app/use-osc-bridge.ts @@ -342,7 +342,7 @@ export function useOscBridge(options: OscBridgeOptions = {}): OscBridgeBinding { */ const settledOptions = flattening.morphs.activeAt(frame) - ? parameterReadOptions({ graph, registry, frame, channels, flattening: { morphs: NO_MORPHS, instanceChannels: flattening.instanceChannels } }) + ? parameterReadOptions({ graph, registry, frame, channels, flattening: { morphs: NO_MORPHS, instanceChannels: flattening.instanceChannels, instancePages: flattening.instancePages } }) : null; /* diff --git a/src/app/use-value-graph.ts b/src/app/use-value-graph.ts index 9f311ac12..13c0aa53f 100644 --- a/src/app/use-value-graph.ts +++ b/src/app/use-value-graph.ts @@ -244,7 +244,7 @@ export function useValueGraph(runtime: AppRuntime, externalChannels?: ChannelRes const result = once.evaluate(flattened.graph, ZERO_FRAME, { pointer: { x: 0, y: 0, buttons: 0 }, // The structural compile reads no fade (it has no frame); it does read instances. - flattening: { morphs: NO_MORPHS, instanceChannels: flattened.instanceChannels, ...(flattened.structure === undefined ? {} : { structure: flattened.structure }) }, + flattening: { morphs: NO_MORPHS, instanceChannels: flattened.instanceChannels, instancePages: flattened.instancePages, ...(flattened.structure === undefined ? {} : { structure: flattened.structure }) }, }); structural.current = { flattened, resolver: result.resolver, byName: result.byName }; return result.resolver(channel, context); diff --git a/src/app/values-lane.test.ts b/src/app/values-lane.test.ts index 180314fd9..58bf49f65 100644 --- a/src/app/values-lane.test.ts +++ b/src/app/values-lane.test.ts @@ -128,7 +128,7 @@ function harness(opened: Opened) { const session = createValueGraphSession(opened.registry); const evaluated = session.evaluate(flattened.graph, ZERO_FRAME, { pointer: { x: 0, y: 0, buttons: 0 }, - flattening: { morphs: NO_MORPHS, instanceChannels: flattened.instanceChannels }, + flattening: { morphs: NO_MORPHS, instanceChannels: flattened.instanceChannels, instancePages: flattened.instancePages }, }); zero = { flattened, resolver: evaluated.resolver }; } diff --git a/src/compiler/compile.ts b/src/compiler/compile.ts index 049cb7f95..e5240d405 100644 --- a/src/compiler/compile.ts +++ b/src/compiler/compile.ts @@ -94,7 +94,7 @@ function withTimeProbe(probe: TimeProbe | undefined): { timeProbe?: TimeProbe } } import { effectiveParameterSchema } from "../domain/parameters/resolve.ts"; import type { ParameterMorphs } from "../domain/parameters/resolve.ts"; -import type { InstanceChannelSources } from "../domain/parameters/node-references.ts"; +import type { InstanceChannelSources, InstancePages } from "../domain/parameters/node-references.ts"; import { buildMorphIndex } from "../domain/presets/morph-index.ts"; import { timelineCueProblems } from "../domain/presets/timeline-cues.ts"; import { outputPixelScale } from "../domain/types/graph.ts"; @@ -864,6 +864,8 @@ export interface RetainedCompile { readonly morphs: ParameterMorphs; /** T1485b: the component instances this compile's `op()` reads could name, kept as `morphs` is. */ readonly instances: InstanceChannelSources | undefined; + /** VN36: and the instance pages its `op('').par` (and `parent()`) reads resolve. */ + readonly instancePages: InstancePages | undefined; /** * T1652b: what each node SAID about its own values in this compile, by id: the * diagnostics of resolving its parameters, then those its `compile` returned. Only @@ -940,7 +942,14 @@ export function compileGraphRetaining(request: CompileRequest): CompileGraphResu request.resolution?.morphs ?? flattened?.morphs ?? buildMorphIndex({ document: request.graph, registry }); // T1485b: and the instances `op('').chan` can name, by the same precedence. const instances = request.resolution?.instances ?? flattened?.instanceChannels; - const reading: ParameterResolution = { ...(request.resolution ?? {}), morphs, ...(instances === undefined ? {} : { instances }) }; + // VN36: and the instance pages `op('').par` reads, by the same precedence. + const instancePages = request.resolution?.instancePages ?? flattened?.instancePages; + const reading: ParameterResolution = { + ...(request.resolution ?? {}), + morphs, + ...(instances === undefined ? {} : { instances }), + ...(instancePages === undefined ? {} : { instancePages }), + }; // §T1559b (2): what a cue list that follows the timeline cannot do as written (every // `cue.timeline.*` warning of its plan), where both roots read problems. A flattening // already carries them (`flattened.diagnostics`, above: once per flattening, not per frame @@ -2712,7 +2721,7 @@ export function compileGraphRetaining(request: CompileRequest): CompileGraphResu signature: structure.signature, estimatedResourceBytes, }, - retained: { request, graph, order: topology.order, nodes: retainedNodes, scenePayloads: sceneInfoByOutput, morphs, instances, said }, + retained: { request, graph, order: topology.order, nodes: retainedNodes, scenePayloads: sceneInfoByOutput, morphs, instances, instancePages, said }, }; } diff --git a/src/compiler/flatten.ts b/src/compiler/flatten.ts index eabab9c86..1b4b8e95d 100644 --- a/src/compiler/flatten.ts +++ b/src/compiler/flatten.ts @@ -13,7 +13,7 @@ import type { StoredParameter, } from "../domain/types/parameters.ts"; import type { ParameterMorphs } from "../domain/parameters/resolve.ts"; -import type { FlatteningReads, InstanceChannelSource, InstanceChannelSources } from "../domain/parameters/node-references.ts"; +import { NO_PAGES, type FlatteningReads, type InstanceChannelSource, type InstanceChannelSources, type InstancePage, type InstancePages } from "../domain/parameters/node-references.ts"; import { NO_MORPHS, buildMorphIndex, type MorphIndexInput, type PublishedOrigin } from "../domain/presets/morph-index.ts"; import { timelineCueProblems } from "../domain/presets/timeline-cues.ts"; import { renumberedName, rewriteNodeNameReferences } from "../domain/graph/names.ts"; @@ -414,6 +414,7 @@ function identityFlattening(graph: GraphDocument): FlattenedGraph { sources, instanceOutputs: new Map(), instanceChannels: new Map(), + instancePages: NO_PAGES, sinks: [], recursion: null, diagnostics: [], @@ -485,6 +486,7 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { sources: new Map(), instanceOutputs: new Map(), instanceChannels: new Map(), + instancePages: NO_PAGES, sinks: [], recursion, diagnostics, @@ -497,6 +499,8 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { const nodes: Record = {}; const instanceNodes = new Map(); + /** VN36: each instance's published page as a schema, for `instancePages`. */ + const pageSchemas = new Map(); const edges: Record = {}; const sources = new Map(); const instanceOutputs = new Map>(); @@ -743,6 +747,7 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { if (instance !== null) { instanceNodes.set(flatId, resolved); + if (componentDefinition !== undefined) pageSchemas.set(flatId, schema ?? {}); if (Object.keys(publishedFrom).length > 0) publishedOrigins.set(flatId, publishedFrom); } @@ -1061,6 +1066,7 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { sources, instanceOutputs, instanceChannels: instanceChannelsOf(instanceNodes, instanceOutputs, nodes, request.registry), + instancePages: instancePagesOf(instanceNodes, pageSchemas), sinks, recursion: null, diagnostics, @@ -1108,6 +1114,26 @@ function instanceChannelsOf( return byLabel; } +/** + * VN36: instance LABEL → its page, for `op('').par.` and so `parent()`. + * First-wins in flat-id order, like `nodeNames` and `instanceChannelsOf`; B41 has already + * made instance labels unique across the flattening, so first-wins decides nothing in a + * flattening this walk produced. An unlabelled instance has no name to read it by. + */ +function instancePagesOf( + instanceNodes: ReadonlyMap, + pageSchemas: ReadonlyMap, +): InstancePages { + const byLabel = new Map(); + for (const instanceId of [...instanceNodes.keys()].sort()) { + const node = instanceNodes.get(instanceId); + const schema = pageSchemas.get(instanceId); + if (node?.label === undefined || schema === undefined || byLabel.has(node.label)) continue; + byLabel.set(node.label, { node, schema }); + } + return byLabel; +} + /** * Rewrites a sink that named a component instance to name what the instance became. * diff --git a/src/compiler/frame-compile.ts b/src/compiler/frame-compile.ts index 521e40217..b67ad05c9 100644 --- a/src/compiler/frame-compile.ts +++ b/src/compiler/frame-compile.ts @@ -336,13 +336,15 @@ function frameCompilerOver( const morphs = resolution.morphs ?? retained.morphs; // T1485b: the instances the BASE compile read through, by the same precedence. const instances = resolution.instances ?? retained.instances; + // VN36: and the instance pages, the same way. + const instancePages = resolution.instancePages ?? retained.instancePages; // The same reader `validateGraph` builds (§V939). const reader = parameterReadOptions({ graph: retained.graph, registry: request.registry, frame: resolution.frame, channels: resolution.channels, - flattening: flatteningReadsOf({ morphs, instances }), + flattening: flatteningReadsOf({ morphs, instances, instancePages }), }); // Per-frame resolution diagnostics (a clamped expression, an unattached channel) are // dropped, exactly as the full per-frame compile's were by its one consumer. @@ -376,7 +378,7 @@ function frameCompilerOver( const sceneMoved = bindingsReadScene(record.context.inputs, recompiled); if (frameValues === undefined && !sceneMoved) continue; // T1421b: the probe moves with the frame, exactly as the full compile's does. - const probe = timeProbeFor(record.node, record.definition, retained.graph, request.registry, { ...resolution, morphs, ...(instances === undefined ? {} : { instances }) }, retained.request.settings); + const probe = timeProbeFor(record.node, record.definition, retained.graph, request.registry, { ...resolution, morphs, ...(instances === undefined ? {} : { instances }), ...(instancePages === undefined ? {} : { instancePages }) }, retained.request.settings); const context: CompilerNodeContext = { ...record.context, ...(frameValues === undefined ? {} : frameValues), @@ -692,18 +694,24 @@ export function rebaseOnValues(previous: CompileGraphResult, request: CompileReq const graph: FlatGraph = { ...retained.graph, nodes }; const morphs = request.resolution?.morphs ?? request.flattened?.morphs ?? retained.morphs; const instances = request.resolution?.instances ?? request.flattened?.instanceChannels; + const instancePages = request.resolution?.instancePages ?? request.flattened?.instancePages; const records = new Map(retained.nodes); for (const id of moved) { const record = records.get(id); if (record !== undefined) records.set(id, { ...record, node: nodes[id] as GraphNode }); } - const staged: RetainedCompile = { ...retained, request, graph, nodes: records, morphs, instances }; + const staged: RetainedCompile = { ...retained, request, graph, nodes: records, morphs, instances, instancePages }; const rerun = new Set([...linked].filter((id) => records.has(id))); const compiler = frameCompilerOver(request, { compiled: base, retained: staged }, rerun); if (!compiler.uniformOnly) return compiler.reason ?? "A node that reads the value animates a structural parameter."; const capture: RerunCapture = { contexts: new Map(), scene: null, said: new Map() }; - const reading: ParameterResolution = { ...(request.resolution ?? {}), morphs, ...(instances === undefined ? {} : { instances }) }; + const reading: ParameterResolution = { + ...(request.resolution ?? {}), + morphs, + ...(instances === undefined ? {} : { instances }), + ...(instancePages === undefined ? {} : { instancePages }), + }; const spliced = compiler.compileFrame(reading, capture); if (spliced === null) return compiler.reason ?? "A re-run node could not be proven structure-preserving."; for (const id of capture.contexts.keys()) { diff --git a/src/compiler/generated-text.test.ts b/src/compiler/generated-text.test.ts index fd75cf72b..eeecd7cf8 100644 --- a/src/compiler/generated-text.test.ts +++ b/src/compiler/generated-text.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest"; import { createValueGraphSession } from "../domain/channels/value-graph.ts"; import { graphChannelResolver } from "../domain/channels/graph-channels.ts"; import { createComponentSystem } from "../domain/components/index.ts"; -import { NO_INSTANCES } from "../domain/parameters/node-references.ts"; +import { NO_INSTANCES, NO_PAGES } from "../domain/parameters/node-references.ts"; import { effectiveParameterSchema } from "../domain/parameters/resolve.ts"; import { buildMorphIndex } from "../domain/presets/morph-index.ts"; import { loadProject } from "../domain/project/index.ts"; @@ -137,7 +137,7 @@ function sentinel(): Animated { request: { graph, settings: built.settings, registry, capabilities: TIER_B_CAPABILITIES }, resolutionAt: (frameIndex) => { const frame = frameAt(frameIndex); - const evaluated = session.evaluate(logical, frame, { pointer: { x: 0, y: 0, buttons: 0 } as never, flattening: { morphs, instanceChannels: NO_INSTANCES } }); + const evaluated = session.evaluate(logical, frame, { pointer: { x: 0, y: 0, buttons: 0 } as never, flattening: { morphs, instanceChannels: NO_INSTANCES, instancePages: NO_PAGES } }); return { frame, channels: evaluated.resolver }; }, }; diff --git a/src/compiler/validate.ts b/src/compiler/validate.ts index 59ee5a2ef..3115407f0 100644 --- a/src/compiler/validate.ts +++ b/src/compiler/validate.ts @@ -8,9 +8,11 @@ import { arePortsCompatible, describePortType } from "../domain/graph/port-compa import { resolveParameterSchema, effectiveParameterSchema, type ParameterMapBinding } from "../domain/parameters/resolve.ts"; import { NO_INSTANCES, + NO_PAGES, parameterReadOptions, type FlatteningReads, type InstanceChannelSources, + type InstancePages, } from "../domain/parameters/node-references.ts"; import { NO_MORPHS } from "../domain/presets/morph-index.ts"; import type { ParameterReadOptions, ResolveParametersOptions } from "../domain/parameters/resolve.ts"; @@ -47,6 +49,8 @@ export type ParameterResolution = Pick').par.` reads, by the same rule. */ + readonly instancePages?: InstancePages | undefined; }; /** @@ -56,7 +60,11 @@ export type ParameterResolution = Pick; +/** + * VN36 — ONE COMPONENT INSTANCE'S PUBLISHED PAGE, as a node a `.par` read can resolve. + * + * `op('rig1').par.gain` names an instance, and flattening DELETES the instance, so the flat + * graph `op()` resolves against has nothing called `rig1`. T1485b answered that for `.chan` + * (its exposed value outputs); this answers it for `.par`. The page is the instance as the + * flattener resolved it (`FlattenedGraph.instanceNodes`: its own stored slots, `parent.` + * binds already read where their scope is) and its published schema, which is what a read + * of it resolves against, per frame, through the same `targetOf` as any node — so an + * animated knob is evaluated once, at its publisher, and the reader gets a number. + * + * It is how `parent(n).par.key` reads: the flattener rewrites the read to + * `op('').par.key` (`compiler/parent-references.ts`). + * + * ⚠ A STAGE-1 BRIDGE (COMP-model proposal 01 §4). Once a component is a folder of real + * document nodes (stage 2) and linked instances are linked folders (stage 3), the COMP is a + * node in the flat graph and `nodeIdNamed` finds it; this map retires with dissolved + * instances. + */ +export interface InstancePage { + /** The instance node as flattened: id is its flat id, parameters its page. */ + readonly node: GraphNode; + /** Its published page as a schema (`publishedSchema`). */ + readonly schema: ParameterSchema; +} + +/** Instance LABEL → its page. First-wins in flat-id order, as `nodeNames` is. */ +export type InstancePages = ReadonlyMap; + /** * The channel names `op('').chan.` can complete to: the union of what the * instance's publishers carry right now, MINUS every name two of them carry — the reader @@ -273,6 +302,8 @@ export interface NodeReferenceOptions { * instance's channels are unreadable, as they were before. */ readonly instances?: InstanceChannelSources | undefined; + /** VN36: the dissolved instances `op('').par.` can name (`InstancePages`). */ + readonly pages?: InstancePages | undefined; /** * §T1674b: the channels a node's definition composes from its own parameters. Asked * BEFORE the channel resolver: they need none. @@ -494,6 +525,8 @@ export interface FlatteningReads { readonly morphs: ParameterMorphs; /** T1485b: the component instances `op('').chan.` can name. */ readonly instanceChannels: InstanceChannelSources; + /** VN36: the component instances `op('').par.` (and so `parent()`) can name. */ + readonly instancePages: InstancePages; /** * T1668b — THE SAME OBJECT FOR TWO FLATTENINGS THAT DIFFER IN VALUES ONLY, where the * producer can say so (the app's one flattening, `flattened-graph.ts`, which asks @@ -508,11 +541,14 @@ export interface FlatteningReads { /** No component instance to name. One object, so "none" is an identity check. */ export const NO_INSTANCES: InstanceChannelSources = new Map(); +/** No instance page to read (VN36). One object, so "none" is an identity check. */ +export const NO_PAGES: InstancePages = new Map(); + /** * A read with no flattening behind it: nothing fading, no instance to name. A caller that * has none says so with this, by name — there is no omitted field for it to forget. */ -export const NO_FLATTENING: FlatteningReads = { morphs: NO_MORPHS, instanceChannels: NO_INSTANCES }; +export const NO_FLATTENING: FlatteningReads = { morphs: NO_MORPHS, instanceChannels: NO_INSTANCES, instancePages: NO_PAGES }; /** * §T1551b — THE LIVE READ WORLD: what every CPU reader outside the plan resolves with — the @@ -588,7 +624,7 @@ export interface ParameterReadContext { * `parameter-read-context.test.ts` holds that no product file builds a reader any other way. */ export function parameterReadOptions(context: ParameterReadContext): ParameterReadOptions { - const { morphs, instanceChannels } = context.flattening; + const { morphs, instanceChannels, instancePages } = context.flattening; const base = { ...(context.channels === undefined ? {} : { channels: context.channels }), ...(context.frame === undefined ? {} : { frame: context.frame }), @@ -611,6 +647,7 @@ export function parameterReadOptions(context: ParameterReadContext): ParameterRe }, base, instances: instanceChannels, + pages: instancePages, declaredChannelsOf: (node) => context.registry.get(node.type)?.parameterChannels, }), ...base, @@ -833,7 +870,9 @@ function readerWithin( }; } - const targetId = nodeIdNamed(scope, options.graph, name); + // VN36: a name no flat node carries may be a dissolved instance, read through its page. + const page = nodeIdNamed(scope, options.graph, name) === undefined ? options.pages?.get(name) : undefined; + const targetId = page?.node.id ?? nodeIdNamed(scope, options.graph, name); if (targetId === undefined) { return { ok: false, kind: "node", reason: `${reference}: there is no node named "${name}"` }; } @@ -850,11 +889,11 @@ function readerWithin( reason: `${reference}: that reference is a cycle (${ringText([...visited, readKey(targetId, key)])})`, }; } - const target = options.graph.nodes[targetId]; + const target = page?.node ?? options.graph.nodes[targetId]; if (target === undefined) { return { ok: false, kind: "node", reason: `${reference}: there is no node named "${name}"` }; } - const schema = options.schemaOf(target); + const schema = page?.schema ?? options.schemaOf(target); if (schema === undefined) { return { ok: false, kind: "unknownType", reason: `${reference}: "${name}" has an unknown node type` }; } diff --git a/src/domain/parameters/test-support.ts b/src/domain/parameters/test-support.ts index 8427f5548..79d18efb5 100644 --- a/src/domain/parameters/test-support.ts +++ b/src/domain/parameters/test-support.ts @@ -1,6 +1,6 @@ import type { FrameEvaluationInput } from "../types/frame.ts"; import { authoredGraph, type GraphDocument } from "../types/graph.ts"; -import { NO_INSTANCES, parameterReadOptions, type InstanceChannelSources, type ParameterReadContext } from "./node-references.ts"; +import { NO_INSTANCES, NO_PAGES, parameterReadOptions, type InstanceChannelSources, type InstancePages, type ParameterReadContext } from "./node-references.ts"; import { NO_MORPHS, type ChannelResolver, type ParameterMorphs, type ParameterReadOptions } from "./resolve.ts"; const EMPTY_GRAPH: GraphDocument = { revision: 0, nodes: {}, edges: {}, groups: {} }; @@ -14,6 +14,8 @@ export interface TestReadContext { readonly channels?: ChannelResolver | undefined; readonly morphs?: ParameterMorphs; readonly instances?: InstanceChannelSources; + /** VN36: the instance pages `op('').par` reads. */ + readonly pages?: InstancePages; } /** @@ -30,6 +32,6 @@ export function testRead(context: TestReadContext = {}): ParameterReadOptions { registry: context.registry ?? NO_TYPES, frame: context.frame, channels: context.channels, - flattening: { morphs: context.morphs ?? NO_MORPHS, instanceChannels: context.instances ?? NO_INSTANCES }, + flattening: { morphs: context.morphs ?? NO_MORPHS, instanceChannels: context.instances ?? NO_INSTANCES, instancePages: context.pages ?? NO_PAGES }, }); } diff --git a/src/editor/controls/controls-pane.tsx b/src/editor/controls/controls-pane.tsx index f4a6c43b2..63d25a1c2 100644 --- a/src/editor/controls/controls-pane.tsx +++ b/src/editor/controls/controls-pane.tsx @@ -140,7 +140,7 @@ export function ControlsPane({ graph, registry, bus, invocation, phone, midi, ch // Authored and no fade, on purpose: the pane lists authored widgets (none inside a component, §T1143), and mid-morph a control shows its document value (§T1525b). // §T1559b: the instances `op('').chan.` can name are the flattening's, off the bus's read scope — the value graph reads them, so the display must. return resolveParameters(node, definition, parameterReadOptions({ graph: authoredGraph(current), registry, channels, - frame, flattening: { morphs: NO_MORPHS, instanceChannels: bus.readScope().flattening.instanceChannels } })).values; + frame, flattening: { morphs: NO_MORPHS, instanceChannels: bus.readScope().flattening.instanceChannels, instancePages: bus.readScope().flattening.instancePages } })).values; } }), [bus, registry, channels, latestFrame]); const apply = (operations: GraphPatchOperation[], label: string): void => { diff --git a/src/editor/inspector/inspector.tsx b/src/editor/inspector/inspector.tsx index 1d5936500..87d9f5c1d 100644 --- a/src/editor/inspector/inspector.tsx +++ b/src/editor/inspector/inspector.tsx @@ -58,6 +58,7 @@ import type { ComponentRegistryView } from "@domain/components/index.ts"; import { resolveParameters } from "./parameter-resolver.ts"; import { NO_INSTANCES, + NO_PAGES, parameterReadOptions, nodeReferenceMembers, nodeReferenceNames, @@ -664,7 +665,13 @@ export function Inspector({ * reads here as it does in the plan (T1485b). No `instanceChannels` (a test mount * with no value graph): no instance to name. */ - flattening: { morphs: NO_MORPHS, instanceChannels: instanceChannels?.() ?? NO_INSTANCES }, + // VN36: and the pages of the instances it is inside, so a `parent()` read (rewritten to + // `op('').par.` on the flat node) reads here as it does in the plan. + flattening: { + morphs: NO_MORPHS, + instanceChannels: instanceChannels?.() ?? NO_INSTANCES, + instancePages: instanceParameters?.bus.readScope().flattening.instancePages ?? NO_PAGES, + }, }); const readOptions = readOptionsAt(); diff --git a/src/tests/headless/cook-oracle.ts b/src/tests/headless/cook-oracle.ts index 58b14d28e..a5e74eca0 100644 --- a/src/tests/headless/cook-oracle.ts +++ b/src/tests/headless/cook-oracle.ts @@ -10,7 +10,7 @@ import { createDomainBus } from "../../domain/commands/index.ts"; import type { GraphPatchOperation } from "../../domain/types/patch.ts"; import { createValueGraphSession } from "../../domain/channels/value-graph.ts"; import type { ComponentRegistryView } from "../../domain/components/index.ts"; -import { NO_INSTANCES, type FlatteningReads } from "../../domain/parameters/node-references.ts"; +import { NO_INSTANCES, NO_PAGES, type FlatteningReads } from "../../domain/parameters/node-references.ts"; import { buildMorphIndex } from "../../domain/presets/morph-index.ts"; import { effectiveParameterSchema } from "../../domain/parameters/resolve.ts"; import type { FlatGraph, GraphDocument, ProjectSettings } from "../../domain/types/graph.ts"; @@ -357,6 +357,7 @@ export async function renderUnderPolicy(request: OracleRunRequest): Promise diff --git a/src/tests/headless/render-harness.ts b/src/tests/headless/render-harness.ts index 3314f60ab..493f7f0f2 100644 --- a/src/tests/headless/render-harness.ts +++ b/src/tests/headless/render-harness.ts @@ -25,7 +25,7 @@ import type { AudioFeatures } from "../../domain/types/frame.ts"; import type { FeatureTrackRecorder } from "../../domain/audio/feature-track.ts"; import type { GpuHost } from "../../runtime/backend/vgpu/gpu-host.ts"; import { analyzeChannelEntries, analyzeOperationOf, createAnalyzeChannels } from "../../runtime/execution/analyze-channels.ts"; -import { NO_INSTANCES } from "../../domain/parameters/node-references.ts"; +import { NO_INSTANCES, NO_PAGES } from "../../domain/parameters/node-references.ts"; import { createFrameDriver } from "../../runtime/execution/frame-driver.ts"; import { inferenceSourceIdFor } from "../../runtime/execution/inference-sources.ts"; import { offlineTransport } from "../../runtime/execution/offline-transport.ts"; @@ -1283,7 +1283,7 @@ export async function renderHeadless(unmeasured: HeadlessRenderRequest): Promise // T1497b: the same morph index the per-frame compile below derives, so a // recalled widget publishes the fading value here as it does live — and // (§T1559b) the instances a value node's own `op('')` can name. - flattening: { morphs, instanceChannels: flattened?.instanceChannels ?? NO_INSTANCES }, + flattening: { morphs, instanceChannels: flattened?.instanceChannels ?? NO_INSTANCES, instancePages: flattened?.instancePages ?? NO_PAGES }, // T655/T654: analyze readbacks enter the value graph here — the same // extras.channels seam `useValueGraph` threads live, number-narrowed // the same way. @@ -1321,7 +1321,7 @@ export async function renderHeadless(unmeasured: HeadlessRenderRequest): Promise if (analyze !== null) { // T1530b: Operation AT THIS FRAME, before the sample that reads its reduction. let changed = false; - const read = { frame: inputs.frame, channels, flattening: { morphs, instanceChannels: flattened?.instanceChannels ?? NO_INSTANCES } }; + const read = { frame: inputs.frame, channels, flattening: { morphs, instanceChannels: flattened?.instanceChannels ?? NO_INSTANCES, instancePages: flattened?.instancePages ?? NO_PAGES } }; const nextEntries = analyzeTracked.map((entry) => { const node = logicalGraph.nodes[entry.nodeId as keyof typeof logicalGraph.nodes]; const operation = node === undefined ? entry.operation : analyzeOperationOf(node, logicalGraph, registry(request.nodes), read); diff --git a/src/tests/integration/instance-parameter-reference.test.ts b/src/tests/integration/instance-parameter-reference.test.ts new file mode 100644 index 000000000..6cbcf5503 --- /dev/null +++ b/src/tests/integration/instance-parameter-reference.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, it } from "vitest"; + +import { compileGraphRetaining, flattenComponents, prepareFrameCompiler } from "@compiler/index.ts"; +import { testCapabilities, testSettings } from "@compiler/test-support.ts"; +import { createValueGraphSession } from "@domain/channels/value-graph.ts"; +import { componentNodeType, createComponentSystem } from "@domain/components/index.ts"; +import type { GraphComponentDefinition } from "@domain/types/components.ts"; +import type { FrameEvaluationInput } from "@domain/types/frame.ts"; +import type { GraphDocument, GraphNode } from "@domain/types/graph.ts"; +import type { StoredParameter } from "@domain/types/parameters.ts"; +import { expressionSlot } from "@/examples/documents/builders.ts"; +import { allNodeDefinitions } from "@nodes/definitions/index.ts"; +import { createNodeRegistry } from "@nodes/registry/registry.ts"; + +/** + * VN36 — `op('').par.`: a DISSOLVED instance's published page, read per frame. + * + * Flattening deletes the instance node, so the compiler's reader (over the flat graph) found + * nothing called `rig1`. The flattening now hands its pages over (`instancePages`) and the + * reader resolves the page key through its own slot, at the frame — the read `parent()` + * becomes. Real flattener, real value graph, real compiler; the GPU half is + * `parent-expressions.gpu.test.ts`. + */ + +const frameAt = (timeSeconds: number): FrameEvaluationInput => ({ + timeSeconds, + deltaSeconds: 1 / 60, + frameIndex: Math.round(timeSeconds * 60), + mode: "realtime", + randomSeed: 1, +}); + +const node = (id: string, type: string, parameters: Record, label?: string): GraphNode => + ({ id, type, definitionVersion: 1, position: { x: 0, y: 0 }, parameters, ...(label === undefined ? {} : { label }) }) as never; + +const edge = (id: string, from: readonly [string, string], to: readonly [string, string]) => ({ + id, + source: { nodeId: from[0], portId: from[1] }, + target: { nodeId: to[0], portId: to[1] }, +}); + +/** A component whose page publishes `gain` (no targets: it exists to be read) and `tint`. */ +const RIG: GraphComponentDefinition = { + componentId: "rig", + version: 1, + name: "Rig", + graph: { revision: 1, groups: {}, nodes: { hold: node("hold", "valueExpression", { expressions: "x = 1" }, "value_hold") }, edges: {} }, + inputs: [], + outputs: [], + parameters: [ + { key: "gain", definition: { type: "number", label: "Gain", default: 0.3 }, targets: [] }, + { key: "tint", definition: { type: "color", label: "Tint", space: "linear", default: [0.1, 0.2, 0.3, 1] }, targets: [] }, + ], +}; + +function document(gain: StoredParameter, amount: StoredParameter): GraphDocument { + return { + revision: 1, + groups: {}, + nodes: { + inst: node("inst", componentNodeType("rig", 1), { gain }, "rig1"), + solid: node("solid", "solid", { color: [1, 1, 1, 1] }), + fx: node("fx", "customWgsl", { amount }, "fx1"), + out: node("out", "output", {}), + }, + edges: { e0: edge("e0", ["solid", "out"], ["fx", "input"]), e1: edge("e1", ["fx", "out"], ["out", "input"]) }, + }; +} + +function request(gain: StoredParameter, amount: StoredParameter) { + const system = createComponentSystem(createNodeRegistry(allNodeDefinitions).view()); + system.components.register(RIG); + const graph = document(gain, amount); + const components = system.components.view(); + const flattened = flattenComponents({ graph, registry: system.nodes, components }); + expect(Object.keys(flattened.graph.nodes)).not.toContain("inst"); + return { system, graph, components, flattened }; +} + +/** What `customWgsl.compile` was handed for `amount` at `time`, and what the compile said about it. */ +function compiledAt(gain: StoredParameter, amount: StoredParameter, time: number) { + const { system, graph, components, flattened } = request(gain, amount); + const frame = frameAt(time); + const evaluated = createValueGraphSession(system.nodes).evaluate(flattened.graph, frame, { flattening: flattened }); + const result = compileGraphRetaining({ + graph, + settings: testSettings(), + registry: system.nodes, + capabilities: testCapabilities(), + components, + flattened, + resolution: { frame, channels: evaluated.resolver }, + }); + return { + amount: result.retained?.nodes.get("fx")?.context.parameters["amount"], + said: result.compiled.diagnostics.filter((entry) => entry.nodeId === "fx" && entry.code.startsWith("parameter.")), + }; +} + +describe("VN36 — the compiler reads op('').par.", () => { + it("reads the instance's page value, and follows it when the page changes", () => { + const read = expressionSlot("op('rig1').par.gain", 0.25); + expect(compiledAt(0.6, read, 1)).toEqual({ amount: 0.6, said: [] }); + // Cut the question the other way: another page value, another number. + expect(compiledAt(0.9, read, 1).amount).toBe(0.9); + }); + + it("evaluates an ANIMATED page knob at the frame, at its publisher", () => { + const read = expressionSlot("op('rig1').par.gain * 2", 0.25); + const knob = expressionSlot("time * 0.25", 0.3); + expect(compiledAt(knob, read, 1).amount).toBe(0.5); + expect(compiledAt(knob, read, 2).amount).toBe(1); + }); + + it("reads one component of a published compound, and refuses the compound whole by name", () => { + expect(compiledAt(0.6, expressionSlot("op('rig1').par.tint.g", 0.25), 1).amount).toBe(0.2); + const whole = compiledAt(0.6, expressionSlot("op('rig1').par.tint", 0.25), 1); + expect(whole.amount).toBe(0.25); + expect(whole.said[0]?.message).toContain("name a component"); + }); + + it("refuses a key the page does not publish, listing what it does", () => { + const missing = compiledAt(0.6, expressionSlot("op('rig1').par.gian", 0.25), 1); + expect(missing.amount).toBe(0.25); + expect(missing.said[0]?.message).toContain(`has no parameter "gian"`); + expect(missing.said[0]?.suggestion).toContain(`Nearest: "gain"`); + }); + + it("the per-frame values-only compile reads the page too, and moves with it", () => { + const read = expressionSlot("op('rig1').par.gain", 0.25); + const knob = expressionSlot("time * 0.25", 0.3); + const { system, graph, components, flattened } = request(knob, read); + const base = { graph, settings: testSettings(), registry: system.nodes, capabilities: testCapabilities(), components, flattened }; + const fast = prepareFrameCompiler(base); + expect(fast.reason).toBeNull(); + const passesAt = (time: number) => { + const frame = frameAt(time); + const channels = createValueGraphSession(system.nodes).evaluate(flattened.graph, frame, { flattening: flattened }).resolver; + const spliced = fast.compileFrame({ frame, channels }); + expect(spliced).not.toBeNull(); + // The fast path's own contract: the plan the full compile makes at this frame. + expect(spliced?.passes).toEqual(compileGraphRetaining({ ...base, resolution: { frame, channels } }).compiled.passes); + return spliced?.passes; + }; + expect(passesAt(1)).not.toEqual(passesAt(3)); + }); +}); From b04d4d7857ca4031cd5bb0b4f485fb6ab97efe1b Mon Sep 17 00:00:00 2001 From: Vincent Naples Date: Tue, 6 Oct 2026 23:19:39 -0500 Subject: [PATCH 5/5] VN36: parent(n).par.key reads the enclosing component's page, per frame MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit COMP-model proposal 01 §2.3. An expression could not read its own component's published parameter, so stage-previz-8 keeps 17 Constant "knob holders" for formulas to read. Now `parent().par.gain * 0.5 + op('lfo1').chan.value` is one expression. TD's model: `parent()` names the COMP, and `.par.key` is evaluated once, where it lives; readers get the number, not the formula. - Flatten resolves a NAME (`compiler/parent-references.ts`, beside `effectiveParameters`): `parent(n).par.key` becomes `op('').par.key`. It runs as each node's parameters are made, the instance's own page included, so a page slot T1017 carries inward keeps the `parent()` it was written with. - The reader reads that instance's page per frame (previous commit). - Same rule as §V81: only the published page is reachable. A key it does not publish, a root node, or reaching past the outermost component is refused by name (`compiler/parent-reference-unknown-key`, `-no-parent`, class never), and the parameter keeps its static (§V108). It never reads 0. - Value-graph order and liveness follow a read through the page, so a page knob reading an LFO orders its readers after it and keeps what it reads alive. T1485b's `.chan` branch no longer swallows `.par` reads. - `component.detach` rewrites `parent()` for where the copies land, by the rule it applies to `parent.` binds. What it cannot carry is said. - `parent.` binds are unchanged (VN38 migrates them). - Fixes the grammar commit's case fallthrough (lint). Gate (Dawn, parent-expressions.gpu.test.ts, through the app's commands): a Solid saved as "Lamp" with red = parent().par.gain and green = 1 - parent().par.gain, placed twice at gain 1 and 0, renders pure red and pure green. Cut the publish: both hold static black and four unknown-key warnings. An animated page knob: two frames, two colours. Red-verified (rewrite off: all three fail on the evaluator's refusal). Headless: nesting, nested page values, a carried slot, root, too deep, value-graph order, liveness, detach, each red-verified. Design and follow-ups: docs/parent-expressions-2026-10-06.md. Co-Authored-By: Claude Opus 5.5 --- docs/parent-expressions-2026-10-06.md | 136 +++++++++ src/compiler/compile.ts | 2 +- src/compiler/diagnostics.ts | 7 + src/compiler/flatten.ts | 29 +- src/compiler/parent-references.ts | 133 +++++++++ src/compiler/prune.ts | 9 + src/domain/channels/value-graph.ts | 23 +- src/domain/components/detach-values.ts | 92 +++++- src/domain/components/detach.test.ts | 49 ++++ src/domain/diagnostics/class-reasons.ts | 2 + src/domain/diagnostics/classes.ts | 2 + src/domain/expressions/evaluate.ts | 2 +- .../headless/parent-expressions.gpu.test.ts | 161 +++++++++++ .../integration/parent-expressions.test.ts | 264 ++++++++++++++++++ 14 files changed, 899 insertions(+), 12 deletions(-) create mode 100644 docs/parent-expressions-2026-10-06.md create mode 100644 src/compiler/parent-references.ts create mode 100644 src/tests/headless/parent-expressions.gpu.test.ts create mode 100644 src/tests/integration/parent-expressions.test.ts diff --git a/docs/parent-expressions-2026-10-06.md b/docs/parent-expressions-2026-10-06.md new file mode 100644 index 000000000..e9bad374d --- /dev/null +++ b/docs/parent-expressions-2026-10-06.md @@ -0,0 +1,136 @@ +# `parent()` in expressions (VN36) + +COMP-model proposal 01 §2.3 and proposal 02 (the `parent.` row). Stacked on VN35 +(`a5c77599`). + +## What it is + +``` +parent().par.gain * 0.5 + op('lfo_wobble').chan.value +parent(2).par.throw two components out +parent().par.tint.r one component of a published compound (§V113) +``` + +`parent()` is `parent(1)`, and `n` is a positive integer literal. After `parent(n)` the +grammar takes `.par.` with an optional `.`, and nothing else. That is +checked at parse time, so `parent().chan.x` and `parent(0)` are syntax errors that say what +to write. A bare `parent` is still a variable name; only `parent(` changes meaning. + +The AST gains `{ kind: "parentRef", hops, path, at, end }`. The span is a pure function of +the text, so the parse memo (T1172) still holds. The three exhaustive walks over +`ExpressionAst` handle the new node. A `parentRef` is not an `op()` dependency in the +authored document (§V81: a lexical read, never an edge). Reaching the evaluator unrewritten +means the expression is not inside a component, and it fails as `reference.unreadable` with +that reason. It never reads 0. + +## How it reads: a name at flatten, a value per frame + +This follows TouchDesigner. `parent()` returns the parent COMP, its `.par.Gain` evaluates +once where it lives, and readers get the number. They never get the formula. + +1. **Flatten resolves a name** (`src/compiler/parent-references.ts`, called beside + `effectiveParameters`). `parent(n).par.key` becomes + `op('').par.key`. It runs as each node's parameters are made, + including an instance's own page. That ordering matters for T1017: an animated page slot + is carried INWARD onto its targets as text, and a `parent()` inside it means the component + around the instance. Resolved here, it is carried as a name, which means the same thing + at every depth. In VN35's end-of-walk pass it would be resolved one level too deep (a + test pins this). +2. **The reader reads a dissolved instance's page** (`node-references.ts`). Flattening + deletes the instance node. Its page survives as `FlattenedGraph.instancePages` (label → + the instance as flattened, plus its published schema), and `op('').par.` + resolves there through the same `targetOf` as any node. This is T1485b's shape for + `.chan`, applied to `.par`. So an animated knob is evaluated once per frame at its + publisher, and an edit to it reaches every reader with the next flattening. + `flattenComponents` stays a pure function of the document (§V529). + +Same rule as §V81: the read goes through the published page (§V80) and only that. A value +set on a nested instance's page, or on a private nested page, is read exactly where it is +set. `publishedKeyOrigins` is not involved. + +As a side effect, `op('comp1').par.gain` from OUTSIDE a component is readable too. That is +TD's idiom. + +### What sees the page + +- **`FlatteningReads.instancePages` is required** (T1551b's rule). Every reader site says it: + the compile and the per-frame compile (beside `resolution.instances`), the value graph, the + OSC pump, parameter commands, the controls pane, the inspector (the root flattening's + pages while you are inside an instance), and the test harnesses. +- **Value-graph order.** The dependency walk follows `op('').par.` into the + page and on to whatever the page knob reads. A Constant inside a component that reads a + page knob reading a root LFO therefore evaluates after the LFO in the same frame, not one + frame late. (T1485b's `.chan` branch had been catching `.par` reads of an instance name + too. It is now channel-only.) +- **Liveness.** `pruneToActiveSinks` adds each page as a liveness node that is never a + candidate, so a node read only by a page knob, through `parent()`, is not reported dead. + +## Diagnostics + +Both are warnings, and both fall back to the slot's retained static (§V108), exactly as a +failing `parent.` bind does. One problem gives one diagnostic, and the value is never 0. +Class `never`. + +| code | when | +|---|---| +| `compiler/parent-reference-no-parent` | `parent()` on a root node, `parent(n)` past the outermost component, or an enclosing instance with no name | +| `compiler/parent-reference-unknown-key` | the component publishes no `key`. Lists what it does publish, with the nearest spelling | + +A component name the page lacks, or a compound read whole, is refused per frame by the +reader, like any `op()` read. At the root, `flatteningIsIdentity` treats a `parent()` read as +it treats a `parent.` bind: it takes the full walk, so the diagnostic is raised. + +## Detach + +`component.detach` lands the copies at the instance's own level. `parent(n ≥ 2)` loses one +hop. `parent().par.k` becomes what the page key is from that level: +- its carried `parent.` source, re-aimed as a `parent()` read; +- the instance's own expression for it, inlined (it was written at that very level); +- or its value. + +A read the copies cannot make the same way is reported (`component.detach.inexact`), and +the copy holds its static. `nestedParentReads` counts `parent(n)` too. + +## Unchanged + +- `parent.` binds keep their current behaviour. That includes the fact that a bind + BAKES the page value, so an animated knob does not animate through a bind; only the §V80 + fan-out and now `parent()` carry it live. VN38 migrates binds. +- Reference cycles (§V152). A ring through the boundary (a page knob reads an inner node + that reads `parent()`) is a plain `(node, key)` ring for the reader's guard, which names + it at runtime. The authoring-time refusal does not see it yet. +- Rename (§V128). `parent()` names no node. The rewritten name is a flattening artifact and + is never stored. + +## Stage-1 bridge + +`instancePages`, the value-graph look-through and the liveness entries exist because the +instance is dissolved. Once a COMP is a real node in the flat graph (proposal 01 stages 2–3), +the name index finds it and they retire together. The grammar, the rewrite to a name, and +the diagnostics are permanent. + +## Tests + +- Dawn (`parent-expressions.gpu.test.ts`), through the app's commands: Lamp (a Solid, red = + `parent().par.gain`, green = `1 - parent().par.gain`), placed twice with gain 1 and 0, + renders pure red and pure green. With the publish cut, both instances render their static + black and raise four `unknown-key` warnings. An animated page knob (`frame % 2`) gives two + frames and two colours. +- Integration (`parent-expressions.test.ts`): two instances; animated; cut; misspelt key; + `parent(2)`; a nested page value; a nested page that itself reads `parent()`; a page slot + carried inward (T1017); too deep; root; value-graph order; liveness. +- Reader (`instance-parameter-reference.test.ts`): page value, animated, a component, an + unknown key, and the per-frame values-only compile against the full compile. +- Grammar (`parent-reads.test.ts`), detach (`detach.test.ts`). +- Every gate red-verified by editing the code and restoring it. + +## Next + +- VN60: delete stage-previz-8's 17 knob holders onto `parent()`. +- Preset morphs through `parent()`: the reader resolves the page node by its flat id, and + the morph index keys a root instance's fade by that same id, so it should fade. No test + pins it yet. +- Completion: offer `parent().par.` keys, and `op('').par.` keys (§V150 allows + offering less than the reader accepts, and this does). +- Authoring-time refusal of a ring through the boundary. +- VN38 (two-way bind) and VN43 (`parent.Name` shortcuts). diff --git a/src/compiler/compile.ts b/src/compiler/compile.ts index e5240d405..65da320e3 100644 --- a/src/compiler/compile.ts +++ b/src/compiler/compile.ts @@ -1096,7 +1096,7 @@ export function compileGraphRetaining(request: CompileRequest): CompileGraphResu const [width, height] = previewTargetSize(); return width / height; }; - const { kept, pruned } = pruneToActiveSinks(validated.nodes, validated.edges, sinkResolution.sinks); + const { kept, pruned } = pruneToActiveSinks(validated.nodes, validated.edges, sinkResolution.sinks, instancePages); diagnostics.push(...validateRequiredInputs(validated.nodes, validated.edges, kept)); // 3. temporal split, cycle rejection, ordering (T25, §V4) diff --git a/src/compiler/diagnostics.ts b/src/compiler/diagnostics.ts index 37334012f..de6f31d6d 100644 --- a/src/compiler/diagnostics.ts +++ b/src/compiler/diagnostics.ts @@ -60,6 +60,13 @@ export const CompilerDiagnosticCode = { * names the intended copy is the fix (proposal 01 §2.2). */ referenceCrossScope: "compiler/reference-cross-scope", + /** + * VN36: a `parent()` read with no component to reach: on a root node, past the outermost + * component, or naming an instance with no name. The parameter keeps its static (§V108). + */ + parentReferenceNoParent: "compiler/parent-reference-no-parent", + /** VN36: a `parent()` read of a key the component's page does not publish (§V81). */ + parentReferenceUnknownKey: "compiler/parent-reference-unknown-key", /** * T546: more than one renderer frames itself with this camera, so "what the renderer * sees" has no single answer and the preview shows the stock reference scene. INFO, not diff --git a/src/compiler/flatten.ts b/src/compiler/flatten.ts index 1b4b8e95d..878bd2eec 100644 --- a/src/compiler/flatten.ts +++ b/src/compiler/flatten.ts @@ -51,6 +51,8 @@ import type { ActiveSink } from "./types.ts"; import { COMPONENT_ID_SEPARATOR, flattenedNodeId } from "../domain/components/internal-resolutions.ts"; import type { NameScope } from "../domain/components/addressing.ts"; import { resolvePathReferences } from "./path-references.ts"; +import { resolveParentReferences, type EnclosingInstance } from "./parent-references.ts"; +import { parentReadsOf } from "../domain/expressions/index.ts"; import { applyInstance } from "../domain/components/apply-instance.ts"; import { isDefaultChannelMask } from "../domain/types/graph.ts"; export { COMPONENT_ID_SEPARATOR, flattenedNodeId } from "../domain/components/internal-resolutions.ts"; @@ -337,9 +339,9 @@ interface LevelResult { * needs it. (It is read in exactly one place: the `parent.` driver loop in * `effectiveParameters`. With no drivers, nothing reads it.) * - * ## The three things that make the walk NOT the identity + * ## The four things that make the walk NOT the identity * - * All three are checked, and any of them sends the document down the full walk: + * All four are checked, and any of them sends the document down the full walk: * * 1. a COMPONENT INSTANCE — the whole point of the walk; * 2. `state.parentBindings` on a node — at the root there is no parent scope, so @@ -349,6 +351,8 @@ interface LevelResult { * reading a value that no longer exists with nothing said; * 3. a `bind`-mode slot whose ref starts `parent.` — the same case through §V107's * slot, where the walk warns and falls back to §V108's retained static. + * 4. a `parent()` read in an expression (VN36) — the same case again, through the grammar, + * and the same answer: `compiler/parent-reference-no-parent` and the retained static. * * §V83's recursion detector is skipped with them, and provably: it walks the document's * component references, and a document with no instance has none. @@ -368,6 +372,14 @@ function flatteningIsIdentity(graph: GraphDocument): boolean { const binding = stored.bindings.bind; if (binding?.kind === "bind" && binding.ref.startsWith("parent.")) return false; } + // VN36 — 4. a `parent()` read in an active expression: at the root it has no parent, and + // the walk is what says so. + for (const key of Object.keys(node.parameters ?? {})) { + const stored = node.parameters?.[key]; + if (!isParameterSlot(stored) || stored.mode !== "expression") continue; + const binding = stored.bindings.expression; + if (binding?.kind === "expression" && parentReadsOf(binding.source).length > 0) return false; + } } return true; } @@ -711,6 +723,11 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { const levelGraph = withUniqueNames(input.graph); if (!scopes.has(input.prefix)) scopes.set(input.prefix, { parent: undefined, label: undefined, names: new Map() }); const scope = buildParentScope(input.chain); + /** VN36: the instances around this level, outermost first, as a `parent()` read sees them. */ + const parents: EnclosingInstance[] = input.path.map((instanceId) => ({ + label: instanceNodes.get(instanceId)?.label, + schema: pageSchemas.get(instanceId), + })); const grouped = overridesByNode(input.overrides); const origins = originsByNode(input.origins); /** Raw instance id -> the boundary of the subgraph it expanded into. */ @@ -742,7 +759,13 @@ export function flattenComponents(request: FlattenRequest): FlattenedGraph { // T1524b: the root parameters this node's values came from — the published fan-out // (§V80) and, beside it, every `parent.` read `effectiveParameters` resolves. const publishedFrom: Record = { ...origins.get(nodeId) }; - const parameters = effectiveParameters(node, schema, grouped.get(nodeId) ?? {}, scope, flatId, input.scopeOrigins, publishedFrom); + // VN36: and every `parent()` read becomes an `op()` read of the instance it names, here, + // before an instance's page is carried inward (T1017). See `parent-references.ts`. + const parameters = resolveParentReferences( + effectiveParameters(node, schema, grouped.get(nodeId) ?? {}, scope, flatId, input.scopeOrigins, publishedFrom), + parents, + (diagnostic) => report(diagnostic, flatId), + ); const resolved: GraphNode = { ...node, id: flatId, parameters }; if (instance !== null) { diff --git a/src/compiler/parent-references.ts b/src/compiler/parent-references.ts new file mode 100644 index 000000000..56ead9236 --- /dev/null +++ b/src/compiler/parent-references.ts @@ -0,0 +1,133 @@ +import { formatParentRead, parentReadsOf, rewriteParentReads, type ParentRead } from "../domain/expressions/index.ts"; +import { nearestSpelling } from "../domain/expressions/index.ts"; +import { isParameterSlot, storedStaticValue } from "../domain/parameters/slots.ts"; +import type { RuntimeDiagnostic } from "../domain/types/diagnostics.ts"; +import type { ParameterSchema, StoredParameter } from "../domain/types/parameters.ts"; +import { CompilerDiagnosticCode, compilerDiagnostic } from "./diagnostics.ts"; + +/** + * VN36 — `parent(n).par.key` BECOMES `op('').par.key`, here. + * + * The per-frame evaluator runs on the flat graph, where no node knows which component it was + * in, so a `parent()` read is resolved where the scope exists: in the flattener, level by + * level. What it resolves to is a NAME, not a value. The instance is dissolved, and its page + * survives as `FlattenedGraph.instancePages`, which the `op()` reader reads per frame + * (`node-references.ts`). So an animated knob is evaluated once, at its publisher, an edit to + * it reaches every reader with the next flattening, and this walk stays a pure function of + * the document (§V529). + * + * The same rule as §V81: the read goes through the published page (§V80) and only that. A key + * the page does not publish is refused HERE, where the page is known, rather than per frame. + * + * WHY HERE AND NOT IN VN35'S PASS (`path-references.ts`), which runs once over the finished + * flattening. A page slot that animates is carried INWARD onto its targets (T1017) before + * that pass runs, and a `parent()` in it means the component around the INSTANCE. Carried + * as text, it would be resolved from the target's scope, one level too deep. Resolved here, + * as the instance's own parameters are made, it is carried as a name, which means the same + * thing at every depth. + * + * A read that resolves nothing is reported and the parameter falls back to its retained + * static value (§V108), exactly as a failing `parent.` bind does in `effectiveParameters`: + * one problem, one diagnostic, never a read of 0. + */ + +/** One enclosing instance, as a `parent()` read from inside it sees it. */ +export interface EnclosingInstance { + /** Its name in the flattening: what `op()` and `instancePages` know it by. */ + readonly label: string | undefined; + /** Its published page, or undefined when its component is not installed. */ + readonly schema: ParameterSchema | undefined; +} + +/** + * `parameters` with every active expression's `parent()` reads rewritten against `chain` + * (the enclosing instances, OUTERMOST FIRST, the last owning the node). Returns the record + * it was given when nothing reads `parent()`. + */ +export function resolveParentReferences( + parameters: Record, + chain: readonly EnclosingInstance[], + report: (diagnostic: RuntimeDiagnostic) => void, +): Record { + let rewritten: Record | undefined; + for (const key of Object.keys(parameters).sort()) { + const stored = parameters[key]; + if (stored === undefined || !isParameterSlot(stored) || stored.mode !== "expression") continue; + const binding = stored.bindings.expression; + if (binding?.kind !== "expression") continue; + const reads = parentReadsOf(binding.source); + if (reads.length === 0) continue; + + const refusal = reads.map((read) => refusalOf(read, chain)).find((each) => each !== undefined); + rewritten ??= { ...parameters }; + if (refusal !== undefined) { + report( + compilerDiagnostic("warning", refusal.code, `"${key}" reads ${formatParentRead(refusal.read)}: ${refusal.message}`, { + suggestion: `${refusal.suggestion} Until then "${key}" holds its static value (§V108).`, + }), + ); + const retained = storedStaticValue(stored); + if (retained === undefined) delete rewritten[key]; + else rewritten[key] = retained; + continue; + } + const source = rewriteParentReads(binding.source, (read) => { + const owner = chain[chain.length - read.hops]; + return `op('${owner?.label ?? ""}').${["par", read.key, ...(read.component === undefined ? [] : [read.component])].join(".")}`; + }); + rewritten[key] = { ...stored, bindings: { ...stored.bindings, expression: { kind: "expression", source } } }; + } + return rewritten ?? parameters; +} + +interface Refusal { + readonly read: ParentRead; + readonly code: (typeof CompilerDiagnosticCode)["parentReferenceNoParent" | "parentReferenceUnknownKey"]; + readonly message: string; + readonly suggestion: string; +} + +function refusalOf(read: ParentRead, chain: readonly EnclosingInstance[]): Refusal | undefined { + if (chain.length === 0) { + return { + read, + code: CompilerDiagnosticCode.parentReferenceNoParent, + message: "this node is not inside a component, so there is no parent to read.", + suggestion: "Move the node into a component, or read the parameter by name with op('').par..", + }; + } + if (read.hops > chain.length) { + return { + read, + code: CompilerDiagnosticCode.parentReferenceNoParent, + message: `this node is ${chain.length} component${chain.length === 1 ? "" : "s"} deep, so parent(${read.hops}) reaches past the outermost one.`, + suggestion: `Count from 1 for the component the node is in, up to parent(${chain.length}).`, + }; + } + const owner = chain[chain.length - read.hops]; + if (owner === undefined || owner.label === undefined) { + return { + read, + code: CompilerDiagnosticCode.parentReferenceNoParent, + message: "the component instance it names has no name to read it by.", + suggestion: "Name the instance.", + }; + } + // An uninstalled component is reported where it stands (`component-missing`), and nothing + // inside it flattens, so there is no read from inside it to refuse. + const schema = owner.schema ?? {}; + if (!Object.hasOwn(schema, read.key)) { + const published = Object.keys(schema).sort(); + const near = nearestSpelling(read.key, published); + return { + read, + code: CompilerDiagnosticCode.parentReferenceUnknownKey, + message: `the component "${owner.label}" publishes no parameter "${read.key}"${published.length === 0 ? " (it publishes none)" : ""}.`, + suggestion: + published.length === 0 + ? `Publish "${read.key}" on the component.` + : `${near === null ? "" : `Nearest: "${near}". `}It publishes: ${published.join(", ")}.`, + }; + } + return undefined; +} diff --git a/src/compiler/prune.ts b/src/compiler/prune.ts index 93c95b750..aba28e638 100644 --- a/src/compiler/prune.ts +++ b/src/compiler/prune.ts @@ -2,6 +2,7 @@ import type { NodeId } from "../domain/types/ids.ts"; import type { RuntimeDiagnostic } from "../domain/types/diagnostics.ts"; import type { NodeDefinition } from "../domain/types/node-definition.ts"; import { computeLiveness, isValueSourceDefinition, type LivenessNode } from "../domain/graph/liveness.ts"; +import { NO_PAGES, type InstancePages } from "../domain/parameters/node-references.ts"; import { CompilerDiagnosticCode, compilerDiagnostic } from "./diagnostics.ts"; import type { ActiveSink, CompileEdge } from "./types.ts"; import type { ResolvedNode } from "./validate.ts"; @@ -176,6 +177,8 @@ export function pruneToActiveSinks( nodes: ReadonlyMap, edges: ReadonlyArray, sinks: ReadonlyArray, + /** VN36: the dissolved instances' pages, which `op('').par` (and `parent()`) reads. */ + pages: InstancePages = NO_PAGES, ): PruneResult { const producers = new Map(); for (const edge of edges) { @@ -211,6 +214,12 @@ export function pruneToActiveSinks( isSink: false, // seeds come from the resolved ACTIVE sinks below, not the manifest }); } + // VN36: a page is read like a node (`op('').par.`, what `parent()` becomes), + // so what ITS knobs read is read too. Never a candidate itself: it has no GPU work. + for (const page of pages.values()) { + if (livenessNodes.has(page.node.id)) continue; + livenessNodes.set(page.node.id, { name: page.node.label, parameters: page.node.parameters, isValueSource: true, isSink: false }); + } const { dead } = computeLiveness(livenessNodes, producers, [...kept].sort()); return { kept, pruned: dead }; } diff --git a/src/domain/channels/value-graph.ts b/src/domain/channels/value-graph.ts index 33b263ddf..c11dc84eb 100644 --- a/src/domain/channels/value-graph.ts +++ b/src/domain/channels/value-graph.ts @@ -1,4 +1,4 @@ -import type { FlatGraph } from "../types/graph.ts"; +import type { FlatGraph, GraphNode } from "../types/graph.ts"; import type { NodeId, PortId } from "../types/ids.ts"; import type { AudioFeatures, FrameEvaluationInput } from "../types/frame.ts"; import type { RuntimeDiagnostic } from "../types/diagnostics.ts"; @@ -221,13 +221,21 @@ export function createValueGraphSession(registry: NodeRegistryView): ValueGraphS * from, and it is ordered after them like any other, or a reader whose id sorts * first reads a bag that is not published yet. The instances are the flattening's * own, so they are as fixed as the graph this memo is keyed on. + * + * VN36: `op('').par.` (what `parent()` becomes) names no node either. + * The read is of the instance's PAGE, which the walk follows like any node's + * parameter, so a page knob reading `op('lfo1').chan.value` orders its readers after + * `lfo1`. Without it the reader evaluates before the LFO and lags a frame. */ const named = nodeNames(graph); + const pages = new Map(); + for (const page of flattening.instancePages.values()) pages.set(page.node.id, page.node); + const nodeOf = (id: NodeId): GraphNode | undefined => graph.nodes[id] ?? pages.get(id); const readsByNode = new Map(); const readsOf = (owner: NodeId): readonly KeyRead[] => { const known = readsByNode.get(owner); if (known !== undefined) return known; - const reads = keyReads(graph.nodes[owner]?.parameters ?? {}); + const reads = keyReads(nodeOf(owner)?.parameters ?? {}); readsByNode.set(owner, reads); return reads; }; @@ -245,7 +253,7 @@ export function createValueGraphSession(registry: NodeRegistryView): ValueGraphS const id = `${owner}\u0000${key ?? ""}`; if (visited.has(id) || visited.has(`${owner}\u0000`)) continue; visited.add(id); - const ownerNode = graph.nodes[owner]; + const ownerNode = nodeOf(owner); if (ownerNode === undefined) continue; // A legacy `driven` slot names a channel outright. for (const driven of bindingTargets(ownerNode.parameters)) { @@ -256,7 +264,7 @@ export function createValueGraphSession(registry: NodeRegistryView): ValueGraphS } for (const read of readsOf(owner)) { if (key !== null && read.from !== key) continue; - const instance = read.node === null ? undefined : flattening.instanceChannels.get(read.node); + const instance = read.node === null || read.kind !== "channel" ? undefined : flattening.instanceChannels.get(read.node); if (instance !== undefined) { for (const source of instance) { const publisher = named.get(source.publisher); @@ -264,8 +272,11 @@ export function createValueGraphSession(registry: NodeRegistryView): ValueGraphS } continue; } - const to = read.node === null ? owner : named.get(read.node); - const toNode = to === undefined ? undefined : graph.nodes[to]; + const to = + read.node === null + ? owner + : (named.get(read.node) ?? (read.kind === "parameter" ? flattening.instancePages.get(read.node)?.node.id : undefined)); + const toNode = to === undefined ? undefined : nodeOf(to); if (to === undefined || toNode === undefined) continue; if (read.kind === "parameter") { pending.push([to, read.key]); diff --git a/src/domain/components/detach-values.ts b/src/domain/components/detach-values.ts index 8e9d75b64..5e72a72a4 100644 --- a/src/domain/components/detach-values.ts +++ b/src/domain/components/detach-values.ts @@ -3,7 +3,8 @@ import type { GraphDocument, GraphNode } from "../types/graph.ts"; import type { NodeId } from "../types/ids.ts"; import type { ParameterDefinition, ParameterSchema, StoredParameter } from "../types/parameters.ts"; import { numericRangeOf } from "../parameters/expression-range.ts"; -import { isParameterSlot, parseComponentKey, storedStaticValue, withBinding } from "../parameters/slots.ts"; +import { formatParentRead, parentReadsOf, rewriteParentReads, type ParentRead } from "../expressions/index.ts"; +import { componentNamesFor, isParameterSlot, parseComponentKey, storedStaticValue, withBinding } from "../parameters/slots.ts"; import type { AppliedInstance } from "./apply-instance.ts"; import { PARENT_BINDINGS_STATE_KEY, internalParameterPath, parseInternalParameterPath, readComponentInstance, readParentBindings } from "./instance.ts"; import { buildParentScope, formatParentReference, parentBindResolver, parentScopeDrivers, parseParentReference } from "./parent-scope.ts"; @@ -58,6 +59,12 @@ import { publishedSchema } from "./published-page.ts"; * session an outer published knob that drove a page key drives the copies instead * (`MovedOuterTarget`; a one-hop read of that key becomes `parent.`). * + * A `parent()` read in an EXPRESSION inside the definition (VN36) follows the same rule: + * `parent(n)` past the instance loses one hop, and `parent().par.k` becomes what the page key + * is from the copies' level — its carried source re-aimed as a `parent()` read, the instance's + * own expression for it inlined, or its value. One the copies cannot read the same way is + * said (`inexact`) and the copy holds its static. + * * Nested instances inside the definition stay instances: their pages are written by the * rules above and keep driving their own internals. A ref inside a NESTED definition that * reaches past its own component cannot be rewritten without editing that shared @@ -151,6 +158,14 @@ type Carry = | { readonly kind: "legacy"; readonly ref: string } | { readonly kind: "outer"; readonly keys: readonly string[] }; +/** VN36: the furthest `parent(n)` an active expression slot reads, or 0. */ +function expressionParentHops(stored: StoredParameter | undefined): number { + if (!isParameterSlot(stored) || stored.mode !== "expression") return 0; + const binding = stored.bindings.expression; + if (binding?.kind !== "expression") return 0; + return Math.max(0, ...parentReadsOf(binding.source).map((read) => read.hops)); +} + /** The ref of a `bind`-mode slot reading `parent.*`, or undefined. */ function parentBindRef(stored: StoredParameter | undefined): string | undefined { if (!isParameterSlot(stored) || stored.mode !== "bind") return undefined; @@ -254,6 +269,54 @@ export function detachedValues(input: DetachedValuesInput): DetachedValues { const carriedRef = (carry: Exclude): string => carry.kind === "legacy" ? carry.ref : formatParentReference({ hops: 1, key: carry.keys[carry.keys.length - 1] as string }); + /** + * VN36 — what one `parent()` read in a copied node becomes, from the level the copies land + * at (the instance's own), or undefined when no expression there reads the same number. + * Past the instance, one `parent` fewer, as a bind loses one `parent.`. One hop read the + * instance's page, which is gone: a page key set from outside re-aims at that source, the + * instance's own expression for it is inlined (it was written at this very level), and a + * value is written as one. + */ + const pageRead = (read: ParentRead): string | undefined => { + if (read.hops > 1) return formatParentRead({ ...read, hops: read.hops - 1 }); + const definitionOfKey = schema[read.key]; + if (definitionOfKey === undefined) return undefined; + const carry = carriedByKey.get(read.key); + if (carry !== undefined) { + const reference = parseParentReference(carry.kind === "slot" ? (parentBindRef(carry.slot) ?? "") : carriedRef(carry)); + return reference === null ? undefined : formatParentRead({ hops: reference.hops, key: reference.key, component: read.component }); + } + const own = instance.parameters[read.key]; + if (isParameterSlot(own) && own.mode === "expression" && own.bindings.expression?.kind === "expression") { + return read.component === undefined ? `(${own.bindings.expression.source})` : undefined; + } + const value = page.values[read.key]; + const components = componentNamesFor(definitionOfKey); + const number = + read.component === undefined + ? value + : Array.isArray(value) && components !== null + ? (value as readonly unknown[])[components.indexOf(read.component)] + : undefined; + if (typeof number === "boolean") return number ? "1" : "0"; + return typeof number === "number" && Number.isFinite(number) ? `(${number})` : undefined; + }; + + // VN36: the reads no copy can make, said NOW — `inexact` is read before any copy is made. + for (const internalId of Object.keys(definition.graph.nodes).sort()) { + const internal = definition.graph.nodes[internalId] as GraphNode; + const fannedHere = new Set((byNode.get(internalId) ?? []).map(([key]) => key)); + for (const key of Object.keys(internal.parameters).sort()) { + const stored = internal.parameters[key]; + if (fannedHere.has(key) || !isParameterSlot(stored) || stored.mode !== "expression") continue; + const binding = stored.bindings.expression; + if (binding?.kind !== "expression") continue; + const unreadable = parentReadsOf(binding.source).find((read) => pageRead(read) === undefined); + if (unreadable === undefined) continue; + inexact.push(`"${look}"'s ${internal.label ?? internalId}.${key} reads ${formatParentRead(unreadable)}, which the copies cannot read the same way; they hold its static value`); + } + } + const copy = (internalId: NodeId, node: GraphNode): { node: GraphNode; baked: number; moved: MovedOuterTarget[] } => { let baked = 0; const moved: MovedOuterTarget[] = []; @@ -309,6 +372,31 @@ export function detachedValues(input: DetachedValuesInput): DetachedValues { else parameters[key] = retained; } + // VN36: `parent()` reads in the copy's own expressions, rewritten for where the copies land. + for (const key of Object.keys(parameters).sort()) { + const stored = parameters[key]; + if (!isParameterSlot(stored) || stored.mode !== "expression" || fannedKeys.has(key)) continue; + const binding = stored.bindings.expression; + if (binding?.kind !== "expression" || parentReadsOf(binding.source).length === 0) continue; + let unreadable: string | undefined; + let fromPage = false; + const source = rewriteParentReads(binding.source, (read) => { + fromPage ||= read.hops === 1; + const rewritten = pageRead(read); + if (rewritten === undefined) unreadable ??= formatParentRead(read); + return rewritten; + }); + if (unreadable !== undefined) { + // Said up front (below `pageRead`): the command reads `inexact` before it copies. + const retained = storedStaticValue(stored); + if (retained === undefined) delete parameters[key]; + else parameters[key] = retained; + continue; + } + parameters[key] = withBinding(stored, { kind: "expression", source }); + if (fromPage) baked += 1; + } + // Legacy `state.parentBindings` (§V81), after the slots, as flattening orders them. const bindings = readParentBindings(node); const kept: Record = {}; @@ -372,6 +460,8 @@ export function nestedParentReads( ...Object.values(readParentBindings(node)), ]; if (refs.some((ref) => ref !== undefined && (parseParentReference(ref)?.hops ?? 0) > depth)) return true; + // VN36: and a `parent(n)` read in an expression, by the same count. + if (Object.values(node.parameters).some((stored) => expressionParentHops(stored) > depth)) return true; const nested = readComponentInstance(node) === null ? undefined : definitionOf(node); return nested !== undefined && readsPast(nested.graph, depth + 1); }); diff --git a/src/domain/components/detach.test.ts b/src/domain/components/detach.test.ts index d408b317f..86796ded9 100644 --- a/src/domain/components/detach.test.ts +++ b/src/domain/components/detach.test.ts @@ -725,3 +725,52 @@ describe("T1545b — an in-session detach names the root and catalogue paths it ]); }); }); + +/** + * VN36 — a `parent()` read in an expression inside the definition. The copies land at the + * instance's own level, where `parent()` means the component AROUND the instance, so detach + * rewrites each read by the rule it applies to `parent.` binds. + */ +describe("VN36 — detach rewrites parent() reads for where the copies land", () => { + const expression = (source: string, retained: number) => slot("expression", { kind: "expression", source }, retained); + function reader(): GraphComponentDefinition { + const base = look(); + return { + ...base, + componentId: "reader", + name: "Reader", + graph: graphOf([ + node("blurA", "test.blur", {}, { label: "blurA", position: { x: 0, y: 0 }, parameters: { radius: expression("parent().par.soft * 2", 1) } }), + node("deep", "test.blur", {}, { label: "deep", position: { x: 100, y: 0 }, parameters: { radius: expression("parent(2).par.gain + 1", 3) } }), + node("green", "test.blur", {}, { label: "green", position: { x: 200, y: 0 }, parameters: { radius: expression("parent().par.tint.g", 2) } }), + ]), + parameters: base.parameters.map((each) => ({ ...each, targets: [] })), + }; + } + const radiusOf = (detached: Detached, id: string) => detached.copies[id]?.parameters["radius"]; + + it("a page VALUE is written as a number; parent(2) loses one hop; a component reads its channel", async () => { + const detached = await detach({ ...instanceOf("reader", { ...PAGE }) }, [reader()]); + expect(radiusOf(detached, "blurA")).toEqual(expression("(6) * 2", 1)); + expect(radiusOf(detached, "deep")).toEqual(expression("parent().par.gain + 1", 3)); + expect(radiusOf(detached, "green")).toEqual(expression("(0.2)", 2)); + }); + + it("an ANIMATED page key inlines the instance's own expression, written at this very level", async () => { + const detached = await detach(instanceOf("reader", { ...PAGE, soft: expression("time", 4) }), [reader()]); + expect(radiusOf(detached, "blurA")).toEqual(expression("(time) * 2", 1)); + }); + + it("a page key bound to parent. re-aims at that source as a parent() read", async () => { + const detached = await detach(instanceOf("reader", { ...PAGE, soft: bindSlot("parent.level", 7) }), [reader()]); + expect(radiusOf(detached, "blurA")).toEqual(expression("parent().par.level * 2", 1)); + }); + + it("a read the copies cannot make is said, and the copy holds its static", async () => { + const missing = reader(); + missing.graph.nodes["blurA"] = { ...missing.graph.nodes["blurA"]!, parameters: { radius: expression("parent().par.nothing", 1) } }; + const detached = await detach(instanceOf("reader", { ...PAGE }), [missing]); + expect(radiusOf(detached, "blurA")).toBe(1); + expect(detached.messages.map((each) => each.message).join("\n")).toContain("parent().par.nothing"); + }); +}); diff --git a/src/domain/diagnostics/class-reasons.ts b/src/domain/diagnostics/class-reasons.ts index 7c904a177..f8108c8fa 100644 --- a/src/domain/diagnostics/class-reasons.ts +++ b/src/domain/diagnostics/class-reasons.ts @@ -94,6 +94,8 @@ export const DIAGNOSTIC_CLASS_REASONS: Readonly> = { "compiler/port-incompatible": "two port types with no conversion between them", "compiler/port-missing": "an edge on a port the type does not declare", "compiler/port-occupied": "a second wire into a single input is ignored", + "compiler/parent-reference-no-parent": "a parent() read with no component around the node to reach", + "compiler/parent-reference-unknown-key": "a parent() read of a key the component does not publish", "compiler/reference-cross-scope": "a bare name that reaches into an instance binds as stored; a path says which copy", "compiler/resolution-clamped": "scaled down to the limit in force", "compiler/resolution-custom": "the project resolution stands in for a custom policy", diff --git a/src/domain/diagnostics/classes.ts b/src/domain/diagnostics/classes.ts index f0c437a85..d4a6f8a23 100644 --- a/src/domain/diagnostics/classes.ts +++ b/src/domain/diagnostics/classes.ts @@ -145,6 +145,8 @@ export const DIAGNOSTIC_CLASSES: Readonly> = "compiler/port-incompatible": { class: "never" }, "compiler/port-missing": { class: "never" }, "compiler/port-occupied": { class: "never" }, + "compiler/parent-reference-no-parent": { class: "never" }, + "compiler/parent-reference-unknown-key": { class: "never" }, "compiler/reference-cross-scope": { class: "advice" }, "compiler/resolution-clamped": { class: "degraded" }, "compiler/resolution-custom": { class: "degraded" }, diff --git a/src/domain/expressions/evaluate.ts b/src/domain/expressions/evaluate.ts index 86e38b24b..a87eace85 100644 --- a/src/domain/expressions/evaluate.ts +++ b/src/domain/expressions/evaluate.ts @@ -1040,7 +1040,7 @@ function evaluateNode( // VN36: the flattener rewrites every one inside a component to an `op()` read of the // instance it names, so one that gets here is outside any. A number here would be one // that looks like an answer. - fail("reference.unreadable", `parent() reads a published parameter of the component a node is in, and this expression is not inside one`, { + return fail("reference.unreadable", `parent() reads a published parameter of the component a node is in, and this expression is not inside one`, { suggestion: "Use parent() in a node inside a component, or read the parameter with op('').par..", }); case "call": { diff --git a/src/tests/headless/parent-expressions.gpu.test.ts b/src/tests/headless/parent-expressions.gpu.test.ts new file mode 100644 index 000000000..c47ab501a --- /dev/null +++ b/src/tests/headless/parent-expressions.gpu.test.ts @@ -0,0 +1,161 @@ +import { describe, expect, it } from "vitest"; + +import { createAppRuntime } from "../../app/app-runtime.ts"; +import { openComponentSession } from "../../domain/components/session.ts"; +import type { RuntimeDiagnostic } from "../../domain/types/diagnostics.ts"; +import type { GraphDocument, ProjectSettings } from "../../domain/types/graph.ts"; +import type { StoredParameter } from "../../domain/types/parameters.ts"; +import { expressionSlot } from "../../examples/documents/builders.ts"; +import { nodeGpuHost, probeDawn } from "../../runtime/backend/vgpu/node-gpu-host.ts"; +import { renderHeadless } from "./render-harness.ts"; + +/** + * VN36 — `parent().par.gain` INSIDE A COMPONENT, PLACED TWICE, on Dawn. + * + * Proposal 01 §2.3: an expression could not read its component's published parameter, so the + * previz put a Constant "knob holder" in every component for a formula to read. Now the + * component's Solid reads its page directly: red = `parent().par.gain`, green = + * `1 - parent().par.gain`. Two instances, gain 1 and gain 0, must render pure red and pure + * green: each from ITS OWN page (§V321), through the flattener's rewrite to + * `op('').par.gain` and the reader of a dissolved instance's page. + * + * Built through the app's commands: the Solid saved as "Lamp", placed twice and renamed, its + * output exposed and `gain` published from a component session, the Solid's two channels set there. 0 and 1 are + * fixed points of the display decode (§V56), so every assertion is an exact byte (§V147). + */ + +const SIZE = 16; +const SETTINGS: ProjectSettings = { + outputResolution: { width: SIZE, height: SIZE }, + workingFormat: "rgba8unorm", + randomSeed: 7, + previewLongEdge: 64, + previewFps: 20, + limits: { maxResolution: 4096, maxDispatch: 65535, maxBufferBytes: 268_435_456, memoryBudgetBytes: 1_073_741_824 }, +}; + +interface Staged { + readonly graph: GraphDocument; + readonly instances: { readonly a: string; readonly b: string }; + /** The Solid's id inside the component: the instance's flat child is `/`. */ + readonly inner: string; + readonly components: ReturnType["components"]["view"]>; +} + +/** `pages`: each instance's `gain`. `publish`: false cuts the publish. */ +async function stage(pages: { a: StoredParameter; b: StoredParameter }, publish = true): Promise { + const runtime = createAppRuntime({ identityStorage: null }); + const { bus, invocation } = runtime; + const added = await bus.execute("graph.applyPatch", { baseRevision: 0, operations: [ + { op: "addNode", ref: "$solid", type: "solid", position: { x: 0, y: 0 }, label: "solid_lamp", parameters: { color: [0, 0, 0, 1] } }, + ] }, invocation); + expect(added.status).toBe("applied"); + const solid = added.output.createdIds["$solid"]!; + const saved = await bus.execute("component.saveSelection", { nodeIds: [solid], name: "Lamp" }, invocation); + expect(saved.status).toBe("applied"); + const componentId = saved.output.componentId!; + const placed = await bus.execute("component.instantiate", { componentId }, invocation); + expect(placed.status).toBe("applied"); + const instances = { a: saved.output.instanceNodeId!, b: placed.output.nodeId! }; + for (const [nodeId, label] of [[instances.a, "lamp_a"], [instances.b, "lamp_b"]] as const) { + expect((await bus.execute("node.rename", { nodeId, label }, invocation)).status).toBe("applied"); + } + + // Inside the component: publish `gain`, and aim the Solid's red and green at it. + const session = openComponentSession({ components: runtime.components, nodes: runtime.registry, componentId, version: 1 }); + const inner = Object.keys(session.bus.store.getGraph().nodes)[0]!; + const exposed = await session.bus.execute("component.exposePort", { direction: "output", nodeId: inner, portId: "out", externalId: "out", label: "Out" }, invocation); + expect(exposed.status, exposed.diagnostics.map((each) => each.message).join("; ")).toBe("applied"); + if (publish) { + const published = await session.bus.execute("component.publishParameter", { + key: "gain", definition: { type: "number", label: "Gain", default: 0.5, min: 0, max: 1 }, targets: [], + }, invocation); + expect(published.status, published.diagnostics.map((each) => each.message).join("; ")).toBe("applied"); + } + const aimed = await session.bus.execute("graph.applyPatch", { baseRevision: session.bus.store.getRevision(), operations: [ + { op: "setParameters", nodeId: inner, parameters: { + "color.r": expressionSlot("parent().par.gain", 0), + "color.g": expressionSlot("1 - parent().par.gain", 0), + } }, + ] }, invocation); + expect(aimed.status, aimed.diagnostics.map((each) => each.message).join("; ")).toBe("applied"); + session.dispose(); + + const definition = runtime.components.get(componentId, 1)!; + // A page key the component does not publish is refused at the door, so the cut leaves the + // pages at nothing: what the reads then see is exactly "no such key". + if (publish) { + const paged = await bus.execute("graph.applyPatch", { baseRevision: bus.store.getRevision(), operations: [ + { op: "setParameters", nodeId: instances.a, parameters: { gain: pages.a } }, + { op: "setParameters", nodeId: instances.b, parameters: { gain: pages.b } }, + ] }, invocation); + expect(paged.status, paged.diagnostics.map((each) => each.message).join("; ")).toBe("applied"); + } + const shown = await bus.execute("graph.applyPatch", { baseRevision: bus.store.getRevision(), operations: [ + { op: "addNode", ref: "$out", type: "output", position: { x: 400, y: 0 }, label: "output_main" }, + { op: "connect", source: { nodeId: instances.a, portId: "out" }, target: { nodeId: "$out", portId: "input" } }, + ] }, invocation); + expect(shown.status).toBe("applied"); + expect(definition.outputs.map((each) => each.externalId)).toEqual(["out"]); + return { graph: bus.store.getGraph(), instances, inner, components: runtime.components.view() }; +} + +/** Every frame of `instance`'s output, as the first pixel's RGB. The Solid fills the frame. */ +async function render(staged: Staged, instance: string, frames = 1): Promise<{ rgb: number[][]; diagnostics: readonly RuntimeDiagnostic[] }> { + // The one Output shows the instance under test: its wire is re-aimed, nothing else moves. + const edges = Object.fromEntries(Object.entries(staged.graph.edges).map(([id, each]) => + [id, staged.graph.nodes[each.target.nodeId]?.type === "output" ? { ...each, source: { ...each.source, nodeId: instance } } : each])); + const result = await renderHeadless({ + host: nodeGpuHost(), + graph: { ...staged.graph, edges }, + components: staged.components, + settings: SETTINGS, + frames, + capture: Array.from({ length: frames }, (_, index) => index), + animate: frames > 1, + // The instance is flattened away; its Solid, by flat id, is what the plan materialises. + outputNodeId: `${instance}/${staged.inner}`, + outputPortId: "out", + }); + return { rgb: result.frames.map((frame) => [frame.bytes[0]!, frame.bytes[1]!, frame.bytes[2]!]), diagnostics: result.diagnostics }; +} + +const parentCodes = (diagnostics: readonly RuntimeDiagnostic[]) => + diagnostics.filter((each) => each.code.startsWith("compiler/parent-reference")).map((each) => each.code); + +async function dawn(): Promise { + const probe = await probeDawn(); + if (!probe.available) throw new Error(`Dawn unavailable: ${probe.error}`); +} + +describe("VN36: parent().par.gain, one component placed twice (Dawn)", () => { + it("each instance renders from ITS OWN page: gain 1 is red, gain 0 is green", async () => { + await dawn(); + const staged = await stage({ a: 1, b: 0 }); + const a = await render(staged, staged.instances.a); + const b = await render(staged, staged.instances.b); + expect(a.diagnostics.filter((each) => each.severity === "error")).toEqual([]); + expect(parentCodes(a.diagnostics)).toEqual([]); + expect(a.rgb).toEqual([[255, 0, 0]]); + expect(b.rgb).toEqual([[0, 255, 0]]); + }, 120_000); + + it("CUT THE PUBLISH: no page key, so the reads are refused by name and both hold their static black", async () => { + await dawn(); + const staged = await stage({ a: 1, b: 0 }, false); + const a = await render(staged, staged.instances.a); + const b = await render(staged, staged.instances.b); + expect(a.rgb).toEqual([[0, 0, 0]]); + expect(b.rgb).toEqual([[0, 0, 0]]); + // Red and green, in each of the two instances. + expect(parentCodes(a.diagnostics)).toEqual(Array(4).fill("compiler/parent-reference-unknown-key")); + }, 120_000); + + it("an ANIMATED page knob animates through parent(): two frames, two colours", async () => { + await dawn(); + const staged = await stage({ a: expressionSlot("frame % 2", 0), b: 0 }); + const { rgb } = await render(staged, staged.instances.a, 2); + expect(rgb).toHaveLength(2); + expect(new Set(rgb.map((each) => each.join(",")))).toEqual(new Set(["255,0,0", "0,255,0"])); + }, 120_000); +}); diff --git a/src/tests/integration/parent-expressions.test.ts b/src/tests/integration/parent-expressions.test.ts new file mode 100644 index 000000000..5bc8fd1df --- /dev/null +++ b/src/tests/integration/parent-expressions.test.ts @@ -0,0 +1,264 @@ +import { describe, expect, it } from "vitest"; + +import { compileGraphRetaining, flattenComponents } from "@compiler/index.ts"; +import { testCapabilities, testSettings } from "@compiler/test-support.ts"; +import { createValueGraphSession } from "@domain/channels/value-graph.ts"; +import { componentNodeType, createComponentSystem } from "@domain/components/index.ts"; +import type { GraphComponentDefinition, PublishedParameter } from "@domain/types/components.ts"; +import type { FrameEvaluationInput } from "@domain/types/frame.ts"; +import type { GraphDocument, GraphNode } from "@domain/types/graph.ts"; +import type { StoredParameter } from "@domain/types/parameters.ts"; +import { expressionSlot } from "@/examples/documents/builders.ts"; +import { allNodeDefinitions } from "@nodes/definitions/index.ts"; +import { createNodeRegistry } from "@nodes/registry/registry.ts"; + +/** + * VN36 — `parent(n).par.key` through the real flattener, value graph and compiler. + * + * The flattener rewrites each read to `op('').par.key` + * (`compiler/parent-references.ts`) and the reader reads that instance's page per frame + * (`instance-parameter-reference.test.ts`). The pixels are `parent-expressions.gpu.test.ts`. + */ + +const frameAt = (timeSeconds: number): FrameEvaluationInput => ({ + timeSeconds, + deltaSeconds: 1 / 60, + frameIndex: Math.round(timeSeconds * 60), + mode: "realtime", + randomSeed: 1, +}); + +const node = (id: string, type: string, parameters: Record, label: string): GraphNode => + ({ id, type, definitionVersion: 1, position: { x: 0, y: 0 }, parameters, label }) as never; + +const edge = (id: string, from: readonly [string, string], to: readonly [string, string]) => ({ + id, + source: { nodeId: from[0], portId: from[1] }, + target: { nodeId: to[0], portId: to[1] }, +}); + +const knob = (key: string, targets: PublishedParameter["targets"] = []): PublishedParameter => ({ + key, + definition: { type: "number", label: key, default: 0.3 }, + targets, +}); + +/** `in → fx → out`, fx's `amount` the given slot. */ +function lamp(amount: StoredParameter, published: PublishedParameter[] = [knob("gain")]): GraphComponentDefinition { + return { + componentId: "lamp", + version: 1, + name: "Lamp", + graph: { revision: 1, groups: {}, nodes: { fx: node("fx", "customWgsl", { amount }, "fx_lamp") }, edges: {} }, + inputs: [{ externalId: "source", label: "Source", nodeId: "fx", portId: "input" }], + outputs: [{ externalId: "out", label: "Out", nodeId: "fx", portId: "out" }], + parameters: published, + }; +} + +/** A component that holds one Lamp, publishes `master`, and sets the Lamp's page to `page`. */ +function rack(page: Record): GraphComponentDefinition { + return { + componentId: "rack", + version: 1, + name: "Rack", + graph: { + revision: 1, + groups: {}, + nodes: { inner: node("inner", componentNodeType("lamp", 1), page, "lamp_inner") }, + edges: {}, + }, + inputs: [{ externalId: "source", label: "Source", nodeId: "inner", portId: "source" }], + outputs: [{ externalId: "out", label: "Out", nodeId: "inner", portId: "out" }], + parameters: [knob("master")], + }; +} + +/** `solid → → output`, chained. */ +function chain(instances: GraphNode[]): GraphDocument { + const nodes = [node("solid", "solid", { color: [1, 1, 1, 1] }, "solid_base"), ...instances, node("out", "output", {}, "output_main")]; + const edges: GraphDocument["edges"] = {}; + for (let index = 0; index < nodes.length - 1; index += 1) { + const from = nodes[index] as GraphNode; + const to = nodes[index + 1] as GraphNode; + const port = to.type === "output" ? "input" : to.type === "customWgsl" ? "input" : "source"; + edges[`e${index}`] = edge(`e${index}`, [from.id, "out"], [to.id, port]); + } + return { revision: 1, groups: {}, nodes: Object.fromEntries(nodes.map((each) => [each.id, each])), edges }; +} + +/** Each customWgsl's `amount` as compiled at `time`, keyed by flat id, and what the compile said. */ +function compiled(definitions: GraphComponentDefinition[], graph: GraphDocument, time = 1) { + const system = createComponentSystem(createNodeRegistry(allNodeDefinitions).view()); + for (const definition of definitions) system.components.register(definition); + const components = system.components.view(); + const flattened = flattenComponents({ graph, registry: system.nodes, components }); + const frame = frameAt(time); + const channels = createValueGraphSession(system.nodes).evaluate(flattened.graph, frame, { flattening: flattened }).resolver; + const result = compileGraphRetaining({ + graph, + settings: testSettings(), + registry: system.nodes, + capabilities: testCapabilities(), + components, + flattened, + resolution: { frame, channels }, + }); + const amounts: Record = {}; + for (const [id, record] of result.retained?.nodes ?? []) { + if (record.node.type === "customWgsl") amounts[id] = record.context.parameters["amount"]; + } + // The compile restates the flattening's diagnostics, so its list is the whole answer. What + // a READER said: `parent()`'s own codes, and any parameter problem on a reading node. + const said = result.compiled.diagnostics.filter( + (entry) => + entry.code.startsWith("compiler/parent-reference") || + (entry.code.startsWith("parameter.") && entry.nodeId !== undefined && result.retained?.nodes.get(entry.nodeId)?.node.type === "customWgsl"), + ); + return { amounts, said, flattened, pruned: result.compiled.ok ? result.compiled.pruned : [] }; +} + +const instanceOf = (id: string, componentId: string, label: string, page: Record = {}) => + node(id, componentNodeType(componentId, 1), page, label); + +describe("VN36 — parent().par.key inside a component", () => { + const reader = lamp(expressionSlot("parent().par.gain * 0.5", 0.25)); + + it("reads ITS instance's page: two instances, two values (§V321)", () => { + const { amounts, said, flattened } = compiled( + [reader], + chain([instanceOf("a", "lamp", "lamp_a", { gain: 0.4 }), instanceOf("b", "lamp", "lamp_b", { gain: 0.8 })]), + ); + expect(said).toEqual([]); + expect(amounts).toEqual({ "a/fx": 0.2, "b/fx": 0.4 }); + // The rewrite itself: a name, not a value — the instance's page is read per frame. + const slot = flattened.graph.nodes["a/fx"]?.parameters["amount"]; + expect(slot).toMatchObject({ bindings: { expression: { source: "op('lamp_a').par.gain * 0.5" } } }); + }); + + it("follows an ANIMATED page knob per frame", () => { + const graph = chain([instanceOf("a", "lamp", "lamp_a", { gain: expressionSlot("time * 0.2", 0.3) })]); + expect(compiled([reader], graph, 1).amounts["a/fx"]).toBe(0.1); + expect(compiled([reader], graph, 3).amounts["a/fx"]).toBeCloseTo(0.3, 12); + }); + + it("CUT THE PUBLISH: the read is refused by name and the static stands, never 0", () => { + const unpublished = lamp(expressionSlot("parent().par.gain * 0.5", 0.25), []); + const { amounts, said } = compiled([unpublished], chain([instanceOf("a", "lamp", "lamp_a", { gain: 0.4 })])); + expect(amounts["a/fx"]).toBe(0.25); + expect(said.map((entry) => entry.code)).toEqual(["compiler/parent-reference-unknown-key"]); + expect(said[0]?.nodeId).toBe("a/fx"); + expect(said[0]?.message).toContain(`publishes no parameter "gain"`); + }); + + it("names the nearest published key when the read misspells it", () => { + const misspelt = lamp(expressionSlot("parent().par.gian", 0.25)); + const { said } = compiled([misspelt], chain([instanceOf("a", "lamp", "lamp_a")])); + expect(said[0]?.code).toBe("compiler/parent-reference-unknown-key"); + expect(said[0]?.suggestion).toContain(`Nearest: "gain"`); + }); +}); + +describe("VN36 — parent() across nesting", () => { + it("parent(2) reads two components out", () => { + const deep = lamp(expressionSlot("parent(2).par.master + parent().par.gain", 0.25)); + const { amounts, said } = compiled( + [deep, rack({ gain: 0.1 })], + chain([instanceOf("r", "rack", "rack_a", { master: 0.5 })]), + ); + expect(said).toEqual([]); + expect(amounts["r/inner/fx"]).toBeCloseTo(0.6, 12); + }); + + it("reads a page value set on a NESTED instance, which no root parameter stands behind", () => { + const { amounts } = compiled( + [lamp(expressionSlot("parent().par.gain", 0.25)), rack({ gain: 0.7 })], + chain([instanceOf("r", "rack", "rack_a")]), + ); + expect(amounts["r/inner/fx"]).toBe(0.7); + }); + + it("a nested page that reads parent() animates through to the inner reader", () => { + const graph = chain([instanceOf("r", "rack", "rack_a", { master: expressionSlot("time * 0.1", 0.3) })]); + const definitions = [lamp(expressionSlot("parent().par.gain", 0.25)), rack({ gain: expressionSlot("parent().par.master * 2", 0.3) })]; + expect(compiled(definitions, graph, 1).amounts["r/inner/fx"]).toBeCloseTo(0.2, 12); + expect(compiled(definitions, graph, 2).amounts["r/inner/fx"]).toBeCloseTo(0.4, 12); + }); + + it("a page slot CARRIED inward (T1017) keeps the parent() it was written with", () => { + // `amount` is published onto fx.amount, and the Rack sets it, on its Lamp, to an animated + // read of the Rack's own page. Carried as text, `parent()` would be read from fx — one + // level too deep, where the Lamp publishes no `master`. + const fanned = lamp(0.25, [knob("gain"), knob("amount", [{ nodeId: "fx", key: "amount" }])]); + const graph = chain([instanceOf("r", "rack", "rack_a", { master: expressionSlot("time * 0.1", 0.3) })]); + const definitions = [fanned, rack({ amount: expressionSlot("parent().par.master * 3", 0.3) })]; + const { amounts, said } = compiled(definitions, graph, 2); + expect(said).toEqual([]); + expect(amounts["r/inner/fx"]).toBeCloseTo(0.6, 12); + }); + + it("parent(n) past the outermost component is refused", () => { + const tooDeep = lamp(expressionSlot("parent(2).par.gain", 0.25)); + const { amounts, said } = compiled([tooDeep], chain([instanceOf("a", "lamp", "lamp_a")])); + expect(amounts["a/fx"]).toBe(0.25); + expect(said.map((entry) => entry.code)).toEqual(["compiler/parent-reference-no-parent"]); + expect(said[0]?.message).toContain("reaches past the outermost one"); + }); +}); + +describe("VN36 — parent() at the root", () => { + it("raises no-parent and keeps the static, rather than reading 0", () => { + const graph = chain([node("fx", "customWgsl", { amount: expressionSlot("parent().par.gain", 0.25) }, "fx_root")]); + const { amounts, said } = compiled([], graph); + expect(amounts["fx"]).toBe(0.25); + expect(said.map((entry) => entry.code)).toEqual(["compiler/parent-reference-no-parent"]); + expect(said[0]?.nodeId).toBe("fx"); + }); +}); + +describe("VN36 — the value graph orders a parent() read after what the page reads", () => { + /** + * The reader is a Constant INSIDE the component (flat id `a/k`), and the page knob it reads + * reads a Constant at the root whose id, `zsrc`, sorts AFTER it. The value graph evaluates in + * dependency order, ties by id, so unless the walk follows `op('knob_a').par.level` into the + * page and on to `op('constant_src')`, the reader evaluates first and reads a bag not yet + * published: the default, one frame late at best. + */ + it("reads the root channel through the page in the SAME evaluation", () => { + const knobHolder: GraphComponentDefinition = { + componentId: "knob", + version: 1, + name: "Knob", + graph: { revision: 1, groups: {}, nodes: { k: node("k", "constant", { value: expressionSlot("parent().par.level", 0) }, "constant_k") }, edges: {} }, + inputs: [], + outputs: [], + parameters: [knob("level")], + }; + const graph: GraphDocument = { + revision: 1, + groups: {}, + nodes: { + zsrc: node("zsrc", "constant", { value: 0.7 }, "constant_src"), + a: instanceOf("a", "knob", "knob_a", { level: expressionSlot("op('constant_src').chan.value", 0.3) }), + }, + edges: {}, + }; + const system = createComponentSystem(createNodeRegistry(allNodeDefinitions).view()); + system.components.register(knobHolder); + const flattened = flattenComponents({ graph, registry: system.nodes, components: system.components.view() }); + const evaluated = createValueGraphSession(system.nodes).evaluate(flattened.graph, frameAt(1), { flattening: flattened }); + expect(evaluated.byName.get("constant_k")).toEqual({ value: 0.7 }); + }); +}); + +describe("VN36 — liveness follows a parent() read through the page", () => { + it("a node read only by a page knob, through parent(), is not reported dead", () => { + // `fx_spare` is wired to nothing. The one thing that reads it is the Lamp's page, and the + // one thing that reads the page is the Lamp's inner node, through parent(). + const graph = chain([instanceOf("a", "lamp", "lamp_a", { gain: expressionSlot("op('fx_spare').par.amount", 0.3) })]); + graph.nodes["spare"] = node("spare", "customWgsl", { amount: 0.9 }, "fx_spare"); + const { amounts, pruned } = compiled([lamp(expressionSlot("parent().par.gain", 0.25))], graph); + expect(amounts["a/fx"]).toBe(0.9); + expect(pruned).not.toContain("spare"); + }); +});