relu-trace 0.0.0-stage → 0.1.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.
@@ -0,0 +1,125 @@
1
+ export type ErrorCode = 'VALIDATION_ERROR' | 'ARITHMETIC_OVERFLOW' | 'OUT_OF_RANGE' | 'INVALID_CONDITION' | 'INVALID_ADDRESS';
2
+ export declare class ReluTraceError extends Error {
3
+ readonly code: ErrorCode;
4
+ readonly path?: string;
5
+ constructor(code: ErrorCode, message: string, path?: string);
6
+ }
7
+ export declare const MAX_BANK_SIZE = 1048576;
8
+ export type Range = {
9
+ min: number;
10
+ max: number;
11
+ };
12
+ export type Bank = Range & {
13
+ size: number;
14
+ };
15
+ export type Term = {
16
+ from: string;
17
+ weight: number;
18
+ };
19
+ export type Gate = {
20
+ id: string;
21
+ bias: number;
22
+ terms: Term[];
23
+ };
24
+ export type Target = string | null;
25
+ export type Control = Target | {
26
+ test: string;
27
+ yes: Target;
28
+ no: Target;
29
+ };
30
+ export type Instruction = {
31
+ inputs?: Record<string, string>;
32
+ reads?: {
33
+ id: string;
34
+ bank: string;
35
+ address: string;
36
+ }[];
37
+ gates: Gate[];
38
+ next: Control;
39
+ set?: Record<string, string>;
40
+ writes?: {
41
+ bank: string;
42
+ address: string;
43
+ value: string;
44
+ when?: string;
45
+ }[];
46
+ };
47
+ export type Machine = {
48
+ version: 1;
49
+ entry: string;
50
+ registers: Record<string, Range>;
51
+ banks: Record<string, Bank>;
52
+ instructions: Record<string, Instruction>;
53
+ };
54
+ export type Snapshot = {
55
+ instruction: Target;
56
+ registers: Record<string, number>;
57
+ ram: Record<string, number[]>;
58
+ };
59
+ export type Write = {
60
+ bank: string;
61
+ address: number;
62
+ before: number;
63
+ value: number;
64
+ };
65
+ export type Transition = {
66
+ next: Target;
67
+ changes: Record<string, {
68
+ before: number;
69
+ value: number;
70
+ }>;
71
+ writes: Write[];
72
+ };
73
+ export type Reference = (before: Snapshot) => Transition;
74
+ export type Clamp = {
75
+ tick: number;
76
+ instruction: string;
77
+ signal: string;
78
+ };
79
+ export type GateTrace = {
80
+ id: string;
81
+ bias: number;
82
+ terms: (Term & {
83
+ input: number;
84
+ product: number;
85
+ })[];
86
+ sum: number;
87
+ activation: number;
88
+ output: number;
89
+ };
90
+ export type Trace = {
91
+ tick: number;
92
+ instruction: string;
93
+ inputs: {
94
+ id: string;
95
+ register: string;
96
+ value: number;
97
+ }[];
98
+ reads: {
99
+ id: string;
100
+ bank: string;
101
+ address: number;
102
+ value: number;
103
+ }[];
104
+ gates: GateTrace[];
105
+ branch?: {
106
+ signal: string;
107
+ value: 0 | 1;
108
+ };
109
+ } & ({
110
+ outcome: 'committed';
111
+ transition: Transition;
112
+ } | {
113
+ outcome: 'invalid';
114
+ error: string;
115
+ code: ErrorCode;
116
+ });
117
+ export type Status = 'running' | 'halt' | 'invalid' | 'budget';
118
+ export declare function requireThat(ok: unknown, message: string, code?: ErrorCode, path?: string): asserts ok;
119
+ export declare function integer(value: unknown, label: string, code?: ErrorCode, path?: string): number;
120
+ export declare function inRange(input: unknown, { min, max }: Range, label: string, code?: ErrorCode, path?: string): number;
121
+ export declare function requireRecord(value: unknown, path: string): asserts value is Record<string, unknown>;
122
+ export declare function requireAllowedKeys(record: Record<string, unknown>, allowed: readonly string[], path: string): void;
123
+ export declare function cloneInput<T>(value: T, label: string): T;
124
+ /** Copy and validate a portable v1 definition, including objects from JSON.parse. */
125
+ export declare function parseMachine(definition: unknown): Machine;
package/dist/model.js ADDED
@@ -0,0 +1,169 @@
1
+ export class ReluTraceError extends Error {
2
+ code;
3
+ path;
4
+ constructor(code, message, path) {
5
+ super(message);
6
+ this.name = 'ReluTraceError';
7
+ this.code = code;
8
+ if (path !== undefined)
9
+ this.path = path;
10
+ }
11
+ }
12
+ export const MAX_BANK_SIZE = 1_048_576;
13
+ const idPattern = /^[A-Za-z_][A-Za-z0-9_-]*$/;
14
+ export function requireThat(ok, message, code = 'VALIDATION_ERROR', path) {
15
+ if (!ok)
16
+ throw new ReluTraceError(code, message, path);
17
+ }
18
+ export function integer(value, label, code = 'VALIDATION_ERROR', path) {
19
+ requireThat(typeof value === 'number' && Number.isSafeInteger(value), `${label} must be a safe integer`, code, path);
20
+ return value === 0 ? 0 : value;
21
+ }
22
+ export function inRange(input, { min, max }, label, code = 'VALIDATION_ERROR', path) {
23
+ const value = integer(input, label, code, path);
24
+ requireThat(value >= min && value <= max, `${label} ${value} is outside [${min}, ${max}]`, code, path);
25
+ return value;
26
+ }
27
+ export function requireRecord(value, path) {
28
+ requireThat(value !== null && typeof value === 'object' && [Object.prototype, null].includes(Object.getPrototypeOf(value)), `${path} must be an object`, 'VALIDATION_ERROR', path);
29
+ }
30
+ export function requireAllowedKeys(record, allowed, path) {
31
+ for (const key of Object.keys(record)) {
32
+ requireThat(allowed.includes(key), `${path}: unexpected property ${key}`, 'VALIDATION_ERROR', `${path}.${key}`);
33
+ }
34
+ }
35
+ export function cloneInput(value, label) {
36
+ try {
37
+ return structuredClone(value);
38
+ }
39
+ catch {
40
+ throw new ReluTraceError('VALIDATION_ERROR', `${label} must be structured-cloneable`, label);
41
+ }
42
+ }
43
+ /** Copy and validate a portable v1 definition, including objects from JSON.parse. */
44
+ export function parseMachine(definition) {
45
+ const input = cloneInput(definition, 'Machine');
46
+ validate(input);
47
+ return input;
48
+ }
49
+ const machineKeys = ['version', 'entry', 'registers', 'banks', 'instructions'];
50
+ const rangeKeys = ['min', 'max'];
51
+ const bankKeys = ['min', 'max', 'size'];
52
+ const instructionKeys = ['inputs', 'reads', 'gates', 'next', 'set', 'writes'];
53
+ const readKeys = ['id', 'bank', 'address'];
54
+ const gateKeys = ['id', 'bias', 'terms'];
55
+ const termKeys = ['from', 'weight'];
56
+ const controlKeys = ['test', 'yes', 'no'];
57
+ const writeKeys = ['bank', 'address', 'value', 'when'];
58
+ function validate(machine) {
59
+ requireRecord(machine, 'Machine');
60
+ requireAllowedKeys(machine, machineKeys, 'Machine');
61
+ requireThat(machine.version === 1, 'Expected machine definition version 1', 'VALIDATION_ERROR', 'version');
62
+ function object(value, path) {
63
+ requireRecord(value, path);
64
+ return value;
65
+ }
66
+ function list(value, path) {
67
+ requireThat(Array.isArray(value), `${path} must be an ordered array`, 'VALIDATION_ERROR', path);
68
+ return value;
69
+ }
70
+ function id(name, path) {
71
+ requireThat(typeof name === 'string' && idPattern.test(name), `${path} must be an identifier matching [A-Za-z_][A-Za-z0-9_-]*`, 'VALIDATION_ERROR', path);
72
+ }
73
+ const registers = object(machine.registers, 'registers');
74
+ const banks = object(machine.banks, 'banks');
75
+ const instructions = object(machine.instructions, 'instructions');
76
+ function named(value, names, path) {
77
+ id(value, path);
78
+ requireThat(Object.hasOwn(names, value), `${path}: unknown name ${value}`, 'VALIDATION_ERROR', path);
79
+ }
80
+ function range(value, path, allowed) {
81
+ const bounds = object(value, path);
82
+ requireAllowedKeys(bounds, allowed, path);
83
+ const min = integer(bounds.min, `${path}.min`, 'VALIDATION_ERROR', `${path}.min`);
84
+ const max = integer(bounds.max, `${path}.max`, 'VALIDATION_ERROR', `${path}.max`);
85
+ requireThat(min <= max, `${path}: minimum exceeds maximum`, 'VALIDATION_ERROR', path);
86
+ bounds.min = min;
87
+ bounds.max = max;
88
+ return bounds;
89
+ }
90
+ for (const [name, value] of Object.entries(registers)) {
91
+ id(name, 'Register name');
92
+ range(value, `registers.${name}`, rangeKeys);
93
+ }
94
+ for (const [name, value] of Object.entries(banks)) {
95
+ id(name, 'Bank name');
96
+ const bank = range(value, `banks.${name}`, bankKeys);
97
+ bank.size = inRange(bank.size, { min: 1, max: MAX_BANK_SIZE }, `banks.${name}.size`, 'VALIDATION_ERROR', `banks.${name}.size`);
98
+ }
99
+ named(machine.entry, instructions, 'entry');
100
+ for (const [name, value] of Object.entries(instructions)) {
101
+ id(name, 'Instruction name');
102
+ const at = `instructions.${name}`;
103
+ const block = object(value, at);
104
+ requireAllowedKeys(block, instructionKeys, at);
105
+ const signals = new Set();
106
+ function add(signal, path) {
107
+ id(signal, path);
108
+ requireThat(!signals.has(signal), `${path}: duplicate signal ${signal}`, 'VALIDATION_ERROR', path);
109
+ signals.add(signal);
110
+ }
111
+ function use(signal, path) {
112
+ id(signal, path);
113
+ requireThat(signals.has(signal), `${path}: unknown or forward signal ${signal}`, 'VALIDATION_ERROR', path);
114
+ }
115
+ for (const [signal, source] of Object.entries(block.inputs === undefined ? {} : object(block.inputs, `${at}.inputs`))) {
116
+ const path = `${at}.inputs.${signal}`;
117
+ named(source, registers, path);
118
+ add(signal, path);
119
+ }
120
+ for (const [i, value] of (block.reads === undefined ? [] : list(block.reads, `${at}.reads`)).entries()) {
121
+ const path = `${at}.reads[${i}]`;
122
+ const read = object(value, path);
123
+ requireAllowedKeys(read, readKeys, path);
124
+ named(read.bank, banks, `${path}.bank`);
125
+ use(read.address, `${path}.address`);
126
+ add(read.id, `${path}.id`);
127
+ }
128
+ for (const [i, value] of list(block.gates, `${at}.gates`).entries()) {
129
+ const path = `${at}.gates[${i}]`;
130
+ const gate = object(value, path);
131
+ requireAllowedKeys(gate, gateKeys, path);
132
+ gate.bias = integer(gate.bias, `${path}.bias`, 'VALIDATION_ERROR', `${path}.bias`);
133
+ for (const [j, value] of list(gate.terms, `${path}.terms`).entries()) {
134
+ const termPath = `${path}.terms[${j}]`;
135
+ const term = object(value, termPath);
136
+ requireAllowedKeys(term, termKeys, termPath);
137
+ use(term.from, `${termPath}.from`);
138
+ term.weight = integer(term.weight, `${termPath}.weight`, 'VALIDATION_ERROR', `${termPath}.weight`);
139
+ }
140
+ add(gate.id, `${path}.id`);
141
+ }
142
+ if (block.next !== null && typeof block.next === 'object') {
143
+ const next = object(block.next, `${at}.next`);
144
+ requireAllowedKeys(next, controlKeys, `${at}.next`);
145
+ use(next.test, `${at}.next.test`);
146
+ if (next.yes !== null)
147
+ named(next.yes, instructions, `${at}.next.yes`);
148
+ if (next.no !== null)
149
+ named(next.no, instructions, `${at}.next.no`);
150
+ }
151
+ else if (block.next !== null)
152
+ named(block.next, instructions, `${at}.next`);
153
+ for (const [dest, signal] of Object.entries(block.set === undefined ? {} : object(block.set, `${at}.set`))) {
154
+ const path = `${at}.set.${dest}`;
155
+ named(dest, registers, path);
156
+ use(signal, path);
157
+ }
158
+ for (const [i, value] of (block.writes === undefined ? [] : list(block.writes, `${at}.writes`)).entries()) {
159
+ const path = `${at}.writes[${i}]`;
160
+ const write = object(value, path);
161
+ requireAllowedKeys(write, writeKeys, path);
162
+ named(write.bank, banks, `${path}.bank`);
163
+ use(write.address, `${path}.address`);
164
+ use(write.value, `${path}.value`);
165
+ if (write.when !== undefined)
166
+ use(write.when, `${path}.when`);
167
+ }
168
+ }
169
+ }
@@ -0,0 +1,19 @@
1
+ import type { Clamp, ErrorCode, Machine, Snapshot, Status, Trace } from './model.js';
2
+ export type SessionOptions = {
3
+ limit: number;
4
+ clamp?: Clamp;
5
+ };
6
+ export type Session = {
7
+ readonly status: Status;
8
+ readonly ticks: number;
9
+ readonly error: string | undefined;
10
+ readonly errorCode: ErrorCode | undefined;
11
+ snapshot: () => Snapshot;
12
+ step: (options?: {
13
+ trace?: boolean;
14
+ }) => Trace | undefined;
15
+ run: (options?: {
16
+ trace?: boolean;
17
+ }) => Trace[];
18
+ };
19
+ export declare function createSession(definition: Machine, initial: Snapshot, options: SessionOptions): Session;
@@ -0,0 +1,157 @@
1
+ import { cloneInput, inRange, integer, parseMachine, ReluTraceError, requireAllowedKeys, requireRecord, requireThat } from './model.js';
2
+ const snapshotKeys = ['instruction', 'registers', 'ram'];
3
+ const sessionOptionKeys = ['limit', 'clamp'];
4
+ const clampKeys = ['tick', 'instruction', 'signal'];
5
+ function copyInitial(machine, initial) {
6
+ const copy = cloneInput(initial, 'Snapshot');
7
+ requireRecord(copy, 'Snapshot');
8
+ requireAllowedKeys(copy, snapshotKeys, 'Snapshot');
9
+ const { instruction, registers, ram } = copy;
10
+ requireRecord(registers, 'Snapshot registers');
11
+ requireRecord(ram, 'Snapshot RAM');
12
+ requireThat(instruction === null || (typeof instruction === 'string' && Object.hasOwn(machine.instructions, instruction)), `Unknown initial instruction: ${instruction}`, 'VALIDATION_ERROR', 'Snapshot.instruction');
13
+ requireThat(Object.keys(registers).length === Object.keys(machine.registers).length &&
14
+ Object.keys(ram).length === Object.keys(machine.banks).length, 'Snapshot must contain exactly the declared registers and RAM banks', 'VALIDATION_ERROR', 'Snapshot');
15
+ for (const [id, range] of Object.entries(machine.registers)) {
16
+ requireThat(Object.hasOwn(registers, id), `Missing register ${id}`, 'VALIDATION_ERROR', `Snapshot.registers.${id}`);
17
+ registers[id] = inRange(registers[id], range, `Register ${id}`, 'VALIDATION_ERROR', `Snapshot.registers.${id}`);
18
+ }
19
+ for (const [id, bank] of Object.entries(machine.banks)) {
20
+ requireThat(Object.hasOwn(ram, id) && Array.isArray(ram[id]) && ram[id].length === bank.size, `RAM ${id} must have exactly ${bank.size} cells`, 'VALIDATION_ERROR', `Snapshot.ram.${id}`);
21
+ for (let i = 0; i < bank.size; i++) {
22
+ ram[id][i] = inRange(ram[id][i], bank, `${id}[${i}]`, 'VALIDATION_ERROR', `Snapshot.ram.${id}[${i}]`);
23
+ }
24
+ }
25
+ return { instruction: instruction, registers: registers, ram: ram };
26
+ }
27
+ export function createSession(definition, initial, options) {
28
+ const machine = parseMachine(definition);
29
+ requireRecord(options, 'Session options');
30
+ requireAllowedKeys(options, sessionOptionKeys, 'Session options');
31
+ const limit = integer(options.limit, 'Tick limit', 'VALIDATION_ERROR', 'Session options.limit');
32
+ requireThat(limit > 0, 'Tick limit must be positive', 'VALIDATION_ERROR', 'Session options.limit');
33
+ let intervention;
34
+ if (options.clamp !== undefined) {
35
+ const clonedClamp = cloneInput(options.clamp, 'Clamp');
36
+ requireRecord(clonedClamp, 'Clamp');
37
+ requireAllowedKeys(clonedClamp, clampKeys, 'Clamp');
38
+ const tick = integer(clonedClamp.tick, 'Clamp tick', 'VALIDATION_ERROR', 'Clamp.tick');
39
+ requireThat(tick >= 1 && tick <= limit, 'Clamp tick is outside the session limit', 'VALIDATION_ERROR', 'Clamp.tick');
40
+ requireThat(typeof clonedClamp.instruction === 'string' &&
41
+ typeof clonedClamp.signal === 'string' &&
42
+ Object.hasOwn(machine.instructions, clonedClamp.instruction) &&
43
+ machine.instructions[clonedClamp.instruction].gates.some(gate => gate.id === clonedClamp.signal), `Clamp must name a gate: ${clonedClamp.instruction}.${clonedClamp.signal}`, 'VALIDATION_ERROR', 'Clamp');
44
+ intervention = { tick, instruction: clonedClamp.instruction, signal: clonedClamp.signal };
45
+ }
46
+ const state = copyInitial(machine, initial);
47
+ let attempted = 0;
48
+ let status = state.instruction === null ? 'halt' : 'running';
49
+ let error;
50
+ let errorCode;
51
+ function step({ trace = true } = {}) {
52
+ if (status !== 'running' || state.instruction === null)
53
+ return;
54
+ const instruction = state.instruction;
55
+ const block = machine.instructions[instruction];
56
+ const tick = ++attempted;
57
+ const record = trace ? { tick, instruction, inputs: [], reads: [], gates: [] } : undefined;
58
+ const signals = new Map();
59
+ // Definitions are validated once. Every signal use must follow its definition.
60
+ const value = (id) => signals.get(id);
61
+ function condition(id) {
62
+ const bit = value(id);
63
+ requireThat(bit === 0 || bit === 1, `${id} must be 0 or 1 (got ${bit})`, 'INVALID_CONDITION', id);
64
+ return bit;
65
+ }
66
+ function address(bank, id) {
67
+ return inRange(value(id), { min: 0, max: machine.banks[bank].size - 1 }, `RAM ${bank} address`, 'INVALID_ADDRESS', bank);
68
+ }
69
+ let next;
70
+ const changes = {};
71
+ const writes = [];
72
+ try {
73
+ for (const [id, register] of Object.entries(block.inputs ?? {})) {
74
+ const input = state.registers[register];
75
+ signals.set(id, input);
76
+ record?.inputs.push({ id, register, value: input });
77
+ }
78
+ for (const read of block.reads ?? []) {
79
+ const index = address(read.bank, read.address);
80
+ const input = state.ram[read.bank][index];
81
+ signals.set(read.id, input);
82
+ record?.reads.push({ id: read.id, bank: read.bank, address: index, value: input });
83
+ }
84
+ for (const gate of block.gates) {
85
+ const terms = record ? [] : undefined;
86
+ let sum = gate.bias;
87
+ for (const { from, weight } of gate.terms) {
88
+ const input = value(from);
89
+ const product = integer(input * weight, `${gate.id} product`, 'ARITHMETIC_OVERFLOW', gate.id);
90
+ sum = integer(sum + product, `${gate.id} partial sum`, 'ARITHMETIC_OVERFLOW', gate.id);
91
+ terms?.push({ from, weight, input, product });
92
+ }
93
+ const activation = Math.max(0, sum);
94
+ const output = intervention?.tick === tick && intervention.instruction === instruction && intervention.signal === gate.id
95
+ ? 0 : activation;
96
+ signals.set(gate.id, output);
97
+ if (record && terms)
98
+ record.gates.push({ id: gate.id, bias: gate.bias, terms, sum, activation, output });
99
+ }
100
+ if (block.next !== null && typeof block.next === 'object') {
101
+ const bit = condition(block.next.test);
102
+ next = bit ? block.next.yes : block.next.no;
103
+ if (record)
104
+ record.branch = { signal: block.next.test, value: bit };
105
+ }
106
+ else
107
+ next = block.next;
108
+ for (const [dest, id] of Object.entries(block.set ?? {})) {
109
+ const updated = inRange(value(id), machine.registers[dest], `Register ${dest}`, 'OUT_OF_RANGE', dest);
110
+ const before = state.registers[dest];
111
+ if (before !== updated)
112
+ Object.defineProperty(changes, dest, { value: { before, value: updated }, enumerable: true });
113
+ }
114
+ for (const write of block.writes ?? []) {
115
+ if (write.when !== undefined && condition(write.when) === 0)
116
+ continue;
117
+ const index = address(write.bank, write.address);
118
+ const updated = inRange(value(write.value), machine.banks[write.bank], `RAM ${write.bank}[${index}]`, 'OUT_OF_RANGE', `${write.bank}[${index}]`);
119
+ writes.push({ bank: write.bank, address: index, before: state.ram[write.bank][index], value: updated });
120
+ }
121
+ }
122
+ catch (reason) {
123
+ status = 'invalid';
124
+ error = reason instanceof Error ? reason.message : String(reason);
125
+ errorCode = reason instanceof ReluTraceError ? reason.code : 'VALIDATION_ERROR';
126
+ return record && { ...record, outcome: 'invalid', error, code: errorCode };
127
+ }
128
+ // Only commit after every condition, address and result has been validated.
129
+ for (const [dest, change] of Object.entries(changes))
130
+ state.registers[dest] = change.value;
131
+ for (const write of writes)
132
+ state.ram[write.bank][write.address] = write.value;
133
+ state.instruction = next;
134
+ if (next === null)
135
+ status = 'halt';
136
+ else if (tick === limit)
137
+ status = 'budget';
138
+ return record && { ...record, outcome: 'committed', transition: { next, changes, writes } };
139
+ }
140
+ return {
141
+ get status() { return status; },
142
+ get ticks() { return attempted; },
143
+ get error() { return error; },
144
+ get errorCode() { return errorCode; },
145
+ snapshot: () => structuredClone(state),
146
+ step,
147
+ run({ trace = false } = {}) {
148
+ const history = [];
149
+ while (status === 'running') {
150
+ const record = step({ trace });
151
+ if (record)
152
+ history.push(record);
153
+ }
154
+ return history;
155
+ },
156
+ };
157
+ }
@@ -0,0 +1,17 @@
1
+ # Contribute: add an independently checkable fixture
2
+
3
+ Run `npm ci`, `npm test`, and `npm run build:playground` from a clean checkout. The package uses TypeScript and the test suite uses Node's built-in test runner. No app framework or runtime dependency is needed.
4
+
5
+ ## Follow one tick
6
+
7
+ 1. `src/model.ts` defines the portable machine and validates name resolution, operand order, and ranges. `src/builder.ts` only emits that same representation.
8
+ 2. `src/runtime.ts` owns the clock boundary: capture pre-tick sources, evaluate ReLUs, validate all proposed writes and the target conditions, then commit. Trace fields are populated during that evaluation, not by re-evaluating the circuit later.
9
+ 3. `src/compare.ts` finds the first differing field. `src/browser.ts` owns playback and presentation, not ReLU evaluation. `playground/main.mjs` mounts the same browser entry point that an external app imports.
10
+
11
+ ## Add a case worth keeping
12
+
13
+ Start by writing ordinary code for a single reference transition. For example, a guarded write could store `from + edge` in `distance[to]` only when it is strictly smaller than the current distance. Declare how large the distance and address can be. Include an improving case with unequal operands, a tie that must not write, and a non-improving case. Assert the written address and value, not just that the machine halted.
14
+
15
+ Then emit the gate definition, start a `createSession`, and call `compareTick(reference(before), tick)` using a pre-tick snapshot. In the existing relaxation fixture, temporarily change the second write's `value` from `oldPred` to `source`: the intended mismatch assertion in `test/runtime.test.mjs` must fail locally. Revert that temporary mutation before contributing. Add a new playground entry only if it teaches a different debugging question, not just another circuit of the same shape.
16
+
17
+ Before proposing a change, run `npm run lint`, `npm run typecheck`, `npm test`, and `npm run build:playground`. `npm run test:package` installs the tarball into an independent consumer and compiles the Integrate guide's snippets. For browser changes, install the test browsers (`npx playwright install chromium firefox webkit`; on Linux add `--with-deps` if system libraries are missing), then run `npm run test:e2e` (set `PLAYWRIGHT_SITE_PORT` / `PLAYWRIGHT_CONSUMER_PORT` if ports `4173`/`4174` are busy). The suite serves the playground and the packed consumer separately using Python 3 and drives the same controls a user sees. It also compares installed browser and Node traces for all the examples. Keep new assertions on observable transitions rather than on how a tick is implemented.
@@ -0,0 +1,11 @@
1
+ # Explore: change a branch without changing a write
2
+
3
+ Open a hosted ReLU Trace playground. If you are starting from the source checkout, use the [local playground instructions](../README.md#start-here).
4
+
5
+ 1. Select **Pointer chase**. RAM holds `1 → 4`, `4 → 2`, and `2 → 0`. A _register_ holds a named number, such as the current position. A _RAM bank_ is a numbered row of cells. A _tick_ executes one named instruction. Before touching the controls, predict where the first tick goes.
6
+ 2. Press **Step** once. Session state moves from tick 0 to tick 1; **Tick trace** shows `follow → follow`. It reads `pointers[1] = 4` and writes `visits[0]` from `0` to `1`. The trace shows the old `position = 1`; **Session state** shows the new `position = 4`.
7
+ 3. Look at **Activation**, with `hasNext` selected. A ReLU keeps the positive part of its weighted sum. The two terms here are `4 × 1` and `3 × −1`; with bias zero the result is `1`, a yes signal. The circuit uses two earlier gates to turn any positive pointer into one, not four.
8
+ 4. Press **Clamp to zero & replay**. It doesn't edit the weights or starting RAM. It forces only this activation at this tick to output zero. The first difference is `follow → Halt`; `visits[0]` is still written with `1`. The intervention changed control flow, not the logging rule.
9
+ 5. Press **Reset**, then **Run** to completion. The ordinary run halts with the visits `1 · 4 · 2` at the start of its visit bank. Use **History** to inspect tick 1 without modifying the final state.
10
+
11
+ Try **Shortest-path relaxation** next. The distance improves from 12 to 6, so checking only the distance would pass. The reference shows the second write should set `predecessor[1]` to `2`, but the machine writes `0`. Then run **Pointer cycle** and step **Invalid pointer**: a budget stop still has a next instruction; an invalid tick commits nothing.
@@ -0,0 +1,52 @@
1
+ # Integrate: use the same machine in Node and the browser
2
+
3
+ In a Node 22+ ESM project, run `npm install relu-trace`. The code below uses TypeScript; JavaScript consumers can use the same exports without the type-only import and annotations.
4
+
5
+ Save the shared definition as `machine.ts`. The first ReLU increments a counter; the host commits that value and halts because `next` is `null`.
6
+
7
+ ```ts
8
+ import { defineMachine, relu, type Snapshot } from 'relu-trace';
9
+
10
+ export const machine = defineMachine({ count: { min: 0, max: 8 } }, {}, {
11
+ add: {
12
+ inputs: { old: 'count' },
13
+ gates: [relu('incremented', 1, { old: 1 })],
14
+ set: { count: 'incremented' },
15
+ next: null,
16
+ },
17
+ }, 'add');
18
+
19
+ export const initial: Snapshot = { instruction: machine.entry, registers: { count: 2 }, ram: {} };
20
+ ```
21
+
22
+ Put this in `check.ts`. Compile both files with your TypeScript setup (for example `tsc --strict --target es2022 --module nodenext machine.ts check.ts`) and run `node --test check.js`.
23
+
24
+ ```ts
25
+ import { createSession } from 'relu-trace';
26
+ import { machine, initial } from './machine.js';
27
+
28
+ const session = createSession(machine, initial, { limit: 4 });
29
+ const tick = session.step();
30
+ if (tick?.outcome !== 'committed' || tick.transition.changes.count?.value !== 3 || session.status !== 'halt') {
31
+ throw new Error('Expected one committed increment followed by halt');
32
+ }
33
+ ```
34
+
35
+ Put this in a browser module such as `browser.ts`. Add `<div id="debugger"></div>` to your page and load the module after the element exists. Use your app's bundler to resolve the package imports, or use an import map that serves the installed `dist/index.js` and `dist/browser.js` with their relative dependencies, as [the playground](../playground/index.html) does.
36
+
37
+ ```ts
38
+ import { mountInspector } from 'relu-trace/browser';
39
+ import { machine, initial } from './machine.js';
40
+
41
+ const target = document.querySelector<HTMLElement>('#debugger');
42
+ if (!target) throw new Error('Missing debugger element');
43
+ export const unmount = mountInspector(target, { machine, initial, limit: 4 });
44
+ ```
45
+
46
+ The inspector shows `count = 2` before you start and `count = 3` after one step. Call `unmount()` on route or component cleanup (active playback timers also stop automatically if the host element is removed from the DOM). Optional `onTick(trace, snapshot)` and `onStatusChange(status, snapshot)` callbacks let host apps observe execution without touching internal state. For an app that already runs a machine, pass a copy from your session's `snapshot()` at the point you want to investigate; your live app's clocks and memory are not touched. Mount behind a development route when snapshots contain application data. The inspector builds its Shadow DOM without `innerHTML` and applies styles via `adoptedStyleSheets` (with a `<style>` fallback), making it compatible with Trusted Types and strict-CSP hosts. Host pages can theme it by setting `--relu-bg`, `--relu-surface`, `--relu-panel`, `--relu-ink`, `--relu-muted`, `--relu-accent`, `--relu-rule`, `--relu-mono`, `--relu-font`, `--relu-control-font`, `--relu-heading-font`, or `--relu-radius` on the mounted container or any ancestor.
47
+
48
+ ## Bring your own definition
49
+
50
+ You can replace `defineMachine(...)` above with a plain `Machine` object. Keep registers, RAM, and instruction boundaries explicit: map pre-tick inputs to names, topologically order the weighted ReLUs, then bind outputs to register destinations, condition bits, or write ports. Pass the resulting object to both `createSession` and `mountInspector`. See the [v1 contract](machine-v1.md) and [raw relaxation definition](../examples/machines.mjs) for a guarded-write example. Do not round floating-point weights or silently translate unsupported ops.
51
+
52
+ An optional `reference(before)` callback returns the expected next instruction, changed registers, and ordered RAM writes. It runs over a detached pre-tick snapshot and never affects execution. For headless tests, compare the output of the same callback with `compareTick(expected, actual)`. Stop at the first difference; a later comparison on an already-diverged state does not measure the original failure.
@@ -0,0 +1,36 @@
1
+ # Portable machine definition v1
2
+
3
+ `Machine` is a plain, JSON-serializable object. Builder and raw definitions meet at this boundary; the runtime does not run functions embedded in a definition. For parsed JSON, call `parseMachine(JSON.parse(text))` to get a detached, typed definition. Unknown properties, invalid shapes, and invalid bindings throw `ReluTraceError` (`code: 'VALIDATION_ERROR'`) naming the field that failed validation; `-0` values are normalized to `0`. RAM bank sizes are bounded by `MAX_BANK_SIZE` (`1,048,576` cells). Definitions and snapshots are trusted local inputs, not a hardened interchange format for untrusted uploads.
4
+
5
+ ```json
6
+ {
7
+ "version": 1,
8
+ "entry": "add",
9
+ "registers": { "count": { "min": 0, "max": 8 } },
10
+ "banks": {},
11
+ "instructions": {
12
+ "add": {
13
+ "inputs": { "old": "count" },
14
+ "gates": [{ "id": "incremented", "bias": 1, "terms": [{ "from": "old", "weight": 1 }] }],
15
+ "set": { "count": "incremented" },
16
+ "next": null
17
+ }
18
+ }
19
+ }
20
+ ```
21
+
22
+ `entry` is the conventional starting instruction. An explicit snapshot has `instruction` (a defined instruction name, or `null` for already halted), `registers` (all declared names with initial values), and `ram` (all declared banks with dense arrays of exactly `size` cells each). Identifiers match `[A-Za-z_][A-Za-z0-9_-]*`. Signal identifiers are unique within their instruction. The stable identity of an activation is `(instruction, signal)`; its occurrence adds the one-based tick number. Definitions and starting state are copied on session creation; `snapshot()` returns a detached copy.
23
+
24
+ ## One tick
25
+
26
+ 1. Resolve `inputs` as **signal name → register name**, using the old state. Evaluate optional `reads` in array order. A read has `{ id, bank, address }`; `address` names a register input or an earlier read signal. All reads see pre-tick RAM. If you need a read address computed by gates, put the address into a register and read on the next instruction.
27
+ 2. Evaluate `gates` in array order. Each term references an earlier signal (`from`), multiplied by its integer `weight`; terms are added in array order starting with `bias`. The result is `max(0, sum)`. If an intervention matches this tick, instruction, and gate, consumers see zero instead; the trace preserves both computed activation and effective output.
28
+ 3. Resolve `next`: an instruction name, `null` to halt, or `{ test, yes, no }`. `test` names a bit signal; `yes` is selected for `1`. Resolve optional `set` as **register destination → signal name**. Each optional `writes` entry has `{ bank, address, value, when? }`; `address`, `value`, and `when` are signal names. Omitted `when` enables the write; `0` skips it, including dynamic address/value checks. Conditions are exactly `0` or `1`, never JS truthiness.
29
+ 4. Validate every proposed update before committing any. Enabled writes commit in array order; if two target the same address, the later one wins. Each traced write's `before` records the pre-tick cell. Enabled writes of an unchanged value are still recorded. `changes` lists only registers whose values changed. Failed ticks leave all state, including the instruction, untouched.
30
+
31
+ ## Numbers, stopping, and evidence
32
+
33
+ - **Checked integers:** inclusive register and RAM cell bounds; addresses between `0` and `size - 1`. Integers must be exactly representable safe JS integers. Every product and partial sum must also be a safe integer; cancellation after an overflow does not make it valid. There is no rounding/clipping to Float32. Negative gates' pre-activations are allowed; ReLU output is nonnegative. This is dynamic checking of attempted execution, not static proof of all reachable values.
34
+ - **Construction vs execution:** an invalid definition, snapshot, limit or clamp option throws `ReluTraceError` (`code: 'VALIDATION_ERROR'`) on creation. A dynamic arithmetic (`ARITHMETIC_OVERFLOW`), bit (`INVALID_CONDITION`), address (`INVALID_ADDRESS`) or bounds (`OUT_OF_RANGE`) failure sets `status = 'invalid'`; `error` and `errorCode` are available even with tracing off, and invalid trace records include `code`. The failed attempt counts as a tick. `halt` means the machine chose `null` (including on its last allowed tick); `budget` means the last permitted tick committed and left a next instruction. After any terminal outcome, `step` does not advance.
35
+ - **Tracing:** `step()` returns one trace by default (or `undefined` after a terminal outcome). `step({ trace: false })` executes without collecting explanatory records; `run()` returns an empty history by default. `run({ trace: true })` returns the traces of the remaining attempted ticks. The core never keeps a hidden history. `mountInspector` keeps history for its own bounded session (default 128 ticks, configurable up to 1,000); it previews the first 16 cells per bank with an expand toggle for larger banks and shows any traced read/write address. The browser replays synchronously, intended for small machines.
36
+ - **Comparison:** `compareTick` compares committed next instruction, then ordered writes (bank/address/value), then changed register values, with register names sorted (no-op `{ before, value }` entries where `before === value` in `expected.changes` are treated as unchanged). The browser highlights the earliest differing tick. It stops consulting the reference after a difference, because the actual state may now differ from the reference's. A clamp is one counterfactual with the same snapshot, not a proof that a signal is necessary in all contexts.