unit 0.21.0

A self-replicating software nanobot — minimal Forth interpreter that is also a networked mesh agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# unit

**A self-replicating software nanobot** — a minimal Forth interpreter that is also a networked mesh agent.

![unit demo](unit-demo.gif)

**[Try the live demo]https://davidcanhelp.github.io/unit/** | **Install**: `cargo install unit`

[![CI]https://github.com/DavidCanHelp/unit/actions/workflows/ci.yml/badge.svg]https://github.com/DavidCanHelp/unit/actions/workflows/ci.yml

## Install

```
cargo install unit
```

## What Happens

```
$ unit
unit v0.21.0 -- seed online
Mesh node a1b2c3d4e5f67890 gen=0 peers=0 fitness=0
> 2 3 + .
5  ok
> : SQUARE DUP * ;
 ok
> 7 SQUARE .
49  ok
> SPAWN
spawned child pid=12345 id=cafe0123deadbeef
> SEXP" (* 6 7)" .
42  ok
```

## The Idea

A unit is the smallest self-replicating piece of software. It boots from
kernel primitives, builds its own language, networks with peers over UDP
gossip, packages its own binary, and spawns copies of itself. It monitors
services, evolves programs through genetic programming, distributes
computation across a mesh, persists its brain as human-readable JSON,
and connects across machines over the internet.

Forth is the brain. S-expressions are the voice. The mesh is the body.
Zero external dependencies. ~25,000 lines of Rust + Forth.

## The Five Concerns

| Concern | Mechanism |
|---------|-----------|
| **Execute** | Forth VM — stacks, dictionary, inner interpreter |
| **Communicate** | S-expression mesh protocol over UDP gossip |
| **Replicate** | Reads own binary, packages state, spawns child processes |
| **Mutate** | Genetic programming — 50 candidates, tournament selection, 5 mutation operators |
| **Persist** | JSON snapshots — hibernate, resurrect, automatic resurrection on startup |

## S-Expressions

Forth is the execution model. S-expressions are the wire format. Any
future nanobot implementation in any language can parse the mesh messages.

```
> SEXP" (+ 10 32)" .
42  ok
> SEXP" (* 6 7)" .
42  ok
> SEXP-SEND" (event :type ping :data hello)"
sexp sent
```

Mesh messages are self-describing:

```
(peer-status :id "aaa" :peers 2 :fitness 10 :load 190 :capacity 100)
(sub-goal :id 1 :seq 0 :from "aaa" :expr "99 99 *")
(evolve-share :gen 100 :fitness 890 :program "0 1 10 0 DO OVER + SWAP LOOP DROP .")
```

## Genetic Programming

50 programs mutate and compete. The default challenge: find the shortest
program that computes the 10th Fibonacci number (55).

```
> GP-EVOLVE
[gen 0] best: 890 | pop: 50 | "0 1 10 0 DO OVER + SWAP LOOP DROP ." (11 tokens)
[gen 0] WINNER: "0 1 10 0 DO OVER + SWAP LOOP DROP ." (fitness=890, 11 tokens)
```

Tournament selection, crossover, 5 token-level mutation operators (swap,
insert, delete, replace, double). Each candidate evaluated in a sandboxed
VM with step limit. On a mesh, best programs migrate between units every
100 generations.

## Distributed Computation

Break a problem into pieces. Fan sub-goals out to mesh peers as
S-expressions. Collect results. Assemble the answer.

```
> DIST-GOAL{ 99 99 * . | 77 77 * . | 55 55 * . }
9801 5929 3025
(distributed 3 sub-goals, 1 local, 2 remote)
```

Round-robin across local + peers. If a peer doesn't respond within
timeout, fall back to local computation. The distributing unit also
participates — it doesn't just delegate.

## Persistence & Resurrection

A unit saves its entire state as human-readable JSON. It can die and
come back exactly where it left off.

```
> : SQUARE DUP * ;
> : CUBE DUP SQUARE * ;
> 42
> HIBERNATE
hibernating... saved to ~/.unit/snapshots/d1b74e159948b52b.json
```

Later, same port:

```
resurrected from snapshot
> .S
<1> 42  ok
> 7 CUBE .
343  ok
```

The JSON is hand-editable:

```json
{
  "node_id": "d1b74e159948b52b",
  "fitness": 0,
  "stack": [42],
  "words": {
    "SQUARE": ": SQUARE DUP * ;",
    "CUBE": ": CUBE DUP SQUARE * ;"
  }
}
```

## Cross-Machine Mesh

Two machines, same mesh:

```sh
# Machine A
UNIT_PORT=4201 unit

# Machine B (discovers A, gossip finds the rest)
UNIT_PORT=4201 UNIT_PEERS=<A-ip>:4201 unit
```

DNS hostnames work: `UNIT_PEERS=myhost.example.com:4201`

NAT traversal: `UNIT_EXTERNAL_ADDR=203.0.113.5:4201`

Authentication: `UNIT_MESH_KEY=mysecret` on all machines.

Manual connect from the REPL:

```
> CONNECT" 192.168.1.10:4201"
connected to 192.168.1.10:4201
> PEER-TABLE
--- peer table ---
  cafe0123deadbeef @ 192.168.1.10:4201 fitness=45 seen=1s ago
```

Gossip self-assembles: A tells B about C, the mesh grows.

## Swarm Mode

```
> SWARM-ON
swarm mode active
```

One command enables: auto-discovery, word sharing, autonomous
spawn/cull, fitness-driven evolution. Define a word on one unit,
it appears on the other:

```
# Unit A:
> : CUBE DUP DUP * * ;
> SHARE" CUBE"

# Unit B:
> 3 CUBE .
27
```

## Goals

Humans set direction, the mesh navigates.

```
> 5 GOAL{ 6 7 * }
goal #101 created [exec]: 6 7 *
[auto] stack: 42

> DASHBOARD
--- dashboard ---
watches: 0  alerts: 0  peers: 1  fitness: 30
```

## Self-Replication

A unit reads its own executable, serializes its state, and births a new
process. The child boots with the parent's dictionary, goals, fitness,
and mutations — then gets its own identity and joins the mesh.

```
> SPAWN
spawned child pid=12345 id=cafe0123deadbeef
> FAMILY
id: a1b2c3d4e5f67890 gen: 0 parent: none children: 1
```

Trust levels control who can replicate to you:

| Level | Behavior |
|-------|----------|
| `TRUST-ALL` | Auto-accept everything (default) |
| `TRUST-MESH` | Auto-accept known peers |
| `TRUST-FAMILY` | Auto-accept parent/children only |
| `TRUST-NONE` | Manual approval for all |

## Monitoring & Ops

```
> 10 WATCH" http://myapp:8080/health"
watch #1 created (every 10s)

> 1 ON-ALERT" ." service down!" CR"
alert handler set for watch #1

> HEAL
--- heal cycle ---
  running handler for alert #2
  service down!
--- heal done ---
```

## Architecture

```
src/
├── vm/               # Forth virtual machine
│   ├── mod.rs        # VM struct, interpreter, dispatch (~200 primitives)
│   ├── primitives.rs # stack, arithmetic, memory, I/O
│   ├── compiler.rs   # definitions, control flow, prelude loader
│   └── tests.rs      # 132 tests
├── types.rs          # Cell (i64), Entry, Instruction enum
├── mesh.rs           # UDP gossip, peer discovery, word sharing, cross-machine
├── sexp.rs           # S-expression parser, serializer, Forth translator
├── evolve.rs         # Genetic programming engine
├── distgoal.rs       # Distributed goal splitting and collection
├── goals.rs          # Goal registry, task decomposition
├── snapshot.rs       # JSON snapshots, persistence, resurrection
├── spawn.rs          # Self-replication, UREP package format
├── persist.rs        # Binary state serialization
├── platform.rs       # Platform detection (native vs WASM)
├── wasm_entry.rs     # WASM C FFI bindings
├── prelude.fs        # Forth prelude (~500 lines)
├── features/
│   ├── io_words.rs   # file, HTTP, shell, env
│   ├── mutation.rs   # self-mutation engine, smart mutation
│   ├── fitness.rs    # fitness tracking, leaderboard
│   ├── monitor.rs    # watches, alerts, dashboard, scheduler
│   └── ws_bridge.rs  # WebSocket bridge (raw RFC 6455)
└── main.rs           # feature wiring, REPL, CLI, entry point
```

132 tests. Zero dependencies. ~25,000 lines of Rust + Forth.

## All the Words

309 words. Organized by category:

### Stack

| Word | Effect | | Word | Effect |
|------|--------|-|------|--------|
| `DUP` | `( a -- a a )` | | `2DUP` | `( a b -- a b a b )` |
| `DROP` | `( a -- )` | | `2DROP` | `( a b -- )` |
| `SWAP` | `( a b -- b a )` | | `NIP` | `( a b -- b )` |
| `OVER` | `( a b -- a b a )` | | `TUCK` | `( a b -- b a b )` |
| `ROT` | `( a b c -- b c a )` | | `.S` | print stack |

### Arithmetic & Logic

| Word | Effect | | Word | Effect |
|------|--------|-|------|--------|
| `+` `-` `*` `/` `MOD` | arithmetic | | `=` `<` `>` | comparison |
| `AND` `OR` `NOT` | bitwise logic | | `ABS` `NEGATE` `MIN` `MAX` | math |
| `1+` `1-` `2*` `2/` | shortcuts | | `0=` `0<` `<>` `TRUE` `FALSE` | predicates |

### Memory

| Word | Description |
|------|-------------|
| `@` `!` | fetch / store |
| `HERE` `,` `C,` `ALLOT` `CELLS` | data space allocation |
| `VARIABLE` `CONSTANT` `CREATE` | data words |

### I/O

| Word | Description |
|------|-------------|
| `.` `.S` `EMIT` `CR` `SPACE` `SPACES` `TYPE` | output |
| `KEY` `."` | input / string literal |
| `FILE-READ"` `FILE-WRITE"` `FILE-EXISTS"` `FILE-LIST"` `FILE-DELETE"` | filesystem |
| `HTTP-GET"` `HTTP-POST"` | raw HTTP/1.1 |
| `SHELL"` `ENV"` `TIMESTAMP` `SLEEP` | system |
| `IO-LOG` `SANDBOX-ON` `SANDBOX-OFF` `SHELL-ENABLE` | security |

### Control Flow

| Word | Description |
|------|-------------|
| `IF` `ELSE` `THEN` | conditional |
| `DO` `LOOP` `I` `J` | counted loop |
| `BEGIN` `UNTIL` `WHILE` `REPEAT` | indefinite loop |
| `:` `;` `RECURSE` | word definitions |
| `WORDS` `SEE` `EVAL"` | introspection |

### S-Expressions

| Word | Description |
|------|-------------|
| `SEXP"` | parse S-expression, translate to Forth, execute |
| `SEXP-SEND"` | broadcast S-expression to mesh peers |
| `SEXP-RECV` | drain inbound S-expression messages |

### Mesh & Gossip

| Word | Description |
|------|-------------|
| `PEERS` `MESH-STATUS` `ID` `MY-ADDR` | mesh info |
| `PEER-TABLE` `MESH-STATS` `MESH-KEY` | cross-machine |
| `CONNECT"` `DISCONNECT"` | manual peer management |
| `SEND` `RECV` | raw messaging |
| `DISCOVER` `AUTO-DISCOVER` | LAN discovery |
| `SHARE"` `SHARE-ALL` `AUTO-SHARE` `SHARED-WORDS` | word sharing |
| `SWARM-ON` `SWARM-OFF` `SWARM-STATUS` | swarm mode |

### Distributed Computation

| Word | Description |
|------|-------------|
| `DIST-GOAL{` | distribute pipe-separated expressions across peers |
| `DIST-STATUS` | show active distributed goals |
| `DIST-CANCEL` | cancel all distributed goals |

### Genetic Programming

| Word | Description |
|------|-------------|
| `GP-EVOLVE` | run 10 generations (call repeatedly to continue) |
| `GP-STATUS` `GP-BEST` | inspect evolution state |
| `GP-STOP` `GP-RESET` | control evolution |

### Goals & Tasks

| Word | Description |
|------|-------------|
| `GOAL"` | `( priority -- id )` description-only goal |
| `GOAL{` `}` | `( priority -- id )` executable Forth goal |
| `GOALS` `TASKS` `REPORT` `CLAIM` `COMPLETE` | lifecycle |
| `SUBTASK{` `FORK` `RESULTS` `REDUCE"` `PROGRESS` | decomposition |
| `AUTO-CLAIM` `TIMEOUT` | execution control |

### Monitoring

| Word | Description |
|------|-------------|
| `WATCH"` `WATCH-FILE"` `WATCH-PROC"` | create watches |
| `WATCHES` `UNWATCH` `WATCH-LOG` `UPTIME` | manage watches |
| `ON-ALERT"` `ALERTS` `ACK` `ALERT-HISTORY` `HEAL` | alerting |
| `DASHBOARD` `HEALTH` `OPS` | overview |
| `EVERY` `SCHEDULE` `UNSCHED` | scheduling |

### Fitness & Mutation

| Word | Description |
|------|-------------|
| `FITNESS` `LEADERBOARD` `RATE` | scoring |
| `MUTATE` `MUTATE-WORD"` `UNDO-MUTATE` `MUTATIONS` | mutation |
| `SMART-MUTATE` `MUTATION-REPORT` `MUTATION-STATS` | smart mutation |
| `EVOLVE` `AUTO-EVOLVE` `BENCHMARK"` | fitness-driven evolution |

### Spawn & Replication

| Word | Description |
|------|-------------|
| `SPAWN` `SPAWN-N` | local replication |
| `PACKAGE` `PACKAGE-SIZE` | build UREP package |
| `REPLICATE-TO"` | remote replication |
| `CHILDREN` `FAMILY` `GENERATION` `KILL-CHILD` | lineage |
| `ACCEPT-REPLICATE` `DENY-REPLICATE` `QUARANTINE` `MAX-CHILDREN` | safety |

### Trust & Consent

| Word | Description |
|------|-------------|
| `TRUST-ALL` `TRUST-MESH` `TRUST-FAMILY` `TRUST-NONE` | trust levels |
| `TRUST-LEVEL` `REQUESTS` `ACCEPT` `DENY` `DENY-ALL` | consent flow |
| `REPLICATION-LOG` | audit trail |

### Persistence

| Word | Description |
|------|-------------|
| `JSON-SNAPSHOT` `JSON-RESTORE` | save/load JSON snapshots |
| `HIBERNATE` | snapshot and exit |
| `AUTO-SNAPSHOT` | periodic auto-save |
| `SNAPSHOT-PATH` `JSON-SNAPSHOTS` | inspect storage |
| `EXPORT-GENOME` `IMPORT-GENOME"` | genome transfer |
| `SAVE` `LOAD-STATE` `RESET` | binary state management |
| `SNAPSHOT` `SNAPSHOTS` `RESTORE` | binary versioned backups |
| `AUTO-SAVE` | binary auto-save |

## Binary Sizes

| Target | Size |
|--------|------|
| Native (macOS arm64, release) | ~1.2 MB |
| WASM (browser) | ~338 KB |

## License

MIT — see [LICENSE](LICENSE).