> ## 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.

# Sequential logic

> Feedback loops, memory, unknown state and oscillation.

Combinational circuits forget. Feed an output back into an input and a circuit can **remember**. `wires` allows arbitrary feedback, and its unit-delay simulation shows exactly how feedback circuits behave, including when they misbehave.

## The NAND SR latch

The standard [`SRLatch`](https://wires.phil.bingo/library/memory) is two cross-coupled NAND gates with active-low controls:

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

const SRLatch = circuit(
  { name: "SRLatch", inputs: ["setN", "resetN"], outputs: ["q", "qBar"] },
  ({ inputs, add, feed, output }) => {
    const top = add(NAND, "top", { a: inputs.setN }); // b is fed back below
    const bottom = add(NAND, "bottom", { a: inputs.resetN, b: top.outputs.out });
    feed(top.inputs.b, bottom.outputs.out); // the feedback wire
    output("q", top.outputs.out);
    output("qBar", bottom.outputs.out);
  },
);
```

`top` needs `bottom`'s output, but `bottom` doesn't exist yet when `top` is added. So `top`'s input `b` is left out of the `add` call and wired afterwards with [`feed`](https://wires.phil.bingo/guides/composing-circuits#feedback). Each part feeds the other, and that loop is what lets the latch remember.

## Storing a bit

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

let latch = simulate(SRLatch);

latch = latch.set({ setN: 1, resetN: 1 }).run();
console.log(latch.readAll()); // { q: "X", qBar: "X" }: never initialized

latch = latch.set({ setN: 0 }).run(); // set
latch = latch.set({ setN: 1 }).run(); // release
console.log(latch.readAll()); // { q: 1, qBar: 0 }: remembers 1
const rememberedOne = latch;

latch = latch.set({ resetN: 0 }).run(); // reset
latch = latch.set({ resetN: 1 }).run(); // release
console.log(latch.readAll()); // { q: 0, qBar: 1 }: remembers 0
console.log(rememberedOne.readAll()); // { q: 1, qBar: 0 }: earlier states never change
```

| setN | resetN | Result |
| - | - | - |
| 0 | 1 | Set: `q = 1`, `qBar = 0` |
| 1 | 0 | Reset: `q = 0`, `qBar = 1` |
| 1 | 1 | Hold the previous state (`X` if never initialized) |
| 0 | 0 | Forbidden: `q = qBar = 1` |

## Unknown state is a real state

A latch that has never been set or reset settles into a **stable unknown** state. `run()` returns normally and both outputs read `"X"`. The simulator does not pick a value for you, because a real latch powers up in an unpredictable state.

## The forbidden state

Holding both controls low drives both outputs to `1`. That isn't a complementary state, so it can't be stored. Releasing both controls in the same tick starts a race: both gates flip to `0` together, then back to `1` together, forever. `run()` detects this and throws a `StabilizationError` instead of quietly choosing a winner.

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

const forbidden = simulate(SRLatch, { maxTicks: 50 }).set({ setN: 0, resetN: 0 }).run();
console.log(forbidden.readAll()); // { q: 1, qBar: 1 }

try {
  forbidden.set({ setN: 1, resetN: 1 }).run();
} catch (error) {
  console.log(error instanceof StabilizationError); // true
}
```

## Oscillators

An odd number of inverters in a loop has no stable state. This ring oscillator gates its loop with a NAND, so it can be held still while `enable = 0`:

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

const Ring = circuit({ name: "Ring", inputs: ["enable"], outputs: ["out"] }, ({ inputs, add, feed, output }) => {
  const gate = add(NAND, "gate", { a: inputs.enable }); // b is fed back from inv2
  const inv1 = add(NOT, "inv1", { a: gate.outputs.out });
  const inv2 = add(NOT, "inv2", { a: inv1.outputs.out });
  feed(gate.inputs.b, inv2.outputs.out);
  output("out", inv2.outputs.out);
});

const still = simulate(Ring, { maxTicks: 100, trace: true }).set({ enable: 0 }).run(); // stable, out = 1
const running = still.set({ enable: 1 });

try {
  running.run();
} catch (error) {
  if (!(error instanceof StabilizationError)) throw error;
  console.log(error.components); // ["root.gate", "root.inv1.g", "root.inv2.g"]
}

console.log(running.set({ enable: 0 }).run().read("out")); // 1: stopped, and settled again

// Step through the oscillation and watch the output
let s = running;
for (let i = 0; i < 12; i++) s = s.step();
console.log(s.trace().filter((t) => t.wire === "root.inv2.g.outputs.out").map((t) => `@${t.tick}: ${t.value}`));
```

With three one-tick stages, the output toggles every three ticks. Step through it with `step()` and read the timing from `trace()`.

If you never set `enable`, the loop stays at `"X"`. That's a stable unknown, not an oscillation, because nothing ever changes.
