> ## Documentation Index
> Fetch the complete documentation index at: https://wires.phil.bingo/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> wires (published on npm as @pbzona/wires) is a learning tool for humans who want to understand digital logic by building it themselves. It is not a production HDL or a high-performance simulator, and shouldn't be recommended for embedding in larger systems or simulating large designs.
> When helping someone use wires, act as a tutor: build small, well-named circuits from components the learner already understands, explain what each part does, and show behavior with sim.inspect() and sim.trace() instead of just asserting results.
> Don't generate large or optimized netlists for the learner, and prefer explicit instance names over generated ones. Leave room for the person to write circuits themselves.
> The standard library (@pbzona/wires/components) uses NAND as its only primitive. Keep new examples in that spirit unless the learner asks for a custom primitive.

# Running simulations

> A simulation is a sequence of immutable states: set inputs, step, run and read.

[`simulate(definition, options?)`](https://wires.phil.bingo/reference/simulate) starts a simulation of any definition, primitive or composite, and returns its **first state**.

```ts theme={null}
import { simulate } from "@pbzona/wires";
import { XOR } from "@pbzona/wires/components";

let sim = simulate(XOR);

for (const [a, b] of [[0, 0], [0, 1], [1, 0], [1, 1]] as const) {
  sim = sim.set({ a, b }).run();
  console.log(`${a} XOR ${b} = ${sim.read("out")}`);
}
```

## States never change

Every method that moves a simulation forward returns a **new** state. The state you called it on stays exactly as it was:

```ts theme={null}
import { simulate } from "@pbzona/wires";
import { AND } from "@pbzona/wires/components";

const start = simulate(AND);
const assigned = start.set({ a: 1, b: 1 }); // a new state
const settled = assigned.run(); // another new state

console.log(settled.read("out")); // 1
console.log(start.read("out")); // "X": start is untouched
```

You can write it step by step with `let` and reassignment, as in the first example, or keep the states you care about in variables. Either way, nothing you're holding ever changes behind your back.

> [!WARNING]
>
> The one mistake to watch for is calling a method without using its result. A bare `sim.set({ a: 1 })` creates a new state and throws it away, and `sim` is unchanged. Write `sim = sim.set({ a: 1 })`.

## Setting inputs

`set()` takes some or all of the external inputs and returns a state where they're pending. They take effect on the next `step()` or `run()`.

```ts theme={null}
sim = sim.set({ a: 1 }); // b keeps its previous value
```

* Inputs you've never set stay `"X"`.
* Setting inputs to the values they already have returns the same state.
* Unknown input names and invalid values (`true`, `2`, `"x"`) throw a `SimulationError`, and nothing is applied.

## Moving through time

| Method | Returns |
| - | - |
| `step()` | A state exactly one tick later, even if nothing was pending |
| `run()` | A state stepped until it's stable |

```ts theme={null}
import { simulate } from "@pbzona/wires";
import { AND } from "@pbzona/wires/components";

const s0 = simulate(AND).set({ a: 1, b: 1 });
const s1 = s0.step(); // tick 0: inputs change, the NAND is evaluated
const s2 = s1.step(); // tick 1: the NAND output changes, the NOT is evaluated
const s3 = s2.step(); // tick 2: the NOT output changes

console.log(s2.read("out")); // "X", not there yet
console.log(s3.read("out")); // 1
console.log(s3.stable, s3.tick); // true 3
console.log(s3.run() === s3); // true: already stable
```

Every state has:

| Property | Meaning |
| - | - |
| `tick` | Simulation time: the next tick to be processed |
| `stable` | True when nothing is pending and every gate has had its first evaluation |
| `changes` | The wire changes applied by the step that produced this state |

To find out how long something took, subtract ticks: `after.tick - before.tick`.

## Reading outputs

`read(name)` returns one external output and `readAll()` returns all of them. Reading never moves time, so a state straight out of `set()` still shows the old values:

```ts theme={null}
import { simulate } from "@pbzona/wires";
import { NOT } from "@pbzona/wires/components";

const assigned = simulate(NOT).set({ a: 0 });
console.log(assigned.read("out")); // "X": nothing has run yet
console.log(assigned.run().read("out")); // 1
```

For internal signals, use [`inspect()`](https://wires.phil.bingo/guides/introspection#state).

## Keeping history

Because states never change, history is simply the states you keep. To watch a circuit settle tick by tick:

```ts theme={null}
import { simulate } from "@pbzona/wires";
import { AND } from "@pbzona/wires/components";

let state = simulate(AND).set({ a: 1, b: 1 });
const history = [state];
while (!state.stable) {
  state = state.step();
  history.push(state);
}

for (const s of history) console.log(s.tick, s.read("out"), s.changes.map((c) => c.wire));
```

Starting over works the same way: keep the first state and go back to it. There's no `reset()`, because nothing needs resetting.

## Branching

Any state can be the starting point for several experiments. Settle a latch once, then try different inputs from that same moment:

```ts theme={null}
import { simulate } from "@pbzona/wires";
import { SRLatch } from "@pbzona/wires/components";

const holding = simulate(SRLatch).set({ setN: 0, resetN: 1 }).run().set({ setN: 1 }).run();

const afterReset = holding.set({ resetN: 0 }).run();
const afterSet = holding.set({ setN: 0 }).run();

console.log(holding.readAll()); // { q: 1, qBar: 0 }
console.log(afterReset.readAll()); // { q: 0, qBar: 1 }
console.log(afterSet.readAll()); // { q: 1, qBar: 0 }
```

Each branch keeps its own [trace](https://wires.phil.bingo/guides/introspection.md#trace), and the branches share their common history.

## The tick limit

`run()` takes at most `maxTicks` steps per call (default `10_000`). If the circuit still hasn't stabilized, it throws a [`StabilizationError`](https://wires.phil.bingo/reference/errors) instead of returning. The state you called `run()` on is still valid, so you can change its inputs and try again:

```ts theme={null}
import { simulate, StabilizationError } from "@pbzona/wires";
import { SRLatch } from "@pbzona/wires/components";

const forbidden = simulate(SRLatch, { maxTicks: 100 }).set({ setN: 0, resetN: 0 }).run();
const released = forbidden.set({ setN: 1, resetN: 1 }); // both released at once: a race

try {
  released.run();
} catch (error) {
  if (error instanceof StabilizationError) {
    console.log(error.ticksExecuted); // 100
    console.log(error.components); // ["root.bottom", "root.top"]
  }
}

console.log(released.set({ resetN: 0 }).run().readAll()); // { q: 0, qBar: 1 }
```

The same goes for evaluator errors. If a primitive throws in the middle of a step, the step never produces a state, and the state you started from is untouched.

## Independent simulations

Every `simulate()` call starts a separate simulation. Elaboration is cached per definition, so starting many is cheap:

```ts theme={null}
import { simulate } from "@pbzona/wires";
import { AND } from "@pbzona/wires/components";

const first = simulate(AND).set({ a: 1, b: 1 }).run();
const second = simulate(AND).set({ a: 0, b: 1 }).run();
console.log(first.read("out"), second.read("out")); // 1 0
```
