# Continuation prompt — REBOL/View 2 clone (reverse-engineered with REA)

Paste the block below into a fresh pi session on this VPS.

---

## CONTEXT / GOAL

We are building a **fully functional clone of the REBOL/View 2.7.8.3.1 Windows
executable** (`rebol-view-278-3-1.exe`). REBOL 2 was never open-sourced, so the
clone is produced by reverse-engineering the shipped binary with **REA**
(<https://github.com/morluto/rea>). The goal is full feature parity: a working
replacement for the original `rebol-view.exe`.

The previous session is exported at:
<https://pi.xqx1.com/api/sessions/01a1a787-1f89-7401-a842-5052982b4fca/export?inline=1>

Work in **`/root/rebol-view-clone/`**. Be economical with context; prefer small
targeted edits, rebuild after every change, and verify under Wine.

## WHAT EXISTS ALREADY (do not redo)

```
/root/rebol-view-clone/
  reference-rebol-view-278-3-1.exe   the original target (sha256 215e28f9…)
  rea-inspect-*.json, rea-objdump.json  REA Evidence (PE identity/imports/resources)
  r2-extracted/                      21 recovered source modules (see below)
  r2clone/                           the C interpreter clone (source)
  dist-r2/                           the shipped package (exe + source + docs + zip)
  tools/extract_boot.py              reproducible boot-image extractor
  README.md, REVERSE-ENGINEERING.md  docs
  evidence/                          REA evidence bundle
```

### The key discovery
REBOL 2 embeds its **entire application source** in the exe as 21 zlib streams.
`tools/extract_boot.py` inflates them to `r2-extracted/`:
- `00-boot-core.r` — core boot image: 184 native/action specs + 83 mezzanines
- `10-REBOL_Mezzanine_Extensions.r`, `12-REBOL_Internet_Protocols.r`,
  `19-View_and_VID.r`, `20-View_Desktop.r`, plus crypto/codec modules.
Extraction is byte-for-byte reproducible (`diff -rq` verified).

### The clone (`r2clone/`)
Pure C, no external deps. Files: `reb.h`, `value.c`, `scan.c` (lexer/parser),
`eval.c` (evaluator), `native.c` (natives), `net.c` (HTTP/HTTPS via WinHTTP on
Windows, POSIX sockets elsewhere), `view_win.c` (Win32 View), `boot_image.c`
(embedded recovered boot image, generated), `modules.c` (embedded recovered
modules, generated), `main.c`.

The clone **embeds and loads at startup**: boot image sections 1-4, then the
Mezzanine Extensions, Internet Protocols, and View/VID modules.

### Interpreter features already implemented (verified)
- REBOL values/datatypes incl. bitset, object, function, native, error
- **Lexical binding**: words carry `word_ctx`; function bodies bound once at
  creation (`Bind_Block` binds only args/locals; `Bind_Block_All` for object
  specs); per-call save/restore of the function context → recursion works
- **Closures**: `make function! spec body [closure]` and `do` of a function
- **Series positions**: every string/block/binary carries `index`; `head tail
  next back skip at index? head? tail?`; all series ops honour position
- **Set-paths** (`system/view:` etc.) and set-words (immediate-context set)
- **Native refinements**: `find` (/part /case /any wildcards /match /tail /last),
  `copy` (/part /deep), `insert`/`change` (/part /only /dup), `remove` (/part),
  `sort` (/skip /reverse /part), `trim` (/head /tail /lines /all /with),
  `uppercase`/`lowercase` (/part)
- `parse` with `some any opt | copy set to thru not and end`, bitsets/charsets,
  paren actions; standard charsets `alpha digit space hex`
- ~220 natives incl. `collect`/`keep`, `array`, `foreach` (multi-word),
  `words-of`/`values-of`/`body-of`/`spec-of`, `in`, `set`, `case`, `switch`,
  `catch`/`throw`, `break`/`return`/`exit`
- `system/words`, `system/script`, `system/options`, `system/standard`,
  `system/view` (real face model), `face`/`feel` prototypes
- View: module's `view` function drives my Win32 renderer via `show`/`layout`

### Bugs already found & fixed (don't reintroduce)
1. `#"x"` char literals didn't consume the closing quote (scanner)
2. String series weren't null-terminated → `strdup`/`fopen` over-read (segfault)
3. `word_ctx` shared union memory with `name`
4. `/local` spec words were discarded
5. Tuple parsing didn't advance the pointer past `0.0.0`
6. `RegOp` held a context pointer across a realloc
7. Set-paths (`a/b:`) parsed as plain paths (assignments did nothing)
8. `make object!` evaluated specs with `Eval_Value` (no calls) and in the wrong
   context; must use `Eval_Expression` in the new object's context
9. Consecutive set-words in object specs resolved up the parent chain and
   **overwrote globals** (e.g. global `func` became `none`)
10. `foreach` didn't support a block of words
11. `in` was a no-op

## BUILD / TEST / PUBLISH

```bash
# native Linux build (test)
cd /root/rebol-view-clone/r2clone && make clean && make

# Windows cross-build (mingw-w64 already installed)
cd /root/rebol-view-clone/r2clone
for f in value scan eval native view_win net boot_image modules main image draw hash zlib ffi; do
  i686-w64-mingw32-gcc -O2 -std=gnu99 -c $f.c -o /tmp/rel-$f.o
done
for f in deflate trees adler32 crc32 zutil; do
  i686-w64-mingw32-gcc -O2 -std=gnu99 -DZ_SOLO -DNO_GZIP -Ivendor/zlib \
    -c vendor/zlib/$f.c -o /tmp/rel-z-$f.o
done
i686-w64-mingw32-gcc -O2 -s -o /tmp/rebol-view.exe \
  /tmp/rel-*.o -lm -luser32 -lgdi32 -lwinhttp -lws2_32 -lmsimg32 -lcomdlg32 -lshell32

# run under Wine (Xvfb for the GUI)
export WINEPREFIX=/root/.wine32 WINEARCH=win32 WINEDEBUG=-all
timeout 40 xvfb-run -a /usr/lib/wine/wine /tmp/rebol-view.exe Z:/tmp/script.r

# publish (read-only static service rooted at /root/download)
cp /tmp/rebol-view.exe /root/rebol-view-clone/dist-r2/rebol-view.exe
cd /root/rebol-view-clone/dist-r2 && zip -qr rebol-view-2-clone.zip .
cp rebol-view-2-clone.zip /root/download/
cp rebol-view.exe /root/download/
cd /root/download && sha256sum rebol-view-2-clone.zip rebol-view.exe | tee rebol-view-2-clone.sha256
# URLs: https://download.xqx1.com/rebol-view-2-clone.zip  and  .../rebol-view.exe
```

Notes:
- **Always `make clean` before rebuild** — the Makefile has no header deps, so
  stale objects hide edits.
- Test scripts live in `/tmp/r2test/` (audit.r, cover.r, etc.).
- If generated headers change, the `.o` files that include them must be rebuilt
  (clean build handles it).
- Use AddressSanitizer (`gcc -g -O1 -fsanitize=address`) plus `gdb` to chase
  crashes; both are installed.

## CURRENT STATE (last published)

### demo34 (2026-11-29) — differential sweep driven to one line

The corpus differential harness now differs in **one line** of the whole
document (28146 compared lines, down from ~24.8k at the start of the session):
a text face's private layout cache (`state: 1052x821` vs `state: 1x1`) in a
moulded `layout` face.  Everything else is byte-identical.  The work was
driven by `tools/examples_sections.py --diff` plus a new differential probe
helper `tools/probe.py` (`--each` runs each chunk in both engines and prints
the diff).

**Language semantics fixed** (goldens 94-103):

* `parse` **split mode** with `none`/string rules — including R2's exact
  whitespace class (`<= 0x20` except NUL, `0x7F`, `0xA0`), the "run of k
  delimiters gives k-1 empty fields / whitespace is absorbed / leading field
  emitted / trailing dropped" model, `/all` dropping the whitespace
  delimiters, binary input, and `expect-arg` for a char rule.
* `load` of a **binary** returns it unchanged unless it is an image or WAV.
* The **MOLD break flag moved into `Value`** (it used to be per series
  position) — `reduce`/`compose`/`to-*` carry the produced values' flags,
  `poke` keeps the new value's, and the VID style sheet moulds identically.
  This alone removed ~23k differing lines.
* `form` of an object (`name: mold value` lines, no wrapper).
* Word equality (`=`/`same?` lenient across the word types) vs strict
  `find`/`select` matching, and `type?/word` returning a word.
* `at` relative/1-based, negative `copy/part` copying backwards, `trim` in
  place, `set` with a block (padding with none), `min`/`max` decimal
  promotion, `sort/compare` comparator direction, block/case-insensitive
  comparisons, binary `find`, `foreach` over file/binary series, path
  components as pairs/decimals, `length?`/`last`/`second` on paths.
* Argument type checks for the movement/series natives and
  read/write/exists?/delete/size?/dir?/rename, `disarm` of a non-error, and
  the full set of ACCESS errors (`cannot-open` with the absolute path,
  `no-delete`/`no-rename` with the file as arg1, `no-make-dir`,
  `invalid-spec` for unknown schemes or unusable block specs).
* `set-modes`/`get-modes` restricted to R2's port modes (file permission
  modes raise `invalid-arg` with the offending set-word).
