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

# Composing circuits

> Build composite circuits by adding parts and saying what feeds them.

A composite circuit is defined with [`circuit()`](https://wires.phil.bingo/reference/circuit): a spec with its name and external ports, plus a builder callback that adds parts and wires them together.

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

const NOT = circuit({ name: "NOT", inputs: ["a"], outputs: ["out"] }, ({ inputs, add, output }) => {
  const g = add(NAND, "g", { a: inputs.a, b: inputs.a });
  output("out", g.outputs.out);
});

const AND = circuit({ name: "AND", inputs: ["a", "b"], outputs: ["out"] }, ({ inputs, add, output }) => {
  const nand = add(NAND, "nand", { a: inputs.a, b: inputs.b });
  const not = add(NOT, "not", { a: nand.outputs.out }); // composites are added exactly like primitives
  output("out", not.outputs.out);
});

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

Read it top to bottom. Each line adds one part and says what feeds each of its inputs, so the signal flows down the page: the circuit's inputs feed `nand`, `nand` feeds `not`, and `not` drives the output.

## The builder context

| Member | Description |
| - | - |
| `inputs` | The circuit's own inputs. Use them as sources for the parts you add. |
| `add(definition, name?, inputs?)` | Adds a part (primitive or composite), wires the inputs you list, and returns it |
| `feed(part.inputs.x, source)` | Wires an input of a part you already added. Used for feedback. |
| `output(name, source)` | Drives one of the circuit's own outputs |

Every wiring call reads **destination ← source**, like an assignment:

```ts theme={null}
add(NOT, "not", { a: nand.outputs.out }); // not's input a  ← nand's output
feed(top.inputs.b, bottom.outputs.out);   // top's input b  ← bottom's output
output("out", not.outputs.out);           // circuit's out  ← not's output
```

`add` doesn't care whether a definition is primitive or composite, and nesting depth is unlimited.

## Sources

A **source** is anything that can drive a wire:

* the circuit's own inputs (`inputs.a`)
* the outputs of parts you've added (`nand.outputs.out`)

A part's inputs are never sources: they receive a signal, they don't produce one. One source can feed any number of inputs (fan-out), but each input has exactly one source.

## Naming parts

Part names are optional:

* **Explicit names** must be identifiers and unique within the circuit. `inputs` and `outputs` are reserved.
* **Generated names** have the form `<Definition>#<n>`, counted per definition in the order you call `add`, for example `XOR#0` and `XOR#1`. Leave the name out and pass the inputs second: `add(NOT, { a: inputs.a })`.

Explicit names make hierarchical paths readable (`root.fa3.or` rather than `root.FullAdder#3.OR#0`), so prefer them for anything you plan to inspect.

## Feedback

Sometimes a part needs a signal from a part that comes later. Memory works this way. Leave that input out of the `add` call, then wire it with `feed` once the source exists:

```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);
  },
);
```

Because feedback is the only time you need `feed`, every feedback wire stands out when you read a circuit. Cycles are never rejected just for being cycles. See [Sequential logic](https://wires.phil.bingo/guides/sequential-logic.md) for how they behave.

The one exception is a loop made only of wires, with no gate anywhere in it. That can happen through pass-through composites, and since such a wire has no driver, it is reported when the circuit is elaborated.

## Checks

The builder checks your wiring and reports problems as a `CircuitError` prefixed with the circuit name. Most of them are also compile-time errors.

| Check | Example message |
| - | - |
| Input names the part doesn't have | `C: NAND has no input "c" (its inputs are a, b)` |
| Ports that don't exist | `C: n.inputs.b is not a port (got undefined); check that the port name exists` |
| A part's input used as a source | `C: b.inputs.a can't be used as a source for outputs.out: it's a component input, …` |
| Two sources for one input or output | `C: outputs.out has multiple drivers (inputs.a and inputs.b); …` |
| Output names the circuit doesn't have | `C: "other" is not an output of C (its outputs are out)` |
| Ports belonging to another circuit | `C: … belongs to circuit "Other", which is not part of this circuit …` |
| Duplicate, invalid or reserved part names | `C: Duplicate component instance name "x"` |

After the builder returns, every part input that was never wired and every output that was never driven is reported together:

```text theme={null}
HalfBroken: Invalid circuit:
  - input n.inputs.b is not connected
  - output outputs.other is not driven
```

Unused circuit inputs and unused part outputs are fine.

## When the builder runs

The builder callback runs **immediately**, inside `circuit()`, and the result is checked before `circuit()` returns. A wiring mistake is reported where you define the circuit, not later when you first simulate it.

It also means a circuit can only contain parts that already exist. A circuit can never contain itself, so every circuit elaborates into a finite set of gates. Builders must be synchronous, and the builder context can't be used after the callback returns.
