@mica-js/simulator 2.4.0 → 2.5.1

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  import { S as snapshot, _ as nextRandom, a as copyBytePayload, b as range, c as samePayload, d as captureValue, f as dataObject, g as integer, h as identity, i as simulationRuntimeTopicService, l as targetKey, m as finite, n as simulationRuntimeEventTransfer, o as copyPayload, p as externalValue, r as simulationRuntimeService, s as payloadMatches, u as bytesView, v as nonnegative, x as same, y as randomState } from "./rpc-BB5wM0QN.js";
2
2
  import { Emitter } from "@mica-js/core/lifecycle";
3
3
  import { BuildError, createJitBlockBuilder, validateBoundBlockIR, validateDeviceIR } from "@mica-js/device-model";
4
- import { RESUMABLE_RECEIVE, checkBoolean, compileBody, compileComputation, compileDirectJit, compileResumableBody, createBytes, createEnum, createRecord, equalValues, nonNull, readIndex } from "@mica-js/compiler";
4
+ import { RESUMABLE_RECEIVE, checkBoolean, compileBody, compileComputation, compileDirectJit, compileResumableBody, compileSynchronousBody, createBytes, createEnum, createRecord, equalValues, nonNull, readIndex } from "@mica-js/compiler";
5
5
  import { addTime, timePs } from "@mica-js/core";
6
6
  import { assetSrcError } from "@mica-js/document";
7
7
  import { deriveSchematicTopology, deviceMetadataSymbol, isAssetReference, parseDeviceMetadata, parseDeviceReference, parseSchematic, symbolRole } from "@mica-js/document/schematic";
@@ -273,8 +273,14 @@ function arraysEqual(first, second) {
273
273
  for (let index = 0; index < first.length; index++) if (first[index] !== second[index]) return false;
274
274
  return true;
275
275
  }