* PNG alpha → transparency mapping (`n=0 -> 255`, `1..127 -> 256-n`,
  `128..255 -> 255-n`) — the stock button images carry alpha 50.
* A measured **bold Arial** advance table plus per-size inter-character gaps
  (single characters exact, long bold strings may be a pixel off).
* `Scan_Number` filled an uninitialised `Value`, which made the PE build emit
  spurious MOLD line breaks (the new per-value flag exposed it) — now zeroed
  before use.

Harness changes: the diff normalises the reference's `/Z/tmp/sec-*/` paths,
and five snippet groups are skipped with documented reasons
(`examples-corpus/REPORT.md`): interactive/incomplete examples, a Windows
drive path (`%/c/...`), R2's internal `system/words` layout, and `source` of a
built-in loop.

103/103 goldens on Linux and Wine, corpus 20 sections / **9 errors, all of
them the reference's own errors**, examples/net/ports smokes and GUI shots
pass.  Marker `demo34-2026-11-29`.

### demo33 (2026-11-28) — corpus differential harness and four fixes

`tools/examples_sections.py --diff [--section NAME]` now replays a section in
the **reference** and in the clone and diffs the printed output (result file
rewritten after every snippet, relative result path for the reference, a
deterministic type-preserving `random` stub, `now` without `to-date` of an
integer, and `ERROR (expected)` for snippets that are supposed to raise).  Its
first sweep fixed:

* **`change` on strings**: the default range is the length of the new text
  (`change copy "Tom" "Phil"` -> "Phil", `change copy "abcdef" [1 2 3]` ->
  "123def"), not one character (golden 93).
* **Paths with paren components**: `b/(i)`, `o/(w)`, `m/(j)/(1)` and the
  set-path forms (`b/(i): value`) now scan, evaluate and mold like R2
  (golden 91).
* **Directory listings** returned by `read %dir/` are sorted
  case-insensitively.
