/** * `CoreEngine` — the facade over one Rust engine handle. Implements * `EngineReadout` (surface.ts) so a host can read it exactly like a classic * `SimEngine`; see that file's header for why loading/advancing is NOT part * of the shared interface. * * One handle per instance, for its whole lifetime. `bo_engine_create()` is * called EAGERLY in the constructor rather than lazily on first `load()`: * handles are cheap (a Rust `Vec` push), and eager creation means there is no * "constructed but not yet holding a handle" state to special-case in every * method below — a `CoreEngine` either has a handle or it has thrown out of * its constructor, never something in between. * * GENERATIONS. `initCore()` can be called again after the instance it * produced is poisoned by a trap (wasm.ts, "Traps"); that produces a NEW * instance with its own handle table, where THIS engine's handle number * could coincidentally name a real, unrelated engine. Every method here * therefore checks its recorded generation against the live one * (`coreGeneration()`) and refuses to run at all once they disagree — * `CoreStaleInstanceError`, not silent misbehaviour against the wrong * instance. * * "NO PROGRAM LOADED" IS A FACADE-LEVEL STATE, NOT JUST A RUST ONE. A failed * `bo_engine_load` leaves the RUST side exactly as it was — the previous * program, still loaded, still answering queries (core/README.md's * contract; abi.rs's own `a_failed_reload_leaves_the_previous_program_intact` * test asserts this). This facade deliberately does NOT expose that: any * `load()` call that throws — whether compileCircuit rejected the circuit or * `bo_engine_load` returned an error code — clears this engine's own * "loaded" state first, so every readout throws `CoreNotLoadedError` until * the NEXT successful `load()`. Silently continuing to serve the OLD * circuit's readouts after a `load()` call the caller just saw fail would be * a far worse surprise than an explicit throw. */ import { type CompileOptions } from "./compile/index.js"; import type { EngineReadout } from "./surface.js"; import type { BatteryRuntimeReadout, SimCircuit, SimFailure, SimWarning, ThermalRuntimeReadout } from "../sim/engine/sim-engine.js"; import type { Net } from "../sim/engine/graph.js"; import type { DisplayInfo } from "../sim/messages.js"; /** `CoreEngine.load`'s third argument: `CompileOptions` (compile/index.js's options passthrough) plus the facade-clock seed. */ export interface CoreEngineLoadOptions extends CompileOptions { simTime?: number; } /** One `CoreEngine.setParams` change: every named param in `params` is applied to the device compiled for `componentId`. */ /** * What one {@link CoreEngine.advanceFor} call did: `"reached"` the target, * `"yielded"` short of it at an instant when its wall budget ran out (call * again with the same target), or `"failed"`: a non-convergent advance * (-4, -7) handled exactly as {@link CoreEngine.advance} handles one. */ export type CoreAdvanceOutcome = "reached" | "yielded" | "failed"; /** The code and the core's message of the last failed advance (-4 solve failed, -7 no progress or livelock). */ export interface CoreAdvanceFailure { readonly code: number; readonly message: string; } export interface CoreParamChange { readonly componentId: string; readonly params: Readonly>; } /** `bo_engine_stat`'s four counters (core/README.md's index table), named. */ export interface CoreEngineStats { partitions: number; staticSolves: number; largestPartition: number; fixedNodes: number; } export declare class CoreEngine implements EngineReadout { private readonly _handle; private readonly _generation; private _disposed; private _compiled; private _netV; private _elementI; private _digitalState; private _elementChannelI; private _lastConverged; /** The loaded circuit, which `resetFailures` re-derives the static warnings from, as classic's `this.circuit`. */ private _circuit; /** * W2c: the loaded circuit as it was at the load, which the next reload's * carry maps from. A copy: a host may edit the circuit object it loaded in * place and reload that same object (classic keeps what it needs at load, * its EEPROM's contents hash and a battery's authored charge). */ private _loadedAs; /** The static warnings and the announce queue (W1g point 11). A reload carries a same-kind component's entries, as classic's load (W2c); coldLoad starts afresh. */ private _warnings; /** * W2c: each EEPROM's image as this facade last knew it (the ROM blob it * loaded, then every image `takeEepromUpdates` or a reload drained), by * component id: what a reload onto the same authored contents loads as * the new ROM blob, so a written byte survives it as in classic. */ private _eepromImages; /** Component ids `setParams` has already reported as unknown, so a host retrying the same stale id every frame logs it once (ruling R41). Per engine, kept across loads. */ private _reportedUnknownParamIds; /** Whether advanceFor has already warned that this core has no `bo_engine_advance_for` (logged once per engine). */ private _warnedNoAdvanceFor; private _lastAdvanceFailure; /** Bumped at every load() call, so a snapshot knows whether the program it was taken on is still the one loaded (W2a). */ private _loadSerial; /** W2b: the nets the observer samples, in take order (`null`: disarmed); a load disarms. */ private _acquired; /** W2b piece 4: the components whose charge is armed, in take order, with each one's channel count (`null`: disarmed); a load disarms. */ private _charged; private _simTime; constructor(); /** * Every public method's first line: disposed, stale-generation, and * poisoned are all refused before anything else runs — INCLUDING a pure * cached-value getter like getNetV(). A poisoned instance could in * principle leave a cached readout technically still accurate (it was * copied out before the trap), but "some methods still work while * poisoned and some don't" is a worse contract than "poisoned means * refuses everything, uniformly, until initCore() runs again." */ private _checkGeneration; /** * True when this engine is still safe to use RIGHT NOW: not disposed, its * recorded generation matches the live one, and the live instance is * `"ready"` (not poisoned, not uninitialized). Never throws — unlike * `_checkGeneration()`, this is a query a caller uses to decide WHETHER to * call a method, not a guard inside one. A host adapter holding a * long-lived `CoreEngine` (HeadlessRunner) uses this to notice when its * cached engine has been superseded by a re-init (e.g. trap recovery) and * needs to be dropped and replaced, rather than finding out via a thrown * `CoreStaleInstanceError` on the next call. */ isCurrent(): boolean; /** Every readout's guard: generation-fresh AND a program is currently (successfully) loaded. */ private _requireLoaded; /** * Compile `circuit` and load it onto the core. `implementedKinds` is NOT * the "safe to route here" accuracy gate (that's `CORE_SUPPORTED_KINDS` / * select.ts, a host-adapter concern) — it is only "which kinds can this * compiler even produce a program for," and almost never needs to be * narrowed by a caller of `CoreEngine` directly. * * `options.simTime`, when given, is the facade time the JUST-LOADED * program starts at — overriding whatever this engine's own clock already * read, rather than carrying it forward as a bare `load(circuit)` does * (see the class doc comment on `_simTime`). This is for a host * adapter switching a live-edit reload from ANOTHER engine onto this one * (HeadlessRunner.load(): "classic to core" passes the classic engine's * current simTime here) — a caller loading onto an engine that was already * running should not pass it. Must be finite and `>= 0`, or this throws a * `RangeError` before anything else (before even a topology/parameter * check) — a caller bug, not a circuit problem, so unlike a rejected * circuit it does NOT clear this engine's currently loaded program. * * **Carry** (W2c, classic's `load()`, core/README.md "Carry"). A load * onto a loaded program, with no `options.simTime`, carries its state: * capacitor charges by id or net-pair fingerprint, IC state and outputs * in flight, a battery's charge, the slow physics and latched failures, * each kind-gated as classic's, an EEPROM's written image onto the same * authored contents, and the warnings of components whose id and kind * survive, none announced again. The program goes to the core as v4 with * its `CARRY` block. A load given a time (another engine's, or a cold * start), a core without the carry exports, and {@link coldLoad} carry * nothing. A carry the core fails to take (bringing the old program to its * time, `-4`/`-7`) throws `CoreUnsupportedError` with `carry:`-prefixed * reasons, the engine left with no program as after any failed load: the * host routes it as a load-time failure, or calls {@link coldLoad}. * * `options`' other fields (`integrationMethod`, and the exactness switches) * pass straight through to `compileCircuit` (compile/index.js's * `CompileOptions`) — the ambient temperature option is NOT here, since * `compileCircuit` always derives it from `circuit.environment` itself. * `startTimeS` is the one exception: this method ALWAYS overrides it with * `previousSimTime` (below) before calling compileCircuit, regardless of * whether the caller's `options` happened to set it — "the facade passes * START_TIME on every load" means this engine's own carried-over clock is * the only source for it, never a caller-supplied compile option. * * Throws `CoreUnsupportedError` (with `reasons`) for anything compileCircuit * rejects, for a Rust-side topology rejection (`bo_engine_load` code -3, * reason prefixed `topology:`), for a load-time delta-cycle livelock * (code -7, reason prefixed `livelock:`), or for a load-time solve failure * (code -4, reason prefixed `solve-failed:` — finding 11: W1c's IC-supply * fixed point not converging is an ordinary way to reach this) — decision * 8's load-settle pass covers all three; see `mapLoadFailure`'s doc * comment. Throws `CoreLoadError` for -1/-2/-5/-8 (see `mapLoadFailure`'s * doc comment for why -2 is grouped there, not with -3/-4/-7). In every * OTHER throwing case this engine ends up in the "no program loaded" state * (see the class doc comment) regardless of what was loaded before. */ load(circuit: SimCircuit, implementedKinds?: ReadonlySet, options?: CoreEngineLoadOptions): void; /** * Classic's `coldLoad` (W2c): load `circuit` at time 0 with nothing carried, * every capacitor, register and integrator at its power-on value, as a * fresh engine would. Throws as {@link load} does. */ coldLoad(circuit: SimCircuit, implementedKinds?: ReadonlySet, options?: Omit): void; /** * W2c's carry, taken off the loaded program before a reload replaces it: * the core's records (`bo_engine_carry_take`), what they were taken from, * and every EEPROM's current image (the dirty ones drained here: the * records carry their dirty flags, so the new program still reports them * to the host). `null` when nothing is loaded, or the core has no carry * exports (R100 (a): an older core loads cold). A take that fails (its * clamp to the engine's time: `-4`, `-7`) is the error `_load` throws once * it has cleared the program, as a load-time failure: a reload that * silently went cold would drop the charges, registers and latches the * user edited around. */ private _takeCarry; private _load; /** * Advance to `tEnd` (absolute seconds — Rust's own clock IS the facade's * clock now that load() always seeds START_TIME with it; see the class doc * comment). `tEnd` earlier than the current simTime by more than float * slack throws a `RangeError` (core/README.md error -6): a caller bug, not * a circuit problem, so it is never wrapped in `CoreUnsupportedError`/ * `CoreLoadError`. A non-finite `tEnd` (`NaN`/`Infinity`/`-Infinity`) is * rejected the same way, and BEFORE any ABI call: the Rust side's own * backwards-time guard (`t_end < self.time - TIME_EPS`) is false for NaN, * so a NaN or Infinite `tEnd` would otherwise reach `bo_engine_advance`, * succeed, and permanently disable that guard (every later comparison * against a NaN/Infinite clock is also false) — see engine.rs's `advance`. * * A NON-CONVERGENT advance (-4 solve failed, -7 delta-cycle livelock) does * NOT throw (core/README.md, "A failed advance": "the host treats this as * non-convergence, as classic's `lastConverged = false`... It is not a load * error"). Rust keeps the state of the last instant it actually completed, * so this sets `lastConverged = false`, reads `simTime` back from * `bo_engine_time()` (the instant Rust actually reached, not the `tEnd` * that was requested), and leaves the published readouts exactly as the * last successful call left them — that IS "the last good instant" the * contract promises, so there is nothing to re-publish. Every other * non-zero code is still a genuine error and throws `CoreLoadError`, as * before. */ advance(tEnd: number): void; /** * The yielding advance (ruling R86, core/README.md "A yielding advance"): * {@link advance} toward `tEnd` for about `budgetMs` of wall time on the * loader's clock (`env.bo_host_now_ms`, {@link coreImports}). * * - `"reached"`: as `advance`'s success (`simTime === tEnd`, readouts * published). * - `"yielded"`: not an error. The core stopped at an instant short of * `tEnd` when the budget ran out; `simTime` is that instant (read back), * `lastConverged` stays true and the readouts are that instant's. Call * again with the SAME `tEnd` and the core goes on with the same host * step, so the run is the unsplit one bit for bit; a different target or * any input in between (`setParams`, a load, a restore...) starts a new * host step. * - `"failed"`: `-4`/`-7` exactly as `advance` makes them (`lastConverged` * false, `simTime` read back, readouts left at the last good call), with * {@link lastAdvanceFailure} saying which and why. Never a yield. * * A non-finite `tEnd`, a non-finite or negative `budgetMs`, or a `tEnd` in * the past throws `RangeError`, as `advance` does. A budget of 0 never * yields. A core built without `bo_engine_advance_for` runs `advance` * instead (which cannot yield, so a long one blocks the caller) and warns * once per engine. */ advanceFor(tEnd: number, budgetMs: number): CoreAdvanceOutcome; /** * The last failed advance's code and the core's message, or `null` when * the last `advance`/`advanceFor` did not fail. A load clears it. */ get lastAdvanceFailure(): CoreAdvanceFailure | null; /** A non-convergent advance (-4, -7): the state of the last completed instant, its time read back, the readouts left as they were. */ private _failAdvance; /** * Applies a live parameter update to already-loaded devices through * `bo_engine_set_params` (core/README.md's ABI v2, owner decision 1) rather * than a reload — the mechanism `test/core/equivalence/stimuli.ts`'s * `replayStimuliOnCore` uses to replay a verify-script phase's toggles * without discarding capacitor charge, register contents or pending delays * the way a reload would. * * Each `change.params` entry is resolved through the SAME per-kind value * resolver the compiler itself used at load time (`compile/index.js`'s * `LIVE_PARAM_SPECS`, built from each kind-family module's own resolver * functions — e.g. compile/passives.ts's `resolveSwitchClosed`), so a live * toggle and the initial compiled value agree bit for bit ("converting * values with the same resolution as the compiler", this worker's brief). * * Every `(deviceIndex, paramIndex, value)` triple is validated on THIS side * before any ABI call — belt and braces, mirroring `ProgramWriter * .addDevice`'s own "validate, but the reader is still the real source of * truth" stance: * - an unknown `componentId` (no device compiled for it) is skipped, and * the call returns `false` (ruling R41, 2026-10-21). A host edits the * circuit while param changes are in flight, so an id the loaded program * no longer holds is routine; classic has no runtime param call at all * and its reload path ignores an override for an absent component the * same way. Outside production the id is logged once per engine * (`isDevBuild`); the rest of the batch is still validated and applied. * - an unknown param name for a known device's kind, or a param that * exists but is NOT live (`CORE_RECORD_SHAPES.get(kindCode).liveParams`) * each throw a plain `RangeError` naming exactly what was wrong — a * caller/corpus-data bug, not a circuit fact, so (like `load()`'s * `options.simTime` check) this is refused before anything else runs and * never wrapped in `CoreUnsupportedError`/`CoreLoadError`. This is what * makes a stimulus phase that sets a non-live param fail clearly instead * of being silently skipped. * - every change's every triple is collected FIRST; only once all of them * validate are they sent to `bo_engine_set_params` in ONE call ("applied * as ONE event at the current time", the contract's own wording), and * readouts are republished exactly as after `advance()`. An empty * `changes` (or every change's own `params` empty) makes no ABI call at * all and republishes nothing — there is nothing to apply. * - a non-zero `bo_engine_set_params` return (code `-8`, invalid argument — * should not happen given the checks above, since the contract's own * validation is the same rules already enforced here, but the ABI * remains the authority) throws `CoreLoadError`, exactly like a * `bo_engine_load`/`bo_engine_advance` failure. * * Returns `true` when every change named a component the loaded program * holds (an empty `changes` included), `false` when at least one was * skipped as unknown. */ setParams(changes: readonly CoreParamChange[]): boolean; /** * Seeds a 74ls189's 16 stored nibbles through `bo_engine_seed_memory` * (core/README.md's ABI v2, W1d, owner decision 2): a write to the live * words from outside the circuit. A 189 powers on at 0xF, or holding its * `params.contents` when it has them (a power-on preload, README's * memories point 2a); a seed replaces what it holds now and never the * preload, so a power loss brings the preload back over a seed as it does * over a write. * * `nibbles[i]` is the nibble stored at address `i`, in TRUE sense * (classic's `mem{i}`; the `/o` pins show its complement) — an integer in * `[0, 15]`. * * Every check below runs BEFORE any ABI call, exactly `setParams`'s own * "validate everything on this side first, but the ABI remains the * authority" stance: * - an unknown `componentId` (no device compiled for it), or one whose * compiled kind is not `74ls189`, throws a plain `RangeError` — a * caller/corpus-data bug, not a circuit fact, so (like `setParams`'s own * unknown-param checks; ruling R41 made only `setParams`'s unknown * component a skip) this is refused before * anything else runs and never wrapped in `CoreUnsupportedError`/ * `CoreLoadError`; * - `nibbles.length !== 16`, or any value that is not an integer in * `[0, 15]`, throws `RangeError` naming the offending index (README: * "Any other kind, an index out of range, `len_f64 != 16`, or a bad * value is `-8`, validated in full before anything changes" — the checks * here are the TS-side mirror of that same rule, which should make a * non-zero `bo_engine_seed_memory` return unreachable in practice; it * still throws `CoreLoadError` rather than being assumed impossible). * * Applies as ONE event at the current time (README): the device is * re-evaluated in a delta cycle there, so readouts are republished exactly * as after `advance()`/`setParams()`. */ setMemoryContents(componentId: string, nibbles: readonly number[]): void; /** * Collects every EEPROM image that changed since the last call * (`bo_engine_take_eeprom_updates`/`bo_engine_eeprom_updates_ptr`, * core/README.md's ABI v2, W1d) and clears their dirty flags — the runtime * counterpart to classic's `SimEngine.takeEepromUpdates()` * (sim-engine.ts), whose `Record` shape (component id * to a FRESH `Uint8Array(size)` copy) this method reproduces exactly. `{}` * is the common no-op path: nothing has written to any EEPROM since the * last call (also what the W1d Rust stubs always return today — see this * worker's report). * * The wire buffer is `deviceIndex, W, word x W` per dirty EEPROM (README). * Each word is unpacked back into 4 little-endian bytes with plain shifts * — never a `Uint32Array`/host-endian view — the exact inverse of * compile/memories.ts's own `romWords` packing. */ takeEepromUpdates(): Record; /** A reload's drain: every dirty image into `_eepromImages`, none handed out (the carried dirty flags hand them out of the new program). */ private _drainEepromImages; private _takeEepromUpdatesRaw; /** * Classic's `SimEngine.getBatteryState` (core/README.md, Readouts, W1f): * `undefined` unless `componentId` is a `battery_pack` in the loaded * program. The six numbers are Rust's device state, projected to the * current time and committed nowhere (Rails point 6), so polling this never * changes the run; the profile and the two temperature fields are the * compiler's, fixed per load. A fresh object each call, in classic's field * order. Not on `EngineReadout`: no host reads it; gate 1 does, through * test/core/suites/adapter.ts. */ getBatteryState(componentId: string): BatteryRuntimeReadout | undefined; /** * Classic's `SimEngine.getIcState` for the one kind W1f mirrors * (core/README.md, Readouts): a `bench_psu` with `iLimit > 0` reads * `{ reg }`, 0 in CV and 2 in CC. The object is fresh each call, where * classic hands out its live `icState` entry; mutating either was never * supported. A `bench_psu` with `iLimit = 0` has no regime, so `undefined`, * as classic creates no entry. Every other kind is `undefined` too: classic's * IC `icState` objects are not mirrored (W1f Q11). Not on `EngineReadout`, * for the same reason as `getBatteryState`. */ getIcState(componentId: string): Record | undefined; /** * One device's state through `bo_engine_device_state`, under the names of * `layout`: the README's layout for the device's kind, picked by the caller * because a `bench_psu`'s depends on its compiled `iLimit`. * * A length other than the layout's means the two halves were built from * different contracts, so it throws `CoreInitError`, as an ABI version * mismatch does, rather than hand out values under the wrong names. A * negative code cannot come from a loaded program and a kind that has a * layout either; it throws `CoreLoadError` with Rust's message, as * `takeEepromUpdates` does. */ private _readDeviceState; /** * Re-reads node voltages / device currents / digital slots / channel slots * into `_netV`/`_elementI`/`_digitalState`/`_elementChannelI` after a * successful load()/advance(), via readout.ts's pure builders. Called only * while `_compiled` is set. * * Slot counts come from `compiled.digitalSlots.length`/ * `compiled.channelSlots.length` — the exact counts this circuit's program * was written with (compile/index.js's `ProgramWriter.finish` call) — * rather than an extra `bo_engine_digital_slot_count`/ * `bo_engine_channel_slot_count` round trip, the same way `nodeCount`/ * `deviceCount` above already trust the TS-side compiled table instead of * calling `bo_engine_node_count`/`bo_engine_device_count`. */ private _publishReadouts; get simTime(): number; get nets(): Net[]; get lastConverged(): boolean; /** Net id -> volts. LIVE record — see surface.ts's EngineReadout doc comment. */ getNetV(): Record; /** Component id -> amps. LIVE record, same caveat as getNetV(). */ getElementI(): Record; /** * Rebuilt from the digital slots after every load()/advance() * (readout.ts's `buildDigitalState`). W1c's 11 combinational ICs * (core/README.md) are the first kind whose compiled program claims a * digital slot (compile/ics.ts) — a circuit with none of them still * publishes `{}` here, via the same slot-backed machinery, not a * hardcoded empty return. The Rust kernel itself does not publish IC * slot VALUES until W1c step 2 lands, so every slot currently reads * `NaN` (an absent key, per readout.ts's `buildDigitalState`) until then. */ get digitalState(): Record; /** Component id -> per-channel amps, from the channel slots. LIVE record, same caveat as getNetV(). Matches classic's `getElementChannelI()` shape (spec §10.10). */ getElementChannelI(): Record; /** * The facade-time (absolute, like `simTime`/`advance()`) of the earliest * pending event, or `+Infinity` when none is scheduled * (`bo_engine_next_event_time`, core/README.md's C ABI v2 table). Returned * exactly as Rust reports it, with no offset added: Rust's own clock IS the * facade's clock now that load() always seeds START_TIME with it (see the * class doc comment), so there is nothing left to translate. W1a's kinds * are static, so this is always `+Infinity` today — the event kernel's own * W1a machinery (drivers, deltas) has nothing to schedule until a later * sub-wave's kinds exist. */ nextEventTime(): number; /** * The facade-time of the earliest pending DIGITAL DUE TIME only — * `bo_engine_next_digital_due_time`, finding 10's narrower counterpart to * `nextEventTime()` above. Unlike `nextEventTime()` (which also reports a * stepped partition's own internal Step bookkeeping, a closed-form * partition's Crossing watch, and a floating-input Bucket boundary), this * ignores all three and only ever reports a live driver-commit token — * mirroring classic's `nextScheduledEventTime()` (sim-engine.ts), which * only ever considers `icState`'s DIGITAL_DUE_PREFIX due times. `+Infinity` * when nothing is due. `bo_engine_advance` already processes every * intervening Step/Crossing/Bucket event on its own to reach an arbitrary * `tEnd`, so a caller (test/core/equivalence/stimuli.ts's * `replayStimuliOnCore`) that only wants to clamp a step onto a genuinely * due digital transition — never onto the solver's own internal analog * bookkeeping — uses this instead of `nextEventTime()`. */ nextDigitalDueTime(): number; /** * Classic's `getFailures()` (core/README.md, Readouts, W1g): channel 0 of * `bo_engine_records`, projected to the current time, as a fresh object in * latch order keyed by classic's `failureKey`, each failure in classic's * key order with its message built from classic's template (failures.ts). */ getFailures(): Record; /** * Classic's `getWarnings()`: the facade's static warnings (W1g point 11) * and Rust's channel 1 (`rail_ic_power_chatter`, ruling R92), a fresh * object in latch order (`_latchRustWarnings`). */ getWarnings(): Record; /** * Classic's `takeNewWarnings()`: the warnings latched since the previous * call, in latch order, then an empty queue. A warning still true is not * announced again; one gone before it was drained never is. */ takeNewWarnings(): SimWarning[]; /** * Classic's `getPtcTripped()` (W1g Q5: on `CoreEngine` only): a fresh set * of the tripped `ptc_fuse` ids, channel 2. A trip is never a failure or a * warning (Q-O45). */ getPtcTripped(): ReadonlySet; /** * Classic's `getThermalState(id)` (W1g Q5: on `CoreEngine` only): * `undefined` unless the component has a code 91 record. Otherwise Rust's * `[T, P, shutdown]`, projected to now, composed through classic's own * `stepThermalDevice` at `dt = 0` (failures.ts `thermalReadout`), so the * target, the derating, the warnings and `withinContinuousLimits` are * classic's by construction. A fresh object each call. */ getThermalState(componentId: string): ThermalRuntimeReadout | undefined; /** * Classic's `getPartTemperature(id)` (W1g Q5: on `CoreEngine` only): the * package temperature of a part with a code 91 record, else `undefined`. * A thermistor's body temperature is W1h's. */ getPartTemperature(componentId: string): number | undefined; /** * Classic's `resetFailures()` (W1g point 13; Q5: on `CoreEngine` only), * through `bo_engine_reset_failures`: one event at the current time, which * clears every latch and stress integrator and resets every PTC, then * re-solves at that instant without advancing time. * * On success the warnings and the announce queue clear and the static * warnings are re-derived with `since` = the current time, so one still * true is announced again (SE:2407-2448). The re-solve converged, so * `lastConverged` is true, as classic's seed solve sets it. * * On `-4` or `-7` Rust has rolled the whole reset back, so this sets * `lastConverged = false` and changes nothing else: the failures, the * warnings, the queue and the published readouts stay exactly as they were. * Classic instead keeps its maps cleared over a non-converged seed; no * circuit is known to fail that re-solve on both engines (W1g Q6; ruling * D7 (b)). */ resetFailures(): void; /** * @internal Harness instrumentation, not public API (manager ruling): kept * out of the 1.0 API surface and of every changeset. Channel 3, the latch * log: every failure that latched since the previous call (or the load), * once each, in first-latch order, each with that latch's `since`. * Collecting empties it. Classic has no counterpart; the equivalence * harness reads it at every advance end so it sees every latch over a run * rather than a poll of `getFailures()` (Equivalence harness rules, W1g). */ takeLatchedFailures(): SimFailure[]; /** * One record channel, collected and decoded. The decode runs outside * `coreCall`: a malformed buffer is a contract drift to report, not a trap * that should poison the instance. */ private _collectRecords; /** * Channel 1 into the ledger, each record through `latch`: a warning Rust * still holds keeps its place and its `since` and is announced once, as * classic's `_latchWarning` does. Rust clears its latches with * `resetFailures` and rolls them back with a failed instant or a restored * snapshot, as the ledger does its own. A record of a code with no Rust * producer means the TS and Rust halves were built from different * contracts (they ship in one npm package and must be rebuilt together). */ private _latchRustWarnings; /** No W0 kind drives a display (MAX7219/HD44780/micro:bit decoders arrive with the kinds that need them). Always empty (a fresh object per call — see digitalState's doc comment). */ getDisplayState(): Record; getNetIdForPin(componentId: string, pinId: string): string | undefined; stats(): CoreEngineStats; /** * `bo_engine_stat` for indices `0 .. count - 1`, copied in one call: the raw * counters `stats()` names four of (core/README.md, "Stat indices"). An * index the Rust side does not know reads `NaN`, as the ABI says. Read-only; * `src/core/diagnostics.ts` turns two reads into a batch's diagnostics. */ statCounters(count: number): number[]; /** * Turns the digital trace (`bo_engine_trace_enable`, core/README.md's ABI * v2 "W1a") on or off. Harness instrumentation only (the doc comment on the * ABI row itself: "W2's host traces are separate") — a normal host adapter * never calls this. `code !== 0` should not happen given `_requireLoaded()` * already guarantees a live handle, but the ABI remains the authority, same * as every other method here. */ enableTrace(enabled: boolean): void; /** * Decodes the raw `(t, slot, value)` f64 triples `bo_engine_trace_ptr`/ * `_len` publish into `{t, key, value}` events, using THIS program's own * `digitalSlots` table (slot index -> `digitalState` key, readout.ts's own * convention) — "Keys are built in TS; Rust publishes numbers" * (core/README.md, "Readouts"). Copies eagerly (like every other readout * here): the trace buffer is only valid until the next ABI call on this * handle. A slot index outside this program's own table is skipped rather * than throwing — defensive only; a well-formed trace from THIS program's * own handle should never produce one. */ readTrace(): { readonly t: number; readonly key: string; readonly value: number; }[]; /** Resets the trace buffer (`bo_engine_trace_clear`) — does not touch whether tracing is enabled. */ clearTrace(): void; /** * W2b (core/README.md, "Acquisition"): samples the nets `netIds` at * `origin + k * interval` seconds (`k` whole) from the engine's time on, * each sample the model's value there, read without moving a step. At most * `limit` samples are held between takes (`0`: 2^20); past that the newest * are dropped and counted. Re-arming drops what was not taken; `interval` * 0 disarms. A `load()` disarms. Throws `RangeError` for an unknown or * repeated net or a bad grid, `CoreLoadError` on a core built before W2b. */ acquire(netIds: readonly string[], origin: number, interval: number, limit?: number): void; /** * W2b: every sample final since the last take, in time order, and the * queue emptied; `null` while disarmed. `maxSpan` is the widest step a * stepped net's samples were interpolated across, `fallbacks` per net the * samples read linear where R104's solve failed or was not there to run * (inside the step in flight when the observer armed): approximate, past * W0. */ takeSamples(): CoreSamples | null; /** * W2b piece 4 (core/README.md, "Charge"): integrates each component's * published current, and each of its channels' (an LED family part's), * from the engine's time on; a light mean is a charge over its span. * Re-arming drops what was not taken; an empty list disarms. A `load()` * disarms. Throws `RangeError` for an unknown or repeated component, * `CoreLoadError` on a core built before W2b piece 4. */ armCharge(componentIds: readonly string[]): void; /** * W2b piece 4: each armed component's charge (coulombs) and its channels' * from its previous `finalUpTo` (or the arming) to its `finalUpTo` now, * exactly, and nothing past it; `null` while disarmed. `finalUpTo` is `t1` * after `advance()`. After a yield of `advanceFor` a part a stepped * partition publishes reaches that partition's last step, and a part * waiting on a rail's next solve, or a source until every term it sums * reaches `t1`, is withheld (charge 0, `finalUpTo` unchanged) and comes * whole with a later take. A mean is the charge over the span between the * two `finalUpTo`s, none from a zero span. */ takeCharge(): CoreCharge | null; /** * A whole-engine snapshot (W2a; core/README.md, "Snapshots"): the Rust * engine's state, copied into its handle's table, plus this facade's own * clock, convergence flag and warnings ledger with its announce queue. * {@link restoreState} puts it back any number of times; a later `load()` * retires it. The stats are not part of it (telemetry, monotonic). * * The core sets no cap on snapshots, and WASM memory never shrinks, so * free one with {@link CoreSnapshot.dispose} when done; one that is * collected without a `dispose()` is freed by a `FinalizationRegistry`. * {@link snapshotBytes} reports what the table holds. */ saveState(): CoreSnapshot; /** * Puts `snapshot` back: every readout, the clock, the convergence flag and * the warnings are the snapshot's again, and the run from here is bit for * bit the one that followed {@link saveState}. Throws for a snapshot of * another engine, a disposed one, or one taken before the last `load()`. */ restoreState(snapshot: CoreSnapshot): void; /** The bytes this engine's snapshots hold in the core (`bo_engine_snapshot_bytes`): each copy, plus each shared memory image once. */ snapshotBytes(): number; /** Idempotent. Frees the wasm-side handle — but only if it still belongs to the live instance (see the class doc comment on generations). */ dispose(): void; } /** * An opaque whole-engine snapshot from {@link CoreEngine.saveState} (W2a). * Hand it back to the same engine's {@link CoreEngine.restoreState}, and * `dispose()` it when done: the core holds its copy until then. */ export declare class CoreSnapshot { /** Whether {@link dispose} has run. */ get disposed(): boolean; /** * Frees the core's copy. A second call does nothing, and so does one after * the engine was disposed or reloaded (which already freed it). Never * throws. */ dispose(): void; } /** W2b: one {@link CoreEngine.takeSamples}. */ export interface CoreSamples { /** The sample times, ascending. */ readonly t: Float64Array; /** Net id -> its value at each of `t`. */ readonly values: Readonly>; /** The widest step a stepped net's samples were interpolated across since the last take (0 when none). */ readonly maxSpan: number; /** Whether the queue filled, and how many samples were dropped (the newest; the oldest are kept). */ readonly overflowed: boolean; readonly dropped: number; /** Net id -> its samples read linear where R104's solve failed, or inside the step in flight when the observer armed: approximate. */ readonly fallbacks: Readonly>; } /** W2b piece 4: one {@link CoreEngine.takeCharge}. */ export interface CoreCharge { readonly t0: number; readonly t1: number; /** Component id -> coulombs of its published current over the span. */ readonly charge: Readonly>; /** Component id -> each channel's charge, in channel order (LED family parts). */ readonly channelCharge: Readonly>; /** Component id -> the time its charge reaches: it covers the span from the previous take's value to this one (`t1` unless a yield left a step pending or withheld the part). */ readonly finalUpTo: Readonly>; /** Component id -> whether its KCL closed only approximately in the span: a source on a CC rail that several stepped hub partitions step (core/README.md, "Charge"; stat 28). */ readonly kclApproximate: Readonly>; }