276
- function sameConfiguration(previous, component) {
277
- if (previous.edges.length !== component.edges.length) return false;
276
+ function sameConfiguration(previous, component, nodes) {
277
+ const layout = component.nodes;
278
+ if (previous.nodes.length !== layout.length || previous.edges.length !== component.edges.length) return false;
279
+ for (let index = 0; index < layout.length; index++) {
280
+ const node = layout[index];
281
+ if (previous.nodes[index] !== node) return false;
282
+ if (!Object.is(previous.references[index], nodes[node].reference)) return false;
283
+ }
278
284
  for (let index = 0; index < previous.edges.length; index++) {
279
285
  const edge = previous.edges[index];
280
286
  const other = component.edges[index];
@@ -928,20 +934,13 @@ function createElectricalNetwork(inputPins, inputNets) {
928
934
  applyLeaf(updatedSlots.length);
929
935
  return changedSlots.length === 0 ? emptySlots : changedSlots;
930
936
  }
931
- if (blocksStale) {
932
- blocksStale = false;
933
- cache = /* @__PURE__ */ new Map();
934
- topologyChanged = true;
935
- }
936
- const updates = /* @__PURE__ */ new Map();
937
- for (let position = 0; position < updatedSlots.length; position++) updates.set(updatedSlots[position], {
938
- intent: updatedIntents[position],
939
- edges: updatedEdges[position]
940
- });
937
+ if (blocksStale) topologyChanged = true;
938
+ const updated = updatedSlots.length;
941
939
  if (prepared !== void 0 && !topologyChanged && replacedEdges.length === 0) {
942
- for (const [index, update] of updates) {
943
- intents[index] = update.intent;
944
- pinEdges[index] = update.edges;
940
+ for (let position = 0; position < updated; position++) {
941
+ const index = updatedSlots[position];
942
+ intents[index] = updatedIntents[position];
943
+ pinEdges[index] = updatedEdges[position];
945
944
  }
946
945
  statistics.solves++;
947
946
  statistics.cacheHits += prepared.blocks.length;
@@ -951,18 +950,22 @@ function createElectricalNetwork(inputPins, inputNets) {
951
950
  let topology = prepared;
952
951
  let bucket;
953
952
  let restored;
953
+ /** Prospective rebuilds; committed only when the batch is accepted. */
954
+ let topologyPrepares = 0;
954
955
  const dirtyBlocks = /* @__PURE__ */ new Map();
955
956
  for (let position = 0; position < updatedEdgeSlots.length; position++) updatedEdgeLists[updatedEdgeSlots[position]] = void 0;
956
957
  updatedEdgeSlots.length = 0;
957
- for (const [index, update] of updates) {
958
- updatedEdgeLists[index] = update.edges;
958
+ for (let position = 0; position < updated; position++) {
959
+ const index = updatedSlots[position];
960
+ updatedEdgeLists[index] = updatedEdges[position];
959
961
  updatedEdgeSlots.push(index);
960
962
  }
961
963
  if (topologyChanged) {
962
964
  let hash = topologyHash;
963
965
  let spread = topologySpread;
964
- for (const [index, update] of updates) {
965
- const next = hashEdges(index, update.edges);
966
+ for (let position = 0; position < updated; position++) {
967
+ const index = updatedSlots[position];
968
+ const next = hashEdges(index, updatedEdges[position]);
966
969
  const previous = pinHashes[index];
967
970
  if (next === previous) continue;
968
971
  hash += next - previous;
@@ -973,9 +976,9 @@ function createElectricalNetwork(inputPins, inputNets) {
973
976
  if (restored !== void 0) topology = restoreTopology(restored.topology, pinEdges, updatedEdgeLists);
974
977
  else {
975
978
  const nextEdges = pinEdges.slice();
976
- for (const [index, update] of updates) nextEdges[index] = update.edges;
979
+ for (let position = 0; position < updated; position++) nextEdges[updatedSlots[position]] = updatedEdges[position];
977
980
  topology = prepareTopology(nodes, nextEdges);
978
- statistics.topologyPrepares++;
981
+ topologyPrepares++;
979
982
  }
980
983
  } else {
981
984
  const dirty = /* @__PURE__ */ new Set();
@@ -993,7 +996,7 @@ function createElectricalNetwork(inputPins, inputNets) {
993
996
  for (const block of topologyChanged ? topology.blocks : dirtyBlocks.values()) {
994
997
  const { component, key } = block;
995
998
  const previous = cache.get(key);
996
- if (previous !== void 0 && sameConfiguration(previous, component)) {
999
+ if (previous !== void 0 && sameConfiguration(previous, component, nodes)) {
997
1000
  cacheHits++;
998
1001
  (nextCache ??= /* @__PURE__ */ new Map()).set(key, previous);
999
1002
  continue;
@@ -1083,6 +1086,8 @@ function createElectricalNetwork(inputPins, inputNets) {
1083
1086
  }
1084
1087
  }
1085
1088
  const entry = {
1089
+ nodes: component.nodes,
1090
+ references: component.nodes.map((node) => nodes[node].reference),
1086
1091
  edges: component.edges,
1087
1092
  voltages: component.nodes.map((node) => voltages.get(node)),
1088
1093
  factorization
@@ -1112,11 +1117,13 @@ function createElectricalNetwork(inputPins, inputNets) {
1112
1117
  if (changedSlots.length > 1) changedSlots.sort(ascendingSlot);
1113
1118
  for (const [pin, sample] of pending) pin.sample = sample;
1114
1119
  for (const [node, voltage] of pendingVoltages) publishedVoltages[node] = voltage;
1115
- for (const [index, update] of updates) {
1116
- syncDegrees(pinEdges[index], update.edges);
1117
- intents[index] = update.intent;
1118
- pinEdges[index] = update.edges;
1119
- setPinHash(index, update.edges);
1120
+ for (let position = 0; position < updated; position++) {
1121
+ const index = updatedSlots[position];
1122
+ const edges = updatedEdges[position];
1123
+ syncDegrees(pinEdges[index], edges);
1124
+ intents[index] = updatedIntents[position];
1125
+ pinEdges[index] = edges;
1126
+ setPinHash(index, edges);
1120
1127
  }
1121
1128
  if (topologyChanged) cache = nextCache ?? /* @__PURE__ */ new Map();
1122
1129
  else {
@@ -1125,6 +1132,7 @@ function createElectricalNetwork(inputPins, inputNets) {
1125
1132
  }
1126
1133
  prepared = topology;
1127
1134
  componentArraysOwned = false;
1135
+ blocksStale = false;
1128
1136
  if (topologyChanged) {
1129
1137
  const admitted = restored !== void 0 && topology === restored.topology ? restored : {
1130
1138
  id: restored?.id ?? nextTopologyId++,
@@ -1140,6 +1148,7 @@ function createElectricalNetwork(inputPins, inputNets) {
1140
1148
  statistics.factorizations += factorizations;
1141
1149
  statistics.factorizationReuses += factorizationReuses;
1142
1150
  statistics.cacheHits += cacheHits;
1151
+ statistics.topologyPrepares += topologyPrepares;
1143
1152
  flushAdmissions();
1144
1153
  return changedSlots.length === 0 ? emptySlots : changedSlots;
1145
1154
  }
@@ -1811,6 +1820,12 @@ function compileObservation(target, key, path) {
1811
1820
  var compiledBodies = /* @__PURE__ */ new WeakMap();
1812
1821
  var resumablePrograms = /* @__PURE__ */ new WeakMap();
1813
1822
  var compiledComputations = /* @__PURE__ */ new WeakMap();
1823
+ /**
1824
+ * Synchronous programs are instance independent, but their static function resolution
1825
+ * belongs to one device model. The outer key prevents reusing a root region compiled
1826
+ * against another model's function table; `null` records a whole-body fallback.
1827
+ */
1828
+ var synchronousPrograms = /* @__PURE__ */ new WeakMap();
1814
1829
  var MAX_TIME = 72e14;
1815
1830
  function time(value) {
1816
1831
  if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) throw new TypeError("Time must be a finite integer");
@@ -1825,6 +1840,30 @@ function body(region) {
1825
1840
  }
1826
1841
  return result;
1827
1842
  }
1843
+ /**
1844
+ * Compile one reaction body for one device model. Static callees are resolved from the
1845
+ * same declaration environment the generator uses. A compiler decline is cached as a
1846
+ * whole-body fallback; execution errors are never caught here and never replay effects.
1847
+ */
1848
+ function synchronousBody(instance, region) {
1849
+ const model = instance.entry.model;
1850
+ let cache = synchronousPrograms.get(model);
1851
+ if (cache === void 0) {
1852
+ cache = /* @__PURE__ */ new WeakMap();
1853
+ synchronousPrograms.set(model, cache);
1854
+ }
1855
+ const cached = cache.get(region);
1856
+ if (cached !== void 0) return cached ?? void 0;
1857
+ const program = compileSynchronousBody(region, {
1858
+ bindResources: true,
1859
+ resolveFunction: (name) => {
1860
+ const declaration = instance.declarations.get(name);
1861
+ return declaration?.kind === "function" ? declaration.body : void 0;
1862
+ }
1863
+ });
1864
+ cache.set(region, program ?? null);
1865
+ return program;
1866
+ }
1828
1867
  function resumable(region) {
1829
1868
  let result = resumablePrograms.get(region);
1830
1869
  if (result === void 0) {
@@ -1920,15 +1959,15 @@ function hasEvery(previous, next) {
1920
1959
  function createContext(owner, board) {
1921
1960
  return Object.freeze({
1922
1961
  get props() {
1923
- board.guard(owner, true);
1962
+ board.assertReadAllowed(owner);
1924
1963
  return Object.freeze(Object.fromEntries([...owner.props].map(([key, value]) => [key, externalValue(value)])));
1925
1964
  },
1926
1965
  get inputs() {
1927
- owner.guard();
1966
+ owner.assertCallAllowed();
1928
1967
  return owner.inputs();
1929
1968
  },
1930
1969
  get memory() {
1931
- board.guard(owner, true);
1970
+ board.assertReadAllowed(owner);
1932
1971
  return owner.publicMemory();
1933
1972
  },
1934
1973
  topics: board.topicBridge(owner),
@@ -1945,6 +1984,7 @@ var Instance = class {
1945
1984
  props = /* @__PURE__ */ new Map();
1946
1985
  constants = /* @__PURE__ */ new Map();
1947
1986
  states = /* @__PURE__ */ new Map();
1987
+ directBank;
1948
1988
  memories = /* @__PURE__ */ new Map();
1949
1989
  memoryViews = /* @__PURE__ */ new Map();
1950
1990
  memorySizes = /* @__PURE__ */ new Map();
@@ -2000,11 +2040,7 @@ var Instance = class {
2000
2040
  this.random = randomState(seed, id, override);
2001
2041
  this.host = {
2002
2042
  read: (kind, name) => this.read(kind, name),
2003
- write: (name, value) => {
2004
- const slot = this.stateSlot(name);
2005
- this.states.set(name, snapshot(value));
2006
- this.board.invalidate(slot);
2007
- },
2043
+ write: (name, value) => this.writeState(name, value, this.stateSlot(name)),
2008
2044
  sample: (ref) => {
2009
2045
  return this.readSample(ref);
2010
2046
  },
@@ -2263,7 +2299,28 @@ var Instance = class {
2263
2299
  if (!bytes) throw new TypeError(`Unknown memory ${String(ref)}`);
2264
2300
  return bytes;
2265
2301
  }
2266
- /** Cached resource bookkeeping for state and memory, resolved once per declaration name. */
2302
+ /** Instance-owned numeric bank, mirrored by every non-direct state write. */
2303
+ directStateBank() {
2304
+ if (this.directBank === void 0) {
2305
+ const stateNames = [...this.states.keys()].filter((name) => {
2306
+ const declaration = this.declarations.get(name);
2307
+ return declaration.type.kind === "number" || declaration.type.kind === "bool";
2308
+ });
2309
+ this.directBank = {
2310
+ stateNames: Object.freeze(stateNames),
2311
+ states: new Map(stateNames.map((name, index) => [name, index])),
2312
+ stateValues: stateNames.map((name) => this.states.get(name))
2313
+ };
2314
+ }
2315
+ return this.directBank;
2316
+ }
2317
+ writeState(name, value, slot) {
2318
+ const captured = snapshot(value);
2319
+ this.states.set(name, captured);
2320
+ const index = this.directBank?.states.get(name);
2321
+ if (index !== void 0) this.directBank.stateValues[index] = captured;
2322
+ this.board.invalidate(slot);
2323
+ }
2267
2324
  stateSlot(name) {
2268
2325
  let slot = this.stateSlots.get(name);
2269
2326
  if (slot === void 0) {
@@ -2303,6 +2360,7 @@ var Instance = class {
2303
2360
  jit.directPrograms.clear();
2304
2361
  jit.directProgramRevision = -1;
2305
2362
  jit.directSkip = void 0;
2363
+ jit.directMisses = 0;
2306
2364
  if (jit.direct?.frame.resume) jit.direct.frame.stopAfterInstruction = true;
2307
2365
  else jit.direct = void 0;
2308
2366
  }
@@ -2379,8 +2437,7 @@ var Instance = class {
2379
2437
  },
2380
2438
  write: (value) => {
2381
2439
  const current = resolve();
2382
- states.set(name, snapshot(value));
2383
- this.board.invalidate(current);
2440
+ this.writeState(name, value, current);
2384
2441
  }
2385
2442
  });
2386
2443
  }
@@ -2496,6 +2553,7 @@ var Instance = class {
2496
2553
  instance: this,
2497
2554
  declaration,
2498
2555
  previous: void 0,
2556
+ synchronousProgram: synchronousBody(this, declaration.body) ?? null,
2499
2557
  frame: void 0
2500
2558
  });
2501
2559
  }
@@ -2548,18 +2606,18 @@ var Instance = class {
2548
2606
  }
2549
2607
  this.memorySizes.clear();
2550
2608
  }
2551
- guard() {
2552
- this.board.guard(this);
2609
+ assertCallAllowed() {
2610
+ this.board.assertCallAllowed(this);
2553
2611
  }
2554
2612
  inputs() {
2555
2613
  const result = Object.create(null);
2556
2614
  for (const declaration of this.entry.model.declarations) {
2557
2615
  if (declaration.kind === "channel" && declaration.direction === "input") result[declaration.name] = Object.freeze({ send: (value) => {
2558
- this.guard();
2616
+ this.assertCallAllowed();
2559
2617
  this.send(declaration.name, value, true);
2560
2618
  } });
2561
2619
  if (declaration.kind === "notification" && declaration.direction === "input") result[declaration.name] = Object.freeze({ notify: () => {
2562
- this.guard();
2620
+ this.assertCallAllowed();
2563
2621
  this.notificationInputs.add(declaration.name);
2564
2622
  } });
2565
2623
  }
@@ -2568,7 +2626,7 @@ var Instance = class {
2568
2626
  publicMemory() {
2569
2627
  const result = Object.create(null);
2570
2628
  for (const declaration of this.entry.model.declarations) if (declaration.kind === "memory" && declaration.public) result[declaration.name] = bytesView(this.memory(declaration.name), () => {
2571
- this.board.validity(this);
2629
+ this.board.assertAlive(this);
2572
2630
  if (![
2573
2631
  "idle",
2574
2632
  "initialize",
@@ -2599,7 +2657,7 @@ var Instance = class {
2599
2657
  });
2600
2658
  }
2601
2659
  attach(options) {
2602
- this.guard();
2660
+ this.assertCallAllowed();
2603
2661
  if (this.board.phase !== "initialize" || this.board.current !== this) throw this.board.error("INVALID_CALL_STATE", "attachJit is initialization-only", this);
2604
2662
  dataObject(options, [
2605
2663
  "entry",
@@ -2624,12 +2682,40 @@ var Instance = class {
2624
2682
  if (Object.hasOwn(options, "polling")) {
2625
2683
  if (!Array.isArray(options.polling)) throw new TypeError("polling must be an array");
2626
2684
  for (const item of options.polling) {
2627
- dataObject(item, ["pc", "predicate"]);
2685
+ dataObject(item, [
2686
+ "pc",
2687
+ "predicate",
2688
+ "consume",
2689
+ "wait"
2690
+ ]);
2628
2691
  const pc = finite(item.pc, "polling pc");
2629
2692
  const predicate = identity(item.predicate);
2630
2693
  const declaration = this.declarations.get(predicate);
2631
2694
  if (polling.has(pc) || declaration?.kind !== "function" || !declaration.pure || declaration.params.length || declaration.returns?.kind !== "bool") throw this.board.error("INVALID_BINDING", "Invalid polling declaration", this);
2632
- polling.set(pc, predicate);
2695
+ let consume;
2696
+ if (Object.hasOwn(item, "consume")) {
2697
+ consume = identity(item.consume);
2698
+ const fn = this.declarations.get(consume);
2699
+ if (fn?.kind !== "function" || fn.params.length !== 0 || fn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling consume function", this);
2700
+ }
2701
+ let wait;
2702
+ if (Object.hasOwn(item, "wait")) {
2703
+ dataObject(item.wait, ["delay", "advance"]);
2704
+ const delay = identity(item.wait.delay);
2705
+ const advance = identity(item.wait.advance);
2706
+ const delayFn = this.declarations.get(delay);
2707
+ const advanceFn = this.declarations.get(advance);
2708
+ if (delayFn?.kind !== "function" || !delayFn.pure || delayFn.params.length !== 0 || delayFn.returns?.kind !== "number" || advanceFn?.kind !== "function" || advanceFn.params.length !== 1 || advanceFn.params[0].type.kind !== "number" || advanceFn.returns !== void 0) throw this.board.error("INVALID_BINDING", "Invalid polling wait functions", this);
2709
+ wait = Object.freeze({
2710
+ delay,
2711
+ advance
2712
+ });
2713
+ }
2714
+ polling.set(pc, Object.freeze({
2715
+ predicate,
2716
+ ...consume === void 0 ? {} : { consume },
2717
+ ...wait === void 0 ? {} : { wait }
2718
+ }));
2633
2719
  }
2634
2720
  }
2635
2721
  if (Object.hasOwn(options, "delays") && !(options.delays instanceof Map)) throw new TypeError("delays must be a Map");
@@ -2652,12 +2738,14 @@ var Instance = class {
2652
2738
  directProgramRevision: -1,
2653
2739
  direct: void 0,
2654
2740
  directSkip: void 0,
2741
+ directMisses: 0,
2655
2742
  pollReads: void 0,
2656
2743
  currentPc: void 0,
2657
2744
  automaticPolling: false,
2658
2745
  pollingWait: false,
2659
2746
  pollingPeriod: 0,
2660
2747
  pollingOrigin: 0,
2748
+ pollingToken: 0,
2661
2749
  active: true,
2662
2750
  stopped: false,
2663
2751
  queued: false,
@@ -2670,6 +2758,7 @@ var Instance = class {
2670
2758
  jit.active = false;
2671
2759
  jit.execution = void 0;
2672
2760
  delete jit.predicate;
2761
+ jit.pollingToken++;
2673
2762
  this.board.waitingJits.delete(jit);
2674
2763
  jit.cache.clear();
2675
2764
  jit.directPrograms.clear();
@@ -2680,7 +2769,7 @@ var Instance = class {
2680
2769
  return disposable;
2681
2770
  }
2682
2771
  loadBytes(name, bytes, offset) {
2683
- this.guard();
2772
+ this.assertCallAllowed();
2684
2773
  if (this.board.phase !== "idle" && !(this.board.phase === "initialize" && this.board.current === this)) throw this.board.error("INVALID_CALL_STATE", "Code loading is not allowed in this phase", this);
2685
2774
  if (typeof name !== "string" || !this.jits.some((jit) => jit.active && jit.options.code === name)) throw this.board.error("INVALID_BINDING", "Memory is not bound as code", this);
2686
2775
  if (!(bytes instanceof Uint8Array)) throw new TypeError("Code must be Uint8Array");
@@ -2706,6 +2795,18 @@ var Instance = class {
2706
2795
  }
2707
2796
  };
2708
2797
  //#endregion
2798
+ //#region src/runtime/publish-gate.ts
2799
+ var gates = /* @__PURE__ */ new WeakMap();
2800
+ /** Attach the gate to the facade the board hands out; never exposed through the package entry. */
2801
+ function registerPublishGate(bridge, gate) {
2802
+ gates.set(bridge, gate);
2803
+ }
2804
+ function publishGate(bridge) {
2805
+ const gate = gates.get(bridge);
2806
+ if (gate === void 0) throw new TypeError("Topic bridge was not created by a board");
2807
+ return gate;
2808
+ }
2809
+ //#endregion
2709
2810
  //#region src/polling.ts
2710
2811
  function isPollingInstruction(body, pc, pcName) {
2711
2812
  const definitions = /* @__PURE__ */ new Map();
@@ -2769,6 +2870,20 @@ function isPollingInstruction(body, pc, pcName) {
2769
2870
  //#region src/runtime/jit.ts
2770
2871
  /** Large programs dispatch through shards; small ones stay on the faster monolithic form. */
2771
2872
  var DIRECT_SHARD_SIZE = 8;
2873
+ /**
2874
+ * Program size above which whole-program rebuilds are amortized instead of immediate.
2875
+ *
2876
+ * Translation only ever adds cache entries, so a compiled program stays valid for every PC it
2877
+ * already contains; only a missing PC needs a rebuild. Rebuilding on every new block is
2878
+ * quadratic, and that dominated warm-up on a real firmware image (411 blocks: 43 rebuilds and
2879
+ * ~1.7 s before any simulated time). Small programs rebuild in milliseconds, so they keep the
2880
+ * exact behaviour; only larger ones switch to a stride that grows with the program.
2881
+ */
2882
+ var DIRECT_REBUILD_LINEAR_LIMIT = 16;
2883
+ /** Stride floor once a program exceeds `DIRECT_REBUILD_LINEAR_LIMIT`. */
2884
+ var DIRECT_REBUILD_MIN_BLOCKS = 64;
2885
+ /** A PC that keeps falling back buys an early rebuild instead of waiting out a full stride. */
2886
+ var DIRECT_REBUILD_PATIENCE = 512;
2772
2887
  var barriers = /* @__PURE__ */ new WeakMap();
2773
2888
  function directBarriers(jit) {
2774
2889
  let entry = barriers.get(jit);
@@ -2785,6 +2900,7 @@ function directStats(jit) {
2785
2900
  const counted = jit;
2786
2901
  return counted.directStats ??= {
2787
2902
  directCompiles: 0,
2903
+ directShards: 0,
2788
2904
  directCalls: 0,
2789
2905
  directFallbacks: 0,
2790
2906
  directDeadlines: 0,
@@ -2853,7 +2969,9 @@ function directHost(board, instance, frame) {
2853
2969
  },
2854
2970
  intent: (pin, value) => {
2855
2971
  publishTime();
2972
+ const changed = instance.pin(pin).intent !== value;
2856
2973
  instance.host.intent(pin, value);
2974
+ if (changed) frame.publishPending = true;
2857
2975
  },
2858
2976
  resistor: (pin, resistance) => {
2859
2977
  publishTime();
@@ -2877,13 +2995,32 @@ function directHost(board, instance, frame) {
2877
2995
  }
2878
2996
  };
2879
2997
  }
2880
- function createDirectFrame(board, instance, stateNames, memoryNames, program, barrier) {
2998
+ /** Build the numeric bank layout once; rebuilds then only need the cached instruction bodies. */
2999
+ function directLayout(jit) {
3000
+ if (jit.directLayout !== void 0) return jit.directLayout;
3001
+ const instance = jit.instance;
3002
+ const bank = instance.directStateBank();
3003
+ const memoryNames = [...instance.memories.keys()];
3004
+ const memories = new Map(memoryNames.map((name, index) => [name, index]));
3005
+ const memoryBanks = memoryNames.map((name) => instance.memory(name));
3006
+ const memoryViews = memoryBanks.map((memory) => new DataView(memory.buffer, memory.byteOffset, memory.byteLength));
3007
+ jit.directLayout = {
3008
+ ...bank,
3009
+ memoryNames: Object.freeze(memoryNames),
3010
+ memories,
3011
+ memoryBanks: Object.freeze(memoryBanks),
3012
+ memoryViews: Object.freeze(memoryViews)
3013
+ };
3014
+ return jit.directLayout;
3015
+ }
3016
+ function createDirectFrame(board, instance, layout, program, barrier) {
2881
3017
  const frame = {
2882
- states: new Array(stateNames.length),
2883
- memories: memoryNames.map((name) => instance.memory(name)),
3018
+ states: layout.stateValues,
3019
+ memories: [...layout.memoryBanks],
3020
+ memoryViews: layout.memoryViews,
2884
3021
  locals: new Array(program.localCount),
2885
- stateDirty: new Array(Math.ceil(stateNames.length / 32)).fill(0),
2886
- memoryDirty: new Array(Math.ceil(memoryNames.length / 32)).fill(0),
3022
+ stateDirty: new Array(Math.ceil(layout.stateNames.length / 32)).fill(0),
3023
+ memoryDirty: new Array(Math.ceil(layout.memoryNames.length / 32)).fill(0),
2887
3024
  time: board.time,
2888
3025
  due: board.time,
2889
3026
  resume: 0
@@ -2902,63 +3039,85 @@ function runDirect(board, jit, hookReads) {
2902
3039
  refreshDirectGuards(jit, hookReads);
2903
3040
  if (jit.directSkip === pc) return false;
2904
3041
  if (jit.directRevision !== jit.revision) {
2905
- if (jit.directProgramRevision !== jit.revision) {
2906
- jit.directPrograms.clear();
2907
- jit.directProgramRevision = jit.revision;
2908
- }
2909
- const key = JSON.stringify([...jit.delays.keys()].sort((left, right) => left - right));
2910
- const cached = jit.directPrograms.get(key);
2911
- if (cached) {
2912
- jit.direct = cached;
2913
- jit.directRevision = jit.revision;
3042
+ const compiled = jit.direct?.pcs.size ?? 0;
3043
+ const stale = jit.revision - jit.directRevision;
3044
+ const stride = compiled < DIRECT_REBUILD_LINEAR_LIMIT ? 1 : Math.max(DIRECT_REBUILD_MIN_BLOCKS, compiled);
3045
+ const covered = jit.direct?.pcs.has(pc) === true;
3046
+ if (!(jit.direct === void 0 || stale >= stride || !covered && jit.directMisses >= DIRECT_REBUILD_PATIENCE)) {
3047
+ if (!covered) {
3048
+ const stats = directStats(jit);
3049
+ stats.directCalls++;
3050
+ stats.directFallbacks++;
3051
+ jit.directMisses += 1;
3052
+ return false;
3053
+ }
2914
3054
  } else {
2915
- const stateNames = [...instance.states.keys()].filter((name) => {
2916
- const declaration = instance.declarations.get(name);
2917
- return declaration.type.kind === "number" || declaration.type.kind === "bool";
2918
- });
2919
- const memoryNames = [...instance.memories.keys()];
2920
- const states = new Map(stateNames.map((name, index) => [name, index]));
2921
- const memories = new Map(memoryNames.map((name, index) => [name, index]));
3055
+ if (jit.directProgramRevision !== jit.revision) {
3056
+ if (jit.directProgramRevision === -1 && jit.directCache !== void 0) compileDirectJit.clearCache(jit.directCache);
3057
+ jit.directPrograms.clear();
3058
+ jit.directProgramRevision = jit.revision;
3059
+ }
3060
+ const layout = directLayout(jit);
2922
3061
  const instructions = [...jit.cache.values()].filter((instruction) => !instruction.polling && !jit.polling.has(instruction.pc));
2923
3062
  /** Declared busy-wait heads fold their remaining rounds inside the emitted body. */
2924
3063
  const delayLoops = /* @__PURE__ */ new Map();
2925
- for (const [pc, delay] of jit.delays) {
2926
- const counter = states.get(delay.counter);
2927
- if (counter !== void 0) delayLoops.set(pc, {
3064
+ for (const [headPc, delay] of jit.delays) {
3065
+ const counter = layout.states.get(delay.counter);
3066
+ if (counter === void 0) continue;
3067
+ const pending = delay.pending === void 0 ? void 0 : {
3068
+ state: layout.states.get(delay.pending.state),
3069
+ period: layout.states.get(delay.pending.period),
3070
+ active: layout.states.get(delay.pending.active)
3071
+ };
3072
+ delayLoops.set(headPc, pending !== void 0 && pending.state !== void 0 && pending.period !== void 0 && pending.active !== void 0 ? {
3073
+ counter,
3074
+ cycles: delay.cycles,
3075
+ pending
3076
+ } : {
2928
3077
  counter,
2929
3078
  cycles: delay.cycles
2930
3079
  });
2931
3080
  }
2932
- const program = compileDirectJit(instructions, {
2933
- states,
2934
- memories,
2935
- pc: {
2936
- name: jit.options.pc,
2937
- index: states.get(jit.options.pc)
2938
- },
2939
- host: true,
2940
- split: true,
2941
- shardSize: DIRECT_SHARD_SIZE,
2942
- delayLoops
2943
- });
2944
- jit.directRevision = jit.revision;
2945
- if (program) directStats(jit).directCompiles++;
2946
- const barrier = directBarriers(jit);
2947
- barrier.stateIndex = states;
2948
- barrier.memoryIndex = memories;
2949
- barrier.stateMask.length = Math.ceil(stateNames.length / 32);
2950
- barrier.memoryMask.length = Math.ceil(memoryNames.length / 32);
2951
- syncDirectBarriers(jit);
2952
- jit.direct = program ? {
2953
- program,
2954
- stateReads: program.readStates.map((name) => [name, states.get(name)]),
2955
- stateWrites: program.writeStates.map((name) => [name, states.get(name)]),
2956
- memoryWrites: program.writeMemories.map((name) => [name, memories.get(name)]),
2957
- revision: jit.revision,
2958
- frame: createDirectFrame(board, instance, stateNames, memoryNames, program, barrier)
2959
- } : void 0;
2960
- if (!jit.direct) jit.directPrograms.delete(key);
2961
- else jit.directPrograms.set(key, jit.direct);
3081
+ const key = JSON.stringify([...delayLoops].sort(([left], [right]) => left - right));
3082
+ const cached = jit.directPrograms.get(key);
3083
+ if (cached) {
3084
+ jit.direct = cached;
3085
+ jit.directRevision = jit.revision;
3086
+ } else {
3087
+ const { states, memories } = layout;
3088
+ const cache = jit.directCache ??= compileDirectJit.createCache();
3089
+ const program = compileDirectJit(instructions, {
3090
+ states,
3091
+ memories,
3092
+ pc: {
3093
+ name: jit.options.pc,
3094
+ index: states.get(jit.options.pc)
3095
+ },
3096
+ host: true,
3097
+ split: true,
3098
+ shardSize: DIRECT_SHARD_SIZE,
3099
+ delayLoops
3100
+ }, cache);
3101
+ jit.directRevision = jit.revision;
3102
+ jit.directMisses = 0;
3103
+ const stats = directStats(jit);
3104
+ stats.directShards = program?.shards ?? 0;
3105
+ if (program) stats.directCompiles++;
3106
+ const barrier = directBarriers(jit);
3107
+ barrier.stateIndex = states;
3108
+ barrier.memoryIndex = memories;
3109
+ barrier.stateMask.length = Math.ceil(layout.stateNames.length / 32);
3110
+ barrier.memoryMask.length = Math.ceil(layout.memoryNames.length / 32);
3111
+ syncDirectBarriers(jit);
3112
+ jit.direct = program ? {
3113
+ program,
3114
+ pcs: new Set(program.pcs),
3115
+ revision: jit.revision,
3116
+ frame: createDirectFrame(board, instance, layout, program, barrier)
3117
+ } : void 0;
3118
+ if (!jit.direct) jit.directPrograms.delete(key);
3119
+ else jit.directPrograms.set(key, jit.direct);
3120
+ }
2962
3121
  }
2963
3122
  }
2964
3123
  if (!jit.direct) return false;
@@ -2966,7 +3125,6 @@ function runDirect(board, jit, hookReads) {
2966
3125
  const direct = jit.direct;
2967
3126
  const frame = direct.frame;
2968
3127
  if (pending) frame.stopAfterInstruction = true;
2969
- for (const [name, index] of direct.stateReads) frame.states[index] = instance.states.get(name);
2970
3128
  frame.time = board.time;
2971
3129
  frame.stateDirty.fill(0);
2972
3130
  frame.memoryDirty.fill(0);
@@ -2979,19 +3137,34 @@ function runDirect(board, jit, hookReads) {
2979
3137
  reason = direct.program.run(frame, Math.min(board.executionEnd, board.events.time));
2980
3138
  } finally {
2981
3139
  board.time = frame.time;
2982
- for (const [name, index] of direct.stateWrites) if ((frame.stateDirty[index >>> 5] & 1 << (index & 31)) !== 0) {
2983
- instance.host.write(name, frame.states[index]);
2984
- wrote = true;
3140
+ frame.publishPending = false;
3141
+ const layout = jit.directLayout;
3142
+ for (let word = 0; word < frame.stateDirty.length; word++) {
3143
+ let bits = frame.stateDirty[word];
3144
+ while (bits !== 0) {
3145
+ const slot = word * 32 + 31 - Math.clz32(bits & -bits);
3146
+ instance.host.write(layout.stateNames[slot], frame.states[slot]);
3147
+ bits &= bits - 1;
3148
+ wrote = true;
3149
+ }
2985
3150
  }
2986
- for (const [name, index] of direct.memoryWrites) if ((frame.memoryDirty[index >>> 5] & 1 << (index & 31)) !== 0) {
2987
- instance.memoryChanged(name);
2988
- wrote = true;
3151
+ for (let word = 0; word < frame.memoryDirty.length; word++) {
3152
+ let bits = frame.memoryDirty[word];
3153
+ while (bits !== 0) {
3154
+ const slot = word * 32 + 31 - Math.clz32(bits & -bits);
3155
+ instance.memoryChanged(layout.memoryNames[slot]);
3156
+ bits &= bits - 1;
3157
+ wrote = true;
3158
+ }
2989
3159
  }
2990
3160
  }
2991
3161
  if (reason !== "fallback" || wrote || board.time !== start) board.boundary();
2992
3162
  if (reason === "fallback") {
2993
- stats.directFallbacks++;
2994
- jit.directSkip = finite(instance.states.get(jit.options.pc), "pc");
3163
+ const nextPc = finite(instance.states.get(jit.options.pc), "pc");
3164
+ if (!(jit.polling.has(nextPc) || jit.cache.get(nextPc)?.polling)) {
3165
+ stats.directFallbacks++;
3166
+ jit.directSkip = nextPc;
3167
+ }
2995
3168
  if (board.time === start && board.time < board.executionEnd) return false;
2996
3169
  } else if (reason === "stopped") {
2997
3170
  stats.directStopped++;
@@ -3014,6 +3187,33 @@ function pollingDependencies(jit, dependencies) {
3014
3187
  for (const slot of [instance.stateResources.get(jit.options.pc), instance.memoryResources.get(jit.options.code)]) result.set(slot, slot.version);
3015
3188
  return result;
3016
3189
  }
3190
+ /** Park a polling JIT and, when requested, schedule the next device time event. */
3191
+ function waitForPolling(board, jit, dependencies, duration, advance) {
3192
+ jit.dependencies = dependencies;
3193
+ jit.pollingWait = true;
3194
+ jit.pollingPeriod = 0;
3195
+ board.waitingJits.add(jit);
3196
+ const token = ++jit.pollingToken;
3197
+ board.boundary();
3198
+ if (duration === 0 || advance === void 0) return;
3199
+ const due = time(board.time + duration);
3200
+ board.events.push(due, () => {
3201
+ if (token !== jit.pollingToken || !jit.active || jit.stopped || !board.waitingJits.has(jit)) return;
3202
+ const pending = jit.dependencies;
3203
+ jit.pollingWait = false;
3204
+ delete jit.dependencies;
3205
+ board.waitingJits.delete(jit);
3206
+ jit.pollingToken++;
3207
+ board.current = jit.instance;
3208
+ if (!jit.instance.dependenciesCurrent(pending)) {
3209
+ board.queueJit(jit);
3210
+ return;
3211
+ }
3212
+ jit.instance.syncCall(advance, [duration]);
3213
+ board.boundary();
3214
+ board.queueJit(jit);
3215
+ });
3216
+ }
3017
3217
  function jitSignal(board, jit, signal) {
3018
3218
  if (signal.kind === "elapse") {
3019
3219
  const duration = time(signal.duration);
@@ -3097,17 +3297,18 @@ function runJit(board, jit) {
3097
3297
  }
3098
3298
  const pc = finite(jit.instance.states.get(jit.options.pc), "pc");
3099
3299
  if (board.execution === "throughput") {
3100
- const predicate = jit.polling.get(pc);
3101
- if (predicate) {
3102
- const checked = jit.instance.evaluate(() => jit.instance.syncCall(predicate));
3300
+ const declaration = jit.polling.get(pc);
3301
+ if (declaration) {
3302
+ const checked = jit.instance.evaluate(() => jit.instance.syncCall(declaration.predicate));
3103
3303
  if (checked.value !== true) {
3104
- jit.dependencies = pollingDependencies(jit, new Map([...hookReads ?? [], ...checked.dependencies]));
3105
- jit.pollingWait = true;
3106
- jit.pollingPeriod = 0;
3107
- board.waitingJits.add(jit);
3108
- board.boundary();
3304
+ const dependencies = new Map([...hookReads ?? [], ...checked.dependencies]);
3305
+ let duration = 0;
3306
+ const wait = declaration.wait;
3307
+ if (wait) duration = time(jit.instance.evaluate(() => jit.instance.syncCall(wait.delay), dependencies).value);
3308
+ waitForPolling(board, jit, pollingDependencies(jit, dependencies), duration, wait?.advance);
3109
3309
  return;
3110
3310
  }
3311
+ if (declaration.consume) jit.instance.syncCall(declaration.consume);
3111
3312
  }
3112
3313
  if (!hookPending && board.jits.length === 1 && runDirect(board, jit, hookReads)) return;
3113
3314
  }
@@ -3397,7 +3598,13 @@ var BoardRuntime = class {
3397
3598
  source: chain.plan.source,
3398
3599
  comparison: chain.plan.comparison
3399
3600
  }))),
3400
- skipped: Object.freeze(this.skippedPlans.map((entry) => Object.freeze({ ...entry })))
3601
+ skipped: Object.freeze(this.skippedPlans.map((entry) => Object.freeze({ ...entry }))),
3602
+ reactions: Object.freeze(this.instances.flatMap((instance) => instance.reactions.map((reaction) => Object.freeze({
3603
+ instance: instance.id,
3604
+ name: reaction.declaration.name,
3605
+ mode: reaction.synchronousProgram === void 0 ? "pending" : reaction.synchronousProgram === null ? "generic" : reaction.synchronous !== void 0 && reaction.synchronous !== null ? "sync" : "ready",
3606
+ functions: reaction.synchronousProgram?.functions.length ?? 0
3607
+ }))))
3401
3608
  });
3402
3609
  }
3403
3610
  /**
@@ -3418,18 +3625,26 @@ var BoardRuntime = class {
3418
3625
  bindings: Object.freeze(this.instances.map((instance) => instance.bindingReport()))
3419
3626
  });
3420
3627
  }
3421
- validity(instance) {
3628
+ assertAlive(instance) {
3422
3629
  if (this.status === "disposed" || instance && !instance.valid) throw this.error("OBJECT_DISPOSED", "Object is disposed", instance);
3423
3630
  }
3424
- guard(instance, readOnly = false) {
3425
- this.validity(instance);
3631
+ /** Admission for a call that may change board state or is visible to a device. */
3632
+ assertCallAllowed(instance) {
3633
+ this.admit(instance, false);
3634
+ }
3635
+ /** Admission for a read-only entry point: a faulted board stays inspectable. */
3636
+ assertReadAllowed(instance) {
3637
+ this.admit(instance, true);
3638
+ }
3639
+ admit(instance, allowFaulted) {
3640
+ this.assertAlive(instance);
3426
3641
  if (instance && [
3427
3642
  "execute",
3428
3643
  "translate",
3429
3644
  "dispose",
3430
3645
  "assembly"
3431
3646
  ].includes(this.phase)) throw this.error("INVALID_CALL_STATE", "Operation is not allowed in this phase", instance);
3432
- if (!readOnly && this.status === "faulted") throw this.error("BOARD_FAULTED", "Board is faulted", instance);
3647
+ if (!allowFaulted && this.status === "faulted") throw this.error("BOARD_FAULTED", "Board is faulted", instance);
3433
3648
  }
3434
3649
  error(code, message, instance, cause, phase) {
3435
3650
  const electrical = cause instanceof ElectricalError ? cause : void 0;
@@ -3495,13 +3710,9 @@ var BoardRuntime = class {
3495
3710
  this.fault(this.error("REPORTED_ERROR", cause instanceof Error ? cause.message : String(cause), instance, cause, "report"));
3496
3711
  }
3497
3712
  topicBridge(owner) {
3498
- const hostListenerCount = () => this.hostListeners;
3499
- return Object.freeze({
3500
- get hostListenerCount() {
3501
- return hostListenerCount();
3502
- },
3713
+ const facade = Object.freeze({
3503
3714
  onDidReceive: ((listener, thisArgs, disposables) => {
3504
- this.guard(owner);
3715
+ this.assertCallAllowed(owner);
3505
3716
  const entry = {
3506
3717
  ...owner ? { owner } : {},
3507
3718
  call: (message) => listener.call(thisArgs, message)
@@ -3519,9 +3730,8 @@ var BoardRuntime = class {
3519
3730
  owner?.resources.push(disposable);
3520
3731
  return disposable;
3521
3732
  }),
3522
- assertCanPublish: () => this.guard(owner),
3523
3733
  publish: (topic, payload) => {
3524
- this.guard(owner);
3734
+ this.assertCallAllowed(owner);
3525
3735
  if (typeof topic !== "string") throw new TypeError("Topic must be a string");
3526
3736
  this.dispatchDepth++;
3527
3737
  try {
@@ -3544,6 +3754,11 @@ var BoardRuntime = class {
3544
3754
  }
3545
3755
  }
3546
3756
  });
3757
+ registerPublishGate(facade, {
3758
+ assertPublishAllowed: () => this.assertCallAllowed(owner),
3759
+ hostListeners: () => this.hostListeners
3760
+ });
3761
+ return facade;
3547
3762
  }
3548
3763
  enqueue(process) {
3549
3764
  if (process.state === "idle") {
@@ -3557,6 +3772,15 @@ var BoardRuntime = class {
3557
3772
  this.readyJits.push(jit);
3558
3773
  }
3559
3774
  }
3775
+ /**
3776
+ * Fail-closed admission for staying inside generated code after a publication checkpoint.
3777
+ * The JIT must be the only direct owner, all same-time scheduler stages must be empty,
3778
+ * and no event may be due through the requested horizon. The target time is exclusive:
3779
+ * code must not resume at `executionEnd`.
3780
+ */
3781
+ canContinueDirect(jit, horizon) {
3782
+ return this.status === "ready" && this.phase === "execute" && !this.isFaulted && this.execution === "throughput" && this.jits.length === 1 && this.jits[0] === jit && jit.active && !jit.stopped && !jit.queued && this.readyJits.length === 0 && this.models.length === 0 && this.waitingJits.size === 0 && this.time < this.executionEnd && horizon >= this.time && horizon < this.executionEnd && this.events.time > horizon;
3783
+ }
3560
3784
  invalidate(slot) {
3561
3785
  slot.version++;
3562
3786
  if (slot.subscribers.size === 0) return;
@@ -3693,27 +3917,36 @@ var BoardRuntime = class {
3693
3917
  applyChange(observation, previous, current) {
3694
3918
  if (observation.declaration.kind === "reaction") {
3695
3919
  const reaction = observation;
3696
- reaction.frame = {
3920
+ const frame = reaction.frame;
3921
+ if (frame === void 0) reaction.frame = {
3697
3922
  previous,
3698
3923
  current,
3699
3924
  captures: []
3700
3925
  };
3926
+ else {
3927
+ frame.previous = previous;
3928
+ frame.current = current;
3929
+ frame.captures.length = 0;
3930
+ }
3701
3931
  this.reactionBatch.push(reaction);
3702
3932
  } else this.enqueue(observation);
3703
3933
  }
3704
3934
  recordChange(observation, previous, current) {
3705
- const list = this.changeObservations;
3706
- let at = list.length;
3935
+ this.insertOrderedChange(this.changeObservations, this.changePrevious, this.changeCurrent, observation, previous, current);
3936
+ }
3937
+ /** Shared stable insertion; receivers are few, so in-place insertion beats a sort. */
3938
+ insertOrderedChange(receivers, previous, current, observation, before, after) {
3939
+ let at = receivers.length;
3707
3940
  const order = observation.order;
3708
- while (at > 0 && list[at - 1].order > order) at--;
3709
- if (at === list.length) {
3710
- list.push(observation);
3711
- this.changePrevious.push(previous);
3712
- this.changeCurrent.push(current);
3941
+ while (at > 0 && receivers[at - 1].order > order) at--;
3942
+ if (at === receivers.length) {
3943
+ receivers.push(observation);
3944
+ previous.push(before);
3945
+ current.push(after);
3713
3946
  } else {
3714
- list.splice(at, 0, observation);
3715
- this.changePrevious.splice(at, 0, previous);
3716
- this.changeCurrent.splice(at, 0, current);
3947
+ receivers.splice(at, 0, observation);
3948
+ previous.splice(at, 0, before);
3949
+ current.splice(at, 0, after);
3717
3950
  }
3718
3951
  }
3719
3952
  boundary() {
@@ -3726,43 +3959,80 @@ var BoardRuntime = class {
3726
3959
  changes.length = 0;
3727
3960
  this.changePrevious.length = 0;
3728
3961
  this.changeCurrent.length = 0;
3729
- try {
3730
- const batch = this.observations.take();
3731
- for (let index = 0; index < batch.length; index++) {
3732
- const observation = batch[index];
3733
- if ("plan" in observation) {
3734
- this.collectChain(observation);
3735
- continue;
3736
- }
3737
- const current = observation.readSource();
3738
- if (same(observation.previous, current)) continue;
3739
- const previous = observation.previous;
3740
- observation.previous = current;
3741
- if (changes.length) this.recordChange(observation, previous, current);
3742
- else this.applyChange(observation, previous, current);
3743
- }
3744
- const count = changes.length;
3745
- if (count) {
3746
- for (let index = 0; index < count; index++) this.applyChange(changes[index], this.changePrevious[index], this.changeCurrent[index]);
3747
- changes.length = 0;
3748
- this.changePrevious.length = 0;
3749
- this.changeCurrent.length = 0;
3750
- }
3751
- if (!reactions.length) return;
3752
- for (const reaction of reactions) if (reaction.declaration.captures.length) reaction.frame = {
3753
- ...reaction.frame,
3754
- captures: reaction.declaration.captures.map((capture) => snapshot(computation(capture.value, reaction.instance.host)))
3755
- };
3756
- for (const reaction of reactions) {
3757
- this.current = reaction.instance;
3758
- reaction.execute ??= body(reaction.declaration.body);
3759
- if (!reaction.execute(reaction.instance.host, [], reaction.frame).next().done) throw new TypeError("Reaction cannot suspend");
3962
+ const batch = this.observations.take();
3963
+ for (let index = 0; index < batch.length; index++) {
3964
+ const observation = batch[index];
3965
+ if ("plan" in observation) {
3966
+ this.collectChain(observation);
3967
+ continue;
3760
3968
  }
3761
- } finally {
3762
- for (const reaction of reactions) reaction.frame = void 0;
3969
+ const current = observation.readSource();
3970
+ if (same(observation.previous, current)) continue;
3971
+ const previous = observation.previous;
3972
+ observation.previous = current;
3973
+ if (changes.length) this.recordChange(observation, previous, current);
3974
+ else this.applyChange(observation, previous, current);
3975
+ }
3976
+ const count = changes.length;
3977
+ if (count) {
3978
+ for (let index = 0; index < count; index++) this.applyChange(changes[index], this.changePrevious[index], this.changeCurrent[index]);
3979
+ changes.length = 0;
3980
+ this.changePrevious.length = 0;
3981
+ this.changeCurrent.length = 0;
3982
+ }
3983
+ if (reactions.length) this.runBoundaryReactions(reactions);
3984
+ else return;
3985
+ }
3986
+ }
3987
+ /** Shared capture barrier and ordered body runner for generic and static boundaries. */
3988
+ runBoundaryReactions(reactions) {
3989
+ try {
3990
+ for (const reaction of reactions) if (reaction.declaration.captures.length) {
3991
+ const frame = reaction.frame;
3992
+ frame.captures = reaction.declaration.captures.map((capture) => snapshot(computation(capture.value, reaction.instance.host)));
3993
+ }
3994
+ for (const reaction of reactions) {
3995
+ this.current = reaction.instance;
3996
+ this.runReaction(reaction);
3763
3997
  }
3998
+ } finally {
3999
+ this.clearReactionFrames(reactions);
4000
+ }
4001
+ }
4002
+ clearReactionFrames(reactions) {
4003
+ for (const reaction of reactions) {
4004
+ const frame = reaction.frame;
4005
+ if (frame === void 0) continue;
4006
+ frame.previous = void 0;
4007
+ frame.current = void 0;
4008
+ frame.captures.length = 0;
3764
4009
  }
3765
4010
  }
4011
+ /**
4012
+ * Execute one synchronous boundary reaction. The capture barrier already froze every
4013
+ * frame before this method runs. Admission is whole-body: a compiler decline selects
4014
+ * the generator path before any effect, while bind/execution errors propagate without
4015
+ * a catch-and-replay fallback.
4016
+ */
4017
+ runReaction(reaction) {
4018
+ const instance = reaction.instance;
4019
+ let program = reaction.synchronousProgram;
4020
+ if (program === void 0) {
4021
+ program = synchronousBody(instance, reaction.declaration.body) ?? null;
4022
+ reaction.synchronousProgram = program;
4023
+ }
4024
+ if (program !== null) {
4025
+ let runner = reaction.synchronous;
4026
+ if (runner === void 0 || runner === null) {
4027
+ runner = program.bind(instance.host);
4028
+ reaction.synchronous = runner;
4029
+ }
4030
+ runner(void 0, reaction.frame);
4031
+ return;
4032
+ }
4033
+ reaction.execute ??= body(reaction.declaration.body);
4034
+ if (!reaction.execute(instance.host, [], reaction.frame).next().done) throw new TypeError("Reaction cannot suspend");
4035
+ }
3766
4036
  drive(process, value) {
3767
4037
  const program = process.resumable;
3768
4038
  if (program) {
@@ -3861,7 +4131,7 @@ var BoardRuntime = class {
3861
4131
  }
3862
4132
  }
3863
4133
  runUntil(target) {
3864
- this.validity();
4134
+ this.assertAlive();
3865
4135
  if (this.phase !== "idle" || this.dispatchDepth) throw this.error("INVALID_CALL_STATE", "Board is busy");
3866
4136
  if (this.status === "faulted") throw this.error("BOARD_FAULTED", "Board is faulted");
3867
4137
  const end = time(target);
@@ -3913,6 +4183,7 @@ var BoardRuntime = class {
3913
4183
  if (lastStart < 72e14 && lastStart < end) {
3914
4184
  if (lastStart === this.time) {
3915
4185
  jit.pollingWait = false;
4186
+ jit.pollingToken++;
3916
4187
  delete jit.dependencies;
3917
4188
  this.waitingJits.delete(jit);
3918
4189
  this.queueJit(jit);
@@ -3923,6 +4194,7 @@ var BoardRuntime = class {
3923
4194
  }
3924
4195
  if (jit.pollingWait) {
3925
4196
  jit.pollingWait = false;
4197
+ jit.pollingToken++;
3926
4198
  delete jit.dependencies;
3927
4199
  this.waitingJits.delete(jit);
3928
4200
  const remainder = jit.pollingPeriod > 0 ? (this.time - jit.pollingOrigin) % jit.pollingPeriod : 0;
@@ -4130,6 +4402,7 @@ async function prepareSimulation(input, importer, assertActive) {
4130
4402
  symbol: symbol.id,
4131
4403
  device: devices.get(symbol.device)
4132
4404
  })),
4405
+ ...input.execution === void 0 ? {} : { execution: input.execution },
4133
4406
  description: {
4134
4407
  instances: symbols.map((symbol) => ({
4135
4408
  id: symbol.id,
@@ -4357,7 +4630,7 @@ function buildLoadedRuntime(prepared, publishObserved) {
4357
4630
  ...instance,
4358
4631
  props: Object.fromEntries(Object.entries(instance.props ?? {}).map(([key, value]) => [key, value instanceof Uint8Array ? new Uint8Array(value) : value]))
4359
4632
  }))
4360
- });
4633
+ }, prepared.execution === void 0 ? {} : { execution: prepared.execution });
4361
4634
  const project = (diagnostic, fatal) => {
4362
4635
  found.push({
4363
4636
  code: fatal ? diagnostic.phase === "topic" ? "device/input-failed" : diagnostic.phase === "sync" ? "device/output-failed" : "board/error" : "board/diagnostic",
@@ -4385,16 +4658,15 @@ function buildLoadedRuntime(prepared, publishObserved) {
4385
4658
  *
4386
4659
  * `publishObserved` reports whether anything outside the board consumes published messages; with no
4387
4660
  * scoped subscriber, no owner-less bridge listener and no consumer, an accepted output is dropped
4388
- * before it is copied, fanned out or queued, while `assertCanPublish` keeps the publish guards.
4661
+ * before it is copied, fanned out or queued, while the bridge's internal publish gate keeps the
4662
+ * board's call admission.
4389
4663
  */
4390
4664
  function scopeTopics(bridge, instance, outputs, diagnostics, publishObserved) {
4391
4665
  const prefix = `${encodeURIComponent(instance.symbol)}/`;
4666
+ const gate = publishGate(bridge);
4392
4667
  let scopedListeners = 0;
4393
- const unobserved = () => scopedListeners === 0 && bridge.hostListenerCount === 0 && !publishObserved();
4668
+ const unobserved = () => scopedListeners === 0 && gate.hostListeners() === 0 && !publishObserved();
4394
4669
  return {
4395
- get hostListenerCount() {
4396
- return bridge.hostListenerCount;
4397
- },
4398
4670
  onDidReceive: ((listener, thisArgs, disposables) => {
4399
4671
  const subscription = bridge.onDidReceive((message) => {
4400
4672
  if (!message.topic.startsWith(prefix)) return;
@@ -4417,7 +4689,6 @@ function scopeTopics(bridge, instance, outputs, diagnostics, publishObserved) {
4417
4689
  disposables?.push(disposable);
4418
4690
  return disposable;
4419
4691
  }),
4420
- assertCanPublish: () => bridge.assertCanPublish(),
4421
4692
  publish(port, payload) {
4422
4693
  const topic = instance.device.topics.get(port);
4423
4694
  if (topic?.direction !== "output" || !payloadMatches(topic.type, payload)) {
@@ -4431,7 +4702,7 @@ function scopeTopics(bridge, instance, outputs, diagnostics, publishObserved) {
4431
4702
  return;
4432
4703
  }
4433
4704
  if (unobserved()) {
4434
- bridge.assertCanPublish();
4705
+ gate.assertPublishAllowed();
4435
4706
  return;
4436
4707
  }
4437
4708
  const snapshot = copyPayload(payload);
@@ -4471,7 +4742,8 @@ function registerSimulationRuntimeServices(rpc, runtime, topicRpc) {
4471
4742
  const serviceRegistration = rpc.register(simulationRuntimeService, service, { transfer: simulationRuntimeEventTransfer });
4472
4743
  const topicRegistration = topicRpc === void 0 ? void 0 : topicRpc.register(simulationRuntimeTopicService, {
4473
4744
  deliver: service.deliver,
4474
- onDidPublish: service.onDidPublish
4745
+ onDidPublish: service.onDidPublish,
4746
+ async flushPublishes() {}
4475
4747
  }, { transfer: simulationRuntimeEventTransfer });
4476
4748
  let disposed = false;
4477
4749
  return { dispose() {