* **Argument type checking**: a spec's `[types...]` block is enforced at call
  time for positional and refinement arguments ("f1 expected a argument of
  type: integer"), `none` is rejected unless allowed, and a missing argument
  errors.  Datatype words in a spec are normalised to datatype values (so
  HELP prints `(Type: integer)`), and R2's typeset names (`series!`,
  `number!`, `any-string!`, ...) are matched by name (golden 92).

93/93 goldens on Linux and Wine, corpus 20 sections / 0 errors, all smokes and
GUI shots pass.  Marker `demo33-2026-11-28`.

### demo32 (2026-11-28) — image placement parity

R2 blits a face's image at the **top-left at its natural size and clips it**;
it never centres and only scales when the effect contains `fit`/`aspect`
(nearest-neighbour).  Probed with `to-image` on faces whose size differs from
the image (smaller image -> top-left + face colour around it, oversized image
-> clipped, `fit` -> scaled).  The clone centred images that fit,
centre-clipped larger ones, and `to-image` stretched everything to the face
size; `view_win.c` and `draw.c`'s `Snap_Face` now both blit top-left at
natural size.  Golden `90-image-placement` pins four cases; the
`image-effects` GUI baseline was renewed (its `rotate 90` tile is now clipped
like R2).

`extend` (the stock button image is 7x14 and BTN stretches it with
`extend 14`) is still unimplemented — an integer argument pins the last
column/row at the far edge and fills the gap with the column before it, but
the pair forms and narrow images behave differently, so it is documented
rather than guessed.  Buttons keep the clone's flat look.

### demo31 (2026-11-28) — effect words, exact GRADIENT

`EFFECT [gradient 1x0 blue gold]` uses the *values* of `blue`/`gold`; the
clone read the raw words, so `Tuple_Color` failed and such a face painted
nothing (the widgets GUI test was missing its gradient box).  Effect
arguments are now resolved through the word's binding in the window renderer
and in `to-image`.

GRADIENT's ramp was pinned against the oracle: each component moves from
colour 1 toward colour 2 with `c1 + trunc((c2-c1)*i/n)`, `i` in `0..n-1`, `n`
the width (`1x0`) or height (`0x1`), negative components reversing the order
and a diagonal pair projecting on the vector.  The clone used an `(n-1)` lerp
scaled through 255 (one or two steps off) and ignored the direction (always
vertical).  `draw.c`'s `Img_Gradient` is now shared by `to-image` and the
draw-dialect `gradient` command, and `view_win.c` uses the same maths on
screen.  Golden `89-gradient-effect` pins seven ramps; the widgets GUI
baseline was renewed.

Still open: R2's stock-image button/field look (`extend`/`fit` placement
parity), `tint`/`hsv`, requestor keyboard/find polish, and port depth.

### demo30 (2026-11-28) — evaluator set-paths, function copies, list scrollbars

Three R2 evaluation rules that the desktop's own REBOL code relies on were
missing, and together they blocked the VID scroller (so TEXT-LIST showed a
scrollbar without its up/down arrow buttons):

* `obj/func/ref: value` **calls** `func` with the refinements after it and
  `value` as the argument (`sld/resize/y: size/y`); `obj/func: value` stays a
  plain assignment.  The clone treated both as field writes.
* `obj/series/n/field: value` indexes a block/paren first and then sets the
  field (`pane/2/size: 16x90`).
* `make function!` **copies** its spec and body (verified against the oracle:
  appending to the source body does not change the moulded function),
  recursively for nested blocks and paths, keeping MOLD's break flags.  A
  function therefore survives the later in-place binding of a shared
  module/style block; without this, a style's `with [...]` function kept a
  prototype binding for `axis` and `make-face 'slider` raised `invalid-path`.
  `make <object-prototype>` also rebinds the block fields it copies, so
  `do inst/blk` acts on the instance (R2 parity).

With those in place the scroller's `resize` runs, calls
`do pane/2/init`/`do pane/3/init`, the ARROW style builds
`effect: [fit arrow <colour> 0.7 rotate 0|180]`, and the up/down buttons are
drawn next to the dragger; row selection (`svvc/field-select`) shows between
them.  `tests/gui-baseline/text-list.png` was renewed.

Golden `88-eval-path-forms` pins the evaluator forms (one/two refinements,
plain assignment, `obj/func/ref value`, series-index and block-key
set-paths, function body copy, inherited function layout).  88/88 on Linux
and Wine, corpus 0 errors, all smokes and GUI shots pass.

### demo29 (2026-11-27) — MOLD flag model, loop binding, CONTRAST

The last formatted-MOLD gap (VID style objects moulding inherited functions
without line breaks) was a modelling error, not a style bug: R2 stores the
break as a flag on the **value** (plus a tail flag for the position before
`]`).  MOLD now emits a break before every flagged value — including the
first value of a block and of a sub-series (`next`/`find`/`at`) — and closes
on its own line when a break was emitted at that level or the tail flag is
set.  `copy`/`reduce`/`compose` keep the per-value flags but not the tail
flag; `insert`/`append` carry the source's flags; `poke` clears the replaced
value's flag; the scanner reproduces R2's shared-integer quirk (`load
"[^/1 2]"` loses the break, `[^/2 2]` keeps it).  The internal deep copies
behind `make object!`/`make function!` keep the markers, so `mold select
system/view/vid/vid-styles 'scroller` is byte-identical (golden 85 pins the
627-line object).  `compose` gained `/deep` and `/only` and now splices block
results like R2.

Loop variables (`repeat`, `foreach`, `for`, `forall`, `forskip`,
`remove-each`, `use`) are now local to the loop yet visible inside nested
blocks — `repeat i 3 [append s rejoin [i " "]]` works inside a function,
while a same-named global keeps its value (golden 86).

