@mica-js/simulator 2.7.1 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/electrical.ts","../src/queue.ts","../src/observations.ts","../src/runtime/execution.ts","../src/types.ts","../src/runtime/errors.ts","../src/runtime/instance.ts","../src/runtime/publish-gate.ts","../src/polling.ts","../src/runtime/jit.ts","../src/runtime.ts","../src/simulation-runtime/errors.ts","../src/simulation-runtime/prepare.ts","../src/simulation-runtime/runtime.ts","../src/simulation-runtime/guest.ts"],"sourcesContent":["export type PinSample = {\n voltage: number | null;\n level: 'low' | 'high' | 'unknown';\n status: 'valid' | 'floating';\n};\n\nexport interface ElectricalPin {\n readonly id: string;\n readonly instance: string;\n readonly name: string;\n readonly low?: number;\n readonly high?: number;\n intent: readonly ResistorBranch[];\n sample: PinSample;\n}\n\nexport interface ResistorBranch {\n readonly to: ElectricalPin;\n readonly resistance: number;\n}\n\nexport interface NetInput {\n readonly id: string;\n readonly pins: readonly ElectricalPin[];\n readonly voltage?: number;\n}\n\nexport type ElectricalErrorCode =\n 'INVALID_ELECTRICAL_PARAMETER' | 'CONFLICTING_REFERENCE' | 'ELECTRICAL_SOLVE_FAILED';\n\nexport interface ElectricalErrorLocation {\n readonly instanceId?: string;\n readonly resource?: string;\n readonly network?: string;\n readonly networks?: readonly string[];\n readonly component?: readonly string[];\n}\n\nexport class ElectricalError extends Error {\n readonly code: ElectricalErrorCode;\n readonly instanceId: string | undefined;\n readonly resource: string | undefined;\n readonly network: string | undefined;\n readonly networks: readonly string[] | undefined;\n readonly component: readonly string[] | undefined;\n readonly reason: string;\n\n constructor(code: ElectricalErrorCode, reason: string, location: ElectricalErrorLocation = {}) {\n super(reason);\n this.name = 'ElectricalError';\n this.code = code;\n this.reason = reason;\n this.instanceId = location.instanceId;\n this.resource = location.resource;\n this.network = location.network;\n this.networks = location.networks;\n this.component = location.component;\n }\n}\n\n/** Invoke at resistor construction, including branches never assigned to an intent. */\nexport function validateResistance(\n resistance: number,\n location: ElectricalErrorLocation = {},\n): void {\n if (!Number.isFinite(resistance) || resistance < 0.001 || resistance > 1_000_000_000) {\n throw new ElectricalError(\n 'INVALID_ELECTRICAL_PARAMETER',\n 'Resistance must be finite and in [0.001, 1000000000] ohms.',\n location,\n );\n }\n}\n\nexport interface ElectricalStats {\n /** Successful, atomically published solves, including the initial baseline. */\n readonly solves: number;\n readonly components: number;\n readonly floatingComponents: number;\n readonly factorizations: number;\n readonly factorizationReuses: number;\n /** Block results served from a cache entry, including one retained across a rebuild. */\n readonly cacheHits: number;\n /** Distinct `(pin, target, resistance)` leaf shapes admitted for reuse. */\n readonly leafPlans: number;\n /** Solves served by replaying an admitted leaf plan instead of rebuilding edges. */\n readonly leafPropagations: number;\n /** Whole-graph rebuilds (`prepareTopology`); a bucket hit restores instead. */\n readonly topologyPrepares: number;\n}\n\nexport interface ElectricalNetwork {\n /**\n * The caller establishes the initial observation baseline after the first solve.\n * Omit changedPins to detect intent identity changes automatically. When supplied,\n * it must include every pin assigned since the last successful solve; intents are immutable.\n * The first solve always reads all pins, regardless of this hint.\n */\n solve(changedPins?: Iterable<ElectricalPin>): readonly ElectricalPin[];\n /**\n * Slot-addressed form of :func:`solve` for callers that already know board pin slots.\n * A number denotes a complete, single-slot dirty batch.\n * Returns a fresh ascending array of the changed slots.\n */\n solveSlots(changedSlots?: number | Iterable<number>): readonly number[];\n /** One complete single-slot dirty batch; same contract as `solveSlots(slot)`. */\n solveSlot(slot: number): readonly number[];\n /**\n * Board-facing single-slot entry: solves the batch and hands each changed slot to\n * `publish` in visit order, so no result array is materialised. The sink is the board's\n * slot bitmap, which ignores the order; callers that need an ascending array use\n * `solveSlot`.\n */\n solveSlotInto(slot: number, publish?: (slot: number) => void): void;\n /**\n * Board-facing batch entry for a complete multi-slot dirty batch. `slots[0, count)` must\n * hold board pin slots; repetitions are ignored. Same atomicity as `solveSlots`, which it\n * shares every guard with, and the same order-free publication as `solveSlotInto`.\n */\n solveSlotBatchInto(\n slots: ArrayLike<number>,\n count: number,\n publish?: (slot: number) => void,\n ): void;\n readonly stats: ElectricalStats;\n}\n\ninterface Node {\n readonly pins: readonly ElectricalPin[];\n readonly networks: readonly string[];\n reference: number | undefined;\n}\n\n/**\n * A pin that keeps exactly one branch onto a node with a fixed potential. A node with one\n * incident branch carries no current by KCL, so its voltage equals the target's reference\n * voltage whatever else the target's component contains. Replaying an admitted shape\n * therefore needs no edge rebuild, no partition check and no matrix work.\n */\ninterface LeafPropagation {\n intent: readonly ResistorBranch[];\n readonly targetPin: ElectricalPin;\n readonly resistance: number;\n readonly target: number;\n readonly edges: readonly Edge[];\n readonly edgeHash: number;\n /** Node of the switching pin and the sample every pin on it takes for this target. */\n readonly node: number;\n readonly voltage: number;\n readonly slots: readonly number[];\n readonly pins: readonly ElectricalPin[];\n readonly samples: readonly PinSample[];\n}\n\ninterface Edge {\n readonly pin: number;\n readonly index: number;\n readonly from: number;\n readonly to: number;\n readonly resistance: number;\n readonly conductance: number;\n}\n\ninterface Component {\n readonly nodes: number[];\n readonly edges: Edge[];\n readonly physical?: Component;\n}\n\ninterface Factorization {\n readonly matrix: Float64Array;\n readonly anchors: Float64Array;\n readonly pivots: Float64Array;\n readonly weights: Float64Array;\n}\n\ninterface CachedComponent {\n /** Node layout the entry was solved for; equal slots mean the same equation order. */\n readonly nodes: readonly number[];\n /** Fixed potential per layout slot; `undefined` marks that slot's node as unknown. */\n readonly references: readonly (number | undefined)[];\n readonly edges: readonly Edge[];\n readonly voltages: readonly (number | null)[];\n readonly factorization: Factorization | undefined;\n}\n\ninterface PreparedBlock {\n readonly component: Component;\n readonly key: string;\n}\n\ninterface PreparedTopology {\n readonly blocks: PreparedBlock[];\n /** Stable pin/branch slots allow equivalent older Edge objects to be shared. */\n readonly edgeBlocks: readonly (readonly (number | undefined)[] | undefined)[];\n readonly components: number;\n readonly floatingComponents: number;\n}\n\n/** Dirty pin edges indexed by slot; `undefined` means the pin kept its committed edges. */\ntype PinUpdates = readonly (readonly Edge[] | undefined)[];\n\ninterface TopologySnapshot {\n readonly id: number;\n readonly cost: number;\n readonly topology: PreparedTopology;\n /** Per-pin endpoint hashes the graph was built from; confirms a bucket hit exactly. */\n readonly hashes: Uint32Array;\n}\n\n/**\n * Descriptors and admitted graphs share these buckets. The budget covers a whole-board\n * working set: a 288-pin board steps through roughly 1.2k distinct shapes in 300 ms, so\n * the former limit of eight discarded every descriptor before its second observation could\n * ever admit a graph.\n */\nconst topologyTransitionLimit = 4096;\n/** Compiled reference programs cost far more per entry than a graph descriptor. */\nconst referenceProgramLimit = 8;\nconst topologySnapshotLimit = 65_536;\n\n/** FNV-1a over the pin slot and its ordered endpoints: the key without the 288 strings. */\nfunction hashEdges(slot: number, edges: readonly Edge[]): number {\n let hash = Math.imul(0x811c9dc5 ^ slot, 0x01000193);\n for (let index = 0; index < edges.length; index++) {\n hash = Math.imul(hash ^ edges[index]!.to, 0x01000193);\n }\n return Math.imul(hash ^ edges.length, 0x01000193) >>> 0;\n}\n\nfunction topologyCost(topology: PreparedTopology): number {\n let cost = 0;\n const physicals = new Set<Component>();\n for (const block of topology.blocks) {\n cost += block.component.nodes.length + 2 * block.component.edges.length;\n const physical = block.component.physical;\n if (physical !== undefined && !physicals.has(physical)) {\n physicals.add(physical);\n cost += physical.nodes.length + physical.edges.length;\n }\n if (cost > topologySnapshotLimit) break;\n }\n return cost;\n}\n\nfunction rebindBlock(\n block: PreparedBlock,\n pinEdges: readonly (readonly Edge[])[],\n updates: PinUpdates,\n): PreparedBlock {\n let edges: Edge[] | undefined;\n for (let index = 0; index < block.component.edges.length; index++) {\n const edge = block.component.edges[index]!;\n const next = (updates[edge.pin] ?? pinEdges[edge.pin]!)[edge.index]!;\n if (edge.from === next.from && edge.to === next.to && edge.resistance === next.resistance)\n continue;\n edges ??= block.component.edges.slice();\n edges[index] = next;\n }\n if (edges === undefined) return block;\n return { ...block, component: { ...block.component, edges } };\n}\n\n/**\n * Every block edge is re-read from the committed pin edges. A bucket key records\n * connectivity only, so a resistance-only change keeps its key and still has to be\n * repaired in blocks that no pin of this solve touches.\n */\nfunction restoreTopology(\n topology: PreparedTopology,\n pinEdges: readonly (readonly Edge[])[],\n updates: PinUpdates,\n): PreparedTopology {\n let blocks: PreparedBlock[] | undefined;\n for (let index = 0; index < topology.blocks.length; index++) {\n const previous = topology.blocks[index]!;\n const block = rebindBlock(previous, pinEdges, updates);\n if (block === previous) continue;\n blocks ??= topology.blocks.slice();\n blocks[index] = block;\n }\n return blocks === undefined ? topology : { ...topology, blocks };\n}\n\nfunction prepareBlock(component: Component): PreparedBlock {\n return { component, key: component.nodes.join(',') };\n}\n\nfunction prepareTopology(\n nodes: readonly Node[],\n pinEdges: readonly (readonly Edge[])[],\n): PreparedTopology {\n const topology = new DisjointSet(nodes.length);\n for (const edges of pinEdges) {\n for (const edge of edges) topology.join(edge.from, edge.to);\n }\n const groups = new Map<number, Component>();\n for (let node = 0; node < nodes.length; node++) {\n const root = topology.find(node);\n let group = groups.get(root);\n if (group === undefined) {\n group = { nodes: [], edges: [] };\n groups.set(root, group);\n }\n group.nodes.push(node);\n }\n for (const edges of pinEdges) {\n for (const edge of edges) groups.get(topology.find(edge.from))!.edges.push(edge);\n }\n let floatingComponents = 0;\n const blocks: PreparedBlock[] = [];\n const edgeBlocks: (number | undefined)[][] = [];\n for (const component of groups.values()) {\n let floating = true;\n for (const node of component.nodes) {\n if (nodes[node]!.reference !== undefined) {\n floating = false;\n break;\n }\n }\n if (floating) floatingComponents++;\n for (const block of solveBlocks(component, nodes)) {\n const index = blocks.length;\n blocks.push(prepareBlock(block));\n for (const edge of block.edges) (edgeBlocks[edge.pin] ??= [])[edge.index] = index;\n }\n }\n return {\n blocks,\n edgeBlocks,\n components: groups.size,\n floatingComponents,\n };\n}\n\nconst cleanZero = (value: number): number => (value === 0 ? 0 : value);\n\nfunction pinLocation(pin: ElectricalPin): ElectricalErrorLocation {\n return { instanceId: pin.instance, resource: pin.name };\n}\n\nclass DisjointSet {\n private readonly parents: number[];\n\n constructor(count: number) {\n this.parents = new Array<number>(count);\n for (let index = 0; index < count; index++) this.parents[index] = index;\n }\n\n find(index: number): number {\n let root = index;\n while (this.parents[root] !== root) root = this.parents[root]!;\n while (index !== root) {\n const next = this.parents[index]!;\n this.parents[index] = root;\n index = next;\n }\n return root;\n }\n\n join(first: number, second: number): void {\n const a = this.find(first);\n const b = this.find(second);\n if (a !== b) this.parents[Math.max(a, b)] = Math.min(a, b);\n }\n}\n\nfunction solveBlocks(component: Component, nodes: readonly Node[]): Component[] {\n let unknownCount = 0;\n let reference: number | undefined;\n let mixedReferences = false;\n for (const node of component.nodes) {\n const potential = nodes[node]!.reference;\n if (potential === undefined) unknownCount++;\n else if (reference === undefined) reference = potential;\n else if (potential !== reference) mixedReferences = true;\n }\n if (unknownCount < 2 || !mixedReferences) return [component];\n const slots = new Map<number, number>();\n for (const node of component.nodes) {\n if (nodes[node]!.reference === undefined) slots.set(node, slots.size);\n }\n const topology = new DisjointSet(unknownCount);\n let coupled = false;\n for (const edge of component.edges) {\n const from = slots.get(edge.from);\n const to = slots.get(edge.to);\n if (from !== undefined && to !== undefined) {\n topology.join(from, to);\n coupled = true;\n }\n }\n // Tiny independent systems cost less as one matrix than as individual blocks.\n if (!coupled && unknownCount <= 32) return [component];\n const groups = new Array<Component | undefined>(unknownCount);\n const blocks: Component[] = [];\n for (let index = 0; index < unknownCount; index++) {\n const root = topology.find(index);\n let group = groups[root];\n if (group === undefined) {\n group = { nodes: [], edges: [], physical: component };\n blocks.push(group);\n }\n // Union roots are minimum slots, so their groups are initialized first.\n groups[index] = group;\n }\n if (blocks.length === 1) return [component];\n const boundaries = new Map<number, Component[]>();\n // Fixed potentials are boundary values, not couplings between unknowns.\n for (const edge of component.edges) {\n const from = slots.get(edge.from);\n const to = slots.get(edge.to);\n const unknownSlot = from ?? to;\n if (unknownSlot === undefined) continue;\n const group = groups[unknownSlot]!;\n group.edges.push(edge);\n const boundary = from === undefined ? edge.from : to === undefined ? edge.to : undefined;\n if (boundary === undefined) continue;\n let adjacent = boundaries.get(boundary);\n if (adjacent === undefined) {\n adjacent = [];\n boundaries.set(boundary, adjacent);\n }\n adjacent.push(group);\n }\n // Physical nodes are already sorted; append each boundary once per block.\n for (const node of component.nodes) {\n const slot = slots.get(node);\n if (slot !== undefined) groups[slot]!.nodes.push(node);\n else {\n const adjacent = boundaries.get(node);\n if (adjacent === undefined) continue;\n for (const group of adjacent) {\n if (group.nodes[group.nodes.length - 1] !== node) group.nodes.push(node);\n }\n }\n }\n return blocks;\n}\n\n/** Compensated summation also preserves small positive grounding contributions. */\nfunction sum(values: Iterable<number>): number {\n let total = 0;\n let correction = 0;\n for (const value of values) {\n const next = total + value;\n correction += Math.abs(total) >= Math.abs(value) ? total - next + value : value - next + total;\n total = next;\n }\n return total + correction;\n}\n\nfunction arraysEqual(first: Float64Array, second: Float64Array): boolean {\n if (first === second) return true;\n if (first.length !== second.length) return false;\n for (let index = 0; index < first.length; index++) {\n if (first[index] !== second[index]) return false;\n }\n return true;\n}\n\nfunction sameConfiguration(\n previous: CachedComponent,\n component: Component,\n nodes: readonly Node[],\n): boolean {\n const layout = component.nodes;\n if (previous.nodes.length !== layout.length || previous.edges.length !== component.edges.length)\n return false;\n for (let index = 0; index < layout.length; index++) {\n const node = layout[index]!;\n if (previous.nodes[index] !== node) return false;\n // A cached voltage belongs to one fixed-potential assignment, and the unknown set is\n // exactly the subset without a reference. Both are revalidated instead of assumed.\n if (!Object.is(previous.references[index], nodes[node]!.reference)) return false;\n }\n for (let index = 0; index < previous.edges.length; index++) {\n const edge = previous.edges[index]!;\n const other = component.edges[index]!;\n if (edge.from !== other.from || edge.to !== other.to || edge.resistance !== other.resistance)\n return false;\n }\n return true;\n}\n\nfunction factorize(\n matrix: Float64Array,\n anchors: Float64Array,\n fail: (reason: string) => never,\n): Factorization {\n const count = anchors.length;\n if (matrix.length === 0) {\n for (const pivot of anchors) {\n if (!(pivot > 0) || !Number.isFinite(pivot)) fail('Invalid LDL pivot.');\n }\n return { matrix, anchors, pivots: anchors, weights: new Float64Array(0) };\n }\n const work = matrix.slice();\n const grounding = anchors.slice();\n const pivots = new Float64Array(count);\n const weights = new Float64Array(count * count);\n for (let row = 0; row < count; row++) {\n const offset = row * count;\n const terms = [grounding[row]!];\n for (let column = row + 1; column < count; column++) terms.push(work[offset + column]!);\n const pivot = sum(terms);\n if (!(pivot > 0) || !Number.isFinite(pivot)) fail('Invalid LDL pivot.');\n pivots[row] = pivot;\n for (let column = row + 1; column < count; column++) {\n const conductance = work[offset + column]!;\n if (conductance === 0) continue;\n const weight = conductance / pivot;\n if (!(weight > 0) || !Number.isFinite(weight)) fail('Unrepresentable LDL coefficient.');\n weights[offset + column] = weight;\n }\n // Positive star-mesh Schur updates avoid subtracting almost equal diagonals.\n // The retained grounding term keeps even very weak reference paths intact.\n for (let first = row + 1; first < count; first++) {\n const conductance = work[offset + first]!;\n if (conductance === 0) continue;\n const ground = conductance * (grounding[row]! / pivot);\n if (grounding[row]! > 0 && !(ground > 0)) fail('Reference coefficient underflow.');\n grounding[first] = grounding[first]! + ground;\n for (let second = first + 1; second < count; second++) {\n const weight = weights[offset + second]!;\n if (weight === 0) continue;\n const fill = conductance * weight;\n if (!(fill > 0)) fail('Schur coefficient underflow.');\n const slot = first * count + second;\n work[slot] = work[slot]! + fill;\n }\n }\n }\n return { matrix, anchors, pivots, weights };\n}\n\nfunction substitute(\n factorization: Factorization,\n right: Float64Array,\n fail: (reason: string) => never,\n): Float64Array {\n const { weights, pivots } = factorization;\n const count = right.length;\n const solution = new Float64Array(count);\n if (weights.length === 0) {\n for (let row = 0; row < count; row++) {\n solution[row] = right[row]! / pivots[row]!;\n if (!Number.isFinite(solution[row])) fail('Non-finite backward substitution.');\n }\n } else {\n const forward = new Float64Array(count);\n for (let row = 0; row < count; row++) {\n const terms = [right[row]!];\n for (let column = 0; column < row; column++) {\n terms.push(weights[column * count + row]! * forward[column]!);\n }\n forward[row] = sum(terms);\n if (!Number.isFinite(forward[row])) fail('Non-finite forward substitution.');\n }\n for (let row = count - 1; row >= 0; row--) {\n const terms = [forward[row]! / pivots[row]!];\n for (let column = row + 1; column < count; column++) {\n terms.push(weights[row * count + column]! * solution[column]!);\n }\n solution[row] = sum(terms);\n if (!Number.isFinite(solution[row])) fail('Non-finite backward substitution.');\n }\n }\n return solution;\n}\n\ninterface ReferenceProgram {\n matches(edges: readonly Edge[], unknown: readonly number[]): boolean;\n assemble(\n edges: readonly Edge[],\n conductanceScale: number,\n voltageScale: number,\n ): { anchors: Float64Array; right: Float64Array };\n}\n\nfunction sumPair(first: number, second: number): number {\n first = 0 + first;\n const total = first + second;\n const correction =\n Math.abs(first) >= Math.abs(second) ? first - total + second : second - total + first;\n return total + correction;\n}\n\nfunction compileReferenceProgram(\n unknown: readonly number[],\n edges: readonly Edge[],\n slots: ReadonlyMap<number, number>,\n nodes: readonly Node[],\n): ReferenceProgram | undefined {\n if (unknown.length > 32 || edges.length > 128) return undefined;\n const rows: number[][] = Array.from({ length: unknown.length }, () => []);\n const guards = [`unknown.length === ${unknown.length}`, `edges.length === ${edges.length}`];\n const references: string[] = [];\n for (let index = 0; index < edges.length; index++) {\n const edge = edges[index]!;\n const from = slots.get(edge.from);\n const to = slots.get(edge.to);\n if (from !== undefined && to !== undefined) return undefined;\n if (from === undefined && to === undefined) {\n guards.push(\n `nodes[edges[${index}].from].reference !== undefined`,\n `nodes[edges[${index}].to].reference !== undefined`,\n );\n continue;\n }\n const row = from ?? to!;\n if (rows[row]!.length === 2) return undefined;\n rows[row]!.push(index);\n const fixed = from === undefined ? 'from' : 'to';\n const variable = from === undefined ? 'to' : 'from';\n references[index] = `nodes[edges[${index}].${fixed}].reference`;\n guards.push(\n `edges[${index}].${variable} === unknown[${row}]`,\n `${references[index]} !== undefined`,\n );\n }\n if (rows.some((row) => row.length === 0)) return undefined;\n const assembly: string[] = [];\n for (let row = 0; row < rows.length; row++) {\n const indices = rows[row]!;\n const reduce = (terms: readonly string[]): string =>\n terms.length === 1 ? `(0 + ${terms[0]})` : `pair(${terms.join(',')})`;\n for (const index of indices)\n assembly.push(`const g${index} = edges[${index}].conductance / gScale;`);\n assembly.push(\n `anchors[${row}] = ${reduce(indices.map((index) => `g${index}`))};`,\n `right[${row}] = ${reduce(indices.map((index) => `g${index} * (${references[index]} / vScale)`))};`,\n );\n }\n // Bind closed reference rows while retaining their original compensated summation order.\n const factory = new Function(\n 'pair',\n 'nodes',\n `\"use strict\"; return {\n matches(edges, unknown) { return ${guards.join(' && ')}; },\n assemble(edges, gScale, vScale) {\n const anchors = new Float64Array(${unknown.length});\n const right = new Float64Array(${unknown.length});\n ${assembly.join('\\n')}\n return { anchors, right };\n }\n };`,\n ) as (pair: typeof sumPair, nodes: readonly Node[]) => ReferenceProgram;\n return factory(sumPair, nodes);\n}\n\nexport function createElectricalNetwork(\n inputPins: readonly ElectricalPin[],\n inputNets: readonly NetInput[],\n): ElectricalNetwork {\n const pins = [...inputPins];\n const pinSlots = new Map(pins.map((pin, index) => [pin, index]));\n const assembly = new DisjointSet(pins.length);\n const nets = inputNets.map((net) => ({ id: net.id, pins: [...net.pins], voltage: net.voltage }));\n for (const pin of pins) {\n if (\n (pin.low === undefined) !== (pin.high === undefined) ||\n (pin.low !== undefined &&\n (!Number.isFinite(pin.low) || !Number.isFinite(pin.high) || !(pin.low < pin.high!)))\n ) {\n throw new ElectricalError(\n 'INVALID_ELECTRICAL_PARAMETER',\n 'Pin thresholds must both be omitted or finite with low < high.',\n pinLocation(pin),\n );\n }\n }\n const requirePin = (pin: ElectricalPin, network?: string): number => {\n const slot = pinSlots.get(pin);\n if (slot === undefined) {\n throw new ElectricalError(\n 'INVALID_ELECTRICAL_PARAMETER',\n 'Electrical endpoint is not part of this board.',\n network === undefined ? pinLocation(pin) : { network },\n );\n }\n return slot;\n };\n const requireEndpoint = (pin: ElectricalPin, owner: ElectricalPin): number => {\n const slot = pinSlots.get(pin);\n if (slot === undefined)\n throw new ElectricalError(\n 'INVALID_ELECTRICAL_PARAMETER',\n 'Electrical endpoint is not part of this board.',\n pinLocation(owner),\n );\n return slot;\n };\n const validResistance = (resistance: number): boolean =>\n Number.isFinite(resistance) && resistance >= 0.001 && resistance <= 1_000_000_000;\n for (const net of nets) {\n if (net.voltage !== undefined && !Number.isFinite(net.voltage)) {\n throw new ElectricalError('INVALID_ELECTRICAL_PARAMETER', 'Reference must be finite.', {\n network: net.id,\n });\n }\n let first: number | undefined;\n for (const pin of net.pins) {\n const slot = requirePin(pin, net.id);\n if (first === undefined) first = slot;\n else assembly.join(first, slot);\n }\n }\n const nodes: Node[] = [];\n /** Pin slots per node in ascending board order, so samples publish without lookups. */\n const nodeSlots: number[][] = [];\n const rootNodes = new Map<number, number>();\n const pinNodes = pins.map((pin, index) => {\n const root = assembly.find(index);\n let node = rootNodes.get(root);\n if (node === undefined) {\n node = nodes.length;\n rootNodes.set(root, node);\n nodes.push({ pins: [], networks: [], reference: undefined });\n nodeSlots.push([]);\n }\n (nodes[node]!.pins as ElectricalPin[]).push(pin);\n nodeSlots[node]!.push(index);\n return node;\n });\n for (const net of nets) {\n if (net.pins.length === 0) continue;\n const node = nodes[pinNodes[requirePin(net.pins[0]!, net.id)]!]!;\n (node.networks as string[]).push(net.id);\n if (net.voltage === undefined) continue;\n const reference = cleanZero(net.voltage);\n if (node.reference !== undefined && node.reference !== reference) {\n throw new ElectricalError('CONFLICTING_REFERENCE', 'Conflicting fixed potentials on a net.', {\n network: net.id,\n networks: Object.freeze([...node.networks]),\n });\n }\n node.reference = reference;\n }\n let cache = new Map<string, CachedComponent>();\n const referencePrograms: ReferenceProgram[] = [];\n let prepared: PreparedTopology | undefined;\n let nextTopologyId = 0;\n const transitions = new Map<string, TopologySnapshot | undefined>();\n /**\n * Per-pin endpoint hash. Their exact integer summary is the bucket key, so a repeated\n * shape costs one hash per dirty pin instead of a 288-entry string join.\n */\n const pinHashes = new Uint32Array(pins.length);\n let topologyHash = 0;\n let topologySpread = 0;\n for (let slot = 0; slot < pins.length; slot++) {\n const hash = hashEdges(slot, []);\n pinHashes[slot] = hash;\n topologyHash += hash;\n topologySpread ^= hash;\n }\n const setPinHash = (slot: number, edges: readonly Edge[]): void => {\n const hash = hashEdges(slot, edges);\n const previous = pinHashes[slot]!;\n if (hash === previous) return;\n pinHashes[slot] = hash;\n topologyHash += hash - previous;\n topologySpread ^= previous ^ hash;\n };\n /** Confirms a bucket hit against the exact hashes the stored graph was built from. */\n const lookupTransition = (key: string, updated: PinUpdates): TopologySnapshot | undefined => {\n const candidate = transitions.get(key);\n if (candidate === undefined) return undefined;\n const hashes = candidate.hashes;\n if (hashes.length !== pinHashes.length) return undefined;\n for (let slot = 0; slot < hashes.length; slot++) {\n const edges = updated[slot];\n const hash = edges === undefined ? pinHashes[slot]! : hashEdges(slot, edges);\n if (hashes[slot] !== hash) return undefined;\n }\n return candidate;\n };\n const rememberTransition = (key: string, admitted: TopologySnapshot): void => {\n if (admitted.cost > topologySnapshotLimit) return;\n if (!transitions.has(key)) {\n // A first observation retains only its bucket, never the graph; a repeated\n // observation admits the graph.\n transitions.set(key, undefined);\n } else if (transitions.get(key) !== admitted) transitions.set(key, admitted);\n // Map insertion order is age order, so eviction needs no scan.\n while (transitions.size > topologyTransitionLimit) {\n const oldest = transitions.keys().next().value;\n if (oldest === undefined) break;\n transitions.delete(oldest);\n }\n };\n const publishedVoltages: (number | null | undefined)[] = new Array(nodes.length);\n const intents: (readonly ResistorBranch[] | undefined)[] = new Array(pins.length);\n const pinEdges: (readonly Edge[])[] = Array.from({ length: pins.length }, () => []);\n const unchangedPins: readonly ElectricalPin[] = Object.freeze([]);\n /** Undirected incidence count per node, used to prove a node has no other branches. */\n const nodeDegree = new Int32Array(nodes.length);\n const updatedSlots: number[] = [];\n const updatedIntents: (readonly ResistorBranch[])[] = [];\n const updatedEdges: (readonly Edge[])[] = [];\n /** Dirty edges indexed by slot, so rebinding avoids a Map lookup per block edge. */\n const updatedEdgeLists: (readonly Edge[] | undefined)[] = new Array(pins.length);\n const updatedEdgeSlots: number[] = [];\n const replacedEdges: Edge[] = [];\n const seenSlots = new Int32Array(pins.length);\n let seenStamp = 0;\n /** Only the matrix partition is out of date; component arrays and buckets stay valid. */\n let blocksStale = false;\n const syncDegrees = (previous: readonly Edge[], next: readonly Edge[]): void => {\n for (const edge of previous) {\n if (next.indexOf(edge) === -1) {\n nodeDegree[edge.from] = nodeDegree[edge.from]! - 1;\n nodeDegree[edge.to] = nodeDegree[edge.to]! - 1;\n }\n }\n for (const edge of next) {\n if (previous.indexOf(edge) === -1) {\n nodeDegree[edge.from] = nodeDegree[edge.from]! + 1;\n nodeDegree[edge.to] = nodeDegree[edge.to]! + 1;\n }\n }\n };\n const statistics = {\n solves: 0,\n components: 0,\n floatingComponents: 0,\n factorizations: 0,\n factorizationReuses: 0,\n cacheHits: 0,\n leafPlans: 0,\n leafPropagations: 0,\n topologyPrepares: 0,\n };\n const emptySlots: readonly number[] = Object.freeze([]);\n /** Dirty slots supplied by the caller, deduplicated in place without an iterator per pin. */\n const inputSlots: number[] = [];\n /**\n * Changed pin slots of the last solve, valid in `[0, changedCount)`. The leaf path\n * collects them in visit order and orders them only for the entries that return an\n * array; the board publication sink is a slot bitmap. The array keeps its high-water\n * length so a new batch never pays for clearing it.\n */\n const changedSlots: number[] = [];\n let changedCount = 0;\n /** Admitted leaf shapes per pin slot; a pin normally alternates between two references. */\n const leafPlans: (LeafPropagation[] | undefined)[] = new Array(pins.length);\n /** Last topology check for the single-slot entry, independent of intent identity. */\n const leafEpochs = new Int32Array(pins.length);\n let leafEpoch = 1;\n const leafSlots: number[] = [];\n const leafIntents: (readonly ResistorBranch[])[] = [];\n const leafEdges: (readonly Edge[])[] = [];\n const leafTargets: number[] = [];\n /** Matched admitted shape per batch position, so publishing reuses its bound payload. */\n const leafPayloads: (LeafPropagation | undefined)[] = [];\n /** Shapes proven by the current solve; they are admitted only after it is accepted. */\n const pendingAdmissions: {\n readonly slot: number;\n readonly intent: readonly ResistorBranch[];\n readonly branch: ResistorBranch;\n readonly target: number;\n readonly edges: readonly Edge[];\n }[] = [];\n /** Canonical immutable samples; published samples never change once created. */\n const referenceSamples = new Map<number, Partial<Record<PinSample['level'], PinSample>>>();\n const nextStamp = (): number => {\n if (++seenStamp === 0x7fffffff) {\n seenSlots.fill(0);\n seenStamp = 1;\n }\n return seenStamp;\n };\n const sampleFor = (voltage: number, level: PinSample['level']): PinSample => {\n let entry = referenceSamples.get(voltage);\n if (entry === undefined) {\n if (referenceSamples.size >= 256) referenceSamples.clear();\n entry = {};\n referenceSamples.set(voltage, entry);\n }\n let sample = entry[level];\n if (sample === undefined) {\n sample = Object.freeze({ voltage: cleanZero(voltage), level, status: 'valid' as const });\n entry[level] = sample;\n }\n return sample;\n };\n /**\n * Records `(pin, target, resistance)` once the general path proved the shape: one branch\n * from a leaf node straight onto a fixed reference. Replays are only allowed while the\n * intent still names that branch, the pin still has one incident edge, the pin node is\n * still an unknown leaf and the target node still carries a fixed potential.\n */\n const pinLevel = (pin: ElectricalPin, voltage: number): PinSample['level'] =>\n pin.low === undefined\n ? 'unknown'\n : voltage <= pin.low\n ? 'low'\n : voltage >= pin.high!\n ? 'high'\n : 'unknown';\n /**\n * Bind the publish payload of one admitted shape: the switching pin's node, its pins in\n * board order, and the immutable sample each of them takes on the fixed target voltage.\n * A replay therefore commits precomputed samples instead of re-deriving voltages, levels\n * and canonical samples on every publication.\n */\n const leafPlan = (\n slot: number,\n intent: readonly ResistorBranch[],\n branch: ResistorBranch,\n target: number,\n edges: readonly Edge[],\n ): LeafPropagation => {\n const node = pinNodes[slot]!;\n const nodePins = nodeSlots[node]!;\n const voltage = nodes[target]!.reference!;\n const slots: number[] = [];\n const planPins: ElectricalPin[] = [];\n const samples: PinSample[] = [];\n for (let at = 0; at < nodePins.length; at++) {\n const nodeSlot = nodePins[at]!;\n const pinned = pins[nodeSlot]!;\n slots.push(nodeSlot);\n planPins.push(pinned);\n samples.push(sampleFor(voltage, pinLevel(pinned, voltage)));\n }\n return {\n intent,\n targetPin: branch.to,\n resistance: branch.resistance,\n target,\n edges,\n edgeHash: hashEdges(slot, edges),\n node,\n voltage,\n slots: Object.freeze(slots),\n pins: Object.freeze(planPins),\n samples: Object.freeze(samples),\n };\n };\n const admitLeaf = (\n slot: number,\n intent: readonly ResistorBranch[],\n branch: ResistorBranch,\n target: number,\n edges: readonly Edge[],\n ): void => {\n const plan = leafPlan(slot, intent, branch, target, edges);\n const plans = leafPlans[slot];\n if (plans === undefined) {\n leafPlans[slot] = [plan];\n statistics.leafPlans++;\n return;\n }\n for (const existing of plans)\n if (existing.targetPin === branch.to && existing.resistance === branch.resistance) {\n existing.intent = intent;\n return;\n }\n if (plans.length < 2) plans.push(plan);\n else plans[plans.length - 1] = plan;\n statistics.leafPlans++;\n };\n const flushAdmissions = (): void => {\n for (let index = 0; index < pendingAdmissions.length; index++) {\n const admission = pendingAdmissions[index]!;\n admitLeaf(\n admission.slot,\n admission.intent,\n admission.branch,\n admission.target,\n admission.edges,\n );\n }\n pendingAdmissions.length = 0;\n };\n const matchLeaf = (\n slot: number,\n intent: readonly ResistorBranch[],\n ): LeafPropagation | undefined => {\n if (prepared === undefined) return undefined;\n const plans = leafPlans[slot];\n if (plans === undefined) return undefined;\n const previous = pinEdges[slot]!;\n if (previous.length !== 1 || nodes[previous[0]!.to]!.reference === undefined) return undefined;\n const from = pinNodes[slot]!;\n if (nodeDegree[from] !== 1 || nodes[from]!.reference !== undefined) return undefined;\n const p0 = plans[0]!;\n if (p0.intent === intent) return nodes[p0.target]!.reference === undefined ? undefined : p0;\n if (plans.length > 1) {\n const p1 = plans[1]!;\n if (p1.intent === intent) return nodes[p1.target]!.reference === undefined ? undefined : p1;\n }\n if (intent.length !== 1) return undefined;\n const branch = intent[0]!;\n for (let index = 0; index < plans.length; index++) {\n const plan = plans[index]!;\n if (plan.targetPin !== branch.to || plan.resistance !== branch.resistance) continue;\n if (nodes[plan.target]!.reference === undefined) return undefined;\n plan.intent = intent;\n return plan;\n }\n return undefined;\n };\n /**\n * Appends one changed slot. A whole corrected batch is ordered once, after collecting,\n * so each leaf contributes its pins without paying for an insertion pass per pin.\n */\n const pushChanged = (slot: number): void => {\n changedSlots[changedCount++] = slot;\n };\n /** Restores the ascending board order the public entries promise; callers opt in. */\n const sortChanged = (): void => {\n for (let index = 1; index < changedCount; index++) {\n const slot = changedSlots[index]!;\n let position = index;\n while (position > 0 && changedSlots[position - 1]! > slot) {\n changedSlots[position] = changedSlots[position - 1]!;\n position--;\n }\n changedSlots[position] = slot;\n }\n };\n /** Hands every published slot to the board. The consumer is a slot bitmap. */\n const emitChanged = (publish: (slot: number) => void): void => {\n for (let index = 0; index < changedCount; index++) publish(changedSlots[index]!);\n };\n /** A fresh ascending copy for the public solve entries; the buffer is reused. */\n const copyChanged = (): readonly number[] => {\n if (changedCount === 0) return emptySlots;\n sortChanged();\n const result = new Array<number>(changedCount);\n for (let index = 0; index < changedCount; index++) result[index] = changedSlots[index]!;\n return result;\n };\n const commitLeafEdges = (\n slot: number,\n target: number,\n voltage: number,\n intent: readonly ResistorBranch[],\n edges: readonly Edge[],\n precomputedHash?: number,\n ): void => {\n const previousTarget = pinEdges[slot]![0]!.to;\n if (previousTarget !== target) {\n nodeDegree[previousTarget] = nodeDegree[previousTarget]! - 1;\n nodeDegree[target] = nodeDegree[target]! + 1;\n }\n publishedVoltages[pinNodes[slot]!] = voltage;\n intents[slot] = intent;\n pinEdges[slot] = edges;\n if (precomputedHash !== undefined) {\n const previous = pinHashes[slot]!;\n if (precomputedHash !== previous) {\n pinHashes[slot] = precomputedHash;\n topologyHash += precomputedHash - previous;\n topologySpread ^= previous ^ precomputedHash;\n }\n } else setPinHash(slot, edges);\n };\n const finishLeaf = (): void => {\n // The general solver can rebuild the partition from the committed edges without\n // discarding the admitted graphs or the numerical cache.\n blocksStale = true;\n statistics.solves++;\n statistics.leafPropagations++;\n };\n /**\n * Once the single dirty slot is admitted, the whole batch is known to be valid.\n * The plan visits one node's pins in board order, so no staging or merging is needed.\n */\n const applySingleLeaf = (\n slot: number,\n intent: readonly ResistorBranch[],\n plan: LeafPropagation,\n ): void => {\n const { node, target, voltage } = plan;\n changedCount = 0;\n if (publishedVoltages[node] !== voltage) {\n const planPins = plan.pins;\n const planSamples = plan.samples;\n const planSlots = plan.slots;\n for (let index = 0; index < planPins.length; index++) {\n const pin = planPins[index]!;\n const sample = planSamples[index]!;\n if (pin.sample === sample) continue;\n pin.sample = sample;\n changedSlots[changedCount++] = planSlots[index]!;\n }\n }\n commitLeafEdges(slot, target, voltage, intent, plan.edges, plan.edgeHash);\n finishLeaf();\n };\n /**\n * Publishes the accepted leaf batch. The caller has already matched every dirty slot to\n * an admitted shape (or proven the shapes below through the general solver), so each\n * pin's sample is an independent function of its node's fixed reference: committing them\n * in place is atomic. Slots are collected in visit order and ordered only when a public\n * entry asks for the ascending array.\n */\n const applyLeaf = (count: number): void => {\n changedCount = 0;\n for (let position = 0; position < count; position++) {\n const node = pinNodes[leafSlots[position]!]!;\n const plan = leafPayloads[position];\n if (plan !== undefined) {\n // Admitted shape: the target voltage, every pin on the node and each pin's\n // immutable sample were bound once, so only the current sample identity is checked.\n if (publishedVoltages[node] === plan.voltage) continue;\n const planSlots = plan.slots;\n const planPins = plan.pins;\n const planSamples = plan.samples;\n for (let at = 0; at < planSlots.length; at++) {\n const pinned = planPins[at]!;\n const sample = planSamples[at]!;\n if (pinned.sample === sample) continue;\n pinned.sample = sample;\n pushChanged(planSlots[at]!);\n }\n continue;\n }\n const voltage = nodes[leafTargets[position]!]!.reference!;\n if (publishedVoltages[node] === voltage) continue;\n const slots = nodeSlots[node]!;\n for (let at = 0; at < slots.length; at++) {\n const slot = slots[at]!;\n const pin = pins[slot]!;\n const level: PinSample['level'] =\n pin.low === undefined\n ? 'unknown'\n : voltage <= pin.low\n ? 'low'\n : voltage >= pin.high!\n ? 'high'\n : 'unknown';\n const previous = pin.sample;\n if (previous.voltage === voltage && previous.level === level && previous.status === 'valid')\n continue;\n pin.sample = sampleFor(voltage, level);\n pushChanged(slot);\n }\n }\n for (let position = 0; position < count; position++) {\n const slot = leafSlots[position]!;\n const target = leafTargets[position]!;\n commitLeafEdges(\n slot,\n target,\n nodes[target]!.reference!,\n leafIntents[position]!,\n leafEdges[position]!,\n leafPayloads[position]?.edgeHash,\n );\n }\n finishLeaf();\n };\n\n /** One complete single-slot dirty batch; leaves the publication buffer filled. */\n function solveSingleSlot(slot: number): void {\n const plans = leafPlans[slot];\n if (plans !== undefined) {\n const intent = pins[slot]!.intent;\n if (intent !== intents[slot]) {\n if (leafEpochs[slot] === leafEpoch) {\n const first = plans[0]!;\n const plan = first.intent === intent ? first : plans[1];\n if (plan?.intent === intent) {\n applySingleLeaf(slot, intent, plan);\n return;\n }\n }\n const plan = matchLeaf(slot, intent);\n if (plan !== undefined) {\n leafEpochs[slot] = leafEpoch;\n applySingleLeaf(slot, intent, plan);\n return;\n }\n }\n }\n inputSlots[0] = slot;\n inputSlots.length = 1;\n runSolve(inputSlots);\n }\n\n /**\n * One admitted-shape probe over `slots[0, length)`. A slot whose shape this epoch already\n * proved resolves through the same two-plan pointer comparison as `solveSingleSlot`; only\n * the first switch of a shape pays for `matchLeaf`. Any slot without an admitted shape\n * hands the whole batch to the general solver, which repeats the match.\n */\n function solveBatch(slots: ArrayLike<number>, length: number): void {\n if (prepared !== undefined) {\n const stamp = nextStamp();\n let count = 0;\n let complete = true;\n for (let position = 0; position < length; position++) {\n const slot = slots[position]!;\n if (seenSlots[slot] === stamp) continue;\n seenSlots[slot] = stamp;\n const intent = pins[slot]!.intent;\n if (intent === intents[slot]) continue;\n let plan: LeafPropagation | undefined;\n if (leafEpochs[slot] === leafEpoch) {\n const plans = leafPlans[slot]!;\n const first = plans[0]!;\n const cached = first.intent === intent ? first : plans[1];\n if (cached?.intent === intent) plan = cached;\n }\n if (plan === undefined) {\n plan = matchLeaf(slot, intent);\n if (plan === undefined) {\n complete = false;\n break;\n }\n leafEpochs[slot] = leafEpoch;\n }\n leafSlots[count] = slot;\n leafIntents[count] = intent;\n leafEdges[count] = plan.edges;\n leafTargets[count] = plan.target;\n leafPayloads[count] = plan;\n count++;\n }\n if (complete) {\n if (count === 0) {\n fillInput(slots, length);\n runSolve(inputSlots);\n return;\n }\n applyLeaf(count);\n return;\n }\n }\n fillInput(slots, length);\n runSolve(inputSlots);\n }\n\n /** Board-facing single-slot entry: solves and publishes without an intermediate array. */\n function solveSlotInto(slot: number, publish?: (slot: number) => void): void {\n solveSingleSlot(slot);\n if (publish !== undefined && changedCount !== 0) emitChanged(publish);\n }\n\n /** Board-facing batch entry: solves and publishes without an intermediate array. */\n function solveSlotBatchInto(\n slots: ArrayLike<number>,\n count: number,\n publish?: (slot: number) => void,\n ): void {\n solveBatch(slots, count);\n if (publish !== undefined && changedCount !== 0) emitChanged(publish);\n }\n\n return {\n get stats(): ElectricalStats {\n return Object.freeze({ ...statistics });\n },\n solve(changedPins?: Iterable<ElectricalPin>): readonly ElectricalPin[] {\n runSolve(gatherPins(changedPins));\n if (changedCount === 0) return unchangedPins;\n sortChanged();\n const published: ElectricalPin[] = [];\n for (let position = 0; position < changedCount; position++)\n published.push(pins[changedSlots[position]!]!);\n return Object.freeze(published);\n },\n solveSlot(slot: number): readonly number[] {\n solveSingleSlot(slot);\n return copyChanged();\n },\n solveSlotInto,\n solveSlotBatchInto,\n solveSlots(changedSlotNumbers?: number | Iterable<number>): readonly number[] {\n if (typeof changedSlotNumbers === 'number') {\n solveSingleSlot(changedSlotNumbers);\n return copyChanged();\n }\n if (changedSlotNumbers === undefined) {\n runSolve(undefined);\n return copyChanged();\n }\n // The batch is materialised exactly once into the solver's own input buffer, so a\n // one-shot generator is neither probed twice nor silently truncated: the probe and\n // any fallback both read that owned array.\n inputSlots.length = 0;\n if (\n Array.isArray(changedSlotNumbers) ||\n (ArrayBuffer.isView(changedSlotNumbers) && Symbol.iterator in changedSlotNumbers)\n ) {\n const indexed = changedSlotNumbers as ArrayLike<number>;\n for (let position = 0; position < indexed.length; position++)\n inputSlots.push(indexed[position]!);\n } else for (const slot of changedSlotNumbers) inputSlots.push(slot);\n solveBatch(inputSlots, inputSlots.length);\n return copyChanged();\n },\n };\n\n function gatherPins(changedPins: Iterable<ElectricalPin> | undefined): number[] | undefined {\n if (changedPins === undefined) return undefined;\n inputSlots.length = 0;\n for (const pin of changedPins) inputSlots.push(requirePin(pin));\n return inputSlots;\n }\n /** Places a caller-supplied batch into the solver input buffer without allocating. */\n function fillInput(slots: ArrayLike<number>, length: number): void {\n inputSlots.length = length;\n for (let position = 0; position < length; position++) inputSlots[position] = slots[position]!;\n }\n /**\n * One atomically published solve over `input` (dirty slots) or, when it is omitted, over\n * every pin. The published slots end up in the ascending buffer.\n */\n function runSolve(input: readonly number[] | undefined): void {\n // The general solver may add an edge to a previously admitted leaf or change its\n // driver. An admitted replay only moves an existing leaf's edge between fixed\n // references, leaving all unknown-node degrees and every leaf's eligibility intact.\n if (++leafEpoch === 0x7fffffff) {\n leafEpochs.fill(0);\n leafEpoch = 1;\n }\n const initial = prepared === undefined;\n pendingAdmissions.length = 0;\n changedCount = 0;\n if (prepared !== undefined && !blocksStale && input !== undefined && input.length === 0) {\n statistics.solves++;\n statistics.cacheHits += prepared.blocks.length;\n return;\n }\n updatedSlots.length = 0;\n updatedIntents.length = 0;\n updatedEdges.length = 0;\n replacedEdges.length = 0;\n let stamp = nextStamp();\n let topologyChanged = initial;\n // Structurally safe local updates never need the block partition to be rebuilt.\n let leafSwitch = prepared !== undefined && input !== undefined;\n if (leafSwitch) {\n // Precomputed leaf plan: replay the admitted shapes for the whole dirty batch.\n let count = 0;\n for (let position = 0; position < input!.length; position++) {\n const slot = input![position]!;\n if (seenSlots[slot] === stamp) continue;\n seenSlots[slot] = stamp;\n const intent = pins[slot]!.intent;\n if (intent === intents[slot]) continue;\n const plan = matchLeaf(slot, intent);\n if (plan === undefined) {\n count = -1;\n break;\n }\n leafSlots[count] = slot;\n leafIntents[count] = intent;\n leafEdges[count] = plan.edges;\n leafTargets[count] = plan.target;\n leafPayloads[count] = plan;\n count++;\n }\n if (count > 0) {\n applyLeaf(count);\n return;\n }\n // The general path re-deduplicates, so it needs its own marks.\n stamp = nextStamp();\n }\n const scanAll = initial || input === undefined;\n for (let position = 0; position < (scanAll ? pins.length : input!.length); position++) {\n const index = scanAll ? position : input![position]!;\n if (!scanAll) {\n if (seenSlots[index] === stamp) continue;\n seenSlots[index] = stamp;\n }\n const pin = pins[index]!;\n const intent = pin.intent;\n if (intent === intents[index]) continue;\n const from = pinNodes[index]!;\n const previous = pinEdges[index]!;\n const edges: Edge[] = [];\n for (const branch of intent) {\n if (!validResistance(branch.resistance))\n validateResistance(branch.resistance, pinLocation(pin));\n const to = pinNodes[requireEndpoint(branch.to, pin)]!;\n if (from === to) continue;\n const old = previous[edges.length];\n if (old?.to === to && old.resistance === branch.resistance) edges.push(old);\n else {\n const edge = {\n pin: index,\n index: edges.length,\n from,\n to,\n resistance: branch.resistance,\n conductance: 1 / branch.resistance,\n };\n edges.push(edge);\n if (old?.to === to) replacedEdges.push(old);\n else topologyChanged = true;\n }\n }\n if (edges.length !== previous.length) topologyChanged = true;\n // The node must stay a leaf hanging off a fixed reference on both sides of the update.\n // With one incident branch on each side no unknown-unknown coupling exists, the old\n // component keeps its own pinned node, the new component keeps its own, and the\n // component and floating censuses provably cannot change. A branch that used to\n // reach an unknown node can remove a whole floating component when several such\n // leaves leave together, so that shape falls back to the general solver.\n const leafShape =\n previous.length === 1 &&\n edges.length === 1 &&\n nodeDegree[from] === 1 &&\n nodes[from]!.reference === undefined &&\n nodes[previous[0]!.to]!.reference !== undefined &&\n nodes[edges[0]!.to]!.reference !== undefined;\n if (leafSwitch && !leafShape) leafSwitch = false;\n // One branch from a leaf node onto a fixed reference: remember the shape so that the\n // next switch between the same references replays it instead of rebuilding edges.\n if (leafShape && intent.length === 1 && edges[0] !== previous[0])\n pendingAdmissions.push({\n slot: index,\n intent,\n branch: intent[0]!,\n target: edges[0]!.to,\n edges,\n });\n updatedSlots.push(index);\n updatedIntents.push(intent);\n updatedEdges.push(edges);\n }\n if (leafSwitch && topologyChanged) {\n for (let position = 0; position < updatedSlots.length; position++) {\n leafSlots[position] = updatedSlots[position]!;\n leafIntents[position] = updatedIntents[position]!;\n leafEdges[position] = updatedEdges[position]!;\n leafTargets[position] = updatedEdges[position]![0]!.to;\n leafPayloads[position] = undefined;\n }\n flushAdmissions();\n applyLeaf(updatedSlots.length);\n return;\n }\n if (blocksStale) {\n // The partition is rebuilt from pinEdges, but neither the buckets nor the numerical\n // cache is discarded. Every retained entry is revalidated by layout, fixed\n // potentials, edges and resistance before reuse, and its factorization is reused\n // only when the normalized matrix and anchors are identical.\n topologyChanged = true;\n }\n const updated = updatedSlots.length;\n if (prepared !== undefined && !topologyChanged && replacedEdges.length === 0) {\n for (let position = 0; position < updated; position++) {\n const index = updatedSlots[position]!;\n intents[index] = updatedIntents[position]!;\n pinEdges[index] = updatedEdges[position]!;\n }\n statistics.solves++;\n statistics.cacheHits += prepared.blocks.length;\n flushAdmissions();\n return;\n }\n let topology = prepared;\n let bucket: string | undefined;\n let restored: TopologySnapshot | undefined;\n /** Prospective rebuilds; committed only when the batch is accepted. */\n let topologyPrepares = 0;\n const dirtyBlocks = new Map<number, PreparedBlock>();\n // Dirty edges are also indexed by slot, so rebinding never hashes a pin number.\n for (let position = 0; position < updatedEdgeSlots.length; position++)\n updatedEdgeLists[updatedEdgeSlots[position]!] = undefined;\n updatedEdgeSlots.length = 0;\n for (let position = 0; position < updated; position++) {\n const index = updatedSlots[position]!;\n updatedEdgeLists[index] = updatedEdges[position]!;\n updatedEdgeSlots.push(index);\n }\n if (topologyChanged) {\n // Only dirty pins are hashed, and the aggregate stays prospective: a rejected solve\n // must not move the bucket a committed graph is filed under.\n let hash = topologyHash;\n let spread = topologySpread;\n for (let position = 0; position < updated; position++) {\n const index = updatedSlots[position]!;\n const next = hashEdges(index, updatedEdges[position]!);\n const previous = pinHashes[index]!;\n if (next === previous) continue;\n hash += next - previous;\n spread ^= previous ^ next;\n }\n bucket = `${hash}:${spread}`;\n restored = lookupTransition(bucket, updatedEdgeLists);\n if (restored !== undefined)\n topology = restoreTopology(restored.topology, pinEdges, updatedEdgeLists);\n else {\n const nextEdges = pinEdges.slice();\n for (let position = 0; position < updated; position++)\n nextEdges[updatedSlots[position]!] = updatedEdges[position]!;\n topology = prepareTopology(nodes, nextEdges);\n topologyPrepares++;\n }\n } else {\n const dirty = new Set<number>();\n for (const edge of replacedEdges) {\n const index = topology!.edgeBlocks[edge.pin]?.[edge.index];\n if (index !== undefined) dirty.add(index);\n }\n for (const index of dirty) {\n dirtyBlocks.set(index, rebindBlock(topology!.blocks[index]!, pinEdges, updatedEdgeLists));\n }\n }\n let nextCache: Map<string, CachedComponent> | undefined;\n const pendingVoltages = new Map<number, number | null>();\n let factorizations = 0;\n let factorizationReuses = 0;\n let cacheHits = topologyChanged ? 0 : topology!.blocks.length - dirtyBlocks.size;\n for (const block of topologyChanged ? topology!.blocks : dirtyBlocks.values()) {\n const { component, key } = block;\n const previous = cache.get(key);\n if (previous !== undefined && sameConfiguration(previous, component, nodes)) {\n cacheHits++;\n (nextCache ??= new Map()).set(key, previous);\n continue;\n }\n const voltages = new Map(\n component.nodes.map((node) => [node, nodes[node]!.reference ?? null]),\n );\n const references = component.nodes.filter((node) => nodes[node]!.reference !== undefined);\n const physical = component.physical ?? component;\n const fail = (reason: string): never => {\n const networkIds = physical.nodes.flatMap((node) => [...nodes[node]!.networks]);\n const resources = physical.nodes.flatMap((node) => nodes[node]!.pins.map((pin) => pin.id));\n const firstPin = nodes[physical.nodes[0]!]!.pins[0]!;\n throw new ElectricalError('ELECTRICAL_SOLVE_FAILED', reason, {\n ...pinLocation(firstPin),\n ...(networkIds[0] === undefined ? {} : { network: networkIds[0] }),\n networks: Object.freeze(networkIds),\n component: Object.freeze(resources),\n });\n };\n let factorization: Factorization | undefined;\n let referenceProgram: ReferenceProgram | undefined;\n if (references.length !== 0) {\n const unknown = component.nodes.filter((node) => nodes[node]!.reference === undefined);\n for (const node of references) voltages.set(node, nodes[node]!.reference!);\n const firstReference = nodes[references[0]!]!.reference!;\n if (references.every((node) => nodes[node]!.reference === firstReference)) {\n for (const node of unknown) voltages.set(node, firstReference);\n } else if (unknown.length !== 0) {\n const count = unknown.length;\n const slots = new Map(unknown.map((node, index) => [node, index]));\n let conductanceScale = 0;\n let voltageScale = 0;\n let coupled = false;\n for (const node of references) {\n voltageScale = Math.max(voltageScale, Math.abs(nodes[node]!.reference!));\n }\n for (const edge of component.edges) {\n const from = slots.has(edge.from);\n const to = slots.has(edge.to);\n if (from || to) conductanceScale = Math.max(conductanceScale, edge.conductance);\n if (from && to) coupled = true;\n }\n if (!(conductanceScale > 0) || !(voltageScale > 0)) fail('Invalid equation scaling.');\n if (!coupled) {\n referenceProgram = referencePrograms.find((program) =>\n program.matches(component.edges, unknown),\n );\n if (referenceProgram === undefined) {\n referenceProgram = compileReferenceProgram(unknown, component.edges, slots, nodes);\n if (referenceProgram !== undefined) {\n referencePrograms.push(referenceProgram);\n if (referencePrograms.length > referenceProgramLimit) referencePrograms.shift();\n }\n }\n }\n const matrix = new Float64Array(coupled ? count * count : 0);\n let anchors: Float64Array;\n let right: Float64Array;\n if (referenceProgram !== undefined) {\n ({ anchors, right } = referenceProgram.assemble(\n component.edges,\n conductanceScale,\n voltageScale,\n ));\n } else {\n const anchorTerms: number[][] = Array.from({ length: count }, () => []);\n const rightTerms: number[][] = Array.from({ length: count }, () => []);\n for (const edge of component.edges) {\n const from = slots.get(edge.from);\n const to = slots.get(edge.to);\n const conductance = edge.conductance / conductanceScale;\n if (from !== undefined && to !== undefined) {\n const slot = Math.min(from, to) * count + Math.max(from, to);\n matrix[slot] = matrix[slot]! + conductance;\n } else if (from !== undefined || to !== undefined) {\n const slot = from ?? to!;\n const reference = nodes[from === undefined ? edge.from : edge.to]!.reference!;\n anchorTerms[slot]!.push(conductance);\n rightTerms[slot]!.push(conductance * (reference / voltageScale));\n }\n }\n anchors = Float64Array.from(anchorTerms, (terms) => sum(terms));\n right = Float64Array.from(rightTerms, (terms) => sum(terms));\n }\n if (\n previous?.factorization !== undefined &&\n arraysEqual(previous.factorization.matrix, matrix) &&\n arraysEqual(previous.factorization.anchors, anchors)\n ) {\n factorization = previous.factorization;\n factorizationReuses++;\n } else {\n factorization = factorize(matrix, anchors, fail);\n factorizations++;\n }\n const solution = substitute(factorization, right, fail);\n unknown.forEach((node, index) => {\n const voltage = cleanZero(solution[index]! * voltageScale);\n if (!Number.isFinite(voltage)) fail('Non-finite node voltage.');\n voltages.set(node, voltage);\n });\n }\n }\n const entry: CachedComponent = {\n nodes: component.nodes,\n references: component.nodes.map((node) => nodes[node]!.reference),\n edges: component.edges,\n voltages: component.nodes.map((node) => voltages.get(node)!),\n factorization,\n };\n (nextCache ??= new Map()).set(key, entry);\n for (const [node, voltage] of voltages) {\n if (publishedVoltages[node] !== voltage) pendingVoltages.set(node, voltage);\n }\n }\n const pending = new Map<ElectricalPin, PinSample>();\n changedCount = 0;\n for (const [node, voltage] of pendingVoltages) {\n const slots = nodeSlots[node]!;\n for (let at = 0; at < slots.length; at++) {\n const slot = slots[at]!;\n const pin = pins[slot]!;\n const level =\n voltage === null || pin.low === undefined\n ? 'unknown'\n : voltage <= pin.low\n ? 'low'\n : voltage >= pin.high!\n ? 'high'\n : 'unknown';\n const status = voltage === null ? 'floating' : 'valid';\n const previous = pin.sample;\n const dirty =\n previous.voltage !== voltage || previous.level !== level || previous.status !== status;\n if (dirty) changedSlots[changedCount++] = slot;\n if (dirty || statistics.solves === 0) {\n pending.set(\n pin,\n Object.freeze({\n voltage: voltage === null ? null : cleanZero(voltage),\n level,\n status,\n }),\n );\n }\n }\n }\n // The buffer is trimmed to `changedCount`, so ordering is an in-place insertion sort\n // of the written prefix.\n for (let index = 1; index < changedCount; index++) {\n const slot = changedSlots[index]!;\n let position = index;\n while (position > 0 && changedSlots[position - 1]! > slot) {\n changedSlots[position] = changedSlots[position - 1]!;\n position--;\n }\n changedSlots[position] = slot;\n }\n // No pin, intent snapshot, adjacency or factorization cache changes before acceptance.\n for (const [pin, sample] of pending) pin.sample = sample;\n for (const [node, voltage] of pendingVoltages) publishedVoltages[node] = voltage;\n for (let position = 0; position < updated; position++) {\n const index = updatedSlots[position]!;\n const edges = updatedEdges[position]!;\n syncDegrees(pinEdges[index]!, edges);\n intents[index] = updatedIntents[position]!;\n pinEdges[index] = edges;\n setPinHash(index, edges);\n }\n if (topologyChanged) cache = nextCache ?? new Map();\n else {\n // Column-wise merge keeps a rejected solve from leaving a half-rebuilt cache.\n if (nextCache !== undefined) for (const [key, value] of nextCache) cache.set(key, value);\n for (const [index, block] of dirtyBlocks) topology!.blocks[index] = block;\n }\n prepared = topology!;\n // A rejected solve leaves the stale flag set, so a retry rebuilds and revalidates the\n // partition instead of trusting blocks it never committed.\n blocksStale = false;\n if (topologyChanged) {\n const admitted: TopologySnapshot =\n restored !== undefined && topology === restored.topology\n ? restored\n : {\n // Reusing the id keeps the bucket age stable while a graph is only re-bound.\n id: restored?.id ?? nextTopologyId++,\n cost: restored?.cost ?? topologyCost(topology!),\n topology: topology!,\n // A confirmed bucket hit already carries the exact hashes.\n hashes: restored?.hashes ?? pinHashes.slice(),\n };\n rememberTransition(bucket!, admitted);\n }\n statistics.solves++;\n statistics.components = topology!.components;\n statistics.floatingComponents = topology!.floatingComponents;\n statistics.factorizations += factorizations;\n statistics.factorizationReuses += factorizationReuses;\n statistics.cacheHits += cacheHits;\n statistics.topologyPrepares += topologyPrepares;\n flushAdmissions();\n }\n}\n","/**\n * Binary min-heap over parallel arrays. Every push/pop used to allocate a `{ time, order,\n * value }` record; a timed board pushes one continuation per suspension, so the flat form\n * keeps the scheduler loop allocation-free.\n */\nexport class EventQueue<T> {\n private readonly times: number[] = [];\n private readonly orders: number[] = [];\n private readonly values: (T | undefined)[] = [];\n private size = 0;\n private sequence = 0;\n get time(): number {\n return this.size === 0 ? Infinity : this.times[0]!;\n }\n push(time: number, value: T): void {\n const at = this.size++;\n this.times[at] = time;\n this.orders[at] = this.sequence++;\n this.values[at] = value;\n this.siftUp(at);\n }\n pop(): T {\n const value = this.values[0]!;\n const last = --this.size;\n if (last >= 0) {\n this.times[0] = this.times[last]!;\n this.orders[0] = this.orders[last]!;\n this.values[0] = this.values[last]!;\n this.times[last] = 0;\n this.orders[last] = 0;\n this.values[last] = undefined;\n this.siftDown();\n }\n return value;\n }\n clear(): void {\n this.size = 0;\n }\n private before(first: number, second: number): boolean {\n const times = this.times;\n const a = times[first]!;\n const b = times[second]!;\n return a < b || (a === b && this.orders[first]! < this.orders[second]!);\n }\n private swap(first: number, second: number): void {\n const times = this.times;\n const orders = this.orders;\n const values = this.values;\n const time = times[first]!;\n const order = orders[first]!;\n const value = values[first]!;\n times[first] = times[second]!;\n orders[first] = orders[second]!;\n values[first] = values[second];\n times[second] = time;\n orders[second] = order;\n values[second] = value;\n }\n private siftUp(at: number): void {\n while (at > 0) {\n const parent = (at - 1) >>> 1;\n if (!this.before(at, parent)) break;\n this.swap(at, parent);\n at = parent;\n }\n }\n private siftDown(): void {\n const size = this.size;\n let at = 0;\n for (;;) {\n const left = at * 2 + 1;\n if (left >= size) break;\n const right = left + 1;\n const child = right < size && this.before(right, left) ? right : left;\n if (!this.before(child, at)) break;\n this.swap(at, child);\n at = child;\n }\n }\n}\nexport class ActivationQueue<T> {\n private readonly entries: T[] = [];\n private readonly words: number[] = [];\n /**\n * Active word indices in `[0, activeCount)`. The array keeps its high-water length:\n * truncating it would right-trim the backing store on every boundary.\n */\n private readonly activeWords: number[] = [];\n private activeCount = 0;\n get size(): number {\n return this.activeCount;\n }\n register(entry: T): number {\n return this.entries.push(entry) - 1;\n }\n add(slot: number): void {\n const word = slot >>> 5;\n const previous = this.words[word] ?? 0;\n if (previous === 0) this.activeWords[this.activeCount++] = word;\n this.words[word] = previous | (1 << (slot & 31));\n }\n /**\n * Visits every active entry in board order without materialising a batch. Entries added\n * by the visitor land past the visited range and survive.\n */\n drain(visit: (entry: T) => void): void {\n const active = this.activeWords;\n const visited = this.activeCount;\n if (visited === 0) return;\n if (visited > 1) {\n // Word indices arrive in insertion order; a handful of words sort faster in place\n // than through a comparator call, and the stale tail must not be reordered.\n for (let index = 1; index < visited; index++) {\n const word = active[index]!;\n let position = index;\n while (position > 0 && active[position - 1]! > word) {\n active[position] = active[position - 1]!;\n position--;\n }\n active[position] = word;\n }\n }\n for (let index = 0; index < visited; index++) {\n const word = active[index]!;\n let bits = this.words[word]!;\n this.words[word] = 0;\n const base = word * 32;\n while (bits !== 0) {\n visit(this.entries[base + 31 - Math.clz32(bits & -bits)]!);\n bits &= bits - 1;\n }\n }\n if (this.activeCount === visited) this.activeCount = 0;\n else {\n // A word re-added during the drain was appended past `visited`; shift it down.\n for (let index = visited; index < this.activeCount; index++)\n active[index - visited] = active[index]!;\n this.activeCount -= visited;\n }\n }\n clear(): void {\n this.entries.length = 0;\n this.words.length = 0;\n this.activeWords.length = 0;\n this.activeCount = 0;\n }\n}\n\nexport class Fifo<T> {\n private readonly values: (T | undefined)[] = [];\n private head = 0;\n private tail = 0;\n get length(): number {\n return this.tail - this.head;\n }\n push(value: T): void {\n // The backing array keeps its high-water length, so a push never clears elements.\n this.values[this.tail++] = value;\n }\n shift(): T {\n const value = this.values[this.head]!;\n this.values[this.head++] = undefined;\n if (this.head === this.tail) {\n this.head = 0;\n this.tail = 0;\n }\n return value;\n }\n clear(): void {\n this.values.length = 0;\n this.head = 0;\n this.tail = 0;\n }\n drain(): T[] {\n const result = this.values.slice(this.head, this.tail) as T[];\n this.clear();\n return result;\n }\n}\n","import type {\n ArgumentIR,\n BinaryOperator,\n DeclarationIR,\n MemoryRefIR,\n NumericBuiltin,\n OperationIR,\n PinRefIR,\n RegionIR,\n UnaryOperator,\n ValueRegionIR,\n ValueTypeIR,\n} from '@mica-js/device-model';\nimport {\n checkBoolean,\n createBytes,\n createEnum,\n createRecord,\n equalValues,\n nonNull,\n readIndex,\n} from '@mica-js/compiler';\nimport { range, same } from './values.js';\n\n/**\n * A generated observation plan for one static source path.\n *\n * The generic path already compiles each computation to JavaScript; what this plan adds\n * is binding. The source path, its projection, the resource objects and the resource\n * slots are resolved once, so a publication round performs no host or resource name\n * resolution, no dependency-stack tracking, no derived cache staleness check and no\n * per-round dependency map merge. Every operation of every branch is emitted from the\n * supported set; anything outside it rejects the whole plan and the caller keeps the\n * generic path.\n */\nexport interface PlannedSlot {\n readonly version: number;\n}\n\nexport interface ObservationMemory {\n readonly bytes: Uint8Array;\n readonly view: DataView;\n readonly slot: PlannedSlot;\n}\n\nexport interface ObservationTarget {\n readonly declarations: ReadonlyMap<string, DeclarationIR>;\n readonly states: ReadonlyMap<string, unknown>;\n readonly pins: ReadonlyMap<string, { readonly sample: unknown }>;\n readonly stateResources: ReadonlyMap<string, PlannedSlot>;\n readonly sampleResources: ReadonlyMap<string, PlannedSlot>;\n readonly memoryResources: ReadonlyMap<string, PlannedSlot>;\n memoryPlan(ref: unknown): ObservationMemory;\n read(kind: string, name: string): unknown;\n}\n\nexport interface CompiledObservation {\n readonly key: string;\n readonly path: readonly string[];\n /** Generated reader source; kept for tests and diagnostics, not evaluated again. */\n readonly source: string;\n /** Generated comparator source. */\n readonly comparison: string;\n readonly slots: readonly PlannedSlot[];\n /** Raw value of the source path, exactly what an unmodified derived read returns. */\n readonly evaluate: () => unknown;\n readonly equals: (previous: unknown, current: unknown) => boolean;\n /** Non-primitive results are snapshotted for the immutable observation baseline. */\n readonly needsSnapshot: boolean;\n}\n\nexport type ObservationCompilation =\n | { readonly ok: true; readonly plan: CompiledObservation }\n | { readonly ok: false; readonly reason: string };\n\nconst unaryOperators: Partial<Record<UnaryOperator, string>> = {\n positive: '+',\n negate: '-',\n not: '!',\n bitNot: '~',\n};\nconst binaryOperators: Partial<Record<BinaryOperator, string>> = {\n add: '+',\n subtract: '-',\n multiply: '*',\n divide: '/',\n remainder: '%',\n power: '**',\n lessThan: '<',\n lessThanOrEqual: '<=',\n greaterThan: '>',\n greaterThanOrEqual: '>=',\n concat: '+',\n bitAnd: '&',\n bitOr: '|',\n bitXor: '^',\n shiftLeft: '<<',\n shiftRight: '>>',\n shiftRightUnsigned: '>>>',\n};\nconst numericBuiltins = new Set<NumericBuiltin>([\n 'isNaN',\n 'isFinite',\n 'isInteger',\n 'isSafeInteger',\n 'abs',\n 'floor',\n 'ceil',\n 'trunc',\n 'round',\n 'sqrt',\n 'min',\n 'max',\n 'pow',\n]);\nconst numberBuiltins = new Set<NumericBuiltin>(['isNaN', 'isFinite', 'isInteger', 'isSafeInteger']);\n\nfunction load(kind: string, memory: ObservationMemory, offset: unknown): number {\n const size = kind.startsWith('load8') ? 1 : kind.startsWith('load16') ? 2 : 4;\n const at = range(memory.bytes, offset, size);\n if (size === 1) return memory.bytes[at]!;\n return size === 2\n ? memory.view.getUint16(at, kind.endsWith('le'))\n : memory.view.getUint32(at, kind.endsWith('le'));\n}\nfunction copyBytes(memory: ObservationMemory, offset: unknown, length: unknown): Uint8Array {\n const at = range(memory.bytes, offset, length);\n return memory.bytes.slice(at, at + Number(length));\n}\nfunction assertFalse(message: unknown): never {\n throw new Error(message === undefined ? 'Assertion failed' : String(message));\n}\nfunction sameBytes(left: Uint8Array, right: Uint8Array): boolean {\n for (let index = 0; index < left.length; index++) if (left[index] !== right[index]) return false;\n return true;\n}\nconst helpers = Object.freeze({\n checkBoolean,\n createBytes,\n createEnum,\n createRecord,\n equalValues,\n nonNull,\n readIndex,\n load,\n copyBytes,\n assertFalse,\n sameBytes,\n});\n\nclass Unsupported extends Error {}\n\nfunction reject(reason: string): never {\n throw new Unsupported(reason);\n}\n\n/** Emits one generated reader; every unsupported operation rejects the whole plan. */\nclass ReaderEmitter {\n private readonly bindings: unknown[] = [];\n private readonly bindingIds = new Map<unknown, number>();\n private readonly slots: PlannedSlot[] = [];\n private readonly nested: string[] = [];\n private readonly named = new Map<string, string>();\n private readonly visiting = new Set<string>();\n /** Result ids already defined by an emitted operation, for static legality checks. */\n private readonly results = new Set<number>();\n private readonly buffers: string[][] = [[]];\n private depth = 0;\n private serial = 0;\n\n constructor(private readonly target: ObservationTarget) {\n this.bindings.push(target);\n this.bindingIds.set(target, 0);\n }\n\n build(declaration: Extract<DeclarationIR, { kind: 'derived' }>, path: readonly string[]): string {\n const read = this.nestedDerived(declaration);\n // The observation source is the full static path: project every suffix field with\n // the same step the generic source walk performs, so the reader value, the\n // comparator type and the snapshot decision all describe the observed field.\n if (path.length === 1) {\n this.line(`return ${read}();`);\n } else {\n this.line(`let projected = ${read}();`);\n for (let index = 1; index < path.length; index++)\n this.line(`projected = projected[${this.ref(path[index]!)}];`);\n this.line('return projected;');\n }\n return [\n 'function () {',\n ...this.nested.map((text) => text),\n ...this.buffers[0]!.map((text) => ` ${text}`),\n '}',\n ].join('\\n');\n }\n\n slotsUsed(): readonly PlannedSlot[] {\n return this.slots;\n }\n\n bindingTable(): readonly unknown[] {\n return this.bindings;\n }\n\n private get lines(): string[] {\n return this.buffers[this.buffers.length - 1]!;\n }\n\n private line(text: string): void {\n this.lines.push(`${' '.repeat(this.depth)}${text}`);\n }\n\n private block(header: string, body: () => void): void {\n this.line(`${header} {`);\n this.depth++;\n body();\n this.depth--;\n this.line('}');\n }\n\n private bind(value: unknown): number {\n const object = value !== null && typeof value === 'object';\n if (!object && Object.is(value, -0)) return this.bindings.push(value) - 1;\n const existing = this.bindingIds.get(value);\n if (existing !== undefined) return existing;\n const index = this.bindings.push(value) - 1;\n this.bindingIds.set(value, index);\n return index;\n }\n\n private ref(value: unknown): string {\n return `B[${this.bind(value)}]`;\n }\n\n private slot(slot: PlannedSlot): void {\n if (!this.slots.includes(slot)) this.slots.push(slot);\n }\n\n private nestedSource(name: string, params: readonly string[], body: () => void): string {\n this.buffers.push([]);\n const outer = this.depth;\n this.depth = 0;\n try {\n body();\n } finally {\n this.depth = outer;\n }\n const lines = this.buffers.pop()!;\n const text = [`function ${name}(${params.join(', ')}) {`, ...lines, '}'].join('\\n');\n this.nested.push(text);\n return name;\n }\n\n private nestedDerived(declaration: Extract<DeclarationIR, { kind: 'derived' }>): string {\n const key = `derived:${declaration.name}`;\n const existing = this.named.get(key);\n if (existing) return existing;\n if (this.visiting.has(key)) reject(`recursive derived ${declaration.name}`);\n const name = `d${this.serial++}`;\n this.named.set(key, name);\n this.visiting.add(key);\n try {\n this.nestedSource(name, [], () => this.region(declaration.value.body, undefined));\n } finally {\n this.visiting.delete(key);\n }\n return name;\n }\n\n private nestedFunction(\n name: string,\n declaration: Extract<DeclarationIR, { kind: 'function' }>,\n ): string {\n const key = `function:${name}`;\n const existing = this.named.get(key);\n if (existing) return existing;\n if (this.visiting.has(key)) reject(`recursive pure call ${name}`);\n const id = `f${this.serial++}`;\n this.named.set(key, id);\n this.visiting.add(key);\n try {\n const params = declaration.params.map((_, index) => `p${index}`);\n this.nestedSource(id, params, () => {\n const outer = this.params;\n this.params = params;\n try {\n this.region(declaration.body, undefined);\n } finally {\n this.params = outer;\n }\n });\n } finally {\n this.visiting.delete(key);\n }\n return id;\n }\n\n private params: readonly string[] | undefined;\n\n private value(id: number): string {\n if (!this.results.has(id)) reject(`result ${id} is used before it is defined`);\n return `v${id}`;\n }\n\n private defineResult(id: number): string {\n this.results.add(id);\n return `v${id}`;\n }\n\n private region(region: RegionIR, output: { slot: string; label: string } | undefined): void {\n for (const operation of region.operations) this.operation(operation, output);\n }\n\n private valueRegion(region: ValueRegionIR, slot: string): void {\n const label = `s${this.serial++}`;\n this.line(`${label}: {`);\n this.depth++;\n this.region(region.body, { slot, label });\n this.depth--;\n this.line('}');\n }\n\n private argument(argument: ArgumentIR): string {\n if (argument.kind !== 'value') reject('resource argument');\n return this.value(argument.value);\n }\n\n private memoryRef(ref: MemoryRefIR, kind: string): ObservationMemory {\n if (ref.kind === 'parameter') reject(`parameterised memory ${kind}`);\n const memory = this.target.memoryPlan(ref.name);\n this.slot(memory.slot);\n return memory;\n }\n\n private pinRef(ref: PinRefIR, kind: string): { readonly sample: unknown } {\n if (ref.kind === 'parameter') reject(`parameterised pin ${kind}`);\n const pin = this.target.pins.get(ref.name);\n const slot = this.target.sampleResources.get(ref.name);\n if (!pin || !slot) reject(`unknown pin ${ref.name}`);\n this.slot(slot);\n return pin;\n }\n\n private operation(\n operation: OperationIR,\n output: { slot: string; label: string } | undefined,\n ): void {\n const assign = (expression: string): void => {\n if (!('result' in operation)) reject('resultless operation');\n this.line(`const ${this.defineResult(operation.result)} = ${expression};`);\n };\n const child = (region: RegionIR): void => this.region(region, output);\n switch (operation.kind) {\n case 'constant': {\n const constant = operation.constant;\n if (constant.kind === 'bytes')\n assign(\n `H.createBytes(${this.ref(Object.freeze(Array.from(createBytes(constant.value))))})`,\n );\n else if (constant.kind === 'enum')\n assign(this.ref(createEnum(constant.name, constant.member)));\n else if (constant.kind === 'record')\n assign(\n this.ref(\n createRecord(constant.fields.map((field) => [field.name, field.value] as const)),\n ),\n );\n else if (constant.kind === 'none') assign('null');\n else assign(this.ref(constant.value));\n break;\n }\n case 'read': {\n if (operation.resource === 'state') {\n const slot = this.target.stateResources.get(operation.name);\n if (!slot || !this.target.states.has(operation.name))\n reject(`unknown state ${operation.name}`);\n this.slot(slot);\n assign(`${this.ref(this.target.states)}.get(${this.ref(operation.name)})`);\n } else if (operation.resource === 'derived') {\n const declaration = this.target.declarations.get(operation.name);\n if (declaration?.kind !== 'derived') reject(`unknown derived ${operation.name}`);\n assign(`${this.nestedDerived(declaration)}()`);\n } else {\n assign(\n `${this.ref(this.target)}.read(${this.ref(operation.resource)}, ${this.ref(operation.name)})`,\n );\n }\n break;\n }\n case 'parameter': {\n const params = this.params;\n if (!params || operation.index >= params.length) reject('value parameter outside a call');\n assign(params[operation.index]!);\n break;\n }\n case 'unary': {\n const operator = unaryOperators[operation.operator];\n if (!operator) reject(`unsupported unary ${operation.operator}`);\n assign(`(${operator}${this.value(operation.value)})`);\n break;\n }\n case 'binary': {\n if (operation.operator === 'equal' || operation.operator === 'notEqual')\n assign(\n `${operation.operator === 'notEqual' ? '!' : ''}H.equalValues(${this.value(operation.left)}, ${this.value(operation.right)})`,\n );\n else {\n const operator = binaryOperators[operation.operator];\n if (!operator) reject(`unsupported binary ${operation.operator}`);\n assign(`(${this.value(operation.left)} ${operator} ${this.value(operation.right)})`);\n }\n break;\n }\n case 'numeric': {\n if (!numericBuiltins.has(operation.builtin))\n reject(`unsupported builtin ${operation.builtin}`);\n const receiver = numberBuiltins.has(operation.builtin) ? 'Number' : 'Math';\n assign(\n `${receiver}.${operation.builtin}(${operation.args.map((id) => this.value(id)).join(', ')})`,\n );\n break;\n }\n case 'record':\n assign(\n `H.createRecord([${operation.fields\n .map((field) => `[${this.ref(field.name)}, ${this.value(field.value)}]`)\n .join(', ')}])`,\n );\n break;\n case 'field':\n assign(`${this.value(operation.value)}[${this.ref(operation.field)}]`);\n break;\n case 'bytes':\n assign(`H.createBytes([${operation.elements.map((id) => this.value(id)).join(', ')}])`);\n break;\n case 'length':\n assign(`${this.value(operation.value)}.length`);\n break;\n case 'index':\n assign(`H.readIndex(${this.value(operation.value)}, ${this.value(operation.index)})`);\n break;\n case 'optional':\n assign(this.value(operation.value));\n break;\n case 'isNone':\n assign(`(${this.value(operation.value)} === null)`);\n break;\n case 'nonNull':\n assign(`H.nonNull(${this.value(operation.value)})`);\n break;\n case 'localRead':\n assign(`l${operation.local}`);\n break;\n case 'local':\n this.line(`let l${operation.local} = ${this.value(operation.initial)};`);\n break;\n case 'localWrite':\n this.line(`l${operation.local} = ${this.value(operation.value)};`);\n break;\n case 'memoryLength':\n assign(`${this.ref(this.memoryRef(operation.memory, operation.kind))}.bytes.length`);\n break;\n case 'load8':\n case 'load16le':\n case 'load16be':\n case 'load32le':\n case 'load32be':\n assign(\n `H.load(${this.ref(operation.kind)}, ${this.ref(this.memoryRef(operation.memory, operation.kind))}, ${this.value(operation.offset)})`,\n );\n break;\n case 'copyBytes': {\n const memory = this.memoryRef(operation.memory, operation.kind);\n assign(\n `H.copyBytes(${this.ref(memory)}, ${this.value(operation.offset)}, ${this.value(operation.length)})`,\n );\n break;\n }\n case 'readSample':\n assign(`${this.ref(this.pinRef(operation.pin, operation.kind))}.sample`);\n break;\n case 'callValue': {\n if (!operation.pure) reject('impure call');\n const declaration = this.target.declarations.get(operation.name);\n if (declaration?.kind !== 'function' || !declaration.pure)\n reject(`unknown pure function ${operation.name}`);\n assign(\n `${this.nestedFunction(operation.name, declaration)}(${operation.args\n .map((argument) => this.argument(argument))\n .join(', ')})`,\n );\n break;\n }\n case 'if':\n this.block(`if (H.checkBoolean(${this.value(operation.condition)}))`, () =>\n child(operation.yes),\n );\n if (operation.no) this.block('else', () => child(operation.no!));\n break;\n case 'match': {\n operation.arms.forEach((arm, index) => {\n const pattern = arm.pattern;\n const constant =\n pattern.kind === 'none'\n ? null\n : pattern.kind === 'enum'\n ? createEnum(pattern.name, pattern.member)\n : pattern.value;\n this.block(\n `${index ? 'else if' : 'if'} (H.equalValues(${this.value(operation.value)}, ${this.ref(constant)}))`,\n () => child(arm.body),\n );\n });\n if (operation.otherwise)\n this.block(operation.arms.length ? 'else' : '', () => child(operation.otherwise!));\n break;\n }\n case 'while':\n this.block('while (true)', () => {\n const slot = `s${this.serial++}`;\n this.line(`let ${slot};`);\n this.valueRegion(operation.test, slot);\n this.line(`if (!H.checkBoolean(${slot})) break;`);\n this.block('', () => child(operation.body));\n });\n break;\n case 'loop':\n this.block('while (true)', () => child(operation.body));\n break;\n case 'and':\n case 'or': {\n const slot = this.defineResult(operation.result);\n this.line(`let ${slot} = H.checkBoolean(${this.value(operation.left)});`);\n this.block(`if (${operation.kind === 'or' ? '!' : ''}${slot})`, () => {\n this.valueRegion(operation.right, slot);\n this.line(`${slot} = H.checkBoolean(${slot});`);\n });\n break;\n }\n case 'select': {\n const slot = this.defineResult(operation.result);\n this.line(`let ${slot};`);\n this.block(`if (H.checkBoolean(${this.value(operation.condition)}))`, () =>\n this.valueRegion(operation.yes, slot),\n );\n this.block('else', () => this.valueRegion(operation.no, slot));\n break;\n }\n case 'assert':\n this.block(`if (!H.checkBoolean(${this.value(operation.condition)}))`, () => {\n if (operation.message) {\n const slot = `s${this.serial++}`;\n this.line(`let ${slot};`);\n this.valueRegion(operation.message, slot);\n this.line(`H.assertFalse(${slot});`);\n } else this.line('H.assertFalse(undefined);');\n });\n break;\n case 'return':\n this.line('return;');\n break;\n case 'returnValue':\n this.line(`return ${this.value(operation.value)};`);\n break;\n case 'break':\n this.line('break;');\n break;\n case 'continue':\n this.line('continue;');\n break;\n case 'yield':\n if (!output) reject('yield outside a value region');\n this.line(`${output.slot} = ${this.value(operation.value)};`);\n this.line(`break ${output.label};`);\n break;\n default: {\n const kind = (operation as { kind?: unknown }).kind;\n reject(`unsupported operation ${String(kind)}`);\n }\n }\n }\n}\n\ninterface SemanticType {\n readonly type: ValueTypeIR | undefined;\n}\n\nfunction fieldType(\n declarations: ReadonlyMap<string, DeclarationIR>,\n type: ValueTypeIR | undefined,\n field: string,\n): ValueTypeIR | undefined {\n if (!type) return undefined;\n if (type.kind === 'optional') return undefined;\n if (type.kind === 'record') {\n const declaration = declarations.get(type.name);\n if (declaration?.kind !== 'record') return undefined;\n const entry = declaration.fields.find((candidate) => candidate.name === field);\n return entry ? { kind: entry.type } : undefined;\n }\n if (type.kind === 'sample') {\n if (field === 'voltage') return { kind: 'optional', inner: { kind: 'number' } };\n if (field === 'level' || field === 'status') return { kind: 'enum', name: 'Logic' };\n }\n return undefined;\n}\n\nfunction resolvePathType(\n declarations: ReadonlyMap<string, DeclarationIR>,\n type: ValueTypeIR,\n path: readonly string[],\n): SemanticType {\n let current: ValueTypeIR | undefined = type;\n for (let index = 1; index < path.length; index++)\n current = fieldType(declarations, current, path[index]!);\n return { type: current };\n}\n\nfunction primitive(type: ValueTypeIR | undefined): boolean {\n if (!type) return false;\n if (type.kind === 'optional') return primitive(type.inner);\n return ['number', 'bool', 'string', 'enum'].includes(type.kind);\n}\n\n/**\n * Stable observation comparison for the declared source type. Numbers compare NaN as\n * equal and treat positive and negative zero as equal; bytes compare length and\n * content; records and samples compare their declared fields recursively; nullables\n * compare none first. Language equality is deliberately not reused here.\n */\nfunction comparison(\n declarations: ReadonlyMap<string, DeclarationIR>,\n type: ValueTypeIR | undefined,\n left: string,\n right: string,\n): string | undefined {\n if (!type) return undefined;\n switch (type.kind) {\n case 'number':\n return `(${left} === ${right} || (${left} !== ${left} && ${right} !== ${right}))`;\n case 'bool':\n case 'string':\n case 'enum':\n return `(${left} === ${right})`;\n case 'bytes':\n return `(${left} === ${right} || (${left} !== null && ${right} !== null && typeof ${left} === \"object\" && typeof ${right} === \"object\" && ${left}.length === ${right}.length && H.sameBytes(${left}, ${right})))`;\n case 'sample': {\n const fields = ['voltage', 'level', 'status'].map((field) =>\n comparison(\n declarations,\n fieldType(declarations, type, field),\n `${left}[${JSON.stringify(field)}]`,\n `${right}[${JSON.stringify(field)}]`,\n ),\n );\n if (fields.some((field) => field === undefined)) return undefined;\n return `(${left} === ${right} || (${left} !== null && ${right} !== null && typeof ${left} === \"object\" && typeof ${right} === \"object\" && ${fields.join(' && ')}))`;\n }\n case 'record': {\n const declaration = declarations.get(type.name);\n if (declaration?.kind !== 'record' || !declaration.fields.length) return undefined;\n const fields = declaration.fields.map((field) =>\n comparison(\n declarations,\n { kind: field.type },\n `${left}[${JSON.stringify(field.name)}]`,\n `${right}[${JSON.stringify(field.name)}]`,\n ),\n );\n if (fields.some((field) => field === undefined)) return undefined;\n return `(${left} === ${right} || (${left} !== null && ${right} !== null && typeof ${left} === \"object\" && typeof ${right} === \"object\" && ${fields.join(' && ')}))`;\n }\n case 'optional': {\n const inner = comparison(declarations, type.inner, left, right);\n if (inner === undefined) return undefined;\n return `(${left} === ${right} || (${left} === null ? ${right} === null : (${right} !== null && ${inner})))`;\n }\n default:\n return undefined;\n }\n}\n\n/** Bind a source path to one generated reader and one generated comparator. */\nexport function compileObservation(\n target: ObservationTarget,\n key: string,\n path: readonly string[],\n): ObservationCompilation {\n const declaration = target.declarations.get(path[0]!);\n if (declaration?.kind !== 'derived')\n return { ok: false, reason: 'source root is not a derived declaration' };\n const { type } = resolvePathType(target.declarations, declaration.type, path);\n if (type === undefined) return { ok: false, reason: 'source field type is not resolvable' };\n if (type.kind === 'intent')\n return { ok: false, reason: 'intent has no stable content comparison' };\n try {\n const emitter = new ReaderEmitter(target);\n const source = emitter.build(declaration, path);\n const factory = new Function('B', 'H', `\"use strict\"; return (${source});`) as (\n bindings: readonly unknown[],\n helpers: unknown,\n ) => () => unknown;\n const evaluate = factory(emitter.bindingTable(), helpers);\n const compare = comparison(target.declarations, type, 'a', 'b');\n const comparisonSource = `function (a, b) { return ${compare ?? 'H.same(a, b)'}; }`;\n const comparer = new Function('H', `\"use strict\"; return (${comparisonSource});`)({\n ...helpers,\n same,\n }) as (previous: unknown, current: unknown) => boolean;\n return {\n ok: true,\n plan: {\n key,\n path: [...path],\n source,\n comparison: comparisonSource,\n slots: emitter.slotsUsed(),\n evaluate,\n equals: comparer,\n needsSnapshot: !primitive(type),\n },\n };\n } catch (cause) {\n return {\n ok: false,\n reason:\n cause instanceof Unsupported\n ? cause.message\n : `unexpected code generation failure: ${cause instanceof Error ? cause.message : String(cause)}`,\n };\n }\n}\n","import {\n compileBody,\n compileComputation,\n compileResumableBody,\n compileSynchronousBody,\n type CompiledBody,\n type ExecutionHost,\n type ResumableFrame,\n type ResumableProgram,\n type SynchronousProgram,\n} from '@mica-js/compiler';\nimport type { ComputationIR, DeviceIR, RegionIR } from '@mica-js/device-model';\nimport type { Instance } from './instance';\n\nconst compiledBodies = new WeakMap<RegionIR, CompiledBody>();\nconst resumablePrograms = new WeakMap<RegionIR, ResumableProgram | null>();\nconst compiledComputations = new WeakMap<ComputationIR, (host: ExecutionHost) => unknown>();\n/**\n * Synchronous programs are instance independent, but their static function resolution\n * belongs to one device model. The outer key prevents reusing a root region compiled\n * against another model's function table; `null` records a whole-body fallback.\n */\nconst synchronousPrograms = new WeakMap<DeviceIR, WeakMap<RegionIR, SynchronousProgram | null>>();\nexport const MAX_TIME = 7_200_000_000_000_000;\nexport function time(value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value))\n throw new TypeError('Time must be a finite integer');\n if (value < 0 || value > MAX_TIME) throw new RangeError('Time out of range');\n return value === 0 ? 0 : value;\n}\nexport function body(region: RegionIR): CompiledBody {\n let result = compiledBodies.get(region);\n if (!result) {\n result = compileBody(region);\n compiledBodies.set(region, result);\n }\n return result;\n}\n/**\n * Compile one reaction body for one device model. Static callees are resolved from the\n * same declaration environment the generator uses. A compiler decline is cached as a\n * whole-body fallback; execution errors are never caught here and never replay effects.\n */\nexport function synchronousBody(\n instance: Instance,\n region: RegionIR,\n): SynchronousProgram | undefined {\n const model = instance.entry.model;\n let cache = synchronousPrograms.get(model);\n if (cache === undefined) {\n cache = new WeakMap();\n synchronousPrograms.set(model, cache);\n }\n const cached = cache.get(region);\n if (cached !== undefined) return cached ?? undefined;\n const program = compileSynchronousBody(region, {\n bindResources: true,\n resolveFunction: (name) => {\n const declaration = instance.declarations.get(name);\n return declaration?.kind === 'function' ? declaration.body : undefined;\n },\n });\n cache.set(region, program ?? null);\n return program;\n}\nexport function resumable(region: RegionIR): ResumableProgram | undefined {\n let result = resumablePrograms.get(region);\n if (result === undefined) {\n result = compileResumableBody(region, { bindResources: true }) ?? null;\n resumablePrograms.set(region, result);\n }\n return result ?? undefined;\n}\nexport function frame(program: ResumableProgram): ResumableFrame {\n return {\n pc: program.start,\n slots: new Array<unknown>(program.slotCount),\n kind: 0,\n duration: 0,\n channel: '',\n value: undefined,\n };\n}\nexport function computation(value: ComputationIR, host: ExecutionHost): unknown {\n let result = compiledComputations.get(value);\n if (!result) {\n result = compileComputation(value);\n compiledComputations.set(value, result);\n }\n return result(host);\n}\n","/** D5 宿主与器件 SDK 合同;声明附件不表示运行时已经实现。 */\nimport type { Disposable, Event } from '@mica-js/core/lifecycle';\nimport type {\n BlockIR,\n DeclarationIR,\n DeviceIR,\n InputPath,\n SourceInfo,\n JitBlockBuilder,\n} from '@mica-js/device-model';\nexport type { Disposable, Event } from '@mica-js/core/lifecycle';\n\ndeclare const snapshotTag: unique symbol;\ndeclare const borrowedTag: unique symbol;\ndeclare const libraryTag: unique symbol;\n\ninterface ByteReader extends Iterable<number> {\n readonly length: number;\n readonly byteLength: number;\n readonly [index: number]: number | undefined;\n [Symbol.iterator](): IterableIterator<number>;\n slice(start?: number, end?: number): Uint8Array;\n}\n\n/** 可跨推进和销毁留存的自有只读快照;slice 返回调用方拥有的可变副本。 */\nexport interface ReadonlyBytes extends ByteReader {\n readonly [snapshotTag]: true;\n}\n/** 句柄随所属板或本次翻译失效;内容稳定期与允许读取阶段由 memory 合同规定。 */\nexport interface BorrowedBytes extends ByteReader {\n readonly [borrowedTag]: true;\n}\n\nexport interface InputChannel<T> {\n send(value: T): void;\n}\nexport interface InputNotification {\n notify(): void;\n}\nexport interface ChannelMessage<T> {\n readonly time: number;\n readonly value: T;\n}\nexport interface Notification {\n readonly time: number;\n}\nexport interface TopicMessage {\n readonly topic: string;\n readonly payload: unknown;\n}\nexport interface TopicBridge {\n readonly onDidReceive: Event<TopicMessage>;\n publish(topic: string, payload: unknown): void;\n}\n\n/** 一段可执行代码区域;`base` 是逻辑 PC 基址,区域从对应 memory 的偏移 0 开始。 */\nexport interface JitCodeRegion {\n readonly memory: string;\n readonly base: number;\n readonly size: number;\n}\nexport interface JitTranslateInput {\n readonly pc: number;\n /** 仅在本次同步 translate 回调内有效;长度最多为本 region 的 `size`。 */\n readonly code: BorrowedBytes;\n /** 本次翻译所属 region 的逻辑基址;未命中 region 的服务 PC 回退主 code 时为 0。 */\n readonly codeBase: number;\n /** 按实例 memory 维护的代码代际;代码区域内的成功写入即时递增。 */\n readonly codeVersion: number;\n}\nexport type JitTranslate = (input: JitTranslateInput, builder: JitBlockBuilder) => BlockIR;\nexport interface InstructionHook {\n readonly when: string;\n readonly call: string;\n}\n/**\n * 一条忙等延时环的声明:入口 `pc` 每轮把 number 状态 `counter` 减一,消耗 `cycles` ps。\n * 环内不得产生其他可观察效果,因此跳过多轮只推进时间、只留下最后一轮的效果。\n *\n * `pending` 给按累加器计时的外设(SysTick、USART 位时钟):折算必须停在下一次服务边界,\n * 并把折叠掉的时间记进 `state`,否则跳过轮次会让这些外设永远等不到自己的节拍。\n */\nexport interface JitDelay {\n readonly counter: string;\n readonly cycles: number;\n readonly pending?: {\n /** 已累积的节拍时长(ps)。 */\n readonly state: string;\n /** 一次服务的粒度(ps)。 */\n readonly period: string;\n /** 是否需要按时间推进外设。 */\n readonly active: string;\n };\n}\n\n/**\n * A throughput-only wait point. When `predicate` is false the JIT parks until a dependency\n * changes. If `wait` is present, `delay` supplies the picoseconds to the next device time\n * event and `advance` applies that elapsed interval before the JIT is re-queued.\n *\n * `consume` runs once after `predicate` becomes true, allowing a one-shot wake token to be\n * cleared before the guest instruction executes. These functions take zero or one\n * argument; only `predicate` and `delay` must be pure.\n */\nexport interface JitPolling {\n readonly pc: number;\n readonly predicate: string;\n readonly consume?: string;\n readonly wait?: {\n /** Pure zero-argument function returning the delay in picoseconds, or zero to park. */\n readonly delay: string;\n /** Function receiving the elapsed picoseconds and applying the device time event. */\n readonly advance: string;\n };\n}\n\n/** 按 region 传给 codeMetadata provider 的只读代码视图;仅在本次同步回调内有效。 */\nexport interface JitCodeRegionView {\n readonly memory: string;\n readonly base: number;\n readonly size: number;\n readonly codeVersion: number;\n readonly code: BorrowedBytes;\n}\n/** 自上次该 region metadata 成功刷新以来的实际写入范围,单位为 memory offset;首次调用表示整区。 */\nexport interface JitCodeChange {\n readonly memory: string;\n readonly offset: number;\n readonly length: number;\n}\nexport interface JitCodeMetadata {\n readonly polling: readonly JitPolling[];\n readonly delays: ReadonlyMap<number, JitDelay>;\n}\nexport interface JitCodeMetadataInput {\n readonly region: JitCodeRegionView;\n readonly changes: readonly JitCodeChange[];\n}\nexport type JitCodeMetadataProvider = (input: JitCodeMetadataInput) => JitCodeMetadata;\n\nexport interface JitOptions {\n readonly entry: string;\n readonly code: string;\n /**\n * 主 `code` 内存仍隐式提供 0 基址 region;这里追加 Flash alias、SRAM、CCM 等\n * 可执行区域。区域不得与隐式主区域或彼此重叠。\n */\n readonly codeRegions?: readonly JitCodeRegion[];\n /**\n * 按 region、按 codeVersion 懒加载的代码派生 metadata。与静态\n * `polling`/`delays` 互斥;省略时完全保持旧静态路径。\n */\n readonly codeMetadata?: JitCodeMetadataProvider;\n readonly pc: string;\n /** Return immutable synchronous function IR scoped to this JIT. Reuse its array to reuse binding. */\n readonly functions?: (\n device: DeviceIR,\n ) => readonly Extract<DeclarationIR, { kind: 'function' }>[];\n readonly beforeInstruction?: InstructionHook;\n readonly polling?: readonly JitPolling[];\n readonly delays?: ReadonlyMap<number, JitDelay>;\n readonly translate: JitTranslate;\n}\nexport interface JitHost {\n attachJit(options: JitOptions): Disposable;\n loadBytes(memory: string, bytes: Uint8Array, offset?: number): void;\n}\n\n/** 具体字段由生成模块或工厂泛型注解投影;这里不重复声明资源名称。 */\nexport interface DeviceContext<\n Props extends object = object,\n Inputs extends object = object,\n Memory extends object = object,\n> extends JitHost {\n readonly props: Readonly<Props>;\n readonly inputs: Readonly<Inputs>;\n readonly memory: Readonly<Memory>;\n readonly topics: TopicBridge;\n reportError(error: unknown): void;\n}\nexport interface DeviceBatch<Outputs extends object = object> {\n readonly from: number;\n readonly to: number;\n readonly outputs: Readonly<Outputs>;\n}\nexport interface DeviceAdapter<Batch extends DeviceBatch = DeviceBatch> extends Disposable {\n sync(batch: Batch): void;\n}\nexport type DeviceFactory<\n Context extends DeviceContext = DeviceContext,\n Batch extends DeviceBatch = DeviceBatch,\n> = (context: Context) => DeviceAdapter<Batch>;\n\n/** 异构登记在库边界擦除器件泛型;工厂使用生成类型或精确的 SDK 泛型注解。 */\nexport interface DeviceLibraryEntry {\n readonly id: string;\n readonly model: DeviceIR;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 库边界有意擦除异构工厂的类型。\n readonly create: DeviceFactory<any, any>;\n}\n/** 已校验并捕获模型和登记关系的可复用库;没有运行中资源。 */\nexport interface DeviceLibrary {\n readonly [libraryTag]: true;\n}\nexport declare function createDeviceLibrary(entries: readonly DeviceLibraryEntry[]): DeviceLibrary;\n\n/** 四个 uint32,不能全零;精确数值合法性在创建前校验。 */\nexport type RandomState = readonly [number, number, number, number];\nexport type PropertyInput = number | boolean | string | null | Uint8Array;\nexport interface InstanceDescription {\n readonly id: string;\n readonly type: string;\n readonly props?: Readonly<Record<string, PropertyInput>>;\n readonly randomState?: RandomState;\n}\nexport interface PinEndpoint {\n readonly instance: string;\n readonly pin: string;\n}\nexport interface NetDescription {\n readonly id: string;\n readonly pins: readonly PinEndpoint[];\n /** 有限对地电压,0 表示地;省略时不建立理想参考。 */\n readonly voltage?: number;\n}\nexport interface BoardDescription {\n readonly instances: readonly InstanceDescription[];\n readonly nets: readonly NetDescription[];\n}\nexport interface BoardOptions {\n /** uint32,省略为 0;实例派生算法见 execution/random。 */\n readonly seed?: number;\n readonly execution?: 'throughput' | 'precise';\n /** CPU execution quantum in integer picoseconds, default 10_000_000. */\n readonly cpuQuantum?: number;\n}\nexport type BoardStatus = 'ready' | 'faulted' | 'disposed';\nexport type RuntimePhase =\n | 'library'\n | 'assembly'\n | 'initialize'\n | 'execute'\n | 'translate'\n | 'sync'\n | 'topic'\n | 'dispose'\n | 'host'\n | 'report';\nexport type RuntimeDiagnosticCode =\n | 'INVALID_CONFIGURATION'\n | 'MODEL_VALIDATION_FAILED'\n | 'RESOURCE_ALLOCATION_FAILED'\n | 'INVALID_ELECTRICAL_PARAMETER'\n | 'CONFLICTING_REFERENCE'\n | 'ELECTRICAL_SOLVE_FAILED'\n | 'CHANNEL_CONSUMER_CONFLICT'\n | 'INVALID_CALL_STATE'\n | 'OBJECT_DISPOSED'\n | 'BOARD_FAULTED'\n | 'INVALID_BINDING'\n | 'MODEL_EXECUTION_FAILED'\n | 'JIT_FAILED'\n | 'DEVICE_CALLBACK_FAILED'\n | 'ASYNC_HOOK_RESULT'\n | 'CHANNEL_OVERFLOW'\n | 'REPORTED_ERROR'\n | 'CLEANUP_FAILED'\n | 'STALE_REPORT'\n | 'HOST_LISTENER_FAILED';\n\n/** cause 保留原异常引用;只读约束不要求冻结宿主异常对象。 */\nexport interface RuntimeDiagnostic {\n readonly code: RuntimeDiagnosticCode;\n readonly message: string;\n readonly phase: RuntimePhase;\n readonly time: number | null;\n readonly instanceId?: string;\n readonly resource?: string;\n readonly path?: InputPath;\n readonly source?: SourceInfo;\n readonly cause?: unknown;\n readonly related: readonly RuntimeDiagnostic[];\n}\nexport class SimulationError extends Error {\n readonly code: RuntimeDiagnosticCode;\n readonly diagnostic: RuntimeDiagnostic;\n readonly related: readonly RuntimeDiagnostic[];\n constructor(diagnostic: RuntimeDiagnostic) {\n super(diagnostic.message);\n this.name = 'SimulationError';\n this.code = diagnostic.code;\n this.diagnostic = diagnostic;\n this.related = diagnostic.related;\n }\n}\n\nexport interface Board extends Disposable {\n readonly time: number;\n readonly status: BoardStatus;\n readonly topics: TopicBridge;\n readonly onDidError: Event<RuntimeDiagnostic>;\n readonly onDidDiagnostic: Event<RuntimeDiagnostic>;\n runUntil(target: number): void;\n}\n/** 同步捕获配置、建立资源与调用工厂;成功后才返回 ready 板。 */\nexport declare function createBoard(\n library: DeviceLibrary,\n description: BoardDescription,\n options?: BoardOptions,\n): Board;\n","import { BuildError } from '@mica-js/device-model';\nimport {\n SimulationError,\n type RuntimeDiagnostic,\n type RuntimeDiagnosticCode,\n type RuntimePhase,\n} from '../types';\nimport { snapshot } from '../values';\n\nfunction thenable(value: unknown): boolean {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\nexport class AsyncHookError extends TypeError {\n readonly code = 'ASYNC_HOOK_RESULT';\n constructor() {\n super('Device hooks must return synchronously');\n }\n}\nexport class ElectricalParameterError extends RangeError {\n readonly code = 'INVALID_ELECTRICAL_PARAMETER';\n}\nexport function electricalNumber(value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value))\n throw new ElectricalParameterError('Electrical parameters must be finite numbers');\n return value;\n}\nexport function acceptSync(value: unknown): void {\n if (thenable(value)) {\n void Promise.resolve(value).catch(() => {});\n throw new AsyncHookError();\n }\n}\nexport function modelLocation(cause: unknown): Partial<Pick<RuntimeDiagnostic, 'path' | 'source'>> {\n if (!(cause instanceof BuildError)) return {};\n const diagnostic = cause.diagnostics[0];\n if (!diagnostic) return {};\n return {\n ...(diagnostic.path ? { path: Object.freeze([...diagnostic.path]) } : {}),\n ...(diagnostic.source\n ? { source: snapshot(diagnostic.source) as NonNullable<RuntimeDiagnostic['source']> }\n : {}),\n };\n}\nexport function standalone(\n code: RuntimeDiagnosticCode,\n cause: unknown,\n phase: RuntimePhase,\n): SimulationError {\n return new SimulationError(\n Object.freeze({\n code,\n message: cause instanceof Error ? cause.message : String(cause),\n phase,\n time: null,\n cause,\n ...modelLocation(cause),\n related: Object.freeze([]),\n }),\n );\n}\n","import type { Disposable } from '@mica-js/core/lifecycle';\nimport { type DeclarationIR, type DeviceIR, validateDeviceIR } from '@mica-js/device-model';\nimport type { ExecutionHost, ResourceHandle } from '@mica-js/compiler';\nimport type { ElectricalPin, ResistorBranch } from '../electrical';\nimport { Fifo } from '../queue';\nimport { body, computation, resumable, synchronousBody } from './execution';\nimport { acceptSync, electricalNumber, ElectricalParameterError } from './errors';\nimport type {\n Channel,\n Decl,\n Dependencies,\n DerivedEntry,\n DirectJitLayout,\n Entry,\n Execution,\n Jit,\n JitMetadataRegion,\n JitPollingBinding,\n Observation,\n Process,\n Reaction,\n ResourceSlot,\n} from './state';\nimport {\n bytesView,\n captureValue,\n dataObject,\n externalValue,\n finite,\n identity,\n integer,\n nonnegative,\n nextRandom,\n randomState,\n range,\n snapshot,\n} from '../values';\nimport type {\n DeviceAdapter,\n DeviceBatch,\n DeviceContext,\n JitCodeChange,\n JitCodeRegion,\n JitDelay,\n JitOptions,\n RuntimeDiagnosticCode,\n RuntimePhase,\n SimulationError,\n TopicBridge,\n} from '../types';\n\n/** Board capabilities used by an instance; the board owns scheduling and publication. */\nexport interface InstanceBoard {\n readonly time: number;\n readonly phase: string;\n readonly current: Instance | undefined;\n /** Monotonic count of resource-version mutations on the whole board. */\n readonly resourceEpoch: number;\n noteResourceVersion(slot: ResourceSlot): void;\n markElectricalDirty(slot: number): void;\n readonly jits: Jit[];\n readonly waitingJits: Set<Jit>;\n /** Wakes or drops a parked JIT and removes its dependency registrations. */\n unparkWaiter(jit: Jit): void;\n assertAlive(instance?: Instance): void;\n /** Admission for a call that may change board state or is visible to a device. */\n assertCallAllowed(instance?: Instance): void;\n /** Admission for a read-only entry point: a faulted board stays inspectable. */\n assertReadAllowed(instance?: Instance): void;\n error(\n code: RuntimeDiagnosticCode,\n message: string,\n instance?: Instance,\n cause?: unknown,\n phase?: RuntimePhase,\n ): SimulationError;\n fault(error: SimulationError): void;\n report(instance: Instance, cause: unknown): void;\n topicBridge(owner?: Instance): TopicBridge;\n electricalSlot(pin: ElectricalPin): number;\n invalidate(slot: ResourceSlot): void;\n}\n\nconst EMPTY_MESSAGES: readonly never[] = Object.freeze([]);\ntype JitFunctions = readonly Decl<'function'>[];\nconst jitModels = new WeakMap<DeviceIR, WeakMap<JitFunctions, DeviceIR>>();\n\n/** Retain the binding identity when adapters reuse the same immutable function table. */\nfunction bindJitFunctions(base: DeviceIR, functions: JitFunctions): DeviceIR {\n if (functions.length === 0) return base;\n let models = jitModels.get(base);\n const cached = models?.get(functions);\n if (cached !== undefined) return cached;\n const model = validateDeviceIR({ ...base, declarations: base.declarations.concat(functions) });\n for (const declaration of model.declarations.slice(base.declarations.length))\n if (declaration.kind !== 'function') throw new TypeError('Expected JIT function declaration');\n if (models === undefined) {\n models = new WeakMap();\n jitModels.set(base, models);\n }\n models.set(functions, model);\n return model;\n}\n\n/** Membership test without allocating: every key of `next` is already in `previous`. */\nfunction hasEvery(\n previous: ReadonlyMap<ResourceSlot, number>,\n next: ReadonlyMap<ResourceSlot, number>,\n): boolean {\n for (const slot of next.keys()) if (!previous.has(slot)) return false;\n return true;\n}\nfunction createContext(owner: Instance, board: InstanceBoard): DeviceContext {\n return Object.freeze({\n get props() {\n board.assertReadAllowed(owner);\n return Object.freeze(\n Object.fromEntries([...owner.props].map(([key, value]) => [key, externalValue(value)])),\n );\n },\n get inputs() {\n owner.assertCallAllowed();\n return owner.inputs();\n },\n get memory() {\n board.assertReadAllowed(owner);\n return owner.publicMemory();\n },\n topics: board.topicBridge(owner),\n reportError: (error: unknown) => board.report(owner, error),\n attachJit: (options: JitOptions) => owner.attach(options),\n loadBytes: (name: string, bytes: Uint8Array, ...offset: unknown[]) =>\n owner.loadBytes(name, bytes, offset.length ? offset[0] : 0),\n });\n}\n\n/**\n * State map whose scalar direct-bank writes are synced lazily on read.\n *\n * Direct JIT writes update `stateValues` and invalidate `stateSlots` at every boundary,\n * while no observer or host reads `instance.states` until a reaction, observation,\n * fallback or external query accesses it. Deferring the string-keyed `Map.set` calls\n * until an actual read removes redundant map updates across resident GPIO edges while\n * keeping `instance.states` an exact `Map<string, unknown>` at every read site.\n */\nclass StateMirrorMap extends Map<string, unknown> {\n private names: readonly string[] = [];\n private bankValues: unknown[] = [];\n private dirty = new Int32Array(0);\n private pending = false;\n\n bindDirectBank(names: readonly string[], values: unknown[]): void {\n this.names = names;\n this.bankValues = values;\n this.dirty = new Int32Array(Math.ceil(names.length / 32));\n }\n\n markDirectDirty(word: number, bits: number): void {\n this.dirty[word]! |= bits;\n this.pending = true;\n }\n\n private flush(): void {\n if (!this.pending) return;\n this.pending = false;\n const { names, bankValues, dirty } = this;\n for (let word = 0; word < dirty.length; word++) {\n let bits = dirty[word]!;\n if (bits === 0) continue;\n dirty[word] = 0;\n const base = word << 5;\n while (bits !== 0) {\n const index = base + 31 - Math.clz32(bits & -bits);\n super.set(names[index]!, bankValues[index]);\n bits &= bits - 1;\n }\n }\n }\n\n override get(key: string): unknown {\n if (this.pending) this.flush();\n return super.get(key);\n }\n\n override set(key: string, value: unknown): this {\n if (this.pending) this.flush();\n return super.set(key, value);\n }\n\n override entries(): MapIterator<[string, unknown]> {\n if (this.pending) this.flush();\n return super.entries();\n }\n\n override values(): MapIterator<unknown> {\n if (this.pending) this.flush();\n return super.values();\n }\n\n override forEach(\n callbackfn: (value: unknown, key: string, map: Map<string, unknown>) => void,\n thisArg?: unknown,\n ): void {\n if (this.pending) this.flush();\n super.forEach(callbackfn, thisArg);\n }\n\n override [Symbol.iterator](): MapIterator<[string, unknown]> {\n if (this.pending) this.flush();\n return super[Symbol.iterator]();\n }\n}\n\nexport class Instance {\n readonly declarations = new Map<string, DeclarationIR>();\n readonly props = new Map<string, unknown>();\n readonly constants = new Map<string, unknown>();\n readonly states = new StateMirrorMap();\n private directBank?: Pick<\n DirectJitLayout,\n 'stateNames' | 'stateSlots' | 'states' | 'stateValues'\n >;\n readonly memories = new Map<string, Uint8Array>();\n private readonly memoryViews = new Map<string, DataView>();\n private readonly memorySizes = new Map<string, number>();\n readonly pins = new Map<string, ElectricalPin>();\n readonly channels = new Map<string, Channel>();\n readonly notificationInputs = new Set<string>();\n readonly notificationOutputs = new Map<string, number | null>();\n private readonly batchInputs: Channel[] = [];\n private readonly batchOutputs: (readonly [string, Channel])[] = [];\n private readonly batchNotifications: string[] = [];\n private readonly emptyOutputs: Record<string, unknown> = Object.create(null);\n readonly resources: Disposable[] = [];\n readonly jits: Jit[] = [];\n readonly processes: Process[] = [];\n readonly reactions: Reaction[] = [];\n readonly derived = new Map<string, DerivedEntry>();\n /** One-entry memo for repeated `read('derived', name)` calls inside a body. */\n private derivedName: string | undefined;\n private derivedEntry: DerivedEntry | undefined;\n private readonly derivedBuffers = new Map<string, Map<ResourceSlot, number>>();\n readonly stateResources = new Map<string, ResourceSlot>();\n readonly memoryResources = new Map<string, ResourceSlot>();\n readonly sampleResources = new Map<string, ResourceSlot>();\n observerRevision = 0;\n private readonly dependencyStack: Map<ResourceSlot, number>[] = [];\n private readonly observations = new WeakMap<Observation, Dependencies>();\n private readonly staticObservations = new WeakMap<Observation, () => unknown>();\n private readonly resistorIntents = new Map<string, Map<number, readonly ResistorBranch[]>>();\n private readonly sampleEntries = new Map<string, { pin: ElectricalPin; slot: ResourceSlot }>();\n private readonly intentEntries = new Map<string, { pin: ElectricalPin; slot: number }>();\n private readonly stateSlots = new Map<string, ResourceSlot>();\n /** Per-instance handles for the fixed resources a resumable process body binds. */\n private readonly resourceHandles = new Map<string, ResourceHandle>();\n private readonly memoryPlans = new Map<\n string,\n { name: string; bytes: Uint8Array; view: DataView; slot: ResourceSlot }\n >();\n /** 按 memory 维护的代码代际;只有 code region 内写入才递增。 */\n private readonly codeVersions = new Map<string, number>();\n /**\n * Every memory name any attached JIT binds as a code region. A write outside this set\n * cannot affect a JIT, so the store path skips the region scans entirely.\n */\n private readonly codeMemories = new Set<string>();\n private readonly observationFrames = new WeakMap<\n Observation,\n { first: Map<ResourceSlot, number>; second: Map<ResourceSlot, number>; alternate: boolean }\n >();\n readonly evaluating = new Set<string>();\n readonly random: Uint32Array;\n readonly host: ExecutionHost;\n readonly context: DeviceContext;\n adapter?: DeviceAdapter;\n valid = true;\n rawProps: Record<string, unknown>;\n constructor(\n readonly board: InstanceBoard,\n readonly entry: Entry,\n readonly id: string,\n props: unknown,\n seed: number,\n override?: readonly number[],\n ) {\n for (const declaration of entry.model.declarations) {\n if ('name' in declaration) this.declarations.set(declaration.name, declaration);\n if (\n declaration.kind === 'state' ||\n declaration.kind === 'memory' ||\n declaration.kind === 'pin'\n ) {\n const resources =\n declaration.kind === 'state'\n ? this.stateResources\n : declaration.kind === 'memory'\n ? this.memoryResources\n : this.sampleResources;\n resources.set(declaration.name, {\n version: 0,\n subscribers: new Set(),\n waiters: undefined,\n });\n }\n }\n dataObject(props);\n this.rawProps = props;\n for (const key of Object.keys(props))\n if (this.declarations.get(key)?.kind !== 'property')\n throw new TypeError(`Unknown property ${key}`);\n this.random = randomState(seed, id, override);\n this.host = {\n read: (kind, name) => this.read(kind, name),\n write: (name, value) => this.writeState(name, value, this.stateSlot(name)),\n sample: (ref) => {\n return this.readSample(ref);\n },\n intent: (pin, value) => {\n this.writeIntent(pin, value);\n },\n resistor: (pin, resistance) => {\n const r = electricalNumber(resistance);\n if (r < 0.001 || r > 1e9)\n throw new ElectricalParameterError('Resistance outside [0.001, 1e9]');\n return this.resistorIntent(pin, r);\n },\n memoryLength: (memory) => this.memory(memory).length,\n load: (kind, memory, offset) => {\n const plan = this.memoryPlan(memory);\n const size = kind.startsWith('load8') ? 1 : kind.startsWith('load16') ? 2 : 4;\n const at = range(plan.bytes, offset, size);\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(plan.slot, plan.slot.version);\n if (size === 1) return plan.bytes[at]!;\n return size === 2\n ? plan.view.getUint16(at, kind.endsWith('le'))\n : plan.view.getUint32(at, kind.endsWith('le'));\n },\n store: (kind, memory, offset, value) => {\n const plan = this.memoryPlan(memory);\n const size = kind.startsWith('store8') ? 1 : kind.startsWith('store16') ? 2 : 4;\n const at = range(plan.bytes, offset, size);\n const n = integer(value, 'stored value');\n if (size === 1) plan.bytes[at] = n;\n else if (size === 2) plan.view.setUint16(at, n, kind.endsWith('le'));\n else plan.view.setUint32(at, n, kind.endsWith('le'));\n this.memoryChangedPlan(plan, at, size);\n },\n copyBytes: (memory, offset, length) => {\n this.track(this.memoryResources, String(memory));\n const bytes = this.memory(memory),\n at = range(bytes, offset, length);\n return bytes.slice(at, at + Number(length));\n },\n send: (name, value) => this.send(name, value, false),\n notify: (name) => {\n if (!this.notificationOutputs.has(name))\n throw new TypeError(`Unknown notification ${name}`);\n this.notificationOutputs.set(name, board.time);\n },\n now: () => board.time,\n random: () => nextRandom(this.random),\n call: (name, args) => this.invoke(name, args),\n assert: (condition, message) => {\n if (condition !== true)\n throw new Error(message === undefined ? 'Assertion failed' : String(message));\n },\n bind: (specs) => this.bindResources(specs),\n };\n this.context = createContext(this, board);\n }\n private track(resources: ReadonlyMap<string, ResourceSlot>, name: string): void {\n this.trackSlot(resources.get(name)!);\n }\n /** Innermost dependency sink, or `undefined` outside an evaluation. */\n private dependencies(): Map<ResourceSlot, number> | undefined {\n const stack = this.dependencyStack;\n return stack.length === 0 ? undefined : stack[stack.length - 1];\n }\n private trackSlot(slot: ResourceSlot): void {\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(slot, slot.version);\n }\n /** Read-only evidence that a process frame bound per-instance resource handles. */\n bindingReport(): unknown {\n return Object.freeze({\n instance: this.id,\n handles: this.resourceHandles.size,\n bound: Object.freeze([...this.resourceHandles.keys()].sort()),\n processes: Object.freeze(\n this.processes.map((process) =>\n Object.freeze({\n name: process.declaration.kind === 'on' ? process.declaration.name : 'start',\n bound: process.frame?.resources?.length ?? 0,\n }),\n ),\n ),\n });\n }\n dependenciesCurrent(dependencies: Dependencies | undefined): boolean {\n if (!dependencies) return false;\n for (const [slot, version] of dependencies) if (slot.version !== version) return false;\n return true;\n }\n /** Publishes a derived cache entry; the memo must follow every table write. */\n setDerived(name: string, entry: DerivedEntry): void {\n // Observation chains republish the same entry on every boundary they observe; the\n // memo already proves `derived` maps this name to this entry, so the map write is\n // skipped. Every other writer still replaces the map entry below.\n if (this.derivedName === name && this.derivedEntry === entry) return;\n this.derived.set(name, entry);\n this.derivedName = name;\n this.derivedEntry = entry;\n }\n evaluate<T>(\n compute: () => T,\n target?: Map<ResourceSlot, number>,\n ): { value: T; dependencies: Dependencies } {\n const dependencies = target ?? new Map<ResourceSlot, number>();\n this.dependencyStack.push(dependencies);\n try {\n return { value: compute(), dependencies };\n } finally {\n this.dependencyStack.pop();\n const parent = this.dependencies();\n if (parent) for (const [key, version] of dependencies) parent.set(key, version);\n }\n }\n /** Leaf form of :func:`evaluate` for a source walk: no closure and no result wrapper. */\n private evaluateSource(\n path: readonly string[],\n dependencies: Map<ResourceSlot, number>,\n ): unknown {\n this.dependencyStack.push(dependencies);\n try {\n return snapshot(this.source(path));\n } finally {\n this.dependencyStack.pop();\n const parent = this.dependencies();\n if (parent) for (const [key, version] of dependencies) parent.set(key, version);\n }\n }\n observe(observation: Observation, path: readonly string[]): unknown {\n const read = this.staticObservations.get(observation);\n if (read) return read();\n const declaration = this.declarations.get(path[0]!);\n if (declaration?.kind === 'pin' || declaration?.kind === 'state') {\n const resources = declaration.kind === 'pin' ? this.sampleResources : this.stateResources;\n const pin = declaration.kind === 'pin' ? this.pin(declaration.name) : undefined;\n if (pin && path[1] !== 'sample') throw new TypeError(`Invalid source ${path.join('.')}`);\n // Published samples are immutable; state values may contain byte snapshots.\n const read = () => {\n let value: unknown = pin ? pin.sample : this.states.get(declaration.name);\n for (let index = pin ? 2 : 1; index < path.length; index++)\n value = (value as Record<string, unknown>)[path[index]!];\n return pin ? value : snapshot(value);\n };\n const value = read();\n const slot = resources.get(declaration.name)!;\n if (!slot.subscribers.size) this.observerRevision++;\n slot.subscribers.add(observation);\n this.staticObservations.set(observation, read);\n return value;\n }\n // Dynamic sources alternate between two reusable dependency buffers, so one round can\n // be diffed against the other without allocating a map per publication boundary.\n const frames = this.observationFrames.get(observation);\n let target: Map<ResourceSlot, number>;\n if (frames === undefined) {\n target = new Map();\n this.observationFrames.set(observation, {\n first: target,\n second: new Map(),\n alternate: true,\n });\n } else {\n target = frames.alternate ? frames.second : frames.first;\n frames.alternate = !frames.alternate;\n target.clear();\n }\n const observed = this.evaluateSource(path, target);\n const previous = this.observations.get(observation);\n // A stable network re-derives the same slots every round; only membership changes\n // touch subscriber bookkeeping.\n if (previous === undefined || previous.size !== target.size || !hasEvery(previous, target)) {\n if (previous)\n for (const slot of previous.keys())\n if (!target.has(slot) && slot.subscribers.delete(observation) && !slot.subscribers.size)\n this.observerRevision++;\n for (const slot of target.keys())\n if (!previous?.has(slot)) {\n if (!slot.subscribers.size) this.observerRevision++;\n slot.subscribers.add(observation);\n }\n }\n this.observations.set(observation, target);\n return observed;\n }\n observationReader(observation: Observation, path: readonly string[]): () => unknown {\n return this.staticObservations.get(observation) ?? (() => this.observe(observation, path));\n }\n read(kind: string, name: string): unknown {\n if (kind === 'state') {\n this.trackSlot(this.stateSlot(name));\n return this.states.get(name);\n }\n if (kind === 'derived') {\n // A body re-reads the same derived value between boundaries; one memoized name\n // saves the string-keyed lookup. Every writer of `derived` goes through `setDerived`,\n // so the memo can never disagree with the table.\n let cached = name === this.derivedName ? this.derivedEntry : this.derived.get(name);\n const epoch = this.board.resourceEpoch;\n if (\n cached === undefined ||\n (cached.epoch !== epoch && !this.dependenciesCurrent(cached.dependencies))\n ) {\n const declaration = this.declarations.get(name);\n if (declaration?.kind !== 'derived') throw new TypeError(`Unknown derived ${name}`);\n // The previous dependency set is only used by the staleness check above, so this\n // name's buffer can be cleared and refilled in place for the new evaluation.\n let buffer = this.derivedBuffers.get(name);\n if (buffer === undefined) {\n buffer = new Map();\n this.derivedBuffers.set(name, buffer);\n } else buffer.clear();\n const evaluated = this.evaluate(() => computation(declaration.value, this.host), buffer);\n cached = {\n value: evaluated.value,\n dependencies: evaluated.dependencies,\n epoch: this.board.resourceEpoch,\n };\n this.setDerived(name, cached);\n } else if (cached.epoch !== epoch) {\n // The versions still match, so the value holds while later mutations keep\n // advancing the epoch: record the checkpoint and skip the scan until then.\n cached.epoch = epoch;\n }\n const parent = this.dependencies();\n if (parent) for (const [key, version] of cached.dependencies) parent.set(key, version);\n return cached.value;\n }\n const values = kind === 'property' ? this.props : this.constants;\n if (values.has(name)) return values.get(name);\n if (this.evaluating.has(name)) throw new TypeError(`Circular creation dependency ${name}`);\n this.evaluating.add(name);\n try {\n const declaration = this.declarations.get(name);\n if (declaration?.kind !== 'property' && declaration?.kind !== 'const')\n throw new TypeError(`Invalid creation reference ${name}`);\n let value: unknown;\n if (declaration.kind === 'property') {\n if (Object.hasOwn(this.rawProps, name))\n value = captureValue(declaration.type, this.rawProps[name], this.declarations, true);\n else if (declaration.default)\n value = captureValue(\n declaration.type,\n computation(declaration.default, this.host),\n this.declarations,\n true,\n );\n else throw new TypeError(`Missing property ${name}`);\n } else value = computation(declaration.value, this.host);\n values.set(name, value);\n return value;\n } finally {\n this.evaluating.delete(name);\n }\n }\n invoke(name: string, args: readonly unknown[] = []): Execution {\n const fn = this.declarations.get(name);\n if (fn?.kind !== 'function') throw new TypeError(`Unknown function ${name}`);\n return body(fn.body)(this.host, args);\n }\n syncCall(name: string, args: readonly unknown[] = []): unknown {\n const step = this.invoke(name, args).next();\n if (!step.done) throw new TypeError('Unexpected suspension in synchronous function');\n return step.value;\n }\n pin(ref: unknown): ElectricalPin {\n const pin = this.pins.get(String(ref));\n if (!pin) throw new TypeError(`Unknown pin ${String(ref)}`);\n return pin;\n }\n /** Shared by the generic host and direct JIT, which needs to know whether to publish. */\n writeIntent(ref: unknown, value: unknown): boolean {\n const name = typeof ref === 'string' ? ref : String(ref);\n const board = this.board;\n let entry = this.intentEntries.get(name);\n if (entry === undefined) {\n const pin = this.pin(name);\n entry = { pin, slot: board.electricalSlot(pin) };\n this.intentEntries.set(name, entry);\n }\n if (entry.pin.intent === value) return false;\n entry.pin.intent = value as readonly ResistorBranch[];\n board.markElectricalDirty(entry.slot);\n return true;\n }\n /**\n * One frozen, reusable intent value per (pin, resistance); intents are immutable. The\n * outer map is keyed by pin name and the inner one by resistance, so the hot path builds\n * no key string. Bounds: at most 64 names, and at most 8 resistances per name; a full\n * level is cleared wholesale (no least-recently-used eviction), so identity is only\n * reused while both levels stay under their limits.\n */\n resistorIntent(pin: unknown, resistance: number): readonly ResistorBranch[] {\n const name = typeof pin === 'string' ? pin : String(pin);\n let byResistance = this.resistorIntents.get(name);\n if (byResistance === undefined) {\n if (this.resistorIntents.size >= 64) this.resistorIntents.clear();\n byResistance = new Map();\n this.resistorIntents.set(name, byResistance);\n }\n let intent = byResistance.get(resistance);\n if (intent === undefined) {\n if (byResistance.size >= 8) byResistance.clear();\n intent = Object.freeze([Object.freeze({ to: this.pin(name), resistance })]);\n byResistance.set(resistance, intent);\n }\n return intent;\n }\n private readSample(ref: unknown): ElectricalPin['sample'] {\n const name = typeof ref === 'string' ? ref : String(ref);\n let entry = this.sampleEntries.get(name);\n if (entry === undefined) {\n const pin = this.pin(name);\n entry = { pin, slot: this.sampleResources.get(pin.name)! };\n if (this.sampleEntries.size >= 512) this.sampleEntries.clear();\n this.sampleEntries.set(name, entry);\n }\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(entry.slot, entry.slot.version);\n return entry.pin.sample;\n }\n memory(ref: unknown): Uint8Array {\n const bytes = this.memories.get(String(ref));\n if (!bytes) throw new TypeError(`Unknown memory ${String(ref)}`);\n return bytes;\n }\n /** Instance-owned numeric bank, mirrored by every non-direct state write. */\n directStateBank(): NonNullable<Instance['directBank']> {\n if (this.directBank === undefined) {\n const stateNames = [...this.states.keys()].filter((name) => {\n const declaration = this.declarations.get(name) as Decl<'state'>;\n return declaration.type.kind === 'number' || declaration.type.kind === 'bool';\n });\n const frozenNames = Object.freeze(stateNames);\n const stateValues = stateNames.map((name) => this.states.get(name));\n this.states.bindDirectBank(frozenNames, stateValues);\n this.directBank = {\n stateNames: frozenNames,\n stateSlots: Object.freeze(stateNames.map((name) => this.stateResources.get(name)!)),\n states: new Map(stateNames.map((name, index) => [name, index])),\n stateValues,\n };\n }\n return this.directBank;\n }\n /** Direct scalar writes are already in the numeric bank. Commit the mirror and version. */\n commitDirectStates(dirty: number[] | Int32Array): boolean {\n const { stateSlots } = this.directBank!;\n const states = this.states;\n const board = this.board;\n let wrote = false;\n for (let word = 0; word < dirty.length; word++) {\n let bits = dirty[word]!;\n if (bits === 0) continue;\n dirty[word] = 0;\n wrote = true;\n states.markDirectDirty(word, bits);\n const base = word << 5;\n while (bits !== 0) {\n const index = base + 31 - Math.clz32(bits & -bits);\n const slot = stateSlots[index]!;\n if (slot.subscribers.size === 0) {\n slot.version++;\n board.noteResourceVersion(slot);\n } else board.invalidate(slot);\n bits &= bits - 1;\n }\n }\n return wrote;\n }\n private writeState(name: string, value: unknown, slot: ResourceSlot): void {\n const captured = snapshot(value);\n this.states.set(name, captured);\n const index = this.directBank?.states.get(name);\n if (index !== undefined) this.directBank!.stateValues[index] = captured;\n this.board.invalidate(slot);\n }\n private stateSlot(name: string): ResourceSlot {\n let slot = this.stateSlots.get(name);\n if (slot === undefined) {\n if (!this.states.has(name)) throw new TypeError(`Unknown state ${name}`);\n slot = this.stateResources.get(name)!;\n this.stateSlots.set(name, slot);\n }\n return slot;\n }\n memoryPlan(ref: unknown): {\n name: string;\n bytes: Uint8Array;\n view: DataView;\n slot: ResourceSlot;\n } {\n const name = typeof ref === 'string' ? ref : String(ref);\n let plan = this.memoryPlans.get(name);\n if (plan === undefined) {\n const bytes = this.memories.get(name);\n if (!bytes) throw new TypeError(`Unknown memory ${name}`);\n plan = {\n name,\n bytes,\n view: this.memoryViews.get(name)!,\n slot: this.memoryResources.get(name)!,\n };\n this.memoryPlans.set(name, plan);\n }\n return plan;\n }\n codeVersion(name: string): number {\n return this.codeVersions.get(name) ?? 0;\n }\n private intersectsCodeRegion(\n region: JitCodeRegion,\n offset: number | undefined,\n size: number | undefined,\n ): boolean {\n if (offset === undefined || size === undefined) return true;\n return offset < region.size && offset + size > 0;\n }\n private hasCodeRegion(name: string, offset?: number, size?: number): boolean {\n for (const jit of this.jits) {\n if (!jit.active) continue;\n for (const region of jit.codeRegions)\n if (region.memory === name && this.intersectsCodeRegion(region, offset, size)) return true;\n }\n return false;\n }\n private addMetadataChange(state: JitMetadataRegion, change: JitCodeChange): void {\n const pending = state.pending;\n let end = change.offset + change.length;\n let start = change.offset;\n for (let index = 0; index < pending.length;) {\n const current = pending[index]!;\n const currentEnd = current.offset + current.length;\n if (change.offset <= currentEnd && current.offset <= end) {\n start = Math.min(start, current.offset);\n end = Math.max(end, currentEnd);\n pending.splice(index, 1);\n } else index++;\n }\n pending.push({ memory: change.memory, offset: start, length: end - start });\n }\n private markMetadataChanged(\n jit: Jit,\n name: string,\n offset: number | undefined,\n size: number | undefined,\n ): void {\n if (!jit.metadata) return;\n for (const state of jit.metadata.regions.values()) {\n const region = state.region;\n if (region.memory !== name) continue;\n // The first successful callback receives the whole region; no pending range is\n // needed before that (and none is available to merge into).\n if (state.appliedVersion === -1) continue;\n if (name === jit.options.code) {\n // Primary aliases may jump to each other in one direct program. Every primary\n // alias is revalidated before a direct build, even if the write did not intersect\n // that alias's logical window; changes still carry only the actual write range.\n state.dirty = true;\n }\n if (!this.intersectsCodeRegion(region, offset, size)) continue;\n state.dirty = true;\n const start = offset === undefined ? 0 : Math.max(0, offset);\n const end = offset === undefined ? region.size : Math.min(region.size, offset + (size ?? 0));\n if (end > start)\n this.addMetadataChange(state, { memory: name, offset: start, length: end - start });\n }\n }\n memoryChanged(name: string, offset?: number, size?: number): void {\n this.memoryChangedSlot(name, this.memoryPlan(name).slot, offset, size);\n }\n private memoryChangedPlan(\n plan: { name: string; slot: ResourceSlot },\n offset?: number,\n size?: number,\n ): void {\n this.memoryChangedSlot(plan.name, plan.slot, offset, size);\n }\n private memoryChangedSlot(\n name: string,\n slot: ResourceSlot,\n offset?: number,\n size?: number,\n ): void {\n this.board.invalidate(slot);\n // Data memories are never bound as code, so no JIT region, cache or metadata can care.\n if (!this.codeMemories.has(name)) return;\n if (this.hasCodeRegion(name, offset, size))\n this.codeVersions.set(name, this.codeVersion(name) + 1);\n for (const jit of this.jits) {\n let affected = false;\n for (const region of jit.codeRegions)\n if (region.memory === name && this.intersectsCodeRegion(region, offset, size)) {\n affected = true;\n break;\n }\n if (!affected) continue;\n this.markMetadataChanged(jit, name, offset, size);\n if (jit.options.code === name) {\n // Primary code keeps the exact legacy invalidation and active-instruction contract.\n jit.cache.clear();\n jit.cacheMemories.clear();\n jit.revision++;\n jit.directPrograms.clear();\n jit.directProgramRevision = -1;\n jit.directSkip = undefined;\n jit.directMisses.clear();\n if (jit.direct?.frame.resume) jit.direct.frame.stopAfterInstruction = true;\n else jit.direct = undefined;\n } else if (jit.cacheMemories.has(name)) {\n // Additional regions are conservatively invalidated as a whole. They never feed the\n // direct program, so Flash cache/direct/revision and the active frame stay untouched.\n for (const [pc, instruction] of jit.cache)\n if (instruction.codeRegion?.memory === name) jit.cache.delete(pc);\n jit.cacheMemories.delete(name);\n }\n }\n }\n /**\n * Handles for the fixed names a resumable process body uses. They live on the instance,\n * so a shared program text binds each instance (and each process frame) separately, and\n * every read still resolves the current sample or state value.\n */\n private bindResources(specs: readonly (readonly [string, string])[]): readonly ResourceHandle[] {\n const handles = new Array<ResourceHandle>(specs.length);\n for (let index = 0; index < specs.length; index++) {\n const spec = specs[index]!;\n const key = `${spec[0]}\\0${spec[1]}`;\n let handle = this.resourceHandles.get(key);\n if (handle === undefined) {\n handle = this.resourceHandle(spec[0], spec[1]);\n this.resourceHandles.set(key, handle);\n }\n handles[index] = handle;\n }\n return handles;\n }\n /**\n * Each method repeats the generic host operation exactly: dependency slots are still\n * recorded, state writes still snapshot, and memory stores still run the code-memory\n * invalidation that clears JIT caches. Every resource a declaration already provides is\n * resolved here, at bind time; a name that does not exist yet keeps resolving lazily so\n * it still fails at its first real use, not while binding.\n */\n private resourceHandle(kind: string, name: string): ResourceHandle {\n if (kind === 'pin') {\n let pin = this.pins.get(name);\n let slot = pin === undefined ? -1 : this.board.electricalSlot(pin);\n let sample = pin === undefined ? undefined : this.sampleResources.get(name)!;\n // One-entry cache for the constant resistance a body repeats on every execution.\n let lastResistance: unknown;\n let lastIntent: readonly ResistorBranch[] | undefined;\n const resolve = (): ElectricalPin => {\n if (pin === undefined) {\n pin = this.pin(name);\n slot = this.board.electricalSlot(pin);\n sample = this.sampleResources.get(name)!;\n }\n return pin;\n };\n return Object.freeze({\n sample: () => {\n const current = resolve();\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(sample!, sample!.version);\n return current.sample;\n },\n intent: (value: unknown) => {\n const current = resolve();\n if (current.intent === value) return;\n current.intent = value as readonly ResistorBranch[];\n this.board.markElectricalDirty(slot);\n },\n resistor: (resistance: unknown) => {\n // Device bodies pass a pinned resistance on every execution; repeating the same\n // argument reuses the frozen intent instead of resolving `(pin, resistance)` again.\n // The intent is checked as well: an empty cache starts at `undefined`, which must\n // still reach `electricalNumber` and fail like the generic host path.\n if (lastIntent !== undefined && resistance === lastResistance) return lastIntent;\n const r = electricalNumber(resistance);\n if (r < 0.001 || r > 1e9)\n throw new ElectricalParameterError('Resistance outside [0.001, 1e9]');\n const intent = this.resistorIntent(name, r);\n lastResistance = resistance;\n lastIntent = intent;\n return intent;\n },\n });\n }\n if (kind === 'state') {\n let slot: ResourceSlot | undefined = this.states.has(name)\n ? this.stateResources.get(name)!\n : undefined;\n // Direct-bank index of this state: -2 not probed yet (the bank appears with the first\n // direct program), -1 outside the scalar bank, otherwise the live value's index.\n let banked = slot === undefined ? -1 : (this.directBank?.states.get(name) ?? -2);\n const resolve = (): ResourceSlot => (slot ??= this.stateSlot(name));\n const states = this.states;\n return Object.freeze({\n read: () => {\n const current = resolve();\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(current, current.version);\n if (banked === -2) banked = this.directBank?.states.get(name) ?? -1;\n return banked < 0 ? states.get(name) : this.directBank!.stateValues[banked];\n },\n write: (value: unknown) => {\n const current = resolve();\n this.writeState(name, value, current);\n },\n });\n }\n let plan: { name: string; bytes: Uint8Array; view: DataView; slot: ResourceSlot } | undefined =\n this.memories.has(name) ? this.memoryPlan(name) : undefined;\n const resolve = (): NonNullable<typeof plan> => (plan ??= this.memoryPlan(name));\n const read = (size: number, little: boolean, offset: unknown): number => {\n const current = resolve();\n const at = range(current.bytes, offset, size);\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(current.slot, current.slot.version);\n return size === 1\n ? current.bytes[at]!\n : size === 2\n ? current.view.getUint16(at, little)\n : current.view.getUint32(at, little);\n };\n const write = (size: number, little: boolean, offset: unknown, value: unknown): void => {\n const current = resolve();\n const at = range(current.bytes, offset, size);\n const n = integer(value, 'stored value');\n if (size === 1) current.bytes[at] = n;\n else if (size === 2) current.view.setUint16(at, n, little);\n else current.view.setUint32(at, n, little);\n this.memoryChangedSlot(name, current.slot, at, size);\n };\n return Object.freeze({\n load8: (offset: unknown) => read(1, false, offset),\n load16le: (offset: unknown) => read(2, true, offset),\n load16be: (offset: unknown) => read(2, false, offset),\n load32le: (offset: unknown) => read(4, true, offset),\n load32be: (offset: unknown) => read(4, false, offset),\n store8: (offset: unknown, value: unknown) => write(1, false, offset, value),\n store16le: (offset: unknown, value: unknown) => write(2, true, offset, value),\n store16be: (offset: unknown, value: unknown) => write(2, false, offset, value),\n store32le: (offset: unknown, value: unknown) => write(4, true, offset, value),\n store32be: (offset: unknown, value: unknown) => write(4, false, offset, value),\n length: () => this.memory(name).length,\n copy: (offset: unknown, length: unknown) => {\n this.track(this.memoryResources, name);\n const bytes = this.memory(name),\n at = range(bytes, offset, length);\n return bytes.slice(at, at + Number(length));\n },\n });\n }\n prepare(): void {\n for (const declaration of this.entry.model.declarations)\n if (declaration.kind === 'pin')\n this.pins.set(declaration.name, {\n id: `${this.id}\\0${declaration.name}`,\n instance: this.id,\n name: declaration.name,\n intent: [],\n sample: { voltage: null, level: 'unknown', status: 'floating' },\n });\n for (const declaration of this.entry.model.declarations) {\n switch (declaration.kind) {\n case 'property':\n case 'const':\n this.read(declaration.kind, declaration.name);\n break;\n case 'state':\n this.states.set(declaration.name, snapshot(computation(declaration.initial, this.host)));\n break;\n case 'memory': {\n const length = nonnegative(computation(declaration.length, this.host), 'memory length');\n this.memorySizes.set(declaration.name, length);\n break;\n }\n case 'pin': {\n const pin = this.pins.get(declaration.name)!;\n if (declaration.low && declaration.high) {\n const low = electricalNumber(computation(declaration.low, this.host)),\n high = electricalNumber(computation(declaration.high, this.host));\n if (low >= high)\n throw new ElectricalParameterError('Pin thresholds must satisfy low < high');\n Object.assign(pin, { low, high });\n }\n if (declaration.initial)\n pin.intent = computation(declaration.initial, this.host) as readonly ResistorBranch[];\n break;\n }\n case 'channel': {\n const capacity = nonnegative(computation(declaration.capacity, this.host), 'capacity');\n if (capacity === 0) throw new RangeError('Capacity must be positive');\n let maxLength: number | undefined;\n if (declaration.maxLength) {\n maxLength = nonnegative(computation(declaration.maxLength, this.host), 'maxLength');\n if (maxLength === 0) throw new RangeError('maxLength must be positive');\n }\n this.channels.set(declaration.name, {\n declaration,\n capacity,\n ...(maxLength === undefined ? {} : { maxLength }),\n overflow: declaration.overflow\n ? String(computation(declaration.overflow, this.host))\n : 'drop_new',\n incoming: new Fifo(),\n pending: new Fifo(),\n outgoing: new Fifo(),\n });\n break;\n }\n case 'notification':\n if (declaration.direction === 'output')\n this.notificationOutputs.set(declaration.name, null);\n break;\n case 'start':\n case 'on':\n this.processes.push({\n instance: this,\n declaration,\n resumable: resumable(declaration.body),\n ...(declaration.kind === 'on' ? { source: declaration.sourcePath } : {}),\n state: 'idle',\n pending: false,\n });\n break;\n case 'reaction':\n this.reactions.push({\n instance: this,\n declaration,\n previous: undefined,\n synchronousProgram: synchronousBody(this, declaration.body) ?? null,\n frame: undefined,\n });\n break;\n }\n }\n // Preserve the batch key order: output channels, then output notifications.\n for (const [name, channel] of this.channels) {\n if (channel.declaration.direction === 'input') this.batchInputs.push(channel);\n else {\n this.batchOutputs.push([name, channel]);\n this.emptyOutputs[name] = EMPTY_MESSAGES;\n }\n }\n for (const name of this.notificationOutputs.keys()) {\n this.batchNotifications.push(name);\n this.emptyOutputs[name] = null;\n }\n Object.freeze(this.emptyOutputs);\n }\n captureBatch(from: number, to: number): DeviceBatch {\n for (const channel of this.batchInputs) if (channel.incoming.length) channel.incoming.clear();\n let outputs = this.emptyOutputs;\n for (const [name, channel] of this.batchOutputs) {\n if (!channel.outgoing.length) continue;\n if (outputs === this.emptyOutputs)\n outputs = Object.assign(Object.create(null), this.emptyOutputs);\n outputs[name] = Object.freeze(\n channel.outgoing\n .drain()\n .map((message) =>\n Object.freeze({ time: message.time, value: externalValue(message.value) }),\n ),\n );\n }\n for (const name of this.batchNotifications) {\n const notified = this.notificationOutputs.get(name)!;\n if (notified === null) continue;\n if (outputs === this.emptyOutputs)\n outputs = Object.assign(Object.create(null), this.emptyOutputs);\n outputs[name] = Object.freeze({ time: notified });\n this.notificationOutputs.set(name, null);\n }\n return Object.freeze({\n from,\n to,\n outputs: outputs === this.emptyOutputs ? outputs : Object.freeze(outputs),\n });\n }\n assertCreation(): void {\n for (const declaration of this.entry.model.declarations) {\n if (declaration.kind !== 'assert') continue;\n const step = body(declaration.body)(this.host).next();\n if (!step.done) throw new TypeError('Creation assertion suspended');\n }\n }\n allocate(): void {\n for (const [name, length] of this.memorySizes) {\n const bytes = new Uint8Array(length);\n this.memories.set(name, bytes);\n this.memoryViews.set(name, new DataView(bytes.buffer));\n }\n this.memorySizes.clear();\n }\n assertCallAllowed(): void {\n this.board.assertCallAllowed(this);\n }\n inputs(): Record<string, unknown> {\n const result: Record<string, unknown> = Object.create(null);\n for (const declaration of this.entry.model.declarations) {\n if (declaration.kind === 'channel' && declaration.direction === 'input')\n result[declaration.name] = Object.freeze({\n send: (value: unknown) => {\n this.assertCallAllowed();\n this.send(declaration.name, value, true);\n },\n });\n if (declaration.kind === 'notification' && declaration.direction === 'input')\n result[declaration.name] = Object.freeze({\n notify: () => {\n this.assertCallAllowed();\n this.notificationInputs.add(declaration.name);\n },\n });\n }\n return Object.freeze(result);\n }\n publicMemory(): Record<string, unknown> {\n const result: Record<string, unknown> = Object.create(null);\n for (const declaration of this.entry.model.declarations)\n if (declaration.kind === 'memory' && declaration.public)\n result[declaration.name] = bytesView(this.memory(declaration.name), () => {\n this.board.assertAlive(this);\n if (!['idle', 'initialize', 'sync'].includes(this.board.phase))\n throw this.board.error(\n 'INVALID_CALL_STATE',\n 'Memory cannot be borrowed in this phase',\n this,\n );\n if (this.board.phase === 'initialize' && this.board.current !== this)\n throw this.board.error('INVALID_CALL_STATE', 'Another factory is initializing', this);\n });\n return Object.freeze(result);\n }\n send(name: string, value: unknown, input: boolean): void {\n const channel = this.channels.get(name);\n if (!channel || channel.declaration.direction !== (input ? 'input' : 'output'))\n throw new TypeError(`Unknown channel ${name}`);\n const captured = captureValue(channel.declaration.type, value, this.declarations);\n if (channel.maxLength !== undefined && (captured as Uint8Array).length > channel.maxLength)\n throw new RangeError('Message exceeds maxLength');\n const queue = input ? channel.pending : channel.outgoing;\n if (queue.length === channel.capacity) {\n if (channel.overflow === 'drop_new') return;\n if (channel.overflow === 'error') {\n const error = this.board.error('CHANNEL_OVERFLOW', `Channel ${name} overflow`, this);\n this.board.fault(error);\n throw error;\n }\n queue.shift();\n }\n queue.push({ time: this.board.time, value: captured });\n }\n private captureCodeRegions(options: JitOptions): {\n readonly all: readonly JitCodeRegion[];\n readonly additional: readonly JitCodeRegion[];\n } {\n const primaryMemory = this.memories.get(options.code)!;\n const primary = Object.freeze({\n memory: options.code,\n base: 0,\n size: primaryMemory.length,\n });\n const additional: JitCodeRegion[] = [];\n if (Object.hasOwn(options, 'codeRegions')) {\n if (!Array.isArray(options.codeRegions)) throw new TypeError('codeRegions must be an array');\n for (const item of options.codeRegions) {\n dataObject(item, ['memory', 'base', 'size']);\n const memory = identity(item.memory);\n const base = nonnegative(item.base, 'code region base');\n const size = nonnegative(item.size, 'code region size');\n if (size === 0) throw new RangeError('Code region size must be positive');\n const length = this.memories.get(memory)?.length;\n if (length === undefined)\n throw this.board.error('INVALID_BINDING', 'Unknown code region memory', this);\n if (size > length)\n throw this.board.error('INVALID_BINDING', 'Code region exceeds memory', this);\n if (base > Number.MAX_SAFE_INTEGER - size)\n throw this.board.error(\n 'INVALID_BINDING',\n 'Code region range is not a safe integer',\n this,\n );\n const region = Object.freeze({ memory, base, size });\n for (const existing of [primary, ...additional]) {\n if (\n region.base < existing.base + existing.size &&\n existing.base < region.base + region.size\n )\n throw this.board.error('INVALID_BINDING', 'Code regions overlap', this);\n }\n additional.push(region);\n }\n }\n return {\n all: Object.freeze([primary, ...additional]),\n additional: Object.freeze(additional),\n };\n }\n private capturePolling(items: unknown, region?: JitCodeRegion): Map<number, JitPollingBinding> {\n const polling = new Map<number, JitPollingBinding>();\n if (!Array.isArray(items)) throw new TypeError('polling must be an array');\n for (const item of items) {\n dataObject(item, ['pc', 'predicate', 'consume', 'wait']);\n const pc = finite(item.pc, 'polling pc');\n if (region !== undefined && (pc < region.base || pc >= region.base + region.size))\n throw this.board.error('INVALID_BINDING', 'Polling pc is outside its code region', this);\n const predicate = identity(item.predicate);\n const declaration = this.declarations.get(predicate);\n if (\n polling.has(pc) ||\n declaration?.kind !== 'function' ||\n !declaration.pure ||\n declaration.params.length ||\n declaration.returns?.kind !== 'bool'\n )\n throw this.board.error('INVALID_BINDING', 'Invalid polling declaration', this);\n let consume: string | undefined;\n if (Object.hasOwn(item, 'consume')) {\n consume = identity(item.consume);\n const fn = this.declarations.get(consume);\n if (fn?.kind !== 'function' || fn.params.length !== 0 || fn.returns !== undefined)\n throw this.board.error('INVALID_BINDING', 'Invalid polling consume function', this);\n }\n let wait: JitPollingBinding['wait'];\n if (Object.hasOwn(item, 'wait')) {\n dataObject(item.wait, ['delay', 'advance']);\n const delay = identity(item.wait.delay);\n const advance = identity(item.wait.advance);\n const delayFn = this.declarations.get(delay);\n const advanceFn = this.declarations.get(advance);\n if (\n delayFn?.kind !== 'function' ||\n !delayFn.pure ||\n delayFn.params.length !== 0 ||\n delayFn.returns?.kind !== 'number' ||\n advanceFn?.kind !== 'function' ||\n advanceFn.params.length !== 1 ||\n advanceFn.params[0]!.type.kind !== 'number' ||\n advanceFn.returns !== undefined\n )\n throw this.board.error('INVALID_BINDING', 'Invalid polling wait functions', this);\n wait = Object.freeze({ delay, advance });\n }\n polling.set(\n pc,\n Object.freeze({\n predicate,\n ...(consume === undefined ? {} : { consume }),\n ...(wait === undefined ? {} : { wait }),\n }),\n );\n }\n return polling;\n }\n private captureMetadataDelays(value: unknown, region: JitCodeRegion): Map<number, JitDelay> {\n if (!(value instanceof Map)) throw new TypeError('codeMetadata delays must be a Map');\n const delays = new Map<number, JitDelay>();\n for (const [key, item] of value) {\n const pc = finite(key, 'delay pc');\n if (pc < region.base || pc >= region.base + region.size)\n throw this.board.error('INVALID_BINDING', 'Delay pc is outside its code region', this);\n dataObject(item, ['counter', 'cycles', 'pending']);\n const counter = identity(item.counter);\n const cycles = integer(item.cycles, 'delay cycles');\n if (cycles <= 0) throw new RangeError('Delay cycles must be positive');\n let pending:\n | {\n readonly state: string;\n readonly period: string;\n readonly active: string;\n }\n | undefined;\n if (Object.hasOwn(item, 'pending')) {\n dataObject(item.pending, ['state', 'period', 'active']);\n pending = Object.freeze({\n state: identity(item.pending.state),\n period: identity(item.pending.period),\n active: identity(item.pending.active),\n });\n }\n delays.set(pc, Object.freeze({ counter, cycles, ...(pending ? { pending } : {}) }));\n }\n return delays;\n }\n /** Validate and copy provider output; caller applies it atomically. */\n captureCodeMetadata(\n region: JitCodeRegion,\n value: unknown,\n ): {\n readonly polling: Map<number, JitPollingBinding>;\n readonly delays: Map<number, JitDelay>;\n } {\n dataObject(value, ['polling', 'delays']);\n if (!Object.hasOwn(value, 'polling') || !Object.hasOwn(value, 'delays'))\n throw new TypeError('codeMetadata must contain polling and delays');\n return {\n polling: this.capturePolling(value.polling, region),\n delays: this.captureMetadataDelays(value.delays, region),\n };\n }\n attach(options: JitOptions): Disposable {\n this.assertCallAllowed();\n if (this.board.phase !== 'initialize' || this.board.current !== this)\n throw this.board.error('INVALID_CALL_STATE', 'attachJit is initialization-only', this);\n dataObject(options, [\n 'entry',\n 'code',\n 'codeRegions',\n 'codeMetadata',\n 'pc',\n 'functions',\n 'beforeInstruction',\n 'polling',\n 'delays',\n 'translate',\n ]);\n identity(options.entry);\n identity(options.code);\n identity(options.pc);\n if (this.jits.some((jit) => jit.active && jit.options.entry === options.entry))\n throw this.board.error('INVALID_BINDING', 'Duplicate JIT entry', this);\n if (\n !this.memories.has(options.code) ||\n this.declarations.get(options.pc)?.kind !== 'state' ||\n (this.declarations.get(options.pc) as Decl<'state'>).type.kind !== 'number' ||\n typeof options.translate !== 'function'\n )\n throw this.board.error('INVALID_BINDING', 'Invalid JIT binding', this);\n const codeRegions = this.captureCodeRegions(options);\n if (Object.hasOwn(options, 'codeMetadata')) {\n if (typeof options.codeMetadata !== 'function')\n throw this.board.error('INVALID_BINDING', 'Invalid codeMetadata provider', this);\n if (Object.hasOwn(options, 'polling') || Object.hasOwn(options, 'delays'))\n throw this.board.error(\n 'INVALID_BINDING',\n 'codeMetadata is mutually exclusive with static polling/delays',\n this,\n );\n }\n if (options.beforeInstruction !== undefined) {\n dataObject(options.beforeInstruction, ['when', 'call']);\n const condition = this.declarations.get(options.beforeInstruction.when),\n fn = this.declarations.get(options.beforeInstruction.call);\n if (\n !condition ||\n !['state', 'derived'].includes(condition.kind) ||\n !('type' in condition) ||\n condition.type.kind !== 'bool' ||\n fn?.kind !== 'function' ||\n fn.params.length ||\n fn.returns\n )\n throw this.board.error('INVALID_BINDING', 'Invalid instruction hook', this);\n } else if (Object.hasOwn(options, 'beforeInstruction'))\n throw new TypeError('Invalid beforeInstruction');\n const polling = Object.hasOwn(options, 'polling')\n ? this.capturePolling(options.polling)\n : new Map<number, JitPollingBinding>();\n if (Object.hasOwn(options, 'delays') && !(options.delays instanceof Map))\n throw new TypeError('delays must be a Map');\n const metadata = Object.hasOwn(options, 'codeMetadata')\n ? {\n regions: new Map(\n codeRegions.all.map((region) => [\n region,\n {\n region,\n appliedVersion: -1,\n dirty: false,\n pending: [] as JitCodeChange[],\n polling: new Map<number, JitPollingBinding>(),\n delays: new Map<number, JitDelay>(),\n },\n ]),\n ),\n polling: new Map<number, JitPollingBinding>(),\n delays: new Map<number, JitDelay>(),\n }\n : undefined;\n const base = this.entry.model;\n const emit = options.functions;\n if (Object.hasOwn(options, 'functions') && typeof emit !== 'function')\n throw new TypeError('functions must be a JIT function builder callback');\n let model = base;\n let functions: Map<string, Decl<'function'>> | undefined;\n let host = this.host;\n if (emit) {\n const declarations = emit(base);\n acceptSync(declarations);\n if (!Array.isArray(declarations)) throw new TypeError('Expected JIT function declarations');\n model = bindJitFunctions(base, declarations);\n const local = new Map<string, Decl<'function'>>();\n for (const declaration of model.declarations.slice(base.declarations.length))\n if (declaration.kind === 'function') local.set(declaration.name, declaration);\n functions = local;\n host = {\n ...this.host,\n call: (name, args) => {\n const fn = local.get(name);\n return fn ? body(fn.body)(host, args) : this.invoke(name, args);\n },\n };\n }\n const jit: Jit = {\n instance: this,\n model,\n host,\n ...(functions === undefined ? {} : { functions }),\n options: Object.freeze({\n ...options,\n ...(options.codeRegions === undefined ? {} : { codeRegions: codeRegions.additional }),\n ...(options.beforeInstruction\n ? { beforeInstruction: Object.freeze({ ...options.beforeInstruction }) }\n : {}),\n }),\n codeRegions: codeRegions.all,\n cache: new Map(),\n cacheMemories: new Set(),\n metadata,\n polling,\n delays: options.delays ?? new Map(),\n revision: 0,\n directRevision: -1,\n directObserverRevision: -1,\n directStateGuards: new Set(),\n directMemoryGuards: new Set(),\n directHookReads: new Set(),\n directPrograms: new Map(),\n directProgramRevision: -1,\n direct: undefined,\n directSkip: undefined,\n directMisses: new Map(),\n pollReads: undefined,\n currentPc: undefined,\n automaticPolling: false,\n pollingWait: false,\n pollingPeriod: 0,\n pollingOrigin: 0,\n pollingToken: 0,\n dependencyDirty: true,\n waiterSlots: undefined,\n active: true,\n stopped: false,\n queued: false,\n execution: undefined,\n };\n this.jits.push(jit);\n this.board.jits.push(jit);\n for (const region of jit.codeRegions) this.codeMemories.add(region.memory);\n const disposable = {\n dispose: () => {\n if (!jit.active) return;\n jit.active = false;\n jit.execution = undefined;\n delete jit.predicate;\n jit.pollingToken++;\n this.board.unparkWaiter(jit);\n jit.cache.clear();\n jit.cacheMemories.clear();\n jit.directPrograms.clear();\n jit.direct = undefined;\n jit.directMisses.clear();\n jit.pollReads = undefined;\n },\n };\n this.resources.push(disposable);\n return disposable;\n }\n loadBytes(name: string, bytes: Uint8Array, offset: unknown): void {\n this.assertCallAllowed();\n if (\n this.board.phase !== 'idle' &&\n !(this.board.phase === 'initialize' && this.board.current === this)\n )\n throw this.board.error(\n 'INVALID_CALL_STATE',\n 'Code loading is not allowed in this phase',\n this,\n );\n if (\n typeof name !== 'string' ||\n !this.jits.some(\n (jit) => jit.active && jit.codeRegions.some((region) => region.memory === name),\n )\n )\n throw this.board.error('INVALID_BINDING', 'Memory is not bound as code', this);\n if (!(bytes instanceof Uint8Array)) throw new TypeError('Code must be Uint8Array');\n const memory = this.memory(name),\n at = range(memory, offset, bytes.length);\n if (bytes.length) {\n memory.set(bytes.slice(), at);\n this.memoryChanged(name, at, bytes.length);\n }\n }\n source(path: readonly string[]): unknown {\n const declaration = this.declarations.get(path[0]!);\n let value: unknown;\n let firstField = 1;\n if (declaration?.kind === 'pin') {\n this.track(this.sampleResources, declaration.name);\n if (path[1] !== 'sample') throw new TypeError(`Invalid source ${path.join('.')}`);\n value = this.pin(declaration.name).sample;\n firstField = 2;\n } else if (declaration?.kind === 'state' || declaration?.kind === 'derived')\n value = this.read(declaration.kind, declaration.name);\n else throw new TypeError(`Invalid source ${path.join('.')}`);\n for (let index = firstField; index < path.length; index++)\n value = (value as Record<string, unknown>)[path[index]!];\n return value;\n }\n}\n","import type { TopicBridge } from '../types';\n\n/**\n * Facts the adapter layer needs about a bridge, kept off the public `TopicBridge` contract.\n *\n * A bridge's `publish` both delivers and enforces the board's call admission (alive, phase,\n * faulted). A caller that decides nobody would receive a message still has to run that\n * admission, and it has to know whether any owner-less listener exists. Both are internal to\n * this package: device adapters and hosts act through `onDidReceive` and `publish` only.\n */\nexport interface PublishGate {\n /** The same admission `publish` runs first, without copying, freezing or dispatching. */\n assertPublishAllowed(): void;\n /** Owner-less listeners of the shared dispatch set: the host's direct subscriptions. */\n hostListeners(): number;\n}\n\nconst gates = new WeakMap<object, PublishGate>();\n\n/** Attach the gate to the facade the board hands out; never exposed through the package entry. */\nexport function registerPublishGate(bridge: object, gate: PublishGate): void {\n gates.set(bridge, gate);\n}\n\nexport function publishGate(bridge: TopicBridge): PublishGate {\n const gate = gates.get(bridge);\n if (gate === undefined) throw new TypeError('Topic bridge was not created by a board');\n return gate;\n}\n","import type { OperationIR, RegionIR } from '@mica-js/device-model';\n\nexport function isPollingInstruction(body: RegionIR, pc: number, pcName: string): boolean {\n const definitions = new Map<number, OperationIR>();\n const redirects: number[] = [];\n const visit = (region: RegionIR): boolean => {\n for (const operation of region.operations) {\n if ('result' in operation) definitions.set(operation.result, operation);\n switch (operation.kind) {\n case 'constant':\n case 'unary':\n case 'binary':\n case 'numeric':\n case 'field':\n case 'length':\n case 'index':\n case 'isNone':\n case 'nonNull':\n case 'optional':\n case 'local':\n case 'localRead':\n case 'localWrite':\n case 'memoryLength':\n case 'load8':\n case 'load16le':\n case 'load16be':\n case 'load32le':\n case 'load32be':\n case 'readSample':\n case 'yield':\n break;\n case 'read':\n if (operation.resource === 'derived' || operation.name === pcName) return false;\n break;\n case 'if':\n if (!visit(operation.yes) || (operation.no && !visit(operation.no))) return false;\n break;\n case 'select':\n if (!visit(operation.yes.body) || !visit(operation.no.body)) return false;\n break;\n case 'and':\n case 'or':\n if (!visit(operation.right.body)) return false;\n break;\n case 'match':\n if (\n operation.arms.some((arm) => !visit(arm.body)) ||\n (operation.otherwise && !visit(operation.otherwise))\n )\n return false;\n break;\n case 'redirect':\n redirects.push(operation.target);\n break;\n default:\n return false;\n }\n }\n return true;\n };\n if (!visit(body)) return false;\n return redirects.some((target) => {\n const definition = definitions.get(target);\n return (\n definition?.kind !== 'constant' ||\n (definition.constant.kind === 'number' && definition.constant.value === pc)\n );\n });\n}\n","import {\n compileDirectJit,\n type DirectJitFrame,\n type DirectJitHost,\n type DirectJitProgram,\n type ExecutionSignal,\n} from '@mica-js/compiler';\nimport { createJitBlockBuilder, validateBoundBlockIR } from '@mica-js/device-model';\nimport { isPollingInstruction } from '../polling';\nimport type { EventQueue } from '../queue';\nimport { acceptSync } from './errors';\nimport { body, time } from './execution';\nimport type { Instance, InstanceBoard } from './instance';\nimport type {\n Dependencies,\n DirectJitLayout,\n Jit,\n JitInstruction,\n JitMetadataRegion,\n JitPollingBinding,\n} from './state';\nimport type {\n JitCodeChange,\n JitCodeMetadataInput,\n JitCodeRegion,\n JitCodeRegionView,\n JitDelay,\n RuntimeDiagnosticCode,\n RuntimePhase,\n SimulationError,\n} from '../types';\nimport { bytesView, finite } from '../values';\n\n/** Large programs dispatch through shards; small ones stay on the faster monolithic form. */\nconst DIRECT_SHARD_SIZE = 32;\n\nexport function syncJitCall(jit: Jit, name: string): unknown {\n const step = jit.host.call(name, []).next();\n if (!step.done) throw new TypeError('Unexpected suspension in synchronous function');\n return step.value;\n}\n/**\n * Program size above which whole-program rebuilds are amortized instead of immediate.\n *\n * Translation only ever adds cache entries, so a compiled program stays valid for every PC it\n * already contains; only a missing PC needs a rebuild. Rebuilding on every new block is\n * quadratic, and that dominated warm-up on a real firmware image (411 blocks: 43 rebuilds and\n * ~1.7 s before any simulated time). Small programs rebuild in milliseconds, so they keep the\n * exact behaviour; only larger ones switch to a stride that grows with the program.\n */\nconst DIRECT_REBUILD_LINEAR_LIMIT = 16;\n/** Stride floor once a program exceeds `DIRECT_REBUILD_LINEAR_LIMIT`. */\nconst DIRECT_REBUILD_MIN_BLOCKS = 64;\n/** A repeatedly visited translated PC can force a rebuild before the append-only stride. */\nconst DIRECT_REBUILD_PATIENCE = 4;\n\nfunction directRebuildStride(compiled: number): number {\n return compiled < DIRECT_REBUILD_LINEAR_LIMIT ? 1 : Math.max(DIRECT_REBUILD_MIN_BLOCKS, compiled);\n}\n\n/**\n * Deterministic direct-execution counters, kept on the `Jit` itself so `Board.jits` stays the\n * only diagnostic surface: the benchmark reads them instead of patching runtime internals.\n */\nexport interface DirectJitStats {\n /** Successful program builds; one per compile, so observer churn must not move it. */\n directCompiles: number;\n /** Resident shard functions backing the current direct program. */\n directShards: number;\n directCalls: number;\n directFallbacks: number;\n directDeadlines: number;\n directStopped: number;\n}\n\ntype CountedJit = Jit & { directStats?: DirectJitStats };\n\n/** Word masks the compiled blocks test at entry; mutated in place, so programs stay valid. */\ninterface DirectBarriers {\n stateMask: Int32Array;\n memoryMask: Int32Array;\n /** Bank layout of the current program; absent until one has been compiled. */\n stateIndex?: ReadonlyMap<string, number>;\n memoryIndex?: ReadonlyMap<string, number>;\n}\n\n/** Frame fields `compileDirectJit` reads but `DirectJitFrame` does not declare. */\ninterface BarrierFrame extends DirectJitFrame {\n blockedStates?: Int32Array;\n blockedMemories?: Int32Array;\n}\n\nconst barriers = new WeakMap<Jit, DirectBarriers>();\n\nfunction directBarriers(jit: Jit): DirectBarriers {\n let entry = barriers.get(jit);\n if (entry === undefined) {\n entry = { stateMask: new Int32Array(0), memoryMask: new Int32Array(0) };\n barriers.set(jit, entry);\n }\n return entry;\n}\n\nfunction directStats(jit: Jit): DirectJitStats {\n const counted = jit as CountedJit;\n return (counted.directStats ??= {\n directCompiles: 0,\n directShards: 0,\n directCalls: 0,\n directFallbacks: 0,\n directDeadlines: 0,\n directStopped: 0,\n });\n}\n\n/** Direct execution counters of one JIT; absent until the runtime attempted a direct run. */\nexport function directJitStats(jit: Jit): DirectJitStats | undefined {\n return (jit as CountedJit).directStats;\n}\n\n/** Region that supplies bytes for a logical PC; undefined means the service-PC fallback. */\nfunction codeRegionFor(jit: Jit, pc: number): JitCodeRegion | undefined {\n for (const region of jit.codeRegions)\n if (pc >= region.base && pc < region.base + region.size) return region;\n return undefined;\n}\n\n/** Additional regions stay on the interpreter; only the primary memory feeds direct programs. */\nfunction directCodeInstruction(jit: Jit, instruction: JitInstruction): boolean {\n const region = instruction.codeRegion;\n return region === undefined || region.memory === jit.options.code;\n}\n\nfunction effectivePolling(jit: Jit): ReadonlyMap<number, JitPollingBinding> {\n return jit.metadata?.polling ?? jit.polling;\n}\n\nfunction effectiveDelays(jit: Jit): ReadonlyMap<number, JitDelay> {\n return jit.metadata?.delays ?? jit.delays;\n}\n\n/** Aliases of the primary memory must refresh together before a direct program is built. */\nfunction primaryCodeRegions(jit: Jit): readonly JitCodeRegion[] {\n return jit.codeRegions.filter((region) => region.memory === jit.options.code);\n}\n\n/**\n * Lazily (re)build code-derived metadata for the requested regions. Provider calls never\n * happen from attach/store; this runs inside the translate phase immediately before the\n * polling/direct/translate decision that needs it.\n */\nfunction ensureMetadata(board: JitRuntimeHost, jit: Jit, regions: readonly JitCodeRegion[]): void {\n const metadata = jit.metadata;\n const provider = jit.options.codeMetadata;\n if (metadata === undefined || provider === undefined) return;\n const needed: {\n readonly state: JitMetadataRegion;\n readonly changes: readonly JitCodeChange[];\n readonly version: number;\n }[] = [];\n const seen = new Set<JitMetadataRegion>();\n for (const region of regions) {\n const state = metadata.regions.get(region);\n if (state === undefined || seen.has(state)) continue;\n seen.add(state);\n const version = jit.instance.codeVersion(region.memory);\n if (state.appliedVersion === version && state.pending.length === 0 && !state.dirty) continue;\n const changes =\n state.appliedVersion === -1\n ? [\n Object.freeze({\n memory: region.memory,\n offset: 0,\n length: region.size,\n }),\n ]\n : state.pending.map((change) => Object.freeze({ ...change }));\n needed.push({ state, changes, version });\n }\n if (needed.length === 0) return;\n\n const prior = board.phase;\n board.phase = 'translate';\n const prepared: {\n readonly state: JitMetadataRegion;\n readonly version: number;\n readonly polling: Map<number, JitPollingBinding>;\n readonly delays: Map<number, JitDelay>;\n }[] = [];\n try {\n for (const item of needed) {\n const { region } = item.state;\n const memory = jit.instance.memory(region.memory);\n const bytes = region.size >= memory.length ? memory : memory.subarray(0, region.size);\n let valid = true;\n try {\n const code = bytesView(bytes, () => {\n if (!valid) throw board.error('OBJECT_DISPOSED', 'Metadata view expired', jit.instance);\n });\n const view: JitCodeRegionView = Object.freeze({\n memory: region.memory,\n base: region.base,\n size: region.size,\n codeVersion: item.version,\n code: code as import('../types').BorrowedBytes,\n });\n const input: JitCodeMetadataInput = Object.freeze({\n region: view,\n changes: Object.freeze(item.changes.slice()),\n });\n const result = provider(input);\n acceptSync(result);\n const captured = jit.instance.captureCodeMetadata(region, result);\n prepared.push({\n state: item.state,\n version: item.version,\n polling: captured.polling,\n delays: captured.delays,\n });\n } finally {\n valid = false;\n }\n }\n // Nothing from the provider is visible until every requested region validated.\n let primary = false;\n for (const item of prepared) {\n item.state.appliedVersion = item.version;\n item.state.dirty = false;\n item.state.pending.length = 0;\n item.state.polling.clear();\n for (const [pc, binding] of item.polling) item.state.polling.set(pc, binding);\n item.state.delays.clear();\n for (const [pc, delay] of item.delays) item.state.delays.set(pc, delay);\n if (item.state.region.memory === jit.options.code) primary = true;\n }\n metadata.polling.clear();\n metadata.delays.clear();\n for (const state of metadata.regions.values()) {\n for (const [pc, binding] of state.polling) metadata.polling.set(pc, binding);\n for (const [pc, delay] of state.delays) metadata.delays.set(pc, delay);\n }\n if (primary) {\n jit.directPrograms.clear();\n jit.directProgramRevision = -1;\n jit.directSkip = undefined;\n if (!jit.direct?.frame.resume) {\n jit.direct = undefined;\n jit.directRevision = -1;\n }\n }\n } catch (cause) {\n throw board.wrap(cause, 'JIT_FAILED', 'translate', jit.instance);\n } finally {\n board.phase = prior;\n }\n}\n\nfunction ensureMetadataForPc(board: JitRuntimeHost, jit: Jit, pc: number): void {\n if (jit.metadata === undefined) return;\n const region = codeRegionFor(jit, pc) ?? jit.codeRegions[0]!;\n const needed = [region];\n // Direct programs may include every primary alias; refresh all of their delays together.\n if (\n board.execution === 'throughput' &&\n board.jits.length === 1 &&\n region.memory === jit.options.code\n )\n needed.push(...primaryCodeRegions(jit));\n ensureMetadata(board, jit, needed);\n}\n\n/** Publish the current guard sets into the masks the compiled blocks test at entry. */\nfunction syncDirectBarriers(jit: Jit): void {\n const entry = directBarriers(jit);\n const { stateIndex, memoryIndex } = entry;\n if (stateIndex === undefined || memoryIndex === undefined) return;\n const fill = (\n mask: Int32Array,\n index: ReadonlyMap<string, number>,\n guards: ReadonlySet<string>,\n ): void => {\n mask.fill(0);\n for (const name of guards) {\n const slot = index.get(name);\n if (slot === undefined) continue;\n mask[slot >>> 5] = (mask[slot >>> 5] ?? 0) | (1 << (slot & 31));\n }\n };\n fill(entry.stateMask, stateIndex, jit.directStateGuards);\n fill(entry.memoryMask, memoryIndex, jit.directMemoryGuards);\n}\n\n/** Scheduling capabilities needed by JIT execution; all queues remain board-owned. */\nexport interface JitRuntimeHost extends Pick<InstanceBoard, 'error'> {\n time: number;\n phase: string;\n current: Instance | undefined;\n readonly execution: 'throughput' | 'precise';\n readonly executionEnd: number;\n readonly jits: readonly Jit[];\n readonly waitingJits: Set<Jit>;\n /** Parks a JIT on its recorded dependency versions; the next round scans it once. */\n parkWaiter(jit: Jit): void;\n /** Wakes or drops a parked JIT and removes its dependency registrations. */\n unparkWaiter(jit: Jit): void;\n readonly events: Pick<EventQueue<() => void>, 'time' | 'push'>;\n boundary(): void;\n canContinueDirect(jit: Jit, horizon: number): boolean;\n queueJit(jit: Jit): void;\n wrap(\n cause: unknown,\n code: RuntimeDiagnosticCode,\n phase: RuntimePhase,\n instance?: Instance,\n ): SimulationError;\n}\n\nfunction refreshDirectGuards(jit: Jit, hookReads?: Dependencies): void {\n let changed = false;\n const instance = jit.instance;\n const hookCount = jit.directHookReads.size;\n // IRQ masking and short-circuit reads must not churn the compiled barrier set.\n if (hookReads) for (const slot of hookReads.keys()) jit.directHookReads.add(slot);\n if (\n jit.directObserverRevision === instance.observerRevision &&\n hookCount === jit.directHookReads.size\n )\n return;\n jit.directObserverRevision = instance.observerRevision;\n for (const [name, slot] of instance.stateResources) {\n const blocked = slot.subscribers.size > 0 || jit.directHookReads.has(slot);\n if (jit.directStateGuards.has(name) === blocked) continue;\n if (blocked) jit.directStateGuards.add(name);\n else jit.directStateGuards.delete(name);\n changed = true;\n }\n for (const [name, slot] of instance.memoryResources) {\n const blocked =\n slot.subscribers.size > 0 || jit.directHookReads.has(slot) || name === jit.options.code;\n if (jit.directMemoryGuards.has(name) === blocked) continue;\n if (blocked) jit.directMemoryGuards.add(name);\n else jit.directMemoryGuards.delete(name);\n changed = true;\n }\n if (changed) {\n // Guards no longer invalidate the program: the compiled blocks test these masks at entry,\n // so a membership change only flips individual blocks between direct and interpreted.\n syncDirectBarriers(jit);\n // A block that fell back while it was blocked may be eligible again.\n jit.directSkip = undefined;\n }\n}\n/**\n * Direct programs advance `frame.time` between host calls, while the board only adopts the\n * final time after `run` returns. Publish the current frame time before every host effect so\n * channel publications, electrical intents and diagnostics carry the instruction's time.\n */\nfunction directHost(\n board: JitRuntimeHost,\n instance: Instance,\n frame: DirectJitFrame,\n): DirectJitHost {\n const publishTime = (): void => {\n board.time = frame.time;\n };\n return {\n send: (name, value) => {\n publishTime();\n instance.host.send(name, value);\n },\n sample: (pin) => {\n publishTime();\n return instance.host.sample(pin);\n },\n intent: (pin, value) => {\n publishTime();\n if (instance.writeIntent(pin, value)) frame.publishPending = true;\n },\n resistor: (pin, resistance) => {\n publishTime();\n return instance.host.resistor(pin, resistance);\n },\n notify: (name) => {\n publishTime();\n instance.host.notify(name);\n },\n now: () => {\n publishTime();\n return instance.host.now();\n },\n random: () => {\n publishTime();\n return instance.host.random();\n },\n assert: (condition, message) => {\n publishTime();\n instance.host.assert(condition, message);\n },\n };\n}\n\n/** Build the numeric bank layout once; rebuilds then only need the cached instruction bodies. */\nfunction directLayout(jit: Jit): DirectJitLayout {\n if (jit.directLayout !== undefined) return jit.directLayout;\n const instance = jit.instance;\n const bank = instance.directStateBank();\n const memoryNames = [...instance.memories.keys()];\n const memories = new Map(memoryNames.map((name, index) => [name, index]));\n const memoryBanks = memoryNames.map((name) => instance.memory(name));\n const memoryViews = memoryBanks.map(\n (memory) => new DataView(memory.buffer, memory.byteOffset, memory.byteLength),\n );\n const pinNames = [...instance.pins.keys()];\n const pins = new Map(pinNames.map((name, index) => [name, index]));\n const pinObjects = pinNames.map((name) => instance.pin(name));\n const pinElectricalSlots = Int32Array.from(pinObjects, (pin) =>\n instance.board.electricalSlot(pin),\n );\n jit.directLayout = {\n ...bank,\n memoryNames: Object.freeze(memoryNames),\n memories,\n memoryBanks: Object.freeze(memoryBanks),\n memoryViews: Object.freeze(memoryViews),\n pinNames: Object.freeze(pinNames),\n pins,\n pinObjects: Object.freeze(pinObjects),\n pinElectricalSlots,\n };\n return jit.directLayout;\n}\n\nfunction flushDirect(\n board: JitRuntimeHost,\n instance: Instance,\n layout: DirectJitLayout,\n frame: DirectJitFrame,\n): boolean {\n board.time = frame.time;\n frame.publishPending = false;\n let wrote = instance.commitDirectStates(frame.stateDirty);\n for (let word = 0; word < frame.memoryDirty.length; word++) {\n let bits = frame.memoryDirty[word]!;\n if (bits === 0) continue;\n frame.memoryDirty[word] = 0;\n while (bits !== 0) {\n const slot = word * 32 + 31 - Math.clz32(bits & -bits);\n instance.memoryChanged(layout.memoryNames[slot]!);\n bits &= bits - 1;\n wrote = true;\n }\n }\n return wrote;\n}\n\ninterface RuntimeDirectFrame extends DirectJitFrame {\n /** The checkpoint already published the exit boundary before returning to the scheduler. */\n boundarySettled: boolean;\n}\n\nfunction createDirectFrame(\n board: JitRuntimeHost,\n jit: Jit,\n layout: DirectJitLayout,\n program: DirectJitProgram,\n barrier: DirectBarriers,\n): RuntimeDirectFrame {\n const instance = jit.instance;\n const { pinObjects, pinNames, pinElectricalSlots } = layout;\n const frame: RuntimeDirectFrame = {\n states: layout.stateValues,\n memories: [...layout.memoryBanks],\n memoryViews: layout.memoryViews,\n pins: pinObjects,\n resistors: [],\n locals: new Array(program.localCount),\n stateDirty: new Int32Array(Math.ceil(layout.stateNames.length / 32)),\n memoryDirty: new Int32Array(Math.ceil(layout.memoryNames.length / 32)),\n time: board.time,\n due: board.time,\n resume: 0,\n // First resumption must not add a property to a frame already seen by hot shards.\n stopAfterInstruction: false,\n boundarySettled: false,\n };\n frame.writePinIntent = (pinIndex: number, value: unknown): void => {\n if (!Object.hasOwn(instance, 'writeIntent')) {\n const pin = pinObjects[pinIndex]!;\n if (pin.intent === value) return;\n pin.intent = value as never;\n instance.board.markElectricalDirty(pinElectricalSlots[pinIndex]!);\n frame.publishPending = true;\n return;\n }\n board.time = frame.time;\n if (instance.writeIntent(pinNames[pinIndex]!, value)) frame.publishPending = true;\n };\n (frame as { host?: DirectJitHost }).host = directHost(board, instance, frame);\n if (jit.metadata === undefined) {\n frame.publishCheckpoint = () => {\n flushDirect(board, instance, layout, frame);\n board.boundary();\n if (jit.directProgramRevision === -1 || !board.canContinueDirect(jit, frame.due)) {\n frame.boundarySettled = true;\n return false;\n }\n // The boundary may have run reactions with their own current instance.\n board.current = instance;\n return true;\n };\n if (jit.options.beforeInstruction === undefined) {\n const pcIndex = layout.states.get(jit.options.pc)!;\n frame.finishCheckpoint = (deadline, emptySuffix) => {\n // The prefix was flushed and admitted through due. An empty suffix only\n // advances time, so that scheduler admission still holds after its boundary.\n if (emptySuffix) board.time = frame.time;\n else flushDirect(board, instance, layout, frame);\n board.boundary();\n const direct = jit.direct;\n const nextPc = frame.states[pcIndex] as number;\n if (\n jit.directProgramRevision === -1 ||\n direct?.frame !== frame ||\n !direct.pcs.has(nextPc) ||\n jit.directSkip === nextPc ||\n (jit.directRevision !== jit.revision &&\n jit.revision - jit.directRevision >= directRebuildStride(direct.pcs.size)) ||\n frame.time >= deadline ||\n board.events.time < deadline ||\n (!emptySuffix && !board.canContinueDirect(jit, frame.time))\n ) {\n frame.boundarySettled = true;\n return false;\n }\n // Program membership excludes polling/secondary-code PCs. Barriers may still\n // have changed during reactions; the next generated block checks the refreshed masks.\n if (jit.directObserverRevision !== instance.observerRevision) refreshDirectGuards(jit);\n frame.stopAfterInstruction = false;\n board.current = instance;\n return true;\n };\n }\n }\n // Both masks are shared with every frame of this JIT and refreshed in place on guard churn.\n (frame as BarrierFrame).blockedStates = barrier.stateMask;\n (frame as BarrierFrame).blockedMemories = barrier.memoryMask;\n return frame;\n}\nfunction runDirect(board: JitRuntimeHost, jit: Jit, hookReads?: Dependencies): boolean {\n const instance = jit.instance;\n let pending = Boolean(jit.direct?.frame.resume);\n if (!pending) {\n const pc = finite(instance.states.get(jit.options.pc), 'pc');\n const region = codeRegionFor(jit, pc);\n if (\n board.execution !== 'throughput' ||\n board.jits.length !== 1 ||\n (region !== undefined && region.memory !== jit.options.code) ||\n effectivePolling(jit).has(pc) ||\n jit.cache.get(pc)?.polling\n )\n return false;\n refreshDirectGuards(jit, hookReads);\n if (jit.directSkip === pc) return false;\n // An append-only translation revision leaves compiled bodies valid. Reuse them as long\n // as the current program covers this PC. Amortize rebuilds over a stride of new blocks,\n // but count repeat dispatches per translated PC so a hot path catches up promptly\n // without rebuilding for each PC visited once during initialization.\n if (jit.directRevision !== jit.revision) {\n const compiled = jit.direct?.pcs.size ?? 0;\n const stale = jit.revision - jit.directRevision;\n const stride = directRebuildStride(compiled);\n const covered = jit.direct?.pcs.has(pc) === true;\n const misses = covered ? 0 : (jit.directMisses.get(pc) ?? 0);\n const rebuild =\n jit.direct === undefined || stale >= stride || misses >= DIRECT_REBUILD_PATIENCE;\n\n if (!rebuild) {\n if (!covered) {\n // The interpreter runs this instruction; the catch-up rebuild picks it up. It is\n // still a direct attempt that fell back, so the counters keep describing \"how many\n // dispatches reached the compiled program\" rather than where the decision was made.\n const stats = directStats(jit);\n stats.directCalls++;\n stats.directFallbacks++;\n if (jit.cache.has(pc)) jit.directMisses.set(pc, misses + 1);\n\n return false;\n }\n // Covered: reuse the current program and fall through to the shared execution tail.\n } else {\n if (jit.directProgramRevision !== jit.revision) {\n // Code-memory replacement resets this marker to -1. The translated cache is gone, so\n // cached instruction bodies must go with it; old programs stay self-contained.\n if (jit.directProgramRevision === -1 && jit.directCache !== undefined)\n compileDirectJit.clearCache(jit.directCache);\n jit.directPrograms.clear();\n jit.directProgramRevision = jit.revision;\n }\n const layout = directLayout(jit);\n const instructions = [...jit.cache.values()].filter(\n (instruction) =>\n !instruction.polling &&\n !effectivePolling(jit).has(instruction.pc) &&\n directCodeInstruction(jit, instruction),\n );\n /** Declared busy-wait heads fold their remaining rounds inside the emitted body. */\n const delayLoops = new Map<\n number,\n {\n counter: number;\n cycles: number;\n pending?: { state: number; period: number; active: number };\n }\n >();\n for (const [headPc, delay] of effectiveDelays(jit)) {\n const counter = layout.states.get(delay.counter);\n if (counter === undefined) continue;\n const pending =\n delay.pending === undefined\n ? undefined\n : {\n state: layout.states.get(delay.pending.state),\n period: layout.states.get(delay.pending.period),\n active: layout.states.get(delay.pending.active),\n };\n delayLoops.set(\n headPc,\n pending !== undefined &&\n pending.state !== undefined &&\n pending.period !== undefined &&\n pending.active !== undefined\n ? { counter, cycles: delay.cycles, pending: pending as never }\n : { counter, cycles: delay.cycles },\n );\n }\n // Guards stay out of the key: blocks test the barriers at entry, so one program serves\n // every observer set. The full delay descriptor participates because it changes the\n // emitted guard; translation revision changes still clear the program cache.\n const key = JSON.stringify([...delayLoops].sort(([left], [right]) => left - right));\n const cached = jit.directPrograms.get(key);\n if (cached) {\n jit.direct = cached;\n jit.directRevision = jit.revision;\n } else {\n const { states, memories, pins } = layout;\n const cache = (jit.directCache ??= compileDirectJit.createCache());\n const program = compileDirectJit(\n instructions,\n {\n states,\n memories,\n pins,\n pc: { name: jit.options.pc, index: states.get(jit.options.pc)! },\n host: true,\n ...(jit.functions === undefined ? {} : { functions: jit.functions }),\n split: true,\n shardSize: DIRECT_SHARD_SIZE,\n delayLoops,\n },\n cache,\n );\n jit.directRevision = jit.revision;\n jit.directMisses.clear();\n const stats = directStats(jit);\n\n stats.directShards = program?.shards ?? 0;\n if (program) stats.directCompiles++;\n const barrier = directBarriers(jit);\n barrier.stateIndex = states;\n barrier.memoryIndex = memories;\n const stateMaskWords = Math.ceil(layout.stateNames.length / 32);\n const memoryMaskWords = Math.ceil(layout.memoryNames.length / 32);\n if (barrier.stateMask.length !== stateMaskWords)\n barrier.stateMask = new Int32Array(stateMaskWords);\n if (barrier.memoryMask.length !== memoryMaskWords)\n barrier.memoryMask = new Int32Array(memoryMaskWords);\n syncDirectBarriers(jit);\n jit.direct = program\n ? {\n program,\n pcs: new Set(program.pcs),\n frame: createDirectFrame(board, jit, layout, program, barrier),\n }\n : undefined;\n // A declined program must not be cached, or the key would keep answering `undefined`.\n if (!jit.direct) jit.directPrograms.delete(key);\n // The key no longer carries the guard set, so one program covers every observer set:\n // the eight-slot cap (and its eviction churn) has nothing left to bound.\n else jit.directPrograms.set(key, jit.direct);\n }\n }\n }\n if (!jit.direct) return false;\n }\n const direct = jit.direct!;\n const frame = direct.frame as RuntimeDirectFrame;\n const layout = jit.directLayout!;\n for (;;) {\n if (pending) frame.stopAfterInstruction = true;\n frame.time = board.time;\n // The frame starts clean and flushDirect clears both banks, including the fault path.\n const start = board.time;\n let reason: ReturnType<DirectJitProgram['run']>;\n let wrote: boolean;\n const stats = directStats(jit);\n stats.directCalls++;\n try {\n // Resource barriers exclude intermediate observers; real events retain exact deadlines.\n reason = direct.program.run(frame, Math.min(board.executionEnd, board.events.time));\n } finally {\n wrote = flushDirect(board, instance, layout, frame);\n }\n // A fallback with no flushed slot and no elapsed time did not execute anything; the cached\n // entry PC can safely be interpreted. A zero-duration block can still write state/PC before\n // the dispatcher rejects the next uncompiled PC: `wrote` records that prefix, so the caller\n // must re-read the flushed PC instead of replaying the old one.\n if (frame.boundarySettled) frame.boundarySettled = false;\n else if (reason !== 'fallback' || wrote || board.time !== start) board.boundary();\n if (reason === 'fallback') {\n const nextPc = finite(instance.states.get(jit.options.pc), 'pc');\n // Polling PCs are deliberately absent from direct programs. Reaching one is a normal\n // shard boundary, not a failed direct dispatch, so it must neither compound fallback\n // statistics nor poison the next interpreter attempt for this PC.\n const polling = effectivePolling(jit).has(nextPc) || jit.cache.get(nextPc)?.polling;\n if (!polling) {\n stats.directFallbacks++;\n jit.directSkip = nextPc;\n }\n if (!wrote && board.time === start && board.time < board.executionEnd) return false;\n } else if (reason === 'stopped') {\n stats.directStopped++;\n jit.stopped = true;\n return true;\n } else if (reason === 'invalidated') {\n frame.stopAfterInstruction = false;\n // An electrical publication or a resumed suffix can return \"invalidated\" without\n // invalidating any code. An append-only revision must still honour the rebuild stride.\n // Primary code writes / metadata changes explicitly reset the program revision.\n if (jit.directProgramRevision === -1 && frame.resume === 0) {\n jit.direct = undefined;\n jit.directRevision = -1;\n }\n } else stats.directDeadlines++;\n // Publish and settle the whole boundary first. Without intervening scheduler work,\n // an already-started suffix can resume at its wake time without a queue round trip.\n // A metadata provider must still be checked by runJit before resumption.\n if (frame.resume) {\n const wake = Math.max(frame.due, board.time);\n if (jit.metadata === undefined && board.canContinueDirect(jit, wake)) {\n board.time = wake;\n board.current = instance;\n pending = true;\n continue;\n }\n if (wake > board.time) {\n board.events.push(wake, () => board.queueJit(jit));\n return true;\n }\n }\n board.queueJit(jit);\n return true;\n }\n}\nfunction pollingDependencies(\n jit: Jit,\n dependencies: Dependencies,\n pc: number | undefined,\n): Dependencies {\n const result = new Map(dependencies);\n const instance = jit.instance;\n const pcSlot = instance.stateResources.get(jit.options.pc)!;\n result.set(pcSlot, pcSlot.version);\n const region = pc === undefined ? undefined : codeRegionFor(jit, pc);\n const memory = region?.memory ?? jit.options.code;\n const slot = instance.memoryResources.get(memory)!;\n result.set(slot, slot.version);\n return result;\n}\n\n/** Park a polling JIT and, when requested, schedule the next device time event. */\nfunction waitForPolling(\n board: JitRuntimeHost,\n jit: Jit,\n dependencies: Dependencies,\n duration: number,\n advance: string | undefined,\n): void {\n jit.dependencies = dependencies;\n jit.pollingWait = true;\n jit.pollingPeriod = 0;\n board.parkWaiter(jit);\n const token = ++jit.pollingToken;\n\n board.boundary();\n if (duration === 0 || advance === undefined) return;\n const due = time(board.time + duration);\n\n board.events.push(due, () => {\n if (token !== jit.pollingToken || !jit.active || jit.stopped || !board.waitingJits.has(jit))\n return;\n const pending = jit.dependencies;\n\n delete jit.dependencies;\n board.unparkWaiter(jit);\n jit.pollingToken++;\n board.current = jit.instance;\n // An external event won the race at the same timestamp. Re-evaluate the guest rather\n // than applying a device step against a configuration that has already changed.\n if (!jit.instance.dependenciesCurrent(pending)) {\n board.queueJit(jit);\n return;\n }\n jit.instance.syncCall(advance, [duration]);\n board.boundary();\n board.queueJit(jit);\n });\n}\n\nfunction jitSignal(board: JitRuntimeHost, jit: Jit, signal: ExecutionSignal): boolean {\n if (signal.kind === 'elapse') {\n const duration = time(signal.duration);\n if (duration === 0) return false;\n const due = time(board.time + duration);\n board.events.push(due, () => board.queueJit(jit));\n board.boundary();\n return true;\n }\n if (signal.kind === 'waitUntil') {\n const checked = jit.instance.evaluate(() => syncJitCall(jit, signal.predicate));\n if (checked.value === true) return false;\n jit.predicate = signal.predicate;\n jit.pollingWait = false;\n jit.dependencies = checked.dependencies;\n board.parkWaiter(jit);\n board.boundary();\n return true;\n }\n if (signal.kind === 'stop') {\n jit.stopped = true;\n jit.execution = undefined;\n board.boundary();\n return true;\n }\n if (signal.kind === 'redirect') {\n finite(signal.pc, 'redirect target');\n const duration = time(signal.delay);\n jit.instance.host.write(jit.options.pc, signal.pc);\n jit.execution = undefined;\n const polling =\n jit.automaticPolling && duration > 0 && signal.pc === jit.currentPc && jit.pollReads;\n const dependencies = polling ? pollingDependencies(jit, polling, jit.currentPc) : undefined;\n jit.automaticPolling = false;\n jit.pollReads = undefined;\n board.boundary();\n if (duration === 0) board.queueJit(jit);\n else\n board.events.push(time(board.time + duration), () => {\n if (!jit.active || jit.stopped) return;\n if (dependencies && jit.instance.dependenciesCurrent(dependencies)) {\n jit.dependencies = dependencies;\n jit.pollingWait = true;\n jit.pollingPeriod = duration;\n jit.pollingOrigin = board.time;\n board.parkWaiter(jit);\n } else board.queueJit(jit);\n });\n return true;\n }\n throw new TypeError('Invalid JIT suspension');\n}\nexport function runJit(board: JitRuntimeHost, jit: Jit): void {\n jit.queued = false;\n if (!jit.active || jit.stopped) return;\n board.current = jit.instance;\n if (jit.metadata !== undefined) {\n const pc = finite(jit.instance.states.get(jit.options.pc), 'pc');\n ensureMetadataForPc(board, jit, pc);\n }\n if (jit.direct?.frame.resume) {\n runDirect(board, jit);\n return;\n }\n if (!jit.execution) {\n jit.automaticPolling = false;\n jit.pollReads = undefined;\n let hookReads: Dependencies | undefined;\n let hookPending = false;\n const hook = jit.options.beforeInstruction;\n if (hook) {\n const kind = jit.instance.declarations.get(hook.when)!.kind;\n const priorPc = jit.instance.states.get(jit.options.pc) as number;\n const collect =\n board.execution === 'throughput' &&\n (board.jits.length === 1 || effectivePolling(jit).has(priorPc));\n const checked = collect\n ? jit.instance.evaluate(() => jit.instance.read(kind, hook.when))\n : undefined;\n const handled = (checked ? checked.value : jit.instance.read(kind, hook.when)) === true;\n if (handled) {\n const execution = jit.instance.invoke(hook.call);\n const step = execution.next();\n if (!step.done) {\n jit.execution = execution;\n if (jitSignal(board, jit, step.value)) return;\n throw new TypeError('Invalid hook suspension');\n }\n }\n hookReads = checked?.dependencies;\n hookPending = handled;\n }\n const pc = finite(jit.instance.states.get(jit.options.pc), 'pc');\n if (board.execution === 'throughput') {\n const declaration = effectivePolling(jit).get(pc);\n if (declaration) {\n const checked = jit.instance.evaluate(() => jit.instance.syncCall(declaration.predicate));\n if (checked.value !== true) {\n const dependencies = new Map([...(hookReads ?? []), ...checked.dependencies]);\n let duration = 0;\n const wait = declaration.wait;\n if (wait) {\n const delayed = jit.instance.evaluate(\n () => jit.instance.syncCall(wait.delay),\n dependencies,\n );\n duration = time(delayed.value);\n }\n waitForPolling(\n board,\n jit,\n pollingDependencies(jit, dependencies, pc),\n duration,\n wait?.advance,\n );\n return;\n }\n if (declaration.consume) jit.instance.syncCall(declaration.consume);\n }\n if (!hookPending && board.jits.length === 1 && runDirect(board, jit, hookReads)) return;\n }\n let instruction = jit.cache.get(pc);\n if (!instruction) {\n const prior = board.phase;\n board.phase = 'translate';\n let valid = true;\n try {\n const codeRegion = codeRegionFor(jit, pc);\n const codeMemory = codeRegion?.memory ?? jit.options.code;\n const memory = jit.instance.memory(codeMemory);\n const bytes =\n codeRegion === undefined || codeRegion.size >= memory.length\n ? memory\n : memory.subarray(0, codeRegion.size);\n const code = bytesView(bytes, () => {\n if (!valid)\n throw board.error('OBJECT_DISPOSED', 'Translation view expired', jit.instance);\n });\n const result = jit.options.translate(\n Object.freeze({\n pc,\n code: code as import('../types').BorrowedBytes,\n codeBase: codeRegion?.base ?? 0,\n codeVersion: jit.instance.codeVersion(codeMemory),\n }),\n createJitBlockBuilder({ device: jit.model }),\n );\n acceptSync(result);\n const block = validateBoundBlockIR(result, jit.model);\n if (block.instructions[0]?.pc !== pc)\n throw new TypeError('Translated first pc does not match');\n const instructions = block.instructions.map((instruction) => {\n const region = codeRegionFor(jit, instruction.pc);\n return {\n pc: instruction.pc,\n nextPc: instruction.nextPc,\n body: instruction.body,\n polling: isPollingInstruction(instruction.body, instruction.pc, jit.options.pc),\n execute: body(instruction.body),\n codeRegion: region,\n };\n });\n // An overlapping translation can replace a covered body instead of just adding PCs.\n // It runs only after any direct continuation has drained, so discard that program now.\n if (instructions.some((entry) => jit.direct?.pcs.has(entry.pc))) {\n jit.direct = undefined;\n jit.directPrograms.clear();\n }\n // Match the first instruction when a block contains a repeated PC.\n for (let index = instructions.length - 1; index >= 0; index--) {\n const entry = instructions[index]!;\n jit.cache.set(entry.pc, entry);\n jit.cacheMemories.add(entry.codeRegion?.memory ?? jit.options.code);\n }\n // A block may legally span multiple PCs. Every entry gets its own logical region;\n // direct programs only admit primary/fallback entries. The start region only supplies\n // the translate-time byte view and codeVersion.\n if (\n instructions.some(\n (entry) =>\n entry.codeRegion === undefined || entry.codeRegion.memory === jit.options.code,\n )\n )\n jit.revision++;\n jit.directSkip = undefined;\n instruction = instructions[0]!;\n } catch (cause) {\n throw board.wrap(cause, 'JIT_FAILED', 'translate', jit.instance);\n } finally {\n valid = false;\n board.phase = prior;\n }\n }\n jit.currentPc = pc;\n jit.automaticPolling =\n board.execution === 'throughput' &&\n board.jits.length === 1 &&\n instruction.polling &&\n !hookPending &&\n (!hook || hookReads !== undefined);\n jit.pollReads = hookReads;\n jit.instance.host.write(jit.options.pc, instruction.nextPc);\n jit.execution = instruction.execute(jit.host);\n }\n for (;;) {\n const step = jit.automaticPolling\n ? (() => {\n const checked = jit.instance.evaluate(() => jit.execution!.next());\n jit.pollReads = new Map([...(jit.pollReads ?? []), ...checked.dependencies]);\n return checked.value;\n })()\n : jit.execution.next();\n if (step.done) {\n jit.execution = undefined;\n board.boundary();\n board.queueJit(jit);\n return;\n }\n if (jitSignal(board, jit, step.value)) return;\n }\n}\n","import { Emitter, type Event, type Disposable } from '@mica-js/core/lifecycle';\nimport { BuildError, validateDeviceIR, type DeviceIR } from '@mica-js/device-model';\nimport { RESUMABLE_RECEIVE, type ResumableProgram } from '@mica-js/compiler';\nimport {\n createElectricalNetwork,\n ElectricalError,\n type ElectricalPin,\n type ElectricalNetwork,\n} from './electrical';\nimport { ActivationQueue, EventQueue, Fifo } from './queue';\nimport { compileObservation } from './observations';\nimport { Instance } from './runtime/instance';\nimport { registerPublishGate } from './runtime/publish-gate';\nimport { runJit, syncJitCall } from './runtime/jit';\nimport { body, computation, frame, MAX_TIME, synchronousBody, time } from './runtime/execution';\nimport {\n acceptSync,\n AsyncHookError,\n ElectricalParameterError,\n modelLocation,\n standalone,\n} from './runtime/errors';\nimport type {\n Entry,\n Jit,\n Observation,\n ObservationChain,\n Process,\n Reaction,\n Receiver,\n ResourceSlot,\n} from './runtime/state';\nimport { dataObject, finite, identity, integer, same, snapshot } from './values';\nimport {\n SimulationError,\n type Board,\n type BoardDescription,\n type BoardOptions,\n type BoardStatus,\n type DeviceAdapter,\n type DeviceLibrary,\n type DeviceLibraryEntry,\n type RuntimeDiagnostic,\n type RuntimeDiagnosticCode,\n type RuntimePhase,\n type TopicBridge,\n type TopicMessage,\n} from './types';\n\nconst OBSERVATION_PROBE = Symbol.for('mica-js.simulator/observations');\nconst PROCESS_PROBE = Symbol.for('mica-js.simulator/processes');\nconst EMPTY_QUEUE_ENTRY = Object.freeze({}) as unknown as Observation;\nconst libraries = new WeakMap<object, readonly Entry[]>();\n\nexport function createDeviceLibrary(entries: readonly DeviceLibraryEntry[]): DeviceLibrary {\n try {\n if (!Array.isArray(entries)) throw new TypeError('Expected device entries');\n const seen = new Set<string>();\n const captured = entries.map((entry) => {\n dataObject(entry, ['id', 'model', 'create']);\n const id = identity(entry.id);\n if (seen.has(id)) throw new TypeError(`Duplicate device type ${id}`);\n seen.add(id);\n if (typeof entry.create !== 'function') throw new TypeError('Expected device factory');\n let model: DeviceIR;\n try {\n model = validateDeviceIR(entry.model);\n } catch (cause) {\n const conflict =\n cause instanceof BuildError &&\n Object.getOwnPropertyDescriptor(cause, 'code')?.value === 'CHANNEL_CONSUMER_CONFLICT';\n throw standalone(\n conflict ? 'CHANNEL_CONSUMER_CONFLICT' : 'MODEL_VALIDATION_FAILED',\n cause,\n 'library',\n );\n }\n return Object.freeze({ id, model, create: entry.create as DeviceLibraryEntry['create'] });\n });\n const library = Object.freeze({}) as DeviceLibrary;\n libraries.set(library, captured);\n return library;\n } catch (cause) {\n if (cause instanceof SimulationError) throw cause;\n throw standalone('INVALID_CONFIGURATION', cause, 'library');\n }\n}\ninterface TopicListener {\n readonly owner?: Instance;\n readonly call: (message: TopicMessage) => unknown;\n}\n\n/** Mutable view of the compiler's readonly reaction frame, reused across boundaries. */\ninterface MutableReactionFrame {\n previous: unknown;\n current: unknown;\n captures: unknown[];\n}\n\nclass BoardRuntime implements Board {\n time = 0;\n status: BoardStatus = 'ready';\n phase = 'assembly';\n current: Instance | undefined;\n /** -1: clean; -2: initial solve or multiple dirty slots; otherwise the only dirty slot. */\n private pendingElectricalSlot = -2;\n /** Flat dirty batch for the multi-slot publication path, stamped to drop repetitions. */\n private dirtyElectricalSlots = new Int32Array(0);\n private dirtyElectricalStamps = new Int32Array(0);\n private dirtyElectricalLength = 0;\n private dirtyElectricalEpoch = 1;\n private readonly observations = new ActivationQueue<Observation>();\n private readonly reactionBatch: Reaction[] = [];\n private readonly changeObservations: Receiver[] = [];\n private readonly changePrevious: unknown[] = [];\n private readonly changeCurrent: unknown[] = [];\n private readonly plans: ObservationChain[] = [];\n private readonly skippedPlans: { readonly key: string; readonly reason: string }[] = [];\n private readonly sampleSlots = new Map<ElectricalPin, ResourceSlot>();\n /** Electrical slot → published sample slot, bound once so publishing needs no lookup. */\n private readonly sampleSlotsBySlot: ResourceSlot[] = [];\n /** Electrical endpoint → its board slot, used to record dirty pins by slot. */\n private readonly electricalSlots = new Map<ElectricalPin, number>();\n private readonly byId = new Map<string, Instance>();\n private dispatchDepth = 0;\n private initialized = false;\n private readonly errors = new Emitter<RuntimeDiagnostic>();\n private readonly diagnostics = new Emitter<RuntimeDiagnostic>();\n private readonly listeners = new Set<TopicListener>();\n /** Owner-less listeners of the shared set: the host's direct subscriptions on `topics`. */\n private hostListeners = 0;\n private readonly models = new Fifo<Process>();\n readonly events = new EventQueue<() => void>();\n private readonly readyJits = new Fifo<Jit>();\n /**\n * Bumped on every resource-version mutation board wide. The value is bare arithmetic: a\n * difference proves *some* resource moved, never which one, so it only ever guards\n * \"nothing changed at all\" conclusions.\n *\n * Mutations cluster inside `publish()` while derived reads spread across the gaps\n * between publications, so a checkpoint compared against this counter hits far more\n * often than the raw mutation-to-read ratio suggests: `camera-mcu` sees 8514 bumps and\n * 5638 derived reads per frame, yet 99.93% of those reads find the epoch unchanged.\n */\n private versionEpoch = 0;\n readonly waitingJits = new Set<Jit>();\n /**\n * Advances whenever a parked JIT is flagged or parks. The global `versionEpoch` cannot\n * gate the scan: every electrical publish bumps it even when no JIT waits on the slot.\n */\n private waiterEpoch = 0;\n /** `waiterEpoch` at the last parked-JIT scan; equal means no parked JIT can have woken. */\n private waitingScanEpoch = 0;\n /** Parked JITs whose `pollingWait` is set: their polling boundary needs every round. */\n private pollingWaiterCount = 0;\n readonly jits: Jit[] = [];\n readonly instances: Instance[] = [];\n private network!: ElectricalNetwork;\n private primary: SimulationError | undefined;\n readonly execution: 'throughput' | 'precise';\n executionEnd = 0;\n readonly onDidError: Event<RuntimeDiagnostic> = (listener, thisArgs, disposables) =>\n this.errors.event(\n (diagnostic) => {\n try {\n listener.call(thisArgs, diagnostic);\n } catch (cause) {\n this.diagnostic('HOST_LISTENER_FAILED', cause);\n }\n },\n undefined,\n disposables,\n );\n readonly onDidDiagnostic: Event<RuntimeDiagnostic> = (listener, thisArgs, disposables) =>\n this.diagnostics.event(\n (diagnostic) => {\n try {\n listener.call(thisArgs, diagnostic);\n } catch (cause) {\n this.fallback(cause);\n }\n },\n undefined,\n disposables,\n );\n readonly topics: TopicBridge = this.topicBridge();\n constructor(entries: readonly Entry[], description: BoardDescription, options: BoardOptions) {\n try {\n dataObject(description, ['instances', 'nets']);\n dataObject(options, ['seed', 'execution', 'cpuQuantum']);\n const execution = Object.hasOwn(options, 'execution') ? options.execution : 'throughput';\n if (execution !== 'throughput' && execution !== 'precise')\n throw new TypeError('Invalid execution mode');\n this.execution = execution;\n const cpuQuantum = Object.hasOwn(options, 'cpuQuantum')\n ? integer(options.cpuQuantum, 'cpuQuantum')\n : 10_000_000;\n if (cpuQuantum < 1 || cpuQuantum > 10_000_000)\n throw new RangeError('cpuQuantum outside [1, 10000000]');\n if (!Array.isArray(description.instances) || !Array.isArray(description.nets))\n throw new TypeError('instances and nets are required arrays');\n const seed = Object.hasOwn(options, 'seed') ? integer(options.seed, 'seed') : 0;\n if (seed < 0 || seed > 0xffffffff) throw new RangeError('seed out of uint32 range');\n const library = new Map(entries.map((entry) => [entry.id, entry]));\n const ids = new Set<string>();\n for (const input of description.instances) {\n dataObject(input, ['id', 'type', 'props', 'randomState']);\n const id = identity(input.id),\n type = identity(input.type);\n if (ids.has(id)) throw new TypeError(`Duplicate instance ${id}`);\n ids.add(id);\n const entry = library.get(type);\n if (!entry) throw new TypeError(`Unknown device type ${type}`);\n const props = Object.hasOwn(input, 'props') ? input.props : {};\n if (Object.hasOwn(input, 'randomState') && input.randomState === undefined)\n throw new TypeError('Invalid randomState');\n this.instances.push(\n new Instance(\n this,\n entry,\n id,\n props,\n seed,\n input.randomState as readonly number[] | undefined,\n ),\n );\n }\n for (const instance of this.instances) this.byId.set(instance.id, instance);\n const byId = this.byId;\n const netIds = new Set<string>(),\n connected = new Set<string>();\n for (const net of description.nets) {\n dataObject(net, ['id', 'pins', 'voltage']);\n const id = identity(net.id);\n if (netIds.has(id)) throw new TypeError(`Duplicate network ${id}`);\n netIds.add(id);\n if (!Array.isArray(net.pins)) throw new TypeError('Network pins must be an array');\n if (Object.hasOwn(net, 'voltage')) finite(net.voltage, 'voltage');\n for (const endpoint of net.pins) {\n dataObject(endpoint, ['instance', 'pin']);\n const instanceName = identity(endpoint.instance),\n pinName = identity(endpoint.pin);\n const instance = byId.get(instanceName);\n if (instance?.declarations.get(pinName)?.kind !== 'pin')\n throw new TypeError('Unknown pin endpoint');\n const key = `${instanceName}\\0${pinName}`;\n if (connected.has(key)) throw new TypeError('Duplicate connected endpoint');\n connected.add(key);\n }\n }\n try {\n for (const instance of this.instances) {\n this.current = instance;\n instance.prepare();\n }\n for (const instance of this.instances) {\n this.current = instance;\n instance.assertCreation();\n }\n for (const instance of this.instances) {\n this.current = instance;\n instance.allocate();\n }\n } catch (cause) {\n throw this.wrap(cause, 'MODEL_EXECUTION_FAILED', 'assembly', this.current);\n }\n const nets = description.nets.map((net) => ({\n id: net.id,\n pins: net.pins.map((p: import('./types').PinEndpoint) => byId.get(p.instance)!.pin(p.pin)),\n ...(Object.hasOwn(net, 'voltage') ? { voltage: net.voltage! } : {}),\n }));\n const pins: ElectricalPin[] = [];\n for (const instance of this.instances)\n for (const pin of instance.pins.values()) {\n // The electrical slot is the position in this board-ordered pin list, so the\n // publish plan resolves a changed slot without a map lookup.\n const slot = instance.sampleResources.get(pin.name)!;\n pins.push(pin);\n this.sampleSlots.set(pin, slot);\n this.electricalSlots.set(pin, this.sampleSlotsBySlot.length);\n this.sampleSlotsBySlot.push(slot);\n }\n this.network = createElectricalNetwork(pins, nets);\n // One dirty list and one stamp per board pin: publication never allocates.\n this.dirtyElectricalSlots = new Int32Array(pins.length);\n this.dirtyElectricalStamps = new Int32Array(pins.length);\n this.phase = 'initialize';\n for (const instance of this.instances) {\n this.current = instance;\n let adapter: unknown;\n try {\n adapter = instance.entry.create(instance.context);\n acceptSync(adapter);\n if (\n adapter === null ||\n typeof adapter !== 'object' ||\n typeof (adapter as DeviceAdapter).sync !== 'function' ||\n typeof (adapter as DeviceAdapter).dispose !== 'function'\n )\n throw new TypeError('Invalid device adapter');\n } catch (cause) {\n throw this.wrap(cause, 'DEVICE_CALLBACK_FAILED', 'initialize', instance);\n }\n instance.adapter = adapter as unknown as DeviceAdapter;\n if (this.isFaulted) throw this.primary!;\n }\n this.current = undefined;\n this.phase = 'idle';\n Object.defineProperty(this, OBSERVATION_PROBE, {\n value: () => this.observationReport(),\n enumerable: false,\n });\n Object.defineProperty(this, PROCESS_PROBE, {\n value: () => this.processReport(),\n enumerable: false,\n });\n } catch (cause) {\n const error =\n cause instanceof SimulationError\n ? cause\n : this.wrap(cause, 'INVALID_CONFIGURATION', 'assembly', this.current);\n this.primary = error;\n const cleanupErrors = this.cleanup();\n throw cleanupErrors.length ? this.aggregate(error, cleanupErrors) : error;\n }\n }\n private get isFaulted(): boolean {\n return this.status === 'faulted';\n }\n /**\n * Read-only diagnostic view of generated observation chains. It is reachable only via\n * `Symbol.for('mica-js.simulator/observations')` and is not part of the public SDK.\n */\n private observationReport(): unknown {\n return Object.freeze({\n plans: Object.freeze(\n this.plans.map((chain) =>\n Object.freeze({\n key: chain.plan.key,\n path: Object.freeze([...chain.plan.path]),\n receivers: chain.members.length,\n slots: chain.plan.slots.length,\n source: chain.plan.source,\n comparison: chain.plan.comparison,\n }),\n ),\n ),\n skipped: Object.freeze(this.skippedPlans.map((entry) => Object.freeze({ ...entry }))),\n reactions: Object.freeze(\n this.instances.flatMap((instance) =>\n instance.reactions.map((reaction) =>\n Object.freeze({\n instance: instance.id,\n name: reaction.declaration.name,\n mode:\n reaction.synchronousProgram === undefined\n ? 'pending'\n : reaction.synchronousProgram === null\n ? 'generic'\n : reaction.synchronous !== undefined && reaction.synchronous !== null\n ? 'sync'\n : 'ready',\n functions: reaction.synchronousProgram?.functions.length ?? 0,\n }),\n ),\n ),\n ),\n });\n }\n /**\n * Read-only diagnostic view of process execution: bodies admitted as resumable blocks\n * versus bodies kept on the generator path. Reachable only via\n * `Symbol.for('mica-js.simulator/processes')`; not part of the public SDK.\n */\n private processReport(): unknown {\n const resumable: string[] = [];\n const generic: string[] = [];\n const programs: { readonly key: string; readonly blocks: number }[] = [];\n for (const instance of this.instances)\n for (const process of instance.processes) {\n const key = `${instance.id}/${process.declaration.kind === 'on' ? process.declaration.name : 'start'}`;\n (process.resumable ? resumable : generic).push(key);\n // Blocks stay zero for generator bodies: they have no machine to measure.\n programs.push(Object.freeze({ key, blocks: process.resumable?.blocks ?? 0 }));\n }\n return Object.freeze({\n resumable: Object.freeze(resumable),\n generic: Object.freeze(generic),\n programs: Object.freeze(programs),\n bindings: Object.freeze(this.instances.map((instance) => instance.bindingReport())),\n });\n }\n assertAlive(instance?: Instance): void {\n if (this.status === 'disposed' || (instance && !instance.valid))\n throw this.error('OBJECT_DISPOSED', 'Object is disposed', instance);\n }\n /** Admission for a call that may change board state or is visible to a device. */\n assertCallAllowed(instance?: Instance): void {\n this.admit(instance, false);\n }\n /** Admission for a read-only entry point: a faulted board stays inspectable. */\n assertReadAllowed(instance?: Instance): void {\n this.admit(instance, true);\n }\n private admit(instance: Instance | undefined, allowFaulted: boolean): void {\n this.assertAlive(instance);\n if (instance && ['execute', 'translate', 'dispose', 'assembly'].includes(this.phase))\n throw this.error('INVALID_CALL_STATE', 'Operation is not allowed in this phase', instance);\n if (!allowFaulted && this.status === 'faulted')\n throw this.error('BOARD_FAULTED', 'Board is faulted', instance);\n }\n error(\n code: RuntimeDiagnosticCode,\n message: string,\n instance?: Instance,\n cause?: unknown,\n phase?: RuntimePhase,\n ): SimulationError {\n const electrical = cause instanceof ElectricalError ? cause : undefined;\n return new SimulationError(\n Object.freeze({\n code,\n message,\n phase: phase ?? (this.phase === 'idle' ? 'host' : (this.phase as RuntimePhase)),\n time: this.time,\n ...(electrical?.instanceId !== undefined\n ? { instanceId: electrical.instanceId }\n : instance\n ? { instanceId: instance.id }\n : {}),\n ...(electrical?.resource !== undefined ? { resource: electrical.resource } : {}),\n ...modelLocation(cause),\n ...(cause === undefined ? {} : { cause }),\n related: Object.freeze([]),\n }),\n );\n }\n wrap(\n cause: unknown,\n code: RuntimeDiagnosticCode,\n phase: RuntimePhase,\n instance?: Instance,\n ): SimulationError {\n if (\n cause instanceof SimulationError &&\n !['DEVICE_CALLBACK_FAILED', 'JIT_FAILED', 'CLEANUP_FAILED'].includes(code)\n )\n return cause;\n const ownCode =\n cause instanceof ElectricalError ||\n cause instanceof ElectricalParameterError ||\n cause instanceof AsyncHookError\n ? cause.code\n : undefined;\n return this.error(\n phase !== 'dispose' && ownCode ? ownCode : code,\n cause instanceof Error ? cause.message : String(cause),\n instance,\n cause,\n phase,\n );\n }\n fault(error: SimulationError): void {\n if (this.status !== 'ready') return;\n this.status = 'faulted';\n this.primary = error;\n this.dispatchDepth++;\n try {\n this.errors.fire(error.diagnostic);\n } finally {\n this.dispatchDepth--;\n }\n }\n private diagnostic(code: RuntimeDiagnosticCode, cause: unknown, instance?: Instance): void {\n const diagnostic = this.error(\n code,\n cause instanceof Error ? cause.message : String(cause),\n instance,\n cause,\n ).diagnostic;\n this.dispatchDepth++;\n try {\n this.diagnostics.fire(diagnostic);\n } finally {\n this.dispatchDepth--;\n }\n }\n private fallback(cause: unknown): void {\n try {\n console.error(cause);\n } catch {\n /* Reporting cannot replace the primary failure. */\n }\n }\n report(instance: Instance, cause: unknown): void {\n if (this.status === 'disposed') {\n this.fallback(cause);\n return;\n }\n if (!instance.valid) {\n this.diagnostic('STALE_REPORT', cause, instance);\n return;\n }\n if (this.status === 'faulted') {\n this.diagnostic('REPORTED_ERROR', cause, instance);\n return;\n }\n this.fault(\n this.error(\n 'REPORTED_ERROR',\n cause instanceof Error ? cause.message : String(cause),\n instance,\n cause,\n 'report',\n ),\n );\n }\n topicBridge(owner?: Instance): TopicBridge {\n const facade = Object.freeze({\n onDidReceive: ((\n listener: (message: TopicMessage) => unknown,\n thisArgs?: unknown,\n disposables?: Disposable[],\n ) => {\n this.assertCallAllowed(owner);\n const entry: TopicListener = {\n ...(owner ? { owner } : {}),\n call: (message) => listener.call(thisArgs, message),\n };\n this.listeners.add(entry);\n if (!owner) this.hostListeners++;\n let active = true;\n const disposable = {\n dispose: () => {\n if (active) {\n active = false;\n // Deleting decides the decrement, so a cleared set cannot drive the count negative.\n if (this.listeners.delete(entry) && !owner) this.hostListeners--;\n }\n },\n };\n disposables?.push(disposable);\n owner?.resources.push(disposable);\n return disposable;\n }) as Event<TopicMessage>,\n publish: (topic: string, payload: unknown) => {\n this.assertCallAllowed(owner);\n if (typeof topic !== 'string') throw new TypeError('Topic must be a string');\n this.dispatchDepth++;\n try {\n const message = Object.freeze({ topic, payload });\n for (const entry of [...this.listeners]) {\n if (entry.owner && this.status !== 'ready') continue;\n try {\n const result = entry.call(message);\n if (entry.owner) acceptSync(result);\n } catch (cause) {\n if (entry.owner)\n this.fault(this.wrap(cause, 'DEVICE_CALLBACK_FAILED', 'topic', entry.owner));\n else this.diagnostic('HOST_LISTENER_FAILED', cause);\n }\n }\n } finally {\n this.dispatchDepth--;\n }\n },\n });\n // The admission check and the owner-less listener count stay off the public contract: they\n // exist for the adapter layer, which decides whether anyone would receive a message.\n registerPublishGate(facade, {\n assertPublishAllowed: () => this.assertCallAllowed(owner),\n hostListeners: () => this.hostListeners,\n });\n return facade;\n }\n private enqueue(process: Process): void {\n if (process.state === 'idle') {\n process.state = 'queued';\n this.models.push(process);\n } else if (process.state !== 'queued') process.pending = true;\n }\n queueJit(jit: Jit): void {\n if (jit.active && !jit.stopped && !jit.queued) {\n jit.queued = true;\n this.readyJits.push(jit);\n }\n }\n /**\n * Fail-closed admission for resuming generated code without a scheduler round trip.\n * The JIT must be the only direct owner, all same-time scheduler stages must be empty,\n * and no event may be due through the requested horizon. The target time is exclusive:\n * code must not resume at `executionEnd`.\n */\n canContinueDirect(jit: Jit, horizon: number): boolean {\n return (\n this.status === 'ready' &&\n this.phase === 'execute' &&\n !this.isFaulted &&\n this.execution === 'throughput' &&\n this.jits.length === 1 &&\n this.jits[0] === jit &&\n jit.active &&\n !jit.stopped &&\n !jit.queued &&\n this.readyJits.length === 0 &&\n this.models.length === 0 &&\n this.waitingJits.size === 0 &&\n this.time < this.executionEnd &&\n horizon >= this.time &&\n horizon < this.executionEnd &&\n this.events.time > horizon\n );\n }\n invalidate(slot: ResourceSlot): void {\n slot.version++;\n this.versionEpoch++;\n this.flagWaiters(slot);\n if (slot.subscribers.size === 0) return;\n for (const observation of slot.subscribers) this.observations.add(observation.order!);\n }\n /** Records a resource version bumped outside :func:`invalidate` (direct JIT writes). */\n noteResourceVersion(slot: ResourceSlot): void {\n this.versionEpoch++;\n this.flagWaiters(slot);\n }\n /** Flags every parked JIT that recorded `slot`, so the next round rescans it exactly once. */\n private flagWaiters(slot: ResourceSlot): void {\n const waiters = slot.waiters;\n if (waiters === undefined || waiters.size === 0) return;\n for (const jit of waiters) jit.dependencyDirty = true;\n this.waiterEpoch++;\n }\n /**\n * Registers a parked JIT on the slots its predicate recorded. A later version bump then\n * flags that JIT directly, so a scheduler round rescans dependencies only when the\n * evidence it would read has actually moved.\n */\n private watchWaiter(jit: Jit): void {\n const dependencies = jit.dependencies;\n if (jit.waiterSlots === dependencies) return;\n const previous = jit.waiterSlots;\n if (previous !== undefined) for (const slot of previous.keys()) slot.waiters?.delete(jit);\n if (dependencies !== undefined)\n for (const slot of dependencies.keys()) (slot.waiters ??= new Set()).add(jit);\n jit.waiterSlots = dependencies;\n // The recorded versions are only proven current by a scan after this registration, so\n // a write in the same round cannot be missed.\n jit.dependencyDirty = true;\n }\n /**\n * Parks a JIT on the versions it just recorded. Registering here instead of in the scan\n * makes `waiterEpoch` a complete wake source: the scan can then be skipped whenever no\n * parked JIT was flagged or registered since the last scan, and no poll is due.\n */\n parkWaiter(jit: Jit): void {\n if (!this.waitingJits.has(jit)) {\n this.waitingJits.add(jit);\n if (jit.pollingWait) this.pollingWaiterCount++;\n }\n this.watchWaiter(jit);\n jit.dependencyDirty = true;\n this.waiterEpoch++;\n }\n /** Wakes or drops a parked JIT and removes the registrations that would flag it later. */\n unparkWaiter(jit: Jit): void {\n if (this.waitingJits.delete(jit) && jit.pollingWait) {\n jit.pollingWait = false;\n this.pollingWaiterCount--;\n }\n const slots = jit.waiterSlots;\n if (slots !== undefined) {\n for (const slot of slots.keys()) slot.waiters?.delete(jit);\n jit.waiterSlots = undefined;\n }\n }\n /**\n * Checkpoint source for cached dependency evidence. An unchanged value since a previous\n * checkpoint proves no resource version moved in between, which is enough to reuse that\n * evidence without scanning it.\n */\n get resourceEpoch(): number {\n return this.versionEpoch;\n }\n /** Pin slot of an electrical endpoint; bound once because the board order is fixed. */\n electricalSlot(pin: ElectricalPin): number {\n return this.electricalSlots.get(pin)!;\n }\n markElectricalDirty(slot: number): void {\n const pending = this.pendingElectricalSlot;\n if (pending === slot) return;\n const stamps = this.dirtyElectricalStamps;\n if (slot >= stamps.length) throw new RangeError('Electrical slot is outside the board');\n const epoch = this.dirtyElectricalEpoch;\n if (stamps[slot] === epoch) return;\n stamps[slot] = epoch;\n if (pending >= 0) {\n // The promoted batch holds the single pending slot first, then this one.\n const list = this.dirtyElectricalSlots;\n list[0] = pending;\n list[1] = slot;\n stamps[pending] = epoch;\n this.dirtyElectricalLength = 2;\n this.pendingElectricalSlot = -2;\n return;\n }\n if (pending === -1) {\n this.pendingElectricalSlot = slot;\n return;\n }\n this.dirtyElectricalSlots[this.dirtyElectricalLength++] = slot;\n }\n /** Dirty slot count for diagnostics, not used by the publication path. */\n get dirtyElectricalCount(): number {\n return this.pendingElectricalSlot >= 0 ? 1 : this.dirtyElectricalLength;\n }\n private publish(): void {\n const pending = this.pendingElectricalSlot;\n if (pending === -1) return;\n // Fused publish: the solver hands every changed slot straight to `publishSlot`, which\n // resolves the pre-bound sample slot without any intermediate result array.\n if (pending >= 0) this.network.solveSlotInto(pending, this.publishSlot);\n else\n this.network.solveSlotBatchInto(\n this.dirtyElectricalSlots,\n this.dirtyElectricalLength,\n this.publishSlot,\n );\n if (pending === -2) this.dirtyElectricalLength = 0;\n // A new epoch retires every stamp, including the single pending slot's own mark.\n if (++this.dirtyElectricalEpoch === 0x7fffffff) {\n this.dirtyElectricalStamps.fill(0);\n this.dirtyElectricalEpoch = 1;\n }\n this.pendingElectricalSlot = -1;\n }\n /** Publication sink: enter the observation queue for one published board slot. */\n private readonly publishSlot = (slot: number): void => {\n this.invalidate(this.sampleSlotsBySlot[slot]!);\n };\n private bindObservation(observation: Receiver, path: readonly string[]): void {\n const instance = observation.instance;\n observation.previous = instance.observe(observation, path);\n observation.readSource = instance.observationReader(observation, path);\n observation.order = this.observations.register(observation);\n }\n /**\n * Static sources whose root is a derived declaration are grouped into one generated\n * chain per (instance, path): the reader, the stable comparator and the dependency\n * slots are bound once at baseline and shared by every receiver. Every other source\n * keeps the generic path.\n */\n private baseline(): void {\n this.publish();\n const entries: {\n observation: Receiver;\n path: readonly string[];\n key: string;\n instance: Instance;\n }[] = [];\n for (const instance of this.instances) {\n const prefix = `${instance.id}\\0`;\n for (const process of instance.processes)\n if (\n process.source &&\n instance.declarations.get(process.source[0]!)?.kind !== 'notification'\n )\n entries.push({\n observation: process,\n path: process.source,\n key: prefix + process.source.join('\\0'),\n instance,\n });\n for (const reaction of instance.reactions) {\n const path = reaction.declaration.sourcePath;\n entries.push({\n observation: reaction,\n path,\n key: prefix + path.join('\\0'),\n instance,\n });\n }\n }\n const groups = new Map<string, ObservationChain | undefined>();\n for (const entry of entries) {\n if (groups.has(entry.key)) continue;\n const compilation = compileObservation(entry.instance, entry.key, entry.path);\n if (!compilation.ok) {\n this.skippedPlans.push({ key: entry.key, reason: compilation.reason });\n groups.set(entry.key, undefined);\n continue;\n }\n const plan = compilation.plan;\n const chain: ObservationChain = {\n plan,\n instance: entry.instance,\n members: [],\n dependencies: new Map(),\n entry: { dependencies: new Map<ResourceSlot, number>(), value: undefined, epoch: -1 },\n order: 0,\n previous: undefined,\n bound: false,\n };\n groups.set(entry.key, chain);\n this.plans.push(chain);\n }\n for (const entry of entries) {\n const chain = groups.get(entry.key);\n if (chain === undefined) {\n this.bindObservation(entry.observation, entry.path);\n continue;\n }\n if (chain.bound) {\n // One queue slot per collapsed receiver keeps unrelated observation indices and\n // the original relative order intact.\n entry.observation.order = this.observations.register(EMPTY_QUEUE_ENTRY);\n } else {\n chain.bound = true;\n chain.order = this.observations.register(chain);\n entry.observation.order = chain.order;\n this.bindChain(chain);\n }\n chain.members.push(entry.observation);\n entry.observation.previous = chain.previous;\n }\n }\n private bindChain(chain: ObservationChain): void {\n const instance = chain.instance;\n for (const slot of chain.plan.slots as readonly ResourceSlot[]) {\n if (!slot.subscribers.size) instance.observerRevision++;\n slot.subscribers.add(chain);\n }\n const value = chain.plan.evaluate();\n chain.previous = chain.plan.needsSnapshot ? snapshot(value) : value;\n this.commitChain(chain, value);\n }\n /** Keep the derived cache populated with the value the chain just computed. */\n private commitChain(chain: ObservationChain, value: unknown): void {\n const path = chain.plan.path;\n if (path.length !== 1) return;\n const slots = chain.plan.slots as readonly ResourceSlot[];\n const dependencies = chain.dependencies;\n for (let index = 0; index < slots.length; index++) {\n const slot = slots[index]!;\n dependencies.set(slot, slot.version);\n }\n const entry = chain.entry;\n if (entry.value !== value) entry.value = value;\n entry.dependencies = dependencies;\n entry.epoch = this.versionEpoch;\n chain.instance.setDerived(path[0]!, entry);\n }\n private collectChain(chain: ObservationChain): void {\n const value = chain.plan.evaluate();\n const current = chain.plan.needsSnapshot ? snapshot(value) : value;\n this.commitChain(chain, value);\n if (chain.plan.equals(chain.previous, current)) return;\n const previous = chain.previous;\n chain.previous = current;\n const members = chain.members;\n const member = members[0]!;\n if (members.length === 1 && !this.changeObservations.length) {\n // A single receiver has the chain's own queue slot, so its order is already the\n // batch position and the effect can be applied without the reordering table.\n member.previous = current;\n this.applyChange(member, previous, current);\n return;\n }\n for (const entry of members) {\n entry.previous = current;\n this.recordChange(entry, previous, current);\n }\n }\n private applyChange(observation: Receiver, previous: unknown, current: unknown): void {\n if (observation.declaration.kind === 'reaction') {\n const reaction = observation as Reaction;\n const frame = reaction.frame as MutableReactionFrame | undefined;\n if (frame === undefined) reaction.frame = { previous, current, captures: [] };\n else {\n frame.previous = previous;\n frame.current = current;\n frame.captures.length = 0;\n }\n this.reactionBatch.push(reaction);\n } else this.enqueue(observation as Process);\n }\n private recordChange(observation: Receiver, previous: unknown, current: unknown): void {\n this.insertOrderedChange(\n this.changeObservations,\n this.changePrevious,\n this.changeCurrent,\n observation,\n previous,\n current,\n );\n }\n /** Shared stable insertion; receivers are few, so in-place insertion beats a sort. */\n private insertOrderedChange(\n receivers: Receiver[],\n previous: unknown[],\n current: unknown[],\n observation: Receiver,\n before: unknown,\n after: unknown,\n ): void {\n let at = receivers.length;\n const order = observation.order!;\n while (at > 0 && receivers[at - 1]!.order! > order) at--;\n if (at === receivers.length) {\n receivers.push(observation);\n previous.push(before);\n current.push(after);\n } else {\n receivers.splice(at, 0, observation);\n previous.splice(at, 0, before);\n current.splice(at, 0, after);\n }\n }\n boundary(): void {\n for (;;) {\n if (this.pendingElectricalSlot !== -1) this.publish();\n if (!this.observations.size) return;\n // Truncating a non-empty array clears its elements; an already-empty buffer needs\n // no store at all, which is the common case for the ordering tables.\n const reactions = this.reactionBatch;\n if (reactions.length) reactions.length = 0;\n const changes = this.changeObservations;\n if (changes.length) changes.length = 0;\n if (this.changePrevious.length) this.changePrevious.length = 0;\n if (this.changeCurrent.length) this.changeCurrent.length = 0;\n this.observations.drain(this.consumeObservation);\n const count = changes.length;\n if (count) {\n for (let index = 0; index < count; index++)\n this.applyChange(changes[index]!, this.changePrevious[index], this.changeCurrent[index]);\n changes.length = 0;\n this.changePrevious.length = 0;\n this.changeCurrent.length = 0;\n }\n if (reactions.length) this.runBoundaryReactions(reactions);\n else return;\n }\n }\n /** One due receiver: chains collapse their members, plain sources apply inline. */\n private readonly consumeObservation = (observation: Observation): void => {\n if ('plan' in observation) {\n this.collectChain(observation);\n return;\n }\n const current = observation.readSource!();\n if (same(observation.previous, current)) return;\n const previous = observation.previous;\n observation.previous = current;\n // Once a collapsed chain buffered its receivers, later effects must wait for the\n // ordered table; otherwise the original inline application is kept.\n if (this.changeObservations.length) this.recordChange(observation, previous, current);\n else this.applyChange(observation, previous, current);\n };\n /** Shared capture barrier and ordered body runner for generic and static boundaries. */\n private runBoundaryReactions(reactions: Reaction[]): void {\n try {\n // Every instance completes observation and capture before any reaction body runs.\n for (const reaction of reactions)\n if (reaction.declaration.captures.length) {\n const frame = reaction.frame as MutableReactionFrame;\n frame.captures = reaction.declaration.captures.map((capture) =>\n snapshot(computation(capture.value, reaction.instance.host)),\n );\n }\n for (const reaction of reactions) {\n this.current = reaction.instance;\n this.runReaction(reaction);\n }\n } finally {\n this.clearReactionFrames(reactions);\n }\n }\n private clearReactionFrames(reactions: Reaction[]): void {\n for (const reaction of reactions) {\n const frame = reaction.frame as MutableReactionFrame | undefined;\n if (frame === undefined) continue;\n frame.previous = undefined;\n frame.current = undefined;\n frame.captures.length = 0;\n }\n }\n /**\n * Execute one synchronous boundary reaction. The capture barrier already froze every\n * frame before this method runs. Admission is whole-body: a compiler decline selects\n * the generator path before any effect, while bind/execution errors propagate without\n * a catch-and-replay fallback.\n */\n private runReaction(reaction: Reaction): void {\n const instance = reaction.instance;\n let program = reaction.synchronousProgram;\n if (program === undefined) {\n program = synchronousBody(instance, reaction.declaration.body) ?? null;\n reaction.synchronousProgram = program;\n }\n if (program !== null) {\n let runner = reaction.synchronous;\n if (runner === undefined || runner === null) {\n runner = program.bind(instance.host);\n reaction.synchronous = runner;\n }\n runner(undefined, reaction.frame);\n return;\n }\n reaction.execute ??= body(reaction.declaration.body);\n const step = reaction.execute(instance.host, [], reaction.frame).next();\n if (!step.done) throw new TypeError('Reaction cannot suspend');\n }\n private drive(process: Process, value?: unknown): void {\n const program = process.resumable;\n if (program) {\n this.driveResumable(process, program, value);\n return;\n }\n this.current = process.instance;\n process.state = 'running';\n process.execution ??= body(process.declaration.body)(process.instance.host);\n for (;;) {\n const step = process.execution.next(value);\n if (step.done) {\n this.boundary();\n process.execution = undefined;\n process.state = 'idle';\n if (process.pending) {\n process.pending = false;\n this.enqueue(process);\n }\n return;\n }\n const signal = step.value;\n if (signal.kind === 'receive') {\n const channel = process.instance.channels.get(signal.channel)!;\n if (channel.incoming.length) {\n value = channel.incoming.shift().value;\n continue;\n }\n process.state = 'waiting';\n channel.receiver = process;\n this.boundary();\n return;\n }\n if (signal.kind !== 'ticks') throw new TypeError('Invalid process suspension');\n const duration = time(signal.duration),\n due = time(this.time + duration);\n process.state = 'waiting';\n this.boundary();\n if (duration === 0) {\n process.state = 'queued';\n this.models.push(process);\n } else {\n // The continuation is bound once per process: only one timed wake can be pending.\n process.wake ??= () => {\n process.state = 'queued';\n this.models.push(process);\n };\n this.events.push(due, process.wake);\n }\n return;\n }\n }\n /**\n * Same suspension contract as `drive`, driven by the body's own pc and reused frame:\n * the body reports ticks/receive through the frame and returns whether it suspended.\n */\n private driveResumable(process: Process, program: ResumableProgram, value?: unknown): void {\n const instance = process.instance;\n this.current = instance;\n process.state = 'running';\n const state = (process.frame ??= frame(program));\n const host = instance.host;\n let input = value;\n for (;;) {\n state.value = input;\n if (!program.run(host, undefined, undefined, state)) {\n this.boundary();\n process.state = 'idle';\n if (process.pending) {\n process.pending = false;\n this.enqueue(process);\n }\n return;\n }\n if (state.kind === RESUMABLE_RECEIVE) {\n const channel = instance.channels.get(state.channel)!;\n if (channel.incoming.length) {\n input = channel.incoming.shift().value;\n continue;\n }\n process.state = 'waiting';\n channel.receiver = process;\n this.boundary();\n return;\n }\n // The body already validated the duration with H.checkDuration; only the sum needs\n // the shared range check.\n const duration = state.duration,\n due = time(this.time + duration);\n process.state = 'waiting';\n this.boundary();\n if (duration === 0) {\n process.state = 'queued';\n this.models.push(process);\n } else {\n process.wake ??= () => {\n process.state = 'queued';\n this.models.push(process);\n };\n this.events.push(due, process.wake);\n }\n return;\n }\n }\n runUntil(target: number): void {\n this.assertAlive();\n if (this.phase !== 'idle' || this.dispatchDepth)\n throw this.error('INVALID_CALL_STATE', 'Board is busy');\n if (this.status === 'faulted') throw this.error('BOARD_FAULTED', 'Board is faulted');\n const end = time(target);\n if (end < this.time) throw new RangeError('Cannot run backwards');\n const from = this.time;\n this.phase = 'execute';\n this.executionEnd = end;\n try {\n if (!this.initialized) {\n this.baseline();\n this.initialized = true;\n for (const instance of this.instances)\n for (const process of instance.processes)\n if (process.declaration.kind === 'start') this.enqueue(process);\n for (const jit of this.jits) this.queueJit(jit);\n }\n for (const instance of this.instances) {\n for (const channel of instance.channels.values()) {\n if (channel.pending.length)\n for (const message of channel.pending.drain()) channel.incoming.push(message);\n if (channel.receiver && channel.incoming.length) {\n const process = channel.receiver;\n channel.receiver = undefined;\n const received = channel.incoming.shift()!.value;\n this.events.push(this.time, () => {\n process.state = 'queued';\n process.resumeValue = received;\n this.models.push(process);\n });\n }\n }\n for (const notification of instance.notificationInputs)\n for (const process of instance.processes)\n if (process.source?.[0] === notification) this.enqueue(process);\n instance.notificationInputs.clear();\n }\n // A parked JIT records the versions it read, so it can only become runnable once one\n // of those slots is invalidated; the wait set binds exactly that dependency set, and a\n // periodic poll still needs its boundary recomputed on every round. Both facts are\n // counted in `waiterEpoch` / `pollingWaiterCount`, so a round where neither moved\n // skips the scan entirely with `pollingBoundary` left at Infinity.\n for (;;) {\n while (this.events.time === this.time) this.events.pop()();\n if (this.models.length) {\n const process = this.models.shift()!;\n const value = process.resumeValue;\n process.resumeValue = undefined;\n this.drive(process, value);\n if (this.isFaulted) throw this.primary!;\n continue;\n }\n let pollingBoundary = Infinity;\n if (\n this.waitingJits.size &&\n (this.waiterEpoch !== this.waitingScanEpoch || this.pollingWaiterCount !== 0)\n ) {\n this.waitingScanEpoch = this.waiterEpoch;\n for (let index = 0; index < this.jits.length; index++) {\n const jit = this.jits[index]!;\n if (!jit.active || jit.stopped || !this.waitingJits.has(jit)) continue;\n this.watchWaiter(jit);\n if (!jit.dependencyDirty && !jit.pollingWait) continue;\n if (jit.instance.dependenciesCurrent(jit.dependencies)) {\n jit.dependencyDirty = false;\n if (jit.pollingWait && jit.pollingPeriod > 0) {\n const lastStart = MAX_TIME - ((MAX_TIME - jit.pollingOrigin) % jit.pollingPeriod);\n if (lastStart < MAX_TIME && lastStart < end) {\n if (lastStart === this.time) {\n jit.pollingToken++;\n delete jit.dependencies;\n this.unparkWaiter(jit);\n this.queueJit(jit);\n } else pollingBoundary = Math.min(pollingBoundary, lastStart);\n }\n }\n continue;\n }\n jit.dependencyDirty = false;\n if (jit.pollingWait) {\n jit.pollingToken++;\n delete jit.dependencies;\n this.unparkWaiter(jit);\n const remainder =\n jit.pollingPeriod > 0 ? (this.time - jit.pollingOrigin) % jit.pollingPeriod : 0;\n if (remainder)\n this.events.push(time(this.time + (jit.pollingPeriod - remainder)), () =>\n this.queueJit(jit),\n );\n else this.queueJit(jit);\n } else if (jit.predicate) {\n const checked = jit.instance.evaluate(() => syncJitCall(jit, jit.predicate!));\n jit.dependencies = checked.dependencies;\n if (checked.value === true) {\n delete jit.predicate;\n delete jit.dependencies;\n this.unparkWaiter(jit);\n this.queueJit(jit);\n } else {\n // The replaced dependency set is re-registered and needs its own scan.\n this.watchWaiter(jit);\n this.waiterEpoch++;\n }\n }\n }\n }\n if (this.time < end && this.readyJits.length) {\n runJit(this, this.readyJits.shift());\n if (this.isFaulted) throw this.primary!;\n continue;\n }\n if (pollingBoundary < this.events.time && pollingBoundary <= end) {\n this.time = pollingBoundary;\n continue;\n }\n const next = this.events.time;\n if (next <= end) {\n this.time = next;\n // The next round would only drain these events at the top of the loop; doing it\n // here saves one scheduler round per due event and observes the same order\n // (callbacks still run before the model queue is served).\n while (this.events.time === this.time) this.events.pop()();\n continue;\n }\n this.time = end;\n break;\n }\n const batches = this.instances.map((instance) => instance.captureBatch(from, end));\n this.phase = 'sync';\n for (let i = 0; i < this.instances.length; i++) {\n const instance = this.instances[i]!;\n this.current = instance;\n try {\n acceptSync(instance.adapter!.sync(batches[i]!));\n } catch (cause) {\n throw this.wrap(cause, 'DEVICE_CALLBACK_FAILED', 'sync', instance);\n }\n if (this.isFaulted) throw this.primary!;\n }\n } catch (cause) {\n const error = this.wrap(\n cause,\n 'MODEL_EXECUTION_FAILED',\n this.phase === 'sync' ? 'sync' : 'execute',\n this.current,\n );\n this.fault(error);\n throw error;\n } finally {\n this.current = undefined;\n this.phase = 'idle';\n }\n }\n dispose(): void {\n if (this.status === 'disposed') return;\n if (this.phase !== 'idle' || this.dispatchDepth)\n throw this.error('INVALID_CALL_STATE', 'Board is busy');\n const errors = this.cleanup();\n if (errors.length)\n throw this.primary\n ? this.aggregate(this.primary, errors)\n : this.aggregate(errors[0]!, errors.slice(1));\n }\n private aggregate(primary: SimulationError, errors: readonly SimulationError[]): SimulationError {\n return new SimulationError(\n Object.freeze({\n ...primary.diagnostic,\n related: Object.freeze([...primary.related, ...errors.map((error) => error.diagnostic)]),\n }),\n );\n }\n private cleanup(): SimulationError[] {\n this.phase = 'dispose';\n for (const instance of this.instances) instance.valid = false;\n const errors: SimulationError[] = [];\n for (const instance of [...this.instances].reverse()) {\n if (instance.adapter) {\n try {\n acceptSync(instance.adapter.dispose());\n } catch (cause) {\n errors.push(this.wrap(cause, 'CLEANUP_FAILED', 'dispose', instance));\n }\n }\n for (const resource of [...instance.resources].reverse()) {\n try {\n resource.dispose();\n } catch (cause) {\n errors.push(this.wrap(cause, 'CLEANUP_FAILED', 'dispose', instance));\n }\n }\n instance.resources.length = 0;\n }\n this.events.clear();\n this.models.clear();\n this.readyJits.clear();\n this.observations.clear();\n this.reactionBatch.length = 0;\n this.plans.length = 0;\n this.skippedPlans.length = 0;\n this.changeObservations.length = 0;\n this.changePrevious.length = 0;\n this.changeCurrent.length = 0;\n this.sampleSlots.clear();\n this.listeners.clear();\n this.hostListeners = 0;\n this.errors.dispose();\n this.diagnostics.dispose();\n this.status = 'disposed';\n this.phase = 'idle';\n return errors;\n }\n}\nexport function createBoard(\n library: DeviceLibrary,\n description: BoardDescription,\n options?: BoardOptions,\n): Board {\n const entries = libraries.get(library);\n if (!entries)\n throw standalone('INVALID_CONFIGURATION', new TypeError('Unknown device library'), 'assembly');\n if (arguments.length >= 3 && options === undefined)\n throw standalone(\n 'INVALID_CONFIGURATION',\n new TypeError('Explicit undefined options'),\n 'assembly',\n );\n return new BoardRuntime(entries, description, options ?? {});\n}\n","/** Stable failure codes of the prepared-simulation runtime. */\nexport type SimulationRuntimeErrorCode =\n | 'invalid-input'\n | 'invalid-device'\n | 'unresolved-device'\n | 'unresolved-asset'\n | 'not-loaded'\n | 'disposed';\n\nexport interface ISimulationRuntimeErrorOptions {\n /** Device the failure belongs to, as the prepared simulation names it. */\n readonly deviceId?: string;\n readonly cause?: unknown;\n}\n\n/**\n * Error raised while preparing or driving a prepared simulation.\n *\n * The code is stable and machine-checkable; the message names the offending device, symbol or\n * asset so a caller can report it without parsing the cause chain.\n */\nexport class SimulationRuntimeError extends Error {\n override readonly name = 'SimulationRuntimeError';\n readonly code: SimulationRuntimeErrorCode;\n readonly deviceId: string | undefined;\n\n constructor(\n code: SimulationRuntimeErrorCode,\n message: string,\n options: ISimulationRuntimeErrorOptions = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.code = code;\n this.deviceId = options.deviceId;\n }\n}\n\n/** Message of one thrown value, used to give load failures a readable envelope. */\nexport function errorMessage(error: unknown): string {\n return error instanceof Error && error.message.length > 0 ? error.message : String(error);\n}\n","import { validateDeviceIR } from '@mica-js/device-model';\nimport type { DeviceIR } from '@mica-js/device-model';\nimport { assetSrcError } from '@mica-js/document';\nimport {\n deriveSchematicTopology,\n deviceMetadataSymbol,\n isAssetReference,\n parseDeviceMetadata,\n parseDeviceReference,\n parseSchematic,\n symbolRole,\n} from '@mica-js/document/schematic';\nimport type {\n DeviceMetadata,\n DeviceSymbolProvider,\n SchematicSymbol,\n} from '@mica-js/document/schematic';\nimport { resolveDelivery } from '@mica-js/document/canvas';\nimport type { DeliveryKind, PayloadType } from '@mica-js/document/canvas';\nimport type { BoardDescription, DeviceLibraryEntry, PropertyInput } from '../types';\nimport { errorMessage, SimulationRuntimeError } from './errors';\nimport type { IPreparedSimulation, SimulationModuleImporter } from './types';\n\nexport interface IPreparedDeviceTopic {\n readonly port: string;\n readonly direction: 'input' | 'output';\n readonly type: PayloadType;\n readonly delivery: DeliveryKind;\n}\n\nexport interface IPreparedDevice {\n readonly id: string;\n readonly definition: DeviceMetadata;\n readonly model: DeviceIR;\n readonly create: DeviceLibraryEntry['create'];\n readonly topics: ReadonlyMap<string, IPreparedDeviceTopic>;\n}\n\nexport interface IPreparedInstance {\n readonly symbol: string;\n readonly device: IPreparedDevice;\n}\n\nexport interface IResolvedSimulation {\n readonly instances: readonly IPreparedInstance[];\n readonly description: BoardDescription;\n readonly execution?: IPreparedSimulation['execution'];\n}\n\n/** Imports only referenced SDK modules and captures all inputs before any factory runs. */\nexport async function prepareSimulation(\n input: IPreparedSimulation,\n importer: SimulationModuleImporter,\n assertActive: () => void,\n): Promise<IResolvedSimulation> {\n if (!isRecord(input) || !Array.isArray(input.devices)) {\n throw new SimulationRuntimeError('invalid-input', 'Expected schematic and devices');\n }\n const schematic = parseSchematic(input.schematic);\n const assets = readAssets(input.assets);\n const voltageReferences = readVoltageReferences(input.voltageReferences);\n const candidates = new Map<\n string,\n { readonly definition: DeviceMetadata; readonly code: string }\n >();\n for (const candidate of input.devices) {\n if (\n !isRecord(candidate) ||\n typeof candidate.id !== 'string' ||\n parseDeviceReference(candidate.id) === undefined ||\n candidates.has(candidate.id) ||\n typeof candidate.code !== 'string' ||\n candidate.code.trim().length === 0\n ) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n 'Expected unique device ids and self-contained ESM code',\n );\n }\n let definition: DeviceMetadata;\n try {\n definition = structuredClone(parseDeviceMetadata(candidate.definition));\n } catch (cause) {\n throw new SimulationRuntimeError(\n 'invalid-device',\n `Invalid metadata for \"${candidate.id}\": ${errorMessage(cause)}`,\n { cause },\n );\n }\n if (definition.id !== parseDeviceReference(candidate.id)!.deviceId) {\n throw new SimulationRuntimeError(\n 'invalid-device',\n `Metadata id does not match \"${candidate.id}\"`,\n { deviceId: candidate.id },\n );\n }\n candidates.set(candidate.id, { definition, code: candidate.code });\n }\n const devices = new Map<string, IPreparedDevice>();\n const symbols = schematic.sheet.symbols.filter(\n (symbol) => symbolRole(symbol.device) === 'component',\n );\n for (const symbol of symbols) {\n if (devices.has(symbol.device)) continue;\n const candidate = candidates.get(symbol.device);\n if (candidate === undefined) {\n throw new SimulationRuntimeError(\n 'unresolved-device',\n `Missing prepared device \"${symbol.device}\"`,\n { deviceId: symbol.device },\n );\n }\n assertActive();\n try {\n const namespace = await importer(candidate.code, symbol.device);\n assertActive();\n if (\n !isRecord(namespace) ||\n !Object.hasOwn(namespace, 'model') ||\n !Object.hasOwn(namespace, 'create') ||\n typeof namespace.create !== 'function'\n ) {\n throw new TypeError('SDK device modules must export named model and synchronous create');\n }\n const model = validateDeviceIR(namespace.model);\n const pinNames = model.declarations\n .filter((declaration) => declaration.kind === 'pin')\n .map((pin) => pin.name);\n const metadataPins = candidate.definition.pins;\n if (metadataPins !== undefined && !sameNames(Object.keys(metadataPins), pinNames)) {\n throw new TypeError('Metadata pins do not match model pins');\n }\n const definition: DeviceMetadata = {\n ...candidate.definition,\n pins: metadataPins ?? Object.fromEntries(pinNames.map((name) => [name, {}])),\n };\n const geometry = deviceMetadataSymbol(definition);\n if (!sameNames(Object.keys(geometry.pins), pinNames)) {\n throw new TypeError('Symbol pins do not match model pins');\n }\n devices.set(symbol.device, {\n id: symbol.device,\n definition,\n model,\n create: namespace.create as DeviceLibraryEntry['create'],\n topics: new Map(\n Object.entries(definition.ports ?? {}).map(([port, topic]) => [\n port,\n { port, ...topic, delivery: resolveDelivery(topic.delivery, topic.type) },\n ]),\n ),\n });\n } catch (cause) {\n assertActive();\n throw new SimulationRuntimeError(\n 'invalid-device',\n `Device \"${symbol.device}\" failed to load: ${errorMessage(cause)}`,\n { deviceId: symbol.device, cause },\n );\n }\n }\n const provider: DeviceSymbolProvider = {\n getDeviceName: (reference) => devices.get(reference.raw)?.definition.displayName,\n getDeviceSymbol: (reference) => {\n const device = devices.get(reference.raw);\n return device === undefined ? undefined : deviceMetadataSymbol(device.definition);\n },\n };\n const topology = deriveSchematicTopology(schematic, { devices: provider });\n const empty =\n schematic.sheet.symbols.length === 0 &&\n schematic.sheet.wires.length === 0 &&\n schematic.sheet.junctions.length === 0;\n for (const name of voltageReferences.keys()) {\n if (!empty && !topology.nets.some((net) => net.name === name)) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n `Voltage reference names missing schematic net \"${name}\"`,\n );\n }\n }\n return {\n instances: symbols.map((symbol) => ({\n symbol: symbol.id,\n device: devices.get(symbol.device)!,\n })),\n ...(input.execution === undefined ? {} : { execution: input.execution }),\n description: {\n instances: symbols.map((symbol) => ({\n id: symbol.id,\n type: symbol.id,\n props: resolveProperties(symbol, devices.get(symbol.device)!, assets.get(symbol.id)),\n })),\n nets: topology.nets.map((net, index) => {\n const reference = net.name === null ? undefined : voltageReferences.get(net.name);\n const grounded = net.members.some((member) => member.kind === 'ground');\n if (grounded && reference !== undefined && reference !== 0) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n `Conflicting voltage references on ground net \"${net.name}\": 0 and ${reference}`,\n );\n }\n const voltage = grounded ? 0 : reference;\n return {\n id: `net:${index}`,\n pins: net.members.flatMap((member) =>\n member.kind === 'pin' ? [{ instance: member.symbolId, pin: member.pinId }] : [],\n ),\n ...(voltage === undefined ? {} : { voltage }),\n };\n }),\n },\n };\n}\n\nfunction resolveProperties(\n symbol: SchematicSymbol,\n device: IPreparedDevice,\n assets: ReadonlyMap<string, Uint8Array> | undefined,\n): Readonly<Record<string, PropertyInput>> {\n const values: Record<string, unknown> = Object.create(null);\n for (const [key, descriptor] of Object.entries(device.definition.properties ?? {})) {\n if (Object.hasOwn(descriptor, 'default')) values[key] = descriptor.default;\n }\n Object.assign(values, symbol.properties);\n const props: Record<string, PropertyInput> = Object.create(null);\n for (const [key, value] of Object.entries(values)) {\n if (isAssetReference(value)) {\n const problem = assetSrcError(value.mode, value.src);\n if (problem !== undefined)\n throw new SimulationRuntimeError('invalid-input', problem, { deviceId: device.id });\n const bytes = assets?.get(value.src);\n if (bytes === undefined) {\n throw new SimulationRuntimeError(\n 'unresolved-asset',\n `Symbol \"${symbol.id}\" is missing resource \"${value.src}\"`,\n { deviceId: device.id },\n );\n }\n props[key] = new Uint8Array(bytes);\n } else if (value instanceof Uint8Array) props[key] = new Uint8Array(value);\n else if (\n value === null ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'string'\n )\n props[key] = value;\n else\n throw new SimulationRuntimeError(\n 'invalid-input',\n `Unsupported property \"${symbol.id}.${key}\"`,\n { deviceId: device.id },\n );\n }\n return props;\n}\n\nfunction readVoltageReferences(value: unknown): ReadonlyMap<string, number> {\n if (value === undefined) return new Map();\n if (\n !isRecord(value) ||\n (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)\n ) {\n throw new SimulationRuntimeError('invalid-input', 'Expected a plain voltageReferences map');\n }\n const references = new Map<string, number>();\n for (const name of Reflect.ownKeys(value)) {\n const voltage = typeof name === 'string' ? value[name] : undefined;\n if (\n typeof name !== 'string' ||\n name.trim().length === 0 ||\n typeof voltage !== 'number' ||\n !Number.isFinite(voltage)\n ) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n 'Expected voltageReferences with nonempty net names and finite numeric voltages',\n );\n }\n references.set(name, voltage);\n }\n return references;\n}\n\nfunction readAssets(value: unknown): ReadonlyMap<string, ReadonlyMap<string, Uint8Array>> {\n const result = new Map<string, ReadonlyMap<string, Uint8Array>>();\n if (value === undefined) return result;\n if (!isRecord(value))\n throw new SimulationRuntimeError('invalid-input', 'Expected assets keyed by symbol id');\n for (const [symbol, entries] of Object.entries(value)) {\n if (!isRecord(entries))\n throw new SimulationRuntimeError('invalid-input', 'Expected asset entries keyed by src');\n const assets = new Map<string, Uint8Array>();\n for (const [src, bytes] of Object.entries(entries)) {\n if (!src || !(bytes instanceof Uint8Array))\n throw new SimulationRuntimeError('invalid-input', 'Resource bytes must be Uint8Array');\n assets.set(src, new Uint8Array(bytes));\n }\n result.set(symbol, assets);\n }\n return result;\n}\n\nfunction sameNames(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((name) => right.includes(name));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n","import { addTime, timePs } from '@mica-js/core';\nimport type { TimePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { Disposable, Event } from '@mica-js/core/lifecycle';\nimport type { DeliveryKind } from '@mica-js/document/canvas';\nimport { createBoard, createDeviceLibrary } from '../runtime';\nimport { publishGate } from '../runtime/publish-gate';\nimport type { Board, DeviceContext, RuntimeDiagnostic, TopicBridge, TopicMessage } from '../types';\nimport { errorMessage, SimulationRuntimeError } from './errors';\nimport { copyPayload, payloadMatches, samePayload, targetKey } from './payload';\nimport { prepareSimulation } from './prepare';\nimport type { IPreparedDeviceTopic, IPreparedInstance, IResolvedSimulation } from './prepare';\nimport type {\n IPreparedSimulation,\n ISimulationDiagnostic,\n ISimulationMessage,\n ISimulationRuntime,\n ISimulationRuntimeOptions,\n ISimulationTickReport,\n} from './types';\n\ninterface IOutput {\n readonly symbol: string;\n readonly port: string;\n readonly payload: unknown;\n readonly delivery: DeliveryKind;\n}\ninterface IDelivery {\n readonly symbol: string;\n readonly port: string;\n readonly payload: unknown;\n}\ninterface ILoadedRuntime {\n readonly prepared: IResolvedSimulation;\n readonly board: Board;\n readonly inputs: ReadonlyMap<string, IPreparedDeviceTopic>;\n readonly outputs: IOutput[];\n readonly diagnostics: ISimulationDiagnostic[];\n readonly subscriptions: readonly Disposable[];\n}\n\n/** Runs self-contained SDK devices on an atomic, replaceable Board. */\nexport function createSimulationRuntime(\n options: ISimulationRuntimeOptions = {},\n): ISimulationRuntime {\n const publishes = new Emitter<ISimulationMessage>();\n const diagnostics = new Emitter<ISimulationDiagnostic>();\n const pending: IDelivery[] = [];\n const published = new Map<string, unknown>();\n let active: ILoadedRuntime | undefined;\n let simTime = timePs(0);\n let disposed = false;\n let generation = 0;\n\n const assertActive = (): void => {\n if (disposed)\n throw new SimulationRuntimeError('disposed', 'Simulation runtime has been disposed');\n };\n const flush = (loaded: ILoadedRuntime): void => {\n // Without a publish listener nothing can observe these messages, and no listener can be added\n // while this loop runs, so the copies and messages are skipped instead of built and dropped.\n if (publishes.hasListeners) {\n for (const output of loaded.outputs.splice(0)) {\n if (output.delivery === 'level') {\n const key = targetKey(output.symbol, output.port);\n if (published.has(key) && samePayload(published.get(key), output.payload)) continue;\n // Keep the equality baseline independent from buffers/objects handed to listeners.\n if (publishes.hasListeners) published.set(key, copyPayload(output.payload));\n }\n // The publish snapshot in `outputs` is already an owned copy, so listeners may share it.\n publishes.fire({\n target: { symbol: output.symbol, port: output.port },\n payload: output.payload,\n simTime,\n });\n }\n } else {\n loaded.outputs.length = 0;\n }\n for (const diagnostic of loaded.diagnostics.splice(0)) {\n diagnostics.fire(\n diagnostic.runtimeCode === undefined ? { ...diagnostic, simTime } : diagnostic,\n );\n }\n };\n const release = (loaded: ILoadedRuntime | undefined): void => {\n if (loaded === undefined) return;\n try {\n loaded.board.dispose();\n } catch (cause) {\n diagnostics.fire({\n code: 'board/diagnostic',\n symbol: '',\n message: errorMessage(cause),\n simTime,\n phase: 'dispose',\n });\n } finally {\n for (const subscription of loaded.subscriptions) subscription.dispose();\n }\n };\n const install = (next: ILoadedRuntime): void => {\n const previous = active;\n active = next;\n pending.length = 0;\n published.clear();\n simTime = timePs(0);\n release(previous);\n };\n return {\n async load(input: IPreparedSimulation): Promise<void> {\n assertActive();\n const current = ++generation;\n const prepared = await prepareSimulation(\n input,\n options.importer ?? importBlobModule,\n assertActive,\n );\n assertActive();\n if (current !== generation) return;\n install(buildLoadedRuntime(prepared, () => publishes.hasListeners));\n },\n async reset(): Promise<void> {\n assertActive();\n ++generation;\n if (active !== undefined)\n install(buildLoadedRuntime(active.prepared, () => publishes.hasListeners));\n else {\n pending.length = 0;\n published.clear();\n simTime = timePs(0);\n }\n },\n async tick(dt: TimePs): Promise<ISimulationTickReport> {\n assertActive();\n if (!Number.isSafeInteger(dt) || dt <= 0)\n throw new TypeError('tick expects a positive integer dt in picoseconds');\n // Check the cumulative bound before consuming queued inputs or touching the board.\n const target = addTime(simTime, dt);\n const loaded = active;\n if (loaded === undefined) {\n simTime = target;\n return { simTime, executed: 0 };\n }\n try {\n for (const delivery of pending.splice(0)) {\n loaded.board.topics.publish(\n scopedTopic(delivery.symbol, delivery.port),\n delivery.payload,\n );\n }\n loaded.board.runUntil(target);\n } finally {\n simTime = timePs(loaded.board.time);\n flush(loaded);\n }\n return { simTime, executed: 1 };\n },\n async deliver(message: ISimulationMessage): Promise<void> {\n assertActive();\n if (\n message === null ||\n typeof message !== 'object' ||\n message.target === null ||\n typeof message.target !== 'object' ||\n typeof message.target.symbol !== 'string' ||\n typeof message.target.port !== 'string'\n ) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n 'Expected a message with string symbol and port',\n );\n }\n if (active === undefined)\n throw new SimulationRuntimeError('not-loaded', 'No simulation loaded');\n const { symbol, port } = message.target;\n const topic = active.inputs.get(targetKey(symbol, port));\n if (topic === undefined || !payloadMatches(topic.type, message.payload)) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n `Unknown input or invalid payload for ${symbol}.${port}`,\n );\n }\n if (topic.delivery === 'level') {\n const previous = pending.findIndex(\n (entry) => entry.symbol === symbol && entry.port === port,\n );\n if (previous !== -1) pending.splice(previous, 1);\n }\n pending.push({ symbol, port, payload: copyPayload(message.payload) });\n },\n onDidPublish: publishes.event,\n onDidDiagnostic: diagnostics.event,\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n ++generation;\n pending.length = 0;\n published.clear();\n release(active);\n active = undefined;\n publishes.dispose();\n diagnostics.dispose();\n },\n };\n}\n\nfunction buildLoadedRuntime(\n prepared: IResolvedSimulation,\n publishObserved: () => boolean,\n): ILoadedRuntime {\n const outputs: IOutput[] = [];\n const found: ISimulationDiagnostic[] = [];\n const inputs = new Map<string, IPreparedDeviceTopic>();\n const library = createDeviceLibrary(\n prepared.instances.map((instance) => {\n for (const topic of instance.device.topics.values()) {\n if (topic.direction === 'input') inputs.set(targetKey(instance.symbol, topic.port), topic);\n }\n return {\n id: instance.symbol,\n model: instance.device.model,\n create: (context: DeviceContext) =>\n instance.device.create({\n ...context,\n topics: scopeTopics(context.topics, instance, outputs, found, publishObserved),\n }),\n };\n }),\n );\n // Board captures bytes, but clone per creation as well so a factory cannot alter reset inputs.\n const description = {\n ...prepared.description,\n instances: prepared.description.instances.map((instance) => ({\n ...instance,\n props: Object.fromEntries(\n Object.entries(instance.props ?? {}).map(([key, value]) => [\n key,\n value instanceof Uint8Array ? new Uint8Array(value) : value,\n ]),\n ),\n })),\n };\n const board = createBoard(\n library,\n description,\n prepared.execution === undefined ? {} : { execution: prepared.execution },\n );\n const project = (diagnostic: RuntimeDiagnostic, fatal: boolean): void => {\n found.push({\n code: fatal\n ? diagnostic.phase === 'topic'\n ? 'device/input-failed'\n : diagnostic.phase === 'sync'\n ? 'device/output-failed'\n : 'board/error'\n : 'board/diagnostic',\n symbol: diagnostic.instanceId ?? '',\n message: diagnostic.message,\n simTime: timePs(diagnostic.time ?? board.time),\n runtimeCode: diagnostic.code,\n phase: diagnostic.phase,\n });\n };\n return {\n prepared,\n board,\n inputs,\n outputs,\n diagnostics: found,\n subscriptions: [\n board.onDidError((event) => project(event, true)),\n board.onDidDiagnostic((event) => project(event, false)),\n ],\n };\n}\n\n/**\n * Board topics are opaque global strings; this boundary gives each factory local port names.\n *\n * Exported for the fan-out regression test, which drives it against a real `Board`: every accepted\n * output must still reach `board.topics` listeners even when the instance has no scoped subscriber.\n *\n * `publishObserved` reports whether anything outside the board consumes published messages; with no\n * scoped subscriber, no owner-less bridge listener and no consumer, an accepted output is dropped\n * before it is copied, fanned out or queued, while the bridge's internal publish gate keeps the\n * board's call admission.\n */\nexport function scopeTopics(\n bridge: TopicBridge,\n instance: IPreparedInstance,\n outputs: IOutput[],\n diagnostics: ISimulationDiagnostic[],\n publishObserved: () => boolean,\n): TopicBridge {\n const prefix = `${encodeURIComponent(instance.symbol)}/`;\n const gate = publishGate(bridge);\n let scopedListeners = 0;\n const unobserved = (): boolean =>\n scopedListeners === 0 && gate.hostListeners() === 0 && !publishObserved();\n return {\n onDidReceive: ((listener, thisArgs, disposables) => {\n const subscription = bridge.onDidReceive(\n (message) => {\n if (!message.topic.startsWith(prefix)) return;\n const port = message.topic.slice(prefix.length);\n if (instance.device.topics.get(port)?.direction !== 'input') return;\n return listener.call(thisArgs, { topic: port, payload: copyPayload(message.payload) });\n },\n undefined,\n undefined,\n );\n scopedListeners++;\n let active = true;\n const disposable = {\n dispose: () => {\n if (active) {\n active = false;\n scopedListeners--;\n subscription.dispose();\n }\n },\n };\n disposables?.push(disposable);\n return disposable;\n }) as Event<TopicMessage>,\n publish(port, payload): void {\n const topic = instance.device.topics.get(port);\n if (topic?.direction !== 'output' || !payloadMatches(topic.type, payload)) {\n diagnostics.push({\n code: 'device/output-failed',\n symbol: instance.symbol,\n port,\n message: `Unknown output or invalid payload for ${instance.symbol}.${port}`,\n simTime: timePs(0),\n });\n return;\n }\n // Publish would copy first and only then enforce the phase, disposed and faulted guards, so\n // the skipped path keeps the guard on its own instead of losing the error.\n if (unobserved()) {\n gate.assertPublishAllowed();\n return;\n }\n const snapshot = copyPayload(payload);\n // Publish first so Board still enforces its phase and disposed/faulted guards.\n bridge.publish(scopedTopic(instance.symbol, port), snapshot);\n outputs.push({ symbol: instance.symbol, port, payload: snapshot, delivery: topic.delivery });\n },\n };\n}\n\nfunction scopedTopic(symbol: string, port: string): string {\n return `${encodeURIComponent(symbol)}/${port}`;\n}\n\nfunction importBlobModule(code: string): Promise<unknown> {\n if (\n typeof URL === 'undefined' ||\n typeof URL.createObjectURL !== 'function' ||\n typeof Blob === 'undefined'\n ) {\n return Promise.reject(new Error('Inject a module importer outside a browser worker'));\n }\n const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));\n return import(/* @vite-ignore */ url).finally(() => URL.revokeObjectURL(url));\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport { copyBytePayload } from './payload';\nimport {\n simulationRuntimeEventTransfer,\n simulationRuntimeService,\n simulationRuntimeTopicService,\n} from './rpc';\nimport type { ISimulationRuntimeRpc, ISimulationRuntimeTopicRpc } from './rpc';\nimport { createSimulationRuntime } from './runtime';\nimport type {\n ISimulationMessage,\n ISimulationRuntime,\n SimulationModuleImporter,\n ISimulationRuntimeOptions,\n} from './types';\n\n/** Startup options of the in-process runtime guest; none of them travel over RPC. */\nexport interface ISimulationRuntimeGuestOptions {\n readonly importer?: SimulationModuleImporter;\n /** Extra ports the worker received; the first one is the direct topic channel. */\n readonly ports?: readonly MessagePort[];\n}\n\n/** Running runtime guest: where the typed service lives and which ports it owns. */\nexport interface ISimulationRuntimeGuest {\n readonly rpc: RpcEndpoint;\n readonly ports: readonly MessagePort[];\n readonly runtime: ISimulationRuntime;\n dispose(): Promise<void>;\n}\n\n/** Registrations that put one runtime on an existing endpoint and its topic port. */\nexport interface IRegisteredSimulationRuntime {\n dispose(): void;\n}\n\n/**\n * Registers the prepared simulation runtime as `simulation-runtime` on an existing endpoint.\n *\n * The primary endpoint gets the full control surface and diagnostics; `topicRpc`, when present,\n * gets `deliver` plus `onDidPublish` only, so a widget guest talks to the simulation directly.\n * Both registrations share the one runtime instance and are released together. The caller owns\n * `rpc` and `topicRpc`; this function only owns the registrations it creates.\n */\nexport function registerSimulationRuntimeServices(\n rpc: RpcEndpoint,\n runtime: ISimulationRuntime,\n topicRpc?: RpcEndpoint,\n): IRegisteredSimulationRuntime {\n const service = createRuntimeService(runtime);\n const serviceRegistration = rpc.register(simulationRuntimeService, service, {\n transfer: simulationRuntimeEventTransfer,\n });\n const topicRegistration =\n topicRpc === undefined\n ? undefined\n : topicRpc.register(\n simulationRuntimeTopicService,\n {\n deliver: service.deliver,\n onDidPublish: service.onDidPublish,\n // The empty reply follows earlier callbacks on this port, providing a FIFO barrier.\n async flushPublishes() {},\n },\n { transfer: simulationRuntimeEventTransfer },\n );\n\n let disposed = false;\n return {\n dispose(): void {\n if (disposed) return;\n disposed = true;\n try {\n topicRegistration?.dispose();\n } finally {\n serviceRegistration.dispose();\n }\n },\n };\n}\n\n/**\n * Starts the prepared simulation runtime on one sandbox RPC port.\n *\n * A worker script calls this after taking `event.ports[0]`; extra ports stay in order. The returned\n * node owns the runtime and disposes it with the registrations.\n */\nexport function startSimulationRuntimeGuest(\n port: MessagePort,\n options: ISimulationRuntimeGuestOptions = {},\n): ISimulationRuntimeGuest {\n const rpc = createRpc(port);\n const runtime = createSimulationRuntime(runtimeOptions(options));\n const ports = options.ports ?? [];\n const topicPort = ports[0];\n const topicRpc = topicPort === undefined ? undefined : createRpc(topicPort);\n const registered = registerSimulationRuntimeServices(rpc, runtime, topicRpc);\n let disposed = false;\n return {\n rpc,\n ports,\n runtime,\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n try {\n registered.dispose();\n await runtime.dispose();\n } finally {\n topicRpc?.dispose();\n rpc.dispose();\n port.close();\n for (const extra of ports) extra.close();\n }\n },\n };\n}\n\nfunction runtimeOptions(options: ISimulationRuntimeGuestOptions): ISimulationRuntimeOptions {\n return {\n ...(options.importer === undefined ? {} : { importer: options.importer }),\n };\n}\n\nfunction createRuntimeService(runtime: ISimulationRuntime): ISimulationRuntimeRpc {\n const onDidPublish: ISimulationRuntimeTopicRpc['onDidPublish'] = (listener) => {\n const subscription = runtime.onDidPublish((message) => listener(copyMessage(message)));\n return () => subscription.dispose();\n };\n return {\n load: (input) => runtime.load(input),\n reset: () => runtime.reset(),\n tick: (dt) => runtime.tick(dt),\n deliver: (message) => runtime.deliver(message),\n onDidPublish,\n onDidDiagnostic(listener) {\n const subscription = runtime.onDidDiagnostic(listener);\n return () => subscription.dispose();\n },\n dispose: () => runtime.dispose(),\n };\n}\n\nfunction copyMessage(message: ISimulationMessage): ISimulationMessage {\n const payload = copyBytePayload(message.payload);\n return payload === message.payload ? message : { ...message, payload };\n}\n"],"mappings":";;;;;;;;;;AAsCA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,MAA2B,QAAgB,WAAoC,CAAC,GAAG;EAC7F,MAAM,MAAM;EACZ,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,aAAa,SAAS;EAC3B,KAAK,WAAW,SAAS;EACzB,KAAK,UAAU,SAAS;EACxB,KAAK,WAAW,SAAS;EACzB,KAAK,YAAY,SAAS;CAC5B;AACF;;AAGA,SAAgB,mBACd,YACA,WAAoC,CAAC,GAC/B;CACN,IAAI,CAAC,OAAO,SAAS,UAAU,KAAK,aAAa,QAAS,aAAa,KACrE,MAAM,IAAI,gBACR,gCACA,8DACA,QACF;AAEJ;;;;;;;AAgJA,IAAM,0BAA0B;;AAEhC,IAAM,wBAAwB;AAC9B,IAAM,wBAAwB;;AAG9B,SAAS,UAAU,MAAc,OAAgC;CAC/D,IAAI,OAAO,KAAK,KAAK,aAAa,MAAM,QAAU;CAClD,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SACxC,OAAO,KAAK,KAAK,OAAO,MAAM,MAAM,CAAE,IAAI,QAAU;CAEtD,OAAO,KAAK,KAAK,OAAO,MAAM,QAAQ,QAAU,MAAM;AACxD;AAEA,SAAS,aAAa,UAAoC;CACxD,IAAI,OAAO;CACX,MAAM,4BAAY,IAAI,IAAe;CACrC,KAAK,MAAM,SAAS,SAAS,QAAQ;EACnC,QAAQ,MAAM,UAAU,MAAM,SAAS,IAAI,MAAM,UAAU,MAAM;EACjE,MAAM,WAAW,MAAM,UAAU;EACjC,IAAI,aAAa,KAAA,KAAa,CAAC,UAAU,IAAI,QAAQ,GAAG;GAC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Q;GACrD,aAAa,aAAa,QAAQ;EACpC;EACA,eAAe,QAAQ,QAAQ;CACjC;AACF;AAEA,SAAS,YAAY,SAAiD;CACpE,MAAM,UAAU,gBAAgB,QAAQ,OAAO;CAC/C,OAAO,YAAY,QAAQ,UAAU,UAAU;EAAE,GAAG;EAAS;CAAQ;AACvE"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/electrical.ts","../src/queue.ts","../src/observations.ts","../src/runtime/execution.ts","../src/types.ts","../src/runtime/errors.ts","../src/runtime/instance.ts","../src/runtime/publish-gate.ts","../src/polling.ts","../src/runtime/jit.ts","../src/runtime.ts","../src/simulation-runtime/errors.ts","../src/simulation-runtime/prepare.ts","../src/simulation-runtime/runtime.ts","../src/simulation-runtime/guest.ts"],"sourcesContent":["export type PinSample = {\n voltage: number | null;\n level: 'low' | 'high' | 'unknown';\n status: 'valid' | 'floating';\n};\n\nexport interface ElectricalPin {\n readonly id: string;\n readonly instance: string;\n readonly name: string;\n readonly low?: number;\n readonly high?: number;\n intent: readonly ResistorBranch[];\n sample: PinSample;\n}\n\nexport interface ResistorBranch {\n readonly to: ElectricalPin;\n readonly resistance: number;\n}\n\nexport interface NetInput {\n readonly id: string;\n readonly pins: readonly ElectricalPin[];\n readonly voltage?: number;\n}\n\nexport type ElectricalErrorCode =\n 'INVALID_ELECTRICAL_PARAMETER' | 'CONFLICTING_REFERENCE' | 'ELECTRICAL_SOLVE_FAILED';\n\nexport interface ElectricalErrorLocation {\n readonly instanceId?: string;\n readonly resource?: string;\n readonly network?: string;\n readonly networks?: readonly string[];\n readonly component?: readonly string[];\n}\n\nexport class ElectricalError extends Error {\n readonly code: ElectricalErrorCode;\n readonly instanceId: string | undefined;\n readonly resource: string | undefined;\n readonly network: string | undefined;\n readonly networks: readonly string[] | undefined;\n readonly component: readonly string[] | undefined;\n readonly reason: string;\n\n constructor(code: ElectricalErrorCode, reason: string, location: ElectricalErrorLocation = {}) {\n super(reason);\n this.name = 'ElectricalError';\n this.code = code;\n this.reason = reason;\n this.instanceId = location.instanceId;\n this.resource = location.resource;\n this.network = location.network;\n this.networks = location.networks;\n this.component = location.component;\n }\n}\n\n/** Invoke at resistor construction, including branches never assigned to an intent. */\nexport function validateResistance(\n resistance: number,\n location: ElectricalErrorLocation = {},\n): void {\n if (!Number.isFinite(resistance) || resistance < 0.001 || resistance > 1_000_000_000) {\n throw new ElectricalError(\n 'INVALID_ELECTRICAL_PARAMETER',\n 'Resistance must be finite and in [0.001, 1000000000] ohms.',\n location,\n );\n }\n}\n\nexport interface ElectricalStats {\n /** Successful, atomically published solves, including the initial baseline. */\n readonly solves: number;\n readonly components: number;\n readonly floatingComponents: number;\n readonly factorizations: number;\n readonly factorizationReuses: number;\n /** Block results served from a cache entry, including one retained across a rebuild. */\n readonly cacheHits: number;\n /** Distinct `(pin, target, resistance)` leaf shapes admitted for reuse. */\n readonly leafPlans: number;\n /** Solves served by replaying an admitted leaf plan instead of rebuilding edges. */\n readonly leafPropagations: number;\n /** Whole-graph rebuilds (`prepareTopology`); a bucket hit restores instead. */\n readonly topologyPrepares: number;\n}\n\nexport interface ElectricalNetwork {\n /**\n * The caller establishes the initial observation baseline after the first solve.\n * Omit changedPins to detect intent identity changes automatically. When supplied,\n * it must include every pin assigned since the last successful solve; intents are immutable.\n * The first solve always reads all pins, regardless of this hint.\n */\n solve(changedPins?: Iterable<ElectricalPin>): readonly ElectricalPin[];\n /**\n * Slot-addressed form of :func:`solve` for callers that already know board pin slots.\n * A number denotes a complete, single-slot dirty batch.\n * Returns a fresh ascending array of the changed slots.\n */\n solveSlots(changedSlots?: number | Iterable<number>): readonly number[];\n /** One complete single-slot dirty batch; same contract as `solveSlots(slot)`. */\n solveSlot(slot: number): readonly number[];\n /**\n * Board-facing single-slot entry: solves the batch and hands each changed slot to\n * `publish` in visit order, so no result array is materialised. The sink is the board's\n * slot bitmap, which ignores the order; callers that need an ascending array use\n * `solveSlot`.\n */\n solveSlotInto(slot: number, publish?: (slot: number) => void): void;\n /**\n * Board-facing batch entry for a complete multi-slot dirty batch. `slots[0, count)` must\n * hold board pin slots; repetitions are ignored. Same atomicity as `solveSlots`, which it\n * shares every guard with, and the same order-free publication as `solveSlotInto`.\n */\n solveSlotBatchInto(\n slots: ArrayLike<number>,\n count: number,\n publish?: (slot: number) => void,\n ): void;\n readonly stats: ElectricalStats;\n}\n\ninterface Node {\n readonly pins: readonly ElectricalPin[];\n readonly networks: readonly string[];\n reference: number | undefined;\n}\n\n/**\n * A pin that keeps exactly one branch onto a node with a fixed potential. A node with one\n * incident branch carries no current by KCL, so its voltage equals the target's reference\n * voltage whatever else the target's component contains. Replaying an admitted shape\n * therefore needs no edge rebuild, no partition check and no matrix work.\n */\ninterface LeafPropagation {\n intent: readonly ResistorBranch[];\n readonly targetPin: ElectricalPin;\n readonly resistance: number;\n readonly target: number;\n readonly edges: readonly Edge[];\n readonly edgeHash: number;\n /** Node of the switching pin and the sample every pin on it takes for this target. */\n readonly node: number;\n readonly voltage: number;\n readonly slots: readonly number[];\n readonly pins: readonly ElectricalPin[];\n readonly samples: readonly PinSample[];\n}\n\ninterface Edge {\n readonly pin: number;\n readonly index: number;\n readonly from: number;\n readonly to: number;\n readonly resistance: number;\n readonly conductance: number;\n}\n\ninterface Component {\n readonly nodes: number[];\n readonly edges: Edge[];\n readonly physical?: Component;\n}\n\ninterface Factorization {\n readonly matrix: Float64Array;\n readonly anchors: Float64Array;\n readonly pivots: Float64Array;\n readonly weights: Float64Array;\n}\n\ninterface CachedComponent {\n /** Node layout the entry was solved for; equal slots mean the same equation order. */\n readonly nodes: readonly number[];\n /** Fixed potential per layout slot; `undefined` marks that slot's node as unknown. */\n readonly references: readonly (number | undefined)[];\n readonly edges: readonly Edge[];\n readonly voltages: readonly (number | null)[];\n readonly factorization: Factorization | undefined;\n}\n\ninterface PreparedBlock {\n readonly component: Component;\n readonly key: string;\n}\n\ninterface PreparedTopology {\n readonly blocks: PreparedBlock[];\n /** Stable pin/branch slots allow equivalent older Edge objects to be shared. */\n readonly edgeBlocks: readonly (readonly (number | undefined)[] | undefined)[];\n readonly components: number;\n readonly floatingComponents: number;\n}\n\n/** Dirty pin edges indexed by slot; `undefined` means the pin kept its committed edges. */\ntype PinUpdates = readonly (readonly Edge[] | undefined)[];\n\ninterface TopologySnapshot {\n readonly id: number;\n readonly cost: number;\n readonly topology: PreparedTopology;\n /** Per-pin endpoint hashes the graph was built from; confirms a bucket hit exactly. */\n readonly hashes: Uint32Array;\n}\n\n/**\n * Descriptors and admitted graphs share these buckets. The budget covers a whole-board\n * working set: a 288-pin board steps through roughly 1.2k distinct shapes in 300 ms, so\n * the former limit of eight discarded every descriptor before its second observation could\n * ever admit a graph.\n */\nconst topologyTransitionLimit = 4096;\n/** Compiled reference programs cost far more per entry than a graph descriptor. */\nconst referenceProgramLimit = 8;\nconst topologySnapshotLimit = 65_536;\n\n/** FNV-1a over the pin slot and its ordered endpoints: the key without the 288 strings. */\nfunction hashEdges(slot: number, edges: readonly Edge[]): number {\n let hash = Math.imul(0x811c9dc5 ^ slot, 0x01000193);\n for (let index = 0; index < edges.length; index++) {\n hash = Math.imul(hash ^ edges[index]!.to, 0x01000193);\n }\n return Math.imul(hash ^ edges.length, 0x01000193) >>> 0;\n}\n\nfunction topologyCost(topology: PreparedTopology): number {\n let cost = 0;\n const physicals = new Set<Component>();\n for (const block of topology.blocks) {\n cost += block.component.nodes.length + 2 * block.component.edges.length;\n const physical = block.component.physical;\n if (physical !== undefined && !physicals.has(physical)) {\n physicals.add(physical);\n cost += physical.nodes.length + physical.edges.length;\n }\n if (cost > topologySnapshotLimit) break;\n }\n return cost;\n}\n\nfunction rebindBlock(\n block: PreparedBlock,\n pinEdges: readonly (readonly Edge[])[],\n updates: PinUpdates,\n): PreparedBlock {\n let edges: Edge[] | undefined;\n for (let index = 0; index < block.component.edges.length; index++) {\n const edge = block.component.edges[index]!;\n const next = (updates[edge.pin] ?? pinEdges[edge.pin]!)[edge.index]!;\n if (edge.from === next.from && edge.to === next.to && edge.resistance === next.resistance)\n continue;\n edges ??= block.component.edges.slice();\n edges[index] = next;\n }\n if (edges === undefined) return block;\n return { ...block, component: { ...block.component, edges } };\n}\n\n/**\n * Every block edge is re-read from the committed pin edges. A bucket key records\n * connectivity only, so a resistance-only change keeps its key and still has to be\n * repaired in blocks that no pin of this solve touches.\n */\nfunction restoreTopology(\n topology: PreparedTopology,\n pinEdges: readonly (readonly Edge[])[],\n updates: PinUpdates,\n): PreparedTopology {\n let blocks: PreparedBlock[] | undefined;\n for (let index = 0; index < topology.blocks.length; index++) {\n const previous = topology.blocks[index]!;\n const block = rebindBlock(previous, pinEdges, updates);\n if (block === previous) continue;\n blocks ??= topology.blocks.slice();\n blocks[index] = block;\n }\n return blocks === undefined ? topology : { ...topology, blocks };\n}\n\nfunction prepareBlock(component: Component): PreparedBlock {\n return { component, key: component.nodes.join(',') };\n}\n\nfunction prepareTopology(\n nodes: readonly Node[],\n pinEdges: readonly (readonly Edge[])[],\n): PreparedTopology {\n const topology = new DisjointSet(nodes.length);\n for (const edges of pinEdges) {\n for (const edge of edges) topology.join(edge.from, edge.to);\n }\n const groups = new Map<number, Component>();\n for (let node = 0; node < nodes.length; node++) {\n const root = topology.find(node);\n let group = groups.get(root);\n if (group === undefined) {\n group = { nodes: [], edges: [] };\n groups.set(root, group);\n }\n group.nodes.push(node);\n }\n for (const edges of pinEdges) {\n for (const edge of edges) groups.get(topology.find(edge.from))!.edges.push(edge);\n }\n let floatingComponents = 0;\n const blocks: PreparedBlock[] = [];\n const edgeBlocks: (number | undefined)[][] = [];\n for (const component of groups.values()) {\n let floating = true;\n for (const node of component.nodes) {\n if (nodes[node]!.reference !== undefined) {\n floating = false;\n break;\n }\n }\n if (floating) floatingComponents++;\n for (const block of solveBlocks(component, nodes)) {\n const index = blocks.length;\n blocks.push(prepareBlock(block));\n for (const edge of block.edges) (edgeBlocks[edge.pin] ??= [])[edge.index] = index;\n }\n }\n return {\n blocks,\n edgeBlocks,\n components: groups.size,\n floatingComponents,\n };\n}\n\nconst cleanZero = (value: number): number => (value === 0 ? 0 : value);\n\nfunction pinLocation(pin: ElectricalPin): ElectricalErrorLocation {\n return { instanceId: pin.instance, resource: pin.name };\n}\n\nclass DisjointSet {\n private readonly parents: number[];\n\n constructor(count: number) {\n this.parents = new Array<number>(count);\n for (let index = 0; index < count; index++) this.parents[index] = index;\n }\n\n find(index: number): number {\n let root = index;\n while (this.parents[root] !== root) root = this.parents[root]!;\n while (index !== root) {\n const next = this.parents[index]!;\n this.parents[index] = root;\n index = next;\n }\n return root;\n }\n\n join(first: number, second: number): void {\n const a = this.find(first);\n const b = this.find(second);\n if (a !== b) this.parents[Math.max(a, b)] = Math.min(a, b);\n }\n}\n\nfunction solveBlocks(component: Component, nodes: readonly Node[]): Component[] {\n let unknownCount = 0;\n let reference: number | undefined;\n let mixedReferences = false;\n for (const node of component.nodes) {\n const potential = nodes[node]!.reference;\n if (potential === undefined) unknownCount++;\n else if (reference === undefined) reference = potential;\n else if (potential !== reference) mixedReferences = true;\n }\n if (unknownCount < 2 || !mixedReferences) return [component];\n const slots = new Map<number, number>();\n for (const node of component.nodes) {\n if (nodes[node]!.reference === undefined) slots.set(node, slots.size);\n }\n const topology = new DisjointSet(unknownCount);\n let coupled = false;\n for (const edge of component.edges) {\n const from = slots.get(edge.from);\n const to = slots.get(edge.to);\n if (from !== undefined && to !== undefined) {\n topology.join(from, to);\n coupled = true;\n }\n }\n // Tiny independent systems cost less as one matrix than as individual blocks.\n if (!coupled && unknownCount <= 32) return [component];\n const groups = new Array<Component | undefined>(unknownCount);\n const blocks: Component[] = [];\n for (let index = 0; index < unknownCount; index++) {\n const root = topology.find(index);\n let group = groups[root];\n if (group === undefined) {\n group = { nodes: [], edges: [], physical: component };\n blocks.push(group);\n }\n // Union roots are minimum slots, so their groups are initialized first.\n groups[index] = group;\n }\n if (blocks.length === 1) return [component];\n const boundaries = new Map<number, Component[]>();\n // Fixed potentials are boundary values, not couplings between unknowns.\n for (const edge of component.edges) {\n const from = slots.get(edge.from);\n const to = slots.get(edge.to);\n const unknownSlot = from ?? to;\n if (unknownSlot === undefined) continue;\n const group = groups[unknownSlot]!;\n group.edges.push(edge);\n const boundary = from === undefined ? edge.from : to === undefined ? edge.to : undefined;\n if (boundary === undefined) continue;\n let adjacent = boundaries.get(boundary);\n if (adjacent === undefined) {\n adjacent = [];\n boundaries.set(boundary, adjacent);\n }\n adjacent.push(group);\n }\n // Physical nodes are already sorted; append each boundary once per block.\n for (const node of component.nodes) {\n const slot = slots.get(node);\n if (slot !== undefined) groups[slot]!.nodes.push(node);\n else {\n const adjacent = boundaries.get(node);\n if (adjacent === undefined) continue;\n for (const group of adjacent) {\n if (group.nodes[group.nodes.length - 1] !== node) group.nodes.push(node);\n }\n }\n }\n return blocks;\n}\n\n/** Compensated summation also preserves small positive grounding contributions. */\nfunction sum(values: Iterable<number>): number {\n let total = 0;\n let correction = 0;\n for (const value of values) {\n const next = total + value;\n correction += Math.abs(total) >= Math.abs(value) ? total - next + value : value - next + total;\n total = next;\n }\n return total + correction;\n}\n\nfunction arraysEqual(first: Float64Array, second: Float64Array): boolean {\n if (first === second) return true;\n if (first.length !== second.length) return false;\n for (let index = 0; index < first.length; index++) {\n if (first[index] !== second[index]) return false;\n }\n return true;\n}\n\nfunction sameConfiguration(\n previous: CachedComponent,\n component: Component,\n nodes: readonly Node[],\n): boolean {\n const layout = component.nodes;\n if (previous.nodes.length !== layout.length || previous.edges.length !== component.edges.length)\n return false;\n for (let index = 0; index < layout.length; index++) {\n const node = layout[index]!;\n if (previous.nodes[index] !== node) return false;\n // A cached voltage belongs to one fixed-potential assignment, and the unknown set is\n // exactly the subset without a reference. Both are revalidated instead of assumed.\n if (!Object.is(previous.references[index], nodes[node]!.reference)) return false;\n }\n for (let index = 0; index < previous.edges.length; index++) {\n const edge = previous.edges[index]!;\n const other = component.edges[index]!;\n if (edge.from !== other.from || edge.to !== other.to || edge.resistance !== other.resistance)\n return false;\n }\n return true;\n}\n\nfunction factorize(\n matrix: Float64Array,\n anchors: Float64Array,\n fail: (reason: string) => never,\n): Factorization {\n const count = anchors.length;\n if (matrix.length === 0) {\n for (const pivot of anchors) {\n if (!(pivot > 0) || !Number.isFinite(pivot)) fail('Invalid LDL pivot.');\n }\n return { matrix, anchors, pivots: anchors, weights: new Float64Array(0) };\n }\n const work = matrix.slice();\n const grounding = anchors.slice();\n const pivots = new Float64Array(count);\n const weights = new Float64Array(count * count);\n for (let row = 0; row < count; row++) {\n const offset = row * count;\n const terms = [grounding[row]!];\n for (let column = row + 1; column < count; column++) terms.push(work[offset + column]!);\n const pivot = sum(terms);\n if (!(pivot > 0) || !Number.isFinite(pivot)) fail('Invalid LDL pivot.');\n pivots[row] = pivot;\n for (let column = row + 1; column < count; column++) {\n const conductance = work[offset + column]!;\n if (conductance === 0) continue;\n const weight = conductance / pivot;\n if (!(weight > 0) || !Number.isFinite(weight)) fail('Unrepresentable LDL coefficient.');\n weights[offset + column] = weight;\n }\n // Positive star-mesh Schur updates avoid subtracting almost equal diagonals.\n // The retained grounding term keeps even very weak reference paths intact.\n for (let first = row + 1; first < count; first++) {\n const conductance = work[offset + first]!;\n if (conductance === 0) continue;\n const ground = conductance * (grounding[row]! / pivot);\n if (grounding[row]! > 0 && !(ground > 0)) fail('Reference coefficient underflow.');\n grounding[first] = grounding[first]! + ground;\n for (let second = first + 1; second < count; second++) {\n const weight = weights[offset + second]!;\n if (weight === 0) continue;\n const fill = conductance * weight;\n if (!(fill > 0)) fail('Schur coefficient underflow.');\n const slot = first * count + second;\n work[slot] = work[slot]! + fill;\n }\n }\n }\n return { matrix, anchors, pivots, weights };\n}\n\nfunction substitute(\n factorization: Factorization,\n right: Float64Array,\n fail: (reason: string) => never,\n): Float64Array {\n const { weights, pivots } = factorization;\n const count = right.length;\n const solution = new Float64Array(count);\n if (weights.length === 0) {\n for (let row = 0; row < count; row++) {\n solution[row] = right[row]! / pivots[row]!;\n if (!Number.isFinite(solution[row])) fail('Non-finite backward substitution.');\n }\n } else {\n const forward = new Float64Array(count);\n for (let row = 0; row < count; row++) {\n const terms = [right[row]!];\n for (let column = 0; column < row; column++) {\n terms.push(weights[column * count + row]! * forward[column]!);\n }\n forward[row] = sum(terms);\n if (!Number.isFinite(forward[row])) fail('Non-finite forward substitution.');\n }\n for (let row = count - 1; row >= 0; row--) {\n const terms = [forward[row]! / pivots[row]!];\n for (let column = row + 1; column < count; column++) {\n terms.push(weights[row * count + column]! * solution[column]!);\n }\n solution[row] = sum(terms);\n if (!Number.isFinite(solution[row])) fail('Non-finite backward substitution.');\n }\n }\n return solution;\n}\n\ninterface ReferenceProgram {\n matches(edges: readonly Edge[], unknown: readonly number[]): boolean;\n assemble(\n edges: readonly Edge[],\n conductanceScale: number,\n voltageScale: number,\n ): { anchors: Float64Array; right: Float64Array };\n}\n\nfunction sumPair(first: number, second: number): number {\n first = 0 + first;\n const total = first + second;\n const correction =\n Math.abs(first) >= Math.abs(second) ? first - total + second : second - total + first;\n return total + correction;\n}\n\nfunction compileReferenceProgram(\n unknown: readonly number[],\n edges: readonly Edge[],\n slots: ReadonlyMap<number, number>,\n nodes: readonly Node[],\n): ReferenceProgram | undefined {\n if (unknown.length > 32 || edges.length > 128) return undefined;\n const rows: number[][] = Array.from({ length: unknown.length }, () => []);\n const guards = [`unknown.length === ${unknown.length}`, `edges.length === ${edges.length}`];\n const references: string[] = [];\n for (let index = 0; index < edges.length; index++) {\n const edge = edges[index]!;\n const from = slots.get(edge.from);\n const to = slots.get(edge.to);\n if (from !== undefined && to !== undefined) return undefined;\n if (from === undefined && to === undefined) {\n guards.push(\n `nodes[edges[${index}].from].reference !== undefined`,\n `nodes[edges[${index}].to].reference !== undefined`,\n );\n continue;\n }\n const row = from ?? to!;\n if (rows[row]!.length === 2) return undefined;\n rows[row]!.push(index);\n const fixed = from === undefined ? 'from' : 'to';\n const variable = from === undefined ? 'to' : 'from';\n references[index] = `nodes[edges[${index}].${fixed}].reference`;\n guards.push(\n `edges[${index}].${variable} === unknown[${row}]`,\n `${references[index]} !== undefined`,\n );\n }\n if (rows.some((row) => row.length === 0)) return undefined;\n const assembly: string[] = [];\n for (let row = 0; row < rows.length; row++) {\n const indices = rows[row]!;\n const reduce = (terms: readonly string[]): string =>\n terms.length === 1 ? `(0 + ${terms[0]})` : `pair(${terms.join(',')})`;\n for (const index of indices)\n assembly.push(`const g${index} = edges[${index}].conductance / gScale;`);\n assembly.push(\n `anchors[${row}] = ${reduce(indices.map((index) => `g${index}`))};`,\n `right[${row}] = ${reduce(indices.map((index) => `g${index} * (${references[index]} / vScale)`))};`,\n );\n }\n // Bind closed reference rows while retaining their original compensated summation order.\n const factory = new Function(\n 'pair',\n 'nodes',\n `\"use strict\"; return {\n matches(edges, unknown) { return ${guards.join(' && ')}; },\n assemble(edges, gScale, vScale) {\n const anchors = new Float64Array(${unknown.length});\n const right = new Float64Array(${unknown.length});\n ${assembly.join('\\n')}\n return { anchors, right };\n }\n };`,\n ) as (pair: typeof sumPair, nodes: readonly Node[]) => ReferenceProgram;\n return factory(sumPair, nodes);\n}\n\nexport function createElectricalNetwork(\n inputPins: readonly ElectricalPin[],\n inputNets: readonly NetInput[],\n): ElectricalNetwork {\n const pins = [...inputPins];\n const pinSlots = new Map(pins.map((pin, index) => [pin, index]));\n const assembly = new DisjointSet(pins.length);\n const nets = inputNets.map((net) => ({ id: net.id, pins: [...net.pins], voltage: net.voltage }));\n for (const pin of pins) {\n if (\n (pin.low === undefined) !== (pin.high === undefined) ||\n (pin.low !== undefined &&\n (!Number.isFinite(pin.low) || !Number.isFinite(pin.high) || !(pin.low < pin.high!)))\n ) {\n throw new ElectricalError(\n 'INVALID_ELECTRICAL_PARAMETER',\n 'Pin thresholds must both be omitted or finite with low < high.',\n pinLocation(pin),\n );\n }\n }\n const requirePin = (pin: ElectricalPin, network?: string): number => {\n const slot = pinSlots.get(pin);\n if (slot === undefined) {\n throw new ElectricalError(\n 'INVALID_ELECTRICAL_PARAMETER',\n 'Electrical endpoint is not part of this board.',\n network === undefined ? pinLocation(pin) : { network },\n );\n }\n return slot;\n };\n const requireEndpoint = (pin: ElectricalPin, owner: ElectricalPin): number => {\n const slot = pinSlots.get(pin);\n if (slot === undefined)\n throw new ElectricalError(\n 'INVALID_ELECTRICAL_PARAMETER',\n 'Electrical endpoint is not part of this board.',\n pinLocation(owner),\n );\n return slot;\n };\n const validResistance = (resistance: number): boolean =>\n Number.isFinite(resistance) && resistance >= 0.001 && resistance <= 1_000_000_000;\n for (const net of nets) {\n if (net.voltage !== undefined && !Number.isFinite(net.voltage)) {\n throw new ElectricalError('INVALID_ELECTRICAL_PARAMETER', 'Reference must be finite.', {\n network: net.id,\n });\n }\n let first: number | undefined;\n for (const pin of net.pins) {\n const slot = requirePin(pin, net.id);\n if (first === undefined) first = slot;\n else assembly.join(first, slot);\n }\n }\n const nodes: Node[] = [];\n /** Pin slots per node in ascending board order, so samples publish without lookups. */\n const nodeSlots: number[][] = [];\n const rootNodes = new Map<number, number>();\n const pinNodes = pins.map((pin, index) => {\n const root = assembly.find(index);\n let node = rootNodes.get(root);\n if (node === undefined) {\n node = nodes.length;\n rootNodes.set(root, node);\n nodes.push({ pins: [], networks: [], reference: undefined });\n nodeSlots.push([]);\n }\n (nodes[node]!.pins as ElectricalPin[]).push(pin);\n nodeSlots[node]!.push(index);\n return node;\n });\n for (const net of nets) {\n if (net.pins.length === 0) continue;\n const node = nodes[pinNodes[requirePin(net.pins[0]!, net.id)]!]!;\n (node.networks as string[]).push(net.id);\n if (net.voltage === undefined) continue;\n const reference = cleanZero(net.voltage);\n if (node.reference !== undefined && node.reference !== reference) {\n throw new ElectricalError('CONFLICTING_REFERENCE', 'Conflicting fixed potentials on a net.', {\n network: net.id,\n networks: Object.freeze([...node.networks]),\n });\n }\n node.reference = reference;\n }\n let cache = new Map<string, CachedComponent>();\n const referencePrograms: ReferenceProgram[] = [];\n let prepared: PreparedTopology | undefined;\n let nextTopologyId = 0;\n const transitions = new Map<string, TopologySnapshot | undefined>();\n /**\n * Per-pin endpoint hash. Their exact integer summary is the bucket key, so a repeated\n * shape costs one hash per dirty pin instead of a 288-entry string join.\n */\n const pinHashes = new Uint32Array(pins.length);\n let topologyHash = 0;\n let topologySpread = 0;\n for (let slot = 0; slot < pins.length; slot++) {\n const hash = hashEdges(slot, []);\n pinHashes[slot] = hash;\n topologyHash += hash;\n topologySpread ^= hash;\n }\n const setPinHash = (slot: number, edges: readonly Edge[]): void => {\n const hash = hashEdges(slot, edges);\n const previous = pinHashes[slot]!;\n if (hash === previous) return;\n pinHashes[slot] = hash;\n topologyHash += hash - previous;\n topologySpread ^= previous ^ hash;\n };\n /** Confirms a bucket hit against the exact hashes the stored graph was built from. */\n const lookupTransition = (key: string, updated: PinUpdates): TopologySnapshot | undefined => {\n const candidate = transitions.get(key);\n if (candidate === undefined) return undefined;\n const hashes = candidate.hashes;\n if (hashes.length !== pinHashes.length) return undefined;\n for (let slot = 0; slot < hashes.length; slot++) {\n const edges = updated[slot];\n const hash = edges === undefined ? pinHashes[slot]! : hashEdges(slot, edges);\n if (hashes[slot] !== hash) return undefined;\n }\n return candidate;\n };\n const rememberTransition = (key: string, admitted: TopologySnapshot): void => {\n if (admitted.cost > topologySnapshotLimit) return;\n if (!transitions.has(key)) {\n // A first observation retains only its bucket, never the graph; a repeated\n // observation admits the graph.\n transitions.set(key, undefined);\n } else if (transitions.get(key) !== admitted) transitions.set(key, admitted);\n // Map insertion order is age order, so eviction needs no scan.\n while (transitions.size > topologyTransitionLimit) {\n const oldest = transitions.keys().next().value;\n if (oldest === undefined) break;\n transitions.delete(oldest);\n }\n };\n const publishedVoltages: (number | null | undefined)[] = new Array(nodes.length);\n const intents: (readonly ResistorBranch[] | undefined)[] = new Array(pins.length);\n const pinEdges: (readonly Edge[])[] = Array.from({ length: pins.length }, () => []);\n const unchangedPins: readonly ElectricalPin[] = Object.freeze([]);\n /** Undirected incidence count per node, used to prove a node has no other branches. */\n const nodeDegree = new Int32Array(nodes.length);\n const updatedSlots: number[] = [];\n const updatedIntents: (readonly ResistorBranch[])[] = [];\n const updatedEdges: (readonly Edge[])[] = [];\n /** Dirty edges indexed by slot, so rebinding avoids a Map lookup per block edge. */\n const updatedEdgeLists: (readonly Edge[] | undefined)[] = new Array(pins.length);\n const updatedEdgeSlots: number[] = [];\n const replacedEdges: Edge[] = [];\n const seenSlots = new Int32Array(pins.length);\n let seenStamp = 0;\n /** Only the matrix partition is out of date; component arrays and buckets stay valid. */\n let blocksStale = false;\n const syncDegrees = (previous: readonly Edge[], next: readonly Edge[]): void => {\n for (const edge of previous) {\n if (next.indexOf(edge) === -1) {\n nodeDegree[edge.from] = nodeDegree[edge.from]! - 1;\n nodeDegree[edge.to] = nodeDegree[edge.to]! - 1;\n }\n }\n for (const edge of next) {\n if (previous.indexOf(edge) === -1) {\n nodeDegree[edge.from] = nodeDegree[edge.from]! + 1;\n nodeDegree[edge.to] = nodeDegree[edge.to]! + 1;\n }\n }\n };\n const statistics = {\n solves: 0,\n components: 0,\n floatingComponents: 0,\n factorizations: 0,\n factorizationReuses: 0,\n cacheHits: 0,\n leafPlans: 0,\n leafPropagations: 0,\n topologyPrepares: 0,\n };\n const emptySlots: readonly number[] = Object.freeze([]);\n /** Dirty slots supplied by the caller, deduplicated in place without an iterator per pin. */\n const inputSlots: number[] = [];\n /**\n * Changed pin slots of the last solve, valid in `[0, changedCount)`. The leaf path\n * collects them in visit order and orders them only for the entries that return an\n * array; the board publication sink is a slot bitmap. The array keeps its high-water\n * length so a new batch never pays for clearing it.\n */\n const changedSlots: number[] = [];\n let changedCount = 0;\n /** Admitted leaf shapes per pin slot; a pin normally alternates between two references. */\n const leafPlans: (LeafPropagation[] | undefined)[] = new Array(pins.length);\n /** Last topology check for the single-slot entry, independent of intent identity. */\n const leafEpochs = new Int32Array(pins.length);\n let leafEpoch = 1;\n const leafSlots: number[] = [];\n const leafIntents: (readonly ResistorBranch[])[] = [];\n const leafEdges: (readonly Edge[])[] = [];\n const leafTargets: number[] = [];\n /** Matched admitted shape per batch position, so publishing reuses its bound payload. */\n const leafPayloads: (LeafPropagation | undefined)[] = [];\n /** Shapes proven by the current solve; they are admitted only after it is accepted. */\n const pendingAdmissions: {\n readonly slot: number;\n readonly intent: readonly ResistorBranch[];\n readonly branch: ResistorBranch;\n readonly target: number;\n readonly edges: readonly Edge[];\n }[] = [];\n /** Canonical immutable samples; published samples never change once created. */\n const referenceSamples = new Map<number, Partial<Record<PinSample['level'], PinSample>>>();\n const nextStamp = (): number => {\n if (++seenStamp === 0x7fffffff) {\n seenSlots.fill(0);\n seenStamp = 1;\n }\n return seenStamp;\n };\n const sampleFor = (voltage: number, level: PinSample['level']): PinSample => {\n let entry = referenceSamples.get(voltage);\n if (entry === undefined) {\n if (referenceSamples.size >= 256) referenceSamples.clear();\n entry = {};\n referenceSamples.set(voltage, entry);\n }\n let sample = entry[level];\n if (sample === undefined) {\n sample = Object.freeze({ voltage: cleanZero(voltage), level, status: 'valid' as const });\n entry[level] = sample;\n }\n return sample;\n };\n /**\n * Records `(pin, target, resistance)` once the general path proved the shape: one branch\n * from a leaf node straight onto a fixed reference. Replays are only allowed while the\n * intent still names that branch, the pin still has one incident edge, the pin node is\n * still an unknown leaf and the target node still carries a fixed potential.\n */\n const pinLevel = (pin: ElectricalPin, voltage: number): PinSample['level'] =>\n pin.low === undefined\n ? 'unknown'\n : voltage <= pin.low\n ? 'low'\n : voltage >= pin.high!\n ? 'high'\n : 'unknown';\n /**\n * Bind the publish payload of one admitted shape: the switching pin's node, its pins in\n * board order, and the immutable sample each of them takes on the fixed target voltage.\n * A replay therefore commits precomputed samples instead of re-deriving voltages, levels\n * and canonical samples on every publication.\n */\n const leafPlan = (\n slot: number,\n intent: readonly ResistorBranch[],\n branch: ResistorBranch,\n target: number,\n edges: readonly Edge[],\n ): LeafPropagation => {\n const node = pinNodes[slot]!;\n const nodePins = nodeSlots[node]!;\n const voltage = nodes[target]!.reference!;\n const slots: number[] = [];\n const planPins: ElectricalPin[] = [];\n const samples: PinSample[] = [];\n for (let at = 0; at < nodePins.length; at++) {\n const nodeSlot = nodePins[at]!;\n const pinned = pins[nodeSlot]!;\n slots.push(nodeSlot);\n planPins.push(pinned);\n samples.push(sampleFor(voltage, pinLevel(pinned, voltage)));\n }\n return {\n intent,\n targetPin: branch.to,\n resistance: branch.resistance,\n target,\n edges,\n edgeHash: hashEdges(slot, edges),\n node,\n voltage,\n slots: Object.freeze(slots),\n pins: Object.freeze(planPins),\n samples: Object.freeze(samples),\n };\n };\n const admitLeaf = (\n slot: number,\n intent: readonly ResistorBranch[],\n branch: ResistorBranch,\n target: number,\n edges: readonly Edge[],\n ): void => {\n const plan = leafPlan(slot, intent, branch, target, edges);\n const plans = leafPlans[slot];\n if (plans === undefined) {\n leafPlans[slot] = [plan];\n statistics.leafPlans++;\n return;\n }\n for (const existing of plans)\n if (existing.targetPin === branch.to && existing.resistance === branch.resistance) {\n existing.intent = intent;\n return;\n }\n if (plans.length < 2) plans.push(plan);\n else plans[plans.length - 1] = plan;\n statistics.leafPlans++;\n };\n const flushAdmissions = (): void => {\n for (let index = 0; index < pendingAdmissions.length; index++) {\n const admission = pendingAdmissions[index]!;\n admitLeaf(\n admission.slot,\n admission.intent,\n admission.branch,\n admission.target,\n admission.edges,\n );\n }\n pendingAdmissions.length = 0;\n };\n const matchLeaf = (\n slot: number,\n intent: readonly ResistorBranch[],\n ): LeafPropagation | undefined => {\n if (prepared === undefined) return undefined;\n const plans = leafPlans[slot];\n if (plans === undefined) return undefined;\n const previous = pinEdges[slot]!;\n if (previous.length !== 1 || nodes[previous[0]!.to]!.reference === undefined) return undefined;\n const from = pinNodes[slot]!;\n if (nodeDegree[from] !== 1 || nodes[from]!.reference !== undefined) return undefined;\n const p0 = plans[0]!;\n if (p0.intent === intent) return nodes[p0.target]!.reference === undefined ? undefined : p0;\n if (plans.length > 1) {\n const p1 = plans[1]!;\n if (p1.intent === intent) return nodes[p1.target]!.reference === undefined ? undefined : p1;\n }\n if (intent.length !== 1) return undefined;\n const branch = intent[0]!;\n for (let index = 0; index < plans.length; index++) {\n const plan = plans[index]!;\n if (plan.targetPin !== branch.to || plan.resistance !== branch.resistance) continue;\n if (nodes[plan.target]!.reference === undefined) return undefined;\n plan.intent = intent;\n return plan;\n }\n return undefined;\n };\n /**\n * Appends one changed slot. A whole corrected batch is ordered once, after collecting,\n * so each leaf contributes its pins without paying for an insertion pass per pin.\n */\n const pushChanged = (slot: number): void => {\n changedSlots[changedCount++] = slot;\n };\n /** Restores the ascending board order the public entries promise; callers opt in. */\n const sortChanged = (): void => {\n for (let index = 1; index < changedCount; index++) {\n const slot = changedSlots[index]!;\n let position = index;\n while (position > 0 && changedSlots[position - 1]! > slot) {\n changedSlots[position] = changedSlots[position - 1]!;\n position--;\n }\n changedSlots[position] = slot;\n }\n };\n /** Hands every published slot to the board. The consumer is a slot bitmap. */\n const emitChanged = (publish: (slot: number) => void): void => {\n for (let index = 0; index < changedCount; index++) publish(changedSlots[index]!);\n };\n /** A fresh ascending copy for the public solve entries; the buffer is reused. */\n const copyChanged = (): readonly number[] => {\n if (changedCount === 0) return emptySlots;\n sortChanged();\n const result = new Array<number>(changedCount);\n for (let index = 0; index < changedCount; index++) result[index] = changedSlots[index]!;\n return result;\n };\n const commitLeafEdges = (\n slot: number,\n target: number,\n voltage: number,\n intent: readonly ResistorBranch[],\n edges: readonly Edge[],\n precomputedHash?: number,\n ): void => {\n const previousTarget = pinEdges[slot]![0]!.to;\n if (previousTarget !== target) {\n nodeDegree[previousTarget] = nodeDegree[previousTarget]! - 1;\n nodeDegree[target] = nodeDegree[target]! + 1;\n }\n publishedVoltages[pinNodes[slot]!] = voltage;\n intents[slot] = intent;\n pinEdges[slot] = edges;\n if (precomputedHash !== undefined) {\n const previous = pinHashes[slot]!;\n if (precomputedHash !== previous) {\n pinHashes[slot] = precomputedHash;\n topologyHash += precomputedHash - previous;\n topologySpread ^= previous ^ precomputedHash;\n }\n } else setPinHash(slot, edges);\n };\n const finishLeaf = (): void => {\n // The general solver can rebuild the partition from the committed edges without\n // discarding the admitted graphs or the numerical cache.\n blocksStale = true;\n statistics.solves++;\n statistics.leafPropagations++;\n };\n /**\n * Once the single dirty slot is admitted, the whole batch is known to be valid.\n * The plan visits one node's pins in board order, so no staging or merging is needed.\n */\n const applySingleLeaf = (\n slot: number,\n intent: readonly ResistorBranch[],\n plan: LeafPropagation,\n ): void => {\n const { node, target, voltage } = plan;\n changedCount = 0;\n if (publishedVoltages[node] !== voltage) {\n const planPins = plan.pins;\n const planSamples = plan.samples;\n const planSlots = plan.slots;\n for (let index = 0; index < planPins.length; index++) {\n const pin = planPins[index]!;\n const sample = planSamples[index]!;\n if (pin.sample === sample) continue;\n pin.sample = sample;\n changedSlots[changedCount++] = planSlots[index]!;\n }\n }\n commitLeafEdges(slot, target, voltage, intent, plan.edges, plan.edgeHash);\n finishLeaf();\n };\n /**\n * Publishes the accepted leaf batch. The caller has already matched every dirty slot to\n * an admitted shape (or proven the shapes below through the general solver), so each\n * pin's sample is an independent function of its node's fixed reference: committing them\n * in place is atomic. Slots are collected in visit order and ordered only when a public\n * entry asks for the ascending array.\n */\n const applyLeaf = (count: number): void => {\n changedCount = 0;\n for (let position = 0; position < count; position++) {\n const node = pinNodes[leafSlots[position]!]!;\n const plan = leafPayloads[position];\n if (plan !== undefined) {\n // Admitted shape: the target voltage, every pin on the node and each pin's\n // immutable sample were bound once, so only the current sample identity is checked.\n if (publishedVoltages[node] === plan.voltage) continue;\n const planSlots = plan.slots;\n const planPins = plan.pins;\n const planSamples = plan.samples;\n for (let at = 0; at < planSlots.length; at++) {\n const pinned = planPins[at]!;\n const sample = planSamples[at]!;\n if (pinned.sample === sample) continue;\n pinned.sample = sample;\n pushChanged(planSlots[at]!);\n }\n continue;\n }\n const voltage = nodes[leafTargets[position]!]!.reference!;\n if (publishedVoltages[node] === voltage) continue;\n const slots = nodeSlots[node]!;\n for (let at = 0; at < slots.length; at++) {\n const slot = slots[at]!;\n const pin = pins[slot]!;\n const level: PinSample['level'] =\n pin.low === undefined\n ? 'unknown'\n : voltage <= pin.low\n ? 'low'\n : voltage >= pin.high!\n ? 'high'\n : 'unknown';\n const previous = pin.sample;\n if (previous.voltage === voltage && previous.level === level && previous.status === 'valid')\n continue;\n pin.sample = sampleFor(voltage, level);\n pushChanged(slot);\n }\n }\n for (let position = 0; position < count; position++) {\n const slot = leafSlots[position]!;\n const target = leafTargets[position]!;\n commitLeafEdges(\n slot,\n target,\n nodes[target]!.reference!,\n leafIntents[position]!,\n leafEdges[position]!,\n leafPayloads[position]?.edgeHash,\n );\n }\n finishLeaf();\n };\n\n /** One complete single-slot dirty batch; leaves the publication buffer filled. */\n function solveSingleSlot(slot: number): void {\n const plans = leafPlans[slot];\n if (plans !== undefined) {\n const intent = pins[slot]!.intent;\n if (intent !== intents[slot]) {\n if (leafEpochs[slot] === leafEpoch) {\n const first = plans[0]!;\n const plan = first.intent === intent ? first : plans[1];\n if (plan?.intent === intent) {\n applySingleLeaf(slot, intent, plan);\n return;\n }\n }\n const plan = matchLeaf(slot, intent);\n if (plan !== undefined) {\n leafEpochs[slot] = leafEpoch;\n applySingleLeaf(slot, intent, plan);\n return;\n }\n }\n }\n inputSlots[0] = slot;\n inputSlots.length = 1;\n runSolve(inputSlots);\n }\n\n /**\n * One admitted-shape probe over `slots[0, length)`. A slot whose shape this epoch already\n * proved resolves through the same two-plan pointer comparison as `solveSingleSlot`; only\n * the first switch of a shape pays for `matchLeaf`. Any slot without an admitted shape\n * hands the whole batch to the general solver, which repeats the match.\n */\n function solveBatch(slots: ArrayLike<number>, length: number): void {\n if (prepared !== undefined) {\n const stamp = nextStamp();\n let count = 0;\n let complete = true;\n for (let position = 0; position < length; position++) {\n const slot = slots[position]!;\n if (seenSlots[slot] === stamp) continue;\n seenSlots[slot] = stamp;\n const intent = pins[slot]!.intent;\n if (intent === intents[slot]) continue;\n let plan: LeafPropagation | undefined;\n if (leafEpochs[slot] === leafEpoch) {\n const plans = leafPlans[slot]!;\n const first = plans[0]!;\n const cached = first.intent === intent ? first : plans[1];\n if (cached?.intent === intent) plan = cached;\n }\n if (plan === undefined) {\n plan = matchLeaf(slot, intent);\n if (plan === undefined) {\n complete = false;\n break;\n }\n leafEpochs[slot] = leafEpoch;\n }\n leafSlots[count] = slot;\n leafIntents[count] = intent;\n leafEdges[count] = plan.edges;\n leafTargets[count] = plan.target;\n leafPayloads[count] = plan;\n count++;\n }\n if (complete) {\n if (count === 0) {\n fillInput(slots, length);\n runSolve(inputSlots);\n return;\n }\n applyLeaf(count);\n return;\n }\n }\n fillInput(slots, length);\n runSolve(inputSlots);\n }\n\n /** Board-facing single-slot entry: solves and publishes without an intermediate array. */\n function solveSlotInto(slot: number, publish?: (slot: number) => void): void {\n solveSingleSlot(slot);\n if (publish !== undefined && changedCount !== 0) emitChanged(publish);\n }\n\n /** Board-facing batch entry: solves and publishes without an intermediate array. */\n function solveSlotBatchInto(\n slots: ArrayLike<number>,\n count: number,\n publish?: (slot: number) => void,\n ): void {\n solveBatch(slots, count);\n if (publish !== undefined && changedCount !== 0) emitChanged(publish);\n }\n\n return {\n get stats(): ElectricalStats {\n return Object.freeze({ ...statistics });\n },\n solve(changedPins?: Iterable<ElectricalPin>): readonly ElectricalPin[] {\n runSolve(gatherPins(changedPins));\n if (changedCount === 0) return unchangedPins;\n sortChanged();\n const published: ElectricalPin[] = [];\n for (let position = 0; position < changedCount; position++)\n published.push(pins[changedSlots[position]!]!);\n return Object.freeze(published);\n },\n solveSlot(slot: number): readonly number[] {\n solveSingleSlot(slot);\n return copyChanged();\n },\n solveSlotInto,\n solveSlotBatchInto,\n solveSlots(changedSlotNumbers?: number | Iterable<number>): readonly number[] {\n if (typeof changedSlotNumbers === 'number') {\n solveSingleSlot(changedSlotNumbers);\n return copyChanged();\n }\n if (changedSlotNumbers === undefined) {\n runSolve(undefined);\n return copyChanged();\n }\n // The batch is materialised exactly once into the solver's own input buffer, so a\n // one-shot generator is neither probed twice nor silently truncated: the probe and\n // any fallback both read that owned array.\n inputSlots.length = 0;\n if (\n Array.isArray(changedSlotNumbers) ||\n (ArrayBuffer.isView(changedSlotNumbers) && Symbol.iterator in changedSlotNumbers)\n ) {\n const indexed = changedSlotNumbers as ArrayLike<number>;\n for (let position = 0; position < indexed.length; position++)\n inputSlots.push(indexed[position]!);\n } else for (const slot of changedSlotNumbers) inputSlots.push(slot);\n solveBatch(inputSlots, inputSlots.length);\n return copyChanged();\n },\n };\n\n function gatherPins(changedPins: Iterable<ElectricalPin> | undefined): number[] | undefined {\n if (changedPins === undefined) return undefined;\n inputSlots.length = 0;\n for (const pin of changedPins) inputSlots.push(requirePin(pin));\n return inputSlots;\n }\n /** Places a caller-supplied batch into the solver input buffer without allocating. */\n function fillInput(slots: ArrayLike<number>, length: number): void {\n inputSlots.length = length;\n for (let position = 0; position < length; position++) inputSlots[position] = slots[position]!;\n }\n /**\n * One atomically published solve over `input` (dirty slots) or, when it is omitted, over\n * every pin. The published slots end up in the ascending buffer.\n */\n function runSolve(input: readonly number[] | undefined): void {\n // The general solver may add an edge to a previously admitted leaf or change its\n // driver. An admitted replay only moves an existing leaf's edge between fixed\n // references, leaving all unknown-node degrees and every leaf's eligibility intact.\n if (++leafEpoch === 0x7fffffff) {\n leafEpochs.fill(0);\n leafEpoch = 1;\n }\n const initial = prepared === undefined;\n pendingAdmissions.length = 0;\n changedCount = 0;\n if (prepared !== undefined && !blocksStale && input !== undefined && input.length === 0) {\n statistics.solves++;\n statistics.cacheHits += prepared.blocks.length;\n return;\n }\n updatedSlots.length = 0;\n updatedIntents.length = 0;\n updatedEdges.length = 0;\n replacedEdges.length = 0;\n let stamp = nextStamp();\n let topologyChanged = initial;\n // Structurally safe local updates never need the block partition to be rebuilt.\n let leafSwitch = prepared !== undefined && input !== undefined;\n if (leafSwitch) {\n // Precomputed leaf plan: replay the admitted shapes for the whole dirty batch.\n let count = 0;\n for (let position = 0; position < input!.length; position++) {\n const slot = input![position]!;\n if (seenSlots[slot] === stamp) continue;\n seenSlots[slot] = stamp;\n const intent = pins[slot]!.intent;\n if (intent === intents[slot]) continue;\n const plan = matchLeaf(slot, intent);\n if (plan === undefined) {\n count = -1;\n break;\n }\n leafSlots[count] = slot;\n leafIntents[count] = intent;\n leafEdges[count] = plan.edges;\n leafTargets[count] = plan.target;\n leafPayloads[count] = plan;\n count++;\n }\n if (count > 0) {\n applyLeaf(count);\n return;\n }\n // The general path re-deduplicates, so it needs its own marks.\n stamp = nextStamp();\n }\n const scanAll = initial || input === undefined;\n for (let position = 0; position < (scanAll ? pins.length : input!.length); position++) {\n const index = scanAll ? position : input![position]!;\n if (!scanAll) {\n if (seenSlots[index] === stamp) continue;\n seenSlots[index] = stamp;\n }\n const pin = pins[index]!;\n const intent = pin.intent;\n if (intent === intents[index]) continue;\n const from = pinNodes[index]!;\n const previous = pinEdges[index]!;\n const edges: Edge[] = [];\n for (const branch of intent) {\n if (!validResistance(branch.resistance))\n validateResistance(branch.resistance, pinLocation(pin));\n const to = pinNodes[requireEndpoint(branch.to, pin)]!;\n if (from === to) continue;\n const old = previous[edges.length];\n if (old?.to === to && old.resistance === branch.resistance) edges.push(old);\n else {\n const edge = {\n pin: index,\n index: edges.length,\n from,\n to,\n resistance: branch.resistance,\n conductance: 1 / branch.resistance,\n };\n edges.push(edge);\n if (old?.to === to) replacedEdges.push(old);\n else topologyChanged = true;\n }\n }\n if (edges.length !== previous.length) topologyChanged = true;\n // The node must stay a leaf hanging off a fixed reference on both sides of the update.\n // With one incident branch on each side no unknown-unknown coupling exists, the old\n // component keeps its own pinned node, the new component keeps its own, and the\n // component and floating censuses provably cannot change. A branch that used to\n // reach an unknown node can remove a whole floating component when several such\n // leaves leave together, so that shape falls back to the general solver.\n const leafShape =\n previous.length === 1 &&\n edges.length === 1 &&\n nodeDegree[from] === 1 &&\n nodes[from]!.reference === undefined &&\n nodes[previous[0]!.to]!.reference !== undefined &&\n nodes[edges[0]!.to]!.reference !== undefined;\n if (leafSwitch && !leafShape) leafSwitch = false;\n // One branch from a leaf node onto a fixed reference: remember the shape so that the\n // next switch between the same references replays it instead of rebuilding edges.\n if (leafShape && intent.length === 1 && edges[0] !== previous[0])\n pendingAdmissions.push({\n slot: index,\n intent,\n branch: intent[0]!,\n target: edges[0]!.to,\n edges,\n });\n updatedSlots.push(index);\n updatedIntents.push(intent);\n updatedEdges.push(edges);\n }\n if (leafSwitch && topologyChanged) {\n for (let position = 0; position < updatedSlots.length; position++) {\n leafSlots[position] = updatedSlots[position]!;\n leafIntents[position] = updatedIntents[position]!;\n leafEdges[position] = updatedEdges[position]!;\n leafTargets[position] = updatedEdges[position]![0]!.to;\n leafPayloads[position] = undefined;\n }\n flushAdmissions();\n applyLeaf(updatedSlots.length);\n return;\n }\n if (blocksStale) {\n // The partition is rebuilt from pinEdges, but neither the buckets nor the numerical\n // cache is discarded. Every retained entry is revalidated by layout, fixed\n // potentials, edges and resistance before reuse, and its factorization is reused\n // only when the normalized matrix and anchors are identical.\n topologyChanged = true;\n }\n const updated = updatedSlots.length;\n if (prepared !== undefined && !topologyChanged && replacedEdges.length === 0) {\n for (let position = 0; position < updated; position++) {\n const index = updatedSlots[position]!;\n intents[index] = updatedIntents[position]!;\n pinEdges[index] = updatedEdges[position]!;\n }\n statistics.solves++;\n statistics.cacheHits += prepared.blocks.length;\n flushAdmissions();\n return;\n }\n let topology = prepared;\n let bucket: string | undefined;\n let restored: TopologySnapshot | undefined;\n /** Prospective rebuilds; committed only when the batch is accepted. */\n let topologyPrepares = 0;\n const dirtyBlocks = new Map<number, PreparedBlock>();\n // Dirty edges are also indexed by slot, so rebinding never hashes a pin number.\n for (let position = 0; position < updatedEdgeSlots.length; position++)\n updatedEdgeLists[updatedEdgeSlots[position]!] = undefined;\n updatedEdgeSlots.length = 0;\n for (let position = 0; position < updated; position++) {\n const index = updatedSlots[position]!;\n updatedEdgeLists[index] = updatedEdges[position]!;\n updatedEdgeSlots.push(index);\n }\n if (topologyChanged) {\n // Only dirty pins are hashed, and the aggregate stays prospective: a rejected solve\n // must not move the bucket a committed graph is filed under.\n let hash = topologyHash;\n let spread = topologySpread;\n for (let position = 0; position < updated; position++) {\n const index = updatedSlots[position]!;\n const next = hashEdges(index, updatedEdges[position]!);\n const previous = pinHashes[index]!;\n if (next === previous) continue;\n hash += next - previous;\n spread ^= previous ^ next;\n }\n bucket = `${hash}:${spread}`;\n restored = lookupTransition(bucket, updatedEdgeLists);\n if (restored !== undefined)\n topology = restoreTopology(restored.topology, pinEdges, updatedEdgeLists);\n else {\n const nextEdges = pinEdges.slice();\n for (let position = 0; position < updated; position++)\n nextEdges[updatedSlots[position]!] = updatedEdges[position]!;\n topology = prepareTopology(nodes, nextEdges);\n topologyPrepares++;\n }\n } else {\n const dirty = new Set<number>();\n for (const edge of replacedEdges) {\n const index = topology!.edgeBlocks[edge.pin]?.[edge.index];\n if (index !== undefined) dirty.add(index);\n }\n for (const index of dirty) {\n dirtyBlocks.set(index, rebindBlock(topology!.blocks[index]!, pinEdges, updatedEdgeLists));\n }\n }\n let nextCache: Map<string, CachedComponent> | undefined;\n const pendingVoltages = new Map<number, number | null>();\n let factorizations = 0;\n let factorizationReuses = 0;\n let cacheHits = topologyChanged ? 0 : topology!.blocks.length - dirtyBlocks.size;\n for (const block of topologyChanged ? topology!.blocks : dirtyBlocks.values()) {\n const { component, key } = block;\n const previous = cache.get(key);\n if (previous !== undefined && sameConfiguration(previous, component, nodes)) {\n cacheHits++;\n (nextCache ??= new Map()).set(key, previous);\n continue;\n }\n const voltages = new Map(\n component.nodes.map((node) => [node, nodes[node]!.reference ?? null]),\n );\n const references = component.nodes.filter((node) => nodes[node]!.reference !== undefined);\n const physical = component.physical ?? component;\n const fail = (reason: string): never => {\n const networkIds = physical.nodes.flatMap((node) => [...nodes[node]!.networks]);\n const resources = physical.nodes.flatMap((node) => nodes[node]!.pins.map((pin) => pin.id));\n const firstPin = nodes[physical.nodes[0]!]!.pins[0]!;\n throw new ElectricalError('ELECTRICAL_SOLVE_FAILED', reason, {\n ...pinLocation(firstPin),\n ...(networkIds[0] === undefined ? {} : { network: networkIds[0] }),\n networks: Object.freeze(networkIds),\n component: Object.freeze(resources),\n });\n };\n let factorization: Factorization | undefined;\n let referenceProgram: ReferenceProgram | undefined;\n if (references.length !== 0) {\n const unknown = component.nodes.filter((node) => nodes[node]!.reference === undefined);\n for (const node of references) voltages.set(node, nodes[node]!.reference!);\n const firstReference = nodes[references[0]!]!.reference!;\n if (references.every((node) => nodes[node]!.reference === firstReference)) {\n for (const node of unknown) voltages.set(node, firstReference);\n } else if (unknown.length !== 0) {\n const count = unknown.length;\n const slots = new Map(unknown.map((node, index) => [node, index]));\n let conductanceScale = 0;\n let voltageScale = 0;\n let coupled = false;\n for (const node of references) {\n voltageScale = Math.max(voltageScale, Math.abs(nodes[node]!.reference!));\n }\n for (const edge of component.edges) {\n const from = slots.has(edge.from);\n const to = slots.has(edge.to);\n if (from || to) conductanceScale = Math.max(conductanceScale, edge.conductance);\n if (from && to) coupled = true;\n }\n if (!(conductanceScale > 0) || !(voltageScale > 0)) fail('Invalid equation scaling.');\n if (!coupled) {\n referenceProgram = referencePrograms.find((program) =>\n program.matches(component.edges, unknown),\n );\n if (referenceProgram === undefined) {\n referenceProgram = compileReferenceProgram(unknown, component.edges, slots, nodes);\n if (referenceProgram !== undefined) {\n referencePrograms.push(referenceProgram);\n if (referencePrograms.length > referenceProgramLimit) referencePrograms.shift();\n }\n }\n }\n const matrix = new Float64Array(coupled ? count * count : 0);\n let anchors: Float64Array;\n let right: Float64Array;\n if (referenceProgram !== undefined) {\n ({ anchors, right } = referenceProgram.assemble(\n component.edges,\n conductanceScale,\n voltageScale,\n ));\n } else {\n const anchorTerms: number[][] = Array.from({ length: count }, () => []);\n const rightTerms: number[][] = Array.from({ length: count }, () => []);\n for (const edge of component.edges) {\n const from = slots.get(edge.from);\n const to = slots.get(edge.to);\n const conductance = edge.conductance / conductanceScale;\n if (from !== undefined && to !== undefined) {\n const slot = Math.min(from, to) * count + Math.max(from, to);\n matrix[slot] = matrix[slot]! + conductance;\n } else if (from !== undefined || to !== undefined) {\n const slot = from ?? to!;\n const reference = nodes[from === undefined ? edge.from : edge.to]!.reference!;\n anchorTerms[slot]!.push(conductance);\n rightTerms[slot]!.push(conductance * (reference / voltageScale));\n }\n }\n anchors = Float64Array.from(anchorTerms, (terms) => sum(terms));\n right = Float64Array.from(rightTerms, (terms) => sum(terms));\n }\n if (\n previous?.factorization !== undefined &&\n arraysEqual(previous.factorization.matrix, matrix) &&\n arraysEqual(previous.factorization.anchors, anchors)\n ) {\n factorization = previous.factorization;\n factorizationReuses++;\n } else {\n factorization = factorize(matrix, anchors, fail);\n factorizations++;\n }\n const solution = substitute(factorization, right, fail);\n unknown.forEach((node, index) => {\n const voltage = cleanZero(solution[index]! * voltageScale);\n if (!Number.isFinite(voltage)) fail('Non-finite node voltage.');\n voltages.set(node, voltage);\n });\n }\n }\n const entry: CachedComponent = {\n nodes: component.nodes,\n references: component.nodes.map((node) => nodes[node]!.reference),\n edges: component.edges,\n voltages: component.nodes.map((node) => voltages.get(node)!),\n factorization,\n };\n (nextCache ??= new Map()).set(key, entry);\n for (const [node, voltage] of voltages) {\n if (publishedVoltages[node] !== voltage) pendingVoltages.set(node, voltage);\n }\n }\n const pending = new Map<ElectricalPin, PinSample>();\n changedCount = 0;\n for (const [node, voltage] of pendingVoltages) {\n const slots = nodeSlots[node]!;\n for (let at = 0; at < slots.length; at++) {\n const slot = slots[at]!;\n const pin = pins[slot]!;\n const level =\n voltage === null || pin.low === undefined\n ? 'unknown'\n : voltage <= pin.low\n ? 'low'\n : voltage >= pin.high!\n ? 'high'\n : 'unknown';\n const status = voltage === null ? 'floating' : 'valid';\n const previous = pin.sample;\n const dirty =\n previous.voltage !== voltage || previous.level !== level || previous.status !== status;\n if (dirty) changedSlots[changedCount++] = slot;\n if (dirty || statistics.solves === 0) {\n pending.set(\n pin,\n Object.freeze({\n voltage: voltage === null ? null : cleanZero(voltage),\n level,\n status,\n }),\n );\n }\n }\n }\n // The buffer is trimmed to `changedCount`, so ordering is an in-place insertion sort\n // of the written prefix.\n for (let index = 1; index < changedCount; index++) {\n const slot = changedSlots[index]!;\n let position = index;\n while (position > 0 && changedSlots[position - 1]! > slot) {\n changedSlots[position] = changedSlots[position - 1]!;\n position--;\n }\n changedSlots[position] = slot;\n }\n // No pin, intent snapshot, adjacency or factorization cache changes before acceptance.\n for (const [pin, sample] of pending) pin.sample = sample;\n for (const [node, voltage] of pendingVoltages) publishedVoltages[node] = voltage;\n for (let position = 0; position < updated; position++) {\n const index = updatedSlots[position]!;\n const edges = updatedEdges[position]!;\n syncDegrees(pinEdges[index]!, edges);\n intents[index] = updatedIntents[position]!;\n pinEdges[index] = edges;\n setPinHash(index, edges);\n }\n if (topologyChanged) cache = nextCache ?? new Map();\n else {\n // Column-wise merge keeps a rejected solve from leaving a half-rebuilt cache.\n if (nextCache !== undefined) for (const [key, value] of nextCache) cache.set(key, value);\n for (const [index, block] of dirtyBlocks) topology!.blocks[index] = block;\n }\n prepared = topology!;\n // A rejected solve leaves the stale flag set, so a retry rebuilds and revalidates the\n // partition instead of trusting blocks it never committed.\n blocksStale = false;\n if (topologyChanged) {\n const admitted: TopologySnapshot =\n restored !== undefined && topology === restored.topology\n ? restored\n : {\n // Reusing the id keeps the bucket age stable while a graph is only re-bound.\n id: restored?.id ?? nextTopologyId++,\n cost: restored?.cost ?? topologyCost(topology!),\n topology: topology!,\n // A confirmed bucket hit already carries the exact hashes.\n hashes: restored?.hashes ?? pinHashes.slice(),\n };\n rememberTransition(bucket!, admitted);\n }\n statistics.solves++;\n statistics.components = topology!.components;\n statistics.floatingComponents = topology!.floatingComponents;\n statistics.factorizations += factorizations;\n statistics.factorizationReuses += factorizationReuses;\n statistics.cacheHits += cacheHits;\n statistics.topologyPrepares += topologyPrepares;\n flushAdmissions();\n }\n}\n","/**\n * Binary min-heap over parallel arrays. Every push/pop used to allocate a `{ time, order,\n * value }` record; a timed board pushes one continuation per suspension, so the flat form\n * keeps the scheduler loop allocation-free.\n */\nexport class EventQueue<T> {\n private readonly times: number[] = [];\n private readonly orders: number[] = [];\n private readonly values: (T | undefined)[] = [];\n private size = 0;\n private sequence = 0;\n get time(): number {\n return this.size === 0 ? Infinity : this.times[0]!;\n }\n push(time: number, value: T): void {\n const at = this.size++;\n this.times[at] = time;\n this.orders[at] = this.sequence++;\n this.values[at] = value;\n this.siftUp(at);\n }\n pop(): T {\n const value = this.values[0]!;\n const last = --this.size;\n if (last >= 0) {\n this.times[0] = this.times[last]!;\n this.orders[0] = this.orders[last]!;\n this.values[0] = this.values[last]!;\n this.times[last] = 0;\n this.orders[last] = 0;\n this.values[last] = undefined;\n this.siftDown();\n }\n return value;\n }\n clear(): void {\n this.size = 0;\n }\n private before(first: number, second: number): boolean {\n const times = this.times;\n const a = times[first]!;\n const b = times[second]!;\n return a < b || (a === b && this.orders[first]! < this.orders[second]!);\n }\n private swap(first: number, second: number): void {\n const times = this.times;\n const orders = this.orders;\n const values = this.values;\n const time = times[first]!;\n const order = orders[first]!;\n const value = values[first]!;\n times[first] = times[second]!;\n orders[first] = orders[second]!;\n values[first] = values[second];\n times[second] = time;\n orders[second] = order;\n values[second] = value;\n }\n private siftUp(at: number): void {\n while (at > 0) {\n const parent = (at - 1) >>> 1;\n if (!this.before(at, parent)) break;\n this.swap(at, parent);\n at = parent;\n }\n }\n private siftDown(): void {\n const size = this.size;\n let at = 0;\n for (;;) {\n const left = at * 2 + 1;\n if (left >= size) break;\n const right = left + 1;\n const child = right < size && this.before(right, left) ? right : left;\n if (!this.before(child, at)) break;\n this.swap(at, child);\n at = child;\n }\n }\n}\nexport class ActivationQueue<T> {\n private readonly entries: T[] = [];\n private readonly words: number[] = [];\n /**\n * Active word indices in `[0, activeCount)`. The array keeps its high-water length:\n * truncating it would right-trim the backing store on every boundary.\n */\n private readonly activeWords: number[] = [];\n private activeCount = 0;\n get size(): number {\n return this.activeCount;\n }\n register(entry: T): number {\n return this.entries.push(entry) - 1;\n }\n add(slot: number): void {\n const word = slot >>> 5;\n const previous = this.words[word] ?? 0;\n if (previous === 0) this.activeWords[this.activeCount++] = word;\n this.words[word] = previous | (1 << (slot & 31));\n }\n /**\n * Visits every active entry in board order without materialising a batch. Entries added\n * by the visitor land past the visited range and survive.\n */\n drain(visit: (entry: T) => void): void {\n const active = this.activeWords;\n const visited = this.activeCount;\n if (visited === 0) return;\n if (visited > 1) {\n // Word indices arrive in insertion order; a handful of words sort faster in place\n // than through a comparator call, and the stale tail must not be reordered.\n for (let index = 1; index < visited; index++) {\n const word = active[index]!;\n let position = index;\n while (position > 0 && active[position - 1]! > word) {\n active[position] = active[position - 1]!;\n position--;\n }\n active[position] = word;\n }\n }\n for (let index = 0; index < visited; index++) {\n const word = active[index]!;\n let bits = this.words[word]!;\n this.words[word] = 0;\n const base = word * 32;\n while (bits !== 0) {\n visit(this.entries[base + 31 - Math.clz32(bits & -bits)]!);\n bits &= bits - 1;\n }\n }\n if (this.activeCount === visited) this.activeCount = 0;\n else {\n // A word re-added during the drain was appended past `visited`; shift it down.\n for (let index = visited; index < this.activeCount; index++)\n active[index - visited] = active[index]!;\n this.activeCount -= visited;\n }\n }\n clear(): void {\n this.entries.length = 0;\n this.words.length = 0;\n this.activeWords.length = 0;\n this.activeCount = 0;\n }\n}\n\nexport class Fifo<T> {\n private readonly values: (T | undefined)[] = [];\n private head = 0;\n private tail = 0;\n get length(): number {\n return this.tail - this.head;\n }\n push(value: T): void {\n // The backing array keeps its high-water length, so a push never clears elements.\n this.values[this.tail++] = value;\n }\n shift(): T {\n const value = this.values[this.head]!;\n this.values[this.head++] = undefined;\n if (this.head === this.tail) {\n this.head = 0;\n this.tail = 0;\n }\n return value;\n }\n clear(): void {\n this.values.length = 0;\n this.head = 0;\n this.tail = 0;\n }\n drain(): T[] {\n const result = this.values.slice(this.head, this.tail) as T[];\n this.clear();\n return result;\n }\n}\n","import type {\n ArgumentIR,\n BinaryOperator,\n DeclarationIR,\n MemoryRefIR,\n NumericBuiltin,\n OperationIR,\n PinRefIR,\n RegionIR,\n UnaryOperator,\n ValueRegionIR,\n ValueTypeIR,\n} from '@mica-js/device-model';\nimport {\n checkBoolean,\n createBytes,\n createEnum,\n createRecord,\n equalValues,\n nonNull,\n readIndex,\n} from '@mica-js/compiler';\nimport { range, same } from './values.js';\n\n/**\n * A generated observation plan for one static source path.\n *\n * The generic path already compiles each computation to JavaScript; what this plan adds\n * is binding. The source path, its projection, the resource objects and the resource\n * slots are resolved once, so a publication round performs no host or resource name\n * resolution, no dependency-stack tracking, no derived cache staleness check and no\n * per-round dependency map merge. Every operation of every branch is emitted from the\n * supported set; anything outside it rejects the whole plan and the caller keeps the\n * generic path.\n */\nexport interface PlannedSlot {\n readonly version: number;\n}\n\nexport interface ObservationMemory {\n readonly bytes: Uint8Array;\n readonly view: DataView;\n readonly slot: PlannedSlot;\n}\n\nexport interface ObservationTarget {\n readonly declarations: ReadonlyMap<string, DeclarationIR>;\n readonly states: ReadonlyMap<string, unknown>;\n readonly pins: ReadonlyMap<string, { readonly sample: unknown }>;\n readonly stateResources: ReadonlyMap<string, PlannedSlot>;\n readonly sampleResources: ReadonlyMap<string, PlannedSlot>;\n readonly memoryResources: ReadonlyMap<string, PlannedSlot>;\n memoryPlan(ref: unknown): ObservationMemory;\n read(kind: string, name: string): unknown;\n}\n\nexport interface CompiledObservation {\n readonly key: string;\n readonly path: readonly string[];\n /** Generated reader source; kept for tests and diagnostics, not evaluated again. */\n readonly source: string;\n /** Generated comparator source. */\n readonly comparison: string;\n readonly slots: readonly PlannedSlot[];\n /** Raw value of the source path, exactly what an unmodified derived read returns. */\n readonly evaluate: () => unknown;\n readonly equals: (previous: unknown, current: unknown) => boolean;\n /** Non-primitive results are snapshotted for the immutable observation baseline. */\n readonly needsSnapshot: boolean;\n}\n\nexport type ObservationCompilation =\n | { readonly ok: true; readonly plan: CompiledObservation }\n | { readonly ok: false; readonly reason: string };\n\nconst unaryOperators: Partial<Record<UnaryOperator, string>> = {\n positive: '+',\n negate: '-',\n not: '!',\n bitNot: '~',\n};\nconst binaryOperators: Partial<Record<BinaryOperator, string>> = {\n add: '+',\n subtract: '-',\n multiply: '*',\n divide: '/',\n remainder: '%',\n power: '**',\n lessThan: '<',\n lessThanOrEqual: '<=',\n greaterThan: '>',\n greaterThanOrEqual: '>=',\n concat: '+',\n bitAnd: '&',\n bitOr: '|',\n bitXor: '^',\n shiftLeft: '<<',\n shiftRight: '>>',\n shiftRightUnsigned: '>>>',\n};\nconst numericBuiltins = new Set<NumericBuiltin>([\n 'isNaN',\n 'isFinite',\n 'isInteger',\n 'isSafeInteger',\n 'abs',\n 'floor',\n 'ceil',\n 'trunc',\n 'round',\n 'sqrt',\n 'min',\n 'max',\n 'pow',\n]);\nconst numberBuiltins = new Set<NumericBuiltin>(['isNaN', 'isFinite', 'isInteger', 'isSafeInteger']);\n\nfunction load(kind: string, memory: ObservationMemory, offset: unknown): number {\n const size = kind.startsWith('load8') ? 1 : kind.startsWith('load16') ? 2 : 4;\n const at = range(memory.bytes, offset, size);\n if (size === 1) return memory.bytes[at]!;\n return size === 2\n ? memory.view.getUint16(at, kind.endsWith('le'))\n : memory.view.getUint32(at, kind.endsWith('le'));\n}\nfunction copyBytes(memory: ObservationMemory, offset: unknown, length: unknown): Uint8Array {\n const at = range(memory.bytes, offset, length);\n return memory.bytes.slice(at, at + Number(length));\n}\nfunction assertFalse(message: unknown): never {\n throw new Error(message === undefined ? 'Assertion failed' : String(message));\n}\nfunction sameBytes(left: Uint8Array, right: Uint8Array): boolean {\n for (let index = 0; index < left.length; index++) if (left[index] !== right[index]) return false;\n return true;\n}\nconst helpers = Object.freeze({\n checkBoolean,\n createBytes,\n createEnum,\n createRecord,\n equalValues,\n nonNull,\n readIndex,\n load,\n copyBytes,\n assertFalse,\n sameBytes,\n});\n\nclass Unsupported extends Error {}\n\nfunction reject(reason: string): never {\n throw new Unsupported(reason);\n}\n\n/** Emits one generated reader; every unsupported operation rejects the whole plan. */\nclass ReaderEmitter {\n private readonly bindings: unknown[] = [];\n private readonly bindingIds = new Map<unknown, number>();\n private readonly slots: PlannedSlot[] = [];\n private readonly nested: string[] = [];\n private readonly named = new Map<string, string>();\n private readonly visiting = new Set<string>();\n /** Result ids already defined by an emitted operation, for static legality checks. */\n private readonly results = new Set<number>();\n private readonly buffers: string[][] = [[]];\n private depth = 0;\n private serial = 0;\n\n constructor(private readonly target: ObservationTarget) {\n this.bindings.push(target);\n this.bindingIds.set(target, 0);\n }\n\n build(declaration: Extract<DeclarationIR, { kind: 'derived' }>, path: readonly string[]): string {\n const read = this.nestedDerived(declaration);\n // The observation source is the full static path: project every suffix field with\n // the same step the generic source walk performs, so the reader value, the\n // comparator type and the snapshot decision all describe the observed field.\n if (path.length === 1) {\n this.line(`return ${read}();`);\n } else {\n this.line(`let projected = ${read}();`);\n for (let index = 1; index < path.length; index++)\n this.line(`projected = projected[${this.ref(path[index]!)}];`);\n this.line('return projected;');\n }\n return [\n 'function () {',\n ...this.nested.map((text) => text),\n ...this.buffers[0]!.map((text) => ` ${text}`),\n '}',\n ].join('\\n');\n }\n\n slotsUsed(): readonly PlannedSlot[] {\n return this.slots;\n }\n\n bindingTable(): readonly unknown[] {\n return this.bindings;\n }\n\n private get lines(): string[] {\n return this.buffers[this.buffers.length - 1]!;\n }\n\n private line(text: string): void {\n this.lines.push(`${' '.repeat(this.depth)}${text}`);\n }\n\n private block(header: string, body: () => void): void {\n this.line(`${header} {`);\n this.depth++;\n body();\n this.depth--;\n this.line('}');\n }\n\n private bind(value: unknown): number {\n const object = value !== null && typeof value === 'object';\n if (!object && Object.is(value, -0)) return this.bindings.push(value) - 1;\n const existing = this.bindingIds.get(value);\n if (existing !== undefined) return existing;\n const index = this.bindings.push(value) - 1;\n this.bindingIds.set(value, index);\n return index;\n }\n\n private ref(value: unknown): string {\n return `B[${this.bind(value)}]`;\n }\n\n private slot(slot: PlannedSlot): void {\n if (!this.slots.includes(slot)) this.slots.push(slot);\n }\n\n private nestedSource(name: string, params: readonly string[], body: () => void): string {\n this.buffers.push([]);\n const outer = this.depth;\n this.depth = 0;\n try {\n body();\n } finally {\n this.depth = outer;\n }\n const lines = this.buffers.pop()!;\n const text = [`function ${name}(${params.join(', ')}) {`, ...lines, '}'].join('\\n');\n this.nested.push(text);\n return name;\n }\n\n private nestedDerived(declaration: Extract<DeclarationIR, { kind: 'derived' }>): string {\n const key = `derived:${declaration.name}`;\n const existing = this.named.get(key);\n if (existing) return existing;\n if (this.visiting.has(key)) reject(`recursive derived ${declaration.name}`);\n const name = `d${this.serial++}`;\n this.named.set(key, name);\n this.visiting.add(key);\n try {\n this.nestedSource(name, [], () => this.region(declaration.value.body, undefined));\n } finally {\n this.visiting.delete(key);\n }\n return name;\n }\n\n private nestedFunction(\n name: string,\n declaration: Extract<DeclarationIR, { kind: 'function' }>,\n ): string {\n const key = `function:${name}`;\n const existing = this.named.get(key);\n if (existing) return existing;\n if (this.visiting.has(key)) reject(`recursive pure call ${name}`);\n const id = `f${this.serial++}`;\n this.named.set(key, id);\n this.visiting.add(key);\n try {\n const params = declaration.params.map((_, index) => `p${index}`);\n this.nestedSource(id, params, () => {\n const outer = this.params;\n this.params = params;\n try {\n this.region(declaration.body, undefined);\n } finally {\n this.params = outer;\n }\n });\n } finally {\n this.visiting.delete(key);\n }\n return id;\n }\n\n private params: readonly string[] | undefined;\n\n private value(id: number): string {\n if (!this.results.has(id)) reject(`result ${id} is used before it is defined`);\n return `v${id}`;\n }\n\n private defineResult(id: number): string {\n this.results.add(id);\n return `v${id}`;\n }\n\n private region(region: RegionIR, output: { slot: string; label: string } | undefined): void {\n for (const operation of region.operations) this.operation(operation, output);\n }\n\n private valueRegion(region: ValueRegionIR, slot: string): void {\n const label = `s${this.serial++}`;\n this.line(`${label}: {`);\n this.depth++;\n this.region(region.body, { slot, label });\n this.depth--;\n this.line('}');\n }\n\n private argument(argument: ArgumentIR): string {\n if (argument.kind !== 'value') reject('resource argument');\n return this.value(argument.value);\n }\n\n private memoryRef(ref: MemoryRefIR, kind: string): ObservationMemory {\n if (ref.kind === 'parameter') reject(`parameterised memory ${kind}`);\n const memory = this.target.memoryPlan(ref.name);\n this.slot(memory.slot);\n return memory;\n }\n\n private pinRef(ref: PinRefIR, kind: string): { readonly sample: unknown } {\n if (ref.kind === 'parameter') reject(`parameterised pin ${kind}`);\n const pin = this.target.pins.get(ref.name);\n const slot = this.target.sampleResources.get(ref.name);\n if (!pin || !slot) reject(`unknown pin ${ref.name}`);\n this.slot(slot);\n return pin;\n }\n\n private operation(\n operation: OperationIR,\n output: { slot: string; label: string } | undefined,\n ): void {\n const assign = (expression: string): void => {\n if (!('result' in operation)) reject('resultless operation');\n this.line(`const ${this.defineResult(operation.result)} = ${expression};`);\n };\n const child = (region: RegionIR): void => this.region(region, output);\n switch (operation.kind) {\n case 'constant': {\n const constant = operation.constant;\n if (constant.kind === 'bytes')\n assign(\n `H.createBytes(${this.ref(Object.freeze(Array.from(createBytes(constant.value))))})`,\n );\n else if (constant.kind === 'enum')\n assign(this.ref(createEnum(constant.name, constant.member)));\n else if (constant.kind === 'record')\n assign(\n this.ref(\n createRecord(constant.fields.map((field) => [field.name, field.value] as const)),\n ),\n );\n else if (constant.kind === 'none') assign('null');\n else assign(this.ref(constant.value));\n break;\n }\n case 'read': {\n if (operation.resource === 'state') {\n const slot = this.target.stateResources.get(operation.name);\n if (!slot || !this.target.states.has(operation.name))\n reject(`unknown state ${operation.name}`);\n this.slot(slot);\n assign(`${this.ref(this.target.states)}.get(${this.ref(operation.name)})`);\n } else if (operation.resource === 'derived') {\n const declaration = this.target.declarations.get(operation.name);\n if (declaration?.kind !== 'derived') reject(`unknown derived ${operation.name}`);\n assign(`${this.nestedDerived(declaration)}()`);\n } else {\n assign(\n `${this.ref(this.target)}.read(${this.ref(operation.resource)}, ${this.ref(operation.name)})`,\n );\n }\n break;\n }\n case 'parameter': {\n const params = this.params;\n if (!params || operation.index >= params.length) reject('value parameter outside a call');\n assign(params[operation.index]!);\n break;\n }\n case 'unary': {\n const operator = unaryOperators[operation.operator];\n if (!operator) reject(`unsupported unary ${operation.operator}`);\n assign(`(${operator}${this.value(operation.value)})`);\n break;\n }\n case 'binary': {\n if (operation.operator === 'equal' || operation.operator === 'notEqual')\n assign(\n `${operation.operator === 'notEqual' ? '!' : ''}H.equalValues(${this.value(operation.left)}, ${this.value(operation.right)})`,\n );\n else {\n const operator = binaryOperators[operation.operator];\n if (!operator) reject(`unsupported binary ${operation.operator}`);\n assign(`(${this.value(operation.left)} ${operator} ${this.value(operation.right)})`);\n }\n break;\n }\n case 'numeric': {\n if (!numericBuiltins.has(operation.builtin))\n reject(`unsupported builtin ${operation.builtin}`);\n const receiver = numberBuiltins.has(operation.builtin) ? 'Number' : 'Math';\n assign(\n `${receiver}.${operation.builtin}(${operation.args.map((id) => this.value(id)).join(', ')})`,\n );\n break;\n }\n case 'record':\n assign(\n `H.createRecord([${operation.fields\n .map((field) => `[${this.ref(field.name)}, ${this.value(field.value)}]`)\n .join(', ')}])`,\n );\n break;\n case 'field':\n assign(`${this.value(operation.value)}[${this.ref(operation.field)}]`);\n break;\n case 'bytes':\n assign(`H.createBytes([${operation.elements.map((id) => this.value(id)).join(', ')}])`);\n break;\n case 'length':\n assign(`${this.value(operation.value)}.length`);\n break;\n case 'index':\n assign(`H.readIndex(${this.value(operation.value)}, ${this.value(operation.index)})`);\n break;\n case 'optional':\n assign(this.value(operation.value));\n break;\n case 'isNone':\n assign(`(${this.value(operation.value)} === null)`);\n break;\n case 'nonNull':\n assign(`H.nonNull(${this.value(operation.value)})`);\n break;\n case 'localRead':\n assign(`l${operation.local}`);\n break;\n case 'local':\n this.line(`let l${operation.local} = ${this.value(operation.initial)};`);\n break;\n case 'localWrite':\n this.line(`l${operation.local} = ${this.value(operation.value)};`);\n break;\n case 'memoryLength':\n assign(`${this.ref(this.memoryRef(operation.memory, operation.kind))}.bytes.length`);\n break;\n case 'load8':\n case 'load16le':\n case 'load16be':\n case 'load32le':\n case 'load32be':\n assign(\n `H.load(${this.ref(operation.kind)}, ${this.ref(this.memoryRef(operation.memory, operation.kind))}, ${this.value(operation.offset)})`,\n );\n break;\n case 'copyBytes': {\n const memory = this.memoryRef(operation.memory, operation.kind);\n assign(\n `H.copyBytes(${this.ref(memory)}, ${this.value(operation.offset)}, ${this.value(operation.length)})`,\n );\n break;\n }\n case 'readSample':\n assign(`${this.ref(this.pinRef(operation.pin, operation.kind))}.sample`);\n break;\n case 'callValue': {\n if (!operation.pure) reject('impure call');\n const declaration = this.target.declarations.get(operation.name);\n if (declaration?.kind !== 'function' || !declaration.pure)\n reject(`unknown pure function ${operation.name}`);\n assign(\n `${this.nestedFunction(operation.name, declaration)}(${operation.args\n .map((argument) => this.argument(argument))\n .join(', ')})`,\n );\n break;\n }\n case 'if':\n this.block(`if (H.checkBoolean(${this.value(operation.condition)}))`, () =>\n child(operation.yes),\n );\n if (operation.no) this.block('else', () => child(operation.no!));\n break;\n case 'match': {\n operation.arms.forEach((arm, index) => {\n const pattern = arm.pattern;\n const constant =\n pattern.kind === 'none'\n ? null\n : pattern.kind === 'enum'\n ? createEnum(pattern.name, pattern.member)\n : pattern.value;\n this.block(\n `${index ? 'else if' : 'if'} (H.equalValues(${this.value(operation.value)}, ${this.ref(constant)}))`,\n () => child(arm.body),\n );\n });\n if (operation.otherwise)\n this.block(operation.arms.length ? 'else' : '', () => child(operation.otherwise!));\n break;\n }\n case 'while':\n this.block('while (true)', () => {\n const slot = `s${this.serial++}`;\n this.line(`let ${slot};`);\n this.valueRegion(operation.test, slot);\n this.line(`if (!H.checkBoolean(${slot})) break;`);\n this.block('', () => child(operation.body));\n });\n break;\n case 'loop':\n this.block('while (true)', () => child(operation.body));\n break;\n case 'and':\n case 'or': {\n const slot = this.defineResult(operation.result);\n this.line(`let ${slot} = H.checkBoolean(${this.value(operation.left)});`);\n this.block(`if (${operation.kind === 'or' ? '!' : ''}${slot})`, () => {\n this.valueRegion(operation.right, slot);\n this.line(`${slot} = H.checkBoolean(${slot});`);\n });\n break;\n }\n case 'select': {\n const slot = this.defineResult(operation.result);\n this.line(`let ${slot};`);\n this.block(`if (H.checkBoolean(${this.value(operation.condition)}))`, () =>\n this.valueRegion(operation.yes, slot),\n );\n this.block('else', () => this.valueRegion(operation.no, slot));\n break;\n }\n case 'assert':\n this.block(`if (!H.checkBoolean(${this.value(operation.condition)}))`, () => {\n if (operation.message) {\n const slot = `s${this.serial++}`;\n this.line(`let ${slot};`);\n this.valueRegion(operation.message, slot);\n this.line(`H.assertFalse(${slot});`);\n } else this.line('H.assertFalse(undefined);');\n });\n break;\n case 'return':\n this.line('return;');\n break;\n case 'returnValue':\n this.line(`return ${this.value(operation.value)};`);\n break;\n case 'break':\n this.line('break;');\n break;\n case 'continue':\n this.line('continue;');\n break;\n case 'yield':\n if (!output) reject('yield outside a value region');\n this.line(`${output.slot} = ${this.value(operation.value)};`);\n this.line(`break ${output.label};`);\n break;\n default: {\n const kind = (operation as { kind?: unknown }).kind;\n reject(`unsupported operation ${String(kind)}`);\n }\n }\n }\n}\n\ninterface SemanticType {\n readonly type: ValueTypeIR | undefined;\n}\n\nfunction fieldType(\n declarations: ReadonlyMap<string, DeclarationIR>,\n type: ValueTypeIR | undefined,\n field: string,\n): ValueTypeIR | undefined {\n if (!type) return undefined;\n if (type.kind === 'optional') return undefined;\n if (type.kind === 'record') {\n const declaration = declarations.get(type.name);\n if (declaration?.kind !== 'record') return undefined;\n const entry = declaration.fields.find((candidate) => candidate.name === field);\n return entry ? { kind: entry.type } : undefined;\n }\n if (type.kind === 'sample') {\n if (field === 'voltage') return { kind: 'optional', inner: { kind: 'number' } };\n if (field === 'level' || field === 'status') return { kind: 'enum', name: 'Logic' };\n }\n return undefined;\n}\n\nfunction resolvePathType(\n declarations: ReadonlyMap<string, DeclarationIR>,\n type: ValueTypeIR,\n path: readonly string[],\n): SemanticType {\n let current: ValueTypeIR | undefined = type;\n for (let index = 1; index < path.length; index++)\n current = fieldType(declarations, current, path[index]!);\n return { type: current };\n}\n\nfunction primitive(type: ValueTypeIR | undefined): boolean {\n if (!type) return false;\n if (type.kind === 'optional') return primitive(type.inner);\n return ['number', 'bool', 'string', 'enum'].includes(type.kind);\n}\n\n/**\n * Stable observation comparison for the declared source type. Numbers compare NaN as\n * equal and treat positive and negative zero as equal; bytes compare length and\n * content; records and samples compare their declared fields recursively; nullables\n * compare none first. Language equality is deliberately not reused here.\n */\nfunction comparison(\n declarations: ReadonlyMap<string, DeclarationIR>,\n type: ValueTypeIR | undefined,\n left: string,\n right: string,\n): string | undefined {\n if (!type) return undefined;\n switch (type.kind) {\n case 'number':\n return `(${left} === ${right} || (${left} !== ${left} && ${right} !== ${right}))`;\n case 'bool':\n case 'string':\n case 'enum':\n return `(${left} === ${right})`;\n case 'bytes':\n return `(${left} === ${right} || (${left} !== null && ${right} !== null && typeof ${left} === \"object\" && typeof ${right} === \"object\" && ${left}.length === ${right}.length && H.sameBytes(${left}, ${right})))`;\n case 'sample': {\n const fields = ['voltage', 'level', 'status'].map((field) =>\n comparison(\n declarations,\n fieldType(declarations, type, field),\n `${left}[${JSON.stringify(field)}]`,\n `${right}[${JSON.stringify(field)}]`,\n ),\n );\n if (fields.some((field) => field === undefined)) return undefined;\n return `(${left} === ${right} || (${left} !== null && ${right} !== null && typeof ${left} === \"object\" && typeof ${right} === \"object\" && ${fields.join(' && ')}))`;\n }\n case 'record': {\n const declaration = declarations.get(type.name);\n if (declaration?.kind !== 'record' || !declaration.fields.length) return undefined;\n const fields = declaration.fields.map((field) =>\n comparison(\n declarations,\n { kind: field.type },\n `${left}[${JSON.stringify(field.name)}]`,\n `${right}[${JSON.stringify(field.name)}]`,\n ),\n );\n if (fields.some((field) => field === undefined)) return undefined;\n return `(${left} === ${right} || (${left} !== null && ${right} !== null && typeof ${left} === \"object\" && typeof ${right} === \"object\" && ${fields.join(' && ')}))`;\n }\n case 'optional': {\n const inner = comparison(declarations, type.inner, left, right);\n if (inner === undefined) return undefined;\n return `(${left} === ${right} || (${left} === null ? ${right} === null : (${right} !== null && ${inner})))`;\n }\n default:\n return undefined;\n }\n}\n\n/** Bind a source path to one generated reader and one generated comparator. */\nexport function compileObservation(\n target: ObservationTarget,\n key: string,\n path: readonly string[],\n): ObservationCompilation {\n const declaration = target.declarations.get(path[0]!);\n if (declaration?.kind !== 'derived')\n return { ok: false, reason: 'source root is not a derived declaration' };\n const { type } = resolvePathType(target.declarations, declaration.type, path);\n if (type === undefined) return { ok: false, reason: 'source field type is not resolvable' };\n if (type.kind === 'intent')\n return { ok: false, reason: 'intent has no stable content comparison' };\n try {\n const emitter = new ReaderEmitter(target);\n const source = emitter.build(declaration, path);\n const factory = new Function('B', 'H', `\"use strict\"; return (${source});`) as (\n bindings: readonly unknown[],\n helpers: unknown,\n ) => () => unknown;\n const evaluate = factory(emitter.bindingTable(), helpers);\n const compare = comparison(target.declarations, type, 'a', 'b');\n const comparisonSource = `function (a, b) { return ${compare ?? 'H.same(a, b)'}; }`;\n const comparer = new Function('H', `\"use strict\"; return (${comparisonSource});`)({\n ...helpers,\n same,\n }) as (previous: unknown, current: unknown) => boolean;\n return {\n ok: true,\n plan: {\n key,\n path: [...path],\n source,\n comparison: comparisonSource,\n slots: emitter.slotsUsed(),\n evaluate,\n equals: comparer,\n needsSnapshot: !primitive(type),\n },\n };\n } catch (cause) {\n return {\n ok: false,\n reason:\n cause instanceof Unsupported\n ? cause.message\n : `unexpected code generation failure: ${cause instanceof Error ? cause.message : String(cause)}`,\n };\n }\n}\n","import {\n compileBody,\n compileComputation,\n compileResumableBody,\n compileSynchronousBody,\n type CompiledBody,\n type ExecutionHost,\n type ResumableFrame,\n type ResumableProgram,\n type SynchronousProgram,\n} from '@mica-js/compiler';\nimport type { ComputationIR, DeviceIR, RegionIR } from '@mica-js/device-model';\nimport type { Instance } from './instance';\n\nconst compiledBodies = new WeakMap<RegionIR, CompiledBody>();\nconst resumablePrograms = new WeakMap<RegionIR, ResumableProgram | null>();\nconst compiledComputations = new WeakMap<ComputationIR, (host: ExecutionHost) => unknown>();\n/**\n * Synchronous programs are instance independent, but their static function resolution\n * belongs to one device model. The outer key prevents reusing a root region compiled\n * against another model's function table; `null` records a whole-body fallback.\n */\nconst synchronousPrograms = new WeakMap<DeviceIR, WeakMap<RegionIR, SynchronousProgram | null>>();\nexport const MAX_TIME = 7_200_000_000_000_000;\nexport function time(value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value))\n throw new TypeError('Time must be a finite integer');\n if (value < 0 || value > MAX_TIME) throw new RangeError('Time out of range');\n return value === 0 ? 0 : value;\n}\nexport function body(region: RegionIR): CompiledBody {\n let result = compiledBodies.get(region);\n if (!result) {\n result = compileBody(region);\n compiledBodies.set(region, result);\n }\n return result;\n}\n/**\n * Compile one reaction body for one device model. Static callees are resolved from the\n * same declaration environment the generator uses. A compiler decline is cached as a\n * whole-body fallback; execution errors are never caught here and never replay effects.\n */\nexport function synchronousBody(\n instance: Instance,\n region: RegionIR,\n): SynchronousProgram | undefined {\n const model = instance.entry.model;\n let cache = synchronousPrograms.get(model);\n if (cache === undefined) {\n cache = new WeakMap();\n synchronousPrograms.set(model, cache);\n }\n const cached = cache.get(region);\n if (cached !== undefined) return cached ?? undefined;\n const program = compileSynchronousBody(region, {\n bindResources: true,\n resolveFunction: (name) => {\n const declaration = instance.declarations.get(name);\n return declaration?.kind === 'function' ? declaration.body : undefined;\n },\n });\n cache.set(region, program ?? null);\n return program;\n}\nexport function resumable(region: RegionIR): ResumableProgram | undefined {\n let result = resumablePrograms.get(region);\n if (result === undefined) {\n result = compileResumableBody(region, { bindResources: true }) ?? null;\n resumablePrograms.set(region, result);\n }\n return result ?? undefined;\n}\nexport function frame(program: ResumableProgram): ResumableFrame {\n return {\n pc: program.start,\n slots: new Array<unknown>(program.slotCount),\n kind: 0,\n duration: 0,\n channel: '',\n value: undefined,\n };\n}\nexport function computation(value: ComputationIR, host: ExecutionHost): unknown {\n let result = compiledComputations.get(value);\n if (!result) {\n result = compileComputation(value);\n compiledComputations.set(value, result);\n }\n return result(host);\n}\n","/** D5 宿主与器件 SDK 合同;声明附件不表示运行时已经实现。 */\nimport type { Disposable, Event } from '@mica-js/core/lifecycle';\nimport type {\n BlockIR,\n DeclarationIR,\n DeviceIR,\n InputPath,\n SourceInfo,\n JitBlockBuilder,\n} from '@mica-js/device-model';\nexport type { Disposable, Event } from '@mica-js/core/lifecycle';\n\ndeclare const snapshotTag: unique symbol;\ndeclare const borrowedTag: unique symbol;\ndeclare const libraryTag: unique symbol;\n\ninterface ByteReader extends Iterable<number> {\n readonly length: number;\n readonly byteLength: number;\n readonly [index: number]: number | undefined;\n [Symbol.iterator](): IterableIterator<number>;\n slice(start?: number, end?: number): Uint8Array;\n}\n\n/** 可跨推进和销毁留存的自有只读快照;slice 返回调用方拥有的可变副本。 */\nexport interface ReadonlyBytes extends ByteReader {\n readonly [snapshotTag]: true;\n}\n/** 句柄随所属板或本次翻译失效;内容稳定期与允许读取阶段由 memory 合同规定。 */\nexport interface BorrowedBytes extends ByteReader {\n readonly [borrowedTag]: true;\n}\n\nexport interface InputChannel<T> {\n send(value: T): void;\n}\nexport interface InputNotification {\n notify(): void;\n}\nexport interface ChannelMessage<T> {\n readonly time: number;\n readonly value: T;\n}\nexport interface Notification {\n readonly time: number;\n}\nexport interface TopicMessage {\n readonly topic: string;\n readonly payload: unknown;\n}\nexport interface TopicBridge {\n readonly onDidReceive: Event<TopicMessage>;\n publish(topic: string, payload: unknown): void;\n}\n\n/** 一段可执行代码区域;`base` 是逻辑 PC 基址,区域从对应 memory 的偏移 0 开始。 */\nexport interface JitCodeRegion {\n readonly memory: string;\n readonly base: number;\n readonly size: number;\n}\nexport interface JitTranslateInput {\n readonly pc: number;\n /** 仅在本次同步 translate 回调内有效;长度最多为本 region 的 `size`。 */\n readonly code: BorrowedBytes;\n /** 本次翻译所属 region 的逻辑基址;未命中 region 的服务 PC 回退主 code 时为 0。 */\n readonly codeBase: number;\n /** 按实例 memory 维护的代码代际;代码区域内的成功写入即时递增。 */\n readonly codeVersion: number;\n}\nexport type JitTranslate = (input: JitTranslateInput, builder: JitBlockBuilder) => BlockIR;\nexport interface InstructionHook {\n readonly when: string;\n readonly call: string;\n}\n/**\n * 一条忙等延时环的声明:入口 `pc` 每轮把 number 状态 `counter` 减一,消耗 `cycles` ps。\n * 环内不得产生其他可观察效果,因此跳过多轮只推进时间、只留下最后一轮的效果。\n *\n * `pending` 给按累加器计时的外设(SysTick、USART 位时钟):折算必须停在下一次服务边界,\n * 并把折叠掉的时间记进 `state`,否则跳过轮次会让这些外设永远等不到自己的节拍。\n */\nexport interface JitDelay {\n readonly counter: string;\n readonly cycles: number;\n readonly pending?: {\n /** 已累积的节拍时长(ps)。 */\n readonly state: string;\n /** 一次服务的粒度(ps)。 */\n readonly period: string;\n /** 是否需要按时间推进外设。 */\n readonly active: string;\n };\n}\n\n/**\n * A throughput-only wait point. When `predicate` is false the JIT parks until a dependency\n * changes. If `wait` is present, `delay` supplies the picoseconds to the next device time\n * event and `advance` applies that elapsed interval before the JIT is re-queued.\n *\n * `consume` runs once after `predicate` becomes true, allowing a one-shot wake token to be\n * cleared before the guest instruction executes. These functions take zero or one\n * argument; only `predicate` and `delay` must be pure.\n */\nexport interface JitPolling {\n readonly pc: number;\n readonly predicate: string;\n readonly consume?: string;\n readonly wait?: {\n /** Pure zero-argument function returning the delay in picoseconds, or zero to park. */\n readonly delay: string;\n /** Function receiving the elapsed picoseconds and applying the device time event. */\n readonly advance: string;\n };\n}\n\n/** 按 region 传给 codeMetadata provider 的只读代码视图;仅在本次同步回调内有效。 */\nexport interface JitCodeRegionView {\n readonly memory: string;\n readonly base: number;\n readonly size: number;\n readonly codeVersion: number;\n readonly code: BorrowedBytes;\n}\n/** 自上次该 region metadata 成功刷新以来的实际写入范围,单位为 memory offset;首次调用表示整区。 */\nexport interface JitCodeChange {\n readonly memory: string;\n readonly offset: number;\n readonly length: number;\n}\nexport interface JitCodeMetadata {\n readonly polling: readonly JitPolling[];\n readonly delays: ReadonlyMap<number, JitDelay>;\n}\nexport interface JitCodeMetadataInput {\n readonly region: JitCodeRegionView;\n readonly changes: readonly JitCodeChange[];\n}\nexport type JitCodeMetadataProvider = (input: JitCodeMetadataInput) => JitCodeMetadata;\n\nexport interface JitOptions {\n readonly entry: string;\n readonly code: string;\n /**\n * 主 `code` 内存仍隐式提供 0 基址 region;这里追加 Flash alias、SRAM、CCM 等\n * 可执行区域。区域不得与隐式主区域或彼此重叠。\n */\n readonly codeRegions?: readonly JitCodeRegion[];\n /**\n * 按 region、按 codeVersion 懒加载的代码派生 metadata。与静态\n * `polling`/`delays` 互斥;省略时完全保持旧静态路径。\n */\n readonly codeMetadata?: JitCodeMetadataProvider;\n readonly pc: string;\n /** Return immutable synchronous function IR scoped to this JIT. Reuse its array to reuse binding. */\n readonly functions?: (\n device: DeviceIR,\n ) => readonly Extract<DeclarationIR, { kind: 'function' }>[];\n readonly beforeInstruction?: InstructionHook;\n readonly polling?: readonly JitPolling[];\n readonly delays?: ReadonlyMap<number, JitDelay>;\n readonly translate: JitTranslate;\n}\nexport interface JitHost {\n attachJit(options: JitOptions): Disposable;\n loadBytes(memory: string, bytes: Uint8Array, offset?: number): void;\n}\n\n/** 具体字段由生成模块或工厂泛型注解投影;这里不重复声明资源名称。 */\nexport interface DeviceContext<\n Props extends object = object,\n Inputs extends object = object,\n Memory extends object = object,\n> extends JitHost {\n readonly props: Readonly<Props>;\n readonly inputs: Readonly<Inputs>;\n readonly memory: Readonly<Memory>;\n readonly topics: TopicBridge;\n reportError(error: unknown): void;\n}\nexport interface DeviceBatch<Outputs extends object = object> {\n readonly from: number;\n readonly to: number;\n readonly outputs: Readonly<Outputs>;\n}\nexport interface DeviceAdapter<Batch extends DeviceBatch = DeviceBatch> extends Disposable {\n sync(batch: Batch): void;\n}\nexport type DeviceFactory<\n Context extends DeviceContext = DeviceContext,\n Batch extends DeviceBatch = DeviceBatch,\n> = (context: Context) => DeviceAdapter<Batch>;\n\n/** 异构登记在库边界擦除器件泛型;工厂使用生成类型或精确的 SDK 泛型注解。 */\nexport interface DeviceLibraryEntry {\n readonly id: string;\n readonly model: DeviceIR;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 库边界有意擦除异构工厂的类型。\n readonly create: DeviceFactory<any, any>;\n}\n/** 已校验并捕获模型和登记关系的可复用库;没有运行中资源。 */\nexport interface DeviceLibrary {\n readonly [libraryTag]: true;\n}\nexport declare function createDeviceLibrary(entries: readonly DeviceLibraryEntry[]): DeviceLibrary;\n\n/** 四个 uint32,不能全零;精确数值合法性在创建前校验。 */\nexport type RandomState = readonly [number, number, number, number];\nexport type PropertyInput = number | boolean | string | null | Uint8Array;\nexport interface InstanceDescription {\n readonly id: string;\n readonly type: string;\n readonly props?: Readonly<Record<string, PropertyInput>>;\n readonly randomState?: RandomState;\n}\nexport interface PinEndpoint {\n readonly instance: string;\n readonly pin: string;\n}\nexport interface NetDescription {\n readonly id: string;\n readonly pins: readonly PinEndpoint[];\n /** 有限对地电压,0 表示地;省略时不建立理想参考。 */\n readonly voltage?: number;\n}\nexport interface BoardDescription {\n readonly instances: readonly InstanceDescription[];\n readonly nets: readonly NetDescription[];\n}\nexport interface BoardOptions {\n /** uint32,省略为 0;实例派生算法见 execution/random。 */\n readonly seed?: number;\n readonly execution?: 'throughput' | 'precise';\n /** CPU execution quantum in integer picoseconds, default 10_000_000. */\n readonly cpuQuantum?: number;\n}\nexport type BoardStatus = 'ready' | 'faulted' | 'disposed';\nexport type RuntimePhase =\n | 'library'\n | 'assembly'\n | 'initialize'\n | 'execute'\n | 'translate'\n | 'sync'\n | 'topic'\n | 'dispose'\n | 'host'\n | 'report';\nexport type RuntimeDiagnosticCode =\n | 'INVALID_CONFIGURATION'\n | 'MODEL_VALIDATION_FAILED'\n | 'RESOURCE_ALLOCATION_FAILED'\n | 'INVALID_ELECTRICAL_PARAMETER'\n | 'CONFLICTING_REFERENCE'\n | 'ELECTRICAL_SOLVE_FAILED'\n | 'CHANNEL_CONSUMER_CONFLICT'\n | 'INVALID_CALL_STATE'\n | 'OBJECT_DISPOSED'\n | 'BOARD_FAULTED'\n | 'INVALID_BINDING'\n | 'MODEL_EXECUTION_FAILED'\n | 'JIT_FAILED'\n | 'DEVICE_CALLBACK_FAILED'\n | 'ASYNC_HOOK_RESULT'\n | 'CHANNEL_OVERFLOW'\n | 'REPORTED_ERROR'\n | 'CLEANUP_FAILED'\n | 'STALE_REPORT'\n | 'HOST_LISTENER_FAILED';\n\n/** cause 保留原异常引用;只读约束不要求冻结宿主异常对象。 */\nexport interface RuntimeDiagnostic {\n readonly code: RuntimeDiagnosticCode;\n readonly message: string;\n readonly phase: RuntimePhase;\n readonly time: number | null;\n readonly instanceId?: string;\n readonly resource?: string;\n readonly path?: InputPath;\n readonly source?: SourceInfo;\n readonly cause?: unknown;\n readonly related: readonly RuntimeDiagnostic[];\n}\nexport class SimulationError extends Error {\n readonly code: RuntimeDiagnosticCode;\n readonly diagnostic: RuntimeDiagnostic;\n readonly related: readonly RuntimeDiagnostic[];\n constructor(diagnostic: RuntimeDiagnostic) {\n super(diagnostic.message);\n this.name = 'SimulationError';\n this.code = diagnostic.code;\n this.diagnostic = diagnostic;\n this.related = diagnostic.related;\n }\n}\n\nexport interface Board extends Disposable {\n readonly time: number;\n readonly status: BoardStatus;\n readonly topics: TopicBridge;\n readonly onDidError: Event<RuntimeDiagnostic>;\n readonly onDidDiagnostic: Event<RuntimeDiagnostic>;\n runUntil(target: number): void;\n}\n/** 同步捕获配置、建立资源与调用工厂;成功后才返回 ready 板。 */\nexport declare function createBoard(\n library: DeviceLibrary,\n description: BoardDescription,\n options?: BoardOptions,\n): Board;\n","import { BuildError } from '@mica-js/device-model';\nimport {\n SimulationError,\n type RuntimeDiagnostic,\n type RuntimeDiagnosticCode,\n type RuntimePhase,\n} from '../types';\nimport { snapshot } from '../values';\n\nfunction thenable(value: unknown): boolean {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as { then?: unknown }).then === 'function'\n );\n}\nexport class AsyncHookError extends TypeError {\n readonly code = 'ASYNC_HOOK_RESULT';\n constructor() {\n super('Device hooks must return synchronously');\n }\n}\nexport class ElectricalParameterError extends RangeError {\n readonly code = 'INVALID_ELECTRICAL_PARAMETER';\n}\nexport function electricalNumber(value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value))\n throw new ElectricalParameterError('Electrical parameters must be finite numbers');\n return value;\n}\nexport function acceptSync(value: unknown): void {\n if (thenable(value)) {\n void Promise.resolve(value).catch(() => {});\n throw new AsyncHookError();\n }\n}\nexport function modelLocation(cause: unknown): Partial<Pick<RuntimeDiagnostic, 'path' | 'source'>> {\n if (!(cause instanceof BuildError)) return {};\n const diagnostic = cause.diagnostics[0];\n if (!diagnostic) return {};\n return {\n ...(diagnostic.path ? { path: Object.freeze([...diagnostic.path]) } : {}),\n ...(diagnostic.source\n ? { source: snapshot(diagnostic.source) as NonNullable<RuntimeDiagnostic['source']> }\n : {}),\n };\n}\nexport function standalone(\n code: RuntimeDiagnosticCode,\n cause: unknown,\n phase: RuntimePhase,\n): SimulationError {\n return new SimulationError(\n Object.freeze({\n code,\n message: cause instanceof Error ? cause.message : String(cause),\n phase,\n time: null,\n cause,\n ...modelLocation(cause),\n related: Object.freeze([]),\n }),\n );\n}\n","import type { Disposable } from '@mica-js/core/lifecycle';\nimport { type DeclarationIR, type DeviceIR, validateDeviceIR } from '@mica-js/device-model';\nimport type { ExecutionHost, ResourceHandle } from '@mica-js/compiler';\nimport type { ElectricalPin, ResistorBranch } from '../electrical';\nimport { Fifo } from '../queue';\nimport { body, computation, resumable, synchronousBody } from './execution';\nimport { acceptSync, electricalNumber, ElectricalParameterError } from './errors';\nimport type {\n Channel,\n Decl,\n Dependencies,\n DerivedEntry,\n DirectJitLayout,\n Entry,\n Execution,\n Jit,\n JitMetadataRegion,\n JitPollingBinding,\n Observation,\n Process,\n Reaction,\n ResourceSlot,\n} from './state';\nimport {\n bytesView,\n captureValue,\n dataObject,\n externalValue,\n finite,\n identity,\n integer,\n nonnegative,\n nextRandom,\n randomState,\n range,\n snapshot,\n} from '../values';\nimport type {\n DeviceAdapter,\n DeviceBatch,\n DeviceContext,\n JitCodeChange,\n JitCodeRegion,\n JitDelay,\n JitOptions,\n RuntimeDiagnosticCode,\n RuntimePhase,\n SimulationError,\n TopicBridge,\n} from '../types';\n\n/** Board capabilities used by an instance; the board owns scheduling and publication. */\nexport interface InstanceBoard {\n readonly time: number;\n readonly phase: string;\n readonly current: Instance | undefined;\n /** Monotonic count of resource-version mutations on the whole board. */\n readonly resourceEpoch: number;\n noteResourceVersion(slot: ResourceSlot): void;\n markElectricalDirty(slot: number): void;\n readonly jits: Jit[];\n readonly waitingJits: Set<Jit>;\n /** Wakes or drops a parked JIT and removes its dependency registrations. */\n unparkWaiter(jit: Jit): void;\n assertAlive(instance?: Instance): void;\n /** Admission for a call that may change board state or is visible to a device. */\n assertCallAllowed(instance?: Instance): void;\n /** Admission for a read-only entry point: a faulted board stays inspectable. */\n assertReadAllowed(instance?: Instance): void;\n error(\n code: RuntimeDiagnosticCode,\n message: string,\n instance?: Instance,\n cause?: unknown,\n phase?: RuntimePhase,\n ): SimulationError;\n fault(error: SimulationError): void;\n report(instance: Instance, cause: unknown): void;\n topicBridge(owner?: Instance): TopicBridge;\n electricalSlot(pin: ElectricalPin): number;\n invalidate(slot: ResourceSlot): void;\n}\n\nconst EMPTY_MESSAGES: readonly never[] = Object.freeze([]);\ntype JitFunctions = readonly Decl<'function'>[];\nconst jitModels = new WeakMap<DeviceIR, WeakMap<JitFunctions, DeviceIR>>();\n\n/** Retain the binding identity when adapters reuse the same immutable function table. */\nfunction bindJitFunctions(base: DeviceIR, functions: JitFunctions): DeviceIR {\n if (functions.length === 0) return base;\n let models = jitModels.get(base);\n const cached = models?.get(functions);\n if (cached !== undefined) return cached;\n const model = validateDeviceIR({ ...base, declarations: base.declarations.concat(functions) });\n for (const declaration of model.declarations.slice(base.declarations.length))\n if (declaration.kind !== 'function') throw new TypeError('Expected JIT function declaration');\n if (models === undefined) {\n models = new WeakMap();\n jitModels.set(base, models);\n }\n models.set(functions, model);\n return model;\n}\n\n/** Membership test without allocating: every key of `next` is already in `previous`. */\nfunction hasEvery(\n previous: ReadonlyMap<ResourceSlot, number>,\n next: ReadonlyMap<ResourceSlot, number>,\n): boolean {\n for (const slot of next.keys()) if (!previous.has(slot)) return false;\n return true;\n}\nfunction createContext(owner: Instance, board: InstanceBoard): DeviceContext {\n return Object.freeze({\n get props() {\n board.assertReadAllowed(owner);\n return Object.freeze(\n Object.fromEntries([...owner.props].map(([key, value]) => [key, externalValue(value)])),\n );\n },\n get inputs() {\n owner.assertCallAllowed();\n return owner.inputs();\n },\n get memory() {\n board.assertReadAllowed(owner);\n return owner.publicMemory();\n },\n topics: board.topicBridge(owner),\n reportError: (error: unknown) => board.report(owner, error),\n attachJit: (options: JitOptions) => owner.attach(options),\n loadBytes: (name: string, bytes: Uint8Array, ...offset: unknown[]) =>\n owner.loadBytes(name, bytes, offset.length ? offset[0] : 0),\n });\n}\n\n/**\n * State map whose scalar direct-bank writes are synced lazily on read.\n *\n * Direct JIT writes update `stateValues` and invalidate `stateSlots` at every boundary,\n * while no observer or host reads `instance.states` until a reaction, observation,\n * fallback or external query accesses it. Deferring the string-keyed `Map.set` calls\n * until an actual read removes redundant map updates across resident GPIO edges while\n * keeping `instance.states` an exact `Map<string, unknown>` at every read site.\n */\nclass StateMirrorMap extends Map<string, unknown> {\n private names: readonly string[] = [];\n private bankValues: unknown[] = [];\n private dirty = new Int32Array(0);\n private pending = false;\n\n bindDirectBank(names: readonly string[], values: unknown[]): void {\n this.names = names;\n this.bankValues = values;\n this.dirty = new Int32Array(Math.ceil(names.length / 32));\n }\n\n markDirectDirty(word: number, bits: number): void {\n this.dirty[word]! |= bits;\n this.pending = true;\n }\n\n private flush(): void {\n if (!this.pending) return;\n this.pending = false;\n const { names, bankValues, dirty } = this;\n for (let word = 0; word < dirty.length; word++) {\n let bits = dirty[word]!;\n if (bits === 0) continue;\n dirty[word] = 0;\n const base = word << 5;\n while (bits !== 0) {\n const index = base + 31 - Math.clz32(bits & -bits);\n super.set(names[index]!, bankValues[index]);\n bits &= bits - 1;\n }\n }\n }\n\n override get(key: string): unknown {\n if (this.pending) this.flush();\n return super.get(key);\n }\n\n override set(key: string, value: unknown): this {\n if (this.pending) this.flush();\n return super.set(key, value);\n }\n\n override entries(): MapIterator<[string, unknown]> {\n if (this.pending) this.flush();\n return super.entries();\n }\n\n override values(): MapIterator<unknown> {\n if (this.pending) this.flush();\n return super.values();\n }\n\n override forEach(\n callbackfn: (value: unknown, key: string, map: Map<string, unknown>) => void,\n thisArg?: unknown,\n ): void {\n if (this.pending) this.flush();\n super.forEach(callbackfn, thisArg);\n }\n\n override [Symbol.iterator](): MapIterator<[string, unknown]> {\n if (this.pending) this.flush();\n return super[Symbol.iterator]();\n }\n}\n\nexport class Instance {\n readonly declarations = new Map<string, DeclarationIR>();\n readonly props = new Map<string, unknown>();\n readonly constants = new Map<string, unknown>();\n readonly states = new StateMirrorMap();\n private directBank?: Pick<\n DirectJitLayout,\n 'stateNames' | 'stateSlots' | 'states' | 'stateValues'\n >;\n readonly memories = new Map<string, Uint8Array>();\n private readonly memoryViews = new Map<string, DataView>();\n private readonly memorySizes = new Map<string, number>();\n readonly pins = new Map<string, ElectricalPin>();\n readonly channels = new Map<string, Channel>();\n readonly notificationInputs = new Set<string>();\n readonly notificationOutputs = new Map<string, number | null>();\n private readonly batchInputs: Channel[] = [];\n private readonly batchOutputs: (readonly [string, Channel])[] = [];\n private readonly batchNotifications: string[] = [];\n private readonly emptyOutputs: Record<string, unknown> = Object.create(null);\n readonly resources: Disposable[] = [];\n readonly jits: Jit[] = [];\n readonly processes: Process[] = [];\n readonly reactions: Reaction[] = [];\n readonly derived = new Map<string, DerivedEntry>();\n /** One-entry memo for repeated `read('derived', name)` calls inside a body. */\n private derivedName: string | undefined;\n private derivedEntry: DerivedEntry | undefined;\n private readonly derivedBuffers = new Map<string, Map<ResourceSlot, number>>();\n readonly stateResources = new Map<string, ResourceSlot>();\n readonly memoryResources = new Map<string, ResourceSlot>();\n readonly sampleResources = new Map<string, ResourceSlot>();\n observerRevision = 0;\n private readonly dependencyStack: Map<ResourceSlot, number>[] = [];\n private readonly observations = new WeakMap<Observation, Dependencies>();\n private readonly staticObservations = new WeakMap<Observation, () => unknown>();\n private readonly resistorIntents = new Map<string, Map<number, readonly ResistorBranch[]>>();\n private readonly sampleEntries = new Map<string, { pin: ElectricalPin; slot: ResourceSlot }>();\n private readonly intentEntries = new Map<string, { pin: ElectricalPin; slot: number }>();\n private readonly stateSlots = new Map<string, ResourceSlot>();\n /** Per-instance handles for the fixed resources a resumable process body binds. */\n private readonly resourceHandles = new Map<string, ResourceHandle>();\n private readonly memoryPlans = new Map<\n string,\n { name: string; bytes: Uint8Array; view: DataView; slot: ResourceSlot }\n >();\n /** 按 memory 维护的代码代际;只有 code region 内写入才递增。 */\n private readonly codeVersions = new Map<string, number>();\n /**\n * Every memory name any attached JIT binds as a code region. A write outside this set\n * cannot affect a JIT, so the store path skips the region scans entirely.\n */\n private readonly codeMemories = new Set<string>();\n private readonly observationFrames = new WeakMap<\n Observation,\n { first: Map<ResourceSlot, number>; second: Map<ResourceSlot, number>; alternate: boolean }\n >();\n readonly evaluating = new Set<string>();\n readonly random: Uint32Array;\n readonly host: ExecutionHost;\n readonly context: DeviceContext;\n adapter?: DeviceAdapter;\n valid = true;\n rawProps: Record<string, unknown>;\n constructor(\n readonly board: InstanceBoard,\n readonly entry: Entry,\n readonly id: string,\n props: unknown,\n seed: number,\n override?: readonly number[],\n ) {\n for (const declaration of entry.model.declarations) {\n if ('name' in declaration) this.declarations.set(declaration.name, declaration);\n if (\n declaration.kind === 'state' ||\n declaration.kind === 'memory' ||\n declaration.kind === 'pin'\n ) {\n const resources =\n declaration.kind === 'state'\n ? this.stateResources\n : declaration.kind === 'memory'\n ? this.memoryResources\n : this.sampleResources;\n resources.set(declaration.name, {\n version: 0,\n subscribers: new Set(),\n waiters: undefined,\n });\n }\n }\n dataObject(props);\n this.rawProps = props;\n for (const key of Object.keys(props))\n if (this.declarations.get(key)?.kind !== 'property')\n throw new TypeError(`Unknown property ${key}`);\n this.random = randomState(seed, id, override);\n this.host = {\n read: (kind, name) => this.read(kind, name),\n write: (name, value) => this.writeState(name, value, this.stateSlot(name)),\n sample: (ref) => {\n return this.readSample(ref);\n },\n intent: (pin, value) => {\n this.writeIntent(pin, value);\n },\n resistor: (pin, resistance) => {\n const r = electricalNumber(resistance);\n if (r < 0.001 || r > 1e9)\n throw new ElectricalParameterError('Resistance outside [0.001, 1e9]');\n return this.resistorIntent(pin, r);\n },\n memoryLength: (memory) => this.memory(memory).length,\n load: (kind, memory, offset) => {\n const plan = this.memoryPlan(memory);\n const size = kind.startsWith('load8') ? 1 : kind.startsWith('load16') ? 2 : 4;\n const at = range(plan.bytes, offset, size);\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(plan.slot, plan.slot.version);\n if (size === 1) return plan.bytes[at]!;\n return size === 2\n ? plan.view.getUint16(at, kind.endsWith('le'))\n : plan.view.getUint32(at, kind.endsWith('le'));\n },\n store: (kind, memory, offset, value) => {\n const plan = this.memoryPlan(memory);\n const size = kind.startsWith('store8') ? 1 : kind.startsWith('store16') ? 2 : 4;\n const at = range(plan.bytes, offset, size);\n const n = integer(value, 'stored value');\n if (size === 1) plan.bytes[at] = n;\n else if (size === 2) plan.view.setUint16(at, n, kind.endsWith('le'));\n else plan.view.setUint32(at, n, kind.endsWith('le'));\n this.memoryChangedPlan(plan, at, size);\n },\n copyBytes: (memory, offset, length) => {\n this.track(this.memoryResources, String(memory));\n const bytes = this.memory(memory),\n at = range(bytes, offset, length);\n return bytes.slice(at, at + Number(length));\n },\n send: (name, value) => this.send(name, value, false),\n notify: (name) => {\n if (!this.notificationOutputs.has(name))\n throw new TypeError(`Unknown notification ${name}`);\n this.notificationOutputs.set(name, board.time);\n },\n now: () => board.time,\n random: () => nextRandom(this.random),\n call: (name, args) => this.invoke(name, args),\n assert: (condition, message) => {\n if (condition !== true)\n throw new Error(message === undefined ? 'Assertion failed' : String(message));\n },\n bind: (specs) => this.bindResources(specs),\n };\n this.context = createContext(this, board);\n }\n private track(resources: ReadonlyMap<string, ResourceSlot>, name: string): void {\n this.trackSlot(resources.get(name)!);\n }\n /** Innermost dependency sink, or `undefined` outside an evaluation. */\n private dependencies(): Map<ResourceSlot, number> | undefined {\n const stack = this.dependencyStack;\n return stack.length === 0 ? undefined : stack[stack.length - 1];\n }\n private trackSlot(slot: ResourceSlot): void {\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(slot, slot.version);\n }\n /** Read-only evidence that a process frame bound per-instance resource handles. */\n bindingReport(): unknown {\n return Object.freeze({\n instance: this.id,\n handles: this.resourceHandles.size,\n bound: Object.freeze([...this.resourceHandles.keys()].sort()),\n processes: Object.freeze(\n this.processes.map((process) =>\n Object.freeze({\n name: process.declaration.kind === 'on' ? process.declaration.name : 'start',\n bound: process.frame?.resources?.length ?? 0,\n }),\n ),\n ),\n });\n }\n dependenciesCurrent(dependencies: Dependencies | undefined): boolean {\n if (!dependencies) return false;\n for (const [slot, version] of dependencies) if (slot.version !== version) return false;\n return true;\n }\n /** Publishes a derived cache entry; the memo must follow every table write. */\n setDerived(name: string, entry: DerivedEntry): void {\n // Observation chains republish the same entry on every boundary they observe; the\n // memo already proves `derived` maps this name to this entry, so the map write is\n // skipped. Every other writer still replaces the map entry below.\n if (this.derivedName === name && this.derivedEntry === entry) return;\n this.derived.set(name, entry);\n this.derivedName = name;\n this.derivedEntry = entry;\n }\n evaluate<T>(\n compute: () => T,\n target?: Map<ResourceSlot, number>,\n ): { value: T; dependencies: Dependencies } {\n const dependencies = target ?? new Map<ResourceSlot, number>();\n this.dependencyStack.push(dependencies);\n try {\n return { value: compute(), dependencies };\n } finally {\n this.dependencyStack.pop();\n const parent = this.dependencies();\n if (parent) for (const [key, version] of dependencies) parent.set(key, version);\n }\n }\n /** Leaf form of :func:`evaluate` for a source walk: no closure and no result wrapper. */\n private evaluateSource(\n path: readonly string[],\n dependencies: Map<ResourceSlot, number>,\n ): unknown {\n this.dependencyStack.push(dependencies);\n try {\n return snapshot(this.source(path));\n } finally {\n this.dependencyStack.pop();\n const parent = this.dependencies();\n if (parent) for (const [key, version] of dependencies) parent.set(key, version);\n }\n }\n observe(observation: Observation, path: readonly string[]): unknown {\n const read = this.staticObservations.get(observation);\n if (read) return read();\n const declaration = this.declarations.get(path[0]!);\n if (declaration?.kind === 'pin' || declaration?.kind === 'state') {\n const resources = declaration.kind === 'pin' ? this.sampleResources : this.stateResources;\n const pin = declaration.kind === 'pin' ? this.pin(declaration.name) : undefined;\n if (pin && path[1] !== 'sample') throw new TypeError(`Invalid source ${path.join('.')}`);\n // Published samples are immutable; state values may contain byte snapshots.\n const read = () => {\n let value: unknown = pin ? pin.sample : this.states.get(declaration.name);\n for (let index = pin ? 2 : 1; index < path.length; index++)\n value = (value as Record<string, unknown>)[path[index]!];\n return pin ? value : snapshot(value);\n };\n const value = read();\n const slot = resources.get(declaration.name)!;\n if (!slot.subscribers.size) this.observerRevision++;\n slot.subscribers.add(observation);\n this.staticObservations.set(observation, read);\n return value;\n }\n // Dynamic sources alternate between two reusable dependency buffers, so one round can\n // be diffed against the other without allocating a map per publication boundary.\n const frames = this.observationFrames.get(observation);\n let target: Map<ResourceSlot, number>;\n if (frames === undefined) {\n target = new Map();\n this.observationFrames.set(observation, {\n first: target,\n second: new Map(),\n alternate: true,\n });\n } else {\n target = frames.alternate ? frames.second : frames.first;\n frames.alternate = !frames.alternate;\n target.clear();\n }\n const observed = this.evaluateSource(path, target);\n const previous = this.observations.get(observation);\n // A stable network re-derives the same slots every round; only membership changes\n // touch subscriber bookkeeping.\n if (previous === undefined || previous.size !== target.size || !hasEvery(previous, target)) {\n if (previous)\n for (const slot of previous.keys())\n if (!target.has(slot) && slot.subscribers.delete(observation) && !slot.subscribers.size)\n this.observerRevision++;\n for (const slot of target.keys())\n if (!previous?.has(slot)) {\n if (!slot.subscribers.size) this.observerRevision++;\n slot.subscribers.add(observation);\n }\n }\n this.observations.set(observation, target);\n return observed;\n }\n observationReader(observation: Observation, path: readonly string[]): () => unknown {\n return this.staticObservations.get(observation) ?? (() => this.observe(observation, path));\n }\n read(kind: string, name: string): unknown {\n if (kind === 'state') {\n this.trackSlot(this.stateSlot(name));\n return this.states.get(name);\n }\n if (kind === 'derived') {\n // A body re-reads the same derived value between boundaries; one memoized name\n // saves the string-keyed lookup. Every writer of `derived` goes through `setDerived`,\n // so the memo can never disagree with the table.\n let cached = name === this.derivedName ? this.derivedEntry : this.derived.get(name);\n const epoch = this.board.resourceEpoch;\n if (\n cached === undefined ||\n (cached.epoch !== epoch && !this.dependenciesCurrent(cached.dependencies))\n ) {\n const declaration = this.declarations.get(name);\n if (declaration?.kind !== 'derived') throw new TypeError(`Unknown derived ${name}`);\n // The previous dependency set is only used by the staleness check above, so this\n // name's buffer can be cleared and refilled in place for the new evaluation.\n let buffer = this.derivedBuffers.get(name);\n if (buffer === undefined) {\n buffer = new Map();\n this.derivedBuffers.set(name, buffer);\n } else buffer.clear();\n const evaluated = this.evaluate(() => computation(declaration.value, this.host), buffer);\n cached = {\n value: evaluated.value,\n dependencies: evaluated.dependencies,\n epoch: this.board.resourceEpoch,\n };\n this.setDerived(name, cached);\n } else if (cached.epoch !== epoch) {\n // The versions still match, so the value holds while later mutations keep\n // advancing the epoch: record the checkpoint and skip the scan until then.\n cached.epoch = epoch;\n }\n const parent = this.dependencies();\n if (parent) for (const [key, version] of cached.dependencies) parent.set(key, version);\n return cached.value;\n }\n const values = kind === 'property' ? this.props : this.constants;\n if (values.has(name)) return values.get(name);\n if (this.evaluating.has(name)) throw new TypeError(`Circular creation dependency ${name}`);\n this.evaluating.add(name);\n try {\n const declaration = this.declarations.get(name);\n if (declaration?.kind !== 'property' && declaration?.kind !== 'const')\n throw new TypeError(`Invalid creation reference ${name}`);\n let value: unknown;\n if (declaration.kind === 'property') {\n if (Object.hasOwn(this.rawProps, name))\n value = captureValue(declaration.type, this.rawProps[name], this.declarations, true);\n else if (declaration.default)\n value = captureValue(\n declaration.type,\n computation(declaration.default, this.host),\n this.declarations,\n true,\n );\n else throw new TypeError(`Missing property ${name}`);\n } else value = computation(declaration.value, this.host);\n values.set(name, value);\n return value;\n } finally {\n this.evaluating.delete(name);\n }\n }\n invoke(name: string, args: readonly unknown[] = []): Execution {\n const fn = this.declarations.get(name);\n if (fn?.kind !== 'function') throw new TypeError(`Unknown function ${name}`);\n return body(fn.body)(this.host, args);\n }\n syncCall(name: string, args: readonly unknown[] = []): unknown {\n const step = this.invoke(name, args).next();\n if (!step.done) throw new TypeError('Unexpected suspension in synchronous function');\n return step.value;\n }\n pin(ref: unknown): ElectricalPin {\n const pin = this.pins.get(String(ref));\n if (!pin) throw new TypeError(`Unknown pin ${String(ref)}`);\n return pin;\n }\n /** Shared by the generic host and direct JIT, which needs to know whether to publish. */\n writeIntent(ref: unknown, value: unknown): boolean {\n const name = typeof ref === 'string' ? ref : String(ref);\n const board = this.board;\n let entry = this.intentEntries.get(name);\n if (entry === undefined) {\n const pin = this.pin(name);\n entry = { pin, slot: board.electricalSlot(pin) };\n this.intentEntries.set(name, entry);\n }\n if (entry.pin.intent === value) return false;\n entry.pin.intent = value as readonly ResistorBranch[];\n board.markElectricalDirty(entry.slot);\n return true;\n }\n /**\n * One frozen, reusable intent value per (pin, resistance); intents are immutable. The\n * outer map is keyed by pin name and the inner one by resistance, so the hot path builds\n * no key string. Bounds: at most 64 names, and at most 8 resistances per name; a full\n * level is cleared wholesale (no least-recently-used eviction), so identity is only\n * reused while both levels stay under their limits.\n */\n resistorIntent(pin: unknown, resistance: number): readonly ResistorBranch[] {\n const name = typeof pin === 'string' ? pin : String(pin);\n let byResistance = this.resistorIntents.get(name);\n if (byResistance === undefined) {\n if (this.resistorIntents.size >= 64) this.resistorIntents.clear();\n byResistance = new Map();\n this.resistorIntents.set(name, byResistance);\n }\n let intent = byResistance.get(resistance);\n if (intent === undefined) {\n if (byResistance.size >= 8) byResistance.clear();\n intent = Object.freeze([Object.freeze({ to: this.pin(name), resistance })]);\n byResistance.set(resistance, intent);\n }\n return intent;\n }\n private readSample(ref: unknown): ElectricalPin['sample'] {\n const name = typeof ref === 'string' ? ref : String(ref);\n let entry = this.sampleEntries.get(name);\n if (entry === undefined) {\n const pin = this.pin(name);\n entry = { pin, slot: this.sampleResources.get(pin.name)! };\n if (this.sampleEntries.size >= 512) this.sampleEntries.clear();\n this.sampleEntries.set(name, entry);\n }\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(entry.slot, entry.slot.version);\n return entry.pin.sample;\n }\n memory(ref: unknown): Uint8Array {\n const bytes = this.memories.get(String(ref));\n if (!bytes) throw new TypeError(`Unknown memory ${String(ref)}`);\n return bytes;\n }\n /** Instance-owned numeric bank, mirrored by every non-direct state write. */\n directStateBank(): NonNullable<Instance['directBank']> {\n if (this.directBank === undefined) {\n const stateNames = [...this.states.keys()].filter((name) => {\n const declaration = this.declarations.get(name) as Decl<'state'>;\n return declaration.type.kind === 'number' || declaration.type.kind === 'bool';\n });\n const frozenNames = Object.freeze(stateNames);\n const stateValues = stateNames.map((name) => this.states.get(name));\n this.states.bindDirectBank(frozenNames, stateValues);\n this.directBank = {\n stateNames: frozenNames,\n stateSlots: Object.freeze(stateNames.map((name) => this.stateResources.get(name)!)),\n states: new Map(stateNames.map((name, index) => [name, index])),\n stateValues,\n };\n }\n return this.directBank;\n }\n /** Direct scalar writes are already in the numeric bank. Commit the mirror and version. */\n commitDirectStates(dirty: number[] | Int32Array): boolean {\n const { stateSlots } = this.directBank!;\n const states = this.states;\n const board = this.board;\n let wrote = false;\n for (let word = 0; word < dirty.length; word++) {\n let bits = dirty[word]!;\n if (bits === 0) continue;\n dirty[word] = 0;\n wrote = true;\n states.markDirectDirty(word, bits);\n const base = word << 5;\n while (bits !== 0) {\n const index = base + 31 - Math.clz32(bits & -bits);\n const slot = stateSlots[index]!;\n if (slot.subscribers.size === 0) {\n slot.version++;\n board.noteResourceVersion(slot);\n } else board.invalidate(slot);\n bits &= bits - 1;\n }\n }\n return wrote;\n }\n private writeState(name: string, value: unknown, slot: ResourceSlot): void {\n const captured = snapshot(value);\n this.states.set(name, captured);\n const index = this.directBank?.states.get(name);\n if (index !== undefined) this.directBank!.stateValues[index] = captured;\n this.board.invalidate(slot);\n }\n private stateSlot(name: string): ResourceSlot {\n let slot = this.stateSlots.get(name);\n if (slot === undefined) {\n if (!this.states.has(name)) throw new TypeError(`Unknown state ${name}`);\n slot = this.stateResources.get(name)!;\n this.stateSlots.set(name, slot);\n }\n return slot;\n }\n memoryPlan(ref: unknown): {\n name: string;\n bytes: Uint8Array;\n view: DataView;\n slot: ResourceSlot;\n } {\n const name = typeof ref === 'string' ? ref : String(ref);\n let plan = this.memoryPlans.get(name);\n if (plan === undefined) {\n const bytes = this.memories.get(name);\n if (!bytes) throw new TypeError(`Unknown memory ${name}`);\n plan = {\n name,\n bytes,\n view: this.memoryViews.get(name)!,\n slot: this.memoryResources.get(name)!,\n };\n this.memoryPlans.set(name, plan);\n }\n return plan;\n }\n codeVersion(name: string): number {\n return this.codeVersions.get(name) ?? 0;\n }\n private intersectsCodeRegion(\n region: JitCodeRegion,\n offset: number | undefined,\n size: number | undefined,\n ): boolean {\n if (offset === undefined || size === undefined) return true;\n return offset < region.size && offset + size > 0;\n }\n private hasCodeRegion(name: string, offset?: number, size?: number): boolean {\n for (const jit of this.jits) {\n if (!jit.active) continue;\n for (const region of jit.codeRegions)\n if (region.memory === name && this.intersectsCodeRegion(region, offset, size)) return true;\n }\n return false;\n }\n private addMetadataChange(state: JitMetadataRegion, change: JitCodeChange): void {\n const pending = state.pending;\n let end = change.offset + change.length;\n let start = change.offset;\n for (let index = 0; index < pending.length;) {\n const current = pending[index]!;\n const currentEnd = current.offset + current.length;\n if (change.offset <= currentEnd && current.offset <= end) {\n start = Math.min(start, current.offset);\n end = Math.max(end, currentEnd);\n pending.splice(index, 1);\n } else index++;\n }\n pending.push({ memory: change.memory, offset: start, length: end - start });\n }\n private markMetadataChanged(\n jit: Jit,\n name: string,\n offset: number | undefined,\n size: number | undefined,\n ): void {\n if (!jit.metadata) return;\n for (const state of jit.metadata.regions.values()) {\n const region = state.region;\n if (region.memory !== name) continue;\n // The first successful callback receives the whole region; no pending range is\n // needed before that (and none is available to merge into).\n if (state.appliedVersion === -1) continue;\n if (name === jit.options.code) {\n // Primary aliases may jump to each other in one direct program. Every primary\n // alias is revalidated before a direct build, even if the write did not intersect\n // that alias's logical window; changes still carry only the actual write range.\n state.dirty = true;\n }\n if (!this.intersectsCodeRegion(region, offset, size)) continue;\n state.dirty = true;\n const start = offset === undefined ? 0 : Math.max(0, offset);\n const end = offset === undefined ? region.size : Math.min(region.size, offset + (size ?? 0));\n if (end > start)\n this.addMetadataChange(state, { memory: name, offset: start, length: end - start });\n }\n }\n memoryChanged(name: string, offset?: number, size?: number): void {\n this.memoryChangedSlot(name, this.memoryPlan(name).slot, offset, size);\n }\n private memoryChangedPlan(\n plan: { name: string; slot: ResourceSlot },\n offset?: number,\n size?: number,\n ): void {\n this.memoryChangedSlot(plan.name, plan.slot, offset, size);\n }\n private memoryChangedSlot(\n name: string,\n slot: ResourceSlot,\n offset?: number,\n size?: number,\n ): void {\n this.board.invalidate(slot);\n // Data memories are never bound as code, so no JIT region, cache or metadata can care.\n if (!this.codeMemories.has(name)) return;\n if (this.hasCodeRegion(name, offset, size))\n this.codeVersions.set(name, this.codeVersion(name) + 1);\n for (const jit of this.jits) {\n let affected = false;\n for (const region of jit.codeRegions)\n if (region.memory === name && this.intersectsCodeRegion(region, offset, size)) {\n affected = true;\n break;\n }\n if (!affected) continue;\n this.markMetadataChanged(jit, name, offset, size);\n if (jit.options.code === name) {\n // Primary code keeps the exact legacy invalidation and active-instruction contract.\n jit.cache.clear();\n jit.cacheMemories.clear();\n jit.revision++;\n jit.directPrograms.clear();\n jit.directProgramRevision = -1;\n jit.directSkip = undefined;\n jit.directMisses.clear();\n if (jit.direct?.frame.resume) jit.direct.frame.stopAfterInstruction = true;\n else jit.direct = undefined;\n } else if (jit.cacheMemories.has(name)) {\n // Additional regions are conservatively invalidated as a whole. They never feed the\n // direct program, so Flash cache/direct/revision and the active frame stay untouched.\n for (const [pc, instruction] of jit.cache)\n if (instruction.codeRegion?.memory === name) jit.cache.delete(pc);\n jit.cacheMemories.delete(name);\n }\n }\n }\n /**\n * Handles for the fixed names a resumable process body uses. They live on the instance,\n * so a shared program text binds each instance (and each process frame) separately, and\n * every read still resolves the current sample or state value.\n */\n private bindResources(specs: readonly (readonly [string, string])[]): readonly ResourceHandle[] {\n const handles = new Array<ResourceHandle>(specs.length);\n for (let index = 0; index < specs.length; index++) {\n const spec = specs[index]!;\n const key = `${spec[0]}\\0${spec[1]}`;\n let handle = this.resourceHandles.get(key);\n if (handle === undefined) {\n handle = this.resourceHandle(spec[0], spec[1]);\n this.resourceHandles.set(key, handle);\n }\n handles[index] = handle;\n }\n return handles;\n }\n /**\n * Each method repeats the generic host operation exactly: dependency slots are still\n * recorded, state writes still snapshot, and memory stores still run the code-memory\n * invalidation that clears JIT caches. Every resource a declaration already provides is\n * resolved here, at bind time; a name that does not exist yet keeps resolving lazily so\n * it still fails at its first real use, not while binding.\n */\n private resourceHandle(kind: string, name: string): ResourceHandle {\n if (kind === 'pin') {\n let pin = this.pins.get(name);\n let slot = pin === undefined ? -1 : this.board.electricalSlot(pin);\n let sample = pin === undefined ? undefined : this.sampleResources.get(name)!;\n // One-entry cache for the constant resistance a body repeats on every execution.\n let lastResistance: unknown;\n let lastIntent: readonly ResistorBranch[] | undefined;\n const resolve = (): ElectricalPin => {\n if (pin === undefined) {\n pin = this.pin(name);\n slot = this.board.electricalSlot(pin);\n sample = this.sampleResources.get(name)!;\n }\n return pin;\n };\n return Object.freeze({\n sample: () => {\n const current = resolve();\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(sample!, sample!.version);\n return current.sample;\n },\n intent: (value: unknown) => {\n const current = resolve();\n if (current.intent === value) return;\n current.intent = value as readonly ResistorBranch[];\n this.board.markElectricalDirty(slot);\n },\n resistor: (resistance: unknown) => {\n // Device bodies pass a pinned resistance on every execution; repeating the same\n // argument reuses the frozen intent instead of resolving `(pin, resistance)` again.\n // The intent is checked as well: an empty cache starts at `undefined`, which must\n // still reach `electricalNumber` and fail like the generic host path.\n if (lastIntent !== undefined && resistance === lastResistance) return lastIntent;\n const r = electricalNumber(resistance);\n if (r < 0.001 || r > 1e9)\n throw new ElectricalParameterError('Resistance outside [0.001, 1e9]');\n const intent = this.resistorIntent(name, r);\n lastResistance = resistance;\n lastIntent = intent;\n return intent;\n },\n });\n }\n if (kind === 'state') {\n let slot: ResourceSlot | undefined = this.states.has(name)\n ? this.stateResources.get(name)!\n : undefined;\n // Direct-bank index of this state: -2 not probed yet (the bank appears with the first\n // direct program), -1 outside the scalar bank, otherwise the live value's index.\n let banked = slot === undefined ? -1 : (this.directBank?.states.get(name) ?? -2);\n const resolve = (): ResourceSlot => (slot ??= this.stateSlot(name));\n const states = this.states;\n return Object.freeze({\n read: () => {\n const current = resolve();\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(current, current.version);\n if (banked === -2) banked = this.directBank?.states.get(name) ?? -1;\n return banked < 0 ? states.get(name) : this.directBank!.stateValues[banked];\n },\n write: (value: unknown) => {\n const current = resolve();\n this.writeState(name, value, current);\n },\n });\n }\n let plan: { name: string; bytes: Uint8Array; view: DataView; slot: ResourceSlot } | undefined =\n this.memories.has(name) ? this.memoryPlan(name) : undefined;\n const resolve = (): NonNullable<typeof plan> => (plan ??= this.memoryPlan(name));\n const read = (size: number, little: boolean, offset: unknown): number => {\n const current = resolve();\n const at = range(current.bytes, offset, size);\n const dependencies = this.dependencies();\n if (dependencies) dependencies.set(current.slot, current.slot.version);\n return size === 1\n ? current.bytes[at]!\n : size === 2\n ? current.view.getUint16(at, little)\n : current.view.getUint32(at, little);\n };\n const write = (size: number, little: boolean, offset: unknown, value: unknown): void => {\n const current = resolve();\n const at = range(current.bytes, offset, size);\n const n = integer(value, 'stored value');\n if (size === 1) current.bytes[at] = n;\n else if (size === 2) current.view.setUint16(at, n, little);\n else current.view.setUint32(at, n, little);\n this.memoryChangedSlot(name, current.slot, at, size);\n };\n return Object.freeze({\n load8: (offset: unknown) => read(1, false, offset),\n load16le: (offset: unknown) => read(2, true, offset),\n load16be: (offset: unknown) => read(2, false, offset),\n load32le: (offset: unknown) => read(4, true, offset),\n load32be: (offset: unknown) => read(4, false, offset),\n store8: (offset: unknown, value: unknown) => write(1, false, offset, value),\n store16le: (offset: unknown, value: unknown) => write(2, true, offset, value),\n store16be: (offset: unknown, value: unknown) => write(2, false, offset, value),\n store32le: (offset: unknown, value: unknown) => write(4, true, offset, value),\n store32be: (offset: unknown, value: unknown) => write(4, false, offset, value),\n length: () => this.memory(name).length,\n copy: (offset: unknown, length: unknown) => {\n this.track(this.memoryResources, name);\n const bytes = this.memory(name),\n at = range(bytes, offset, length);\n return bytes.slice(at, at + Number(length));\n },\n });\n }\n prepare(): void {\n for (const declaration of this.entry.model.declarations)\n if (declaration.kind === 'pin')\n this.pins.set(declaration.name, {\n id: `${this.id}\\0${declaration.name}`,\n instance: this.id,\n name: declaration.name,\n intent: [],\n sample: { voltage: null, level: 'unknown', status: 'floating' },\n });\n for (const declaration of this.entry.model.declarations) {\n switch (declaration.kind) {\n case 'property':\n case 'const':\n this.read(declaration.kind, declaration.name);\n break;\n case 'state':\n this.states.set(declaration.name, snapshot(computation(declaration.initial, this.host)));\n break;\n case 'memory': {\n const length = nonnegative(computation(declaration.length, this.host), 'memory length');\n this.memorySizes.set(declaration.name, length);\n break;\n }\n case 'pin': {\n const pin = this.pins.get(declaration.name)!;\n if (declaration.low && declaration.high) {\n const low = electricalNumber(computation(declaration.low, this.host)),\n high = electricalNumber(computation(declaration.high, this.host));\n if (low >= high)\n throw new ElectricalParameterError('Pin thresholds must satisfy low < high');\n Object.assign(pin, { low, high });\n }\n if (declaration.initial)\n pin.intent = computation(declaration.initial, this.host) as readonly ResistorBranch[];\n break;\n }\n case 'channel': {\n const capacity = nonnegative(computation(declaration.capacity, this.host), 'capacity');\n if (capacity === 0) throw new RangeError('Capacity must be positive');\n let maxLength: number | undefined;\n if (declaration.maxLength) {\n maxLength = nonnegative(computation(declaration.maxLength, this.host), 'maxLength');\n if (maxLength === 0) throw new RangeError('maxLength must be positive');\n }\n this.channels.set(declaration.name, {\n declaration,\n capacity,\n ...(maxLength === undefined ? {} : { maxLength }),\n overflow: declaration.overflow\n ? String(computation(declaration.overflow, this.host))\n : 'drop_new',\n incoming: new Fifo(),\n pending: new Fifo(),\n outgoing: new Fifo(),\n });\n break;\n }\n case 'notification':\n if (declaration.direction === 'output')\n this.notificationOutputs.set(declaration.name, null);\n break;\n case 'start':\n case 'on':\n this.processes.push({\n instance: this,\n declaration,\n resumable: resumable(declaration.body),\n ...(declaration.kind === 'on' ? { source: declaration.sourcePath } : {}),\n state: 'idle',\n pending: false,\n });\n break;\n case 'reaction':\n this.reactions.push({\n instance: this,\n declaration,\n previous: undefined,\n synchronousProgram: synchronousBody(this, declaration.body) ?? null,\n frame: undefined,\n });\n break;\n }\n }\n // Preserve the batch key order: output channels, then output notifications.\n for (const [name, channel] of this.channels) {\n if (channel.declaration.direction === 'input') this.batchInputs.push(channel);\n else {\n this.batchOutputs.push([name, channel]);\n this.emptyOutputs[name] = EMPTY_MESSAGES;\n }\n }\n for (const name of this.notificationOutputs.keys()) {\n this.batchNotifications.push(name);\n this.emptyOutputs[name] = null;\n }\n Object.freeze(this.emptyOutputs);\n }\n captureBatch(from: number, to: number): DeviceBatch {\n for (const channel of this.batchInputs) if (channel.incoming.length) channel.incoming.clear();\n let outputs = this.emptyOutputs;\n for (const [name, channel] of this.batchOutputs) {\n if (!channel.outgoing.length) continue;\n if (outputs === this.emptyOutputs)\n outputs = Object.assign(Object.create(null), this.emptyOutputs);\n outputs[name] = Object.freeze(\n channel.outgoing\n .drain()\n .map((message) =>\n Object.freeze({ time: message.time, value: externalValue(message.value) }),\n ),\n );\n }\n for (const name of this.batchNotifications) {\n const notified = this.notificationOutputs.get(name)!;\n if (notified === null) continue;\n if (outputs === this.emptyOutputs)\n outputs = Object.assign(Object.create(null), this.emptyOutputs);\n outputs[name] = Object.freeze({ time: notified });\n this.notificationOutputs.set(name, null);\n }\n return Object.freeze({\n from,\n to,\n outputs: outputs === this.emptyOutputs ? outputs : Object.freeze(outputs),\n });\n }\n assertCreation(): void {\n for (const declaration of this.entry.model.declarations) {\n if (declaration.kind !== 'assert') continue;\n const step = body(declaration.body)(this.host).next();\n if (!step.done) throw new TypeError('Creation assertion suspended');\n }\n }\n allocate(): void {\n for (const [name, length] of this.memorySizes) {\n const bytes = new Uint8Array(length);\n this.memories.set(name, bytes);\n this.memoryViews.set(name, new DataView(bytes.buffer));\n }\n this.memorySizes.clear();\n }\n assertCallAllowed(): void {\n this.board.assertCallAllowed(this);\n }\n inputs(): Record<string, unknown> {\n const result: Record<string, unknown> = Object.create(null);\n for (const declaration of this.entry.model.declarations) {\n if (declaration.kind === 'channel' && declaration.direction === 'input')\n result[declaration.name] = Object.freeze({\n send: (value: unknown) => {\n this.assertCallAllowed();\n this.send(declaration.name, value, true);\n },\n });\n if (declaration.kind === 'notification' && declaration.direction === 'input')\n result[declaration.name] = Object.freeze({\n notify: () => {\n this.assertCallAllowed();\n this.notificationInputs.add(declaration.name);\n },\n });\n }\n return Object.freeze(result);\n }\n publicMemory(): Record<string, unknown> {\n const result: Record<string, unknown> = Object.create(null);\n for (const declaration of this.entry.model.declarations)\n if (declaration.kind === 'memory' && declaration.public)\n result[declaration.name] = bytesView(this.memory(declaration.name), () => {\n this.board.assertAlive(this);\n if (!['idle', 'initialize', 'sync'].includes(this.board.phase))\n throw this.board.error(\n 'INVALID_CALL_STATE',\n 'Memory cannot be borrowed in this phase',\n this,\n );\n if (this.board.phase === 'initialize' && this.board.current !== this)\n throw this.board.error('INVALID_CALL_STATE', 'Another factory is initializing', this);\n });\n return Object.freeze(result);\n }\n send(name: string, value: unknown, input: boolean): void {\n const channel = this.channels.get(name);\n if (!channel || channel.declaration.direction !== (input ? 'input' : 'output'))\n throw new TypeError(`Unknown channel ${name}`);\n const captured = captureValue(channel.declaration.type, value, this.declarations);\n if (channel.maxLength !== undefined && (captured as Uint8Array).length > channel.maxLength)\n throw new RangeError('Message exceeds maxLength');\n const queue = input ? channel.pending : channel.outgoing;\n if (queue.length === channel.capacity) {\n if (channel.overflow === 'drop_new') return;\n if (channel.overflow === 'error') {\n const error = this.board.error('CHANNEL_OVERFLOW', `Channel ${name} overflow`, this);\n this.board.fault(error);\n throw error;\n }\n queue.shift();\n }\n queue.push({ time: this.board.time, value: captured });\n }\n private captureCodeRegions(options: JitOptions): {\n readonly all: readonly JitCodeRegion[];\n readonly additional: readonly JitCodeRegion[];\n } {\n const primaryMemory = this.memories.get(options.code)!;\n const primary = Object.freeze({\n memory: options.code,\n base: 0,\n size: primaryMemory.length,\n });\n const additional: JitCodeRegion[] = [];\n if (Object.hasOwn(options, 'codeRegions')) {\n if (!Array.isArray(options.codeRegions)) throw new TypeError('codeRegions must be an array');\n for (const item of options.codeRegions) {\n dataObject(item, ['memory', 'base', 'size']);\n const memory = identity(item.memory);\n const base = nonnegative(item.base, 'code region base');\n const size = nonnegative(item.size, 'code region size');\n if (size === 0) throw new RangeError('Code region size must be positive');\n const length = this.memories.get(memory)?.length;\n if (length === undefined)\n throw this.board.error('INVALID_BINDING', 'Unknown code region memory', this);\n if (size > length)\n throw this.board.error('INVALID_BINDING', 'Code region exceeds memory', this);\n if (base > Number.MAX_SAFE_INTEGER - size)\n throw this.board.error(\n 'INVALID_BINDING',\n 'Code region range is not a safe integer',\n this,\n );\n const region = Object.freeze({ memory, base, size });\n for (const existing of [primary, ...additional]) {\n if (\n region.base < existing.base + existing.size &&\n existing.base < region.base + region.size\n )\n throw this.board.error('INVALID_BINDING', 'Code regions overlap', this);\n }\n additional.push(region);\n }\n }\n return {\n all: Object.freeze([primary, ...additional]),\n additional: Object.freeze(additional),\n };\n }\n private capturePolling(items: unknown, region?: JitCodeRegion): Map<number, JitPollingBinding> {\n const polling = new Map<number, JitPollingBinding>();\n if (!Array.isArray(items)) throw new TypeError('polling must be an array');\n for (const item of items) {\n dataObject(item, ['pc', 'predicate', 'consume', 'wait']);\n const pc = finite(item.pc, 'polling pc');\n if (region !== undefined && (pc < region.base || pc >= region.base + region.size))\n throw this.board.error('INVALID_BINDING', 'Polling pc is outside its code region', this);\n const predicate = identity(item.predicate);\n const declaration = this.declarations.get(predicate);\n if (\n polling.has(pc) ||\n declaration?.kind !== 'function' ||\n !declaration.pure ||\n declaration.params.length ||\n declaration.returns?.kind !== 'bool'\n )\n throw this.board.error('INVALID_BINDING', 'Invalid polling declaration', this);\n let consume: string | undefined;\n if (Object.hasOwn(item, 'consume')) {\n consume = identity(item.consume);\n const fn = this.declarations.get(consume);\n if (fn?.kind !== 'function' || fn.params.length !== 0 || fn.returns !== undefined)\n throw this.board.error('INVALID_BINDING', 'Invalid polling consume function', this);\n }\n let wait: JitPollingBinding['wait'];\n if (Object.hasOwn(item, 'wait')) {\n dataObject(item.wait, ['delay', 'advance']);\n const delay = identity(item.wait.delay);\n const advance = identity(item.wait.advance);\n const delayFn = this.declarations.get(delay);\n const advanceFn = this.declarations.get(advance);\n if (\n delayFn?.kind !== 'function' ||\n !delayFn.pure ||\n delayFn.params.length !== 0 ||\n delayFn.returns?.kind !== 'number' ||\n advanceFn?.kind !== 'function' ||\n advanceFn.params.length !== 1 ||\n advanceFn.params[0]!.type.kind !== 'number' ||\n advanceFn.returns !== undefined\n )\n throw this.board.error('INVALID_BINDING', 'Invalid polling wait functions', this);\n wait = Object.freeze({ delay, advance });\n }\n polling.set(\n pc,\n Object.freeze({\n predicate,\n ...(consume === undefined ? {} : { consume }),\n ...(wait === undefined ? {} : { wait }),\n }),\n );\n }\n return polling;\n }\n private captureMetadataDelays(value: unknown, region: JitCodeRegion): Map<number, JitDelay> {\n if (!(value instanceof Map)) throw new TypeError('codeMetadata delays must be a Map');\n const delays = new Map<number, JitDelay>();\n for (const [key, item] of value) {\n const pc = finite(key, 'delay pc');\n if (pc < region.base || pc >= region.base + region.size)\n throw this.board.error('INVALID_BINDING', 'Delay pc is outside its code region', this);\n dataObject(item, ['counter', 'cycles', 'pending']);\n const counter = identity(item.counter);\n const cycles = integer(item.cycles, 'delay cycles');\n if (cycles <= 0) throw new RangeError('Delay cycles must be positive');\n let pending:\n | {\n readonly state: string;\n readonly period: string;\n readonly active: string;\n }\n | undefined;\n if (Object.hasOwn(item, 'pending')) {\n dataObject(item.pending, ['state', 'period', 'active']);\n pending = Object.freeze({\n state: identity(item.pending.state),\n period: identity(item.pending.period),\n active: identity(item.pending.active),\n });\n }\n delays.set(pc, Object.freeze({ counter, cycles, ...(pending ? { pending } : {}) }));\n }\n return delays;\n }\n /** Validate and copy provider output; caller applies it atomically. */\n captureCodeMetadata(\n region: JitCodeRegion,\n value: unknown,\n ): {\n readonly polling: Map<number, JitPollingBinding>;\n readonly delays: Map<number, JitDelay>;\n } {\n dataObject(value, ['polling', 'delays']);\n if (!Object.hasOwn(value, 'polling') || !Object.hasOwn(value, 'delays'))\n throw new TypeError('codeMetadata must contain polling and delays');\n return {\n polling: this.capturePolling(value.polling, region),\n delays: this.captureMetadataDelays(value.delays, region),\n };\n }\n attach(options: JitOptions): Disposable {\n this.assertCallAllowed();\n if (this.board.phase !== 'initialize' || this.board.current !== this)\n throw this.board.error('INVALID_CALL_STATE', 'attachJit is initialization-only', this);\n dataObject(options, [\n 'entry',\n 'code',\n 'codeRegions',\n 'codeMetadata',\n 'pc',\n 'functions',\n 'beforeInstruction',\n 'polling',\n 'delays',\n 'translate',\n ]);\n identity(options.entry);\n identity(options.code);\n identity(options.pc);\n if (this.jits.some((jit) => jit.active && jit.options.entry === options.entry))\n throw this.board.error('INVALID_BINDING', 'Duplicate JIT entry', this);\n if (\n !this.memories.has(options.code) ||\n this.declarations.get(options.pc)?.kind !== 'state' ||\n (this.declarations.get(options.pc) as Decl<'state'>).type.kind !== 'number' ||\n typeof options.translate !== 'function'\n )\n throw this.board.error('INVALID_BINDING', 'Invalid JIT binding', this);\n const codeRegions = this.captureCodeRegions(options);\n if (Object.hasOwn(options, 'codeMetadata')) {\n if (typeof options.codeMetadata !== 'function')\n throw this.board.error('INVALID_BINDING', 'Invalid codeMetadata provider', this);\n if (Object.hasOwn(options, 'polling') || Object.hasOwn(options, 'delays'))\n throw this.board.error(\n 'INVALID_BINDING',\n 'codeMetadata is mutually exclusive with static polling/delays',\n this,\n );\n }\n if (options.beforeInstruction !== undefined) {\n dataObject(options.beforeInstruction, ['when', 'call']);\n const condition = this.declarations.get(options.beforeInstruction.when),\n fn = this.declarations.get(options.beforeInstruction.call);\n if (\n !condition ||\n !['state', 'derived'].includes(condition.kind) ||\n !('type' in condition) ||\n condition.type.kind !== 'bool' ||\n fn?.kind !== 'function' ||\n fn.params.length ||\n fn.returns\n )\n throw this.board.error('INVALID_BINDING', 'Invalid instruction hook', this);\n } else if (Object.hasOwn(options, 'beforeInstruction'))\n throw new TypeError('Invalid beforeInstruction');\n const polling = Object.hasOwn(options, 'polling')\n ? this.capturePolling(options.polling)\n : new Map<number, JitPollingBinding>();\n if (Object.hasOwn(options, 'delays') && !(options.delays instanceof Map))\n throw new TypeError('delays must be a Map');\n const metadata = Object.hasOwn(options, 'codeMetadata')\n ? {\n regions: new Map(\n codeRegions.all.map((region) => [\n region,\n {\n region,\n appliedVersion: -1,\n dirty: false,\n pending: [] as JitCodeChange[],\n polling: new Map<number, JitPollingBinding>(),\n delays: new Map<number, JitDelay>(),\n },\n ]),\n ),\n polling: new Map<number, JitPollingBinding>(),\n delays: new Map<number, JitDelay>(),\n }\n : undefined;\n const base = this.entry.model;\n const emit = options.functions;\n if (Object.hasOwn(options, 'functions') && typeof emit !== 'function')\n throw new TypeError('functions must be a JIT function builder callback');\n let model = base;\n let functions: Map<string, Decl<'function'>> | undefined;\n let host = this.host;\n if (emit) {\n const declarations = emit(base);\n acceptSync(declarations);\n if (!Array.isArray(declarations)) throw new TypeError('Expected JIT function declarations');\n model = bindJitFunctions(base, declarations);\n const local = new Map<string, Decl<'function'>>();\n for (const declaration of model.declarations.slice(base.declarations.length))\n if (declaration.kind === 'function') local.set(declaration.name, declaration);\n functions = local;\n host = {\n ...this.host,\n call: (name, args) => {\n const fn = local.get(name);\n return fn ? body(fn.body)(host, args) : this.invoke(name, args);\n },\n };\n }\n const jit: Jit = {\n instance: this,\n model,\n host,\n ...(functions === undefined ? {} : { functions }),\n options: Object.freeze({\n ...options,\n ...(options.codeRegions === undefined ? {} : { codeRegions: codeRegions.additional }),\n ...(options.beforeInstruction\n ? { beforeInstruction: Object.freeze({ ...options.beforeInstruction }) }\n : {}),\n }),\n codeRegions: codeRegions.all,\n cache: new Map(),\n cacheMemories: new Set(),\n metadata,\n polling,\n delays: options.delays ?? new Map(),\n revision: 0,\n directRevision: -1,\n directObserverRevision: -1,\n directStateGuards: new Set(),\n directMemoryGuards: new Set(),\n directHookReads: new Set(),\n directPrograms: new Map(),\n directProgramRevision: -1,\n direct: undefined,\n directSkip: undefined,\n directMisses: new Map(),\n pollReads: undefined,\n currentPc: undefined,\n automaticPolling: false,\n pollingWait: false,\n pollingPeriod: 0,\n pollingOrigin: 0,\n pollingToken: 0,\n dependencyDirty: true,\n waiterSlots: undefined,\n active: true,\n stopped: false,\n queued: false,\n execution: undefined,\n };\n this.jits.push(jit);\n this.board.jits.push(jit);\n for (const region of jit.codeRegions) this.codeMemories.add(region.memory);\n const disposable = {\n dispose: () => {\n if (!jit.active) return;\n jit.active = false;\n jit.execution = undefined;\n delete jit.predicate;\n jit.pollingToken++;\n this.board.unparkWaiter(jit);\n jit.cache.clear();\n jit.cacheMemories.clear();\n jit.directPrograms.clear();\n jit.direct = undefined;\n jit.directMisses.clear();\n jit.pollReads = undefined;\n },\n };\n this.resources.push(disposable);\n return disposable;\n }\n loadBytes(name: string, bytes: Uint8Array, offset: unknown): void {\n this.assertCallAllowed();\n if (\n this.board.phase !== 'idle' &&\n !(this.board.phase === 'initialize' && this.board.current === this)\n )\n throw this.board.error(\n 'INVALID_CALL_STATE',\n 'Code loading is not allowed in this phase',\n this,\n );\n if (\n typeof name !== 'string' ||\n !this.jits.some(\n (jit) => jit.active && jit.codeRegions.some((region) => region.memory === name),\n )\n )\n throw this.board.error('INVALID_BINDING', 'Memory is not bound as code', this);\n if (!(bytes instanceof Uint8Array)) throw new TypeError('Code must be Uint8Array');\n const memory = this.memory(name),\n at = range(memory, offset, bytes.length);\n if (bytes.length) {\n memory.set(bytes.slice(), at);\n this.memoryChanged(name, at, bytes.length);\n }\n }\n source(path: readonly string[]): unknown {\n const declaration = this.declarations.get(path[0]!);\n let value: unknown;\n let firstField = 1;\n if (declaration?.kind === 'pin') {\n this.track(this.sampleResources, declaration.name);\n if (path[1] !== 'sample') throw new TypeError(`Invalid source ${path.join('.')}`);\n value = this.pin(declaration.name).sample;\n firstField = 2;\n } else if (declaration?.kind === 'state' || declaration?.kind === 'derived')\n value = this.read(declaration.kind, declaration.name);\n else throw new TypeError(`Invalid source ${path.join('.')}`);\n for (let index = firstField; index < path.length; index++)\n value = (value as Record<string, unknown>)[path[index]!];\n return value;\n }\n}\n","import type { TopicBridge } from '../types';\n\n/**\n * Facts the adapter layer needs about a bridge, kept off the public `TopicBridge` contract.\n *\n * A bridge's `publish` both delivers and enforces the board's call admission (alive, phase,\n * faulted). A caller that decides nobody would receive a message still has to run that\n * admission, and it has to know whether any owner-less listener exists. Both are internal to\n * this package: device adapters and hosts act through `onDidReceive` and `publish` only.\n */\nexport interface PublishGate {\n /** The same admission `publish` runs first, without copying, freezing or dispatching. */\n assertPublishAllowed(): void;\n /** Owner-less listeners of the shared dispatch set: the host's direct subscriptions. */\n hostListeners(): number;\n}\n\nconst gates = new WeakMap<object, PublishGate>();\n\n/** Attach the gate to the facade the board hands out; never exposed through the package entry. */\nexport function registerPublishGate(bridge: object, gate: PublishGate): void {\n gates.set(bridge, gate);\n}\n\nexport function publishGate(bridge: TopicBridge): PublishGate {\n const gate = gates.get(bridge);\n if (gate === undefined) throw new TypeError('Topic bridge was not created by a board');\n return gate;\n}\n","import type { OperationIR, RegionIR } from '@mica-js/device-model';\n\nexport function isPollingInstruction(body: RegionIR, pc: number, pcName: string): boolean {\n const definitions = new Map<number, OperationIR>();\n const redirects: number[] = [];\n const visit = (region: RegionIR): boolean => {\n for (const operation of region.operations) {\n if ('result' in operation) definitions.set(operation.result, operation);\n switch (operation.kind) {\n case 'constant':\n case 'unary':\n case 'binary':\n case 'numeric':\n case 'field':\n case 'length':\n case 'index':\n case 'isNone':\n case 'nonNull':\n case 'optional':\n case 'local':\n case 'localRead':\n case 'localWrite':\n case 'memoryLength':\n case 'load8':\n case 'load16le':\n case 'load16be':\n case 'load32le':\n case 'load32be':\n case 'readSample':\n case 'yield':\n break;\n case 'read':\n if (operation.resource === 'derived' || operation.name === pcName) return false;\n break;\n case 'if':\n if (!visit(operation.yes) || (operation.no && !visit(operation.no))) return false;\n break;\n case 'select':\n if (!visit(operation.yes.body) || !visit(operation.no.body)) return false;\n break;\n case 'and':\n case 'or':\n if (!visit(operation.right.body)) return false;\n break;\n case 'match':\n if (\n operation.arms.some((arm) => !visit(arm.body)) ||\n (operation.otherwise && !visit(operation.otherwise))\n )\n return false;\n break;\n case 'redirect':\n redirects.push(operation.target);\n break;\n default:\n return false;\n }\n }\n return true;\n };\n if (!visit(body)) return false;\n return redirects.some((target) => {\n const definition = definitions.get(target);\n return (\n definition?.kind !== 'constant' ||\n (definition.constant.kind === 'number' && definition.constant.value === pc)\n );\n });\n}\n","import {\n compileDirectJit,\n type DirectJitFrame,\n type DirectJitHost,\n type DirectJitProgram,\n type ExecutionSignal,\n} from '@mica-js/compiler';\nimport { createJitBlockBuilder, validateBoundBlockIR } from '@mica-js/device-model';\nimport { isPollingInstruction } from '../polling';\nimport type { EventQueue } from '../queue';\nimport { acceptSync } from './errors';\nimport { body, time } from './execution';\nimport type { Instance, InstanceBoard } from './instance';\nimport type {\n Dependencies,\n DirectJitLayout,\n Jit,\n JitInstruction,\n JitMetadataRegion,\n JitPollingBinding,\n} from './state';\nimport type {\n JitCodeChange,\n JitCodeMetadataInput,\n JitCodeRegion,\n JitCodeRegionView,\n JitDelay,\n RuntimeDiagnosticCode,\n RuntimePhase,\n SimulationError,\n} from '../types';\nimport { bytesView, finite } from '../values';\n\n/** Large programs dispatch through shards; small ones stay on the faster monolithic form. */\nconst DIRECT_SHARD_SIZE = 32;\n\nexport function syncJitCall(jit: Jit, name: string): unknown {\n const step = jit.host.call(name, []).next();\n if (!step.done) throw new TypeError('Unexpected suspension in synchronous function');\n return step.value;\n}\n/**\n * Program size above which whole-program rebuilds are amortized instead of immediate.\n *\n * Translation only ever adds cache entries, so a compiled program stays valid for every PC it\n * already contains; only a missing PC needs a rebuild. Rebuilding on every new block is\n * quadratic, and that dominated warm-up on a real firmware image (411 blocks: 43 rebuilds and\n * ~1.7 s before any simulated time). Small programs rebuild in milliseconds, so they keep the\n * exact behaviour; only larger ones switch to a stride that grows with the program.\n */\nconst DIRECT_REBUILD_LINEAR_LIMIT = 16;\n/** Stride floor once a program exceeds `DIRECT_REBUILD_LINEAR_LIMIT`. */\nconst DIRECT_REBUILD_MIN_BLOCKS = 64;\n/** A repeatedly visited translated PC can force a rebuild before the append-only stride. */\nconst DIRECT_REBUILD_PATIENCE = 4;\n\nfunction directRebuildStride(compiled: number): number {\n return compiled < DIRECT_REBUILD_LINEAR_LIMIT ? 1 : Math.max(DIRECT_REBUILD_MIN_BLOCKS, compiled);\n}\n\n/** Call sites that settle a publication boundary; used only by opt-in diagnostics. */\nexport type BoundarySource =\n | 'checkpointPublish'\n | 'checkpointFinish'\n | 'jitSignal'\n | 'runJit'\n | 'runDirect'\n | 'polling'\n | 'process'\n | 'other';\n\n/**\n * Deterministic direct-execution counters, kept on the `Jit` itself so `Board.jits` stays the\n * only diagnostic surface: the benchmark reads them instead of patching runtime internals.\n */\nexport interface DirectJitStats {\n /** Successful program builds; one per compile, so observer churn must not move it. */\n directCompiles: number;\n /** Resident shard functions backing the current direct program. */\n directShards: number;\n directCalls: number;\n directFallbacks: number;\n directDeadlines: number;\n directStopped: number;\n}\n\n/**\n * Opt-in checkpoint counters. They live beside `directStats` so diagnostic hosts that\n * pre-install the legacy `directStats` shape keep paying nothing for these measurements.\n */\nexport interface DirectCheckpointStats {\n /** `publishCheckpoint` entries. */\n publications: number;\n /** `finishCheckpoint` entries. */\n finishes: number;\n /** Finish entries whose suffix only advanced time. */\n emptySuffixes: number;\n /** Boundary settlements requested by either checkpoint. */\n boundaryCalls: number;\n /** Checkpoints that returned true and stayed in Direct execution. */\n continues: number;\n /** Checkpoints that returned false and handed control back to the scheduler. */\n exits: number;\n}\n\nconst checkpointStatsByJit = new WeakMap<Jit, DirectCheckpointStats>();\n\n/** Create the opt-in checkpoint counters once, on the first instrumented Direct frame. */\nexport function directCheckpointStats(jit: Jit): DirectCheckpointStats {\n let stats = checkpointStatsByJit.get(jit);\n if (stats === undefined) {\n stats = {\n publications: 0,\n finishes: 0,\n emptySuffixes: 0,\n boundaryCalls: 0,\n continues: 0,\n exits: 0,\n };\n checkpointStatsByJit.set(jit, stats);\n }\n return stats;\n}\n\n/** Read counters without creating them; undefined means diagnostics stayed off. */\nexport function readDirectCheckpointStats(jit: Jit): DirectCheckpointStats | undefined {\n return checkpointStatsByJit.get(jit);\n}\n\ntype CountedJit = Jit & { directStats?: DirectJitStats };\n\n/** Word masks written by compiled blocks to trigger instruction-boundary publication. */\ninterface DirectBarriers {\n stateMask: Int32Array;\n memoryMask: Int32Array;\n /** Bank layout of the current program; absent until one has been compiled. */\n stateIndex?: ReadonlyMap<string, number>;\n memoryIndex?: ReadonlyMap<string, number>;\n}\n\n/** Frame fields `compileDirectJit` reads but `DirectJitFrame` does not declare. */\ninterface BarrierFrame extends DirectJitFrame {\n blockedStates?: Int32Array;\n blockedMemories?: Int32Array;\n}\n\nconst barriers = new WeakMap<Jit, DirectBarriers>();\n\nfunction directBarriers(jit: Jit): DirectBarriers {\n let entry = barriers.get(jit);\n if (entry === undefined) {\n entry = { stateMask: new Int32Array(0), memoryMask: new Int32Array(0) };\n barriers.set(jit, entry);\n }\n return entry;\n}\n\nfunction directStats(jit: Jit): DirectJitStats {\n const counted = jit as CountedJit;\n return (counted.directStats ??= {\n directCompiles: 0,\n directShards: 0,\n directCalls: 0,\n directFallbacks: 0,\n directDeadlines: 0,\n directStopped: 0,\n });\n}\n\n/** Direct execution counters of one JIT; absent until the runtime attempted a direct run. */\nexport function directJitStats(jit: Jit): DirectJitStats | undefined {\n return (jit as CountedJit).directStats;\n}\n\n/** Region that supplies bytes for a logical PC; undefined means the service-PC fallback. */\nfunction codeRegionFor(jit: Jit, pc: number): JitCodeRegion | undefined {\n for (const region of jit.codeRegions)\n if (pc >= region.base && pc < region.base + region.size) return region;\n return undefined;\n}\n\n/** Additional regions stay on the interpreter; only the primary memory feeds direct programs. */\nfunction directCodeInstruction(jit: Jit, instruction: JitInstruction): boolean {\n const region = instruction.codeRegion;\n return region === undefined || region.memory === jit.options.code;\n}\n\nfunction effectivePolling(jit: Jit): ReadonlyMap<number, JitPollingBinding> {\n return jit.metadata?.polling ?? jit.polling;\n}\n\nfunction effectiveDelays(jit: Jit): ReadonlyMap<number, JitDelay> {\n return jit.metadata?.delays ?? jit.delays;\n}\n\n/** Aliases of the primary memory must refresh together before a direct program is built. */\nfunction primaryCodeRegions(jit: Jit): readonly JitCodeRegion[] {\n return jit.codeRegions.filter((region) => region.memory === jit.options.code);\n}\n\n/**\n * Lazily (re)build code-derived metadata for the requested regions. Provider calls never\n * happen from attach/store; this runs inside the translate phase immediately before the\n * polling/direct/translate decision that needs it.\n */\nfunction ensureMetadata(board: JitRuntimeHost, jit: Jit, regions: readonly JitCodeRegion[]): void {\n const metadata = jit.metadata;\n const provider = jit.options.codeMetadata;\n if (metadata === undefined || provider === undefined) return;\n const needed: {\n readonly state: JitMetadataRegion;\n readonly changes: readonly JitCodeChange[];\n readonly version: number;\n }[] = [];\n const seen = new Set<JitMetadataRegion>();\n for (const region of regions) {\n const state = metadata.regions.get(region);\n if (state === undefined || seen.has(state)) continue;\n seen.add(state);\n const version = jit.instance.codeVersion(region.memory);\n if (state.appliedVersion === version && state.pending.length === 0 && !state.dirty) continue;\n const changes =\n state.appliedVersion === -1\n ? [\n Object.freeze({\n memory: region.memory,\n offset: 0,\n length: region.size,\n }),\n ]\n : state.pending.map((change) => Object.freeze({ ...change }));\n needed.push({ state, changes, version });\n }\n if (needed.length === 0) return;\n\n const prior = board.phase;\n board.phase = 'translate';\n const prepared: {\n readonly state: JitMetadataRegion;\n readonly version: number;\n readonly polling: Map<number, JitPollingBinding>;\n readonly delays: Map<number, JitDelay>;\n }[] = [];\n try {\n for (const item of needed) {\n const { region } = item.state;\n const memory = jit.instance.memory(region.memory);\n const bytes = region.size >= memory.length ? memory : memory.subarray(0, region.size);\n let valid = true;\n try {\n const code = bytesView(bytes, () => {\n if (!valid) throw board.error('OBJECT_DISPOSED', 'Metadata view expired', jit.instance);\n });\n const view: JitCodeRegionView = Object.freeze({\n memory: region.memory,\n base: region.base,\n size: region.size,\n codeVersion: item.version,\n code: code as import('../types').BorrowedBytes,\n });\n const input: JitCodeMetadataInput = Object.freeze({\n region: view,\n changes: Object.freeze(item.changes.slice()),\n });\n const result = provider(input);\n acceptSync(result);\n const captured = jit.instance.captureCodeMetadata(region, result);\n prepared.push({\n state: item.state,\n version: item.version,\n polling: captured.polling,\n delays: captured.delays,\n });\n } finally {\n valid = false;\n }\n }\n // Nothing from the provider is visible until every requested region validated.\n let primary = false;\n for (const item of prepared) {\n item.state.appliedVersion = item.version;\n item.state.dirty = false;\n item.state.pending.length = 0;\n item.state.polling.clear();\n for (const [pc, binding] of item.polling) item.state.polling.set(pc, binding);\n item.state.delays.clear();\n for (const [pc, delay] of item.delays) item.state.delays.set(pc, delay);\n if (item.state.region.memory === jit.options.code) primary = true;\n }\n metadata.polling.clear();\n metadata.delays.clear();\n for (const state of metadata.regions.values()) {\n for (const [pc, binding] of state.polling) metadata.polling.set(pc, binding);\n for (const [pc, delay] of state.delays) metadata.delays.set(pc, delay);\n }\n if (primary) {\n jit.directPrograms.clear();\n jit.directProgramRevision = -1;\n jit.directSkip = undefined;\n if (!jit.direct?.frame.resume) {\n jit.direct = undefined;\n jit.directRevision = -1;\n }\n }\n } catch (cause) {\n throw board.wrap(cause, 'JIT_FAILED', 'translate', jit.instance);\n } finally {\n board.phase = prior;\n }\n}\n\nfunction ensureMetadataForPc(board: JitRuntimeHost, jit: Jit, pc: number): void {\n if (jit.metadata === undefined) return;\n const region = codeRegionFor(jit, pc) ?? jit.codeRegions[0]!;\n const needed = [region];\n // Direct programs may include every primary alias; refresh all of their delays together.\n if (\n board.execution === 'throughput' &&\n board.jits.length === 1 &&\n region.memory === jit.options.code\n )\n needed.push(...primaryCodeRegions(jit));\n ensureMetadata(board, jit, needed);\n}\n\n/** Publish the current subscriber sets into the masks the compiled blocks test on writes. */\nfunction syncDirectBarriers(jit: Jit): void {\n const entry = directBarriers(jit);\n const { stateIndex, memoryIndex } = entry;\n if (stateIndex === undefined || memoryIndex === undefined) return;\n const fill = (\n mask: Int32Array,\n index: ReadonlyMap<string, number>,\n guards: ReadonlySet<string>,\n ): void => {\n mask.fill(0);\n for (const name of guards) {\n const slot = index.get(name);\n if (slot === undefined) continue;\n mask[slot >>> 5] = (mask[slot >>> 5] ?? 0) | (1 << (slot & 31));\n }\n };\n fill(entry.stateMask, stateIndex, jit.directStateGuards);\n fill(entry.memoryMask, memoryIndex, jit.directMemoryGuards);\n}\n\n/** Scheduling capabilities needed by JIT execution; all queues remain board-owned. */\nexport interface JitRuntimeHost extends Pick<InstanceBoard, 'error'> {\n time: number;\n phase: string;\n current: Instance | undefined;\n readonly execution: 'throughput' | 'precise';\n readonly executionEnd: number;\n readonly jits: readonly Jit[];\n readonly waitingJits: Set<Jit>;\n /** Parks a JIT on its recorded dependency versions; the next round scans it once. */\n parkWaiter(jit: Jit): void;\n /** Wakes or drops a parked JIT and removes its dependency registrations. */\n unparkWaiter(jit: Jit): void;\n readonly events: Pick<EventQueue<() => void>, 'time' | 'push'>;\n readonly checkpointDiagnostics: boolean;\n boundary(source?: BoundarySource): void;\n canContinueDirect(jit: Jit, horizon: number): boolean;\n queueJit(jit: Jit): void;\n wrap(\n cause: unknown,\n code: RuntimeDiagnosticCode,\n phase: RuntimePhase,\n instance?: Instance,\n ): SimulationError;\n}\n\n/** Settle one checkpoint boundary and attribute it to its source when diagnostics are on. */\nfunction checkpointBoundary(\n board: JitRuntimeHost,\n stats: DirectCheckpointStats | undefined,\n source: 'checkpointPublish' | 'checkpointFinish',\n): void {\n if (stats !== undefined) stats.boundaryCalls++;\n board.boundary(source);\n}\n\n/** Reverse-map the hook's resource slots; slot values are not bank indices. */\nfunction entryBlockedNames(jit: Jit): {\n readonly states: ReadonlySet<string>;\n readonly memories: ReadonlySet<string>;\n} {\n const states = new Set<string>();\n const memories = new Set<string>([jit.options.code]);\n const instance = jit.instance;\n for (const [name, slot] of instance.stateResources)\n if (jit.directHookReads.has(slot)) states.add(name);\n for (const [name, slot] of instance.memoryResources)\n if (jit.directHookReads.has(slot)) memories.add(name);\n return { states, memories };\n}\n\nfunction refreshDirectGuards(jit: Jit, hookReads?: Dependencies): void {\n let observersChanged = false;\n let entryChanged = false;\n const instance = jit.instance;\n const hookCount = jit.directHookReads.size;\n if (hookReads) {\n for (const slot of hookReads.keys()) {\n if (jit.directHookReads.has(slot)) continue;\n jit.directHookReads.add(slot);\n // Entry blocks are compiled against the hook's current state/memory dependencies.\n // A newly discovered dependency must rebuild instead of running an old block, while\n // pin/sample reads need no entry change.\n let resource = false;\n for (const candidate of instance.stateResources.values())\n if (candidate === slot) {\n resource = true;\n break;\n }\n if (!resource)\n for (const candidate of instance.memoryResources.values())\n if (candidate === slot) {\n resource = true;\n break;\n }\n if (resource) entryChanged = true;\n }\n }\n if (\n jit.directObserverRevision === instance.observerRevision &&\n hookCount === jit.directHookReads.size &&\n !entryChanged\n )\n return;\n jit.directObserverRevision = instance.observerRevision;\n for (const [name, slot] of instance.stateResources) {\n // Hook reads are entry barriers; only ordinary subscribers publish dynamically.\n const blocked = slot.subscribers.size > 0;\n if (jit.directStateGuards.has(name) === blocked) continue;\n if (blocked) jit.directStateGuards.add(name);\n else jit.directStateGuards.delete(name);\n observersChanged = true;\n }\n for (const [name, slot] of instance.memoryResources) {\n const blocked = slot.subscribers.size > 0;\n if (jit.directMemoryGuards.has(name) === blocked) continue;\n if (blocked) jit.directMemoryGuards.add(name);\n else jit.directMemoryGuards.delete(name);\n observersChanged = true;\n }\n if (entryChanged && jit.direct !== undefined) {\n // Entry masks are compile-time facts, so an old resident program cannot be patched.\n jit.direct = undefined;\n jit.directPrograms.clear();\n jit.directRevision = -1;\n }\n if (observersChanged) {\n // Subscriber masks are shared in place: one program survives observer churn.\n syncDirectBarriers(jit);\n }\n if (observersChanged || entryChanged) jit.directSkip = undefined;\n}\n/**\n * Direct programs advance `frame.time` between host calls, while the board only adopts the\n * final time after `run` returns. Publish the current frame time before every host effect so\n * channel publications, electrical intents and diagnostics carry the instruction's time.\n */\nfunction directHost(\n board: JitRuntimeHost,\n instance: Instance,\n frame: DirectJitFrame,\n): DirectJitHost {\n const publishTime = (): void => {\n board.time = frame.time;\n };\n return {\n send: (name, value) => {\n publishTime();\n instance.host.send(name, value);\n },\n sample: (pin) => {\n publishTime();\n return instance.host.sample(pin);\n },\n intent: (pin, value) => {\n publishTime();\n if (instance.writeIntent(pin, value)) frame.publishPending = true;\n },\n resistor: (pin, resistance) => {\n publishTime();\n return instance.host.resistor(pin, resistance);\n },\n notify: (name) => {\n publishTime();\n instance.host.notify(name);\n },\n now: () => {\n publishTime();\n return instance.host.now();\n },\n random: () => {\n publishTime();\n return instance.host.random();\n },\n assert: (condition, message) => {\n publishTime();\n instance.host.assert(condition, message);\n },\n };\n}\n\n/** Build the numeric bank layout once; rebuilds then only need the cached instruction bodies. */\nfunction directLayout(jit: Jit): DirectJitLayout {\n if (jit.directLayout !== undefined) return jit.directLayout;\n const instance = jit.instance;\n const bank = instance.directStateBank();\n const memoryNames = [...instance.memories.keys()];\n const memories = new Map(memoryNames.map((name, index) => [name, index]));\n const memoryBanks = memoryNames.map((name) => instance.memory(name));\n const memoryViews = memoryBanks.map(\n (memory) => new DataView(memory.buffer, memory.byteOffset, memory.byteLength),\n );\n const pinNames = [...instance.pins.keys()];\n const pins = new Map(pinNames.map((name, index) => [name, index]));\n const pinObjects = pinNames.map((name) => instance.pin(name));\n const pinElectricalSlots = Int32Array.from(pinObjects, (pin) =>\n instance.board.electricalSlot(pin),\n );\n jit.directLayout = {\n ...bank,\n memoryNames: Object.freeze(memoryNames),\n memories,\n memoryBanks: Object.freeze(memoryBanks),\n memoryViews: Object.freeze(memoryViews),\n pinNames: Object.freeze(pinNames),\n pins,\n pinObjects: Object.freeze(pinObjects),\n pinElectricalSlots,\n };\n return jit.directLayout;\n}\n\nfunction flushDirect(\n board: JitRuntimeHost,\n instance: Instance,\n layout: DirectJitLayout,\n frame: DirectJitFrame,\n): boolean {\n board.time = frame.time;\n frame.publishPending = false;\n let wrote = instance.commitDirectStates(frame.stateDirty);\n for (let word = 0; word < frame.memoryDirty.length; word++) {\n let bits = frame.memoryDirty[word]!;\n if (bits === 0) continue;\n frame.memoryDirty[word] = 0;\n while (bits !== 0) {\n const slot = word * 32 + 31 - Math.clz32(bits & -bits);\n instance.memoryChanged(layout.memoryNames[slot]!);\n bits &= bits - 1;\n wrote = true;\n }\n }\n return wrote;\n}\n\ninterface RuntimeDirectFrame extends DirectJitFrame {\n /** The checkpoint already published the exit boundary before returning to the scheduler. */\n boundarySettled: boolean;\n}\n\nfunction createDirectFrame(\n board: JitRuntimeHost,\n jit: Jit,\n layout: DirectJitLayout,\n program: DirectJitProgram,\n barrier: DirectBarriers,\n): RuntimeDirectFrame {\n const instance = jit.instance;\n const { pinObjects, pinNames, pinElectricalSlots } = layout;\n // Counters are created once, only when the benchmark opted in; legacy directStats is untouched.\n const checkpointStats = board.checkpointDiagnostics ? directCheckpointStats(jit) : undefined;\n const frame: RuntimeDirectFrame = {\n states: layout.stateValues,\n memories: [...layout.memoryBanks],\n memoryViews: layout.memoryViews,\n pins: pinObjects,\n resistors: [],\n locals: new Array(program.localCount),\n stateDirty: new Int32Array(Math.ceil(layout.stateNames.length / 32)),\n memoryDirty: new Int32Array(Math.ceil(layout.memoryNames.length / 32)),\n time: board.time,\n due: board.time,\n resume: 0,\n // First resumption must not add a property to a frame already seen by hot shards.\n stopAfterInstruction: false,\n boundarySettled: false,\n };\n frame.writePinIntent = (pinIndex: number, value: unknown): void => {\n if (!Object.hasOwn(instance, 'writeIntent')) {\n const pin = pinObjects[pinIndex]!;\n if (pin.intent === value) return;\n pin.intent = value as never;\n instance.board.markElectricalDirty(pinElectricalSlots[pinIndex]!);\n frame.publishPending = true;\n return;\n }\n board.time = frame.time;\n if (instance.writeIntent(pinNames[pinIndex]!, value)) frame.publishPending = true;\n };\n (frame as { host?: DirectJitHost }).host = directHost(board, instance, frame);\n if (jit.metadata === undefined) {\n frame.publishCheckpoint = () => {\n if (checkpointStats !== undefined) checkpointStats.publications++;\n flushDirect(board, instance, layout, frame);\n // Writeback has completed before the boundary observes the published state.\n checkpointBoundary(board, checkpointStats, 'checkpointPublish');\n if (jit.directProgramRevision === -1 || !board.canContinueDirect(jit, frame.due)) {\n frame.boundarySettled = true;\n if (checkpointStats !== undefined) checkpointStats.exits++;\n return false;\n }\n // The boundary may have run reactions with their own current instance.\n board.current = instance;\n if (checkpointStats !== undefined) checkpointStats.continues++;\n return true;\n };\n if (jit.options.beforeInstruction === undefined) {\n const pcIndex = layout.states.get(jit.options.pc)!;\n frame.finishCheckpoint = (deadline, emptySuffix) => {\n if (checkpointStats !== undefined) {\n checkpointStats.finishes++;\n if (emptySuffix) checkpointStats.emptySuffixes++;\n }\n // The prefix was flushed and admitted through due. An empty suffix only\n // advances time, so that scheduler admission still holds after its boundary.\n if (emptySuffix) board.time = frame.time;\n else flushDirect(board, instance, layout, frame);\n checkpointBoundary(board, checkpointStats, 'checkpointFinish');\n const direct = jit.direct;\n const nextPc = frame.states[pcIndex] as number;\n if (\n jit.directProgramRevision === -1 ||\n direct?.frame !== frame ||\n !direct.pcs.has(nextPc) ||\n jit.directSkip === nextPc ||\n (jit.directRevision !== jit.revision &&\n jit.revision - jit.directRevision >= directRebuildStride(direct.pcs.size)) ||\n frame.time >= deadline ||\n board.events.time < deadline ||\n (!emptySuffix && !board.canContinueDirect(jit, frame.time))\n ) {\n frame.boundarySettled = true;\n if (checkpointStats !== undefined) checkpointStats.exits++;\n return false;\n }\n // Program membership excludes polling/secondary-code PCs. Barriers may still\n // have changed during reactions; the next generated block checks the refreshed masks.\n if (jit.directObserverRevision !== instance.observerRevision) refreshDirectGuards(jit);\n frame.stopAfterInstruction = false;\n board.current = instance;\n if (checkpointStats !== undefined) checkpointStats.continues++;\n return true;\n };\n }\n }\n // Both masks are shared with every frame of this JIT and refreshed in place on guard churn.\n (frame as BarrierFrame).blockedStates = barrier.stateMask;\n (frame as BarrierFrame).blockedMemories = barrier.memoryMask;\n return frame;\n}\nfunction runDirect(board: JitRuntimeHost, jit: Jit, hookReads?: Dependencies): boolean {\n const instance = jit.instance;\n let pending = Boolean(jit.direct?.frame.resume);\n if (!pending) {\n const pc = finite(instance.states.get(jit.options.pc), 'pc');\n const region = codeRegionFor(jit, pc);\n if (\n board.execution !== 'throughput' ||\n board.jits.length !== 1 ||\n (region !== undefined && region.memory !== jit.options.code) ||\n effectivePolling(jit).has(pc) ||\n jit.cache.get(pc)?.polling\n )\n return false;\n refreshDirectGuards(jit, hookReads);\n if (jit.directSkip === pc) return false;\n // An append-only translation revision leaves compiled bodies valid. Reuse them as long\n // as the current program covers this PC. Amortize rebuilds over a stride of new blocks,\n // but count repeat dispatches per translated PC so a hot path catches up promptly\n // without rebuilding for each PC visited once during initialization.\n if (jit.directRevision !== jit.revision) {\n const compiled = jit.direct?.pcs.size ?? 0;\n const stale = jit.revision - jit.directRevision;\n const stride = directRebuildStride(compiled);\n const covered = jit.direct?.pcs.has(pc) === true;\n const misses = covered ? 0 : (jit.directMisses.get(pc) ?? 0);\n const rebuild =\n jit.direct === undefined || stale >= stride || misses >= DIRECT_REBUILD_PATIENCE;\n\n if (!rebuild) {\n if (!covered) {\n // The interpreter runs this instruction; the catch-up rebuild picks it up. It is\n // still a direct attempt that fell back, so the counters keep describing \"how many\n // dispatches reached the compiled program\" rather than where the decision was made.\n const stats = directStats(jit);\n stats.directCalls++;\n stats.directFallbacks++;\n if (jit.cache.has(pc)) jit.directMisses.set(pc, misses + 1);\n\n return false;\n }\n // Covered: reuse the current program and fall through to the shared execution tail.\n } else {\n if (jit.directProgramRevision !== jit.revision) {\n // Code-memory replacement resets this marker to -1. The translated cache is gone, so\n // cached instruction bodies must go with it; old programs stay self-contained.\n if (jit.directProgramRevision === -1 && jit.directCache !== undefined)\n compileDirectJit.clearCache(jit.directCache);\n jit.directPrograms.clear();\n jit.directProgramRevision = jit.revision;\n }\n const layout = directLayout(jit);\n const instructions = [...jit.cache.values()].filter(\n (instruction) =>\n !instruction.polling &&\n !effectivePolling(jit).has(instruction.pc) &&\n directCodeInstruction(jit, instruction),\n );\n /** Declared busy-wait heads fold their remaining rounds inside the emitted body. */\n const delayLoops = new Map<\n number,\n {\n counter: number;\n cycles: number;\n pending?: { state: number; period: number; active: number };\n }\n >();\n for (const [headPc, delay] of effectiveDelays(jit)) {\n const counter = layout.states.get(delay.counter);\n if (counter === undefined) continue;\n const pending =\n delay.pending === undefined\n ? undefined\n : {\n state: layout.states.get(delay.pending.state),\n period: layout.states.get(delay.pending.period),\n active: layout.states.get(delay.pending.active),\n };\n delayLoops.set(\n headPc,\n pending !== undefined &&\n pending.state !== undefined &&\n pending.period !== undefined &&\n pending.active !== undefined\n ? { counter, cycles: delay.cycles, pending: pending as never }\n : { counter, cycles: delay.cycles },\n );\n }\n // Observer guards stay out of the key: blocks test them only when writing, so one\n // program serves every observer set. Entry guards participate in the binding\n // fingerprint because they change compile-time admission. The full delay descriptor\n // also participates because it changes the emitted guard.\n const key = JSON.stringify([...delayLoops].sort(([left], [right]) => left - right));\n const cached = jit.directPrograms.get(key);\n if (cached) {\n jit.direct = cached;\n jit.directRevision = jit.revision;\n } else {\n const { states, memories, pins } = layout;\n const entry = entryBlockedNames(jit);\n const cache = (jit.directCache ??= compileDirectJit.createCache());\n const binding = {\n states,\n memories,\n pins,\n pc: { name: jit.options.pc, index: states.get(jit.options.pc)! },\n host: true,\n ...(jit.functions === undefined ? {} : { functions: jit.functions }),\n split: true,\n shardSize: DIRECT_SHARD_SIZE,\n delayLoops,\n entryBlockedStates: entry.states,\n entryBlockedMemories: entry.memories,\n blockedStates: jit.directStateGuards,\n blockedMemories: jit.directMemoryGuards,\n };\n const program = compileDirectJit(instructions, binding, cache);\n jit.directRevision = jit.revision;\n jit.directMisses.clear();\n const stats = directStats(jit);\n\n stats.directShards = program?.shards ?? 0;\n if (program) stats.directCompiles++;\n const barrier = directBarriers(jit);\n barrier.stateIndex = states;\n barrier.memoryIndex = memories;\n const stateMaskWords = Math.ceil(layout.stateNames.length / 32);\n const memoryMaskWords = Math.ceil(layout.memoryNames.length / 32);\n if (barrier.stateMask.length !== stateMaskWords)\n barrier.stateMask = new Int32Array(stateMaskWords);\n if (barrier.memoryMask.length !== memoryMaskWords)\n barrier.memoryMask = new Int32Array(memoryMaskWords);\n syncDirectBarriers(jit);\n jit.direct = program\n ? {\n program,\n pcs: new Set(program.pcs),\n frame: createDirectFrame(board, jit, layout, program, barrier),\n }\n : undefined;\n // A declined program must not be cached, or the key would keep answering `undefined`.\n if (!jit.direct) jit.directPrograms.delete(key);\n // One program covers every subscriber set because its write masks are shared and\n // refreshed in place; entry-hook changes clear this map above.\n else jit.directPrograms.set(key, jit.direct);\n }\n }\n }\n if (!jit.direct) return false;\n }\n const direct = jit.direct!;\n const frame = direct.frame as RuntimeDirectFrame;\n const layout = jit.directLayout!;\n for (;;) {\n if (pending) frame.stopAfterInstruction = true;\n frame.time = board.time;\n // The frame starts clean and flushDirect clears both banks, including the fault path.\n const start = board.time;\n let reason: ReturnType<DirectJitProgram['run']>;\n let wrote: boolean;\n const stats = directStats(jit);\n stats.directCalls++;\n try {\n // Resource barriers exclude intermediate observers; real events retain exact deadlines.\n reason = direct.program.run(frame, Math.min(board.executionEnd, board.events.time));\n } finally {\n wrote = flushDirect(board, instance, layout, frame);\n }\n // A fallback with no flushed slot and no elapsed time did not execute anything; the cached\n // entry PC can safely be interpreted. A zero-duration block can still write state/PC before\n // the dispatcher rejects the next uncompiled PC: `wrote` records that prefix, so the caller\n // must re-read the flushed PC instead of replaying the old one.\n if (frame.boundarySettled) frame.boundarySettled = false;\n else if (reason !== 'fallback' || wrote || board.time !== start) board.boundary('runDirect');\n if (reason === 'fallback') {\n const nextPc = finite(instance.states.get(jit.options.pc), 'pc');\n // Polling PCs are deliberately absent from direct programs. Reaching one is a normal\n // shard boundary, not a failed direct dispatch, so it must neither compound fallback\n // statistics nor poison the next interpreter attempt for this PC.\n const polling = effectivePolling(jit).has(nextPc) || jit.cache.get(nextPc)?.polling;\n if (!polling) {\n stats.directFallbacks++;\n jit.directSkip = nextPc;\n }\n if (!wrote && board.time === start && board.time < board.executionEnd) return false;\n } else if (reason === 'stopped') {\n stats.directStopped++;\n jit.stopped = true;\n return true;\n } else if (reason === 'invalidated') {\n frame.stopAfterInstruction = false;\n // An electrical publication or a resumed suffix can return \"invalidated\" without\n // invalidating any code. An append-only revision must still honour the rebuild stride.\n // Primary code writes / metadata changes explicitly reset the program revision.\n if (jit.directProgramRevision === -1 && frame.resume === 0) {\n jit.direct = undefined;\n jit.directRevision = -1;\n }\n } else stats.directDeadlines++;\n // Publish and settle the whole boundary first. Without intervening scheduler work,\n // an already-started suffix can resume at its wake time without a queue round trip.\n // A metadata provider must still be checked by runJit before resumption.\n if (frame.resume) {\n const wake = Math.max(frame.due, board.time);\n if (jit.metadata === undefined && board.canContinueDirect(jit, wake)) {\n board.time = wake;\n board.current = instance;\n pending = true;\n continue;\n }\n if (wake > board.time) {\n board.events.push(wake, () => board.queueJit(jit));\n return true;\n }\n }\n board.queueJit(jit);\n return true;\n }\n}\nfunction pollingDependencies(\n jit: Jit,\n dependencies: Dependencies,\n pc: number | undefined,\n): Dependencies {\n const result = new Map(dependencies);\n const instance = jit.instance;\n const pcSlot = instance.stateResources.get(jit.options.pc)!;\n result.set(pcSlot, pcSlot.version);\n const region = pc === undefined ? undefined : codeRegionFor(jit, pc);\n const memory = region?.memory ?? jit.options.code;\n const slot = instance.memoryResources.get(memory)!;\n result.set(slot, slot.version);\n return result;\n}\n\n/** Park a polling JIT and, when requested, schedule the next device time event. */\nfunction waitForPolling(\n board: JitRuntimeHost,\n jit: Jit,\n dependencies: Dependencies,\n duration: number,\n advance: string | undefined,\n): void {\n jit.dependencies = dependencies;\n jit.pollingWait = true;\n jit.pollingPeriod = 0;\n board.parkWaiter(jit);\n const token = ++jit.pollingToken;\n\n board.boundary('polling');\n if (duration === 0 || advance === undefined) return;\n const due = time(board.time + duration);\n\n board.events.push(due, () => {\n if (token !== jit.pollingToken || !jit.active || jit.stopped || !board.waitingJits.has(jit))\n return;\n const pending = jit.dependencies;\n\n delete jit.dependencies;\n board.unparkWaiter(jit);\n jit.pollingToken++;\n board.current = jit.instance;\n // An external event won the race at the same timestamp. Re-evaluate the guest rather\n // than applying a device step against a configuration that has already changed.\n if (!jit.instance.dependenciesCurrent(pending)) {\n board.queueJit(jit);\n return;\n }\n jit.instance.syncCall(advance, [duration]);\n board.boundary('polling');\n board.queueJit(jit);\n });\n}\n\nfunction jitSignal(board: JitRuntimeHost, jit: Jit, signal: ExecutionSignal): boolean {\n if (signal.kind === 'elapse') {\n const duration = time(signal.duration);\n if (duration === 0) return false;\n const due = time(board.time + duration);\n board.events.push(due, () => board.queueJit(jit));\n board.boundary('jitSignal');\n return true;\n }\n if (signal.kind === 'waitUntil') {\n const checked = jit.instance.evaluate(() => syncJitCall(jit, signal.predicate));\n if (checked.value === true) return false;\n jit.predicate = signal.predicate;\n jit.pollingWait = false;\n jit.dependencies = checked.dependencies;\n board.parkWaiter(jit);\n board.boundary('jitSignal');\n return true;\n }\n if (signal.kind === 'stop') {\n jit.stopped = true;\n jit.execution = undefined;\n board.boundary('jitSignal');\n return true;\n }\n if (signal.kind === 'redirect') {\n finite(signal.pc, 'redirect target');\n const duration = time(signal.delay);\n jit.instance.host.write(jit.options.pc, signal.pc);\n jit.execution = undefined;\n const polling =\n jit.automaticPolling && duration > 0 && signal.pc === jit.currentPc && jit.pollReads;\n const dependencies = polling ? pollingDependencies(jit, polling, jit.currentPc) : undefined;\n jit.automaticPolling = false;\n jit.pollReads = undefined;\n board.boundary('jitSignal');\n if (duration === 0) board.queueJit(jit);\n else\n board.events.push(time(board.time + duration), () => {\n if (!jit.active || jit.stopped) return;\n if (dependencies && jit.instance.dependenciesCurrent(dependencies)) {\n jit.dependencies = dependencies;\n jit.pollingWait = true;\n jit.pollingPeriod = duration;\n jit.pollingOrigin = board.time;\n board.parkWaiter(jit);\n } else board.queueJit(jit);\n });\n return true;\n }\n throw new TypeError('Invalid JIT suspension');\n}\nexport function runJit(board: JitRuntimeHost, jit: Jit): void {\n jit.queued = false;\n if (!jit.active || jit.stopped) return;\n board.current = jit.instance;\n if (jit.metadata !== undefined) {\n const pc = finite(jit.instance.states.get(jit.options.pc), 'pc');\n ensureMetadataForPc(board, jit, pc);\n }\n if (jit.direct?.frame.resume) {\n runDirect(board, jit);\n return;\n }\n if (!jit.execution) {\n jit.automaticPolling = false;\n jit.pollReads = undefined;\n let hookReads: Dependencies | undefined;\n let hookPending = false;\n const hook = jit.options.beforeInstruction;\n if (hook) {\n const kind = jit.instance.declarations.get(hook.when)!.kind;\n const priorPc = jit.instance.states.get(jit.options.pc) as number;\n const collect =\n board.execution === 'throughput' &&\n (board.jits.length === 1 || effectivePolling(jit).has(priorPc));\n const checked = collect\n ? jit.instance.evaluate(() => jit.instance.read(kind, hook.when))\n : undefined;\n const handled = (checked ? checked.value : jit.instance.read(kind, hook.when)) === true;\n if (handled) {\n const execution = jit.instance.invoke(hook.call);\n const step = execution.next();\n if (!step.done) {\n jit.execution = execution;\n if (jitSignal(board, jit, step.value)) return;\n throw new TypeError('Invalid hook suspension');\n }\n }\n hookReads = checked?.dependencies;\n hookPending = handled;\n }\n const pc = finite(jit.instance.states.get(jit.options.pc), 'pc');\n if (board.execution === 'throughput') {\n const declaration = effectivePolling(jit).get(pc);\n if (declaration) {\n const checked = jit.instance.evaluate(() => jit.instance.syncCall(declaration.predicate));\n if (checked.value !== true) {\n const dependencies = new Map([...(hookReads ?? []), ...checked.dependencies]);\n let duration = 0;\n const wait = declaration.wait;\n if (wait) {\n const delayed = jit.instance.evaluate(\n () => jit.instance.syncCall(wait.delay),\n dependencies,\n );\n duration = time(delayed.value);\n }\n waitForPolling(\n board,\n jit,\n pollingDependencies(jit, dependencies, pc),\n duration,\n wait?.advance,\n );\n return;\n }\n if (declaration.consume) jit.instance.syncCall(declaration.consume);\n }\n if (!hookPending && board.jits.length === 1 && runDirect(board, jit, hookReads)) return;\n }\n let instruction = jit.cache.get(pc);\n if (!instruction) {\n const prior = board.phase;\n board.phase = 'translate';\n let valid = true;\n try {\n const codeRegion = codeRegionFor(jit, pc);\n const codeMemory = codeRegion?.memory ?? jit.options.code;\n const memory = jit.instance.memory(codeMemory);\n const bytes =\n codeRegion === undefined || codeRegion.size >= memory.length\n ? memory\n : memory.subarray(0, codeRegion.size);\n const code = bytesView(bytes, () => {\n if (!valid)\n throw board.error('OBJECT_DISPOSED', 'Translation view expired', jit.instance);\n });\n const result = jit.options.translate(\n Object.freeze({\n pc,\n code: code as import('../types').BorrowedBytes,\n codeBase: codeRegion?.base ?? 0,\n codeVersion: jit.instance.codeVersion(codeMemory),\n }),\n createJitBlockBuilder({ device: jit.model }),\n );\n acceptSync(result);\n const block = validateBoundBlockIR(result, jit.model);\n if (block.instructions[0]?.pc !== pc)\n throw new TypeError('Translated first pc does not match');\n const instructions = block.instructions.map((instruction) => {\n const region = codeRegionFor(jit, instruction.pc);\n return {\n pc: instruction.pc,\n nextPc: instruction.nextPc,\n body: instruction.body,\n polling: isPollingInstruction(instruction.body, instruction.pc, jit.options.pc),\n execute: body(instruction.body),\n codeRegion: region,\n };\n });\n // An overlapping translation can replace a covered body instead of just adding PCs.\n // It runs only after any direct continuation has drained, so discard that program now.\n if (instructions.some((entry) => jit.direct?.pcs.has(entry.pc))) {\n jit.direct = undefined;\n jit.directPrograms.clear();\n }\n // Match the first instruction when a block contains a repeated PC.\n for (let index = instructions.length - 1; index >= 0; index--) {\n const entry = instructions[index]!;\n jit.cache.set(entry.pc, entry);\n jit.cacheMemories.add(entry.codeRegion?.memory ?? jit.options.code);\n }\n // A block may legally span multiple PCs. Every entry gets its own logical region;\n // direct programs only admit primary/fallback entries. The start region only supplies\n // the translate-time byte view and codeVersion.\n if (\n instructions.some(\n (entry) =>\n entry.codeRegion === undefined || entry.codeRegion.memory === jit.options.code,\n )\n )\n jit.revision++;\n jit.directSkip = undefined;\n instruction = instructions[0]!;\n } catch (cause) {\n throw board.wrap(cause, 'JIT_FAILED', 'translate', jit.instance);\n } finally {\n valid = false;\n board.phase = prior;\n }\n }\n jit.currentPc = pc;\n jit.automaticPolling =\n board.execution === 'throughput' &&\n board.jits.length === 1 &&\n instruction.polling &&\n !hookPending &&\n (!hook || hookReads !== undefined);\n jit.pollReads = hookReads;\n jit.instance.host.write(jit.options.pc, instruction.nextPc);\n jit.execution = instruction.execute(jit.host);\n }\n for (;;) {\n const step = jit.automaticPolling\n ? (() => {\n const checked = jit.instance.evaluate(() => jit.execution!.next());\n jit.pollReads = new Map([...(jit.pollReads ?? []), ...checked.dependencies]);\n return checked.value;\n })()\n : jit.execution.next();\n if (step.done) {\n jit.execution = undefined;\n board.boundary('runJit');\n board.queueJit(jit);\n return;\n }\n if (jitSignal(board, jit, step.value)) return;\n }\n}\n","import { Emitter, type Event, type Disposable } from '@mica-js/core/lifecycle';\nimport { BuildError, validateDeviceIR, type DeviceIR } from '@mica-js/device-model';\nimport { RESUMABLE_RECEIVE, type ResumableProgram } from '@mica-js/compiler';\nimport {\n createElectricalNetwork,\n ElectricalError,\n type ElectricalPin,\n type ElectricalNetwork,\n} from './electrical';\nimport { ActivationQueue, EventQueue, Fifo } from './queue';\nimport { compileObservation } from './observations';\nimport { Instance } from './runtime/instance';\nimport { registerPublishGate } from './runtime/publish-gate';\nimport { readDirectCheckpointStats, runJit, syncJitCall, type BoundarySource } from './runtime/jit';\nimport { body, computation, frame, MAX_TIME, synchronousBody, time } from './runtime/execution';\nimport {\n acceptSync,\n AsyncHookError,\n ElectricalParameterError,\n modelLocation,\n standalone,\n} from './runtime/errors';\nimport type {\n Entry,\n Jit,\n Observation,\n ObservationChain,\n Process,\n Reaction,\n Receiver,\n ResourceSlot,\n} from './runtime/state';\nimport { dataObject, finite, identity, integer, same, snapshot } from './values';\nimport {\n SimulationError,\n type Board,\n type BoardDescription,\n type BoardOptions,\n type BoardStatus,\n type DeviceAdapter,\n type DeviceLibrary,\n type DeviceLibraryEntry,\n type RuntimeDiagnostic,\n type RuntimeDiagnosticCode,\n type RuntimePhase,\n type TopicBridge,\n type TopicMessage,\n} from './types';\n\nconst OBSERVATION_PROBE = Symbol.for('mica-js.simulator/observations');\nconst PROCESS_PROBE = Symbol.for('mica-js.simulator/processes');\nconst CHECKPOINT_PROBE = Symbol.for('mica-js.simulator/checkpoints');\n/**\n * Internal diagnostics opt-in. It stays a `globalThis` symbol so the runtime remains\n * browser-compatible and the public SDK surface does not grow:\n *\n * `globalThis[Symbol.for('mica-js.simulator/checkpoint-experiment')]?.diagnostics`\n *\n * Counters default to off; they classify boundary sources without changing runtime behavior.\n */\nconst CHECKPOINT_EXPERIMENT = Symbol.for('mica-js.simulator/checkpoint-experiment');\n\nconst EMPTY_BOUNDARY_SOURCES: Readonly<Record<BoundarySource, number>> = Object.freeze({\n checkpointPublish: 0,\n checkpointFinish: 0,\n jitSignal: 0,\n runJit: 0,\n runDirect: 0,\n polling: 0,\n process: 0,\n other: 0,\n});\n\ninterface BoundaryStats {\n /** Every boundary() entry. */\n calls: number;\n /** Calls that neither published an electrical change nor drained observations. */\n empty: number;\n /** Electrical publish passes driven by a boundary. */\n publishes: number;\n /** Observation batches drained by a boundary. */\n batches: number;\n /** Reaction bodies executed by boundaries. */\n reactions: number;\n /** Capture values frozen by the reaction capture barrier. */\n captures: number;\n /** Boundary entries grouped by the call site that requested the settlement. */\n sources: Record<BoundarySource, number>;\n}\n\nfunction createBoundaryStats(): BoundaryStats {\n return {\n calls: 0,\n empty: 0,\n publishes: 0,\n batches: 0,\n reactions: 0,\n captures: 0,\n sources: { ...EMPTY_BOUNDARY_SOURCES },\n };\n}\n\nfunction checkpointDiagnosticsEnabled(): boolean {\n const value = (globalThis as unknown as Record<PropertyKey, unknown>)[CHECKPOINT_EXPERIMENT];\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { diagnostics?: unknown }).diagnostics === true\n );\n}\n\nconst EMPTY_QUEUE_ENTRY = Object.freeze({}) as unknown as Observation;\nconst libraries = new WeakMap<object, readonly Entry[]>();\n\nexport function createDeviceLibrary(entries: readonly DeviceLibraryEntry[]): DeviceLibrary {\n try {\n if (!Array.isArray(entries)) throw new TypeError('Expected device entries');\n const seen = new Set<string>();\n const captured = entries.map((entry) => {\n dataObject(entry, ['id', 'model', 'create']);\n const id = identity(entry.id);\n if (seen.has(id)) throw new TypeError(`Duplicate device type ${id}`);\n seen.add(id);\n if (typeof entry.create !== 'function') throw new TypeError('Expected device factory');\n let model: DeviceIR;\n try {\n model = validateDeviceIR(entry.model);\n } catch (cause) {\n const conflict =\n cause instanceof BuildError &&\n Object.getOwnPropertyDescriptor(cause, 'code')?.value === 'CHANNEL_CONSUMER_CONFLICT';\n throw standalone(\n conflict ? 'CHANNEL_CONSUMER_CONFLICT' : 'MODEL_VALIDATION_FAILED',\n cause,\n 'library',\n );\n }\n return Object.freeze({ id, model, create: entry.create as DeviceLibraryEntry['create'] });\n });\n const library = Object.freeze({}) as DeviceLibrary;\n libraries.set(library, captured);\n return library;\n } catch (cause) {\n if (cause instanceof SimulationError) throw cause;\n throw standalone('INVALID_CONFIGURATION', cause, 'library');\n }\n}\ninterface TopicListener {\n readonly owner?: Instance;\n readonly call: (message: TopicMessage) => unknown;\n}\n\n/** Mutable view of the compiler's readonly reaction frame, reused across boundaries. */\ninterface MutableReactionFrame {\n previous: unknown;\n current: unknown;\n captures: unknown[];\n}\n\nclass BoardRuntime implements Board {\n time = 0;\n status: BoardStatus = 'ready';\n phase = 'assembly';\n current: Instance | undefined;\n /** -1: clean; -2: initial solve or multiple dirty slots; otherwise the only dirty slot. */\n private pendingElectricalSlot = -2;\n /** Flat dirty batch for the multi-slot publication path, stamped to drop repetitions. */\n private dirtyElectricalSlots = new Int32Array(0);\n private dirtyElectricalStamps = new Int32Array(0);\n private dirtyElectricalLength = 0;\n private dirtyElectricalEpoch = 1;\n private readonly observations = new ActivationQueue<Observation>();\n private readonly reactionBatch: Reaction[] = [];\n private readonly changeObservations: Receiver[] = [];\n private readonly changePrevious: unknown[] = [];\n private readonly changeCurrent: unknown[] = [];\n private readonly plans: ObservationChain[] = [];\n private readonly skippedPlans: { readonly key: string; readonly reason: string }[] = [];\n private readonly sampleSlots = new Map<ElectricalPin, ResourceSlot>();\n /** Electrical slot → published sample slot, bound once so publishing needs no lookup. */\n private readonly sampleSlotsBySlot: ResourceSlot[] = [];\n /** Electrical endpoint → its board slot, used to record dirty pins by slot. */\n private readonly electricalSlots = new Map<ElectricalPin, number>();\n private readonly byId = new Map<string, Instance>();\n private dispatchDepth = 0;\n private initialized = false;\n private readonly errors = new Emitter<RuntimeDiagnostic>();\n private readonly diagnostics = new Emitter<RuntimeDiagnostic>();\n private readonly listeners = new Set<TopicListener>();\n /** Owner-less listeners of the shared set: the host's direct subscriptions on `topics`. */\n private hostListeners = 0;\n private readonly models = new Fifo<Process>();\n readonly events = new EventQueue<() => void>();\n private readonly readyJits = new Fifo<Jit>();\n /**\n * Bumped on every resource-version mutation board wide. The value is bare arithmetic: a\n * difference proves *some* resource moved, never which one, so it only ever guards\n * \"nothing changed at all\" conclusions.\n *\n * Mutations cluster inside `publish()` while derived reads spread across the gaps\n * between publications, so a checkpoint compared against this counter hits far more\n * often than the raw mutation-to-read ratio suggests: `camera-mcu` sees 8514 bumps and\n * 5638 derived reads per frame, yet 99.93% of those reads find the epoch unchanged.\n */\n private versionEpoch = 0;\n readonly waitingJits = new Set<Jit>();\n /**\n * Advances whenever a parked JIT is flagged or parks. The global `versionEpoch` cannot\n * gate the scan: every electrical publish bumps it even when no JIT waits on the slot.\n */\n private waiterEpoch = 0;\n /** `waiterEpoch` at the last parked-JIT scan; equal means no parked JIT can have woken. */\n private waitingScanEpoch = 0;\n /** Parked JITs whose `pollingWait` is set: their polling boundary needs every round. */\n private pollingWaiterCount = 0;\n readonly jits: Jit[] = [];\n readonly instances: Instance[] = [];\n /** Aggregate counters are disabled by default so formal runs avoid per-checkpoint writes. */\n readonly checkpointDiagnostics: boolean;\n private readonly boundaryStats: BoundaryStats | undefined;\n private network!: ElectricalNetwork;\n private primary: SimulationError | undefined;\n readonly execution: 'throughput' | 'precise';\n executionEnd = 0;\n readonly onDidError: Event<RuntimeDiagnostic> = (listener, thisArgs, disposables) =>\n this.errors.event(\n (diagnostic) => {\n try {\n listener.call(thisArgs, diagnostic);\n } catch (cause) {\n this.diagnostic('HOST_LISTENER_FAILED', cause);\n }\n },\n undefined,\n disposables,\n );\n readonly onDidDiagnostic: Event<RuntimeDiagnostic> = (listener, thisArgs, disposables) =>\n this.diagnostics.event(\n (diagnostic) => {\n try {\n listener.call(thisArgs, diagnostic);\n } catch (cause) {\n this.fallback(cause);\n }\n },\n undefined,\n disposables,\n );\n readonly topics: TopicBridge = this.topicBridge();\n constructor(entries: readonly Entry[], description: BoardDescription, options: BoardOptions) {\n try {\n dataObject(description, ['instances', 'nets']);\n dataObject(options, ['seed', 'execution', 'cpuQuantum']);\n this.checkpointDiagnostics = checkpointDiagnosticsEnabled();\n this.boundaryStats = this.checkpointDiagnostics ? createBoundaryStats() : undefined;\n const execution = Object.hasOwn(options, 'execution') ? options.execution : 'throughput';\n if (execution !== 'throughput' && execution !== 'precise')\n throw new TypeError('Invalid execution mode');\n this.execution = execution;\n const cpuQuantum = Object.hasOwn(options, 'cpuQuantum')\n ? integer(options.cpuQuantum, 'cpuQuantum')\n : 10_000_000;\n if (cpuQuantum < 1 || cpuQuantum > 10_000_000)\n throw new RangeError('cpuQuantum outside [1, 10000000]');\n if (!Array.isArray(description.instances) || !Array.isArray(description.nets))\n throw new TypeError('instances and nets are required arrays');\n const seed = Object.hasOwn(options, 'seed') ? integer(options.seed, 'seed') : 0;\n if (seed < 0 || seed > 0xffffffff) throw new RangeError('seed out of uint32 range');\n const library = new Map(entries.map((entry) => [entry.id, entry]));\n const ids = new Set<string>();\n for (const input of description.instances) {\n dataObject(input, ['id', 'type', 'props', 'randomState']);\n const id = identity(input.id),\n type = identity(input.type);\n if (ids.has(id)) throw new TypeError(`Duplicate instance ${id}`);\n ids.add(id);\n const entry = library.get(type);\n if (!entry) throw new TypeError(`Unknown device type ${type}`);\n const props = Object.hasOwn(input, 'props') ? input.props : {};\n if (Object.hasOwn(input, 'randomState') && input.randomState === undefined)\n throw new TypeError('Invalid randomState');\n this.instances.push(\n new Instance(\n this,\n entry,\n id,\n props,\n seed,\n input.randomState as readonly number[] | undefined,\n ),\n );\n }\n for (const instance of this.instances) this.byId.set(instance.id, instance);\n const byId = this.byId;\n const netIds = new Set<string>(),\n connected = new Set<string>();\n for (const net of description.nets) {\n dataObject(net, ['id', 'pins', 'voltage']);\n const id = identity(net.id);\n if (netIds.has(id)) throw new TypeError(`Duplicate network ${id}`);\n netIds.add(id);\n if (!Array.isArray(net.pins)) throw new TypeError('Network pins must be an array');\n if (Object.hasOwn(net, 'voltage')) finite(net.voltage, 'voltage');\n for (const endpoint of net.pins) {\n dataObject(endpoint, ['instance', 'pin']);\n const instanceName = identity(endpoint.instance),\n pinName = identity(endpoint.pin);\n const instance = byId.get(instanceName);\n if (instance?.declarations.get(pinName)?.kind !== 'pin')\n throw new TypeError('Unknown pin endpoint');\n const key = `${instanceName}\\0${pinName}`;\n if (connected.has(key)) throw new TypeError('Duplicate connected endpoint');\n connected.add(key);\n }\n }\n try {\n for (const instance of this.instances) {\n this.current = instance;\n instance.prepare();\n }\n for (const instance of this.instances) {\n this.current = instance;\n instance.assertCreation();\n }\n for (const instance of this.instances) {\n this.current = instance;\n instance.allocate();\n }\n } catch (cause) {\n throw this.wrap(cause, 'MODEL_EXECUTION_FAILED', 'assembly', this.current);\n }\n const nets = description.nets.map((net) => ({\n id: net.id,\n pins: net.pins.map((p: import('./types').PinEndpoint) => byId.get(p.instance)!.pin(p.pin)),\n ...(Object.hasOwn(net, 'voltage') ? { voltage: net.voltage! } : {}),\n }));\n const pins: ElectricalPin[] = [];\n for (const instance of this.instances)\n for (const pin of instance.pins.values()) {\n // The electrical slot is the position in this board-ordered pin list, so the\n // publish plan resolves a changed slot without a map lookup.\n const slot = instance.sampleResources.get(pin.name)!;\n pins.push(pin);\n this.sampleSlots.set(pin, slot);\n this.electricalSlots.set(pin, this.sampleSlotsBySlot.length);\n this.sampleSlotsBySlot.push(slot);\n }\n this.network = createElectricalNetwork(pins, nets);\n // One dirty list and one stamp per board pin: publication never allocates.\n this.dirtyElectricalSlots = new Int32Array(pins.length);\n this.dirtyElectricalStamps = new Int32Array(pins.length);\n this.phase = 'initialize';\n for (const instance of this.instances) {\n this.current = instance;\n let adapter: unknown;\n try {\n adapter = instance.entry.create(instance.context);\n acceptSync(adapter);\n if (\n adapter === null ||\n typeof adapter !== 'object' ||\n typeof (adapter as DeviceAdapter).sync !== 'function' ||\n typeof (adapter as DeviceAdapter).dispose !== 'function'\n )\n throw new TypeError('Invalid device adapter');\n } catch (cause) {\n throw this.wrap(cause, 'DEVICE_CALLBACK_FAILED', 'initialize', instance);\n }\n instance.adapter = adapter as unknown as DeviceAdapter;\n if (this.isFaulted) throw this.primary!;\n }\n this.current = undefined;\n this.phase = 'idle';\n Object.defineProperty(this, OBSERVATION_PROBE, {\n value: () => this.observationReport(),\n enumerable: false,\n });\n Object.defineProperty(this, PROCESS_PROBE, {\n value: () => this.processReport(),\n enumerable: false,\n });\n Object.defineProperty(this, CHECKPOINT_PROBE, {\n value: () => this.checkpointReport(),\n enumerable: false,\n });\n } catch (cause) {\n const error =\n cause instanceof SimulationError\n ? cause\n : this.wrap(cause, 'INVALID_CONFIGURATION', 'assembly', this.current);\n this.primary = error;\n const cleanupErrors = this.cleanup();\n throw cleanupErrors.length ? this.aggregate(error, cleanupErrors) : error;\n }\n }\n private get isFaulted(): boolean {\n return this.status === 'faulted';\n }\n /**\n * Read-only diagnostic view of generated observation chains. It is reachable only via\n * `Symbol.for('mica-js.simulator/observations')` and is not part of the public SDK.\n */\n private observationReport(): unknown {\n return Object.freeze({\n plans: Object.freeze(\n this.plans.map((chain) =>\n Object.freeze({\n key: chain.plan.key,\n path: Object.freeze([...chain.plan.path]),\n receivers: chain.members.length,\n slots: chain.plan.slots.length,\n source: chain.plan.source,\n comparison: chain.plan.comparison,\n }),\n ),\n ),\n skipped: Object.freeze(this.skippedPlans.map((entry) => Object.freeze({ ...entry }))),\n reactions: Object.freeze(\n this.instances.flatMap((instance) =>\n instance.reactions.map((reaction) =>\n Object.freeze({\n instance: instance.id,\n name: reaction.declaration.name,\n mode:\n reaction.synchronousProgram === undefined\n ? 'pending'\n : reaction.synchronousProgram === null\n ? 'generic'\n : reaction.synchronous !== undefined && reaction.synchronous !== null\n ? 'sync'\n : 'ready',\n functions: reaction.synchronousProgram?.functions.length ?? 0,\n }),\n ),\n ),\n ),\n });\n }\n /**\n * Read-only diagnostic view of process execution: bodies admitted as resumable blocks\n * versus bodies kept on the generator path. Reachable only via\n * `Symbol.for('mica-js.simulator/processes')`; not part of the public SDK.\n */\n private processReport(): unknown {\n const resumable: string[] = [];\n const generic: string[] = [];\n const programs: { readonly key: string; readonly blocks: number }[] = [];\n for (const instance of this.instances)\n for (const process of instance.processes) {\n const key = `${instance.id}/${process.declaration.kind === 'on' ? process.declaration.name : 'start'}`;\n (process.resumable ? resumable : generic).push(key);\n // Blocks stay zero for generator bodies: they have no machine to measure.\n programs.push(Object.freeze({ key, blocks: process.resumable?.blocks ?? 0 }));\n }\n return Object.freeze({\n resumable: Object.freeze(resumable),\n generic: Object.freeze(generic),\n programs: Object.freeze(programs),\n bindings: Object.freeze(this.instances.map((instance) => instance.bindingReport())),\n });\n }\n /**\n * Read-only diagnostic view of boundary and Direct-checkpoint counters. Reachable only via\n * `Symbol.for('mica-js.simulator/checkpoints')`; zero counters mean diagnostics were off.\n */\n private checkpointReport(): unknown {\n const boundary = this.boundaryStats;\n return Object.freeze({\n diagnostics: this.checkpointDiagnostics,\n boundary: Object.freeze({\n calls: boundary?.calls ?? 0,\n empty: boundary?.empty ?? 0,\n publishes: boundary?.publishes ?? 0,\n batches: boundary?.batches ?? 0,\n reactions: boundary?.reactions ?? 0,\n captures: boundary?.captures ?? 0,\n sources: Object.freeze({ ...(boundary?.sources ?? EMPTY_BOUNDARY_SOURCES) }),\n }),\n checkpoints: Object.freeze(\n this.instances.flatMap((instance) =>\n instance.jits.map((jit) => {\n const stats = readDirectCheckpointStats(jit);\n return Object.freeze({\n instance: instance.id,\n publications: stats?.publications ?? 0,\n finishes: stats?.finishes ?? 0,\n emptySuffixes: stats?.emptySuffixes ?? 0,\n boundaryCalls: stats?.boundaryCalls ?? 0,\n continues: stats?.continues ?? 0,\n exits: stats?.exits ?? 0,\n });\n }),\n ),\n ),\n });\n }\n assertAlive(instance?: Instance): void {\n if (this.status === 'disposed' || (instance && !instance.valid))\n throw this.error('OBJECT_DISPOSED', 'Object is disposed', instance);\n }\n /** Admission for a call that may change board state or is visible to a device. */\n assertCallAllowed(instance?: Instance): void {\n this.admit(instance, false);\n }\n /** Admission for a read-only entry point: a faulted board stays inspectable. */\n assertReadAllowed(instance?: Instance): void {\n this.admit(instance, true);\n }\n private admit(instance: Instance | undefined, allowFaulted: boolean): void {\n this.assertAlive(instance);\n if (instance && ['execute', 'translate', 'dispose', 'assembly'].includes(this.phase))\n throw this.error('INVALID_CALL_STATE', 'Operation is not allowed in this phase', instance);\n if (!allowFaulted && this.status === 'faulted')\n throw this.error('BOARD_FAULTED', 'Board is faulted', instance);\n }\n error(\n code: RuntimeDiagnosticCode,\n message: string,\n instance?: Instance,\n cause?: unknown,\n phase?: RuntimePhase,\n ): SimulationError {\n const electrical = cause instanceof ElectricalError ? cause : undefined;\n return new SimulationError(\n Object.freeze({\n code,\n message,\n phase: phase ?? (this.phase === 'idle' ? 'host' : (this.phase as RuntimePhase)),\n time: this.time,\n ...(electrical?.instanceId !== undefined\n ? { instanceId: electrical.instanceId }\n : instance\n ? { instanceId: instance.id }\n : {}),\n ...(electrical?.resource !== undefined ? { resource: electrical.resource } : {}),\n ...modelLocation(cause),\n ...(cause === undefined ? {} : { cause }),\n related: Object.freeze([]),\n }),\n );\n }\n wrap(\n cause: unknown,\n code: RuntimeDiagnosticCode,\n phase: RuntimePhase,\n instance?: Instance,\n ): SimulationError {\n if (\n cause instanceof SimulationError &&\n !['DEVICE_CALLBACK_FAILED', 'JIT_FAILED', 'CLEANUP_FAILED'].includes(code)\n )\n return cause;\n const ownCode =\n cause instanceof ElectricalError ||\n cause instanceof ElectricalParameterError ||\n cause instanceof AsyncHookError\n ? cause.code\n : undefined;\n return this.error(\n phase !== 'dispose' && ownCode ? ownCode : code,\n cause instanceof Error ? cause.message : String(cause),\n instance,\n cause,\n phase,\n );\n }\n fault(error: SimulationError): void {\n if (this.status !== 'ready') return;\n this.status = 'faulted';\n this.primary = error;\n this.dispatchDepth++;\n try {\n this.errors.fire(error.diagnostic);\n } finally {\n this.dispatchDepth--;\n }\n }\n private diagnostic(code: RuntimeDiagnosticCode, cause: unknown, instance?: Instance): void {\n const diagnostic = this.error(\n code,\n cause instanceof Error ? cause.message : String(cause),\n instance,\n cause,\n ).diagnostic;\n this.dispatchDepth++;\n try {\n this.diagnostics.fire(diagnostic);\n } finally {\n this.dispatchDepth--;\n }\n }\n private fallback(cause: unknown): void {\n try {\n console.error(cause);\n } catch {\n /* Reporting cannot replace the primary failure. */\n }\n }\n report(instance: Instance, cause: unknown): void {\n if (this.status === 'disposed') {\n this.fallback(cause);\n return;\n }\n if (!instance.valid) {\n this.diagnostic('STALE_REPORT', cause, instance);\n return;\n }\n if (this.status === 'faulted') {\n this.diagnostic('REPORTED_ERROR', cause, instance);\n return;\n }\n this.fault(\n this.error(\n 'REPORTED_ERROR',\n cause instanceof Error ? cause.message : String(cause),\n instance,\n cause,\n 'report',\n ),\n );\n }\n topicBridge(owner?: Instance): TopicBridge {\n const facade = Object.freeze({\n onDidReceive: ((\n listener: (message: TopicMessage) => unknown,\n thisArgs?: unknown,\n disposables?: Disposable[],\n ) => {\n this.assertCallAllowed(owner);\n const entry: TopicListener = {\n ...(owner ? { owner } : {}),\n call: (message) => listener.call(thisArgs, message),\n };\n this.listeners.add(entry);\n if (!owner) this.hostListeners++;\n let active = true;\n const disposable = {\n dispose: () => {\n if (active) {\n active = false;\n // Deleting decides the decrement, so a cleared set cannot drive the count negative.\n if (this.listeners.delete(entry) && !owner) this.hostListeners--;\n }\n },\n };\n disposables?.push(disposable);\n owner?.resources.push(disposable);\n return disposable;\n }) as Event<TopicMessage>,\n publish: (topic: string, payload: unknown) => {\n this.assertCallAllowed(owner);\n if (typeof topic !== 'string') throw new TypeError('Topic must be a string');\n this.dispatchDepth++;\n try {\n const message = Object.freeze({ topic, payload });\n for (const entry of [...this.listeners]) {\n if (entry.owner && this.status !== 'ready') continue;\n try {\n const result = entry.call(message);\n if (entry.owner) acceptSync(result);\n } catch (cause) {\n if (entry.owner)\n this.fault(this.wrap(cause, 'DEVICE_CALLBACK_FAILED', 'topic', entry.owner));\n else this.diagnostic('HOST_LISTENER_FAILED', cause);\n }\n }\n } finally {\n this.dispatchDepth--;\n }\n },\n });\n // The admission check and the owner-less listener count stay off the public contract: they\n // exist for the adapter layer, which decides whether anyone would receive a message.\n registerPublishGate(facade, {\n assertPublishAllowed: () => this.assertCallAllowed(owner),\n hostListeners: () => this.hostListeners,\n });\n return facade;\n }\n private enqueue(process: Process): void {\n if (process.state === 'idle') {\n process.state = 'queued';\n this.models.push(process);\n } else if (process.state !== 'queued') process.pending = true;\n }\n queueJit(jit: Jit): void {\n if (jit.active && !jit.stopped && !jit.queued) {\n jit.queued = true;\n this.readyJits.push(jit);\n }\n }\n /**\n * Fail-closed admission for resuming generated code without a scheduler round trip.\n * The JIT must be the only direct owner, all same-time scheduler stages must be empty,\n * and no event may be due through the requested horizon. The target time is exclusive:\n * code must not resume at `executionEnd`.\n */\n canContinueDirect(jit: Jit, horizon: number): boolean {\n return (\n this.status === 'ready' &&\n this.phase === 'execute' &&\n !this.isFaulted &&\n this.execution === 'throughput' &&\n this.jits.length === 1 &&\n this.jits[0] === jit &&\n jit.active &&\n !jit.stopped &&\n !jit.queued &&\n this.readyJits.length === 0 &&\n this.models.length === 0 &&\n this.waitingJits.size === 0 &&\n this.time < this.executionEnd &&\n horizon >= this.time &&\n horizon < this.executionEnd &&\n this.events.time > horizon\n );\n }\n invalidate(slot: ResourceSlot): void {\n slot.version++;\n this.versionEpoch++;\n this.flagWaiters(slot);\n if (slot.subscribers.size === 0) return;\n for (const observation of slot.subscribers) this.observations.add(observation.order!);\n }\n /** Records a resource version bumped outside :func:`invalidate` (direct JIT writes). */\n noteResourceVersion(slot: ResourceSlot): void {\n this.versionEpoch++;\n this.flagWaiters(slot);\n }\n /** Flags every parked JIT that recorded `slot`, so the next round rescans it exactly once. */\n private flagWaiters(slot: ResourceSlot): void {\n const waiters = slot.waiters;\n if (waiters === undefined || waiters.size === 0) return;\n for (const jit of waiters) jit.dependencyDirty = true;\n this.waiterEpoch++;\n }\n /**\n * Registers a parked JIT on the slots its predicate recorded. A later version bump then\n * flags that JIT directly, so a scheduler round rescans dependencies only when the\n * evidence it would read has actually moved.\n */\n private watchWaiter(jit: Jit): void {\n const dependencies = jit.dependencies;\n if (jit.waiterSlots === dependencies) return;\n const previous = jit.waiterSlots;\n if (previous !== undefined) for (const slot of previous.keys()) slot.waiters?.delete(jit);\n if (dependencies !== undefined)\n for (const slot of dependencies.keys()) (slot.waiters ??= new Set()).add(jit);\n jit.waiterSlots = dependencies;\n // The recorded versions are only proven current by a scan after this registration, so\n // a write in the same round cannot be missed.\n jit.dependencyDirty = true;\n }\n /**\n * Parks a JIT on the versions it just recorded. Registering here instead of in the scan\n * makes `waiterEpoch` a complete wake source: the scan can then be skipped whenever no\n * parked JIT was flagged or registered since the last scan, and no poll is due.\n */\n parkWaiter(jit: Jit): void {\n if (!this.waitingJits.has(jit)) {\n this.waitingJits.add(jit);\n if (jit.pollingWait) this.pollingWaiterCount++;\n }\n this.watchWaiter(jit);\n jit.dependencyDirty = true;\n this.waiterEpoch++;\n }\n /** Wakes or drops a parked JIT and removes the registrations that would flag it later. */\n unparkWaiter(jit: Jit): void {\n if (this.waitingJits.delete(jit) && jit.pollingWait) {\n jit.pollingWait = false;\n this.pollingWaiterCount--;\n }\n const slots = jit.waiterSlots;\n if (slots !== undefined) {\n for (const slot of slots.keys()) slot.waiters?.delete(jit);\n jit.waiterSlots = undefined;\n }\n }\n /**\n * Checkpoint source for cached dependency evidence. An unchanged value since a previous\n * checkpoint proves no resource version moved in between, which is enough to reuse that\n * evidence without scanning it.\n */\n get resourceEpoch(): number {\n return this.versionEpoch;\n }\n /** Pin slot of an electrical endpoint; bound once because the board order is fixed. */\n electricalSlot(pin: ElectricalPin): number {\n return this.electricalSlots.get(pin)!;\n }\n markElectricalDirty(slot: number): void {\n const pending = this.pendingElectricalSlot;\n if (pending === slot) return;\n const stamps = this.dirtyElectricalStamps;\n if (slot >= stamps.length) throw new RangeError('Electrical slot is outside the board');\n const epoch = this.dirtyElectricalEpoch;\n if (stamps[slot] === epoch) return;\n stamps[slot] = epoch;\n if (pending >= 0) {\n // The promoted batch holds the single pending slot first, then this one.\n const list = this.dirtyElectricalSlots;\n list[0] = pending;\n list[1] = slot;\n stamps[pending] = epoch;\n this.dirtyElectricalLength = 2;\n this.pendingElectricalSlot = -2;\n return;\n }\n if (pending === -1) {\n this.pendingElectricalSlot = slot;\n return;\n }\n this.dirtyElectricalSlots[this.dirtyElectricalLength++] = slot;\n }\n /** Dirty slot count for diagnostics, not used by the publication path. */\n get dirtyElectricalCount(): number {\n return this.pendingElectricalSlot >= 0 ? 1 : this.dirtyElectricalLength;\n }\n private publish(): void {\n const pending = this.pendingElectricalSlot;\n if (pending === -1) return;\n // Fused publish: the solver hands every changed slot straight to `publishSlot`, which\n // resolves the pre-bound sample slot without any intermediate result array.\n if (pending >= 0) this.network.solveSlotInto(pending, this.publishSlot);\n else\n this.network.solveSlotBatchInto(\n this.dirtyElectricalSlots,\n this.dirtyElectricalLength,\n this.publishSlot,\n );\n if (pending === -2) this.dirtyElectricalLength = 0;\n // A new epoch retires every stamp, including the single pending slot's own mark.\n if (++this.dirtyElectricalEpoch === 0x7fffffff) {\n this.dirtyElectricalStamps.fill(0);\n this.dirtyElectricalEpoch = 1;\n }\n this.pendingElectricalSlot = -1;\n }\n /** Publication sink: enter the observation queue for one published board slot. */\n private readonly publishSlot = (slot: number): void => {\n this.invalidate(this.sampleSlotsBySlot[slot]!);\n };\n private bindObservation(observation: Receiver, path: readonly string[]): void {\n const instance = observation.instance;\n observation.previous = instance.observe(observation, path);\n observation.readSource = instance.observationReader(observation, path);\n observation.order = this.observations.register(observation);\n }\n /**\n * Static sources whose root is a derived declaration are grouped into one generated\n * chain per (instance, path): the reader, the stable comparator and the dependency\n * slots are bound once at baseline and shared by every receiver. Every other source\n * keeps the generic path.\n */\n private baseline(): void {\n this.publish();\n const entries: {\n observation: Receiver;\n path: readonly string[];\n key: string;\n instance: Instance;\n }[] = [];\n for (const instance of this.instances) {\n const prefix = `${instance.id}\\0`;\n for (const process of instance.processes)\n if (\n process.source &&\n instance.declarations.get(process.source[0]!)?.kind !== 'notification'\n )\n entries.push({\n observation: process,\n path: process.source,\n key: prefix + process.source.join('\\0'),\n instance,\n });\n for (const reaction of instance.reactions) {\n const path = reaction.declaration.sourcePath;\n entries.push({\n observation: reaction,\n path,\n key: prefix + path.join('\\0'),\n instance,\n });\n }\n }\n const groups = new Map<string, ObservationChain | undefined>();\n for (const entry of entries) {\n if (groups.has(entry.key)) continue;\n const compilation = compileObservation(entry.instance, entry.key, entry.path);\n if (!compilation.ok) {\n this.skippedPlans.push({ key: entry.key, reason: compilation.reason });\n groups.set(entry.key, undefined);\n continue;\n }\n const plan = compilation.plan;\n const chain: ObservationChain = {\n plan,\n instance: entry.instance,\n members: [],\n dependencies: new Map(),\n entry: { dependencies: new Map<ResourceSlot, number>(), value: undefined, epoch: -1 },\n order: 0,\n previous: undefined,\n bound: false,\n };\n groups.set(entry.key, chain);\n this.plans.push(chain);\n }\n for (const entry of entries) {\n const chain = groups.get(entry.key);\n if (chain === undefined) {\n this.bindObservation(entry.observation, entry.path);\n continue;\n }\n if (chain.bound) {\n // One queue slot per collapsed receiver keeps unrelated observation indices and\n // the original relative order intact.\n entry.observation.order = this.observations.register(EMPTY_QUEUE_ENTRY);\n } else {\n chain.bound = true;\n chain.order = this.observations.register(chain);\n entry.observation.order = chain.order;\n this.bindChain(chain);\n }\n chain.members.push(entry.observation);\n entry.observation.previous = chain.previous;\n }\n }\n private bindChain(chain: ObservationChain): void {\n const instance = chain.instance;\n for (const slot of chain.plan.slots as readonly ResourceSlot[]) {\n if (!slot.subscribers.size) instance.observerRevision++;\n slot.subscribers.add(chain);\n }\n const value = chain.plan.evaluate();\n chain.previous = chain.plan.needsSnapshot ? snapshot(value) : value;\n this.commitChain(chain, value);\n }\n /** Keep the derived cache populated with the value the chain just computed. */\n private commitChain(chain: ObservationChain, value: unknown): void {\n const path = chain.plan.path;\n if (path.length !== 1) return;\n const slots = chain.plan.slots as readonly ResourceSlot[];\n const dependencies = chain.dependencies;\n for (let index = 0; index < slots.length; index++) {\n const slot = slots[index]!;\n dependencies.set(slot, slot.version);\n }\n const entry = chain.entry;\n if (entry.value !== value) entry.value = value;\n entry.dependencies = dependencies;\n entry.epoch = this.versionEpoch;\n chain.instance.setDerived(path[0]!, entry);\n }\n private collectChain(chain: ObservationChain): void {\n const value = chain.plan.evaluate();\n const current = chain.plan.needsSnapshot ? snapshot(value) : value;\n this.commitChain(chain, value);\n if (chain.plan.equals(chain.previous, current)) return;\n const previous = chain.previous;\n chain.previous = current;\n const members = chain.members;\n const member = members[0]!;\n if (members.length === 1 && !this.changeObservations.length) {\n // A single receiver has the chain's own queue slot, so its order is already the\n // batch position and the effect can be applied without the reordering table.\n member.previous = current;\n this.applyChange(member, previous, current);\n return;\n }\n for (const entry of members) {\n entry.previous = current;\n this.recordChange(entry, previous, current);\n }\n }\n private applyChange(observation: Receiver, previous: unknown, current: unknown): void {\n if (observation.declaration.kind === 'reaction') {\n const reaction = observation as Reaction;\n const frame = reaction.frame as MutableReactionFrame | undefined;\n if (frame === undefined) reaction.frame = { previous, current, captures: [] };\n else {\n frame.previous = previous;\n frame.current = current;\n frame.captures.length = 0;\n }\n this.reactionBatch.push(reaction);\n } else this.enqueue(observation as Process);\n }\n private recordChange(observation: Receiver, previous: unknown, current: unknown): void {\n this.insertOrderedChange(\n this.changeObservations,\n this.changePrevious,\n this.changeCurrent,\n observation,\n previous,\n current,\n );\n }\n /** Shared stable insertion; receivers are few, so in-place insertion beats a sort. */\n private insertOrderedChange(\n receivers: Receiver[],\n previous: unknown[],\n current: unknown[],\n observation: Receiver,\n before: unknown,\n after: unknown,\n ): void {\n let at = receivers.length;\n const order = observation.order!;\n while (at > 0 && receivers[at - 1]!.order! > order) at--;\n if (at === receivers.length) {\n receivers.push(observation);\n previous.push(before);\n current.push(after);\n } else {\n receivers.splice(at, 0, observation);\n previous.splice(at, 0, before);\n current.splice(at, 0, after);\n }\n }\n boundary(source: BoundarySource = 'other'): void {\n const stats = this.boundaryStats;\n if (stats !== undefined) {\n stats.calls++;\n stats.sources[source]++;\n }\n let worked = false;\n for (;;) {\n if (this.pendingElectricalSlot !== -1) {\n if (stats !== undefined) stats.publishes++;\n this.publish();\n worked = true;\n }\n if (!this.observations.size) {\n if (stats !== undefined && !worked) stats.empty++;\n return;\n }\n if (stats !== undefined) stats.batches++;\n worked = true;\n // Truncating a non-empty array clears its elements; an already-empty buffer needs\n // no store at all, which is the common case for the ordering tables.\n const reactions = this.reactionBatch;\n if (reactions.length) reactions.length = 0;\n const changes = this.changeObservations;\n if (changes.length) changes.length = 0;\n if (this.changePrevious.length) this.changePrevious.length = 0;\n if (this.changeCurrent.length) this.changeCurrent.length = 0;\n this.observations.drain(this.consumeObservation);\n const count = changes.length;\n if (count) {\n for (let index = 0; index < count; index++)\n this.applyChange(changes[index]!, this.changePrevious[index], this.changeCurrent[index]);\n changes.length = 0;\n this.changePrevious.length = 0;\n this.changeCurrent.length = 0;\n }\n if (reactions.length) {\n if (stats !== undefined) stats.reactions += reactions.length;\n this.runBoundaryReactions(reactions);\n } else return;\n }\n }\n /** One due receiver: chains collapse their members, plain sources apply inline. */\n private readonly consumeObservation = (observation: Observation): void => {\n if ('plan' in observation) {\n this.collectChain(observation);\n return;\n }\n const current = observation.readSource!();\n if (same(observation.previous, current)) return;\n const previous = observation.previous;\n observation.previous = current;\n // Once a collapsed chain buffered its receivers, later effects must wait for the\n // ordered table; otherwise the original inline application is kept.\n if (this.changeObservations.length) this.recordChange(observation, previous, current);\n else this.applyChange(observation, previous, current);\n };\n /** Shared capture barrier and ordered body runner for generic and static boundaries. */\n private runBoundaryReactions(reactions: Reaction[]): void {\n try {\n const stats = this.boundaryStats;\n // Every instance completes observation and capture before any reaction body runs.\n for (const reaction of reactions)\n if (reaction.declaration.captures.length) {\n if (stats !== undefined) stats.captures += reaction.declaration.captures.length;\n const frame = reaction.frame as MutableReactionFrame;\n frame.captures = reaction.declaration.captures.map((capture) =>\n snapshot(computation(capture.value, reaction.instance.host)),\n );\n }\n for (const reaction of reactions) {\n this.current = reaction.instance;\n this.runReaction(reaction);\n }\n } finally {\n this.clearReactionFrames(reactions);\n }\n }\n private clearReactionFrames(reactions: Reaction[]): void {\n for (const reaction of reactions) {\n const frame = reaction.frame as MutableReactionFrame | undefined;\n if (frame === undefined) continue;\n frame.previous = undefined;\n frame.current = undefined;\n frame.captures.length = 0;\n }\n }\n /**\n * Execute one synchronous boundary reaction. The capture barrier already froze every\n * frame before this method runs. Admission is whole-body: a compiler decline selects\n * the generator path before any effect, while bind/execution errors propagate without\n * a catch-and-replay fallback.\n */\n private runReaction(reaction: Reaction): void {\n const instance = reaction.instance;\n let program = reaction.synchronousProgram;\n if (program === undefined) {\n program = synchronousBody(instance, reaction.declaration.body) ?? null;\n reaction.synchronousProgram = program;\n }\n if (program !== null) {\n let runner = reaction.synchronous;\n if (runner === undefined || runner === null) {\n runner = program.bind(instance.host);\n reaction.synchronous = runner;\n }\n runner(undefined, reaction.frame);\n return;\n }\n reaction.execute ??= body(reaction.declaration.body);\n const step = reaction.execute(instance.host, [], reaction.frame).next();\n if (!step.done) throw new TypeError('Reaction cannot suspend');\n }\n private drive(process: Process, value?: unknown): void {\n const program = process.resumable;\n if (program) {\n this.driveResumable(process, program, value);\n return;\n }\n this.current = process.instance;\n process.state = 'running';\n process.execution ??= body(process.declaration.body)(process.instance.host);\n for (;;) {\n const step = process.execution.next(value);\n if (step.done) {\n this.boundary('process');\n process.execution = undefined;\n process.state = 'idle';\n if (process.pending) {\n process.pending = false;\n this.enqueue(process);\n }\n return;\n }\n const signal = step.value;\n if (signal.kind === 'receive') {\n const channel = process.instance.channels.get(signal.channel)!;\n if (channel.incoming.length) {\n value = channel.incoming.shift().value;\n continue;\n }\n process.state = 'waiting';\n channel.receiver = process;\n this.boundary('process');\n return;\n }\n if (signal.kind !== 'ticks') throw new TypeError('Invalid process suspension');\n const duration = time(signal.duration),\n due = time(this.time + duration);\n process.state = 'waiting';\n this.boundary('process');\n if (duration === 0) {\n process.state = 'queued';\n this.models.push(process);\n } else {\n // The continuation is bound once per process: only one timed wake can be pending.\n process.wake ??= () => {\n process.state = 'queued';\n this.models.push(process);\n };\n this.events.push(due, process.wake);\n }\n return;\n }\n }\n /**\n * Same suspension contract as `drive`, driven by the body's own pc and reused frame:\n * the body reports ticks/receive through the frame and returns whether it suspended.\n */\n private driveResumable(process: Process, program: ResumableProgram, value?: unknown): void {\n const instance = process.instance;\n this.current = instance;\n process.state = 'running';\n const state = (process.frame ??= frame(program));\n const host = instance.host;\n let input = value;\n for (;;) {\n state.value = input;\n if (!program.run(host, undefined, undefined, state)) {\n this.boundary('process');\n process.state = 'idle';\n if (process.pending) {\n process.pending = false;\n this.enqueue(process);\n }\n return;\n }\n if (state.kind === RESUMABLE_RECEIVE) {\n const channel = instance.channels.get(state.channel)!;\n if (channel.incoming.length) {\n input = channel.incoming.shift().value;\n continue;\n }\n process.state = 'waiting';\n channel.receiver = process;\n this.boundary('process');\n return;\n }\n // The body already validated the duration with H.checkDuration; only the sum needs\n // the shared range check.\n const duration = state.duration,\n due = time(this.time + duration);\n process.state = 'waiting';\n this.boundary('process');\n if (duration === 0) {\n process.state = 'queued';\n this.models.push(process);\n } else {\n process.wake ??= () => {\n process.state = 'queued';\n this.models.push(process);\n };\n this.events.push(due, process.wake);\n }\n return;\n }\n }\n runUntil(target: number): void {\n this.assertAlive();\n if (this.phase !== 'idle' || this.dispatchDepth)\n throw this.error('INVALID_CALL_STATE', 'Board is busy');\n if (this.status === 'faulted') throw this.error('BOARD_FAULTED', 'Board is faulted');\n const end = time(target);\n if (end < this.time) throw new RangeError('Cannot run backwards');\n const from = this.time;\n this.phase = 'execute';\n this.executionEnd = end;\n try {\n if (!this.initialized) {\n this.baseline();\n this.initialized = true;\n for (const instance of this.instances)\n for (const process of instance.processes)\n if (process.declaration.kind === 'start') this.enqueue(process);\n for (const jit of this.jits) this.queueJit(jit);\n }\n for (const instance of this.instances) {\n for (const channel of instance.channels.values()) {\n if (channel.pending.length)\n for (const message of channel.pending.drain()) channel.incoming.push(message);\n if (channel.receiver && channel.incoming.length) {\n const process = channel.receiver;\n channel.receiver = undefined;\n const received = channel.incoming.shift()!.value;\n this.events.push(this.time, () => {\n process.state = 'queued';\n process.resumeValue = received;\n this.models.push(process);\n });\n }\n }\n for (const notification of instance.notificationInputs)\n for (const process of instance.processes)\n if (process.source?.[0] === notification) this.enqueue(process);\n instance.notificationInputs.clear();\n }\n // A parked JIT records the versions it read, so it can only become runnable once one\n // of those slots is invalidated; the wait set binds exactly that dependency set, and a\n // periodic poll still needs its boundary recomputed on every round. Both facts are\n // counted in `waiterEpoch` / `pollingWaiterCount`, so a round where neither moved\n // skips the scan entirely with `pollingBoundary` left at Infinity.\n for (;;) {\n while (this.events.time === this.time) this.events.pop()();\n if (this.models.length) {\n const process = this.models.shift()!;\n const value = process.resumeValue;\n process.resumeValue = undefined;\n this.drive(process, value);\n if (this.isFaulted) throw this.primary!;\n continue;\n }\n let pollingBoundary = Infinity;\n if (\n this.waitingJits.size &&\n (this.waiterEpoch !== this.waitingScanEpoch || this.pollingWaiterCount !== 0)\n ) {\n this.waitingScanEpoch = this.waiterEpoch;\n for (let index = 0; index < this.jits.length; index++) {\n const jit = this.jits[index]!;\n if (!jit.active || jit.stopped || !this.waitingJits.has(jit)) continue;\n this.watchWaiter(jit);\n if (!jit.dependencyDirty && !jit.pollingWait) continue;\n if (jit.instance.dependenciesCurrent(jit.dependencies)) {\n jit.dependencyDirty = false;\n if (jit.pollingWait && jit.pollingPeriod > 0) {\n const lastStart = MAX_TIME - ((MAX_TIME - jit.pollingOrigin) % jit.pollingPeriod);\n if (lastStart < MAX_TIME && lastStart < end) {\n if (lastStart === this.time) {\n jit.pollingToken++;\n delete jit.dependencies;\n this.unparkWaiter(jit);\n this.queueJit(jit);\n } else pollingBoundary = Math.min(pollingBoundary, lastStart);\n }\n }\n continue;\n }\n jit.dependencyDirty = false;\n if (jit.pollingWait) {\n jit.pollingToken++;\n delete jit.dependencies;\n this.unparkWaiter(jit);\n const remainder =\n jit.pollingPeriod > 0 ? (this.time - jit.pollingOrigin) % jit.pollingPeriod : 0;\n if (remainder)\n this.events.push(time(this.time + (jit.pollingPeriod - remainder)), () =>\n this.queueJit(jit),\n );\n else this.queueJit(jit);\n } else if (jit.predicate) {\n const checked = jit.instance.evaluate(() => syncJitCall(jit, jit.predicate!));\n jit.dependencies = checked.dependencies;\n if (checked.value === true) {\n delete jit.predicate;\n delete jit.dependencies;\n this.unparkWaiter(jit);\n this.queueJit(jit);\n } else {\n // The replaced dependency set is re-registered and needs its own scan.\n this.watchWaiter(jit);\n this.waiterEpoch++;\n }\n }\n }\n }\n if (this.time < end && this.readyJits.length) {\n runJit(this, this.readyJits.shift());\n if (this.isFaulted) throw this.primary!;\n continue;\n }\n if (pollingBoundary < this.events.time && pollingBoundary <= end) {\n this.time = pollingBoundary;\n continue;\n }\n const next = this.events.time;\n if (next <= end) {\n this.time = next;\n // The next round would only drain these events at the top of the loop; doing it\n // here saves one scheduler round per due event and observes the same order\n // (callbacks still run before the model queue is served).\n while (this.events.time === this.time) this.events.pop()();\n continue;\n }\n this.time = end;\n break;\n }\n const batches = this.instances.map((instance) => instance.captureBatch(from, end));\n this.phase = 'sync';\n for (let i = 0; i < this.instances.length; i++) {\n const instance = this.instances[i]!;\n this.current = instance;\n try {\n acceptSync(instance.adapter!.sync(batches[i]!));\n } catch (cause) {\n throw this.wrap(cause, 'DEVICE_CALLBACK_FAILED', 'sync', instance);\n }\n if (this.isFaulted) throw this.primary!;\n }\n } catch (cause) {\n const error = this.wrap(\n cause,\n 'MODEL_EXECUTION_FAILED',\n this.phase === 'sync' ? 'sync' : 'execute',\n this.current,\n );\n this.fault(error);\n throw error;\n } finally {\n this.current = undefined;\n this.phase = 'idle';\n }\n }\n dispose(): void {\n if (this.status === 'disposed') return;\n if (this.phase !== 'idle' || this.dispatchDepth)\n throw this.error('INVALID_CALL_STATE', 'Board is busy');\n const errors = this.cleanup();\n if (errors.length)\n throw this.primary\n ? this.aggregate(this.primary, errors)\n : this.aggregate(errors[0]!, errors.slice(1));\n }\n private aggregate(primary: SimulationError, errors: readonly SimulationError[]): SimulationError {\n return new SimulationError(\n Object.freeze({\n ...primary.diagnostic,\n related: Object.freeze([...primary.related, ...errors.map((error) => error.diagnostic)]),\n }),\n );\n }\n private cleanup(): SimulationError[] {\n this.phase = 'dispose';\n for (const instance of this.instances) instance.valid = false;\n const errors: SimulationError[] = [];\n for (const instance of [...this.instances].reverse()) {\n if (instance.adapter) {\n try {\n acceptSync(instance.adapter.dispose());\n } catch (cause) {\n errors.push(this.wrap(cause, 'CLEANUP_FAILED', 'dispose', instance));\n }\n }\n for (const resource of [...instance.resources].reverse()) {\n try {\n resource.dispose();\n } catch (cause) {\n errors.push(this.wrap(cause, 'CLEANUP_FAILED', 'dispose', instance));\n }\n }\n instance.resources.length = 0;\n }\n this.events.clear();\n this.models.clear();\n this.readyJits.clear();\n this.observations.clear();\n this.reactionBatch.length = 0;\n this.plans.length = 0;\n this.skippedPlans.length = 0;\n this.changeObservations.length = 0;\n this.changePrevious.length = 0;\n this.changeCurrent.length = 0;\n this.sampleSlots.clear();\n this.listeners.clear();\n this.hostListeners = 0;\n this.errors.dispose();\n this.diagnostics.dispose();\n this.status = 'disposed';\n this.phase = 'idle';\n return errors;\n }\n}\nexport function createBoard(\n library: DeviceLibrary,\n description: BoardDescription,\n options?: BoardOptions,\n): Board {\n const entries = libraries.get(library);\n if (!entries)\n throw standalone('INVALID_CONFIGURATION', new TypeError('Unknown device library'), 'assembly');\n if (arguments.length >= 3 && options === undefined)\n throw standalone(\n 'INVALID_CONFIGURATION',\n new TypeError('Explicit undefined options'),\n 'assembly',\n );\n return new BoardRuntime(entries, description, options ?? {});\n}\n","/** Stable failure codes of the prepared-simulation runtime. */\nexport type SimulationRuntimeErrorCode =\n | 'invalid-input'\n | 'invalid-device'\n | 'unresolved-device'\n | 'unresolved-asset'\n | 'not-loaded'\n | 'disposed';\n\nexport interface ISimulationRuntimeErrorOptions {\n /** Device the failure belongs to, as the prepared simulation names it. */\n readonly deviceId?: string;\n readonly cause?: unknown;\n}\n\n/**\n * Error raised while preparing or driving a prepared simulation.\n *\n * The code is stable and machine-checkable; the message names the offending device, symbol or\n * asset so a caller can report it without parsing the cause chain.\n */\nexport class SimulationRuntimeError extends Error {\n override readonly name = 'SimulationRuntimeError';\n readonly code: SimulationRuntimeErrorCode;\n readonly deviceId: string | undefined;\n\n constructor(\n code: SimulationRuntimeErrorCode,\n message: string,\n options: ISimulationRuntimeErrorOptions = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.code = code;\n this.deviceId = options.deviceId;\n }\n}\n\n/** Message of one thrown value, used to give load failures a readable envelope. */\nexport function errorMessage(error: unknown): string {\n return error instanceof Error && error.message.length > 0 ? error.message : String(error);\n}\n","import { validateDeviceIR } from '@mica-js/device-model';\nimport type { DeviceIR } from '@mica-js/device-model';\nimport { assetSrcError } from '@mica-js/document';\nimport {\n deriveSchematicTopology,\n deviceMetadataSymbol,\n isAssetReference,\n parseDeviceMetadata,\n parseDeviceReference,\n parseSchematic,\n symbolRole,\n} from '@mica-js/document/schematic';\nimport type {\n DeviceMetadata,\n DeviceSymbolProvider,\n SchematicSymbol,\n} from '@mica-js/document/schematic';\nimport { resolveDelivery } from '@mica-js/document/canvas';\nimport type { DeliveryKind, PayloadType } from '@mica-js/document/canvas';\nimport type { BoardDescription, DeviceLibraryEntry, PropertyInput } from '../types';\nimport { errorMessage, SimulationRuntimeError } from './errors';\nimport type { IPreparedSimulation, SimulationModuleImporter } from './types';\n\nexport interface IPreparedDeviceTopic {\n readonly port: string;\n readonly direction: 'input' | 'output';\n readonly type: PayloadType;\n readonly delivery: DeliveryKind;\n}\n\nexport interface IPreparedDevice {\n readonly id: string;\n readonly definition: DeviceMetadata;\n readonly model: DeviceIR;\n readonly create: DeviceLibraryEntry['create'];\n readonly topics: ReadonlyMap<string, IPreparedDeviceTopic>;\n}\n\nexport interface IPreparedInstance {\n readonly symbol: string;\n readonly device: IPreparedDevice;\n}\n\nexport interface IResolvedSimulation {\n readonly instances: readonly IPreparedInstance[];\n readonly description: BoardDescription;\n readonly execution?: IPreparedSimulation['execution'];\n}\n\n/** Imports only referenced SDK modules and captures all inputs before any factory runs. */\nexport async function prepareSimulation(\n input: IPreparedSimulation,\n importer: SimulationModuleImporter,\n assertActive: () => void,\n): Promise<IResolvedSimulation> {\n if (!isRecord(input) || !Array.isArray(input.devices)) {\n throw new SimulationRuntimeError('invalid-input', 'Expected schematic and devices');\n }\n const schematic = parseSchematic(input.schematic);\n const assets = readAssets(input.assets);\n const voltageReferences = readVoltageReferences(input.voltageReferences);\n const candidates = new Map<\n string,\n { readonly definition: DeviceMetadata; readonly code: string }\n >();\n for (const candidate of input.devices) {\n if (\n !isRecord(candidate) ||\n typeof candidate.id !== 'string' ||\n parseDeviceReference(candidate.id) === undefined ||\n candidates.has(candidate.id) ||\n typeof candidate.code !== 'string' ||\n candidate.code.trim().length === 0\n ) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n 'Expected unique device ids and self-contained ESM code',\n );\n }\n let definition: DeviceMetadata;\n try {\n definition = structuredClone(parseDeviceMetadata(candidate.definition));\n } catch (cause) {\n throw new SimulationRuntimeError(\n 'invalid-device',\n `Invalid metadata for \"${candidate.id}\": ${errorMessage(cause)}`,\n { cause },\n );\n }\n if (definition.id !== parseDeviceReference(candidate.id)!.deviceId) {\n throw new SimulationRuntimeError(\n 'invalid-device',\n `Metadata id does not match \"${candidate.id}\"`,\n { deviceId: candidate.id },\n );\n }\n candidates.set(candidate.id, { definition, code: candidate.code });\n }\n const devices = new Map<string, IPreparedDevice>();\n const symbols = schematic.sheet.symbols.filter(\n (symbol) => symbolRole(symbol.device) === 'component',\n );\n for (const symbol of symbols) {\n if (devices.has(symbol.device)) continue;\n const candidate = candidates.get(symbol.device);\n if (candidate === undefined) {\n throw new SimulationRuntimeError(\n 'unresolved-device',\n `Missing prepared device \"${symbol.device}\"`,\n { deviceId: symbol.device },\n );\n }\n assertActive();\n try {\n const namespace = await importer(candidate.code, symbol.device);\n assertActive();\n if (\n !isRecord(namespace) ||\n !Object.hasOwn(namespace, 'model') ||\n !Object.hasOwn(namespace, 'create') ||\n typeof namespace.create !== 'function'\n ) {\n throw new TypeError('SDK device modules must export named model and synchronous create');\n }\n const model = validateDeviceIR(namespace.model);\n const pinNames = model.declarations\n .filter((declaration) => declaration.kind === 'pin')\n .map((pin) => pin.name);\n const metadataPins = candidate.definition.pins;\n if (metadataPins !== undefined && !sameNames(Object.keys(metadataPins), pinNames)) {\n throw new TypeError('Metadata pins do not match model pins');\n }\n const definition: DeviceMetadata = {\n ...candidate.definition,\n pins: metadataPins ?? Object.fromEntries(pinNames.map((name) => [name, {}])),\n };\n const geometry = deviceMetadataSymbol(definition);\n if (!sameNames(Object.keys(geometry.pins), pinNames)) {\n throw new TypeError('Symbol pins do not match model pins');\n }\n devices.set(symbol.device, {\n id: symbol.device,\n definition,\n model,\n create: namespace.create as DeviceLibraryEntry['create'],\n topics: new Map(\n Object.entries(definition.ports ?? {}).map(([port, topic]) => [\n port,\n { port, ...topic, delivery: resolveDelivery(topic.delivery, topic.type) },\n ]),\n ),\n });\n } catch (cause) {\n assertActive();\n throw new SimulationRuntimeError(\n 'invalid-device',\n `Device \"${symbol.device}\" failed to load: ${errorMessage(cause)}`,\n { deviceId: symbol.device, cause },\n );\n }\n }\n const provider: DeviceSymbolProvider = {\n getDeviceName: (reference) => devices.get(reference.raw)?.definition.displayName,\n getDeviceSymbol: (reference) => {\n const device = devices.get(reference.raw);\n return device === undefined ? undefined : deviceMetadataSymbol(device.definition);\n },\n };\n const topology = deriveSchematicTopology(schematic, { devices: provider });\n const empty =\n schematic.sheet.symbols.length === 0 &&\n schematic.sheet.wires.length === 0 &&\n schematic.sheet.junctions.length === 0;\n for (const name of voltageReferences.keys()) {\n if (!empty && !topology.nets.some((net) => net.name === name)) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n `Voltage reference names missing schematic net \"${name}\"`,\n );\n }\n }\n return {\n instances: symbols.map((symbol) => ({\n symbol: symbol.id,\n device: devices.get(symbol.device)!,\n })),\n ...(input.execution === undefined ? {} : { execution: input.execution }),\n description: {\n instances: symbols.map((symbol) => ({\n id: symbol.id,\n type: symbol.id,\n props: resolveProperties(symbol, devices.get(symbol.device)!, assets.get(symbol.id)),\n })),\n nets: topology.nets.map((net, index) => {\n const reference = net.name === null ? undefined : voltageReferences.get(net.name);\n const grounded = net.members.some((member) => member.kind === 'ground');\n if (grounded && reference !== undefined && reference !== 0) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n `Conflicting voltage references on ground net \"${net.name}\": 0 and ${reference}`,\n );\n }\n const voltage = grounded ? 0 : reference;\n return {\n id: `net:${index}`,\n pins: net.members.flatMap((member) =>\n member.kind === 'pin' ? [{ instance: member.symbolId, pin: member.pinId }] : [],\n ),\n ...(voltage === undefined ? {} : { voltage }),\n };\n }),\n },\n };\n}\n\nfunction resolveProperties(\n symbol: SchematicSymbol,\n device: IPreparedDevice,\n assets: ReadonlyMap<string, Uint8Array> | undefined,\n): Readonly<Record<string, PropertyInput>> {\n const values: Record<string, unknown> = Object.create(null);\n for (const [key, descriptor] of Object.entries(device.definition.properties ?? {})) {\n if (Object.hasOwn(descriptor, 'default')) values[key] = descriptor.default;\n }\n Object.assign(values, symbol.properties);\n const props: Record<string, PropertyInput> = Object.create(null);\n for (const [key, value] of Object.entries(values)) {\n if (isAssetReference(value)) {\n const problem = assetSrcError(value.mode, value.src);\n if (problem !== undefined)\n throw new SimulationRuntimeError('invalid-input', problem, { deviceId: device.id });\n const bytes = assets?.get(value.src);\n if (bytes === undefined) {\n throw new SimulationRuntimeError(\n 'unresolved-asset',\n `Symbol \"${symbol.id}\" is missing resource \"${value.src}\"`,\n { deviceId: device.id },\n );\n }\n props[key] = new Uint8Array(bytes);\n } else if (value instanceof Uint8Array) props[key] = new Uint8Array(value);\n else if (\n value === null ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'string'\n )\n props[key] = value;\n else\n throw new SimulationRuntimeError(\n 'invalid-input',\n `Unsupported property \"${symbol.id}.${key}\"`,\n { deviceId: device.id },\n );\n }\n return props;\n}\n\nfunction readVoltageReferences(value: unknown): ReadonlyMap<string, number> {\n if (value === undefined) return new Map();\n if (\n !isRecord(value) ||\n (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)\n ) {\n throw new SimulationRuntimeError('invalid-input', 'Expected a plain voltageReferences map');\n }\n const references = new Map<string, number>();\n for (const name of Reflect.ownKeys(value)) {\n const voltage = typeof name === 'string' ? value[name] : undefined;\n if (\n typeof name !== 'string' ||\n name.trim().length === 0 ||\n typeof voltage !== 'number' ||\n !Number.isFinite(voltage)\n ) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n 'Expected voltageReferences with nonempty net names and finite numeric voltages',\n );\n }\n references.set(name, voltage);\n }\n return references;\n}\n\nfunction readAssets(value: unknown): ReadonlyMap<string, ReadonlyMap<string, Uint8Array>> {\n const result = new Map<string, ReadonlyMap<string, Uint8Array>>();\n if (value === undefined) return result;\n if (!isRecord(value))\n throw new SimulationRuntimeError('invalid-input', 'Expected assets keyed by symbol id');\n for (const [symbol, entries] of Object.entries(value)) {\n if (!isRecord(entries))\n throw new SimulationRuntimeError('invalid-input', 'Expected asset entries keyed by src');\n const assets = new Map<string, Uint8Array>();\n for (const [src, bytes] of Object.entries(entries)) {\n if (!src || !(bytes instanceof Uint8Array))\n throw new SimulationRuntimeError('invalid-input', 'Resource bytes must be Uint8Array');\n assets.set(src, new Uint8Array(bytes));\n }\n result.set(symbol, assets);\n }\n return result;\n}\n\nfunction sameNames(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((name) => right.includes(name));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n","import { addTime, timePs } from '@mica-js/core';\nimport type { TimePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { Disposable, Event } from '@mica-js/core/lifecycle';\nimport type { DeliveryKind } from '@mica-js/document/canvas';\nimport { createBoard, createDeviceLibrary } from '../runtime';\nimport { publishGate } from '../runtime/publish-gate';\nimport type { Board, DeviceContext, RuntimeDiagnostic, TopicBridge, TopicMessage } from '../types';\nimport { errorMessage, SimulationRuntimeError } from './errors';\nimport { copyPayload, payloadMatches, samePayload, targetKey } from './payload';\nimport { prepareSimulation } from './prepare';\nimport type { IPreparedDeviceTopic, IPreparedInstance, IResolvedSimulation } from './prepare';\nimport type {\n IPreparedSimulation,\n ISimulationDiagnostic,\n ISimulationMessage,\n ISimulationRuntime,\n ISimulationRuntimeOptions,\n ISimulationTickReport,\n} from './types';\n\ninterface IOutput {\n readonly symbol: string;\n readonly port: string;\n readonly payload: unknown;\n readonly delivery: DeliveryKind;\n}\ninterface IDelivery {\n readonly symbol: string;\n readonly port: string;\n readonly payload: unknown;\n}\ninterface ILoadedRuntime {\n readonly prepared: IResolvedSimulation;\n readonly board: Board;\n readonly inputs: ReadonlyMap<string, IPreparedDeviceTopic>;\n readonly outputs: IOutput[];\n readonly diagnostics: ISimulationDiagnostic[];\n readonly subscriptions: readonly Disposable[];\n}\n\n/** Runs self-contained SDK devices on an atomic, replaceable Board. */\nexport function createSimulationRuntime(\n options: ISimulationRuntimeOptions = {},\n): ISimulationRuntime {\n const publishes = new Emitter<ISimulationMessage>();\n const diagnostics = new Emitter<ISimulationDiagnostic>();\n const pending: IDelivery[] = [];\n const published = new Map<string, unknown>();\n let active: ILoadedRuntime | undefined;\n let simTime = timePs(0);\n let disposed = false;\n let generation = 0;\n\n const assertActive = (): void => {\n if (disposed)\n throw new SimulationRuntimeError('disposed', 'Simulation runtime has been disposed');\n };\n const flush = (loaded: ILoadedRuntime): void => {\n // Without a publish listener nothing can observe these messages, and no listener can be added\n // while this loop runs, so the copies and messages are skipped instead of built and dropped.\n if (publishes.hasListeners) {\n for (const output of loaded.outputs.splice(0)) {\n if (output.delivery === 'level') {\n const key = targetKey(output.symbol, output.port);\n if (published.has(key) && samePayload(published.get(key), output.payload)) continue;\n // Keep the equality baseline independent from buffers/objects handed to listeners.\n if (publishes.hasListeners) published.set(key, copyPayload(output.payload));\n }\n // The publish snapshot in `outputs` is already an owned copy, so listeners may share it.\n publishes.fire({\n target: { symbol: output.symbol, port: output.port },\n payload: output.payload,\n simTime,\n });\n }\n } else {\n loaded.outputs.length = 0;\n }\n for (const diagnostic of loaded.diagnostics.splice(0)) {\n diagnostics.fire(\n diagnostic.runtimeCode === undefined ? { ...diagnostic, simTime } : diagnostic,\n );\n }\n };\n const release = (loaded: ILoadedRuntime | undefined): void => {\n if (loaded === undefined) return;\n try {\n loaded.board.dispose();\n } catch (cause) {\n diagnostics.fire({\n code: 'board/diagnostic',\n symbol: '',\n message: errorMessage(cause),\n simTime,\n phase: 'dispose',\n });\n } finally {\n for (const subscription of loaded.subscriptions) subscription.dispose();\n }\n };\n const install = (next: ILoadedRuntime): void => {\n const previous = active;\n active = next;\n pending.length = 0;\n published.clear();\n simTime = timePs(0);\n release(previous);\n };\n return {\n async load(input: IPreparedSimulation): Promise<void> {\n assertActive();\n const current = ++generation;\n const prepared = await prepareSimulation(\n input,\n options.importer ?? importBlobModule,\n assertActive,\n );\n assertActive();\n if (current !== generation) return;\n install(buildLoadedRuntime(prepared, () => publishes.hasListeners));\n },\n async reset(): Promise<void> {\n assertActive();\n ++generation;\n if (active !== undefined)\n install(buildLoadedRuntime(active.prepared, () => publishes.hasListeners));\n else {\n pending.length = 0;\n published.clear();\n simTime = timePs(0);\n }\n },\n async tick(dt: TimePs): Promise<ISimulationTickReport> {\n assertActive();\n if (!Number.isSafeInteger(dt) || dt <= 0)\n throw new TypeError('tick expects a positive integer dt in picoseconds');\n // Check the cumulative bound before consuming queued inputs or touching the board.\n const target = addTime(simTime, dt);\n const loaded = active;\n if (loaded === undefined) {\n simTime = target;\n return { simTime, executed: 0 };\n }\n try {\n for (const delivery of pending.splice(0)) {\n loaded.board.topics.publish(\n scopedTopic(delivery.symbol, delivery.port),\n delivery.payload,\n );\n }\n loaded.board.runUntil(target);\n } finally {\n simTime = timePs(loaded.board.time);\n flush(loaded);\n }\n return { simTime, executed: 1 };\n },\n async deliver(message: ISimulationMessage): Promise<void> {\n assertActive();\n if (\n message === null ||\n typeof message !== 'object' ||\n message.target === null ||\n typeof message.target !== 'object' ||\n typeof message.target.symbol !== 'string' ||\n typeof message.target.port !== 'string'\n ) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n 'Expected a message with string symbol and port',\n );\n }\n if (active === undefined)\n throw new SimulationRuntimeError('not-loaded', 'No simulation loaded');\n const { symbol, port } = message.target;\n const topic = active.inputs.get(targetKey(symbol, port));\n if (topic === undefined || !payloadMatches(topic.type, message.payload)) {\n throw new SimulationRuntimeError(\n 'invalid-input',\n `Unknown input or invalid payload for ${symbol}.${port}`,\n );\n }\n if (topic.delivery === 'level') {\n const previous = pending.findIndex(\n (entry) => entry.symbol === symbol && entry.port === port,\n );\n if (previous !== -1) pending.splice(previous, 1);\n }\n pending.push({ symbol, port, payload: copyPayload(message.payload) });\n },\n onDidPublish: publishes.event,\n onDidDiagnostic: diagnostics.event,\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n ++generation;\n pending.length = 0;\n published.clear();\n release(active);\n active = undefined;\n publishes.dispose();\n diagnostics.dispose();\n },\n };\n}\n\nfunction buildLoadedRuntime(\n prepared: IResolvedSimulation,\n publishObserved: () => boolean,\n): ILoadedRuntime {\n const outputs: IOutput[] = [];\n const found: ISimulationDiagnostic[] = [];\n const inputs = new Map<string, IPreparedDeviceTopic>();\n const library = createDeviceLibrary(\n prepared.instances.map((instance) => {\n for (const topic of instance.device.topics.values()) {\n if (topic.direction === 'input') inputs.set(targetKey(instance.symbol, topic.port), topic);\n }\n return {\n id: instance.symbol,\n model: instance.device.model,\n create: (context: DeviceContext) =>\n instance.device.create({\n ...context,\n topics: scopeTopics(context.topics, instance, outputs, found, publishObserved),\n }),\n };\n }),\n );\n // Board captures bytes, but clone per creation as well so a factory cannot alter reset inputs.\n const description = {\n ...prepared.description,\n instances: prepared.description.instances.map((instance) => ({\n ...instance,\n props: Object.fromEntries(\n Object.entries(instance.props ?? {}).map(([key, value]) => [\n key,\n value instanceof Uint8Array ? new Uint8Array(value) : value,\n ]),\n ),\n })),\n };\n const board = createBoard(\n library,\n description,\n prepared.execution === undefined ? {} : { execution: prepared.execution },\n );\n const project = (diagnostic: RuntimeDiagnostic, fatal: boolean): void => {\n found.push({\n code: fatal\n ? diagnostic.phase === 'topic'\n ? 'device/input-failed'\n : diagnostic.phase === 'sync'\n ? 'device/output-failed'\n : 'board/error'\n : 'board/diagnostic',\n symbol: diagnostic.instanceId ?? '',\n message: diagnostic.message,\n simTime: timePs(diagnostic.time ?? board.time),\n runtimeCode: diagnostic.code,\n phase: diagnostic.phase,\n });\n };\n return {\n prepared,\n board,\n inputs,\n outputs,\n diagnostics: found,\n subscriptions: [\n board.onDidError((event) => project(event, true)),\n board.onDidDiagnostic((event) => project(event, false)),\n ],\n };\n}\n\n/**\n * Board topics are opaque global strings; this boundary gives each factory local port names.\n *\n * Exported for the fan-out regression test, which drives it against a real `Board`: every accepted\n * output must still reach `board.topics` listeners even when the instance has no scoped subscriber.\n *\n * `publishObserved` reports whether anything outside the board consumes published messages; with no\n * scoped subscriber, no owner-less bridge listener and no consumer, an accepted output is dropped\n * before it is copied, fanned out or queued, while the bridge's internal publish gate keeps the\n * board's call admission.\n */\nexport function scopeTopics(\n bridge: TopicBridge,\n instance: IPreparedInstance,\n outputs: IOutput[],\n diagnostics: ISimulationDiagnostic[],\n publishObserved: () => boolean,\n): TopicBridge {\n const prefix = `${encodeURIComponent(instance.symbol)}/`;\n const gate = publishGate(bridge);\n let scopedListeners = 0;\n const unobserved = (): boolean =>\n scopedListeners === 0 && gate.hostListeners() === 0 && !publishObserved();\n return {\n onDidReceive: ((listener, thisArgs, disposables) => {\n const subscription = bridge.onDidReceive(\n (message) => {\n if (!message.topic.startsWith(prefix)) return;\n const port = message.topic.slice(prefix.length);\n if (instance.device.topics.get(port)?.direction !== 'input') return;\n return listener.call(thisArgs, { topic: port, payload: copyPayload(message.payload) });\n },\n undefined,\n undefined,\n );\n scopedListeners++;\n let active = true;\n const disposable = {\n dispose: () => {\n if (active) {\n active = false;\n scopedListeners--;\n subscription.dispose();\n }\n },\n };\n disposables?.push(disposable);\n return disposable;\n }) as Event<TopicMessage>,\n publish(port, payload): void {\n const topic = instance.device.topics.get(port);\n if (topic?.direction !== 'output' || !payloadMatches(topic.type, payload)) {\n diagnostics.push({\n code: 'device/output-failed',\n symbol: instance.symbol,\n port,\n message: `Unknown output or invalid payload for ${instance.symbol}.${port}`,\n simTime: timePs(0),\n });\n return;\n }\n // Publish would copy first and only then enforce the phase, disposed and faulted guards, so\n // the skipped path keeps the guard on its own instead of losing the error.\n if (unobserved()) {\n gate.assertPublishAllowed();\n return;\n }\n const snapshot = copyPayload(payload);\n // Publish first so Board still enforces its phase and disposed/faulted guards.\n bridge.publish(scopedTopic(instance.symbol, port), snapshot);\n outputs.push({ symbol: instance.symbol, port, payload: snapshot, delivery: topic.delivery });\n },\n };\n}\n\nfunction scopedTopic(symbol: string, port: string): string {\n return `${encodeURIComponent(symbol)}/${port}`;\n}\n\nfunction importBlobModule(code: string): Promise<unknown> {\n if (\n typeof URL === 'undefined' ||\n typeof URL.createObjectURL !== 'function' ||\n typeof Blob === 'undefined'\n ) {\n return Promise.reject(new Error('Inject a module importer outside a browser worker'));\n }\n const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));\n return import(/* @vite-ignore */ url).finally(() => URL.revokeObjectURL(url));\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport { copyBytePayload } from './payload';\nimport {\n simulationRuntimeEventTransfer,\n simulationRuntimeService,\n simulationRuntimeTopicService,\n} from './rpc';\nimport type { ISimulationRuntimeRpc, ISimulationRuntimeTopicRpc } from './rpc';\nimport { createSimulationRuntime } from './runtime';\nimport type {\n ISimulationMessage,\n ISimulationRuntime,\n SimulationModuleImporter,\n ISimulationRuntimeOptions,\n} from './types';\n\n/** Startup options of the in-process runtime guest; none of them travel over RPC. */\nexport interface ISimulationRuntimeGuestOptions {\n readonly importer?: SimulationModuleImporter;\n /** Extra ports the worker received; the first one is the direct topic channel. */\n readonly ports?: readonly MessagePort[];\n}\n\n/** Running runtime guest: where the typed service lives and which ports it owns. */\nexport interface ISimulationRuntimeGuest {\n readonly rpc: RpcEndpoint;\n readonly ports: readonly MessagePort[];\n readonly runtime: ISimulationRuntime;\n dispose(): Promise<void>;\n}\n\n/** Registrations that put one runtime on an existing endpoint and its topic port. */\nexport interface IRegisteredSimulationRuntime {\n dispose(): void;\n}\n\n/**\n * Registers the prepared simulation runtime as `simulation-runtime` on an existing endpoint.\n *\n * The primary endpoint gets the full control surface and diagnostics; `topicRpc`, when present,\n * gets `deliver` plus `onDidPublish` only, so a widget guest talks to the simulation directly.\n * Both registrations share the one runtime instance and are released together. The caller owns\n * `rpc` and `topicRpc`; this function only owns the registrations it creates.\n */\nexport function registerSimulationRuntimeServices(\n rpc: RpcEndpoint,\n runtime: ISimulationRuntime,\n topicRpc?: RpcEndpoint,\n): IRegisteredSimulationRuntime {\n const service = createRuntimeService(runtime);\n const serviceRegistration = rpc.register(simulationRuntimeService, service, {\n transfer: simulationRuntimeEventTransfer,\n });\n const topicRegistration =\n topicRpc === undefined\n ? undefined\n : topicRpc.register(\n simulationRuntimeTopicService,\n {\n deliver: service.deliver,\n onDidPublish: service.onDidPublish,\n // The empty reply follows earlier callbacks on this port, providing a FIFO barrier.\n async flushPublishes() {},\n },\n { transfer: simulationRuntimeEventTransfer },\n );\n\n let disposed = false;\n return {\n dispose(): void {\n if (disposed) return;\n disposed = true;\n try {\n topicRegistration?.dispose();\n } finally {\n serviceRegistration.dispose();\n }\n },\n };\n}\n\n/**\n * Starts the prepared simulation runtime on one sandbox RPC port.\n *\n * A worker script calls this after taking `event.ports[0]`; extra ports stay in order. The returned\n * node owns the runtime and disposes it with the registrations.\n */\nexport function startSimulationRuntimeGuest(\n port: MessagePort,\n options: ISimulationRuntimeGuestOptions = {},\n): ISimulationRuntimeGuest {\n const rpc = createRpc(port);\n const runtime = createSimulationRuntime(runtimeOptions(options));\n const ports = options.ports ?? [];\n const topicPort = ports[0];\n const topicRpc = topicPort === undefined ? undefined : createRpc(topicPort);\n const registered = registerSimulationRuntimeServices(rpc, runtime, topicRpc);\n let disposed = false;\n return {\n rpc,\n ports,\n runtime,\n async dispose(): Promise<void> {\n if (disposed) return;\n disposed = true;\n try {\n registered.dispose();\n await runtime.dispose();\n } finally {\n topicRpc?.dispose();\n rpc.dispose();\n port.close();\n for (const extra of ports) extra.close();\n }\n },\n };\n}\n\nfunction runtimeOptions(options: ISimulationRuntimeGuestOptions): ISimulationRuntimeOptions {\n return {\n ...(options.importer === undefined ? {} : { importer: options.importer }),\n };\n}\n\nfunction createRuntimeService(runtime: ISimulationRuntime): ISimulationRuntimeRpc {\n const onDidPublish: ISimulationRuntimeTopicRpc['onDidPublish'] = (listener) => {\n const subscription = runtime.onDidPublish((message) => listener(copyMessage(message)));\n return () => subscription.dispose();\n };\n return {\n load: (input) => runtime.load(input),\n reset: () => runtime.reset(),\n tick: (dt) => runtime.tick(dt),\n deliver: (message) => runtime.deliver(message),\n onDidPublish,\n onDidDiagnostic(listener) {\n const subscription = runtime.onDidDiagnostic(listener);\n return () => subscription.dispose();\n },\n dispose: () => runtime.dispose(),\n };\n}\n\nfunction copyMessage(message: ISimulationMessage): ISimulationMessage {\n const payload = copyBytePayload(message.payload);\n return payload === message.payload ? message : { ...message, payload };\n}\n"],"mappings":";;;;;;;;;;AAsCA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,MAA2B,QAAgB,WAAoC,CAAC,GAAG;EAC7F,MAAM,MAAM;EACZ,KAAK,OAAO;EACZ,KAAK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