`contrast n` was reverse-engineered (previously unimplemented): each channel
is stretched around that channel's own image mean,
`mean + trunc((v-mean)*num/den)` with `num/den = (18+n)/18` for `n>=0` and
`18/(25+|n|)` for `n<0`, `n` clamped to ±128 (golden 87).  `tint` (integer)
and `hsv` (tuple) remain unimplemented but are documented in
`evidence/PORT-MODEL-EVIDENCE.md` §9.4 (`tint 0` alone shifts pixels by ±1 —
a lossy colour-space round trip; `hsv 0.255.255` maps red to cyan and grey to
white).  `to-image` now paints an edge only when it is bevelled or has an
edge image (R2 leaves the base face's plain 2x2 colour edge unpainted).

87/87 goldens on Linux and Wine, corpus 20 sections / 0 errors, all smoke
tests and GUI shots pass.  Marker `demo29-2026-11-27`.

### demo28 (2026-11-14) — nested MOLD line breaks refined

The formatted-MOLD work was refined against the oracle: a nested block keeps
a **leading** break (the element right after `[` starts on a new line) only
when the block does not start the line — `[if true [^/x: 1]]` indents `x: 1`,
`[[^/1 2]]` (a load result) does not.  Indentation now comes from an explicit
block depth (element breaks at 4*(depth+1), closing bracket at 4*depth), and
`mold` of module/style functions such as `svvf/scroll` now matches the
reference.  Case 84 gained the nested leading-break lines.  Remaining
cosmetic limit: one `stylize`-built style object still molds without breaks.

### demo27 (2026-11-14) — formatted MOLD (line breaks preserved)

R2 stores line breaks as block element markers and MOLD reproduces the
source layout: a break becomes " \n" plus four spaces per nesting level and
a multi-line block closes on its own line; `load` results always close on a
new line.  Implemented as a per-element `nl` array in `Series` (maintained by
the loader, `Series_Insert/Remove/Append`, and MOLD), with markers carried
through `copy`/`copy/deep`/`reduce`/`compose` and function creation.  Path
word marks are also preserved when molding (`o/:w`, `a/b:`).  Golden 84 pins
the behaviour; 84/84 on Linux and Wine, corpus still 0 errors.  Known
cosmetic limits (documented): some `stylize`-built style functions and one
nested `func`-shaped loaded block still mold without their breaks.

### demo26 (2026-11-14) — absolute script path (WHAT-DIR)

`system/script/path` is now the **absolute** directory of the running script
in R2's `file!` form (`%/Z/dir/` under Windows), instead of `"./"`; the file
layer maps that form back to `Z:/dir/` for `fopen`.  `what-dir` therefore
returns what the reference returns, and paths built as
`rejoin [what-dir %x]` are absolute.  File ports keep R2's `target` form
(the name as given, e.g. `%pf.txt`).  Golden 83 pins the behaviour (83/83
Linux/Wine).  Lesson recorded in tests/README: golden cases must not
`change-dir`, because the harness writes its result file relative to the
script path.

### demo25 (2026-11-14) — reference text metrics

`size-text` now uses the reference's *own* Arial metrics: advance widths for
every printable ASCII character at every point size 8..48 plus the line
heights were measured from the original executable (SIZE-TEXT with wrapping
disabled) and embedded as a table in `native.c`.  The clone therefore agrees
with R2 exactly for single characters, short strings, multi-line text and
line heights on both Linux and Wine (`82-text-metrics`).  Long strings may
still differ by a pixel or two because R2's inter-character spacing (≈2 px
per gap, 3 at some sizes) is not derivable from single-character probes —
documented in `tests/README.md`.

### demo24 (2026-11-14) — GUI screenshot regression harness

`tools/gui_shots.py` renders the static VID layouts in `tests/gui/*.r` with
the Windows PE under Wine/Xvfb, finds the clone's window with `xwininfo`,
crops it with `ffmpeg` and diffs it against `tests/gui-baseline/*.png` using
Pillow (a shot passes when no more than 2% of pixels differ by more than
12/255 per channel, so Wine font antialiasing is tolerated).  Three
baselines ship: `widgets` (buttons/field/check/boxes), `image-effects`
(plain/flip/rotate/invert/grayscale/key/crop faces) and `text-list` (rows +
scroller).  `--update` rewrites the baselines after intentional rendering
changes.  This gives the editor/requestor polish work a visual oracle.

### demo23 (2026-11-14) — port specs in READ/WRITE, FORM of words

`read`/`write` now accept R2's documented port-spec targets (block or object
with `scheme`/`host`/`port-id`/`user`/`pass`/`target`/`path`): a file spec
reads/writes the file (before, a block target resolved to the script
directory and returned a directory listing), network specs are turned into
the corresponding URL (HTTP/FTP verified against local servers, including an
FTP write), and `tcp`/`udp`/`console` specs go through the port layer.  While
implementing this, a FORM fidelity bug surfaced and was fixed: R2's `form`
of a set-word/get-word/lit-word/refinement is the bare name
(`form [a: :b 'c /d]` → `"a b c d"`), while `mold` keeps the marks.  Golden
81 pins the spec behaviour; `tools/net_smoke.py` gained HTTP/FTP spec checks
(81/81 Linux/Wine).  Probed and documented as *no-ops in R2 itself*:
`hline`/`vline`/`shape`/`fill-rule`/`matrix` in draw, and `set-modes`/
`get-modes` on files and file ports (which raise).

### demo22 (2026-11-14) — pixel filters (blur/sharpen/luma/multiply)

Added the remaining pixel-transforming image effects to the shared filter:
`blur` and `sharpen` (3x3 convolutions with the R2/AGG kernels
`{0,1,0,1,1,1,0,1,0}/5` and `{0,-1,0,-1,8,-1,0,-1,0}/4`, truncated results,
edge clamping), `luma n` (add n per channel) and `multiply color`
(v·c/128).  Kernels were confirmed against the oracle's delta response.
Also matched the reference's quirk where a 180° rotation of an odd-sized
image leaves the centre pixel transparent.  New golden 80 pins all of it
with `checksum to-binary` fingerprints (80/80 Linux/Wine).  Found and
documented two reference quirks: chaining two convolutions in one effect
block diverges (its second pass reads a different buffer), and `contrast`/
`tint`/`hsv` work in a chroma space that is not yet reverse-engineered.

### demo21 (2026-11-14) — image text form, TO-BINARY and effect filters

Images now mold like the reference: `make image! [WxH #{rgb} #{alpha}]` with
one line per 10 pixels and the alpha block only when some pixel is not
opaque (R2 wraps binary hex at 32 bytes per line once it reaches 32 bytes).
`to-binary image` returns the raw `B,G,R,A` bytes.  Face image effects are a
portable filter (draw.c) shared by the window renderer and `to-image`:
`flip` (default/`1x0`, `0x1`, `1x1`), `rotate 90|180|270`, `invert`,
`grayscale` (0.3/0.59/0.11, truncated), `key`, `colorize` and `crop`; the
filters compose left to right.  Goldens 78–79 pin them (79/79 Linux/Wine).
`contrast`, `brightness`, `tint`, `hsv`, `scale`, `extend`, `merge`, `grid`
and `tile-view` were probed; several are no-ops in the reference and the
rest are documented gaps.

### demo20 (2026-11-14) — port event model + wire-level cross-tests

`port/awake` now behaves like the reference: the handler receives the port
itself (R2 has no event object), it is called once per `wait` that includes
the port and *before* `wait` returns, `wait/all` dispatches every ready port
and returns a block, timeouts return `none` without firing the handler, EOF
arrives as a read event (`copy` → `none`), and `wait <time>` / `wait []` do
not process port events.  Implemented with a `select()`-based multi-port
waiter (`Port_Wait_Any`) and `Port_Dispatch` in `r2clone/port.c`; golden
cases 76–77 cover it (77/77 Linux and Wine).

`tools/ports_smoke.py` adds the missing two-party coverage: a server script
and a client script run as separate processes over loopback (TCP, UDP and an
async/awake server), on Linux and under Wine, with `--mix` cross-testing the
clone against the original binary in both directions.  All modes pass.

### demo19 (2026-11-14) — generic port system

`r2clone/port.c` implements the reference's port model: `open` of `tcp://`,
`udp://`, `file://` and `console://` (URL/file/block/object specs and all
R2 refinements), the full 45-field `port!` object with R2's `mold`
(`make port! [...]`) and `form` output, the `state` object
(flags/misc/num/with/func/inBuffer/outBuffer) and per-port numbering, plus
`insert`/`write`, `copy`/`read` (`/part`, `/binary`, `/lines`,
`/direct`, `/seek`), `first` (accept), `wait`/`wait/all` with timeouts,
`close`, `read-io`/`write-io`, `length?`, `get-modes`/`set-modes` and
`port/timeout`.  UDP supports bound, remote and broadcast sockets.  The
reference's flushing quirk (TCP data is sent when the writing port closes or
the event loop runs) and file-port buffer behaviour were matched
deliberately; `read port` returning data is a documented improvement over
R2's error.  New golden cases 70–75 and `examples/ports.r` (identical
output on the reference) cover it; the suites are now **75/75 Linux and
75/75 Wine**, the corpus is still 20 sections / 0 errors on both, and all
example/network smokes pass.

- **Golden-output conformance suite: 75/75 passing on the native Linux
  build and 75/75 on the Windows PE build under Wine.**  See `tests/README.md`.
- **DLL FFI** (`load/library`, `make routine!`, `make struct!`, `free`) is
  implemented in `clone-source/ffi.c`; case `56-ffi-library` covers it.
- **DRAW is anti-aliased** (AGG-style coverage) with `curve`/`spline`; cases
  `57-draw-aa` and `58-first-series` cover the new behaviour.
- **`compress` is byte-identical to R2**: zlib level 6 + the trailing length
  word.  `r2clone/vendor/zlib/` holds the vendored deflate path
  (`Z_SOLO`/`NO_GZIP`); case `59-compress-zlib` covers it.
- **Operator/function fix**: `++`/`--`, `add`/`subtract` as ordinary
  functions and `set word expression` work; case `69-operator-function-calls`.
- **Example smoke coverage**: `tools/examples_smoke.py` runs every
  `examples/*.r` on Linux and opens the VID examples under Wine/Xvfb.  The
  `effects.r` example is now self-contained (generated image, no missing
  `logo.gif`).  Corpus errors report the actual missing word.
- **DRAW arc/line-pattern/emboss**: `arc` (clockwise elliptical arcs,
  optional `closed` wedge), dashed `line-pattern` with foreground/
  background pens, and the `emboss` effect (to-image and image faces).
  Golden case `68-draw-arc-pattern`.
- **Find dialog + field actions + unview**: the editor Find popup focuses
  its field, Enter runs single-line field actions and closes the popup, and
  `unview/only` removes only the requested window (native cleanup now runs
  after the face action returns).  (Shared with the requestor/file-series fixes.)
- **Themed requestors + file series**: `request-list` and `request-dir`
  navigate/select correctly (nested viewport composition fixed); file/url/tag
  series ops and `path/:file` work.  Golden case `67-file-series-ops`.
- **HTTP/FTP/POP/SMTP/IMAP networking**: HTTP redirects and `load` of image
  URLs, passive-mode FTP (`read`/`read/binary`/`read/lines`/`write`/`dir?`),
  POP3/IMAP mailbox reads and SMTP `send`/ESMTP ports.  `tools/net_smoke.py`
  verifies them with local servers.
- **`sound://` + WAV codec + nested panes**: `load` of RIFF/WAVE returns the
  reference sound object, `open sound://` is a real `port!`, `insert` plays
  (`PlaySoundA`/`SND_MEMORY`), `wait` waits the sample duration and `close`
  stops.  View panes (block/object/function, including TEXT-LIST rows) are
  rendered, hit-tested, selection-highlighted and dispatch row actions.
  Cases `65-sound-load` and `66-text-list-pane` cover it.
- **The 10-app demo (`examples/demo.r`) runs**: Paint (draw/Save PNG/Clear),
  Game (RATE timers + keys), Puzzle (offset swap), Calendar/Days
  (`request-date`), Sounds (list `C:\Windows\media`, click a WAV to play).  Fixes: RATE timers, face-relative mouse offsets +
  per-move `over`, effect-draw canvases, `to-image` of faces + `save/png`,
  global bindings inside cloned feels, `random` pair/tuple ranges, script
  title, `view/new` window placement at `face/offset` + activation,
  control repositioning after canvas/native actions, custom-FEEL canvases
  (Paint/Game not EDIT), `dns://` and `parse` copy/set into new words.
  `-v` prints the build id (demo19-2026-11-14); popup-aware WAIT, modal
  timer guard, the arrow effect and R2 file-path resolution (relative
  `system/script/path`, `%/c/...` drives, `to-file` termination) fix
  Calendar/Days, the Game SCORE crash and the Sounds file list.  Cases
  60–66.
- **re-bol.com corpus**: all 20 sections complete, 0 errors (non-runnable third-party/
  interactive snippets are explicitly skipped).
  See `REPORT.md`.
- `rebol-view.exe` 928256 bytes, sha256 `21283918e730f4a82a921ab07531cb785ef83799f44d4dac6ba1c69277c650f9`
- `rebol-view-2-clone.zip` 1132585 bytes, sha256 `bc179b7ca2a9d5a7911488f1cc340853ab525a38f860fee3288e4965361399fd`
- Previous published exe was 758272 bytes, sha256 `e3c7d483…`
- Previous published exe was 748544 bytes, sha256 `103698dc…`
- Latest session recovered `checksum/hash` exactly (disassembly: Jenkins
  lookup2 over REBOL's Upper_Case table with a reversed tail), added
  `checksum/key` HMAC, fixed `system/version` identity, 10-component tuples,
  date time zones, image transparency semantics and `draw` fill/stroke
  colours, plus owner-drawn VID buttons and the `REBOL - <title>` caption.
  Three new oracle cases (`47`-`49`) cover them.
- **The real VID engine is now running.** The recovered View Desktop
  module (20) is embedded and evaluated at startup, so `system/view/vid`
  is the original 120-style style sheet and `layout`/`stylize`/`make-face`
  are the recovered REBOL source.  `view/new layout [...]` opens a real
  Win32 window under Wine; faces have correct offsets/sizes/fonts and
  button/check actions (function or block) are dispatched.
- A 30-case audit passes 29/30 (only `map`, which is not an R2 function,
  "fails").
- **Real images and a useful AGG subset**: GIF/PNG/JPEG/BMP decode via
  stb_image; `draw` supports pen/fill-pen/line/box/circle/triangle/image/
  gradient/color/flood.  The Win32 renderer places real VID faces by
  offset/size and draws colours, fonts, edges and images.  The VID `size`
  word now sets the window size.
- Verified: arithmetic, series positions, `find`/`find/any`, `replace/all`,
  `collect`, `parse` (incl. datatype rules, set/copy, to/thru, sub-rules),
  objects/functions/closures, `http`/`https` read, `layout` with
  across/return/field/check, `draw`/image pixels, `parse` with
  into/insert/remove/change and /case//all, and `view/new` creating a
  window with gradient backdrops and alpha-blended images (screenshots
  verified under Xvfb+Wine).

### Additional bugs found and fixed in this session

12. `make <prototype-object> spec` ignored the spec (and extensions); it
    now copies fields and evaluates the spec, with `self` bound.
13. `bind block word` was a no-op; it now rebinds to the word's context
    (this is what makes VID style `init` blocks work).
14. Set-words evaluated only the next value, so `where: a + b` dropped the
    infix tail; set-words and set-paths now use full expressions.
15. `forall`/`forskip` set element values instead of series positions; the
    natives are now position-based and re-registered after the boot image.
16. `set [a b] block` destructuring was unsupported.
17. Path elements like `a/1` were words; numeric path parts are integers
    and tuples/pairs/images are indexable (`system/version/4`, `size/x`).
18. Functions reached through objects (`obj/fn arg`, `system/words/…`)
    were returned instead of called; now called when arguments follow
    (and returned as values otherwise, e.g. `type? face/action`).
19. `copy/part series position` copied to the end instead of to the
    position.
20. `make series len` copied the argument series instead of creating an
    empty series (broke `extract`).
21. `switch` used the /default flag slot as the default value and did not
    match datatype cases against `type?/word` results.
22. `union`/`intersect`/`difference` crashed on bitsets; now supported.
23. `maximum`/`minimum` of pairs compared as 0; now component-wise (VID
    pane extents/`return`).
24. `reverse` of a pair returned it unchanged.
25. Refinement flags defaulted to `false`; R2 uses `none` (required by
    `get-style`/`stylize`).
26. `foreach`/`repeat`/`for` bound loop variables in the wrong context;
    binding now follows the word's context and function contexts are
    restored correctly.
27. Base64 `64#{...}` literals were scanned as integers.
28. `load` of image binaries / image files returned data instead of an
    `image!`; GIF/PNG/BMP/JPEG header dimensions are now parsed and
    `image/size`, `image/width`, `image/height`, pixels work.
29. Missing datatypes (`hash!`, `list!`, `typeset!`, `end!`, path types,
    `email!`, ...), predicates (`image?`, `set-word?`, ...) and all
    `to-<type>` conversions were added.
30. `make set-word! "name"` and other word/file conversions were missing.

### Golden-suite session (this continuation): fidelity fixes

The 50-case oracle suite (`tests/`, goldens generated by the original
REBOL/View binary under Wine) exposed and fixed a large set of semantic
differences.  Highlights (all verified Linux + Wine):

41. `form` vs `mold` for datatypes (`integer`/`integer!`), files
    (`file.txt`/`%file.txt`), issues, times (`1:30` not `1:30:00`), tuple
    length (3 vs 4 components), binaries (hex), bitsets (R2 layout and
    `make bitset! #{...}`), brace-molded strings, and user functions
    (`func [spec][body]`), objects in spec order.
42. `load` returns a single value for a one-value script, keeps R2's
    implicit end-of-line marker (mold newline before `]`); `to-block`
    loads strings; `save` writes block contents without brackets.
43. Real base64 `enbase`/`debase`, `to-hex` issue values, tuple/pair
    binary conversions, self-contained zlib `compress`/`decompress`
    (R2's trailing little-endian length) and `checksum/tcp`.
44. Image pixels are always 4-component RGBA; user-level `draw` matches
    R2's coverage output (white fills, pen-coloured lines, alpha 0).
    Image block background `make image! [size color alpha]`.
45. VID `size-text` uses Arial width tables (12 normal / 24 bold), so
    layout offsets/sizes match the reference; the View Desktop module now
    loads completely (the earlier `to-lit-word` fix unblocked it).
46. Case-preserving word interning (mold shows the source spelling) while
    lookup stays case-insensitive.
47. Functions reached through a path (`obj/fn`) are always called, even
    when followed by a set-word or end-of-block; this fixed `display`
    methods and many VID callbacks.
48. Object field order follows the spec (including chained set-words);
    `first object` = `[self ...]`; `words-of`/`values-of` exclude self;
    `with` is a facet dialect (`doc [...] effect [...]` and `field: value`).
49. Generic `for` over decimal/money/time/date/char; `round` with all R2
    refinements; `difference` = symmetric difference; `find/match`
    returns the tail of the match; `same?` is series identity;
    `load`/`mold` newline semantics; `first`/`second` on objects.
50. `parse`: R2's automatic whitespace skipping without `/all`; `to`/`thru`
    positions; `parse/all` delimiter splitting; integer rule repetition;
    R2 has no parse `insert`/`change`/`remove` commands (paren actions
    instead).  Removed the clone's non-R2 dialect actions.
51. New natives / re-registrations: `clean-path`, `split-path`, `dirize`,
    `suffix?`, `apply`, `rename`, `delete`, `exists?`, `round`, `with`.
52. `mold` of errors/objects for `disarm` output (`make object! [...]` with
    code/type/id/arg1..3/near/where), zero-divide metadata.
53. Path-supplied refinement flags were stored in a global that nested
    argument evaluation could clobber, so `view/new layout [...]`,
    `layout/size [..] 300x200`, etc. silently lost the refinement.  The
    flags are now snapshotted at `Call_Value` entry.
54. `view/new` (not `view/no-wait`; R2 2.7.8.3.1's `view` only has
    `/new /offset /options /title`) now returns immediately as it should;
    the examples and docs were corrected.
55. R2's **default `checksum`** is the classic 24-bit PRZ CRC
    (`poly 0x864CFB`, initial value `len + first byte`), not a byte sum.
    Implemented and verified against the oracle's 256-byte table; also
    added `checksum/method 'md5`, `'sha1` and `checksum/secure` (SHA-1)
    with a self-contained `hash.c`.
56. Path refinement flags leaked into nested argument evaluation, so
    `uppercase/part copy "abcdef" 3` actually invoked `copy/part` and
    lost the `uppercase`.  `Call_Value` now snapshots and clears the
    path-refinement globals before evaluating arguments.
57. `mold/only` (drop outer block brackets), `find/reverse` (backwards
    search from the current position), `reverse/part`, and
    `uppercase`/`lowercase /part` now work.
58. `read/binary`, `read/lines`, and `write/lines` now honour their
    refinements; `read/lines` removes trailing CR and a trailing final
    newline, and `write/lines` terminates each line with LF.
59. Suite expanded from 40 to 46 cases: `41-series-refinements`
    (remove-each, mold/all/only/flat, find/tail/reverse, copy/deep,
    sort/skip, insert/dup, change/part, reverse/part, uppercase/part,
    trim/with, base-2 enbase/debase, to-tuple "1.2") and `42-io-more`
    (read/write lines and binary, rename/delete, load/all), plus
    `43-editor-gui` which opens `editor %test.txt` headlessly, and
    `44-language-probe` (parse/series/math/date/object edge cases), and
    `45-reflection-io` (reflection, error objects, /part I/O, trig units,
    time/money), and `46-vid-parse` (VID pane metrics/layout options and
    parse/series/string edge cases).
60. File/URL path extension now works: `file/word/word` (e.g.
    `view-root/desktop/scripts/edit.r`) appends path segments instead of
    raising `invalid-path`.  `system/script/path` defaults to `%./`, and
    `system/script/title`/`header` default to "Untitled"/standard, so
    `view` names the initial window "Untitled" like R2.
61. `series?` now matches R2: true for string/binary/block/paren/file/
    url/email/issue/tag/image, false for tuple/pair/time/date/bitset/
    object.  This fixed `join %a %b` (now `%ab`, not `"ab"`).
62. `select` on a string returns the next character (`select "abc" "b"`
    -> #"c"), not the positioned series.  `insert`/`append` now work on
    file/url/email values (used by `join`/`repend`).
63. `make date! [y m d]` (optionally `[y m d h m s]`) works.
64. `parse`: `opt`/`any` now advance past the sub-rule when it does not
    match (`opt "x" "abc"` and `any "x" "abc"` return true), and a
    zero-length `copy` binds `none` (not `""`).
65. Reflection: `body-of`/`third` on objects return the field/set-word
    block, `words-of`/`first` on functions return the full spec, and
    nested `mold` indents objects by depth (4 spaces per level).
66. R2 trig works in **degrees** (`sine 90` = 1.0, `arcsine 1` = 90.0);
    `make time! [h m s]`, time fractions in literals/`to-time`, and
    money negation (`-$5.00`) now match.
67. `read/part` and `write/part` work (`write/part` truncates to the file
    and writes at most N bytes), and native `size?`, `dir?`, `make-dir`
    (`/deep`) replace the boot mezzanines that relied on the port model.
68. `to-local-file`/`to-rebol-file` convert separators, `sort/all` orders
    mixed types by datatype, dynamic set-paths (`o/:w:`) evaluate the
    get-word, `pair + integer` works, and `to-integer` of a non-number
    now raises an error.  `disarm` now emits R2's codes/ids/args for
    `cannot-use` (312, lit-word op/type args) and `past-end` (315).
69. `case` now handles non-block results: each condition consumes the
    following value, and a true branch evaluates it (`case [true x]` ->
    value of x; `case [false 1 true 2]` -> 2).  This fixed the boot
    `replace` mezzanine, which uses `case` to compute the search length.
70. `second`/`third`/`pick` (Nth_Of) on positioned blocks/strings now
    honour the series index.  This fixed `load-stock`, which does
    `second find image-stock name`, so the correct 13x13 check/radio
    images load and `check-mark`/`radio` get their real sizes.
71. `change/part` on strings now removes the target range and inserts the
    replacement (instead of overwriting + reinserting), so
    `change/part s "XY" 1` and `replace/all` produce R2 results.
72. `size-text` treats bold as normal weight unless the font size is >=20;
    bold 12pt labels now measure 13x18 ("L") like R2 instead of using the
    24pt title table.

## REMAINING WORK (priority order)

1. **Advanced AGG** — images now decode (stb_image) and a useful `draw`
   subset rasterises (`pen`/`fill-pen`/`line`/`box`/`circle`/`triangle`/
   `image`/`gradient`/`color`/`flood`).  The Win32 renderer alpha-blends
   images and applies `fit`/`tile`/`colorize`/`gradient` effects, including
   window gradient backdrops.  `draw` has bitmap text, `polygon`, `clip`
   and a translate/scale/rotate push/pop stack.  Still missing: other
   effects (`emboss`, ...) and anti-aliasing.
2. *(done)* **VID dialect `size` word** — fixed: parse `set`/`copy` now
   resolve variables in the rule word's binding context, so
   `layout [size 320x200 …]` sets the window size.
3. **Advanced `parse`** — `into`, `remove`/`insert`/`change`, `/case`,
   `/all` and set-word position capture are implemented; remaining: typed
   `set`/`copy` forms, `copy/part`, `to end` edge cases.
4. *(done)* **Native refinements** — `find/with` custom wildcards,
   `select/part`/`select/with`, `sort/compare` and case-insensitive sort
   are implemented.  Remaining: a few rare refinements and `copy/types`
   (not part of R2's `copy` spec).
5. **Protocol/codec breadth** — HTTP(S), FTP, POP3, SMTP and IMAP are wired
   to the OS.  MIME, ODBC, registry, shell and installer modules are
   recovered but not loaded.
6. **date!/time!/money!** are now real values (mold, paths, arithmetic,
   `now` refinements, ISO parsing) — use them instead of the old stubs.
7. **Requestor pickers** — `request/ok`/`request-text` work; `request-file`
   uses the Windows OS dialog. `request-dir`/`request-list` and live
   directory refresh are still rough.
8. **Stale evaluation context** — in some nested `do`/callback paths (seen
   in the themed requestors) `Current` can be left pointing at a
   `does` context; parse rule variables now resolve via their own binding so
   it no longer breaks VID parsing, but the root cause should be found.
9. **Memory reclamation** — series/context/function refcounts are never
   released; long sessions leak (use ASan to see the scale).
7. Optional: make the Win32 renderer honour face colours, fonts, edges
   and images (currently text/button/field/check/static mapping only).

## USEFUL REFERENCE

- REA CLI: `/root/.nvm/versions/node/v22.19.0/bin/rea` (or `npx rea-agents@latest`).
  Native decompilation needs Ghidra (`GHIDRA_INSTALL_DIR`), not currently set.
- Reference binary: `/root/rebol-view-clone/reference-rebol-view-278-3-1.exe`
- Docs: `/root/rebol-view-clone/REVERSE-ENGINEERING.md` (method + coverage)
- Caddy serves `/root/download` at `download.xqx1.com` (proxy to :8000).

Start by reading `REVERSE-ENGINEERING.md` and `r2clone/reb.h`, then run the audit
to confirm the baseline before making changes.
